Skip to main content

rustc_resolve/late/
diagnostics.rs

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