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