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 is_accessible = self.r.is_accessible_from(ctor_vis, self.parent_scope.module);
1946                if !is_expected(ctor_def) || is_accessible {
1947                    return true;
1948                }
1949
1950                let field_spans = match source {
1951                    // e.g. `if let Enum::TupleVariant(field1, field2) = _`
1952                    PathSource::TupleStruct(_, pattern_spans) => {
1953                        err.primary_message(
1954                            "cannot match against a tuple struct which contains private fields",
1955                        );
1956
1957                        // Use spans of the tuple struct pattern.
1958                        Some(Vec::from(pattern_spans))
1959                    }
1960                    // e.g. `let _ = Enum::TupleVariant(field1, field2);`
1961                    PathSource::Expr(Some(Expr {
1962                        kind: ExprKind::Call(path, args),
1963                        span: call_span,
1964                        ..
1965                    })) => {
1966                        err.primary_message(
1967                            "cannot initialize a tuple struct which contains private fields",
1968                        );
1969                        self.suggest_alternative_construction_methods(
1970                            def_id,
1971                            err,
1972                            path.span,
1973                            *call_span,
1974                            &args[..],
1975                        );
1976                        // Use spans of the tuple struct definition.
1977                        self.r
1978                            .field_idents(def_id)
1979                            .map(|fields| fields.iter().map(|f| f.span).collect::<Vec<_>>())
1980                    }
1981                    _ => None,
1982                };
1983
1984                if let Some(spans) =
1985                    field_spans.filter(|spans| spans.len() > 0 && fields.len() == spans.len())
1986                {
1987                    let non_visible_spans: Vec<Span> = iter::zip(&fields, &spans)
1988                        .filter(|(vis, _)| {
1989                            !self.r.is_accessible_from(**vis, self.parent_scope.module)
1990                        })
1991                        .map(|(_, span)| *span)
1992                        .collect();
1993
1994                    if non_visible_spans.len() > 0 {
1995                        if let Some(fields) = self.r.field_visibility_spans.get(&def_id) {
1996                            err.multipart_suggestion_verbose(
1997                                format!(
1998                                    "consider making the field{} publicly accessible",
1999                                    pluralize!(fields.len())
2000                                ),
2001                                fields.iter().map(|span| (*span, "pub ".to_string())).collect(),
2002                                Applicability::MaybeIncorrect,
2003                            );
2004                        }
2005
2006                        let mut m: MultiSpan = non_visible_spans.clone().into();
2007                        non_visible_spans
2008                            .into_iter()
2009                            .for_each(|s| m.push_span_label(s, "private field"));
2010                        err.span_note(m, "constructor is not visible here due to private fields");
2011                    }
2012
2013                    return true;
2014                }
2015
2016                err.span_label(span, "constructor is not visible here due to private fields");
2017            }
2018            (Res::Def(DefKind::Union | DefKind::Variant, def_id), _) if ns == ValueNS => {
2019                bad_struct_syntax_suggestion(self, err, def_id);
2020            }
2021            (Res::Def(DefKind::Ctor(_, CtorKind::Const), def_id), _) if ns == ValueNS => {
2022                match source {
2023                    PathSource::Expr(_) | PathSource::TupleStruct(..) | PathSource::Pat => {
2024                        let span = find_span(&source, err);
2025                        err.span_label(
2026                            self.r.def_span(def_id),
2027                            format!("`{path_str}` defined here"),
2028                        );
2029                        err.span_suggestion(
2030                            span,
2031                            "use this syntax instead",
2032                            path_str,
2033                            Applicability::MaybeIncorrect,
2034                        );
2035                    }
2036                    _ => return false,
2037                }
2038            }
2039            (Res::Def(DefKind::Ctor(_, CtorKind::Fn), ctor_def_id), _) if ns == ValueNS => {
2040                let def_id = self.r.tcx.parent(ctor_def_id);
2041                err.span_label(self.r.def_span(def_id), format!("`{path_str}` defined here"));
2042                let fields = self.r.field_idents(def_id).map_or_else(
2043                    || "/* fields */".to_string(),
2044                    |field_ids| vec!["_"; field_ids.len()].join(", "),
2045                );
2046                err.span_suggestion(
2047                    span,
2048                    "use the tuple variant pattern syntax instead",
2049                    format!("{path_str}({fields})"),
2050                    Applicability::HasPlaceholders,
2051                );
2052            }
2053            (Res::SelfTyParam { .. } | Res::SelfTyAlias { .. }, _) if ns == ValueNS => {
2054                err.span_label(span, fallback_label.to_string());
2055                err.note("can't use `Self` as a constructor, you must use the implemented struct");
2056            }
2057            (
2058                Res::Def(DefKind::TyAlias | DefKind::AssocTy, _),
2059                PathSource::TraitItem(ValueNS, PathSource::TupleStruct(whole, args)),
2060            ) => {
2061                err.note("can't use a type alias as tuple pattern");
2062
2063                let mut suggestion = Vec::new();
2064
2065                if let &&[first, ..] = args
2066                    && let &&[.., last] = args
2067                {
2068                    suggestion.extend([
2069                        // "0: " has to be included here so that the fix is machine applicable.
2070                        //
2071                        // If this would only add " { " and then the code below add "0: ",
2072                        // rustfix would crash, because end of this suggestion is the same as start
2073                        // of the suggestion below. Thus, we have to merge these...
2074                        (span.between(first), " { 0: ".to_owned()),
2075                        (last.between(whole.shrink_to_hi()), " }".to_owned()),
2076                    ]);
2077
2078                    suggestion.extend(
2079                        args.iter()
2080                            .enumerate()
2081                            .skip(1) // See above
2082                            .map(|(index, &arg)| (arg.shrink_to_lo(), format!("{index}: "))),
2083                    )
2084                } else {
2085                    suggestion.push((span.between(whole.shrink_to_hi()), " {}".to_owned()));
2086                }
2087
2088                err.multipart_suggestion(
2089                    "use struct pattern instead",
2090                    suggestion,
2091                    Applicability::MachineApplicable,
2092                );
2093            }
2094            (
2095                Res::Def(DefKind::TyAlias | DefKind::AssocTy, _),
2096                PathSource::TraitItem(
2097                    ValueNS,
2098                    PathSource::Expr(Some(ast::Expr {
2099                        span: whole,
2100                        kind: ast::ExprKind::Call(_, args),
2101                        ..
2102                    })),
2103                ),
2104            ) => {
2105                err.note("can't use a type alias as a constructor");
2106
2107                let mut suggestion = Vec::new();
2108
2109                if let [first, ..] = &**args
2110                    && let [.., last] = &**args
2111                {
2112                    suggestion.extend([
2113                        // "0: " has to be included here so that the fix is machine applicable.
2114                        //
2115                        // If this would only add " { " and then the code below add "0: ",
2116                        // rustfix would crash, because end of this suggestion is the same as start
2117                        // of the suggestion below. Thus, we have to merge these...
2118                        (span.between(first.span), " { 0: ".to_owned()),
2119                        (last.span.between(whole.shrink_to_hi()), " }".to_owned()),
2120                    ]);
2121
2122                    suggestion.extend(
2123                        args.iter()
2124                            .enumerate()
2125                            .skip(1) // See above
2126                            .map(|(index, arg)| (arg.span.shrink_to_lo(), format!("{index}: "))),
2127                    )
2128                } else {
2129                    suggestion.push((span.between(whole.shrink_to_hi()), " {}".to_owned()));
2130                }
2131
2132                err.multipart_suggestion(
2133                    "use struct expression instead",
2134                    suggestion,
2135                    Applicability::MachineApplicable,
2136                );
2137            }
2138            _ => return false,
2139        }
2140        true
2141    }
2142
2143    fn suggest_alternative_construction_methods(
2144        &mut self,
2145        def_id: DefId,
2146        err: &mut Diag<'_>,
2147        path_span: Span,
2148        call_span: Span,
2149        args: &[Box<Expr>],
2150    ) {
2151        if def_id.is_local() {
2152            // Doing analysis on local `DefId`s would cause infinite recursion.
2153            return;
2154        }
2155        // Look at all the associated functions without receivers in the type's
2156        // inherent impls to look for builders that return `Self`
2157        let mut items = self
2158            .r
2159            .tcx
2160            .inherent_impls(def_id)
2161            .iter()
2162            .flat_map(|i| self.r.tcx.associated_items(i).in_definition_order())
2163            // Only assoc fn with no receivers.
2164            .filter(|item| item.is_fn() && !item.is_method())
2165            .filter_map(|item| {
2166                // Only assoc fns that return `Self`
2167                let fn_sig = self.r.tcx.fn_sig(item.def_id).skip_binder();
2168                // Don't normalize the return type, because that can cause cycle errors.
2169                let ret_ty = fn_sig.output().skip_binder();
2170                let ty::Adt(def, _args) = ret_ty.kind() else {
2171                    return None;
2172                };
2173                let input_len = fn_sig.inputs().skip_binder().len();
2174                if def.did() != def_id {
2175                    return None;
2176                }
2177                let name = item.name();
2178                let order = !name.as_str().starts_with("new");
2179                Some((order, name, input_len))
2180            })
2181            .collect::<Vec<_>>();
2182        items.sort_by_key(|(order, _, _)| *order);
2183        let suggestion = |name, args| {
2184            format!(
2185                "::{name}({})",
2186                std::iter::repeat("_").take(args).collect::<Vec<_>>().join(", ")
2187            )
2188        };
2189        match &items[..] {
2190            [] => {}
2191            [(_, name, len)] if *len == args.len() => {
2192                err.span_suggestion_verbose(
2193                    path_span.shrink_to_hi(),
2194                    format!("you might have meant to use the `{name}` associated function",),
2195                    format!("::{name}"),
2196                    Applicability::MaybeIncorrect,
2197                );
2198            }
2199            [(_, name, len)] => {
2200                err.span_suggestion_verbose(
2201                    path_span.shrink_to_hi().with_hi(call_span.hi()),
2202                    format!("you might have meant to use the `{name}` associated function",),
2203                    suggestion(name, *len),
2204                    Applicability::MaybeIncorrect,
2205                );
2206            }
2207            _ => {
2208                err.span_suggestions_with_style(
2209                    path_span.shrink_to_hi().with_hi(call_span.hi()),
2210                    "you might have meant to use an associated function to build this type",
2211                    items.iter().map(|(_, name, len)| suggestion(name, *len)),
2212                    Applicability::MaybeIncorrect,
2213                    SuggestionStyle::ShowAlways,
2214                );
2215            }
2216        }
2217        // We'd ideally use `type_implements_trait` but don't have access to
2218        // the trait solver here. We can't use `get_diagnostic_item` or
2219        // `all_traits` in resolve either. So instead we abuse the import
2220        // suggestion machinery to get `std::default::Default` and perform some
2221        // checks to confirm that we got *only* that trait. We then see if the
2222        // Adt we have has a direct implementation of `Default`. If so, we
2223        // provide a structured suggestion.
2224        let default_trait = self
2225            .r
2226            .lookup_import_candidates(
2227                Ident::with_dummy_span(sym::Default),
2228                Namespace::TypeNS,
2229                &self.parent_scope,
2230                &|res: Res| matches!(res, Res::Def(DefKind::Trait, _)),
2231            )
2232            .iter()
2233            .filter_map(|candidate| candidate.did)
2234            .find(|did| {
2235                self.r
2236                    .tcx
2237                    .get_attrs(*did, sym::rustc_diagnostic_item)
2238                    .any(|attr| attr.value_str() == Some(sym::Default))
2239            });
2240        let Some(default_trait) = default_trait else {
2241            return;
2242        };
2243        if self
2244            .r
2245            .extern_crate_map
2246            .items()
2247            // FIXME: This doesn't include impls like `impl Default for String`.
2248            .flat_map(|(_, crate_)| self.r.tcx.implementations_of_trait((*crate_, default_trait)))
2249            .filter_map(|(_, simplified_self_ty)| *simplified_self_ty)
2250            .filter_map(|simplified_self_ty| match simplified_self_ty {
2251                SimplifiedType::Adt(did) => Some(did),
2252                _ => None,
2253            })
2254            .any(|did| did == def_id)
2255        {
2256            err.multipart_suggestion(
2257                "consider using the `Default` trait",
2258                vec![
2259                    (path_span.shrink_to_lo(), "<".to_string()),
2260                    (
2261                        path_span.shrink_to_hi().with_hi(call_span.hi()),
2262                        " as std::default::Default>::default()".to_string(),
2263                    ),
2264                ],
2265                Applicability::MaybeIncorrect,
2266            );
2267        }
2268    }
2269
2270    fn has_private_fields(&self, def_id: DefId) -> bool {
2271        let fields = match def_id.as_local() {
2272            Some(def_id) => self.r.struct_constructors.get(&def_id).cloned().map(|(_, _, f)| f),
2273            None => Some(
2274                self.r
2275                    .tcx
2276                    .associated_item_def_ids(def_id)
2277                    .iter()
2278                    .map(|field_id| self.r.tcx.visibility(field_id))
2279                    .collect(),
2280            ),
2281        };
2282
2283        fields.is_some_and(|fields| {
2284            fields.iter().any(|vis| !self.r.is_accessible_from(*vis, self.parent_scope.module))
2285        })
2286    }
2287
2288    /// Given the target `ident` and `kind`, search for the similarly named associated item
2289    /// in `self.current_trait_ref`.
2290    pub(crate) fn find_similarly_named_assoc_item(
2291        &mut self,
2292        ident: Symbol,
2293        kind: &AssocItemKind,
2294    ) -> Option<Symbol> {
2295        let (module, _) = self.current_trait_ref.as_ref()?;
2296        if ident == kw::Underscore {
2297            // We do nothing for `_`.
2298            return None;
2299        }
2300
2301        let targets = self
2302            .r
2303            .resolutions(*module)
2304            .borrow()
2305            .iter()
2306            .filter_map(|(key, res)| {
2307                res.borrow().best_binding().map(|binding| (key, binding.res()))
2308            })
2309            .filter(|(_, res)| match (kind, res) {
2310                (AssocItemKind::Const(..), Res::Def(DefKind::AssocConst, _)) => true,
2311                (AssocItemKind::Fn(_), Res::Def(DefKind::AssocFn, _)) => true,
2312                (AssocItemKind::Type(..), Res::Def(DefKind::AssocTy, _)) => true,
2313                (AssocItemKind::Delegation(_), Res::Def(DefKind::AssocFn, _)) => true,
2314                _ => false,
2315            })
2316            .map(|(key, _)| key.ident.name)
2317            .collect::<Vec<_>>();
2318
2319        find_best_match_for_name(&targets, ident, None)
2320    }
2321
2322    fn lookup_assoc_candidate<FilterFn>(
2323        &mut self,
2324        ident: Ident,
2325        ns: Namespace,
2326        filter_fn: FilterFn,
2327        called: bool,
2328    ) -> Option<AssocSuggestion>
2329    where
2330        FilterFn: Fn(Res) -> bool,
2331    {
2332        fn extract_node_id(t: &Ty) -> Option<NodeId> {
2333            match t.kind {
2334                TyKind::Path(None, _) => Some(t.id),
2335                TyKind::Ref(_, ref mut_ty) => extract_node_id(&mut_ty.ty),
2336                // This doesn't handle the remaining `Ty` variants as they are not
2337                // that commonly the self_type, it might be interesting to provide
2338                // support for those in future.
2339                _ => None,
2340            }
2341        }
2342        // Fields are generally expected in the same contexts as locals.
2343        if filter_fn(Res::Local(ast::DUMMY_NODE_ID)) {
2344            if let Some(node_id) =
2345                self.diag_metadata.current_self_type.as_ref().and_then(extract_node_id)
2346                && let Some(resolution) = self.r.partial_res_map.get(&node_id)
2347                && let Some(Res::Def(DefKind::Struct | DefKind::Union, did)) = resolution.full_res()
2348                && let Some(fields) = self.r.field_idents(did)
2349                && let Some(field) = fields.iter().find(|id| ident.name == id.name)
2350            {
2351                // Look for a field with the same name in the current self_type.
2352                return Some(AssocSuggestion::Field(field.span));
2353            }
2354        }
2355
2356        if let Some(items) = self.diag_metadata.current_trait_assoc_items {
2357            for assoc_item in items {
2358                if let Some(assoc_ident) = assoc_item.kind.ident()
2359                    && assoc_ident == ident
2360                {
2361                    return Some(match &assoc_item.kind {
2362                        ast::AssocItemKind::Const(..) => AssocSuggestion::AssocConst,
2363                        ast::AssocItemKind::Fn(box ast::Fn { sig, .. }) if sig.decl.has_self() => {
2364                            AssocSuggestion::MethodWithSelf { called }
2365                        }
2366                        ast::AssocItemKind::Fn(..) => AssocSuggestion::AssocFn { called },
2367                        ast::AssocItemKind::Type(..) => AssocSuggestion::AssocType,
2368                        ast::AssocItemKind::Delegation(..)
2369                            if self
2370                                .r
2371                                .delegation_fn_sigs
2372                                .get(&self.r.local_def_id(assoc_item.id))
2373                                .is_some_and(|sig| sig.has_self) =>
2374                        {
2375                            AssocSuggestion::MethodWithSelf { called }
2376                        }
2377                        ast::AssocItemKind::Delegation(..) => AssocSuggestion::AssocFn { called },
2378                        ast::AssocItemKind::MacCall(_) | ast::AssocItemKind::DelegationMac(..) => {
2379                            continue;
2380                        }
2381                    });
2382                }
2383            }
2384        }
2385
2386        // Look for associated items in the current trait.
2387        if let Some((module, _)) = self.current_trait_ref
2388            && let Ok(binding) = self.r.cm().maybe_resolve_ident_in_module(
2389                ModuleOrUniformRoot::Module(module),
2390                ident,
2391                ns,
2392                &self.parent_scope,
2393                None,
2394            )
2395        {
2396            let res = binding.res();
2397            if filter_fn(res) {
2398                match res {
2399                    Res::Def(DefKind::Fn | DefKind::AssocFn, def_id) => {
2400                        let has_self = match def_id.as_local() {
2401                            Some(def_id) => self
2402                                .r
2403                                .delegation_fn_sigs
2404                                .get(&def_id)
2405                                .is_some_and(|sig| sig.has_self),
2406                            None => {
2407                                self.r.tcx.fn_arg_idents(def_id).first().is_some_and(|&ident| {
2408                                    matches!(ident, Some(Ident { name: kw::SelfLower, .. }))
2409                                })
2410                            }
2411                        };
2412                        if has_self {
2413                            return Some(AssocSuggestion::MethodWithSelf { called });
2414                        } else {
2415                            return Some(AssocSuggestion::AssocFn { called });
2416                        }
2417                    }
2418                    Res::Def(DefKind::AssocConst, _) => {
2419                        return Some(AssocSuggestion::AssocConst);
2420                    }
2421                    Res::Def(DefKind::AssocTy, _) => {
2422                        return Some(AssocSuggestion::AssocType);
2423                    }
2424                    _ => {}
2425                }
2426            }
2427        }
2428
2429        None
2430    }
2431
2432    fn lookup_typo_candidate(
2433        &mut self,
2434        path: &[Segment],
2435        following_seg: Option<&Segment>,
2436        ns: Namespace,
2437        filter_fn: &impl Fn(Res) -> bool,
2438    ) -> TypoCandidate {
2439        let mut names = Vec::new();
2440        if let [segment] = path {
2441            let mut ctxt = segment.ident.span.ctxt();
2442
2443            // Search in lexical scope.
2444            // Walk backwards up the ribs in scope and collect candidates.
2445            for rib in self.ribs[ns].iter().rev() {
2446                let rib_ctxt = if rib.kind.contains_params() {
2447                    ctxt.normalize_to_macros_2_0()
2448                } else {
2449                    ctxt.normalize_to_macro_rules()
2450                };
2451
2452                // Locals and type parameters
2453                for (ident, &res) in &rib.bindings {
2454                    if filter_fn(res) && ident.span.ctxt() == rib_ctxt {
2455                        names.push(TypoSuggestion::typo_from_ident(*ident, res));
2456                    }
2457                }
2458
2459                if let RibKind::Block(Some(module)) = rib.kind {
2460                    self.r.add_module_candidates(module, &mut names, &filter_fn, Some(ctxt));
2461                } else if let RibKind::Module(module) = rib.kind {
2462                    // Encountered a module item, abandon ribs and look into that module and preludes.
2463                    let parent_scope = &ParentScope { module, ..self.parent_scope };
2464                    self.r.add_scope_set_candidates(
2465                        &mut names,
2466                        ScopeSet::All(ns),
2467                        parent_scope,
2468                        ctxt,
2469                        filter_fn,
2470                    );
2471                    break;
2472                }
2473
2474                if let RibKind::MacroDefinition(def) = rib.kind
2475                    && def == self.r.macro_def(ctxt)
2476                {
2477                    // If an invocation of this macro created `ident`, give up on `ident`
2478                    // and switch to `ident`'s source from the macro definition.
2479                    ctxt.remove_mark();
2480                }
2481            }
2482        } else {
2483            // Search in module.
2484            let mod_path = &path[..path.len() - 1];
2485            if let PathResult::Module(ModuleOrUniformRoot::Module(module)) =
2486                self.resolve_path(mod_path, Some(TypeNS), None, PathSource::Type)
2487            {
2488                self.r.add_module_candidates(module, &mut names, &filter_fn, None);
2489            }
2490        }
2491
2492        // if next_seg is present, let's filter everything that does not continue the path
2493        if let Some(following_seg) = following_seg {
2494            names.retain(|suggestion| match suggestion.res {
2495                Res::Def(DefKind::Struct | DefKind::Enum | DefKind::Union, _) => {
2496                    // FIXME: this is not totally accurate, but mostly works
2497                    suggestion.candidate != following_seg.ident.name
2498                }
2499                Res::Def(DefKind::Mod, def_id) => {
2500                    let module = self.r.expect_module(def_id);
2501                    self.r
2502                        .resolutions(module)
2503                        .borrow()
2504                        .iter()
2505                        .any(|(key, _)| key.ident.name == following_seg.ident.name)
2506                }
2507                _ => true,
2508            });
2509        }
2510        let name = path[path.len() - 1].ident.name;
2511        // Make sure error reporting is deterministic.
2512        names.sort_by(|a, b| a.candidate.as_str().cmp(b.candidate.as_str()));
2513
2514        match find_best_match_for_name(
2515            &names.iter().map(|suggestion| suggestion.candidate).collect::<Vec<Symbol>>(),
2516            name,
2517            None,
2518        ) {
2519            Some(found) => {
2520                let Some(sugg) = names.into_iter().find(|suggestion| suggestion.candidate == found)
2521                else {
2522                    return TypoCandidate::None;
2523                };
2524                if found == name {
2525                    TypoCandidate::Shadowed(sugg.res, sugg.span)
2526                } else {
2527                    TypoCandidate::Typo(sugg)
2528                }
2529            }
2530            _ => TypoCandidate::None,
2531        }
2532    }
2533
2534    // Returns the name of the Rust type approximately corresponding to
2535    // a type name in another programming language.
2536    fn likely_rust_type(path: &[Segment]) -> Option<Symbol> {
2537        let name = path[path.len() - 1].ident.as_str();
2538        // Common Java types
2539        Some(match name {
2540            "byte" => sym::u8, // In Java, bytes are signed, but in practice one almost always wants unsigned bytes.
2541            "short" => sym::i16,
2542            "Bool" => sym::bool,
2543            "Boolean" => sym::bool,
2544            "boolean" => sym::bool,
2545            "int" => sym::i32,
2546            "long" => sym::i64,
2547            "float" => sym::f32,
2548            "double" => sym::f64,
2549            _ => return None,
2550        })
2551    }
2552
2553    // try to give a suggestion for this pattern: `name = blah`, which is common in other languages
2554    // suggest `let name = blah` to introduce a new binding
2555    fn let_binding_suggestion(&self, err: &mut Diag<'_>, ident_span: Span) -> bool {
2556        if ident_span.from_expansion() {
2557            return false;
2558        }
2559
2560        // only suggest when the code is a assignment without prefix code
2561        if let Some(Expr { kind: ExprKind::Assign(lhs, ..), .. }) = self.diag_metadata.in_assignment
2562            && let ast::ExprKind::Path(None, ref path) = lhs.kind
2563            && self.r.tcx.sess.source_map().is_line_before_span_empty(ident_span)
2564        {
2565            let (span, text) = match path.segments.first() {
2566                Some(seg) if let Some(name) = seg.ident.as_str().strip_prefix("let") => {
2567                    // a special case for #117894
2568                    let name = name.strip_prefix('_').unwrap_or(name);
2569                    (ident_span, format!("let {name}"))
2570                }
2571                _ => (ident_span.shrink_to_lo(), "let ".to_string()),
2572            };
2573
2574            err.span_suggestion_verbose(
2575                span,
2576                "you might have meant to introduce a new binding",
2577                text,
2578                Applicability::MaybeIncorrect,
2579            );
2580            return true;
2581        }
2582
2583        // a special case for #133713
2584        // '=' maybe a typo of `:`, which is a type annotation instead of assignment
2585        if err.code == Some(E0423)
2586            && let Some((let_span, None, Some(val_span))) = self.diag_metadata.current_let_binding
2587            && val_span.contains(ident_span)
2588            && val_span.lo() == ident_span.lo()
2589        {
2590            err.span_suggestion_verbose(
2591                let_span.shrink_to_hi().to(val_span.shrink_to_lo()),
2592                "you might have meant to use `:` for type annotation",
2593                ": ",
2594                Applicability::MaybeIncorrect,
2595            );
2596            return true;
2597        }
2598        false
2599    }
2600
2601    fn find_module(&self, def_id: DefId) -> Option<(Module<'ra>, ImportSuggestion)> {
2602        let mut result = None;
2603        let mut seen_modules = FxHashSet::default();
2604        let root_did = self.r.graph_root.def_id();
2605        let mut worklist = vec![(
2606            self.r.graph_root,
2607            ThinVec::new(),
2608            root_did.is_local() || !self.r.tcx.is_doc_hidden(root_did),
2609        )];
2610
2611        while let Some((in_module, path_segments, doc_visible)) = worklist.pop() {
2612            // abort if the module is already found
2613            if result.is_some() {
2614                break;
2615            }
2616
2617            in_module.for_each_child(self.r, |r, ident, _, name_binding| {
2618                // abort if the module is already found or if name_binding is private external
2619                if result.is_some() || !name_binding.vis.is_visible_locally() {
2620                    return;
2621                }
2622                if let Some(module_def_id) = name_binding.res().module_like_def_id() {
2623                    // form the path
2624                    let mut path_segments = path_segments.clone();
2625                    path_segments.push(ast::PathSegment::from_ident(ident.0));
2626                    let doc_visible = doc_visible
2627                        && (module_def_id.is_local() || !r.tcx.is_doc_hidden(module_def_id));
2628                    if module_def_id == def_id {
2629                        let path =
2630                            Path { span: name_binding.span, segments: path_segments, tokens: None };
2631                        result = Some((
2632                            r.expect_module(module_def_id),
2633                            ImportSuggestion {
2634                                did: Some(def_id),
2635                                descr: "module",
2636                                path,
2637                                accessible: true,
2638                                doc_visible,
2639                                note: None,
2640                                via_import: false,
2641                                is_stable: true,
2642                            },
2643                        ));
2644                    } else {
2645                        // add the module to the lookup
2646                        if seen_modules.insert(module_def_id) {
2647                            let module = r.expect_module(module_def_id);
2648                            worklist.push((module, path_segments, doc_visible));
2649                        }
2650                    }
2651                }
2652            });
2653        }
2654
2655        result
2656    }
2657
2658    fn collect_enum_ctors(&self, def_id: DefId) -> Option<Vec<(Path, DefId, CtorKind)>> {
2659        self.find_module(def_id).map(|(enum_module, enum_import_suggestion)| {
2660            let mut variants = Vec::new();
2661            enum_module.for_each_child(self.r, |_, ident, _, name_binding| {
2662                if let Res::Def(DefKind::Ctor(CtorOf::Variant, kind), def_id) = name_binding.res() {
2663                    let mut segms = enum_import_suggestion.path.segments.clone();
2664                    segms.push(ast::PathSegment::from_ident(ident.0));
2665                    let path = Path { span: name_binding.span, segments: segms, tokens: None };
2666                    variants.push((path, def_id, kind));
2667                }
2668            });
2669            variants
2670        })
2671    }
2672
2673    /// Adds a suggestion for using an enum's variant when an enum is used instead.
2674    fn suggest_using_enum_variant(
2675        &self,
2676        err: &mut Diag<'_>,
2677        source: PathSource<'_, '_, '_>,
2678        def_id: DefId,
2679        span: Span,
2680    ) {
2681        let Some(variant_ctors) = self.collect_enum_ctors(def_id) else {
2682            err.note("you might have meant to use one of the enum's variants");
2683            return;
2684        };
2685
2686        // If the expression is a field-access or method-call, try to find a variant with the field/method name
2687        // that could have been intended, and suggest replacing the `.` with `::`.
2688        // Otherwise, suggest adding `::VariantName` after the enum;
2689        // and if the expression is call-like, only suggest tuple variants.
2690        let (suggest_path_sep_dot_span, suggest_only_tuple_variants) = match source {
2691            // `Type(a, b)` in a pattern, only suggest adding a tuple variant after `Type`.
2692            PathSource::TupleStruct(..) => (None, true),
2693            PathSource::Expr(Some(expr)) => match &expr.kind {
2694                // `Type(a, b)`, only suggest adding a tuple variant after `Type`.
2695                ExprKind::Call(..) => (None, true),
2696                // `Type.Foo(a, b)`, suggest replacing `.` -> `::` if variant `Foo` exists and is a tuple variant,
2697                // otherwise suggest adding a variant after `Type`.
2698                ExprKind::MethodCall(box MethodCall {
2699                    receiver,
2700                    span,
2701                    seg: PathSegment { ident, .. },
2702                    ..
2703                }) => {
2704                    let dot_span = receiver.span.between(*span);
2705                    let found_tuple_variant = variant_ctors.iter().any(|(path, _, ctor_kind)| {
2706                        *ctor_kind == CtorKind::Fn
2707                            && path.segments.last().is_some_and(|seg| seg.ident == *ident)
2708                    });
2709                    (found_tuple_variant.then_some(dot_span), false)
2710                }
2711                // `Type.Foo`, suggest replacing `.` -> `::` if variant `Foo` exists and is a unit or tuple variant,
2712                // otherwise suggest adding a variant after `Type`.
2713                ExprKind::Field(base, ident) => {
2714                    let dot_span = base.span.between(ident.span);
2715                    let found_tuple_or_unit_variant = variant_ctors.iter().any(|(path, ..)| {
2716                        path.segments.last().is_some_and(|seg| seg.ident == *ident)
2717                    });
2718                    (found_tuple_or_unit_variant.then_some(dot_span), false)
2719                }
2720                _ => (None, false),
2721            },
2722            _ => (None, false),
2723        };
2724
2725        if let Some(dot_span) = suggest_path_sep_dot_span {
2726            err.span_suggestion_verbose(
2727                dot_span,
2728                "use the path separator to refer to a variant",
2729                "::",
2730                Applicability::MaybeIncorrect,
2731            );
2732        } else if suggest_only_tuple_variants {
2733            // Suggest only tuple variants regardless of whether they have fields and do not
2734            // suggest path with added parentheses.
2735            let mut suggestable_variants = variant_ctors
2736                .iter()
2737                .filter(|(.., kind)| *kind == CtorKind::Fn)
2738                .map(|(variant, ..)| path_names_to_string(variant))
2739                .collect::<Vec<_>>();
2740            suggestable_variants.sort();
2741
2742            let non_suggestable_variant_count = variant_ctors.len() - suggestable_variants.len();
2743
2744            let source_msg = if matches!(source, PathSource::TupleStruct(..)) {
2745                "to match against"
2746            } else {
2747                "to construct"
2748            };
2749
2750            if !suggestable_variants.is_empty() {
2751                let msg = if non_suggestable_variant_count == 0 && suggestable_variants.len() == 1 {
2752                    format!("try {source_msg} the enum's variant")
2753                } else {
2754                    format!("try {source_msg} one of the enum's variants")
2755                };
2756
2757                err.span_suggestions(
2758                    span,
2759                    msg,
2760                    suggestable_variants,
2761                    Applicability::MaybeIncorrect,
2762                );
2763            }
2764
2765            // If the enum has no tuple variants..
2766            if non_suggestable_variant_count == variant_ctors.len() {
2767                err.help(format!("the enum has no tuple variants {source_msg}"));
2768            }
2769
2770            // If there are also non-tuple variants..
2771            if non_suggestable_variant_count == 1 {
2772                err.help(format!("you might have meant {source_msg} the enum's non-tuple variant"));
2773            } else if non_suggestable_variant_count >= 1 {
2774                err.help(format!(
2775                    "you might have meant {source_msg} one of the enum's non-tuple variants"
2776                ));
2777            }
2778        } else {
2779            let needs_placeholder = |ctor_def_id: DefId, kind: CtorKind| {
2780                let def_id = self.r.tcx.parent(ctor_def_id);
2781                match kind {
2782                    CtorKind::Const => false,
2783                    CtorKind::Fn => {
2784                        !self.r.field_idents(def_id).is_some_and(|field_ids| field_ids.is_empty())
2785                    }
2786                }
2787            };
2788
2789            let mut suggestable_variants = variant_ctors
2790                .iter()
2791                .filter(|(_, def_id, kind)| !needs_placeholder(*def_id, *kind))
2792                .map(|(variant, _, kind)| (path_names_to_string(variant), kind))
2793                .map(|(variant, kind)| match kind {
2794                    CtorKind::Const => variant,
2795                    CtorKind::Fn => format!("({variant}())"),
2796                })
2797                .collect::<Vec<_>>();
2798            suggestable_variants.sort();
2799            let no_suggestable_variant = suggestable_variants.is_empty();
2800
2801            if !no_suggestable_variant {
2802                let msg = if suggestable_variants.len() == 1 {
2803                    "you might have meant to use the following enum variant"
2804                } else {
2805                    "you might have meant to use one of the following enum variants"
2806                };
2807
2808                err.span_suggestions(
2809                    span,
2810                    msg,
2811                    suggestable_variants,
2812                    Applicability::MaybeIncorrect,
2813                );
2814            }
2815
2816            let mut suggestable_variants_with_placeholders = variant_ctors
2817                .iter()
2818                .filter(|(_, def_id, kind)| needs_placeholder(*def_id, *kind))
2819                .map(|(variant, _, kind)| (path_names_to_string(variant), kind))
2820                .filter_map(|(variant, kind)| match kind {
2821                    CtorKind::Fn => Some(format!("({variant}(/* fields */))")),
2822                    _ => None,
2823                })
2824                .collect::<Vec<_>>();
2825            suggestable_variants_with_placeholders.sort();
2826
2827            if !suggestable_variants_with_placeholders.is_empty() {
2828                let msg =
2829                    match (no_suggestable_variant, suggestable_variants_with_placeholders.len()) {
2830                        (true, 1) => "the following enum variant is available",
2831                        (true, _) => "the following enum variants are available",
2832                        (false, 1) => "alternatively, the following enum variant is available",
2833                        (false, _) => {
2834                            "alternatively, the following enum variants are also available"
2835                        }
2836                    };
2837
2838                err.span_suggestions(
2839                    span,
2840                    msg,
2841                    suggestable_variants_with_placeholders,
2842                    Applicability::HasPlaceholders,
2843                );
2844            }
2845        };
2846
2847        if def_id.is_local() {
2848            err.span_note(self.r.def_span(def_id), "the enum is defined here");
2849        }
2850    }
2851
2852    pub(crate) fn suggest_adding_generic_parameter(
2853        &self,
2854        path: &[Segment],
2855        source: PathSource<'_, '_, '_>,
2856    ) -> Option<(Span, &'static str, String, Applicability)> {
2857        let (ident, span) = match path {
2858            [segment]
2859                if !segment.has_generic_args
2860                    && segment.ident.name != kw::SelfUpper
2861                    && segment.ident.name != kw::Dyn =>
2862            {
2863                (segment.ident.to_string(), segment.ident.span)
2864            }
2865            _ => return None,
2866        };
2867        let mut iter = ident.chars().map(|c| c.is_uppercase());
2868        let single_uppercase_char =
2869            matches!(iter.next(), Some(true)) && matches!(iter.next(), None);
2870        if !self.diag_metadata.currently_processing_generic_args && !single_uppercase_char {
2871            return None;
2872        }
2873        match (self.diag_metadata.current_item, single_uppercase_char, self.diag_metadata.currently_processing_generic_args) {
2874            (Some(Item { kind: ItemKind::Fn(fn_), .. }), _, _) if fn_.ident.name == sym::main => {
2875                // Ignore `fn main()` as we don't want to suggest `fn main<T>()`
2876            }
2877            (
2878                Some(Item {
2879                    kind:
2880                        kind @ ItemKind::Fn(..)
2881                        | kind @ ItemKind::Enum(..)
2882                        | kind @ ItemKind::Struct(..)
2883                        | kind @ ItemKind::Union(..),
2884                    ..
2885                }),
2886                true, _
2887            )
2888            // Without the 2nd `true`, we'd suggest `impl <T>` for `impl T` when a type `T` isn't found
2889            | (Some(Item { kind: kind @ ItemKind::Impl(..), .. }), true, true)
2890            | (Some(Item { kind, .. }), false, _) => {
2891                if let Some(generics) = kind.generics() {
2892                    if span.overlaps(generics.span) {
2893                        // Avoid the following:
2894                        // error[E0405]: cannot find trait `A` in this scope
2895                        //  --> $DIR/typo-suggestion-named-underscore.rs:CC:LL
2896                        //   |
2897                        // L | fn foo<T: A>(x: T) {} // Shouldn't suggest underscore
2898                        //   |           ^- help: you might be missing a type parameter: `, A`
2899                        //   |           |
2900                        //   |           not found in this scope
2901                        return None;
2902                    }
2903
2904                    let (msg, sugg) = match source {
2905                        PathSource::Type | PathSource::PreciseCapturingArg(TypeNS) => {
2906                            ("you might be missing a type parameter", ident)
2907                        }
2908                        PathSource::Expr(_) | PathSource::PreciseCapturingArg(ValueNS) => (
2909                            "you might be missing a const parameter",
2910                            format!("const {ident}: /* Type */"),
2911                        ),
2912                        _ => return None,
2913                    };
2914                    let (span, sugg) = if let [.., param] = &generics.params[..] {
2915                        let span = if let [.., bound] = &param.bounds[..] {
2916                            bound.span()
2917                        } else if let GenericParam {
2918                            kind: GenericParamKind::Const { ty, span: _, default  }, ..
2919                        } = param {
2920                            default.as_ref().map(|def| def.value.span).unwrap_or(ty.span)
2921                        } else {
2922                            param.ident.span
2923                        };
2924                        (span, format!(", {sugg}"))
2925                    } else {
2926                        (generics.span, format!("<{sugg}>"))
2927                    };
2928                    // Do not suggest if this is coming from macro expansion.
2929                    if span.can_be_used_for_suggestions() {
2930                        return Some((
2931                            span.shrink_to_hi(),
2932                            msg,
2933                            sugg,
2934                            Applicability::MaybeIncorrect,
2935                        ));
2936                    }
2937                }
2938            }
2939            _ => {}
2940        }
2941        None
2942    }
2943
2944    /// Given the target `label`, search the `rib_index`th label rib for similarly named labels,
2945    /// optionally returning the closest match and whether it is reachable.
2946    pub(crate) fn suggestion_for_label_in_rib(
2947        &self,
2948        rib_index: usize,
2949        label: Ident,
2950    ) -> Option<LabelSuggestion> {
2951        // Are ribs from this `rib_index` within scope?
2952        let within_scope = self.is_label_valid_from_rib(rib_index);
2953
2954        let rib = &self.label_ribs[rib_index];
2955        let names = rib
2956            .bindings
2957            .iter()
2958            .filter(|(id, _)| id.span.eq_ctxt(label.span))
2959            .map(|(id, _)| id.name)
2960            .collect::<Vec<Symbol>>();
2961
2962        find_best_match_for_name(&names, label.name, None).map(|symbol| {
2963            // Upon finding a similar name, get the ident that it was from - the span
2964            // contained within helps make a useful diagnostic. In addition, determine
2965            // whether this candidate is within scope.
2966            let (ident, _) = rib.bindings.iter().find(|(ident, _)| ident.name == symbol).unwrap();
2967            (*ident, within_scope)
2968        })
2969    }
2970
2971    pub(crate) fn maybe_report_lifetime_uses(
2972        &mut self,
2973        generics_span: Span,
2974        params: &[ast::GenericParam],
2975    ) {
2976        for (param_index, param) in params.iter().enumerate() {
2977            let GenericParamKind::Lifetime = param.kind else { continue };
2978
2979            let def_id = self.r.local_def_id(param.id);
2980
2981            let use_set = self.lifetime_uses.remove(&def_id);
2982            debug!(
2983                "Use set for {:?}({:?} at {:?}) is {:?}",
2984                def_id, param.ident, param.ident.span, use_set
2985            );
2986
2987            let deletion_span = || {
2988                if params.len() == 1 {
2989                    // if sole lifetime, remove the entire `<>` brackets
2990                    Some(generics_span)
2991                } else if param_index == 0 {
2992                    // if removing within `<>` brackets, we also want to
2993                    // delete a leading or trailing comma as appropriate
2994                    match (
2995                        param.span().find_ancestor_inside(generics_span),
2996                        params[param_index + 1].span().find_ancestor_inside(generics_span),
2997                    ) {
2998                        (Some(param_span), Some(next_param_span)) => {
2999                            Some(param_span.to(next_param_span.shrink_to_lo()))
3000                        }
3001                        _ => None,
3002                    }
3003                } else {
3004                    // if removing within `<>` brackets, we also want to
3005                    // delete a leading or trailing comma as appropriate
3006                    match (
3007                        param.span().find_ancestor_inside(generics_span),
3008                        params[param_index - 1].span().find_ancestor_inside(generics_span),
3009                    ) {
3010                        (Some(param_span), Some(prev_param_span)) => {
3011                            Some(prev_param_span.shrink_to_hi().to(param_span))
3012                        }
3013                        _ => None,
3014                    }
3015                }
3016            };
3017            match use_set {
3018                Some(LifetimeUseSet::Many) => {}
3019                Some(LifetimeUseSet::One { use_span, use_ctxt }) => {
3020                    debug!(?param.ident, ?param.ident.span, ?use_span);
3021
3022                    let elidable = matches!(use_ctxt, LifetimeCtxt::Ref);
3023                    let deletion_span =
3024                        if param.bounds.is_empty() { deletion_span() } else { None };
3025
3026                    self.r.lint_buffer.buffer_lint(
3027                        lint::builtin::SINGLE_USE_LIFETIMES,
3028                        param.id,
3029                        param.ident.span,
3030                        lint::BuiltinLintDiag::SingleUseLifetime {
3031                            param_span: param.ident.span,
3032                            use_span: Some((use_span, elidable)),
3033                            deletion_span,
3034                            ident: param.ident,
3035                        },
3036                    );
3037                }
3038                None => {
3039                    debug!(?param.ident, ?param.ident.span);
3040                    let deletion_span = deletion_span();
3041
3042                    // if the lifetime originates from expanded code, we won't be able to remove it #104432
3043                    if deletion_span.is_some_and(|sp| !sp.in_derive_expansion()) {
3044                        self.r.lint_buffer.buffer_lint(
3045                            lint::builtin::UNUSED_LIFETIMES,
3046                            param.id,
3047                            param.ident.span,
3048                            lint::BuiltinLintDiag::SingleUseLifetime {
3049                                param_span: param.ident.span,
3050                                use_span: None,
3051                                deletion_span,
3052                                ident: param.ident,
3053                            },
3054                        );
3055                    }
3056                }
3057            }
3058        }
3059    }
3060
3061    pub(crate) fn emit_undeclared_lifetime_error(
3062        &self,
3063        lifetime_ref: &ast::Lifetime,
3064        outer_lifetime_ref: Option<Ident>,
3065    ) {
3066        debug_assert_ne!(lifetime_ref.ident.name, kw::UnderscoreLifetime);
3067        let mut err = if let Some(outer) = outer_lifetime_ref {
3068            struct_span_code_err!(
3069                self.r.dcx(),
3070                lifetime_ref.ident.span,
3071                E0401,
3072                "can't use generic parameters from outer item",
3073            )
3074            .with_span_label(lifetime_ref.ident.span, "use of generic parameter from outer item")
3075            .with_span_label(outer.span, "lifetime parameter from outer item")
3076        } else {
3077            struct_span_code_err!(
3078                self.r.dcx(),
3079                lifetime_ref.ident.span,
3080                E0261,
3081                "use of undeclared lifetime name `{}`",
3082                lifetime_ref.ident
3083            )
3084            .with_span_label(lifetime_ref.ident.span, "undeclared lifetime")
3085        };
3086
3087        // Check if this is a typo of `'static`.
3088        if edit_distance(lifetime_ref.ident.name.as_str(), "'static", 2).is_some() {
3089            err.span_suggestion_verbose(
3090                lifetime_ref.ident.span,
3091                "you may have misspelled the `'static` lifetime",
3092                "'static",
3093                Applicability::MachineApplicable,
3094            );
3095        } else {
3096            self.suggest_introducing_lifetime(
3097                &mut err,
3098                Some(lifetime_ref.ident),
3099                |err, _, span, message, suggestion, span_suggs| {
3100                    err.multipart_suggestion_verbose(
3101                        message,
3102                        std::iter::once((span, suggestion)).chain(span_suggs.clone()).collect(),
3103                        Applicability::MaybeIncorrect,
3104                    );
3105                    true
3106                },
3107            );
3108        }
3109
3110        err.emit();
3111    }
3112
3113    fn suggest_introducing_lifetime(
3114        &self,
3115        err: &mut Diag<'_>,
3116        name: Option<Ident>,
3117        suggest: impl Fn(
3118            &mut Diag<'_>,
3119            bool,
3120            Span,
3121            Cow<'static, str>,
3122            String,
3123            Vec<(Span, String)>,
3124        ) -> bool,
3125    ) {
3126        let mut suggest_note = true;
3127        for rib in self.lifetime_ribs.iter().rev() {
3128            let mut should_continue = true;
3129            match rib.kind {
3130                LifetimeRibKind::Generics { binder, span, kind } => {
3131                    // Avoid suggesting placing lifetime parameters on constant items unless the relevant
3132                    // feature is enabled. Suggest the parent item as a possible location if applicable.
3133                    if let LifetimeBinderKind::ConstItem = kind
3134                        && !self.r.tcx().features().generic_const_items()
3135                    {
3136                        continue;
3137                    }
3138
3139                    if !span.can_be_used_for_suggestions()
3140                        && suggest_note
3141                        && let Some(name) = name
3142                    {
3143                        suggest_note = false; // Avoid displaying the same help multiple times.
3144                        err.span_label(
3145                            span,
3146                            format!(
3147                                "lifetime `{name}` is missing in item created through this procedural macro",
3148                            ),
3149                        );
3150                        continue;
3151                    }
3152
3153                    let higher_ranked = matches!(
3154                        kind,
3155                        LifetimeBinderKind::FnPtrType
3156                            | LifetimeBinderKind::PolyTrait
3157                            | LifetimeBinderKind::WhereBound
3158                    );
3159
3160                    let mut rm_inner_binders: FxIndexSet<Span> = Default::default();
3161                    let (span, sugg) = if span.is_empty() {
3162                        let mut binder_idents: FxIndexSet<Ident> = Default::default();
3163                        binder_idents.insert(name.unwrap_or(Ident::from_str("'a")));
3164
3165                        // We need to special case binders in the following situation:
3166                        // Change `T: for<'a> Trait<T> + 'b` to `for<'a, 'b> T: Trait<T> + 'b`
3167                        // T: for<'a> Trait<T> + 'b
3168                        //    ^^^^^^^  remove existing inner binder `for<'a>`
3169                        // for<'a, 'b> T: Trait<T> + 'b
3170                        // ^^^^^^^^^^^  suggest outer binder `for<'a, 'b>`
3171                        if let LifetimeBinderKind::WhereBound = kind
3172                            && let Some(predicate) = self.diag_metadata.current_where_predicate
3173                            && let ast::WherePredicateKind::BoundPredicate(
3174                                ast::WhereBoundPredicate { bounded_ty, bounds, .. },
3175                            ) = &predicate.kind
3176                            && bounded_ty.id == binder
3177                        {
3178                            for bound in bounds {
3179                                if let ast::GenericBound::Trait(poly_trait_ref) = bound
3180                                    && let span = poly_trait_ref
3181                                        .span
3182                                        .with_hi(poly_trait_ref.trait_ref.path.span.lo())
3183                                    && !span.is_empty()
3184                                {
3185                                    rm_inner_binders.insert(span);
3186                                    poly_trait_ref.bound_generic_params.iter().for_each(|v| {
3187                                        binder_idents.insert(v.ident);
3188                                    });
3189                                }
3190                            }
3191                        }
3192
3193                        let binders_sugg: String = binder_idents
3194                            .into_iter()
3195                            .map(|ident| ident.to_string())
3196                            .intersperse(", ".to_owned())
3197                            .collect();
3198                        let sugg = format!(
3199                            "{}<{}>{}",
3200                            if higher_ranked { "for" } else { "" },
3201                            binders_sugg,
3202                            if higher_ranked { " " } else { "" },
3203                        );
3204                        (span, sugg)
3205                    } else {
3206                        let span = self
3207                            .r
3208                            .tcx
3209                            .sess
3210                            .source_map()
3211                            .span_through_char(span, '<')
3212                            .shrink_to_hi();
3213                        let sugg =
3214                            format!("{}, ", name.map(|i| i.to_string()).as_deref().unwrap_or("'a"));
3215                        (span, sugg)
3216                    };
3217
3218                    if higher_ranked {
3219                        let message = Cow::from(format!(
3220                            "consider making the {} lifetime-generic with a new `{}` lifetime",
3221                            kind.descr(),
3222                            name.map(|i| i.to_string()).as_deref().unwrap_or("'a"),
3223                        ));
3224                        should_continue = suggest(
3225                            err,
3226                            true,
3227                            span,
3228                            message,
3229                            sugg,
3230                            if !rm_inner_binders.is_empty() {
3231                                rm_inner_binders
3232                                    .into_iter()
3233                                    .map(|v| (v, "".to_string()))
3234                                    .collect::<Vec<_>>()
3235                            } else {
3236                                vec![]
3237                            },
3238                        );
3239                        err.note_once(
3240                            "for more information on higher-ranked polymorphism, visit \
3241                             https://doc.rust-lang.org/nomicon/hrtb.html",
3242                        );
3243                    } else if let Some(name) = name {
3244                        let message =
3245                            Cow::from(format!("consider introducing lifetime `{name}` here"));
3246                        should_continue = suggest(err, false, span, message, sugg, vec![]);
3247                    } else {
3248                        let message = Cow::from("consider introducing a named lifetime parameter");
3249                        should_continue = suggest(err, false, span, message, sugg, vec![]);
3250                    }
3251                }
3252                LifetimeRibKind::Item | LifetimeRibKind::ConstParamTy => break,
3253                _ => {}
3254            }
3255            if !should_continue {
3256                break;
3257            }
3258        }
3259    }
3260
3261    pub(crate) fn emit_non_static_lt_in_const_param_ty_error(&self, lifetime_ref: &ast::Lifetime) {
3262        self.r
3263            .dcx()
3264            .create_err(errors::ParamInTyOfConstParam {
3265                span: lifetime_ref.ident.span,
3266                name: lifetime_ref.ident.name,
3267            })
3268            .emit();
3269    }
3270
3271    /// Non-static lifetimes are prohibited in anonymous constants under `min_const_generics`.
3272    /// This function will emit an error if `generic_const_exprs` is not enabled, the body identified by
3273    /// `body_id` is an anonymous constant and `lifetime_ref` is non-static.
3274    pub(crate) fn emit_forbidden_non_static_lifetime_error(
3275        &self,
3276        cause: NoConstantGenericsReason,
3277        lifetime_ref: &ast::Lifetime,
3278    ) {
3279        match cause {
3280            NoConstantGenericsReason::IsEnumDiscriminant => {
3281                self.r
3282                    .dcx()
3283                    .create_err(errors::ParamInEnumDiscriminant {
3284                        span: lifetime_ref.ident.span,
3285                        name: lifetime_ref.ident.name,
3286                        param_kind: errors::ParamKindInEnumDiscriminant::Lifetime,
3287                    })
3288                    .emit();
3289            }
3290            NoConstantGenericsReason::NonTrivialConstArg => {
3291                assert!(!self.r.tcx.features().generic_const_exprs());
3292                self.r
3293                    .dcx()
3294                    .create_err(errors::ParamInNonTrivialAnonConst {
3295                        span: lifetime_ref.ident.span,
3296                        name: lifetime_ref.ident.name,
3297                        param_kind: errors::ParamKindInNonTrivialAnonConst::Lifetime,
3298                        help: self
3299                            .r
3300                            .tcx
3301                            .sess
3302                            .is_nightly_build()
3303                            .then_some(errors::ParamInNonTrivialAnonConstHelp),
3304                    })
3305                    .emit();
3306            }
3307        }
3308    }
3309
3310    pub(crate) fn report_missing_lifetime_specifiers(
3311        &mut self,
3312        lifetime_refs: Vec<MissingLifetime>,
3313        function_param_lifetimes: Option<(Vec<MissingLifetime>, Vec<ElisionFnParameter>)>,
3314    ) -> ErrorGuaranteed {
3315        let num_lifetimes: usize = lifetime_refs.iter().map(|lt| lt.count).sum();
3316        let spans: Vec<_> = lifetime_refs.iter().map(|lt| lt.span).collect();
3317
3318        let mut err = struct_span_code_err!(
3319            self.r.dcx(),
3320            spans,
3321            E0106,
3322            "missing lifetime specifier{}",
3323            pluralize!(num_lifetimes)
3324        );
3325        self.add_missing_lifetime_specifiers_label(
3326            &mut err,
3327            lifetime_refs,
3328            function_param_lifetimes,
3329        );
3330        err.emit()
3331    }
3332
3333    fn add_missing_lifetime_specifiers_label(
3334        &mut self,
3335        err: &mut Diag<'_>,
3336        lifetime_refs: Vec<MissingLifetime>,
3337        function_param_lifetimes: Option<(Vec<MissingLifetime>, Vec<ElisionFnParameter>)>,
3338    ) {
3339        for &lt in &lifetime_refs {
3340            err.span_label(
3341                lt.span,
3342                format!(
3343                    "expected {} lifetime parameter{}",
3344                    if lt.count == 1 { "named".to_string() } else { lt.count.to_string() },
3345                    pluralize!(lt.count),
3346                ),
3347            );
3348        }
3349
3350        let mut in_scope_lifetimes: Vec<_> = self
3351            .lifetime_ribs
3352            .iter()
3353            .rev()
3354            .take_while(|rib| {
3355                !matches!(rib.kind, LifetimeRibKind::Item | LifetimeRibKind::ConstParamTy)
3356            })
3357            .flat_map(|rib| rib.bindings.iter())
3358            .map(|(&ident, &res)| (ident, res))
3359            .filter(|(ident, _)| ident.name != kw::UnderscoreLifetime)
3360            .collect();
3361        debug!(?in_scope_lifetimes);
3362
3363        let mut maybe_static = false;
3364        debug!(?function_param_lifetimes);
3365        if let Some((param_lifetimes, params)) = &function_param_lifetimes {
3366            let elided_len = param_lifetimes.len();
3367            let num_params = params.len();
3368
3369            let mut m = String::new();
3370
3371            for (i, info) in params.iter().enumerate() {
3372                let ElisionFnParameter { ident, index, lifetime_count, span } = *info;
3373                debug_assert_ne!(lifetime_count, 0);
3374
3375                err.span_label(span, "");
3376
3377                if i != 0 {
3378                    if i + 1 < num_params {
3379                        m.push_str(", ");
3380                    } else if num_params == 2 {
3381                        m.push_str(" or ");
3382                    } else {
3383                        m.push_str(", or ");
3384                    }
3385                }
3386
3387                let help_name = if let Some(ident) = ident {
3388                    format!("`{ident}`")
3389                } else {
3390                    format!("argument {}", index + 1)
3391                };
3392
3393                if lifetime_count == 1 {
3394                    m.push_str(&help_name[..])
3395                } else {
3396                    m.push_str(&format!("one of {help_name}'s {lifetime_count} lifetimes")[..])
3397                }
3398            }
3399
3400            if num_params == 0 {
3401                err.help(
3402                    "this function's return type contains a borrowed value, but there is no value \
3403                     for it to be borrowed from",
3404                );
3405                if in_scope_lifetimes.is_empty() {
3406                    maybe_static = true;
3407                    in_scope_lifetimes = vec![(
3408                        Ident::with_dummy_span(kw::StaticLifetime),
3409                        (DUMMY_NODE_ID, LifetimeRes::Static),
3410                    )];
3411                }
3412            } else if elided_len == 0 {
3413                err.help(
3414                    "this function's return type contains a borrowed value with an elided \
3415                     lifetime, but the lifetime cannot be derived from the arguments",
3416                );
3417                if in_scope_lifetimes.is_empty() {
3418                    maybe_static = true;
3419                    in_scope_lifetimes = vec![(
3420                        Ident::with_dummy_span(kw::StaticLifetime),
3421                        (DUMMY_NODE_ID, LifetimeRes::Static),
3422                    )];
3423                }
3424            } else if num_params == 1 {
3425                err.help(format!(
3426                    "this function's return type contains a borrowed value, but the signature does \
3427                     not say which {m} it is borrowed from",
3428                ));
3429            } else {
3430                err.help(format!(
3431                    "this function's return type contains a borrowed value, but the signature does \
3432                     not say whether it is borrowed from {m}",
3433                ));
3434            }
3435        }
3436
3437        #[allow(rustc::symbol_intern_string_literal)]
3438        let existing_name = match &in_scope_lifetimes[..] {
3439            [] => Symbol::intern("'a"),
3440            [(existing, _)] => existing.name,
3441            _ => Symbol::intern("'lifetime"),
3442        };
3443
3444        let mut spans_suggs: Vec<_> = Vec::new();
3445        let build_sugg = |lt: MissingLifetime| match lt.kind {
3446            MissingLifetimeKind::Underscore => {
3447                debug_assert_eq!(lt.count, 1);
3448                (lt.span, existing_name.to_string())
3449            }
3450            MissingLifetimeKind::Ampersand => {
3451                debug_assert_eq!(lt.count, 1);
3452                (lt.span.shrink_to_hi(), format!("{existing_name} "))
3453            }
3454            MissingLifetimeKind::Comma => {
3455                let sugg: String = std::iter::repeat([existing_name.as_str(), ", "])
3456                    .take(lt.count)
3457                    .flatten()
3458                    .collect();
3459                (lt.span.shrink_to_hi(), sugg)
3460            }
3461            MissingLifetimeKind::Brackets => {
3462                let sugg: String = std::iter::once("<")
3463                    .chain(
3464                        std::iter::repeat(existing_name.as_str()).take(lt.count).intersperse(", "),
3465                    )
3466                    .chain([">"])
3467                    .collect();
3468                (lt.span.shrink_to_hi(), sugg)
3469            }
3470        };
3471        for &lt in &lifetime_refs {
3472            spans_suggs.push(build_sugg(lt));
3473        }
3474        debug!(?spans_suggs);
3475        match in_scope_lifetimes.len() {
3476            0 => {
3477                if let Some((param_lifetimes, _)) = function_param_lifetimes {
3478                    for lt in param_lifetimes {
3479                        spans_suggs.push(build_sugg(lt))
3480                    }
3481                }
3482                self.suggest_introducing_lifetime(
3483                    err,
3484                    None,
3485                    |err, higher_ranked, span, message, intro_sugg, _| {
3486                        err.multipart_suggestion_verbose(
3487                            message,
3488                            std::iter::once((span, intro_sugg))
3489                                .chain(spans_suggs.clone())
3490                                .collect(),
3491                            Applicability::MaybeIncorrect,
3492                        );
3493                        higher_ranked
3494                    },
3495                );
3496            }
3497            1 => {
3498                let post = if maybe_static {
3499                    let owned = if let [lt] = &lifetime_refs[..]
3500                        && lt.kind != MissingLifetimeKind::Ampersand
3501                    {
3502                        ", or if you will only have owned values"
3503                    } else {
3504                        ""
3505                    };
3506                    format!(
3507                        ", but this is uncommon unless you're returning a borrowed value from a \
3508                         `const` or a `static`{owned}",
3509                    )
3510                } else {
3511                    String::new()
3512                };
3513                err.multipart_suggestion_verbose(
3514                    format!("consider using the `{existing_name}` lifetime{post}"),
3515                    spans_suggs,
3516                    Applicability::MaybeIncorrect,
3517                );
3518                if maybe_static {
3519                    // FIXME: what follows are general suggestions, but we'd want to perform some
3520                    // minimal flow analysis to provide more accurate suggestions. For example, if
3521                    // we identified that the return expression references only one argument, we
3522                    // would suggest borrowing only that argument, and we'd skip the prior
3523                    // "use `'static`" suggestion entirely.
3524                    if let [lt] = &lifetime_refs[..]
3525                        && (lt.kind == MissingLifetimeKind::Ampersand
3526                            || lt.kind == MissingLifetimeKind::Underscore)
3527                    {
3528                        let pre = if lt.kind == MissingLifetimeKind::Ampersand
3529                            && let Some((kind, _span)) = self.diag_metadata.current_function
3530                            && let FnKind::Fn(_, _, ast::Fn { sig, .. }) = kind
3531                            && !sig.decl.inputs.is_empty()
3532                            && let sugg = sig
3533                                .decl
3534                                .inputs
3535                                .iter()
3536                                .filter_map(|param| {
3537                                    if param.ty.span.contains(lt.span) {
3538                                        // We don't want to suggest `fn elision(_: &fn() -> &i32)`
3539                                        // when we have `fn elision(_: fn() -> &i32)`
3540                                        None
3541                                    } else if let TyKind::CVarArgs = param.ty.kind {
3542                                        // Don't suggest `&...` for ffi fn with varargs
3543                                        None
3544                                    } else if let TyKind::ImplTrait(..) = &param.ty.kind {
3545                                        // We handle these in the next `else if` branch.
3546                                        None
3547                                    } else {
3548                                        Some((param.ty.span.shrink_to_lo(), "&".to_string()))
3549                                    }
3550                                })
3551                                .collect::<Vec<_>>()
3552                            && !sugg.is_empty()
3553                        {
3554                            let (the, s) = if sig.decl.inputs.len() == 1 {
3555                                ("the", "")
3556                            } else {
3557                                ("one of the", "s")
3558                            };
3559                            err.multipart_suggestion_verbose(
3560                                format!(
3561                                    "instead, you are more likely to want to change {the} \
3562                                     argument{s} to be borrowed...",
3563                                ),
3564                                sugg,
3565                                Applicability::MaybeIncorrect,
3566                            );
3567                            "...or alternatively, you might want"
3568                        } else if (lt.kind == MissingLifetimeKind::Ampersand
3569                            || lt.kind == MissingLifetimeKind::Underscore)
3570                            && let Some((kind, _span)) = self.diag_metadata.current_function
3571                            && let FnKind::Fn(_, _, ast::Fn { sig, .. }) = kind
3572                            && let ast::FnRetTy::Ty(ret_ty) = &sig.decl.output
3573                            && !sig.decl.inputs.is_empty()
3574                            && let arg_refs = sig
3575                                .decl
3576                                .inputs
3577                                .iter()
3578                                .filter_map(|param| match &param.ty.kind {
3579                                    TyKind::ImplTrait(_, bounds) => Some(bounds),
3580                                    _ => None,
3581                                })
3582                                .flat_map(|bounds| bounds.into_iter())
3583                                .collect::<Vec<_>>()
3584                            && !arg_refs.is_empty()
3585                        {
3586                            // We have a situation like
3587                            // fn g(mut x: impl Iterator<Item = &()>) -> Option<&()>
3588                            // So we look at every ref in the trait bound. If there's any, we
3589                            // suggest
3590                            // fn g<'a>(mut x: impl Iterator<Item = &'a ()>) -> Option<&'a ()>
3591                            let mut lt_finder =
3592                                LifetimeFinder { lifetime: lt.span, found: None, seen: vec![] };
3593                            for bound in arg_refs {
3594                                if let ast::GenericBound::Trait(trait_ref) = bound {
3595                                    lt_finder.visit_trait_ref(&trait_ref.trait_ref);
3596                                }
3597                            }
3598                            lt_finder.visit_ty(ret_ty);
3599                            let spans_suggs: Vec<_> = lt_finder
3600                                .seen
3601                                .iter()
3602                                .filter_map(|ty| match &ty.kind {
3603                                    TyKind::Ref(_, mut_ty) => {
3604                                        let span = ty.span.with_hi(mut_ty.ty.span.lo());
3605                                        Some((span, "&'a ".to_string()))
3606                                    }
3607                                    _ => None,
3608                                })
3609                                .collect();
3610                            self.suggest_introducing_lifetime(
3611                                err,
3612                                None,
3613                                |err, higher_ranked, span, message, intro_sugg, _| {
3614                                    err.multipart_suggestion_verbose(
3615                                        message,
3616                                        std::iter::once((span, intro_sugg))
3617                                            .chain(spans_suggs.clone())
3618                                            .collect(),
3619                                        Applicability::MaybeIncorrect,
3620                                    );
3621                                    higher_ranked
3622                                },
3623                            );
3624                            "alternatively, you might want"
3625                        } else {
3626                            "instead, you are more likely to want"
3627                        };
3628                        let mut owned_sugg = lt.kind == MissingLifetimeKind::Ampersand;
3629                        let mut sugg = vec![(lt.span, String::new())];
3630                        if let Some((kind, _span)) = self.diag_metadata.current_function
3631                            && let FnKind::Fn(_, _, ast::Fn { sig, .. }) = kind
3632                            && let ast::FnRetTy::Ty(ty) = &sig.decl.output
3633                        {
3634                            let mut lt_finder =
3635                                LifetimeFinder { lifetime: lt.span, found: None, seen: vec![] };
3636                            lt_finder.visit_ty(&ty);
3637
3638                            if let [Ty { span, kind: TyKind::Ref(_, mut_ty), .. }] =
3639                                &lt_finder.seen[..]
3640                            {
3641                                // We might have a situation like
3642                                // fn g(mut x: impl Iterator<Item = &'_ ()>) -> Option<&'_ ()>
3643                                // but `lt.span` only points at `'_`, so to suggest `-> Option<()>`
3644                                // we need to find a more accurate span to end up with
3645                                // fn g<'a>(mut x: impl Iterator<Item = &'_ ()>) -> Option<()>
3646                                sugg = vec![(span.with_hi(mut_ty.ty.span.lo()), String::new())];
3647                                owned_sugg = true;
3648                            }
3649                            if let Some(ty) = lt_finder.found {
3650                                if let TyKind::Path(None, path) = &ty.kind {
3651                                    // Check if the path being borrowed is likely to be owned.
3652                                    let path: Vec<_> = Segment::from_path(path);
3653                                    match self.resolve_path(
3654                                        &path,
3655                                        Some(TypeNS),
3656                                        None,
3657                                        PathSource::Type,
3658                                    ) {
3659                                        PathResult::Module(ModuleOrUniformRoot::Module(module)) => {
3660                                            match module.res() {
3661                                                Some(Res::PrimTy(PrimTy::Str)) => {
3662                                                    // Don't suggest `-> str`, suggest `-> String`.
3663                                                    sugg = vec![(
3664                                                        lt.span.with_hi(ty.span.hi()),
3665                                                        "String".to_string(),
3666                                                    )];
3667                                                }
3668                                                Some(Res::PrimTy(..)) => {}
3669                                                Some(Res::Def(
3670                                                    DefKind::Struct
3671                                                    | DefKind::Union
3672                                                    | DefKind::Enum
3673                                                    | DefKind::ForeignTy
3674                                                    | DefKind::AssocTy
3675                                                    | DefKind::OpaqueTy
3676                                                    | DefKind::TyParam,
3677                                                    _,
3678                                                )) => {}
3679                                                _ => {
3680                                                    // Do not suggest in all other cases.
3681                                                    owned_sugg = false;
3682                                                }
3683                                            }
3684                                        }
3685                                        PathResult::NonModule(res) => {
3686                                            match res.base_res() {
3687                                                Res::PrimTy(PrimTy::Str) => {
3688                                                    // Don't suggest `-> str`, suggest `-> String`.
3689                                                    sugg = vec![(
3690                                                        lt.span.with_hi(ty.span.hi()),
3691                                                        "String".to_string(),
3692                                                    )];
3693                                                }
3694                                                Res::PrimTy(..) => {}
3695                                                Res::Def(
3696                                                    DefKind::Struct
3697                                                    | DefKind::Union
3698                                                    | DefKind::Enum
3699                                                    | DefKind::ForeignTy
3700                                                    | DefKind::AssocTy
3701                                                    | DefKind::OpaqueTy
3702                                                    | DefKind::TyParam,
3703                                                    _,
3704                                                ) => {}
3705                                                _ => {
3706                                                    // Do not suggest in all other cases.
3707                                                    owned_sugg = false;
3708                                                }
3709                                            }
3710                                        }
3711                                        _ => {
3712                                            // Do not suggest in all other cases.
3713                                            owned_sugg = false;
3714                                        }
3715                                    }
3716                                }
3717                                if let TyKind::Slice(inner_ty) = &ty.kind {
3718                                    // Don't suggest `-> [T]`, suggest `-> Vec<T>`.
3719                                    sugg = vec![
3720                                        (lt.span.with_hi(inner_ty.span.lo()), "Vec<".to_string()),
3721                                        (ty.span.with_lo(inner_ty.span.hi()), ">".to_string()),
3722                                    ];
3723                                }
3724                            }
3725                        }
3726                        if owned_sugg {
3727                            err.multipart_suggestion_verbose(
3728                                format!("{pre} to return an owned value"),
3729                                sugg,
3730                                Applicability::MaybeIncorrect,
3731                            );
3732                        }
3733                    }
3734                }
3735            }
3736            _ => {
3737                let lifetime_spans: Vec<_> =
3738                    in_scope_lifetimes.iter().map(|(ident, _)| ident.span).collect();
3739                err.span_note(lifetime_spans, "these named lifetimes are available to use");
3740
3741                if spans_suggs.len() > 0 {
3742                    // This happens when we have `Foo<T>` where we point at the space before `T`,
3743                    // but this can be confusing so we give a suggestion with placeholders.
3744                    err.multipart_suggestion_verbose(
3745                        "consider using one of the available lifetimes here",
3746                        spans_suggs,
3747                        Applicability::HasPlaceholders,
3748                    );
3749                }
3750            }
3751        }
3752    }
3753}
3754
3755fn mk_where_bound_predicate(
3756    path: &Path,
3757    poly_trait_ref: &ast::PolyTraitRef,
3758    ty: &Ty,
3759) -> Option<ast::WhereBoundPredicate> {
3760    let modified_segments = {
3761        let mut segments = path.segments.clone();
3762        let [preceding @ .., second_last, last] = segments.as_mut_slice() else {
3763            return None;
3764        };
3765        let mut segments = ThinVec::from(preceding);
3766
3767        let added_constraint = ast::AngleBracketedArg::Constraint(ast::AssocItemConstraint {
3768            id: DUMMY_NODE_ID,
3769            ident: last.ident,
3770            gen_args: None,
3771            kind: ast::AssocItemConstraintKind::Equality {
3772                term: ast::Term::Ty(Box::new(ast::Ty {
3773                    kind: ast::TyKind::Path(None, poly_trait_ref.trait_ref.path.clone()),
3774                    id: DUMMY_NODE_ID,
3775                    span: DUMMY_SP,
3776                    tokens: None,
3777                })),
3778            },
3779            span: DUMMY_SP,
3780        });
3781
3782        match second_last.args.as_deref_mut() {
3783            Some(ast::GenericArgs::AngleBracketed(ast::AngleBracketedArgs { args, .. })) => {
3784                args.push(added_constraint);
3785            }
3786            Some(_) => return None,
3787            None => {
3788                second_last.args =
3789                    Some(Box::new(ast::GenericArgs::AngleBracketed(ast::AngleBracketedArgs {
3790                        args: ThinVec::from([added_constraint]),
3791                        span: DUMMY_SP,
3792                    })));
3793            }
3794        }
3795
3796        segments.push(second_last.clone());
3797        segments
3798    };
3799
3800    let new_where_bound_predicate = ast::WhereBoundPredicate {
3801        bound_generic_params: ThinVec::new(),
3802        bounded_ty: Box::new(ty.clone()),
3803        bounds: vec![ast::GenericBound::Trait(ast::PolyTraitRef {
3804            bound_generic_params: ThinVec::new(),
3805            modifiers: ast::TraitBoundModifiers::NONE,
3806            trait_ref: ast::TraitRef {
3807                path: ast::Path { segments: modified_segments, span: DUMMY_SP, tokens: None },
3808                ref_id: DUMMY_NODE_ID,
3809            },
3810            span: DUMMY_SP,
3811            parens: ast::Parens::No,
3812        })],
3813    };
3814
3815    Some(new_where_bound_predicate)
3816}
3817
3818/// Report lifetime/lifetime shadowing as an error.
3819pub(super) fn signal_lifetime_shadowing(sess: &Session, orig: Ident, shadower: Ident) {
3820    struct_span_code_err!(
3821        sess.dcx(),
3822        shadower.span,
3823        E0496,
3824        "lifetime name `{}` shadows a lifetime name that is already in scope",
3825        orig.name,
3826    )
3827    .with_span_label(orig.span, "first declared here")
3828    .with_span_label(shadower.span, format!("lifetime `{}` already in scope", orig.name))
3829    .emit();
3830}
3831
3832struct LifetimeFinder<'ast> {
3833    lifetime: Span,
3834    found: Option<&'ast Ty>,
3835    seen: Vec<&'ast Ty>,
3836}
3837
3838impl<'ast> Visitor<'ast> for LifetimeFinder<'ast> {
3839    fn visit_ty(&mut self, t: &'ast Ty) {
3840        if let TyKind::Ref(_, mut_ty) | TyKind::PinnedRef(_, mut_ty) = &t.kind {
3841            self.seen.push(t);
3842            if t.span.lo() == self.lifetime.lo() {
3843                self.found = Some(&mut_ty.ty);
3844            }
3845        }
3846        walk_ty(self, t)
3847    }
3848}
3849
3850/// Shadowing involving a label is only a warning for historical reasons.
3851//FIXME: make this a proper lint.
3852pub(super) fn signal_label_shadowing(sess: &Session, orig: Span, shadower: Ident) {
3853    let name = shadower.name;
3854    let shadower = shadower.span;
3855    sess.dcx()
3856        .struct_span_warn(
3857            shadower,
3858            format!("label name `{name}` shadows a label name that is already in scope"),
3859        )
3860        .with_span_label(orig, "first declared here")
3861        .with_span_label(shadower, format!("label `{name}` already in scope"))
3862        .emit();
3863}