Skip to content

Commit 877fc0d

Browse files
committed
Detect struct construction with private field in field with default
When trying to construct a struct that has a public field of a private type, suggest using `..` if that field has a default value. ``` error[E0603]: struct `Priv1` is private --> $DIR/non-exhaustive-ctor.rs:25:39 | LL | let _ = S { field: (), field1: m::Priv1 {} }; | ------ ^^^^^ private struct | | | while setting this field | note: the struct `Priv1` is defined here --> $DIR/non-exhaustive-ctor.rs:14:4 | LL | struct Priv1 {} | ^^^^^^^^^^^^ help: the field `field1` you're trying to set has a default value, you can use `..` to use it | LL | let _ = S { field: (), .. }; | ~~ ```
1 parent 2801f9a commit 877fc0d

File tree

11 files changed

+290
-36
lines changed

11 files changed

+290
-36
lines changed

compiler/rustc_metadata/src/rmeta/decoder/cstore_impl.rs

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -420,6 +420,7 @@ provide! { tcx, def_id, other, cdata,
420420

421421
crate_extern_paths => { cdata.source().paths().cloned().collect() }
422422
expn_that_defined => { cdata.get_expn_that_defined(def_id.index, tcx.sess) }
423+
default_field => { cdata.get_default_field(def_id.index) }
423424
is_doc_hidden => { cdata.get_attr_flags(def_id.index).contains(AttrFlags::IS_DOC_HIDDEN) }
424425
doc_link_resolutions => { tcx.arena.alloc(cdata.get_doc_link_resolutions(def_id.index)) }
425426
doc_link_traits_in_scope => {

compiler/rustc_middle/src/query/mod.rs

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1855,6 +1855,13 @@ rustc_queries! {
18551855
feedable
18561856
}
18571857

1858+
/// Returns whether the impl or associated function has the `default` keyword.
1859+
query default_field(def_id: DefId) -> Option<DefId> {
1860+
desc { |tcx| "looking up the `const` corresponding to the default for `{}`", tcx.def_path_str(def_id) }
1861+
separate_provide_extern
1862+
feedable
1863+
}
1864+
18581865
query check_well_formed(key: LocalDefId) -> Result<(), ErrorGuaranteed> {
18591866
desc { |tcx| "checking that `{}` is well-formed", tcx.def_path_str(key) }
18601867
return_result_from_ensure_ok

compiler/rustc_resolve/src/build_reduced_graph.rs

Lines changed: 9 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -396,14 +396,18 @@ impl<'a, 'ra, 'tcx> BuildReducedGraphVisitor<'a, 'ra, 'tcx> {
396396
// The fields are not expanded yet.
397397
return;
398398
}
399-
let fields = fields
399+
let field_name = |i, field: &ast::FieldDef| {
400+
field.ident.unwrap_or_else(|| Ident::from_str_and_span(&format!("{i}"), field.span))
401+
};
402+
let field_names: Vec<_> =
403+
fields.iter().enumerate().map(|(i, field)| field_name(i, field)).collect();
404+
let defaults = fields
400405
.iter()
401406
.enumerate()
402-
.map(|(i, field)| {
403-
field.ident.unwrap_or_else(|| Ident::from_str_and_span(&format!("{i}"), field.span))
404-
})
407+
.filter_map(|(i, field)| field.default.as_ref().map(|_| field_name(i, field).name))
405408
.collect();
406-
self.r.field_names.insert(def_id, fields);
409+
self.r.field_names.insert(def_id, field_names);
410+
self.r.field_defaults.insert(def_id, defaults);
407411
}
408412

409413
fn insert_field_visibilities_local(&mut self, def_id: DefId, fields: &[ast::FieldDef]) {

compiler/rustc_resolve/src/diagnostics.rs

Lines changed: 58 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1946,8 +1946,15 @@ impl<'ra, 'tcx> Resolver<'ra, 'tcx> {
19461946
}
19471947

19481948
fn report_privacy_error(&mut self, privacy_error: &PrivacyError<'ra>) {
1949-
let PrivacyError { ident, binding, outermost_res, parent_scope, single_nested, dedup_span } =
1950-
*privacy_error;
1949+
let PrivacyError {
1950+
ident,
1951+
binding,
1952+
outermost_res,
1953+
parent_scope,
1954+
single_nested,
1955+
dedup_span,
1956+
ref source,
1957+
} = *privacy_error;
19511958

19521959
let res = binding.res();
19531960
let ctor_fields_span = self.ctor_fields_span(binding);
@@ -1963,6 +1970,55 @@ impl<'ra, 'tcx> Resolver<'ra, 'tcx> {
19631970
let mut err =
19641971
self.dcx().create_err(errors::IsPrivate { span: ident.span, ident_descr, ident });
19651972

1973+
if let Some(expr) = source
1974+
&& let ast::ExprKind::Struct(struct_expr) = &expr.kind
1975+
&& let Some(Res::Def(_, def_id)) = self.partial_res_map
1976+
[&struct_expr.path.segments.iter().last().unwrap().id]
1977+
.full_res()
1978+
&& let Some(default_fields) = self.field_defaults(def_id)
1979+
&& !struct_expr.fields.is_empty()
1980+
{
1981+
let last_span = struct_expr.fields.iter().last().unwrap().span;
1982+
let mut iter = struct_expr.fields.iter().peekable();
1983+
let mut prev: Option<Span> = None;
1984+
while let Some(field) = iter.next() {
1985+
if field.expr.span.overlaps(ident.span) {
1986+
err.span_label(field.ident.span, "while setting this field");
1987+
if default_fields.contains(&field.ident.name) {
1988+
let sugg = if last_span == field.span {
1989+
vec![(field.span, "..".to_string())]
1990+
} else {
1991+
vec![
1992+
(
1993+
// Account for trailing commas and ensure we remove them.
1994+
match (prev, iter.peek()) {
1995+
(_, Some(next)) => field.span.with_hi(next.span.lo()),
1996+
(Some(prev), _) => field.span.with_lo(prev.hi()),
1997+
(None, None) => field.span,
1998+
},
1999+
String::new(),
2000+
),
2001+
(last_span.shrink_to_hi(), ", ..".to_string()),
2002+
]
2003+
};
2004+
err.multipart_suggestion_verbose(
2005+
format!(
2006+
"the type `{ident}` of field `{}` is private, but you can \
2007+
construct the default value defined for it in `{}` using `..` in \
2008+
the struct initializer expression",
2009+
field.ident,
2010+
self.tcx.item_name(def_id),
2011+
),
2012+
sugg,
2013+
Applicability::MachineApplicable,
2014+
);
2015+
break;
2016+
}
2017+
}
2018+
prev = Some(field.span);
2019+
}
2020+
}
2021+
19662022
let mut not_publicly_reexported = false;
19672023
if let Some((this_res, outer_ident)) = outermost_res {
19682024
let import_suggestions = self.lookup_import_candidates(

compiler/rustc_resolve/src/ident.rs

Lines changed: 18 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -891,6 +891,7 @@ impl<'ra, 'tcx> Resolver<'ra, 'tcx> {
891891
binding,
892892
dedup_span: path_span,
893893
outermost_res: None,
894+
source: None,
894895
parent_scope: *parent_scope,
895896
single_nested: path_span != root_span,
896897
});
@@ -1407,7 +1408,16 @@ impl<'ra, 'tcx> Resolver<'ra, 'tcx> {
14071408
parent_scope: &ParentScope<'ra>,
14081409
ignore_import: Option<Import<'ra>>,
14091410
) -> PathResult<'ra> {
1410-
self.resolve_path_with_ribs(path, opt_ns, parent_scope, None, None, None, ignore_import)
1411+
self.resolve_path_with_ribs(
1412+
path,
1413+
opt_ns,
1414+
parent_scope,
1415+
None,
1416+
None,
1417+
None,
1418+
None,
1419+
ignore_import,
1420+
)
14111421
}
14121422

14131423
#[instrument(level = "debug", skip(self))]
@@ -1424,6 +1434,7 @@ impl<'ra, 'tcx> Resolver<'ra, 'tcx> {
14241434
path,
14251435
opt_ns,
14261436
parent_scope,
1437+
None,
14271438
finalize,
14281439
None,
14291440
ignore_binding,
@@ -1436,6 +1447,7 @@ impl<'ra, 'tcx> Resolver<'ra, 'tcx> {
14361447
path: &[Segment],
14371448
opt_ns: Option<Namespace>, // `None` indicates a module path in import
14381449
parent_scope: &ParentScope<'ra>,
1450+
source: Option<PathSource<'_, '_, '_>>,
14391451
finalize: Option<Finalize>,
14401452
ribs: Option<&PerNS<Vec<Rib<'ra>>>>,
14411453
ignore_binding: Option<NameBinding<'ra>>,
@@ -1610,6 +1622,11 @@ impl<'ra, 'tcx> Resolver<'ra, 'tcx> {
16101622
// the user it is not accessible.
16111623
for error in &mut self.privacy_errors[privacy_errors_len..] {
16121624
error.outermost_res = Some((res, ident));
1625+
error.source = match source {
1626+
Some(PathSource::Struct(Some(expr)))
1627+
| Some(PathSource::Expr(Some(expr))) => Some(expr.clone()),
1628+
_ => None,
1629+
};
16131630
}
16141631

16151632
let maybe_assoc = opt_ns != Some(MacroNS) && PathSource::Type.is_expected(res);

compiler/rustc_resolve/src/late.rs

Lines changed: 19 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -425,7 +425,7 @@ pub(crate) enum PathSource<'a, 'ast, 'ra> {
425425
/// Paths in path patterns `Path`.
426426
Pat,
427427
/// Paths in struct expressions and patterns `Path { .. }`.
428-
Struct,
428+
Struct(Option<&'a Expr>),
429429
/// Paths in tuple struct patterns `Path(..)`.
430430
TupleStruct(Span, &'ra [Span]),
431431
/// `m::A::B` in `<T as m::A>::B::C`.
@@ -448,7 +448,7 @@ impl PathSource<'_, '_, '_> {
448448
match self {
449449
PathSource::Type
450450
| PathSource::Trait(_)
451-
| PathSource::Struct
451+
| PathSource::Struct(_)
452452
| PathSource::DefineOpaques => TypeNS,
453453
PathSource::Expr(..)
454454
| PathSource::Pat
@@ -465,7 +465,7 @@ impl PathSource<'_, '_, '_> {
465465
PathSource::Type
466466
| PathSource::Expr(..)
467467
| PathSource::Pat
468-
| PathSource::Struct
468+
| PathSource::Struct(_)
469469
| PathSource::TupleStruct(..)
470470
| PathSource::ReturnTypeNotation => true,
471471
PathSource::Trait(_)
@@ -482,7 +482,7 @@ impl PathSource<'_, '_, '_> {
482482
PathSource::Type => "type",
483483
PathSource::Trait(_) => "trait",
484484
PathSource::Pat => "unit struct, unit variant or constant",
485-
PathSource::Struct => "struct, variant or union type",
485+
PathSource::Struct(_) => "struct, variant or union type",
486486
PathSource::TraitItem(ValueNS, PathSource::TupleStruct(..))
487487
| PathSource::TupleStruct(..) => "tuple struct or tuple variant",
488488
PathSource::TraitItem(ns, _) => match ns {
@@ -577,7 +577,7 @@ impl PathSource<'_, '_, '_> {
577577
|| matches!(res, Res::Def(DefKind::Const | DefKind::AssocConst, _))
578578
}
579579
PathSource::TupleStruct(..) => res.expected_in_tuple_struct_pat(),
580-
PathSource::Struct => matches!(
580+
PathSource::Struct(_) => matches!(
581581
res,
582582
Res::Def(
583583
DefKind::Struct
@@ -617,8 +617,8 @@ impl PathSource<'_, '_, '_> {
617617
(PathSource::Trait(_), false) => E0405,
618618
(PathSource::Type | PathSource::DefineOpaques, true) => E0573,
619619
(PathSource::Type | PathSource::DefineOpaques, false) => E0412,
620-
(PathSource::Struct, true) => E0574,
621-
(PathSource::Struct, false) => E0422,
620+
(PathSource::Struct(_), true) => E0574,
621+
(PathSource::Struct(_), false) => E0422,
622622
(PathSource::Expr(..), true) | (PathSource::Delegation, true) => E0423,
623623
(PathSource::Expr(..), false) | (PathSource::Delegation, false) => E0425,
624624
(PathSource::Pat | PathSource::TupleStruct(..), true) => E0532,
@@ -1515,11 +1515,13 @@ impl<'a, 'ast, 'ra, 'tcx> LateResolutionVisitor<'a, 'ast, 'ra, 'tcx> {
15151515
path: &[Segment],
15161516
opt_ns: Option<Namespace>, // `None` indicates a module path in import
15171517
finalize: Option<Finalize>,
1518+
source: PathSource<'_, 'ast, 'ra>,
15181519
) -> PathResult<'ra> {
15191520
self.r.resolve_path_with_ribs(
15201521
path,
15211522
opt_ns,
15221523
&self.parent_scope,
1524+
Some(source),
15231525
finalize,
15241526
Some(&self.ribs),
15251527
None,
@@ -1999,7 +2001,7 @@ impl<'a, 'ast, 'ra, 'tcx> LateResolutionVisitor<'a, 'ast, 'ra, 'tcx> {
19992001
&mut self,
20002002
partial_res: PartialRes,
20012003
path: &[Segment],
2002-
source: PathSource<'_, '_, '_>,
2004+
source: PathSource<'_, 'ast, 'ra>,
20032005
path_span: Span,
20042006
) {
20052007
let proj_start = path.len() - partial_res.unresolved_segments();
@@ -2052,7 +2054,7 @@ impl<'a, 'ast, 'ra, 'tcx> LateResolutionVisitor<'a, 'ast, 'ra, 'tcx> {
20522054
| PathSource::ReturnTypeNotation => false,
20532055
PathSource::Expr(..)
20542056
| PathSource::Pat
2055-
| PathSource::Struct
2057+
| PathSource::Struct(_)
20562058
| PathSource::TupleStruct(..)
20572059
| PathSource::DefineOpaques
20582060
| PathSource::Delegation => true,
@@ -3880,7 +3882,7 @@ impl<'a, 'ast, 'ra, 'tcx> LateResolutionVisitor<'a, 'ast, 'ra, 'tcx> {
38803882
self.smart_resolve_path(pat.id, qself, path, PathSource::Pat);
38813883
}
38823884
PatKind::Struct(ref qself, ref path, ref _fields, ref rest) => {
3883-
self.smart_resolve_path(pat.id, qself, path, PathSource::Struct);
3885+
self.smart_resolve_path(pat.id, qself, path, PathSource::Struct(None));
38843886
self.record_patterns_with_skipped_bindings(pat, rest);
38853887
}
38863888
PatKind::Or(ref ps) => {
@@ -4124,7 +4126,7 @@ impl<'a, 'ast, 'ra, 'tcx> LateResolutionVisitor<'a, 'ast, 'ra, 'tcx> {
41244126
id: NodeId,
41254127
qself: &Option<P<QSelf>>,
41264128
path: &Path,
4127-
source: PathSource<'_, 'ast, '_>,
4129+
source: PathSource<'_, 'ast, 'ra>,
41284130
) {
41294131
self.smart_resolve_path_fragment(
41304132
qself,
@@ -4141,7 +4143,7 @@ impl<'a, 'ast, 'ra, 'tcx> LateResolutionVisitor<'a, 'ast, 'ra, 'tcx> {
41414143
&mut self,
41424144
qself: &Option<P<QSelf>>,
41434145
path: &[Segment],
4144-
source: PathSource<'_, 'ast, '_>,
4146+
source: PathSource<'_, 'ast, 'ra>,
41454147
finalize: Finalize,
41464148
record_partial_res: RecordPartialRes,
41474149
parent_qself: Option<&QSelf>,
@@ -4371,7 +4373,7 @@ impl<'a, 'ast, 'ra, 'tcx> LateResolutionVisitor<'a, 'ast, 'ra, 'tcx> {
43714373
std_path.push(Segment::from_ident(Ident::with_dummy_span(sym::std)));
43724374
std_path.extend(path);
43734375
if let PathResult::Module(_) | PathResult::NonModule(_) =
4374-
self.resolve_path(&std_path, Some(ns), None)
4376+
self.resolve_path(&std_path, Some(ns), None, source)
43754377
{
43764378
// Check if we wrote `str::from_utf8` instead of `std::str::from_utf8`
43774379
let item_span =
@@ -4445,7 +4447,7 @@ impl<'a, 'ast, 'ra, 'tcx> LateResolutionVisitor<'a, 'ast, 'ra, 'tcx> {
44454447
span: Span,
44464448
defer_to_typeck: bool,
44474449
finalize: Finalize,
4448-
source: PathSource<'_, 'ast, '_>,
4450+
source: PathSource<'_, 'ast, 'ra>,
44494451
) -> Result<Option<PartialRes>, Spanned<ResolutionError<'ra>>> {
44504452
let mut fin_res = None;
44514453

@@ -4488,7 +4490,7 @@ impl<'a, 'ast, 'ra, 'tcx> LateResolutionVisitor<'a, 'ast, 'ra, 'tcx> {
44884490
path: &[Segment],
44894491
ns: Namespace,
44904492
finalize: Finalize,
4491-
source: PathSource<'_, 'ast, '_>,
4493+
source: PathSource<'_, 'ast, 'ra>,
44924494
) -> Result<Option<PartialRes>, Spanned<ResolutionError<'ra>>> {
44934495
debug!(
44944496
"resolve_qpath(qself={:?}, path={:?}, ns={:?}, finalize={:?})",
@@ -4551,7 +4553,7 @@ impl<'a, 'ast, 'ra, 'tcx> LateResolutionVisitor<'a, 'ast, 'ra, 'tcx> {
45514553
)));
45524554
}
45534555

4554-
let result = match self.resolve_path(path, Some(ns), Some(finalize)) {
4556+
let result = match self.resolve_path(path, Some(ns), Some(finalize), source) {
45554557
PathResult::NonModule(path_res) => path_res,
45564558
PathResult::Module(ModuleOrUniformRoot::Module(module)) if !module.is_normal() => {
45574559
PartialRes::new(module.res().unwrap())
@@ -4774,7 +4776,7 @@ impl<'a, 'ast, 'ra, 'tcx> LateResolutionVisitor<'a, 'ast, 'ra, 'tcx> {
47744776
}
47754777

47764778
ExprKind::Struct(ref se) => {
4777-
self.smart_resolve_path(expr.id, &se.qself, &se.path, PathSource::Struct);
4779+
self.smart_resolve_path(expr.id, &se.qself, &se.path, PathSource::Struct(parent));
47784780
// This is the same as `visit::walk_expr(self, expr);`, but we want to pass the
47794781
// parent in for accurate suggestions when encountering `Foo { bar }` that should
47804782
// have been `Foo { bar: self.bar }`.

0 commit comments

Comments
 (0)