Skip to content

Commit 0ffcac3

Browse files
committed
Introduce default_field_values feature
Initial implementation of `#[feature(default_field_values]`, proposed in rust-lang/rfcs#3681. Support default fields in enum struct variant Allow default values in an enum struct variant definition: ```rust pub enum Bar { Foo { bar: S = S, baz: i32 = 42 + 3, } } ``` Allow using `..` without a base on an enum struct variant ```rust Bar::Foo { .. } ``` `#[derive(Default)]` doesn't account for these as it is still gating `#[default]` only being allowed on unit variants. Support `#[derive(Default)]` on enum struct variants with all defaulted fields ```rust pub enum Bar { #[default] Foo { bar: S = S, baz: i32 = 42 + 3, } } ``` Check for missing fields in typeck instead of mir_build. Expand test with `const` param case (needs `generic_const_exprs` enabled). Properly instantiate MIR const The following works: ```rust struct S<A> { a: Vec<A> = Vec::new(), } S::<i32> { .. } ```
1 parent 7db7489 commit 0ffcac3

File tree

65 files changed

+923
-319
lines changed

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

65 files changed

+923
-319
lines changed

compiler/rustc_ast/src/ast.rs

+1
Original file line numberDiff line numberDiff line change
@@ -3067,6 +3067,7 @@ pub struct FieldDef {
30673067
pub ident: Option<Ident>,
30683068

30693069
pub ty: P<Ty>,
3070+
pub default: Option<AnonConst>,
30703071
pub is_placeholder: bool,
30713072
}
30723073

compiler/rustc_ast/src/mut_visit.rs

+2-1
Original file line numberDiff line numberDiff line change
@@ -1115,13 +1115,14 @@ fn walk_poly_trait_ref<T: MutVisitor>(vis: &mut T, p: &mut PolyTraitRef) {
11151115
}
11161116

11171117
pub fn walk_field_def<T: MutVisitor>(visitor: &mut T, fd: &mut FieldDef) {
1118-
let FieldDef { span, ident, vis, id, ty, attrs, is_placeholder: _, safety } = fd;
1118+
let FieldDef { span, ident, vis, id, ty, attrs, is_placeholder: _, safety, default } = fd;
11191119
visitor.visit_id(id);
11201120
visit_attrs(visitor, attrs);
11211121
visitor.visit_vis(vis);
11221122
visit_safety(visitor, safety);
11231123
visit_opt(ident, |ident| visitor.visit_ident(ident));
11241124
visitor.visit_ty(ty);
1125+
visit_opt(default, |default| visitor.visit_anon_const(default));
11251126
visitor.visit_span(span);
11261127
}
11271128

compiler/rustc_ast/src/visit.rs

+3-1
Original file line numberDiff line numberDiff line change
@@ -961,11 +961,13 @@ pub fn walk_struct_def<'a, V: Visitor<'a>>(
961961
}
962962

963963
pub fn walk_field_def<'a, V: Visitor<'a>>(visitor: &mut V, field: &'a FieldDef) -> V::Result {
964-
let FieldDef { attrs, id: _, span: _, vis, ident, ty, is_placeholder: _, safety: _ } = field;
964+
let FieldDef { attrs, id: _, span: _, vis, ident, ty, is_placeholder: _, safety: _, default } =
965+
field;
965966
walk_list!(visitor, visit_attribute, attrs);
966967
try_visit!(visitor.visit_vis(vis));
967968
visit_opt!(visitor, visit_ident, ident);
968969
try_visit!(visitor.visit_ty(ty));
970+
visit_opt!(visitor, visit_anon_const, &*default);
969971
V::Result::output()
970972
}
971973

compiler/rustc_ast_lowering/messages.ftl

-4
Original file line numberDiff line numberDiff line change
@@ -45,10 +45,6 @@ ast_lowering_bad_return_type_notation_output =
4545
4646
ast_lowering_bad_return_type_notation_position = return type notation not allowed in this position yet
4747
48-
ast_lowering_base_expression_double_dot =
49-
base expression required after `..`
50-
.suggestion = add a base expression here
51-
5248
ast_lowering_clobber_abi_not_supported =
5349
`clobber_abi` is not supported on this target
5450

