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