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::def::Namespace::{self, *};
21use rustc_hir::def::{self, CtorKind, CtorOf, DefKind, MacroKinds};
22use rustc_hir::def_id::{CRATE_DEF_ID, DefId};
23use rustc_hir::{MissingLifetimeKind, PrimTy, find_attr};
24use rustc_middle::ty;
25use rustc_session::{Session, lint};
26use rustc_span::edit_distance::{edit_distance, find_best_match_for_name};
27use rustc_span::edition::Edition;
28use rustc_span::{DUMMY_SP, Ident, Span, Symbol, kw, sym};
29use thin_vec::ThinVec;
30use tracing::debug;
31
32use super::NoConstantGenericsReason;
33use crate::diagnostics::{ImportSuggestion, LabelSuggestion, TypoSuggestion};
34use crate::late::{
35    AliasPossibility, LateResolutionVisitor, LifetimeBinderKind, LifetimeRes, LifetimeRibKind,
36    LifetimeUseSet, QSelf, RibKind,
37};
38use crate::ty::fast_reject::SimplifiedType;
39use crate::{
40    Module, ModuleKind, ModuleOrUniformRoot, ParentScope, PathResult, PathSource, Resolver,
41    ScopeSet, Segment, errors, path_names_to_string,
42};
43
44type Res = def::Res<ast::NodeId>;
45
46/// A field or associated item from self type suggested in case of resolution failure.
47enum AssocSuggestion {
48    Field(Span),
49    MethodWithSelf { called: bool },
50    AssocFn { called: bool },
51    AssocType,
52    AssocConst,
53}
54
55impl AssocSuggestion {
56    fn action(&self) -> &'static str {
57        match self {
58            AssocSuggestion::Field(_) => "use the available field",
59            AssocSuggestion::MethodWithSelf { called: true } => {
60                "call the method with the fully-qualified path"
61            }
62            AssocSuggestion::MethodWithSelf { called: false } => {
63                "refer to the method with the fully-qualified path"
64            }
65            AssocSuggestion::AssocFn { called: true } => "call the associated function",
66            AssocSuggestion::AssocFn { called: false } => "refer to the associated function",
67            AssocSuggestion::AssocConst => "use the associated `const`",
68            AssocSuggestion::AssocType => "use the associated type",
69        }
70    }
71}
72
73fn is_self_type(path: &[Segment], namespace: Namespace) -> bool {
74    namespace == TypeNS && path.len() == 1 && path[0].ident.name == kw::SelfUpper
75}
76
77fn is_self_value(path: &[Segment], namespace: Namespace) -> bool {
78    namespace == ValueNS && path.len() == 1 && path[0].ident.name == kw::SelfLower
79}
80
81fn path_to_string_without_assoc_item_bindings(path: &Path) -> String {
82    let mut path = path.clone();
83    for segment in &mut path.segments {
84        let mut remove_args = false;
85        if let Some(args) = segment.args.as_deref_mut()
86            && let ast::GenericArgs::AngleBracketed(angle_bracketed) = args
87        {
88            angle_bracketed.args.retain(|arg| #[allow(non_exhaustive_omitted_patterns)] match arg {
    ast::AngleBracketedArg::Arg(_) => true,
    _ => false,
}matches!(arg, ast::AngleBracketedArg::Arg(_)));
89            remove_args = angle_bracketed.args.is_empty();
90        }
91        if remove_args {
92            segment.args = None;
93        }
94    }
95    path_to_string(&path)
96}
97
98/// Gets the stringified path for an enum from an `ImportSuggestion` for an enum variant.
99fn import_candidate_to_enum_paths(suggestion: &ImportSuggestion) -> (String, String) {
100    let variant_path = &suggestion.path;
101    let variant_path_string = path_names_to_string(variant_path);
102
103    let path_len = suggestion.path.segments.len();
104    let enum_path = ast::Path {
105        span: suggestion.path.span,
106        segments: suggestion.path.segments[0..path_len - 1].iter().cloned().collect(),
107        tokens: None,
108    };
109    let enum_path_string = path_names_to_string(&enum_path);
110
111    (variant_path_string, enum_path_string)
112}
113
114/// Description of an elided lifetime.
115#[derive(#[automatically_derived]
impl ::core::marker::Copy for MissingLifetime { }Copy, #[automatically_derived]
impl ::core::clone::Clone for MissingLifetime {
    #[inline]
    fn clone(&self) -> MissingLifetime {
        let _: ::core::clone::AssertParamIsClone<NodeId>;
        let _: ::core::clone::AssertParamIsClone<Span>;
        let _: ::core::clone::AssertParamIsClone<MissingLifetimeKind>;
        let _: ::core::clone::AssertParamIsClone<usize>;
        *self
    }
}Clone, #[automatically_derived]
impl ::core::cmp::PartialEq for MissingLifetime {
    #[inline]
    fn eq(&self, other: &MissingLifetime) -> bool {
        self.id == other.id && self.id_for_lint == other.id_for_lint &&
                    self.span == other.span && self.kind == other.kind &&
            self.count == other.count
    }
}PartialEq, #[automatically_derived]
impl ::core::cmp::Eq for MissingLifetime {
    #[inline]
    #[doc(hidden)]
    #[coverage(off)]
    fn assert_fields_are_eq(&self) {
        let _: ::core::cmp::AssertParamIsEq<NodeId>;
        let _: ::core::cmp::AssertParamIsEq<Span>;
        let _: ::core::cmp::AssertParamIsEq<MissingLifetimeKind>;
        let _: ::core::cmp::AssertParamIsEq<usize>;
    }
}Eq, #[automatically_derived]
impl ::core::cmp::PartialOrd for MissingLifetime {
    #[inline]
    fn partial_cmp(&self, other: &MissingLifetime)
        -> ::core::option::Option<::core::cmp::Ordering> {
        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)]
116pub(super) struct MissingLifetime {
117    /// Used to overwrite the resolution with the suggestion, to avoid cascading errors.
118    pub id: NodeId,
119    /// As we cannot yet emit lints in this crate and have to buffer them instead,
120    /// we need to associate each lint with some `NodeId`,
121    /// however for some `MissingLifetime`s their `NodeId`s are "fake",
122    /// in a sense that they are temporary and not get preserved down the line,
123    /// which means that the lints for those nodes will not get emitted.
124    /// To combat this, we can try to use some other `NodeId`s as a fallback option.
125    pub id_for_lint: NodeId,
126    /// Where to suggest adding the lifetime.
127    pub span: Span,
128    /// How the lifetime was introduced, to have the correct space and comma.
129    pub kind: MissingLifetimeKind,
130    /// Number of elided lifetimes, used for elision in path.
131    pub count: usize,
132}
133
134/// Description of the lifetimes appearing in a function parameter.
135/// This is used to provide a literal explanation to the elision failure.
136#[derive(#[automatically_derived]
impl ::core::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)]
137pub(super) struct ElisionFnParameter {
138    /// The index of the argument in the original definition.
139    pub index: usize,
140    /// The name of the argument if it's a simple ident.
141    pub ident: Option<Ident>,
142    /// The number of lifetimes in the parameter.
143    pub lifetime_count: usize,
144    /// The span of the parameter.
145    pub span: Span,
146}
147
148/// Description of lifetimes that appear as candidates for elision.
149/// This is used to suggest introducing an explicit lifetime.
150#[derive(#[automatically_derived]
impl ::core::clone::Clone for LifetimeElisionCandidate {
    #[inline]
    fn clone(&self) -> LifetimeElisionCandidate {
        let _: ::core::clone::AssertParamIsClone<MissingLifetime>;
        *self
    }
}Clone, #[automatically_derived]
impl ::core::marker::Copy for LifetimeElisionCandidate { }Copy, #[automatically_derived]
impl ::core::fmt::Debug for LifetimeElisionCandidate {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        match self {
            LifetimeElisionCandidate::Ignore =>
                ::core::fmt::Formatter::write_str(f, "Ignore"),
            LifetimeElisionCandidate::Named =>
                ::core::fmt::Formatter::write_str(f, "Named"),
            LifetimeElisionCandidate::Missing(__self_0) =>
                ::core::fmt::Formatter::debug_tuple_field1_finish(f,
                    "Missing", &__self_0),
        }
    }
}Debug)]
151pub(super) enum LifetimeElisionCandidate {
152    /// This is not a real lifetime.
153    Ignore,
154    /// There is a named lifetime, we won't suggest anything.
155    Named,
156    Missing(MissingLifetime),
157}
158
159/// Only used for diagnostics.
160#[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)]
161struct BaseError {
162    msg: String,
163    fallback_label: String,
164    span: Span,
165    span_label: Option<(Span, &'static str)>,
166    could_be_expr: bool,
167    suggestion: Option<(Span, &'static str, String)>,
168    module: Option<DefId>,
169}
170
171#[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)]
172enum TypoCandidate {
173    Typo(TypoSuggestion),
174    Shadowed(Res, Option<Span>),
175    None,
176}
177
178impl TypoCandidate {
179    fn to_opt_suggestion(self) -> Option<TypoSuggestion> {
180        match self {
181            TypoCandidate::Typo(sugg) => Some(sugg),
182            TypoCandidate::Shadowed(_, _) | TypoCandidate::None => None,
183        }
184    }
185}
186
187impl<'ast, 'ra, 'tcx> LateResolutionVisitor<'_, 'ast, 'ra, 'tcx> {
188    fn trait_assoc_type_def_id_by_name(
189        &mut self,
190        trait_def_id: DefId,
191        assoc_name: Symbol,
192    ) -> Option<DefId> {
193        let module = self.r.get_module(trait_def_id)?;
194        self.r.resolutions(module).borrow().iter().find_map(|(key, resolution)| {
195            if key.ident.name != assoc_name {
196                return None;
197            }
198            let resolution = resolution.borrow();
199            let binding = resolution.best_decl()?;
200            match binding.res() {
201                Res::Def(DefKind::AssocTy, def_id) => Some(def_id),
202                _ => None,
203            }
204        })
205    }
206
207    /// This does best-effort work to generate suggestions for associated types.
208    fn suggest_assoc_type_from_bounds(
209        &mut self,
210        err: &mut Diag<'_>,
211        source: PathSource<'_, 'ast, 'ra>,
212        path: &[Segment],
213        ident_span: Span,
214    ) -> bool {
215        // Filter out cases where we cannot emit meaningful suggestions.
216        if source.namespace() != TypeNS {
217            return false;
218        }
219        let [segment] = path else { return false };
220        if segment.has_generic_args {
221            return false;
222        }
223        if !ident_span.can_be_used_for_suggestions() {
224            return false;
225        }
226        let assoc_name = segment.ident.name;
227        if assoc_name == kw::Underscore {
228            return false;
229        }
230
231        // Map: type parameter name -> (trait def id -> (assoc type def id, trait paths as written)).
232        // We keep a set of paths per trait so we can detect cases like
233        // `T: Trait<i32> + Trait<u32>` where suggesting `T::Assoc` would be ambiguous.
234        let mut matching_bounds: FxIndexMap<
235            Symbol,
236            FxIndexMap<DefId, (DefId, FxIndexSet<String>)>,
237        > = FxIndexMap::default();
238
239        let mut record_bound = |this: &mut Self,
240                                ty_param: Symbol,
241                                poly_trait_ref: &ast::PolyTraitRef| {
242            // Avoid generating suggestions we can't print in a well-formed way.
243            if !poly_trait_ref.bound_generic_params.is_empty() {
244                return;
245            }
246            if poly_trait_ref.modifiers != ast::TraitBoundModifiers::NONE {
247                return;
248            }
249            let Some(trait_seg) = poly_trait_ref.trait_ref.path.segments.last() else {
250                return;
251            };
252            let Some(partial_res) = this.r.partial_res_map.get(&trait_seg.id) else {
253                return;
254            };
255            let Some(trait_def_id) = partial_res.full_res().and_then(|res| res.opt_def_id()) else {
256                return;
257            };
258            let Some(assoc_type_def_id) =
259                this.trait_assoc_type_def_id_by_name(trait_def_id, assoc_name)
260            else {
261                return;
262            };
263
264            // Preserve `::` and generic args so we don't generate broken suggestions like
265            // `<T as Foo>::Assoc` for bounds written as `T: ::Foo<'a>`, while stripping
266            // associated-item bindings that are rejected in qualified paths.
267            let trait_path =
268                path_to_string_without_assoc_item_bindings(&poly_trait_ref.trait_ref.path);
269            let trait_bounds = matching_bounds.entry(ty_param).or_default();
270            let trait_bounds = trait_bounds
271                .entry(trait_def_id)
272                .or_insert_with(|| (assoc_type_def_id, FxIndexSet::default()));
273            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);
274            trait_bounds.1.insert(trait_path);
275        };
276
277        let mut record_from_generics = |this: &mut Self, generics: &ast::Generics| {
278            for param in &generics.params {
279                let ast::GenericParamKind::Type { .. } = param.kind else { continue };
280                for bound in &param.bounds {
281                    let ast::GenericBound::Trait(poly_trait_ref) = bound else { continue };
282                    record_bound(this, param.ident.name, poly_trait_ref);
283                }
284            }
285
286            for predicate in &generics.where_clause.predicates {
287                let ast::WherePredicateKind::BoundPredicate(where_bound) = &predicate.kind else {
288                    continue;
289                };
290
291                let ast::TyKind::Path(None, bounded_path) = &where_bound.bounded_ty.kind else {
292                    continue;
293                };
294                let [ast::PathSegment { ident, args: None, .. }] = &bounded_path.segments[..]
295                else {
296                    continue;
297                };
298
299                // Only suggest for bounds that are explicitly on an in-scope type parameter.
300                let Some(partial_res) = this.r.partial_res_map.get(&where_bound.bounded_ty.id)
301                else {
302                    continue;
303                };
304                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, _))) {
305                    continue;
306                }
307
308                for bound in &where_bound.bounds {
309                    let ast::GenericBound::Trait(poly_trait_ref) = bound else { continue };
310                    record_bound(this, ident.name, poly_trait_ref);
311                }
312            }
313        };
314
315        if let Some(item) = self.diag_metadata.current_item
316            && let Some(generics) = item.kind.generics()
317        {
318            record_from_generics(self, generics);
319        }
320
321        if let Some(item) = self.diag_metadata.current_item
322            && #[allow(non_exhaustive_omitted_patterns)] match item.kind {
    ItemKind::Impl(..) => true,
    _ => false,
}matches!(item.kind, ItemKind::Impl(..))
323            && let Some(assoc) = self.diag_metadata.current_impl_item
324        {
325            let generics = match &assoc.kind {
326                AssocItemKind::Const(box ast::ConstItem { generics, .. })
327                | AssocItemKind::Fn(box ast::Fn { generics, .. })
328                | AssocItemKind::Type(box ast::TyAlias { generics, .. }) => Some(generics),
329                AssocItemKind::Delegation(..)
330                | AssocItemKind::MacCall(..)
331                | AssocItemKind::DelegationMac(..) => None,
332            };
333            if let Some(generics) = generics {
334                record_from_generics(self, generics);
335            }
336        }
337
338        let mut suggestions: FxIndexSet<String> = FxIndexSet::default();
339        for (ty_param, traits) in matching_bounds {
340            let ty_param = ty_param.to_ident_string();
341            let trait_paths_len: usize = traits.values().map(|(_, paths)| paths.len()).sum();
342            if traits.len() == 1 && trait_paths_len == 1 {
343                let assoc_type_def_id = traits.values().next().unwrap().0;
344                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!(
345                    "{}{}",
346                    assoc_name,
347                    self.r.item_required_generic_args_suggestion(assoc_type_def_id)
348                );
349                suggestions.insert(::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("{0}::{1}", ty_param,
                assoc_segment))
    })format!("{ty_param}::{assoc_segment}"));
350            } else {
351                for (assoc_type_def_id, trait_paths) in traits.into_values() {
352                    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!(
353                        "{}{}",
354                        assoc_name,
355                        self.r.item_required_generic_args_suggestion(assoc_type_def_id)
356                    );
357                    for trait_path in trait_paths {
358                        suggestions
359                            .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}"));
360                    }
361                }
362            }
363        }
364
365        if suggestions.is_empty() {
366            return false;
367        }
368
369        let mut suggestions: Vec<String> = suggestions.into_iter().collect();
370        suggestions.sort();
371
372        err.span_suggestions_with_style(
373            ident_span,
374            "you might have meant to use an associated type of the same name",
375            suggestions,
376            Applicability::MaybeIncorrect,
377            SuggestionStyle::ShowAlways,
378        );
379
380        true
381    }
382
383    fn make_base_error(
384        &mut self,
385        path: &[Segment],
386        span: Span,
387        source: PathSource<'_, 'ast, 'ra>,
388        res: Option<Res>,
389    ) -> BaseError {
390        // Make the base error.
391        let mut expected = source.descr_expected();
392        let path_str = Segment::names_to_string(path);
393        let item_str = path.last().unwrap().ident;
394
395        if let Some(res) = res {
396            BaseError {
397                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),
398                fallback_label: ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("not a {0}", expected))
    })format!("not a {expected}"),
399                span,
400                span_label: match res {
401                    Res::Def(DefKind::TyParam, def_id) => {
402                        Some((self.r.def_span(def_id), "found this type parameter"))
403                    }
404                    _ => None,
405                },
406                could_be_expr: match res {
407                    Res::Def(DefKind::Fn, _) => {
408                        // Verify whether this is a fn call or an Fn used as a type.
409                        self.r
410                            .tcx
411                            .sess
412                            .source_map()
413                            .span_to_snippet(span)
414                            .is_ok_and(|snippet| snippet.ends_with(')'))
415                    }
416                    Res::Def(
417                        DefKind::Ctor(..)
418                        | DefKind::AssocFn
419                        | DefKind::Const { .. }
420                        | DefKind::AssocConst { .. },
421                        _,
422                    )
423                    | Res::SelfCtor(_)
424                    | Res::PrimTy(_)
425                    | Res::Local(_) => true,
426                    _ => false,
427                },
428                suggestion: None,
429                module: None,
430            }
431        } else {
432            let mut span_label = None;
433            let item_ident = path.last().unwrap().ident;
434            let item_span = item_ident.span;
435            let (mod_prefix, mod_str, module, suggestion) = if path.len() == 1 {
436                {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event compiler/rustc_resolve/src/late/diagnostics.rs:436",
                        "rustc_resolve::late::diagnostics", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_resolve/src/late/diagnostics.rs"),
                        ::tracing_core::__macro_support::Option::Some(436u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_resolve::late::diagnostics"),
                        ::tracing_core::field::FieldSet::new(&["self.diag_metadata.current_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);
437                {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event compiler/rustc_resolve/src/late/diagnostics.rs:437",
                        "rustc_resolve::late::diagnostics", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_resolve/src/late/diagnostics.rs"),
                        ::tracing_core::__macro_support::Option::Some(437u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_resolve::late::diagnostics"),
                        ::tracing_core::field::FieldSet::new(&["self.diag_metadata.current_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);
438                let suggestion = if self.current_trait_ref.is_none()
439                    && let Some((fn_kind, _)) = self.diag_metadata.current_function
440                    && let Some(FnCtxt::Assoc(_)) = fn_kind.ctxt()
441                    && let FnKind::Fn(_, _, ast::Fn { sig, .. }) = fn_kind
442                    && let Some(items) = self.diag_metadata.current_impl_items
443                    && let Some(item) = items.iter().find(|i| {
444                        i.kind.ident().is_some_and(|ident| {
445                            // Don't suggest if the item is in Fn signature arguments (#112590).
446                            ident.name == item_str.name && !sig.span.contains(item_span)
447                        })
448                    }) {
449                    let sp = item_span.shrink_to_lo();
450
451                    // Account for `Foo { field }` when suggesting `self.field` so we result on
452                    // `Foo { field: self.field }`.
453                    let field = match source {
454                        PathSource::Expr(Some(Expr { kind: ExprKind::Struct(expr), .. })) => {
455                            expr.fields.iter().find(|f| f.ident == item_ident)
456                        }
457                        _ => None,
458                    };
459                    let pre = if let Some(field) = field
460                        && field.is_shorthand
461                    {
462                        ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("{0}: ", item_ident))
    })format!("{item_ident}: ")
463                    } else {
464                        String::new()
465                    };
466                    // Ensure we provide a structured suggestion for an assoc fn only for
467                    // expressions that are actually a fn call.
468                    let is_call = match field {
469                        Some(ast::ExprField { expr, .. }) => {
470                            #[allow(non_exhaustive_omitted_patterns)] match expr.kind {
    ExprKind::Call(..) => true,
    _ => false,
}matches!(expr.kind, ExprKind::Call(..))
471                        }
472                        _ => #[allow(non_exhaustive_omitted_patterns)] match source {
    PathSource::Expr(Some(Expr { kind: ExprKind::Call(..), .. })) => true,
    _ => false,
}matches!(
473                            source,
474                            PathSource::Expr(Some(Expr { kind: ExprKind::Call(..), .. })),
475                        ),
476                    };
477
478                    match &item.kind {
479                        AssocItemKind::Fn(fn_)
480                            if (!sig.decl.has_self() || !is_call) && fn_.sig.decl.has_self() =>
481                        {
482                            // Ensure that we only suggest `self.` if `self` is available,
483                            // you can't call `fn foo(&self)` from `fn bar()` (#115992).
484                            // We also want to mention that the method exists.
485                            span_label = Some((
486                                fn_.ident.span,
487                                "a method by that name is available on `Self` here",
488                            ));
489                            None
490                        }
491                        AssocItemKind::Fn(fn_) if !fn_.sig.decl.has_self() && !is_call => {
492                            span_label = Some((
493                                fn_.ident.span,
494                                "an associated function by that name is available on `Self` here",
495                            ));
496                            None
497                        }
498                        AssocItemKind::Fn(fn_) if fn_.sig.decl.has_self() => {
499                            Some((sp, "consider using the method on `Self`", ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("{0}self.", pre))
    })format!("{pre}self.")))
500                        }
501                        AssocItemKind::Fn(_) => Some((
502                            sp,
503                            "consider using the associated function on `Self`",
504                            ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("{0}Self::", pre))
    })format!("{pre}Self::"),
505                        )),
506                        AssocItemKind::Const(..) => Some((
507                            sp,
508                            "consider using the associated constant on `Self`",
509                            ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("{0}Self::", pre))
    })format!("{pre}Self::"),
