Skip to main content

rustc_resolve/late/
diagnostics.rs

1// ignore-tidy-file-filelength
2
3use std::borrow::Cow;
4use std::iter;
5use std::ops::Deref;
6
7use rustc_ast::visit::{FnCtxt, FnKind, LifetimeCtxt, Visitor, walk_ty};
8use rustc_ast::{
9    self as ast, AngleBracketedArg, AssocItemKind, DUMMY_NODE_ID, Expr, ExprKind, GenericArg,
10    GenericArgs, GenericParam, GenericParamKind, Item, ItemKind, MethodCall, NodeId, Path,
11    PathSegment, Ty, TyKind,
12};
13use rustc_ast_pretty::pprust::{path_to_string, where_bound_predicate_to_string};
14use rustc_data_structures::fx::{FxHashMap, FxHashSet, FxIndexMap, FxIndexSet};
15use rustc_data_structures::unord::UnordItems;
16use rustc_errors::codes::*;
17use rustc_errors::{
18    Applicability, Diag, Diagnostic, ErrorGuaranteed, MultiSpan, SuggestionStyle, pluralize,
19    struct_span_code_err,
20};
21use rustc_hir as hir;
22use rustc_hir::attrs::diagnostic::{CustomDiagnostic, FormatArgs};
23use rustc_hir::def::Namespace::{self, *};
24use rustc_hir::def::{CtorKind, CtorOf, DefKind, MacroKinds};
25use rustc_hir::def_id::{CRATE_DEF_ID, DefId};
26use rustc_hir::{MissingLifetimeKind, PrimTy, find_attr};
27use rustc_middle::ty;
28use rustc_session::{Session, lint};
29use rustc_span::edit_distance::{edit_distance, find_best_match_for_name};
30use rustc_span::edition::Edition;
31use rustc_span::{DUMMY_SP, DesugaringKind, Ident, Span, Symbol, kw, sym};
32use thin_vec::{ThinVec, thin_vec};
33use tracing::debug;
34
35use super::NoConstantGenericsReason;
36use crate::diagnostics::impls::{ImportSuggestion, LabelSuggestion, TypoSuggestion};
37use crate::late::{
38    AliasPossibility, LateResolutionVisitor, LifetimeBinderKind, LifetimeRes, LifetimeRibKind,
39    LifetimeUseSet, QSelf, RibKind,
40};
41use crate::ty::fast_reject::SimplifiedType;
42use crate::{
43    Finalize, Module, ModuleOrUniformRoot, ParentScope, PathResult, PathSource, Res, Resolver,
44    ScopeSet, Segment, diagnostics, path_names_to_string,
45};
46
47/// A field or associated item from self type suggested in case of resolution failure.
48enum AssocSuggestion {
49    Field(Span),
50    MethodWithSelf { called: bool },
51    AssocFn { called: bool },
52    AssocType,
53    AssocConst,
54}
55
56impl AssocSuggestion {
57    fn action(&self) -> &'static str {
58        match self {
59            AssocSuggestion::Field(_) => "use the available field",
60            AssocSuggestion::MethodWithSelf { called: true } => {
61                "call the method with the fully-qualified path"
62            }
63            AssocSuggestion::MethodWithSelf { called: false } => {
64                "refer to the method with the fully-qualified path"
65            }
66            AssocSuggestion::AssocFn { called: true } => "call the associated function",
67            AssocSuggestion::AssocFn { called: false } => "refer to the associated function",
68            AssocSuggestion::AssocConst => "use the associated `const`",
69            AssocSuggestion::AssocType => "use the associated type",
70        }
71    }
72}
73
74fn is_self_type(path: &[Segment], namespace: Namespace) -> bool {
75    namespace == TypeNS && path.len() == 1 && path[0].ident.name == kw::SelfUpper
76}
77
78fn is_self_value(path: &[Segment], namespace: Namespace) -> bool {
79    namespace == ValueNS && path.len() == 1 && path[0].ident.name == kw::SelfLower
80}
81
82fn path_to_string_without_assoc_item_bindings(path: &Path) -> String {
83    let mut path = path.clone();
84    for segment in &mut path.segments {
85        let mut remove_args = false;
86        if let Some(args) = segment.args.as_deref_mut()
87            && let ast::GenericArgs::AngleBracketed(angle_bracketed) = args
88        {
89            angle_bracketed.args.retain(|arg| #[allow(non_exhaustive_omitted_patterns)] match arg {
    ast::AngleBracketedArg::Arg(_) => true,
    _ => false,
}matches!(arg, ast::AngleBracketedArg::Arg(_)));
90            remove_args = angle_bracketed.args.is_empty();
91        }
92        if remove_args {
93            segment.args = None;
94        }
95    }
96    path_to_string(&path)
97}
98
99/// Gets the stringified path for an enum from an `ImportSuggestion` for an enum variant.
100fn import_candidate_to_enum_paths(suggestion: &ImportSuggestion) -> (String, String) {
101    let variant_path = &suggestion.path;
102    let variant_path_string = path_names_to_string(variant_path);
103
104    let path_len = suggestion.path.segments.len();
105    let enum_path = ast::Path {
106        span: suggestion.path.span,
107        segments: suggestion.path.segments[0..path_len - 1].iter().cloned().collect(),
108    };
109    let enum_path_string = path_names_to_string(&enum_path);
110
111    (variant_path_string, enum_path_string)
112}
113
114/// Description of an elided lifetime.
115#[derive(#[automatically_derived]
impl ::core::marker::Copy for MissingLifetime { }Copy, #[automatically_derived]
impl ::core::clone::Clone for MissingLifetime {
    #[inline]
    fn clone(&self) -> MissingLifetime {
        let _: ::core::clone::AssertParamIsClone<NodeId>;
        let _: ::core::clone::AssertParamIsClone<Span>;
        let _: ::core::clone::AssertParamIsClone<MissingLifetimeKind>;
        let _: ::core::clone::AssertParamIsClone<usize>;
        *self
    }
}Clone, #[automatically_derived]
impl ::core::cmp::PartialEq for MissingLifetime {
    #[inline]
    fn eq(&self, other: &MissingLifetime) -> bool {
        self.id == other.id && self.id_for_lint == other.id_for_lint &&
                    self.span == other.span && self.kind == other.kind &&
            self.count == other.count
    }
}PartialEq, #[automatically_derived]
impl ::core::cmp::Eq for MissingLifetime {
    #[inline]
    #[doc(hidden)]
    #[coverage(off)]
    fn assert_fields_are_eq(&self) {
        let _: ::core::cmp::AssertParamIsEq<NodeId>;
        let _: ::core::cmp::AssertParamIsEq<Span>;
        let _: ::core::cmp::AssertParamIsEq<MissingLifetimeKind>;
        let _: ::core::cmp::AssertParamIsEq<usize>;
    }
}Eq, #[automatically_derived]
impl ::core::cmp::PartialOrd for MissingLifetime {
    #[inline]
    fn partial_cmp(&self, other: &MissingLifetime)
        -> ::core::option::Option<::core::cmp::Ordering> {
        ::core::option::Option::Some(::core::cmp::Ord::cmp(self, other))
    }
}PartialOrd, #[automatically_derived]
impl ::core::cmp::Ord for MissingLifetime {
    #[inline]
    fn cmp(&self, other: &MissingLifetime) -> ::core::cmp::Ordering {
        match ::core::cmp::Ord::cmp(&self.id, &other.id) {
            ::core::cmp::Ordering::Equal =>
                match ::core::cmp::Ord::cmp(&self.id_for_lint,
                        &other.id_for_lint) {
                    ::core::cmp::Ordering::Equal =>
                        match ::core::cmp::Ord::cmp(&self.span, &other.span) {
                            ::core::cmp::Ordering::Equal =>
                                match ::core::cmp::Ord::cmp(&self.kind, &other.kind) {
                                    ::core::cmp::Ordering::Equal =>
                                        ::core::cmp::Ord::cmp(&self.count, &other.count),
                                    cmp => cmp,
                                },
                            cmp => cmp,
                        },
                    cmp => cmp,
                },
            cmp => cmp,
        }
    }
}Ord, #[automatically_derived]
impl ::core::fmt::Debug for MissingLifetime {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        ::core::fmt::Formatter::debug_struct_field5_finish(f,
            "MissingLifetime", "id", &self.id, "id_for_lint",
            &self.id_for_lint, "span", &self.span, "kind", &self.kind,
            "count", &&self.count)
    }
}Debug)]
116pub(super) struct MissingLifetime {
117    /// Used to overwrite the resolution with the suggestion, to avoid cascading errors.
118    pub id: NodeId,
119    /// As we cannot yet emit lints in this crate and have to buffer them instead,
120    /// we need to associate each lint with some `NodeId`,
121    /// however for some `MissingLifetime`s their `NodeId`s are "fake",
122    /// in a sense that they are temporary and not get preserved down the line,
123    /// which means that the lints for those nodes will not get emitted.
124    /// To combat this, we can try to use some other `NodeId`s as a fallback option.
125    pub id_for_lint: NodeId,
126    /// Where to suggest adding the lifetime.
127    pub span: Span,
128    /// How the lifetime was introduced, to have the correct space and comma.
129    pub kind: MissingLifetimeKind,
130    /// Number of elided lifetimes, used for elision in path.
131    pub count: usize,
132}
133
134/// Description of the lifetimes appearing in a function parameter.
135/// This is used to provide a literal explanation to the elision failure.
136#[derive(#[automatically_derived]
impl ::core::fmt::Debug for ElisionFnParameter {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        ::core::fmt::Formatter::debug_struct_field4_finish(f,
            "ElisionFnParameter", "index", &self.index, "ident", &self.ident,
            "lifetime_count", &self.lifetime_count, "span", &&self.span)
    }
}Debug)]
137pub(super) struct ElisionFnParameter {
138    /// The index of the argument in the original definition.
139    pub index: usize,
140    /// The name of the argument if it's a simple ident.
141    pub ident: Option<Ident>,
142    /// The number of lifetimes in the parameter.
143    pub lifetime_count: usize,
144    /// The span of the parameter.
145    pub span: Span,
146}
147
148/// Description of lifetimes that appear as candidates for elision.
149/// This is used to suggest introducing an explicit lifetime.
150#[derive(#[automatically_derived]
impl ::core::clone::Clone for LifetimeElisionCandidate {
    #[inline]
    fn clone(&self) -> LifetimeElisionCandidate {
        let _: ::core::clone::AssertParamIsClone<MissingLifetime>;
        *self
    }
}Clone, #[automatically_derived]
impl ::core::marker::Copy for LifetimeElisionCandidate { }Copy, #[automatically_derived]
impl ::core::fmt::Debug for LifetimeElisionCandidate {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        match self {
            LifetimeElisionCandidate::Ignore =>
                ::core::fmt::Formatter::write_str(f, "Ignore"),
            LifetimeElisionCandidate::Missing(__self_0) =>
                ::core::fmt::Formatter::debug_tuple_field1_finish(f,
                    "Missing", &__self_0),
        }
    }
}Debug)]
151pub(super) enum LifetimeElisionCandidate {
152    /// This is not a real lifetime, or it is a named lifetime, in which case we won't suggest anything.
153    Ignore,
154    Missing(MissingLifetime),
155}
156
157/// Only used for diagnostics.
158#[derive(#[automatically_derived]
impl ::core::fmt::Debug for BaseError {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        let names: &'static _ =
            &["msg", "fallback_label", "span", "span_label", "could_be_expr",
                        "suggestion", "module", "notes"];
        let values: &[&dyn ::core::fmt::Debug] =
            &[&self.msg, &self.fallback_label, &self.span, &self.span_label,
                        &self.could_be_expr, &self.suggestion, &self.module,
                        &&self.notes];
        ::core::fmt::Formatter::debug_struct_fields_finish(f, "BaseError",
            names, values)
    }
}Debug)]
159struct BaseError {
160    msg: String,
161    fallback_label: String,
162    span: Span,
163    span_label: Option<(Span, &'static str)>,
164    could_be_expr: bool,
165    suggestion: Option<(Span, &'static str, String)>,
166    module: Option<DefId>,
167    notes: Vec<String>,
168}
169
170#[derive(#[automatically_derived]
impl ::core::fmt::Debug for TypoCandidate {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        match self {
            TypoCandidate::Typo(__self_0) =>
                ::core::fmt::Formatter::debug_tuple_field1_finish(f, "Typo",
                    &__self_0),
            TypoCandidate::Shadowed(__self_0, __self_1) =>
                ::core::fmt::Formatter::debug_tuple_field2_finish(f,
                    "Shadowed", __self_0, &__self_1),
            TypoCandidate::None =>
                ::core::fmt::Formatter::write_str(f, "None"),
        }
    }
}Debug)]
171enum TypoCandidate {
172    Typo(TypoSuggestion),
173    Shadowed(Res, Option<Span>),
174    None,
175}
176
177impl TypoCandidate {
178    fn to_opt_suggestion(self) -> Option<TypoSuggestion> {
179        match self {
180            TypoCandidate::Typo(sugg) => Some(sugg),
181            TypoCandidate::Shadowed(_, _) | TypoCandidate::None => None,
182        }
183    }
184}
185
186impl<'ast, 'ra, 'tcx> LateResolutionVisitor<'_, 'ast, 'ra, 'tcx> {
187    fn trait_assoc_type_def_id_by_name(
188        &mut self,
189        trait_def_id: DefId,
190        assoc_name: Symbol,
191    ) -> Option<DefId> {
192        let module = self.r.get_module(trait_def_id)?;
193        self.r.resolutions(module).iter().find_map(|(key, resolution)| {
194            if key.ident.name != assoc_name {
195                return None;
196            }
197            let resolution = resolution.borrow();
198            let binding = resolution.best_decl()?;
199            match binding.res() {
200                Res::Def(DefKind::AssocTy, def_id) => Some(def_id),
201                _ => None,
202            }
203        })
204    }
205
206    /// This does best-effort work to generate suggestions for associated types.
207    fn suggest_assoc_type_from_bounds(
208        &mut self,
209        err: &mut Diag<'_>,
210        source: PathSource<'_, 'ast, 'ra>,
211        path: &[Segment],
212        ident_span: Span,
213    ) -> bool {
214        // Filter out cases where we cannot emit meaningful suggestions.
215        if source.namespace() != TypeNS {
216            return false;
217        }
218        let [segment] = path else { return false };
219        if segment.has_generic_args {
220            return false;
221        }
222        if !ident_span.can_be_used_for_suggestions() {
223            return false;
224        }
225        let assoc_name = segment.ident.name;
226        if assoc_name == kw::Underscore {
227            return false;
228        }
229
230        // Map: type parameter name -> (trait def id -> (assoc type def id, trait paths as written)).
231        // We keep a set of paths per trait so we can detect cases like
232        // `T: Trait<i32> + Trait<u32>` where suggesting `T::Assoc` would be ambiguous.
233        let mut matching_bounds: FxIndexMap<
234            Symbol,
235            FxIndexMap<DefId, (DefId, FxIndexSet<String>)>,
236        > = FxIndexMap::default();
237
238        let mut record_bound = |this: &mut Self,
239                                ty_param: Symbol,
240                                poly_trait_ref: &ast::PolyTraitRef| {
241            // Avoid generating suggestions we can't print in a well-formed way.
242            if !poly_trait_ref.bound_generic_params.is_empty() {
243                return;
244            }
245            if poly_trait_ref.modifiers != ast::TraitBoundModifiers::NONE {
246                return;
247            }
248            let Some(trait_seg) = poly_trait_ref.trait_ref.path.segments.last() else {
249                return;
250            };
251            let Some(partial_res) = this.r.partial_res_map.get(&trait_seg.id) else {
252                return;
253            };
254            let Some(trait_def_id) = partial_res.full_res().and_then(|res| res.opt_def_id()) else {
255                return;
256            };
257            let Some(assoc_type_def_id) =
258                this.trait_assoc_type_def_id_by_name(trait_def_id, assoc_name)
259            else {
260                return;
261            };
262
263            // Preserve `::` and generic args so we don't generate broken suggestions like
264            // `<T as Foo>::Assoc` for bounds written as `T: ::Foo<'a>`, while stripping
265            // associated-item bindings that are rejected in qualified paths.
266            let trait_path =
267                path_to_string_without_assoc_item_bindings(&poly_trait_ref.trait_ref.path);
268            let trait_bounds = matching_bounds.entry(ty_param).or_default();
269            let trait_bounds = trait_bounds
270                .entry(trait_def_id)
271                .or_insert_with(|| (assoc_type_def_id, FxIndexSet::default()));
272            if true {
    {
        match (&trait_bounds.0, &assoc_type_def_id) {
            (left_val, right_val) => {
                if !(*left_val == *right_val) {
                    let kind = ::core::panicking::AssertKind::Eq;
                    ::core::panicking::assert_failed(kind, &*left_val,
                        &*right_val, ::core::option::Option::None);
                }
            }
        }
    };
};debug_assert_eq!(trait_bounds.0, assoc_type_def_id);
273            trait_bounds.1.insert(trait_path);
274        };
275
276        let mut record_from_generics = |this: &mut Self, generics: &ast::Generics| {
277            for param in &generics.params {
278                let ast::GenericParamKind::Type { .. } = param.kind else { continue };
279                for bound in &param.bounds {
280                    let ast::GenericBound::Trait(poly_trait_ref) = bound else { continue };
281                    record_bound(this, param.ident.name, poly_trait_ref);
282                }
283            }
284
285            for predicate in &generics.where_clause.predicates {
286                let ast::WherePredicateKind::BoundPredicate(where_bound) = &predicate.kind else {
287                    continue;
288                };
289
290                let ast::TyKind::Path(None, bounded_path) = &where_bound.bounded_ty.kind else {
291                    continue;
292                };
293                let [ast::PathSegment { ident, args: None, .. }] = &bounded_path.segments[..]
294                else {
295                    continue;
296                };
297
298                // Only suggest for bounds that are explicitly on an in-scope type parameter.
299                let Some(partial_res) = this.r.partial_res_map.get(&where_bound.bounded_ty.id)
300                else {
301                    continue;
302                };
303                if !#[allow(non_exhaustive_omitted_patterns)] match partial_res.full_res() {
    Some(Res::Def(DefKind::TyParam, _)) => true,
    _ => false,
}matches!(partial_res.full_res(), Some(Res::Def(DefKind::TyParam, _))) {
304                    continue;
305                }
306
307                for bound in &where_bound.bounds {
308                    let ast::GenericBound::Trait(poly_trait_ref) = bound else { continue };
309                    record_bound(this, ident.name, poly_trait_ref);
310                }
311            }
312        };
313
314        if let Some(item) = self.diag_metadata.current_item
315            && let Some(generics) = item.kind.generics()
316        {
317            record_from_generics(self, generics);
318        }
319
320        if let Some(item) = self.diag_metadata.current_item
321            && #[allow(non_exhaustive_omitted_patterns)] match item.kind {
    ItemKind::Impl(..) => true,
    _ => false,
}matches!(item.kind, ItemKind::Impl(..))
322            && let Some(assoc) = self.diag_metadata.current_impl_item
323        {
324            let generics = match &assoc.kind {
325                AssocItemKind::Const(ast::ConstItem { generics, .. })
326                | AssocItemKind::Fn(ast::Fn { generics, .. })
327                | AssocItemKind::Type(ast::TyAlias { generics, .. }) => Some(generics),
328                AssocItemKind::Delegation(..)
329                | AssocItemKind::MacCall(..)
330                | AssocItemKind::DelegationMac(..) => None,
331            };
332            if let Some(generics) = generics {
333                record_from_generics(self, generics);
334            }
335        }
336
337        let mut suggestions: FxIndexSet<String> = FxIndexSet::default();
338        for (ty_param, traits) in matching_bounds {
339            let ty_param = ty_param.to_ident_string();
340            let trait_paths_len: usize = traits.values().map(|(_, paths)| paths.len()).sum();
341            if traits.len() == 1 && trait_paths_len == 1 {
342                let assoc_type_def_id = traits.values().next().unwrap().0;
343                let assoc_segment = ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("{0}{1}", assoc_name,
                self.r.item_required_generic_args_suggestion(assoc_type_def_id)))
    })format!(
344                    "{}{}",
345                    assoc_name,
346                    self.r.item_required_generic_args_suggestion(assoc_type_def_id)
347                );
348                suggestions.insert(::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("{0}::{1}", ty_param,
                assoc_segment))
    })format!("{ty_param}::{assoc_segment}"));
