Skip to content

Commit 38f8f98

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 3cd8fcb commit 38f8f98

File tree

11 files changed

+275
-32
lines changed

11 files changed

+275
-32
lines changed

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

+1
Original file line numberDiff line numberDiff line change
@@ -424,6 +424,7 @@ provide! { tcx, def_id, other, cdata,
424424

425425
crate_extern_paths => { cdata.source().paths().cloned().collect() }
426426
expn_that_defined => { cdata.get_expn_that_defined(def_id.index, tcx.sess) }
427+
default_field => { cdata.get_default_field(def_id.index) }
427428
is_doc_hidden => { cdata.get_attr_flags(def_id.index).contains(AttrFlags::IS_DOC_HIDDEN) }
428429
doc_link_resolutions => { tcx.arena.alloc(cdata.get_doc_link_resolutions(def_id.index)) }
429430
doc_link_traits_in_scope => {

compiler/rustc_middle/src/query/mod.rs

+7
Original file line numberDiff line numberDiff line change
@@ -1711,6 +1711,13 @@ rustc_queries! {
17111711
feedable
17121712
}
17131713

1714+
/// Returns the default `const` value for a struct field.
1715+
query default_field(def_id: DefId) -> Option<DefId> {
1716+
desc { |tcx| "looking up the `const` corresponding to the default for `{}`", tcx.def_path_str(def_id) }
1717+
separate_provide_extern
1718+
feedable
1719+
}
1720+
17141721
query check_well_formed(key: LocalDefId) -> Result<(), ErrorGuaranteed> {
17151722
desc { |tcx| "checking that `{}` is well-formed", tcx.def_path_str(key) }
17161723
ensure_forwards_result_if_red

compiler/rustc_resolve/src/build_reduced_graph.rs

+9-5
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

+47-2
Original file line numberDiff line numberDiff line change
@@ -1754,8 +1754,15 @@ impl<'ra, 'tcx> Resolver<'ra, 'tcx> {
17541754
}
17551755

17561756
fn report_privacy_error(&mut self, privacy_error: &PrivacyError<'ra>) {
1757-
let PrivacyError { ident, binding, outermost_res, parent_scope, single_nested, dedup_span } =
1758-
*privacy_error;
1757+
let PrivacyError {
1758+
ident,
1759+
binding,
1760+
outermost_res,
1761+
parent_scope,
1762+
single_nested,
1763+
dedup_span,
1764+
ref source,
1765+
} = *privacy_error;
17591766

17601767
let res = binding.res();
17611768
let ctor_fields_span = self.ctor_fields_span(binding);
@@ -1771,6 +1778,44 @@ impl<'ra, 'tcx> Resolver<'ra, 'tcx> {
17711778
let mut err =
17721779
self.dcx().create_err(errors::IsPrivate { span: ident.span, ident_descr, ident });
17731780

1781+
if let Some(expr) = source
1782+
&& let ast::ExprKind::Struct(struct_expr) = &expr.kind
1783+
&& let Some(Res::Def(_, def_id)) = self.partial_res_map
1784+
[&struct_expr.path.segments.iter().last().unwrap().id]
1785+
.full_res()
1786+
&& let Some(default_fields) = self.field_defaults(def_id)
1787+
&& !struct_expr.fields.is_empty()
1788+
{
1789+
let last_span = struct_expr.fields.iter().last().unwrap().span;
1790+
for field in &struct_expr.fields[..] {
1791+
if field.expr.span.overlaps(ident.span) {
1792+
err.span_label(field.ident.span, "while setting this field");
1793+
if default_fields.contains(&field.ident.name) {
1794+
let sugg = if last_span == field.span {
1795+
vec![(field.span, "..".to_string())]
1796+
} else {
1797+
vec![
1798+
(field.span, String::new()),
1799+
(last_span.shrink_to_hi(), ", ..".to_string()),
1800+
]
1801+
};
1802+
err.multipart_suggestion_verbose(
1803+
format!(
1804+
"the type `{ident}` of field `{}` is private, but you can \
1805+
construct the default value defined for it in `{}` using `..` in \
1806+
the struct initializer expression",
1807+
field.ident,
1808+
self.tcx.item_name(def_id),
1809+
),
1810+
sugg,
1811+
Applicability::MachineApplicable,
1812+
);
1813+
break;
1814+
}
1815+
}
1816+
}
1817+
}
1818+
17741819
let mut not_publicly_reexported = false;
17751820
if let Some((this_res, outer_ident)) = outermost_res {
17761821
let import_suggestions = self.lookup_import_candidates(

compiler/rustc_resolve/src/ident.rs

+18-1
Original file line numberDiff line numberDiff line change
@@ -893,6 +893,7 @@ impl<'ra, 'tcx> Resolver<'ra, 'tcx> {
893893
binding,
894894
dedup_span: path_span,
895895
outermost_res: None,
896+
source: None,
896897
parent_scope: *parent_scope,
897898
single_nested: path_span != root_span,
898899
});
@@ -1389,7 +1390,16 @@ impl<'ra, 'tcx> Resolver<'ra, 'tcx> {
13891390
parent_scope: &ParentScope<'ra>,
13901391
ignore_import: Option<Import<'ra>>,
13911392
) -> PathResult<'ra> {
1392-
self.resolve_path_with_ribs(path, opt_ns, parent_scope, None, None, None, ignore_import)
1393+
self.resolve_path_with_ribs(
1394+
path,
1395+
opt_ns,
1396+
parent_scope,
1397+
None,
1398+
None,
1399+
None,
1400+
None,
1401+
ignore_import,
1402+
)
13931403
}
13941404

13951405
#[instrument(level = "debug", skip(self))]
@@ -1406,6 +1416,7 @@ impl<'ra, 'tcx> Resolver<'ra, 'tcx> {
14061416
path,
14071417
opt_ns,
14081418
parent_scope,
1419+
None,
14091420
finalize,
14101421
None,
14111422
ignore_binding,
@@ -1418,6 +1429,7 @@ impl<'ra, 'tcx> Resolver<'ra, 'tcx> {
14181429
path: &[Segment],
14191430
opt_ns: Option<Namespace>, // `None` indicates a module path in import
14201431
parent_scope: &ParentScope<'ra>,
1432+
source: Option<PathSource<'_>>,
14211433
finalize: Option<Finalize>,
14221434
ribs: Option<&PerNS<Vec<Rib<'ra>>>>,
14231435
ignore_binding: Option<NameBinding<'ra>>,
@@ -1592,6 +1604,11 @@ impl<'ra, 'tcx> Resolver<'ra, 'tcx> {
15921604
// the user it is not accessible.
15931605
for error in &mut self.privacy_errors[privacy_errors_len..] {
15941606
error.outermost_res = Some((res, ident));
1607+
error.source = match source {
1608+
Some(PathSource::Struct(Some(expr)))
1609+
| Some(PathSource::Expr(Some(expr))) => Some(expr.clone()),
1610+
_ => None,
1611+
};
15951612
}
15961613

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

compiler/rustc_resolve/src/late.rs

+18-13
Original file line numberDiff line numberDiff line change
@@ -403,7 +403,7 @@ pub(crate) enum PathSource<'a> {
403403
// Paths in path patterns `Path`.
404404
Pat,
405405
// Paths in struct expressions and patterns `Path { .. }`.
406-
Struct,
406+
Struct(Option<&'a Expr>),
407407
// Paths in tuple struct patterns `Path(..)`.
408408
TupleStruct(Span, &'a [Span]),
409409
// `m::A::B` in `<T as m::A>::B::C`.
@@ -419,7 +419,7 @@ pub(crate) enum PathSource<'a> {
419419
impl<'a> PathSource<'a> {
420420
fn namespace(self) -> Namespace {
421421
match self {
422-
PathSource::Type | PathSource::Trait(_) | PathSource::Struct => TypeNS,
422+
PathSource::Type | PathSource::Trait(_) | PathSource::Struct(_) => TypeNS,
423423
PathSource::Expr(..)
424424
| PathSource::Pat
425425
| PathSource::TupleStruct(..)
@@ -435,7 +435,7 @@ impl<'a> PathSource<'a> {
435435
PathSource::Type
436436
| PathSource::Expr(..)
437437
| PathSource::Pat
438-
| PathSource::Struct
438+
| PathSource::Struct(_)
439439
| PathSource::TupleStruct(..)
440440
| PathSource::ReturnTypeNotation => true,
441441
PathSource::Trait(_)
@@ -450,7 +450,7 @@ impl<'a> PathSource<'a> {
450450
PathSource::Type => "type",
451451
PathSource::Trait(_) => "trait",
452452
PathSource::Pat => "unit struct, unit variant or constant",
453-
PathSource::Struct => "struct, variant or union type",
453+
PathSource::Struct(_) => "struct, variant or union type",
454454
PathSource::TupleStruct(..) => "tuple struct or tuple variant",
455455
PathSource::TraitItem(ns) => match ns {
456456
TypeNS => "associated type",
@@ -531,7 +531,7 @@ impl<'a> PathSource<'a> {
531531
|| matches!(res, Res::Def(DefKind::Const | DefKind::AssocConst, _))
532532
}
533533
PathSource::TupleStruct(..) => res.expected_in_tuple_struct_pat(),
534-
PathSource::Struct => matches!(
534+
PathSource::Struct(_) => matches!(
535535
res,
536536
Res::Def(
537537
DefKind::Struct
@@ -571,8 +571,8 @@ impl<'a> PathSource<'a> {
571571
(PathSource::Trait(_), false) => E0405,
572572
(PathSource::Type, true) => E0573,
573573
(PathSource::Type, false) => E0412,
574-
(PathSource::Struct, true) => E0574,
575-
(PathSource::Struct, false) => E0422,
574+
(PathSource::Struct(_), true) => E0574,
575+
(PathSource::Struct(_), false) => E0422,
576576
(PathSource::Expr(..), true) | (PathSource::Delegation, true) => E0423,
577577
(PathSource::Expr(..), false) | (PathSource::Delegation, false) => E0425,
578578
(PathSource::Pat | PathSource::TupleStruct(..), true) => E0532,
@@ -1454,11 +1454,13 @@ impl<'a, 'ast, 'ra: 'ast, 'tcx> LateResolutionVisitor<'a, 'ast, 'ra, 'tcx> {
14541454
path: &[Segment],
14551455
opt_ns: Option<Namespace>, // `None` indicates a module path in import
14561456
finalize: Option<Finalize>,
1457+
source: PathSource<'ast>,
14571458
) -> PathResult<'ra> {
14581459
self.r.resolve_path_with_ribs(
14591460
path,
14601461
opt_ns,
14611462
&self.parent_scope,
1463+
Some(source),
14621464
finalize,
14631465
Some(&self.ribs),
14641466
None,
@@ -1961,7 +1963,7 @@ impl<'a, 'ast, 'ra: 'ast, 'tcx> LateResolutionVisitor<'a, 'ast, 'ra, 'tcx> {
19611963
| PathSource::ReturnTypeNotation => false,
19621964
PathSource::Expr(..)
19631965
| PathSource::Pat
1964-
| PathSource::Struct
1966+
| PathSource::Struct(_)
19651967
| PathSource::TupleStruct(..)
19661968
| PathSource::Delegation => true,
19671969
};
@@ -3794,7 +3796,7 @@ impl<'a, 'ast, 'ra: 'ast, 'tcx> LateResolutionVisitor<'a, 'ast, 'ra, 'tcx> {
37943796
self.smart_resolve_path(pat.id, qself, path, PathSource::Pat);
37953797
}
37963798
PatKind::Struct(ref qself, ref path, ref _fields, ref rest) => {
3797-
self.smart_resolve_path(pat.id, qself, path, PathSource::Struct);
3799+
self.smart_resolve_path(pat.id, qself, path, PathSource::Struct(None));
37983800
self.record_patterns_with_skipped_bindings(pat, rest);
37993801
}
38003802
PatKind::Or(ref ps) => {
@@ -4200,6 +4202,7 @@ impl<'a, 'ast, 'ra: 'ast, 'tcx> LateResolutionVisitor<'a, 'ast, 'ra, 'tcx> {
42004202
qself,
42014203
path,
42024204
ns,
4205+
source,
42034206
path_span,
42044207
source.defer_to_typeck(),
42054208
finalize,
@@ -4245,7 +4248,7 @@ impl<'a, 'ast, 'ra: 'ast, 'tcx> LateResolutionVisitor<'a, 'ast, 'ra, 'tcx> {
42454248
std_path.push(Segment::from_ident(Ident::with_dummy_span(sym::std)));
42464249
std_path.extend(path);
42474250
if let PathResult::Module(_) | PathResult::NonModule(_) =
4248-
self.resolve_path(&std_path, Some(ns), None)
4251+
self.resolve_path(&std_path, Some(ns), None, source)
42494252
{
42504253
// Check if we wrote `str::from_utf8` instead of `std::str::from_utf8`
42514254
let item_span =
@@ -4316,6 +4319,7 @@ impl<'a, 'ast, 'ra: 'ast, 'tcx> LateResolutionVisitor<'a, 'ast, 'ra, 'tcx> {
43164319
qself: &Option<P<QSelf>>,
43174320
path: &[Segment],
43184321
primary_ns: Namespace,
4322+
source: PathSource<'ast>,
43194323
span: Span,
43204324
defer_to_typeck: bool,
43214325
finalize: Finalize,
@@ -4324,7 +4328,7 @@ impl<'a, 'ast, 'ra: 'ast, 'tcx> LateResolutionVisitor<'a, 'ast, 'ra, 'tcx> {
43244328

43254329
for (i, &ns) in [primary_ns, TypeNS, ValueNS].iter().enumerate() {
43264330
if i == 0 || ns != primary_ns {
4327-
match self.resolve_qpath(qself, path, ns, finalize)? {
4331+
match self.resolve_qpath(qself, path, ns, source, finalize)? {
43284332
Some(partial_res)
43294333
if partial_res.unresolved_segments() == 0 || defer_to_typeck =>
43304334
{
@@ -4360,6 +4364,7 @@ impl<'a, 'ast, 'ra: 'ast, 'tcx> LateResolutionVisitor<'a, 'ast, 'ra, 'tcx> {
43604364
qself: &Option<P<QSelf>>,
43614365
path: &[Segment],
43624366
ns: Namespace,
4367+
source: PathSource<'ast>,
43634368
finalize: Finalize,
43644369
) -> Result<Option<PartialRes>, Spanned<ResolutionError<'ra>>> {
43654370
debug!(
@@ -4421,7 +4426,7 @@ impl<'a, 'ast, 'ra: 'ast, 'tcx> LateResolutionVisitor<'a, 'ast, 'ra, 'tcx> {
44214426
)));
44224427
}
44234428

4424-
let result = match self.resolve_path(path, Some(ns), Some(finalize)) {
4429+
let result = match self.resolve_path(path, Some(ns), Some(finalize), source) {
44254430
PathResult::NonModule(path_res) => path_res,
44264431
PathResult::Module(ModuleOrUniformRoot::Module(module)) if !module.is_normal() => {
44274432
PartialRes::new(module.res().unwrap())
@@ -4642,7 +4647,7 @@ impl<'a, 'ast, 'ra: 'ast, 'tcx> LateResolutionVisitor<'a, 'ast, 'ra, 'tcx> {
46424647
}
46434648

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

0 commit comments

Comments
 (0)