510                        )),
511                        _ => None,
512                    }
513                } else {
514                    None
515                };
516                (String::new(), "this scope".to_string(), None, suggestion)
517            } else if path.len() == 2 && path[0].ident.name == kw::PathRoot {
518                if self.r.tcx.sess.edition() > Edition::Edition2015 {
519                    // In edition 2018 onwards, the `::foo` syntax may only pull from the extern prelude
520                    // which overrides all other expectations of item type
521                    expected = "crate";
522                    (String::new(), "the list of imported crates".to_string(), None, None)
523                } else {
524                    (
525                        String::new(),
526                        "the crate root".to_string(),
527                        Some(CRATE_DEF_ID.to_def_id()),
528                        None,
529                    )
530                }
531            } else if path.len() == 2 && path[0].ident.name == kw::Crate {
532                (String::new(), "the crate root".to_string(), Some(CRATE_DEF_ID.to_def_id()), None)
533            } else {
534                let mod_path = &path[..path.len() - 1];
535                let mod_res = self.resolve_path(mod_path, Some(TypeNS), None, source);
536                let mod_prefix = match mod_res {
537                    PathResult::Module(ModuleOrUniformRoot::Module(module)) => module.res(),
538                    _ => None,
539                };
540
541                let module_did = mod_prefix.as_ref().and_then(Res::mod_def_id);
542
543                let mod_prefix =
544                    mod_prefix.map_or_else(String::new, |res| ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("{0} ", res.descr()))
    })format!("{} ", res.descr()));
545                (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)
546            };
547
548            let (fallback_label, suggestion) = if path_str == "async"
549                && expected.starts_with("struct")
550            {
551                ("`async` blocks are only allowed in Rust 2018 or later".to_string(), suggestion)
552            } else {
553                // check if we are in situation of typo like `True` instead of `true`.
554                let override_suggestion =
555                    if ["true", "false"].contains(&item_str.to_string().to_lowercase().as_str()) {
556                        let item_typo = item_str.to_string().to_lowercase();
557                        Some((item_span, "you may want to use a bool value instead", item_typo))
558                    // FIXME(vincenzopalazzo): make the check smarter,
559                    // and maybe expand with levenshtein distance checks
560                    } else if item_str.as_str() == "printf" {
561                        Some((
562                            item_span,
563                            "you may have meant to use the `print` macro",
564                            "print!".to_owned(),
565                        ))
566                    } else {
567                        suggestion
568                    };
569                (::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("not found in {0}", mod_str))
    })format!("not found in {mod_str}"), override_suggestion)
570            };
571
572            BaseError {
573                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}"),
574                fallback_label,
575                span: item_span,
576                span_label,
577                could_be_expr: false,
578                suggestion,
579                module,
580            }
581        }
582    }
583
584    /// Try to suggest for a module path that cannot be resolved.
585    /// Such as `fmt::Debug` where `fmt` is not resolved without importing,
586    /// here we search with `lookup_import_candidates` for a module named `fmt`
587    /// with `TypeNS` as namespace.
588    ///
589    /// We need a separate function here because we won't suggest for a path with single segment
590    /// and we won't change `SourcePath` api `is_expected` to match `Type` with `DefKind::Mod`
591    pub(crate) fn smart_resolve_partial_mod_path_errors(
592        &mut self,
593        prefix_path: &[Segment],
594        following_seg: Option<&Segment>,
595    ) -> Vec<ImportSuggestion> {
596        if let Some(segment) = prefix_path.last()
597            && let Some(following_seg) = following_seg
598        {
599            let candidates = self.r.lookup_import_candidates(
600                segment.ident,
601                Namespace::TypeNS,
602                &self.parent_scope,
603                &|res: Res| #[allow(non_exhaustive_omitted_patterns)] match res {
    Res::Def(DefKind::Mod, _) => true,
    _ => false,
}matches!(res, Res::Def(DefKind::Mod, _)),
604            );
605            // double check next seg is valid
606            candidates
607                .into_iter()
608                .filter(|candidate| {
609                    if let Some(def_id) = candidate.did
610                        && let Some(module) = self.r.get_module(def_id)
611                    {
612                        Some(def_id) != self.parent_scope.module.opt_def_id()
613                            && self
614                                .r
615                                .resolutions(module)
616                                .borrow()
617                                .iter()
618                                .any(|(key, _r)| key.ident.name == following_seg.ident.name)
619                    } else {
620                        false
621                    }
622                })
623                .collect::<Vec<_>>()
624        } else {
625            Vec::new()
626        }
627    }
628
629    /// Handles error reporting for `smart_resolve_path_fragment` function.
630    /// Creates base error and amends it with one short label and possibly some longer helps/notes.
631    #[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(631u32),
                                    ::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:641",
                                    "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(641u32),
                                    ::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")]
632    pub(crate) fn smart_resolve_report_errors(
633        &mut self,
634        path: &[Segment],
635        following_seg: Option<&Segment>,
636        span: Span,
637        source: PathSource<'_, 'ast, 'ra>,
638        res: Option<Res>,
639        qself: Option<&QSelf>,
640    ) -> (Diag<'tcx>, Vec<ImportSuggestion>) {
641        debug!(?res, ?source);
642        let base_error = self.make_base_error(path, span, source, res);
643
644        let code = source.error_code(res.is_some());
645        let mut err = self.r.dcx().struct_span_err(base_error.span, base_error.msg.clone());
646        err.code(code);
647
648        // Try to get the span of the identifier within the path's syntax context
649        // (if that's different).
650        if let Some(within_macro_span) =
651            base_error.span.within_macro(span, self.r.tcx.sess.source_map())
652        {
653            err.span_label(within_macro_span, "due to this macro variable");
654        }
655
656        self.detect_missing_binding_available_from_pattern(&mut err, path, following_seg);
657        self.suggest_at_operator_in_slice_pat_with_range(&mut err, path);
658        self.suggest_range_struct_destructuring(&mut err, path, source);
659        self.suggest_swapping_misplaced_self_ty_and_trait(&mut err, source, res, base_error.span);
660
661        if let Some((span, label)) = base_error.span_label {
662            err.span_label(span, label);
663        }
664
665        if let Some(ref sugg) = base_error.suggestion {
666            err.span_suggestion_verbose(sugg.0, sugg.1, &sugg.2, Applicability::MaybeIncorrect);
667        }
668
669        self.suggest_changing_type_to_const_param(&mut err, res, source, path, following_seg, span);
670        self.explain_functions_in_pattern(&mut err, res, source);
671
672        if self.suggest_pattern_match_with_let(&mut err, source, span) {
673            // Fallback label.
674            err.span_label(base_error.span, base_error.fallback_label);
675            return (err, Vec::new());
676        }
677
678        self.suggest_self_or_self_ref(&mut err, path, span);
679        self.detect_assoc_type_constraint_meant_as_path(&mut err, &base_error);
680        self.detect_rtn_with_fully_qualified_path(
681            &mut err,
682            path,
683            following_seg,
684            span,
685            source,
686            res,
687            qself,
688        );
689        if self.suggest_self_ty(&mut err, source, path, span)
690            || self.suggest_self_value(&mut err, source, path, span)
691        {
692            return (err, Vec::new());
693        }
694
695        if let Some((did, item)) = self.lookup_doc_alias_name(path, source.namespace()) {
696            let item_name = item.name;
697            let suggestion_name = self.r.tcx.item_name(did);
698            err.span_suggestion(
699                item.span,
700                format!("`{suggestion_name}` has a name defined in the doc alias attribute as `{item_name}`"),
701                    suggestion_name,
702                    Applicability::MaybeIncorrect
703                );
704
705            return (err, Vec::new());
706        };
707
708        let (found, suggested_candidates, mut candidates) = self.try_lookup_name_relaxed(
709            &mut err,
710            source,
711            path,
712            following_seg,
713            span,
714            res,
715            &base_error,
716        );
717        if found {
718            return (err, candidates);
719        }
720
721        if self.suggest_shadowed(&mut err, source, path, following_seg, span) {
722            // if there is already a shadowed name, don'suggest candidates for importing
723            candidates.clear();
724        }
725
726        let mut fallback = self.suggest_trait_and_bounds(&mut err, source, res, span, &base_error);
727        fallback |= self.suggest_typo(
728            &mut err,
729            source,
730            path,
731            following_seg,
732            span,
733            &base_error,
734            suggested_candidates,
735        );
736
737        if fallback {
738            // Fallback label.
739            err.span_label(base_error.span, base_error.fallback_label);
740        }
741        self.err_code_special_cases(&mut err, source, path, span);
742
743        let module = base_error.module.unwrap_or_else(|| CRATE_DEF_ID.to_def_id());
744        self.r.find_cfg_stripped(&mut err, &path.last().unwrap().ident.name, module);
745
746        (err, candidates)
747    }
748
749    fn detect_rtn_with_fully_qualified_path(
750        &self,
751        err: &mut Diag<'_>,
752        path: &[Segment],
753        following_seg: Option<&Segment>,
754        span: Span,
755        source: PathSource<'_, '_, '_>,
756        res: Option<Res>,
757        qself: Option<&QSelf>,
758    ) {
759        if let Some(Res::Def(DefKind::AssocFn, _)) = res
760            && let PathSource::TraitItem(TypeNS, _) = source
761            && let None = following_seg
762            && let Some(qself) = qself
763            && let TyKind::Path(None, ty_path) = &qself.ty.kind
764            && ty_path.segments.len() == 1
765            && self.diag_metadata.current_where_predicate.is_some()
766        {
767            err.span_suggestion_verbose(
768                span,
769                "you might have meant to use the return type notation syntax",
770                ::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),
771                Applicability::MaybeIncorrect,
772            );
773        }
774    }
775
776    fn detect_assoc_type_constraint_meant_as_path(
777        &self,
778        err: &mut Diag<'_>,
779        base_error: &BaseError,
780    ) {
781        let Some(ty) = self.diag_metadata.current_type_path else {
782            return;
783        };
784        let TyKind::Path(_, path) = &ty.kind else {
785            return;
786        };
787        for segment in &path.segments {
788            let Some(params) = &segment.args else {
789                continue;
790            };
791            let ast::GenericArgs::AngleBracketed(params) = params.deref() else {
792                continue;
793            };
794            for param in &params.args {
795                let ast::AngleBracketedArg::Constraint(constraint) = param else {
796                    continue;
797                };
798                let ast::AssocItemConstraintKind::Bound { bounds } = &constraint.kind else {
799                    continue;
800                };
801                for bound in bounds {
802                    let ast::GenericBound::Trait(trait_ref) = bound else {
803                        continue;
804                    };
805                    if trait_ref.modifiers == ast::TraitBoundModifiers::NONE
806                        && base_error.span == trait_ref.span
807                    {
808                        err.span_suggestion_verbose(
809                            constraint.ident.span.between(trait_ref.span),
810                            "you might have meant to write a path instead of an associated type bound",
811                            "::",
812                            Applicability::MachineApplicable,
813                        );
814                    }
815                }
816            }
817        }
818    }
819
820    fn suggest_self_or_self_ref(&mut self, err: &mut Diag<'_>, path: &[Segment], span: Span) {
821        if !self.self_type_is_available() {
822            return;
823        }
824        let Some(path_last_segment) = path.last() else { return };
825        let item_str = path_last_segment.ident;
826        // Emit help message for fake-self from other languages (e.g., `this` in JavaScript).
827        if ["this", "my"].contains(&item_str.as_str()) {
828            err.span_suggestion_short(
829                span,
830                "you might have meant to use `self` here instead",
831                "self",
832                Applicability::MaybeIncorrect,
833            );
834            if !self.self_value_is_available(path[0].ident.span) {
835                if let Some((FnKind::Fn(_, _, ast::Fn { sig, .. }), fn_span)) =
836                    &self.diag_metadata.current_function
837                {
838                    let (span, sugg) = if let Some(param) = sig.decl.inputs.get(0) {
839                        (param.span.shrink_to_lo(), "&self, ")
840                    } else {
841                        (
842                            self.r
843                                .tcx
844                                .sess
845                                .source_map()
846                                .span_through_char(*fn_span, '(')
847                                .shrink_to_hi(),
848                            "&self",
849                        )
850                    };
851                    err.span_suggestion_verbose(
852                        span,
853                        "if you meant to use `self`, you are also missing a `self` receiver \
854                         argument",
855                        sugg,
856                        Applicability::MaybeIncorrect,
857                    );
858                }
859            }
860        }
861    }
862
863    fn try_lookup_name_relaxed(
864        &mut self,
865        err: &mut Diag<'_>,
866        source: PathSource<'_, '_, '_>,
867        path: &[Segment],
868        following_seg: Option<&Segment>,
869        span: Span,
870        res: Option<Res>,
871        base_error: &BaseError,
872    ) -> (bool, FxHashSet<String>, Vec<ImportSuggestion>) {
873        let span = match following_seg {
874            Some(_) if path[0].ident.span.eq_ctxt(path[path.len() - 1].ident.span) => {
875                // The path `span` that comes in includes any following segments, which we don't
876                // want to replace in the suggestions.
877                path[0].ident.span.to(path[path.len() - 1].ident.span)
878            }
879            _ => span,
880        };
881        let mut suggested_candidates = FxHashSet::default();
882        // Try to lookup name in more relaxed fashion for better error reporting.
883        let ident = path.last().unwrap().ident;
884        let is_expected = &|res| source.is_expected(res);
885        let ns = source.namespace();
886        let is_enum_variant = &|res| #[allow(non_exhaustive_omitted_patterns)] match res {
    Res::Def(DefKind::Variant, _) => true,
    _ => false,
}matches!(res, Res::Def(DefKind::Variant, _));
887        let path_str = Segment::names_to_string(path);
888        let ident_span = path.last().map_or(span, |ident| ident.ident.span);
889        let mut candidates = self
890            .r
891            .lookup_import_candidates(ident, ns, &self.parent_scope, is_expected)
892            .into_iter()
893            .filter(|ImportSuggestion { did, .. }| {
894                match (did, res.and_then(|res| res.opt_def_id())) {
895                    (Some(suggestion_did), Some(actual_did)) => *suggestion_did != actual_did,
896                    _ => true,
897                }
898            })
899            .collect::<Vec<_>>();
900        // Try to filter out intrinsics candidates, as long as we have
901        // some other candidates to suggest.
902        let intrinsic_candidates: Vec<_> = candidates
903            .extract_if(.., |sugg| {
904                let path = path_names_to_string(&sugg.path);
905                path.starts_with("core::intrinsics::") || path.starts_with("std::intrinsics::")
906            })
907            .collect();
908        if candidates.is_empty() {
909            // Put them back if we have no more candidates to suggest...
910            candidates = intrinsic_candidates;
911        }
912        let crate_def_id = CRATE_DEF_ID.to_def_id();
913        if candidates.is_empty() && is_expected(Res::Def(DefKind::Enum, crate_def_id)) {
914            let mut enum_candidates: Vec<_> = self
915                .r
916                .lookup_import_candidates(ident, ns, &self.parent_scope, is_enum_variant)
917                .into_iter()
918                .map(|suggestion| import_candidate_to_enum_paths(&suggestion))
919                .filter(|(_, enum_ty_path)| !enum_ty_path.starts_with("std::prelude::"))
920                .collect();
921            if !enum_candidates.is_empty() {
922                enum_candidates.sort();
923
924                // Contextualize for E0425 "cannot find type", but don't belabor the point
925                // (that it's a variant) for E0573 "expected type, found variant".
926                let preamble = if res.is_none() {
927                    let others = match enum_candidates.len() {
928                        1 => String::new(),
929                        2 => " and 1 other".to_owned(),
930                        n => ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!(" and {0} others", n))
    })format!(" and {n} others"),
931                    };
932                    ::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)
933                } else {
934                    String::new()
935                };
936                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");
937
938                suggested_candidates.extend(
939                    enum_candidates
940                        .iter()
941                        .map(|(_variant_path, enum_ty_path)| enum_ty_path.clone()),
942                );
943                err.span_suggestions(
944                    span,
945                    msg,
946                    enum_candidates.into_iter().map(|(_variant_path, enum_ty_path)| enum_ty_path),
947                    Applicability::MachineApplicable,
948                );
949            }
950        }
951
952        // Try finding a suitable replacement.
953        let typo_sugg = self
954            .lookup_typo_candidate(path, following_seg, source.namespace(), is_expected)
955            .to_opt_suggestion()
956            .filter(|sugg| !suggested_candidates.contains(sugg.candidate.as_str()));
957        if let [segment] = path
958            && !#[allow(non_exhaustive_omitted_patterns)] match source {
    PathSource::Delegation => true,
    _ => false,
}matches!(source, PathSource::Delegation)
959            && self.self_type_is_available()
960        {
961            if let Some(candidate) =
962                self.lookup_assoc_candidate(ident, ns, is_expected, source.is_call())
963            {
964                let self_is_available = self.self_value_is_available(segment.ident.span);
965                // Account for `Foo { field }` when suggesting `self.field` so we result on
966                // `Foo { field: self.field }`.
967                let pre = match source {
968                    PathSource::Expr(Some(Expr { kind: ExprKind::Struct(expr), .. }))
969                        if expr
970                            .fields
971                            .iter()
972                            .any(|f| f.ident == segment.ident && f.is_shorthand) =>
973                    {
974                        ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("{0}: ", path_str))
    })format!("{path_str}: ")
975                    }
976                    _ => String::new(),
977                };
978                match candidate {
979                    AssocSuggestion::Field(field_span) => {
980                        if self_is_available {
981                            let source_map = self.r.tcx.sess.source_map();
982                            // check if the field is used in a format string, such as `"{x}"`
983                            let field_is_format_named_arg = source_map
984                                .span_to_source(span, |s, start, _| {
985                                    Ok(s.get(start - 1..start) == Some("{"))
986                                });
987                            if let Ok(true) = field_is_format_named_arg {
988                                err.help(
989                                    ::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),
990                                );
991                            } else {
992                                err.span_suggestion_verbose(
993                                    span.shrink_to_lo(),
994                                    "you might have meant to use the available field",
995                                    ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("{0}self.", pre))
    })format!("{pre}self."),
996                                    Applicability::MaybeIncorrect,
997                                );
998                            }
999                        } else {
1000                            err.span_label(field_span, "a field by that name exists in `Self`");
1001                        }
1002                    }
1003                    AssocSuggestion::MethodWithSelf { called } if self_is_available => {
1004                        let msg = if called {
1005                            "you might have meant to call the method"
1006                        } else {
1007                            "you might have meant to refer to the method"
1008                        };
1009                        err.span_suggestion_verbose(
1010                            span.shrink_to_lo(),
1011                            msg,
1012                            "self.",
1013                            Applicability::MachineApplicable,
1014                        );
1015                    }
1016                    AssocSuggestion::MethodWithSelf { .. }
1017                    | AssocSuggestion::AssocFn { .. }
1018                    | AssocSuggestion::AssocConst
1019                    | AssocSuggestion::AssocType => {
1020                        err.span_suggestion_verbose(
1021                            span.shrink_to_lo(),
1022                            ::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()),
1023                            "Self::",
1024                            Applicability::MachineApplicable,
1025                        );
1026                    }
1027                }
1028                self.r.add_typo_suggestion(err, typo_sugg, ident_span);
1029                return (true, suggested_candidates, candidates);
1030            }
1031
1032            // If the first argument in call is `self` suggest calling a method.
1033            if let Some((call_span, args_span)) = self.call_has_self_arg(source) {
1034                let mut args_snippet = String::new();
1035                if let Some(args_span) = args_span
1036                    && let Ok(snippet) = self.r.tcx.sess.source_map().span_to_snippet(args_span)
1037                {
1038                    args_snippet = snippet;
1039                }
1040
1041                if let Some(Res::Def(DefKind::Struct, def_id)) = res {
1042                    let private_fields = self.has_private_fields(def_id);
1043                    let adjust_error_message =
1044                        private_fields && self.is_struct_with_fn_ctor(def_id);
1045                    if adjust_error_message {
1046                        self.update_err_for_private_tuple_struct_fields(err, &source, def_id);
1047                    }
1048
1049                    if private_fields {
1050                        err.note("constructor is not visible here due to private fields");
1051                    }
1052                } else {
1053                    err.span_suggestion(
1054                        call_span,
1055                        ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("try calling `{0}` as a method",
                ident))
    })format!("try calling `{ident}` as a method"),
1056                        ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("self.{0}({1})", path_str,
                args_snippet))
    })format!("self.{path_str}({args_snippet})"),
