Skip to main content

rustc_hir_typeck/
errors.rs

1// ignore-tidy-file-filelength
2// FIXME: we should move the field error reporting code somewhere else.
3
4//! Type checking expressions.
5//!
6//! See [`rustc_hir_analysis::check`] for more context on type checking in general.
7
8use rustc_abi::FieldIdx;
9use rustc_attr_ir::lang_items::LangItem;
10use rustc_data_structures::fx::{FxHashSet, FxIndexSet};
11use rustc_data_structures::thin_vec::ThinVec;
12use rustc_data_structures::unord::UnordMap;
13use rustc_errors::codes::*;
14use rustc_errors::{
15    Applicability, Diag, ErrorGuaranteed, MultiSpan, StashKey, Subdiagnostic, listify, pluralize,
16    struct_span_code_err,
17};
18use rustc_hir as hir;
19use rustc_hir::def::{CtorKind, Res};
20use rustc_hir::def_id::DefId;
21use rustc_hir::{ExprKind, HirId, is_range_literal};
22use rustc_hir_analysis::diagnostics::NoFieldOnType;
23use rustc_hir_analysis::hir_ty_lowering::HirTyLowerer as _;
24use rustc_middle::ty::print::{with_forced_trimmed_paths, with_no_trimmed_paths};
25use rustc_middle::ty::{self, GenericArgs, Ty, TypeVisitableExt, fold_regions};
26use rustc_span::edit_distance::find_best_match_for_name;
27use rustc_span::{Ident, Span, Symbol, bug, kw, sym};
28use rustc_trait_selection::infer::InferCtxtExt;
29use rustc_trait_selection::traits::{self, ObligationCauseCode};
30use tracing::{debug, instrument};
31
32use crate::diagnostics::{
33    HelpUseLatestEdition, ReturnLikeStatementKind, ReturnStmtOutsideOfFnBody, TypeMismatchFruTypo,
34};
35use crate::{FnCtxt, type_error_struct};
36
37impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
38    /// Emit an error because `return` or `become` is used outside of a function body.
39    ///
40    /// `expr` is the `return` (`become`) "statement", `kind` is the kind of the statement
41    /// either `Return` or `Become`.
42    pub(crate) fn emit_return_outside_of_fn_body(
43        &self,
44        expr: &hir::Expr<'_>,
45        kind: ReturnLikeStatementKind,
46    ) {
47        let mut err = ReturnStmtOutsideOfFnBody {
48            span: expr.span,
49            encl_body_span: None,
50            encl_fn_span: None,
51            statement_kind: kind,
52        };
53
54        let encl_item_id = self.tcx.hir_get_parent_item(expr.hir_id);
55
56        if let hir::Node::Item(hir::Item {
57            kind: hir::ItemKind::Fn { .. },
58            span: encl_fn_span,
59            ..
60        })
61        | hir::Node::TraitItem(hir::TraitItem {
62            kind: hir::TraitItemKind::Fn(_, hir::TraitFn::Provided(_)),
63            span: encl_fn_span,
64            ..
65        })
66        | hir::Node::ImplItem(hir::ImplItem {
67            kind: hir::ImplItemKind::Fn(..),
68            span: encl_fn_span,
69            ..
70        }) = self.tcx.hir_node_by_def_id(encl_item_id.def_id)
71        {
72            // We are inside a function body, so reporting "return statement
73            // outside of function body" needs an explanation.
74
75            let encl_body_owner_id = self.tcx.hir_enclosing_body_owner(expr.hir_id);
76
77            // If this didn't hold, we would not have to report an error in
78            // the first place.
79            {
    match (&encl_item_id.def_id, &encl_body_owner_id) {
        (left_val, right_val) => {
            if *left_val == *right_val {
                let kind = ::core::panicking::AssertKind::Ne;
                ::core::panicking::assert_failed(kind, &*left_val,
                    &*right_val, ::core::option::Option::None);
            }
        }
    }
};assert_ne!(encl_item_id.def_id, encl_body_owner_id);
80
81            let encl_body = self.tcx.hir_body_owned_by(encl_body_owner_id);
82
83            err.encl_body_span = Some(encl_body.value.span);
84            err.encl_fn_span = Some(*encl_fn_span);
85        }
86
87        self.dcx().emit_err(err);
88    }
89
90    pub(crate) fn point_at_return_for_opaque_ty_error(
91        &self,
92        errors: &mut ThinVec<traits::FulfillmentError<'tcx>>,
93        hir_id: HirId,
94        span: Span,
95        return_expr_ty: Ty<'tcx>,
96        return_span: Span,
97    ) {
98        // Don't point at the whole block if it's empty
99        if span == return_span {
100            return;
101        }
102        for err in errors {
103            let cause = &mut err.obligation.cause;
104            if let ObligationCauseCode::OpaqueReturnType(None) = cause.code() {
105                let new_cause = self.cause(
106                    cause.span,
107                    ObligationCauseCode::OpaqueReturnType(Some((return_expr_ty, hir_id))),
108                );
109                *cause = new_cause;
110            }
111        }
112    }
113
114    /// Report an error for a struct field expression when there are fields which aren't provided.
115    ///
116    /// ```text
117    /// error: missing field `you_can_use_this_field` in initializer of `foo::Foo`
118    ///  --> src/main.rs:8:5
119    ///   |
120    /// 8 |     foo::Foo {};
121    ///   |     ^^^^^^^^ missing `you_can_use_this_field`
122    ///
123    /// error: aborting due to 1 previous error
124    /// ```
125    pub(crate) fn report_missing_fields(
126        &self,
127        adt_ty: Ty<'tcx>,
128        span: Span,
129        full_span: Span,
130        remaining_fields: UnordMap<Ident, (FieldIdx, &ty::FieldDef)>,
131        variant: &'tcx ty::VariantDef,
132        hir_fields: &'tcx [hir::ExprField<'tcx>],
133        args: GenericArgs<'tcx>,
134    ) {
135        let len = remaining_fields.len();
136
137        let displayable_field_names: Vec<&str> =
138            remaining_fields.items().map(|(ident, _)| ident.as_str()).into_sorted_stable_ord();
139
140        let mut truncated_fields_error = String::new();
141        let remaining_fields_names = match &displayable_field_names[..] {
142            [field1] => ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("`{0}`", field1))
    })format!("`{field1}`"),
143            [field1, field2] => ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("`{0}` and `{1}`", field1, field2))
    })format!("`{field1}` and `{field2}`"),
144            [field1, field2, field3] => ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("`{0}`, `{1}` and `{2}`", field1,
                field2, field3))
    })format!("`{field1}`, `{field2}` and `{field3}`"),
145            _ => {
146                truncated_fields_error =
147                    ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!(" and {0} other field{1}", len - 3,
                if len - 3 == 1 { "" } else { "s" }))
    })format!(" and {} other field{}", len - 3, pluralize!(len - 3));
148                displayable_field_names
149                    .iter()
150                    .take(3)
151                    .map(|n| ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("`{0}`", n))
    })format!("`{n}`"))
152                    .collect::<Vec<_>>()
153                    .join(", ")
154            }
155        };
156
157        let mut err = {
    self.dcx().struct_span_err(span,
            ::alloc::__export::must_use({
                    ::alloc::fmt::format(format_args!("missing field{0} {1}{2} in initializer of `{3}`",
                            if len == 1 { "" } else { "s" }, remaining_fields_names,
                            truncated_fields_error, adt_ty))
                })).with_code(E0063)
}struct_span_code_err!(
158            self.dcx(),
159            span,
160            E0063,
161            "missing field{} {}{} in initializer of `{}`",
162            pluralize!(len),
163            remaining_fields_names,
164            truncated_fields_error,
165            adt_ty
166        );
167        err.span_label(span, ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("missing {0}{1}",
                remaining_fields_names, truncated_fields_error))
    })format!("missing {remaining_fields_names}{truncated_fields_error}"));
