Skip to main content

rustc_resolve/late/
diagnostics.rs

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