1057                        Applicability::MachineApplicable,
1058                    );
1059                }
1060
1061                return (true, suggested_candidates, candidates);
1062            }
1063        }
1064
1065        // Try context-dependent help if relaxed lookup didn't work.
1066        if let Some(res) = res {
1067            if self.smart_resolve_context_dependent_help(
1068                err,
1069                span,
1070                source,
1071                path,
1072                res,
1073                &path_str,
1074                &base_error.fallback_label,
1075            ) {
1076                // We do this to avoid losing a secondary span when we override the main error span.
1077                self.r.add_typo_suggestion(err, typo_sugg, ident_span);
1078                return (true, suggested_candidates, candidates);
1079            }
1080        }
1081
1082        // Try to find in last block rib
1083        if let Some(rib) = &self.last_block_rib {
1084            for (ident, &res) in &rib.bindings {
1085                if let Res::Local(_) = res
1086                    && path.len() == 1
1087                    && ident.span.eq_ctxt(path[0].ident.span)
1088                    && ident.name == path[0].ident.name
1089                {
1090                    err.span_help(
1091                        ident.span,
1092                        ::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"),
1093                    );
1094                    return (true, suggested_candidates, candidates);
1095                }
1096            }
1097        }
1098
1099        if candidates.is_empty() {
1100            candidates = self.smart_resolve_partial_mod_path_errors(path, following_seg);
1101        }
1102
1103        (false, suggested_candidates, candidates)
1104    }
1105
1106    fn lookup_doc_alias_name(&mut self, path: &[Segment], ns: Namespace) -> Option<(DefId, Ident)> {
1107        let find_doc_alias_name = |r: &mut Resolver<'ra, '_>, m: Module<'ra>, item_name: Symbol| {
1108            for resolution in r.resolutions(m).borrow().values() {
1109                let Some(did) =
1110                    resolution.borrow().best_decl().and_then(|binding| binding.res().opt_def_id())
1111                else {
1112                    continue;
1113                };
1114                if did.is_local() {
1115                    // We don't record the doc alias name in the local crate
1116                    // because the people who write doc alias are usually not
1117                    // confused by them.
1118                    continue;
1119                }
1120                if let Some(d) = {

    #[allow(deprecated)]
    {
        {
            'done:
                {
                for i in r.tcx.get_all_attrs(did) {
                    #[allow(unused_imports)]
                    use rustc_hir::attrs::AttributeKind::*;
                    let i: &rustc_hir::Attribute = i;
                    match i {
                        rustc_hir::Attribute::Parsed(Doc(d)) => {
                            break 'done Some(d);
                        }
                        rustc_hir::Attribute::Unparsed(..) =>
                            {}
                            #[deny(unreachable_patterns)]
                            _ => {}
                    }
                }
                None
            }
        }
    }
}hir::find_attr!(r.tcx, did, Doc(d) => d)
1121                    && d.aliases.contains_key(&item_name)
1122                {
1123                    return Some(did);
1124                }
1125            }
1126            None
1127        };
1128
1129        if path.len() == 1 {
1130            for rib in self.ribs[ns].iter().rev() {
1131                let item = path[0].ident;
1132                if let RibKind::Module(module) | RibKind::Block(Some(module)) = rib.kind
1133                    && let Some(did) = find_doc_alias_name(self.r, module, item.name)
1134                {
1135                    return Some((did, item));
1136                }
1137            }
1138        } else {
1139            // Finds to the last resolved module item in the path
1140            // and searches doc aliases within that module.
1141            //
1142            // Example: For the path `a::b::last_resolved::not_exist::c::d`,
1143            // we will try to find any item has doc aliases named `not_exist`
1144            // in `last_resolved` module.
1145            //
1146            // - Use `skip(1)` because the final segment must remain unresolved.
1147            for (idx, seg) in path.iter().enumerate().rev().skip(1) {
1148                let Some(id) = seg.id else {
1149                    continue;
1150                };
1151                let Some(res) = self.r.partial_res_map.get(&id) else {
1152                    continue;
1153                };
1154                if let Res::Def(DefKind::Mod, module) = res.expect_full_res()
1155                    && let module = self.r.expect_module(module)
1156                    && let item = path[idx + 1].ident
1157                    && let Some(did) = find_doc_alias_name(self.r, module, item.name)
1158                {
1159                    return Some((did, item));
1160                }
1161                break;
1162            }
1163        }
1164        None
1165    }
1166
1167    fn suggest_trait_and_bounds(
1168        &self,
1169        err: &mut Diag<'_>,
1170        source: PathSource<'_, '_, '_>,
1171        res: Option<Res>,
1172        span: Span,
1173        base_error: &BaseError,
1174    ) -> bool {
1175        let is_macro =
1176            base_error.span.from_expansion() && base_error.span.desugaring_kind().is_none();
1177        let mut fallback = false;
1178
1179        if let (
1180            PathSource::Trait(AliasPossibility::Maybe),
1181            Some(Res::Def(DefKind::Struct | DefKind::Enum | DefKind::Union, _)),
1182            false,
1183        ) = (source, res, is_macro)
1184            && let Some(bounds @ [first_bound, .., last_bound]) =
1185                self.diag_metadata.current_trait_object
1186        {
1187            fallback = true;
1188            let spans: Vec<Span> = bounds
1189                .iter()
1190                .map(|bound| bound.span())
1191                .filter(|&sp| sp != base_error.span)
1192                .collect();
1193
1194            let start_span = first_bound.span();
1195            // `end_span` is the end of the poly trait ref (Foo + 'baz + Bar><)
1196            let end_span = last_bound.span();
1197            // `last_bound_span` is the last bound of the poly trait ref (Foo + >'baz< + Bar)
1198            let last_bound_span = spans.last().cloned().unwrap();
1199            let mut multi_span: MultiSpan = spans.clone().into();
1200            for sp in spans {
1201                let msg = if sp == last_bound_span {
1202                    ::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!(
1203                        "...because of {these} bound{s}",
1204                        these = pluralize!("this", bounds.len() - 1),
1205                        s = pluralize!(bounds.len() - 1),
1206                    )
1207                } else {
1208                    String::new()
1209                };
1210                multi_span.push_span_label(sp, msg);
1211            }
1212            multi_span.push_span_label(base_error.span, "expected this type to be a trait...");
1213            err.span_help(
1214                multi_span,
1215                "`+` is used to constrain a \"trait object\" type with lifetimes or \
1216                        auto-traits; structs and enums can't be bound in that way",
1217            );
1218            if bounds.iter().all(|bound| match bound {
1219                ast::GenericBound::Outlives(_) | ast::GenericBound::Use(..) => true,
1220                ast::GenericBound::Trait(tr) => tr.span == base_error.span,
1221            }) {
1222                let mut sugg = ::alloc::vec::Vec::new()vec![];
1223                if base_error.span != start_span {
1224                    sugg.push((start_span.until(base_error.span), String::new()));
1225                }
1226                if base_error.span != end_span {
1227                    sugg.push((base_error.span.shrink_to_hi().to(end_span), String::new()));
1228                }
1229
1230                err.multipart_suggestion(
1231                    "if you meant to use a type and not a trait here, remove the bounds",
1232                    sugg,
1233                    Applicability::MaybeIncorrect,
1234                );
1235            }
1236        }
1237
1238        fallback |= self.restrict_assoc_type_in_where_clause(span, err);
1239        fallback
1240    }
1241
1242    fn suggest_typo(
1243        &mut self,
1244        err: &mut Diag<'_>,
1245        source: PathSource<'_, 'ast, 'ra>,
1246        path: &[Segment],
1247        following_seg: Option<&Segment>,
1248        span: Span,
1249        base_error: &BaseError,
1250        suggested_candidates: FxHashSet<String>,
1251    ) -> bool {
1252        let is_expected = &|res| source.is_expected(res);
1253        let ident_span = path.last().map_or(span, |ident| ident.ident.span);
1254
1255        // Prefer suggestions based on associated types from in-scope bounds (e.g. `T::Item`)
1256        // over purely edit-distance-based identifier suggestions.
1257        // Otherwise suggestions could be verbose.
1258        if self.suggest_assoc_type_from_bounds(err, source, path, ident_span) {
1259            return false;
1260        }
1261
1262        let typo_sugg =
1263            self.lookup_typo_candidate(path, following_seg, source.namespace(), is_expected);
1264        let mut fallback = false;
1265        let typo_sugg = typo_sugg
1266            .to_opt_suggestion()
1267            .filter(|sugg| !suggested_candidates.contains(sugg.candidate.as_str()));
1268        if !self.r.add_typo_suggestion(err, typo_sugg, ident_span) {
1269            fallback = true;
1270            match self.diag_metadata.current_let_binding {
1271                Some((pat_sp, Some(ty_sp), None))
1272                    if ty_sp.contains(base_error.span) && base_error.could_be_expr =>
1273                {
1274                    err.span_suggestion_short(
1275                        pat_sp.between(ty_sp),
1276                        "use `=` if you meant to assign",
1277                        " = ",
1278                        Applicability::MaybeIncorrect,
1279                    );
1280                }
1281                _ => {}
1282            }
1283
1284            // If the trait has a single item (which wasn't matched by the algorithm), suggest it
1285            let suggestion = self.get_single_associated_item(path, &source, is_expected);
1286            self.r.add_typo_suggestion(err, suggestion, ident_span);
1287        }
1288
1289        if self.let_binding_suggestion(err, ident_span) {
1290            fallback = false;
1291        }
1292
1293        fallback
1294    }
1295
1296    fn suggest_shadowed(
1297        &mut self,
1298        err: &mut Diag<'_>,
1299        source: PathSource<'_, '_, '_>,
1300        path: &[Segment],
1301        following_seg: Option<&Segment>,
1302        span: Span,
1303    ) -> bool {
1304        let is_expected = &|res| source.is_expected(res);
1305        let typo_sugg =
1306            self.lookup_typo_candidate(path, following_seg, source.namespace(), is_expected);
1307        let is_in_same_file = &|sp1, sp2| {
1308            let source_map = self.r.tcx.sess.source_map();
1309            let file1 = source_map.span_to_filename(sp1);
1310            let file2 = source_map.span_to_filename(sp2);
1311            file1 == file2
1312        };
1313        // print 'you might have meant' if the candidate is (1) is a shadowed name with
1314        // accessible definition and (2) either defined in the same crate as the typo
1315        // (could be in a different file) or introduced in the same file as the typo
1316        // (could belong to a different crate)
1317        if let TypoCandidate::Shadowed(res, Some(sugg_span)) = typo_sugg
1318            && res.opt_def_id().is_some_and(|id| id.is_local() || is_in_same_file(span, sugg_span))
1319        {
1320            err.span_label(
1321                sugg_span,
1322                ::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()),
1323            );
1324            return true;
1325        }
1326        false
1327    }
1328
1329    fn err_code_special_cases(
1330        &mut self,
1331        err: &mut Diag<'_>,
1332        source: PathSource<'_, '_, '_>,
1333        path: &[Segment],
1334        span: Span,
1335    ) {
1336        if let Some(err_code) = err.code {
1337            if err_code == E0425 {
1338                for label_rib in &self.label_ribs {
1339                    for (label_ident, node_id) in &label_rib.bindings {
1340                        let ident = path.last().unwrap().ident;
1341                        if ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("\'{0}", ident))
    })format!("'{ident}") == label_ident.to_string() {
1342                            err.span_label(label_ident.span, "a label with a similar name exists");
1343                            if let PathSource::Expr(Some(Expr {
1344                                kind: ExprKind::Break(None, Some(_)),
1345                                ..
1346                            })) = source
1347                            {
1348                                err.span_suggestion(
1349                                    span,
1350                                    "use the similarly named label",
1351                                    label_ident.name,
1352                                    Applicability::MaybeIncorrect,
1353                                );
1354                                // Do not lint against unused label when we suggest them.
1355                                self.diag_metadata.unused_labels.swap_remove(node_id);
1356                            }
1357                        }
1358                    }
1359                }
1360
1361                self.suggest_ident_hidden_by_hygiene(err, path, span);
1362                // cannot find type in this scope
1363                if let Some(correct) = Self::likely_rust_type(path) {
1364                    err.span_suggestion(
1365                        span,
1366                        "perhaps you intended to use this type",
1367                        correct,
1368                        Applicability::MaybeIncorrect,
1369                    );
1370                }
1371            }
1372        }
1373    }
1374
1375    fn suggest_ident_hidden_by_hygiene(&self, err: &mut Diag<'_>, path: &[Segment], span: Span) {
1376        let [segment] = path else { return };
1377
1378        let ident = segment.ident;
1379        let callsite_span = span.source_callsite();
1380        for rib in self.ribs[ValueNS].iter().rev() {
1381            for (binding_ident, _) in &rib.bindings {
1382                // Case 1: the identifier is defined in the same scope as the macro is called
1383                if binding_ident.name == ident.name
1384                    && !binding_ident.span.eq_ctxt(span)
1385                    && !binding_ident.span.from_expansion()
1386                    && binding_ident.span.lo() < callsite_span.lo()
1387                {
1388                    err.span_help(
1389                        binding_ident.span,
1390                        "an identifier with the same name exists, but is not accessible due to macro hygiene",
1391                    );
1392                    return;
1393                }
1394
1395                // Case 2: the identifier is defined in a macro call in the same scope
1396                if binding_ident.name == ident.name
1397                    && binding_ident.span.from_expansion()
1398                    && binding_ident.span.source_callsite().eq_ctxt(callsite_span)
1399                    && binding_ident.span.source_callsite().lo() < callsite_span.lo()
1400                {
1401                    err.span_help(
1402                        binding_ident.span,
1403                        "an identifier with the same name is defined here, but is not accessible due to macro hygiene",
1404                    );
1405                    return;
1406                }
1407            }
1408        }
1409    }
1410
1411    /// Emit special messages for unresolved `Self` and `self`.
1412    fn suggest_self_ty(
1413        &self,
1414        err: &mut Diag<'_>,
1415        source: PathSource<'_, '_, '_>,
1416        path: &[Segment],
1417        span: Span,
1418    ) -> bool {
1419        if !is_self_type(path, source.namespace()) {
1420            return false;
1421        }
1422        err.code(E0411);
1423        err.span_label(span, "`Self` is only available in impls, traits, and type definitions");
1424        if let Some(item) = self.diag_metadata.current_item
1425            && let Some(ident) = item.kind.ident()
1426        {
1427            err.span_label(
1428                ident.span,
1429                ::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()),
1430            );
1431        }
1432        true
1433    }
1434
1435    fn suggest_self_value(
1436        &mut self,
1437        err: &mut Diag<'_>,
1438        source: PathSource<'_, '_, '_>,
1439        path: &[Segment],
1440        span: Span,
1441    ) -> bool {
1442        if !is_self_value(path, source.namespace()) {
1443            return false;
1444        }
1445
1446        {
    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:1446",
                        "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(1446u32),
                        ::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);
1447        err.code(E0424);
1448        err.span_label(
1449            span,
1450            match source {
1451                PathSource::Pat => {
1452                    "`self` value is a keyword and may not be bound to variables or shadowed"
1453                }
1454                _ => "`self` value is a keyword only available in methods with a `self` parameter",
1455            },
1456        );
1457
1458        // using `let self` is wrong even if we're not in an associated method or if we're in a macro expansion.
1459        // So, we should return early if we're in a pattern, see issue #143134.
1460        if #[allow(non_exhaustive_omitted_patterns)] match source {
    PathSource::Pat => true,
    _ => false,
}matches!(source, PathSource::Pat) {
1461            return true;
1462        }
1463
1464        let is_assoc_fn = self.self_type_is_available();
1465        let self_from_macro = "a `self` parameter, but a macro invocation can only \
1466                               access identifiers it receives from parameters";
1467        if let Some((fn_kind, fn_span)) = &self.diag_metadata.current_function {
1468            // The current function has a `self` parameter, but we were unable to resolve
1469            // a reference to `self`. This can only happen if the `self` identifier we
1470            // are resolving came from a different hygiene context or a variable binding.
1471            // But variable binding error is returned early above.
1472            if fn_kind.decl().inputs.get(0).is_some_and(|p| p.is_self()) {
1473                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}"));
1474            } else {
1475                let doesnt = if is_assoc_fn {
1476                    let (span, sugg) = fn_kind
1477                        .decl()
1478                        .inputs
1479                        .get(0)
1480                        .map(|p| (p.span.shrink_to_lo(), "&self, "))
1481                        .unwrap_or_else(|| {
1482                            // Try to look for the "(" after the function name, if possible.
1483                            // This avoids placing the suggestion into the visibility specifier.
1484                            let span = fn_kind
1485                                .ident()
1486                                .map_or(*fn_span, |ident| fn_span.with_lo(ident.span.hi()));
1487                            (
1488                                self.r
1489                                    .tcx
1490                                    .sess
1491                                    .source_map()
1492                                    .span_through_char(span, '(')
1493                                    .shrink_to_hi(),
1494                                "&self",
1495                            )
1496                        });
1497                    err.span_suggestion_verbose(
1498                        span,
1499                        "add a `self` receiver parameter to make the associated `fn` a method",
1500                        sugg,
1501                        Applicability::MaybeIncorrect,
1502                    );
1503                    "doesn't"
1504                } else {
1505                    "can't"
1506                };
1507                if let Some(ident) = fn_kind.ident() {
1508                    err.span_label(
1509                        ident.span,
1510                        ::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"),
1511                    );
1512                }
1513            }
1514        } else if let Some(item) = self.diag_metadata.current_item {
1515            if #[allow(non_exhaustive_omitted_patterns)] match item.kind {
    ItemKind::Delegation(..) => true,
    _ => false,
}matches!(item.kind, ItemKind::Delegation(..)) {
1516                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}"));
1517            } else {
1518                let span = if let Some(ident) = item.kind.ident() { ident.span } else { item.span };
1519                err.span_label(
1520                    span,
1521                    ::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()),
1522                );
1523            }
1524        }
1525        true
1526    }
1527
1528    fn detect_missing_binding_available_from_pattern(
1529        &self,
1530        err: &mut Diag<'_>,
1531        path: &[Segment],
1532        following_seg: Option<&Segment>,
1533    ) {
1534        let [segment] = path else { return };
1535        let None = following_seg else { return };
1536        for rib in self.ribs[ValueNS].iter().rev() {
1537            let patterns_with_skipped_bindings = self.r.tcx.with_stable_hashing_context(|hcx| {
1538                rib.patterns_with_skipped_bindings.to_sorted(&hcx, true)
1539            });
1540            for (def_id, spans) in patterns_with_skipped_bindings {
1541                if let DefKind::Struct | DefKind::Variant = self.r.tcx.def_kind(*def_id)
1542                    && let Some(fields) = self.r.field_idents(*def_id)
1543                {
1544                    for field in fields {
1545                        if field.name == segment.ident.name {
1546                            if spans.iter().all(|(_, had_error)| had_error.is_err()) {
1547                                // This resolution error will likely be fixed by fixing a
1548                                // syntax error in a pattern, so it is irrelevant to the user.
1549                                let multispan: MultiSpan =
1550                                    spans.iter().map(|(s, _)| *s).collect::<Vec<_>>().into();
1551                                err.span_note(
1552                                    multispan,
1553                                    "this pattern had a recovered parse error which likely lost \
1554                                     the expected fields",
1555                                );
1556                                err.downgrade_to_delayed_bug();
1557                            }
1558                            let ty = self.r.tcx.item_name(*def_id);
1559                            for (span, _) in spans {
1560                                err.span_label(
1561                                    *span,
1562                                    ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("this pattern doesn\'t include `{0}`, which is available in `{1}`",
                field, ty))
    })format!(
1563                                        "this pattern doesn't include `{field}`, which is \
1564                                         available in `{ty}`",
1565                                    ),
1566                                );
1567                            }
1568                        }
1569                    }
1570                }
1571            }
1572        }
1573    }
1574
1575    fn suggest_at_operator_in_slice_pat_with_range(&self, err: &mut Diag<'_>, path: &[Segment]) {
1576        let Some(pat) = self.diag_metadata.current_pat else { return };
1577        let (bound, side, range) = match &pat.kind {
1578            ast::PatKind::Range(Some(bound), None, range) => (bound, Side::Start, range),
1579            ast::PatKind::Range(None, Some(bound), range) => (bound, Side::End, range),
1580            _ => return,
1581        };
1582        if let ExprKind::Path(None, range_path) = &bound.kind
1583            && let [segment] = &range_path.segments[..]
1584            && let [s] = path
1585            && segment.ident == s.ident
1586            && segment.ident.span.eq_ctxt(range.span)
1587        {
1588            // We've encountered `[first, rest..]` (#88404) or `[first, ..rest]` (#120591)
1589            // where the user might have meant `[first, rest @ ..]`.
1590            let (span, snippet) = match side {
1591                Side::Start => (segment.ident.span.between(range.span), " @ ".into()),
1592                Side::End => (range.span.to(segment.ident.span), ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("{0} @ ..", segment.ident))
    })format!("{} @ ..", segment.ident)),
1593            };
1594            err.subdiagnostic(errors::UnexpectedResUseAtOpInSlicePatWithRangeSugg {
1595                span,
1596                ident: segment.ident,
1597                snippet,
1598            });
1599        }
1600
1601        enum Side {
1602            Start,
1603            End,
1604        }
1605    }
1606
1607    fn suggest_range_struct_destructuring(
1608        &mut self,
1609        err: &mut Diag<'_>,
1610        path: &[Segment],
1611        source: PathSource<'_, '_, '_>,
1612    ) {
1613        if !#[allow(non_exhaustive_omitted_patterns)] match source {
    PathSource::Pat | PathSource::TupleStruct(..) | PathSource::Expr(..) =>
        true,
    _ => false,
}matches!(source, PathSource::Pat | PathSource::TupleStruct(..) | PathSource::Expr(..)) {
1614            return;
1615        }
1616
1617        let Some(pat) = self.diag_metadata.current_pat else { return };
1618        let ast::PatKind::Range(start, end, end_kind) = &pat.kind else { return };
1619
1620        let [segment] = path else { return };
1621        let failing_span = segment.ident.span;
1622
1623        let in_start = start.as_ref().is_some_and(|e| e.span.contains(failing_span));
1624        let in_end = end.as_ref().is_some_and(|e| e.span.contains(failing_span));
1625
1626        if !in_start && !in_end {
1627            return;
1628        }
1629
1630        let start_snippet =
1631            start.as_ref().and_then(|e| self.r.tcx.sess.source_map().span_to_snippet(e.span).ok());
1632        let end_snippet =
1633            end.as_ref().and_then(|e| self.r.tcx.sess.source_map().span_to_snippet(e.span).ok());
1634
1635        let field = |name: &str, val: String| {
1636            if val == name { val } else { ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("{0}: {1}", name, val))
    })format!("{name}: {val}") }
1637        };
1638
1639        let mut resolve_short_name = |short: Symbol, full: &str| -> String {
1640            let ident = Ident::with_dummy_span(short);
1641            let path = Segment::from_path(&Path::from_ident(ident));
1642
1643            match self.resolve_path(&path, Some(TypeNS), None, PathSource::Type) {
1644                PathResult::NonModule(..) => short.to_string(),
1645                _ => full.to_string(),
1646            }
1647        };
1648        // FIXME(new_range): Also account for new range types
1649        let (struct_path, fields) = match (start_snippet, end_snippet, &end_kind.node) {
1650            (Some(start), Some(end), ast::RangeEnd::Excluded) => (
1651                resolve_short_name(sym::Range, "std::ops::Range"),
1652                ::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)],
1653            ),
1654            (Some(start), Some(end), ast::RangeEnd::Included(_)) => (
1655                resolve_short_name(sym::RangeInclusive, "std::ops::RangeInclusive"),
1656                ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
        [field("start", start), field("end", end)]))vec![field("start", start), field("end", end)],
