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