349            } else {
350                for (assoc_type_def_id, trait_paths) in traits.into_values() {
351                    let assoc_segment = ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("{0}{1}", assoc_name,
                self.r.item_required_generic_args_suggestion(assoc_type_def_id)))
    })format!(
352                        "{}{}",
353                        assoc_name,
354                        self.r.item_required_generic_args_suggestion(assoc_type_def_id)
355                    );
356                    for trait_path in trait_paths {
357                        suggestions
358                            .insert(::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("<{0} as {1}>::{2}", ty_param,
                trait_path, assoc_segment))
    })format!("<{ty_param} as {trait_path}>::{assoc_segment}"));
359                    }
360                }
361            }
362        }
363
364        if suggestions.is_empty() {
365            return false;
366        }
367
368        let mut suggestions: Vec<String> = suggestions.into_iter().collect();
369        suggestions.sort();
370
371        err.span_suggestions_with_style(
372            ident_span,
373            "you might have meant to use an associated type of the same name",
374            suggestions,
375            Applicability::MaybeIncorrect,
376            SuggestionStyle::ShowAlways,
377        );
378
379        true
380    }
381
382    fn make_base_error(
383        &mut self,
384        path: &[Segment],
385        span: Span,
386        source: PathSource<'_, 'ast, 'ra>,
387        res: Option<Res>,
388        could_be_expr: bool,
389    ) -> BaseError {
390        // Make the base error.
391        let mut expected = source.descr_expected();
392        let path_str = Segment::names_to_string(path);
393
394        if let Some(res) = res {
395            BaseError {
396                msg: ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("expected {0}, found {1} `{2}`",
                expected, res.descr(), path_str))
    })format!("expected {}, found {} `{}`", expected, res.descr(), path_str),