1657            ),
1658            (Some(start), None, _) => (
1659                resolve_short_name(sym::RangeFrom, "std::ops::RangeFrom"),
1660                ::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)],
1661            ),
1662            (None, Some(end), ast::RangeEnd::Excluded) => {
1663                (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)])
1664            }
1665            (None, Some(end), ast::RangeEnd::Included(_)) => (
1666                resolve_short_name(sym::RangeToInclusive, "std::ops::RangeToInclusive"),
1667                ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
        [field("end", end)]))vec![field("end", end)],
1668            ),
1669            _ => return,
1670        };
1671
1672        err.span_suggestion_verbose(
1673            pat.span,
1674            ::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"),
1675            ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("{0} {{ {1} }}", struct_path,
                fields.join(", ")))
    })format!("{} {{ {} }}", struct_path, fields.join(", ")),
1676            Applicability::MaybeIncorrect,
1677        );
1678
1679        err.note(
1680            "range patterns match against the start and end of a range; \
1681             to bind the components, use a struct pattern",
1682        );
1683    }
1684
1685    fn suggest_swapping_misplaced_self_ty_and_trait(
1686        &mut self,
1687        err: &mut Diag<'_>,
1688        source: PathSource<'_, 'ast, 'ra>,
1689        res: Option<Res>,
1690        span: Span,
1691    ) {
1692        if let Some((trait_ref, self_ty)) =
1693            self.diag_metadata.currently_processing_impl_trait.clone()
1694            && let TyKind::Path(_, self_ty_path) = &self_ty.kind
1695            && let PathResult::Module(ModuleOrUniformRoot::Module(module)) =
1696                self.resolve_path(&Segment::from_path(self_ty_path), Some(TypeNS), None, source)
1697            && let ModuleKind::Def(DefKind::Trait, ..) = module.kind
1698            && trait_ref.path.span == span
1699            && let PathSource::Trait(_) = source
1700            && let Some(Res::Def(DefKind::Struct | DefKind::Enum | DefKind::Union, _)) = res
1701            && let Ok(self_ty_str) = self.r.tcx.sess.source_map().span_to_snippet(self_ty.span)
1702            && let Ok(trait_ref_str) =
1703                self.r.tcx.sess.source_map().span_to_snippet(trait_ref.path.span)
1704        {
1705            err.multipart_suggestion(
1706                    "`impl` items mention the trait being implemented first and the type it is being implemented for second",
1707                    ::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)],
1708                    Applicability::MaybeIncorrect,
1709                );
1710        }
1711    }
1712
1713    fn explain_functions_in_pattern(
1714        &self,
1715        err: &mut Diag<'_>,
1716        res: Option<Res>,
1717        source: PathSource<'_, '_, '_>,
1718    ) {
1719        let PathSource::TupleStruct(_, _) = source else { return };
1720        let Some(Res::Def(DefKind::Fn, _)) = res else { return };
1721        err.primary_message("expected a pattern, found a function call");
1722        err.note("function calls are not allowed in patterns: <https://doc.rust-lang.org/book/ch19-00-patterns.html>");
1723    }
1724
1725    fn suggest_changing_type_to_const_param(
1726        &self,
1727        err: &mut Diag<'_>,
1728        res: Option<Res>,
1729        source: PathSource<'_, '_, '_>,
1730        path: &[Segment],
1731        following_seg: Option<&Segment>,
1732        span: Span,
1733    ) {
1734        if let PathSource::Expr(None) = source
1735            && let Some(Res::Def(DefKind::TyParam, _)) = res
1736            && following_seg.is_none()
1737            && let [segment] = path
1738        {
1739            // We have something like
1740            // impl<T, N> From<[T; N]> for VecWrapper<T> {
1741            //     fn from(slice: [T; N]) -> Self {
1742            //         VecWrapper(slice.to_vec())
1743            //     }
1744            // }
1745            // where `N` is a type param but should likely have been a const param.
1746            let Some(item) = self.diag_metadata.current_item else { return };
1747            let Some(generics) = item.kind.generics() else { return };
1748            let Some(span) = generics.params.iter().find_map(|param| {
1749                // Only consider type params with no bounds.
1750                if param.bounds.is_empty() && param.ident.name == segment.ident.name {
1751                    Some(param.ident.span)
1752                } else {
1753                    None
1754                }
1755            }) else {
1756                return;
1757            };
1758            err.subdiagnostic(errors::UnexpectedResChangeTyParamToConstParamSugg {
1759                before: span.shrink_to_lo(),
1760                after: span.shrink_to_hi(),
1761            });
1762            return;
1763        }
1764        let PathSource::Trait(_) = source else { return };
1765
1766        // We don't include `DefKind::Str` and `DefKind::AssocTy` as they can't be reached here anyway.
1767        let applicability = match res {
1768            Some(Res::PrimTy(PrimTy::Int(_) | PrimTy::Uint(_) | PrimTy::Bool | PrimTy::Char)) => {
1769                Applicability::MachineApplicable
1770            }
1771            // FIXME(const_generics): Add `DefKind::TyParam` and `SelfTyParam` once we support generic
1772            // const generics. Of course, `Struct` and `Enum` may contain ty params, too, but the
1773            // benefits of including them here outweighs the small number of false positives.
1774            Some(Res::Def(DefKind::Struct | DefKind::Enum, _))
1775                if self.r.tcx.features().adt_const_params() =>
1776            {
1777                Applicability::MaybeIncorrect
1778            }
1779            _ => return,
1780        };
1781
1782        let Some(item) = self.diag_metadata.current_item else { return };
1783        let Some(generics) = item.kind.generics() else { return };
1784
1785        let param = generics.params.iter().find_map(|param| {
1786            // Only consider type params with exactly one trait bound.
1787            if let [bound] = &*param.bounds
1788                && let ast::GenericBound::Trait(tref) = bound
1789                && tref.modifiers == ast::TraitBoundModifiers::NONE
1790                && tref.span == span
1791                && param.ident.span.eq_ctxt(span)
1792            {
1793                Some(param.ident.span)
1794            } else {
1795                None
1796            }
1797        });
1798
1799        if let Some(param) = param {
1800            err.subdiagnostic(errors::UnexpectedResChangeTyToConstParamSugg {
1801                span: param.shrink_to_lo(),
1802                applicability,
1803            });
1804        }
1805    }
1806
1807    fn suggest_pattern_match_with_let(
1808        &self,
1809        err: &mut Diag<'_>,
1810        source: PathSource<'_, '_, '_>,
1811        span: Span,
1812    ) -> bool {
1813        if let PathSource::Expr(_) = source
1814            && let Some(Expr { span: expr_span, kind: ExprKind::Assign(lhs, _, _), .. }) =
1815                self.diag_metadata.in_if_condition
1816        {
1817            // Icky heuristic so we don't suggest:
1818            // `if (i + 2) = 2` => `if let (i + 2) = 2` (approximately pattern)
1819            // `if 2 = i` => `if let 2 = i` (lhs needs to contain error span)
1820            if lhs.is_approximately_pattern() && lhs.span.contains(span) {
1821                err.span_suggestion_verbose(
1822                    expr_span.shrink_to_lo(),
1823                    "you might have meant to use pattern matching",
1824                    "let ",
1825                    Applicability::MaybeIncorrect,
1826                );
1827                return true;
1828            }
1829        }
1830        false
1831    }
1832
1833    fn get_single_associated_item(
1834        &mut self,
1835        path: &[Segment],
1836        source: &PathSource<'_, 'ast, 'ra>,
1837        filter_fn: &impl Fn(Res) -> bool,
1838    ) -> Option<TypoSuggestion> {
1839        if let crate::PathSource::TraitItem(_, _) = source {
1840            let mod_path = &path[..path.len() - 1];
1841            if let PathResult::Module(ModuleOrUniformRoot::Module(module)) =
1842                self.resolve_path(mod_path, None, None, *source)
1843            {
1844                let targets: Vec<_> = self
1845                    .r
1846                    .resolutions(module)
1847                    .borrow()
1848                    .iter()
1849                    .filter_map(|(key, resolution)| {
1850                        let resolution = resolution.borrow();
1851                        resolution.best_decl().map(|binding| binding.res()).and_then(|res| {
1852                            if filter_fn(res) {
1853                                Some((key.ident.name, resolution.orig_ident_span, res))
1854                            } else {
1855                                None
1856                            }
1857                        })
1858                    })
1859                    .collect();
1860                if let &[(name, orig_ident_span, res)] = targets.as_slice() {
1861                    return Some(TypoSuggestion::single_item(name, orig_ident_span, res));
1862                }
1863            }
1864        }
1865        None
1866    }
1867
1868    /// Given `where <T as Bar>::Baz: String`, suggest `where T: Bar<Baz = String>`.
1869    fn restrict_assoc_type_in_where_clause(&self, span: Span, err: &mut Diag<'_>) -> bool {
1870        // Detect that we are actually in a `where` predicate.
1871        let Some(ast::WherePredicate {
1872            kind:
1873                ast::WherePredicateKind::BoundPredicate(ast::WhereBoundPredicate {
1874                    bounded_ty,
1875                    bound_generic_params,
1876                    bounds,
1877                }),
1878            span: where_span,
1879            ..
1880        }) = self.diag_metadata.current_where_predicate
1881        else {
1882            return false;
1883        };
1884        if !bound_generic_params.is_empty() {
1885            return false;
1886        }
1887
1888        // Confirm that the target is an associated type.
1889        let ast::TyKind::Path(Some(qself), path) = &bounded_ty.kind else { return false };
1890        // use this to verify that ident is a type param.
1891        let Some(partial_res) = self.r.partial_res_map.get(&bounded_ty.id) else { return false };
1892        if !#[allow(non_exhaustive_omitted_patterns)] match partial_res.full_res() {
    Some(hir::def::Res::Def(hir::def::DefKind::AssocTy, _)) => true,
    _ => false,
}matches!(
1893            partial_res.full_res(),
1894            Some(hir::def::Res::Def(hir::def::DefKind::AssocTy, _))
1895        ) {
1896            return false;
1897        }
1898
1899        let peeled_ty = qself.ty.peel_refs();
1900        let ast::TyKind::Path(None, type_param_path) = &peeled_ty.kind else { return false };
1901        // Confirm that the `SelfTy` is a type parameter.
1902        let Some(partial_res) = self.r.partial_res_map.get(&peeled_ty.id) else {
1903            return false;
1904        };
1905        if !#[allow(non_exhaustive_omitted_patterns)] match partial_res.full_res() {
    Some(hir::def::Res::Def(hir::def::DefKind::TyParam, _)) => true,
    _ => false,
}matches!(
1906            partial_res.full_res(),
1907            Some(hir::def::Res::Def(hir::def::DefKind::TyParam, _))
1908        ) {
1909            return false;
1910        }
1911        let ([ast::PathSegment { args: None, .. }], [ast::GenericBound::Trait(poly_trait_ref)]) =
1912            (&type_param_path.segments[..], &bounds[..])
1913        else {
1914            return false;
1915        };
1916        let [ast::PathSegment { ident, args: None, id }] =
1917            &poly_trait_ref.trait_ref.path.segments[..]
1918        else {
1919            return false;
1920        };
1921        if poly_trait_ref.modifiers != ast::TraitBoundModifiers::NONE {
1922            return false;
1923        }
1924        if ident.span == span {
1925            let Some(partial_res) = self.r.partial_res_map.get(&id) else {
1926                return false;
1927            };
1928            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(..))) {
1929                return false;
1930            }
1931
1932            let Some(new_where_bound_predicate) =
1933                mk_where_bound_predicate(path, poly_trait_ref, &qself.ty)
1934            else {
1935                return false;
1936            };
1937            err.span_suggestion_verbose(
1938                *where_span,
1939                ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("constrain the associated type to `{0}`",
                ident))
    })format!("constrain the associated type to `{ident}`"),
1940                where_bound_predicate_to_string(&new_where_bound_predicate),
1941                Applicability::MaybeIncorrect,
1942            );
1943        }
1944        true
1945    }
1946
1947    /// Check if the source is call expression and the first argument is `self`. If true,
1948    /// return the span of whole call and the span for all arguments expect the first one (`self`).
1949    fn call_has_self_arg(&self, source: PathSource<'_, '_, '_>) -> Option<(Span, Option<Span>)> {
1950        let mut has_self_arg = None;
1951        if let PathSource::Expr(Some(parent)) = source
1952            && let ExprKind::Call(_, args) = &parent.kind
1953            && !args.is_empty()
1954        {
1955            let mut expr_kind = &args[0].kind;
1956            loop {
1957                match expr_kind {
1958                    ExprKind::Path(_, arg_name) if arg_name.segments.len() == 1 => {
1959                        if arg_name.segments[0].ident.name == kw::SelfLower {
1960                            let call_span = parent.span;
1961                            let tail_args_span = if args.len() > 1 {
1962                                Some(Span::new(
1963                                    args[1].span.lo(),
1964                                    args.last().unwrap().span.hi(),
1965                                    call_span.ctxt(),
1966                                    None,
1967                                ))
1968                            } else {
1969                                None
1970                            };
1971                            has_self_arg = Some((call_span, tail_args_span));
1972                        }
1973                        break;
1974                    }
1975                    ExprKind::AddrOf(_, _, expr) => expr_kind = &expr.kind,
1976                    _ => break,
1977                }
1978            }
1979        }
1980        has_self_arg
1981    }
1982
1983    fn followed_by_brace(&self, span: Span) -> (bool, Option<Span>) {
1984        // HACK(estebank): find a better way to figure out that this was a
1985        // parser issue where a struct literal is being used on an expression
1986        // where a brace being opened means a block is being started. Look
1987        // ahead for the next text to see if `span` is followed by a `{`.
1988        let sm = self.r.tcx.sess.source_map();
1989        if let Some(followed_brace_span) = sm.span_look_ahead(span, "{", Some(50)) {
1990            // In case this could be a struct literal that needs to be surrounded
1991            // by parentheses, find the appropriate span.
1992            let close_brace_span = sm.span_look_ahead(followed_brace_span, "}", Some(50));
1993            let closing_brace = close_brace_span.map(|sp| span.to(sp));
1994            (true, closing_brace)
1995        } else {
1996            (false, None)
1997        }
1998    }
1999
2000    fn is_struct_with_fn_ctor(&mut self, def_id: DefId) -> bool {
2001        def_id
2002            .as_local()
2003            .and_then(|local_id| self.r.struct_constructors.get(&local_id))
2004            .map(|struct_ctor| {
2005                #[allow(non_exhaustive_omitted_patterns)] match struct_ctor.0 {
    def::Res::Def(DefKind::Ctor(CtorOf::Struct, CtorKind::Fn), _) => true,
    _ => false,
}matches!(
2006                    struct_ctor.0,
2007                    def::Res::Def(DefKind::Ctor(CtorOf::Struct, CtorKind::Fn), _)
2008                )
2009            })
2010            .unwrap_or(false)
2011    }
2012
2013    fn update_err_for_private_tuple_struct_fields(
2014        &mut self,
2015        err: &mut Diag<'_>,
2016        source: &PathSource<'_, '_, '_>,
2017        def_id: DefId,
2018    ) -> Option<Vec<Span>> {
2019        match source {
2020            // e.g. `if let Enum::TupleVariant(field1, field2) = _`
2021            PathSource::TupleStruct(_, pattern_spans) => {
2022                err.primary_message(
2023                    "cannot match against a tuple struct which contains private fields",
2024                );
2025
2026                // Use spans of the tuple struct pattern.
2027                Some(Vec::from(*pattern_spans))
2028            }
2029            // e.g. `let _ = Enum::TupleVariant(field1, field2);`
2030            PathSource::Expr(Some(Expr {
2031                kind: ExprKind::Call(path, args),
2032                span: call_span,
2033                ..
2034            })) => {
2035                err.primary_message(
2036                    "cannot initialize a tuple struct which contains private fields",
2037                );
2038                self.suggest_alternative_construction_methods(
2039                    def_id,
2040                    err,
2041                    path.span,
2042                    *call_span,
2043                    &args[..],
2044                );
2045
2046                self.r
2047                    .field_idents(def_id)
2048                    .map(|fields| fields.iter().map(|f| f.span).collect::<Vec<_>>())
2049            }
2050            _ => None,
2051        }
2052    }
2053
2054    /// Provides context-dependent help for errors reported by the `smart_resolve_path_fragment`
2055    /// function.
2056    /// Returns `true` if able to provide context-dependent help.
2057    fn smart_resolve_context_dependent_help(
2058        &mut self,
2059        err: &mut Diag<'_>,
2060        span: Span,
2061        source: PathSource<'_, '_, '_>,
2062        path: &[Segment],
2063        res: Res,
2064        path_str: &str,
2065        fallback_label: &str,
2066    ) -> bool {
2067        let ns = source.namespace();
2068        let is_expected = &|res| source.is_expected(res);
2069
2070        let path_sep = |this: &Self, err: &mut Diag<'_>, expr: &Expr, kind: DefKind| {
2071            const MESSAGE: &str = "use the path separator to refer to an item";
2072
2073            let (lhs_span, rhs_span) = match &expr.kind {
2074                ExprKind::Field(base, ident) => (base.span, ident.span),
2075                ExprKind::MethodCall(box MethodCall { receiver, span, .. }) => {
2076                    (receiver.span, *span)
2077                }
2078                _ => return false,
2079            };
2080
2081            if lhs_span.eq_ctxt(rhs_span) {
2082                err.span_suggestion_verbose(
2083                    lhs_span.between(rhs_span),
2084                    MESSAGE,
2085                    "::",
2086                    Applicability::MaybeIncorrect,
2087                );
2088                true
2089            } else if #[allow(non_exhaustive_omitted_patterns)] match kind {
    DefKind::Struct | DefKind::TyAlias => true,
    _ => false,
}matches!(kind, DefKind::Struct | DefKind::TyAlias)
2090                && let Some(lhs_source_span) = lhs_span.find_ancestor_inside(expr.span)
2091                && let Ok(snippet) = this.r.tcx.sess.source_map().span_to_snippet(lhs_source_span)
2092            {
2093                // The LHS is a type that originates from a macro call.
2094                // We have to add angle brackets around it.
2095
2096                err.span_suggestion_verbose(
2097                    lhs_source_span.until(rhs_span),
2098                    MESSAGE,
2099                    ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("<{0}>::", snippet))
    })format!("<{snippet}>::"),
2100                    Applicability::MaybeIncorrect,
2101                );
2102                true
2103            } else {
2104                // Either we were unable to obtain the source span / the snippet or
2105                // the LHS originates from a macro call and it is not a type and thus
2106                // there is no way to replace `.` with `::` and still somehow suggest
2107                // valid Rust code.
2108
2109                false
2110            }
2111        };
2112
2113        let find_span = |source: &PathSource<'_, '_, '_>, err: &mut Diag<'_>| {
2114            match source {
2115                PathSource::Expr(Some(Expr { span, kind: ExprKind::Call(_, _), .. }))
2116                | PathSource::TupleStruct(span, _) => {
2117                    // We want the main underline to cover the suggested code as well for
2118                    // cleaner output.
2119                    err.span(*span);
2120                    *span
2121                }
2122                _ => span,
2123            }
2124        };
2125
2126        let bad_struct_syntax_suggestion = |this: &mut Self, err: &mut Diag<'_>, def_id: DefId| {
2127            let (followed_by_brace, closing_brace) = this.followed_by_brace(span);
2128
2129            match source {
2130                PathSource::Expr(Some(
2131                    parent @ Expr { kind: ExprKind::Field(..) | ExprKind::MethodCall(..), .. },
2132                )) if path_sep(this, err, parent, DefKind::Struct) => {}
2133                PathSource::Expr(
2134                    None
2135                    | Some(Expr {
2136                        kind:
2137                            ExprKind::Path(..)
2138                            | ExprKind::Binary(..)
2139                            | ExprKind::Unary(..)
2140                            | ExprKind::If(..)
2141                            | ExprKind::While(..)
2142                            | ExprKind::ForLoop { .. }
2143                            | ExprKind::Match(..),
2144                        ..
2145                    }),
2146                ) if followed_by_brace => {
2147                    if let Some(sp) = closing_brace {
2148                        err.span_label(span, fallback_label.to_string());
2149                        err.multipart_suggestion(
2150                            "surround the struct literal with parentheses",
2151                            ::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![
2152                                (sp.shrink_to_lo(), "(".to_string()),
2153                                (sp.shrink_to_hi(), ")".to_string()),
2154                            ],
2155                            Applicability::MaybeIncorrect,
2156                        );
2157                    } else {
2158                        err.span_label(
2159                            span, // Note the parentheses surrounding the suggestion below
2160                            ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("you might want to surround a struct literal with parentheses: `({0} {{ /* fields */ }})`?",
                path_str))
    })format!(
2161                                "you might want to surround a struct literal with parentheses: \
2162                                 `({path_str} {{ /* fields */ }})`?"
2163                            ),
2164                        );
2165                    }
2166                }
2167                PathSource::Expr(_) | PathSource::TupleStruct(..) | PathSource::Pat => {
2168                    let span = find_span(&source, err);
2169                    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"));
2170
2171                    let (tail, descr, applicability, old_fields) = match source {
2172                        PathSource::Pat => ("", "pattern", Applicability::MachineApplicable, None),
2173                        PathSource::TupleStruct(_, args) => (
2174                            "",
2175                            "pattern",
2176                            Applicability::MachineApplicable,
2177                            Some(
2178                                args.iter()
2179                                    .map(|a| this.r.tcx.sess.source_map().span_to_snippet(*a).ok())
2180                                    .collect::<Vec<Option<String>>>(),
2181                            ),
2182                        ),
2183                        _ => (": val", "literal", Applicability::HasPlaceholders, None),
2184                    };
2185
2186                    if !this.has_private_fields(def_id) {
2187                        // If the fields of the type are private, we shouldn't be suggesting using
2188                        // the struct literal syntax at all, as that will cause a subsequent error.
2189                        let fields = this.r.field_idents(def_id);
2190                        let has_fields = fields.as_ref().is_some_and(|f| !f.is_empty());
2191
2192                        if let PathSource::Expr(Some(Expr {
2193                            kind: ExprKind::Call(path, args),
2194                            span,
2195                            ..
2196                        })) = source
2197                            && !args.is_empty()
2198                            && let Some(fields) = &fields
2199                            && args.len() == fields.len()
2200                        // Make sure we have same number of args as fields
2201                        {
2202                            let path_span = path.span;
2203                            let mut parts = Vec::new();
2204
2205                            // Start with the opening brace
2206                            parts.push((
2207                                path_span.shrink_to_hi().until(args[0].span),
2208                                "{".to_owned(),
2209                            ));
2210
2211                            for (field, arg) in fields.iter().zip(args.iter()) {
2212                                // Add the field name before the argument
2213                                parts.push((arg.span.shrink_to_lo(), ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("{0}: ", field))
    })format!("{}: ", field)));
2214                            }
2215
2216                            // Add the closing brace
2217                            parts.push((
2218                                args.last().unwrap().span.shrink_to_hi().until(span.shrink_to_hi()),
2219                                "}".to_owned(),
2220                            ));
2221
2222                            err.multipart_suggestion(
2223                                ::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"),
2224                                parts,
2225                                applicability,
2226                            );
2227                        } else {
2228                            let (fields, applicability) = match fields {
2229                                Some(fields) => {
2230                                    let fields = if let Some(old_fields) = old_fields {
2231                                        fields
2232                                            .iter()
2233                                            .enumerate()
2234                                            .map(|(idx, new)| (new, old_fields.get(idx)))
2235                                            .map(|(new, old)| {
2236                                                if let Some(Some(old)) = old
2237                                                    && new.as_str() != old
2238                                                {
2239                                                    ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("{0}: {1}", new, old))
    })format!("{new}: {old}")
2240                                                } else {
2241                                                    new.to_string()
2242                                                }
2243                                            })
2244                                            .collect::<Vec<String>>()
2245                                    } else {
2246                                        fields
2247                                            .iter()
2248                                            .map(|f| ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("{0}{1}", f, tail))
    })format!("{f}{tail}"))
