rustc_resolve/late/
diagnostics.rs

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