397                fallback_label: ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("not a {0}", expected))
    })format!("not a {expected}"),
398                span,
399                span_label: match res {
400                    Res::Def(DefKind::TyParam, def_id) => {
401                        Some((self.r.def_span(def_id), "found this type parameter"))
402                    }
403                    _ => None,
404                },
405                could_be_expr,
406                suggestion: None,
407                module: None,
408                notes: Vec::new(),
409            }
410        } else {
411            let mut span_label = None;
412            let item_ident = path.last().unwrap().ident;
413            let item_span = item_ident.span;
414            let (tick, mod_prefix, mod_str, module, suggestion) = if path.len() == 1 {
415                {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event compiler/rustc_resolve/src/late/diagnostics.rs:415",
                        "rustc_resolve::late::diagnostics", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_resolve/src/late/diagnostics.rs"),
                        ::tracing_core::__macro_support::Option::Some(415u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_resolve::late::diagnostics"),
                        ::tracing_core::field::FieldSet::new(&[{
                                            const NAME:
                                                ::tracing::__macro_support::FieldName<{
                                                    ::tracing::__macro_support::FieldName::len("self.diag_metadata.current_impl_items")
                                                }> =
                                                ::tracing::__macro_support::FieldName::new("self.diag_metadata.current_impl_items");
                                            NAME.as_str()
                                        }], ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() &&
            {
                let interest = __CALLSITE.interest();
                !interest.is_never() &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest)
            };
    if enabled {
        (|value_set: ::tracing::field::ValueSet|
                    {
                        let meta = __CALLSITE.metadata();
                        ::tracing::Event::dispatch(meta, &value_set);
                        ;
                    })({
                #[allow(unused_imports)]
                use ::tracing::field::{debug, display, Value};
                __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&self.diag_metadata.current_impl_items)
                                            as &dyn ::tracing::field::Value))])
            });
    } else { ; }
};debug!(?self.diag_metadata.current_impl_items);
416                {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event compiler/rustc_resolve/src/late/diagnostics.rs:416",
                        "rustc_resolve::late::diagnostics", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_resolve/src/late/diagnostics.rs"),
                        ::tracing_core::__macro_support::Option::Some(416u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_resolve::late::diagnostics"),
                        ::tracing_core::field::FieldSet::new(&[{
                                            const NAME:
                                                ::tracing::__macro_support::FieldName<{
                                                    ::tracing::__macro_support::FieldName::len("self.diag_metadata.current_function")
                                                }> =
                                                ::tracing::__macro_support::FieldName::new("self.diag_metadata.current_function");
                                            NAME.as_str()
                                        }], ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() &&
            {
                let interest = __CALLSITE.interest();
                !interest.is_never() &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest)
            };
    if enabled {
        (|value_set: ::tracing::field::ValueSet|
                    {
                        let meta = __CALLSITE.metadata();
                        ::tracing::Event::dispatch(meta, &value_set);
                        ;
                    })({
                #[allow(unused_imports)]
                use ::tracing::field::{debug, display, Value};
                __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&self.diag_metadata.current_function)
                                            as &dyn ::tracing::field::Value))])
            });
    } else { ; }
};debug!(?self.diag_metadata.current_function);
417                let suggestion = if self.current_trait_ref.is_none()
418                    && let Some((fn_kind, _)) = self.diag_metadata.current_function
419                    && let Some(FnCtxt::Assoc(_)) = fn_kind.ctxt()
420                    && let FnKind::Fn(_, _, ast::Fn { sig, .. }) = fn_kind
421                    && let Some(items) = self.diag_metadata.current_impl_items
422                    && let Some(item) = items.iter().find(|i| {
423                        i.kind.ident().is_some_and(|ident| {
424                            // Don't suggest if the item is in Fn signature arguments (#112590).
425                            ident.name == item_ident.name && !sig.span.contains(item_span)
426                        })
427                    }) {
428                    let sp = item_span.shrink_to_lo();
429
430                    // Account for `Foo { field }` when suggesting `self.field` so we result on
431                    // `Foo { field: self.field }`.
432                    let field = match source {
433                        PathSource::Expr(Some(Expr { kind: ExprKind::Struct(expr), .. })) => {
434                            expr.fields.iter().find(|f| f.ident == item_ident)
435                        }
436                        _ => None,
437                    };
438                    let pre = if let Some(field) = field
439                        && field.is_shorthand
440                    {
441                        ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("{0}: ", item_ident))
    })format!("{item_ident}: ")