2249                                            .collect::<Vec<String>>()
2250                                    };
2251
2252                                    (fields.join(", "), applicability)
2253                                }
2254                                None => {
2255                                    ("/* fields */".to_string(), Applicability::HasPlaceholders)
2256                                }
2257                            };
2258                            let pad = if has_fields { " " } else { "" };
2259                            err.span_suggestion(
2260                                span,
2261                                ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("use struct {0} syntax instead",
                descr))
    })format!("use struct {descr} syntax instead"),
2262                                ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("{0} {{{1}{2}{1}}}", path_str, pad,
                fields))
    })format!("{path_str} {{{pad}{fields}{pad}}}"),
2263                                applicability,
2264                            );
2265                        }
2266                    }
2267                    if let PathSource::Expr(Some(Expr {
2268                        kind: ExprKind::Call(path, args),
2269                        span: call_span,
2270                        ..
2271                    })) = source
2272                    {
2273                        this.suggest_alternative_construction_methods(
2274                            def_id,
2275                            err,
2276                            path.span,
2277                            *call_span,
2278                            &args[..],
2279                        );
2280                    }
2281                }
2282                _ => {
2283                    err.span_label(span, fallback_label.to_string());
2284                }
2285            }
2286        };
2287
2288        match (res, source) {
2289            (
2290                Res::Def(DefKind::Macro(kinds), def_id),
2291                PathSource::Expr(Some(Expr {
2292                    kind: ExprKind::Index(..) | ExprKind::Call(..), ..
2293                }))
2294                | PathSource::Struct(_),
2295            ) if kinds.contains(MacroKinds::BANG) => {
2296                // Don't suggest macro if it's unstable.
2297                let suggestable = def_id.is_local()
2298                    || self.r.tcx.lookup_stability(def_id).is_none_or(|s| s.is_stable());
2299
2300                err.span_label(span, fallback_label.to_string());
2301
2302                // Don't suggest `!` for a macro invocation if there are generic args
2303                if path
2304                    .last()
2305                    .is_some_and(|segment| !segment.has_generic_args && !segment.has_lifetime_args)
2306                    && suggestable
2307                {
2308                    err.span_suggestion_verbose(
2309                        span.shrink_to_hi(),
2310                        "use `!` to invoke the macro",
2311                        "!",
2312                        Applicability::MaybeIncorrect,
2313                    );
2314                }
2315
2316                if path_str == "try" && span.is_rust_2015() {
2317                    err.note("if you want the `try` keyword, you need Rust 2018 or later");
2318                }
2319            }
2320            (Res::Def(DefKind::Macro(kinds), _), _) if kinds.contains(MacroKinds::BANG) => {
2321                err.span_label(span, fallback_label.to_string());
2322            }
2323            (Res::Def(DefKind::TyAlias, def_id), PathSource::Trait(_)) => {
2324                err.span_label(span, "type aliases cannot be used as traits");
2325                if self.r.tcx.sess.is_nightly_build() {
2326                    let msg = "you might have meant to use `#![feature(trait_alias)]` instead of a \
2327                               `type` alias";
2328                    let span = self.r.def_span(def_id);
2329                    if let Ok(snip) = self.r.tcx.sess.source_map().span_to_snippet(span) {
2330                        // The span contains a type alias so we should be able to
2331                        // replace `type` with `trait`.
2332                        let snip = snip.replacen("type", "trait", 1);
2333                        err.span_suggestion(span, msg, snip, Applicability::MaybeIncorrect);
2334                    } else {
2335                        err.span_help(span, msg);
2336                    }
2337                }
2338            }
2339            (
2340                Res::Def(kind @ (DefKind::Mod | DefKind::Trait | DefKind::TyAlias), _),
2341                PathSource::Expr(Some(parent)),
2342            ) if path_sep(self, err, parent, kind) => {
2343                return true;
2344            }
2345            (
2346                Res::Def(DefKind::Enum, def_id),
2347                PathSource::TupleStruct(..) | PathSource::Expr(..),
2348            ) => {
2349                self.suggest_using_enum_variant(err, source, def_id, span);
2350            }
2351            (Res::Def(DefKind::Struct, def_id), source) if ns == ValueNS => {
2352                let struct_ctor = match def_id.as_local() {
2353                    Some(def_id) => self.r.struct_constructors.get(&def_id).cloned(),
2354                    None => {
2355                        let ctor = self.r.cstore().ctor_untracked(self.r.tcx(), def_id);
2356                        ctor.map(|(ctor_kind, ctor_def_id)| {
2357                            let ctor_res =
2358                                Res::Def(DefKind::Ctor(CtorOf::Struct, ctor_kind), ctor_def_id);
2359                            let ctor_vis = self.r.tcx.visibility(ctor_def_id);
2360                            let field_visibilities = self
2361                                .r
2362                                .tcx
2363                                .associated_item_def_ids(def_id)
2364                                .iter()
2365                                .map(|&field_id| self.r.tcx.visibility(field_id))
2366                                .collect();
2367                            (ctor_res, ctor_vis, field_visibilities)
2368                        })
2369                    }
2370                };
2371
2372                let (ctor_def, ctor_vis, fields) = if let Some(struct_ctor) = struct_ctor {
2373                    if let PathSource::Expr(Some(parent)) = source
2374                        && let ExprKind::Field(..) | ExprKind::MethodCall(..) = parent.kind
2375                    {
2376                        bad_struct_syntax_suggestion(self, err, def_id);
2377                        return true;
2378                    }
2379                    struct_ctor
2380                } else {
2381                    bad_struct_syntax_suggestion(self, err, def_id);
2382                    return true;
2383                };
2384
2385                let is_accessible = self.r.is_accessible_from(ctor_vis, self.parent_scope.module);
2386                if let Some(use_span) = self.r.inaccessible_ctor_reexport.get(&span)
2387                    && is_accessible
2388                {
2389                    err.span_note(
2390                        *use_span,
2391                        "the type is accessed through this re-export, but the type's constructor \
2392                         is not visible in this import's scope due to private fields",
2393                    );
2394                    if is_accessible
2395                        && fields
2396                            .iter()
2397                            .all(|vis| self.r.is_accessible_from(*vis, self.parent_scope.module))
2398                    {
2399                        err.span_suggestion_verbose(
2400                            span,
2401                            "the type can be constructed directly, because its fields are \
2402                             available from the current scope",
2403                            // Using `tcx.def_path_str` causes the compiler to hang.
2404                            // We don't need to handle foreign crate types because in that case you
2405                            // can't access the ctor either way.
2406                            ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("crate{0}",
                self.r.tcx.def_path(def_id).to_string_no_crate_verbose()))
    })format!(
2407                                "crate{}", // The method already has leading `::`.
2408                                self.r.tcx.def_path(def_id).to_string_no_crate_verbose(),
2409                            ),
2410                            Applicability::MachineApplicable,
2411                        );
2412                    }
2413                    self.update_err_for_private_tuple_struct_fields(err, &source, def_id);
2414                }
2415                if !is_expected(ctor_def) || is_accessible {
2416                    return true;
2417                }
2418
2419                let field_spans =
2420                    self.update_err_for_private_tuple_struct_fields(err, &source, def_id);
2421
2422                if let Some(spans) =
2423                    field_spans.filter(|spans| spans.len() > 0 && fields.len() == spans.len())
2424                {
2425                    let non_visible_spans: Vec<Span> = iter::zip(&fields, &spans)
2426                        .filter(|(vis, _)| {
2427                            !self.r.is_accessible_from(**vis, self.parent_scope.module)
2428                        })
2429                        .map(|(_, span)| *span)
2430                        .collect();
2431
2432                    if non_visible_spans.len() > 0 {
2433                        if let Some(fields) = self.r.field_visibility_spans.get(&def_id) {
2434                            err.multipart_suggestion(
2435                                ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("consider making the field{0} publicly accessible",
                if fields.len() == 1 { "" } else { "s" }))
    })format!(
2436                                    "consider making the field{} publicly accessible",
2437                                    pluralize!(fields.len())
2438                                ),
2439                                fields.iter().map(|span| (*span, "pub ".to_string())).collect(),
2440                                Applicability::MaybeIncorrect,
2441                            );
2442                        }
2443
2444                        let mut m: MultiSpan = non_visible_spans.clone().into();
2445                        non_visible_spans
2446                            .into_iter()
2447                            .for_each(|s| m.push_span_label(s, "private field"));
2448                        err.span_note(m, "constructor is not visible here due to private fields");
2449                    }
2450
2451                    return true;
2452                }
2453
2454                err.span_label(span, "constructor is not visible here due to private fields");
2455            }
2456            (Res::Def(DefKind::Union | DefKind::Variant, def_id), _) if ns == ValueNS => {
2457                bad_struct_syntax_suggestion(self, err, def_id);
2458            }
2459            (Res::Def(DefKind::Ctor(_, CtorKind::Const), def_id), _) if ns == ValueNS => {
2460                match source {
2461                    PathSource::Expr(_) | PathSource::TupleStruct(..) | PathSource::Pat => {
2462                        let span = find_span(&source, err);
2463                        err.span_label(
2464                            self.r.def_span(def_id),
2465                            ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("`{0}` defined here", path_str))
    })format!("`{path_str}` defined here"),
2466                        );
2467                        err.span_suggestion(
2468                            span,
2469                            "use this syntax instead",
2470                            path_str,
2471                            Applicability::MaybeIncorrect,
2472                        );
2473                    }
2474                    _ => return false,
2475                }
2476            }
2477            (Res::Def(DefKind::Ctor(_, CtorKind::Fn), ctor_def_id), _) if ns == ValueNS => {
2478                let def_id = self.r.tcx.parent(ctor_def_id);
2479                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"));
2480                let fields = self.r.field_idents(def_id).map_or_else(
2481                    || "/* fields */".to_string(),
2482                    |field_ids| ::alloc::vec::from_elem("_", field_ids.len())vec!["_"; field_ids.len()].join(", "),
2483                );
2484                err.span_suggestion(
2485                    span,
2486                    "use the tuple variant pattern syntax instead",
2487                    ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("{0}({1})", path_str, fields))
    })format!("{path_str}({fields})"),
2488                    Applicability::HasPlaceholders,
2489                );
2490            }
2491            (Res::SelfTyParam { .. } | Res::SelfTyAlias { .. }, _) if ns == ValueNS => {
2492                err.span_label(span, fallback_label.to_string());
2493                err.note("can't use `Self` as a constructor, you must use the implemented struct");
2494            }
2495            (
2496                Res::Def(DefKind::TyAlias | DefKind::AssocTy, _),
2497                PathSource::TraitItem(ValueNS, PathSource::TupleStruct(whole, args)),
2498            ) => {
2499                err.note("can't use a type alias as tuple pattern");
2500
2501                let mut suggestion = Vec::new();
2502
2503                if let &&[first, ..] = args
2504                    && let &&[.., last] = args
2505                {
2506                    suggestion.extend([
2507                        // "0: " has to be included here so that the fix is machine applicable.
2508                        //
2509                        // If this would only add " { " and then the code below add "0: ",
2510                        // rustfix would crash, because end of this suggestion is the same as start
2511                        // of the suggestion below. Thus, we have to merge these...
2512                        (span.between(first), " { 0: ".to_owned()),
2513                        (last.between(whole.shrink_to_hi()), " }".to_owned()),
2514                    ]);
2515
2516                    suggestion.extend(
2517                        args.iter()
2518                            .enumerate()
2519                            .skip(1) // See above
2520                            .map(|(index, &arg)| (arg.shrink_to_lo(), ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("{0}: ", index))
    })format!("{index}: "))),
2521                    )
2522                } else {
2523                    suggestion.push((span.between(whole.shrink_to_hi()), " {}".to_owned()));
2524                }
2525
2526                err.multipart_suggestion(
2527                    "use struct pattern instead",
2528                    suggestion,
2529                    Applicability::MachineApplicable,
2530                );
2531            }
2532            (
2533                Res::Def(DefKind::TyAlias | DefKind::AssocTy, _),
2534                PathSource::TraitItem(
2535                    ValueNS,
2536                    PathSource::Expr(Some(ast::Expr {
2537                        span: whole,
2538                        kind: ast::ExprKind::Call(_, args),
2539                        ..
2540                    })),
2541                ),
2542            ) => {
2543                err.note("can't use a type alias as a constructor");
2544
2545                let mut suggestion = Vec::new();
2546
2547                if let [first, ..] = &**args
2548                    && let [.., last] = &**args
2549                {
2550                    suggestion.extend([
2551                        // "0: " has to be included here so that the fix is machine applicable.
2552                        //
2553                        // If this would only add " { " and then the code below add "0: ",
2554                        // rustfix would crash, because end of this suggestion is the same as start
2555                        // of the suggestion below. Thus, we have to merge these...
2556                        (span.between(first.span), " { 0: ".to_owned()),
2557                        (last.span.between(whole.shrink_to_hi()), " }".to_owned()),
2558                    ]);
2559
2560                    suggestion.extend(
2561                        args.iter()
2562                            .enumerate()
2563                            .skip(1) // See above
2564                            .map(|(index, arg)| (arg.span.shrink_to_lo(), ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("{0}: ", index))
    })format!("{index}: "))),
2565                    )
2566                } else {
2567                    suggestion.push((span.between(whole.shrink_to_hi()), " {}".to_owned()));
2568                }
2569
2570                err.multipart_suggestion(
2571                    "use struct expression instead",
2572                    suggestion,
2573                    Applicability::MachineApplicable,
2574                );
2575            }
2576            _ => return false,
2577        }
2578        true
2579    }
2580
2581    fn suggest_alternative_construction_methods(
2582        &mut self,
2583        def_id: DefId,
2584        err: &mut Diag<'_>,
2585        path_span: Span,
2586        call_span: Span,
2587        args: &[Box<Expr>],
2588    ) {
2589        if def_id.is_local() {
2590            // Doing analysis on local `DefId`s would cause infinite recursion.
2591            return;
2592        }
2593        // Look at all the associated functions without receivers in the type's
2594        // inherent impls to look for builders that return `Self`
2595        let mut items = self
2596            .r
2597            .tcx
2598            .inherent_impls(def_id)
2599            .iter()
2600            .flat_map(|&i| self.r.tcx.associated_items(i).in_definition_order())
2601            // Only assoc fn with no receivers.
2602            .filter(|item| item.is_fn() && !item.is_method())
2603            .filter_map(|item| {
2604                // Only assoc fns that return `Self`
2605                let fn_sig = self.r.tcx.fn_sig(item.def_id).skip_binder();
2606                // Don't normalize the return type, because that can cause cycle errors.
2607                let ret_ty = fn_sig.output().skip_binder();
2608                let ty::Adt(def, _args) = ret_ty.kind() else {
2609                    return None;
2610                };
2611                let input_len = fn_sig.inputs().skip_binder().len();
2612                if def.did() != def_id {
2613                    return None;
2614                }
2615                let name = item.name();
2616                let order = !name.as_str().starts_with("new");
2617                Some((order, name, input_len))
2618            })
2619            .collect::<Vec<_>>();
2620        items.sort_by_key(|(order, _, _)| *order);
2621        let suggestion = |name, args| {
2622            ::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(", "))
2623        };
2624        match &items[..] {
2625            [] => {}
2626            [(_, name, len)] if *len == args.len() => {
2627                err.span_suggestion_verbose(
2628                    path_span.shrink_to_hi(),
2629                    ::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",),
2630                    ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("::{0}", name))
    })format!("::{name}"),
2631                    Applicability::MaybeIncorrect,
2632                );
2633            }
2634            [(_, name, len)] => {
2635                err.span_suggestion_verbose(
2636                    path_span.shrink_to_hi().with_hi(call_span.hi()),
2637                    ::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",),
2638                    suggestion(name, *len),
2639                    Applicability::MaybeIncorrect,
2640                );
2641            }
2642            _ => {
2643                err.span_suggestions_with_style(
2644                    path_span.shrink_to_hi().with_hi(call_span.hi()),
2645                    "you might have meant to use an associated function to build this type",
2646                    items.iter().map(|(_, name, len)| suggestion(name, *len)),
2647                    Applicability::MaybeIncorrect,
2648                    SuggestionStyle::ShowAlways,
2649                );
2650            }
2651        }
2652        // We'd ideally use `type_implements_trait` but don't have access to
2653        // the trait solver here. We can't use `get_diagnostic_item` or
2654        // `all_traits` in resolve either. So instead we abuse the import
2655        // suggestion machinery to get `std::default::Default` and perform some
2656        // checks to confirm that we got *only* that trait. We then see if the
2657        // Adt we have has a direct implementation of `Default`. If so, we
2658        // provide a structured suggestion.
2659        let default_trait = self
2660            .r
2661            .lookup_import_candidates(
2662                Ident::with_dummy_span(sym::Default),
2663                Namespace::TypeNS,
2664                &self.parent_scope,
2665                &|res: Res| #[allow(non_exhaustive_omitted_patterns)] match res {
    Res::Def(DefKind::Trait, _) => true,
    _ => false,
}matches!(res, Res::Def(DefKind::Trait, _)),
2666            )
2667            .iter()
2668            .filter_map(|candidate| candidate.did)
2669            .find(|did| {

        #[allow(deprecated)]
        {
            {
                'done:
                    {
                    for i in self.r.tcx.get_all_attrs(*did) {
                        #[allow(unused_imports)]
                        use rustc_hir::attrs::AttributeKind::*;
                        let i: &rustc_hir::Attribute = i;
                        match i {
                            rustc_hir::Attribute::Parsed(RustcDiagnosticItem(sym::Default))
                                => {
                                break 'done Some(());
                            }
                            rustc_hir::Attribute::Unparsed(..) =>
                                {}
                                #[deny(unreachable_patterns)]
                                _ => {}
                        }
                    }
                    None
                }
            }
        }
    }.is_some()find_attr!(self.r.tcx, *did, RustcDiagnosticItem(sym::Default)));
