Skip to main content

rustc_resolve/late/
diagnostics.rs

1// ignore-tidy-file-filelength
2
3use std::borrow::Cow;
4use std::iter;
5use std::ops::Deref;
6
7use rustc_ast::visit::{FnCtxt, FnKind, LifetimeCtxt, Visitor, walk_ty};
8use rustc_ast::{
9    self as ast, AngleBracketedArg, AssocItemKind, DUMMY_NODE_ID, Expr, ExprKind, GenericArg,
10    GenericArgs, GenericParam, GenericParamKind, Item, ItemKind, MethodCall, NodeId, Path,
11    PathSegment, Ty, TyKind,
12};
13use rustc_ast_pretty::pprust::{path_to_string, where_bound_predicate_to_string};
14use rustc_data_structures::fx::{FxHashMap, FxHashSet, FxIndexMap, FxIndexSet};
15use rustc_data_structures::unord::UnordItems;
16use rustc_errors::codes::*;
17use rustc_errors::{
18    Applicability, Diag, Diagnostic, ErrorGuaranteed, MultiSpan, SuggestionStyle, pluralize,
19    struct_span_code_err,
20};
21use rustc_hir as hir;
22use rustc_hir::attrs::diagnostic::{CustomDiagnostic, FormatArgs};
23use rustc_hir::def::Namespace::{self, *};
24use rustc_hir::def::{CtorKind, CtorOf, DefKind, MacroKinds};
25use rustc_hir::def_id::{CRATE_DEF_ID, DefId};
26use rustc_hir::{MissingLifetimeKind, PrimTy, find_attr};
27use rustc_middle::ty;
28use rustc_session::{Session, lint};
29use rustc_span::edit_distance::{edit_distance, find_best_match_for_name};
30use rustc_span::edition::Edition;
31use rustc_span::{DUMMY_SP, DesugaringKind, Ident, Span, Symbol, kw, sym};
32use thin_vec::{ThinVec, thin_vec};
33use tracing::debug;
34
35use super::NoConstantGenericsReason;
36use crate::diagnostics::impls::{ImportSuggestion, LabelSuggestion, TypoSuggestion};
37use crate::late::{
38    AliasPossibility, LateResolutionVisitor, LifetimeBinderKind, LifetimeRes, LifetimeRibKind,
39    LifetimeUseSet, QSelf, RibKind,
40};
41use crate::ty::fast_reject::SimplifiedType;
42use crate::{
43    Finalize, Module, ModuleOrUniformRoot, ParentScope, PathResult, PathSource, Res, Resolver,
44    ScopeSet, Segment, diagnostics, path_names_to_string,
45};
46
47/// A field or associated item from self type suggested in case of resolution failure.
48enum AssocSuggestion {
49    Field(Span),
50    MethodWithSelf { called: bool },
51    AssocFn { called: bool },
52    AssocType,
53    AssocConst,
54}
55
56impl AssocSuggestion {
57    fn action(&self) -> &'static str {
58        match self {
59            AssocSuggestion::Field(_) => "use the available field",
60            AssocSuggestion::MethodWithSelf { called: true } => {
61                "call the method with the fully-qualified path"
62            }
63            AssocSuggestion::MethodWithSelf { called: false } => {
64                "refer to the method with the fully-qualified path"
65            }
66            AssocSuggestion::AssocFn { called: true } => "call the associated function",
67            AssocSuggestion::AssocFn { called: false } => "refer to the associated function",
68            AssocSuggestion::AssocConst => "use the associated `const`",
69            AssocSuggestion::AssocType => "use the associated type",
70        }
71    }
72}
73
74fn is_self_type(path: &[Segment], namespace: Namespace) -> bool {
75    namespace == TypeNS && path.len() == 1 && path[0].ident.name == kw::SelfUpper
76}
77
78fn is_self_value(path: &[Segment], namespace: Namespace) -> bool {
79    namespace == ValueNS && path.len() == 1 && path[0].ident.name == kw::SelfLower
80}
81
82fn path_to_string_without_assoc_item_bindings(path: &Path) -> String {
83    let mut path = path.clone();
84    for segment in &mut path.segments {
85        let mut remove_args = false;
86        if let Some(args) = segment.args.as_deref_mut()
87            && let ast::GenericArgs::AngleBracketed(angle_bracketed) = args
88        {
89            angle_bracketed.args.retain(|arg| #[allow(non_exhaustive_omitted_patterns)] match arg {
    ast::AngleBracketedArg::Arg(_) => true,
    _ => false,
}matches!(arg, ast::AngleBracketedArg::Arg(_)));
90            remove_args = angle_bracketed.args.is_empty();
91        }
92        if remove_args {
93            segment.args = None;
94        }
95    }
96    path_to_string(&path)
97}
98
99/// Gets the stringified path for an enum from an `ImportSuggestion` for an enum variant.
100fn import_candidate_to_enum_paths(suggestion: &ImportSuggestion) -> (String, String) {
101    let variant_path = &suggestion.path;
102    let variant_path_string = path_names_to_string(variant_path);
103
104    let path_len = suggestion.path.segments.len();
105    let enum_path = ast::Path {
106        span: suggestion.path.span,
107        segments: suggestion.path.segments[0..path_len - 1].iter().cloned().collect(),
108    };
109    let enum_path_string = path_names_to_string(&enum_path);
110
111    (variant_path_string, enum_path_string)
112}
113
114/// Description of an elided lifetime.
115#[derive(#[automatically_derived]
impl ::core::marker::Copy for MissingLifetime { }Copy, #[automatically_derived]
impl ::core::clone::Clone for MissingLifetime {
    #[inline]
    fn clone(&self) -> MissingLifetime {
        let _: ::core::clone::AssertParamIsClone<NodeId>;
        let _: ::core::clone::AssertParamIsClone<Span>;
        let _: ::core::clone::AssertParamIsClone<MissingLifetimeKind>;
        let _: ::core::clone::AssertParamIsClone<usize>;
        *self
    }
}Clone, #[automatically_derived]
impl ::core::cmp::PartialEq for MissingLifetime {
    #[inline]
    fn eq(&self, other: &MissingLifetime) -> bool {
        self.id == other.id && self.id_for_lint == other.id_for_lint &&
                    self.span == other.span && self.kind == other.kind &&
            self.count == other.count
    }
}PartialEq, #[automatically_derived]
impl ::core::cmp::Eq for MissingLifetime {
    #[inline]
    #[doc(hidden)]
    #[coverage(off)]
    fn assert_fields_are_eq(&self) {
        let _: ::core::cmp::AssertParamIsEq<NodeId>;
        let _: ::core::cmp::AssertParamIsEq<Span>;
        let _: ::core::cmp::AssertParamIsEq<MissingLifetimeKind>;
        let _: ::core::cmp::AssertParamIsEq<usize>;
    }
}Eq, #[automatically_derived]
impl ::core::cmp::PartialOrd for MissingLifetime {
    #[inline]
    fn partial_cmp(&self, other: &MissingLifetime)
        -> ::core::option::Option<::core::cmp::Ordering> {
        ::core::option::Option::Some(::core::cmp::Ord::cmp(self, other))
    }
}PartialOrd, #[automatically_derived]
impl ::core::cmp::Ord for MissingLifetime {
    #[inline]
    fn cmp(&self, other: &MissingLifetime) -> ::core::cmp::Ordering {
        match ::core::cmp::Ord::cmp(&self.id, &other.id) {
            ::core::cmp::Ordering::Equal =>
                match ::core::cmp::Ord::cmp(&self.id_for_lint,
                        &other.id_for_lint) {
                    ::core::cmp::Ordering::Equal =>
                        match ::core::cmp::Ord::cmp(&self.span, &other.span) {
                            ::core::cmp::Ordering::Equal =>
                                match ::core::cmp::Ord::cmp(&self.kind, &other.kind) {
                                    ::core::cmp::Ordering::Equal =>
                                        ::core::cmp::Ord::cmp(&self.count, &other.count),
                                    cmp => cmp,
                                },
                            cmp => cmp,
                        },
                    cmp => cmp,
                },
            cmp => cmp,
        }
    }
}Ord, #[automatically_derived]
impl ::core::fmt::Debug for MissingLifetime {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        ::core::fmt::Formatter::debug_struct_field5_finish(f,
            "MissingLifetime", "id", &self.id, "id_for_lint",
            &self.id_for_lint, "span", &self.span, "kind", &self.kind,
            "count", &&self.count)
    }
}Debug)]
116pub(super) struct MissingLifetime {
117    /// Used to overwrite the resolution with the suggestion, to avoid cascading errors.
118    pub id: NodeId,
119    /// As we cannot yet emit lints in this crate and have to buffer them instead,
120    /// we need to associate each lint with some `NodeId`,
121    /// however for some `MissingLifetime`s their `NodeId`s are "fake",
122    /// in a sense that they are temporary and not get preserved down the line,
123    /// which means that the lints for those nodes will not get emitted.
124    /// To combat this, we can try to use some other `NodeId`s as a fallback option.
125    pub id_for_lint: NodeId,
126    /// Where to suggest adding the lifetime.
127    pub span: Span,
128    /// How the lifetime was introduced, to have the correct space and comma.
129    pub kind: MissingLifetimeKind,
130    /// Number of elided lifetimes, used for elision in path.
131    pub count: usize,
132}
133
134/// Description of the lifetimes appearing in a function parameter.
135/// This is used to provide a literal explanation to the elision failure.
136#[derive(#[automatically_derived]
impl ::core::fmt::Debug for ElisionFnParameter {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        ::core::fmt::Formatter::debug_struct_field4_finish(f,
            "ElisionFnParameter", "index", &self.index, "ident", &self.ident,
            "lifetime_count", &self.lifetime_count, "span", &&self.span)
    }
}Debug)]
137pub(super) struct ElisionFnParameter {
138    /// The index of the argument in the original definition.
139    pub index: usize,
140    /// The name of the argument if it's a simple ident.
141    pub ident: Option<Ident>,
142    /// The number of lifetimes in the parameter.
143    pub lifetime_count: usize,
144    /// The span of the parameter.
145    pub span: Span,
146}
147
148/// Description of lifetimes that appear as candidates for elision.
149/// This is used to suggest introducing an explicit lifetime.
150#[derive(#[automatically_derived]
impl ::core::clone::Clone for LifetimeElisionCandidate {
    #[inline]
    fn clone(&self) -> LifetimeElisionCandidate {
        let _: ::core::clone::AssertParamIsClone<MissingLifetime>;
        *self
    }
}Clone, #[automatically_derived]
impl ::core::marker::Copy for LifetimeElisionCandidate { }Copy, #[automatically_derived]
impl ::core::fmt::Debug for LifetimeElisionCandidate {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        match self {
            LifetimeElisionCandidate::Ignore =>
                ::core::fmt::Formatter::write_str(f, "Ignore"),
            LifetimeElisionCandidate::Missing(__self_0) =>
                ::core::fmt::Formatter::debug_tuple_field1_finish(f,
                    "Missing", &__self_0),
        }
    }
}Debug)]
151pub(super) enum LifetimeElisionCandidate {
152    /// This is not a real lifetime, or it is a named lifetime, in which case we won't suggest anything.
153    Ignore,
154    Missing(MissingLifetime),
155}
156
157/// Only used for diagnostics.
158#[derive(#[automatically_derived]
impl ::core::fmt::Debug for BaseError {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        let names: &'static _ =
            &["msg", "fallback_label", "span", "span_label", "could_be_expr",
                        "suggestion", "module", "notes"];
        let values: &[&dyn ::core::fmt::Debug] =
            &[&self.msg, &self.fallback_label, &self.span, &self.span_label,
                        &self.could_be_expr, &self.suggestion, &self.module,
                        &&self.notes];
        ::core::fmt::Formatter::debug_struct_fields_finish(f, "BaseError",
            names, values)
    }
}Debug)]
159struct BaseError {
160    msg: String,
161    fallback_label: String,
162    span: Span,
163    span_label: Option<(Span, &'static str)>,
164    could_be_expr: bool,
165    suggestion: Option<(Span, &'static str, String)>,
166    module: Option<DefId>,
167    notes: Vec<String>,
168}
169
170#[derive(#[automatically_derived]
impl ::core::fmt::Debug for TypoCandidate {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        match self {
            TypoCandidate::Typo(__self_0) =>
                ::core::fmt::Formatter::debug_tuple_field1_finish(f, "Typo",
                    &__self_0),
            TypoCandidate::Shadowed(__self_0, __self_1) =>
                ::core::fmt::Formatter::debug_tuple_field2_finish(f,
                    "Shadowed", __self_0, &__self_1),
            TypoCandidate::None =>
                ::core::fmt::Formatter::write_str(f, "None"),
        }
    }
}Debug)]
171enum TypoCandidate {
172    Typo(TypoSuggestion),
173    Shadowed(Res, Option<Span>),
174    None,
175}
176
177impl TypoCandidate {
178    fn to_opt_suggestion(self) -> Option<TypoSuggestion> {
179        match self {
180            TypoCandidate::Typo(sugg) => Some(sugg),
181            TypoCandidate::Shadowed(_, _) | TypoCandidate::None => None,
182        }
183    }
184}
185
186impl<'ast, 'ra, 'tcx> LateResolutionVisitor<'_, 'ast, 'ra, 'tcx> {
187    fn trait_assoc_type_def_id_by_name(
188        &mut self,
189        trait_def_id: DefId,
190        assoc_name: Symbol,
191    ) -> Option<DefId> {
192        let module = self.r.get_module(trait_def_id)?;
193        self.r.resolutions(module).iter().find_map(|(key, resolution)| {
194            if key.ident.name != assoc_name {
195                return None;
196            }
197            let resolution = resolution.borrow(self.r);
198            let binding = resolution.best_decl()?;
199            match binding.res() {
200                Res::Def(DefKind::AssocTy, def_id) => Some(def_id),
201                _ => None,
202            }
203        })
204    }
205
206    /// This does best-effort work to generate suggestions for associated types.
207    fn suggest_assoc_type_from_bounds(
208        &mut self,
209        err: &mut Diag<'_>,
210        source: PathSource<'_, 'ast, 'ra>,
211        path: &[Segment],
212        ident_span: Span,
213    ) -> bool {
214        // Filter out cases where we cannot emit meaningful suggestions.
215        if source.namespace() != TypeNS {
216            return false;
217        }
218        let [segment] = path else { return false };
219        if segment.has_generic_args {
220            return false;
221        }
222        if !ident_span.can_be_used_for_suggestions() {
223            return false;
224        }
225        let assoc_name = segment.ident.name;
226        if assoc_name == kw::Underscore {
227            return false;
228        }
229
230        // Map: type parameter name -> (trait def id -> (assoc type def id, trait paths as written)).
231        // We keep a set of paths per trait so we can detect cases like
232        // `T: Trait<i32> + Trait<u32>` where suggesting `T::Assoc` would be ambiguous.
233        let mut matching_bounds: FxIndexMap<
234            Symbol,
235            FxIndexMap<DefId, (DefId, FxIndexSet<String>)>,
236        > = FxIndexMap::default();
237
238        let mut record_bound = |this: &mut Self,
239                                ty_param: Symbol,
240                                poly_trait_ref: &ast::PolyTraitRef| {
241            // Avoid generating suggestions we can't print in a well-formed way.
242            if !poly_trait_ref.bound_generic_params.is_empty() {
243                return;
244            }
245            if poly_trait_ref.modifiers != ast::TraitBoundModifiers::NONE {
246                return;
247            }
248            let Some(trait_seg) = poly_trait_ref.trait_ref.path.segments.last() else {
249                return;
250            };
251            let Some(partial_res) = this.r.partial_res_map.get(&trait_seg.id) else {
252                return;
253            };
254            let Some(trait_def_id) = partial_res.full_res().and_then(|res| res.opt_def_id()) else {
255                return;
256            };
257            let Some(assoc_type_def_id) =
258                this.trait_assoc_type_def_id_by_name(trait_def_id, assoc_name)
259            else {
260                return;
261            };
262
263            // Preserve `::` and generic args so we don't generate broken suggestions like
264            // `<T as Foo>::Assoc` for bounds written as `T: ::Foo<'a>`, while stripping
265            // associated-item bindings that are rejected in qualified paths.
266            let trait_path =
267                path_to_string_without_assoc_item_bindings(&poly_trait_ref.trait_ref.path);
268            let trait_bounds = matching_bounds.entry(ty_param).or_default();
269            let trait_bounds = trait_bounds
270                .entry(trait_def_id)
271                .or_insert_with(|| (assoc_type_def_id, FxIndexSet::default()));
272            if true {
    {
        match (&trait_bounds.0, &assoc_type_def_id) {
            (left_val, right_val) => {
                if !(*left_val == *right_val) {
                    let kind = ::core::panicking::AssertKind::Eq;
                    ::core::panicking::assert_failed(kind, &*left_val,
                        &*right_val, ::core::option::Option::None);
                }
            }
        }
    };
};debug_assert_eq!(trait_bounds.0, assoc_type_def_id);
273            trait_bounds.1.insert(trait_path);
274        };
275
276        let mut record_from_generics = |this: &mut Self, generics: &ast::Generics| {
277            for param in &generics.params {
278                let ast::GenericParamKind::Type { .. } = param.kind else { continue };
279                for bound in &param.bounds {
280                    let ast::GenericBound::Trait(poly_trait_ref) = bound else { continue };
281                    record_bound(this, param.ident.name, poly_trait_ref);
282                }
283            }
284
285            for predicate in &generics.where_clause.predicates {
286                let ast::WherePredicateKind::BoundPredicate(where_bound) = &predicate.kind else {
287                    continue;
288                };
289
290                let ast::TyKind::Path(None, bounded_path) = &where_bound.bounded_ty.kind else {
291                    continue;
292                };
293                let [ast::PathSegment { ident, args: None, .. }] = &bounded_path.segments[..]
294                else {
295                    continue;
296                };
297
298                // Only suggest for bounds that are explicitly on an in-scope type parameter.
299                let Some(partial_res) = this.r.partial_res_map.get(&where_bound.bounded_ty.id)
300                else {
301                    continue;
302                };
303                if !#[allow(non_exhaustive_omitted_patterns)] match partial_res.full_res() {
    Some(Res::Def(DefKind::TyParam, _)) => true,
    _ => false,
}matches!(partial_res.full_res(), Some(Res::Def(DefKind::TyParam, _))) {
304                    continue;
305                }
306
307                for bound in &where_bound.bounds {
308                    let ast::GenericBound::Trait(poly_trait_ref) = bound else { continue };
309                    record_bound(this, ident.name, poly_trait_ref);
310                }
311            }
312        };
313
314        if let Some(item) = self.diag_metadata.current_item
315            && let Some(generics) = item.kind.generics()
316        {
317            record_from_generics(self, generics);
318        }
319
320        if let Some(item) = self.diag_metadata.current_item
321            && #[allow(non_exhaustive_omitted_patterns)] match item.kind {
    ItemKind::Impl(..) => true,
    _ => false,
}matches!(item.kind, ItemKind::Impl(..))
322            && let Some(assoc) = self.diag_metadata.current_impl_item
323        {
324            let generics = match &assoc.kind {
325                AssocItemKind::Const(ast::ConstItem { generics, .. })
326                | AssocItemKind::Fn(ast::Fn { generics, .. })
327                | AssocItemKind::Type(ast::TyAlias { generics, .. }) => Some(generics),
328                AssocItemKind::Delegation(..)
329                | AssocItemKind::MacCall(..)
330                | AssocItemKind::DelegationMac(..) => None,
331            };
332            if let Some(generics) = generics {
333                record_from_generics(self, generics);
334            }
335        }
336
337        let mut suggestions: FxIndexSet<String> = FxIndexSet::default();
338        for (ty_param, traits) in matching_bounds {
339            let ty_param = ty_param.to_ident_string();
340            let trait_paths_len: usize = traits.values().map(|(_, paths)| paths.len()).sum();
341            if traits.len() == 1 && trait_paths_len == 1 {
342                let assoc_type_def_id = traits.values().next().unwrap().0;
343                let assoc_segment = ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("{0}{1}", assoc_name,
                self.r.item_required_generic_args_suggestion(assoc_type_def_id)))
    })format!(
344                    "{}{}",
345                    assoc_name,
346                    self.r.item_required_generic_args_suggestion(assoc_type_def_id)
347                );
348                suggestions.insert(::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("{0}::{1}", ty_param,
                assoc_segment))
    })format!("{ty_param}::{assoc_segment}"));
349            } else {
350                for (assoc_type_def_id, trait_paths) in traits.into_values() {
351                    let assoc_segment = ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("{0}{1}", assoc_name,
                self.r.item_required_generic_args_suggestion(assoc_type_def_id)))
    })format!(
352                        "{}{}",
353                        assoc_name,
354                        self.r.item_required_generic_args_suggestion(assoc_type_def_id)
355                    );
356                    for trait_path in trait_paths {
357                        suggestions
358                            .insert(::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("<{0} as {1}>::{2}", ty_param,
                trait_path, assoc_segment))
    })format!("<{ty_param} as {trait_path}>::{assoc_segment}"));
359                    }
360                }
361            }
362        }
363
364        if suggestions.is_empty() {
365            return false;
366        }
367
368        let mut suggestions: Vec<String> = suggestions.into_iter().collect();
369        suggestions.sort();
370
371        err.span_suggestions_with_style(
372            ident_span,
373            "you might have meant to use an associated type of the same name",
374            suggestions,
375            Applicability::MaybeIncorrect,
376            SuggestionStyle::ShowAlways,
377        );
378
379        true
380    }
381
382    fn make_base_error(
383        &mut self,
384        path: &[Segment],
385        span: Span,
386        source: PathSource<'_, 'ast, 'ra>,
387        res: Option<Res>,
388        could_be_expr: bool,
389    ) -> BaseError {
390        // Make the base error.
391        let mut expected = source.descr_expected();
392        let path_str = Segment::names_to_string(path);
393
394        if let Some(res) = res {
395            BaseError {
396                msg: ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("expected {0}, found {1} `{2}`",
                expected, res.descr(), path_str))
    })format!("expected {}, found {} `{}`", expected, res.descr(), path_str),
397                fallback_label: ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("not a {0}", expected))
    })format!("not a {expected}"),
398                span,
399                span_label: match res {
400                    Res::Def(DefKind::TyParam, def_id) => {
401                        Some((self.r.def_span(def_id), "found this type parameter"))
402                    }
403                    _ => None,
404                },
405                could_be_expr,
406                suggestion: None,
407                module: None,
408                notes: Vec::new(),
409            }
410        } else {
411            let mut span_label = None;
412            let item_ident = path.last().unwrap().ident;
413            let item_span = item_ident.span;
414            let (tick, mod_prefix, mod_str, module, suggestion) = if path.len() == 1 {
415                {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event compiler/rustc_resolve/src/late/diagnostics.rs:415",
                        "rustc_resolve::late::diagnostics", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_resolve/src/late/diagnostics.rs"),
                        ::tracing_core::__macro_support::Option::Some(415u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_resolve::late::diagnostics"),
                        ::tracing_core::field::FieldSet::new(&[{
                                            const NAME:
                                                ::tracing::__macro_support::FieldName<{
                                                    ::tracing::__macro_support::FieldName::len("self.diag_metadata.current_impl_items")
                                                }> =
                                                ::tracing::__macro_support::FieldName::new("self.diag_metadata.current_impl_items");
                                            NAME.as_str()
                                        }], ::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(&::tracing::field::debug(&self.diag_metadata.current_impl_items)
                                            as &dyn ::tracing::field::Value))])
            });
    } else { ; }
};debug!(?self.diag_metadata.current_impl_items);
416                {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event compiler/rustc_resolve/src/late/diagnostics.rs:416",
                        "rustc_resolve::late::diagnostics", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_resolve/src/late/diagnostics.rs"),
                        ::tracing_core::__macro_support::Option::Some(416u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_resolve::late::diagnostics"),
                        ::tracing_core::field::FieldSet::new(&[{
                                            const NAME:
                                                ::tracing::__macro_support::FieldName<{
                                                    ::tracing::__macro_support::FieldName::len("self.diag_metadata.current_function")
                                                }> =
                                                ::tracing::__macro_support::FieldName::new("self.diag_metadata.current_function");
                                            NAME.as_str()
                                        }], ::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(&::tracing::field::debug(&self.diag_metadata.current_function)
                                            as &dyn ::tracing::field::Value))])
            });
    } else { ; }
};debug!(?self.diag_metadata.current_function);
417                let suggestion = if self.current_trait_ref.is_none()
418                    && let Some((fn_kind, _)) = self.diag_metadata.current_function
419                    && let Some(FnCtxt::Assoc(_)) = fn_kind.ctxt()
420                    && let FnKind::Fn(_, _, ast::Fn { sig, .. }) = fn_kind
421                    && let Some(items) = self.diag_metadata.current_impl_items
422                    && let Some(item) = items.iter().find(|i| {
423                        i.kind.ident().is_some_and(|ident| {
424                            // Don't suggest if the item is in Fn signature arguments (#112590).
425                            ident.name == item_ident.name && !sig.span.contains(item_span)
426                        })
427                    }) {
428                    let sp = item_span.shrink_to_lo();
429
430                    // Account for `Foo { field }` when suggesting `self.field` so we result on
431                    // `Foo { field: self.field }`.
432                    let field = match source {
433                        PathSource::Expr(Some(Expr { kind: ExprKind::Struct(expr), .. })) => {
434                            expr.fields.iter().find(|f| f.ident == item_ident)
435                        }
436                        _ => None,
437                    };
438                    let pre = if let Some(field) = field
439                        && field.is_shorthand
440                    {
441                        ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("{0}: ", item_ident))
    })format!("{item_ident}: ")
442                    } else {
443                        String::new()
444                    };
445                    // Ensure we provide a structured suggestion for an assoc fn only for
446                    // expressions that are actually a fn call.
447                    let is_call = match field {
448                        Some(ast::ExprField { expr, .. }) => {
449                            #[allow(non_exhaustive_omitted_patterns)] match expr.kind {
    ExprKind::Call(..) => true,
    _ => false,
}matches!(expr.kind, ExprKind::Call(..))
450                        }
451                        _ => #[allow(non_exhaustive_omitted_patterns)] match source {
    PathSource::Expr(Some(Expr { kind: ExprKind::Call(..), .. })) => true,
    _ => false,
}matches!(
452                            source,
453                            PathSource::Expr(Some(Expr { kind: ExprKind::Call(..), .. })),
454                        ),
455                    };
456
457                    match &item.kind {
458                        AssocItemKind::Fn(fn_)
459                            if (!sig.decl.has_self() || !is_call) && fn_.sig.decl.has_self() =>
460                        {
461                            // Ensure that we only suggest `self.` if `self` is available,
462                            // you can't call `fn foo(&self)` from `fn bar()` (#115992).
463                            // We also want to mention that the method exists.
464                            span_label = Some((
465                                fn_.ident.span,
466                                "a method by that name is available on `Self` here",
467                            ));
468                            None
469                        }
470                        AssocItemKind::Fn(fn_) if !fn_.sig.decl.has_self() && !is_call => {
471                            span_label = Some((
472                                fn_.ident.span,
473                                "an associated function by that name is available on `Self` here",
474                            ));
475                            None
476                        }
477                        AssocItemKind::Fn(fn_) if fn_.sig.decl.has_self() => {
478                            Some((sp, "consider using the method on `Self`", ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("{0}self.", pre))
    })format!("{pre}self.")))
479                        }
480                        AssocItemKind::Fn(_) => Some((
481                            sp,
482                            "consider using the associated function on `Self`",
483                            ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("{0}Self::", pre))
    })format!("{pre}Self::"),