442                    } else {
443                        String::new()
444                    };
445                    // Ensure we provide a structured suggestion for an assoc fn only for
446                    // expressions that are actually a fn call.
447                    let is_call = match field {
448                        Some(ast::ExprField { expr, .. }) => {
449                            #[allow(non_exhaustive_omitted_patterns)] match expr.kind {
    ExprKind::Call(..) => true,
    _ => false,
}matches!(expr.kind, ExprKind::Call(..))
450                        }
451                        _ => #[allow(non_exhaustive_omitted_patterns)] match source {
    PathSource::Expr(Some(Expr { kind: ExprKind::Call(..), .. })) => true,
    _ => false,
}matches!(
452                            source,
453                            PathSource::Expr(Some(Expr { kind: ExprKind::Call(..), .. })),
454                        ),
455                    };
456
457                    match &item.kind {
458                        AssocItemKind::Fn(fn_)
459                            if (!sig.decl.has_self() || !is_call) && fn_.sig.decl.has_self() =>
460                        {
461                            // Ensure that we only suggest `self.` if `self` is available,
462                            // you can't call `fn foo(&self)` from `fn bar()` (#115992).
463                            // We also want to mention that the method exists.
464                            span_label = Some((
465                                fn_.ident.span,
466                                "a method by that name is available on `Self` here",
467                            ));
468                            None
469                        }
470                        AssocItemKind::Fn(fn_) if !fn_.sig.decl.has_self() && !is_call => {
471                            span_label = Some((
472                                fn_.ident.span,
473                                "an associated function by that name is available on `Self` here",
474                            ));
475                            None
476                        }
477                        AssocItemKind::Fn(fn_) if fn_.sig.decl.has_self() => {
478                            Some((sp, "consider using the method on `Self`", ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("{0}self.", pre))
    })format!("{pre}self.")))