168
169        if remaining_fields.items().all(|(_, (_, field))| field.value.is_some())
170            && self.tcx.sess.is_nightly_build()
171        {
172            let msg = ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("all remaining fields have default values, {0} use those values with `..`",
                if self.tcx.features().default_field_values() {
                    "you can"
                } else {
                    "if you added `#![feature(default_field_values)]` to your crate you could"
                }))
    })format!(
173                "all remaining fields have default values, {you_can} use those values with `..`",
174                you_can = if self.tcx.features().default_field_values() {
175                    "you can"
176                } else {
177                    "if you added `#![feature(default_field_values)]` to your crate you could"
178                },
179            );
180            if let Some(hir_field) = hir_fields.last() {
181                err.span_suggestion_verbose(
182                    hir_field.span.shrink_to_hi(),
183                    msg,
184                    ", ..".to_string(),
185                    Applicability::MachineApplicable,
186                );
187            } else if hir_fields.is_empty() {
188                err.span_suggestion_verbose(
189                    span.shrink_to_hi().with_hi(full_span.hi()),
190                    msg,
191                    " { .. }".to_string(),
192                    Applicability::MachineApplicable,
193                );
194            }
195        }
196
197        if let Some(hir_field) = hir_fields.last() {
198            self.suggest_fru_from_range_and_emit(hir_field, variant, args, err);
199        } else {
200            err.emit();
201        }
202    }
203
204    /// If the last field is a range literal, but it isn't supposed to be, then they probably
205    /// meant to use functional update syntax.
206    pub(crate) fn suggest_fru_from_range_and_emit(
207        &self,
208        last_expr_field: &hir::ExprField<'tcx>,
209        variant: &ty::VariantDef,
210        args: GenericArgs<'tcx>,
211        mut err: Diag<'_>,
212    ) {
213        if is_range_literal(last_expr_field.expr)
214            && let ExprKind::Struct(&qpath, [range_start, range_end], _) = last_expr_field.expr.kind
215            && self.tcx.qpath_is_lang_item(qpath, LangItem::Range)
216            && let variant_field =
217                variant.fields.iter().find(|field| field.ident(self.tcx) == last_expr_field.ident)
218            && let range_def_id = self.tcx.lang_items().range_struct()
219            && variant_field
220                .and_then(|field| field.ty(self.tcx, args).skip_norm_wip().ty_adt_def())
221                .map(|adt| adt.did())
222                != range_def_id
223        {
224            // Use a (somewhat arbitrary) filtering heuristic to avoid printing
225            // expressions that are either too long, or have control character
226            // such as newlines in them.
227            let expr = self
228                .tcx
229                .sess
230                .source_map()
231                .span_to_snippet(range_end.expr.span)
232                .ok()
233                .filter(|s| s.len() < 25 && !s.contains(|c: char| c.is_control()));
234
235            let fru_span = self
236                .tcx
237                .sess
238                .source_map()
239                .span_extend_while_whitespace(range_start.expr.span)
240                .shrink_to_hi()
241                .to(range_end.expr.span);
242
243            err.subdiagnostic(TypeMismatchFruTypo {
244                expr_span: range_start.expr.span,
245                fru_span,
246                expr,
247            });
248
249            // Suppress any range expr type mismatches
250            self.dcx().try_steal_replace_and_emit_err(
251                last_expr_field.span,
252                StashKey::MaybeFruTypo,
253                err,
254            );
255        } else {
256            err.emit();
257        }
258    }
259
260    /// Report an error for a struct field expression when there are invisible fields.
261    ///
262    /// ```text
263    /// error: cannot construct `Foo` with struct literal syntax due to private fields
264    ///  --> src/main.rs:8:5
265    ///   |
266    /// 8 |     foo::Foo {};
267    ///   |     ^^^^^^^^
268    ///
269    /// error: aborting due to 1 previous error
270    /// ```
271    pub(crate) fn report_private_fields(
272        &self,
273        adt_ty: Ty<'tcx>,
274        span: Span,
275        expr_span: Span,
276        private_fields: Vec<&ty::FieldDef>,
277        used_fields: &'tcx [hir::ExprField<'tcx>],
278    ) {
279        let mut err =
280            self.dcx().struct_span_err(
281                span,
282                ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("cannot construct `{0}` with struct literal syntax due to private fields",
                adt_ty))
    })format!(
283                    "cannot construct `{adt_ty}` with struct literal syntax due to private fields",
284                ),
285            );
286        let (used_private_fields, remaining_private_fields): (
287            Vec<(Symbol, Span, bool)>,
288            Vec<(Symbol, Span, bool)>,
289        ) = private_fields
290            .iter()
291            .map(|field| {
292                match used_fields.iter().find(|used_field| field.name == used_field.ident.name) {
293                    Some(used_field) => (field.name, used_field.span, true),
294                    None => (field.name, self.tcx.def_span(field.did), false),
295                }
296            })
297            .partition(|field| field.2);
298        err.span_labels(used_private_fields.iter().map(|(_, span, _)| *span), "private field");
299
300        if let ty::Adt(def, _) = adt_ty.kind() {
301            if (def.did().is_local() || !used_fields.is_empty())
302                && !remaining_private_fields.is_empty()
303            {
304                let names = if remaining_private_fields.len() > 6 {
305                    String::new()
306                } else {
307                    ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("{0} ",
                listify(&remaining_private_fields,
                        |(name, _, _)|
                            ::alloc::__export::must_use({
                                    ::alloc::fmt::format(format_args!("`{0}`", name))
                                })).expect("expected at least one private field to report")))
    })format!(
308                        "{} ",
309                        listify(&remaining_private_fields, |(name, _, _)| format!("`{name}`"))
310                            .expect("expected at least one private field to report")
311                    )
312                };
313                err.note(::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("{0}private field{1} {3}that {2} not provided",
                if used_fields.is_empty() { "" } else { "...and other " },
                if remaining_private_fields.len() == 1 { "" } else { "s" },
                if remaining_private_fields.len() == 1 {
                    "was"
                } else { "were" }, names))
    })format!(
314                    "{}private field{s} {names}that {were} not provided",
315                    if used_fields.is_empty() { "" } else { "...and other " },
316                    s = pluralize!(remaining_private_fields.len()),
317                    were = pluralize!("was", remaining_private_fields.len()),
318                ));
319            }
320
321            let def_id = def.did();
322            let mut items = self
323                .tcx
324                .inherent_impls(def_id)
325                .into_iter()
326                .flat_map(|&i| self.tcx.associated_items(i).in_definition_order())
327                // Only assoc fn with no receivers.
328                .filter(|item| item.is_fn() && !item.is_method())
329                .filter_map(|item| {
330                    // Only assoc fns that return `Self`
331                    let fn_sig = self
332                        .tcx
333                        .fn_sig(item.def_id)
334                        .instantiate(self.tcx, self.fresh_args_for_item(span, item.def_id))
335                        .skip_norm_wip();
336                    let ret_ty = self.tcx.instantiate_bound_regions_with_erased(fn_sig.output());
337                    if !self.can_eq(self.param_env, ret_ty, adt_ty) {
338                        return None;
339                    }
340                    let input_len = fn_sig.inputs().skip_binder().len();
341                    let name = item.name();
342                    let order = !name.as_str().starts_with("new");
343                    Some((order, name, input_len))
344                })
345                .collect::<Vec<_>>();
346            items.sort_by_key(|(order, _, _)| *order);
347            let suggestion = |name, args| {
348                ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("::{1}({0})",
                std::iter::repeat_n("_", args).collect::<Vec<_>>().join(", "),
                name))
    })format!(
349                    "::{name}({})",
350                    std::iter::repeat_n("_", args).collect::<Vec<_>>().join(", ")
351                )
352            };
353            match &items[..] {
354                [] => {}
355                [(_, name, args)] => {
356                    err.span_suggestion_verbose(
357                        span.shrink_to_hi().with_hi(expr_span.hi()),
358                        ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("you might have meant to use the `{0}` associated function",
                name))
    })format!("you might have meant to use the `{name}` associated function"),
