Skip to content

Commit 03cbd41

Browse files
committed
Auto merge of #163235 - estebank:default-field-values-lint, r=fmease
Lint default field values in types with type or const parameters as they won't be evaluated pre-mono Default field values in types that have const generics are no longer being evaluated until mono. Emit a warn-by-default lint so that API designers are not caught of guard by this behavior. ``` warning: field `multiline_field` has a default value that is only checked when a value of `Z` is constructed --> $DIR/field-references-param-accurate-span.rs:9:15 | LL | struct Z<const X: usize> { LL | multiline_field: LL | () LL | = { | _______________^ LL | | f::<X>(); LL | | panic!(); LL | | }, | |_____________^ this can't be const-evaluated until use | = help: structs and enums with type and const parameters only evaluate their default field values during construction, not eagerly when declared = note: `#[warn(unevaluated_default_field_value)]` on by default help: if this behavior is acceptable, allow the lint and preferably write a test relying on the default value | LL + #[expect(unevaluated_default_field_value)] LL | struct Z<const X: usize> { | ``` Support `Span` context in lints. Fixes #146496. Part of #132162. Alternative to #163182. CC @fmease @BoxyUwU
2 parents 080cc27 + 7b71c53 commit 03cbd41

22 files changed

Lines changed: 667 additions & 40 deletions

‎compiler/rustc_hir_analysis/src/check/wfcheck.rs‎