2670        let Some(default_trait) = default_trait else {
2671            return;
2672        };
2673        if self
2674            .r
2675            .extern_crate_map
2676            .items()
2677            // FIXME: This doesn't include impls like `impl Default for String`.
2678            .flat_map(|(_, crate_)| self.r.tcx.implementations_of_trait((*crate_, default_trait)))
2679            .filter_map(|(_, simplified_self_ty)| *simplified_self_ty)
2680            .filter_map(|simplified_self_ty| match simplified_self_ty {
2681                SimplifiedType::Adt(did) => Some(did),
2682                _ => None,
2683            })
2684            .any(|did| did == def_id)
2685        {
2686            err.multipart_suggestion(
2687                "consider using the `Default` trait",
2688                ::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![
2689                    (path_span.shrink_to_lo(), "<".to_string()),
2690                    (
2691                        path_span.shrink_to_hi().with_hi(call_span.hi()),
2692                        " as std::default::Default>::default()".to_string(),
2693                    ),
2694                ],
2695                Applicability::MaybeIncorrect,
2696            );
2697        }
2698    }
2699
2700    fn has_private_fields(&self, def_id: DefId) -> bool {
2701        let fields = match def_id.as_local() {
2702            Some(def_id) => self.r.struct_constructors.get(&def_id).cloned().map(|(_, _, f)| f),
2703            None => Some(
2704                self.r
2705                    .tcx
2706                    .associated_item_def_ids(def_id)
2707                    .iter()
2708                    .map(|&field_id| self.r.tcx.visibility(field_id))
2709                    .collect(),
2710            ),
2711        };
2712
2713        fields.is_some_and(|fields| {
2714            fields.iter().any(|vis| !self.r.is_accessible_from(*vis, self.parent_scope.module))
2715        })
2716    }
2717
2718    /// Given the target `ident` and `kind`, search for the similarly named associated item
2719    /// in `self.current_trait_ref`.
2720    pub(crate) fn find_similarly_named_assoc_item(
2721        &mut self,
2722        ident: Symbol,
2723        kind: &AssocItemKind,
2724    ) -> Option<Symbol> {
2725        let (module, _) = self.current_trait_ref.as_ref()?;
2726        if ident == kw::Underscore {
2727            // We do nothing for `_`.
2728            return None;
2729        }
2730
2731        let targets = self
2732            .r
2733            .resolutions(*module)
2734            .borrow()
2735            .iter()
2736            .filter_map(|(key, res)| res.borrow().best_decl().map(|binding| (key, binding.res())))
2737            .filter(|(_, res)| match (kind, res) {
2738                (AssocItemKind::Const(..), Res::Def(DefKind::AssocConst { .. }, _)) => true,
2739                (AssocItemKind::Fn(_), Res::Def(DefKind::AssocFn, _)) => true,
2740                (AssocItemKind::Type(..), Res::Def(DefKind::AssocTy, _)) => true,
2741                (AssocItemKind::Delegation(_), Res::Def(DefKind::AssocFn, _)) => true,
2742                _ => false,
2743            })
2744            .map(|(key, _)| key.ident.name)
2745            .collect::<Vec<_>>();
2746
2747        find_best_match_for_name(&targets, ident, None)
2748    }
2749
2750    fn lookup_assoc_candidate<FilterFn>(
2751        &mut self,
2752        ident: Ident,
2753        ns: Namespace,
2754        filter_fn: FilterFn,
2755        called: bool,
2756    ) -> Option<AssocSuggestion>
2757    where
2758        FilterFn: Fn(Res) -> bool,
2759    {
2760        fn extract_node_id(t: &Ty) -> Option<NodeId> {
2761            match t.kind {
2762                TyKind::Path(None, _) => Some(t.id),
2763                TyKind::Ref(_, ref mut_ty) => extract_node_id(&mut_ty.ty),
2764                // This doesn't handle the remaining `Ty` variants as they are not
2765                // that commonly the self_type, it might be interesting to provide
2766                // support for those in future.
2767                _ => None,
2768            }
2769        }
2770        // Fields are generally expected in the same contexts as locals.
2771        if filter_fn(Res::Local(ast::DUMMY_NODE_ID)) {
2772            if let Some(node_id) =
2773                self.diag_metadata.current_self_type.as_ref().and_then(extract_node_id)
2774                && let Some(resolution) = self.r.partial_res_map.get(&node_id)
2775                && let Some(Res::Def(DefKind::Struct | DefKind::Union, did)) = resolution.full_res()
2776                && let Some(fields) = self.r.field_idents(did)
2777                && let Some(field) = fields.iter().find(|id| ident.name == id.name)
2778            {
2779                // Look for a field with the same name in the current self_type.
2780                return Some(AssocSuggestion::Field(field.span));
2781            }
2782        }
2783
2784        if let Some(items) = self.diag_metadata.current_trait_assoc_items {
2785            for assoc_item in items {
2786                if let Some(assoc_ident) = assoc_item.kind.ident()
2787                    && assoc_ident == ident
2788                {
2789                    return Some(match &assoc_item.kind {
2790                        ast::AssocItemKind::Const(..) => AssocSuggestion::AssocConst,
2791                        ast::AssocItemKind::Fn(box ast::Fn { sig, .. }) if sig.decl.has_self() => {
2792                            AssocSuggestion::MethodWithSelf { called }
2793                        }
2794                        ast::AssocItemKind::Fn(..) => AssocSuggestion::AssocFn { called },
2795                        ast::AssocItemKind::Type(..) => AssocSuggestion::AssocType,
2796                        ast::AssocItemKind::Delegation(..)
2797                            if self
2798                                .r
2799                                .delegation_fn_sigs
2800                                .get(&self.r.local_def_id(assoc_item.id))
2801                                .is_some_and(|sig| sig.has_self) =>
2802                        {
2803                            AssocSuggestion::MethodWithSelf { called }
2804                        }
2805                        ast::AssocItemKind::Delegation(..) => AssocSuggestion::AssocFn { called },
2806                        ast::AssocItemKind::MacCall(_) | ast::AssocItemKind::DelegationMac(..) => {
2807                            continue;
2808                        }
2809                    });
2810                }
2811            }
2812        }
2813
2814        // Look for associated items in the current trait.
2815        if let Some((module, _)) = self.current_trait_ref
2816            && let Ok(binding) = self.r.cm().maybe_resolve_ident_in_module(
2817                ModuleOrUniformRoot::Module(module),
2818                ident,
2819                ns,
2820                &self.parent_scope,
2821                None,
2822            )
2823        {
2824            let res = binding.res();
2825            if filter_fn(res) {
2826                match res {
2827                    Res::Def(DefKind::Fn | DefKind::AssocFn, def_id) => {
2828                        let has_self = match def_id.as_local() {
2829                            Some(def_id) => self
2830                                .r
2831                                .delegation_fn_sigs
2832                                .get(&def_id)
2833                                .is_some_and(|sig| sig.has_self),
2834                            None => {
2835                                self.r.tcx.fn_arg_idents(def_id).first().is_some_and(|&ident| {
2836                                    #[allow(non_exhaustive_omitted_patterns)] match ident {
    Some(Ident { name: kw::SelfLower, .. }) => true,
    _ => false,
}matches!(ident, Some(Ident { name: kw::SelfLower, .. }))
2837                                })
2838                            }
2839                        };
2840                        if has_self {
2841                            return Some(AssocSuggestion::MethodWithSelf { called });
2842                        } else {
2843                            return Some(AssocSuggestion::AssocFn { called });
2844                        }
2845                    }
2846                    Res::Def(DefKind::AssocConst { .. }, _) => {
2847                        return Some(AssocSuggestion::AssocConst);
2848                    }
2849                    Res::Def(DefKind::AssocTy, _) => {
2850                        return Some(AssocSuggestion::AssocType);
2851                    }
2852                    _ => {}
2853                }
2854            }
2855        }
2856
2857        None
2858    }
2859
2860    fn lookup_typo_candidate(
2861        &mut self,
2862        path: &[Segment],
2863        following_seg: Option<&Segment>,
2864        ns: Namespace,
2865        filter_fn: &impl Fn(Res) -> bool,
2866    ) -> TypoCandidate {
2867        let mut names = Vec::new();
2868        if let [segment] = path {
2869            let mut ctxt = segment.ident.span.ctxt();
2870
2871            // Search in lexical scope.
2872            // Walk backwards up the ribs in scope and collect candidates.
2873            for rib in self.ribs[ns].iter().rev() {
2874                let rib_ctxt = if rib.kind.contains_params() {
2875                    ctxt.normalize_to_macros_2_0()
2876                } else {
2877                    ctxt.normalize_to_macro_rules()
2878                };
2879
2880                // Locals and type parameters
2881                for (ident, &res) in &rib.bindings {
2882                    if filter_fn(res) && ident.span.ctxt() == rib_ctxt {
2883                        names.push(TypoSuggestion::new(ident.name, ident.span, res));
2884                    }
2885                }
2886
2887                if let RibKind::Block(Some(module)) = rib.kind {
2888                    self.r.add_module_candidates(module, &mut names, &filter_fn, Some(ctxt));
2889                } else if let RibKind::Module(module) = rib.kind {
2890                    // Encountered a module item, abandon ribs and look into that module and preludes.
2891                    let parent_scope = &ParentScope { module, ..self.parent_scope };
2892                    self.r.add_scope_set_candidates(
2893                        &mut names,
2894                        ScopeSet::All(ns),
2895                        parent_scope,
2896                        segment.ident.span.with_ctxt(ctxt),
2897                        filter_fn,
2898                    );
2899                    break;
2900                }
2901
2902                if let RibKind::MacroDefinition(def) = rib.kind
2903                    && def == self.r.macro_def(ctxt)
2904                {
2905                    // If an invocation of this macro created `ident`, give up on `ident`
2906                    // and switch to `ident`'s source from the macro definition.
2907                    ctxt.remove_mark();
2908                }
2909            }
2910        } else {
2911            // Search in module.
2912            let mod_path = &path[..path.len() - 1];
2913            if let PathResult::Module(ModuleOrUniformRoot::Module(module)) =
2914                self.resolve_path(mod_path, Some(TypeNS), None, PathSource::Type)
2915            {
2916                self.r.add_module_candidates(module, &mut names, &filter_fn, None);
2917            }
2918        }
2919
2920        // if next_seg is present, let's filter everything that does not continue the path
2921        if let Some(following_seg) = following_seg {
2922            names.retain(|suggestion| match suggestion.res {
2923                Res::Def(DefKind::Struct | DefKind::Enum | DefKind::Union, _) => {
2924                    // FIXME: this is not totally accurate, but mostly works
2925                    suggestion.candidate != following_seg.ident.name
2926                }
2927                Res::Def(DefKind::Mod, def_id) => {
2928                    let module = self.r.expect_module(def_id);
2929                    self.r
2930                        .resolutions(module)
2931                        .borrow()
2932                        .iter()
2933                        .any(|(key, _)| key.ident.name == following_seg.ident.name)
2934                }
2935                _ => true,
2936            });
2937        }
2938        let name = path[path.len() - 1].ident.name;
2939        // Make sure error reporting is deterministic.
2940        names.sort_by(|a, b| a.candidate.as_str().cmp(b.candidate.as_str()));
2941
2942        match find_best_match_for_name(
2943            &names.iter().map(|suggestion| suggestion.candidate).collect::<Vec<Symbol>>(),
2944            name,
2945            None,
2946        ) {
2947            Some(found) => {
2948                let Some(sugg) = names.into_iter().find(|suggestion| suggestion.candidate == found)
2949                else {
2950                    return TypoCandidate::None;
2951                };
2952                if found == name {
2953                    TypoCandidate::Shadowed(sugg.res, sugg.span)
2954                } else {
2955                    TypoCandidate::Typo(sugg)
2956                }
2957            }
2958            _ => TypoCandidate::None,
2959        }
2960    }
2961
2962    // Returns the name of the Rust type approximately corresponding to
2963    // a type name in another programming language.
2964    fn likely_rust_type(path: &[Segment]) -> Option<Symbol> {
2965        let name = path[path.len() - 1].ident.as_str();
2966        // Common Java types
2967        Some(match name {
2968            "byte" => sym::u8, // In Java, bytes are signed, but in practice one almost always wants unsigned bytes.
2969            "short" => sym::i16,
2970            "Bool" => sym::bool,
2971            "Boolean" => sym::bool,
2972            "boolean" => sym::bool,
2973            "int" => sym::i32,
2974            "long" => sym::i64,
2975            "float" => sym::f32,
2976            "double" => sym::f64,
2977            _ => return None,
2978        })
2979    }
2980
2981    // try to give a suggestion for this pattern: `name = blah`, which is common in other languages
2982    // suggest `let name = blah` to introduce a new binding
2983    fn let_binding_suggestion(&self, err: &mut Diag<'_>, ident_span: Span) -> bool {
2984        if ident_span.from_expansion() {
2985            return false;
2986        }
2987
2988        // only suggest when the code is a assignment without prefix code
2989        if let Some(Expr { kind: ExprKind::Assign(lhs, ..), .. }) = self.diag_metadata.in_assignment
2990            && let ast::ExprKind::Path(None, ref path) = lhs.kind
2991            && self.r.tcx.sess.source_map().is_line_before_span_empty(ident_span)
2992        {
2993            let (span, text) = match path.segments.first() {
2994                Some(seg) if let Some(name) = seg.ident.as_str().strip_prefix("let") => {
2995                    // a special case for #117894
2996                    let name = name.trim_prefix('_');
2997                    (ident_span, ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("let {0}", name))
    })format!("let {name}"))
2998                }
2999                _ => (ident_span.shrink_to_lo(), "let ".to_string()),
3000            };
3001
3002            err.span_suggestion_verbose(
3003                span,
3004                "you might have meant to introduce a new binding",
3005                text,
3006                Applicability::MaybeIncorrect,
3007            );
3008            return true;
3009        }
3010
3011        // a special case for #133713
3012        // '=' maybe a typo of `:`, which is a type annotation instead of assignment
3013        if err.code == Some(E0423)
3014            && let Some((let_span, None, Some(val_span))) = self.diag_metadata.current_let_binding
3015            && val_span.contains(ident_span)
3016            && val_span.lo() == ident_span.lo()
3017        {
3018            err.span_suggestion_verbose(
3019                let_span.shrink_to_hi().to(val_span.shrink_to_lo()),
3020                "you might have meant to use `:` for type annotation",
3021                ": ",
3022                Applicability::MaybeIncorrect,
3023            );
3024            return true;
3025        }
3026        false
3027    }
3028
3029    fn find_module(&self, def_id: DefId) -> Option<(Module<'ra>, ImportSuggestion)> {
3030        let mut result = None;
3031        let mut seen_modules = FxHashSet::default();
3032        let root_did = self.r.graph_root.def_id();
3033        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![(
3034            self.r.graph_root,
3035            ThinVec::new(),
3036            root_did.is_local() || !self.r.tcx.is_doc_hidden(root_did),
3037        )];
3038
3039        while let Some((in_module, path_segments, doc_visible)) = worklist.pop() {
3040            // abort if the module is already found
3041            if result.is_some() {
3042                break;
3043            }
3044
3045            in_module.for_each_child(self.r, |r, ident, orig_ident_span, _, name_binding| {
3046                // abort if the module is already found or if name_binding is private external
3047                if result.is_some() || !name_binding.vis().is_visible_locally() {
3048                    return;
3049                }
3050                if let Some(module_def_id) = name_binding.res().module_like_def_id() {
3051                    // form the path
3052                    let mut path_segments = path_segments.clone();
3053                    path_segments.push(ast::PathSegment::from_ident(ident.orig(orig_ident_span)));
3054                    let doc_visible = doc_visible
3055                        && (module_def_id.is_local() || !r.tcx.is_doc_hidden(module_def_id));
3056                    if module_def_id == def_id {
3057                        let path =
3058                            Path { span: name_binding.span, segments: path_segments, tokens: None };
3059                        result = Some((
3060                            r.expect_module(module_def_id),
3061                            ImportSuggestion {
3062                                did: Some(def_id),
3063                                descr: "module",
3064                                path,
3065                                accessible: true,
3066                                doc_visible,
3067                                note: None,
3068                                via_import: false,
3069                                is_stable: true,
3070                            },
3071                        ));
3072                    } else {
3073                        // add the module to the lookup
3074                        if seen_modules.insert(module_def_id) {
3075                            let module = r.expect_module(module_def_id);
3076                            worklist.push((module, path_segments, doc_visible));
3077                        }
3078                    }
3079                }
3080            });
3081        }
3082
3083        result
3084    }
3085
3086    fn collect_enum_ctors(&self, def_id: DefId) -> Option<Vec<(Path, DefId, CtorKind)>> {
3087        self.find_module(def_id).map(|(enum_module, enum_import_suggestion)| {
3088            let mut variants = Vec::new();
3089            enum_module.for_each_child(self.r, |_, ident, orig_ident_span, _, name_binding| {
3090                if let Res::Def(DefKind::Ctor(CtorOf::Variant, kind), def_id) = name_binding.res() {
3091                    let mut segms = enum_import_suggestion.path.segments.clone();
3092                    segms.push(ast::PathSegment::from_ident(ident.orig(orig_ident_span)));
3093                    let path = Path { span: name_binding.span, segments: segms, tokens: None };
3094                    variants.push((path, def_id, kind));
3095                }
3096            });
3097            variants
3098        })
3099    }
3100
3101    /// Adds a suggestion for using an enum's variant when an enum is used instead.
3102    fn suggest_using_enum_variant(
3103        &self,
3104        err: &mut Diag<'_>,
3105        source: PathSource<'_, '_, '_>,
3106        def_id: DefId,
3107        span: Span,
3108    ) {
3109        let Some(variant_ctors) = self.collect_enum_ctors(def_id) else {
3110            err.note("you might have meant to use one of the enum's variants");
3111            return;
3112        };
3113
3114        // If the expression is a field-access or method-call, try to find a variant with the field/method name
3115        // that could have been intended, and suggest replacing the `.` with `::`.
3116        // Otherwise, suggest adding `::VariantName` after the enum;
3117        // and if the expression is call-like, only suggest tuple variants.
3118        let (suggest_path_sep_dot_span, suggest_only_tuple_variants) = match source {
3119            // `Type(a, b)` in a pattern, only suggest adding a tuple variant after `Type`.
3120            PathSource::TupleStruct(..) => (None, true),
3121            PathSource::Expr(Some(expr)) => match &expr.kind {
3122                // `Type(a, b)`, only suggest adding a tuple variant after `Type`.
3123                ExprKind::Call(..) => (None, true),
3124                // `Type.Foo(a, b)`, suggest replacing `.` -> `::` if variant `Foo` exists and is a tuple variant,
3125                // otherwise suggest adding a variant after `Type`.
3126                ExprKind::MethodCall(box MethodCall {
3127                    receiver,
3128                    span,
3129                    seg: PathSegment { ident, .. },
3130                    ..
3131                }) => {
3132                    let dot_span = receiver.span.between(*span);
3133                    let found_tuple_variant = variant_ctors.iter().any(|(path, _, ctor_kind)| {
3134                        *ctor_kind == CtorKind::Fn
3135                            && path.segments.last().is_some_and(|seg| seg.ident == *ident)
3136                    });
3137                    (found_tuple_variant.then_some(dot_span), false)
3138                }
3139                // `Type.Foo`, suggest replacing `.` -> `::` if variant `Foo` exists and is a unit or tuple variant,
3140                // otherwise suggest adding a variant after `Type`.
3141                ExprKind::Field(base, ident) => {
3142                    let dot_span = base.span.between(ident.span);
3143                    let found_tuple_or_unit_variant = variant_ctors.iter().any(|(path, ..)| {
3144                        path.segments.last().is_some_and(|seg| seg.ident == *ident)
3145                    });
3146                    (found_tuple_or_unit_variant.then_some(dot_span), false)
3147                }
3148                _ => (None, false),
3149            },
3150            _ => (None, false),
3151        };
3152
3153        if let Some(dot_span) = suggest_path_sep_dot_span {
3154            err.span_suggestion_verbose(
3155                dot_span,
3156                "use the path separator to refer to a variant",
3157                "::",
3158                Applicability::MaybeIncorrect,
3159            );
3160        } else if suggest_only_tuple_variants {
3161            // Suggest only tuple variants regardless of whether they have fields and do not
3162            // suggest path with added parentheses.
3163            let mut suggestable_variants = variant_ctors
3164                .iter()
3165                .filter(|(.., kind)| *kind == CtorKind::Fn)
3166                .map(|(variant, ..)| path_names_to_string(variant))
3167                .collect::<Vec<_>>();
3168            suggestable_variants.sort();
3169
3170            let non_suggestable_variant_count = variant_ctors.len() - suggestable_variants.len();
3171
3172            let source_msg = if #[allow(non_exhaustive_omitted_patterns)] match source {
    PathSource::TupleStruct(..) => true,
    _ => false,
}matches!(source, PathSource::TupleStruct(..)) {
3173                "to match against"
3174            } else {
3175                "to construct"
3176            };
3177
3178            if !suggestable_variants.is_empty() {
3179                let msg = if non_suggestable_variant_count == 0 && suggestable_variants.len() == 1 {
3180                    ::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")
3181                } else {
3182                    ::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")
3183                };
3184
3185                err.span_suggestions(
3186                    span,
3187                    msg,
3188                    suggestable_variants,
3189                    Applicability::MaybeIncorrect,
3190                );
3191            }
3192
3193            // If the enum has no tuple variants..
3194            if non_suggestable_variant_count == variant_ctors.len() {
3195                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}"));
3196            }
3197
3198            // If there are also non-tuple variants..
3199            if non_suggestable_variant_count == 1 {
3200                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"));
3201            } else if non_suggestable_variant_count >= 1 {
3202                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!(
3203                    "you might have meant {source_msg} one of the enum's non-tuple variants"
3204                ));
3205            }
3206        } else {
3207            let needs_placeholder = |ctor_def_id: DefId, kind: CtorKind| {
3208                let def_id = self.r.tcx.parent(ctor_def_id);
3209                match kind {
3210                    CtorKind::Const => false,
3211                    CtorKind::Fn => {
3212                        !self.r.field_idents(def_id).is_some_and(|field_ids| field_ids.is_empty())
3213                    }
3214                }
3215            };
3216
3217            let mut suggestable_variants = variant_ctors
3218                .iter()
3219                .filter(|(_, def_id, kind)| !needs_placeholder(*def_id, *kind))
3220                .map(|(variant, _, kind)| (path_names_to_string(variant), kind))
3221                .map(|(variant, kind)| match kind {
3222                    CtorKind::Const => variant,
3223                    CtorKind::Fn => ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("({0}())", variant))
    })format!("({variant}())"),
3224                })
3225                .collect::<Vec<_>>();
3226            suggestable_variants.sort();
3227            let no_suggestable_variant = suggestable_variants.is_empty();
3228
3229            if !no_suggestable_variant {
3230                let msg = if suggestable_variants.len() == 1 {
3231                    "you might have meant to use the following enum variant"
3232                } else {
3233                    "you might have meant to use one of the following enum variants"
3234                };
3235
3236                err.span_suggestions(
3237                    span,
3238                    msg,
3239                    suggestable_variants,
3240                    Applicability::MaybeIncorrect,
3241                );
3242            }
3243
3244            let mut suggestable_variants_with_placeholders = variant_ctors
3245                .iter()
3246                .filter(|(_, def_id, kind)| needs_placeholder(*def_id, *kind))
3247                .map(|(variant, _, kind)| (path_names_to_string(variant), kind))
3248                .filter_map(|(variant, kind)| match kind {
3249                    CtorKind::Fn => Some(::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("({0}(/* fields */))", variant))
    })format!("({variant}(/* fields */))")),