359                        suggestion(name, *args),
360                        Applicability::MaybeIncorrect,
361                    );
362                }
363                _ => {
364                    err.span_suggestions(
365                        span.shrink_to_hi().with_hi(expr_span.hi()),
366                        "you might have meant to use an associated function to build this type",
367                        items.iter().map(|(_, name, args)| suggestion(name, *args)),
368                        Applicability::MaybeIncorrect,
369                    );
370                }
371            }
372            if let Some(default_trait) = self.tcx.get_diagnostic_item(sym::Default)
373                && self
374                    .infcx
375                    .type_implements_trait(default_trait, [adt_ty], self.param_env)
376                    .may_apply()
377            {
378                err.multipart_suggestion(
379                    "consider using the `Default` trait",
380                    ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
        [(span.shrink_to_lo(), "<".to_string()),
                (span.shrink_to_hi().with_hi(expr_span.hi()),
                    " as std::default::Default>::default()".to_string())]))vec![
381                        (span.shrink_to_lo(), "<".to_string()),
382                        (
383                            span.shrink_to_hi().with_hi(expr_span.hi()),
384                            " as std::default::Default>::default()".to_string(),
385                        ),
386                    ],
387                    Applicability::MaybeIncorrect,
388                );
389            }
390        }
391
392        err.emit();
393    }
394
395    pub(crate) fn report_unknown_field(
396        &self,
397        ty: Ty<'tcx>,
398        variant: &'tcx ty::VariantDef,
399        expr: &hir::Expr<'_>,
400        field: &hir::ExprField<'_>,
401        skip_fields: &[hir::ExprField<'_>],
402        kind_name: &str,
403    ) -> ErrorGuaranteed {
404        // we don't care to report errors for a struct if the struct itself is tainted
405        if let Err(guar) = variant.has_errors() {
406            return guar;
407        }
408        let mut err = self.err_ctxt().type_error_struct_with_diag(
409            field.ident.span,
410            |actual| match ty.kind() {
411                ty::Adt(adt, ..) if adt.is_enum() => {
    self.dcx().struct_span_err(field.ident.span,
            ::alloc::__export::must_use({
                    ::alloc::fmt::format(format_args!("{0} `{1}::{2}` has no field named `{3}`",
                            kind_name, actual, variant.name, field.ident))
                })).with_code(E0559)
}struct_span_code_err!(
412                    self.dcx(),
413                    field.ident.span,
414                    E0559,
415                    "{} `{}::{}` has no field named `{}`",
416                    kind_name,
417                    actual,
418                    variant.name,
419                    field.ident
420                ),
421                _ => {
    self.dcx().struct_span_err(field.ident.span,
            ::alloc::__export::must_use({
                    ::alloc::fmt::format(format_args!("{0} `{1}` has no field named `{2}`",
                            kind_name, actual, field.ident))
                })).with_code(E0560)
}struct_span_code_err!(
422                    self.dcx(),
423                    field.ident.span,
424                    E0560,
425                    "{} `{}` has no field named `{}`",
426                    kind_name,
427                    actual,
428                    field.ident
429                ),
430            },
431            ty,
432        );
433
434        let variant_ident_span = self.tcx.def_ident_span(variant.def_id).unwrap();
435        match variant.ctor {
436            Some((CtorKind::Fn, def_id)) => match ty.kind() {
437                ty::Adt(adt, ..) if adt.is_enum() => {
438                    err.span_context(self.tcx.def_span(adt.did()).shrink_to_lo());
439                    err.span_label(
440                        variant_ident_span,
441                        ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("`{0}::{1}` defined here", ty,
                variant.name))
    })format!(
442                            "`{adt}::{variant}` defined here",
443                            adt = ty,
444                            variant = variant.name,
445                        ),
446                    );
447                    err.span_label(field.ident.span, "field does not exist");
448                    let fn_sig = self.tcx.fn_sig(def_id).instantiate_identity().skip_norm_wip();
449                    let inputs = fn_sig.inputs().skip_binder();
450                    let fields = ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("({0})",
                inputs.iter().map(|i|
                                ::alloc::__export::must_use({
                                        ::alloc::fmt::format(format_args!("/* {0} */", i))
                                    })).collect::<Vec<_>>().join(", ")))
    })format!(
451                        "({})",
452                        inputs.iter().map(|i| format!("/* {i} */")).collect::<Vec<_>>().join(", ")
453                    );
454                    let (replace_span, sugg) = match expr.kind {
455                        hir::ExprKind::Struct(qpath, ..) => {
456                            (qpath.span().shrink_to_hi().with_hi(expr.span.hi()), fields)
457                        }
458                        _ => {
459                            (expr.span, ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("{1}::{0}{2}", variant.name, ty,
                fields))
    })format!("{ty}::{variant}{fields}", variant = variant.name))
460                        }
461                    };
462                    err.span_suggestion_verbose(
463                        replace_span,
464                        ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("`{0}::{1}` is a tuple {2}, use the appropriate syntax",
                ty, variant.name, kind_name))
    })format!(
465                            "`{adt}::{variant}` is a tuple {kind_name}, use the appropriate syntax",
466                            adt = ty,
467                            variant = variant.name,
468                        ),
469                        sugg,
470                        Applicability::HasPlaceholders,
471                    );
472                }
473                _ => {
474                    err.span_label(variant_ident_span, ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("`{0}` defined here", ty))
    })format!("`{ty}` defined here"));
475                    err.span_label(field.ident.span, "field does not exist");
476                    let fn_sig = self.tcx.fn_sig(def_id).instantiate_identity().skip_norm_wip();
477                    let inputs = fn_sig.inputs().skip_binder();
478                    let fields = ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("({0})",
                inputs.iter().map(|i|
                                ::alloc::__export::must_use({
                                        ::alloc::fmt::format(format_args!("/* {0} */", i))
                                    })).collect::<Vec<_>>().join(", ")))
    })format!(
479                        "({})",
480                        inputs.iter().map(|i| format!("/* {i} */")).collect::<Vec<_>>().join(", ")
481                    );
482                    err.span_suggestion_verbose(
483                        expr.span,
484                        ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("`{0}` is a tuple {1}, use the appropriate syntax",
                ty, kind_name))
    })format!("`{ty}` is a tuple {kind_name}, use the appropriate syntax",),
485                        ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("{0}{1}", ty, fields))
    })format!("{ty}{fields}"),
486                        Applicability::HasPlaceholders,
487                    );
488                }
489            },
490            _ => {
491                // prevent all specified fields from being suggested
492                let available_field_names = self.available_field_names(variant, expr, skip_fields);
493                if let Some(field_name) =
494                    find_best_match_for_name(&available_field_names, field.ident.name, None)
495                    && !(field.ident.name.as_str().parse::<usize>().is_ok()
496                        && field_name.as_str().parse::<usize>().is_ok())
497                {
498                    err.span_label(field.ident.span, "unknown field");
499                    err.span_suggestion_verbose(
500                        field.ident.span,
501                        "a field with a similar name exists",
502                        field_name,
503                        Applicability::MaybeIncorrect,
504                    );
505                } else {
506                    match ty.kind() {
507                        ty::Adt(adt, ..) => {
508                            if adt.is_enum() {
509                                err.span_label(
510                                    field.ident.span,
511                                    ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("`{0}::{1}` does not have this field",
                ty, variant.name))
    })format!("`{}::{}` does not have this field", ty, variant.name),
512                                );
513                            } else {
514                                err.span_label(
515                                    field.ident.span,
516                                    ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("`{0}` does not have this field",
                ty))
    })format!("`{ty}` does not have this field"),
517                                );
518                            }
519                            if available_field_names.is_empty() {
520                                err.note("all struct fields are already assigned");
521                            } else {
522                                err.note(::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("available fields are: {0}",
                self.name_series_display(available_field_names)))
    })format!(
523                                    "available fields are: {}",
524                                    self.name_series_display(available_field_names)
525                                ));
526                            }
527                        }
528                        _ => ::rustc_span::macros::bug_impl(None,
    format_args!("non-ADT passed to report_unknown_field"),
    Location::caller())bug!("non-ADT passed to report_unknown_field"),
529                    }
530                };
531            }
532        }
533        err.emit_err()
534    }
535
536    fn name_series_display(&self, names: Vec<Symbol>) -> String {
537        // dynamic limit, to never omit just one field
538        let limit = if names.len() == 6 { 6 } else { 5 };
539        let mut display =
540            names.iter().take(limit).map(|n| ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("`{0}`", n))
    })format!("`{n}`")).collect::<Vec<_>>().join(", ");
541        if names.len() > limit {
542            display = ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("{0} ... and {1} others", display,
                names.len() - limit))
    })format!("{} ... and {} others", display, names.len() - limit);
