Fix error message for calling a non-tuple struct

This commit is contained in:
James Barford-Evans
2025-11-19 15:50:40 +00:00
parent 140044cffa
commit ed6a78ca86
3 changed files with 46 additions and 13 deletions
+27 -13
View File
@@ -823,8 +823,10 @@ fn try_lookup_name_relaxed(
}
if let Some(Res::Def(DefKind::Struct, def_id)) = res {
self.update_err_for_private_tuple_struct_fields(err, &source, def_id);
err.note("constructor is not visible here due to private fields");
if self.has_private_fields(def_id) {
self.update_err_for_private_tuple_struct_fields(err, &source, def_id);
err.note("constructor is not visible here due to private fields");
}
} else {
err.span_suggestion(
call_span,
@@ -1642,6 +1644,17 @@ fn followed_by_brace(&self, span: Span) -> (bool, Option<Span>) {
}
}
fn has_tuple_fields(&mut self, def_id: DefId) -> bool {
// As we cannot name a field "0", this is an indictation
// that we are looking at a tuple struct
if let Some(fields) = self.r.field_idents(def_id) {
if let Some(first_field) = fields.get(0) {
return first_field.name.as_str() == "0";
}
}
false
}
fn update_err_for_private_tuple_struct_fields(
&mut self,
err: &mut Diag<'_>,
@@ -1664,17 +1677,18 @@ fn update_err_for_private_tuple_struct_fields(
span: call_span,
..
})) => {
err.primary_message(
"cannot initialize a tuple struct which contains private fields",
);
self.suggest_alternative_construction_methods(
def_id,
err,
path.span,
*call_span,
&args[..],
);
// Use spans of the tuple struct definition.
if self.has_tuple_fields(def_id) {
err.primary_message(
"cannot initialize a tuple struct which contains private fields",
);
self.suggest_alternative_construction_methods(
def_id,
err,
path.span,
*call_span,
&args[..],
);
}
self.r
.field_idents(def_id)
.map(|fields| fields.iter().map(|f| f.span).collect::<Vec<_>>())
@@ -0,0 +1,10 @@
struct Bar {}
impl Bar {
fn into_self(self) -> Bar {
Bar(self)
//~^ ERROR expected function, tuple struct or tuple variant, found struct `Bar` [E0423]
}
}
fn main() {}
@@ -0,0 +1,9 @@
error[E0423]: expected function, tuple struct or tuple variant, found struct `Bar`
--> $DIR/regression-struct-called-as-function-148919.rs:5:9
|
LL | Bar(self)
| ^^^
error: aborting due to 1 previous error
For more information about this error, try `rustc --explain E0423`.