479                        }
480                        AssocItemKind::Fn(_) => Some((
481                            sp,
482                            "consider using the associated function on `Self`",
483                            ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("{0}Self::", pre))
    })format!("{pre}Self::"),
484                        )),
485                        AssocItemKind::Const(..) => Some((
486                            sp,
487                            "consider using the associated constant on `Self`",
488                            ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("{0}Self::", pre))
    })format!("{pre}Self::"),
489                        )),
490                        _ => None,
491                    }
492                } else {
493                    None
494                };
495                ("", String::new(), "this scope".to_string(), None, suggestion)
496            } else if path.len() == 2 && path[0].ident.name == kw::PathRoot {
497                if self.r.tcx.sess.edition() > Edition::Edition2015 {
498                    // In edition 2018 onwards, the `::foo` syntax may only pull from the extern prelude
499                    // which overrides all other expectations of item type
500                    expected = "crate";
501                    ("", String::new(), "the list of imported crates".to_string(), None, None)
502                } else {
503                    (
504                        "",
505                        String::new(),
506                        "the crate root".to_string(),
507                        Some(CRATE_DEF_ID.to_def_id()),
508                        None,
509                    )
510                }
511            } else if path.len() == 2 && path[0].ident.name == kw::Crate {
512                (
513                    "",
514                    String::new(),
515                    "the crate root".to_string(),
516                    Some(CRATE_DEF_ID.to_def_id()),
517                    None,
518                )
519            } else {
520                let mod_path = &path[..path.len() - 1];
521                let mod_res = self.resolve_path(mod_path, Some(TypeNS), None, source);
522                let mod_prefix = match mod_res {
523                    PathResult::Module(ModuleOrUniformRoot::Module(module)) => module.res(),
524                    _ => None,
525                };
526
527                let module_did = mod_prefix.as_ref().and_then(Res::mod_def_id);
528
529                let mod_prefix =
530                    mod_prefix.map_or_else(String::new, |res| ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("{0} ", res.descr()))
    })format!("{} ", res.descr()));
