Skip to content

Commit 5f24487

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 6a64e3b commit 5f24487

File tree

11 files changed

+270
-32
lines changed

11 files changed

+270
-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 whether the impl or associated function has the `default` keyword.
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
@@ -1761,8 +1761,15 @@ impl<'ra, 'tcx> Resolver<'ra, 'tcx> {
17611761
}
17621762

17631763
fn report_privacy_error(&mut self, privacy_error: &PrivacyError<'ra>) {
1764-
let PrivacyError { ident, binding, outermost_res, parent_scope, single_nested, dedup_span } =
1765-
*privacy_error;
1764+
let PrivacyError {
1765+
ident,
1766+
binding,
1767+
outermost_res,
1768+
parent_scope,
1769+
single_nested,
1770+
dedup_span,
1771+
ref source,
1772+
} = *privacy_error;
17661773

17671774
let res = binding.res();
17681775
let ctor_fields_span = self.ctor_fields_span(binding);
@@ -1778,6 +1785,44 @@ impl<'ra, 'tcx> Resolver<'ra, 'tcx> {
17781785
let mut err =
17791786
self.dcx().create_err(errors::IsPrivate { span: ident.span, ident_descr, ident });
17801787

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

compiler/rustc_resolve/src/ident.rs

+18-1
Original file line numberDiff line numberDiff line change
@@ -896,6 +896,7 @@ impl<'ra, 'tcx> Resolver<'ra, 'tcx> {
896896
binding,
897897
dedup_span: path_span,
898898
outermost_res: None,
899+
source: None,
899900
parent_scope: *parent_scope,
900901
single_nested: path_span != root_span,
901902
});
@@ -1392,7 +1393,16 @@ impl<'ra, 'tcx> Resolver<'ra, 'tcx> {
13921393
parent_scope: &ParentScope<'ra>,
13931394
ignore_import: Option<Import<'ra>>,
13941395
) -> PathResult<'ra> {
1395-
self.resolve_path_with_ribs(path, opt_ns, parent_scope, None, None, None, ignore_import)
1396+
self.resolve_path_with_ribs(
1397+
path,
1398+
opt_ns,
1399+
parent_scope,
1400+
None,
1401+
None,
1402+
None,
1403+
None,
1404+
ignore_import,
1405+
)
13961406
}
13971407