compiler/rustc_ast_lowering/src/errors.rs

-8
Original file line numberDiff line numberDiff line change
@@ -114,14 +114,6 @@ pub(crate) struct UnderscoreExprLhsAssign {
114114
pub span: Span,
115115
}
116116

117-
#[derive(Diagnostic)]
118-
#[diag(ast_lowering_base_expression_double_dot, code = E0797)]
119-
pub(crate) struct BaseExpressionDoubleDot {
120-
#[primary_span]
121-
#[suggestion(code = "/* expr */", applicability = "has-placeholders", style = "verbose")]
122-
pub span: Span,
123-
}
124-
125117
#[derive(Diagnostic)]
126118
#[diag(ast_lowering_await_only_in_async_fn_and_blocks, code = E0728)]
127119
pub(crate) struct AwaitOnlyInAsyncFnAndBlocks {

compiler/rustc_ast_lowering/src/expr.rs

+8-11
Original file line numberDiff line numberDiff line change
@@ -19,10 +19,10 @@ use thin_vec::{ThinVec, thin_vec};
1919
use visit::{Visitor, walk_expr};
2020

2121
use super::errors::{
22-
AsyncCoroutinesNotSupported, AwaitOnlyInAsyncFnAndBlocks, BaseExpressionDoubleDot,
23-
ClosureCannotBeStatic, CoroutineTooManyParameters,
24-
FunctionalRecordUpdateDestructuringAssignment, InclusiveRangeWithNoEnd, MatchArmWithNoBody,
25-
NeverPatternWithBody, NeverPatternWithGuard, UnderscoreExprLhsAssign,
22+
AsyncCoroutinesNotSupported, AwaitOnlyInAsyncFnAndBlocks, ClosureCannotBeStatic,
23+
CoroutineTooManyParameters, FunctionalRecordUpdateDestructuringAssignment,
24+
InclusiveRangeWithNoEnd, MatchArmWithNoBody, NeverPatternWithBody, NeverPatternWithGuard,
25+
UnderscoreExprLhsAssign,
2626
};
2727
use super::{
2828
GenericArgsMode, ImplTraitContext, LoweringContext, ParamMode, ResolverAstLoweringExt,
@@ -359,12 +359,9 @@ impl<'hir> LoweringContext<'_, 'hir> {
359359
),
360360
ExprKind::Struct(se) => {
361361
let rest = match &se.rest {
362-
StructRest::Base(e) => Some(self.lower_expr(e)),
363-
StructRest::Rest(sp) => {
364-
let guar = self.dcx().emit_err(BaseExpressionDoubleDot { span: *sp });
365-
Some(&*self.arena.alloc(self.expr_err(*sp, guar)))
366-
}
367-
StructRest::None => None,
362+
StructRest::Base(e) => hir::Rest::Base(self.lower_expr(e)),
363+
StructRest::Rest(sp) => hir::Rest::DefaultFields(*sp),
364+
StructRest::None => hir::Rest::None,
368365
};
369366
hir::ExprKind::Struct(
370367
self.arena.alloc(self.lower_qpath(
@@ -1540,7 +1537,7 @@ impl<'hir> LoweringContext<'_, 'hir> {
15401537
hir::ExprKind::Struct(
15411538
self.arena.alloc(hir::QPath::LangItem(lang_item, self.lower_span(span))),
15421539
fields,
1543-
None,
1540+
hir::Rest::None,
15441541
)
15451542
}
15461543

compiler/rustc_ast_lowering/src/item.rs

+1
Original file line numberDiff line numberDiff line change
@@ -723,6 +723,7 @@ impl<'hir> LoweringContext<'_, 'hir> {
723723
None => Ident::new(sym::integer(index), self.lower_span(f.span)),
724724
},
725725
vis_span: self.lower_span(f.vis.span),
726+
default: f.default.as_ref().map(|v| self.lower_anon_const_to_anon_const(v)),
726727
ty,
727728
safety: self.lower_safety(f.safety, hir::Safety::Safe),
728729
}

compiler/rustc_ast_passes/src/feature_gate.rs

+1
Original file line numberDiff line numberDiff line change
@@ -551,6 +551,7 @@ pub fn check_crate(krate: &ast::Crate, sess: &Session, features: &Features) {
551551
gate_all!(builtin_syntax, "`builtin #` syntax is unstable");
552552
gate_all!(explicit_tail_calls, "`become` expression is experimental");
553553
gate_all!(generic_const_items, "generic const items are experimental");
554+
gate_all!(default_field_values, "default values on `struct` fields aren't supported");
554555
gate_all!(fn_delegation, "functions delegation is not yet fully implemented");
555556
gate_all!(postfix_match, "postfix match is experimental");
556557
gate_all!(mut_ref, "mutable by-reference bindings are experimental");

compiler/rustc_borrowck/src/diagnostics/conflict_errors.rs

+4-2
Original file line numberDiff line numberDiff line change
@@ -1151,7 +1151,9 @@ impl<'infcx, 'tcx> MirBorrowckCtxt<'_, 'infcx, 'tcx> {
11511151
expr: &hir::Expr<'_>,
11521152
) {
11531153
let typeck_results = self.infcx.tcx.typeck(self.mir_def_id());
1154-
let hir::ExprKind::Struct(struct_qpath, fields, Some(base)) = expr.kind else { return };
1154+
let hir::ExprKind::Struct(struct_qpath, fields, hir::Rest::Base(base)) = expr.kind else {
1155+
return;
1156+
};
11551157
let hir::QPath::Resolved(_, path) = struct_qpath else { return };
11561158
let hir::def::Res::Def(_, def_id) = path.res else { return };
11571159
let Some(expr_ty) = typeck_results.node_type_opt(expr.hir_id) else { return };
@@ -1239,7 +1241,7 @@ impl<'infcx, 'tcx> MirBorrowckCtxt<'_, 'infcx, 'tcx> {
12391241
expr: &'tcx hir::Expr<'tcx>,
12401242
use_spans: Option<UseSpans<'tcx>>,
12411243
) {
1242-
if let hir::ExprKind::Struct(_, _, Some(_)) = expr.kind {
1244+
if let hir::ExprKind::Struct(_, _, hir::Rest::Base(_)) = expr.kind {
12431245
// We have `S { foo: val, ..base }`. In `check_aggregate_rvalue` we have a single
12441246
// `Location` that covers both the `S { ... }` literal, all of its fields and the
12451247
// `base`. If the move happens because of `S { foo: val, bar: base.bar }` the `expr`

compiler/rustc_builtin_macros/src/deriving/decodable.rs

+1-1
Original file line numberDiff line numberDiff line change
@@ -205,7 +205,7 @@ where
205205
let fields = fields
206206
.iter()
207207
.enumerate()
208-
.map(|(i, &(ident, span))| {
208+
.map(|(i, &(ident, span, _))| {
209209
let arg = getarg(cx, span, ident.name, i);
210210
cx.field_imm(span, ident, arg)
211211
})

compiler/rustc_builtin_macros/src/deriving/default.rs

+56-11
Original file line numberDiff line numberDiff line change
@@ -54,26 +54,38 @@ pub(crate) fn expand_deriving_default(
5454
trait_def.expand(cx, mitem, item, push)
5555
}
5656

57+
fn default_call(cx: &ExtCtxt<'_>, span: Span) -> ast::ptr::P<ast::Expr> {
58+
// Note that `kw::Default` is "default" and `sym::Default` is "Default"!
59+
let default_ident = cx.std_path(&[kw::Default, sym::Default, kw::Default]);
60+
cx.expr_call_global(span, default_ident, ThinVec::new())
61+
}
62+
5763
fn default_struct_substructure(
5864
cx: &ExtCtxt<'_>,
5965
trait_span: Span,
6066
substr: &Substructure<'_>,
6167
summary: &StaticFields,
6268
) -> BlockOrExpr {
63-
// Note that `kw::Default` is "default" and `sym::Default` is "Default"!
64-
let default_ident = cx.std_path(&[kw::Default, sym::Default, kw::Default]);
65-
let default_call = |span| cx.expr_call_global(span, default_ident.clone(), ThinVec::new());
66-
6769
let expr = match summary {
6870
Unnamed(_, IsTuple::No) => cx.expr_ident(trait_span, substr.type_ident),
6971
Unnamed(fields, IsTuple::Yes) => {
70-
let exprs = fields.iter().map(|sp| default_call(*sp)).collect();
72+
let exprs = fields.iter().map(|sp| default_call(cx, *sp)).collect();
7173
cx.expr_call_ident(trait_span, substr.type_ident, exprs)
7274
}
7375
Named(fields) => {
7476
let default_fields = fields
7577
.iter()
76-
.map(|&(ident, span)| cx.field_imm(span, ident, default_call(span)))
78+
.map(|(ident, span, default_val)| {
79+
let value = match default_val {
80+
// We use `Default::default()`.
81+
None => default_call(cx, *span),
82+
// We use the field default const expression.
83+
Some(val) => {
84+
cx.expr(val.value.span, ast::ExprKind::ConstBlock(val.clone()))
85+
}
86+
};
87+
cx.field_imm(*span, *ident, value)
88+
})
7789
.collect();
7890
cx.expr_struct_ident(trait_span, substr.type_ident, default_fields)
7991
}
@@ -93,10 +105,38 @@ fn default_enum_substructure(
93105
} {
94106
Ok(default_variant) => {
95107
// We now know there is exactly one unit variant with exactly one `#[default]` attribute.
96-
cx.expr_path(cx.path(default_variant.span, vec![
97-
Ident::new(kw::SelfUpper, default_variant.span),
98-
default_variant.ident,
99-
]))
108+
match &default_variant.data {
109+
VariantData::Unit(_) => cx.expr_path(cx.path(default_variant.span, vec![
110+
Ident::new(kw::SelfUpper, default_variant.span),
111+
default_variant.ident,
112+
])),
113+
VariantData::Struct { fields, .. } => {
114+
// This only happens if `#![feature(default_field_values)]`. We have validated
115+
// all fields have default values in the definition.
116+
let default_fields = fields
117+
.iter()
118+
.map(|field| {
119+
cx.field_imm(field.span, field.ident.unwrap(), match &field.default {
120+
// We use `Default::default()`.
121+
None => default_call(cx, field.span),
122+
// We use the field default const expression.
123+
Some(val) => {
124+
cx.expr(val.value.span, ast::ExprKind::ConstBlock(val.clone()))
125+
}
126+
})
127+
})
128+
.collect();
129+
let path = cx.path(default_variant.span, vec![
130+
Ident::new(kw::SelfUpper, default_variant.span),
131+
default_variant.ident,
132+
]);
133+
cx.expr_struct(default_variant.span, path, default_fields)
134+
}
135+
// Logic error in `extract_default_variant`.
136+
VariantData::Tuple(..) => {
137+
cx.dcx().bug("encountered tuple variant annotated with `#[default]`")
138+
}
139+
}
100140
}
101141
Err(guar) => DummyResult::raw_expr(trait_span, Some(guar)),
102142
};
@@ -156,7 +196,12 @@ fn extract_default_variant<'a>(
156196
}
157197
};
158198

159-
if !matches!(variant.data, VariantData::Unit(..)) {
199+
if cx.ecfg.features.default_field_values()
200+
&& let VariantData::Struct { fields, .. } = &variant.data
201+
&& fields.iter().all(|f| f.default.is_some())
202+
{
203+
// Allowed
204+
} else if !matches!(variant.data, VariantData::Unit(..)) {
160205
let guar = cx.dcx().emit_err(errors::NonUnitDefault { span: variant.ident.span });
161206
return Err(guar);
162207
}

compiler/rustc_builtin_macros/src/deriving/generic/mod.rs

+4-4
Original file line numberDiff line numberDiff line change
@@ -182,8 +182,8 @@ pub(crate) use StaticFields::*;
182182
pub(crate) use SubstructureFields::*;
183183
use rustc_ast::ptr::P;
184184
use rustc_ast::{
185-
self as ast, BindingMode, ByRef, EnumDef, Expr, GenericArg, GenericParamKind, Generics,
186-
Mutability, PatKind, VariantData,
185+
self as ast, AnonConst, BindingMode, ByRef, EnumDef, Expr, GenericArg, GenericParamKind,
186+
Generics, Mutability, PatKind, VariantData,
187187
};
188188
use rustc_attr as attr;
189189
use rustc_expand::base::{Annotatable, ExtCtxt};
@@ -296,7 +296,7 @@ pub(crate) enum StaticFields {
296296
/// Tuple and unit structs/enum variants like this.
297297
Unnamed(Vec<Span>, IsTuple),
298298
/// Normal structs/struct variants.
299-
Named(Vec<(Ident, Span)>),
299+
Named(Vec<(Ident, Span, Option<AnonConst>)>),
300300
}
301301

302302
/// A summary of the possible sets of fields.
@@ -1449,7 +1449,7 @@ impl<'a> TraitDef<'a> {
14491449
for field in struct_def.fields() {
14501450
let sp = field.span.with_ctxt(self.span.ctxt());
14511451
match field.ident {
1452-
Some(ident) => named_idents.push((ident, sp)),
1452+
Some(ident) => named_idents.push((ident, sp, field.default.clone())),
14531453
_ => just_spans.push(sp),
14541454
}
14551455
}

compiler/rustc_expand/src/placeholders.rs

+1
Original file line numberDiff line numberDiff line change
@@ -174,6 +174,7 @@ pub(crate) fn placeholder(
174174
vis,
175175
is_placeholder: true,
176176
safety: Safety::Default,
177+
default: None,
177178
}]),
178179
AstFragmentKind::Variants => AstFragment::Variants(smallvec![ast::Variant {
179180
attrs: Default::default(),

compiler/rustc_feature/src/unstable.rs

+3
Original file line numberDiff line numberDiff line change
@@ -453,6 +453,9 @@ declare_features! (
453453
(unstable, custom_test_frameworks, "1.30.0", Some(50297)),
454454
/// Allows declarative macros 2.0 (`macro`).
455455
(unstable, decl_macro, "1.17.0", Some(39412)),
456+
/// Allows the use of default values on struct definitions and the construction of struct
457+
/// literals with the functional update syntax without a base.
458+
(unstable, default_field_values, "CURRENT_RUSTC_VERSION", Some(132162)),
456459
/// Allows using `#[deprecated_safe]` to deprecate the safeness of a function or trait
457460
(unstable, deprecated_safe, "1.61.0", Some(94978)),
458461
/// Allows having using `suggestion` in the `#[deprecated]` attribute.

compiler/rustc_hir/src/hir.rs

+31-10
Original file line numberDiff line numberDiff line change
@@ -1868,7 +1868,12 @@ impl Expr<'_> {
18681868
base.can_have_side_effects()
18691869
}
18701870
ExprKind::Struct(_, fields, init) => {
1871-
fields.iter().map(|field| field.expr).chain(init).any(|e| e.can_have_side_effects())
1871+
let init_side_effects = match init {
1872+
Rest::Base(init) => init.can_have_side_effects(),
1873+
Rest::DefaultFields(_) | Rest::None => false,
1874+
};
1875+
fields.iter().map(|field| field.expr).any(|e| e.can_have_side_effects())
1876+
|| init_side_effects
18721877
}
18731878

18741879
ExprKind::Array(args)
@@ -1937,20 +1942,28 @@ impl Expr<'_> {
19371942
ExprKind::Path(QPath::Resolved(None, path2)),
19381943
) => path1.res == path2.res,
19391944
(
1940-
ExprKind::Struct(QPath::LangItem(LangItem::RangeTo, _), [val1], None),
1941-
ExprKind::Struct(QPath::LangItem(LangItem::RangeTo, _), [val2], None),
1945+
ExprKind::Struct(QPath::LangItem(LangItem::RangeTo, _), [val1], Rest::None),
1946+
ExprKind::Struct(QPath::LangItem(LangItem::RangeTo, _), [val2], Rest::None),
19421947
)
19431948
| (
1944-
ExprKind::Struct(QPath::LangItem(LangItem::RangeToInclusive, _), [val1], None),
1945-
ExprKind::Struct(QPath::LangItem(LangItem::RangeToInclusive, _), [val2], None),
1949+
ExprKind::Struct(
1950+
QPath::LangItem(LangItem::RangeToInclusive, _),
1951+
[val1],
1952+
Rest::None,
1953+
),
1954+
ExprKind::Struct(
1955+
QPath::LangItem(LangItem::RangeToInclusive, _),
1956+
[val2],
1957+
Rest::None,
1958+
),
19461959
)
19471960
| (
1948-
ExprKind::Struct(QPath::LangItem(LangItem::RangeFrom, _), [val1], None),
1949-
ExprKind::Struct(QPath::LangItem(LangItem::RangeFrom, _), [val2], None),
1961+
ExprKind::Struct(QPath::LangItem(LangItem::RangeFrom, _), [val1], Rest::None),
1962+
ExprKind::Struct(QPath::LangItem(LangItem::RangeFrom, _), [val2], Rest::None),
19501963
) => val1.expr.equivalent_for_indexing(val2.expr),
19511964
(
1952-
ExprKind::Struct(QPath::LangItem(LangItem::Range, _), [val1, val3], None),
1953-
ExprKind::Struct(QPath::LangItem(LangItem::Range, _), [val2, val4], None),
1965+
ExprKind::Struct(QPath::LangItem(LangItem::Range, _), [val1, val3], Rest::None),
1966+
ExprKind::Struct(QPath::LangItem(LangItem::Range, _), [val2, val4], Rest::None),
19541967
) => {
19551968
val1.expr.equivalent_for_indexing(val2.expr)
19561969
&& val3.expr.equivalent_for_indexing(val4.expr)
@@ -2107,7 +2120,7 @@ pub enum ExprKind<'hir> {
21072120
///
21082121
/// E.g., `Foo {x: 1, y: 2}`, or `Foo {x: 1, .. base}`,
21092122
/// where `base` is the `Option<Expr>`.
2110-
Struct(&'hir QPath<'hir>, &'hir [ExprField<'hir>], Option<&'hir Expr<'hir>>),
2123+
Struct(&'hir QPath<'hir>, &'hir [ExprField<'hir>], Rest<'hir>),
21112124

21122125
/// An array literal constructed from one repeated element.
21132126
///
@@ -2122,6 +2135,13 @@ pub enum ExprKind<'hir> {
21222135
Err(rustc_span::ErrorGuaranteed),
21232136
}
21242137

2138+
#[derive(Debug, Clone, Copy, HashStable_Generic)]
2139+
pub enum Rest<'hir> {
2140+
Base(&'hir Expr<'hir>),
2141+
DefaultFields(Span),
2142+
None,
2143+
}
2144+
21252145
/// Represents an optionally `Self`-qualified value/type path or associated extension.
21262146
///
21272147
/// To resolve the path to a `DefId`, call [`qpath_res`].
@@ -3178,6 +3198,7 @@ pub struct FieldDef<'hir> {
31783198
pub def_id: LocalDefId,
31793199
pub ty: &'hir Ty<'hir>,
31803200
pub safety: Safety,
3201+
pub default: Option<&'hir AnonConst>,
31813202
}
31823203

31833204
impl FieldDef<'_> {

0 commit comments

Comments
 (0)