543        }
544        display
545    }
546
547    fn suggest_await_on_field_access(
548        &self,
549        err: &mut Diag<'_>,
550        field_ident: Ident,
551        base: &'tcx hir::Expr<'tcx>,
552        ty: Ty<'tcx>,
553    ) {
554        let Some(output_ty) = self.tcx.get_impl_future_output_ty(ty) else {
555            err.span_label(field_ident.span, "unknown field");
556            return;
557        };
558        let ty::Adt(def, _) = output_ty.kind() else {
559            err.span_label(field_ident.span, "unknown field");
560            return;
561        };
562        // no field access on enum type
563        if def.is_enum() {
564            err.span_label(field_ident.span, "unknown field");
565            return;
566        }
567        if !def.non_enum_variant().fields.iter().any(|field| field.ident(self.tcx) == field_ident) {
568            err.span_label(field_ident.span, "unknown field");
569            return;
570        }
571        err.span_label(
572            field_ident.span,
573            "field not available in `impl Future`, but it is available in its `Output`",
574        );
575        match self.tcx.coroutine_kind(self.body_def_id) {
576            Some(hir::CoroutineKind::Desugared(hir::CoroutineDesugaring::Async, _)) => {
577                err.span_suggestion_verbose(
578                    base.span.shrink_to_hi(),
579                    "consider `await`ing on the `Future` to access the field",
580                    ".await",
581                    Applicability::MaybeIncorrect,
582                );
583            }
584            _ => {
585                let mut span: MultiSpan = base.span.into();
586                span.push_span_label(self.tcx.def_span(self.body_def_id), "this is not `async`");
587                err.span_note(
588                    span,
589                    "this implements `Future` and its output type has the field, \
590                    but the future cannot be awaited in a synchronous function",
591                );
592            }
593        }
594    }
595
596    pub(crate) fn ban_nonexisting_field(
597        &self,
598        ident: Ident,
599        base: &'tcx hir::Expr<'tcx>,
600        expr: &'tcx hir::Expr<'tcx>,
601        base_ty: Ty<'tcx>,
602    ) -> ErrorGuaranteed {
603        {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event /rustc-dev/6905905bb7727fd0f9223f5fdc9ad4e62236d5a2/compiler/rustc_hir_typeck/src/errors.rs:603",
                        "rustc_hir_typeck::errors", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("/rustc-dev/6905905bb7727fd0f9223f5fdc9ad4e62236d5a2/compiler/rustc_hir_typeck/src/errors.rs"),
                        ::tracing_core::__macro_support::Option::Some(603u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_hir_typeck::errors"),
                        ::tracing_core::field::FieldSet::new(&["message"],
                            ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() &&
            {
                let interest = __CALLSITE.interest();
                !interest.is_never() &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest)
            };
    if enabled {
        (|value_set: ::tracing::field::ValueSet|
                    {
                        let meta = __CALLSITE.metadata();
                        ::tracing::Event::dispatch(meta, &value_set);
                        ;
                    })({
                #[allow(unused_imports)]
                use ::tracing::field::{debug, display, Value};
                __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("ban_nonexisting_field: field={0:?}, base={1:?}, expr={2:?}, base_ty={3:?}",
                                                    ident, base, expr, base_ty) as
                                            &dyn ::tracing::field::Value))])
            });
    } else { ; }
};debug!(
604            "ban_nonexisting_field: field={:?}, base={:?}, expr={:?}, base_ty={:?}",
605            ident, base, expr, base_ty
606        );
607        let mut err = self.no_such_field_err(ident, base_ty, expr);
608
609        match *base_ty.peel_refs().kind() {
610            ty::Array(_, len) => {
611                self.maybe_suggest_array_indexing(&mut err, base, ident, len);
612            }
613            ty::RawPtr(..) => {
614                self.suggest_first_deref_field(&mut err, base, ident);
615            }
616            ty::Param(param_ty) => {
617                err.span_label(ident.span, "unknown field");
618                self.point_at_param_definition(&mut err, param_ty);
619            }
620            ty::Alias(_, ty::AliasTy { kind: ty::Opaque { .. }, .. }) => {
621                self.suggest_await_on_field_access(&mut err, ident, base, base_ty.peel_refs());
622            }
623            _ => {
624                err.span_label(ident.span, "unknown field");
625            }
626        }
627
628        self.suggest_fn_call(&mut err, base, base_ty, |output_ty| {
629            if let ty::Adt(def, _) = output_ty.kind()
630                && !def.is_enum()
631            {
632                def.non_enum_variant().fields.iter().any(|field| {
633                    field.ident(self.tcx) == ident
634                        && field.vis.is_accessible_from(expr.hir_id.owner.def_id, self.tcx)
635                })
636            } else if let ty::Tuple(tys) = output_ty.kind()
637                && let Ok(idx) = ident.as_str().parse::<usize>()
638            {
639                idx < tys.len()
640            } else {
641                false
642            }
643        });
644
645        if ident.name == kw::Await {
646            // We know by construction that `<expr>.await` is either on Rust 2015
647            // or results in `ExprKind::Await`. Suggest switching the edition to 2018.
648            err.note("to `.await` a `Future`, switch to Rust 2018 or later");
649            HelpUseLatestEdition::new().add_to_diag(&mut err);
650        }
651
652        err.emit_err()
653    }
654
655    pub(crate) fn ban_private_field_access(
656        &self,
657        expr: &hir::Expr<'tcx>,
658        expr_t: Ty<'tcx>,
659        field: Ident,
660        base_did: DefId,
661        return_ty: Option<Ty<'tcx>>,
662    ) -> ErrorGuaranteed {
663        let mut err = self.private_field_err(field, base_did);
664
665        // Also check if an accessible method exists, which is often what is meant.
666        if self.method_exists_for_diagnostic(field, expr_t, expr.hir_id, return_ty)
667            && !self.expr_in_place(expr.hir_id)
668        {
669            self.suggest_method_call(
670                &mut err,
671                ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("a method `{0}` also exists, call it with parentheses",
                field))
    })format!("a method `{field}` also exists, call it with parentheses"),
672                field,
673                expr_t,
674                expr,
675                None,
676            );
677        }
678        err.emit_err()
679    }
680
681    pub(crate) fn ban_take_value_of_method(
682        &self,
683        expr: &hir::Expr<'tcx>,
684        expr_t: Ty<'tcx>,
685        field: Ident,
686    ) -> ErrorGuaranteed {
687        let mut err = {
    let mut err =
        {
            self.dcx().struct_span_err(field.span,
                    ::alloc::__export::must_use({
                            ::alloc::fmt::format(format_args!("attempted to take value of method `{0}` on type `{1}`",
                                    field, expr_t))
                        })).with_code(E0615)
        };
    if expr_t.references_error() { err.downgrade_to_delayed_bug(); }
    err
}type_error_struct!(
688            self.dcx(),
689            field.span,
690            expr_t,
691            E0615,
692            "attempted to take value of method `{field}` on type `{expr_t}`",
693        );
694        err.span_label(field.span, "method, not a field");
695        let expr_is_call =
696            if let hir::Node::Expr(hir::Expr { kind: ExprKind::Call(callee, _args), .. }) =
697                self.tcx.parent_hir_node(expr.hir_id)
698            {
699                expr.hir_id == callee.hir_id
700            } else {
701                false
702            };
703        let expr_snippet =
704            self.tcx.sess.source_map().span_to_snippet(expr.span).unwrap_or_default();
705        let is_wrapped = expr_snippet.starts_with('(') && expr_snippet.ends_with(')');
706        let after_open = expr.span.lo() + rustc_span::BytePos(1);
707        let before_close = expr.span.hi() - rustc_span::BytePos(1);
708
709        if expr_is_call && is_wrapped {
710            err.multipart_suggestion(
711                "remove wrapping parentheses to call the method",
712                ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
        [(expr.span.with_hi(after_open), String::new()),
                (expr.span.with_lo(before_close), String::new())]))vec![
713                    (expr.span.with_hi(after_open), String::new()),
714                    (expr.span.with_lo(before_close), String::new()),
715                ],
716                Applicability::MachineApplicable,
717            );
718        } else if !self.expr_in_place(expr.hir_id) {
719            // Suggest call parentheses inside the wrapping parentheses
720            let span = if is_wrapped {
721                expr.span.with_lo(after_open).with_hi(before_close)
722            } else {
723                expr.span
724            };
725            self.suggest_method_call(
726                &mut err,
727                "use parentheses to call the method",
728                field,
729                expr_t,
730                expr,
731                Some(span),
732            );
733        } else if let ty::RawPtr(ptr_ty, _) = expr_t.kind()
734            && let ty::Adt(adt_def, _) = ptr_ty.kind()
735            && let ExprKind::Field(base_expr, _) = expr.kind
736            && let [variant] = &adt_def.variants().raw
737            && variant.fields.iter().any(|f| f.ident(self.tcx) == field)
738        {
739            err.multipart_suggestion(
740                "to access the field, dereference first",
741                ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
        [(base_expr.span.shrink_to_lo(), "(*".to_string()),
                (base_expr.span.shrink_to_hi(), ")".to_string())]))vec![
742                    (base_expr.span.shrink_to_lo(), "(*".to_string()),
743                    (base_expr.span.shrink_to_hi(), ")".to_string()),
744                ],
745                Applicability::MaybeIncorrect,
746            );
747        } else {
748            err.help("methods are immutable and cannot be assigned to");
749        }
750
751        // See `StashKey::GenericInFieldExpr` for more info
752        self.dcx().try_steal_replace_and_emit_err(field.span, StashKey::GenericInFieldExpr, err)
753    }
754
755    fn point_at_param_definition(&self, err: &mut Diag<'_>, param: ty::ParamTy) {
756        let generics = self.tcx.generics_of(self.body_def_id);
757        let generic_param = generics.type_param(param, self.tcx);
758        if let ty::GenericParamDefKind::Type { synthetic: true, .. } = generic_param.kind {
759            return;
760        }
761        let param_def_id = generic_param.def_id;
762        let param_hir_id = match param_def_id.as_local() {
763            Some(x) => self.tcx.local_def_id_to_hir_id(x),
764            None => return,
765        };
766        let param_span = self.tcx.hir_span(param_hir_id);
767        let param_name = self.tcx.hir_ty_param_name(param_def_id.expect_local());
768
769        err.span_label(param_span, ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("type parameter \'{0}\' declared here",
                param_name))
    })format!("type parameter '{param_name}' declared here"));