13981408
#[instrument(level = "debug", skip(self))]
@@ -1409,6 +1419,7 @@ impl<'ra, 'tcx> Resolver<'ra, 'tcx> {
14091419
path,
14101420
opt_ns,
14111421
parent_scope,
1422+
None,
14121423
finalize,
14131424
None,
14141425
ignore_binding,
@@ -1421,6 +1432,7 @@ impl<'ra, 'tcx> Resolver<'ra, 'tcx> {
14211432
path: &[Segment],
14221433
opt_ns: Option<Namespace>, // `None` indicates a module path in import
14231434
parent_scope: &ParentScope<'ra>,
1435+
source: Option<PathSource<'_>>,
14241436
finalize: Option<Finalize>,
14251437
ribs: Option<&PerNS<Vec<Rib<'ra>>>>,
14261438
ignore_binding: Option<NameBinding<'ra>>,
@@ -1597,6 +1609,11 @@ impl<'ra, 'tcx> Resolver<'ra, 'tcx> {
15971609
// the user it is not accessible.
15981610
for error in &mut self.privacy_errors[privacy_errors_len..] {
15991611
error.outermost_res = Some((res, ident));
1612+
error.source = match source {
1613+
Some(PathSource::Struct(Some(expr)))
1614+
| Some(PathSource::Expr(Some(expr))) => Some(expr.clone()),
1615+
_ => None,
1616+
};
16001617
}
16011618

16021619
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",
@@ -535,7 +535,7 @@ impl<'a> PathSource<'a> {
535535
|| matches!(res, Res::Def(DefKind::Const | DefKind::AssocConst, _))
536536
}
537537
PathSource::TupleStruct(..) => res.expected_in_tuple_struct_pat(),
538-
PathSource::Struct => matches!(
538+
PathSource::Struct(_) => matches!(
539539
res,
540540
Res::Def(
541541
DefKind::Struct
@@ -575,8 +575,8 @@ impl<'a> PathSource<'a> {
575575
(PathSource::Trait(_), false) => E0405,
576576
(PathSource::Type, true) => E0573,
577577
(PathSource::Type, false) => E0412,
578-
(PathSource::Struct, true) => E0574,
579-
(PathSource::Struct, false) => E0422,
578+
(PathSource::Struct(_), true) => E0574,
579+
(PathSource::Struct(_), false) => E0422,
580580
(PathSource::Expr(..), true) | (PathSource::Delegation, true) => E0423,
581581
(PathSource::Expr(..), false) | (PathSource::Delegation, false) => E0425,
582582
(PathSource::Pat | PathSource::TupleStruct(..), true) => E0532,
@@ -1461,11 +1461,13 @@ impl<'a, 'ast, 'ra: 'ast, 'tcx> LateResolutionVisitor<'a, 'ast, 'ra, 'tcx> {
14611461
path: &[Segment],
14621462
opt_ns: Option<Namespace>, // `None` indicates a module path in import
14631463
finalize: Option<Finalize>,
1464+
source: PathSource<'ast>,
14641465
) -> PathResult<'ra> {
14651466
self.r.resolve_path_with_ribs(
14661467
path,
14671468
opt_ns,
14681469
&self.parent_scope,
1470+
Some(source),
14691471
finalize,
14701472
Some(&self.ribs),
14711473
None,
@@ -1975,7 +1977,7 @@ impl<'a, 'ast, 'ra: 'ast, 'tcx> LateResolutionVisitor<'a, 'ast, 'ra, 'tcx> {
19751977
| PathSource::ReturnTypeNotation => false,
19761978
PathSource::Expr(..)
19771979
| PathSource::Pat
1978-
| PathSource::Struct
1980+
| PathSource::Struct(_)
19791981
| PathSource::TupleStruct(..)
19801982
| PathSource::Delegation => true,
19811983
};
@@ -3816,7 +3818,7 @@ impl<'a, 'ast, 'ra: 'ast, 'tcx> LateResolutionVisitor<'a, 'ast, 'ra, 'tcx> {
38163818
self.smart_resolve_path(pat.id, qself, path, PathSource::Pat);
38173819
}
38183820
PatKind::Struct(ref qself, ref path, ref _fields, ref rest) => {
3819-
self.smart_resolve_path(pat.id, qself, path, PathSource::Struct);
3821+
self.smart_resolve_path(pat.id, qself, path, PathSource::Struct(None));
38203822
self.record_patterns_with_skipped_bindings(pat, rest);
38213823
}
38223824
PatKind::Or(ref ps) => {
@@ -4222,6 +4224,7 @@ impl<'a, 'ast, 'ra: 'ast, 'tcx> LateResolutionVisitor<'a, 'ast, 'ra, 'tcx> {
42224224
qself,
42234225
path,
42244226
ns,
4227+
source,
42254228
path_span,
42264229
source.defer_to_typeck(),
42274230
finalize,
@@ -4267,7 +4270,7 @@ impl<'a, 'ast, 'ra: 'ast, 'tcx> LateResolutionVisitor<'a, 'ast, 'ra, 'tcx> {
42674270
std_path.push(Segment::from_ident(Ident::with_dummy_span(sym::std)));
42684271
std_path.extend(path);
42694272
if let PathResult::Module(_) | PathResult::NonModule(_) =
4270-
self.resolve_path(&std_path, Some(ns), None)
4273+
self.resolve_path(&std_path, Some(ns), None, source)
42714274
{
42724275
// Check if we wrote `str::from_utf8` instead of `std::str::from_utf8`
42734276
let item_span =
@@ -4338,6 +4341,7 @@ impl<'a, 'ast, 'ra: 'ast, 'tcx> LateResolutionVisitor<'a, 'ast, 'ra, 'tcx> {
43384341
qself: &Option<P<QSelf>>,
43394342
path: &[Segment],
43404343
primary_ns: Namespace,
4344+
source: PathSource<'ast>,
43414345
span: Span,
43424346
defer_to_typeck: bool,
43434347
finalize: Finalize,
@@ -4346,7 +4350,7 @@ impl<'a, 'ast, 'ra: 'ast, 'tcx> LateResolutionVisitor<'a, 'ast, 'ra, 'tcx> {
43464350

43474351
for (i, &ns) in [primary_ns, TypeNS, ValueNS].iter().enumerate() {
43484352
if i == 0 || ns != primary_ns {
4349-
match self.resolve_qpath(qself, path, ns, finalize)? {
4353+
match self.resolve_qpath(qself, path, ns, source, finalize)? {
43504354
Some(partial_res)
43514355
if partial_res.unresolved_segments() == 0 || defer_to_typeck =>
43524356
{
@@ -4382,6 +4386,7 @@ impl<'a, 'ast, 'ra: 'ast, 'tcx> LateResolutionVisitor<'a, 'ast, 'ra, 'tcx> {
43824386
qself: &Option<P<QSelf>>,
43834387
path: &[Segment],
43844388
ns: Namespace,
4389+
source: PathSource<'ast>,
43854390
finalize: Finalize,
43864391
) -> Result<Option<PartialRes>, Spanned<ResolutionError<'ra>>> {
43874392
debug!(
@@ -4443,7 +4448,7 @@ impl<'a, 'ast, 'ra: 'ast, 'tcx> LateResolutionVisitor<'a, 'ast, 'ra, 'tcx> {
44434448
)));
44444449
}
44454450

4446-
let result = match self.resolve_path(path, Some(ns), Some(finalize)) {
4451+
let result = match self.resolve_path(path, Some(ns), Some(finalize), source) {
44474452
PathResult::NonModule(path_res) => path_res,
44484453
PathResult::Module(ModuleOrUniformRoot::Module(module)) if !module.is_normal() => {
44494454
PartialRes::new(module.res().unwrap())
@@ -4664,7 +4669,7 @@ impl<'a, 'ast, 'ra: 'ast, 'tcx> LateResolutionVisitor<'a, 'ast, 'ra, 'tcx> {
46644669
}
46654670

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

0 commit comments

Comments
 (0)