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