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