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