Skip to content

Commit 86b1122

Browse files
committed
Improve diagnostic for const ctors in array repeat expressions
1 parent c06b2b9 commit 86b1122

File tree

7 files changed

+126
-28
lines changed

7 files changed

+126
-28
lines changed

compiler/rustc_hir_typeck/src/expr.rs

+28-7
Original file line numberDiff line numberDiff line change
@@ -1507,21 +1507,42 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
15071507
}
15081508
_ => {}
15091509
}
1510-
// If someone calls a const fn, they can extract that call out into a separate constant (or a const
1511-
// block in the future), so we check that to tell them that in the diagnostic. Does not affect typeck.
1512-
let is_const_fn = match element.kind {
1510+
// If someone calls a const fn or constructs a const value, they can extract that
1511+
// out into a separate constant (or a const block in the future), so we check that
1512+
// to tell them that in the diagnostic. Does not affect typeck.
1513+
let is_constable = match element.kind {
15131514
hir::ExprKind::Call(func, _args) => match *self.node_ty(func.hir_id).kind() {
1514-
ty::FnDef(def_id, _) => tcx.is_const_fn(def_id),
1515-
_ => false,
1515+
ty::FnDef(def_id, _) if tcx.is_const_fn(def_id) => traits::IsConstable::Fn,
1516+
_ => traits::IsConstable::No,
15161517
},
1517-
_ => false,
1518+
hir::ExprKind::Path(qpath) => {
1519+
match self.typeck_results.borrow().qpath_res(&qpath, element.hir_id) {
1520+
Res::Def(DefKind::Ctor(_, CtorKind::Const), _) => traits::IsConstable::Ctor,
1521+
_ => traits::IsConstable::No,
1522+
}
1523+
}
1524+
_ => traits::IsConstable::No,
15181525
};
15191526

15201527
// If the length is 0, we don't create any elements, so we don't copy any. If the length is 1, we
15211528
// don't copy that one element, we move it. Only check for Copy if the length is larger.
15221529
if count.try_eval_target_usize(tcx, self.param_env).map_or(true, |len| len > 1) {
15231530
let lang_item = self.tcx.require_lang_item(LangItem::Copy, None);
1524-
let code = traits::ObligationCauseCode::RepeatElementCopy { is_const_fn };
1531+
let code = traits::ObligationCauseCode::RepeatElementCopy {
1532+
is_constable,
1533+
elt_type: element_ty,
1534+
elt_span: element.span,
1535+
elt_stmt_span: self
1536+
.tcx
1537+
.hir()
1538+
.parent_iter(element.hir_id)
1539+
.find_map(|(_, node)| match node {
1540+
hir::Node::Item(it) => Some(it.span),
1541+
hir::Node::Stmt(stmt) => Some(stmt.span),
1542+
_ => None,
1543+
})
1544+
.expect("array repeat expressions must be inside an item or statement"),
1545+
};
15251546
self.require_type_meets(element_ty, element.span, code, lang_item);
15261547
}
15271548
}

compiler/rustc_middle/src/traits/mod.rs

+23-3
Original file line numberDiff line numberDiff line change
@@ -301,9 +301,14 @@ pub enum ObligationCauseCode<'tcx> {
301301
InlineAsmSized,
302302
/// `[expr; N]` requires `type_of(expr): Copy`.
303303
RepeatElementCopy {
304-
/// If element is a `const fn` we display a help message suggesting to move the
305-
/// function call to a new `const` item while saying that `T` doesn't implement `Copy`.
306-
is_const_fn: bool,
304+
/// If element is a `const fn` or const ctor we display a help message suggesting
305+
/// to move it to a new `const` item while saying that `T` doesn't implement `Copy`.
306+
is_constable: IsConstable,
307+
elt_type: Ty<'tcx>,
308+
elt_span: Span,
309+
/// Span of the statement/item in which the repeat expression occurs. We can use this to
310+
/// place a `const` declaration before it
311+
elt_stmt_span: Span,
307312
},
308313

309314
/// Types of fields (other than the last, except for packed structs) in a struct must be sized.
@@ -448,6 +453,21 @@ pub enum ObligationCauseCode<'tcx> {
448453
TypeAlias(InternedObligationCauseCode<'tcx>, Span, DefId),
449454
}
450455

456+
/// Whether a value can be extracted into a const.
457+
/// Used for diagnostics around array repeat expressions.
458+
#[derive(Copy, Clone, Debug, PartialEq, Eq, HashStable, TyEncodable, TyDecodable)]
459+
pub enum IsConstable {
460+
No,
461+
/// Call to a const fn
462+
Fn,
463+
/// Use of a const ctor
464+
Ctor,
465+
}
466+
467+
crate::TrivialTypeTraversalAndLiftImpls! {
468+
IsConstable,
469+
}
470+
451471
/// The 'location' at which we try to perform HIR-based wf checking.
452472
/// This information is used to obtain an `hir::Ty`, which
453473
/// we can walk in order to obtain precise spans for any