3250                    _ => None,
3251                })
3252                .collect::<Vec<_>>();
3253            suggestable_variants_with_placeholders.sort();
3254
3255            if !suggestable_variants_with_placeholders.is_empty() {
3256                let msg =
3257                    match (no_suggestable_variant, suggestable_variants_with_placeholders.len()) {
3258                        (true, 1) => "the following enum variant is available",
3259                        (true, _) => "the following enum variants are available",
3260                        (false, 1) => "alternatively, the following enum variant is available",
3261                        (false, _) => {
3262                            "alternatively, the following enum variants are also available"
3263                        }
3264                    };
3265
3266                err.span_suggestions(
3267                    span,
3268                    msg,
3269                    suggestable_variants_with_placeholders,
3270                    Applicability::HasPlaceholders,
3271                );
3272            }
3273        };
3274
3275        if def_id.is_local() {
3276            err.span_note(self.r.def_span(def_id), "the enum is defined here");
3277        }
3278    }
3279
3280    pub(crate) fn suggest_adding_generic_parameter(
3281        &self,
3282        path: &[Segment],
3283        source: PathSource<'_, '_, '_>,
3284    ) -> Option<(Span, &'static str, String, Applicability)> {
3285        let (ident, span) = match path {
3286            [segment]
3287                if !segment.has_generic_args
3288                    && segment.ident.name != kw::SelfUpper
3289                    && segment.ident.name != kw::Dyn =>
3290            {
3291                (segment.ident.to_string(), segment.ident.span)
3292            }
3293            _ => return None,
3294        };
3295        let mut iter = ident.chars().map(|c| c.is_uppercase());
3296        let single_uppercase_char =
3297            #[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);
3298        if !self.diag_metadata.currently_processing_generic_args && !single_uppercase_char {
3299            return None;
3300        }
3301        match (self.diag_metadata.current_item, single_uppercase_char, self.diag_metadata.currently_processing_generic_args) {
3302            (Some(Item { kind: ItemKind::Fn(fn_), .. }), _, _) if fn_.ident.name == sym::main => {
3303                // Ignore `fn main()` as we don't want to suggest `fn main<T>()`
3304            }
3305            (
3306                Some(Item {
3307                    kind:
3308                        kind @ ItemKind::Fn(..)
3309                        | kind @ ItemKind::Enum(..)
3310                        | kind @ ItemKind::Struct(..)
3311                        | kind @ ItemKind::Union(..),
3312                    ..
3313                }),
3314                true, _
3315            )
3316            // Without the 2nd `true`, we'd suggest `impl <T>` for `impl T` when a type `T` isn't found
3317            | (Some(Item { kind: kind @ ItemKind::Impl(..), .. }), true, true)
3318            | (Some(Item { kind, .. }), false, _) => {
3319                if let Some(generics) = kind.generics() {
3320                    if span.overlaps(generics.span) {
3321                        // Avoid the following:
3322                        // error[E0405]: cannot find trait `A` in this scope
3323                        //  --> $DIR/typo-suggestion-named-underscore.rs:CC:LL
3324                        //   |
3325                        // L | fn foo<T: A>(x: T) {} // Shouldn't suggest underscore
3326                        //   |           ^- help: you might be missing a type parameter: `, A`
3327                        //   |           |
3328                        //   |           not found in this scope
3329                        return None;
3330                    }
3331
3332                    let (msg, sugg) = match source {
3333                        PathSource::Type | PathSource::PreciseCapturingArg(TypeNS) => {
3334                            ("you might be missing a type parameter", ident)
3335                        }
3336                        PathSource::Expr(_) | PathSource::PreciseCapturingArg(ValueNS) => (
3337                            "you might be missing a const parameter",
3338                            ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("const {0}: /* Type */", ident))
    })format!("const {ident}: /* Type */"),
3339                        ),
3340                        _ => return None,
3341                    };
3342                    let (span, sugg) = if let [.., param] = &generics.params[..] {
3343                        let span = if let [.., bound] = &param.bounds[..] {
3344                            bound.span()
3345                        } else if let GenericParam {
3346                            kind: GenericParamKind::Const { ty, span: _, default  }, ..
3347                        } = param {
3348                            default.as_ref().map(|def| def.value.span).unwrap_or(ty.span)
3349                        } else {
3350                            param.ident.span
3351                        };
3352                        (span, ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!(", {0}", sugg))
    })format!(", {sugg}"))
3353                    } else {
3354                        (generics.span, ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("<{0}>", sugg))
    })format!("<{sugg}>"))
3355                    };
3356                    // Do not suggest if this is coming from macro expansion.
3357                    if span.can_be_used_for_suggestions() {
3358                        return Some((
3359                            span.shrink_to_hi(),
3360                            msg,
3361                            sugg,
3362                            Applicability::MaybeIncorrect,
3363                        ));
3364                    }
3365                }
3366            }
3367            _ => {}
3368        }
3369        None
3370    }
3371
3372    /// Given the target `label`, search the `rib_index`th label rib for similarly named labels,
3373    /// optionally returning the closest match and whether it is reachable.
3374    pub(crate) fn suggestion_for_label_in_rib(
3375        &self,
3376        rib_index: usize,
3377        label: Ident,
3378    ) -> Option<LabelSuggestion> {
3379        // Are ribs from this `rib_index` within scope?
3380        let within_scope = self.is_label_valid_from_rib(rib_index);
3381
3382        let rib = &self.label_ribs[rib_index];
3383        let names = rib
3384            .bindings
3385            .iter()
3386            .filter(|(id, _)| id.span.eq_ctxt(label.span))
3387            .map(|(id, _)| id.name)
3388            .collect::<Vec<Symbol>>();
3389
3390        find_best_match_for_name(&names, label.name, None).map(|symbol| {
3391            // Upon finding a similar name, get the ident that it was from - the span
3392            // contained within helps make a useful diagnostic. In addition, determine
3393            // whether this candidate is within scope.
3394            let (ident, _) = rib.bindings.iter().find(|(ident, _)| ident.name == symbol).unwrap();
3395            (*ident, within_scope)
3396        })
3397    }
3398
3399    pub(crate) fn maybe_report_lifetime_uses(
3400        &mut self,
3401        generics_span: Span,
3402        params: &[ast::GenericParam],
3403    ) {
3404        for (param_index, param) in params.iter().enumerate() {
3405            let GenericParamKind::Lifetime = param.kind else { continue };
3406
3407            let def_id = self.r.local_def_id(param.id);
3408
3409            let use_set = self.lifetime_uses.remove(&def_id);
3410            {
    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:3410",
                        "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(3410u32),
                        ::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!(
3411                "Use set for {:?}({:?} at {:?}) is {:?}",
3412                def_id, param.ident, param.ident.span, use_set
3413            );
3414
3415            let deletion_span = || {
3416                if params.len() == 1 {
3417                    // if sole lifetime, remove the entire `<>` brackets
3418                    Some(generics_span)
3419                } else if param_index == 0 {
3420                    // if removing within `<>` brackets, we also want to
3421                    // delete a leading or trailing comma as appropriate
3422                    match (
3423                        param.span().find_ancestor_inside(generics_span),
3424                        params[param_index + 1].span().find_ancestor_inside(generics_span),
3425                    ) {
3426                        (Some(param_span), Some(next_param_span)) => {
3427                            Some(param_span.to(next_param_span.shrink_to_lo()))
3428                        }
3429                        _ => None,
3430                    }
3431                } else {
3432                    // if removing within `<>` brackets, we also want to
3433                    // delete a leading or trailing comma as appropriate
3434                    match (
3435                        param.span().find_ancestor_inside(generics_span),
3436                        params[param_index - 1].span().find_ancestor_inside(generics_span),
3437                    ) {
3438                        (Some(param_span), Some(prev_param_span)) => {
3439                            Some(prev_param_span.shrink_to_hi().to(param_span))
3440                        }
3441                        _ => None,
3442                    }
3443                }
3444            };
3445            match use_set {
3446                Some(LifetimeUseSet::Many) => {}
3447                Some(LifetimeUseSet::One { use_span, use_ctxt }) => {
3448                    {
    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:3448",
                        "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(3448u32),
                        ::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);
3449
3450                    let elidable = #[allow(non_exhaustive_omitted_patterns)] match use_ctxt {
    LifetimeCtxt::Ref => true,
    _ => false,
}matches!(use_ctxt, LifetimeCtxt::Ref);
3451                    let deletion_span =
3452                        if param.bounds.is_empty() { deletion_span() } else { None };
3453
3454                    self.r.lint_buffer.buffer_lint(
3455                        lint::builtin::SINGLE_USE_LIFETIMES,
3456                        param.id,
3457                        param.ident.span,
3458                        lint::BuiltinLintDiag::SingleUseLifetime {
3459                            param_span: param.ident.span,
3460                            use_span: Some((use_span, elidable)),
3461                            deletion_span,
3462                            ident: param.ident,
3463                        },
3464                    );
3465                }
3466                None => {
3467                    {
    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:3467",
                        "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(3467u32),
                        ::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);
3468                    let deletion_span = deletion_span();
3469
3470                    // if the lifetime originates from expanded code, we won't be able to remove it #104432
3471                    if deletion_span.is_some_and(|sp| !sp.in_derive_expansion()) {
3472                        self.r.lint_buffer.buffer_lint(
3473                            lint::builtin::UNUSED_LIFETIMES,
3474                            param.id,
3475                            param.ident.span,
3476                            lint::BuiltinLintDiag::SingleUseLifetime {
3477                                param_span: param.ident.span,
3478                                use_span: None,
3479                                deletion_span,
3480                                ident: param.ident,
3481                            },
3482                        );
3483                    }
3484                }
3485            }
3486        }
3487    }
3488
3489    pub(crate) fn emit_undeclared_lifetime_error(
3490        &self,
3491        lifetime_ref: &ast::Lifetime,
3492        outer_lifetime_ref: Option<Ident>,
3493    ) -> ErrorGuaranteed {
3494        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);
3495        let mut err = if let Some(outer) = outer_lifetime_ref {
3496            {
    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!(
3497                self.r.dcx(),
3498                lifetime_ref.ident.span,
3499                E0401,
3500                "can't use generic parameters from outer item",
3501            )
3502            .with_span_label(lifetime_ref.ident.span, "use of generic parameter from outer item")
3503            .with_span_label(outer.span, "lifetime parameter from outer item")
3504        } else {
3505            {
    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!(
3506                self.r.dcx(),
3507                lifetime_ref.ident.span,
3508                E0261,
3509                "use of undeclared lifetime name `{}`",
3510                lifetime_ref.ident
3511            )
3512            .with_span_label(lifetime_ref.ident.span, "undeclared lifetime")
3513        };
3514
3515        // Check if this is a typo of `'static`.
3516        if edit_distance(lifetime_ref.ident.name.as_str(), "'static", 2).is_some() {
3517            err.span_suggestion_verbose(
3518                lifetime_ref.ident.span,
3519                "you may have misspelled the `'static` lifetime",
3520                "'static",
3521                Applicability::MachineApplicable,
3522            );
3523        } else {
3524            self.suggest_introducing_lifetime(
3525                &mut err,
3526                Some(lifetime_ref.ident),
3527                |err, _, span, message, suggestion, span_suggs| {
3528                    err.multipart_suggestion(
3529                        message,
3530                        std::iter::once((span, suggestion)).chain(span_suggs).collect(),
3531                        Applicability::MaybeIncorrect,
3532                    );
3533                    true
3534                },
3535            );
3536        }
3537
3538        err.emit()
3539    }
3540
3541    fn suggest_introducing_lifetime(
3542        &self,
3543        err: &mut Diag<'_>,
3544        name: Option<Ident>,
3545        suggest: impl Fn(
3546            &mut Diag<'_>,
3547            bool,
3548            Span,
3549            Cow<'static, str>,
3550            String,
3551            Vec<(Span, String)>,
3552        ) -> bool,
3553    ) {
3554        let mut suggest_note = true;
3555        for rib in self.lifetime_ribs.iter().rev() {
3556            let mut should_continue = true;
3557            match rib.kind {
3558                LifetimeRibKind::Generics { binder, span, kind } => {
3559                    // Avoid suggesting placing lifetime parameters on constant items unless the relevant
3560                    // feature is enabled. Suggest the parent item as a possible location if applicable.
3561                    if let LifetimeBinderKind::ConstItem = kind
3562                        && !self.r.tcx().features().generic_const_items()
3563                    {
3564                        continue;
3565                    }
3566                    if let LifetimeBinderKind::ImplAssocType = kind {
3567                        continue;
3568                    }
3569
3570                    if !span.can_be_used_for_suggestions()
3571                        && suggest_note
3572                        && let Some(name) = name
3573                    {
3574                        suggest_note = false; // Avoid displaying the same help multiple times.
3575                        err.span_label(
3576                            span,
3577                            ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("lifetime `{0}` is missing in item created through this procedural macro",
                name))
    })format!(
3578                                "lifetime `{name}` is missing in item created through this procedural macro",
3579                            ),
3580                        );
3581                        continue;
3582                    }
3583
3584                    let higher_ranked = #[allow(non_exhaustive_omitted_patterns)] match kind {
    LifetimeBinderKind::FnPtrType | LifetimeBinderKind::PolyTrait |
        LifetimeBinderKind::WhereBound => true,
    _ => false,
}matches!(
3585                        kind,
3586                        LifetimeBinderKind::FnPtrType
3587                            | LifetimeBinderKind::PolyTrait
3588                            | LifetimeBinderKind::WhereBound
3589                    );
3590
3591                    let mut rm_inner_binders: FxIndexSet<Span> = Default::default();
3592                    let (span, sugg) = if span.is_empty() {
3593                        let mut binder_idents: FxIndexSet<Ident> = Default::default();
3594                        binder_idents.insert(name.unwrap_or(Ident::from_str("'a")));
3595
3596                        // We need to special case binders in the following situation:
3597                        // Change `T: for<'a> Trait<T> + 'b` to `for<'a, 'b> T: Trait<T> + 'b`
3598                        // T: for<'a> Trait<T> + 'b
3599                        //    ^^^^^^^  remove existing inner binder `for<'a>`
3600                        // for<'a, 'b> T: Trait<T> + 'b
3601                        // ^^^^^^^^^^^  suggest outer binder `for<'a, 'b>`
3602                        if let LifetimeBinderKind::WhereBound = kind
3603                            && let Some(predicate) = self.diag_metadata.current_where_predicate
3604                            && let ast::WherePredicateKind::BoundPredicate(
3605                                ast::WhereBoundPredicate { bounded_ty, bounds, .. },
3606                            ) = &predicate.kind
3607                            && bounded_ty.id == binder
3608                        {
3609                            for bound in bounds {
3610                                if let ast::GenericBound::Trait(poly_trait_ref) = bound
3611                                    && let span = poly_trait_ref
3612                                        .span
3613                                        .with_hi(poly_trait_ref.trait_ref.path.span.lo())
3614                                    && !span.is_empty()
3615                                {
3616                                    rm_inner_binders.insert(span);
3617                                    poly_trait_ref.bound_generic_params.iter().for_each(|v| {
3618                                        binder_idents.insert(v.ident);
3619                                    });
3620                                }
3621                            }
3622                        }
3623
3624                        let binders_sugg: String = binder_idents
3625                            .into_iter()
3626                            .map(|ident| ident.to_string())
3627                            .intersperse(", ".to_owned())
3628                            .collect();
3629                        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!(
3630                            "{}<{}>{}",
3631                            if higher_ranked { "for" } else { "" },
3632                            binders_sugg,
3633                            if higher_ranked { " " } else { "" },
3634                        );
3635                        (span, sugg)
3636                    } else {
3637                        let span = self
3638                            .r
3639                            .tcx
3640                            .sess
3641                            .source_map()
3642                            .span_through_char(span, '<')
3643                            .shrink_to_hi();
3644                        let sugg =
3645                            ::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"));
3646                        (span, sugg)
3647                    };
3648
3649                    if higher_ranked {
3650                        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!(
3651                            "consider making the {} lifetime-generic with a new `{}` lifetime",
3652                            kind.descr(),
3653                            name.map(|i| i.to_string()).as_deref().unwrap_or("'a"),
3654                        ));
3655                        should_continue = suggest(
3656                            err,
3657                            true,
3658                            span,
3659                            message,
3660                            sugg,
3661                            if !rm_inner_binders.is_empty() {
3662                                rm_inner_binders
3663                                    .into_iter()
3664                                    .map(|v| (v, "".to_string()))
3665                                    .collect::<Vec<_>>()
3666                            } else {
3667                                ::alloc::vec::Vec::new()vec![]
3668                            },
3669                        );
3670                        err.note_once(
3671                            "for more information on higher-ranked polymorphism, visit \
3672                             https://doc.rust-lang.org/nomicon/hrtb.html",
3673                        );
3674                    } else if let Some(name) = name {
3675                        let message =
3676                            Cow::from(::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("consider introducing lifetime `{0}` here",
                name))
    })format!("consider introducing lifetime `{name}` here"));
3677                        should_continue = suggest(err, false, span, message, sugg, ::alloc::vec::Vec::new()vec![]);
3678                    } else {
3679                        let message = Cow::from("consider introducing a named lifetime parameter");
3680                        should_continue = suggest(err, false, span, message, sugg, ::alloc::vec::Vec::new()vec![]);
3681                    }
3682                }
3683                LifetimeRibKind::Item | LifetimeRibKind::ConstParamTy => break,
3684                _ => {}
3685            }
3686            if !should_continue {
3687                break;
3688            }
3689        }
3690    }
3691
3692    pub(crate) fn emit_non_static_lt_in_const_param_ty_error(
3693        &self,
3694        lifetime_ref: &ast::Lifetime,
3695    ) -> ErrorGuaranteed {
3696        self.r
3697            .dcx()
3698            .create_err(errors::ParamInTyOfConstParam {
3699                span: lifetime_ref.ident.span,
3700                name: lifetime_ref.ident.name,
3701            })
3702            .emit()
3703    }
3704
3705    /// Non-static lifetimes are prohibited in anonymous constants under `min_const_generics`.
3706    /// This function will emit an error if `generic_const_exprs` is not enabled, the body identified by
3707    /// `body_id` is an anonymous constant and `lifetime_ref` is non-static.
3708    pub(crate) fn emit_forbidden_non_static_lifetime_error(
3709        &self,
3710        cause: NoConstantGenericsReason,
3711        lifetime_ref: &ast::Lifetime,
3712    ) -> ErrorGuaranteed {
3713        match cause {
3714            NoConstantGenericsReason::IsEnumDiscriminant => self
3715                .r
3716                .dcx()
3717                .create_err(errors::ParamInEnumDiscriminant {
3718                    span: lifetime_ref.ident.span,
3719                    name: lifetime_ref.ident.name,
3720                    param_kind: errors::ParamKindInEnumDiscriminant::Lifetime,
3721                })
3722                .emit(),
3723            NoConstantGenericsReason::NonTrivialConstArg => {
3724                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());
3725                self.r
3726                    .dcx()
3727                    .create_err(errors::ParamInNonTrivialAnonConst {
3728                        span: lifetime_ref.ident.span,
3729                        name: lifetime_ref.ident.name,
3730                        param_kind: errors::ParamKindInNonTrivialAnonConst::Lifetime,
3731                        help: self.r.tcx.sess.is_nightly_build(),
3732                        is_ogca: self.r.tcx.features().opaque_generic_const_args(),
3733                        help_ogca: self.r.tcx.features().opaque_generic_const_args(),
3734                    })
3735                    .emit()
3736            }
3737        }
3738    }
3739
3740    pub(crate) fn report_missing_lifetime_specifiers<'a>(
3741        &mut self,
3742        lifetime_refs: impl Clone + IntoIterator<Item = &'a MissingLifetime>,
3743        function_param_lifetimes: Option<(Vec<MissingLifetime>, Vec<ElisionFnParameter>)>,
3744    ) -> ErrorGuaranteed {
3745        let num_lifetimes: usize = lifetime_refs.clone().into_iter().map(|lt| lt.count).sum();
3746        let spans: Vec<_> = lifetime_refs.clone().into_iter().map(|lt| lt.span).collect();
3747
3748        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!(
3749            self.r.dcx(),
3750            spans,
3751            E0106,
3752            "missing lifetime specifier{}",
3753            pluralize!(num_lifetimes)
3754        );
3755        self.add_missing_lifetime_specifiers_label(
3756            &mut err,
3757            lifetime_refs,
3758            function_param_lifetimes,
3759        );
3760        err.emit()
3761    }
3762
3763    fn add_missing_lifetime_specifiers_label<'a>(
3764        &mut self,
3765        err: &mut Diag<'_>,
3766        lifetime_refs: impl Clone + IntoIterator<Item = &'a MissingLifetime>,
3767        function_param_lifetimes: Option<(Vec<MissingLifetime>, Vec<ElisionFnParameter>)>,
3768    ) {
3769        for &lt in lifetime_refs.clone() {
3770            err.span_label(
3771                lt.span,
3772                ::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!(
3773                    "expected {} lifetime parameter{}",
3774                    if lt.count == 1 { "named".to_string() } else { lt.count.to_string() },
3775                    pluralize!(lt.count),
3776                ),
3777            );
3778        }
3779
3780        let mut in_scope_lifetimes: Vec<_> = self
3781            .lifetime_ribs
3782            .iter()
3783            .rev()
3784            .take_while(|rib| {
3785                !#[allow(non_exhaustive_omitted_patterns)] match rib.kind {
    LifetimeRibKind::Item | LifetimeRibKind::ConstParamTy => true,
    _ => false,
}matches!(rib.kind, LifetimeRibKind::Item | LifetimeRibKind::ConstParamTy)
3786            })
3787            .flat_map(|rib| rib.bindings.iter())
3788            .map(|(&ident, &res)| (ident, res))
3789            .filter(|(ident, _)| ident.name != kw::UnderscoreLifetime)
3790            .collect();
3791        {
    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:3791",
                        "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(3791u32),
                        ::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);
3792
3793        let mut maybe_static = false;
3794        {
    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:3794",
                        "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(3794u32),
                        ::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);
