rustc_resolve/late/
diagnostics.rs

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