770    }
771
772    fn maybe_suggest_array_indexing(
773        &self,
774        err: &mut Diag<'_>,
775        base: &hir::Expr<'_>,
776        field: Ident,
777        len: ty::Const<'tcx>,
778    ) {
779        err.span_label(field.span, "unknown field");
780        if let (Some(len), Ok(user_index)) = (
781            self.try_structurally_resolve_const(base.span, len).try_to_target_usize(self.tcx),
782            field.as_str().parse::<u64>(),
783        ) {
784            let help = "instead of using tuple indexing, use array indexing";
785            let applicability = if len < user_index {
786                Applicability::MachineApplicable
787            } else {
788                Applicability::MaybeIncorrect
789            };
790            err.multipart_suggestion(
791                help,
792                ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
        [(base.span.between(field.span), "[".to_string()),
                (field.span.shrink_to_hi(), "]".to_string())]))vec![
793                    (base.span.between(field.span), "[".to_string()),
794                    (field.span.shrink_to_hi(), "]".to_string()),
795                ],
796                applicability,
797            );
798        }
799    }
800
801    fn suggest_first_deref_field(&self, err: &mut Diag<'_>, base: &hir::Expr<'_>, field: Ident) {
802        err.span_label(field.span, "unknown field");
803        if base.span.from_expansion() || field.span.from_expansion() {
804            return;
805        }
806        let val = if let Ok(base) = self.tcx.sess.source_map().span_to_snippet(base.span)
807            && base.len() < 20
808        {
809            ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("`{0}`", base))
    })format!("`{base}`")
810        } else {
811            "the value".to_string()
812        };
813        err.multipart_suggestion(
814            ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("{0} is a raw pointer; try dereferencing it",
                val))
    })format!("{val} is a raw pointer; try dereferencing it"),
815            ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
        [(base.span.shrink_to_lo(), "(*".into()),
                (base.span.between(field.span),
                    ::alloc::__export::must_use({
                            ::alloc::fmt::format(format_args!(")."))
                        }))]))vec![
816                (base.span.shrink_to_lo(), "(*".into()),
817                (base.span.between(field.span), format!(").")),
818            ],
819            Applicability::MaybeIncorrect,
820        );
821    }
822
823    pub(crate) fn no_such_field_err(
824        &self,
825        field: Ident,
826        base_ty: Ty<'tcx>,
827        expr: &hir::Expr<'tcx>,
828    ) -> Diag<'_> {
829        let span = field.span;
830        {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event /rustc-dev/6905905bb7727fd0f9223f5fdc9ad4e62236d5a2/compiler/rustc_hir_typeck/src/errors.rs:830",
                        "rustc_hir_typeck::errors", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("/rustc-dev/6905905bb7727fd0f9223f5fdc9ad4e62236d5a2/compiler/rustc_hir_typeck/src/errors.rs"),
                        ::tracing_core::__macro_support::Option::Some(830u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_hir_typeck::errors"),
                        ::tracing_core::field::FieldSet::new(&["message"],
                            ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() &&
            {
                let interest = __CALLSITE.interest();
                !interest.is_never() &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest)
            };
    if enabled {
        (|value_set: ::tracing::field::ValueSet|
                    {
                        let meta = __CALLSITE.metadata();
                        ::tracing::Event::dispatch(meta, &value_set);
                        ;
                    })({
                #[allow(unused_imports)]
                use ::tracing::field::{debug, display, Value};
                __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("no_such_field_err(span: {0:?}, field: {1:?}, expr_t: {2:?})",
                                                    span, field, base_ty) as &dyn ::tracing::field::Value))])
            });
    } else { ; }
};debug!("no_such_field_err(span: {:?}, field: {:?}, expr_t: {:?})", span, field, base_ty);
831
832        let mut err = self.dcx().create_err(NoFieldOnType { span, ty: base_ty, field });
833        if base_ty.references_error() {
834            err.downgrade_to_delayed_bug();
835        }
836
837        self.detect_shadowed_method_on_incorrect_field_access(&mut err, field, base_ty, expr);
838
839        if let Some(within_macro_span) = span.within_macro(expr.span, self.tcx.sess.source_map()) {
840            err.span_label(within_macro_span, "due to this macro variable");
841        }
842
843        // Check if there is an associated function with the same name.
844        if let Some(def_id) = base_ty.peel_refs().ty_adt_def().map(|d| d.did()) {
845            for &impl_def_id in self.tcx.inherent_impls(def_id) {
846                for item in self.tcx.associated_items(impl_def_id).in_definition_order() {
847                    if let ExprKind::Field(base_expr, _) = expr.kind
848                        && item.name() == field.name
849                        && #[allow(non_exhaustive_omitted_patterns)] match item.kind {
    ty::AssocKind::Fn { has_self: false, .. } => true,
    _ => false,
}matches!(item.kind, ty::AssocKind::Fn { has_self: false, .. })
850                    {
851                        err.span_label(field.span, "this is an associated function, not a method");
852                        err.note("found the following associated function; to be used as method, it must have a `self` parameter");
853                        let impl_ty =
854                            self.tcx.type_of(impl_def_id).instantiate_identity().skip_norm_wip();
855                        err.span_note(
856                            self.tcx.def_span(item.def_id),
857                            ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("the candidate is defined in an impl for the type `{0}`",
                impl_ty))
    })format!("the candidate is defined in an impl for the type `{impl_ty}`"),
858                        );
859
860                        let ty_str = match base_ty.peel_refs().kind() {
861                            ty::Adt(def, args) => self.tcx.def_path_str_with_args(def.did(), *args),
862                            _ => base_ty.peel_refs().to_string(),
863                        };
864                        err.multipart_suggestion(
865                            "use associated function syntax instead",
866                            ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
        [(base_expr.span, ty_str),
                (base_expr.span.between(field.span), "::".to_string())]))vec![
867                                (base_expr.span, ty_str),
868                                (base_expr.span.between(field.span), "::".to_string()),
869                            ],
870                            Applicability::MaybeIncorrect,
871                        );
872                        return err;
873                    }
874                }
875            }
876        }
877
878        // try to add a suggestion in case the field is a nested field of a field of the Adt
879        let (ty, unwrap) = if let ty::Adt(def, args) = base_ty.kind()
880            && (self.tcx.is_diagnostic_item(sym::Result, def.did())
881                || self.tcx.is_diagnostic_item(sym::Option, def.did()))
882            && let Some(arg) = args.get(0)
883            && let Some(ty) = arg.as_type()
884        {
885            (ty, "unwrap().")
886        } else {
887            (base_ty, "")
888        };
889        for found_fields in self.get_field_candidates_considering_privacy_for_diag(span, ty) {
890            let field_names = found_fields.iter().map(|field| field.0.name).collect::<Vec<_>>();
891            let mut candidate_fields: Vec<_> = found_fields
892                .into_iter()
893                .filter_map(|candidate_field| {
894                    self.check_for_nested_field_satisfying_condition_for_diag(
895                        span,
896                        &|candidate_field, _| candidate_field == field,
897                        candidate_field,
898                        ::alloc::vec::Vec::new()vec![],
899                    )
900                })
901                .map(|mut field_path| {
902                    field_path.pop();
903                    field_path.iter().map(|id| ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("{0}.", id))
    })format!("{}.", id)).collect::<String>()