3795        if let Some((param_lifetimes, params)) = &function_param_lifetimes {
3796            let elided_len = param_lifetimes.len();
3797            let num_params = params.len();
3798
3799            let mut m = String::new();
3800
3801            for (i, info) in params.iter().enumerate() {
3802                let ElisionFnParameter { ident, index, lifetime_count, span } = *info;
3803                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);
3804
3805                err.span_label(span, "");
3806
3807                if i != 0 {
3808                    if i + 1 < num_params {
3809                        m.push_str(", ");
3810                    } else if num_params == 2 {
3811                        m.push_str(" or ");
3812                    } else {
3813                        m.push_str(", or ");
3814                    }
3815                }
3816
3817                let help_name = if let Some(ident) = ident {
3818                    ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("`{0}`", ident))
    })format!("`{ident}`")
3819                } else {
3820                    ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("argument {0}", index + 1))
    })format!("argument {}", index + 1)
3821                };
3822
3823                if lifetime_count == 1 {
3824                    m.push_str(&help_name[..])
3825                } else {
3826                    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")[..])
3827                }
3828            }
3829
3830            if num_params == 0 {
3831                err.help(
3832                    "this function's return type contains a borrowed value, but there is no value \
3833                     for it to be borrowed from",
3834                );
3835                if in_scope_lifetimes.is_empty() {
3836                    maybe_static = true;
3837                    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![(
3838                        Ident::with_dummy_span(kw::StaticLifetime),
3839                        (DUMMY_NODE_ID, LifetimeRes::Static),
3840                    )];
3841                }
3842            } else if elided_len == 0 {
3843                err.help(
3844                    "this function's return type contains a borrowed value with an elided \
3845                     lifetime, but the lifetime cannot be derived from the arguments",
3846                );
3847                if in_scope_lifetimes.is_empty() {
3848                    maybe_static = true;
3849                    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![(
3850                        Ident::with_dummy_span(kw::StaticLifetime),
3851                        (DUMMY_NODE_ID, LifetimeRes::Static),
3852                    )];
3853                }
3854            } else if num_params == 1 {
3855                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!(
3856                    "this function's return type contains a borrowed value, but the signature does \
3857                     not say which {m} it is borrowed from",
3858                ));
3859            } else {
3860                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!(
3861                    "this function's return type contains a borrowed value, but the signature does \
3862                     not say whether it is borrowed from {m}",
3863                ));
3864            }
3865        }
3866
3867        #[allow(rustc::symbol_intern_string_literal)]
3868        let existing_name = match &in_scope_lifetimes[..] {
3869            [] => Symbol::intern("'a"),
3870            [(existing, _)] => existing.name,
3871            _ => Symbol::intern("'lifetime"),
3872        };
3873
3874        let mut spans_suggs: Vec<_> = Vec::new();
3875        let build_sugg = |lt: MissingLifetime| match lt.kind {
3876            MissingLifetimeKind::Underscore => {
3877                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);
3878                (lt.span, existing_name.to_string())
3879            }
3880            MissingLifetimeKind::Ampersand => {
3881                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);
3882                (lt.span.shrink_to_hi(), ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("{0} ", existing_name))
    })format!("{existing_name} "))
3883            }
3884            MissingLifetimeKind::Comma => {
3885                let sugg: String = std::iter::repeat_n([existing_name.as_str(), ", "], lt.count)
3886                    .flatten()
3887                    .collect();
3888                (lt.span.shrink_to_hi(), sugg)
3889            }
3890            MissingLifetimeKind::Brackets => {
3891                let sugg: String = std::iter::once("<")
3892                    .chain(std::iter::repeat_n(existing_name.as_str(), lt.count).intersperse(", "))
3893                    .chain([">"])
3894                    .collect();
3895                (lt.span.shrink_to_hi(), sugg)
3896            }
3897        };
3898        for &lt in lifetime_refs.clone() {
3899            spans_suggs.push(build_sugg(lt));
3900        }
3901        {
    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:3901",
                        "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(3901u32),
                        ::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);
3902        match in_scope_lifetimes.len() {
3903            0 => {
3904                if let Some((param_lifetimes, _)) = function_param_lifetimes {
3905                    for lt in param_lifetimes {
3906                        spans_suggs.push(build_sugg(lt))
3907                    }
3908                }
3909                self.suggest_introducing_lifetime(
3910                    err,
3911                    None,
3912                    |err, higher_ranked, span, message, intro_sugg, _| {
3913                        err.multipart_suggestion(
3914                            message,
3915                            std::iter::once((span, intro_sugg))
3916                                .chain(spans_suggs.clone())
3917                                .collect(),
3918                            Applicability::MaybeIncorrect,
3919                        );
3920                        higher_ranked
3921                    },
3922                );
3923            }
3924            1 => {
3925                let post = if maybe_static {
3926                    let mut lifetime_refs = lifetime_refs.clone().into_iter();
3927                    let owned = if let Some(lt) = lifetime_refs.next()
3928                        && lifetime_refs.next().is_none()
3929                        && lt.kind != MissingLifetimeKind::Ampersand
3930                    {
3931                        ", or if you will only have owned values"
3932                    } else {
3933                        ""
3934                    };
3935                    ::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!(
3936                        ", but this is uncommon unless you're returning a borrowed value from a \
3937                         `const` or a `static`{owned}",
3938                    )
3939                } else {
3940                    String::new()
3941                };
3942                err.multipart_suggestion(
3943                    ::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}"),
3944                    spans_suggs,
3945                    Applicability::MaybeIncorrect,
3946                );
3947                if maybe_static {
3948                    // FIXME: what follows are general suggestions, but we'd want to perform some
3949                    // minimal flow analysis to provide more accurate suggestions. For example, if
3950                    // we identified that the return expression references only one argument, we
3951                    // would suggest borrowing only that argument, and we'd skip the prior
3952                    // "use `'static`" suggestion entirely.
3953                    let mut lifetime_refs = lifetime_refs.clone().into_iter();
3954                    if let Some(lt) = lifetime_refs.next()
3955                        && lifetime_refs.next().is_none()
3956                        && (lt.kind == MissingLifetimeKind::Ampersand
3957                            || lt.kind == MissingLifetimeKind::Underscore)
3958                    {
3959                        let pre = if let Some((kind, _span)) = self.diag_metadata.current_function
3960                            && let FnKind::Fn(_, _, ast::Fn { sig, .. }) = kind
3961                            && !sig.decl.inputs.is_empty()
3962                            && let sugg = sig
3963                                .decl
3964                                .inputs
3965                                .iter()
3966                                .filter_map(|param| {
3967                                    if param.ty.span.contains(lt.span) {
3968                                        // We don't want to suggest `fn elision(_: &fn() -> &i32)`
3969                                        // when we have `fn elision(_: fn() -> &i32)`
3970                                        None
3971                                    } else if let TyKind::CVarArgs = param.ty.kind {
3972                                        // Don't suggest `&...` for ffi fn with varargs
3973                                        None
3974                                    } else if let TyKind::ImplTrait(..) = &param.ty.kind {
3975                                        // We handle these in the next `else if` branch.
3976                                        None
3977                                    } else {
3978                                        Some((param.ty.span.shrink_to_lo(), "&".to_string()))
3979                                    }
3980                                })
3981                                .collect::<Vec<_>>()
3982                            && !sugg.is_empty()
3983                        {
3984                            let (the, s) = if sig.decl.inputs.len() == 1 {
3985                                ("the", "")
3986                            } else {
3987                                ("one of the", "s")
3988                            };
3989                            let dotdotdot =
3990                                if lt.kind == MissingLifetimeKind::Ampersand { "..." } else { "" };
3991                            err.multipart_suggestion(
3992                                ::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!(
3993                                    "instead, you are more likely to want to change {the} \
3994                                     argument{s} to be borrowed{dotdotdot}",
3995                                ),
3996                                sugg,
3997                                Applicability::MaybeIncorrect,
3998                            );
3999                            "...or alternatively, you might want"
4000                        } else if (lt.kind == MissingLifetimeKind::Ampersand
4001                            || lt.kind == MissingLifetimeKind::Underscore)
4002                            && let Some((kind, _span)) = self.diag_metadata.current_function
4003                            && let FnKind::Fn(_, _, ast::Fn { sig, .. }) = kind
4004                            && let ast::FnRetTy::Ty(ret_ty) = &sig.decl.output
4005                            && !sig.decl.inputs.is_empty()
4006                            && let arg_refs = sig
4007                                .decl
4008                                .inputs
4009                                .iter()
4010                                .filter_map(|param| match &param.ty.kind {
4011                                    TyKind::ImplTrait(_, bounds) => Some(bounds),
4012                                    _ => None,
4013                                })
4014                                .flat_map(|bounds| bounds.into_iter())
4015                                .collect::<Vec<_>>()
4016                            && !arg_refs.is_empty()
4017                        {
4018                            // We have a situation like
4019                            // fn g(mut x: impl Iterator<Item = &()>) -> Option<&()>
4020                            // So we look at every ref in the trait bound. If there's any, we
4021                            // suggest
4022                            // fn g<'a>(mut x: impl Iterator<Item = &'a ()>) -> Option<&'a ()>
4023                            let mut lt_finder =
4024                                LifetimeFinder { lifetime: lt.span, found: None, seen: ::alloc::vec::Vec::new()vec![] };
4025                            for bound in arg_refs {
4026                                if let ast::GenericBound::Trait(trait_ref) = bound {
4027                                    lt_finder.visit_trait_ref(&trait_ref.trait_ref);
4028                                }
4029                            }
4030                            lt_finder.visit_ty(ret_ty);
4031                            let spans_suggs: Vec<_> = lt_finder
4032                                .seen
4033                                .iter()
4034                                .filter_map(|ty| match &ty.kind {
4035                                    TyKind::Ref(_, mut_ty) => {
4036                                        let span = ty.span.with_hi(mut_ty.ty.span.lo());
4037                                        Some((span, "&'a ".to_string()))
4038                                    }
4039                                    _ => None,
4040                                })
4041                                .collect();
4042                            self.suggest_introducing_lifetime(
4043                                err,
4044                                None,
4045                                |err, higher_ranked, span, message, intro_sugg, _| {
4046                                    err.multipart_suggestion(
4047                                        message,
4048                                        std::iter::once((span, intro_sugg))
4049                                            .chain(spans_suggs.clone())
4050                                            .collect(),
4051                                        Applicability::MaybeIncorrect,
4052                                    );
4053                                    higher_ranked
4054                                },
4055                            );
4056                            "alternatively, you might want"
4057                        } else {
4058                            "instead, you are more likely to want"
4059                        };
4060                        let mut owned_sugg = lt.kind == MissingLifetimeKind::Ampersand;
4061                        let mut sugg_is_str_to_string = false;
4062                        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())];
4063                        if let Some((kind, _span)) = self.diag_metadata.current_function
4064                            && let FnKind::Fn(_, _, ast::Fn { sig, .. }) = kind
4065                        {
4066                            let mut lt_finder =
4067                                LifetimeFinder { lifetime: lt.span, found: None, seen: ::alloc::vec::Vec::new()vec![] };
4068                            for param in &sig.decl.inputs {
4069                                lt_finder.visit_ty(&param.ty);
4070                            }
4071                            if let ast::FnRetTy::Ty(ret_ty) = &sig.decl.output {
4072                                lt_finder.visit_ty(ret_ty);
4073                                let mut ret_lt_finder =
4074                                    LifetimeFinder { lifetime: lt.span, found: None, seen: ::alloc::vec::Vec::new()vec![] };
4075                                ret_lt_finder.visit_ty(ret_ty);
4076                                if let [Ty { span, kind: TyKind::Ref(_, mut_ty), .. }] =
4077                                    &ret_lt_finder.seen[..]
4078                                {
4079                                    // We might have a situation like
4080                                    // fn g(mut x: impl Iterator<Item = &'_ ()>) -> Option<&'_ ()>
4081                                    // but `lt.span` only points at `'_`, so to suggest `-> Option<()>`
4082                                    // we need to find a more accurate span to end up with
4083                                    // fn g<'a>(mut x: impl Iterator<Item = &'_ ()>) -> Option<()>
4084                                    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())];
4085                                    owned_sugg = true;
4086                                }
4087                            }
4088                            if let Some(ty) = lt_finder.found {
4089                                if let TyKind::Path(None, path) = &ty.kind {
4090                                    // Check if the path being borrowed is likely to be owned.
4091                                    let path: Vec<_> = Segment::from_path(path);
4092                                    match self.resolve_path(
4093                                        &path,
4094                                        Some(TypeNS),
4095                                        None,
4096                                        PathSource::Type,
4097                                    ) {
4098                                        PathResult::Module(ModuleOrUniformRoot::Module(module)) => {
4099                                            match module.res() {
4100                                                Some(Res::PrimTy(PrimTy::Str)) => {
4101                                                    // Don't suggest `-> str`, suggest `-> String`.
4102                                                    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![(
4103                                                        lt.span.with_hi(ty.span.hi()),
4104                                                        "String".to_string(),
4105                                                    )];
4106                                                    sugg_is_str_to_string = true;
4107                                                }
4108                                                Some(Res::PrimTy(..)) => {}
4109                                                Some(Res::Def(
4110                                                    DefKind::Struct
4111                                                    | DefKind::Union
4112                                                    | DefKind::Enum
4113                                                    | DefKind::ForeignTy
4114                                                    | DefKind::AssocTy
4115                                                    | DefKind::OpaqueTy
4116                                                    | DefKind::TyParam,
4117                                                    _,
4118                                                )) => {}
4119                                                _ => {
4120                                                    // Do not suggest in all other cases.
4121                                                    owned_sugg = false;
4122                                                }
4123                                            }
4124                                        }
4125                                        PathResult::NonModule(res) => {
4126                                            match res.base_res() {
4127                                                Res::PrimTy(PrimTy::Str) => {
4128                                                    // Don't suggest `-> str`, suggest `-> String`.
4129                                                    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![(
4130                                                        lt.span.with_hi(ty.span.hi()),
4131                                                        "String".to_string(),
4132                                                    )];
4133                                                    sugg_is_str_to_string = true;
4134                                                }
4135                                                Res::PrimTy(..) => {}
4136                                                Res::Def(
4137                                                    DefKind::Struct
4138                                                    | DefKind::Union
4139                                                    | DefKind::Enum
4140                                                    | DefKind::ForeignTy
4141                                                    | DefKind::AssocTy
4142                                                    | DefKind::OpaqueTy
4143                                                    | DefKind::TyParam,
4144                                                    _,
4145                                                ) => {}
4146                                                _ => {
4147                                                    // Do not suggest in all other cases.
4148                                                    owned_sugg = false;
4149                                                }
4150                                            }
4151                                        }
4152                                        _ => {
4153                                            // Do not suggest in all other cases.
4154                                            owned_sugg = false;
4155                                        }
4156                                    }
4157                                }
4158                                if let TyKind::Slice(inner_ty) = &ty.kind {
4159                                    // Don't suggest `-> [T]`, suggest `-> Vec<T>`.
4160                                    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![
4161                                        (lt.span.with_hi(inner_ty.span.lo()), "Vec<".to_string()),
4162                                        (ty.span.with_lo(inner_ty.span.hi()), ">".to_string()),
4163                                    ];
4164                                }
4165                            }
4166                        }
4167                        if owned_sugg {
4168                            if let Some(span) =
4169                                self.find_ref_prefix_span_for_owned_suggestion(lt.span)
4170                                && !sugg_is_str_to_string
4171                            {
4172                                sugg = ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
        [(span, String::new())]))vec![(span, String::new())];
4173                            }
4174                            err.multipart_suggestion(
4175                                ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("{0} to return an owned value",
                pre))
    })format!("{pre} to return an owned value"),
4176                                sugg,
4177                                Applicability::MaybeIncorrect,
4178                            );
4179                        }
4180                    }
4181                }
4182            }
4183            _ => {
4184                let lifetime_spans: Vec<_> =
4185                    in_scope_lifetimes.iter().map(|(ident, _)| ident.span).collect();
4186                err.span_note(lifetime_spans, "these named lifetimes are available to use");
4187
4188                if spans_suggs.len() > 0 {
4189                    // This happens when we have `Foo<T>` where we point at the space before `T`,
4190                    // but this can be confusing so we give a suggestion with placeholders.
4191                    err.multipart_suggestion(
4192                        "consider using one of the available lifetimes here",
4193                        spans_suggs,
4194                        Applicability::HasPlaceholders,
4195                    );
4196                }
4197            }
4198        }
4199    }
4200
4201    fn find_ref_prefix_span_for_owned_suggestion(&self, lifetime: Span) -> Option<Span> {
4202        let mut finder = RefPrefixSpanFinder { lifetime, span: None };
4203        if let Some(item) = self.diag_metadata.current_item {
4204            finder.visit_item(item);
4205        } else if let Some((kind, _span)) = self.diag_metadata.current_function
4206            && let FnKind::Fn(_, _, ast::Fn { sig, .. }) = kind
4207        {
4208            for param in &sig.decl.inputs {
4209                finder.visit_ty(&param.ty);
4210            }
4211            if let ast::FnRetTy::Ty(ret_ty) = &sig.decl.output {
4212                finder.visit_ty(ret_ty);
4213            }
4214        }
4215        finder.span
4216    }
4217}
4218
4219fn mk_where_bound_predicate(
4220    path: &Path,
4221    poly_trait_ref: &ast::PolyTraitRef,
4222    ty: &Ty,
4223) -> Option<ast::WhereBoundPredicate> {
4224    let modified_segments = {
4225        let mut segments = path.segments.clone();
4226        let [preceding @ .., second_last, last] = segments.as_mut_slice() else {
4227            return None;
4228        };
4229        let mut segments = ThinVec::from(preceding);
4230
4231        let added_constraint = ast::AngleBracketedArg::Constraint(ast::AssocItemConstraint {
4232            id: DUMMY_NODE_ID,
4233            ident: last.ident,
4234            gen_args: None,
4235            kind: ast::AssocItemConstraintKind::Equality {
4236                term: ast::Term::Ty(Box::new(ast::Ty {
4237                    kind: ast::TyKind::Path(None, poly_trait_ref.trait_ref.path.clone()),
4238                    id: DUMMY_NODE_ID,
4239                    span: DUMMY_SP,
4240                    tokens: None,
4241                })),
4242            },
4243            span: DUMMY_SP,
4244        });
4245
4246        match second_last.args.as_deref_mut() {
4247            Some(ast::GenericArgs::AngleBracketed(ast::AngleBracketedArgs { args, .. })) => {
4248                args.push(added_constraint);
4249            }
4250            Some(_) => return None,
4251            None => {
4252                second_last.args =
4253                    Some(Box::new(ast::GenericArgs::AngleBracketed(ast::AngleBracketedArgs {
4254                        args: ThinVec::from([added_constraint]),
4255                        span: DUMMY_SP,
4256                    })));
4257            }
4258        }
4259
4260        segments.push(second_last.clone());
4261        segments
4262    };
4263
4264    let new_where_bound_predicate = ast::WhereBoundPredicate {
4265        bound_generic_params: ThinVec::new(),
4266        bounded_ty: Box::new(ty.clone()),
4267        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 {
4268            bound_generic_params: ThinVec::new(),
4269            modifiers: ast::TraitBoundModifiers::NONE,
4270            trait_ref: ast::TraitRef {
4271                path: ast::Path { segments: modified_segments, span: DUMMY_SP, tokens: None },
4272                ref_id: DUMMY_NODE_ID,
4273            },
4274            span: DUMMY_SP,
4275            parens: ast::Parens::No,
4276        })],
4277    };
4278
4279    Some(new_where_bound_predicate)
4280}
4281
4282/// Report lifetime/lifetime shadowing as an error.
4283pub(super) fn signal_lifetime_shadowing(
4284    sess: &Session,
4285    orig: Ident,
4286    shadower: Ident,
4287) -> ErrorGuaranteed {
4288    {
    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!(
4289        sess.dcx(),
4290        shadower.span,
4291        E0496,
4292        "lifetime name `{}` shadows a lifetime name that is already in scope",
4293        orig.name,
4294    )
4295    .with_span_label(orig.span, "first declared here")
4296    .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))
4297    .emit()
4298}
4299
4300struct LifetimeFinder<'ast> {
4301    lifetime: Span,
4302    found: Option<&'ast Ty>,
4303    seen: Vec<&'ast Ty>,
4304}
4305
4306impl<'ast> Visitor<'ast> for LifetimeFinder<'ast> {
4307    fn visit_ty(&mut self, t: &'ast Ty) {
4308        if let TyKind::Ref(_, mut_ty) | TyKind::PinnedRef(_, mut_ty) = &t.kind {
4309            self.seen.push(t);
4310            if t.span.lo() == self.lifetime.lo() {
4311                self.found = Some(&mut_ty.ty);
4312            }
4313        }
4314        walk_ty(self, t)
4315    }
4316}
4317
4318struct RefPrefixSpanFinder {
4319    lifetime: Span,
4320    span: Option<Span>,
4321}
4322
4323impl<'ast> Visitor<'ast> for RefPrefixSpanFinder {
4324    fn visit_ty(&mut self, t: &'ast Ty) {
4325        if self.span.is_some() {
4326            return;
4327        }
4328        if let TyKind::Ref(_, mut_ty) | TyKind::PinnedRef(_, mut_ty) = &t.kind
4329            && t.span.lo() == self.lifetime.lo()
4330        {
4331            self.span = Some(t.span.with_hi(mut_ty.ty.span.lo()));
4332            return;
4333        }
4334        walk_ty(self, t);
4335    }
4336}
4337
4338/// Shadowing involving a label is only a warning for historical reasons.
4339//FIXME: make this a proper lint.
4340pub(super) fn signal_label_shadowing(sess: &Session, orig: Span, shadower: Ident) {
4341    let name = shadower.name;
4342    let shadower = shadower.span;
4343    sess.dcx()
4344        .struct_span_warn(
4345            shadower,
4346            ::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"),
4347        )
4348        .with_span_label(orig, "first declared here")
4349        .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"))
4350        .emit();
4351}