484                        )),
485                        AssocItemKind::Const(..) => Some((
486                            sp,
487                            "consider using the associated constant on `Self`",
488                            ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("{0}Self::", pre))
    })format!("{pre}Self::"),
489                        )),
490                        _ => None,
491                    }
492                } else {
493                    None
494                };
495                ("", String::new(), "this scope".to_string(), None, suggestion)
496            } else if path.len() == 2 && path[0].ident.name == kw::PathRoot {
497                if self.r.tcx.sess.edition() > Edition::Edition2015 {
498                    // In edition 2018 onwards, the `::foo` syntax may only pull from the extern prelude
499                    // which overrides all other expectations of item type
500                    expected = "crate";
501                    ("", String::new(), "the list of imported crates".to_string(), None, None)
502                } else {
503                    (
504                        "",
505                        String::new(),
506                        "the crate root".to_string(),
507                        Some(CRATE_DEF_ID.to_def_id()),
508                        None,
509                    )
510                }
511            } else if path.len() == 2 && path[0].ident.name == kw::Crate {
512                (
513                    "",
514                    String::new(),
515                    "the crate root".to_string(),
516                    Some(CRATE_DEF_ID.to_def_id()),
517                    None,
518                )
519            } else {
520                let mod_path = &path[..path.len() - 1];
521                let mod_res = self.resolve_path(mod_path, Some(TypeNS), None, source);
522                let mod_prefix = match mod_res {
523                    PathResult::Module(ModuleOrUniformRoot::Module(module)) => module.res(),
524                    _ => None,
525                };
526
527                let module_did = mod_prefix.as_ref().and_then(Res::mod_def_id);
528
529                let mod_prefix =
530                    mod_prefix.map_or_else(String::new, |res| ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("{0} ", res.descr()))
    })format!("{} ", res.descr()));
531                ("`", mod_prefix, Segment::names_to_string(mod_path), module_did, None)
532            };
533
534            let suggestion =
535                if ["true", "false"].contains(&item_ident.to_string().to_lowercase().as_str()) {
536                    // check if we are in situation of typo like `True` instead of `true`.
537                    let item_typo = item_ident.to_string().to_lowercase();
538                    Some((item_span, "you may want to use a bool value instead", item_typo))
539                // FIXME(vincenzopalazzo): make the check smarter,
540                // and maybe expand with levenshtein distance checks
541                } else if item_ident.as_str() == "printf" {
542                    Some((
543                        item_span,
544                        "you may have meant to use the `print` macro",
545                        "print!".to_owned(),
546                    ))
547                } else {
548                    suggestion
549                };
550            let mut msg = ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("cannot find {0} `{1}` in {2}{3}{4}{3}",
                expected, item_ident, mod_prefix, tick, mod_str))
    })format!(
551                "cannot find {expected} `{item_ident}` in {mod_prefix}{tick}{mod_str}{tick}"
552            );
553            let mut fallback_label = if path_str == "async" && expected.starts_with("struct") {
554                "`async` blocks are only allowed in Rust 2018 or later".to_string()
555            } else {
556                ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("not found in {0}{1}{0}", tick,
                mod_str))
    })format!("not found in {tick}{mod_str}{tick}")
557            };
558            let mut notes = Vec::new();
559            if let Some(module_def_id) = module
560                && let Some(directive) = self.r.on_unknown_data(module_def_id)
561            {
562                let args = FormatArgs { unresolved: item_ident.to_string(), this: mod_str, .. };
563                let CustomDiagnostic {
564                    message,
565                    label,
566                    notes: custom_notes,
567                    parent_label: _unreachable,
568                } = directive.eval(None, &args);
569                if let Some(message) = message {
570                    notes.push(msg);
571                    msg = message;
572                }
573                if let Some(label) = label {
574                    fallback_label = label;
575                    if let Some((_, span_label)) = span_label.take() {
576                        notes.push(span_label.to_string());
577                    }
578                }
579                notes.extend(custom_notes);
580            }
581
582            BaseError {
583                msg,
584                fallback_label,
585                span: item_span,
586                span_label,
587                could_be_expr,
588                suggestion,
589                module,
590                notes,
591            }
592        }
593    }
594
595    fn could_be_expr(&self, res: Res, span: Span) -> bool {
596        match res {
597            // Verify whether this is a fn call or an Fn used as a type.
598            Res::Def(DefKind::Fn, _) => self
599                .r
600                .tcx
601                .sess
602                .source_map()
603                .span_to_snippet(span)
604                .is_ok_and(|snippet| snippet.ends_with(')')),
605            Res::Def(
606                DefKind::Ctor(..)
607                | DefKind::AssocFn
608                | DefKind::Const { .. }
609                | DefKind::AssocConst { .. },
610                _,
611            )
612            | Res::SelfCtor(_)
613            | Res::PrimTy(_)
614            | Res::Local(_) => true,
615            _ => false,
616        }
617    }
618
619    /// Try to suggest for a module path that cannot be resolved.
620    /// Such as `fmt::Debug` where `fmt` is not resolved without importing,
621    /// here we search with `lookup_import_candidates` for a module named `fmt`
622    /// with `TypeNS` as namespace.
623    ///
624    /// We need a separate function here because we won't suggest for a path with single segment
625    /// and we won't change `SourcePath` api `is_expected` to match `Type` with `DefKind::Mod`
626    pub(crate) fn smart_resolve_partial_mod_path_errors(
627        &mut self,
628        prefix_path: &[Segment],
629        following_seg: Option<&Segment>,
630    ) -> Vec<ImportSuggestion> {
631        if let Some(segment) = prefix_path.last()
632            && let Some(following_seg) = following_seg
633        {
634            let candidates = self.r.lookup_import_candidates(
635                segment.ident,
636                Namespace::TypeNS,
637                &self.parent_scope,
638                &|res: Res| #[allow(non_exhaustive_omitted_patterns)] match res {
    Res::Def(DefKind::Mod, _) => true,
    _ => false,
}matches!(res, Res::Def(DefKind::Mod, _)),
639            );
640            // double check next seg is valid
641            candidates
642                .into_iter()
643                .filter(|candidate| {
644                    if let Some(def_id) = candidate.did
645                        && let Some(module) = self.r.get_module(def_id)
646                    {
647                        Some(def_id) != self.parent_scope.module.opt_def_id()
648                            && self
649                                .r
650                                .resolutions(module)
651                                .iter()
652                                .any(|(key, _r)| key.ident.name == following_seg.ident.name)
653                    } else {
654                        false
655                    }
656                })
657                .collect::<Vec<_>>()
658        } else {
659            Vec::new()
660        }
661    }
662
663    /// Handles error reporting for `smart_resolve_path_fragment` function.
664    /// Creates base error and amends it with one short label and possibly some longer helps/notes.
665    #[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("smart_resolve_report_errors",
                                    "rustc_resolve::late::diagnostics", ::tracing::Level::DEBUG,
                                    ::tracing_core::__macro_support::Option::Some("compiler/rustc_resolve/src/late/diagnostics.rs"),
                                    ::tracing_core::__macro_support::Option::Some(665u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_resolve::late::diagnostics"),
                                    ::tracing_core::field::FieldSet::new(&[{
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("path")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("path");
                                                        NAME.as_str()
                                                    },
                                                    {
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("following_seg")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("following_seg");
                                                        NAME.as_str()
                                                    },
                                                    {
                                                        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("source")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("source");
                                                        NAME.as_str()
                                                    },
                                                    {
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("res")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("res");
                                                        NAME.as_str()
                                                    },
                                                    {
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("qself")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("qself");
                                                        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(&path)
                                                            as &dyn ::tracing::field::Value)),
                                                (::tracing::__macro_support::Option::Some(&::tracing::field::debug(&following_seg)
                                                            as &dyn ::tracing::field::Value)),
                                                (::tracing::__macro_support::Option::Some(&::tracing::field::debug(&span)
                                                            as &dyn ::tracing::field::Value)),
                                                (::tracing::__macro_support::Option::Some(&::tracing::field::debug(&source)
                                                            as &dyn ::tracing::field::Value)),
                                                (::tracing::__macro_support::Option::Some(&::tracing::field::debug(&res)
                                                            as &dyn ::tracing::field::Value)),
                                                (::tracing::__macro_support::Option::Some(&::tracing::field::debug(&qself)
                                                            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:
                    (Diag<'tcx>, Vec<ImportSuggestion>) = loop {};
            return __tracing_attr_fake_return;
        }
        {
            {
                use ::tracing::__macro_support::Callsite as _;
                static __CALLSITE: ::tracing::callsite::DefaultCallsite =
                    {
                        static META: ::tracing::Metadata<'static> =
                            {
                                ::tracing_core::metadata::Metadata::new("event compiler/rustc_resolve/src/late/diagnostics.rs:675",
                                    "rustc_resolve::late::diagnostics", ::tracing::Level::DEBUG,
                                    ::tracing_core::__macro_support::Option::Some("compiler/rustc_resolve/src/late/diagnostics.rs"),
                                    ::tracing_core::__macro_support::Option::Some(675u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_resolve::late::diagnostics"),
                                    ::tracing_core::field::FieldSet::new(&[{
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("res")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("res");
                                                        NAME.as_str()
                                                    },
                                                    {
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("source")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("source");
                                                        NAME.as_str()
                                                    }], ::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(&::tracing::field::debug(&res)
                                                        as &dyn ::tracing::field::Value)),
                                            (::tracing::__macro_support::Option::Some(&::tracing::field::debug(&source)
                                                        as &dyn ::tracing::field::Value))])
                        });
                } else { ; }
            };
            let cross_namespace_res =
                res.filter(|res| !res.matches_ns(source.namespace()));
            let could_be_expr =
                res.is_some_and(|res| self.could_be_expr(res, span));
            let base_error =
                self.make_base_error(path, span, source,
                    if cross_namespace_res.is_some() { None } else { res },
                    could_be_expr);
            let code = source.error_code(res.is_some());
            let mut err =
                self.r.dcx().struct_span_err(base_error.span,
                    base_error.msg.clone());
            err.code(code);
            if let Some(res) = cross_namespace_res {
                err.note(::alloc::__export::must_use({
                            ::alloc::fmt::format(format_args!("{0} {1} named `{2}` exists in another namespace",
                                    res.article(), res.descr(), Segment::names_to_string(path)))
                        }));
            }
            if let Some(within_macro_span) =
                    base_error.span.within_macro(span,
                        self.r.tcx.sess.source_map()) {
                err.span_label(within_macro_span,
                    "due to this macro variable");
            }
            self.detect_missing_binding_available_from_pattern(&mut err, path,
                following_seg);
            self.suggest_at_operator_in_slice_pat_with_range(&mut err, path);
            self.suggest_range_struct_destructuring(&mut err, path, source);
            self.suggest_swapping_misplaced_self_ty_and_trait(&mut err,
                source, res, base_error.span);
            if let Some((span, label)) = base_error.span_label {
                err.span_label(span, label);
            }
            for note in &base_error.notes { err.note(note.clone()); }
            if let Some(ref sugg) = base_error.suggestion {
                err.span_suggestion_verbose(sugg.0, sugg.1, &sugg.2,
                    Applicability::MaybeIncorrect);
            }
            self.suggest_changing_type_to_const_param(&mut err, res, source,
                path, following_seg, span);
            self.explain_functions_in_pattern(&mut err, res, source);
            if self.suggest_pattern_match_with_let(&mut err, source, span) {
                err.span_label(base_error.span, base_error.fallback_label);
                return (err, Vec::new());
            }
            self.suggest_self_or_self_ref(&mut err, path, span);
            self.detect_assoc_type_constraint_meant_as_path(&mut err,
                &base_error);
            self.detect_rtn_with_fully_qualified_path(&mut err, path,
                following_seg, span, source, res, qself);
            if self.suggest_self_ty(&mut err, source, path, span) ||
                    self.suggest_self_value(&mut err, source, path, span) {
                return (err, Vec::new());
            }
            if let Some((did, item)) =
                    self.lookup_doc_alias_name(path, source.namespace()) {
                let item_name = item.name;
                let suggestion_name = self.r.tcx.item_name(did);
                err.span_suggestion(item.span,
                    ::alloc::__export::must_use({
                            ::alloc::fmt::format(format_args!("`{0}` has a name defined in the doc alias attribute as `{1}`",
                                    suggestion_name, item_name))
                        }), suggestion_name, Applicability::MaybeIncorrect);
                return (err, Vec::new());
            };
            let (found, suggested_candidates, mut candidates) =
                self.try_lookup_name_relaxed(&mut err, source, path,
                    following_seg, span, res, &base_error);
            if found { return (err, candidates); }
            if self.suggest_shadowed(&mut err, source, path, following_seg,
                    span) {
                candidates.clear();
            }
            let mut fallback =
                self.suggest_trait_and_bounds(&mut err, source, res, span,
                    &base_error);
            fallback |=
                self.suggest_typo(&mut err, source, path, following_seg, span,
                    &base_error, suggested_candidates);
            if fallback {
                err.span_label(base_error.span, base_error.fallback_label);
            }
            self.err_code_special_cases(&mut err, source, path, span);
            let module =
                base_error.module.unwrap_or_else(|| CRATE_DEF_ID.to_def_id());
            self.r.find_cfg_stripped(&mut err,
                &path.last().unwrap().ident.name, module);
            (err, candidates)
        }
    }
}#[tracing::instrument(skip(self), level = "debug")]
666    pub(crate) fn smart_resolve_report_errors(
667        &mut self,
668        path: &[Segment],
669        following_seg: Option<&Segment>,
670        span: Span,
671        source: PathSource<'_, 'ast, 'ra>,
672        res: Option<Res>,
673        qself: Option<&QSelf>,
674    ) -> (Diag<'tcx>, Vec<ImportSuggestion>) {
675        debug!(?res, ?source);
676        let cross_namespace_res = res.filter(|res| !res.matches_ns(source.namespace()));
677        let could_be_expr = res.is_some_and(|res| self.could_be_expr(res, span));
678        let base_error = self.make_base_error(
679            path,
680            span,
681            source,
682            if cross_namespace_res.is_some() { None } else { res },
683            could_be_expr,
684        );
685
686        let code = source.error_code(res.is_some());
687        let mut err = self.r.dcx().struct_span_err(base_error.span, base_error.msg.clone());
688        err.code(code);
689
690        if let Some(res) = cross_namespace_res {
691            err.note(format!(
692                "{} {} named `{}` exists in another namespace",
693                res.article(),
694                res.descr(),
695                Segment::names_to_string(path),
696            ));
697        }
698
699        // Try to get the span of the identifier within the path's syntax context
700        // (if that's different).
701        if let Some(within_macro_span) =
702            base_error.span.within_macro(span, self.r.tcx.sess.source_map())
703        {
704            err.span_label(within_macro_span, "due to this macro variable");
705        }
706
707        self.detect_missing_binding_available_from_pattern(&mut err, path, following_seg);
708        self.suggest_at_operator_in_slice_pat_with_range(&mut err, path);
709        self.suggest_range_struct_destructuring(&mut err, path, source);
710        self.suggest_swapping_misplaced_self_ty_and_trait(&mut err, source, res, base_error.span);
711
712        if let Some((span, label)) = base_error.span_label {
713            err.span_label(span, label);
714        }
715        for note in &base_error.notes {
716            err.note(note.clone());
717        }
718
719        if let Some(ref sugg) = base_error.suggestion {
720            err.span_suggestion_verbose(sugg.0, sugg.1, &sugg.2, Applicability::MaybeIncorrect);
721        }
722
723        self.suggest_changing_type_to_const_param(&mut err, res, source, path, following_seg, span);
724        self.explain_functions_in_pattern(&mut err, res, source);
725
726        if self.suggest_pattern_match_with_let(&mut err, source, span) {
727            // Fallback label.
728            err.span_label(base_error.span, base_error.fallback_label);
729            return (err, Vec::new());
730        }
731
732        self.suggest_self_or_self_ref(&mut err, path, span);
733        self.detect_assoc_type_constraint_meant_as_path(&mut err, &base_error);
734        self.detect_rtn_with_fully_qualified_path(
735            &mut err,
736            path,
737            following_seg,
738            span,
739            source,
740            res,
741            qself,
742        );
743        if self.suggest_self_ty(&mut err, source, path, span)
744            || self.suggest_self_value(&mut err, source, path, span)
745        {
746            return (err, Vec::new());
747        }
748
749        if let Some((did, item)) = self.lookup_doc_alias_name(path, source.namespace()) {
750            let item_name = item.name;
751            let suggestion_name = self.r.tcx.item_name(did);
752            err.span_suggestion(
753                item.span,
754                format!("`{suggestion_name}` has a name defined in the doc alias attribute as `{item_name}`"),
755                    suggestion_name,
756                    Applicability::MaybeIncorrect
757                );
758
759            return (err, Vec::new());
760        };
761
762        let (found, suggested_candidates, mut candidates) = self.try_lookup_name_relaxed(
763            &mut err,
764            source,
765            path,
766            following_seg,
767            span,
768            res,
769            &base_error,
770        );
771        if found {
772            return (err, candidates);
773        }
774
775        if self.suggest_shadowed(&mut err, source, path, following_seg, span) {
776            // if there is already a shadowed name, don'suggest candidates for importing
777            candidates.clear();
778        }
779
780        let mut fallback = self.suggest_trait_and_bounds(&mut err, source, res, span, &base_error);
781        fallback |= self.suggest_typo(
782            &mut err,
783            source,
784            path,
785            following_seg,
786            span,
787            &base_error,
788            suggested_candidates,
789        );
790
791        if fallback {
792            // Fallback label.
793            err.span_label(base_error.span, base_error.fallback_label);
794        }
795        self.err_code_special_cases(&mut err, source, path, span);
796
797        let module = base_error.module.unwrap_or_else(|| CRATE_DEF_ID.to_def_id());
798        self.r.find_cfg_stripped(&mut err, &path.last().unwrap().ident.name, module);
799
800        (err, candidates)
801    }
802
803    fn detect_rtn_with_fully_qualified_path(
804        &self,
805        err: &mut Diag<'_>,
806        path: &[Segment],
807        following_seg: Option<&Segment>,
808        span: Span,
809        source: PathSource<'_, '_, '_>,
810        res: Option<Res>,
811        qself: Option<&QSelf>,
812    ) {
813        if let Some(Res::Def(DefKind::AssocFn, _)) = res
814            && let PathSource::TraitItem(TypeNS, _) = source
815            && let None = following_seg
816            && let Some(qself) = qself
817            && let TyKind::Path(None, ty_path) = &qself.ty.kind
818            && ty_path.segments.len() == 1
819            && self.diag_metadata.current_where_predicate.is_some()
820        {
821            err.span_suggestion_verbose(
822                span,
823                "you might have meant to use the return type notation syntax",
824                ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("{0}::{1}(..)",
                ty_path.segments[0].ident, path[path.len() - 1].ident))
    })format!("{}::{}(..)", ty_path.segments[0].ident, path[path.len() - 1].ident),
825                Applicability::MaybeIncorrect,
826            );
827        }
828    }
829
830    fn detect_assoc_type_constraint_meant_as_path(
831        &self,
832        err: &mut Diag<'_>,
833        base_error: &BaseError,
834    ) {
835        let Some(ty) = self.diag_metadata.current_type_path else {
836            return;
837        };
838        let TyKind::Path(_, path) = &ty.kind else {
839            return;
840        };
841        for segment in &path.segments {
842            let Some(params) = &segment.args else {
843                continue;
844            };
845            let ast::GenericArgs::AngleBracketed(params) = params.deref() else {
846                continue;
847            };
848            for param in &params.args {
849                let ast::AngleBracketedArg::Constraint(constraint) = param else {
850                    continue;
851                };
852                let ast::AssocItemConstraintKind::Bound { bounds } = &constraint.kind else {
853                    continue;
854                };
855                for bound in bounds {
856                    let ast::GenericBound::Trait(trait_ref) = bound else {
857                        continue;
858                    };
859                    if trait_ref.modifiers == ast::TraitBoundModifiers::NONE
860                        && base_error.span == trait_ref.span
861                    {
862                        err.span_suggestion_verbose(
863                            constraint.ident.span.between(trait_ref.span),
864                            "you might have meant to write a path instead of an associated type bound",
865                            "::",
866                            Applicability::MachineApplicable,
867                        );
868                    }
869                }
870            }
871        }
872    }
873
874    fn suggest_self_or_self_ref(&mut self, err: &mut Diag<'_>, path: &[Segment], span: Span) {
875        if !self.self_type_is_available() {
876            return;
877        }
878        let Some(path_last_segment) = path.last() else { return };
879        let item_str = path_last_segment.ident;
880        // Emit help message for fake-self from other languages (e.g., `this` in JavaScript).
881        if ["this", "my"].contains(&item_str.as_str()) {
882            err.span_suggestion_short(
883                span,
884                "you might have meant to use `self` here instead",
885                "self",
886                Applicability::MaybeIncorrect,
887            );
888            if !self.self_value_is_available(path[0].ident.span) {
889                if let Some((FnKind::Fn(_, _, ast::Fn { sig, .. }), fn_span)) =
890                    &self.diag_metadata.current_function
891                {
892                    let (span, sugg) = if let Some(param) = sig.decl.inputs.get(0) {
893                        (param.span.shrink_to_lo(), "&self, ")
894                    } else {
895                        (
896                            self.r
897                                .tcx
898                                .sess
899                                .source_map()
900                                .span_through_char(*fn_span, '(')
901                                .shrink_to_hi(),
902                            "&self",
903                        )
904                    };
905                    err.span_suggestion_verbose(
906                        span,
907                        "if you meant to use `self`, you are also missing a `self` receiver \
908                         argument",
909                        sugg,
910                        Applicability::MaybeIncorrect,
911                    );
912                }
913            }
914        }
915    }
916
917    fn try_lookup_name_relaxed(
918        &mut self,
919        err: &mut Diag<'_>,
920        source: PathSource<'_, '_, '_>,
921        path: &[Segment],
922        following_seg: Option<&Segment>,
923        span: Span,
924        res: Option<Res>,
925        base_error: &BaseError,
926    ) -> (bool, FxHashSet<String>, Vec<ImportSuggestion>) {
927        let span = match following_seg {
928            Some(_) if path[0].ident.span.eq_ctxt(path[path.len() - 1].ident.span) => {
929                // The path `span` that comes in includes any following segments, which we don't
930                // want to replace in the suggestions.
931                path[0].ident.span.to(path[path.len() - 1].ident.span)
932            }
933            _ => span,
934        };
935        let mut suggested_candidates = FxHashSet::default();
936        // Try to lookup name in more relaxed fashion for better error reporting.
937        let ident = path.last().unwrap().ident;
938        let is_expected = &|res| source.is_expected(res);
939        let ns = source.namespace();
940        let is_enum_variant = &|res| #[allow(non_exhaustive_omitted_patterns)] match res {
    Res::Def(DefKind::Variant, _) => true,
    _ => false,
}matches!(res, Res::Def(DefKind::Variant, _));
941        let path_str = Segment::names_to_string(path);
942        let ident_span = path.last().map_or(span, |ident| ident.ident.span);
943        let mut candidates = self
944            .r
945            .lookup_import_candidates(ident, ns, &self.parent_scope, is_expected)
946            .into_iter()
947            .filter(|ImportSuggestion { did, .. }| {
948                match (did, res.and_then(|res| res.opt_def_id())) {
949                    (Some(suggestion_did), Some(actual_did)) => *suggestion_did != actual_did,
950                    _ => true,
951                }
952            })
953            .collect::<Vec<_>>();
954        // Try to filter out intrinsics candidates, as long as we have
955        // some other candidates to suggest.
956        let intrinsic_candidates: Vec<_> = candidates
957            .extract_if(.., |sugg| {
958                let path = path_names_to_string(&sugg.path);
959                path.starts_with("core::intrinsics::") || path.starts_with("std::intrinsics::")
960            })
961            .collect();
962        if candidates.is_empty() {
963            // Put them back if we have no more candidates to suggest...
964            candidates = intrinsic_candidates;
965        }
966        let crate_def_id = CRATE_DEF_ID.to_def_id();
967        if candidates.is_empty() && is_expected(Res::Def(DefKind::Enum, crate_def_id)) {
968            let mut enum_candidates: Vec<_> = self
969                .r
970                .lookup_import_candidates(ident, ns, &self.parent_scope, is_enum_variant)
971                .into_iter()
972                .map(|suggestion| import_candidate_to_enum_paths(&suggestion))
973                .filter(|(_, enum_ty_path)| !enum_ty_path.starts_with("std::prelude::"))
974                .collect();
975            if !enum_candidates.is_empty() {
976                enum_candidates.sort();
977
978                // Contextualize for E0425 "cannot find type", but don't belabor the point
979                // (that it's a variant) for E0573 "expected type, found variant".
980                let preamble = if res.is_none() {
981                    let others = match enum_candidates.len() {
982                        1 => String::new(),
983                        2 => " and 1 other".to_owned(),
984                        n => ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!(" and {0} others", n))
    })format!(" and {n} others"),
985                    };
986                    ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("there is an enum variant `{0}`{1}; ",
                enum_candidates[0].0, others))
    })format!("there is an enum variant `{}`{}; ", enum_candidates[0].0, others)
987                } else {
988                    String::new()
989                };
990                let msg = ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("{0}try using the variant\'s enum",
                preamble))
    })format!("{preamble}try using the variant's enum");
991
992                suggested_candidates.extend(
993                    enum_candidates
994                        .iter()
995                        .map(|(_variant_path, enum_ty_path)| enum_ty_path.clone()),
996                );
997                err.span_suggestions(
998                    span,
999                    msg,
1000                    enum_candidates.into_iter().map(|(_variant_path, enum_ty_path)| enum_ty_path),
1001                    Applicability::MachineApplicable,
1002                );
1003            }
1004        }
1005
1006        // Try finding a suitable replacement.
1007        let typo_sugg = self
1008            .lookup_typo_candidate(path, following_seg, source.namespace(), is_expected)
1009            .to_opt_suggestion()
1010            .filter(|sugg| !suggested_candidates.contains(sugg.candidate.as_str()));
1011        if let [segment] = path
1012            && !#[allow(non_exhaustive_omitted_patterns)] match source {
    PathSource::Delegation => true,
    _ => false,
}matches!(source, PathSource::Delegation)
1013            && self.self_type_is_available()
1014        {
1015            if let Some(candidate) =
1016                self.lookup_assoc_candidate(ident, ns, is_expected, source.is_call())
1017            {
1018                let self_is_available = self.self_value_is_available(segment.ident.span);
1019                // Account for `Foo { field }` when suggesting `self.field` so we result on
1020                // `Foo { field: self.field }`.
1021                let pre = match source {
1022                    PathSource::Expr(Some(Expr { kind: ExprKind::Struct(expr), .. }))
1023                        if expr
1024                            .fields
1025                            .iter()
1026                            .any(|f| f.ident == segment.ident && f.is_shorthand) =>
1027                    {
1028                        ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("{0}: ", path_str))
    })format!("{path_str}: ")
1029                    }
1030                    _ => String::new(),
1031                };
1032                match candidate {
1033                    AssocSuggestion::Field(field_span) => {
1034                        if self_is_available {
1035                            let source_map = self.r.tcx.sess.source_map();
1036                            let field_is_format_named_arg = #[allow(non_exhaustive_omitted_patterns)] match span.desugaring_kind() {
    Some(DesugaringKind::FormatLiteral { .. }) => true,
    _ => false,
}matches!(
1037                                span.desugaring_kind(),
1038                                Some(DesugaringKind::FormatLiteral { .. })
1039                            ) && source_map
1040                                .span_to_source(span, |s, start, _| {
1041                                    Ok(s.get(start.saturating_sub(1)..start) == Some("{"))
1042                                })
1043                                .unwrap_or(false);
1044                            if field_is_format_named_arg {
1045                                err.help(
1046                                    ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("you might have meant to use the available field in a format string: `\"{{}}\", self.{0}`",
                segment.ident.name))
    })format!("you might have meant to use the available field in a format string: `\"{{}}\", self.{}`", segment.ident.name),
1047                                );
1048                            } else {
1049                                err.span_suggestion_verbose(
1050                                    span.shrink_to_lo(),
1051                                    "you might have meant to use the available field",
1052                                    ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("{0}self.", pre))
    })format!("{pre}self."),
