rustc_resolve/late/
diagnostics.rs

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