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