904                })
905                .collect::<Vec<_>>();
906            candidate_fields.sort();
907
908            let len = candidate_fields.len();
909            // Don't suggest `.field` if the base expr is from a different
910            // syntax context than the field.
911            if len > 0 && expr.span.ctxt() == field.span.ctxt() {
912                err.span_suggestions(
913                    field.span.shrink_to_lo(),
914                    ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("{0} of the expressions\' fields {1} a field of the same name",
                if len > 1 { "some" } else { "one" },
                if len > 1 { "have" } else { "has" }))
    })format!(
915                        "{} of the expressions' fields {} a field of the same name",
916                        if len > 1 { "some" } else { "one" },
917                        if len > 1 { "have" } else { "has" },
918                    ),
919                    candidate_fields.iter().map(|path| ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("{0}{1}", unwrap, path))
    })format!("{unwrap}{path}")),
920                    Applicability::MaybeIncorrect,
921                );
922            } else if let Some(field_name) =
923                find_best_match_for_name(&field_names, field.name, None)
924                && !(field.name.as_str().parse::<usize>().is_ok()
925                    && field_name.as_str().parse::<usize>().is_ok())
926            {
927                err.span_suggestion_verbose(
928                    field.span,
929                    "a field with a similar name exists",
930                    ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("{1}{0}", field_name, unwrap))
    })format!("{unwrap}{}", field_name),
931                    Applicability::MaybeIncorrect,
932                );
933            } else if !field_names.is_empty() {
934                let is = if field_names.len() == 1 { " is" } else { "s are" };
935                err.note(
936                    ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("available field{1}: {0}",
                self.name_series_display(field_names), is))
    })format!("available field{is}: {}", self.name_series_display(field_names),),
937                );
938            }
939        }
940        err
941    }
942
943    fn detect_shadowed_method_on_incorrect_field_access(
944        &self,
945        err: &mut Diag<'_>,
946        field: Ident,
947        base_ty: Ty<'tcx>,
948        expr: &hir::Expr<'tcx>,
949    ) {
950        let hir::ExprKind::Field(expr, ..) = expr.kind else { return };
951        self.find_shadowed_method_and_provide_diagnostic_context(err, base_ty, expr, |ty| {
952            // Does the alternative method call's resulting type auto-deref to a type that has
953            // the field the user is trying to access?
954            self.get_field_candidates_considering_privacy_for_diag(expr.span, ty)
955                .into_iter()
956                .flat_map(|fields| fields.into_iter())
957                .find(|(f, _ty)| f.name == field.name)
958                .is_some()
959        });
960    }
961
962    pub(crate) fn all_methods(
963        &self,
964        method_ident: Ident,
965        ty: Ty<'tcx>,
966    ) -> impl Iterator<Item = (DefId, DefId, bool)> {
967        let mut impls: Vec<_> = self
968            .tcx
969            .all_traits_including_private()
970            .filter(|trait_def_id| {
971                // Consider only traits with the associated type
972                self.tcx
973                    .associated_items(*trait_def_id)
974                    .in_definition_order()
975                    .any(|i| i.is_method() && i.ident(self.tcx).name == method_ident.name)
976                    && self.tcx.all_impls(*trait_def_id).any(|impl_def_id| {
977                        let header = self.tcx.impl_trait_header(impl_def_id);
978                        let trait_ref = header
979                            .trait_ref
980                            .instantiate(
981                                self.tcx,
982                                self.infcx.fresh_args_for_item(method_ident.span, impl_def_id),
983                            )
984                            .skip_norm_wip();
985                        let value = fold_regions(self.tcx, ty, |_, _| self.tcx.lifetimes.re_erased);
986                        if value.has_escaping_bound_vars() {
987                            return false;
988                        }
989                        self.infcx.can_eq(ty::ParamEnv::empty(), trait_ref.self_ty(), value)
990                            && header.polarity != ty::ImplPolarity::Negative
991                    })
992            })
993            .map(|def_id| (def_id, false))
994            .collect();
995        if let ty::Adt(def, _args) = ty.kind() {
996            // Get all the `impl ReceiverType`s.
997            impls.extend(
998                self.tcx
999                    .inherent_impls(def.did())
1000                    .into_iter()
1001                    .cloned()
1002                    .map(|def_id| (def_id, true)),
1003            );
1004        }
1005        impls.into_iter().filter_map(move |(i, inherent)| {
1006            self.tcx
1007                .associated_items(i)
1008                .in_definition_order()
1009                .find(|assoc| assoc.is_method() && assoc.ident(self.tcx).name == method_ident.name)
1010                .map(|assoc| (i, assoc.def_id, inherent))
1011        })
1012    }
1013
1014    /// Given `expr`, detect if it is a method call that might have been shadowed by another trait
1015    /// being in scope. Only include those traits/impls whose similarly named method have a return
1016    /// type that `finder` considers as "valid" (for example, it has the expected field or method).
1017    pub(crate) fn find_shadowed_method_and_provide_diagnostic_context(
1018        &self,
1019        err: &mut Diag<'_>,
1020        base_ty: Ty<'tcx>,
1021        mut expr: &hir::Expr<'tcx>,
1022        finder: impl Fn(Ty<'tcx>) -> bool,
1023    ) {
1024        if let hir::ExprKind::Unary(hir::UnOp::Deref, e) = expr.kind {
1025            // If we have `*foo`, we want `foo`, which will subsequently be resolved to the earlier
1026            // binding.
1027            expr = e;
1028        }
1029        if let hir::ExprKind::Path(hir::QPath::Resolved(
1030            None,
1031            hir::Path { res: Res::Local(hir_id), .. },
1032        )) = expr.kind
1033            && let hir::Node::Pat(_) = self.tcx.hir_node(*hir_id)
1034            && let hir::Node::LetStmt(local) = self.tcx.parent_hir_node(*hir_id)
1035            && let Some(binding_expr) = local.init
1036        {
1037            // Get and point at the binding's prior method call, if it is one:
1038            // ```
1039            // let foo = bar.borrow();
1040            // foo.qux();
1041            // ```
1042            // Where `qux` is present in the return type of `<Bar as RefCell>::borrow`, but not
1043            // `<Bar as Borrow>::borrow`.
1044            expr = binding_expr;
1045        };
1046        let hir::ExprKind::MethodCall(segment, rcvr, args, span_with_args) = expr.kind else {
1047            return;
1048        };
1049        let Some(def_id) = self.typeck_results.borrow().type_dependent_def_id(expr.hir_id) else {
1050            return;
1051        };
1052        let rcvr_ty = self.typeck_results.borrow().expr_ty_adjusted(rcvr);
1053        let autoderef = self.autoderef(span_with_args, rcvr_ty).silence_errors();
1054        let mut alternatives = FxIndexSet::default();
1055        for (ty, _) in autoderef {
1056            // Get all traits that are implemented by the potential autoderefs for the
1057            // receiver for methods with the same name.
1058            let impls = self.all_methods(segment.ident, ty);
1059            // In all the `impl`s for the autoderefs of the receiver type, look for the method
1060            // *except* the one that was actually called. This would end up being an empty set
1061            // if there are no alternatives.
1062            for (parent, def_id, inherent) in impls.filter(|(_, did, _)| def_id != *did) {
1063                let gen_args = if let ty::Adt(_, args) = ty.peel_refs().kind()
1064                    && inherent
1065                {
1066                    // We want the arguments of the *type* to be passed to the `impl ReceiverType`.
1067                    *args
1068                } else {
1069                    // We want to use the `ReceiverType` for `Self` on trait impls.
1070                    GenericArgs::for_item(self.tcx, def_id, |param, _| {
1071                        if let ty::GenericParamDefKind::Lifetime = param.kind {
1072                            self.tcx.lifetimes.re_erased.into()
1073                        } else if param.name == kw::SelfUpper {
1074                            ty.into()
1075                        } else {
1076                            self.infcx.var_for_def(span_with_args, param)
1077                        }
1078                    })
1079                };
1080                let fn_sig =
1081                    self.tcx.fn_sig(def_id).instantiate(self.tcx, gen_args).skip_norm_wip();
1082                let ret_ty = fn_sig.output();
1083                let ret_ty = self.tcx.instantiate_bound_regions_with_erased(
1084                    self.deeply_resolve_ignoring_regions_with_obligations(ret_ty),
1085                );
1086
1087                // Does the alternative method call's resulting type auto-deref to a type that has
1088                // the thing the user is trying to access?
1089                if !finder(ret_ty) {
1090                    continue;
1091                }
1092                // It does! We'll point at it and suggest the fully-qualified path to the
1093                // alternative method call.
1094                let mut span: MultiSpan = self.tcx.def_span(def_id).into();
1095                span.push_span_context(self.tcx.def_span(parent));
1096                let path = { let _guard = NoTrimmedGuard::new(); self.tcx.def_path_str(def_id) }with_no_trimmed_paths!(self.tcx.def_path_str(def_id));
1097                let after_rcvr = match args {
1098                    [] => (rcvr.span.shrink_to_hi().to(span_with_args), ")".to_string()),
1099                    [first, ..] => (rcvr.span.shrink_to_hi().to(first.span), ", ".to_string()),
1100                };
1101                let self_ty = fn_sig.input(0).skip_binder();
1102                let mutbl = match self_ty.kind() {
1103                    ty::Ref(_, _, mutbl) => mutbl.ref_prefix_str(),
1104                    _ => "",
1105                };
1106                // FIXME: in the suggestions we are now (almost) always suggesting the type or trait
1107                // name as if it was already imported, regardless of whether it is. This means that
1108                // a follow up suggestion will be needed if the item is not in scope (which likely
1109                // won't be).
1110                let call = if inherent {
1111                    let args = if let ty::Adt(def, args) = ty.peel_refs().kind() {
1112                        self.fresh_args_for_item(expr.span, parent).rebase_onto(
1113                            self.tcx,
1114                            def.did(),
1115                            *args,
1116                        )
1117                    } else {
1118                        self.fresh_args_for_item(expr.span, def_id)
1119                    };
1120                    // `Type::method(&rcvr)`
1121                    {
    let _guard = ForceTrimmedGuard::new();
    ::alloc::__export::must_use({
            ::alloc::fmt::format(format_args!("{0}({1}",
                    self.tcx.value_path_str_with_args(def_id, args), mutbl))
        })
}with_forced_trimmed_paths!(format!(
1122                        "{}({mutbl}",
1123                        self.tcx.value_path_str_with_args(def_id, args),
1124                    ))
1125                } else {
1126                    // `<_ as Trait>::method(&rcvr)`
1127                    ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("<_ as {0}>::{1}({2}",
                {
                    let _guard = ForceTrimmedGuard::new();
                    self.tcx.def_path_str_with_args(parent,
                        self.fresh_args_for_item(expr.span, parent))
                }, segment.ident, mutbl))
    })format!(
1128                        "<_ as {}>::{}({mutbl}",
1129                        with_forced_trimmed_paths!(self.tcx.def_path_str_with_args(
1130                            parent,
1131                            self.fresh_args_for_item(expr.span, parent)
1132                        )),
1133                        segment.ident
1134                    )
1135                };
1136                let sugg = ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
        [(rcvr.span.shrink_to_lo(), call), after_rcvr]))vec![(rcvr.span.shrink_to_lo(), call), after_rcvr];
