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