1053                                    Applicability::MaybeIncorrect,
1054                                );
1055                            }
1056                        } else {
1057                            err.span_label(field_span, "a field by that name exists in `Self`");
1058                        }
1059                    }
1060                    AssocSuggestion::MethodWithSelf { called } if self_is_available => {
1061                        let msg = if called {
1062                            "you might have meant to call the method"
1063                        } else {
1064                            "you might have meant to refer to the method"
1065                        };
1066                        err.span_suggestion_verbose(
1067                            span.shrink_to_lo(),
1068                            msg,
1069                            "self.",
1070                            Applicability::MachineApplicable,
1071                        );
1072                    }
1073                    AssocSuggestion::MethodWithSelf { .. }
1074                    | AssocSuggestion::AssocFn { .. }
1075                    | AssocSuggestion::AssocConst
1076                    | AssocSuggestion::AssocType => {
1077                        err.span_suggestion_verbose(
1078                            span.shrink_to_lo(),
1079                            ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("you might have meant to {0}",
                candidate.action()))
    })format!("you might have meant to {}", candidate.action()),
1080                            "Self::",
1081                            Applicability::MachineApplicable,
1082                        );
1083                    }
1084                }
1085                self.r.add_typo_suggestion(err, typo_sugg, ident_span);
1086                return (true, suggested_candidates, candidates);
1087            }
1088
1089            // If the first argument in call is `self` suggest calling a method.
1090            if let Some((call_span, args_span)) = self.call_has_self_arg(source) {
1091                let mut args_snippet = String::new();
1092                if let Some(args_span) = args_span
1093                    && let Ok(snippet) = self.r.tcx.sess.source_map().span_to_snippet(args_span)
1094                {
1095                    args_snippet = snippet;
1096                }
1097
1098                if let Some(Res::Def(DefKind::Struct, def_id)) = res {
1099                    if let Some(ctor) = self.r.struct_ctor(def_id)
1100                        && ctor.has_private_fields(self.parent_scope.module, self.r)
1101                    {
1102                        if #[allow(non_exhaustive_omitted_patterns)] match ctor.res {
    Res::Def(DefKind::Ctor(CtorOf::Struct, CtorKind::Fn), _) => true,
    _ => false,
}matches!(
1103                            ctor.res,
1104                            Res::Def(DefKind::Ctor(CtorOf::Struct, CtorKind::Fn), _)
1105                        ) {
1106                            self.update_err_for_private_tuple_struct_fields(err, &source, def_id);
1107                        }
1108                        err.note("constructor is not visible here due to private fields");
1109                    }
1110                } else {
1111                    err.span_suggestion(
1112                        call_span,
1113                        ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("try calling `{0}` as a method",
                ident))
    })format!("try calling `{ident}` as a method"),
1114                        ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("self.{0}({1})", path_str,
                args_snippet))
    })format!("self.{path_str}({args_snippet})"),
1115                        Applicability::MachineApplicable,
1116                    );
1117                }
1118
1119                return (true, suggested_candidates, candidates);
1120            }
1121        }
1122
1123        // Try context-dependent help if relaxed lookup didn't work.
1124        if let Some(res) = res {
1125            if self.smart_resolve_context_dependent_help(
1126                err,
1127                span,
1128                source,
1129                path,
1130                res,
1131                &path_str,
1132                &base_error.fallback_label,
1133            ) {
1134                // We do this to avoid losing a secondary span when we override the main error span.
1135                self.r.add_typo_suggestion(err, typo_sugg, ident_span);
1136                return (true, suggested_candidates, candidates);
1137            }
1138        }
1139
1140        // Try to find in last block rib
1141        if let Some(rib) = &self.last_block_rib {
1142            for (ident, &res) in &rib.bindings {
1143                if let Res::Local(_) = res
1144                    && path.len() == 1
1145                    && ident.span.eq_ctxt(path[0].ident.span)
1146                    && ident.name == path[0].ident.name
1147                {
1148                    err.span_help(
1149                        ident.span,
1150                        ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("the binding `{0}` is available in a different scope in the same function",
                path_str))
    })format!("the binding `{path_str}` is available in a different scope in the same function"),
1151                    );
1152                    return (true, suggested_candidates, candidates);
1153                }
1154            }
1155        }
1156
1157        if candidates.is_empty() {
1158            candidates = self.smart_resolve_partial_mod_path_errors(path, following_seg);
1159        }
1160
1161        (false, suggested_candidates, candidates)
1162    }
1163
1164    fn lookup_doc_alias_name(&mut self, path: &[Segment], ns: Namespace) -> Option<(DefId, Ident)> {
1165        let find_doc_alias_name = |r: &mut Resolver<'ra, '_>, m: Module<'ra>, item_name: Symbol| {
1166            for resolution in r.resolutions(m).values() {
1167                let Some(did) =
1168                    resolution.borrow(r).best_decl().and_then(|binding| binding.res().opt_def_id())
1169                else {
1170                    continue;
1171                };
1172                if did.is_local() {
1173                    // We don't record the doc alias name in the local crate
1174                    // because the people who write doc alias are usually not
1175                    // confused by them.
1176                    continue;
1177                }
1178                if let Some(d) = {
    {
        'done:
            {
            for i in ::rustc_attr_ir::HasAttrs::get_attrs(did, &r.tcx) {
                #[allow(unused_imports)]
                use ::rustc_attr_ir::AttributeKind::*;
                let i: &::rustc_attr_ir::Attribute = i;
                match i {
                    ::rustc_attr_ir::Attribute::Parsed(Doc(d)) => {
                        break 'done Some(d);
                    }
                    ::rustc_attr_ir::Attribute::Unparsed(..) =>
                        {}
                        #[deny(unreachable_patterns)]
                        _ => {}
                }
            }
            None
        }
    }
}hir::find_attr!(r.tcx, did, Doc(d) => d)
1179                    && d.aliases.contains_key(&item_name)
1180                {
1181                    return Some(did);
1182                }
1183            }
1184            None
1185        };
1186
1187        if path.len() == 1 {
1188            for rib in self.ribs[ns].iter().rev() {
1189                let item = path[0].ident;
1190                if let RibKind::Module(module) | RibKind::Block(Some(module)) = rib.kind
1191                    && let Some(did) = find_doc_alias_name(self.r, module.to_module(), item.name)
1192                {
1193                    return Some((did, item));
1194                }
1195            }
1196        } else {
1197            // Finds to the last resolved module item in the path
1198            // and searches doc aliases within that module.
1199            //
1200            // Example: For the path `a::b::last_resolved::not_exist::c::d`,
1201            // we will try to find any item has doc aliases named `not_exist`
1202            // in `last_resolved` module.
1203            //
1204            // - Use `skip(1)` because the final segment must remain unresolved.
1205            for (idx, seg) in path.iter().enumerate().rev().skip(1) {
1206                let Some(id) = seg.id else {
1207                    continue;
1208                };
1209                let Some(res) = self.r.partial_res_map.get(&id) else {
1210                    continue;
1211                };
1212                if let Res::Def(DefKind::Mod, module) = res.expect_full_res()
1213                    && let module = self.r.expect_module(module)
1214                    && let item = path[idx + 1].ident
1215                    && let Some(did) = find_doc_alias_name(self.r, module, item.name)
1216                {
1217                    return Some((did, item));
1218                }
1219                break;
1220            }
1221        }
1222        None
1223    }
1224
1225    fn suggest_trait_and_bounds(
1226        &self,
1227        err: &mut Diag<'_>,
1228        source: PathSource<'_, '_, '_>,
1229        res: Option<Res>,
1230        span: Span,
1231        base_error: &BaseError,
1232    ) -> bool {
1233        let is_macro =
1234            base_error.span.from_expansion() && base_error.span.desugaring_kind().is_none();
1235        let mut fallback = false;
1236
1237        if let (
1238            PathSource::Trait(AliasPossibility::Maybe),
1239            Some(Res::Def(DefKind::Struct | DefKind::Enum | DefKind::Union, _)),
1240            false,
1241        ) = (source, res, is_macro)
1242            && let Some(bounds @ [first_bound, .., last_bound]) =
1243                self.diag_metadata.current_trait_object
1244        {
1245            fallback = true;
1246            let spans: Vec<Span> = bounds
1247                .iter()
1248                .map(|bound| bound.span())
1249                .filter(|&sp| sp != base_error.span)
1250                .collect();
1251
1252            let start_span = first_bound.span();
1253            // `end_span` is the end of the poly trait ref (Foo + 'baz + Bar><)
1254            let end_span = last_bound.span();
1255            // `last_bound_span` is the last bound of the poly trait ref (Foo + >'baz< + Bar)
1256            let last_bound_span = spans.last().cloned().unwrap();
1257            let mut multi_span: MultiSpan = spans.clone().into();
1258            for sp in spans {
1259                let msg = if sp == last_bound_span {
1260                    ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("...because of {0} bound{1}",
                if bounds.len() - 1 == 1 { "this" } else { "these" },
                if bounds.len() - 1 == 1 { "" } else { "s" }))
    })format!(
1261                        "...because of {these} bound{s}",
1262                        these = pluralize!("this", bounds.len() - 1),
1263                        s = pluralize!(bounds.len() - 1),
1264                    )
1265                } else {
1266                    String::new()
1267                };
1268                multi_span.push_span_label(sp, msg);
1269            }
1270            multi_span.push_span_label(base_error.span, "expected this type to be a trait...");
1271            err.span_help(
1272                multi_span,
1273                "`+` is used to constrain a \"trait object\" type with lifetimes or \
1274                        auto-traits; structs and enums can't be bound in that way",
1275            );
1276            if bounds.iter().all(|bound| match bound {
1277                ast::GenericBound::Outlives(_) | ast::GenericBound::Use(..) => true,
1278                ast::GenericBound::Trait(tr) => tr.span == base_error.span,
1279            }) {
1280                let mut sugg = ::alloc::vec::Vec::new()vec![];
1281                if base_error.span != start_span {
1282                    sugg.push((start_span.until(base_error.span), String::new()));
1283                }
1284                if base_error.span != end_span {
1285                    sugg.push((base_error.span.shrink_to_hi().to(end_span), String::new()));
1286                }
1287
1288                err.multipart_suggestion(
1289                    "if you meant to use a type and not a trait here, remove the bounds",
1290                    sugg,
1291                    Applicability::MaybeIncorrect,
1292                );
1293            }
1294        }
1295
1296        fallback |= self.restrict_assoc_type_in_where_clause(span, err);
1297        fallback
1298    }
1299
1300    fn suggest_typo(
1301        &mut self,
1302        err: &mut Diag<'_>,
1303        source: PathSource<'_, 'ast, 'ra>,
1304        path: &[Segment],
1305        following_seg: Option<&Segment>,
1306        span: Span,
1307        base_error: &BaseError,
1308        suggested_candidates: FxHashSet<String>,
1309    ) -> bool {
1310        let is_expected = &|res| source.is_expected(res);
1311        let ident_span = path.last().map_or(span, |ident| ident.ident.span);
1312
1313        // Prefer suggestions based on associated types from in-scope bounds (e.g. `T::Item`)
1314        // over purely edit-distance-based identifier suggestions.
1315        // Otherwise suggestions could be verbose.
1316        if self.suggest_assoc_type_from_bounds(err, source, path, ident_span) {
1317            return false;
1318        }
1319
1320        let typo_sugg =
1321            self.lookup_typo_candidate(path, following_seg, source.namespace(), is_expected);
1322        let mut fallback = false;
1323        let typo_sugg = typo_sugg
1324            .to_opt_suggestion()
1325            .filter(|sugg| !suggested_candidates.contains(sugg.candidate.as_str()));
1326        if !self.r.add_typo_suggestion(err, typo_sugg, ident_span) {
1327            fallback = true;
1328            match self.diag_metadata.current_let_binding {
1329                Some((pat_sp, Some(ty_sp), None))
1330                    if ty_sp.contains(base_error.span) && base_error.could_be_expr =>
1331                {
1332                    err.span_suggestion_verbose(
1333                        pat_sp.between(ty_sp),
1334                        "use `=` if you meant to assign",
1335                        " = ",
1336                        Applicability::MaybeIncorrect,
1337                    );
1338                }
1339                _ => {}
1340            }
1341
1342            // If the trait has a single item (which wasn't matched by the algorithm), suggest it
1343            let suggestion = self.get_single_associated_item(path, &source, is_expected);
1344            self.r.add_typo_suggestion(err, suggestion, ident_span);
1345        }
1346
1347        if self.let_binding_suggestion(err, ident_span) {
1348            fallback = false;
1349        }
1350
1351        fallback
1352    }
1353
1354    fn suggest_shadowed(
1355        &mut self,
1356        err: &mut Diag<'_>,
1357        source: PathSource<'_, '_, '_>,
1358        path: &[Segment],
1359        following_seg: Option<&Segment>,
1360        span: Span,
1361    ) -> bool {
1362        let is_expected = &|res| source.is_expected(res);
1363        let typo_sugg =
1364            self.lookup_typo_candidate(path, following_seg, source.namespace(), is_expected);
1365        let is_in_same_file = &|sp1, sp2| {
1366            let source_map = self.r.tcx.sess.source_map();
1367            let file1 = source_map.span_to_filename(sp1);
1368            let file2 = source_map.span_to_filename(sp2);
1369            file1 == file2
1370        };
1371        // print 'you might have meant' if the candidate is (1) is a shadowed name with
1372        // accessible definition and (2) either defined in the same crate as the typo
1373        // (could be in a different file) or introduced in the same file as the typo
1374        // (could belong to a different crate)
1375        if let TypoCandidate::Shadowed(res, Some(sugg_span)) = typo_sugg
1376            && res.opt_def_id().is_some_and(|id| id.is_local() || is_in_same_file(span, sugg_span))
1377        {
1378            err.span_label(
1379                sugg_span,
1380                ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("you might have meant to refer to this {0}",
                res.descr()))
    })format!("you might have meant to refer to this {}", res.descr()),
1381            );
1382            return true;
1383        }
1384        false
1385    }
1386
1387    fn err_code_special_cases(
1388        &mut self,
1389        err: &mut Diag<'_>,
1390        source: PathSource<'_, '_, '_>,
1391        path: &[Segment],
1392        span: Span,
1393    ) {
1394        if let Some(err_code) = err.code {
1395            if err_code == E0425 {
1396                for label_rib in &self.label_ribs {
1397                    for (label_ident, node_id) in &label_rib.bindings {
1398                        let ident = path.last().unwrap().ident;
1399                        if ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("\'{0}", ident))
    })format!("'{ident}") == label_ident.to_string() {
1400                            err.span_label(label_ident.span, "a label with a similar name exists");
1401                            if let PathSource::Expr(Some(Expr {
1402                                kind: ExprKind::Break(None, Some(_)),
1403                                ..
1404                            })) = source
1405                            {
1406                                err.span_suggestion(
1407                                    span,
1408                                    "use the similarly named label",
1409                                    label_ident.name,
1410                                    Applicability::MaybeIncorrect,
1411                                );
1412                                // Do not lint against unused label when we suggest them.
1413                                self.diag_metadata.unused_labels.swap_remove(node_id);
1414                            }
1415                        }
1416                    }
1417                }
1418
1419                self.suggest_ident_hidden_by_hygiene(err, path, span);
1420                // cannot find type in this scope
1421                if let Some(correct) = Self::likely_rust_type(path) {
1422                    err.span_suggestion(
1423                        span,
1424                        "perhaps you intended to use this type",
1425                        correct,
1426                        Applicability::MaybeIncorrect,
1427                    );
1428                }
1429            }
1430        }
1431    }
1432
1433    fn suggest_ident_hidden_by_hygiene(&self, err: &mut Diag<'_>, path: &[Segment], span: Span) {
1434        let [segment] = path else { return };
1435
1436        let ident = segment.ident;
1437        let callsite_span = span.source_callsite();
1438        for rib in self.ribs[ValueNS].iter().rev() {
1439            for (binding_ident, _) in &rib.bindings {
1440                // Case 1: the identifier is defined in the same scope as the macro is called
1441                if binding_ident.name == ident.name
1442                    && !binding_ident.span.eq_ctxt(span)
1443                    && !binding_ident.span.from_expansion()
1444                    && binding_ident.span.lo() < callsite_span.lo()
1445                {
1446                    err.span_help(
1447                        binding_ident.span,
1448                        "an identifier with the same name exists, but is not accessible due to macro hygiene",
1449                    );
1450                    return;
1451                }
1452
1453                // Case 2: the identifier is defined in a macro call in the same scope
1454                if binding_ident.name == ident.name
1455                    && binding_ident.span.from_expansion()
1456                    && binding_ident.span.source_callsite().eq_ctxt(callsite_span)
1457                    && binding_ident.span.source_callsite().lo() < callsite_span.lo()
1458                {
1459                    err.span_help(
1460                        binding_ident.span,
1461                        "an identifier with the same name is defined here, but is not accessible due to macro hygiene",
1462                    );
1463                    return;
1464                }
1465            }
1466        }
1467    }
1468
1469    /// Emit special messages for unresolved `Self` and `self`.
1470    fn suggest_self_ty(
1471        &self,
1472        err: &mut Diag<'_>,
1473        source: PathSource<'_, '_, '_>,
1474        path: &[Segment],
1475        span: Span,
1476    ) -> bool {
1477        if !is_self_type(path, source.namespace()) {
1478            return false;
1479        }
1480        err.code(E0411);
1481        err.span_label(span, "`Self` is only available in impls, traits, and type definitions");
1482        if let Some(item) = self.diag_metadata.current_item
1483            && let Some(ident) = item.kind.ident()
1484        {
1485            err.span_label(
1486                ident.span,
1487                ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("`Self` not allowed in {0} {1}",
                item.kind.article(), item.kind.descr()))
    })format!("`Self` not allowed in {} {}", item.kind.article(), item.kind.descr()),
1488            );
1489        }
1490        true
1491    }
1492
1493    fn suggest_self_value(
1494        &mut self,
1495        err: &mut Diag<'_>,
1496        source: PathSource<'_, '_, '_>,
1497        path: &[Segment],
1498        span: Span,
1499    ) -> bool {
1500        if !is_self_value(path, source.namespace()) {
1501            return false;
1502        }
1503
1504        {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event compiler/rustc_resolve/src/late/diagnostics.rs:1504",
                        "rustc_resolve::late::diagnostics", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_resolve/src/late/diagnostics.rs"),
                        ::tracing_core::__macro_support::Option::Some(1504u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_resolve::late::diagnostics"),
                        ::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!("smart_resolve_path_fragment: E0424, source={0:?}",
                                                    source) as &dyn ::tracing::field::Value))])
            });
    } else { ; }
};debug!("smart_resolve_path_fragment: E0424, source={:?}", source);
1505        err.code(E0424);
1506        err.span_label(
1507            span,
1508            match source {
1509                PathSource::Pat => {
1510                    "`self` value is a keyword and may not be bound to variables or shadowed"
1511                }
1512                _ => "`self` value is a keyword only available in methods with a `self` parameter",
1513            },
1514        );
1515
1516        // using `let self` is wrong even if we're not in an associated method or if we're in a macro expansion.
1517        // So, we should return early if we're in a pattern, see issue #143134.
1518        if #[allow(non_exhaustive_omitted_patterns)] match source {
    PathSource::Pat => true,
    _ => false,
}matches!(source, PathSource::Pat) {
1519            return true;
1520        }
1521
1522        let is_assoc_fn = self.self_type_is_available();
1523        let self_from_macro = "a `self` parameter, but a macro invocation can only \
1524                               access identifiers it receives from parameters";
1525        if let Some((fn_kind, fn_span)) = &self.diag_metadata.current_function {
1526            // The current function has a `self` parameter, but we were unable to resolve
1527            // a reference to `self`. This can only happen if the `self` identifier we
1528            // are resolving came from a different hygiene context or a variable binding.
1529            // But variable binding error is returned early above.
1530            if fn_kind.decl().inputs.get(0).is_some_and(|p| p.is_self()) {
1531                err.span_label(*fn_span, ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("this function has {0}",
                self_from_macro))
    })format!("this function has {self_from_macro}"));
1532            } else {
1533                let doesnt = if is_assoc_fn {
1534                    let (span, sugg) = fn_kind
1535                        .decl()
1536                        .inputs
1537                        .get(0)
1538                        .map(|p| (p.span.shrink_to_lo(), "&self, "))
1539                        .unwrap_or_else(|| {
1540                            // Try to look for the "(" after the function name, if possible.
1541                            // This avoids placing the suggestion into the visibility specifier.
1542                            let span = fn_kind
1543                                .ident()
1544                                .map_or(*fn_span, |ident| fn_span.with_lo(ident.span.hi()));
1545                            (
1546                                self.r
1547                                    .tcx
1548                                    .sess
1549                                    .source_map()
1550                                    .span_through_char(span, '(')
1551                                    .shrink_to_hi(),
1552                                "&self",
1553                            )
1554                        });
1555                    err.span_suggestion_verbose(
1556                        span,
1557                        "add a `self` receiver parameter to make the associated `fn` a method",
1558                        sugg,
1559                        Applicability::MaybeIncorrect,
1560                    );
1561                    "doesn't"
1562                } else {
1563                    "can't"
1564                };
1565                if let Some(ident) = fn_kind.ident() {
1566                    err.span_label(
1567                        ident.span,
1568                        ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("this function {0} have a `self` parameter",
                doesnt))
    })format!("this function {doesnt} have a `self` parameter"),
1569                    );
1570                }
1571            }
1572        } else if let Some(item) = self.diag_metadata.current_item {
1573            if #[allow(non_exhaustive_omitted_patterns)] match item.kind {
    ItemKind::Delegation(..) => true,
    _ => false,
}matches!(item.kind, ItemKind::Delegation(..)) {
1574                err.span_label(item.span, ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("delegation supports {0}",
                self_from_macro))
    })format!("delegation supports {self_from_macro}"));
1575            } else {
1576                let span = if let Some(ident) = item.kind.ident() { ident.span } else { item.span };
1577                err.span_label(
1578                    span,
1579                    ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("`self` not allowed in {0} {1}",
                item.kind.article(), item.kind.descr()))
    })format!("`self` not allowed in {} {}", item.kind.article(), item.kind.descr()),
1580                );
1581            }
1582        }
1583        true
1584    }
1585
1586    fn detect_missing_binding_available_from_pattern(
1587        &self,
1588        err: &mut Diag<'_>,
1589        path: &[Segment],
1590        following_seg: Option<&Segment>,
1591    ) {
1592        let [segment] = path else { return };
1593        let None = following_seg else { return };
1594        for rib in self.ribs[ValueNS].iter().rev() {
1595            let patterns_with_skipped_bindings =
1596                self.r.tcx.with_stable_hashing_context(|mut hcx| {
1597                    rib.patterns_with_skipped_bindings.to_sorted(&mut hcx, true)
1598                });
1599            for (def_id, spans) in patterns_with_skipped_bindings {
1600                if let DefKind::Struct | DefKind::Variant = self.r.tcx.def_kind(*def_id)
1601                    && let Some(fields) = self.r.field_idents(*def_id)
1602                {
1603                    for field in fields {
1604                        if field.name == segment.ident.name {
1605                            if spans.iter().all(|(_, had_error)| had_error.is_err()) {
1606                                // This resolution error will likely be fixed by fixing a
1607                                // syntax error in a pattern, so it is irrelevant to the user.
1608                                let multispan: MultiSpan =
1609                                    spans.iter().map(|(s, _)| *s).collect::<Vec<_>>().into();
1610                                err.span_note(
1611                                    multispan,
1612                                    "this pattern had a recovered parse error which likely lost \
1613                                     the expected fields",
1614                                );
1615                                err.downgrade_to_delayed_bug();
1616                            }
1617                            let ty = self.r.tcx.item_name(*def_id);
1618                            for (span, _) in spans {
1619                                err.span_label(
1620                                    *span,
1621                                    ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("this pattern doesn\'t include `{0}`, which is available in `{1}`",
                field, ty))
    })format!(
1622                                        "this pattern doesn't include `{field}`, which is \
1623                                         available in `{ty}`",
1624                                    ),
1625                                );
1626                            }
1627                        }
1628                    }
1629                }
1630            }
1631        }
1632    }
1633
1634    fn suggest_at_operator_in_slice_pat_with_range(&self, err: &mut Diag<'_>, path: &[Segment]) {
1635        let Some(pat) = self.diag_metadata.current_pat else { return };
1636        let (bound, side, range) = match &pat.kind {
1637            ast::PatKind::Range(Some(bound), None, range) => (bound, Side::Start, range),
1638            ast::PatKind::Range(None, Some(bound), range) => (bound, Side::End, range),
1639            _ => return,
1640        };
1641        if let ExprKind::Path(None, range_path) = &bound.kind
1642            && let [segment] = &range_path.segments[..]
1643            && let [s] = path
1644            && segment.ident == s.ident
1645            && segment.ident.span.eq_ctxt(range.span)
1646        {
1647            // We've encountered `[first, rest..]` (#88404) or `[first, ..rest]` (#120591)
1648            // where the user might have meant `[first, rest @ ..]`.
1649            let (span, snippet) = match side {
1650                Side::Start => (segment.ident.span.between(range.span), " @ ".into()),
1651                Side::End => (range.span.to(segment.ident.span), ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("{0} @ ..", segment.ident))
    })format!("{} @ ..", segment.ident)),
1652            };
1653            err.subdiagnostic(diagnostics::UnexpectedResUseAtOpInSlicePatWithRangeSugg {
1654                span,
1655                ident: segment.ident,
1656                snippet,
1657            });
1658        }
1659
1660        enum Side {
1661            Start,
1662            End,
1663        }
1664    }
1665
1666    fn suggest_range_struct_destructuring(
1667        &mut self,
1668        err: &mut Diag<'_>,
1669        path: &[Segment],
1670        source: PathSource<'_, '_, '_>,
1671    ) {
1672        if !#[allow(non_exhaustive_omitted_patterns)] match source {
    PathSource::Pat | PathSource::TupleStruct(..) | PathSource::Expr(..) =>
        true,
    _ => false,
}matches!(source, PathSource::Pat | PathSource::TupleStruct(..) | PathSource::Expr(..)) {
1673            return;
1674        }
1675
1676        let Some(pat) = self.diag_metadata.current_pat else { return };
1677        let ast::PatKind::Range(start, end, end_kind) = &pat.kind else { return };
1678
1679        let [segment] = path else { return };
1680        let failing_span = segment.ident.span;
1681
1682        let in_start = start.as_ref().is_some_and(|e| e.span.contains(failing_span));
1683        let in_end = end.as_ref().is_some_and(|e| e.span.contains(failing_span));
1684
1685        if !in_start && !in_end {
1686            return;
1687        }
1688
1689        let start_snippet =
1690            start.as_ref().and_then(|e| self.r.tcx.sess.source_map().span_to_snippet(e.span).ok());
1691        let end_snippet =
1692            end.as_ref().and_then(|e| self.r.tcx.sess.source_map().span_to_snippet(e.span).ok());
1693
1694        let field = |name: &str, val: String| {
1695            if val == name { val } else { ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("{0}: {1}", name, val))
    })format!("{name}: {val}") }