1137                alternatives.insert((path, span, sugg));
1138            }
1139        }
1140        if alternatives.is_empty() {
1141            return;
1142        }
1143        let path = { let _guard = NoTrimmedGuard::new(); self.tcx.def_path_str(def_id) }with_no_trimmed_paths!(self.tcx.def_path_str(def_id));
1144
1145        // On the main diagnostic, point at the method call before the field access to make it clear
1146        // what it actually was.
1147        err.span_label(segment.ident.span, ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("this method is `{0}`", path))
    })format!("this method is `{path}`"));
1148
1149        // Point at the method definition, including its impl or trait, being explicit about what
1150        // type it returns, which at this point we know doesn't have the desired field.
1151        let base_ty = self.tcx.short_string(base_ty, err.long_ty_path());
1152        let mut span: MultiSpan = self.tcx.def_span(def_id).into();
1153        span.push_span_context(self.tcx.def_span(self.tcx.parent(def_id)));
1154        err.span_note(span, ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("this returns `{0}`", base_ty))
    })format!("this returns `{base_ty}`"));
1155
1156        for (path, span, sugg) in alternatives {
1157            // Show the alternatives' method definition...
1158            err.span_note(span, ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("you might have meant to call `{0}` instead",
                path))
    })format!("you might have meant to call `{path}` instead"));
1159            // ...and suggest the fully-qualified path to call them instead.
1160            err.multipart_suggestion(
1161                ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("consider calling `{0}` using the fully-qualified path",
                path))
    })format!("consider calling `{path}` using the fully-qualified path"),
