rustc_resolve/late/
diagnostics.rs

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