1696        };
1697
1698        let mut resolve_short_name = |short: Symbol, full: &str| -> String {
1699            let ident = Ident::with_dummy_span(short);
1700            let path = Segment::from_path(&Path::from_ident(ident));
1701
1702            match self.resolve_path(&path, Some(TypeNS), None, PathSource::Type) {
1703                PathResult::NonModule(..) => short.to_string(),
1704                _ => full.to_string(),
1705            }
1706        };
1707        // FIXME(new_range): Also account for new range types
1708        let (struct_path, fields) = match (start_snippet, end_snippet, &end_kind.node) {
1709            (Some(start), Some(end), ast::RangeEnd::Excluded) => (
1710                resolve_short_name(sym::Range, "std::ops::Range"),
1711                ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
        [field("start", start), field("end", end)]))vec![field("start", start), field("end", end)],
1712            ),
1713            (Some(start), Some(end), ast::RangeEnd::Included(_)) => (
1714                resolve_short_name(sym::RangeInclusive, "std::ops::RangeInclusive"),
1715                ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
        [field("start", start), field("end", end)]))vec![field("start", start), field("end", end)],
1716            ),
1717            (Some(start), None, _) => (
1718                resolve_short_name(sym::RangeFrom, "std::ops::RangeFrom"),
1719                ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
        [field("start", start)]))vec![field("start", start)],
1720            ),
1721            (None, Some(end), ast::RangeEnd::Excluded) => {
1722                (resolve_short_name(sym::RangeTo, "std::ops::RangeTo"), ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
        [field("end", end)]))vec![field("end", end)])
1723            }
1724            (None, Some(end), ast::RangeEnd::Included(_)) => (
1725                resolve_short_name(sym::RangeToInclusive, "std::ops::RangeToInclusive"),
1726                ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
        [field("end", end)]))vec![field("end", end)],
1727            ),
1728            _ => return,
1729        };
1730
1731        err.span_suggestion_verbose(
1732            pat.span,
1733            ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("if you meant to destructure a range use a struct pattern"))
    })format!("if you meant to destructure a range use a struct pattern"),
1734            ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("{0} {{ {1} }}", struct_path,
                fields.join(", ")))
    })format!("{} {{ {} }}", struct_path, fields.join(", ")),
1735            Applicability::MaybeIncorrect,
1736        );
1737
1738        err.note(
1739            "range patterns match against the start and end of a range; \
1740             to bind the components, use a struct pattern",
1741        );
1742    }
1743
1744    fn suggest_swapping_misplaced_self_ty_and_trait(
1745        &mut self,
1746        err: &mut Diag<'_>,
1747        source: PathSource<'_, 'ast, 'ra>,
1748        res: Option<Res>,
1749        span: Span,
1750    ) {
1751        if let Some((trait_ref, self_ty)) =
1752            self.diag_metadata.currently_processing_impl_trait.clone()
1753            && let TyKind::Path(_, self_ty_path) = &self_ty.kind
1754            && let PathResult::Module(ModuleOrUniformRoot::Module(module)) =
1755                self.resolve_path(&Segment::from_path(self_ty_path), Some(TypeNS), None, source)
1756            && module.def_kind() == Some(DefKind::Trait)
1757            && trait_ref.path.span == span
1758            && let PathSource::Trait(_) = source
1759            && let Some(Res::Def(DefKind::Struct | DefKind::Enum | DefKind::Union, _)) = res
1760            && let Ok(self_ty_str) = self.r.tcx.sess.source_map().span_to_snippet(self_ty.span)
1761            && let Ok(trait_ref_str) =
1762                self.r.tcx.sess.source_map().span_to_snippet(trait_ref.path.span)
1763        {
1764            err.multipart_suggestion(
1765                    "`impl` items mention the trait being implemented first and the type it is being implemented for second",
1766                    ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
        [(trait_ref.path.span, self_ty_str), (self_ty.span, trait_ref_str)]))vec![(trait_ref.path.span, self_ty_str), (self_ty.span, trait_ref_str)],
1767                    Applicability::MaybeIncorrect,
1768                );
1769        }
1770    }
1771
1772    fn explain_functions_in_pattern(
1773        &self,
1774        err: &mut Diag<'_>,
1775        res: Option<Res>,
1776        source: PathSource<'_, '_, '_>,
1777    ) {
1778        let PathSource::TupleStruct(_, _) = source else { return };
1779        let Some(Res::Def(DefKind::Fn, _)) = res else { return };
1780        err.primary_message("expected a pattern, found a function call");
1781        err.note("function calls are not allowed in patterns: <https://doc.rust-lang.org/book/ch19-00-patterns.html>");
1782    }
1783
1784    fn suggest_changing_type_to_const_param(
1785        &self,
1786        err: &mut Diag<'_>,
1787        res: Option<Res>,
1788        source: PathSource<'_, '_, '_>,
1789        path: &[Segment],
1790        following_seg: Option<&Segment>,
1791        span: Span,
1792    ) {
1793        if let PathSource::Expr(None) = source
1794            && let Some(Res::Def(DefKind::TyParam, _)) = res
1795            && following_seg.is_none()
1796            && let [segment] = path
1797        {
1798            // We have something like
1799            // impl<T, N> From<[T; N]> for VecWrapper<T> {
1800            //     fn from(slice: [T; N]) -> Self {
1801            //         VecWrapper(slice.to_vec())
1802            //     }
1803            // }
1804            // where `N` is a type param but should likely have been a const param.
1805            let Some(item) = self.diag_metadata.current_item else { return };
1806            let Some(generics) = item.kind.generics() else { return };
1807            let Some(span) = generics.params.iter().find_map(|param| {
1808                // Only consider type params with no bounds.
1809                if param.bounds.is_empty() && param.ident.name == segment.ident.name {
1810                    Some(param.ident.span)
1811                } else {
1812                    None
1813                }
1814            }) else {
1815                return;
1816            };
1817            err.subdiagnostic(diagnostics::UnexpectedResChangeTyParamToConstParamSugg {
1818                before: span.shrink_to_lo(),
1819                after: span.shrink_to_hi(),
1820            });
1821            return;
1822        }
1823        let PathSource::Trait(_) = source else { return };
1824
1825        // We don't include `DefKind::Str` and `DefKind::AssocTy` as they can't be reached here anyway.
1826        let applicability = match res {
1827            Some(Res::PrimTy(PrimTy::Int(_) | PrimTy::Uint(_) | PrimTy::Bool | PrimTy::Char)) => {
1828                Applicability::MachineApplicable
1829            }
1830            // FIXME(const_generics): Add `DefKind::TyParam` and `SelfTyParam` once we support generic
1831            // const generics. Of course, `Struct` and `Enum` may contain ty params, too, but the
1832            // benefits of including them here outweighs the small number of false positives.
1833            Some(Res::Def(DefKind::Struct | DefKind::Enum, _))
1834                if self.r.features.adt_const_params() || self.r.features.min_adt_const_params() =>
1835            {
1836                Applicability::MaybeIncorrect
1837            }
1838            _ => return,
1839        };
1840
1841        let Some(item) = self.diag_metadata.current_item else { return };
1842        let Some(generics) = item.kind.generics() else { return };
1843
1844        let param = generics.params.iter().find_map(|param| {
1845            // Only consider type params with exactly one trait bound.
1846            if let [bound] = &*param.bounds
1847                && let ast::GenericBound::Trait(tref) = bound
1848                && tref.modifiers == ast::TraitBoundModifiers::NONE
1849                && tref.span == span
1850                && param.ident.span.eq_ctxt(span)
1851            {
1852                Some(param.ident.span)
1853            } else {
1854                None
1855            }
1856        });
1857
1858        if let Some(param) = param {
1859            err.subdiagnostic(diagnostics::UnexpectedResChangeTyToConstParamSugg {
1860                span: param.shrink_to_lo(),
1861                applicability,
1862            });
1863        }
1864    }
1865
1866    fn suggest_pattern_match_with_let(
1867        &self,
1868        err: &mut Diag<'_>,
1869        source: PathSource<'_, '_, '_>,
1870        span: Span,
1871    ) -> bool {
1872        if let PathSource::Expr(_) = source
1873            && let Some(Expr { span: expr_span, kind: ExprKind::Assign(lhs, _, _), .. }) =
1874                self.diag_metadata.in_if_condition
1875        {
1876            // Icky heuristic so we don't suggest:
1877            // `if (i + 2) = 2` => `if let (i + 2) = 2` (approximately pattern)
1878            // `if 2 = i` => `if let 2 = i` (lhs needs to contain error span)
1879            if lhs.is_approximately_pattern() && lhs.span.contains(span) {
1880                err.span_suggestion_verbose(
1881                    expr_span.shrink_to_lo(),
1882                    "you might have meant to use pattern matching",
1883                    "let ",
1884                    Applicability::MaybeIncorrect,
1885                );
1886                return true;
1887            }
1888        }
1889        false
1890    }
1891
1892    fn get_single_associated_item(
1893        &mut self,
1894        path: &[Segment],
1895        source: &PathSource<'_, 'ast, 'ra>,
1896        filter_fn: &impl Fn(Res) -> bool,
1897    ) -> Option<TypoSuggestion> {
1898        if let crate::PathSource::TraitItem(_, _) = source {
1899            let mod_path = &path[..path.len() - 1];
1900            if let PathResult::Module(ModuleOrUniformRoot::Module(module)) =
1901                self.resolve_path(mod_path, None, None, *source)
1902            {
1903                let targets: Vec<_> = self
1904                    .r
1905                    .resolutions(module)
1906                    .iter()
1907                    .filter_map(|(key, resolution)| {
1908                        let resolution = resolution.borrow(self.r);
1909                        resolution.best_decl().map(|binding| binding.res()).and_then(|res| {
1910                            if filter_fn(res) {
1911                                Some((key.ident.name, resolution.orig_ident_span, res))
1912                            } else {
1913                                None
1914                            }
1915                        })
1916                    })
1917                    .collect();
1918                if let &[(name, orig_ident_span, res)] = targets.as_slice() {
1919                    return Some(TypoSuggestion::single_item(name, orig_ident_span, res));
1920                }
1921            }
1922        }
1923        None
1924    }
1925
1926    /// Given `where <T as Bar>::Baz: String`, suggest `where T: Bar<Baz = String>`.
1927    fn restrict_assoc_type_in_where_clause(&self, span: Span, err: &mut Diag<'_>) -> bool {
1928        // Detect that we are actually in a `where` predicate.
1929        let Some(ast::WherePredicate {
1930            kind:
1931                ast::WherePredicateKind::BoundPredicate(ast::WhereBoundPredicate {
1932                    bounded_ty,
1933                    bound_generic_params,
1934                    bounds,
1935                }),
1936            span: where_span,
1937            ..
1938        }) = self.diag_metadata.current_where_predicate
1939        else {
1940            return false;
1941        };
1942        if !bound_generic_params.is_empty() {
1943            return false;
1944        }
1945
1946        // Confirm that the target is an associated type.
1947        let ast::TyKind::Path(Some(qself), path) = &bounded_ty.kind else { return false };
1948        // use this to verify that ident is a type param.
1949        let Some(partial_res) = self.r.partial_res_map.get(&bounded_ty.id) else { return false };
1950        if !#[allow(non_exhaustive_omitted_patterns)] match partial_res.full_res() {
    Some(Res::Def(DefKind::AssocTy, _)) => true,
    _ => false,
}matches!(partial_res.full_res(), Some(Res::Def(DefKind::AssocTy, _))) {
1951            return false;
1952        }
1953
1954        let peeled_ty = qself.ty.peel_refs();
1955        let ast::TyKind::Path(None, type_param_path) = &peeled_ty.kind else { return false };
1956        // Confirm that the `SelfTy` is a type parameter.
1957        let Some(partial_res) = self.r.partial_res_map.get(&peeled_ty.id) else {
1958            return false;
1959        };
1960        if !#[allow(non_exhaustive_omitted_patterns)] match partial_res.full_res() {
    Some(Res::Def(DefKind::TyParam, _)) => true,
    _ => false,
}matches!(partial_res.full_res(), Some(Res::Def(DefKind::TyParam, _))) {
1961            return false;
1962        }
1963        let ([ast::PathSegment { args: None, .. }], [ast::GenericBound::Trait(poly_trait_ref)]) =
1964            (&type_param_path.segments[..], &bounds[..])
1965        else {
1966            return false;
1967        };
1968        let [ast::PathSegment { ident, args: None, id }] =
1969            &poly_trait_ref.trait_ref.path.segments[..]
1970        else {
1971            return false;
1972        };
1973        if poly_trait_ref.modifiers != ast::TraitBoundModifiers::NONE {
1974            return false;
1975        }
1976        if ident.span == span {
1977            let Some(partial_res) = self.r.partial_res_map.get(&id) else {
1978                return false;
1979            };
1980            if !#[allow(non_exhaustive_omitted_patterns)] match partial_res.full_res() {
    Some(Res::Def(..)) => true,
    _ => false,
}matches!(partial_res.full_res(), Some(Res::Def(..))) {
1981                return false;
1982            }
1983
1984            let Some(new_where_bound_predicate) =
1985                mk_where_bound_predicate(path, poly_trait_ref, &qself.ty)
1986            else {
1987                return false;
1988            };
1989            err.span_suggestion_verbose(
1990                *where_span,
1991                ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("constrain the associated type to `{0}`",
                ident))
    })format!("constrain the associated type to `{ident}`"),
1992                where_bound_predicate_to_string(&new_where_bound_predicate),
1993                Applicability::MaybeIncorrect,
1994            );
1995        }
1996        true
1997    }
1998
1999    /// Check if the source is call expression and the first argument is `self`. If true,
2000    /// return the span of whole call and the span for all arguments expect the first one (`self`).
2001    fn call_has_self_arg(&self, source: PathSource<'_, '_, '_>) -> Option<(Span, Option<Span>)> {
2002        let mut has_self_arg = None;
2003        if let PathSource::Expr(Some(parent)) = source
2004            && let ExprKind::Call(_, args) = &parent.kind
2005            && !args.is_empty()
2006        {
2007            let mut expr_kind = &args[0].kind;
2008            loop {
2009                match expr_kind {
2010                    ExprKind::Path(_, arg_name) if arg_name.segments.len() == 1 => {
2011                        if arg_name.segments[0].ident.name == kw::SelfLower {
2012                            let call_span = parent.span;
2013                            let tail_args_span = if args.len() > 1 {
2014                                Some(Span::new(
2015                                    args[1].span.lo(),
2016                                    args.last().unwrap().span.hi(),
2017                                    call_span.ctxt(),
2018                                    None,
2019                                ))
2020                            } else {
2021                                None
2022                            };
2023                            has_self_arg = Some((call_span, tail_args_span));
2024                        }
2025                        break;
2026                    }
2027                    ExprKind::AddrOf(_, _, expr) => expr_kind = &expr.kind,
2028                    _ => break,
2029                }
2030            }
2031        }
2032        has_self_arg
2033    }
2034
2035    fn followed_by_brace(&self, span: Span) -> (bool, Option<Span>) {
2036        // HACK(estebank): find a better way to figure out that this was a
2037        // parser issue where a struct literal is being used on an expression
2038        // where a brace being opened means a block is being started. Look
2039        // ahead for the next text to see if `span` is followed by a `{`.
2040        let sm = self.r.tcx.sess.source_map();
2041        if let Some(open_brace_span) = sm.span_followed_by(span, "{") {
2042            // In case this could be a struct literal that needs to be surrounded
2043            // by parentheses, find the appropriate span.
2044            let close_brace_span =
2045                sm.span_to_next_source(open_brace_span).ok().and_then(|next_source| {
2046                    // Find the matching `}` accounting for nested braces.
2047                    let mut depth: u32 = 1;
2048                    let offset = next_source.char_indices().find_map(|(i, c)| {
2049                        match c {
2050                            '{' => depth += 1,
2051                            '}' if depth == 1 => return Some(i),
2052                            '}' => depth -= 1,
2053                            _ => {}
2054                        }
2055                        None
2056                    })?;
2057                    let start = open_brace_span.hi() + rustc_span::BytePos(offset as u32);
2058                    Some(open_brace_span.with_lo(start).with_hi(start + rustc_span::BytePos(1)))
2059                });
2060            let closing_brace = close_brace_span.map(|sp| span.to(sp));
2061            (true, closing_brace)
2062        } else {
2063            (false, None)
2064        }
2065    }
2066
2067    fn update_err_for_private_tuple_struct_fields(
2068        &self,
2069        err: &mut Diag<'_>,
2070        source: &PathSource<'_, '_, '_>,
2071        def_id: DefId,
2072    ) -> Option<Vec<Span>> {
2073        match source {
2074            // e.g. `if let Enum::TupleVariant(field1, field2) = _`
2075            PathSource::TupleStruct(_, pattern_spans) => {
2076                err.primary_message(
2077                    "cannot match against a tuple struct which contains private fields",
2078                );
2079
2080                // Use spans of the tuple struct pattern.
2081                Some(Vec::from(*pattern_spans))
2082            }
2083            // e.g. `let _ = Enum::TupleVariant(field1, field2);`
2084            PathSource::Expr(Some(Expr {
2085                kind: ExprKind::Call(path, args),
2086                span: call_span,
2087                ..
2088            })) => {
2089                err.primary_message(
2090                    "cannot initialize a tuple struct which contains private fields",
2091                );
2092                self.suggest_alternative_construction_methods(
2093                    def_id,
2094                    err,
2095                    path.span,
2096                    *call_span,
2097                    &args[..],
2098                );
2099
2100                self.r
2101                    .field_idents(def_id)
2102                    .map(|fields| fields.iter().map(|f| f.span).collect::<Vec<_>>())
2103            }
2104            _ => None,
2105        }
2106    }
2107
2108    /// Provides context-dependent help for errors reported by the `smart_resolve_path_fragment`
2109    /// function.
2110    /// Returns `true` if able to provide context-dependent help.
2111    fn smart_resolve_context_dependent_help(
2112        &mut self,
2113        err: &mut Diag<'_>,
2114        span: Span,
2115        source: PathSource<'_, '_, '_>,
2116        path: &[Segment],
2117        res: Res,
2118        path_str: &str,
2119        fallback_label: &str,
2120    ) -> bool {
2121        let ns = source.namespace();
2122        let is_expected = &|res| source.is_expected(res);
2123
2124        let path_sep = |this: &Self, err: &mut Diag<'_>, expr: &Expr, kind: DefKind| {
2125            const MESSAGE: &str = "use the path separator to refer to an item";
2126
2127            let (lhs_span, rhs_span) = match &expr.kind {
2128                ExprKind::Field(base, ident) => (base.span, ident.span),
2129                ExprKind::MethodCall(MethodCall { receiver, span, .. }) => (receiver.span, *span),
2130                _ => return false,
2131            };
2132
2133            if lhs_span.eq_ctxt(rhs_span) {
2134                err.span_suggestion_verbose(
2135                    lhs_span.between(rhs_span),
2136                    MESSAGE,
2137                    "::",
2138                    Applicability::MaybeIncorrect,
2139                );
2140                true
2141            } else if #[allow(non_exhaustive_omitted_patterns)] match kind {
    DefKind::Struct | DefKind::TyAlias => true,
    _ => false,
}matches!(kind, DefKind::Struct | DefKind::TyAlias)
2142                && let Some(lhs_source_span) = lhs_span.find_ancestor_inside(expr.span)
2143                && let Ok(snippet) = this.r.tcx.sess.source_map().span_to_snippet(lhs_source_span)
2144            {
2145                // The LHS is a type that originates from a macro call.
2146                // We have to add angle brackets around it.
2147
2148                err.span_suggestion_verbose(
2149                    lhs_source_span.until(rhs_span),
2150                    MESSAGE,
2151                    ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("<{0}>::", snippet))
    })format!("<{snippet}>::"),
2152                    Applicability::MaybeIncorrect,
2153                );
2154                true
2155            } else {
2156                // Either we were unable to obtain the source span / the snippet or
2157                // the LHS originates from a macro call and it is not a type and thus
2158                // there is no way to replace `.` with `::` and still somehow suggest
2159                // valid Rust code.
2160
2161                false
2162            }
2163        };
2164
2165        let find_span = |source: &PathSource<'_, '_, '_>, err: &mut Diag<'_>| {
2166            match source {
2167                PathSource::Expr(Some(Expr { span, kind: ExprKind::Call(_, _), .. }))
2168                | PathSource::TupleStruct(span, _) => {
2169                    // We want the main underline to cover the suggested code as well for
2170                    // cleaner output.
2171                    err.span(*span);
2172                    *span
2173                }
2174                _ => span,
2175            }
2176        };
2177
2178        let bad_struct_syntax_suggestion = |this: &Self, err: &mut Diag<'_>, def_id: DefId| {
2179            let (followed_by_brace, closing_brace) = this.followed_by_brace(span);
2180
2181            match source {
2182                PathSource::Expr(Some(
2183                    parent @ Expr { kind: ExprKind::Field(..) | ExprKind::MethodCall(..), .. },
2184                )) if path_sep(this, err, parent, DefKind::Struct) => {}
2185                PathSource::Expr(
2186                    None
2187                    | Some(Expr {
2188                        kind:
2189                            ExprKind::Path(..)
2190                            | ExprKind::Binary(..)
2191                            | ExprKind::Unary(..)
2192                            | ExprKind::If(..)
2193                            | ExprKind::While(..)
2194                            | ExprKind::ForLoop { .. }
2195                            | ExprKind::Match(..),
2196                        ..
2197                    }),
2198                ) if followed_by_brace => {
2199                    if let Some(sp) = closing_brace {
2200                        err.span_label(span, fallback_label.to_string());
2201                        err.multipart_suggestion(
2202                            "surround the struct literal with parentheses",
2203                            ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
        [(sp.shrink_to_lo(), "(".to_string()),
                (sp.shrink_to_hi(), ")".to_string())]))vec![
2204                                (sp.shrink_to_lo(), "(".to_string()),
2205                                (sp.shrink_to_hi(), ")".to_string()),
2206                            ],
2207                            Applicability::MaybeIncorrect,
2208                        );
2209                    } else {
2210                        err.span_label(
2211                            span, // Note the parentheses surrounding the suggestion below
2212                            ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("you might want to surround a struct literal with parentheses: `({0} {{ /* fields */ }})`?",
                path_str))
    })format!(
2213                                "you might want to surround a struct literal with parentheses: \
2214                                 `({path_str} {{ /* fields */ }})`?"
2215                            ),
2216                        );
2217                    }
2218                }
2219                PathSource::Expr(_) | PathSource::TupleStruct(..) | PathSource::Pat => {
2220                    let span = find_span(&source, err);
2221                    err.span_label(this.r.def_span(def_id), ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("`{0}` defined here", path_str))
    })format!("`{path_str}` defined here"));
2222
2223                    let (tail, descr, applicability, old_fields) = match source {
2224                        PathSource::Pat => ("", "pattern", Applicability::MachineApplicable, None),
2225                        PathSource::TupleStruct(_, args) => (
2226                            "",
2227                            "pattern",
2228                            Applicability::MachineApplicable,
2229                            Some(
2230                                args.iter()
2231                                    .map(|a| this.r.tcx.sess.source_map().span_to_snippet(*a).ok())
2232                                    .collect::<Vec<Option<String>>>(),
2233                            ),
2234                        ),
2235                        _ => (": val", "literal", Applicability::HasPlaceholders, None),
2236                    };
2237
2238                    // Imprecise for local structs without ctors, we don't keep fields for them.
2239                    let has_private_fields = match def_id.as_local() {
2240                        Some(def_id) => this.r.struct_ctors.get(&def_id).is_some_and(|ctor| {
2241                            ctor.has_private_fields(this.parent_scope.module, this.r)
2242                        }),
2243                        None => this.r.tcx.associated_item_def_ids(def_id).iter().any(|field_id| {
2244                            let vis = this.r.tcx.visibility(*field_id);
2245                            !this.r.is_accessible_from(vis, this.parent_scope.module)
2246                        }),
2247                    };
2248                    if !has_private_fields {
2249                        // If the fields of the type are private, we shouldn't be suggesting using
2250                        // the struct literal syntax at all, as that will cause a subsequent error.
2251                        let fields = this.r.field_idents(def_id);
2252                        let has_fields = fields.as_ref().is_some_and(|f| !f.is_empty());
2253
2254                        if let PathSource::Expr(Some(Expr {
2255                            kind: ExprKind::Call(path, args),
2256                            span,
2257                            ..
2258                        })) = source
2259                            && !args.is_empty()
2260                            && let Some(fields) = &fields
2261                            && args.len() == fields.len()
2262                        // Make sure we have same number of args as fields
2263                        {
2264                            let path_span = path.span;
2265                            let mut parts = Vec::new();
2266
2267                            // Start with the opening brace
2268                            parts.push((
2269                                path_span.shrink_to_hi().until(args[0].span),
2270                                "{".to_owned(),
2271                            ));
2272
2273                            for (field, arg) in fields.iter().zip(args.iter()) {
2274                                // Add the field name before the argument
2275                                parts.push((arg.span.shrink_to_lo(), ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("{0}: ", field))
    })format!("{}: ", field)));
2276                            }
2277
2278                            // Add the closing brace
2279                            parts.push((
2280                                args.last().unwrap().span.shrink_to_hi().until(span.shrink_to_hi()),
2281                                "}".to_owned(),
2282                            ));
2283
2284                            err.multipart_suggestion(
2285                                ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("use struct {0} syntax instead of calling",
                descr))
    })format!("use struct {descr} syntax instead of calling"),
2286                                parts,
2287                                applicability,
2288                            );
2289                        } else {
2290                            let (fields, applicability) = match fields {
2291                                Some(fields) => {
2292                                    let fields = if let Some(old_fields) = old_fields {
2293                                        fields
2294                                            .iter()
2295                                            .enumerate()
2296                                            .map(|(idx, new)| (new, old_fields.get(idx)))
2297                                            .map(|(new, old)| {
2298                                                if let Some(Some(old)) = old
2299                                                    && new.as_str() != old
2300                                                {
2301                                                    ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("{0}: {1}", new, old))
    })format!("{new}: {old}")
2302                                                } else {
2303                                                    new.to_string()
2304                                                }
2305                                            })
2306                                            .collect::<Vec<String>>()
2307                                    } else {
2308                                        fields
2309                                            .iter()
2310                                            .map(|f| ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("{0}{1}", f, tail))
    })format!("{f}{tail}"))
2311                                            .collect::<Vec<String>>()
2312                                    };
2313
2314                                    (fields.join(", "), applicability)
2315                                }
2316                                None => {
2317                                    ("/* fields */".to_string(), Applicability::HasPlaceholders)
2318                                }
2319                            };
2320                            let pad = if has_fields { " " } else { "" };
2321                            err.span_suggestion(
2322                                span,
2323                                ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("use struct {0} syntax instead",
                descr))
    })format!("use struct {descr} syntax instead"),
2324                                ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("{0} {{{1}{2}{1}}}", path_str, pad,
                fields))
    })format!("{path_str} {{{pad}{fields}{pad}}}"),
