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, ParentScope, PathResult, PathSource, Resolver,
42    ScopeSet, Segment, 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            for (ident, &res) in &rib.bindings {
854                if let Res::Local(_) = res
855                    && path.len() == 1
856                    && ident.span.eq_ctxt(path[0].ident.span)
857                    && ident.name == path[0].ident.name
858                {
859                    err.span_help(
860                        ident.span,
861                        format!("the binding `{path_str}` is available in a different scope in the same function"),
862                    );
863                    return (true, suggested_candidates, candidates);
864                }
865            }
866        }
867
868        if candidates.is_empty() {
869            candidates = self.smart_resolve_partial_mod_path_errors(path, following_seg);
870        }
871
872        (false, suggested_candidates, candidates)
873    }
874
875    fn lookup_doc_alias_name(&mut self, path: &[Segment], ns: Namespace) -> Option<(DefId, Ident)> {
876        let find_doc_alias_name = |r: &mut Resolver<'ra, '_>, m: Module<'ra>, item_name: Symbol| {
877            for resolution in r.resolutions(m).borrow().values() {
878                let Some(did) = resolution
879                    .borrow()
880                    .best_binding()
881                    .and_then(|binding| binding.res().opt_def_id())
882                else {
883                    continue;
884                };
885                if did.is_local() {
886                    // We don't record the doc alias name in the local crate
887                    // because the people who write doc alias are usually not
888                    // confused by them.
889                    continue;
890                }
891                if is_doc_alias_attrs_contain_symbol(r.tcx.get_attrs(did, sym::doc), item_name) {
892                    return Some(did);
893                }
894            }
895            None
896        };
897
898        if path.len() == 1 {
899            for rib in self.ribs[ns].iter().rev() {
900                let item = path[0].ident;
901                if let RibKind::Module(module) | RibKind::Block(Some(module)) = rib.kind
902                    && let Some(did) = find_doc_alias_name(self.r, module, item.name)
903                {
904                    return Some((did, item));
905                }
906            }
907        } else {
908            // Finds to the last resolved module item in the path
909            // and searches doc aliases within that module.
910            //
911            // Example: For the path `a::b::last_resolved::not_exist::c::d`,
912            // we will try to find any item has doc aliases named `not_exist`
913            // in `last_resolved` module.
914            //
915            // - Use `skip(1)` because the final segment must remain unresolved.
916            for (idx, seg) in path.iter().enumerate().rev().skip(1) {
917                let Some(id) = seg.id else {
918                    continue;
919                };
920                let Some(res) = self.r.partial_res_map.get(&id) else {
921                    continue;
922                };
923                if let Res::Def(DefKind::Mod, module) = res.expect_full_res()
924                    && let module = self.r.expect_module(module)
925                    && let item = path[idx + 1].ident
926                    && let Some(did) = find_doc_alias_name(self.r, module, item.name)
927                {
928                    return Some((did, item));
929                }
930                break;
931            }
932        }
933        None
934    }
935
936    fn suggest_trait_and_bounds(
937        &self,
938        err: &mut Diag<'_>,
939        source: PathSource<'_, '_, '_>,
940        res: Option<Res>,
941        span: Span,
942        base_error: &BaseError,
943    ) -> bool {
944        let is_macro =
945            base_error.span.from_expansion() && base_error.span.desugaring_kind().is_none();
946        let mut fallback = false;
947
948        if let (
949            PathSource::Trait(AliasPossibility::Maybe),
950            Some(Res::Def(DefKind::Struct | DefKind::Enum | DefKind::Union, _)),
951            false,
952        ) = (source, res, is_macro)
953            && let Some(bounds @ [first_bound, .., last_bound]) =
954                self.diag_metadata.current_trait_object
955        {
956            fallback = true;
957            let spans: Vec<Span> = bounds
958                .iter()
959                .map(|bound| bound.span())
960                .filter(|&sp| sp != base_error.span)
961                .collect();
962
963            let start_span = first_bound.span();
964            // `end_span` is the end of the poly trait ref (Foo + 'baz + Bar><)
965            let end_span = last_bound.span();
966            // `last_bound_span` is the last bound of the poly trait ref (Foo + >'baz< + Bar)
967            let last_bound_span = spans.last().cloned().unwrap();
968            let mut multi_span: MultiSpan = spans.clone().into();
969            for sp in spans {
970                let msg = if sp == last_bound_span {
971                    format!(
972                        "...because of {these} bound{s}",
973                        these = pluralize!("this", bounds.len() - 1),
974                        s = pluralize!(bounds.len() - 1),
975                    )
976                } else {
977                    String::new()
978                };
979                multi_span.push_span_label(sp, msg);
980            }
981            multi_span.push_span_label(base_error.span, "expected this type to be a trait...");
982            err.span_help(
983                multi_span,
984                "`+` is used to constrain a \"trait object\" type with lifetimes or \
985                        auto-traits; structs and enums can't be bound in that way",
986            );
987            if bounds.iter().all(|bound| match bound {
988                ast::GenericBound::Outlives(_) | ast::GenericBound::Use(..) => true,
989                ast::GenericBound::Trait(tr) => tr.span == base_error.span,
990            }) {
991                let mut sugg = vec![];
992                if base_error.span != start_span {
993                    sugg.push((start_span.until(base_error.span), String::new()));
994                }
995                if base_error.span != end_span {
996                    sugg.push((base_error.span.shrink_to_hi().to(end_span), String::new()));
997                }
998
999                err.multipart_suggestion(
1000                    "if you meant to use a type and not a trait here, remove the bounds",
1001                    sugg,
1002                    Applicability::MaybeIncorrect,
1003                );
1004            }
1005        }
1006
1007        fallback |= self.restrict_assoc_type_in_where_clause(span, err);
1008        fallback
1009    }
1010
1011    fn suggest_typo(
1012        &mut self,
1013        err: &mut Diag<'_>,
1014        source: PathSource<'_, 'ast, 'ra>,
1015        path: &[Segment],
1016        following_seg: Option<&Segment>,
1017        span: Span,
1018        base_error: &BaseError,
1019        suggested_candidates: FxHashSet<String>,
1020    ) -> bool {
1021        let is_expected = &|res| source.is_expected(res);
1022        let ident_span = path.last().map_or(span, |ident| ident.ident.span);
1023        let typo_sugg =
1024            self.lookup_typo_candidate(path, following_seg, source.namespace(), is_expected);
1025        let mut fallback = false;
1026        let typo_sugg = typo_sugg
1027            .to_opt_suggestion()
1028            .filter(|sugg| !suggested_candidates.contains(sugg.candidate.as_str()));
1029        if !self.r.add_typo_suggestion(err, typo_sugg, ident_span) {
1030            fallback = true;
1031            match self.diag_metadata.current_let_binding {
1032                Some((pat_sp, Some(ty_sp), None))
1033                    if ty_sp.contains(base_error.span) && base_error.could_be_expr =>
1034                {
1035                    err.span_suggestion_short(
1036                        pat_sp.between(ty_sp),
1037                        "use `=` if you meant to assign",
1038                        " = ",
1039                        Applicability::MaybeIncorrect,
1040                    );
1041                }
1042                _ => {}
1043            }
1044
1045            // If the trait has a single item (which wasn't matched by the algorithm), suggest it
1046            let suggestion = self.get_single_associated_item(path, &source, is_expected);
1047            self.r.add_typo_suggestion(err, suggestion, ident_span);
1048        }
1049
1050        if self.let_binding_suggestion(err, ident_span) {
1051            fallback = false;
1052        }
1053
1054        fallback
1055    }
1056
1057    fn suggest_shadowed(
1058        &mut self,
1059        err: &mut Diag<'_>,
1060        source: PathSource<'_, '_, '_>,
1061        path: &[Segment],
1062        following_seg: Option<&Segment>,
1063        span: Span,
1064    ) -> bool {
1065        let is_expected = &|res| source.is_expected(res);
1066        let typo_sugg =
1067            self.lookup_typo_candidate(path, following_seg, source.namespace(), is_expected);
1068        let is_in_same_file = &|sp1, sp2| {
1069            let source_map = self.r.tcx.sess.source_map();
1070            let file1 = source_map.span_to_filename(sp1);
1071            let file2 = source_map.span_to_filename(sp2);
1072            file1 == file2
1073        };
1074        // print 'you might have meant' if the candidate is (1) is a shadowed name with
1075        // accessible definition and (2) either defined in the same crate as the typo
1076        // (could be in a different file) or introduced in the same file as the typo
1077        // (could belong to a different crate)
1078        if let TypoCandidate::Shadowed(res, Some(sugg_span)) = typo_sugg
1079            && res.opt_def_id().is_some_and(|id| id.is_local() || is_in_same_file(span, sugg_span))
1080        {
1081            err.span_label(
1082                sugg_span,
1083                format!("you might have meant to refer to this {}", res.descr()),
1084            );
1085            return true;
1086        }
1087        false
1088    }
1089
1090    fn err_code_special_cases(
1091        &mut self,
1092        err: &mut Diag<'_>,
1093        source: PathSource<'_, '_, '_>,
1094        path: &[Segment],
1095        span: Span,
1096    ) {
1097        if let Some(err_code) = err.code {
1098            if err_code == E0425 {
1099                for label_rib in &self.label_ribs {
1100                    for (label_ident, node_id) in &label_rib.bindings {
1101                        let ident = path.last().unwrap().ident;
1102                        if format!("'{ident}") == label_ident.to_string() {
1103                            err.span_label(label_ident.span, "a label with a similar name exists");
1104                            if let PathSource::Expr(Some(Expr {
1105                                kind: ExprKind::Break(None, Some(_)),
1106                                ..
1107                            })) = source
1108                            {
1109                                err.span_suggestion(
1110                                    span,
1111                                    "use the similarly named label",
1112                                    label_ident.name,
1113                                    Applicability::MaybeIncorrect,
1114                                );
1115                                // Do not lint against unused label when we suggest them.
1116                                self.diag_metadata.unused_labels.swap_remove(node_id);
1117                            }
1118                        }
1119                    }
1120                }
1121            } else if err_code == E0412 {
1122                if let Some(correct) = Self::likely_rust_type(path) {
1123                    err.span_suggestion(
1124                        span,
1125                        "perhaps you intended to use this type",
1126                        correct,
1127                        Applicability::MaybeIncorrect,
1128                    );
1129                }
1130            }
1131        }
1132    }
1133
1134    /// Emit special messages for unresolved `Self` and `self`.
1135    fn suggest_self_ty(
1136        &self,
1137        err: &mut Diag<'_>,
1138        source: PathSource<'_, '_, '_>,
1139        path: &[Segment],
1140        span: Span,
1141    ) -> bool {
1142        if !is_self_type(path, source.namespace()) {
1143            return false;
1144        }
1145        err.code(E0411);
1146        err.span_label(span, "`Self` is only available in impls, traits, and type definitions");
1147        if let Some(item) = self.diag_metadata.current_item
1148            && let Some(ident) = item.kind.ident()
1149        {
1150            err.span_label(
1151                ident.span,
1152                format!("`Self` not allowed in {} {}", item.kind.article(), item.kind.descr()),
1153            );
1154        }
1155        true
1156    }
1157
1158    fn suggest_self_value(
1159        &mut self,
1160        err: &mut Diag<'_>,
1161        source: PathSource<'_, '_, '_>,
1162        path: &[Segment],
1163        span: Span,
1164    ) -> bool {
1165        if !is_self_value(path, source.namespace()) {
1166            return false;
1167        }
1168
1169        debug!("smart_resolve_path_fragment: E0424, source={:?}", source);
1170        err.code(E0424);
1171        err.span_label(
1172            span,
1173            match source {
1174                PathSource::Pat => {
1175                    "`self` value is a keyword and may not be bound to variables or shadowed"
1176                }
1177                _ => "`self` value is a keyword only available in methods with a `self` parameter",
1178            },
1179        );
1180
1181        // using `let self` is wrong even if we're not in an associated method or if we're in a macro expansion.
1182        // So, we should return early if we're in a pattern, see issue #143134.
1183        if matches!(source, PathSource::Pat) {
1184            return true;
1185        }
1186
1187        let is_assoc_fn = self.self_type_is_available();
1188        let self_from_macro = "a `self` parameter, but a macro invocation can only \
1189                               access identifiers it receives from parameters";
1190        if let Some((fn_kind, fn_span)) = &self.diag_metadata.current_function {
1191            // The current function has a `self` parameter, but we were unable to resolve
1192            // a reference to `self`. This can only happen if the `self` identifier we
1193            // are resolving came from a different hygiene context or a variable binding.
1194            // But variable binding error is returned early above.
1195            if fn_kind.decl().inputs.get(0).is_some_and(|p| p.is_self()) {
1196                err.span_label(*fn_span, format!("this function has {self_from_macro}"));
1197            } else {
1198                let doesnt = if is_assoc_fn {
1199                    let (span, sugg) = fn_kind
1200                        .decl()
1201                        .inputs
1202                        .get(0)
1203                        .map(|p| (p.span.shrink_to_lo(), "&self, "))
1204                        .unwrap_or_else(|| {
1205                            // Try to look for the "(" after the function name, if possible.
1206                            // This avoids placing the suggestion into the visibility specifier.
1207                            let span = fn_kind
1208                                .ident()
1209                                .map_or(*fn_span, |ident| fn_span.with_lo(ident.span.hi()));
1210                            (
1211                                self.r
1212                                    .tcx
1213                                    .sess
1214                                    .source_map()
1215                                    .span_through_char(span, '(')
1216                                    .shrink_to_hi(),
1217                                "&self",
1218                            )
1219                        });
1220                    err.span_suggestion_verbose(
1221                        span,
1222                        "add a `self` receiver parameter to make the associated `fn` a method",
1223                        sugg,
1224                        Applicability::MaybeIncorrect,
1225                    );
1226                    "doesn't"
1227                } else {
1228                    "can't"
1229                };
1230                if let Some(ident) = fn_kind.ident() {
1231                    err.span_label(
1232                        ident.span,
1233                        format!("this function {doesnt} have a `self` parameter"),
1234                    );
1235                }
1236            }
1237        } else if let Some(item) = self.diag_metadata.current_item {
1238            if matches!(item.kind, ItemKind::Delegation(..)) {
1239                err.span_label(item.span, format!("delegation supports {self_from_macro}"));
1240            } else {
1241                let span = if let Some(ident) = item.kind.ident() { ident.span } else { item.span };
1242                err.span_label(
1243                    span,
1244                    format!("`self` not allowed in {} {}", item.kind.article(), item.kind.descr()),
1245                );
1246            }
1247        }
1248        true
1249    }
1250
1251    fn detect_missing_binding_available_from_pattern(
1252        &self,
1253        err: &mut Diag<'_>,
1254        path: &[Segment],
1255        following_seg: Option<&Segment>,
1256    ) {
1257        let [segment] = path else { return };
1258        let None = following_seg else { return };
1259        for rib in self.ribs[ValueNS].iter().rev() {
1260            let patterns_with_skipped_bindings = self.r.tcx.with_stable_hashing_context(|hcx| {
1261                rib.patterns_with_skipped_bindings.to_sorted(&hcx, true)
1262            });
1263            for (def_id, spans) in patterns_with_skipped_bindings {
1264                if let DefKind::Struct | DefKind::Variant = self.r.tcx.def_kind(*def_id)
1265                    && let Some(fields) = self.r.field_idents(*def_id)
1266                {
1267                    for field in fields {
1268                        if field.name == segment.ident.name {
1269                            if spans.iter().all(|(_, had_error)| had_error.is_err()) {
1270                                // This resolution error will likely be fixed by fixing a
1271                                // syntax error in a pattern, so it is irrelevant to the user.
1272                                let multispan: MultiSpan =
1273                                    spans.iter().map(|(s, _)| *s).collect::<Vec<_>>().into();
1274                                err.span_note(
1275                                    multispan,
1276                                    "this pattern had a recovered parse error which likely lost \
1277                                     the expected fields",
1278                                );
1279                                err.downgrade_to_delayed_bug();
1280                            }
1281                            let ty = self.r.tcx.item_name(*def_id);
1282                            for (span, _) in spans {
1283                                err.span_label(
1284                                    *span,
1285                                    format!(
1286                                        "this pattern doesn't include `{field}`, which is \
1287                                         available in `{ty}`",
1288                                    ),
1289                                );
1290                            }
1291                        }
1292                    }
1293                }
1294            }
1295        }
1296    }
1297
1298    fn suggest_at_operator_in_slice_pat_with_range(&self, err: &mut Diag<'_>, path: &[Segment]) {
1299        let Some(pat) = self.diag_metadata.current_pat else { return };
1300        let (bound, side, range) = match &pat.kind {
1301            ast::PatKind::Range(Some(bound), None, range) => (bound, Side::Start, range),
1302            ast::PatKind::Range(None, Some(bound), range) => (bound, Side::End, range),
1303            _ => return,
1304        };
1305        if let ExprKind::Path(None, range_path) = &bound.kind
1306            && let [segment] = &range_path.segments[..]
1307            && let [s] = path
1308            && segment.ident == s.ident
1309            && segment.ident.span.eq_ctxt(range.span)
1310        {
1311            // We've encountered `[first, rest..]` (#88404) or `[first, ..rest]` (#120591)
1312            // where the user might have meant `[first, rest @ ..]`.
1313            let (span, snippet) = match side {
1314                Side::Start => (segment.ident.span.between(range.span), " @ ".into()),
1315                Side::End => (range.span.to(segment.ident.span), format!("{} @ ..", segment.ident)),
1316            };
1317            err.subdiagnostic(errors::UnexpectedResUseAtOpInSlicePatWithRangeSugg {
1318                span,
1319                ident: segment.ident,
1320                snippet,
1321            });
1322        }
1323
1324        enum Side {
1325            Start,
1326            End,
1327        }
1328    }
1329
1330    fn suggest_swapping_misplaced_self_ty_and_trait(
1331        &mut self,
1332        err: &mut Diag<'_>,
1333        source: PathSource<'_, 'ast, 'ra>,
1334        res: Option<Res>,
1335        span: Span,
1336    ) {
1337        if let Some((trait_ref, self_ty)) =
1338            self.diag_metadata.currently_processing_impl_trait.clone()
1339            && let TyKind::Path(_, self_ty_path) = &self_ty.kind
1340            && let PathResult::Module(ModuleOrUniformRoot::Module(module)) =
1341                self.resolve_path(&Segment::from_path(self_ty_path), Some(TypeNS), None, source)
1342            && let ModuleKind::Def(DefKind::Trait, ..) = module.kind
1343            && trait_ref.path.span == span
1344            && let PathSource::Trait(_) = source
1345            && let Some(Res::Def(DefKind::Struct | DefKind::Enum | DefKind::Union, _)) = res
1346            && let Ok(self_ty_str) = self.r.tcx.sess.source_map().span_to_snippet(self_ty.span)
1347            && let Ok(trait_ref_str) =
1348                self.r.tcx.sess.source_map().span_to_snippet(trait_ref.path.span)
1349        {
1350            err.multipart_suggestion(
1351                    "`impl` items mention the trait being implemented first and the type it is being implemented for second",
1352                    vec![(trait_ref.path.span, self_ty_str), (self_ty.span, trait_ref_str)],
1353                    Applicability::MaybeIncorrect,
1354                );
1355        }
1356    }
1357
1358    fn explain_functions_in_pattern(
1359        &self,
1360        err: &mut Diag<'_>,
1361        res: Option<Res>,
1362        source: PathSource<'_, '_, '_>,
1363    ) {
1364        let PathSource::TupleStruct(_, _) = source else { return };
1365        let Some(Res::Def(DefKind::Fn, _)) = res else { return };
1366        err.primary_message("expected a pattern, found a function call");
1367        err.note("function calls are not allowed in patterns: <https://doc.rust-lang.org/book/ch19-00-patterns.html>");
1368    }
1369
1370    fn suggest_changing_type_to_const_param(
1371        &self,
1372        err: &mut Diag<'_>,
1373        res: Option<Res>,
1374        source: PathSource<'_, '_, '_>,
1375        span: Span,
1376    ) {
1377        let PathSource::Trait(_) = source else { return };
1378
1379        // We don't include `DefKind::Str` and `DefKind::AssocTy` as they can't be reached here anyway.
1380        let applicability = match res {
1381            Some(Res::PrimTy(PrimTy::Int(_) | PrimTy::Uint(_) | PrimTy::Bool | PrimTy::Char)) => {
1382                Applicability::MachineApplicable
1383            }
1384            // FIXME(const_generics): Add `DefKind::TyParam` and `SelfTyParam` once we support generic
1385            // const generics. Of course, `Struct` and `Enum` may contain ty params, too, but the
1386            // benefits of including them here outweighs the small number of false positives.
1387            Some(Res::Def(DefKind::Struct | DefKind::Enum, _))
1388                if self.r.tcx.features().adt_const_params() =>
1389            {
1390                Applicability::MaybeIncorrect
1391            }
1392            _ => return,
1393        };
1394
1395        let Some(item) = self.diag_metadata.current_item else { return };
1396        let Some(generics) = item.kind.generics() else { return };
1397
1398        let param = generics.params.iter().find_map(|param| {
1399            // Only consider type params with exactly one trait bound.
1400            if let [bound] = &*param.bounds
1401                && let ast::GenericBound::Trait(tref) = bound
1402                && tref.modifiers == ast::TraitBoundModifiers::NONE
1403                && tref.span == span
1404                && param.ident.span.eq_ctxt(span)
1405            {
1406                Some(param.ident.span)
1407            } else {
1408                None
1409            }
1410        });
1411
1412        if let Some(param) = param {
1413            err.subdiagnostic(errors::UnexpectedResChangeTyToConstParamSugg {
1414                span: param.shrink_to_lo(),
1415                applicability,
1416            });
1417        }
1418    }
1419
1420    fn suggest_pattern_match_with_let(
1421        &self,
1422        err: &mut Diag<'_>,
1423        source: PathSource<'_, '_, '_>,
1424        span: Span,
1425    ) -> bool {
1426        if let PathSource::Expr(_) = source
1427            && let Some(Expr { span: expr_span, kind: ExprKind::Assign(lhs, _, _), .. }) =
1428                self.diag_metadata.in_if_condition
1429        {
1430            // Icky heuristic so we don't suggest:
1431            // `if (i + 2) = 2` => `if let (i + 2) = 2` (approximately pattern)
1432            // `if 2 = i` => `if let 2 = i` (lhs needs to contain error span)
1433            if lhs.is_approximately_pattern() && lhs.span.contains(span) {
1434                err.span_suggestion_verbose(
1435                    expr_span.shrink_to_lo(),
1436                    "you might have meant to use pattern matching",
1437                    "let ",
1438                    Applicability::MaybeIncorrect,
1439                );
1440                return true;
1441            }
1442        }
1443        false
1444    }
1445
1446    fn get_single_associated_item(
1447        &mut self,
1448        path: &[Segment],
1449        source: &PathSource<'_, 'ast, 'ra>,
1450        filter_fn: &impl Fn(Res) -> bool,
1451    ) -> Option<TypoSuggestion> {
1452        if let crate::PathSource::TraitItem(_, _) = source {
1453            let mod_path = &path[..path.len() - 1];
1454            if let PathResult::Module(ModuleOrUniformRoot::Module(module)) =
1455                self.resolve_path(mod_path, None, None, *source)
1456            {
1457                let targets: Vec<_> = self
1458                    .r
1459                    .resolutions(module)
1460                    .borrow()
1461                    .iter()
1462                    .filter_map(|(key, resolution)| {
1463                        resolution
1464                            .borrow()
1465                            .best_binding()
1466                            .map(|binding| binding.res())
1467                            .and_then(|res| if filter_fn(res) { Some((*key, res)) } else { None })
1468                    })
1469                    .collect();
1470                if let [target] = targets.as_slice() {
1471                    return Some(TypoSuggestion::single_item_from_ident(
1472                        target.0.ident.0,
1473                        target.1,
1474                    ));
1475                }
1476            }
1477        }
1478        None
1479    }
1480
1481    /// Given `where <T as Bar>::Baz: String`, suggest `where T: Bar<Baz = String>`.
1482    fn restrict_assoc_type_in_where_clause(&self, span: Span, err: &mut Diag<'_>) -> bool {
1483        // Detect that we are actually in a `where` predicate.
1484        let (bounded_ty, bounds, where_span) = if let Some(ast::WherePredicate {
1485            kind:
1486                ast::WherePredicateKind::BoundPredicate(ast::WhereBoundPredicate {
1487                    bounded_ty,
1488                    bound_generic_params,
1489                    bounds,
1490                }),
1491            span,
1492            ..
1493        }) = self.diag_metadata.current_where_predicate
1494        {
1495            if !bound_generic_params.is_empty() {
1496                return false;
1497            }
1498            (bounded_ty, bounds, span)
1499        } else {
1500            return false;
1501        };
1502
1503        // Confirm that the target is an associated type.
1504        let (ty, _, path) = if let ast::TyKind::Path(Some(qself), path) = &bounded_ty.kind {
1505            // use this to verify that ident is a type param.
1506            let Some(partial_res) = self.r.partial_res_map.get(&bounded_ty.id) else {
1507                return false;
1508            };
1509            if !matches!(
1510                partial_res.full_res(),
1511                Some(hir::def::Res::Def(hir::def::DefKind::AssocTy, _))
1512            ) {
1513                return false;
1514            }
1515            (&qself.ty, qself.position, path)
1516        } else {
1517            return false;
1518        };
1519
1520        let peeled_ty = ty.peel_refs();
1521        if let ast::TyKind::Path(None, type_param_path) = &peeled_ty.kind {
1522            // Confirm that the `SelfTy` is a type parameter.
1523            let Some(partial_res) = self.r.partial_res_map.get(&peeled_ty.id) else {
1524                return false;
1525            };
1526            if !matches!(
1527                partial_res.full_res(),
1528                Some(hir::def::Res::Def(hir::def::DefKind::TyParam, _))
1529            ) {
1530                return false;
1531            }
1532            if let (
1533                [ast::PathSegment { args: None, .. }],
1534                [ast::GenericBound::Trait(poly_trait_ref)],
1535            ) = (&type_param_path.segments[..], &bounds[..])
1536                && poly_trait_ref.modifiers == ast::TraitBoundModifiers::NONE
1537            {
1538                if let [ast::PathSegment { ident, args: None, .. }] =
1539                    &poly_trait_ref.trait_ref.path.segments[..]
1540                {
1541                    if ident.span == span {
1542                        let Some(new_where_bound_predicate) =
1543                            mk_where_bound_predicate(path, poly_trait_ref, ty)
1544                        else {
1545                            return false;
1546                        };
1547                        err.span_suggestion_verbose(
1548                            *where_span,
1549                            format!("constrain the associated type to `{ident}`"),
1550                            where_bound_predicate_to_string(&new_where_bound_predicate),
1551                            Applicability::MaybeIncorrect,
1552                        );
1553                    }
1554                    return true;
1555                }
1556            }
1557        }
1558        false
1559    }
1560
1561    /// Check if the source is call expression and the first argument is `self`. If true,
1562    /// return the span of whole call and the span for all arguments expect the first one (`self`).
1563    fn call_has_self_arg(&self, source: PathSource<'_, '_, '_>) -> Option<(Span, Option<Span>)> {
1564        let mut has_self_arg = None;
1565        if let PathSource::Expr(Some(parent)) = source
1566            && let ExprKind::Call(_, args) = &parent.kind
1567            && !args.is_empty()
1568        {
1569            let mut expr_kind = &args[0].kind;
1570            loop {
1571                match expr_kind {
1572                    ExprKind::Path(_, arg_name) if arg_name.segments.len() == 1 => {
1573                        if arg_name.segments[0].ident.name == kw::SelfLower {
1574                            let call_span = parent.span;
1575                            let tail_args_span = if args.len() > 1 {
1576                                Some(Span::new(
1577                                    args[1].span.lo(),
1578                                    args.last().unwrap().span.hi(),
1579                                    call_span.ctxt(),
1580                                    None,
1581                                ))
1582                            } else {
1583                                None
1584                            };
1585                            has_self_arg = Some((call_span, tail_args_span));
1586                        }
1587                        break;
1588                    }
1589                    ExprKind::AddrOf(_, _, expr) => expr_kind = &expr.kind,
1590                    _ => break,
1591                }
1592            }
1593        }
1594        has_self_arg
1595    }
1596
1597    fn followed_by_brace(&self, span: Span) -> (bool, Option<Span>) {
1598        // HACK(estebank): find a better way to figure out that this was a
1599        // parser issue where a struct literal is being used on an expression
1600        // where a brace being opened means a block is being started. Look
1601        // ahead for the next text to see if `span` is followed by a `{`.
1602        let sm = self.r.tcx.sess.source_map();
1603        if let Some(followed_brace_span) = sm.span_look_ahead(span, "{", Some(50)) {
1604            // In case this could be a struct literal that needs to be surrounded
1605            // by parentheses, find the appropriate span.
1606            let close_brace_span = sm.span_look_ahead(followed_brace_span, "}", Some(50));
1607            let closing_brace = close_brace_span.map(|sp| span.to(sp));
1608            (true, closing_brace)
1609        } else {
1610            (false, None)
1611        }
1612    }
1613
1614    /// Provides context-dependent help for errors reported by the `smart_resolve_path_fragment`
1615    /// function.
1616    /// Returns `true` if able to provide context-dependent help.
1617    fn smart_resolve_context_dependent_help(
1618        &mut self,
1619        err: &mut Diag<'_>,
1620        span: Span,
1621        source: PathSource<'_, '_, '_>,
1622        path: &[Segment],
1623        res: Res,
1624        path_str: &str,
1625        fallback_label: &str,
1626    ) -> bool {
1627        let ns = source.namespace();
1628        let is_expected = &|res| source.is_expected(res);
1629
1630        let path_sep = |this: &Self, err: &mut Diag<'_>, expr: &Expr, kind: DefKind| {
1631            const MESSAGE: &str = "use the path separator to refer to an item";
1632
1633            let (lhs_span, rhs_span) = match &expr.kind {
1634                ExprKind::Field(base, ident) => (base.span, ident.span),
1635                ExprKind::MethodCall(box MethodCall { receiver, span, .. }) => {
1636                    (receiver.span, *span)
1637                }
1638                _ => return false,
1639            };
1640
1641            if lhs_span.eq_ctxt(rhs_span) {
1642                err.span_suggestion_verbose(
1643                    lhs_span.between(rhs_span),
1644                    MESSAGE,
1645                    "::",
1646                    Applicability::MaybeIncorrect,
1647                );
1648                true
1649            } else if matches!(kind, DefKind::Struct | DefKind::TyAlias)
1650                && let Some(lhs_source_span) = lhs_span.find_ancestor_inside(expr.span)
1651                && let Ok(snippet) = this.r.tcx.sess.source_map().span_to_snippet(lhs_source_span)
1652            {
1653                // The LHS is a type that originates from a macro call.
1654                // We have to add angle brackets around it.
1655
1656                err.span_suggestion_verbose(
1657                    lhs_source_span.until(rhs_span),
1658                    MESSAGE,
1659                    format!("<{snippet}>::"),
1660                    Applicability::MaybeIncorrect,
1661                );
1662                true
1663            } else {
1664                // Either we were unable to obtain the source span / the snippet or
1665                // the LHS originates from a macro call and it is not a type and thus
1666                // there is no way to replace `.` with `::` and still somehow suggest
1667                // valid Rust code.
1668
1669                false
1670            }
1671        };
1672
1673        let find_span = |source: &PathSource<'_, '_, '_>, err: &mut Diag<'_>| {
1674            match source {
1675                PathSource::Expr(Some(Expr { span, kind: ExprKind::Call(_, _), .. }))
1676                | PathSource::TupleStruct(span, _) => {
1677                    // We want the main underline to cover the suggested code as well for
1678                    // cleaner output.
1679                    err.span(*span);
1680                    *span
1681                }
1682                _ => span,
1683            }
1684        };
1685
1686        let bad_struct_syntax_suggestion = |this: &mut Self, err: &mut Diag<'_>, def_id: DefId| {
1687            let (followed_by_brace, closing_brace) = this.followed_by_brace(span);
1688
1689            match source {
1690                PathSource::Expr(Some(
1691                    parent @ Expr { kind: ExprKind::Field(..) | ExprKind::MethodCall(..), .. },
1692                )) if path_sep(this, err, parent, DefKind::Struct) => {}
1693                PathSource::Expr(
1694                    None
1695                    | Some(Expr {
1696                        kind:
1697                            ExprKind::Path(..)
1698                            | ExprKind::Binary(..)
1699                            | ExprKind::Unary(..)
1700                            | ExprKind::If(..)
1701                            | ExprKind::While(..)
1702                            | ExprKind::ForLoop { .. }
1703                            | ExprKind::Match(..),
1704                        ..
1705                    }),
1706                ) if followed_by_brace => {
1707                    if let Some(sp) = closing_brace {
1708                        err.span_label(span, fallback_label.to_string());
1709                        err.multipart_suggestion(
1710                            "surround the struct literal with parentheses",
1711                            vec![
1712                                (sp.shrink_to_lo(), "(".to_string()),
1713                                (sp.shrink_to_hi(), ")".to_string()),
1714                            ],
1715                            Applicability::MaybeIncorrect,
1716                        );
1717                    } else {
1718                        err.span_label(
1719                            span, // Note the parentheses surrounding the suggestion below
1720                            format!(
1721                                "you might want to surround a struct literal with parentheses: \
1722                                 `({path_str} {{ /* fields */ }})`?"
1723                            ),
1724                        );
1725                    }
1726                }
1727                PathSource::Expr(_) | PathSource::TupleStruct(..) | PathSource::Pat => {
1728                    let span = find_span(&source, err);
1729                    err.span_label(this.r.def_span(def_id), format!("`{path_str}` defined here"));
1730
1731                    let (tail, descr, applicability, old_fields) = match source {
1732                        PathSource::Pat => ("", "pattern", Applicability::MachineApplicable, None),
1733                        PathSource::TupleStruct(_, args) => (
1734                            "",
1735                            "pattern",
1736                            Applicability::MachineApplicable,
1737                            Some(
1738                                args.iter()
1739                                    .map(|a| this.r.tcx.sess.source_map().span_to_snippet(*a).ok())
1740                                    .collect::<Vec<Option<String>>>(),
1741                            ),
1742                        ),
1743                        _ => (": val", "literal", Applicability::HasPlaceholders, None),
1744                    };
1745
1746                    if !this.has_private_fields(def_id) {
1747                        // If the fields of the type are private, we shouldn't be suggesting using
1748                        // the struct literal syntax at all, as that will cause a subsequent error.
1749                        let fields = this.r.field_idents(def_id);
1750                        let has_fields = fields.as_ref().is_some_and(|f| !f.is_empty());
1751
1752                        if let PathSource::Expr(Some(Expr {
1753                            kind: ExprKind::Call(path, args),
1754                            span,
1755                            ..
1756                        })) = source
1757                            && !args.is_empty()
1758                            && let Some(fields) = &fields
1759                            && args.len() == fields.len()
1760                        // Make sure we have same number of args as fields
1761                        {
1762                            let path_span = path.span;
1763                            let mut parts = Vec::new();
1764
1765                            // Start with the opening brace
1766                            parts.push((
1767                                path_span.shrink_to_hi().until(args[0].span),
1768                                "{".to_owned(),
1769                            ));
1770
1771                            for (field, arg) in fields.iter().zip(args.iter()) {
1772                                // Add the field name before the argument
1773                                parts.push((arg.span.shrink_to_lo(), format!("{}: ", field)));
1774                            }
1775
1776                            // Add the closing brace
1777                            parts.push((
1778                                args.last().unwrap().span.shrink_to_hi().until(span.shrink_to_hi()),
1779                                "}".to_owned(),
1780                            ));
1781
1782                            err.multipart_suggestion_verbose(
1783                                format!("use struct {descr} syntax instead of calling"),
1784                                parts,
1785                                applicability,
1786                            );
1787                        } else {
1788                            let (fields, applicability) = match fields {
1789                                Some(fields) => {
1790                                    let fields = if let Some(old_fields) = old_fields {
1791                                        fields
1792                                            .iter()
1793                                            .enumerate()
1794                                            .map(|(idx, new)| (new, old_fields.get(idx)))
1795                                            .map(|(new, old)| {
1796                                                if let Some(Some(old)) = old
1797                                                    && new.as_str() != old
1798                                                {
1799                                                    format!("{new}: {old}")
1800                                                } else {
1801                                                    new.to_string()
1802                                                }
1803                                            })
1804                                            .collect::<Vec<String>>()
1805                                    } else {
1806                                        fields
1807                                            .iter()
1808                                            .map(|f| format!("{f}{tail}"))
1809                                            .collect::<Vec<String>>()
1810                                    };
1811
1812                                    (fields.join(", "), applicability)
1813                                }
1814                                None => {
1815                                    ("/* fields */".to_string(), Applicability::HasPlaceholders)
1816                                }
1817                            };
1818                            let pad = if has_fields { " " } else { "" };
1819                            err.span_suggestion(
1820                                span,
1821                                format!("use struct {descr} syntax instead"),
1822                                format!("{path_str} {{{pad}{fields}{pad}}}"),
1823                                applicability,
1824                            );
1825                        }
1826                    }
1827                    if let PathSource::Expr(Some(Expr {
1828                        kind: ExprKind::Call(path, args),
1829                        span: call_span,
1830                        ..
1831                    })) = source
1832                    {
1833                        this.suggest_alternative_construction_methods(
1834                            def_id,
1835                            err,
1836                            path.span,
1837                            *call_span,
1838                            &args[..],
1839                        );
1840                    }
1841                }
1842                _ => {
1843                    err.span_label(span, fallback_label.to_string());
1844                }
1845            }
1846        };
1847
1848        match (res, source) {
1849            (
1850                Res::Def(DefKind::Macro(kinds), def_id),
1851                PathSource::Expr(Some(Expr {
1852                    kind: ExprKind::Index(..) | ExprKind::Call(..), ..
1853                }))
1854                | PathSource::Struct(_),
1855            ) if kinds.contains(MacroKinds::BANG) => {
1856                // Don't suggest macro if it's unstable.
1857                let suggestable = def_id.is_local()
1858                    || self.r.tcx.lookup_stability(def_id).is_none_or(|s| s.is_stable());
1859
1860                err.span_label(span, fallback_label.to_string());
1861
1862                // Don't suggest `!` for a macro invocation if there are generic args
1863                if path
1864                    .last()
1865                    .is_some_and(|segment| !segment.has_generic_args && !segment.has_lifetime_args)
1866                    && suggestable
1867                {
1868                    err.span_suggestion_verbose(
1869                        span.shrink_to_hi(),
1870                        "use `!` to invoke the macro",
1871                        "!",
1872                        Applicability::MaybeIncorrect,
1873                    );
1874                }
1875
1876                if path_str == "try" && span.is_rust_2015() {
1877                    err.note("if you want the `try` keyword, you need Rust 2018 or later");
1878                }
1879            }
1880            (Res::Def(DefKind::Macro(kinds), _), _) if kinds.contains(MacroKinds::BANG) => {
1881                err.span_label(span, fallback_label.to_string());
1882            }
1883            (Res::Def(DefKind::TyAlias, def_id), PathSource::Trait(_)) => {
1884                err.span_label(span, "type aliases cannot be used as traits");
1885                if self.r.tcx.sess.is_nightly_build() {
1886                    let msg = "you might have meant to use `#![feature(trait_alias)]` instead of a \
1887                               `type` alias";
1888                    let span = self.r.def_span(def_id);
1889                    if let Ok(snip) = self.r.tcx.sess.source_map().span_to_snippet(span) {
1890                        // The span contains a type alias so we should be able to
1891                        // replace `type` with `trait`.
1892                        let snip = snip.replacen("type", "trait", 1);
1893                        err.span_suggestion(span, msg, snip, Applicability::MaybeIncorrect);
1894                    } else {
1895                        err.span_help(span, msg);
1896                    }
1897                }
1898            }
1899            (
1900                Res::Def(kind @ (DefKind::Mod | DefKind::Trait | DefKind::TyAlias), _),
1901                PathSource::Expr(Some(parent)),
1902            ) if path_sep(self, err, parent, kind) => {
1903                return true;
1904            }
1905            (
1906                Res::Def(DefKind::Enum, def_id),
1907                PathSource::TupleStruct(..) | PathSource::Expr(..),
1908            ) => {
1909                self.suggest_using_enum_variant(err, source, def_id, span);
1910            }
1911            (Res::Def(DefKind::Struct, def_id), source) if ns == ValueNS => {
1912                let struct_ctor = match def_id.as_local() {
1913                    Some(def_id) => self.r.struct_constructors.get(&def_id).cloned(),
1914                    None => {
1915                        let ctor = self.r.cstore().ctor_untracked(def_id);
1916                        ctor.map(|(ctor_kind, ctor_def_id)| {
1917                            let ctor_res =
1918                                Res::Def(DefKind::Ctor(CtorOf::Struct, ctor_kind), ctor_def_id);
1919                            let ctor_vis = self.r.tcx.visibility(ctor_def_id);
1920                            let field_visibilities = self
1921                                .r
1922                                .tcx
1923                                .associated_item_def_ids(def_id)
1924                                .iter()
1925                                .map(|field_id| self.r.tcx.visibility(field_id))
1926                                .collect();
1927                            (ctor_res, ctor_vis, field_visibilities)
1928                        })
1929                    }
1930                };
1931
1932                let (ctor_def, ctor_vis, fields) = if let Some(struct_ctor) = struct_ctor {
1933                    if let PathSource::Expr(Some(parent)) = source
1934                        && let ExprKind::Field(..) | ExprKind::MethodCall(..) = parent.kind
1935                    {
1936                        bad_struct_syntax_suggestion(self, err, def_id);
1937                        return true;
1938                    }
1939                    struct_ctor
1940                } else {
1941                    bad_struct_syntax_suggestion(self, err, def_id);
1942                    return true;
1943                };
1944
1945                let update_message =
1946                    |this: &mut Self, err: &mut Diag<'_>, source: &PathSource<'_, '_, '_>| {
1947                        match source {
1948                            // e.g. `if let Enum::TupleVariant(field1, field2) = _`
1949                            PathSource::TupleStruct(_, pattern_spans) => {
1950                                err.primary_message(
1951                                "cannot match against a tuple struct which contains private fields",
1952                            );
1953
1954                                // Use spans of the tuple struct pattern.
1955                                Some(Vec::from(*pattern_spans))
1956                            }
1957                            // e.g. `let _ = Enum::TupleVariant(field1, field2);`
1958                            PathSource::Expr(Some(Expr {
1959                                kind: ExprKind::Call(path, args),
1960                                span: call_span,
1961                                ..
1962                            })) => {
1963                                err.primary_message(
1964                                "cannot initialize a tuple struct which contains private fields",
1965                            );
1966                                this.suggest_alternative_construction_methods(
1967                                    def_id,
1968                                    err,
1969                                    path.span,
1970                                    *call_span,
1971                                    &args[..],
1972                                );
1973                                // Use spans of the tuple struct definition.
1974                                this.r
1975                                    .field_idents(def_id)
1976                                    .map(|fields| fields.iter().map(|f| f.span).collect::<Vec<_>>())
1977                            }
1978                            _ => None,
1979                        }
1980                    };
1981                let is_accessible = self.r.is_accessible_from(ctor_vis, self.parent_scope.module);
1982                if let Some(use_span) = self.r.inaccessible_ctor_reexport.get(&span)
1983                    && is_accessible
1984                {
1985                    err.span_note(
1986                        *use_span,
1987                        "the type is accessed through this re-export, but the type's constructor \
1988                         is not visible in this import's scope due to private fields",
1989                    );
1990                    if is_accessible
1991                        && fields
1992                            .iter()
1993                            .all(|vis| self.r.is_accessible_from(*vis, self.parent_scope.module))
1994                    {
1995                        err.span_suggestion_verbose(
1996                            span,
1997                            "the type can be constructed directly, because its fields are \
1998                             available from the current scope",
1999                            // Using `tcx.def_path_str` causes the compiler to hang.
2000                            // We don't need to handle foreign crate types because in that case you
2001                            // can't access the ctor either way.
2002                            format!(
2003                                "crate{}", // The method already has leading `::`.
2004                                self.r.tcx.def_path(def_id).to_string_no_crate_verbose(),
2005                            ),
2006                            Applicability::MachineApplicable,
2007                        );
2008                    }
2009                    update_message(self, err, &source);
2010                }
2011                if !is_expected(ctor_def) || is_accessible {
2012                    return true;
2013                }
2014
2015                let field_spans = update_message(self, err, &source);
2016
2017                if let Some(spans) =
2018                    field_spans.filter(|spans| spans.len() > 0 && fields.len() == spans.len())
2019                {
2020                    let non_visible_spans: Vec<Span> = iter::zip(&fields, &spans)
2021                        .filter(|(vis, _)| {
2022                            !self.r.is_accessible_from(**vis, self.parent_scope.module)
2023                        })
2024                        .map(|(_, span)| *span)
2025                        .collect();
2026
2027                    if non_visible_spans.len() > 0 {
2028                        if let Some(fields) = self.r.field_visibility_spans.get(&def_id) {
2029                            err.multipart_suggestion_verbose(
2030                                format!(
2031                                    "consider making the field{} publicly accessible",
2032                                    pluralize!(fields.len())
2033                                ),
2034                                fields.iter().map(|span| (*span, "pub ".to_string())).collect(),
2035                                Applicability::MaybeIncorrect,
2036                            );
2037                        }
2038
2039                        let mut m: MultiSpan = non_visible_spans.clone().into();
2040                        non_visible_spans
2041                            .into_iter()
2042                            .for_each(|s| m.push_span_label(s, "private field"));
2043                        err.span_note(m, "constructor is not visible here due to private fields");
2044                    }
2045
2046                    return true;
2047                }
2048
2049                err.span_label(span, "constructor is not visible here due to private fields");
2050            }
2051            (Res::Def(DefKind::Union | DefKind::Variant, def_id), _) if ns == ValueNS => {
2052                bad_struct_syntax_suggestion(self, err, def_id);
2053            }
2054            (Res::Def(DefKind::Ctor(_, CtorKind::Const), def_id), _) if ns == ValueNS => {
2055                match source {
2056                    PathSource::Expr(_) | PathSource::TupleStruct(..) | PathSource::Pat => {
2057                        let span = find_span(&source, err);
2058                        err.span_label(
2059                            self.r.def_span(def_id),
2060                            format!("`{path_str}` defined here"),
2061                        );
2062                        err.span_suggestion(
2063                            span,
2064                            "use this syntax instead",
2065                            path_str,
2066                            Applicability::MaybeIncorrect,
2067                        );
2068                    }
2069                    _ => return false,
2070                }
2071            }
2072            (Res::Def(DefKind::Ctor(_, CtorKind::Fn), ctor_def_id), _) if ns == ValueNS => {
2073                let def_id = self.r.tcx.parent(ctor_def_id);
2074                err.span_label(self.r.def_span(def_id), format!("`{path_str}` defined here"));
2075                let fields = self.r.field_idents(def_id).map_or_else(
2076                    || "/* fields */".to_string(),
2077                    |field_ids| vec!["_"; field_ids.len()].join(", "),
2078                );
2079                err.span_suggestion(
2080                    span,
2081                    "use the tuple variant pattern syntax instead",
2082                    format!("{path_str}({fields})"),
2083                    Applicability::HasPlaceholders,
2084                );
2085            }
2086            (Res::SelfTyParam { .. } | Res::SelfTyAlias { .. }, _) if ns == ValueNS => {
2087                err.span_label(span, fallback_label.to_string());
2088                err.note("can't use `Self` as a constructor, you must use the implemented struct");
2089            }
2090            (
2091                Res::Def(DefKind::TyAlias | DefKind::AssocTy, _),
2092                PathSource::TraitItem(ValueNS, PathSource::TupleStruct(whole, args)),
2093            ) => {
2094                err.note("can't use a type alias as tuple pattern");
2095
2096                let mut suggestion = Vec::new();
2097
2098                if let &&[first, ..] = args
2099                    && let &&[.., last] = args
2100                {
2101                    suggestion.extend([
2102                        // "0: " has to be included here so that the fix is machine applicable.
2103                        //
2104                        // If this would only add " { " and then the code below add "0: ",
2105                        // rustfix would crash, because end of this suggestion is the same as start
2106                        // of the suggestion below. Thus, we have to merge these...
2107                        (span.between(first), " { 0: ".to_owned()),
2108                        (last.between(whole.shrink_to_hi()), " }".to_owned()),
2109                    ]);
2110
2111                    suggestion.extend(
2112                        args.iter()
2113                            .enumerate()
2114                            .skip(1) // See above
2115                            .map(|(index, &arg)| (arg.shrink_to_lo(), format!("{index}: "))),
2116                    )
2117                } else {
2118                    suggestion.push((span.between(whole.shrink_to_hi()), " {}".to_owned()));
2119                }
2120
2121                err.multipart_suggestion(
2122                    "use struct pattern instead",
2123                    suggestion,
2124                    Applicability::MachineApplicable,
2125                );
2126            }
2127            (
2128                Res::Def(DefKind::TyAlias | DefKind::AssocTy, _),
2129                PathSource::TraitItem(
2130                    ValueNS,
2131                    PathSource::Expr(Some(ast::Expr {
2132                        span: whole,
2133                        kind: ast::ExprKind::Call(_, args),
2134                        ..
2135                    })),
2136                ),
2137            ) => {
2138                err.note("can't use a type alias as a constructor");
2139
2140                let mut suggestion = Vec::new();
2141
2142                if let [first, ..] = &**args
2143                    && let [.., last] = &**args
2144                {
2145                    suggestion.extend([
2146                        // "0: " has to be included here so that the fix is machine applicable.
2147                        //
2148                        // If this would only add " { " and then the code below add "0: ",
2149                        // rustfix would crash, because end of this suggestion is the same as start
2150                        // of the suggestion below. Thus, we have to merge these...
2151                        (span.between(first.span), " { 0: ".to_owned()),
2152                        (last.span.between(whole.shrink_to_hi()), " }".to_owned()),
2153                    ]);
2154
2155                    suggestion.extend(
2156                        args.iter()
2157                            .enumerate()
2158                            .skip(1) // See above
2159                            .map(|(index, arg)| (arg.span.shrink_to_lo(), format!("{index}: "))),
2160                    )
2161                } else {
2162                    suggestion.push((span.between(whole.shrink_to_hi()), " {}".to_owned()));
2163                }
2164
2165                err.multipart_suggestion(
2166                    "use struct expression instead",
2167                    suggestion,
2168                    Applicability::MachineApplicable,
2169                );
2170            }
2171            _ => return false,
2172        }
2173        true
2174    }
2175
2176    fn suggest_alternative_construction_methods(
2177        &mut self,
2178        def_id: DefId,
2179        err: &mut Diag<'_>,
2180        path_span: Span,
2181        call_span: Span,
2182        args: &[Box<Expr>],
2183    ) {
2184        if def_id.is_local() {
2185            // Doing analysis on local `DefId`s would cause infinite recursion.
2186            return;
2187        }
2188        // Look at all the associated functions without receivers in the type's
2189        // inherent impls to look for builders that return `Self`
2190        let mut items = self
2191            .r
2192            .tcx
2193            .inherent_impls(def_id)
2194            .iter()
2195            .flat_map(|i| self.r.tcx.associated_items(i).in_definition_order())
2196            // Only assoc fn with no receivers.
2197            .filter(|item| item.is_fn() && !item.is_method())
2198            .filter_map(|item| {
2199                // Only assoc fns that return `Self`
2200                let fn_sig = self.r.tcx.fn_sig(item.def_id).skip_binder();
2201                // Don't normalize the return type, because that can cause cycle errors.
2202                let ret_ty = fn_sig.output().skip_binder();
2203                let ty::Adt(def, _args) = ret_ty.kind() else {
2204                    return None;
2205                };
2206                let input_len = fn_sig.inputs().skip_binder().len();
2207                if def.did() != def_id {
2208                    return None;
2209                }
2210                let name = item.name();
2211                let order = !name.as_str().starts_with("new");
2212                Some((order, name, input_len))
2213            })
2214            .collect::<Vec<_>>();
2215        items.sort_by_key(|(order, _, _)| *order);
2216        let suggestion = |name, args| {
2217            format!("::{name}({})", std::iter::repeat_n("_", args).collect::<Vec<_>>().join(", "))
2218        };
2219        match &items[..] {
2220            [] => {}
2221            [(_, name, len)] if *len == args.len() => {
2222                err.span_suggestion_verbose(
2223                    path_span.shrink_to_hi(),
2224                    format!("you might have meant to use the `{name}` associated function",),
2225                    format!("::{name}"),
2226                    Applicability::MaybeIncorrect,
2227                );
2228            }
2229            [(_, name, len)] => {
2230                err.span_suggestion_verbose(
2231                    path_span.shrink_to_hi().with_hi(call_span.hi()),
2232                    format!("you might have meant to use the `{name}` associated function",),
2233                    suggestion(name, *len),
2234                    Applicability::MaybeIncorrect,
2235                );
2236            }
2237            _ => {
2238                err.span_suggestions_with_style(
2239                    path_span.shrink_to_hi().with_hi(call_span.hi()),
2240                    "you might have meant to use an associated function to build this type",
2241                    items.iter().map(|(_, name, len)| suggestion(name, *len)),
2242                    Applicability::MaybeIncorrect,
2243                    SuggestionStyle::ShowAlways,
2244                );
2245            }
2246        }
2247        // We'd ideally use `type_implements_trait` but don't have access to
2248        // the trait solver here. We can't use `get_diagnostic_item` or
2249        // `all_traits` in resolve either. So instead we abuse the import
2250        // suggestion machinery to get `std::default::Default` and perform some
2251        // checks to confirm that we got *only* that trait. We then see if the
2252        // Adt we have has a direct implementation of `Default`. If so, we
2253        // provide a structured suggestion.
2254        let default_trait = self
2255            .r
2256            .lookup_import_candidates(
2257                Ident::with_dummy_span(sym::Default),
2258                Namespace::TypeNS,
2259                &self.parent_scope,
2260                &|res: Res| matches!(res, Res::Def(DefKind::Trait, _)),
2261            )
2262            .iter()
2263            .filter_map(|candidate| candidate.did)
2264            .find(|did| {
2265                self.r
2266                    .tcx
2267                    .get_attrs(*did, sym::rustc_diagnostic_item)
2268                    .any(|attr| attr.value_str() == Some(sym::Default))
2269            });
2270        let Some(default_trait) = default_trait else {
2271            return;
2272        };
2273        if self
2274            .r
2275            .extern_crate_map
2276            .items()
2277            // FIXME: This doesn't include impls like `impl Default for String`.
2278            .flat_map(|(_, crate_)| self.r.tcx.implementations_of_trait((*crate_, default_trait)))
2279            .filter_map(|(_, simplified_self_ty)| *simplified_self_ty)
2280            .filter_map(|simplified_self_ty| match simplified_self_ty {
2281                SimplifiedType::Adt(did) => Some(did),
2282                _ => None,
2283            })
2284            .any(|did| did == def_id)
2285        {
2286            err.multipart_suggestion(
2287                "consider using the `Default` trait",
2288                vec![
2289                    (path_span.shrink_to_lo(), "<".to_string()),
2290                    (
2291                        path_span.shrink_to_hi().with_hi(call_span.hi()),
2292                        " as std::default::Default>::default()".to_string(),
2293                    ),
2294                ],
2295                Applicability::MaybeIncorrect,
2296            );
2297        }
2298    }
2299
2300    fn has_private_fields(&self, def_id: DefId) -> bool {
2301        let fields = match def_id.as_local() {
2302            Some(def_id) => self.r.struct_constructors.get(&def_id).cloned().map(|(_, _, f)| f),
2303            None => Some(
2304                self.r
2305                    .tcx
2306                    .associated_item_def_ids(def_id)
2307                    .iter()
2308                    .map(|field_id| self.r.tcx.visibility(field_id))
2309                    .collect(),
2310            ),
2311        };
2312
2313        fields.is_some_and(|fields| {
2314            fields.iter().any(|vis| !self.r.is_accessible_from(*vis, self.parent_scope.module))
2315        })
2316    }
2317
2318    /// Given the target `ident` and `kind`, search for the similarly named associated item
2319    /// in `self.current_trait_ref`.
2320    pub(crate) fn find_similarly_named_assoc_item(
2321        &mut self,
2322        ident: Symbol,
2323        kind: &AssocItemKind,
2324    ) -> Option<Symbol> {
2325        let (module, _) = self.current_trait_ref.as_ref()?;
2326        if ident == kw::Underscore {
2327            // We do nothing for `_`.
2328            return None;
2329        }
2330
2331        let targets = self
2332            .r
2333            .resolutions(*module)
2334            .borrow()
2335            .iter()
2336            .filter_map(|(key, res)| {
2337                res.borrow().best_binding().map(|binding| (key, binding.res()))
2338            })
2339            .filter(|(_, res)| match (kind, res) {
2340                (AssocItemKind::Const(..), Res::Def(DefKind::AssocConst, _)) => true,
2341                (AssocItemKind::Fn(_), Res::Def(DefKind::AssocFn, _)) => true,
2342                (AssocItemKind::Type(..), Res::Def(DefKind::AssocTy, _)) => true,
2343                (AssocItemKind::Delegation(_), Res::Def(DefKind::AssocFn, _)) => true,
2344                _ => false,
2345            })
2346            .map(|(key, _)| key.ident.name)
2347            .collect::<Vec<_>>();
2348
2349        find_best_match_for_name(&targets, ident, None)
2350    }
2351
2352    fn lookup_assoc_candidate<FilterFn>(
2353        &mut self,
2354        ident: Ident,
2355        ns: Namespace,
2356        filter_fn: FilterFn,
2357        called: bool,
2358    ) -> Option<AssocSuggestion>
2359    where
2360        FilterFn: Fn(Res) -> bool,
2361    {
2362        fn extract_node_id(t: &Ty) -> Option<NodeId> {
2363            match t.kind {
2364                TyKind::Path(None, _) => Some(t.id),
2365                TyKind::Ref(_, ref mut_ty) => extract_node_id(&mut_ty.ty),
2366                // This doesn't handle the remaining `Ty` variants as they are not
2367                // that commonly the self_type, it might be interesting to provide
2368                // support for those in future.
2369                _ => None,
2370            }
2371        }
2372        // Fields are generally expected in the same contexts as locals.
2373        if filter_fn(Res::Local(ast::DUMMY_NODE_ID)) {
2374            if let Some(node_id) =
2375                self.diag_metadata.current_self_type.as_ref().and_then(extract_node_id)
2376                && let Some(resolution) = self.r.partial_res_map.get(&node_id)
2377                && let Some(Res::Def(DefKind::Struct | DefKind::Union, did)) = resolution.full_res()
2378                && let Some(fields) = self.r.field_idents(did)
2379                && let Some(field) = fields.iter().find(|id| ident.name == id.name)
2380            {
2381                // Look for a field with the same name in the current self_type.
2382                return Some(AssocSuggestion::Field(field.span));
2383            }
2384        }
2385
2386        if let Some(items) = self.diag_metadata.current_trait_assoc_items {
2387            for assoc_item in items {
2388                if let Some(assoc_ident) = assoc_item.kind.ident()
2389                    && assoc_ident == ident
2390                {
2391                    return Some(match &assoc_item.kind {
2392                        ast::AssocItemKind::Const(..) => AssocSuggestion::AssocConst,
2393                        ast::AssocItemKind::Fn(box ast::Fn { sig, .. }) if sig.decl.has_self() => {
2394                            AssocSuggestion::MethodWithSelf { called }
2395                        }
2396                        ast::AssocItemKind::Fn(..) => AssocSuggestion::AssocFn { called },
2397                        ast::AssocItemKind::Type(..) => AssocSuggestion::AssocType,
2398                        ast::AssocItemKind::Delegation(..)
2399                            if self
2400                                .r
2401                                .delegation_fn_sigs
2402                                .get(&self.r.local_def_id(assoc_item.id))
2403                                .is_some_and(|sig| sig.has_self) =>
2404                        {
2405                            AssocSuggestion::MethodWithSelf { called }
2406                        }
2407                        ast::AssocItemKind::Delegation(..) => AssocSuggestion::AssocFn { called },
2408                        ast::AssocItemKind::MacCall(_) | ast::AssocItemKind::DelegationMac(..) => {
2409                            continue;
2410                        }
2411                    });
2412                }
2413            }
2414        }
2415
2416        // Look for associated items in the current trait.
2417        if let Some((module, _)) = self.current_trait_ref
2418            && let Ok(binding) = self.r.cm().maybe_resolve_ident_in_module(
2419                ModuleOrUniformRoot::Module(module),
2420                ident,
2421                ns,
2422                &self.parent_scope,
2423                None,
2424            )
2425        {
2426            let res = binding.res();
2427            if filter_fn(res) {
2428                match res {
2429                    Res::Def(DefKind::Fn | DefKind::AssocFn, def_id) => {
2430                        let has_self = match def_id.as_local() {
2431                            Some(def_id) => self
2432                                .r
2433                                .delegation_fn_sigs
2434                                .get(&def_id)
2435                                .is_some_and(|sig| sig.has_self),
2436                            None => {
2437                                self.r.tcx.fn_arg_idents(def_id).first().is_some_and(|&ident| {
2438                                    matches!(ident, Some(Ident { name: kw::SelfLower, .. }))
2439                                })
2440                            }
2441                        };
2442                        if has_self {
2443                            return Some(AssocSuggestion::MethodWithSelf { called });
2444                        } else {
2445                            return Some(AssocSuggestion::AssocFn { called });
2446                        }
2447                    }
2448                    Res::Def(DefKind::AssocConst, _) => {
2449                        return Some(AssocSuggestion::AssocConst);
2450                    }
2451                    Res::Def(DefKind::AssocTy, _) => {
2452                        return Some(AssocSuggestion::AssocType);
2453                    }
2454                    _ => {}
2455                }
2456            }
2457        }
2458
2459        None
2460    }
2461
2462    fn lookup_typo_candidate(
2463        &mut self,
2464        path: &[Segment],
2465        following_seg: Option<&Segment>,
2466        ns: Namespace,
2467        filter_fn: &impl Fn(Res) -> bool,
2468    ) -> TypoCandidate {
2469        let mut names = Vec::new();
2470        if let [segment] = path {
2471            let mut ctxt = segment.ident.span.ctxt();
2472
2473            // Search in lexical scope.
2474            // Walk backwards up the ribs in scope and collect candidates.
2475            for rib in self.ribs[ns].iter().rev() {
2476                let rib_ctxt = if rib.kind.contains_params() {
2477                    ctxt.normalize_to_macros_2_0()
2478                } else {
2479                    ctxt.normalize_to_macro_rules()
2480                };
2481
2482                // Locals and type parameters
2483                for (ident, &res) in &rib.bindings {
2484                    if filter_fn(res) && ident.span.ctxt() == rib_ctxt {
2485                        names.push(TypoSuggestion::typo_from_ident(*ident, res));
2486                    }
2487                }
2488
2489                if let RibKind::Block(Some(module)) = rib.kind {
2490                    self.r.add_module_candidates(module, &mut names, &filter_fn, Some(ctxt));
2491                } else if let RibKind::Module(module) = rib.kind {
2492                    // Encountered a module item, abandon ribs and look into that module and preludes.
2493                    let parent_scope = &ParentScope { module, ..self.parent_scope };
2494                    self.r.add_scope_set_candidates(
2495                        &mut names,
2496                        ScopeSet::All(ns),
2497                        parent_scope,
2498                        ctxt,
2499                        filter_fn,
2500                    );
2501                    break;
2502                }
2503
2504                if let RibKind::MacroDefinition(def) = rib.kind
2505                    && def == self.r.macro_def(ctxt)
2506                {
2507                    // If an invocation of this macro created `ident`, give up on `ident`
2508                    // and switch to `ident`'s source from the macro definition.
2509                    ctxt.remove_mark();
2510                }
2511            }
2512        } else {
2513            // Search in module.
2514            let mod_path = &path[..path.len() - 1];
2515            if let PathResult::Module(ModuleOrUniformRoot::Module(module)) =
2516                self.resolve_path(mod_path, Some(TypeNS), None, PathSource::Type)
2517            {
2518                self.r.add_module_candidates(module, &mut names, &filter_fn, None);
2519            }
2520        }
2521
2522        // if next_seg is present, let's filter everything that does not continue the path
2523        if let Some(following_seg) = following_seg {
2524            names.retain(|suggestion| match suggestion.res {
2525                Res::Def(DefKind::Struct | DefKind::Enum | DefKind::Union, _) => {
2526                    // FIXME: this is not totally accurate, but mostly works
2527                    suggestion.candidate != following_seg.ident.name
2528                }
2529                Res::Def(DefKind::Mod, def_id) => {
2530                    let module = self.r.expect_module(def_id);
2531                    self.r
2532                        .resolutions(module)
2533                        .borrow()
2534                        .iter()
2535                        .any(|(key, _)| key.ident.name == following_seg.ident.name)
2536                }
2537                _ => true,
2538            });
2539        }
2540        let name = path[path.len() - 1].ident.name;
2541        // Make sure error reporting is deterministic.
2542        names.sort_by(|a, b| a.candidate.as_str().cmp(b.candidate.as_str()));
2543
2544        match find_best_match_for_name(
2545            &names.iter().map(|suggestion| suggestion.candidate).collect::<Vec<Symbol>>(),
2546            name,
2547            None,
2548        ) {
2549            Some(found) => {
2550                let Some(sugg) = names.into_iter().find(|suggestion| suggestion.candidate == found)
2551                else {
2552                    return TypoCandidate::None;
2553                };
2554                if found == name {
2555                    TypoCandidate::Shadowed(sugg.res, sugg.span)
2556                } else {
2557                    TypoCandidate::Typo(sugg)
2558                }
2559            }
2560            _ => TypoCandidate::None,
2561        }
2562    }
2563
2564    // Returns the name of the Rust type approximately corresponding to
2565    // a type name in another programming language.
2566    fn likely_rust_type(path: &[Segment]) -> Option<Symbol> {
2567        let name = path[path.len() - 1].ident.as_str();
2568        // Common Java types
2569        Some(match name {
2570            "byte" => sym::u8, // In Java, bytes are signed, but in practice one almost always wants unsigned bytes.
2571            "short" => sym::i16,
2572            "Bool" => sym::bool,
2573            "Boolean" => sym::bool,
2574            "boolean" => sym::bool,
2575            "int" => sym::i32,
2576            "long" => sym::i64,
2577            "float" => sym::f32,
2578            "double" => sym::f64,
2579            _ => return None,
2580        })
2581    }
2582
2583    // try to give a suggestion for this pattern: `name = blah`, which is common in other languages
2584    // suggest `let name = blah` to introduce a new binding
2585    fn let_binding_suggestion(&self, err: &mut Diag<'_>, ident_span: Span) -> bool {
2586        if ident_span.from_expansion() {
2587            return false;
2588        }
2589
2590        // only suggest when the code is a assignment without prefix code
2591        if let Some(Expr { kind: ExprKind::Assign(lhs, ..), .. }) = self.diag_metadata.in_assignment
2592            && let ast::ExprKind::Path(None, ref path) = lhs.kind
2593            && self.r.tcx.sess.source_map().is_line_before_span_empty(ident_span)
2594        {
2595            let (span, text) = match path.segments.first() {
2596                Some(seg) if let Some(name) = seg.ident.as_str().strip_prefix("let") => {
2597                    // a special case for #117894
2598                    let name = name.strip_prefix('_').unwrap_or(name);
2599                    (ident_span, format!("let {name}"))
2600                }
2601                _ => (ident_span.shrink_to_lo(), "let ".to_string()),
2602            };
2603
2604            err.span_suggestion_verbose(
2605                span,
2606                "you might have meant to introduce a new binding",
2607                text,
2608                Applicability::MaybeIncorrect,
2609            );
2610            return true;
2611        }
2612
2613        // a special case for #133713
2614        // '=' maybe a typo of `:`, which is a type annotation instead of assignment
2615        if err.code == Some(E0423)
2616            && let Some((let_span, None, Some(val_span))) = self.diag_metadata.current_let_binding
2617            && val_span.contains(ident_span)
2618            && val_span.lo() == ident_span.lo()
2619        {
2620            err.span_suggestion_verbose(
2621                let_span.shrink_to_hi().to(val_span.shrink_to_lo()),
2622                "you might have meant to use `:` for type annotation",
2623                ": ",
2624                Applicability::MaybeIncorrect,
2625            );
2626            return true;
2627        }
2628        false
2629    }
2630
2631    fn find_module(&self, def_id: DefId) -> Option<(Module<'ra>, ImportSuggestion)> {
2632        let mut result = None;
2633        let mut seen_modules = FxHashSet::default();
2634        let root_did = self.r.graph_root.def_id();
2635        let mut worklist = vec![(
2636            self.r.graph_root,
2637            ThinVec::new(),
2638            root_did.is_local() || !self.r.tcx.is_doc_hidden(root_did),
2639        )];
2640
2641        while let Some((in_module, path_segments, doc_visible)) = worklist.pop() {
2642            // abort if the module is already found
2643            if result.is_some() {
2644                break;
2645            }
2646
2647            in_module.for_each_child(self.r, |r, ident, _, name_binding| {
2648                // abort if the module is already found or if name_binding is private external
2649                if result.is_some() || !name_binding.vis.is_visible_locally() {
2650                    return;
2651                }
2652                if let Some(module_def_id) = name_binding.res().module_like_def_id() {
2653                    // form the path
2654                    let mut path_segments = path_segments.clone();
2655                    path_segments.push(ast::PathSegment::from_ident(ident.0));
2656                    let doc_visible = doc_visible
2657                        && (module_def_id.is_local() || !r.tcx.is_doc_hidden(module_def_id));
2658                    if module_def_id == def_id {
2659                        let path =
2660                            Path { span: name_binding.span, segments: path_segments, tokens: None };
2661                        result = Some((
2662                            r.expect_module(module_def_id),
2663                            ImportSuggestion {
2664                                did: Some(def_id),
2665                                descr: "module",
2666                                path,
2667                                accessible: true,
2668                                doc_visible,
2669                                note: None,
2670                                via_import: false,
2671                                is_stable: true,
2672                            },
2673                        ));
2674                    } else {
2675                        // add the module to the lookup
2676                        if seen_modules.insert(module_def_id) {
2677                            let module = r.expect_module(module_def_id);
2678                            worklist.push((module, path_segments, doc_visible));
2679                        }
2680                    }
2681                }
2682            });
2683        }
2684
2685        result
2686    }
2687
2688    fn collect_enum_ctors(&self, def_id: DefId) -> Option<Vec<(Path, DefId, CtorKind)>> {
2689        self.find_module(def_id).map(|(enum_module, enum_import_suggestion)| {
2690            let mut variants = Vec::new();
2691            enum_module.for_each_child(self.r, |_, ident, _, name_binding| {
2692                if let Res::Def(DefKind::Ctor(CtorOf::Variant, kind), def_id) = name_binding.res() {
2693                    let mut segms = enum_import_suggestion.path.segments.clone();
2694                    segms.push(ast::PathSegment::from_ident(ident.0));
2695                    let path = Path { span: name_binding.span, segments: segms, tokens: None };
2696                    variants.push((path, def_id, kind));
2697                }
2698            });
2699            variants
2700        })
2701    }
2702
2703    /// Adds a suggestion for using an enum's variant when an enum is used instead.
2704    fn suggest_using_enum_variant(
2705        &self,
2706        err: &mut Diag<'_>,
2707        source: PathSource<'_, '_, '_>,
2708        def_id: DefId,
2709        span: Span,
2710    ) {
2711        let Some(variant_ctors) = self.collect_enum_ctors(def_id) else {
2712            err.note("you might have meant to use one of the enum's variants");
2713            return;
2714        };
2715
2716        // If the expression is a field-access or method-call, try to find a variant with the field/method name
2717        // that could have been intended, and suggest replacing the `.` with `::`.
2718        // Otherwise, suggest adding `::VariantName` after the enum;
2719        // and if the expression is call-like, only suggest tuple variants.
2720        let (suggest_path_sep_dot_span, suggest_only_tuple_variants) = match source {
2721            // `Type(a, b)` in a pattern, only suggest adding a tuple variant after `Type`.
2722            PathSource::TupleStruct(..) => (None, true),
2723            PathSource::Expr(Some(expr)) => match &expr.kind {
2724                // `Type(a, b)`, only suggest adding a tuple variant after `Type`.
2725                ExprKind::Call(..) => (None, true),
2726                // `Type.Foo(a, b)`, suggest replacing `.` -> `::` if variant `Foo` exists and is a tuple variant,
2727                // otherwise suggest adding a variant after `Type`.
2728                ExprKind::MethodCall(box MethodCall {
2729                    receiver,
2730                    span,
2731                    seg: PathSegment { ident, .. },
2732                    ..
2733                }) => {
2734                    let dot_span = receiver.span.between(*span);
2735                    let found_tuple_variant = variant_ctors.iter().any(|(path, _, ctor_kind)| {
2736                        *ctor_kind == CtorKind::Fn
2737                            && path.segments.last().is_some_and(|seg| seg.ident == *ident)
2738                    });
2739                    (found_tuple_variant.then_some(dot_span), false)
2740                }
2741                // `Type.Foo`, suggest replacing `.` -> `::` if variant `Foo` exists and is a unit or tuple variant,
2742                // otherwise suggest adding a variant after `Type`.
2743                ExprKind::Field(base, ident) => {
2744                    let dot_span = base.span.between(ident.span);
2745                    let found_tuple_or_unit_variant = variant_ctors.iter().any(|(path, ..)| {
2746                        path.segments.last().is_some_and(|seg| seg.ident == *ident)
2747                    });
2748                    (found_tuple_or_unit_variant.then_some(dot_span), false)
2749                }
2750                _ => (None, false),
2751            },
2752            _ => (None, false),
2753        };
2754
2755        if let Some(dot_span) = suggest_path_sep_dot_span {
2756            err.span_suggestion_verbose(
2757                dot_span,
2758                "use the path separator to refer to a variant",
2759                "::",
2760                Applicability::MaybeIncorrect,
2761            );
2762        } else if suggest_only_tuple_variants {
2763            // Suggest only tuple variants regardless of whether they have fields and do not
2764            // suggest path with added parentheses.
2765            let mut suggestable_variants = variant_ctors
2766                .iter()
2767                .filter(|(.., kind)| *kind == CtorKind::Fn)
2768                .map(|(variant, ..)| path_names_to_string(variant))
2769                .collect::<Vec<_>>();
2770            suggestable_variants.sort();
2771
2772            let non_suggestable_variant_count = variant_ctors.len() - suggestable_variants.len();
2773
2774            let source_msg = if matches!(source, PathSource::TupleStruct(..)) {
2775                "to match against"
2776            } else {
2777                "to construct"
2778            };
2779
2780            if !suggestable_variants.is_empty() {
2781                let msg = if non_suggestable_variant_count == 0 && suggestable_variants.len() == 1 {
2782                    format!("try {source_msg} the enum's variant")
2783                } else {
2784                    format!("try {source_msg} one of the enum's variants")
2785                };
2786
2787                err.span_suggestions(
2788                    span,
2789                    msg,
2790                    suggestable_variants,
2791                    Applicability::MaybeIncorrect,
2792                );
2793            }
2794
2795            // If the enum has no tuple variants..
2796            if non_suggestable_variant_count == variant_ctors.len() {
2797                err.help(format!("the enum has no tuple variants {source_msg}"));
2798            }
2799
2800            // If there are also non-tuple variants..
2801            if non_suggestable_variant_count == 1 {
2802                err.help(format!("you might have meant {source_msg} the enum's non-tuple variant"));
2803            } else if non_suggestable_variant_count >= 1 {
2804                err.help(format!(
2805                    "you might have meant {source_msg} one of the enum's non-tuple variants"
2806                ));
2807            }
2808        } else {
2809            let needs_placeholder = |ctor_def_id: DefId, kind: CtorKind| {
2810                let def_id = self.r.tcx.parent(ctor_def_id);
2811                match kind {
2812                    CtorKind::Const => false,
2813                    CtorKind::Fn => {
2814                        !self.r.field_idents(def_id).is_some_and(|field_ids| field_ids.is_empty())
2815                    }
2816                }
2817            };
2818
2819            let mut suggestable_variants = 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                .map(|(variant, kind)| match kind {
2824                    CtorKind::Const => variant,
2825                    CtorKind::Fn => format!("({variant}())"),
2826                })
2827                .collect::<Vec<_>>();
2828            suggestable_variants.sort();
2829            let no_suggestable_variant = suggestable_variants.is_empty();
2830
2831            if !no_suggestable_variant {
2832                let msg = if suggestable_variants.len() == 1 {
2833                    "you might have meant to use the following enum variant"
2834                } else {
2835                    "you might have meant to use one of the following enum variants"
2836                };
2837
2838                err.span_suggestions(
2839                    span,
2840                    msg,
2841                    suggestable_variants,
2842                    Applicability::MaybeIncorrect,
2843                );
2844            }
2845
2846            let mut suggestable_variants_with_placeholders = variant_ctors
2847                .iter()
2848                .filter(|(_, def_id, kind)| needs_placeholder(*def_id, *kind))
2849                .map(|(variant, _, kind)| (path_names_to_string(variant), kind))
2850                .filter_map(|(variant, kind)| match kind {
2851                    CtorKind::Fn => Some(format!("({variant}(/* fields */))")),
2852                    _ => None,
2853                })
2854                .collect::<Vec<_>>();
2855            suggestable_variants_with_placeholders.sort();
2856
2857            if !suggestable_variants_with_placeholders.is_empty() {
2858                let msg =
2859                    match (no_suggestable_variant, suggestable_variants_with_placeholders.len()) {
2860                        (true, 1) => "the following enum variant is available",
2861                        (true, _) => "the following enum variants are available",
2862                        (false, 1) => "alternatively, the following enum variant is available",
2863                        (false, _) => {
2864                            "alternatively, the following enum variants are also available"
2865                        }
2866                    };
2867
2868                err.span_suggestions(
2869                    span,
2870                    msg,
2871                    suggestable_variants_with_placeholders,
2872                    Applicability::HasPlaceholders,
2873                );
2874            }
2875        };
2876
2877        if def_id.is_local() {
2878            err.span_note(self.r.def_span(def_id), "the enum is defined here");
2879        }
2880    }
2881
2882    pub(crate) fn suggest_adding_generic_parameter(
2883        &self,
2884        path: &[Segment],
2885        source: PathSource<'_, '_, '_>,
2886    ) -> Option<(Span, &'static str, String, Applicability)> {
2887        let (ident, span) = match path {
2888            [segment]
2889                if !segment.has_generic_args
2890                    && segment.ident.name != kw::SelfUpper
2891                    && segment.ident.name != kw::Dyn =>
2892            {
2893                (segment.ident.to_string(), segment.ident.span)
2894            }
2895            _ => return None,
2896        };
2897        let mut iter = ident.chars().map(|c| c.is_uppercase());
2898        let single_uppercase_char =
2899            matches!(iter.next(), Some(true)) && matches!(iter.next(), None);
2900        if !self.diag_metadata.currently_processing_generic_args && !single_uppercase_char {
2901            return None;
2902        }
2903        match (self.diag_metadata.current_item, single_uppercase_char, self.diag_metadata.currently_processing_generic_args) {
2904            (Some(Item { kind: ItemKind::Fn(fn_), .. }), _, _) if fn_.ident.name == sym::main => {
2905                // Ignore `fn main()` as we don't want to suggest `fn main<T>()`
2906            }
2907            (
2908                Some(Item {
2909                    kind:
2910                        kind @ ItemKind::Fn(..)
2911                        | kind @ ItemKind::Enum(..)
2912                        | kind @ ItemKind::Struct(..)
2913                        | kind @ ItemKind::Union(..),
2914                    ..
2915                }),
2916                true, _
2917            )
2918            // Without the 2nd `true`, we'd suggest `impl <T>` for `impl T` when a type `T` isn't found
2919            | (Some(Item { kind: kind @ ItemKind::Impl(..), .. }), true, true)
2920            | (Some(Item { kind, .. }), false, _) => {
2921                if let Some(generics) = kind.generics() {
2922                    if span.overlaps(generics.span) {
2923                        // Avoid the following:
2924                        // error[E0405]: cannot find trait `A` in this scope
2925                        //  --> $DIR/typo-suggestion-named-underscore.rs:CC:LL
2926                        //   |
2927                        // L | fn foo<T: A>(x: T) {} // Shouldn't suggest underscore
2928                        //   |           ^- help: you might be missing a type parameter: `, A`
2929                        //   |           |
2930                        //   |           not found in this scope
2931                        return None;
2932                    }
2933
2934                    let (msg, sugg) = match source {
2935                        PathSource::Type | PathSource::PreciseCapturingArg(TypeNS) => {
2936                            ("you might be missing a type parameter", ident)
2937                        }
2938                        PathSource::Expr(_) | PathSource::PreciseCapturingArg(ValueNS) => (
2939                            "you might be missing a const parameter",
2940                            format!("const {ident}: /* Type */"),
2941                        ),
2942                        _ => return None,
2943                    };
2944                    let (span, sugg) = if let [.., param] = &generics.params[..] {
2945                        let span = if let [.., bound] = &param.bounds[..] {
2946                            bound.span()
2947                        } else if let GenericParam {
2948                            kind: GenericParamKind::Const { ty, span: _, default  }, ..
2949                        } = param {
2950                            default.as_ref().map(|def| def.value.span).unwrap_or(ty.span)
2951                        } else {
2952                            param.ident.span
2953                        };
2954                        (span, format!(", {sugg}"))
2955                    } else {
2956                        (generics.span, format!("<{sugg}>"))
2957                    };
2958                    // Do not suggest if this is coming from macro expansion.
2959                    if span.can_be_used_for_suggestions() {
2960                        return Some((
2961                            span.shrink_to_hi(),
2962                            msg,
2963                            sugg,
2964                            Applicability::MaybeIncorrect,
2965                        ));
2966                    }
2967                }
2968            }
2969            _ => {}
2970        }
2971        None
2972    }
2973
2974    /// Given the target `label`, search the `rib_index`th label rib for similarly named labels,
2975    /// optionally returning the closest match and whether it is reachable.
2976    pub(crate) fn suggestion_for_label_in_rib(
2977        &self,
2978        rib_index: usize,
2979        label: Ident,
2980    ) -> Option<LabelSuggestion> {
2981        // Are ribs from this `rib_index` within scope?
2982        let within_scope = self.is_label_valid_from_rib(rib_index);
2983
2984        let rib = &self.label_ribs[rib_index];
2985        let names = rib
2986            .bindings
2987            .iter()
2988            .filter(|(id, _)| id.span.eq_ctxt(label.span))
2989            .map(|(id, _)| id.name)
2990            .collect::<Vec<Symbol>>();
2991
2992        find_best_match_for_name(&names, label.name, None).map(|symbol| {
2993            // Upon finding a similar name, get the ident that it was from - the span
2994            // contained within helps make a useful diagnostic. In addition, determine
2995            // whether this candidate is within scope.
2996            let (ident, _) = rib.bindings.iter().find(|(ident, _)| ident.name == symbol).unwrap();
2997            (*ident, within_scope)
2998        })
2999    }
3000
3001    pub(crate) fn maybe_report_lifetime_uses(
3002        &mut self,
3003        generics_span: Span,
3004        params: &[ast::GenericParam],
3005    ) {
3006        for (param_index, param) in params.iter().enumerate() {
3007            let GenericParamKind::Lifetime = param.kind else { continue };
3008
3009            let def_id = self.r.local_def_id(param.id);
3010
3011            let use_set = self.lifetime_uses.remove(&def_id);
3012            debug!(
3013                "Use set for {:?}({:?} at {:?}) is {:?}",
3014                def_id, param.ident, param.ident.span, use_set
3015            );
3016
3017            let deletion_span = || {
3018                if params.len() == 1 {
3019                    // if sole lifetime, remove the entire `<>` brackets
3020                    Some(generics_span)
3021                } else if param_index == 0 {
3022                    // if removing within `<>` brackets, we also want to
3023                    // delete a leading or trailing comma as appropriate
3024                    match (
3025                        param.span().find_ancestor_inside(generics_span),
3026                        params[param_index + 1].span().find_ancestor_inside(generics_span),
3027                    ) {
3028                        (Some(param_span), Some(next_param_span)) => {
3029                            Some(param_span.to(next_param_span.shrink_to_lo()))
3030                        }
3031                        _ => None,
3032                    }
3033                } else {
3034                    // if removing within `<>` brackets, we also want to
3035                    // delete a leading or trailing comma as appropriate
3036                    match (
3037                        param.span().find_ancestor_inside(generics_span),
3038                        params[param_index - 1].span().find_ancestor_inside(generics_span),
3039                    ) {
3040                        (Some(param_span), Some(prev_param_span)) => {
3041                            Some(prev_param_span.shrink_to_hi().to(param_span))
3042                        }
3043                        _ => None,
3044                    }
3045                }
3046            };
3047            match use_set {
3048                Some(LifetimeUseSet::Many) => {}
3049                Some(LifetimeUseSet::One { use_span, use_ctxt }) => {
3050                    debug!(?param.ident, ?param.ident.span, ?use_span);
3051
3052                    let elidable = matches!(use_ctxt, LifetimeCtxt::Ref);
3053                    let deletion_span =
3054                        if param.bounds.is_empty() { deletion_span() } else { None };
3055
3056                    self.r.lint_buffer.buffer_lint(
3057                        lint::builtin::SINGLE_USE_LIFETIMES,
3058                        param.id,
3059                        param.ident.span,
3060                        lint::BuiltinLintDiag::SingleUseLifetime {
3061                            param_span: param.ident.span,
3062                            use_span: Some((use_span, elidable)),
3063                            deletion_span,
3064                            ident: param.ident,
3065                        },
3066                    );
3067                }
3068                None => {
3069                    debug!(?param.ident, ?param.ident.span);
3070                    let deletion_span = deletion_span();
3071
3072                    // if the lifetime originates from expanded code, we won't be able to remove it #104432
3073                    if deletion_span.is_some_and(|sp| !sp.in_derive_expansion()) {
3074                        self.r.lint_buffer.buffer_lint(
3075                            lint::builtin::UNUSED_LIFETIMES,
3076                            param.id,
3077                            param.ident.span,
3078                            lint::BuiltinLintDiag::SingleUseLifetime {
3079                                param_span: param.ident.span,
3080                                use_span: None,
3081                                deletion_span,
3082                                ident: param.ident,
3083                            },
3084                        );
3085                    }
3086                }
3087            }
3088        }
3089    }
3090
3091    pub(crate) fn emit_undeclared_lifetime_error(
3092        &self,
3093        lifetime_ref: &ast::Lifetime,
3094        outer_lifetime_ref: Option<Ident>,
3095    ) {
3096        debug_assert_ne!(lifetime_ref.ident.name, kw::UnderscoreLifetime);
3097        let mut err = if let Some(outer) = outer_lifetime_ref {
3098            struct_span_code_err!(
3099                self.r.dcx(),
3100                lifetime_ref.ident.span,
3101                E0401,
3102                "can't use generic parameters from outer item",
3103            )
3104            .with_span_label(lifetime_ref.ident.span, "use of generic parameter from outer item")
3105            .with_span_label(outer.span, "lifetime parameter from outer item")
3106        } else {
3107            struct_span_code_err!(
3108                self.r.dcx(),
3109                lifetime_ref.ident.span,
3110                E0261,
3111                "use of undeclared lifetime name `{}`",
3112                lifetime_ref.ident
3113            )
3114            .with_span_label(lifetime_ref.ident.span, "undeclared lifetime")
3115        };
3116
3117        // Check if this is a typo of `'static`.
3118        if edit_distance(lifetime_ref.ident.name.as_str(), "'static", 2).is_some() {
3119            err.span_suggestion_verbose(
3120                lifetime_ref.ident.span,
3121                "you may have misspelled the `'static` lifetime",
3122                "'static",
3123                Applicability::MachineApplicable,
3124            );
3125        } else {
3126            self.suggest_introducing_lifetime(
3127                &mut err,
3128                Some(lifetime_ref.ident),
3129                |err, _, span, message, suggestion, span_suggs| {
3130                    err.multipart_suggestion_verbose(
3131                        message,
3132                        std::iter::once((span, suggestion)).chain(span_suggs).collect(),
3133                        Applicability::MaybeIncorrect,
3134                    );
3135                    true
3136                },
3137            );
3138        }
3139
3140        err.emit();
3141    }
3142
3143    fn suggest_introducing_lifetime(
3144        &self,
3145        err: &mut Diag<'_>,
3146        name: Option<Ident>,
3147        suggest: impl Fn(
3148            &mut Diag<'_>,
3149            bool,
3150            Span,
3151            Cow<'static, str>,
3152            String,
3153            Vec<(Span, String)>,
3154        ) -> bool,
3155    ) {
3156        let mut suggest_note = true;
3157        for rib in self.lifetime_ribs.iter().rev() {
3158            let mut should_continue = true;
3159            match rib.kind {
3160                LifetimeRibKind::Generics { binder, span, kind } => {
3161                    // Avoid suggesting placing lifetime parameters on constant items unless the relevant
3162                    // feature is enabled. Suggest the parent item as a possible location if applicable.
3163                    if let LifetimeBinderKind::ConstItem = kind
3164                        && !self.r.tcx().features().generic_const_items()
3165                    {
3166                        continue;
3167                    }
3168
3169                    if !span.can_be_used_for_suggestions()
3170                        && suggest_note
3171                        && let Some(name) = name
3172                    {
3173                        suggest_note = false; // Avoid displaying the same help multiple times.
3174                        err.span_label(
3175                            span,
3176                            format!(
3177                                "lifetime `{name}` is missing in item created through this procedural macro",
3178                            ),
3179                        );
3180                        continue;
3181                    }
3182
3183                    let higher_ranked = matches!(
3184                        kind,
3185                        LifetimeBinderKind::FnPtrType
3186                            | LifetimeBinderKind::PolyTrait
3187                            | LifetimeBinderKind::WhereBound
3188                    );
3189
3190                    let mut rm_inner_binders: FxIndexSet<Span> = Default::default();
3191                    let (span, sugg) = if span.is_empty() {
3192                        let mut binder_idents: FxIndexSet<Ident> = Default::default();
3193                        binder_idents.insert(name.unwrap_or(Ident::from_str("'a")));
3194
3195                        // We need to special case binders in the following situation:
3196                        // Change `T: for<'a> Trait<T> + 'b` to `for<'a, 'b> T: Trait<T> + 'b`
3197                        // T: for<'a> Trait<T> + 'b
3198                        //    ^^^^^^^  remove existing inner binder `for<'a>`
3199                        // for<'a, 'b> T: Trait<T> + 'b
3200                        // ^^^^^^^^^^^  suggest outer binder `for<'a, 'b>`
3201                        if let LifetimeBinderKind::WhereBound = kind
3202                            && let Some(predicate) = self.diag_metadata.current_where_predicate
3203                            && let ast::WherePredicateKind::BoundPredicate(
3204                                ast::WhereBoundPredicate { bounded_ty, bounds, .. },
3205                            ) = &predicate.kind
3206                            && bounded_ty.id == binder
3207                        {
3208                            for bound in bounds {
3209                                if let ast::GenericBound::Trait(poly_trait_ref) = bound
3210                                    && let span = poly_trait_ref
3211                                        .span
3212                                        .with_hi(poly_trait_ref.trait_ref.path.span.lo())
3213                                    && !span.is_empty()
3214                                {
3215                                    rm_inner_binders.insert(span);
3216                                    poly_trait_ref.bound_generic_params.iter().for_each(|v| {
3217                                        binder_idents.insert(v.ident);
3218                                    });
3219                                }
3220                            }
3221                        }
3222
3223                        let binders_sugg: String = binder_idents
3224                            .into_iter()
3225                            .map(|ident| ident.to_string())
3226                            .intersperse(", ".to_owned())
3227                            .collect();
3228                        let sugg = format!(
3229                            "{}<{}>{}",
3230                            if higher_ranked { "for" } else { "" },
3231                            binders_sugg,
3232                            if higher_ranked { " " } else { "" },
3233                        );
3234                        (span, sugg)
3235                    } else {
3236                        let span = self
3237                            .r
3238                            .tcx
3239                            .sess
3240                            .source_map()
3241                            .span_through_char(span, '<')
3242                            .shrink_to_hi();
3243                        let sugg =
3244                            format!("{}, ", name.map(|i| i.to_string()).as_deref().unwrap_or("'a"));
3245                        (span, sugg)
3246                    };
3247
3248                    if higher_ranked {
3249                        let message = Cow::from(format!(
3250                            "consider making the {} lifetime-generic with a new `{}` lifetime",
3251                            kind.descr(),
3252                            name.map(|i| i.to_string()).as_deref().unwrap_or("'a"),
3253                        ));
3254                        should_continue = suggest(
3255                            err,
3256                            true,
3257                            span,
3258                            message,
3259                            sugg,
3260                            if !rm_inner_binders.is_empty() {
3261                                rm_inner_binders
3262                                    .into_iter()
3263                                    .map(|v| (v, "".to_string()))
3264                                    .collect::<Vec<_>>()
3265                            } else {
3266                                vec![]
3267                            },
3268                        );
3269                        err.note_once(
3270                            "for more information on higher-ranked polymorphism, visit \
3271                             https://doc.rust-lang.org/nomicon/hrtb.html",
3272                        );
3273                    } else if let Some(name) = name {
3274                        let message =
3275                            Cow::from(format!("consider introducing lifetime `{name}` here"));
3276                        should_continue = suggest(err, false, span, message, sugg, vec![]);
3277                    } else {
3278                        let message = Cow::from("consider introducing a named lifetime parameter");
3279                        should_continue = suggest(err, false, span, message, sugg, vec![]);
3280                    }
3281                }
3282                LifetimeRibKind::Item | LifetimeRibKind::ConstParamTy => break,
3283                _ => {}
3284            }
3285            if !should_continue {
3286                break;
3287            }
3288        }
3289    }
3290
3291    pub(crate) fn emit_non_static_lt_in_const_param_ty_error(&self, lifetime_ref: &ast::Lifetime) {
3292        self.r
3293            .dcx()
3294            .create_err(errors::ParamInTyOfConstParam {
3295                span: lifetime_ref.ident.span,
3296                name: lifetime_ref.ident.name,
3297            })
3298            .emit();
3299    }
3300
3301    /// Non-static lifetimes are prohibited in anonymous constants under `min_const_generics`.
3302    /// This function will emit an error if `generic_const_exprs` is not enabled, the body identified by
3303    /// `body_id` is an anonymous constant and `lifetime_ref` is non-static.
3304    pub(crate) fn emit_forbidden_non_static_lifetime_error(
3305        &self,
3306        cause: NoConstantGenericsReason,
3307        lifetime_ref: &ast::Lifetime,
3308    ) {
3309        match cause {
3310            NoConstantGenericsReason::IsEnumDiscriminant => {
3311                self.r
3312                    .dcx()
3313                    .create_err(errors::ParamInEnumDiscriminant {
3314                        span: lifetime_ref.ident.span,
3315                        name: lifetime_ref.ident.name,
3316                        param_kind: errors::ParamKindInEnumDiscriminant::Lifetime,
3317                    })
3318                    .emit();
3319            }
3320            NoConstantGenericsReason::NonTrivialConstArg => {
3321                assert!(!self.r.tcx.features().generic_const_exprs());
3322                self.r
3323                    .dcx()
3324                    .create_err(errors::ParamInNonTrivialAnonConst {
3325                        span: lifetime_ref.ident.span,
3326                        name: lifetime_ref.ident.name,
3327                        param_kind: errors::ParamKindInNonTrivialAnonConst::Lifetime,
3328                        help: self
3329                            .r
3330                            .tcx
3331                            .sess
3332                            .is_nightly_build()
3333                            .then_some(errors::ParamInNonTrivialAnonConstHelp),
3334                    })
3335                    .emit();
3336            }
3337        }
3338    }
3339
3340    pub(crate) fn report_missing_lifetime_specifiers(
3341        &mut self,
3342        lifetime_refs: Vec<MissingLifetime>,
3343        function_param_lifetimes: Option<(Vec<MissingLifetime>, Vec<ElisionFnParameter>)>,
3344    ) -> ErrorGuaranteed {
3345        let num_lifetimes: usize = lifetime_refs.iter().map(|lt| lt.count).sum();
3346        let spans: Vec<_> = lifetime_refs.iter().map(|lt| lt.span).collect();
3347
3348        let mut err = struct_span_code_err!(
3349            self.r.dcx(),
3350            spans,
3351            E0106,
3352            "missing lifetime specifier{}",
3353            pluralize!(num_lifetimes)
3354        );
3355        self.add_missing_lifetime_specifiers_label(
3356            &mut err,
3357            lifetime_refs,
3358            function_param_lifetimes,
3359        );
3360        err.emit()
3361    }
3362
3363    fn add_missing_lifetime_specifiers_label(
3364        &mut self,
3365        err: &mut Diag<'_>,
3366        lifetime_refs: Vec<MissingLifetime>,
3367        function_param_lifetimes: Option<(Vec<MissingLifetime>, Vec<ElisionFnParameter>)>,
3368    ) {
3369        for &lt in &lifetime_refs {
3370            err.span_label(
3371                lt.span,
3372                format!(
3373                    "expected {} lifetime parameter{}",
3374                    if lt.count == 1 { "named".to_string() } else { lt.count.to_string() },
3375                    pluralize!(lt.count),
3376                ),
3377            );
3378        }
3379
3380        let mut in_scope_lifetimes: Vec<_> = self
3381            .lifetime_ribs
3382            .iter()
3383            .rev()
3384            .take_while(|rib| {
3385                !matches!(rib.kind, LifetimeRibKind::Item | LifetimeRibKind::ConstParamTy)
3386            })
3387            .flat_map(|rib| rib.bindings.iter())
3388            .map(|(&ident, &res)| (ident, res))
3389            .filter(|(ident, _)| ident.name != kw::UnderscoreLifetime)
3390            .collect();
3391        debug!(?in_scope_lifetimes);
3392
3393        let mut maybe_static = false;
3394        debug!(?function_param_lifetimes);
3395        if let Some((param_lifetimes, params)) = &function_param_lifetimes {
3396            let elided_len = param_lifetimes.len();
3397            let num_params = params.len();
3398
3399            let mut m = String::new();
3400
3401            for (i, info) in params.iter().enumerate() {
3402                let ElisionFnParameter { ident, index, lifetime_count, span } = *info;
3403                debug_assert_ne!(lifetime_count, 0);
3404
3405                err.span_label(span, "");
3406
3407                if i != 0 {
3408                    if i + 1 < num_params {
3409                        m.push_str(", ");
3410                    } else if num_params == 2 {
3411                        m.push_str(" or ");
3412                    } else {
3413                        m.push_str(", or ");
3414                    }
3415                }
3416
3417                let help_name = if let Some(ident) = ident {
3418                    format!("`{ident}`")
3419                } else {
3420                    format!("argument {}", index + 1)
3421                };
3422
3423                if lifetime_count == 1 {
3424                    m.push_str(&help_name[..])
3425                } else {
3426                    m.push_str(&format!("one of {help_name}'s {lifetime_count} lifetimes")[..])
3427                }
3428            }
3429
3430            if num_params == 0 {
3431                err.help(
3432                    "this function's return type contains a borrowed value, but there is no value \
3433                     for it to be borrowed from",
3434                );
3435                if in_scope_lifetimes.is_empty() {
3436                    maybe_static = true;
3437                    in_scope_lifetimes = vec![(
3438                        Ident::with_dummy_span(kw::StaticLifetime),
3439                        (DUMMY_NODE_ID, LifetimeRes::Static),
3440                    )];
3441                }
3442            } else if elided_len == 0 {
3443                err.help(
3444                    "this function's return type contains a borrowed value with an elided \
3445                     lifetime, but the lifetime cannot be derived from the arguments",
3446                );
3447                if in_scope_lifetimes.is_empty() {
3448                    maybe_static = true;
3449                    in_scope_lifetimes = vec![(
3450                        Ident::with_dummy_span(kw::StaticLifetime),
3451                        (DUMMY_NODE_ID, LifetimeRes::Static),
3452                    )];
3453                }
3454            } else if num_params == 1 {
3455                err.help(format!(
3456                    "this function's return type contains a borrowed value, but the signature does \
3457                     not say which {m} it is borrowed from",
3458                ));
3459            } else {
3460                err.help(format!(
3461                    "this function's return type contains a borrowed value, but the signature does \
3462                     not say whether it is borrowed from {m}",
3463                ));
3464            }
3465        }
3466
3467        #[allow(rustc::symbol_intern_string_literal)]
3468        let existing_name = match &in_scope_lifetimes[..] {
3469            [] => Symbol::intern("'a"),
3470            [(existing, _)] => existing.name,
3471            _ => Symbol::intern("'lifetime"),
3472        };
3473
3474        let mut spans_suggs: Vec<_> = Vec::new();
3475        let build_sugg = |lt: MissingLifetime| match lt.kind {
3476            MissingLifetimeKind::Underscore => {
3477                debug_assert_eq!(lt.count, 1);
3478                (lt.span, existing_name.to_string())
3479            }
3480            MissingLifetimeKind::Ampersand => {
3481                debug_assert_eq!(lt.count, 1);
3482                (lt.span.shrink_to_hi(), format!("{existing_name} "))
3483            }
3484            MissingLifetimeKind::Comma => {
3485                let sugg: String = std::iter::repeat_n([existing_name.as_str(), ", "], lt.count)
3486                    .flatten()
3487                    .collect();
3488                (lt.span.shrink_to_hi(), sugg)
3489            }
3490            MissingLifetimeKind::Brackets => {
3491                let sugg: String = std::iter::once("<")
3492                    .chain(std::iter::repeat_n(existing_name.as_str(), lt.count).intersperse(", "))
3493                    .chain([">"])
3494                    .collect();
3495                (lt.span.shrink_to_hi(), sugg)
3496            }
3497        };
3498        for &lt in &lifetime_refs {
3499            spans_suggs.push(build_sugg(lt));
3500        }
3501        debug!(?spans_suggs);
3502        match in_scope_lifetimes.len() {
3503            0 => {
3504                if let Some((param_lifetimes, _)) = function_param_lifetimes {
3505                    for lt in param_lifetimes {
3506                        spans_suggs.push(build_sugg(lt))
3507                    }
3508                }
3509                self.suggest_introducing_lifetime(
3510                    err,
3511                    None,
3512                    |err, higher_ranked, span, message, intro_sugg, _| {
3513                        err.multipart_suggestion_verbose(
3514                            message,
3515                            std::iter::once((span, intro_sugg))
3516                                .chain(spans_suggs.clone())
3517                                .collect(),
3518                            Applicability::MaybeIncorrect,
3519                        );
3520                        higher_ranked
3521                    },
3522                );
3523            }
3524            1 => {
3525                let post = if maybe_static {
3526                    let owned = if let [lt] = &lifetime_refs[..]
3527                        && lt.kind != MissingLifetimeKind::Ampersand
3528                    {
3529                        ", or if you will only have owned values"
3530                    } else {
3531                        ""
3532                    };
3533                    format!(
3534                        ", but this is uncommon unless you're returning a borrowed value from a \
3535                         `const` or a `static`{owned}",
3536                    )
3537                } else {
3538                    String::new()
3539                };
3540                err.multipart_suggestion_verbose(
3541                    format!("consider using the `{existing_name}` lifetime{post}"),
3542                    spans_suggs,
3543                    Applicability::MaybeIncorrect,
3544                );
3545                if maybe_static {
3546                    // FIXME: what follows are general suggestions, but we'd want to perform some
3547                    // minimal flow analysis to provide more accurate suggestions. For example, if
3548                    // we identified that the return expression references only one argument, we
3549                    // would suggest borrowing only that argument, and we'd skip the prior
3550                    // "use `'static`" suggestion entirely.
3551                    if let [lt] = &lifetime_refs[..]
3552                        && (lt.kind == MissingLifetimeKind::Ampersand
3553                            || lt.kind == MissingLifetimeKind::Underscore)
3554                    {
3555                        let pre = if lt.kind == MissingLifetimeKind::Ampersand
3556                            && let Some((kind, _span)) = self.diag_metadata.current_function
3557                            && let FnKind::Fn(_, _, ast::Fn { sig, .. }) = kind
3558                            && !sig.decl.inputs.is_empty()
3559                            && let sugg = sig
3560                                .decl
3561                                .inputs
3562                                .iter()
3563                                .filter_map(|param| {
3564                                    if param.ty.span.contains(lt.span) {
3565                                        // We don't want to suggest `fn elision(_: &fn() -> &i32)`
3566                                        // when we have `fn elision(_: fn() -> &i32)`
3567                                        None
3568                                    } else if let TyKind::CVarArgs = param.ty.kind {
3569                                        // Don't suggest `&...` for ffi fn with varargs
3570                                        None
3571                                    } else if let TyKind::ImplTrait(..) = &param.ty.kind {
3572                                        // We handle these in the next `else if` branch.
3573                                        None
3574                                    } else {
3575                                        Some((param.ty.span.shrink_to_lo(), "&".to_string()))
3576                                    }
3577                                })
3578                                .collect::<Vec<_>>()
3579                            && !sugg.is_empty()
3580                        {
3581                            let (the, s) = if sig.decl.inputs.len() == 1 {
3582                                ("the", "")
3583                            } else {
3584                                ("one of the", "s")
3585                            };
3586                            err.multipart_suggestion_verbose(
3587                                format!(
3588                                    "instead, you are more likely to want to change {the} \
3589                                     argument{s} to be borrowed...",
3590                                ),
3591                                sugg,
3592                                Applicability::MaybeIncorrect,
3593                            );
3594                            "...or alternatively, you might want"
3595                        } else if (lt.kind == MissingLifetimeKind::Ampersand
3596                            || lt.kind == MissingLifetimeKind::Underscore)
3597                            && let Some((kind, _span)) = self.diag_metadata.current_function
3598                            && let FnKind::Fn(_, _, ast::Fn { sig, .. }) = kind
3599                            && let ast::FnRetTy::Ty(ret_ty) = &sig.decl.output
3600                            && !sig.decl.inputs.is_empty()
3601                            && let arg_refs = sig
3602                                .decl
3603                                .inputs
3604                                .iter()
3605                                .filter_map(|param| match &param.ty.kind {
3606                                    TyKind::ImplTrait(_, bounds) => Some(bounds),
3607                                    _ => None,
3608                                })
3609                                .flat_map(|bounds| bounds.into_iter())
3610                                .collect::<Vec<_>>()
3611                            && !arg_refs.is_empty()
3612                        {
3613                            // We have a situation like
3614                            // fn g(mut x: impl Iterator<Item = &()>) -> Option<&()>
3615                            // So we look at every ref in the trait bound. If there's any, we
3616                            // suggest
3617                            // fn g<'a>(mut x: impl Iterator<Item = &'a ()>) -> Option<&'a ()>
3618                            let mut lt_finder =
3619                                LifetimeFinder { lifetime: lt.span, found: None, seen: vec![] };
3620                            for bound in arg_refs {
3621                                if let ast::GenericBound::Trait(trait_ref) = bound {
3622                                    lt_finder.visit_trait_ref(&trait_ref.trait_ref);
3623                                }
3624                            }
3625                            lt_finder.visit_ty(ret_ty);
3626                            let spans_suggs: Vec<_> = lt_finder
3627                                .seen
3628                                .iter()
3629                                .filter_map(|ty| match &ty.kind {
3630                                    TyKind::Ref(_, mut_ty) => {
3631                                        let span = ty.span.with_hi(mut_ty.ty.span.lo());
3632                                        Some((span, "&'a ".to_string()))
3633                                    }
3634                                    _ => None,
3635                                })
3636                                .collect();
3637                            self.suggest_introducing_lifetime(
3638                                err,
3639                                None,
3640                                |err, higher_ranked, span, message, intro_sugg, _| {
3641                                    err.multipart_suggestion_verbose(
3642                                        message,
3643                                        std::iter::once((span, intro_sugg))
3644                                            .chain(spans_suggs.clone())
3645                                            .collect(),
3646                                        Applicability::MaybeIncorrect,
3647                                    );
3648                                    higher_ranked
3649                                },
3650                            );
3651                            "alternatively, you might want"
3652                        } else {
3653                            "instead, you are more likely to want"
3654                        };
3655                        let mut owned_sugg = lt.kind == MissingLifetimeKind::Ampersand;
3656                        let mut sugg = vec![(lt.span, String::new())];
3657                        if let Some((kind, _span)) = self.diag_metadata.current_function
3658                            && let FnKind::Fn(_, _, ast::Fn { sig, .. }) = kind
3659                            && let ast::FnRetTy::Ty(ty) = &sig.decl.output
3660                        {
3661                            let mut lt_finder =
3662                                LifetimeFinder { lifetime: lt.span, found: None, seen: vec![] };
3663                            lt_finder.visit_ty(&ty);
3664
3665                            if let [Ty { span, kind: TyKind::Ref(_, mut_ty), .. }] =
3666                                &lt_finder.seen[..]
3667                            {
3668                                // We might have a situation like
3669                                // fn g(mut x: impl Iterator<Item = &'_ ()>) -> Option<&'_ ()>
3670                                // but `lt.span` only points at `'_`, so to suggest `-> Option<()>`
3671                                // we need to find a more accurate span to end up with
3672                                // fn g<'a>(mut x: impl Iterator<Item = &'_ ()>) -> Option<()>
3673                                sugg = vec![(span.with_hi(mut_ty.ty.span.lo()), String::new())];
3674                                owned_sugg = true;
3675                            }
3676                            if let Some(ty) = lt_finder.found {
3677                                if let TyKind::Path(None, path) = &ty.kind {
3678                                    // Check if the path being borrowed is likely to be owned.
3679                                    let path: Vec<_> = Segment::from_path(path);
3680                                    match self.resolve_path(
3681                                        &path,
3682                                        Some(TypeNS),
3683                                        None,
3684                                        PathSource::Type,
3685                                    ) {
3686                                        PathResult::Module(ModuleOrUniformRoot::Module(module)) => {
3687                                            match module.res() {
3688                                                Some(Res::PrimTy(PrimTy::Str)) => {
3689                                                    // Don't suggest `-> str`, suggest `-> String`.
3690                                                    sugg = vec![(
3691                                                        lt.span.with_hi(ty.span.hi()),
3692                                                        "String".to_string(),
3693                                                    )];
3694                                                }
3695                                                Some(Res::PrimTy(..)) => {}
3696                                                Some(Res::Def(
3697                                                    DefKind::Struct
3698                                                    | DefKind::Union
3699                                                    | DefKind::Enum
3700                                                    | DefKind::ForeignTy
3701                                                    | DefKind::AssocTy
3702                                                    | DefKind::OpaqueTy
3703                                                    | DefKind::TyParam,
3704                                                    _,
3705                                                )) => {}
3706                                                _ => {
3707                                                    // Do not suggest in all other cases.
3708                                                    owned_sugg = false;
3709                                                }
3710                                            }
3711                                        }
3712                                        PathResult::NonModule(res) => {
3713                                            match res.base_res() {
3714                                                Res::PrimTy(PrimTy::Str) => {
3715                                                    // Don't suggest `-> str`, suggest `-> String`.
3716                                                    sugg = vec![(
3717                                                        lt.span.with_hi(ty.span.hi()),
3718                                                        "String".to_string(),
3719                                                    )];
3720                                                }
3721                                                Res::PrimTy(..) => {}
3722                                                Res::Def(
3723                                                    DefKind::Struct
3724                                                    | DefKind::Union
3725                                                    | DefKind::Enum
3726                                                    | DefKind::ForeignTy
3727                                                    | DefKind::AssocTy
3728                                                    | DefKind::OpaqueTy
3729                                                    | DefKind::TyParam,
3730                                                    _,
3731                                                ) => {}
3732                                                _ => {
3733                                                    // Do not suggest in all other cases.
3734                                                    owned_sugg = false;
3735                                                }
3736                                            }
3737                                        }
3738                                        _ => {
3739                                            // Do not suggest in all other cases.
3740                                            owned_sugg = false;
3741                                        }
3742                                    }
3743                                }
3744                                if let TyKind::Slice(inner_ty) = &ty.kind {
3745                                    // Don't suggest `-> [T]`, suggest `-> Vec<T>`.
3746                                    sugg = vec![
3747                                        (lt.span.with_hi(inner_ty.span.lo()), "Vec<".to_string()),
3748                                        (ty.span.with_lo(inner_ty.span.hi()), ">".to_string()),
3749                                    ];
3750                                }
3751                            }
3752                        }
3753                        if owned_sugg {
3754                            err.multipart_suggestion_verbose(
3755                                format!("{pre} to return an owned value"),
3756                                sugg,
3757                                Applicability::MaybeIncorrect,
3758                            );
3759                        }
3760                    }
3761                }
3762            }
3763            _ => {
3764                let lifetime_spans: Vec<_> =
3765                    in_scope_lifetimes.iter().map(|(ident, _)| ident.span).collect();
3766                err.span_note(lifetime_spans, "these named lifetimes are available to use");
3767
3768                if spans_suggs.len() > 0 {
3769                    // This happens when we have `Foo<T>` where we point at the space before `T`,
3770                    // but this can be confusing so we give a suggestion with placeholders.
3771                    err.multipart_suggestion_verbose(
3772                        "consider using one of the available lifetimes here",
3773                        spans_suggs,
3774                        Applicability::HasPlaceholders,
3775                    );
3776                }
3777            }
3778        }
3779    }
3780}
3781
3782fn mk_where_bound_predicate(
3783    path: &Path,
3784    poly_trait_ref: &ast::PolyTraitRef,
3785    ty: &Ty,
3786) -> Option<ast::WhereBoundPredicate> {
3787    let modified_segments = {
3788        let mut segments = path.segments.clone();
3789        let [preceding @ .., second_last, last] = segments.as_mut_slice() else {
3790            return None;
3791        };
3792        let mut segments = ThinVec::from(preceding);
3793
3794        let added_constraint = ast::AngleBracketedArg::Constraint(ast::AssocItemConstraint {
3795            id: DUMMY_NODE_ID,
3796            ident: last.ident,
3797            gen_args: None,
3798            kind: ast::AssocItemConstraintKind::Equality {
3799                term: ast::Term::Ty(Box::new(ast::Ty {
3800                    kind: ast::TyKind::Path(None, poly_trait_ref.trait_ref.path.clone()),
3801                    id: DUMMY_NODE_ID,
3802                    span: DUMMY_SP,
3803                    tokens: None,
3804                })),
3805            },
3806            span: DUMMY_SP,
3807        });
3808
3809        match second_last.args.as_deref_mut() {
3810            Some(ast::GenericArgs::AngleBracketed(ast::AngleBracketedArgs { args, .. })) => {
3811                args.push(added_constraint);
3812            }
3813            Some(_) => return None,
3814            None => {
3815                second_last.args =
3816                    Some(Box::new(ast::GenericArgs::AngleBracketed(ast::AngleBracketedArgs {
3817                        args: ThinVec::from([added_constraint]),
3818                        span: DUMMY_SP,
3819                    })));
3820            }
3821        }
3822
3823        segments.push(second_last.clone());
3824        segments
3825    };
3826
3827    let new_where_bound_predicate = ast::WhereBoundPredicate {
3828        bound_generic_params: ThinVec::new(),
3829        bounded_ty: Box::new(ty.clone()),
3830        bounds: vec![ast::GenericBound::Trait(ast::PolyTraitRef {
3831            bound_generic_params: ThinVec::new(),
3832            modifiers: ast::TraitBoundModifiers::NONE,
3833            trait_ref: ast::TraitRef {
3834                path: ast::Path { segments: modified_segments, span: DUMMY_SP, tokens: None },
3835                ref_id: DUMMY_NODE_ID,
3836            },
3837            span: DUMMY_SP,
3838            parens: ast::Parens::No,
3839        })],
3840    };
3841
3842    Some(new_where_bound_predicate)
3843}
3844
3845/// Report lifetime/lifetime shadowing as an error.
3846pub(super) fn signal_lifetime_shadowing(sess: &Session, orig: Ident, shadower: Ident) {
3847    struct_span_code_err!(
3848        sess.dcx(),
3849        shadower.span,
3850        E0496,
3851        "lifetime name `{}` shadows a lifetime name that is already in scope",
3852        orig.name,
3853    )
3854    .with_span_label(orig.span, "first declared here")
3855    .with_span_label(shadower.span, format!("lifetime `{}` already in scope", orig.name))
3856    .emit();
3857}
3858
3859struct LifetimeFinder<'ast> {
3860    lifetime: Span,
3861    found: Option<&'ast Ty>,
3862    seen: Vec<&'ast Ty>,
3863}
3864
3865impl<'ast> Visitor<'ast> for LifetimeFinder<'ast> {
3866    fn visit_ty(&mut self, t: &'ast Ty) {
3867        if let TyKind::Ref(_, mut_ty) | TyKind::PinnedRef(_, mut_ty) = &t.kind {
3868            self.seen.push(t);
3869            if t.span.lo() == self.lifetime.lo() {
3870                self.found = Some(&mut_ty.ty);
3871            }
3872        }
3873        walk_ty(self, t)
3874    }
3875}
3876
3877/// Shadowing involving a label is only a warning for historical reasons.
3878//FIXME: make this a proper lint.
3879pub(super) fn signal_label_shadowing(sess: &Session, orig: Span, shadower: Ident) {
3880    let name = shadower.name;
3881    let shadower = shadower.span;
3882    sess.dcx()
3883        .struct_span_warn(
3884            shadower,
3885            format!("label name `{name}` shadows a label name that is already in scope"),
3886        )
3887        .with_span_label(orig, "first declared here")
3888        .with_span_label(shadower, format!("label `{name}` already in scope"))
3889        .emit();
3890}