531                ("`", mod_prefix, Segment::names_to_string(mod_path), module_did, None)
532            };
533
534            let suggestion =
535                if ["true", "false"].contains(&item_ident.to_string().to_lowercase().as_str()) {
536                    // check if we are in situation of typo like `True` instead of `true`.
537                    let item_typo = item_ident.to_string().to_lowercase();
538                    Some((item_span, "you may want to use a bool value instead", item_typo))
539                // FIXME(vincenzopalazzo): make the check smarter,
540                // and maybe expand with levenshtein distance checks
541                } else if item_ident.as_str() == "printf" {
542                    Some((
543                        item_span,
544                        "you may have meant to use the `print` macro",
545                        "print!".to_owned(),
546                    ))
547                } else {
548                    suggestion
549                };
550            let mut msg = ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("cannot find {0} `{1}` in {2}{3}{4}{3}",
                expected, item_ident, mod_prefix, tick, mod_str))
    })format!(
551                "cannot find {expected} `{item_ident}` in {mod_prefix}{tick}{mod_str}{tick}"
552            );
553            let mut fallback_label = if path_str == "async" && expected.starts_with("struct") {
554                "`async` blocks are only allowed in Rust 2018 or later".to_string()
555            } else {
556                ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("not found in {0}{1}{0}", tick,
                mod_str))
    })format!("not found in {tick}{mod_str}{tick}")