2325                                applicability,
2326                            );
2327                        }
2328                    }
2329                    if let PathSource::Expr(Some(Expr {
2330                        kind: ExprKind::Call(path, args),
2331                        span: call_span,
2332                        ..
2333                    })) = source
2334                    {
2335                        this.suggest_alternative_construction_methods(
2336                            def_id,
2337                            err,
2338                            path.span,
2339                            *call_span,
2340                            &args[..],
2341                        );
2342                    }
2343                }
2344                _ => {
2345                    err.span_label(span, fallback_label.to_string());
2346                }
2347            }
2348        };
2349
2350        match (res, source) {
2351            (
2352                Res::Def(DefKind::Macro(kinds), def_id),
2353                PathSource::Expr(Some(Expr {
2354                    kind: ExprKind::Index(..) | ExprKind::Call(..), ..
2355                }))
2356                | PathSource::Struct(_),
2357            ) if kinds.contains(MacroKinds::BANG) => {
2358                // Don't suggest macro if it's unstable.
2359                let suggestable = def_id.is_local()
2360                    || self.r.tcx.lookup_stability(def_id).is_none_or(|s| s.is_stable());
2361
2362                err.span_label(span, fallback_label.to_string());
2363
2364                // Don't suggest `!` for a macro invocation if there are generic args
2365                if path
2366                    .last()
2367                    .is_some_and(|segment| !segment.has_generic_args && !segment.has_lifetime_args)
2368                    && suggestable
2369                {
2370                    err.span_suggestion_verbose(
2371                        span.shrink_to_hi(),
2372                        "use `!` to invoke the macro",
2373                        "!",
2374                        Applicability::MaybeIncorrect,
2375                    );
2376                }
2377
2378                if path_str == "try" && span.is_rust_2015() {
2379                    err.note("if you want the `try` keyword, you need Rust 2018 or later");
2380                }
2381            }
2382            (Res::Def(DefKind::Macro(kinds), _), _) if kinds.contains(MacroKinds::BANG) => {
2383                err.span_label(span, fallback_label.to_string());
2384            }
2385            (Res::Def(DefKind::TyAlias, def_id), PathSource::Trait(_)) => {
2386                err.span_label(span, "type aliases cannot be used as traits");
2387                if self.r.tcx.sess.is_nightly_build() {
2388                    let msg = "you might have meant to use `#![feature(trait_alias)]` instead of a \
2389                               `type` alias";
2390                    let span = self.r.def_span(def_id);
2391                    if let Ok(snip) = self.r.tcx.sess.source_map().span_to_snippet(span) {
2392                        // The span contains a type alias so we should be able to
2393                        // replace `type` with `trait`.
2394                        let snip = snip.replacen("type", "trait", 1);
2395                        err.span_suggestion(span, msg, snip, Applicability::MaybeIncorrect);
2396                    } else {
2397                        err.span_help(span, msg);
2398                    }
2399                }
2400            }
2401            (
2402                Res::Def(kind @ (DefKind::Mod | DefKind::Trait | DefKind::TyAlias), _),
2403                PathSource::Expr(Some(parent)),
2404            ) if path_sep(self, err, parent, kind) => {
2405                return true;
2406            }
2407            (
2408                Res::Def(DefKind::Enum, def_id),
2409                PathSource::TupleStruct(..) | PathSource::Expr(..),
2410            ) => {
2411                self.suggest_using_enum_variant(err, source, def_id, span);
2412            }
2413            (Res::Def(DefKind::Struct, def_id), source) if ns == ValueNS => {
2414                if let PathSource::Expr(Some(parent)) = source
2415                    && let ExprKind::Field(..) | ExprKind::MethodCall(..) = parent.kind
2416                {
2417                    bad_struct_syntax_suggestion(self, err, def_id);
2418                    return true;
2419                }
2420                let Some(ctor) = self.r.struct_ctor(def_id) else {
2421                    bad_struct_syntax_suggestion(self, err, def_id);
2422                    return true;
2423                };
2424
2425                // A type is re-exported and has an inaccessible constructor because it has fields
2426                // that are inaccessible from the reexport's scope, extend the diagnostic.
2427                let is_accessible = self.r.is_accessible_from(ctor.vis, self.parent_scope.module);
2428                if is_accessible
2429                    && let mod_path = &path[..path.len() - 1]
2430                    && let PathResult::Module(ModuleOrUniformRoot::Module(import_mod)) =
2431                        self.resolve_path(mod_path, Some(TypeNS), None, PathSource::Module)
2432                    && ctor.has_private_fields(import_mod, self.r)
2433                    && let Ok(import_decl) = self.r.cm().maybe_resolve_ident_in_module(
2434                        ModuleOrUniformRoot::Module(import_mod),
2435                        path.last().unwrap().ident,
2436                        TypeNS,
2437                        &self.parent_scope,
2438                        None,
2439                    )
2440                {
2441                    err.span_note(
2442                        import_decl.span,
2443                        "the type is accessed through this re-export, but the type's constructor \
2444                         is not visible in this import's scope due to private fields",
2445                    );
2446                    if !ctor.has_private_fields(self.parent_scope.module, self.r) {
2447                        err.span_suggestion_verbose(
2448                            span,
2449                            "the type can be constructed directly, because its fields are \
2450                             available from the current scope",
2451                            // Using `tcx.def_path_str` causes the compiler to hang.
2452                            // We don't need to handle foreign crate types because in that case you
2453                            // can't access the ctor either way.
2454                            ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("crate{0}",
                self.r.tcx.def_path(def_id).to_string_no_crate_verbose()))
    })format!(
2455                                "crate{}", // The method already has leading `::`.
2456                                self.r.tcx.def_path(def_id).to_string_no_crate_verbose(),
2457                            ),
2458                            Applicability::MachineApplicable,
2459                        );
2460                    }
2461                    self.update_err_for_private_tuple_struct_fields(err, &source, def_id);
2462                }
2463                if !is_expected(ctor.res) || is_accessible {
2464                    return true;
2465                }
2466
2467                let field_spans =
2468                    self.update_err_for_private_tuple_struct_fields(err, &source, def_id);
2469
2470                if let Some(spans) = field_spans
2471                    .filter(|spans| spans.len() > 0 && ctor.field_visibilities.len() == spans.len())
2472                {
2473                    let non_visible_spans: Vec<Span> = iter::zip(&ctor.field_visibilities, &spans)
2474                        .filter(|(vis, _)| {
2475                            !self.r.is_accessible_from(**vis, self.parent_scope.module)
2476                        })
2477                        .map(|(_, span)| *span)
2478                        .collect();
2479
2480                    if non_visible_spans.len() > 0 {
2481                        if let Some(fields) = self.r.field_visibility_spans.get(&def_id) {
2482                            err.multipart_suggestion(
2483                                ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("consider making the field{0} publicly accessible",
                if fields.len() == 1 { "" } else { "s" }))
    })format!(
2484                                    "consider making the field{} publicly accessible",
2485                                    pluralize!(fields.len())
2486                                ),
2487                                fields.iter().map(|span| (*span, "pub ".to_string())).collect(),
2488                                Applicability::MaybeIncorrect,
2489                            );
2490                        }
2491
2492                        let mut m: MultiSpan = non_visible_spans.clone().into();
2493                        non_visible_spans
2494                            .into_iter()
2495                            .for_each(|s| m.push_span_label(s, "private field"));
2496                        err.span_note(m, "constructor is not visible here due to private fields");
2497                    }
2498
2499                    return true;
2500                }
2501
2502                err.span_label(span, "constructor is not visible here due to private fields");
2503            }
2504            (Res::Def(DefKind::Union | DefKind::Variant, def_id), _) if ns == ValueNS => {
2505                bad_struct_syntax_suggestion(self, err, def_id);
2506            }
2507            (Res::Def(DefKind::Ctor(_, CtorKind::Const), def_id), _) if ns == ValueNS => {
2508                match source {
2509                    PathSource::Expr(_) | PathSource::TupleStruct(..) | PathSource::Pat => {
2510                        let span = find_span(&source, err);
2511                        err.span_label(
2512                            self.r.def_span(def_id),
2513                            ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("`{0}` defined here", path_str))
    })format!("`{path_str}` defined here"),
2514                        );
2515                        err.span_suggestion(
2516                            span,
2517                            "use this syntax instead",
2518                            path_str,
2519                            Applicability::MaybeIncorrect,
2520                        );
2521                    }
2522                    _ => return false,
2523                }
2524            }
2525            (Res::Def(DefKind::Ctor(_, CtorKind::Fn), ctor_def_id), _) if ns == ValueNS => {
2526                let def_id = self.r.tcx.parent(ctor_def_id);
2527                err.span_label(self.r.def_span(def_id), ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("`{0}` defined here", path_str))
    })format!("`{path_str}` defined here"));
2528                let fields = self.r.field_idents(def_id).map_or_else(
2529                    || "/* fields */".to_string(),
2530                    |field_ids| ::alloc::vec::from_elem("_", field_ids.len())vec!["_"; field_ids.len()].join(", "),
2531                );
2532                err.span_suggestion(
2533                    span,
2534                    "use the tuple variant pattern syntax instead",
2535                    ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("{0}({1})", path_str, fields))
    })format!("{path_str}({fields})"),
2536                    Applicability::HasPlaceholders,
2537                );
2538            }
2539            (Res::SelfTyParam { .. } | Res::SelfTyAlias { .. }, _) if ns == ValueNS => {
2540                err.span_label(span, fallback_label.to_string());
2541                err.note("can't use `Self` as a constructor, you must use the implemented struct");
2542            }
2543            (
2544                Res::Def(DefKind::TyAlias | DefKind::AssocTy, _),
2545                PathSource::TraitItem(ValueNS, PathSource::TupleStruct(whole, args)),
2546            ) => {
2547                err.note("can't use a type alias as tuple pattern");
2548
2549                let mut suggestion = Vec::new();
2550
2551                if let &&[first, ..] = args
2552                    && let &&[.., last] = args
2553                {
2554                    suggestion.extend([
2555                        // "0: " has to be included here so that the fix is machine applicable.
2556                        //
2557                        // If this would only add " { " and then the code below add "0: ",
2558                        // rustfix would crash, because end of this suggestion is the same as start
2559                        // of the suggestion below. Thus, we have to merge these...
2560                        (span.between(first), " { 0: ".to_owned()),
2561                        (last.between(whole.shrink_to_hi()), " }".to_owned()),
2562                    ]);
2563
2564                    suggestion.extend(
2565                        args.iter()
2566                            .enumerate()
2567                            .skip(1) // See above
2568                            .map(|(index, &arg)| (arg.shrink_to_lo(), ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("{0}: ", index))
    })format!("{index}: "))),
2569                    )
2570                } else {
2571                    suggestion.push((span.between(whole.shrink_to_hi()), " {}".to_owned()));
2572                }
2573
2574                err.multipart_suggestion(
2575                    "use struct pattern instead",
2576                    suggestion,
2577                    Applicability::MachineApplicable,
2578                );
2579            }
2580            (
2581                Res::Def(DefKind::TyAlias | DefKind::AssocTy, _),
2582                PathSource::TraitItem(
2583                    ValueNS,
2584                    PathSource::Expr(Some(ast::Expr {
2585                        span: whole,
2586                        kind: ast::ExprKind::Call(_, args),
2587                        ..
2588                    })),
2589                ),
2590            ) => {
2591                err.note("can't use a type alias as a constructor");
2592
2593                let mut suggestion = Vec::new();
2594
2595                if let [first, ..] = &**args
2596                    && let [.., last] = &**args
2597                {
2598                    suggestion.extend([
2599                        // "0: " has to be included here so that the fix is machine applicable.
2600                        //
2601                        // If this would only add " { " and then the code below add "0: ",
2602                        // rustfix would crash, because end of this suggestion is the same as start
2603                        // of the suggestion below. Thus, we have to merge these...
2604                        (span.between(first.span), " { 0: ".to_owned()),
2605                        (last.span.between(whole.shrink_to_hi()), " }".to_owned()),
2606                    ]);
2607
2608                    suggestion.extend(
2609                        args.iter()
2610                            .enumerate()
2611                            .skip(1) // See above
2612                            .map(|(index, arg)| (arg.span.shrink_to_lo(), ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("{0}: ", index))
    })format!("{index}: "))),
2613                    )
2614                } else {
2615                    suggestion.push((span.between(whole.shrink_to_hi()), " {}".to_owned()));
2616                }
2617
2618                err.multipart_suggestion(
2619                    "use struct expression instead",
2620                    suggestion,
2621                    Applicability::MachineApplicable,
2622                );
2623            }
2624            _ => return false,
2625        }
2626        true
2627    }
2628
2629    fn suggest_alternative_construction_methods(
2630        &self,
2631        def_id: DefId,
2632        err: &mut Diag<'_>,
2633        path_span: Span,
2634        call_span: Span,
2635        args: &[Box<Expr>],
2636    ) {
2637        if def_id.is_local() {
2638            // Doing analysis on local `DefId`s would cause infinite recursion.
2639            return;
2640        }
2641        // Look at all the associated functions without receivers in the type's
2642        // inherent impls to look for builders that return `Self`
2643        let mut items = self
2644            .r
2645            .tcx
2646            .inherent_impls(def_id)
2647            .iter()
2648            .flat_map(|&i| self.r.tcx.associated_items(i).in_definition_order())
2649            // Only assoc fn with no receivers.
2650            .filter(|item| item.is_fn() && !item.is_method())
2651            .filter_map(|item| {
2652                // Only assoc fns that return `Self`
2653                let fn_sig = self.r.tcx.fn_sig(item.def_id).skip_binder();
2654                // Don't normalize the return type, because that can cause cycle errors.
2655                let ret_ty = fn_sig.output().skip_binder();
2656                let ty::Adt(def, _args) = ret_ty.kind() else {
2657                    return None;
2658                };
2659                let input_len = fn_sig.inputs().skip_binder().len();
2660                if def.did() != def_id {
2661                    return None;
2662                }
2663                let name = item.name();
2664                let order = !name.as_str().starts_with("new");
2665                Some((order, name, input_len))
2666            })
2667            .collect::<Vec<_>>();
2668        items.sort_by_key(|(order, _, _)| *order);
2669        let suggestion = |name, args| {
2670            ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("::{1}({0})",
                std::iter::repeat_n("_", args).collect::<Vec<_>>().join(", "),
                name))
    })format!("::{name}({})", std::iter::repeat_n("_", args).collect::<Vec<_>>().join(", "))
2671        };
2672        match &items[..] {
2673            [] => {}
2674            [(_, name, len)] if *len == args.len() => {
2675                err.span_suggestion_verbose(
2676                    path_span.shrink_to_hi(),
2677                    ::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",),
2678                    ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("::{0}", name))
    })format!("::{name}"),
2679                    Applicability::MaybeIncorrect,
2680                );
2681            }
2682            [(_, name, len)] => {
2683                err.span_suggestion_verbose(
2684                    path_span.shrink_to_hi().with_hi(call_span.hi()),
2685                    ::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",),
2686                    suggestion(name, *len),
2687                    Applicability::MaybeIncorrect,
2688                );
2689            }
2690            _ => {
2691                err.span_suggestions_with_style(
2692                    path_span.shrink_to_hi().with_hi(call_span.hi()),
2693                    "you might have meant to use an associated function to build this type",
2694                    items.iter().map(|(_, name, len)| suggestion(name, *len)),
2695                    Applicability::MaybeIncorrect,
2696                    SuggestionStyle::ShowAlways,
2697                );
2698            }
2699        }
2700        // We'd ideally use `type_implements_trait` but don't have access to
2701        // the trait solver here. We can't use `get_diagnostic_item` or
2702        // `all_traits` in resolve either. So instead we abuse the import
2703        // suggestion machinery to get `std::default::Default` and perform some
2704        // checks to confirm that we got *only* that trait. We then see if the
2705        // Adt we have has a direct implementation of `Default`. If so, we
2706        // provide a structured suggestion.
2707        let default_trait = self
2708            .r
2709            .lookup_import_candidates(
2710                Ident::with_dummy_span(sym::Default),
2711                Namespace::TypeNS,
2712                &self.parent_scope,
2713                &|res: Res| #[allow(non_exhaustive_omitted_patterns)] match res {
    Res::Def(DefKind::Trait, _) => true,
    _ => false,
}matches!(res, Res::Def(DefKind::Trait, _)),
2714            )
2715            .iter()
2716            .filter_map(|candidate| candidate.did)
2717            .find(|did| {
        {
            'done:
                {
                for i in
                    ::rustc_attr_ir::HasAttrs::get_attrs(*did, &self.r.tcx) {
                    #[allow(unused_imports)]
                    use ::rustc_attr_ir::AttributeKind::*;
                    let i: &::rustc_attr_ir::Attribute = i;
                    match i {
                        ::rustc_attr_ir::Attribute::Parsed(RustcDiagnosticItem(sym::Default))
                            => {
                            break 'done Some(());
                        }
                        ::rustc_attr_ir::Attribute::Unparsed(..) =>
                            {}
                            #[deny(unreachable_patterns)]
                            _ => {}
                    }
                }
                None
            }
        }
    }.is_some()find_attr!(self.r.tcx, *did, RustcDiagnosticItem(sym::Default)));
2718        let Some(default_trait) = default_trait else {
2719            return;
2720        };
2721        if self
2722            .r
2723            .extern_crate_map
2724            .items()
2725            // FIXME: This doesn't include impls like `impl Default for String`.
2726            .flat_map(|(_, crate_)| {
2727                UnordItems::new(
2728                    self.r.tcx.implementations_of_trait((*crate_, default_trait)).into_iter(),
2729                )
2730            })
2731            .filter_map(|(_, simplified_self_ty)| *simplified_self_ty)
2732            .filter_map(|simplified_self_ty| match simplified_self_ty {
2733                SimplifiedType::Adt(did) => Some(did),
2734                _ => None,
2735            })
2736            .any(|did| did == def_id)
2737        {
2738            err.multipart_suggestion(
2739                "consider using the `Default` trait",
2740                ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
        [(path_span.shrink_to_lo(), "<".to_string()),
                (path_span.shrink_to_hi().with_hi(call_span.hi()),
                    " as std::default::Default>::default()".to_string())]))vec![
2741                    (path_span.shrink_to_lo(), "<".to_string()),
2742                    (
2743                        path_span.shrink_to_hi().with_hi(call_span.hi()),
2744                        " as std::default::Default>::default()".to_string(),
2745                    ),
2746                ],
2747                Applicability::MaybeIncorrect,
2748            );
2749        }
2750    }
2751
2752    /// Given the target `ident` and `kind`, search for the similarly named associated item
2753    /// in `self.current_trait_ref`.
2754    pub(crate) fn find_similarly_named_assoc_item(
2755        &mut self,
2756        ident: Symbol,
2757        kind: &AssocItemKind,
2758    ) -> Option<Symbol> {
2759        let (module, _) = self.current_trait_ref.as_ref()?;
2760        if ident == kw::Underscore {
2761            // We do nothing for `_`.
2762            return None;
2763        }
2764
2765        let targets = self
2766            .r
2767            .resolutions(*module)
2768            .iter()
2769            .filter_map(|(key, res)| {
2770                res.borrow(self.r).best_decl().map(|binding| (key, binding.res()))
2771            })
2772            .filter(|(_, res)| match (kind, res) {
2773                (AssocItemKind::Const(..), Res::Def(DefKind::AssocConst { .. }, _)) => true,
2774                (AssocItemKind::Fn(_), Res::Def(DefKind::AssocFn, _)) => true,
2775                (AssocItemKind::Type(..), Res::Def(DefKind::AssocTy, _)) => true,
2776                (AssocItemKind::Delegation(_), Res::Def(DefKind::AssocFn, _)) => true,
2777                _ => false,
2778            })
2779            .map(|(key, _)| key.ident.name)
2780            .collect::<Vec<_>>();
2781
2782        find_best_match_for_name(&targets, ident, None)
2783    }
2784
2785    fn lookup_assoc_candidate<FilterFn>(
2786        &self,
2787        ident: Ident,
2788        ns: Namespace,
2789        filter_fn: FilterFn,
2790        called: bool,
2791    ) -> Option<AssocSuggestion>
2792    where
2793        FilterFn: Fn(Res) -> bool,
2794    {
2795        fn extract_node_id(t: &Ty) -> Option<NodeId> {
2796            match t.kind {
2797                TyKind::Path(None, _) => Some(t.id),
2798                TyKind::Ref(_, ref mut_ty) => extract_node_id(&mut_ty.ty),
2799                // This doesn't handle the remaining `Ty` variants as they are not
2800                // that commonly the self_type, it might be interesting to provide
2801                // support for those in future.
2802                _ => None,
2803            }
2804        }
2805        // Fields are generally expected in the same contexts as locals.
2806        if filter_fn(Res::Local(ast::DUMMY_NODE_ID)) {
2807            if let Some(node_id) = self.diag_metadata.current_self_type.and_then(extract_node_id)
2808                && let Some(resolution) = self.r.partial_res_map.get(&node_id)
2809                && let Some(Res::Def(DefKind::Struct | DefKind::Union, did)) = resolution.full_res()
2810                && let Some(fields) = self.r.field_idents(did)
2811                && let Some(field) = fields.iter().find(|id| ident.name == id.name)
2812            {
2813                // Look for a field with the same name in the current self_type.
2814                return Some(AssocSuggestion::Field(field.span));
2815            }
2816        }
2817
2818        if let Some(items) = self.diag_metadata.current_trait_assoc_items {
2819            for assoc_item in items {
2820                if let Some(assoc_ident) = assoc_item.kind.ident()
2821                    && assoc_ident == ident
2822                {
2823                    return Some(match &assoc_item.kind {
2824                        ast::AssocItemKind::Const(..) => AssocSuggestion::AssocConst,
2825                        ast::AssocItemKind::Fn(ast::Fn { sig, .. }) if sig.decl.has_self() => {
2826                            AssocSuggestion::MethodWithSelf { called }
2827                        }
2828                        ast::AssocItemKind::Fn(..) => AssocSuggestion::AssocFn { called },
2829                        ast::AssocItemKind::Type(..) => AssocSuggestion::AssocType,
2830                        ast::AssocItemKind::Delegation(..)
2831                            if self
2832                                .r
2833                                .owners
2834                                .get(&assoc_item.id)
2835                                .and_then(|o| self.r.delegation_fn_sigs.get(&o.def_id))
2836                                .is_some_and(|sig| sig.has_self) =>
2837                        {
2838                            AssocSuggestion::MethodWithSelf { called }
2839                        }
2840                        ast::AssocItemKind::Delegation(..) => AssocSuggestion::AssocFn { called },
2841                        ast::AssocItemKind::MacCall(_) | ast::AssocItemKind::DelegationMac(..) => {
2842                            continue;
2843                        }
2844                    });
2845                }
2846            }
2847        }
2848
2849        // Look for associated items in the current trait.
2850        if let Some((module, _)) = self.current_trait_ref
2851            && let Ok(binding) = self.r.cm().maybe_resolve_ident_in_module(
2852                ModuleOrUniformRoot::Module(module),
2853                ident,
2854                ns,
2855                &self.parent_scope,
2856                None,
2857            )
2858        {
2859            let res = binding.res();
2860            if filter_fn(res) {
2861                match res {
2862                    Res::Def(DefKind::Fn | DefKind::AssocFn, def_id) => {
2863                        let has_self = match def_id.as_local() {
2864                            Some(def_id) => self
2865                                .r
2866                                .delegation_fn_sigs
2867                                .get(&def_id)
2868                                .is_some_and(|sig| sig.has_self),
2869                            None => {
2870                                self.r.tcx.fn_arg_idents(def_id).first().is_some_and(|&ident| {
2871                                    #[allow(non_exhaustive_omitted_patterns)] match ident {
    Some(Ident { name: kw::SelfLower, .. }) => true,
    _ => false,
}matches!(ident, Some(Ident { name: kw::SelfLower, .. }))
2872                                })
2873                            }
2874                        };
2875                        if has_self {
2876                            return Some(AssocSuggestion::MethodWithSelf { called });
2877                        } else {
2878                            return Some(AssocSuggestion::AssocFn { called });
2879                        }
2880                    }
2881                    Res::Def(DefKind::AssocConst { .. }, _) => {
2882                        return Some(AssocSuggestion::AssocConst);
2883                    }
2884                    Res::Def(DefKind::AssocTy, _) => {
2885                        return Some(AssocSuggestion::AssocType);
2886                    }
2887                    _ => {}
2888                }
2889            }
2890        }
2891
2892        None
2893    }
2894
2895    fn lookup_typo_candidate(
2896        &mut self,
2897        path: &[Segment],
2898        following_seg: Option<&Segment>,
2899        ns: Namespace,
2900        filter_fn: &impl Fn(Res) -> bool,
2901    ) -> TypoCandidate {
2902        let mut names = Vec::new();
2903        if let [segment] = path {
2904            let mut ctxt = segment.ident.span.ctxt();
2905
2906            // Search in lexical scope.
2907            // Walk backwards up the ribs in scope and collect candidates.
2908            for rib in self.ribs[ns].iter().rev() {
2909                let rib_ctxt = if rib.kind.contains_params() {
2910                    ctxt.normalize_to_macros_2_0()
2911                } else {
2912                    ctxt.normalize_to_macro_rules()
2913                };
2914
2915                // Locals and type parameters
2916                for (ident, &res) in &rib.bindings {
2917                    if filter_fn(res) && ident.span.ctxt() == rib_ctxt {
2918                        names.push(TypoSuggestion::new(ident.name, ident.span, res));
2919                    }
2920                }
2921
2922                if let RibKind::Block(Some(module)) = rib.kind {
2923                    self.r.add_module_candidates(
2924                        module.to_module(),
2925                        &mut names,
2926                        &filter_fn,
2927                        Some(ctxt),
2928                    );
2929                } else if let RibKind::Module(module) = rib.kind {
2930                    // Encountered a module item, abandon ribs and look into that module and preludes.
2931                    let parent_scope =
2932                        &ParentScope { module: module.to_module(), ..self.parent_scope };
2933                    self.r.add_scope_set_candidates(
2934                        &mut names,
2935                        ScopeSet::All(ns),
2936                        parent_scope,
2937                        segment.ident.span.with_ctxt(ctxt),
2938                        filter_fn,
2939                    );
2940                    break;
2941                }
2942
2943                if let RibKind::MacroDefinition(def) = rib.kind
2944                    && def == self.r.macro_def(ctxt)
2945                {
2946                    // If an invocation of this macro created `ident`, give up on `ident`
2947                    // and switch to `ident`'s source from the macro definition.
2948                    ctxt.remove_mark();
2949                }
2950            }
2951        } else {
2952            // Search in module.
2953            let mod_path = &path[..path.len() - 1];
2954            if let PathResult::Module(ModuleOrUniformRoot::Module(module)) =
2955                self.resolve_path(mod_path, Some(TypeNS), None, PathSource::Type)
2956            {
2957                self.r.add_module_candidates(module, &mut names, &filter_fn, None);
2958            }
2959        }
2960
2961        // if next_seg is present, let's filter everything that does not continue the path
2962        if let Some(following_seg) = following_seg {
2963            names.retain(|suggestion| match suggestion.res {
2964                Res::Def(DefKind::Struct | DefKind::Enum | DefKind::Union, _) => {
2965                    // FIXME: this is not totally accurate, but mostly works
2966                    suggestion.candidate != following_seg.ident.name
2967                }
2968                Res::Def(DefKind::Mod, def_id) => {
2969                    let module = self.r.expect_module(def_id);
2970                    self.r
2971                        .resolutions(module)
2972                        .iter()
2973                        .any(|(key, _)| key.ident.name == following_seg.ident.name)
2974                }
2975                _ => true,
2976            });
2977        }
2978        let name = path[path.len() - 1].ident.name;
2979        // Make sure error reporting is deterministic.
2980        names.sort_by(|a, b| a.candidate.as_str().cmp(b.candidate.as_str()));
2981
2982        match find_best_match_for_name(
2983            &names.iter().map(|suggestion| suggestion.candidate).collect::<Vec<Symbol>>(),
2984            name,
2985            None,
2986        ) {
2987            Some(found) => {
2988                let Some(sugg) = names.into_iter().find(|suggestion| suggestion.candidate == found)
2989                else {
2990                    return TypoCandidate::None;
2991                };
2992                if found == name {
2993                    TypoCandidate::Shadowed(sugg.res, sugg.span)
2994                } else {
2995                    TypoCandidate::Typo(sugg)
2996                }
2997            }
2998            _ => TypoCandidate::None,
2999        }
3000    }
3001
3002    // Returns the name of the Rust type approximately corresponding to
3003    // a type name in another programming language.
3004    fn likely_rust_type(path: &[Segment]) -> Option<Symbol> {
3005        let name = path[path.len() - 1].ident.as_str();
3006        // Common Java types
3007        Some(match name {
3008            "byte" => sym::u8, // In Java, bytes are signed, but in practice one almost always wants unsigned bytes.
3009            "short" => sym::i16,
3010            "Bool" => sym::bool,
3011            "Boolean" => sym::bool,
3012            "boolean" => sym::bool,
3013            "int" => sym::i32,
3014            "long" => sym::i64,
3015            "float" => sym::f32,
3016            "double" => sym::f64,
3017            _ => return None,
3018        })
3019    }
3020
3021    // try to give a suggestion for this pattern: `name = blah`, which is common in other languages
3022    // suggest `let name = blah` to introduce a new binding
3023    fn let_binding_suggestion(&self, err: &mut Diag<'_>, ident_span: Span) -> bool {
3024        if ident_span.from_expansion() {
3025            return false;
3026        }
3027
3028        // only suggest when the code is a assignment without prefix code
3029        if let Some(Expr { kind: ExprKind::Assign(lhs, ..), .. }) = self.diag_metadata.in_assignment
3030            && let ast::ExprKind::Path(None, ref path) = lhs.kind
3031            && self.r.tcx.sess.source_map().is_line_before_span_empty(ident_span)
3032        {
3033            let (span, text) = match path.segments.first() {
3034                Some(seg) if let Some(name) = seg.ident.as_str().strip_prefix("let") => {
3035                    // a special case for #117894
3036                    let name = name.trim_prefix('_');
3037                    (ident_span, ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("let {0}", name))
    })format!("let {name}"))
3038                }
3039                _ => (ident_span.shrink_to_lo(), "let ".to_string()),
3040            };
3041
3042            err.span_suggestion_verbose(
3043                span,
3044                "you might have meant to introduce a new binding",
3045                text,
3046                Applicability::MaybeIncorrect,
3047            );
3048            return true;
3049        }
3050
3051        // a special case for #133713
3052        // '=' maybe a typo of `:`, which is a type annotation instead of assignment
3053        if err.code == Some(E0423)
3054            && let Some((let_span, None, Some(val_span))) = self.diag_metadata.current_let_binding
3055            && val_span.contains(ident_span)
3056            && val_span.lo() == ident_span.lo()
3057        {
3058            err.span_suggestion_verbose(
3059                let_span.shrink_to_hi().to(val_span.shrink_to_lo()),
3060                "you might have meant to use `:` for type annotation",
3061                ": ",
3062                Applicability::MaybeIncorrect,
3063            );
3064            return true;
3065        }
3066        false
3067    }
3068
3069    fn find_module(&self, def_id: DefId) -> Option<(Module<'ra>, ImportSuggestion)> {
3070        let mut result = None;
3071        let mut seen_modules = FxHashSet::default();
3072        let mut worklist = ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
        [(self.r.graph_root.to_module(), ThinVec::new(), true)]))vec![(self.r.graph_root.to_module(), ThinVec::new(), true)];
