Skip to content

Commit 3d33942

Browse files
committed
Use less brittle way for updating error message
1 parent ed6a78c commit 3d33942

File tree

1 file changed

+29
-22
lines changed

1 file changed

+29
-22
lines changed

compiler/rustc_resolve/src/late/diagnostics.rs

Lines changed: 29 additions & 22 deletions
Original file line numberDiff line numberDiff line change
@@ -823,8 +823,14 @@ impl<'ast, 'ra, 'tcx> LateResolutionVisitor<'_, 'ast, 'ra, 'tcx> {
823823
}
824824

825825
if let Some(Res::Def(DefKind::Struct, def_id)) = res {
826-
if self.has_private_fields(def_id) {
826+
let private_fields = self.has_private_fields(def_id);
827+
let adjust_error_message =
828+
private_fields && self.is_struct_with_fn_ctor(def_id);
829+
if adjust_error_message {
827830
self.update_err_for_private_tuple_struct_fields(err, &source, def_id);
831+
}
832+
833+
if private_fields {
828834
err.note("constructor is not visible here due to private fields");
829835
}
830836
} else {
@@ -1644,15 +1650,17 @@ impl<'ast, 'ra, 'tcx> LateResolutionVisitor<'_, 'ast, 'ra, 'tcx> {
16441650
}
16451651
}
16461652

1647-
fn has_tuple_fields(&mut self, def_id: DefId) -> bool {
1648-
// As we cannot name a field "0", this is an indictation
1649-
// that we are looking at a tuple struct
1650-
if let Some(fields) = self.r.field_idents(def_id) {
1651-
if let Some(first_field) = fields.get(0) {
1652-
return first_field.name.as_str() == "0";
1653-
}
1654-
}
1655-
false
1653+
fn is_struct_with_fn_ctor(&mut self, def_id: DefId) -> bool {
1654+
def_id
1655+
.as_local()
1656+
.and_then(|local_id| self.r.struct_constructors.get(&local_id))
1657+
.map(|struct_ctor| {
1658+
matches!(
1659+
struct_ctor.0,
1660+
def::Res::Def(DefKind::Ctor(CtorOf::Struct, CtorKind::Fn), _)
1661+
)
1662+
})
1663+
.unwrap_or(false)
16561664
}
16571665

16581666
fn update_err_for_private_tuple_struct_fields(
@@ -1677,18 +1685,17 @@ impl<'ast, 'ra, 'tcx> LateResolutionVisitor<'_, 'ast, 'ra, 'tcx> {
16771685
span: call_span,
16781686
..
16791687
})) => {
1680-
if self.has_tuple_fields(def_id) {
1681-
err.primary_message(
1682-
"cannot initialize a tuple struct which contains private fields",
1683-
);
1684-
self.suggest_alternative_construction_methods(
1685-
def_id,
1686-
err,
1687-
path.span,
1688-
*call_span,
1689-
&args[..],
1690-
);
1691-
}
1688+
err.primary_message(
1689+
"cannot initialize a tuple struct which contains private fields",
1690+
);
1691+
self.suggest_alternative_construction_methods(
1692+
def_id,
1693+
err,
1694+
path.span,
1695+
*call_span,
1696+
&args[..],
1697+
);
1698+
16921699
self.r
16931700
.field_idents(def_id)
16941701
.map(|fields| fields.iter().map(|f| f.span).collect::<Vec<_>>())

0 commit comments

Comments
 (0)