Lines changed: 43 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -9,18 +9,23 @@ use rustc_attr_ir::{EiiDecl, EiiImpl, EiiImplResolution, find_attr};
99
use rustc_data_structures::fx::{FxHashSet, FxIndexMap, FxIndexSet};
1010
use rustc_data_structures::transitive_relation::TransitiveRelationBuilder;
1111
use rustc_errors::codes::*;
12-
use rustc_errors::{Applicability, ErrorGuaranteed, msg, pluralize, struct_span_code_err};
12+
use rustc_errors::{
13+
Applicability, ErrorGuaranteed, MultiSpan, msg, pluralize, struct_span_code_err,
14+
};
1315
use rustc_hir as hir;
1416
use rustc_hir::def::{DefKind, Res};
1517
use rustc_hir::def_id::{DefId, LocalDefId};
1618
use rustc_hir::{AmbigArg, ItemKind};
1719
use rustc_infer::infer::outlives::env::OutlivesEnvironment;
1820
use rustc_infer::infer::{BoundRegionConversionTime, SolverRegionConstraint, TyCtxtInferExt};
1921
use rustc_infer::traits::{PredicateObligations, TraitErrors};
20-
use rustc_lint_defs::builtin::{REDUNDANT_LIFETIMES, SHADOWING_SUPERTRAIT_ITEMS};
22+
use rustc_lint_defs::builtin::{
23+
REDUNDANT_LIFETIMES, SHADOWING_SUPERTRAIT_ITEMS, UNEVALUATED_DEFAULT_FIELD_VALUE,
24+
};
2125
use rustc_macros::{Diagnostic, TypeFoldable, TypeVisitable};
2226
use rustc_middle::mir::interpret::ErrorHandled;
2327
use rustc_middle::traits::solve::NoSolution;
28+
use rustc_middle::ty::print::with_no_trimmed_paths;
2429
use rustc_middle::ty::region_constraint::{And, LeafRegionConstraint, Or};
2530
use rustc_middle::ty::trait_def::TraitSpecializationKind;
2631
use rustc_middle::ty::{
@@ -47,7 +52,9 @@ use tracing::{debug, instrument};
4752
use super::compare_eii::{compare_eii_function_types, compare_eii_statics};
4853
use crate::autoderef::Autoderef;
4954
use crate::constrained_generic_params::{Parameter, identify_constrained_generic_params};
50-
use crate::diagnostics::{self, InvalidReceiverTyHint, ParamInTyOfConstParam};
55+
use crate::diagnostics::{
56+
self, InvalidReceiverTyHint, ParamInTyOfConstParam, UnevaluatedDefaultFieldValue,
57+
};
5158

5259
pub(super) struct WfCheckingCtxt<'a, 'tcx> {
5360
pub(super) ocx: ObligationCtxt<'a, 'tcx, FulfillmentError<'tcx>>,
@@ -980,28 +987,44 @@ pub(crate) fn check_type_defn<'tcx>(
980987
enter_wf_checking_ctxt(tcx, item, |wfcx| {
981988
let variants = adt_def.variants();
982989
let packed = adt_def.repr().packed();
990+
let own_params_require_monomorphization =
991+
tcx.generics_of(item).own_requires_monomorphization();
983992

984993
for variant in variants.iter() {
985994
// All field types must be well-formed.
986995
for field in &variant.fields {
987-
if let Some(def_id) = field.value
988-
&& let Some(_ty) = tcx.type_of(def_id).no_bound_vars()
989-
{
990-
// FIXME(generic_const_exprs, default_field_values): this is a hack and needs to
991-
// be refactored to check the instantiate-ability of the code better.
992-
if let Some(def_id) = def_id.as_local()
993-
&& let DefKind::AnonConst = tcx.def_kind(def_id)
994-
&& let hir::Node::AnonConst(anon) = tcx.hir_node_by_def_id(def_id)
995-
&& let expr = &tcx.hir_body(anon.body).value
996-
&& let hir::ExprKind::Path(hir::QPath::Resolved(None, path)) = expr.kind
997-
&& let Res::Def(DefKind::ConstParam, _def_id) = path.res
998-
{
999-
// Do not evaluate bare `const` params, as those would ICE and are only
1000-
// usable if `#![feature(generic_const_exprs)]` is enabled.
1001-
} else {
1002-
// Evaluate the constant proactively, to emit an error if the constant has
1003-
// an unconditional error. We only do so if the const has no type params.
996+
if let Some(def_id) = field.value {
997+
if !own_params_require_monomorphization {
1004998
let _ = tcx.const_eval_poly(def_id);
999+
} else if tcx.features().default_field_values()
1000+
&& let Some(local_def_id) = def_id.as_local()
1001+
{
1002+
// Do not redundantly trigger lint if the feature is not actually available.
1003+
1004+
// We use the callsite span for default values that are actually macro calls
1005+
// into other crates, like for example `field: () = panic!(),`.
1006+
let field_span = tcx.def_span(def_id).source_callsite();
1007+
let mut multispan: MultiSpan = field_span.into();
1008+
multispan
1009+
.push_span_label(field_span, "this can't be const-evaluated until use");
1010+
let struct_start = tcx.def_span(item).shrink_to_lo();
1011+
multispan.push_span_context(tcx.def_span(field.did));
1012+
multispan.push_span_context(struct_start);
1013+
tcx.emit_node_span_lint(
1014+
UNEVALUATED_DEFAULT_FIELD_VALUE,
1015+
tcx.local_def_id_to_hir_id(local_def_id),
1016+
multispan,
1017+
UnevaluatedDefaultFieldValue {
1018+
field: field.name,
1019+
ty: with_no_trimmed_paths!(tcx.def_path_str(item)),
1020+
padding: tcx
1021+
.sess
1022+
.source_map()
1023+
.indentation_before(struct_start)
1024+
.unwrap_or_default(),
1025+
struct_start,
1026+
},
1027+
);
10051028
}
10061029
}
10071030
let field_id = field.did.expect_local();

‎compiler/rustc_hir_analysis/src/diagnostics.rs‎

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2157,3 +2157,24 @@ pub(crate) struct ParamInTyOfConstParam<'tcx> {
21572157
pub(crate) span: Span,
21582158
pub(crate) ty: Ty<'tcx>,
21592159
}
2160+
2161+
#[derive(Diagnostic)]
2162+
#[diag(
2163+
"field `{$field}` has a default value that is only checked when a value of `{$ty}` is \
2164+
constructed"
2165+
)]
2166+
#[help(
2167+
"structs and enums with type and const parameters only evaluate their default field values \
2168+
during construction, not eagerly when declared"
2169+
)]
2170+
pub(crate) struct UnevaluatedDefaultFieldValue {
2171+
pub(crate) field: Symbol,
2172+
pub(crate) ty: String,
2173+
#[suggestion(
2174+
"if this behavior is acceptable, allow the lint and preferably write a test relying on the default value",
2175+
code = "{padding}#[expect(unevaluated_default_field_value)]\n",
2176+
applicability = "maybe-incorrect"
2177+
)]
2178+
pub(crate) struct_start: Span,
2179+
pub(crate) padding: String,
2180+
}

‎compiler/rustc_lint_defs/src/builtin.rs‎

Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -125,6 +125,7 @@ pub mod hardwired {
125125
UNCONDITIONAL_PANIC,
126126
UNCONDITIONAL_RECURSION,
127127
UNCOVERED_PARAM_IN_PROJECTION,
128+
UNEVALUATED_DEFAULT_FIELD_VALUE,
128129
UNEXPECTED_CFGS,
129130
UNFULFILLED_LINT_EXPECTATIONS,
130131
UNINHABITED_STATIC,
@@ -5983,3 +5984,38 @@ declare_lint! {
59835984
};
59845985
crate_level_only
59855986
}
5987+
5988+
declare_lint! {
5989+
/// The `unevaluated_default_field_value` lint detects default field values that don't get
5990+
/// evaluated at the definition site because the corresponding struct or enum has type or const
5991+
/// parameters, meaning they only get evaluated when the struct or enum gets constructed using
5992+
/// that default (post-monormophization).
5993+
///
5994+
/// ### Example
5995+
///
5996+
/// ```rust,no_run
5997+
/// #![feature(default_field_values)]
5998+
///
5999+
/// struct Struct<const T: u8> {
6000+
/// field1: u8 = 100 + T, // none of these values will be checked until `Struct` is
6001+
/// field2: u8 = 100, // constructed, even if they don't refer to the cont param
6002+
/// }
6003+
/// ```
6004+
///
6005+
/// {{produces}}
6006+
///
6007+
/// ### Explanation
6008+
///
6009+
/// Const evaluation requires all values to be known. In the case of default field values, they
6010+
/// will get evaluated eagerly, but if there are any type or const parameters, the evaluation of
6011+
/// the default will only occur when materializing a value of its owning struct *and* leaving
6012+
/// the field with a default value unspecified. For the example above, if you wrote
6013+
/// `let _: Struct<180> = Struct { .. };`, you would get a const evaluation compile error.
6014+
///
6015+
/// This inconsistency can be confusing, and surprising, because the fields *are* sometimes
6016+
/// evaluated eagerly.
6017+
pub UNEVALUATED_DEFAULT_FIELD_VALUE,
6018+
Warn,
6019+
r#"detects default field values on types that have const parameters"#,
6020+
@feature_gate = default_field_values;
6021+
}

‎compiler/rustc_middle/src/lint.rs‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -506,6 +506,9 @@ pub fn emit_lint_base<'a, D: Diagnostic<'a> + 'a>(
506506
for (label_span, label) in span.span_labels_raw() {
507507
err.span.push_span_diag(*label_span, label.clone());
508508
}
509+
for span in span.span_context() {
510+
err.span.push_span_context(*span);
511+
}
509512
}
510513