1162                sugg,
1163                Applicability::MaybeIncorrect,
1164            );
1165        }
1166    }
1167
1168    pub(crate) fn private_field_err(&self, field: Ident, base_did: DefId) -> Diag<'_> {
1169        let struct_path = self.tcx().def_path_str(base_did);
1170        let kind_name = self.tcx().def_descr(base_did);
1171        {
    self.dcx().struct_span_err(field.span,
            ::alloc::__export::must_use({
                    ::alloc::fmt::format(format_args!("field `{0}` of {1} `{2}` is private",
                            field, kind_name, struct_path))
                })).with_code(E0616)
}struct_span_code_err!(
1172            self.dcx(),
1173            field.span,
1174            E0616,
1175            "field `{field}` of {kind_name} `{struct_path}` is private",
1176        )
1177        .with_span_label(field.span, "private field")
1178    }
1179
1180    pub(crate) fn get_field_candidates_considering_privacy_for_diag(
1181        &self,
1182        span: Span,
1183        base_ty: Ty<'tcx>,
1184    ) -> Vec<Vec<(Ident, Ty<'tcx>)>> {
1185        {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event /rustc-dev/6905905bb7727fd0f9223f5fdc9ad4e62236d5a2/compiler/rustc_hir_typeck/src/errors.rs:1185",
                        "rustc_hir_typeck::errors", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("/rustc-dev/6905905bb7727fd0f9223f5fdc9ad4e62236d5a2/compiler/rustc_hir_typeck/src/errors.rs"),
                        ::tracing_core::__macro_support::Option::Some(1185u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_hir_typeck::errors"),
                        ::tracing_core::field::FieldSet::new(&["message"],
                            ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() &&
            {
                let interest = __CALLSITE.interest();
                !interest.is_never() &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest)
            };
    if enabled {
        (|value_set: ::tracing::field::ValueSet|
                    {
                        let meta = __CALLSITE.metadata();
                        ::tracing::Event::dispatch(meta, &value_set);
                        ;
                    })({
                #[allow(unused_imports)]
                use ::tracing::field::{debug, display, Value};
                __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("get_field_candidates(span: {0:?}, base_t: {1:?}",
                                                    span, base_ty) as &dyn ::tracing::field::Value))])
            });
    } else { ; }
};debug!("get_field_candidates(span: {:?}, base_t: {:?}", span, base_ty);
1186
1187        let mut autoderef = self.autoderef(span, base_ty).silence_errors();
1188        let deref_chain: Vec<_> = autoderef.by_ref().collect();
1189
1190        // Don't probe if we hit the recursion limit, since it may result in
1191        // quadratic blowup if we then try to further deref the results of this
1192        // function. This is a best-effort method, after all.
1193        if autoderef.reached_recursion_limit() {
1194            return ::alloc::vec::Vec::new()vec![];
1195        }
1196
1197        deref_chain
1198            .into_iter()
1199            .filter_map(move |(base_t, _)| {
1200                match base_t.kind() {
1201                    ty::Adt(base_def, args) if !base_def.is_enum() => {
1202                        let tcx = self.tcx;
1203                        let fields = &base_def.non_enum_variant().fields;
1204                        // Some struct, e.g. some that impl `Deref`, have all private fields
1205                        // because you're expected to deref them to access the _real_ fields.
1206                        // This, for example, will help us suggest accessing a field through a `Box<T>`.
1207                        if fields
1208                            .iter()
1209                            .all(|field| !field.vis.is_accessible_from(self.mod_id, tcx))
1210                        {
1211                            return None;
1212                        }
1213                        return Some(
1214                            fields
1215                                .iter()
1216                                .filter(move |field| {
1217                                    field.vis.is_accessible_from(self.mod_id, tcx)
1218                                        && self.is_field_suggestable(field, span)
1219                                })
1220                                // For compile-time reasons put a limit on number of fields we search
1221                                .take(100)
1222                                .map(|field_def| {
1223                                    (
1224                                        field_def.ident(self.tcx).normalize_to_macros_2_0(),
1225                                        field_def.ty(self.tcx, *args).skip_norm_wip(),
1226                                    )
1227                                })
1228                                .collect::<Vec<_>>(),
1229                        );
1230                    }
1231                    ty::Tuple(types) => {
1232                        return Some(
1233                            types
1234                                .iter()
1235                                .enumerate()
1236                                // For compile-time reasons put a limit on number of fields we search
1237                                .take(100)
1238                                .map(|(i, ty)| (Ident::from_str(&i.to_string()), ty))
1239                                .collect::<Vec<_>>(),
1240                        );
1241                    }
1242                    _ => None,
1243                }
1244            })
1245            .collect()
1246    }
1247
1248    /// This method is called after we have encountered a missing field error to recursively
1249    /// search for the field
1250    {}
#[allow(clippy :: suspicious_else_formatting)]
{
    let __tracing_attr_span;
    let __tracing_attr_guard;
    if ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() ||
            { false } {
        __tracing_attr_span =
            {
                use ::tracing::__macro_support::Callsite as _;
                static __CALLSITE: ::tracing::callsite::DefaultCallsite =
                    {
                        static META: ::tracing::Metadata<'static> =
                            {
                                ::tracing_core::metadata::Metadata::new("check_for_nested_field_satisfying_condition_for_diag",
                                    "rustc_hir_typeck::errors", ::tracing::Level::DEBUG,
                                    ::tracing_core::__macro_support::Option::Some("/rustc-dev/6905905bb7727fd0f9223f5fdc9ad4e62236d5a2/compiler/rustc_hir_typeck/src/errors.rs"),
                                    ::tracing_core::__macro_support::Option::Some(1250u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_hir_typeck::errors"),
                                    ::tracing_core::field::FieldSet::new(&[{
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("span")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("span");
                                                        NAME.as_str()
                                                    },
                                                    {
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("candidate_name")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("candidate_name");
                                                        NAME.as_str()
                                                    },
                                                    {
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("candidate_ty")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("candidate_ty");
                                                        NAME.as_str()
                                                    },
                                                    {
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("field_path")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("field_path");
                                                        NAME.as_str()
                                                    }], ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                    ::tracing::metadata::Kind::SPAN)
                            };
                        ::tracing::callsite::DefaultCallsite::new(&META)
                    };
                let mut interest = ::tracing::subscriber::Interest::never();
                if ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::STATIC_MAX_LEVEL &&
                                ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::LevelFilter::current() &&
                            { interest = __CALLSITE.interest(); !interest.is_never() }
                        &&
                        ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                            interest) {
                    let meta = __CALLSITE.metadata();
                    ::tracing::Span::new(meta,
                        &{
                                #[allow(unused_imports)]
                                use ::tracing::field::{debug, display, Value};
                                meta.fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&span)
                                                            as &dyn ::tracing::field::Value)),
                                                (::tracing::__macro_support::Option::Some(&::tracing::field::debug(&candidate_name)
                                                            as &dyn ::tracing::field::Value)),
                                                (::tracing::__macro_support::Option::Some(&::tracing::field::debug(&candidate_ty)
                                                            as &dyn ::tracing::field::Value)),
                                                (::tracing::__macro_support::Option::Some(&::tracing::field::debug(&field_path)
                                                            as &dyn ::tracing::field::Value))])
                            })
                } else {
                    let span =
                        ::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
                    {};
                    span
                }
            };
        __tracing_attr_guard = __tracing_attr_span.enter();
    }

    #[warn(clippy :: suspicious_else_formatting)]
    {

        #[allow(unknown_lints, unreachable_code, clippy ::
        diverging_sub_expression, clippy :: empty_loop, clippy ::
        let_unit_value, clippy :: let_with_type_underscore, clippy ::
        needless_return, clippy :: unreachable)]
        if false {
            let __tracing_attr_fake_return: Option<Vec<Ident>> = loop {};
            return __tracing_attr_fake_return;
        }
        {
            if field_path.len() > 3 { return None; }
            field_path.push(candidate_name);
            if matches(candidate_name, candidate_ty) {
                return Some(field_path);
            }
            for nested_fields in
                self.get_field_candidates_considering_privacy_for_diag(span,
                    candidate_ty) {
                for field in nested_fields {
                    if let Some(field_path) =
                            self.check_for_nested_field_satisfying_condition_for_diag(span,
                                matches, field, field_path.clone()) {
                        return Some(field_path);
                    }
                }
            }
            None
        }
    }
}#[instrument(skip(self, matches), level = "debug")]
1251    pub(crate) fn check_for_nested_field_satisfying_condition_for_diag(
1252        &self,
1253        span: Span,
1254        matches: &impl Fn(Ident, Ty<'tcx>) -> bool,
1255        (candidate_name, candidate_ty): (Ident, Ty<'tcx>),
1256        mut field_path: Vec<Ident>,
1257    ) -> Option<Vec<Ident>> {
1258        if field_path.len() > 3 {
1259            // For compile-time reasons and to avoid infinite recursion we only check for fields
1260            // up to a depth of three
1261            return None;
1262        }
1263        field_path.push(candidate_name);
1264        if matches(candidate_name, candidate_ty) {
1265            return Some(field_path);
1266        }
1267        for nested_fields in
1268            self.get_field_candidates_considering_privacy_for_diag(span, candidate_ty)
1269        {
1270            // recursively search fields of `candidate_field` if it's a ty::Adt
1271            for field in nested_fields {
1272                if let Some(field_path) = self.check_for_nested_field_satisfying_condition_for_diag(
1273                    span,
1274                    matches,
1275                    field,
1276                    field_path.clone(),
1277                ) {
1278                    return Some(field_path);
1279                }
1280            }
1281        }
1282        None
1283    }
1284
1285    pub(crate) fn point_at_index(
1286        &self,
1287        errors: &mut ThinVec<traits::FulfillmentError<'tcx>>,
1288        span: Span,
1289    ) {
1290        let mut seen_preds = FxHashSet::default();
1291        // We re-sort here so that the outer most root obligations comes first, as we have the
1292        // subsequent weird logic to identify *every* relevant obligation for proper deduplication
1293        // of diagnostics.
1294        errors.sort_by_key(|error| error.root_obligation.recursion_depth);
1295        for error in errors {
1296            match (
1297                error.root_obligation.predicate.kind().skip_binder(),
1298                error.obligation.predicate.kind().skip_binder(),
1299            ) {
1300                (ty::PredicateKind::Clause(ty::ClauseKind::Trait(predicate)), _)
1301                    if self.tcx.is_lang_item(predicate.trait_ref.def_id, LangItem::Index) =>
1302                {
1303                    seen_preds.insert(error.obligation.predicate.kind().skip_binder());
1304                }
1305                (_, ty::PredicateKind::Clause(ty::ClauseKind::Trait(predicate)))
1306                    if self.tcx.is_diagnostic_item(sym::SliceIndex, predicate.trait_ref.def_id) =>
1307                {
1308                    seen_preds.insert(error.obligation.predicate.kind().skip_binder());
1309                }
1310                (root, pred) if seen_preds.contains(&pred) || seen_preds.contains(&root) => {}
1311                _ => continue,
1312            }
1313            error.obligation.cause.span = span;
1314        }
1315    }
1316}