Skip to main content

rustc_resolve/late/
diagnostics.rs

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