557            };
558            let mut notes = Vec::new();
559            if let Some(module_def_id) = module
560                && let Some(directive) = self.r.on_unknown_data(module_def_id)
561            {
562                let args = FormatArgs { unresolved: item_ident.to_string(), this: mod_str, .. };
563                let CustomDiagnostic {
564                    message,
565                    label,
566                    notes: custom_notes,
567                    parent_label: _unreachable,
568                } = directive.eval(None, &args);
569                if let Some(message) = message {
570                    notes.push(msg);
571                    msg = message;
572                }
573                if let Some(label) = label {
574                    fallback_label = label;
575                    if let Some((_, span_label)) = span_label.take() {
576                        notes.push(span_label.to_string());
577                    }
578                }
579                notes.extend(custom_notes);
580            }
581
582            BaseError {
583                msg,
584                fallback_label,
585                span: item_span,
586                span_label,
587                could_be_expr,
588                suggestion,
589                module,
590                notes,
591            }
592        }
593    }
594
595    fn could_be_expr(&self, res: Res, span: Span) -> bool {
596        match res {
597            // Verify whether this is a fn call or an Fn used as a type.
598            Res::Def(DefKind::Fn, _) => self
599                .r
600                .tcx
601                .sess
602                .source_map()
603                .span_to_snippet(span)
604                .is_ok_and(|snippet| snippet.ends_with(')')),
605            Res::Def(
606                DefKind::Ctor(..)
607                | DefKind::AssocFn
608                | DefKind::Const { .. }
609                | DefKind::AssocConst { .. },
610                _,
611            )
612            | Res::SelfCtor(_)
613            | Res::PrimTy(_)
614            | Res::Local(_) => true,
615            _ => false,
616        }
617    }
618
619    /// Try to suggest for a module path that cannot be resolved.
620    /// Such as `fmt::Debug` where `fmt` is not resolved without importing,
621    /// here we search with `lookup_import_candidates` for a module named `fmt`
622    /// with `TypeNS` as namespace.
623    ///
624    /// We need a separate function here because we won't suggest for a path with single segment
625    /// and we won't change `SourcePath` api `is_expected` to match `Type` with `DefKind::Mod`
626    pub(crate) fn smart_resolve_partial_mod_path_errors(
627        &mut self,
628        prefix_path: &[Segment],
629        following_seg: Option<&Segment>,
630    ) -> Vec<ImportSuggestion> {
631        if let Some(segment) = prefix_path.last()
632            && let Some(following_seg) = following_seg
633        {
634            let candidates = self.r.lookup_import_candidates(
635                segment.ident,
636                Namespace::TypeNS,
637                &self.parent_scope,
638                &|res: Res| #[allow(non_exhaustive_omitted_patterns)] match res {
    Res::Def(DefKind::Mod, _) => true,
    _ => false,
}matches!(res, Res::Def(DefKind::Mod, _)),
639            );
640            // double check next seg is valid
641            candidates
642                .into_iter()
643                .filter(|candidate| {
644                    if let Some(def_id) = candidate.did
645                        && let Some(module) = self.r.get_module(def_id)
646                    {
647                        Some(def_id) != self.parent_scope.module.opt_def_id()
648                            && self
649                                .r
650                                .resolutions(module)
651                                .iter()
652                                .any(|(key, _r)| key.ident.name == following_seg.ident.name)
653                    } else {
654                        false
655                    }
656                })
657                .collect::<Vec<_>>()
658        } else {
659            Vec::new()
660        }
661    }
662
663    /// Handles error reporting for `smart_resolve_path_fragment` function.
664    /// Creates base error and amends it with one short label and possibly some longer helps/notes.
665    #[allow(clippy :: suspicious_else_formatting)]
{
    let __tracing_attr_span;
    let __tracing_attr_guard;
    if ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() ||
            { false } {
        __tracing_attr_span =
            {
                use ::tracing::__macro_support::Callsite as _;
                static __CALLSITE: ::tracing::callsite::DefaultCallsite =
                    {
                        static META: ::tracing::Metadata<'static> =
                            {
                                ::tracing_core::metadata::Metadata::new("smart_resolve_report_errors",
                                    "rustc_resolve::late::diagnostics", ::tracing::Level::DEBUG,
                                    ::tracing_core::__macro_support::Option::Some("compiler/rustc_resolve/src/late/diagnostics.rs"),
                                    ::tracing_core::__macro_support::Option::Some(665u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_resolve::late::diagnostics"),
                                    ::tracing_core::field::FieldSet::new(&[{
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("path")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("path");
                                                        NAME.as_str()
                                                    },
                                                    {
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("following_seg")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("following_seg");
                                                        NAME.as_str()
                                                    },
                                                    {
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("span")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("span");
                                                        NAME.as_str()
                                                    },
                                                    {
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("source")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("source");
                                                        NAME.as_str()
                                                    },
                                                    {
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("res")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("res");
                                                        NAME.as_str()
                                                    },
                                                    {
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("qself")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("qself");
                                                        NAME.as_str()
                                                    }], ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                    ::tracing::metadata::Kind::SPAN)
                            };
                        ::tracing::callsite::DefaultCallsite::new(&META)
                    };
                let mut interest = ::tracing::subscriber::Interest::never();
                if ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::STATIC_MAX_LEVEL &&
                                ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::LevelFilter::current() &&
                            { interest = __CALLSITE.interest(); !interest.is_never() }
                        &&
                        ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                            interest) {
                    let meta = __CALLSITE.metadata();
                    ::tracing::Span::new(meta,
                        &{
                                #[allow(unused_imports)]
                                use ::tracing::field::{debug, display, Value};
                                meta.fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&path)
                                                            as &dyn ::tracing::field::Value)),
                                                (::tracing::__macro_support::Option::Some(&::tracing::field::debug(&following_seg)
                                                            as &dyn ::tracing::field::Value)),
                                                (::tracing::__macro_support::Option::Some(&::tracing::field::debug(&span)
                                                            as &dyn ::tracing::field::Value)),
                                                (::tracing::__macro_support::Option::Some(&::tracing::field::debug(&source)
                                                            as &dyn ::tracing::field::Value)),
                                                (::tracing::__macro_support::Option::Some(&::tracing::field::debug(&res)
                                                            as &dyn ::tracing::field::Value)),
                                                (::tracing::__macro_support::Option::Some(&::tracing::field::debug(&qself)
                                                            as &dyn ::tracing::field::Value))])
                            })
                } else {
                    let span =
                        ::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
                    {};
                    span
                }
            };
        __tracing_attr_guard = __tracing_attr_span.enter();
    }

    #[warn(clippy :: suspicious_else_formatting)]
    {

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