3073
3074        while let Some((in_module, path_segments, doc_visible)) = worklist.pop() {
3075            // abort if the module is already found
3076            if result.is_some() {
3077                break;
3078            }
3079
3080            in_module.for_each_child(self.r, |r, ident, orig_ident_span, _, name_binding| {
3081                // abort if the module is already found or if name_binding is private external
3082                if result.is_some() || !name_binding.vis().is_visible_locally() {
3083                    return;
3084                }
3085                if let Some(module_def_id) = name_binding.res().module_like_def_id() {
3086                    // form the path
3087                    let mut path_segments = path_segments.clone();
3088                    path_segments.push(ast::PathSegment::from_ident(ident.orig(orig_ident_span)));
3089                    let doc_visible = doc_visible
3090                        && (module_def_id.is_local() || !r.tcx.is_doc_hidden(module_def_id));
3091                    if module_def_id == def_id {
3092                        let path = Path { span: name_binding.span, segments: path_segments };
3093                        result = Some((
3094                            r.expect_module(module_def_id),
3095                            ImportSuggestion {
3096                                did: Some(def_id),
3097                                descr: "module",
3098                                path,
3099                                accessible: true,
3100                                doc_visible,
3101                                note: None,
3102                                via_import: false,
3103                                is_stable: true,
3104                            },
3105                        ));
3106                    } else {
3107                        // add the module to the lookup
3108                        if seen_modules.insert(module_def_id) {
3109                            let module = r.expect_module(module_def_id);
3110                            worklist.push((module, path_segments, doc_visible));
3111                        }
3112                    }
3113                }
3114            });
3115        }
3116
3117        result
3118    }
3119
3120    fn collect_enum_ctors(&self, def_id: DefId) -> Option<Vec<(Path, DefId, CtorKind)>> {
3121        self.find_module(def_id).map(|(enum_module, enum_import_suggestion)| {
3122            let mut variants = Vec::new();
3123            enum_module.for_each_child(self.r, |_, ident, orig_ident_span, _, name_binding| {
3124                if let Res::Def(DefKind::Ctor(CtorOf::Variant, kind), def_id) = name_binding.res() {
3125                    let mut segms = enum_import_suggestion.path.segments.clone();
3126                    segms.push(ast::PathSegment::from_ident(ident.orig(orig_ident_span)));
3127                    let path = Path { span: name_binding.span, segments: segms };
3128                    variants.push((path, def_id, kind));
3129                }
3130            });
3131            variants
3132        })
3133    }
3134
3135    /// Adds a suggestion for using an enum's variant when an enum is used instead.
3136    fn suggest_using_enum_variant(
3137        &self,
3138        err: &mut Diag<'_>,
3139        source: PathSource<'_, '_, '_>,
3140        def_id: DefId,
3141        span: Span,
3142    ) {
3143        let Some(variant_ctors) = self.collect_enum_ctors(def_id) else {
3144            err.note("you might have meant to use one of the enum's variants");
3145            return;
3146        };
3147
3148        // If the expression is a field-access or method-call, try to find a variant with the field/method name
3149        // that could have been intended, and suggest replacing the `.` with `::`.
3150        // Otherwise, suggest adding `::VariantName` after the enum;
3151        // and if the expression is call-like, only suggest tuple variants.
3152        let (suggest_path_sep_dot_span, suggest_only_tuple_variants) = match source {
3153            // `Type(a, b)` in a pattern, only suggest adding a tuple variant after `Type`.
3154            PathSource::TupleStruct(..) => (None, true),
3155            PathSource::Expr(Some(expr)) => match &expr.kind {
3156                // `Type(a, b)`, only suggest adding a tuple variant after `Type`.
3157                ExprKind::Call(..) => (None, true),
3158                // `Type.Foo(a, b)`, suggest replacing `.` -> `::` if variant `Foo` exists and is a tuple variant,
3159                // otherwise suggest adding a variant after `Type`.
3160                ExprKind::MethodCall(MethodCall {
3161                    receiver,
3162                    span,
3163                    seg: PathSegment { ident, .. },
3164                    ..
3165                }) => {
3166                    let dot_span = receiver.span.between(*span);
3167                    let found_tuple_variant = variant_ctors.iter().any(|(path, _, ctor_kind)| {
3168                        *ctor_kind == CtorKind::Fn
3169                            && path.segments.last().is_some_and(|seg| seg.ident == *ident)
3170                    });
3171                    (found_tuple_variant.then_some(dot_span), false)
3172                }
3173                // `Type.Foo`, suggest replacing `.` -> `::` if variant `Foo` exists and is a unit or tuple variant,
3174                // otherwise suggest adding a variant after `Type`.
3175                ExprKind::Field(base, ident) => {
3176                    let dot_span = base.span.between(ident.span);
3177                    let found_tuple_or_unit_variant = variant_ctors.iter().any(|(path, ..)| {
3178                        path.segments.last().is_some_and(|seg| seg.ident == *ident)
3179                    });
3180                    (found_tuple_or_unit_variant.then_some(dot_span), false)
3181                }
3182                _ => (None, false),
3183            },
3184            _ => (None, false),
3185        };
3186
3187        if let Some(dot_span) = suggest_path_sep_dot_span {
3188            err.span_suggestion_verbose(
3189                dot_span,
3190                "use the path separator to refer to a variant",
3191                "::",
3192                Applicability::MaybeIncorrect,
3193            );
3194        } else if suggest_only_tuple_variants {
3195            // Suggest only tuple variants regardless of whether they have fields and do not
3196            // suggest path with added parentheses.
3197            let mut suggestable_variants = variant_ctors
3198                .iter()
3199                .filter(|(.., kind)| *kind == CtorKind::Fn)
3200                .map(|(variant, ..)| path_names_to_string(variant))
3201                .collect::<Vec<_>>();
3202            suggestable_variants.sort();
3203
3204            let non_suggestable_variant_count = variant_ctors.len() - suggestable_variants.len();
3205
3206            let source_msg = if #[allow(non_exhaustive_omitted_patterns)] match source {
    PathSource::TupleStruct(..) => true,
    _ => false,
}matches!(source, PathSource::TupleStruct(..)) {
3207                "to match against"
3208            } else {
3209                "to construct"
3210            };
3211
3212            if !suggestable_variants.is_empty() {
3213                let msg = if non_suggestable_variant_count == 0 && suggestable_variants.len() == 1 {
3214                    ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("try {0} the enum\'s variant",
                source_msg))
    })format!("try {source_msg} the enum's variant")
3215                } else {
3216                    ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("try {0} one of the enum\'s variants",
                source_msg))
    })format!("try {source_msg} one of the enum's variants")
3217                };
3218
3219                err.span_suggestions(
3220                    span,
3221                    msg,
3222                    suggestable_variants,
3223                    Applicability::MaybeIncorrect,
3224                );
3225            }
3226
3227            // If the enum has no tuple variants..
3228            if non_suggestable_variant_count == variant_ctors.len() {
3229                err.help(::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("the enum has no tuple variants {0}",
                source_msg))
    })format!("the enum has no tuple variants {source_msg}"));
3230            }
3231
3232            // If there are also non-tuple variants..
3233            if non_suggestable_variant_count == 1 {
3234                err.help(::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("you might have meant {0} the enum\'s non-tuple variant",
                source_msg))
    })format!("you might have meant {source_msg} the enum's non-tuple variant"));
3235            } else if non_suggestable_variant_count >= 1 {
3236                err.help(::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("you might have meant {0} one of the enum\'s non-tuple variants",
                source_msg))
    })format!(
3237                    "you might have meant {source_msg} one of the enum's non-tuple variants"
3238                ));
3239            }
3240        } else {
3241            let needs_placeholder = |ctor_def_id: DefId, kind: CtorKind| {
3242                let def_id = self.r.tcx.parent(ctor_def_id);
3243                match kind {
3244                    CtorKind::Const => false,
3245                    CtorKind::Fn => {
3246                        !self.r.field_idents(def_id).is_some_and(|field_ids| field_ids.is_empty())
3247                    }
3248                }
3249            };
3250
3251            let mut suggestable_variants = variant_ctors
3252                .iter()
3253                .filter(|(_, def_id, kind)| !needs_placeholder(*def_id, *kind))
3254                .map(|(variant, _, kind)| (path_names_to_string(variant), kind))
3255                .map(|(variant, kind)| match kind {
3256                    CtorKind::Const => variant,
3257                    CtorKind::Fn => ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("({0}())", variant))
    })format!("({variant}())"),
3258                })
3259                .collect::<Vec<_>>();
3260            suggestable_variants.sort();
3261            let no_suggestable_variant = suggestable_variants.is_empty();
3262
3263            if !no_suggestable_variant {
3264                let msg = if suggestable_variants.len() == 1 {
3265                    "you might have meant to use the following enum variant"
3266                } else {
3267                    "you might have meant to use one of the following enum variants"
3268                };
3269
3270                err.span_suggestions(
3271                    span,
3272                    msg,
3273                    suggestable_variants,
3274                    Applicability::MaybeIncorrect,
3275                );
3276            }
3277
3278            let mut suggestable_variants_with_placeholders = variant_ctors
3279                .iter()
3280                .filter(|(_, def_id, kind)| needs_placeholder(*def_id, *kind))
3281                .map(|(variant, _, kind)| (path_names_to_string(variant), kind))
3282                .filter_map(|(variant, kind)| match kind {
3283                    CtorKind::Fn => Some(::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("({0}(/* fields */))", variant))
    })format!("({variant}(/* fields */))")),
3284                    _ => None,
3285                })
3286                .collect::<Vec<_>>();
3287            suggestable_variants_with_placeholders.sort();
3288
3289            if !suggestable_variants_with_placeholders.is_empty() {
3290                let msg =
3291                    match (no_suggestable_variant, suggestable_variants_with_placeholders.len()) {
3292                        (true, 1) => "the following enum variant is available",
3293                        (true, _) => "the following enum variants are available",
3294                        (false, 1) => "alternatively, the following enum variant is available",
3295                        (false, _) => {
3296                            "alternatively, the following enum variants are also available"
3297                        }
3298                    };
3299
3300                err.span_suggestions(
3301                    span,
3302                    msg,
3303                    suggestable_variants_with_placeholders,
3304                    Applicability::HasPlaceholders,
3305                );
3306            }
3307        };
3308
3309        if def_id.is_local() {
3310            err.span_note(self.r.def_span(def_id), "the enum is defined here");
3311        }
3312    }
3313
3314    /// Detects missing const parameters in `impl` blocks and suggests adding them.
3315    ///
3316    /// When a const parameter is used in the self type of an `impl` but not declared
3317    /// in the `impl`'s own generic parameter list, this function emits a targeted
3318    /// diagnostic with a suggestion to add it at the correct position.
3319    ///
3320    /// Example:
3321    ///
3322    /// ```rust,ignore (suggested field is not completely correct, it should be a single suggestion)
3323    /// struct C<const A: u8, const X: u8, const P: u32>;
3324    ///
3325    /// impl Foo for C<A, X, P> {}
3326    /// //           ^ the struct `C` in `C<A, X, P>` is used as the self type
3327    /// //             ^ ^ ^ but A, X and P are not declared on the impl
3328    ///
3329    /// Suggested fix:
3330    ///
3331    /// impl<const A: u8, const X: u8, const P: u32> Foo for C<A, X, P> {}
3332    ///
3333    /// Current behavior (suggestions are emitted one-by-one):
3334    ///
3335    /// impl<const A: u8> Foo for C<A, X, P> {}
3336    /// impl<const X: u8> Foo for C<A, X, P> {}
3337    /// impl<const P: u32> Foo for C<A, X, P> {}
3338    ///
3339    /// Ideally the suggestion should aggregate them into a single line:
3340    ///
3341    /// impl<const A: u8, const X: u8, const P: u32> Foo for C<A, X, P> {}
3342    /// ```
3343    ///
3344    pub(crate) fn detect_and_suggest_const_parameter_error(
3345        &mut self,
3346        path: &[Segment],
3347        source: PathSource<'_, 'ast, 'ra>,
3348    ) -> Option<Diag<'tcx>> {
3349        let Some(item) = self.diag_metadata.current_item else { return None };
3350        let ItemKind::Impl(impl_) = &item.kind else { return None };
3351        let self_ty = &impl_.self_ty;
3352
3353        // Represents parameter to the struct whether `A`, `X` or `P`
3354        let [current_parameter] = path else {
3355            return None;
3356        };
3357
3358        let target_ident = current_parameter.ident;
3359
3360        // Find the parent segment i.e `C` in `C<A, X, C>`
3361        let visitor = ParentPathVisitor::new(self_ty, target_ident);
3362
3363        let Some(parent_segment) = visitor.parent else {
3364            return None;
3365        };
3366
3367        let Some(args) = parent_segment.args.as_ref() else {
3368            return None;
3369        };
3370
3371        let GenericArgs::AngleBracketed(angle) = args.as_ref() else {
3372            return None;
3373        };
3374
3375        // Build map: NodeId of each usage in C<A, X, C> -> its position
3376        // e.g NodeId(A) -> 0, NodeId(X) -> 1, NodeId(C) -> 2
3377        let usage_to_pos: FxHashMap<NodeId, usize> = angle
3378            .args
3379            .iter()
3380            .enumerate()
3381            .filter_map(|(pos, arg)| {
3382                if let AngleBracketedArg::Arg(GenericArg::Type(ty)) = arg
3383                    && let TyKind::Path(_, path) = &ty.kind
3384                    && let [segment] = path.segments.as_slice()
3385                {
3386                    Some((segment.id, pos))
3387                } else {
3388                    None
3389                }
3390            })
3391            .collect();
3392
3393        // Get the position of the missing param in C<A, X, C>
3394        // e.g for missing `B` in `C<A, B, C>` this gives idx=1
3395        let Some(idx) = current_parameter.id.and_then(|id| usage_to_pos.get(&id).copied()) else {
3396            return None;
3397        };
3398
3399        // Now resolve the parent struct `C` to get its definition
3400        let ns = source.namespace();
3401        let segment = Segment::from(parent_segment);
3402        let segments = [segment];
3403        let finalize = Finalize::new(parent_segment.id, parent_segment.ident.span);
3404
3405        if let Ok(Some(resolve)) = self.resolve_qpath_anywhere(
3406            &None,
3407            &segments,
3408            ns,
3409            source.defer_to_typeck(),
3410            finalize,
3411            source,
3412        ) && let Some(resolve) = resolve.full_res()
3413            && let Res::Def(_, def_id) = resolve
3414            && def_id.is_local()
3415            && let Some(local_def_id) = def_id.as_local()
3416            && let Some(struct_generics) = self.r.struct_generics.get(&local_def_id)
3417            && let Some(target_param) = &struct_generics.params.get(idx)
3418            && let GenericParamKind::Const { ty, .. } = &target_param.kind
3419            && let TyKind::Path(_, path) = &ty.kind
3420        {
3421            let full_type = path
3422                .segments
3423                .iter()
3424                .map(|seg| seg.ident.to_string())
3425                .collect::<Vec<_>>()
3426                .join("::");
3427
3428            // Find the first impl param whose position in C<A, X, C>
3429            // is strictly greater than our missing param's index
3430            // e.g missing B(idx=1), impl has A(pos=0) and C(pos=2)
3431            // C has pos=2 > 1 so insert before C
3432            let next_impl_param = impl_.generics.params.iter().find(|impl_param| {
3433                angle
3434                    .args
3435                    .iter()
3436                    .find_map(|arg| {
3437                        if let AngleBracketedArg::Arg(GenericArg::Type(ty)) = arg
3438                            && let TyKind::Path(_, path) = &ty.kind
3439                            && let [segment] = path.segments.as_slice()
3440                            && segment.ident == impl_param.ident
3441                        {
3442                            usage_to_pos.get(&segment.id).copied()
3443                        } else {
3444                            None
3445                        }
3446                    })
3447                    .map_or(false, |pos| pos > idx)
3448            });
3449
3450            let (insert_span, snippet) = match next_impl_param {
3451                Some(next_param) => {
3452                    // Insert in the middle before next_param
3453                    // e.g impl<A, C> -> impl<A, const B: u8, C>
3454                    (
3455                        next_param.span().shrink_to_lo(),
3456                        ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("const {0}: {1}, ", target_ident,
                full_type))
    })format!("const {}: {}, ", target_ident, full_type),
3457                    )
3458                }
3459                None => match impl_.generics.params.last() {
3460                    Some(last) => {
3461                        // Append after last existing param
3462                        // e.g impl<A, B> -> impl<A, B, const C: u8>
3463                        (
3464                            last.span().shrink_to_hi(),
3465                            ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!(", const {0}: {1}", target_ident,
                full_type))
    })format!(", const {}: {}", target_ident, full_type),
3466                        )
3467                    }
3468                    None => {
3469                        // No generics at all on impl
3470                        // e.g impl Foo for C<A> -> impl<const A: u8> Foo for C<A>
3471                        (
3472                            impl_.generics.span.shrink_to_hi(),
3473                            ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("<const {0}: {1}>", target_ident,
                full_type))
    })format!("<const {}: {}>", target_ident, full_type),
3474                        )
3475                    }
3476                },
3477            };
3478
3479            let mut err = self.r.dcx().struct_span_err(
3480                target_ident.span,
3481                ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("cannot find const `{0}` in this scope",
                target_ident))
    })format!("cannot find const `{}` in this scope", target_ident),
3482            );
3483
3484            err.code(E0425);
3485
3486            err.span_label(target_ident.span, "not found in this scope");
3487
3488            err.span_label(
3489                target_param.span(),
3490                ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("corresponding const parameter on the type defined here"))
    })format!("corresponding const parameter on the type defined here",),
3491            );
3492
3493            err.subdiagnostic(diagnostics::UnexpectedMissingConstParameter {
3494                span: insert_span,
3495                snippet,
3496                item_name: ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("{0}", target_ident))
    })format!("{}", target_ident),
3497                item_location: String::from("impl"),
3498            });
3499
3500            return Some(err);
3501        }
3502
3503        None
3504    }
3505
3506    pub(crate) fn suggest_adding_generic_parameter(
3507        &mut self,
3508        path: &[Segment],
3509        source: PathSource<'_, 'ast, 'ra>,
3510    ) -> (Option<(Span, &'static str, String, Applicability)>, Option<Diag<'tcx>>) {
3511        let (ident, span) = match path {
3512            [segment]
3513                if !segment.has_generic_args
3514                    && segment.ident.name != kw::SelfUpper
3515                    && segment.ident.name != kw::Dyn =>
3516            {
3517                (segment.ident.to_string(), segment.ident.span)
3518            }
3519            _ => return (None, None),
3520        };
3521        let mut iter = ident.chars().map(|c| c.is_uppercase());
3522        let single_uppercase_char =
3523            #[allow(non_exhaustive_omitted_patterns)] match iter.next() {
    Some(true) => true,
    _ => false,
}matches!(iter.next(), Some(true)) && #[allow(non_exhaustive_omitted_patterns)] match iter.next() {
    None => true,
    _ => false,
}matches!(iter.next(), None);
3524        if !self.diag_metadata.currently_processing_generic_args && !single_uppercase_char {
3525            return (None, None);
3526        }
3527        match (
3528            self.diag_metadata.current_item,
3529            single_uppercase_char,
3530            self.diag_metadata.currently_processing_generic_args,
3531        ) {
3532            (Some(Item { kind: ItemKind::Fn(fn_), .. }), _, _) if fn_.ident.name == sym::main => {
3533                // Ignore `fn main()` as we don't want to suggest `fn main<T>()`
3534            }
3535            (
3536                Some(Item {
3537                    kind:
3538                        kind @ ItemKind::Fn(..)
3539                        | kind @ ItemKind::Enum(..)
3540                        | kind @ ItemKind::Struct(..)
3541                        | kind @ ItemKind::Union(..),
3542                    ..
3543                }),
3544                true,
3545                _,
3546            )
3547            // Without the 2nd `true`, we'd suggest `impl <T>` for `impl T` when a type `T` isn't found
3548            | (Some(Item { kind: kind @ ItemKind::Impl(..), .. }), true, true)
3549            | (Some(Item { kind, .. }), false, _) => {
3550                if let Some(generics) = kind.generics() {
3551                    if span.overlaps(generics.span) {
3552                        // Avoid the following:
3553                        // error[E0405]: cannot find trait `A` in this scope
3554                        //  --> $DIR/typo-suggestion-named-underscore.rs:CC:LL
3555                        //   |
3556                        // L | fn foo<T: A>(x: T) {} // Shouldn't suggest underscore
3557                        //   |           ^- help: you might be missing a type parameter: `, A`
3558                        //   |           |
3559                        //   |           not found in this scope
3560                        return (None, None);
3561                    }
3562
3563                    let (msg, sugg) = match source {
3564                        PathSource::Type | PathSource::PreciseCapturingArg(TypeNS) => {
3565                            if let Some(err) =
3566                                self.detect_and_suggest_const_parameter_error(path, source)
3567                            {
3568                                return (None, Some(err));
3569                            }
3570                            ("you might be missing a type parameter", ident)
3571                        }
3572                        PathSource::Expr(_) | PathSource::PreciseCapturingArg(ValueNS) => (
3573                            "you might be missing a const parameter",
3574                            ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("const {0}: /* Type */", ident))
    })format!("const {ident}: /* Type */"),
3575                        ),
3576                        _ => return (None, None),
3577                    };
3578                    let (span, sugg) = if let [.., param] = &generics.params[..] {
3579                        let span = if let [.., bound] = &param.bounds[..] {
3580                            bound.span()
3581                        } else if let GenericParam {
3582                            kind: GenericParamKind::Const { ty, span: _, default },
3583                            ..
3584                        } = param
3585                        {
3586                            default.as_ref().map(|def| def.value.span).unwrap_or(ty.span)
3587                        } else {
3588                            param.ident.span
3589                        };
3590                        (span, ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!(", {0}", sugg))
    })format!(", {sugg}"))
3591                    } else {
3592                        (generics.span, ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("<{0}>", sugg))
    })format!("<{sugg}>"))
