Skip to main content

rustc_resolve/late/
diagnostics.rs

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