Skip to content

Commit 6b508b8

Browse files
committed
clean up struct field suggestions
1 parent e3c631b commit 6b508b8

10 files changed

+188
-131
lines changed

compiler/rustc_hir_typeck/src/expr.rs

+16-62
Original file line numberDiff line numberDiff line change
@@ -41,7 +41,6 @@ use rustc_infer::infer::DefineOpaqueTypes;
4141
use rustc_infer::infer::InferOk;
4242
use rustc_infer::traits::query::NoSolution;
4343
use rustc_infer::traits::ObligationCause;
44-
use rustc_middle::middle::stability;
4544
use rustc_middle::ty::adjustment::{Adjust, Adjustment, AllowTwoPhase};
4645
use rustc_middle::ty::error::{
4746
ExpectedFound,
@@ -1662,6 +1661,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
16621661
self.report_unknown_field(
16631662
adt_ty,
16641663
variant,
1664+
expr_id,
16651665
field,
16661666
ast_fields,
16671667
adt.variant_descr(),
@@ -2049,6 +2049,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
20492049
&self,
20502050
ty: Ty<'tcx>,
20512051
variant: &'tcx ty::VariantDef,
2052+
expr_id: HirId,
20522053
field: &hir::ExprField<'_>,
20532054
skip_fields: &[hir::ExprField<'_>],
20542055
kind_name: &str,
@@ -2129,9 +2130,10 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
21292130
},
21302131
_ => {
21312132
// prevent all specified fields from being suggested
2132-
let skip_fields: Vec<_> = skip_fields.iter().map(|x| x.ident.name).collect();
2133+
let available_field_names =
2134+
self.available_field_names(variant, expr_id, skip_fields);
21332135
if let Some(field_name) =
2134-
self.suggest_field_name(variant, field.ident.name, &skip_fields, expr_span)
2136+
find_best_match_for_name(&available_field_names, field.ident.name, None)
21352137
{
21362138
err.span_suggestion(
21372139
field.ident.span,
@@ -2153,10 +2155,6 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
21532155
format!("`{ty}` does not have this field"),
21542156
);
21552157
}
2156-
let mut available_field_names =
2157-
self.available_field_names(variant, expr_span);
2158-
available_field_names
2159-
.retain(|name| skip_fields.iter().all(|skip| name != skip));
21602158
if available_field_names.is_empty() {
21612159
err.note("all struct fields are already assigned");
21622160
} else {
@@ -2174,63 +2172,19 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
21742172
err.emit()
21752173
}
21762174

2177-
// Return a hint about the closest match in field names
2178-
fn suggest_field_name(
2179-
&self,
2180-
variant: &'tcx ty::VariantDef,
2181-
field: Symbol,
2182-
skip: &[Symbol],
2183-
// The span where stability will be checked
2184-
span: Span,
2185-
) -> Option<Symbol> {
2186-
let names = variant
2187-
.fields
2188-
.iter()
2189-
.filter_map(|field| {
2190-
// ignore already set fields and private fields from non-local crates
2191-
// and unstable fields.
2192-
if skip.iter().any(|&x| x == field.name)
2193-
|| (!variant.def_id.is_local() && !field.vis.is_public())
2194-
|| matches!(
2195-
self.tcx.eval_stability(field.did, None, span, None),
2196-
stability::EvalResult::Deny { .. }
2197-
)
2198-
{
2199-
None
2200-
} else {
2201-
Some(field.name)
2202-
}
2203-
})
2204-
.collect::<Vec<Symbol>>();
2205-
2206-
find_best_match_for_name(&names, field, None)
2207-
}
2208-
22092175
fn available_field_names(
22102176
&self,
22112177
variant: &'tcx ty::VariantDef,
2212-
access_span: Span,
2178+
expr_id: HirId,
2179+
skip_fields: &[hir::ExprField<'_>],
22132180
) -> Vec<Symbol> {
2214-
let body_owner_hir_id = self.tcx.hir().local_def_id_to_hir_id(self.body_id);
22152181
variant
22162182
.fields
22172183
.iter()
22182184
.filter(|field| {
2219-
let def_scope = self
2220-
.tcx
2221-
.adjust_ident_and_get_scope(
2222-
field.ident(self.tcx),
2223-
variant.def_id,
2224-
body_owner_hir_id,
2225-
)
2226-
.1;
2227-
field.vis.is_accessible_from(def_scope, self.tcx)
2228-
&& !matches!(
2229-
self.tcx.eval_stability(field.did, None, access_span, None),
2230-
stability::EvalResult::Deny { .. }
2231-
)
2185+
skip_fields.iter().all(|&skip| skip.ident.name != field.name)
2186+
&& self.is_field_suggestable(field, expr_id)
22322187
})
2233-
.filter(|field| !self.tcx.is_doc_hidden(field.did))
22342188
.map(|field| field.name)
22352189
.collect()
22362190
}
@@ -2460,7 +2414,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
24602414
self.suggest_first_deref_field(&mut err, expr, base, ident);
24612415
}
24622416
ty::Adt(def, _) if !def.is_enum() => {
2463-
self.suggest_fields_on_recordish(&mut err, def, ident, expr.span);
2417+
self.suggest_fields_on_recordish(&mut err, expr.hir_id, def, ident);
24642418
}
24652419
ty::Param(param_ty) => {
24662420
self.point_at_param_definition(&mut err, param_ty);
@@ -2622,12 +2576,14 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
26222576
fn suggest_fields_on_recordish(
26232577
&self,
26242578
err: &mut Diagnostic,
2579+
expr_id: HirId,
26252580
def: ty::AdtDef<'tcx>,
26262581
field: Ident,
2627-
access_span: Span,
26282582
) {
2583+
let available_field_names =
2584+
self.available_field_names(def.non_enum_variant(), expr_id, &[]);
26292585
if let Some(suggested_field_name) =
2630-
self.suggest_field_name(def.non_enum_variant(), field.name, &[], access_span)
2586+
find_best_match_for_name(&available_field_names, field.name, None)
26312587
{
26322588
err.span_suggestion(
26332589
field.span,
@@ -2637,12 +2593,10 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
26372593
);
26382594
} else {
26392595
err.span_label(field.span, "unknown field");
2640-
let struct_variant_def = def.non_enum_variant();
2641-
let field_names = self.available_field_names(struct_variant_def, access_span);
2642-
if !field_names.is_empty() {
2596+
if !available_field_names.is_empty() {
26432597
err.note(format!(
26442598
"available fields are: {}",
2645-
self.name_series_display(field_names),
2599+
self.name_series_display(available_field_names),
26462600
));
26472601
}
26482602
}

compiler/rustc_hir_typeck/src/fn_ctxt/suggestions.rs

+14
Original file line numberDiff line numberDiff line change
@@ -1687,4 +1687,18 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
16871687
false
16881688
}
16891689
}
1690+
1691+
pub(crate) fn is_field_suggestable(&self, field: &ty::FieldDef, hir_id: HirId) -> bool {
1692+
// The field must be visible in the containing module.
1693+
field.vis.is_accessible_from(self.tcx.parent_module(hir_id), self.tcx)
1694+
// The field must not be unstable.
1695+
&& !matches!(
1696+
self.tcx.eval_stability(field.did, None, rustc_span::DUMMY_SP, None),
1697+
rustc_middle::middle::stability::EvalResult::Deny { .. }
1698+
)
1699+
// If the field is from an external crate it must not be `doc(hidden)`.
1700+
&& (field.did.is_local() || !self.tcx.is_doc_hidden(field.did))
1701+
// If the field is hygienic it must not originate from a macro expansion.
1702+
&& !self.tcx.def_ident_span(field.did).unwrap().normalize_to_macros_2_0().from_expansion()
1703+
}
16901704
}

compiler/rustc_hir_typeck/src/pat.rs

+15-26
Original file line numberDiff line numberDiff line change
@@ -12,7 +12,6 @@ use rustc_hir::pat_util::EnumerateAndAdjustIterator;
1212
use rustc_hir::{HirId, Pat, PatKind};
1313
use rustc_infer::infer;
1414
use rustc_infer::infer::type_variable::{TypeVariableOrigin, TypeVariableOriginKind};
15-
use rustc_middle::middle::stability::EvalResult;
1615
use rustc_middle::ty::{self, Adt, BindingMode, Ty, TypeVisitableExt};
1716
use rustc_session::lint::builtin::NON_EXHAUSTIVE_OMITTED_PATTERNS;
1817
use rustc_span::edit_distance::find_best_match_for_name;
@@ -1408,6 +1407,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
14081407
adt.variant_descr(),
14091408
&inexistent_fields,
14101409
&mut unmentioned_fields,
1410+
pat,
14111411
variant,
14121412
args,
14131413
))
@@ -1434,15 +1434,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
14341434
let accessible_unmentioned_fields: Vec<_> = unmentioned_fields
14351435
.iter()
14361436
.copied()
1437-
.filter(|(field, _)| {
1438-
field.vis.is_accessible_from(tcx.parent_module(pat.hir_id), tcx)
1439-
&& !matches!(
1440-
tcx.eval_stability(field.did, None, DUMMY_SP, None),
1441-
EvalResult::Deny { .. }
1442-
)
1443-
// We only want to report the error if it is hidden and not local
1444-
&& !(tcx.is_doc_hidden(field.did) && !field.did.is_local())
1445-
})
1437+
.filter(|(field, _)| self.is_field_suggestable(field, pat.hir_id))
14461438
.collect();
14471439

14481440
if !has_rest_pat {
@@ -1578,12 +1570,13 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
15781570
kind_name: &str,
15791571
inexistent_fields: &[&hir::PatField<'tcx>],
15801572
unmentioned_fields: &mut Vec<(&'tcx ty::FieldDef, Ident)>,
1573+
pat: &'tcx Pat<'tcx>,
15811574
variant: &ty::VariantDef,
15821575
args: &'tcx ty::List<ty::GenericArg<'tcx>>,
15831576
) -> DiagnosticBuilder<'tcx, ErrorGuaranteed> {
15841577
let tcx = self.tcx;
1585-
let (field_names, t, plural) = if inexistent_fields.len() == 1 {
1586-
(format!("a field named `{}`", inexistent_fields[0].ident), "this", "")
1578+
let (field_names, t, plural) = if let [field] = inexistent_fields {
1579+
(format!("a field named `{}`", field.ident), "this", "")
15871580
} else {
15881581
(
15891582
format!(
@@ -1620,10 +1613,11 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
16201613
),
16211614
);
16221615

1623-
if unmentioned_fields.len() == 1 {
1624-
let input =
1625-
unmentioned_fields.iter().map(|(_, field)| field.name).collect::<Vec<_>>();
1626-
let suggested_name = find_best_match_for_name(&input, pat_field.ident.name, None);
1616+
if let [(field_def, field)] = unmentioned_fields.as_slice()
1617+
&& self.is_field_suggestable(field_def, pat.hir_id)
1618+
{
1619+
let suggested_name =
1620+
find_best_match_for_name(&[field.name], pat_field.ident.name, None);
16271621
if let Some(suggested_name) = suggested_name {
16281622
err.span_suggestion(
16291623
pat_field.ident.span,
@@ -1646,22 +1640,17 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
16461640
PatKind::Lit(expr)
16471641
if !self.can_coerce(
16481642
self.typeck_results.borrow().expr_ty(expr),
1649-
self.field_ty(
1650-
unmentioned_fields[0].1.span,
1651-
unmentioned_fields[0].0,
1652-
args,
1653-
),
1643+
self.field_ty(field.span, field_def, args),
16541644
) => {}
16551645
_ => {
1656-
let unmentioned_field = unmentioned_fields[0].1.name;
16571646
err.span_suggestion_short(
16581647
pat_field.ident.span,
16591648
format!(
16601649
"`{}` has a field named `{}`",
16611650
tcx.def_path_str(variant.def_id),
1662-
unmentioned_field
1651+
field.name,
16631652
),
1664-
unmentioned_field.to_string(),
1653+
field.name,
16651654
Applicability::MaybeIncorrect,
16661655
);
16671656
}
@@ -1871,8 +1860,8 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
18711860
fields: &'tcx [hir::PatField<'tcx>],
18721861
) -> DiagnosticBuilder<'tcx, ErrorGuaranteed> {
18731862
let inaccessible = if have_inaccessible_fields { " and inaccessible fields" } else { "" };
1874-
let field_names = if unmentioned_fields.len() == 1 {
1875-
format!("field `{}`{}", unmentioned_fields[0].1, inaccessible)
1863+
let field_names = if let [(_, field)] = unmentioned_fields {
1864+
format!("field `{field}`{inaccessible}")
18761865
} else {
18771866
let fields = unmentioned_fields
18781867
.iter()
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,6 @@
1+
#[derive(Default)]
2+
pub struct B {
3+
#[doc(hidden)]
4+
pub hello: i32,
5+
pub bye: i32,
6+
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
1+
// Regression test for issue #93210.
2+
3+
// aux-crate:doc_hidden_fields=doc-hidden-fields.rs
4+
// edition: 2021
5+
6+
#[derive(Default)]
7+
pub struct A {
8+
#[doc(hidden)]
9+
pub hello: i32,
10+
pub bye: i32,
11+
}
12+
13+
#[derive(Default)]
14+
pub struct C {
15+
pub hello: i32,
16+
pub bye: i32,
17+
}
18+
19+
fn main() {
20+
// We want to list the field `hello` despite being marked
21+
// `doc(hidden)` because it's defined in this crate.
22+
A::default().hey;
23+
//~^ ERROR no field `hey` on type `A`
24+
//~| NOTE unknown field
25+
//~| NOTE available fields are: `hello`, `bye`
26+
27+
// Here we want to hide the field `hello` since it's marked
28+
// `doc(hidden)` and comes from an external crate.
29+
doc_hidden_fields::B::default().hey;
30+
//~^ ERROR no field `hey` on type `B`
31+
//~| NOTE unknown field
32+
//~| NOTE available fields are: `bye`
33+
34+
C::default().hey;
35+
//~^ ERROR no field `hey` on type `C`
36+
//~| NOTE unknown field
37+
//~| NOTE available fields are: `hello`, `bye`
38+
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
1+
error[E0609]: no field `hey` on type `A`
2+
--> $DIR/dont-suggest-doc-hidden-fields.rs:22:18
3+
|
4+
LL | A::default().hey;
5+
| ^^^ unknown field
6+
|
7+
= note: available fields are: `hello`, `bye`
8+
9+
error[E0609]: no field `hey` on type `B`
10+
--> $DIR/dont-suggest-doc-hidden-fields.rs:29:37
11+
|
12+
LL | doc_hidden_fields::B::default().hey;
13+
| ^^^ unknown field
14+
|
15+
= note: available fields are: `bye`
16+
17+
error[E0609]: no field `hey` on type `C`
18+
--> $DIR/dont-suggest-doc-hidden-fields.rs:34:18
19+
|
20+
LL | C::default().hey;
21+
| ^^^ unknown field
22+
|
23+
= note: available fields are: `hello`, `bye`
24+
25+
error: aborting due to 3 previous errors
26+
27+
For more information about this error, try `rustc --explain E0609`.
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,33 @@
1+
// Regression test for issue #116334.
2+
// Don't include hygienic fields in the list of available or similarly named fields.
3+
4+
#![feature(decl_macro)]
5+
6+
macro compound($Ty:ident) {
7+
#[derive(Default)]
8+
struct $Ty {
9+
field: u32, // field `field` is hygienic
10+
}
11+
}
12+
13+
macro component($Ty:ident) {
14+
struct $Ty(u64); // field `0` is hygienic (but still accessible via the constructor)
15+
}
16+
17+
compound! { Compound }
18+
component! { Component }
19+
20+
fn main() {
21+
let ty = Compound::default();
22+
23+
let _ = ty.field; //~ ERROR no field `field` on type `Compound`
24+
let _ = ty.fieeld; //~ ERROR no field `fieeld` on type `Compound`
25+
26+
let Compound { field } = ty;
27+
//~^ ERROR struct `Compound` does not have a field named `field`
28+
//~| ERROR pattern requires `..` due to inaccessible fields
29+
30+
let ty = Component(90);
31+
32+
let _ = ty.0; //~ ERROR no field `0` on type `Component`
33+
}

0 commit comments

Comments
 (0)