Rollup merge of #113925 - clubby789:const-ctor-repeat, r=estebank
Improve diagnostic for const ctors in array repeat expressions Fixes #113912
This commit is contained in:
commit
b724d9c90e
7 changed files with 126 additions and 28 deletions
|
@ -28,6 +28,7 @@ use rustc_infer::infer::error_reporting::TypeErrCtxt;
|
|||
use rustc_infer::infer::type_variable::{TypeVariableOrigin, TypeVariableOriginKind};
|
||||
use rustc_infer::infer::{DefineOpaqueTypes, InferOk, LateBoundRegionConversionTime};
|
||||
use rustc_middle::hir::map;
|
||||
use rustc_middle::traits::IsConstable;
|
||||
use rustc_middle::ty::error::TypeError::{self, Sorts};
|
||||
use rustc_middle::ty::{
|
||||
self, suggest_arbitrary_trait_bound, suggest_constraining_type_param, AdtKind, GenericArgs,
|
||||
|
@ -2768,20 +2769,30 @@ impl<'tcx> TypeErrCtxtExt<'tcx> for TypeErrCtxt<'_, 'tcx> {
|
|||
));
|
||||
}
|
||||
}
|
||||
ObligationCauseCode::RepeatElementCopy { is_const_fn } => {
|
||||
ObligationCauseCode::RepeatElementCopy { is_constable, elt_type, elt_span, elt_stmt_span } => {
|
||||
err.note(
|
||||
"the `Copy` trait is required because this value will be copied for each element of the array",
|
||||
);
|
||||
|
||||
if is_const_fn {
|
||||
err.help(
|
||||
"consider creating a new `const` item and initializing it with the result \
|
||||
of the function call to be used in the repeat position, like \
|
||||
`const VAL: Type = const_fn();` and `let x = [VAL; 42];`",
|
||||
);
|
||||
let value_kind = match is_constable {
|
||||
IsConstable::Fn => Some("the result of the function call"),
|
||||
IsConstable::Ctor => Some("the result of the constructor"),
|
||||
_ => None
|
||||
};
|
||||
let sm = tcx.sess.source_map();
|
||||
if let Some(value_kind) = value_kind &&
|
||||
let Ok(snip) = sm.span_to_snippet(elt_span)
|
||||
{
|
||||
let help_msg = format!(
|
||||
"consider creating a new `const` item and initializing it with {value_kind} \
|
||||
to be used in the repeat position");
|
||||
let indentation = sm.indentation_before(elt_stmt_span).unwrap_or_default();
|
||||
err.multipart_suggestion(help_msg, vec![
|
||||
(elt_stmt_span.shrink_to_lo(), format!("const ARRAY_REPEAT_VALUE: {elt_type} = {snip};\n{indentation}")),
|
||||
(elt_span, "ARRAY_REPEAT_VALUE".to_string())
|
||||
], Applicability::MachineApplicable);
|
||||
}
|
||||
|
||||
if self.tcx.sess.is_nightly_build() && is_const_fn {
|
||||
if self.tcx.sess.is_nightly_build() && matches!(is_constable, IsConstable::Fn|IsConstable::Ctor) {
|
||||
err.help(
|
||||
"create an inline `const` block, see RFC #2920 \
|
||||
<https://github.com/rust-lang/rfcs/pull/2920> for more information",
|
||||
|
|
Loading…
Add table
Add a link
Reference in a new issue