3593                    };
3594                    // Do not suggest if this is coming from macro expansion.
3595                    if span.can_be_used_for_suggestions() {
3596                        return (
3597                            Some((span.shrink_to_hi(), msg, sugg, Applicability::MaybeIncorrect)),
3598                            None,
3599                        );
3600                    }
3601                }
3602            }
3603            _ => {}
3604        }
3605        (None, None)
3606    }
3607
3608    /// Given the target `label`, search the `rib_index`th label rib for similarly named labels,
3609    /// optionally returning the closest match and whether it is reachable.
3610    pub(crate) fn suggestion_for_label_in_rib(
3611        &self,
3612        rib_index: usize,
3613        label: Ident,
3614    ) -> Option<LabelSuggestion> {
3615        // Are ribs from this `rib_index` within scope?
3616        let within_scope = self.is_label_valid_from_rib(rib_index);
3617
3618        let rib = &self.label_ribs[rib_index];
3619        let names = rib
3620            .bindings
3621            .iter()
3622            .filter(|(id, _)| id.span.eq_ctxt(label.span))
3623            .map(|(id, _)| id.name)
3624            .collect::<Vec<Symbol>>();
3625
3626        find_best_match_for_name(&names, label.name, None).map(|symbol| {
3627            // Upon finding a similar name, get the ident that it was from - the span
3628            // contained within helps make a useful diagnostic. In addition, determine
3629            // whether this candidate is within scope.
3630            let (ident, _) = rib.bindings.iter().find(|(ident, _)| ident.name == symbol).unwrap();
3631            (*ident, within_scope)
3632        })
3633    }
3634
3635    pub(crate) fn maybe_report_lifetime_uses(
3636        &mut self,
3637        generics_span: Span,
3638        params: &[ast::GenericParam],
3639    ) {
3640        for (param_index, param) in params.iter().enumerate() {
3641            let GenericParamKind::Lifetime = param.kind else { continue };
3642
3643            let def_id = self.r.local_def_id(param.id);
3644
3645            let use_set = self.lifetime_uses.remove(&def_id);
3646            {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event compiler/rustc_resolve/src/late/diagnostics.rs:3646",
                        "rustc_resolve::late::diagnostics", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_resolve/src/late/diagnostics.rs"),
                        ::tracing_core::__macro_support::Option::Some(3646u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_resolve::late::diagnostics"),
                        ::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!("Use set for {0:?}({1:?} at {2:?}) is {3:?}",
                                                    def_id, param.ident, param.ident.span, use_set) as
                                            &dyn ::tracing::field::Value))])
            });
    } else { ; }
};debug!(
3647                "Use set for {:?}({:?} at {:?}) is {:?}",
3648                def_id, param.ident, param.ident.span, use_set
3649            );
3650
3651            let deletion_span = || {
3652                if params.len() == 1 {
3653                    // if sole lifetime, remove the entire `<>` brackets
3654                    Some(generics_span)
3655                } else if param_index == 0 {
3656                    // if removing within `<>` brackets, we also want to
3657                    // delete a leading or trailing comma as appropriate
3658                    match (
3659                        param.span().find_ancestor_inside(generics_span),
3660                        params[param_index + 1].span().find_ancestor_inside(generics_span),
3661                    ) {
3662                        (Some(param_span), Some(next_param_span)) => {
3663                            Some(param_span.to(next_param_span.shrink_to_lo()))
3664                        }
3665                        _ => None,
3666                    }
3667                } else {
3668                    // if removing within `<>` brackets, we also want to
3669                    // delete a leading or trailing comma as appropriate
3670                    match (
3671                        param.span().find_ancestor_inside(generics_span),
3672                        params[param_index - 1].span().find_ancestor_inside(generics_span),
3673                    ) {
3674                        (Some(param_span), Some(prev_param_span)) => {
3675                            Some(prev_param_span.shrink_to_hi().to(param_span))
3676                        }
3677                        _ => None,
3678                    }
3679                }
3680            };
3681            match use_set {
3682                Some(LifetimeUseSet::Many) => {}
3683                // A lifetime bound is a real use of that lifetime parameter, even
3684                // though visiting a bound like `'b: 'a` only records a use of `'a`.
3685                Some(LifetimeUseSet::One { .. }) if !param.bounds.is_empty() => {}
3686                Some(LifetimeUseSet::One { use_span, use_ctxt }) => {
3687                    let param_ident = param.ident;
3688                    let deletion_span =
3689                        if param.bounds.is_empty() { deletion_span() } else { None };
3690                    self.r.lint_buffer.dyn_buffer_lint_any(
3691                        lint::builtin::SINGLE_USE_LIFETIMES,
3692                        param.id,
3693                        param_ident.span,
3694                        move |dcx, level, sess| {
3695                            {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event compiler/rustc_resolve/src/late/diagnostics.rs:3695",
                        "rustc_resolve::late::diagnostics", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_resolve/src/late/diagnostics.rs"),
                        ::tracing_core::__macro_support::Option::Some(3695u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_resolve::late::diagnostics"),
                        ::tracing_core::field::FieldSet::new(&[{
                                            const NAME:
                                                ::tracing::__macro_support::FieldName<{
                                                    ::tracing::__macro_support::FieldName::len("param_ident")
                                                }> =
                                                ::tracing::__macro_support::FieldName::new("param_ident");
                                            NAME.as_str()
                                        },
                                        {
                                            const NAME:
                                                ::tracing::__macro_support::FieldName<{
                                                    ::tracing::__macro_support::FieldName::len("param_ident.span")
                                                }> =
                                                ::tracing::__macro_support::FieldName::new("param_ident.span");
                                            NAME.as_str()
                                        },
                                        {
                                            const NAME:
                                                ::tracing::__macro_support::FieldName<{
                                                    ::tracing::__macro_support::FieldName::len("use_span")
                                                }> =
                                                ::tracing::__macro_support::FieldName::new("use_span");
                                            NAME.as_str()
                                        }], ::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(&::tracing::field::debug(&param_ident)
                                            as &dyn ::tracing::field::Value)),
                                (::tracing::__macro_support::Option::Some(&::tracing::field::debug(&param_ident.span)
                                            as &dyn ::tracing::field::Value)),
                                (::tracing::__macro_support::Option::Some(&::tracing::field::debug(&use_span)
                                            as &dyn ::tracing::field::Value))])
            });
    } else { ; }
};debug!(?param_ident, ?param_ident.span, ?use_span);
3696
3697                            let elidable = #[allow(non_exhaustive_omitted_patterns)] match use_ctxt {
    LifetimeCtxt::Ref => true,
    _ => false,
}matches!(use_ctxt, LifetimeCtxt::Ref);
3698                            let suggestion = if let Some(deletion_span) = deletion_span {
3699                                let (use_span, replace_lt) = if elidable {
3700                                    let use_span = sess
3701                                        .downcast_ref::<Session>()
3702                                        .expect("expected a `Session`")
3703                                        .source_map()
3704                                        .span_extend_while_whitespace(use_span);
3705                                    (use_span, String::new())
3706                                } else {
3707                                    (use_span, "'_".to_owned())
3708                                };
3709                                {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event compiler/rustc_resolve/src/late/diagnostics.rs:3709",
                        "rustc_resolve::late::diagnostics", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_resolve/src/late/diagnostics.rs"),
                        ::tracing_core::__macro_support::Option::Some(3709u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_resolve::late::diagnostics"),
                        ::tracing_core::field::FieldSet::new(&[{
                                            const NAME:
                                                ::tracing::__macro_support::FieldName<{
                                                    ::tracing::__macro_support::FieldName::len("deletion_span")
                                                }> =
                                                ::tracing::__macro_support::FieldName::new("deletion_span");
                                            NAME.as_str()
                                        },
                                        {
                                            const NAME:
                                                ::tracing::__macro_support::FieldName<{
                                                    ::tracing::__macro_support::FieldName::len("use_span")
                                                }> =
                                                ::tracing::__macro_support::FieldName::new("use_span");
                                            NAME.as_str()
                                        }], ::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(&::tracing::field::debug(&deletion_span)
                                            as &dyn ::tracing::field::Value)),
                                (::tracing::__macro_support::Option::Some(&::tracing::field::debug(&use_span)
                                            as &dyn ::tracing::field::Value))])
            });
    } else { ; }
};debug!(?deletion_span, ?use_span);
3710
3711                                // issue 107998 for the case such as a wrong function pointer type
3712                                // `deletion_span` is empty and there is no need to report lifetime uses here
3713                                let deletion_span = if deletion_span.is_empty() {
3714                                    None
3715                                } else {
3716                                    Some(deletion_span)
3717                                };
3718                                Some(diagnostics::SingleUseLifetimeSugg {
3719                                    deletion_span,
3720                                    use_span,
3721                                    replace_lt,
3722                                })
3723                            } else {
3724                                None
3725                            };
3726                            diagnostics::SingleUseLifetime {
3727                                suggestion,
3728                                param_span: param_ident.span,
3729                                use_span,
3730                                ident: param_ident,
3731                            }
3732                            .into_diag(dcx, level)
3733                        },
3734                    );
3735                }
3736                None => {
3737                    {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event compiler/rustc_resolve/src/late/diagnostics.rs:3737",
                        "rustc_resolve::late::diagnostics", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_resolve/src/late/diagnostics.rs"),
                        ::tracing_core::__macro_support::Option::Some(3737u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_resolve::late::diagnostics"),
                        ::tracing_core::field::FieldSet::new(&[{
                                            const NAME:
                                                ::tracing::__macro_support::FieldName<{
                                                    ::tracing::__macro_support::FieldName::len("param.ident")
                                                }> =
                                                ::tracing::__macro_support::FieldName::new("param.ident");
                                            NAME.as_str()
                                        },
                                        {
                                            const NAME:
                                                ::tracing::__macro_support::FieldName<{
                                                    ::tracing::__macro_support::FieldName::len("param.ident.span")
                                                }> =
                                                ::tracing::__macro_support::FieldName::new("param.ident.span");
                                            NAME.as_str()
                                        }], ::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(&::tracing::field::debug(&param.ident)
                                            as &dyn ::tracing::field::Value)),
                                (::tracing::__macro_support::Option::Some(&::tracing::field::debug(&param.ident.span)
                                            as &dyn ::tracing::field::Value))])
            });
    } else { ; }
};debug!(?param.ident, ?param.ident.span);
3738                    let deletion_span = deletion_span();
3739
3740                    // if the lifetime originates from expanded code, we won't be able to remove it #104432
3741                    if deletion_span.is_some_and(|sp| !sp.in_derive_expansion()) {
3742                        self.r.lint_buffer.buffer_lint(
3743                            lint::builtin::UNUSED_LIFETIMES,
3744                            param.id,
3745                            param.ident.span,
3746                            diagnostics::UnusedLifetime { deletion_span, ident: param.ident },
3747                        );
3748                    }
3749                }
3750            }
3751        }
3752    }
3753
3754    pub(crate) fn emit_undeclared_lifetime_error(
3755        &self,
3756        lifetime_ref: &ast::Lifetime,
3757        outer_lifetime_ref: Option<Ident>,
3758    ) -> ErrorGuaranteed {
3759        if true {
    {
        match (&lifetime_ref.ident.name, &kw::UnderscoreLifetime) {
            (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);
                }
            }
        }
    };
};debug_assert_ne!(lifetime_ref.ident.name, kw::UnderscoreLifetime);
3760        let mut err = if let Some(outer) = outer_lifetime_ref {
3761            {
    self.r.dcx().struct_span_err(lifetime_ref.ident.span,
            ::alloc::__export::must_use({
                    ::alloc::fmt::format(format_args!("can\'t use generic parameters from outer item"))
                })).with_code(E0401)
}struct_span_code_err!(
3762                self.r.dcx(),
3763                lifetime_ref.ident.span,
3764                E0401,
3765                "can't use generic parameters from outer item",
3766            )
3767            .with_span_label(lifetime_ref.ident.span, "use of generic parameter from outer item")
3768            .with_span_label(outer.span, "lifetime parameter from outer item")
3769        } else {
3770            {
    self.r.dcx().struct_span_err(lifetime_ref.ident.span,
            ::alloc::__export::must_use({
                    ::alloc::fmt::format(format_args!("use of undeclared lifetime name `{0}`",
                            lifetime_ref.ident))
                })).with_code(E0261)
}struct_span_code_err!(
3771                self.r.dcx(),
3772                lifetime_ref.ident.span,
3773                E0261,
3774                "use of undeclared lifetime name `{}`",
3775                lifetime_ref.ident
3776            )
3777            .with_span_label(lifetime_ref.ident.span, "undeclared lifetime")
3778        };
3779
3780        // Check if this is a typo of `'static`.
3781        if edit_distance(lifetime_ref.ident.name.as_str(), "'static", 2).is_some() {
3782            err.span_suggestion_verbose(
3783                lifetime_ref.ident.span,
3784                "you may have misspelled the `'static` lifetime",
3785                "'static",
3786                Applicability::MachineApplicable,
3787            );
3788        } else {
3789            self.suggest_introducing_lifetime(
3790                &mut err,
3791                Some(lifetime_ref.ident),
3792                |err, _, span, message, suggestion, span_suggs| {
3793                    err.multipart_suggestion(
3794                        message,
3795                        std::iter::once((span, suggestion)).chain(span_suggs).collect(),
3796                        Applicability::MaybeIncorrect,
3797                    );
3798                    true
3799                },
3800            );
3801        }
3802
3803        err.emit()
3804    }
3805
3806    fn suggest_introducing_lifetime(
3807        &self,
3808        err: &mut Diag<'_>,
3809        name: Option<Ident>,
3810        suggest: impl Fn(
3811            &mut Diag<'_>,
3812            bool,
3813            Span,
3814            Cow<'static, str>,
3815            String,
3816            Vec<(Span, String)>,
3817        ) -> bool,
3818    ) {
3819        self.suggest_introducing_lifetime_filtered(err, name, |_| true, suggest);
3820    }
3821
3822    pub(crate) fn suggest_introducing_lifetime_for_assoc_ty_binding(
3823        &self,
3824        err: &mut Diag<'_>,
3825        lifetime: Span,
3826    ) {
3827        self.suggest_introducing_lifetime_filtered(
3828            err,
3829            None,
3830            |kind| {
3831                !#[allow(non_exhaustive_omitted_patterns)] match kind {
    LifetimeBinderKind::FnPtrType | LifetimeBinderKind::PolyTrait |
        LifetimeBinderKind::WhereBound => true,
    _ => false,
}matches!(
3832                    kind,
3833                    LifetimeBinderKind::FnPtrType
3834                        | LifetimeBinderKind::PolyTrait
3835                        | LifetimeBinderKind::WhereBound
3836                )
3837            },
3838            |err, _higher_ranked, span, message, intro_sugg, _| {
3839                err.multipart_suggestion(
3840                    message,
3841                    ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
        [(span, intro_sugg), (lifetime.shrink_to_hi(), "'a ".to_string())]))vec![(span, intro_sugg), (lifetime.shrink_to_hi(), "'a ".to_string())],
3842                    Applicability::MaybeIncorrect,
3843                );
3844                false
3845            },
3846        );
3847    }
3848
3849    fn suggest_introducing_lifetime_filtered(
3850        &self,
3851        err: &mut Diag<'_>,
3852        name: Option<Ident>,
3853        mut consider: impl FnMut(LifetimeBinderKind) -> bool,
3854        suggest: impl Fn(
3855            &mut Diag<'_>,
3856            bool,
3857            Span,
3858            Cow<'static, str>,
3859            String,
3860            Vec<(Span, String)>,
3861        ) -> bool,
3862    ) {
3863        let mut suggest_note = true;
3864        for rib in self.lifetime_ribs.iter().rev() {
3865            let mut should_continue = true;
3866            match rib.kind {
3867                LifetimeRibKind::Generics { binder, span, kind } => {
3868                    // Avoid suggesting placing lifetime parameters on constant items unless the relevant
3869                    // feature is enabled. Suggest the parent item as a possible location if applicable.
3870                    if let LifetimeBinderKind::ConstItem = kind
3871                        && !self.r.tcx().features().generic_const_items()
3872                    {
3873                        continue;
3874                    }
3875                    if #[allow(non_exhaustive_omitted_patterns)] match kind {
    LifetimeBinderKind::ImplAssocType => true,
    _ => false,
}matches!(kind, LifetimeBinderKind::ImplAssocType) || !consider(kind) {
3876                        continue;
3877                    }
3878
3879                    if !span.can_be_used_for_suggestions()
3880                        && suggest_note
3881                        && let Some(name) = name
3882                    {
3883                        suggest_note = false; // Avoid displaying the same help multiple times.
3884                        err.span_label(
3885                            span,
3886                            ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("lifetime `{0}` is missing in item created through this procedural macro",
                name))
    })format!(
3887                                "lifetime `{name}` is missing in item created through this procedural macro",
3888                            ),
3889                        );
3890                        continue;
3891                    }
3892
3893                    let higher_ranked = #[allow(non_exhaustive_omitted_patterns)] match kind {
    LifetimeBinderKind::FnPtrType | LifetimeBinderKind::PolyTrait |
        LifetimeBinderKind::WhereBound => true,
    _ => false,
}matches!(
3894                        kind,
3895                        LifetimeBinderKind::FnPtrType
3896                            | LifetimeBinderKind::PolyTrait
3897                            | LifetimeBinderKind::WhereBound
3898                    );
3899
3900                    let mut rm_inner_binders: FxIndexSet<Span> = Default::default();
3901                    let (span, sugg) = if span.is_empty() {
3902                        let mut binder_idents: FxIndexSet<Ident> = Default::default();
3903                        binder_idents.insert(name.unwrap_or(Ident::from_str("'a")));
3904
3905                        // We need to special case binders in the following situation:
3906                        // Change `T: for<'a> Trait<T> + 'b` to `for<'a, 'b> T: Trait<T> + 'b`
3907                        // T: for<'a> Trait<T> + 'b
3908                        //    ^^^^^^^  remove existing inner binder `for<'a>`
3909                        // for<'a, 'b> T: Trait<T> + 'b
3910                        // ^^^^^^^^^^^  suggest outer binder `for<'a, 'b>`
3911                        if let LifetimeBinderKind::WhereBound = kind
3912                            && let Some(predicate) = self.diag_metadata.current_where_predicate
3913                            && let ast::WherePredicateKind::BoundPredicate(
3914                                ast::WhereBoundPredicate { bounded_ty, bounds, .. },
3915                            ) = &predicate.kind
3916                            && bounded_ty.id == binder
3917                        {
3918                            for bound in bounds {
3919                                if let ast::GenericBound::Trait(poly_trait_ref) = bound
3920                                    && let span = poly_trait_ref
3921                                        .span
3922                                        .with_hi(poly_trait_ref.trait_ref.path.span.lo())
3923                                    && !span.is_empty()
3924                                {
3925                                    rm_inner_binders.insert(span);
3926                                    poly_trait_ref.bound_generic_params.iter().for_each(|v| {
3927                                        binder_idents.insert(v.ident);
3928                                    });
3929                                }
3930                            }
3931                        }
3932
3933                        let binders_sugg: String = binder_idents
3934                            .into_iter()
3935                            .map(|ident| ident.to_string())
3936                            .intersperse(", ".to_owned())
3937                            .collect();
3938                        let sugg = ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("{0}<{1}>{2}",
                if higher_ranked { "for" } else { "" }, binders_sugg,
                if higher_ranked { " " } else { "" }))
    })format!(
3939                            "{}<{}>{}",
3940                            if higher_ranked { "for" } else { "" },
3941                            binders_sugg,
3942                            if higher_ranked { " " } else { "" },
3943                        );
3944                        (span, sugg)
3945                    } else {
3946                        let span = self
3947                            .r
3948                            .tcx
3949                            .sess
3950                            .source_map()
3951                            .span_through_char(span, '<')
3952                            .shrink_to_hi();
3953                        let sugg =
3954                            ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("{0}, ",
                name.map(|i| i.to_string()).as_deref().unwrap_or("'a")))
    })format!("{}, ", name.map(|i| i.to_string()).as_deref().unwrap_or("'a"));
3955                        (span, sugg)
3956                    };
3957
3958                    if higher_ranked {
3959                        let message = Cow::from(::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("consider making the {0} lifetime-generic with a new `{1}` lifetime",
                kind.descr(),
                name.map(|i| i.to_string()).as_deref().unwrap_or("'a")))
    })format!(
3960                            "consider making the {} lifetime-generic with a new `{}` lifetime",
3961                            kind.descr(),
3962                            name.map(|i| i.to_string()).as_deref().unwrap_or("'a"),
3963                        ));
3964                        should_continue = suggest(
3965                            err,
3966                            true,
3967                            span,
3968                            message,
3969                            sugg,
3970                            if !rm_inner_binders.is_empty() {
3971                                rm_inner_binders
3972                                    .into_iter()
3973                                    .map(|v| (v, "".to_string()))
3974                                    .collect::<Vec<_>>()
3975                            } else {
3976                                ::alloc::vec::Vec::new()vec![]
3977                            },
3978                        );
3979                        err.note_once(
3980                            "for more information on higher-ranked polymorphism, visit \
3981                             https://doc.rust-lang.org/nomicon/hrtb.html",
3982                        );
3983                    } else if let Some(name) = name {
3984                        let message =
3985                            Cow::from(::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("consider introducing lifetime `{0}` here",
                name))
    })format!("consider introducing lifetime `{name}` here"));
3986                        should_continue = suggest(err, false, span, message, sugg, ::alloc::vec::Vec::new()vec![]);
3987                    } else {
3988                        let message = Cow::from("consider introducing a named lifetime parameter");
3989                        should_continue = suggest(err, false, span, message, sugg, ::alloc::vec::Vec::new()vec![]);
3990                    }
3991                }
3992                LifetimeRibKind::Item | LifetimeRibKind::ConstParamTy => break,
3993                _ => {}
3994            }
3995            if !should_continue {
3996                break;
3997            }
3998        }
3999    }
4000
4001    pub(crate) fn emit_non_static_lt_in_const_param_ty_error(
4002        &self,
4003        lifetime_ref: &ast::Lifetime,
4004    ) -> ErrorGuaranteed {
4005        self.r
4006            .dcx()
4007            .create_err(diagnostics::ParamInTyOfConstParam {
4008                span: lifetime_ref.ident.span,
4009                name: lifetime_ref.ident.name,
4010            })
4011            .emit()
4012    }
4013
4014    /// Non-static lifetimes are prohibited in anonymous constants under `min_const_generics`.
4015    /// This function will emit an error if `generic_const_exprs` is not enabled, the body identified by
4016    /// `body_id` is an anonymous constant and `lifetime_ref` is non-static.
4017    pub(crate) fn emit_forbidden_non_static_lifetime_error(
4018        &self,
4019        cause: NoConstantGenericsReason,
4020        lifetime_ref: &ast::Lifetime,
4021    ) -> ErrorGuaranteed {
4022        match cause {
4023            NoConstantGenericsReason::IsEnumDiscriminant => self
4024                .r
4025                .dcx()
4026                .create_err(diagnostics::ParamInEnumDiscriminant {
4027                    span: lifetime_ref.ident.span,
4028                    name: lifetime_ref.ident.name,
4029                    param_kind: diagnostics::ParamKindInEnumDiscriminant::Lifetime,
4030                })
4031                .emit(),
4032            NoConstantGenericsReason::NonTrivialConstArg => {
4033                if !!self.r.features.generic_const_exprs() {
    ::core::panicking::panic("assertion failed: !self.r.features.generic_const_exprs()")
};assert!(!self.r.features.generic_const_exprs());
4034                self.r
4035                    .dcx()
4036                    .create_err(diagnostics::ParamInNonTrivialAnonConst {
4037                        span: lifetime_ref.ident.span,
4038                        name: lifetime_ref.ident.name,
4039                        param_kind: diagnostics::ParamKindInNonTrivialAnonConst::Lifetime,
4040                        help: self.r.tcx.sess.is_nightly_build()
4041                            && !self.r.features.min_generic_const_args(),
4042                        is_gca: self.r.features.generic_const_args(),
4043                        help_gca: self.r.features.generic_const_args(),
4044                        help_suggest_gca: self.r.tcx.sess.is_nightly_build()
4045                            && !self.r.features.generic_const_args(),
4046                    })
4047                    .emit()
4048            }
4049        }
4050    }
4051
4052    pub(crate) fn report_missing_lifetime_specifiers<'a>(
4053        &mut self,
4054        lifetime_refs: impl Clone + IntoIterator<Item = &'a MissingLifetime>,
4055        function_param_lifetimes: Option<(Vec<MissingLifetime>, Vec<ElisionFnParameter>)>,
4056    ) -> ErrorGuaranteed {
4057        let num_lifetimes: usize = lifetime_refs.clone().into_iter().map(|lt| lt.count).sum();
4058        let spans: Vec<_> = lifetime_refs.clone().into_iter().map(|lt| lt.span).collect();
4059
4060        let mut err = {
    self.r.dcx().struct_span_err(spans,
            ::alloc::__export::must_use({
                    ::alloc::fmt::format(format_args!("missing lifetime specifier{0}",
                            if num_lifetimes == 1 { "" } else { "s" }))
                })).with_code(E0106)
}struct_span_code_err!(
4061            self.r.dcx(),
4062            spans,
4063            E0106,
4064            "missing lifetime specifier{}",
4065            pluralize!(num_lifetimes)
4066        );
4067        self.add_missing_lifetime_specifiers_label(
4068            &mut err,
4069            lifetime_refs,
4070            function_param_lifetimes,
4071        );
4072        err.emit()
4073    }
4074
4075    fn add_missing_lifetime_specifiers_label<'a>(
4076        &mut self,
4077        err: &mut Diag<'_>,
4078        lifetime_refs: impl Clone + IntoIterator<Item = &'a MissingLifetime>,
4079        function_param_lifetimes: Option<(Vec<MissingLifetime>, Vec<ElisionFnParameter>)>,
4080    ) {
4081        for &lt in lifetime_refs.clone() {
4082            err.span_label(
4083                lt.span,
4084                ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("expected {0} lifetime parameter{1}",
                if lt.count == 1 {
                    "named".to_string()
                } else { lt.count.to_string() },
                if lt.count == 1 { "" } else { "s" }))
    })format!(
4085                    "expected {} lifetime parameter{}",
4086                    if lt.count == 1 { "named".to_string() } else { lt.count.to_string() },
4087                    pluralize!(lt.count),
4088                ),
4089            );
4090        }
4091
4092        let mut in_scope_lifetimes: Vec<_> = self
4093            .lifetime_ribs
4094            .iter()
4095            .rev()
4096            .take_while(|rib| {
4097                !#[allow(non_exhaustive_omitted_patterns)] match rib.kind {
    LifetimeRibKind::Item | LifetimeRibKind::ConstParamTy => true,
    _ => false,
}matches!(rib.kind, LifetimeRibKind::Item | LifetimeRibKind::ConstParamTy)
4098            })
4099            .flat_map(|rib| rib.bindings.iter())
4100            .map(|(&ident, &res)| (ident, res))
4101            .filter(|(ident, _)| ident.name != kw::UnderscoreLifetime)
4102            .collect();
4103        {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event compiler/rustc_resolve/src/late/diagnostics.rs:4103",
                        "rustc_resolve::late::diagnostics", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_resolve/src/late/diagnostics.rs"),
                        ::tracing_core::__macro_support::Option::Some(4103u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_resolve::late::diagnostics"),
                        ::tracing_core::field::FieldSet::new(&[{
                                            const NAME:
                                                ::tracing::__macro_support::FieldName<{
                                                    ::tracing::__macro_support::FieldName::len("in_scope_lifetimes")
                                                }> =
                                                ::tracing::__macro_support::FieldName::new("in_scope_lifetimes");
                                            NAME.as_str()
                                        }], ::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(&::tracing::field::debug(&in_scope_lifetimes)
                                            as &dyn ::tracing::field::Value))])
            });
    } else { ; }
};debug!(?in_scope_lifetimes);
4104
4105        let mut maybe_static = false;
4106        {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event compiler/rustc_resolve/src/late/diagnostics.rs:4106",
                        "rustc_resolve::late::diagnostics", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_resolve/src/late/diagnostics.rs"),
                        ::tracing_core::__macro_support::Option::Some(4106u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_resolve::late::diagnostics"),
                        ::tracing_core::field::FieldSet::new(&[{
                                            const NAME:
                                                ::tracing::__macro_support::FieldName<{
                                                    ::tracing::__macro_support::FieldName::len("function_param_lifetimes")
                                                }> =
                                                ::tracing::__macro_support::FieldName::new("function_param_lifetimes");
                                            NAME.as_str()
                                        }], ::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(&::tracing::field::debug(&function_param_lifetimes)
                                            as &dyn ::tracing::field::Value))])
            });
    } else { ; }
};debug!(?function_param_lifetimes);
4107        if let Some((param_lifetimes, params)) = &function_param_lifetimes {
4108            let elided_len = param_lifetimes.len();
4109            let num_params = params.len();
4110
4111            let mut m = String::new();
4112
4113            for (i, info) in params.iter().enumerate() {
4114                let ElisionFnParameter { ident, index, lifetime_count, span } = *info;
4115                if true {
    {
        match (&lifetime_count, &0) {
            (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);
                }
            }
        }
    };
};debug_assert_ne!(lifetime_count, 0);
4116
4117                err.span_label(span, "");
4118
4119                if i != 0 {
4120                    if i + 1 < num_params {
4121                        m.push_str(", ");
4122                    } else if num_params == 2 {
4123                        m.push_str(" or ");
4124                    } else {
4125                        m.push_str(", or ");
4126                    }
4127                }
4128
4129                let help_name = if let Some(ident) = ident {
4130                    ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("`{0}`", ident))
    })format!("`{ident}`")