compiler/rustc_trait_selection/src/traits/error_reporting/suggestions.rs

+20-9
Original file line numberDiff line numberDiff line change
@@ -27,6 +27,7 @@ use rustc_infer::infer::error_reporting::TypeErrCtxt;
2727
use rustc_infer::infer::type_variable::{TypeVariableOrigin, TypeVariableOriginKind};
2828
use rustc_infer::infer::{DefineOpaqueTypes, InferOk, LateBoundRegionConversionTime};
2929
use rustc_middle::hir::map;
30+
use rustc_middle::traits::IsConstable;
3031
use rustc_middle::ty::error::TypeError::{self, Sorts};
3132
use rustc_middle::ty::{
3233
self, suggest_arbitrary_trait_bound, suggest_constraining_type_param, AdtKind,
@@ -2832,20 +2833,30 @@ impl<'tcx> TypeErrCtxtExt<'tcx> for TypeErrCtxt<'_, 'tcx> {
28322833
));
28332834
}
28342835
}
2835-
ObligationCauseCode::RepeatElementCopy { is_const_fn } => {
2836+
ObligationCauseCode::RepeatElementCopy { is_constable, elt_type, elt_span, elt_stmt_span } => {
28362837
err.note(
28372838
"the `Copy` trait is required because this value will be copied for each element of the array",
28382839
);
2839-
2840-
if is_const_fn {
2841-
err.help(
2842-
"consider creating a new `const` item and initializing it with the result \
2843-
of the function call to be used in the repeat position, like \
2844-
`const VAL: Type = const_fn();` and `let x = [VAL; 42];`",
2845-
);
2840+
let value_kind = match is_constable {
2841+
IsConstable::Fn => Some("the result of the function call"),
2842+
IsConstable::Ctor => Some("the result of the constructor"),
2843+
_ => None
2844+
};
2845+
let sm = tcx.sess.source_map();
2846+
if let Some(value_kind) = value_kind &&
2847+
let Ok(snip) = sm.span_to_snippet(elt_span)
2848+
{
2849+
let help_msg = format!(
2850+
"consider creating a new `const` item and initializing it with {value_kind} \
2851+
to be used in the repeat position");
2852+
let indentation = sm.indentation_before(elt_stmt_span).unwrap_or_default();
2853+
err.multipart_suggestion(help_msg, vec![
2854+
(elt_stmt_span.shrink_to_lo(), format!("const ARRAY_REPEAT_VALUE: {elt_type} = {snip};\n{indentation}")),
2855+
(elt_span, "ARRAY_REPEAT_VALUE".to_string())
2856+
], Applicability::MachineApplicable);
28462857
}
28472858

2848-
if self.tcx.sess.is_nightly_build() && is_const_fn {
2859+
if self.tcx.sess.is_nightly_build() && matches!(is_constable, IsConstable::Fn|IsConstable::Ctor) {
28492860
err.help(
28502861
"create an inline `const` block, see RFC #2920 \
28512862
<https://github.com/rust-lang/rfcs/pull/2920> for more information",

tests/ui/consts/const-blocks/fn-call-in-non-const.stderr

+5-1
Original file line numberDiff line numberDiff line change
@@ -6,13 +6,17 @@ LL | let _: [Option<Bar>; 2] = [no_copy(); 2];
66
|
77
= note: required for `Option<Bar>` to implement `Copy`
88
= note: the `Copy` trait is required because this value will be copied for each element of the array
9-
= 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];`
109
= help: create an inline `const` block, see RFC #2920 <https://github.com/rust-lang/rfcs/pull/2920> for more information
1110
help: consider annotating `Bar` with `#[derive(Copy)]`
1211
|
1312
LL + #[derive(Copy)]
1413
LL | struct Bar;
1514
|
15+
help: consider creating a new `const` item and initializing it with the result of the function call to be used in the repeat position
16+
|
17+
LL ~ const ARRAY_REPEAT_VALUE: Option<Bar> = no_copy();
18+
LL ~ let _: [Option<Bar>; 2] = [ARRAY_REPEAT_VALUE; 2];
19+
|
1620

1721
error: aborting due to previous error
1822

tests/ui/consts/const-blocks/trait-error.stderr

+5-1
Original file line numberDiff line numberDiff line change
@@ -10,9 +10,13 @@ note: required for `Foo<String>` to implement `Copy`
1010
LL | #[derive(Copy, Clone)]
1111
| ^^^^ unsatisfied trait bound introduced in this `derive` macro
1212
= note: the `Copy` trait is required because this value will be copied for each element of the array
13-
= 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];`
1413
= help: create an inline `const` block, see RFC #2920 <https://github.com/rust-lang/rfcs/pull/2920> for more information
1514
= note: this error originates in the derive macro `Copy` (in Nightly builds, run with -Z macro-backtrace for more info)
15+
help: consider creating a new `const` item and initializing it with the result of the function call to be used in the repeat position
16+
|
17+
LL ~ const ARRAY_REPEAT_VALUE: Foo<String> = Foo(String::new());
18+
LL ~ [ARRAY_REPEAT_VALUE; 4];
19+
|
1620

1721
error: aborting due to previous error
1822

tests/ui/consts/const-fn-in-vec.rs

+6-2
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,11 @@
1+
static _MAYBE_STRINGS: [Option<String>; 5] = [None; 5];
2+
//~^ ERROR the trait bound `String: Copy` is not satisfied
3+
14
fn main() {
25
// should hint to create an inline `const` block
36
// or to create a new `const` item
4-
let strings: [String; 5] = [String::new(); 5];
7+
let _strings: [String; 5] = [String::new(); 5];
8+
//~^ ERROR the trait bound `String: Copy` is not satisfied
9+
let _maybe_strings: [Option<String>; 5] = [None; 5];
510
//~^ ERROR the trait bound `String: Copy` is not satisfied
6-
println!("{:?}", strings);
711
}
+39-5
Original file line numberDiff line numberDiff line change
@@ -1,13 +1,47 @@
11
error[E0277]: the trait bound `String: Copy` is not satisfied
2-
--> $DIR/const-fn-in-vec.rs:4:33
2+
--> $DIR/const-fn-in-vec.rs:1:47
33
|
4-
LL | let strings: [String; 5] = [String::new(); 5];
5-
| ^^^^^^^^^^^^^ the trait `Copy` is not implemented for `String`
4+
LL | static _MAYBE_STRINGS: [Option<String>; 5] = [None; 5];
5+
| ^^^^ the trait `Copy` is not implemented for `String`
66
|
7+
= note: required for `Option<String>` to implement `Copy`
78
= note: the `Copy` trait is required because this value will be copied for each element of the array
8-
= 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];`
99
= help: create an inline `const` block, see RFC #2920 <https://github.com/rust-lang/rfcs/pull/2920> for more information
10+
help: consider creating a new `const` item and initializing it with the result of the constructor to be used in the repeat position
11+
|
12+
LL + const ARRAY_REPEAT_VALUE: Option<String> = None;
13+
LL ~ static _MAYBE_STRINGS: [Option<String>; 5] = [ARRAY_REPEAT_VALUE; 5];
14+
|
15+
16+
error[E0277]: the trait bound `String: Copy` is not satisfied
17+
--> $DIR/const-fn-in-vec.rs:7:34
18+
|
19+
LL | let _strings: [String; 5] = [String::new(); 5];
20+
| ^^^^^^^^^^^^^ the trait `Copy` is not implemented for `String`
21+
|
22+
= note: the `Copy` trait is required because this value will be copied for each element of the array
23+
= help: create an inline `const` block, see RFC #2920 <https://github.com/rust-lang/rfcs/pull/2920> for more information
24+
help: consider creating a new `const` item and initializing it with the result of the function call to be used in the repeat position
25+
|
26+
LL ~ const ARRAY_REPEAT_VALUE: String = String::new();
27+
LL ~ let _strings: [String; 5] = [ARRAY_REPEAT_VALUE; 5];
28+
|
29+
30+
error[E0277]: the trait bound `String: Copy` is not satisfied
31+
--> $DIR/const-fn-in-vec.rs:9:48
32+
|
33+
LL | let _maybe_strings: [Option<String>; 5] = [None; 5];
34+
| ^^^^ the trait `Copy` is not implemented for `String`
35+
|
36+
= note: required for `Option<String>` to implement `Copy`
37+
= note: the `Copy` trait is required because this value will be copied for each element of the array
38+
= help: create an inline `const` block, see RFC #2920 <https://github.com/rust-lang/rfcs/pull/2920> for more information
39+
help: consider creating a new `const` item and initializing it with the result of the constructor to be used in the repeat position
40+
|
41+
LL ~ const ARRAY_REPEAT_VALUE: Option<String> = None;
42+
LL ~ let _maybe_strings: [Option<String>; 5] = [ARRAY_REPEAT_VALUE; 5];
43+
|
1044

11-
error: aborting due to previous error
45+
error: aborting due to 3 previous errors
1246

1347
For more information about this error, try `rustc --explain E0277`.

0 commit comments

Comments
 (0)