511514
if disable_suggestions {

‎tests/ui/structs/default-field-values/failures.rs‎

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -19,10 +19,10 @@ pub struct Bar {
1919

2020
#[derive(Default)]
2121
pub struct Qux<const C: i32> {
22-
bar: S = Self::S,
23-
baz: i32 = foo(),
24-
bat: i32 = <Qux<{ C }> as T>::K,
25-
bay: i32 = C,
22+
bar: S = Self::S, //~ WARN
23+
baz: i32 = foo(), //~ WARN
24+
bat: i32 = <Qux<{ C }> as T>::K, //~ WARN
25+
bay: i32 = C, //~ WARN
2626
}
2727

2828
pub struct Rak(i32 = 42); //~ ERROR default fields are not supported in tuple structs

‎tests/ui/structs/default-field-values/failures.stderr‎

Lines changed: 61 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -24,6 +24,66 @@ error: unions cannot have default field values
2424
LL | y: f32 = 2.,
2525
| ^^
2626

27+
warning: field `bar` has a default value that is only checked when a value of `Qux` is constructed
28+
--> $DIR/failures.rs:22:14
29+
|
30+
LL | pub struct Qux<const C: i32> {
31+
LL | bar: S = Self::S,
32+
| ^^^^^^^ this can't be const-evaluated until use
33+
|
34+
= help: structs and enums with type and const parameters only evaluate their default field values during construction, not eagerly when declared
35+
= note: `#[warn(unevaluated_default_field_value)]` on by default
36+
help: if this behavior is acceptable, allow the lint and preferably write a test relying on the default value
37+
|
38+
LL + #[expect(unevaluated_default_field_value)]
39+
LL | pub struct Qux<const C: i32> {
40+
|
41+
42+
warning: field `baz` has a default value that is only checked when a value of `Qux` is constructed
43+
--> $DIR/failures.rs:23:16
44+
|
45+
LL | pub struct Qux<const C: i32> {
46+
LL | bar: S = Self::S,
47+
LL | baz: i32 = foo(),
48+
| ^^^^^ this can't be const-evaluated until use
49+
|
50+
= help: structs and enums with type and const parameters only evaluate their default field values during construction, not eagerly when declared
51+
help: if this behavior is acceptable, allow the lint and preferably write a test relying on the default value
52+
|
53+
LL + #[expect(unevaluated_default_field_value)]
54+
LL | pub struct Qux<const C: i32> {
55+
|
56+
57+
warning: field `bat` has a default value that is only checked when a value of `Qux` is constructed
58+
--> $DIR/failures.rs:24:16
59+
|
60+
LL | pub struct Qux<const C: i32> {
61+
...
62+
LL | bat: i32 = <Qux<{ C }> as T>::K,
63+
| ^^^^^^^^^^^^^^^^^^^^ this can't be const-evaluated until use
64+
|
65+
= help: structs and enums with type and const parameters only evaluate their default field values during construction, not eagerly when declared
66+
help: if this behavior is acceptable, allow the lint and preferably write a test relying on the default value
67+
|
68+
LL + #[expect(unevaluated_default_field_value)]
69+
LL | pub struct Qux<const C: i32> {
70+
|
71+
72+
warning: field `bay` has a default value that is only checked when a value of `Qux` is constructed
73+
--> $DIR/failures.rs:25:16
74+
|
75+
LL | pub struct Qux<const C: i32> {
76+
...
77+
LL | bay: i32 = C,
78+
| ^ this can't be const-evaluated until use
79+
|
80+
= help: structs and enums with type and const parameters only evaluate their default field values during construction, not eagerly when declared
81+
help: if this behavior is acceptable, allow the lint and preferably write a test relying on the default value
82+
|
83+
LL + #[expect(unevaluated_default_field_value)]
84+
LL | pub struct Qux<const C: i32> {
85+
|
86+
2787
error[E0277]: the trait bound `S: Default` is not satisfied
2888
--> $DIR/failures.rs:16:5
2989
|
@@ -114,7 +174,7 @@ LL - let _ = Rak(.., 0);
114174
LL + let _ = Rak(0);
115175
|
116176

117-
error: aborting due to 10 previous errors
177+
error: aborting due to 10 previous errors; 4 warnings emitted
118178

119179
Some errors have detailed explanations: E0061, E0277, E0308.
120180
For more information about an error, try `rustc --explain E0061`.
Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,37 @@
1+
//@ build-fail
2+
// https://github.com/rust-lang/rust/issues/146496
3+
#![feature(default_field_values)]
4+
5+
struct Z<const X: usize> {
6+
// Ensure that proper context is shown in lint.
7+
multiline_field:
8+
()
9+
= { //~ WARN default value
10+
f::<X>();
11+
panic!();
12+
//~^ ERROR: explicit panic
13+
//~| ERROR: explicit panic
14+
},
15+
}
16+
17+
pub const fn f<const N: usize>() {
18+
// *If* we const evaluated `Z.multiline_field` at definition, but then bailed because `f` needs
19+
// to be const evaluated, commenting out this line would suddenly allow `f` to be evaluated and
20+
// cause the panic in `multiline_field` to be reached.
21+
let _ = [0u8; N];
22+
}
23+
24+
const fn const_use_generically<const X: usize>() {
25+
let x: Z<X> = Z { .. };
26+
}
27+
28+
fn use_generically<const X: usize>() {
29+
let x: Z<X> = Z { .. };
30+
}
31+
32+
fn main() {
33+
let x: Z<1> = Z { .. };
34+
use_generically::<2>();
35+
const_use_generically::<3>();
36+
const { const_use_generically::<4>() };
37+
}
Lines changed: 73 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,73 @@
1+
warning: field `multiline_field` has a default value that is only checked when a value of `Z` is constructed
2+
--> $DIR/field-references-param-accurate-span.rs:9:15
3+
|
4+
LL | struct Z<const X: usize> {
5+
LL | // Ensure that proper context is shown in lint.
6+
LL | multiline_field:
7+
LL | ()
8+
LL | = {
9+
| _______________^
10+
LL | | f::<X>();
11+
LL | | panic!();
12+
LL | |
13+
LL | |
14+
LL | | },
15+
| |_____________^ this can't be const-evaluated until use
16+
|
17+
= help: structs and enums with type and const parameters only evaluate their default field values during construction, not eagerly when declared
18+
= note: `#[warn(unevaluated_default_field_value)]` on by default
19+
help: if this behavior is acceptable, allow the lint and preferably write a test relying on the default value
20+
|
21+
LL + #[expect(unevaluated_default_field_value)]
22+
LL | struct Z<const X: usize> {
23+
|
24+
25+
error[E0080]: evaluation panicked: explicit panic
26+
--> $DIR/field-references-param-accurate-span.rs:11:17
27+
|
28+
LL | panic!();
29+
| ^^^^^^^^ evaluation of `Z::<1>::multiline_field::{constant#0}` failed here
30+
31+
note: erroneous constant encountered
32+
--> $DIR/field-references-param-accurate-span.rs:33:19
33+
|
34+
LL | let x: Z<1> = Z { .. };
35+
| ^^^^^^^^
36+
37+
note: erroneous constant encountered
38+
--> $DIR/field-references-param-accurate-span.rs:33:19
39+
|
40+
LL | let x: Z<1> = Z { .. };
41+
| ^^^^^^^^
42+
|
43+
= note: duplicate diagnostic emitted due to `-Z deduplicate-diagnostics=no`
44+
45+
error[E0080]: evaluation panicked: explicit panic
46+
--> $DIR/field-references-param-accurate-span.rs:11:17
47+
|
48+
LL | panic!();
49+
| ^^^^^^^^ evaluation of `Z::<4>::multiline_field::{constant#0}` failed here
50+
51+
note: erroneous constant encountered
52+
--> $DIR/field-references-param-accurate-span.rs:25:19
53+
|
54+
LL | let x: Z<X> = Z { .. };
55+
| ^^^^^^^^
56+
57+
note: erroneous constant encountered
58+
--> $DIR/field-references-param-accurate-span.rs:36:5
59+
|
60+
LL | const { const_use_generically::<4>() };
61+
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
62+
63+
note: erroneous constant encountered
64+
--> $DIR/field-references-param-accurate-span.rs:36:5
65+
|
66+
LL | const { const_use_generically::<4>() };
67+
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
68+
|
69+
= note: duplicate diagnostic emitted due to `-Z deduplicate-diagnostics=no`
70+
71+
error: aborting due to 2 previous errors; 1 warning emitted
72+
73+
For more information about this error, try `rustc --explain E0080`.

0 commit comments

Comments
 (0)