4131                } else {
4132                    ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("argument {0}", index + 1))
    })format!("argument {}", index + 1)
4133                };
4134
4135                if lifetime_count == 1 {
4136                    m.push_str(&help_name[..])
4137                } else {
4138                    m.push_str(&::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("one of {0}\'s {1} lifetimes",
                help_name, lifetime_count))
    })format!("one of {help_name}'s {lifetime_count} lifetimes")[..])
4139                }
4140            }
4141
4142            if num_params == 0 {
4143                err.help(
4144                    "this function's return type contains a borrowed value, but there is no value \
4145                     for it to be borrowed from",
4146                );
4147                if in_scope_lifetimes.is_empty() {
4148                    maybe_static = true;
4149                    in_scope_lifetimes = ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
        [(Ident::with_dummy_span(kw::StaticLifetime),
                    (DUMMY_NODE_ID, LifetimeRes::Static))]))vec![(
4150                        Ident::with_dummy_span(kw::StaticLifetime),
4151                        (DUMMY_NODE_ID, LifetimeRes::Static),
4152                    )];
4153                }
4154            } else if elided_len == 0 {
4155                err.help(
4156                    "this function's return type contains a borrowed value with an elided \
4157                     lifetime, but the lifetime cannot be derived from the arguments",
4158                );
4159                if in_scope_lifetimes.is_empty() {
4160                    maybe_static = true;
4161                    in_scope_lifetimes = ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
        [(Ident::with_dummy_span(kw::StaticLifetime),
                    (DUMMY_NODE_ID, LifetimeRes::Static))]))vec![(
4162                        Ident::with_dummy_span(kw::StaticLifetime),
4163                        (DUMMY_NODE_ID, LifetimeRes::Static),
4164                    )];
4165                }
4166            } else if num_params == 1 {
4167                err.help(::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("this function\'s return type contains a borrowed value, but the signature does not say which {0} it is borrowed from",
                m))
    })format!(
4168                    "this function's return type contains a borrowed value, but the signature does \
4169                     not say which {m} it is borrowed from",
4170                ));
4171            } else {
4172                err.help(::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("this function\'s return type contains a borrowed value, but the signature does not say whether it is borrowed from {0}",
                m))
    })format!(
4173                    "this function's return type contains a borrowed value, but the signature does \
4174                     not say whether it is borrowed from {m}",
4175                ));
4176            }
4177        }
4178
4179        #[allow(rustc::symbol_intern_string_literal)]
4180        let existing_name = match &in_scope_lifetimes[..] {
4181            [] => Symbol::intern("'a"),
4182            [(existing, _)] => existing.name,
4183            _ => Symbol::intern("'lifetime"),
4184        };
4185
4186        let mut spans_suggs: Vec<_> = Vec::new();
4187        let source_map = self.r.tcx.sess.source_map();
4188        let build_sugg = |lt: MissingLifetime| match lt.kind {
4189            MissingLifetimeKind::Underscore => {
4190                if true {
    {
        match (&lt.count, &1) {
            (left_val, right_val) => {
                if !(*left_val == *right_val) {
                    let kind = ::core::panicking::AssertKind::Eq;
                    ::core::panicking::assert_failed(kind, &*left_val,
                        &*right_val, ::core::option::Option::None);
                }
            }
        }
    };
};debug_assert_eq!(lt.count, 1);
4191                (lt.span, existing_name.to_string())
4192            }
4193            MissingLifetimeKind::Ampersand => {
4194                if true {
    {
        match (&lt.count, &1) {
            (left_val, right_val) => {
                if !(*left_val == *right_val) {
                    let kind = ::core::panicking::AssertKind::Eq;
                    ::core::panicking::assert_failed(kind, &*left_val,
                        &*right_val, ::core::option::Option::None);
                }
            }
        }
    };
};debug_assert_eq!(lt.count, 1);
4195                (lt.span.shrink_to_hi(), ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("{0} ", existing_name))
    })format!("{existing_name} "))
4196            }
4197            MissingLifetimeKind::Comma => {
4198                let sugg: String = std::iter::repeat_n(existing_name.as_str(), lt.count)
4199                    .intersperse(", ")
4200                    .collect();
4201                let is_empty_brackets = source_map.span_followed_by(lt.span, ">").is_some();
4202                let sugg = if is_empty_brackets { sugg } else { ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("{0}, ", sugg))
    })format!("{sugg}, ") };
4203                (lt.span.shrink_to_hi(), sugg)
4204            }
4205            MissingLifetimeKind::Brackets => {
4206                let sugg: String = std::iter::once("<")
4207                    .chain(std::iter::repeat_n(existing_name.as_str(), lt.count).intersperse(", "))
4208                    .chain([">"])
4209                    .collect();
4210                (lt.span.shrink_to_hi(), sugg)
4211            }
4212        };
4213        for &lt in lifetime_refs.clone() {
4214            spans_suggs.push(build_sugg(lt));
4215        }
4216        {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event compiler/rustc_resolve/src/late/diagnostics.rs:4216",
                        "rustc_resolve::late::diagnostics", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_resolve/src/late/diagnostics.rs"),
                        ::tracing_core::__macro_support::Option::Some(4216u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_resolve::late::diagnostics"),
                        ::tracing_core::field::FieldSet::new(&[{
                                            const NAME:
                                                ::tracing::__macro_support::FieldName<{
                                                    ::tracing::__macro_support::FieldName::len("spans_suggs")
                                                }> =
                                                ::tracing::__macro_support::FieldName::new("spans_suggs");
                                            NAME.as_str()
                                        }], ::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(&::tracing::field::debug(&spans_suggs)
                                            as &dyn ::tracing::field::Value))])
            });
    } else { ; }
};debug!(?spans_suggs);
4217        match in_scope_lifetimes.len() {
4218            0 => {
4219                if let Some((param_lifetimes, _)) = function_param_lifetimes {
4220                    for lt in param_lifetimes {
4221                        spans_suggs.push(build_sugg(lt))
4222                    }
4223                }
4224                self.suggest_introducing_lifetime(
4225                    err,
4226                    None,
4227                    |err, higher_ranked, span, message, intro_sugg, _| {
4228                        err.multipart_suggestion(
4229                            message,
4230                            std::iter::once((span, intro_sugg))
4231                                .chain(spans_suggs.clone())
4232                                .collect(),
4233                            Applicability::MaybeIncorrect,
4234                        );
4235                        higher_ranked
4236                    },
4237                );
4238            }
4239            1 => {
4240                let post = if maybe_static {
4241                    let mut lifetime_refs = lifetime_refs.clone().into_iter();
4242                    let owned = if let Some(lt) = lifetime_refs.next()
4243                        && lifetime_refs.next().is_none()
4244                        && lt.kind != MissingLifetimeKind::Ampersand
4245                    {
4246                        ", or if you will only have owned values"
4247                    } else {
4248                        ""
4249                    };
4250                    ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!(", but this is uncommon unless you\'re returning a borrowed value from a `const` or a `static`{0}",
                owned))
    })format!(
4251                        ", but this is uncommon unless you're returning a borrowed value from a \
4252                         `const` or a `static`{owned}",
4253                    )
4254                } else {
4255                    String::new()
4256                };
4257                err.multipart_suggestion(
4258                    ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("consider using the `{0}` lifetime{1}",
                existing_name, post))
    })format!("consider using the `{existing_name}` lifetime{post}"),
4259                    spans_suggs,
4260                    Applicability::MaybeIncorrect,
4261                );
4262                if maybe_static {
4263                    // FIXME: what follows are general suggestions, but we'd want to perform some
4264                    // minimal flow analysis to provide more accurate suggestions. For example, if
4265                    // we identified that the return expression references only one argument, we
4266                    // would suggest borrowing only that argument, and we'd skip the prior
4267                    // "use `'static`" suggestion entirely.
4268                    let mut lifetime_refs = lifetime_refs.clone().into_iter();
4269                    if let Some(lt) = lifetime_refs.next()
4270                        && lifetime_refs.next().is_none()
4271                        && (lt.kind == MissingLifetimeKind::Ampersand
4272                            || lt.kind == MissingLifetimeKind::Underscore)
4273                    {
4274                        let pre = if let Some((kind, _span)) = self.diag_metadata.current_function
4275                            && let FnKind::Fn(_, _, ast::Fn { sig, .. }) = kind
4276                            && !sig.decl.inputs.is_empty()
4277                            && let sugg = sig
4278                                .decl
4279                                .inputs
4280                                .iter()
4281                                .filter_map(|param| {
4282                                    if param.ty.span.contains(lt.span) {
4283                                        // We don't want to suggest `fn elision(_: &fn() -> &i32)`
4284                                        // when we have `fn elision(_: fn() -> &i32)`
4285                                        None
4286                                    } else if let TyKind::CVarArgs = param.ty.kind {
4287                                        // Don't suggest `&...` for ffi fn with varargs
4288                                        None
4289                                    } else if let TyKind::ImplTrait(..) = &param.ty.kind {
4290                                        // We handle these in the next `else if` branch.
4291                                        None
4292                                    } else {
4293                                        Some((param.ty.span.shrink_to_lo(), "&".to_string()))
4294                                    }
4295                                })
4296                                .collect::<Vec<_>>()
4297                            && !sugg.is_empty()
4298                        {
4299                            let (the, s) = if sig.decl.inputs.len() == 1 {
4300                                ("the", "")
4301                            } else {
4302                                ("one of the", "s")
4303                            };
4304                            let dotdotdot =
4305                                if lt.kind == MissingLifetimeKind::Ampersand { "..." } else { "" };
4306                            err.multipart_suggestion(
4307                                ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("instead, you are more likely to want to change {0} argument{1} to be borrowed{2}",
                the, s, dotdotdot))
    })format!(
4308                                    "instead, you are more likely to want to change {the} \
4309                                     argument{s} to be borrowed{dotdotdot}",
4310                                ),
4311                                sugg,
4312                                Applicability::MaybeIncorrect,
4313                            );
4314                            "...or alternatively, you might want"
4315                        } else if (lt.kind == MissingLifetimeKind::Ampersand
4316                            || lt.kind == MissingLifetimeKind::Underscore)
4317                            && let Some((kind, _span)) = self.diag_metadata.current_function
4318                            && let FnKind::Fn(_, _, ast::Fn { sig, .. }) = kind
4319                            && let ast::FnRetTy::Ty(ret_ty) = &sig.decl.output
4320                            && !sig.decl.inputs.is_empty()
4321                            && let arg_refs = sig
4322                                .decl
4323                                .inputs
4324                                .iter()
4325                                .filter_map(|param| match &param.ty.kind {
4326                                    TyKind::ImplTrait(_, bounds) => Some(bounds),
4327                                    _ => None,
4328                                })
4329                                .flat_map(|bounds| bounds.into_iter())
4330                                .collect::<Vec<_>>()
4331                            && !arg_refs.is_empty()
4332                        {
4333                            // We have a situation like
4334                            // fn g(mut x: impl Iterator<Item = &()>) -> Option<&()>
4335                            // So we look at every ref in the trait bound. If there's any, we
4336                            // suggest
4337                            // fn g<'a>(mut x: impl Iterator<Item = &'a ()>) -> Option<&'a ()>
4338                            let mut lt_finder =
4339                                LifetimeFinder { lifetime: lt.span, found: None, seen: ::alloc::vec::Vec::new()vec![] };
4340                            for bound in arg_refs {
4341                                if let ast::GenericBound::Trait(trait_ref) = bound {
4342                                    lt_finder.visit_trait_ref(&trait_ref.trait_ref);
4343                                }
4344                            }
4345                            lt_finder.visit_ty(ret_ty);
4346                            let spans_suggs: Vec<_> = lt_finder
4347                                .seen
4348                                .iter()
4349                                .filter_map(|ty| match &ty.kind {
4350                                    TyKind::Ref(_, mut_ty) => {
4351                                        let span = ty.span.with_hi(mut_ty.ty.span.lo());
4352                                        Some((span, "&'a ".to_string()))
4353                                    }
4354                                    _ => None,
4355                                })
4356                                .collect();
4357                            self.suggest_introducing_lifetime(
4358                                err,
4359                                None,
4360                                |err, higher_ranked, span, message, intro_sugg, _| {
4361                                    err.multipart_suggestion(
4362                                        message,
4363                                        std::iter::once((span, intro_sugg))
4364                                            .chain(spans_suggs.clone())
4365                                            .collect(),
4366                                        Applicability::MaybeIncorrect,
4367                                    );
4368                                    higher_ranked
4369                                },
4370                            );
4371                            "alternatively, you might want"
4372                        } else {
4373                            "instead, you are more likely to want"
4374                        };
4375                        let mut owned_sugg = lt.kind == MissingLifetimeKind::Ampersand;
4376                        let mut sugg_slice_to_vec_or_string = false;
4377                        let mut sugg = ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
        [(lt.span, String::new())]))vec![(lt.span, String::new())];
4378                        if let Some((kind, _span)) = self.diag_metadata.current_function
4379                            && let FnKind::Fn(_, _, ast::Fn { sig, .. }) = kind
4380                        {
4381                            let mut lt_finder =
4382                                LifetimeFinder { lifetime: lt.span, found: None, seen: ::alloc::vec::Vec::new()vec![] };
4383                            for param in &sig.decl.inputs {
4384                                lt_finder.visit_ty(&param.ty);
4385                            }
4386                            if let ast::FnRetTy::Ty(ret_ty) = &sig.decl.output {
4387                                lt_finder.visit_ty(ret_ty);
4388                                let mut ret_lt_finder =
4389                                    LifetimeFinder { lifetime: lt.span, found: None, seen: ::alloc::vec::Vec::new()vec![] };
4390                                ret_lt_finder.visit_ty(ret_ty);
4391                                if let [Ty { span, kind: TyKind::Ref(_, mut_ty), .. }] =
4392                                    &ret_lt_finder.seen[..]
4393                                {
4394                                    // We might have a situation like
4395                                    // fn g(mut x: impl Iterator<Item = &'_ ()>) -> Option<&'_ ()>
4396                                    // but `lt.span` only points at `'_`, so to suggest `-> Option<()>`
4397                                    // we need to find a more accurate span to end up with
4398                                    // fn g<'a>(mut x: impl Iterator<Item = &'_ ()>) -> Option<()>
4399                                    sugg = ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
        [(span.with_hi(mut_ty.ty.span.lo()), String::new())]))vec![(span.with_hi(mut_ty.ty.span.lo()), String::new())];
4400                                    owned_sugg = true;
4401                                }
4402                            }
4403                            if let Some(ty) = lt_finder.found {
4404                                if let TyKind::Path(None, path) = &ty.kind {
4405                                    // Check if the path being borrowed is likely to be owned.
4406                                    let path: Vec<_> = Segment::from_path(path);
4407                                    match self.resolve_path(
4408                                        &path,
4409                                        Some(TypeNS),
4410                                        None,
4411                                        PathSource::Type,
4412                                    ) {
4413                                        PathResult::Module(ModuleOrUniformRoot::Module(module)) => {
4414                                            match module.res() {
4415                                                Some(Res::PrimTy(PrimTy::Str)) => {
4416                                                    // Don't suggest `-> str`, suggest `-> String`.
4417                                                    sugg = ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
        [(lt.span.with_hi(ty.span.hi()), "String".to_string())]))vec![(
4418                                                        lt.span.with_hi(ty.span.hi()),
4419                                                        "String".to_string(),
4420                                                    )];
4421                                                    sugg_slice_to_vec_or_string = true;
4422                                                }
4423                                                Some(Res::PrimTy(..)) => {}
4424                                                Some(Res::Def(
4425                                                    DefKind::Struct
4426                                                    | DefKind::Union
4427                                                    | DefKind::Enum
4428                                                    | DefKind::ForeignTy
4429                                                    | DefKind::AssocTy
4430                                                    | DefKind::OpaqueTy
4431                                                    | DefKind::TyParam,
4432                                                    _,
4433                                                )) => {}
4434                                                _ => {
4435                                                    // Do not suggest in all other cases.
4436                                                    owned_sugg = false;
4437                                                }
4438                                            }
4439                                        }
4440                                        PathResult::NonModule(res) => {
4441                                            match res.base_res() {
4442                                                Res::PrimTy(PrimTy::Str) => {
4443                                                    // Don't suggest `-> str`, suggest `-> String`.
4444                                                    sugg = ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
        [(lt.span.with_hi(ty.span.hi()), "String".to_string())]))vec![(
4445                                                        lt.span.with_hi(ty.span.hi()),
4446                                                        "String".to_string(),
4447                                                    )];
4448                                                    sugg_slice_to_vec_or_string = true;
4449                                                }
4450                                                Res::PrimTy(..) => {}
4451                                                Res::Def(
4452                                                    DefKind::Struct
4453                                                    | DefKind::Union
4454                                                    | DefKind::Enum
4455                                                    | DefKind::ForeignTy
4456                                                    | DefKind::AssocTy
4457                                                    | DefKind::OpaqueTy
4458                                                    | DefKind::TyParam,
4459                                                    _,
4460                                                ) => {}
4461                                                _ => {
4462                                                    // Do not suggest in all other cases.
4463                                                    owned_sugg = false;
4464                                                }
4465                                            }
4466                                        }
4467                                        _ => {
4468                                            // Do not suggest in all other cases.
4469                                            owned_sugg = false;
4470                                        }
4471                                    }
4472                                }
4473                                if let TyKind::Slice(inner_ty) = &ty.kind {
4474                                    // Don't suggest `-> [T]`, suggest `-> Vec<T>`.
4475                                    sugg = ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
        [(lt.span.with_hi(inner_ty.span.lo()), "Vec<".to_string()),
                (ty.span.with_lo(inner_ty.span.hi()), ">".to_string())]))vec![
4476                                        (lt.span.with_hi(inner_ty.span.lo()), "Vec<".to_string()),
4477                                        (ty.span.with_lo(inner_ty.span.hi()), ">".to_string()),
4478                                    ];
4479                                    sugg_slice_to_vec_or_string = true;
4480                                }
4481                            }
4482                        }
4483                        if owned_sugg {
4484                            // Suggest to remove the ref prefix (usually an &) from the return type.
4485                            if let Some(span) =
4486                                self.find_ref_prefix_span_for_owned_suggestion(lt.span)
4487                                && !sugg_slice_to_vec_or_string
4488                            {
4489                                sugg = ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
        [(span, String::new())]))vec![(span, String::new())];
4490                            }
4491                            err.multipart_suggestion(
4492                                ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("{0} to return an owned value",
                pre))
    })format!("{pre} to return an owned value"),
4493                                sugg,
4494                                Applicability::MaybeIncorrect,
4495                            );
4496                        }
4497                    }
4498                }
4499            }
4500            _ => {
4501                let lifetime_spans: Vec<_> =
4502                    in_scope_lifetimes.iter().map(|(ident, _)| ident.span).collect();
4503                err.span_note(lifetime_spans, "these named lifetimes are available to use");
4504
4505                if spans_suggs.len() > 0 {
4506                    // This happens when we have `Foo<T>` where we point at the space before `T`,
4507                    // but this can be confusing so we give a suggestion with placeholders.
4508                    err.multipart_suggestion(
4509                        "consider using one of the available lifetimes here",
4510                        spans_suggs,
4511                        Applicability::HasPlaceholders,
4512                    );
4513                }
4514            }
4515        }
4516    }
4517
4518    fn find_ref_prefix_span_for_owned_suggestion(&self, lifetime: Span) -> Option<Span> {
4519        let mut finder = RefPrefixSpanFinder { lifetime, span: None };
4520        if let Some(item) = self.diag_metadata.current_item {
4521            finder.visit_item(item);
4522        } else if let Some((kind, _span)) = self.diag_metadata.current_function
4523            && let FnKind::Fn(_, _, ast::Fn { sig, .. }) = kind
4524        {
4525            for param in &sig.decl.inputs {
4526                finder.visit_ty(&param.ty);
4527            }
4528            if let ast::FnRetTy::Ty(ret_ty) = &sig.decl.output {
4529                finder.visit_ty(ret_ty);
4530            }
4531        }
4532        finder.span
4533    }
4534}
4535
4536fn mk_where_bound_predicate(
4537    path: &Path,
4538    poly_trait_ref: &ast::PolyTraitRef,
4539    ty: &Ty,
4540) -> Option<ast::WhereBoundPredicate> {
4541    let modified_segments = {
4542        let mut segments = path.segments.clone();
4543        let [preceding @ .., second_last, last] = segments.as_mut_slice() else {
4544            return None;
4545        };
4546        let mut segments = ThinVec::from(preceding);
4547
4548        let added_constraint = ast::AngleBracketedArg::Constraint(ast::AssocItemConstraint {
4549            id: DUMMY_NODE_ID,
4550            ident: last.ident,
4551            gen_args: None,
4552            kind: ast::AssocItemConstraintKind::Equality {
4553                term: ast::Term::Ty(Box::new(ast::Ty {
4554                    kind: ast::TyKind::Path(None, poly_trait_ref.trait_ref.path.clone()),
4555                    id: DUMMY_NODE_ID,
4556                    span: DUMMY_SP,
4557                })),
4558            },
4559            span: DUMMY_SP,
4560        });
4561
4562        match second_last.args.as_deref_mut() {
4563            Some(ast::GenericArgs::AngleBracketed(ast::AngleBracketedArgs { args, .. })) => {
4564                args.push(added_constraint);
4565            }
4566            Some(_) => return None,
4567            None => {
4568                second_last.args =
4569                    Some(Box::new(ast::GenericArgs::AngleBracketed(ast::AngleBracketedArgs {
4570                        args: ThinVec::from([added_constraint]),
4571                        span: DUMMY_SP,
4572                    })));
4573            }
4574        }
4575
4576        segments.push(second_last.clone());
4577        segments
4578    };
4579
4580    let new_where_bound_predicate = ast::WhereBoundPredicate {
4581        bound_generic_params: ThinVec::new(),
4582        bounded_ty: Box::new(ty.clone()),
4583        bounds: {
    let len = [()].len();
    let mut vec = ::thin_vec::ThinVec::with_capacity(len);
    vec.push(ast::GenericBound::Trait(ast::PolyTraitRef {
                bound_generic_params: ThinVec::new(),
                modifiers: ast::TraitBoundModifiers::NONE,
                trait_ref: ast::TraitRef {
                    path: ast::Path {
                        segments: modified_segments,
                        span: DUMMY_SP,
                    },
                    ref_id: DUMMY_NODE_ID,
                },
                span: DUMMY_SP,
                parens: ast::Parens::No,
            }));
    vec
}thin_vec![ast::GenericBound::Trait(ast::PolyTraitRef {
4584            bound_generic_params: ThinVec::new(),
4585            modifiers: ast::TraitBoundModifiers::NONE,
4586            trait_ref: ast::TraitRef {
4587                path: ast::Path { segments: modified_segments, span: DUMMY_SP },
4588                ref_id: DUMMY_NODE_ID,
4589            },
4590            span: DUMMY_SP,
4591            parens: ast::Parens::No,
4592        })],
4593    };
4594
4595    Some(new_where_bound_predicate)
4596}
4597
4598/// Report lifetime/lifetime shadowing as an error.
4599pub(super) fn signal_lifetime_shadowing(
4600    sess: &Session,
4601    orig: Ident,
4602    shadower: Ident,
4603) -> ErrorGuaranteed {
4604    {
    sess.dcx().struct_span_err(shadower.span,
            ::alloc::__export::must_use({
                    ::alloc::fmt::format(format_args!("lifetime name `{0}` shadows a lifetime name that is already in scope",
                            orig.name))
                })).with_code(E0496)
}struct_span_code_err!(
4605        sess.dcx(),
4606        shadower.span,
4607        E0496,
4608        "lifetime name `{}` shadows a lifetime name that is already in scope",
4609        orig.name,
4610    )
4611    .with_span_label(orig.span, "first declared here")
4612    .with_span_label(shadower.span, ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("lifetime `{0}` already in scope",
                orig.name))
    })format!("lifetime `{}` already in scope", orig.name))
4613    .emit()
4614}
4615
4616struct LifetimeFinder<'ast> {
4617    lifetime: Span,
4618    found: Option<&'ast Ty>,
4619    seen: Vec<&'ast Ty>,
4620}
4621
4622impl<'ast> Visitor<'ast> for LifetimeFinder<'ast> {
4623    fn visit_ty(&mut self, t: &'ast Ty) {
4624        if let TyKind::Ref(_, mut_ty) | TyKind::PinnedRef(_, mut_ty) = &t.kind {
4625            self.seen.push(t);
4626            if t.span.lo() == self.lifetime.lo() {
4627                self.found = Some(&mut_ty.ty);
4628            }
4629        }
4630        walk_ty(self, t)
4631    }
4632}
4633
4634struct RefPrefixSpanFinder {
4635    lifetime: Span,
4636    span: Option<Span>,
4637}
4638
4639impl<'ast> Visitor<'ast> for RefPrefixSpanFinder {
4640    fn visit_ty(&mut self, t: &'ast Ty) {
4641        if self.span.is_some() {
4642            return;
4643        }
4644        if let TyKind::Ref(_, mut_ty) | TyKind::PinnedRef(_, mut_ty) = &t.kind
4645            && t.span.lo() == self.lifetime.lo()
4646        {
4647            self.span = Some(t.span.with_hi(mut_ty.ty.span.lo()));
4648            return;
4649        }
4650        walk_ty(self, t);
4651    }
4652}
4653
4654/// Shadowing involving a label is only a warning for historical reasons.
4655//FIXME: make this a proper lint.
4656pub(super) fn signal_label_shadowing(sess: &Session, orig: Span, shadower: Ident) {
4657    let name = shadower.name;
4658    let shadower = shadower.span;
4659    sess.dcx()
4660        .struct_span_warn(
4661            shadower,
4662            ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("label name `{0}` shadows a label name that is already in scope",
                name))
    })format!("label name `{name}` shadows a label name that is already in scope"),
4663        )
4664        .with_span_label(orig, "first declared here")
4665        .with_span_label(shadower, ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("label `{0}` already in scope",
                name))
    })format!("label `{name}` already in scope"))
4666        .emit();
4667}
4668
4669struct ParentPathVisitor<'a> {
4670    target: Ident,
4671    parent: Option<&'a PathSegment>,
4672    stack: Vec<&'a Ty>,
4673}
4674
4675impl<'a> ParentPathVisitor<'a> {
4676    fn new(self_ty: &'a Ty, target: Ident) -> Self {
4677        let mut v = ParentPathVisitor { target, parent: None, stack: Vec::new() };
4678
4679        v.visit_ty(self_ty);
4680        v
4681    }
4682}
4683
4684impl<'a> Visitor<'a> for ParentPathVisitor<'a> {
4685    fn visit_ty(&mut self, ty: &'a Ty) {
4686        if self.parent.is_some() {
4687            return;
4688        }
4689
4690        // push current type
4691        self.stack.push(ty);
4692
4693        if let TyKind::Path(_, path) = &ty.kind
4694            // is this just `N`?
4695            && let [segment] = path.segments.as_slice()
4696            && segment.ident == self.target
4697            // parent is previous element in stack
4698            && let [.., parent_ty, _ty] = self.stack.as_slice()
4699            && let TyKind::Path(_, parent_path) = &parent_ty.kind
4700        {
4701            self.parent = parent_path.segments.first();
4702        }
4703
4704        walk_ty(self, ty);
4705
4706        self.stack.pop();
4707    }
4708}