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