rustc_resolve/
late.rs

1// ignore-tidy-filelength
2//! "Late resolution" is the pass that resolves most of names in a crate beside imports and macros.
3//! It runs when the crate is fully expanded and its module structure is fully built.
4//! So it just walks through the crate and resolves all the expressions, types, etc.
5//!
6//! If you wonder why there's no `early.rs`, that's because it's split into three files -
7//! `build_reduced_graph.rs`, `macros.rs` and `imports.rs`.
8
9use std::assert_matches::debug_assert_matches;
10use std::borrow::Cow;
11use std::collections::BTreeSet;
12use std::collections::hash_map::Entry;
13use std::mem::{replace, swap, take};
14
15use rustc_ast::ptr::P;
16use rustc_ast::visit::{
17    AssocCtxt, BoundKind, FnCtxt, FnKind, Visitor, try_visit, visit_opt, walk_list,
18};
19use rustc_ast::*;
20use rustc_data_structures::fx::{FxHashMap, FxHashSet, FxIndexMap};
21use rustc_data_structures::unord::{UnordMap, UnordSet};
22use rustc_errors::codes::*;
23use rustc_errors::{
24    Applicability, DiagArgValue, ErrorGuaranteed, IntoDiagArg, StashKey, Suggestions,
25};
26use rustc_hir::def::Namespace::{self, *};
27use rustc_hir::def::{self, CtorKind, DefKind, LifetimeRes, NonMacroAttrKind, PartialRes, PerNS};
28use rustc_hir::def_id::{CRATE_DEF_ID, DefId, LOCAL_CRATE, LocalDefId};
29use rustc_hir::{MissingLifetimeKind, PrimTy, TraitCandidate};
30use rustc_middle::middle::resolve_bound_vars::Set1;
31use rustc_middle::ty::{DelegationFnSig, Visibility};
32use rustc_middle::{bug, span_bug};
33use rustc_session::config::{CrateType, ResolveDocLinks};
34use rustc_session::lint::{self, BuiltinLintDiag};
35use rustc_session::parse::feature_err;
36use rustc_span::source_map::{Spanned, respan};
37use rustc_span::{BytePos, Ident, Span, Symbol, SyntaxContext, kw, sym};
38use smallvec::{SmallVec, smallvec};
39use thin_vec::ThinVec;
40use tracing::{debug, instrument, trace};
41
42use crate::{
43    BindingError, BindingKey, Finalize, LexicalScopeBinding, Module, ModuleOrUniformRoot,
44    NameBinding, ParentScope, PathResult, ResolutionError, Resolver, Segment, TyCtxt, UseError,
45    Used, errors, path_names_to_string, rustdoc,
46};
47
48mod diagnostics;
49
50type Res = def::Res<NodeId>;
51
52use diagnostics::{ElisionFnParameter, LifetimeElisionCandidate, MissingLifetime};
53
54#[derive(Copy, Clone, Debug)]
55struct BindingInfo {
56    span: Span,
57    annotation: BindingMode,
58}
59
60#[derive(Copy, Clone, PartialEq, Eq, Debug)]
61pub(crate) enum PatternSource {
62    Match,
63    Let,
64    For,
65    FnParam,
66}
67
68#[derive(Copy, Clone, Debug, PartialEq, Eq)]
69enum IsRepeatExpr {
70    No,
71    Yes,
72}
73
74struct IsNeverPattern;
75
76/// Describes whether an `AnonConst` is a type level const arg or
77/// some other form of anon const (i.e. inline consts or enum discriminants)
78#[derive(Copy, Clone, Debug, PartialEq, Eq)]
79enum AnonConstKind {
80    EnumDiscriminant,
81    FieldDefaultValue,
82    InlineConst,
83    ConstArg(IsRepeatExpr),
84}
85
86impl PatternSource {
87    fn descr(self) -> &'static str {
88        match self {
89            PatternSource::Match => "match binding",
90            PatternSource::Let => "let binding",
91            PatternSource::For => "for binding",
92            PatternSource::FnParam => "function parameter",
93        }
94    }
95}
96
97impl IntoDiagArg for PatternSource {
98    fn into_diag_arg(self, _: &mut Option<std::path::PathBuf>) -> DiagArgValue {
99        DiagArgValue::Str(Cow::Borrowed(self.descr()))
100    }
101}
102
103/// Denotes whether the context for the set of already bound bindings is a `Product`
104/// or `Or` context. This is used in e.g., `fresh_binding` and `resolve_pattern_inner`.
105/// See those functions for more information.
106#[derive(PartialEq)]
107enum PatBoundCtx {
108    /// A product pattern context, e.g., `Variant(a, b)`.
109    Product,
110    /// An or-pattern context, e.g., `p_0 | ... | p_n`.
111    Or,
112}
113
114/// Tracks bindings resolved within a pattern. This serves two purposes:
115///
116/// - This tracks when identifiers are bound multiple times within a pattern. In a product context,
117///   this is an error. In an or-pattern, this lets us reuse the same resolution for each instance.
118///   See `fresh_binding` and `resolve_pattern_inner` for more information.
119///
120/// - The guard expression of a guard pattern may use bindings from within the guard pattern, but
121///   not from elsewhere in the pattern containing it. This allows us to isolate the bindings in the
122///   subpattern to construct the scope for the guard.
123///
124/// Each identifier must map to at most one distinct [`Res`].
125type PatternBindings = SmallVec<[(PatBoundCtx, FxIndexMap<Ident, Res>); 1]>;
126
127/// Does this the item (from the item rib scope) allow generic parameters?
128#[derive(Copy, Clone, Debug)]
129pub(crate) enum HasGenericParams {
130    Yes(Span),
131    No,
132}
133
134/// May this constant have generics?
135#[derive(Copy, Clone, Debug, Eq, PartialEq)]
136pub(crate) enum ConstantHasGenerics {
137    Yes,
138    No(NoConstantGenericsReason),
139}
140
141impl ConstantHasGenerics {
142    fn force_yes_if(self, b: bool) -> Self {
143        if b { Self::Yes } else { self }
144    }
145}
146
147/// Reason for why an anon const is not allowed to reference generic parameters
148#[derive(Copy, Clone, Debug, Eq, PartialEq)]
149pub(crate) enum NoConstantGenericsReason {
150    /// Const arguments are only allowed to use generic parameters when:
151    /// - `feature(generic_const_exprs)` is enabled
152    /// or
153    /// - the const argument is a sole const generic parameter, i.e. `foo::<{ N }>()`
154    ///
155    /// If neither of the above are true then this is used as the cause.
156    NonTrivialConstArg,
157    /// Enum discriminants are not allowed to reference generic parameters ever, this
158    /// is used when an anon const is in the following position:
159    ///
160    /// ```rust,compile_fail
161    /// enum Foo<const N: isize> {
162    ///     Variant = { N }, // this anon const is not allowed to use generics
163    /// }
164    /// ```
165    IsEnumDiscriminant,
166}
167
168#[derive(Copy, Clone, Debug, Eq, PartialEq)]
169pub(crate) enum ConstantItemKind {
170    Const,
171    Static,
172}
173
174impl ConstantItemKind {
175    pub(crate) fn as_str(&self) -> &'static str {
176        match self {
177            Self::Const => "const",
178            Self::Static => "static",
179        }
180    }
181}
182
183#[derive(Debug, Copy, Clone, PartialEq, Eq)]
184enum RecordPartialRes {
185    Yes,
186    No,
187}
188
189/// The rib kind restricts certain accesses,
190/// e.g. to a `Res::Local` of an outer item.
191#[derive(Copy, Clone, Debug)]
192pub(crate) enum RibKind<'ra> {
193    /// No restriction needs to be applied.
194    Normal,
195
196    /// We passed through an impl or trait and are now in one of its
197    /// methods or associated types. Allow references to ty params that impl or trait
198    /// binds. Disallow any other upvars (including other ty params that are
199    /// upvars).
200    AssocItem,
201
202    /// We passed through a function, closure or coroutine signature. Disallow labels.
203    FnOrCoroutine,
204
205    /// We passed through an item scope. Disallow upvars.
206    Item(HasGenericParams, DefKind),
207
208    /// We're in a constant item. Can't refer to dynamic stuff.
209    ///
210    /// The item may reference generic parameters in trivial constant expressions.
211    /// All other constants aren't allowed to use generic params at all.
212    ConstantItem(ConstantHasGenerics, Option<(Ident, ConstantItemKind)>),
213
214    /// We passed through a module.
215    Module(Module<'ra>),
216
217    /// We passed through a `macro_rules!` statement
218    MacroDefinition(DefId),
219
220    /// All bindings in this rib are generic parameters that can't be used
221    /// from the default of a generic parameter because they're not declared
222    /// before said generic parameter. Also see the `visit_generics` override.
223    ForwardGenericParamBan(ForwardGenericParamBanReason),
224
225    /// We are inside of the type of a const parameter. Can't refer to any
226    /// parameters.
227    ConstParamTy,
228
229    /// We are inside a `sym` inline assembly operand. Can only refer to
230    /// globals.
231    InlineAsmSym,
232}
233
234#[derive(Copy, Clone, PartialEq, Eq, Debug)]
235pub(crate) enum ForwardGenericParamBanReason {
236    Default,
237    ConstParamTy,
238}
239
240impl RibKind<'_> {
241    /// Whether this rib kind contains generic parameters, as opposed to local
242    /// variables.
243    pub(crate) fn contains_params(&self) -> bool {
244        match self {
245            RibKind::Normal
246            | RibKind::FnOrCoroutine
247            | RibKind::ConstantItem(..)
248            | RibKind::Module(_)
249            | RibKind::MacroDefinition(_)
250            | RibKind::InlineAsmSym => false,
251            RibKind::ConstParamTy
252            | RibKind::AssocItem
253            | RibKind::Item(..)
254            | RibKind::ForwardGenericParamBan(_) => true,
255        }
256    }
257
258    /// This rib forbids referring to labels defined in upwards ribs.
259    fn is_label_barrier(self) -> bool {
260        match self {
261            RibKind::Normal | RibKind::MacroDefinition(..) => false,
262
263            RibKind::AssocItem
264            | RibKind::FnOrCoroutine
265            | RibKind::Item(..)
266            | RibKind::ConstantItem(..)
267            | RibKind::Module(..)
268            | RibKind::ForwardGenericParamBan(_)
269            | RibKind::ConstParamTy
270            | RibKind::InlineAsmSym => true,
271        }
272    }
273}
274
275/// A single local scope.
276///
277/// A rib represents a scope names can live in. Note that these appear in many places, not just
278/// around braces. At any place where the list of accessible names (of the given namespace)
279/// changes or a new restrictions on the name accessibility are introduced, a new rib is put onto a
280/// stack. This may be, for example, a `let` statement (because it introduces variables), a macro,
281/// etc.
282///
283/// Different [rib kinds](enum@RibKind) are transparent for different names.
284///
285/// The resolution keeps a separate stack of ribs as it traverses the AST for each namespace. When
286/// resolving, the name is looked up from inside out.
287#[derive(Debug)]
288pub(crate) struct Rib<'ra, R = Res> {
289    pub bindings: FxIndexMap<Ident, R>,
290    pub patterns_with_skipped_bindings: UnordMap<DefId, Vec<(Span, Result<(), ErrorGuaranteed>)>>,
291    pub kind: RibKind<'ra>,
292}
293
294impl<'ra, R> Rib<'ra, R> {
295    fn new(kind: RibKind<'ra>) -> Rib<'ra, R> {
296        Rib {
297            bindings: Default::default(),
298            patterns_with_skipped_bindings: Default::default(),
299            kind,
300        }
301    }
302}
303
304#[derive(Clone, Copy, Debug)]
305enum LifetimeUseSet {
306    One { use_span: Span, use_ctxt: visit::LifetimeCtxt },
307    Many,
308}
309
310#[derive(Copy, Clone, Debug)]
311enum LifetimeRibKind {
312    // -- Ribs introducing named lifetimes
313    //
314    /// This rib declares generic parameters.
315    /// Only for this kind the `LifetimeRib::bindings` field can be non-empty.
316    Generics { binder: NodeId, span: Span, kind: LifetimeBinderKind },
317
318    // -- Ribs introducing unnamed lifetimes
319    //
320    /// Create a new anonymous lifetime parameter and reference it.
321    ///
322    /// If `report_in_path`, report an error when encountering lifetime elision in a path:
323    /// ```compile_fail
324    /// struct Foo<'a> { x: &'a () }
325    /// async fn foo(x: Foo) {}
326    /// ```
327    ///
328    /// Note: the error should not trigger when the elided lifetime is in a pattern or
329    /// expression-position path:
330    /// ```
331    /// struct Foo<'a> { x: &'a () }
332    /// async fn foo(Foo { x: _ }: Foo<'_>) {}
333    /// ```
334    AnonymousCreateParameter { binder: NodeId, report_in_path: bool },
335
336    /// Replace all anonymous lifetimes by provided lifetime.
337    Elided(LifetimeRes),
338
339    // -- Barrier ribs that stop lifetime lookup, or continue it but produce an error later.
340    //
341    /// Give a hard error when either `&` or `'_` is written. Used to
342    /// rule out things like `where T: Foo<'_>`. Does not imply an
343    /// error on default object bounds (e.g., `Box<dyn Foo>`).
344    AnonymousReportError,
345
346    /// Resolves elided lifetimes to `'static` if there are no other lifetimes in scope,
347    /// otherwise give a warning that the previous behavior of introducing a new early-bound
348    /// lifetime is a bug and will be removed (if `emit_lint` is enabled).
349    StaticIfNoLifetimeInScope { lint_id: NodeId, emit_lint: bool },
350
351    /// Signal we cannot find which should be the anonymous lifetime.
352    ElisionFailure,
353
354    /// This rib forbids usage of generic parameters inside of const parameter types.
355    ///
356    /// While this is desirable to support eventually, it is difficult to do and so is
357    /// currently forbidden. See rust-lang/project-const-generics#28 for more info.
358    ConstParamTy,
359
360    /// Usage of generic parameters is forbidden in various positions for anon consts:
361    /// - const arguments when `generic_const_exprs` is not enabled
362    /// - enum discriminant values
363    ///
364    /// This rib emits an error when a lifetime would resolve to a lifetime parameter.
365    ConcreteAnonConst(NoConstantGenericsReason),
366
367    /// This rib acts as a barrier to forbid reference to lifetimes of a parent item.
368    Item,
369}
370
371#[derive(Copy, Clone, Debug)]
372enum LifetimeBinderKind {
373    FnPtrType,
374    PolyTrait,
375    WhereBound,
376    Item,
377    ConstItem,
378    Function,
379    Closure,
380    ImplBlock,
381}
382
383impl LifetimeBinderKind {
384    fn descr(self) -> &'static str {
385        use LifetimeBinderKind::*;
386        match self {
387            FnPtrType => "type",
388            PolyTrait => "bound",
389            WhereBound => "bound",
390            Item | ConstItem => "item",
391            ImplBlock => "impl block",
392            Function => "function",
393            Closure => "closure",
394        }
395    }
396}
397
398#[derive(Debug)]
399struct LifetimeRib {
400    kind: LifetimeRibKind,
401    // We need to preserve insertion order for async fns.
402    bindings: FxIndexMap<Ident, (NodeId, LifetimeRes)>,
403}
404
405impl LifetimeRib {
406    fn new(kind: LifetimeRibKind) -> LifetimeRib {
407        LifetimeRib { bindings: Default::default(), kind }
408    }
409}
410
411#[derive(Copy, Clone, PartialEq, Eq, Debug)]
412pub(crate) enum AliasPossibility {
413    No,
414    Maybe,
415}
416
417#[derive(Copy, Clone, Debug)]
418pub(crate) enum PathSource<'a, 'ast, 'ra> {
419    /// Type paths `Path`.
420    Type,
421    /// Trait paths in bounds or impls.
422    Trait(AliasPossibility),
423    /// Expression paths `path`, with optional parent context.
424    Expr(Option<&'ast Expr>),
425    /// Paths in path patterns `Path`.
426    Pat,
427    /// Paths in struct expressions and patterns `Path { .. }`.
428    Struct,
429    /// Paths in tuple struct patterns `Path(..)`.
430    TupleStruct(Span, &'ra [Span]),
431    /// `m::A::B` in `<T as m::A>::B::C`.
432    ///
433    /// Second field holds the "cause" of this one, i.e. the context within
434    /// which the trait item is resolved. Used for diagnostics.
435    TraitItem(Namespace, &'a PathSource<'a, 'ast, 'ra>),
436    /// Paths in delegation item
437    Delegation,
438    /// An arg in a `use<'a, N>` precise-capturing bound.
439    PreciseCapturingArg(Namespace),
440    /// Paths that end with `(..)`, for return type notation.
441    ReturnTypeNotation,
442    /// Paths from `#[define_opaque]` attributes
443    DefineOpaques,
444}
445
446impl PathSource<'_, '_, '_> {
447    fn namespace(self) -> Namespace {
448        match self {
449            PathSource::Type
450            | PathSource::Trait(_)
451            | PathSource::Struct
452            | PathSource::DefineOpaques => TypeNS,
453            PathSource::Expr(..)
454            | PathSource::Pat
455            | PathSource::TupleStruct(..)
456            | PathSource::Delegation
457            | PathSource::ReturnTypeNotation => ValueNS,
458            PathSource::TraitItem(ns, _) => ns,
459            PathSource::PreciseCapturingArg(ns) => ns,
460        }
461    }
462
463    fn defer_to_typeck(self) -> bool {
464        match self {
465            PathSource::Type
466            | PathSource::Expr(..)
467            | PathSource::Pat
468            | PathSource::Struct
469            | PathSource::TupleStruct(..)
470            | PathSource::ReturnTypeNotation => true,
471            PathSource::Trait(_)
472            | PathSource::TraitItem(..)
473            | PathSource::DefineOpaques
474            | PathSource::Delegation
475            | PathSource::PreciseCapturingArg(..) => false,
476        }
477    }
478
479    fn descr_expected(self) -> &'static str {
480        match &self {
481            PathSource::DefineOpaques => "type alias or associated type with opaqaue types",
482            PathSource::Type => "type",
483            PathSource::Trait(_) => "trait",
484            PathSource::Pat => "unit struct, unit variant or constant",
485            PathSource::Struct => "struct, variant or union type",
486            PathSource::TraitItem(ValueNS, PathSource::TupleStruct(..))
487            | PathSource::TupleStruct(..) => "tuple struct or tuple variant",
488            PathSource::TraitItem(ns, _) => match ns {
489                TypeNS => "associated type",
490                ValueNS => "method or associated constant",
491                MacroNS => bug!("associated macro"),
492            },
493            PathSource::Expr(parent) => match parent.as_ref().map(|p| &p.kind) {
494                // "function" here means "anything callable" rather than `DefKind::Fn`,
495                // this is not precise but usually more helpful than just "value".
496                Some(ExprKind::Call(call_expr, _)) => match &call_expr.kind {
497                    // the case of `::some_crate()`
498                    ExprKind::Path(_, path)
499                        if let [segment, _] = path.segments.as_slice()
500                            && segment.ident.name == kw::PathRoot =>
501                    {
502                        "external crate"
503                    }
504                    ExprKind::Path(_, path)
505                        if let Some(segment) = path.segments.last()
506                            && let Some(c) = segment.ident.to_string().chars().next()
507                            && c.is_uppercase() =>
508                    {
509                        "function, tuple struct or tuple variant"
510                    }
511                    _ => "function",
512                },
513                _ => "value",
514            },
515            PathSource::ReturnTypeNotation | PathSource::Delegation => "function",
516            PathSource::PreciseCapturingArg(..) => "type or const parameter",
517        }
518    }
519
520    fn is_call(self) -> bool {
521        matches!(self, PathSource::Expr(Some(&Expr { kind: ExprKind::Call(..), .. })))
522    }
523
524    pub(crate) fn is_expected(self, res: Res) -> bool {
525        match self {
526            PathSource::DefineOpaques => {
527                matches!(
528                    res,
529                    Res::Def(
530                        DefKind::Struct
531                            | DefKind::Union
532                            | DefKind::Enum
533                            | DefKind::TyAlias
534                            | DefKind::AssocTy,
535                        _
536                    ) | Res::SelfTyAlias { .. }
537                )
538            }
539            PathSource::Type => matches!(
540                res,
541                Res::Def(
542                    DefKind::Struct
543                        | DefKind::Union
544                        | DefKind::Enum
545                        | DefKind::Trait
546                        | DefKind::TraitAlias
547                        | DefKind::TyAlias
548                        | DefKind::AssocTy
549                        | DefKind::TyParam
550                        | DefKind::OpaqueTy
551                        | DefKind::ForeignTy,
552                    _,
553                ) | Res::PrimTy(..)
554                    | Res::SelfTyParam { .. }
555                    | Res::SelfTyAlias { .. }
556            ),
557            PathSource::Trait(AliasPossibility::No) => matches!(res, Res::Def(DefKind::Trait, _)),
558            PathSource::Trait(AliasPossibility::Maybe) => {
559                matches!(res, Res::Def(DefKind::Trait | DefKind::TraitAlias, _))
560            }
561            PathSource::Expr(..) => matches!(
562                res,
563                Res::Def(
564                    DefKind::Ctor(_, CtorKind::Const | CtorKind::Fn)
565                        | DefKind::Const
566                        | DefKind::Static { .. }
567                        | DefKind::Fn
568                        | DefKind::AssocFn
569                        | DefKind::AssocConst
570                        | DefKind::ConstParam,
571                    _,
572                ) | Res::Local(..)
573                    | Res::SelfCtor(..)
574            ),
575            PathSource::Pat => {
576                res.expected_in_unit_struct_pat()
577                    || matches!(res, Res::Def(DefKind::Const | DefKind::AssocConst, _))
578            }
579            PathSource::TupleStruct(..) => res.expected_in_tuple_struct_pat(),
580            PathSource::Struct => matches!(
581                res,
582                Res::Def(
583                    DefKind::Struct
584                        | DefKind::Union
585                        | DefKind::Variant
586                        | DefKind::TyAlias
587                        | DefKind::AssocTy,
588                    _,
589                ) | Res::SelfTyParam { .. }
590                    | Res::SelfTyAlias { .. }
591            ),
592            PathSource::TraitItem(ns, _) => match res {
593                Res::Def(DefKind::AssocConst | DefKind::AssocFn, _) if ns == ValueNS => true,
594                Res::Def(DefKind::AssocTy, _) if ns == TypeNS => true,
595                _ => false,
596            },
597            PathSource::ReturnTypeNotation => match res {
598                Res::Def(DefKind::AssocFn, _) => true,
599                _ => false,
600            },
601            PathSource::Delegation => matches!(res, Res::Def(DefKind::Fn | DefKind::AssocFn, _)),
602            PathSource::PreciseCapturingArg(ValueNS) => {
603                matches!(res, Res::Def(DefKind::ConstParam, _))
604            }
605            // We allow `SelfTyAlias` here so we can give a more descriptive error later.
606            PathSource::PreciseCapturingArg(TypeNS) => matches!(
607                res,
608                Res::Def(DefKind::TyParam, _) | Res::SelfTyParam { .. } | Res::SelfTyAlias { .. }
609            ),
610            PathSource::PreciseCapturingArg(MacroNS) => false,
611        }
612    }
613
614    fn error_code(self, has_unexpected_resolution: bool) -> ErrCode {
615        match (self, has_unexpected_resolution) {
616            (PathSource::Trait(_), true) => E0404,
617            (PathSource::Trait(_), false) => E0405,
618            (PathSource::Type | PathSource::DefineOpaques, true) => E0573,
619            (PathSource::Type | PathSource::DefineOpaques, false) => E0412,
620            (PathSource::Struct, true) => E0574,
621            (PathSource::Struct, false) => E0422,
622            (PathSource::Expr(..), true) | (PathSource::Delegation, true) => E0423,
623            (PathSource::Expr(..), false) | (PathSource::Delegation, false) => E0425,
624            (PathSource::Pat | PathSource::TupleStruct(..), true) => E0532,
625            (PathSource::Pat | PathSource::TupleStruct(..), false) => E0531,
626            (PathSource::TraitItem(..) | PathSource::ReturnTypeNotation, true) => E0575,
627            (PathSource::TraitItem(..) | PathSource::ReturnTypeNotation, false) => E0576,
628            (PathSource::PreciseCapturingArg(..), true) => E0799,
629            (PathSource::PreciseCapturingArg(..), false) => E0800,
630        }
631    }
632}
633
634/// At this point for most items we can answer whether that item is exported or not,
635/// but some items like impls require type information to determine exported-ness, so we make a
636/// conservative estimate for them (e.g. based on nominal visibility).
637#[derive(Clone, Copy)]
638enum MaybeExported<'a> {
639    Ok(NodeId),
640    Impl(Option<DefId>),
641    ImplItem(Result<DefId, &'a ast::Visibility>),
642    NestedUse(&'a ast::Visibility),
643}
644
645impl MaybeExported<'_> {
646    fn eval(self, r: &Resolver<'_, '_>) -> bool {
647        let def_id = match self {
648            MaybeExported::Ok(node_id) => Some(r.local_def_id(node_id)),
649            MaybeExported::Impl(Some(trait_def_id)) | MaybeExported::ImplItem(Ok(trait_def_id)) => {
650                trait_def_id.as_local()
651            }
652            MaybeExported::Impl(None) => return true,
653            MaybeExported::ImplItem(Err(vis)) | MaybeExported::NestedUse(vis) => {
654                return vis.kind.is_pub();
655            }
656        };
657        def_id.is_none_or(|def_id| r.effective_visibilities.is_exported(def_id))
658    }
659}
660
661/// Used for recording UnnecessaryQualification.
662#[derive(Debug)]
663pub(crate) struct UnnecessaryQualification<'ra> {
664    pub binding: LexicalScopeBinding<'ra>,
665    pub node_id: NodeId,
666    pub path_span: Span,
667    pub removal_span: Span,
668}
669
670#[derive(Default, Debug)]
671struct DiagMetadata<'ast> {
672    /// The current trait's associated items' ident, used for diagnostic suggestions.
673    current_trait_assoc_items: Option<&'ast [P<AssocItem>]>,
674
675    /// The current self type if inside an impl (used for better errors).
676    current_self_type: Option<Ty>,
677
678    /// The current self item if inside an ADT (used for better errors).
679    current_self_item: Option<NodeId>,
680
681    /// The current trait (used to suggest).
682    current_item: Option<&'ast Item>,
683
684    /// When processing generic arguments and encountering an unresolved ident not found,
685    /// suggest introducing a type or const param depending on the context.
686    currently_processing_generic_args: bool,
687
688    /// The current enclosing (non-closure) function (used for better errors).
689    current_function: Option<(FnKind<'ast>, Span)>,
690
691    /// A list of labels as of yet unused. Labels will be removed from this map when
692    /// they are used (in a `break` or `continue` statement)
693    unused_labels: FxIndexMap<NodeId, Span>,
694
695    /// Only used for better errors on `let <pat>: <expr, not type>;`.
696    current_let_binding: Option<(Span, Option<Span>, Option<Span>)>,
697
698    current_pat: Option<&'ast Pat>,
699
700    /// Used to detect possible `if let` written without `let` and to provide structured suggestion.
701    in_if_condition: Option<&'ast Expr>,
702
703    /// Used to detect possible new binding written without `let` and to provide structured suggestion.
704    in_assignment: Option<&'ast Expr>,
705    is_assign_rhs: bool,
706
707    /// If we are setting an associated type in trait impl, is it a non-GAT type?
708    in_non_gat_assoc_type: Option<bool>,
709
710    /// Used to detect possible `.` -> `..` typo when calling methods.
711    in_range: Option<(&'ast Expr, &'ast Expr)>,
712
713    /// If we are currently in a trait object definition. Used to point at the bounds when
714    /// encountering a struct or enum.
715    current_trait_object: Option<&'ast [ast::GenericBound]>,
716
717    /// Given `where <T as Bar>::Baz: String`, suggest `where T: Bar<Baz = String>`.
718    current_where_predicate: Option<&'ast WherePredicate>,
719
720    current_type_path: Option<&'ast Ty>,
721
722    /// The current impl items (used to suggest).
723    current_impl_items: Option<&'ast [P<AssocItem>]>,
724
725    /// When processing impl trait
726    currently_processing_impl_trait: Option<(TraitRef, Ty)>,
727
728    /// Accumulate the errors due to missed lifetime elision,
729    /// and report them all at once for each function.
730    current_elision_failures: Vec<MissingLifetime>,
731}
732
733struct LateResolutionVisitor<'a, 'ast, 'ra, 'tcx> {
734    r: &'a mut Resolver<'ra, 'tcx>,
735
736    /// The module that represents the current item scope.
737    parent_scope: ParentScope<'ra>,
738
739    /// The current set of local scopes for types and values.
740    ribs: PerNS<Vec<Rib<'ra>>>,
741
742    /// Previous popped `rib`, only used for diagnostic.
743    last_block_rib: Option<Rib<'ra>>,
744
745    /// The current set of local scopes, for labels.
746    label_ribs: Vec<Rib<'ra, NodeId>>,
747
748    /// The current set of local scopes for lifetimes.
749    lifetime_ribs: Vec<LifetimeRib>,
750
751    /// We are looking for lifetimes in an elision context.
752    /// The set contains all the resolutions that we encountered so far.
753    /// They will be used to determine the correct lifetime for the fn return type.
754    /// The `LifetimeElisionCandidate` is used for diagnostics, to suggest introducing named
755    /// lifetimes.
756    lifetime_elision_candidates: Option<Vec<(LifetimeRes, LifetimeElisionCandidate)>>,
757
758    /// The trait that the current context can refer to.
759    current_trait_ref: Option<(Module<'ra>, TraitRef)>,
760
761    /// Fields used to add information to diagnostic errors.
762    diag_metadata: Box<DiagMetadata<'ast>>,
763
764    /// State used to know whether to ignore resolution errors for function bodies.
765    ///
766    /// In particular, rustdoc uses this to avoid giving errors for `cfg()` items.
767    /// In most cases this will be `None`, in which case errors will always be reported.
768    /// If it is `true`, then it will be updated when entering a nested function or trait body.
769    in_func_body: bool,
770
771    /// Count the number of places a lifetime is used.
772    lifetime_uses: FxHashMap<LocalDefId, LifetimeUseSet>,
773}
774
775/// Walks the whole crate in DFS order, visiting each item, resolving names as it goes.
776impl<'ast, 'ra, 'tcx> Visitor<'ast> for LateResolutionVisitor<'_, 'ast, 'ra, 'tcx> {
777    fn visit_attribute(&mut self, _: &'ast Attribute) {
778        // We do not want to resolve expressions that appear in attributes,
779        // as they do not correspond to actual code.
780    }
781    fn visit_item(&mut self, item: &'ast Item) {
782        let prev = replace(&mut self.diag_metadata.current_item, Some(item));
783        // Always report errors in items we just entered.
784        let old_ignore = replace(&mut self.in_func_body, false);
785        self.with_lifetime_rib(LifetimeRibKind::Item, |this| this.resolve_item(item));
786        self.in_func_body = old_ignore;
787        self.diag_metadata.current_item = prev;
788    }
789    fn visit_arm(&mut self, arm: &'ast Arm) {
790        self.resolve_arm(arm);
791    }
792    fn visit_block(&mut self, block: &'ast Block) {
793        let old_macro_rules = self.parent_scope.macro_rules;
794        self.resolve_block(block);
795        self.parent_scope.macro_rules = old_macro_rules;
796    }
797    fn visit_anon_const(&mut self, constant: &'ast AnonConst) {
798        bug!("encountered anon const without a manual call to `resolve_anon_const`: {constant:#?}");
799    }
800    fn visit_expr(&mut self, expr: &'ast Expr) {
801        self.resolve_expr(expr, None);
802    }
803    fn visit_pat(&mut self, p: &'ast Pat) {
804        let prev = self.diag_metadata.current_pat;
805        self.diag_metadata.current_pat = Some(p);
806
807        if let PatKind::Guard(subpat, _) = &p.kind {
808            // We walk the guard expression in `resolve_pattern_inner`. Don't resolve it twice.
809            self.visit_pat(subpat);
810        } else {
811            visit::walk_pat(self, p);
812        }
813
814        self.diag_metadata.current_pat = prev;
815    }
816    fn visit_local(&mut self, local: &'ast Local) {
817        let local_spans = match local.pat.kind {
818            // We check for this to avoid tuple struct fields.
819            PatKind::Wild => None,
820            _ => Some((
821                local.pat.span,
822                local.ty.as_ref().map(|ty| ty.span),
823                local.kind.init().map(|init| init.span),
824            )),
825        };
826        let original = replace(&mut self.diag_metadata.current_let_binding, local_spans);
827        self.resolve_local(local);
828        self.diag_metadata.current_let_binding = original;
829    }
830    fn visit_ty(&mut self, ty: &'ast Ty) {
831        let prev = self.diag_metadata.current_trait_object;
832        let prev_ty = self.diag_metadata.current_type_path;
833        match &ty.kind {
834            TyKind::Ref(None, _) | TyKind::PinnedRef(None, _) => {
835                // Elided lifetime in reference: we resolve as if there was some lifetime `'_` with
836                // NodeId `ty.id`.
837                // This span will be used in case of elision failure.
838                let span = self.r.tcx.sess.source_map().start_point(ty.span);
839                self.resolve_elided_lifetime(ty.id, span);
840                visit::walk_ty(self, ty);
841            }
842            TyKind::Path(qself, path) => {
843                self.diag_metadata.current_type_path = Some(ty);
844
845                // If we have a path that ends with `(..)`, then it must be
846                // return type notation. Resolve that path in the *value*
847                // namespace.
848                let source = if let Some(seg) = path.segments.last()
849                    && let Some(args) = &seg.args
850                    && matches!(**args, GenericArgs::ParenthesizedElided(..))
851                {
852                    PathSource::ReturnTypeNotation
853                } else {
854                    PathSource::Type
855                };
856
857                self.smart_resolve_path(ty.id, qself, path, source);
858
859                // Check whether we should interpret this as a bare trait object.
860                if qself.is_none()
861                    && let Some(partial_res) = self.r.partial_res_map.get(&ty.id)
862                    && let Some(Res::Def(DefKind::Trait | DefKind::TraitAlias, _)) =
863                        partial_res.full_res()
864                {
865                    // This path is actually a bare trait object. In case of a bare `Fn`-trait
866                    // object with anonymous lifetimes, we need this rib to correctly place the
867                    // synthetic lifetimes.
868                    let span = ty.span.shrink_to_lo().to(path.span.shrink_to_lo());
869                    self.with_generic_param_rib(
870                        &[],
871                        RibKind::Normal,
872                        ty.id,
873                        LifetimeBinderKind::PolyTrait,
874                        span,
875                        |this| this.visit_path(path),
876                    );
877                } else {
878                    visit::walk_ty(self, ty)
879                }
880            }
881            TyKind::ImplicitSelf => {
882                let self_ty = Ident::with_dummy_span(kw::SelfUpper);
883                let res = self
884                    .resolve_ident_in_lexical_scope(
885                        self_ty,
886                        TypeNS,
887                        Some(Finalize::new(ty.id, ty.span)),
888                        None,
889                    )
890                    .map_or(Res::Err, |d| d.res());
891                self.r.record_partial_res(ty.id, PartialRes::new(res));
892                visit::walk_ty(self, ty)
893            }
894            TyKind::ImplTrait(..) => {
895                let candidates = self.lifetime_elision_candidates.take();
896                visit::walk_ty(self, ty);
897                self.lifetime_elision_candidates = candidates;
898            }
899            TyKind::TraitObject(bounds, ..) => {
900                self.diag_metadata.current_trait_object = Some(&bounds[..]);
901                visit::walk_ty(self, ty)
902            }
903            TyKind::FnPtr(fn_ptr) => {
904                let span = ty.span.shrink_to_lo().to(fn_ptr.decl_span.shrink_to_lo());
905                self.with_generic_param_rib(
906                    &fn_ptr.generic_params,
907                    RibKind::Normal,
908                    ty.id,
909                    LifetimeBinderKind::FnPtrType,
910                    span,
911                    |this| {
912                        this.visit_generic_params(&fn_ptr.generic_params, false);
913                        this.resolve_fn_signature(
914                            ty.id,
915                            false,
916                            // We don't need to deal with patterns in parameters, because
917                            // they are not possible for foreign or bodiless functions.
918                            fn_ptr.decl.inputs.iter().map(|Param { ty, .. }| (None, &**ty)),
919                            &fn_ptr.decl.output,
920                            false,
921                        )
922                    },
923                )
924            }
925            TyKind::UnsafeBinder(unsafe_binder) => {
926                let span = ty.span.shrink_to_lo().to(unsafe_binder.inner_ty.span.shrink_to_lo());
927                self.with_generic_param_rib(
928                    &unsafe_binder.generic_params,
929                    RibKind::Normal,
930                    ty.id,
931                    LifetimeBinderKind::FnPtrType,
932                    span,
933                    |this| {
934                        this.visit_generic_params(&unsafe_binder.generic_params, false);
935                        this.with_lifetime_rib(
936                            // We don't allow anonymous `unsafe &'_ ()` binders,
937                            // although I guess we could.
938                            LifetimeRibKind::AnonymousReportError,
939                            |this| this.visit_ty(&unsafe_binder.inner_ty),
940                        );
941                    },
942                )
943            }
944            TyKind::Array(element_ty, length) => {
945                self.visit_ty(element_ty);
946                self.resolve_anon_const(length, AnonConstKind::ConstArg(IsRepeatExpr::No));
947            }
948            TyKind::Typeof(ct) => {
949                self.resolve_anon_const(ct, AnonConstKind::ConstArg(IsRepeatExpr::No))
950            }
951            _ => visit::walk_ty(self, ty),
952        }
953        self.diag_metadata.current_trait_object = prev;
954        self.diag_metadata.current_type_path = prev_ty;
955    }
956
957    fn visit_ty_pat(&mut self, t: &'ast TyPat) -> Self::Result {
958        match &t.kind {
959            TyPatKind::Range(start, end, _) => {
960                if let Some(start) = start {
961                    self.resolve_anon_const(start, AnonConstKind::ConstArg(IsRepeatExpr::No));
962                }
963                if let Some(end) = end {
964                    self.resolve_anon_const(end, AnonConstKind::ConstArg(IsRepeatExpr::No));
965                }
966            }
967            TyPatKind::Or(patterns) => {
968                for pat in patterns {
969                    self.visit_ty_pat(pat)
970                }
971            }
972            TyPatKind::Err(_) => {}
973        }
974    }
975
976    fn visit_poly_trait_ref(&mut self, tref: &'ast PolyTraitRef) {
977        let span = tref.span.shrink_to_lo().to(tref.trait_ref.path.span.shrink_to_lo());
978        self.with_generic_param_rib(
979            &tref.bound_generic_params,
980            RibKind::Normal,
981            tref.trait_ref.ref_id,
982            LifetimeBinderKind::PolyTrait,
983            span,
984            |this| {
985                this.visit_generic_params(&tref.bound_generic_params, false);
986                this.smart_resolve_path(
987                    tref.trait_ref.ref_id,
988                    &None,
989                    &tref.trait_ref.path,
990                    PathSource::Trait(AliasPossibility::Maybe),
991                );
992                this.visit_trait_ref(&tref.trait_ref);
993            },
994        );
995    }
996    fn visit_foreign_item(&mut self, foreign_item: &'ast ForeignItem) {
997        self.resolve_doc_links(&foreign_item.attrs, MaybeExported::Ok(foreign_item.id));
998        let def_kind = self.r.local_def_kind(foreign_item.id);
999        match foreign_item.kind {
1000            ForeignItemKind::TyAlias(box TyAlias { ref generics, .. }) => {
1001                self.with_generic_param_rib(
1002                    &generics.params,
1003                    RibKind::Item(HasGenericParams::Yes(generics.span), def_kind),
1004                    foreign_item.id,
1005                    LifetimeBinderKind::Item,
1006                    generics.span,
1007                    |this| visit::walk_item(this, foreign_item),
1008                );
1009            }
1010            ForeignItemKind::Fn(box Fn { ref generics, .. }) => {
1011                self.with_generic_param_rib(
1012                    &generics.params,
1013                    RibKind::Item(HasGenericParams::Yes(generics.span), def_kind),
1014                    foreign_item.id,
1015                    LifetimeBinderKind::Function,
1016                    generics.span,
1017                    |this| visit::walk_item(this, foreign_item),
1018                );
1019            }
1020            ForeignItemKind::Static(..) => {
1021                self.with_static_rib(def_kind, |this| visit::walk_item(this, foreign_item))
1022            }
1023            ForeignItemKind::MacCall(..) => {
1024                panic!("unexpanded macro in resolve!")
1025            }
1026        }
1027    }
1028    fn visit_fn(&mut self, fn_kind: FnKind<'ast>, sp: Span, fn_id: NodeId) {
1029        let previous_value = self.diag_metadata.current_function;
1030        match fn_kind {
1031            // Bail if the function is foreign, and thus cannot validly have
1032            // a body, or if there's no body for some other reason.
1033            FnKind::Fn(FnCtxt::Foreign, _, Fn { sig, ident, generics, .. })
1034            | FnKind::Fn(_, _, Fn { sig, ident, generics, body: None, .. }) => {
1035                self.visit_fn_header(&sig.header);
1036                self.visit_ident(ident);
1037                self.visit_generics(generics);
1038                self.resolve_fn_signature(
1039                    fn_id,
1040                    sig.decl.has_self(),
1041                    sig.decl.inputs.iter().map(|Param { ty, .. }| (None, &**ty)),
1042                    &sig.decl.output,
1043                    false,
1044                );
1045                return;
1046            }
1047            FnKind::Fn(..) => {
1048                self.diag_metadata.current_function = Some((fn_kind, sp));
1049            }
1050            // Do not update `current_function` for closures: it suggests `self` parameters.
1051            FnKind::Closure(..) => {}
1052        };
1053        debug!("(resolving function) entering function");
1054
1055        // Create a value rib for the function.
1056        self.with_rib(ValueNS, RibKind::FnOrCoroutine, |this| {
1057            // Create a label rib for the function.
1058            this.with_label_rib(RibKind::FnOrCoroutine, |this| {
1059                match fn_kind {
1060                    FnKind::Fn(_, _, Fn { sig, generics, contract, body, .. }) => {
1061                        this.visit_generics(generics);
1062
1063                        let declaration = &sig.decl;
1064                        let coro_node_id = sig
1065                            .header
1066                            .coroutine_kind
1067                            .map(|coroutine_kind| coroutine_kind.return_id());
1068
1069                        this.resolve_fn_signature(
1070                            fn_id,
1071                            declaration.has_self(),
1072                            declaration
1073                                .inputs
1074                                .iter()
1075                                .map(|Param { pat, ty, .. }| (Some(&**pat), &**ty)),
1076                            &declaration.output,
1077                            coro_node_id.is_some(),
1078                        );
1079
1080                        if let Some(contract) = contract {
1081                            this.visit_contract(contract);
1082                        }
1083
1084                        if let Some(body) = body {
1085                            // Ignore errors in function bodies if this is rustdoc
1086                            // Be sure not to set this until the function signature has been resolved.
1087                            let previous_state = replace(&mut this.in_func_body, true);
1088                            // We only care block in the same function
1089                            this.last_block_rib = None;
1090                            // Resolve the function body, potentially inside the body of an async closure
1091                            this.with_lifetime_rib(
1092                                LifetimeRibKind::Elided(LifetimeRes::Infer),
1093                                |this| this.visit_block(body),
1094                            );
1095
1096                            debug!("(resolving function) leaving function");
1097                            this.in_func_body = previous_state;
1098                        }
1099                    }
1100                    FnKind::Closure(binder, _, declaration, body) => {
1101                        this.visit_closure_binder(binder);
1102
1103                        this.with_lifetime_rib(
1104                            match binder {
1105                                // We do not have any explicit generic lifetime parameter.
1106                                ClosureBinder::NotPresent => {
1107                                    LifetimeRibKind::AnonymousCreateParameter {
1108                                        binder: fn_id,
1109                                        report_in_path: false,
1110                                    }
1111                                }
1112                                ClosureBinder::For { .. } => LifetimeRibKind::AnonymousReportError,
1113                            },
1114                            // Add each argument to the rib.
1115                            |this| this.resolve_params(&declaration.inputs),
1116                        );
1117                        this.with_lifetime_rib(
1118                            match binder {
1119                                ClosureBinder::NotPresent => {
1120                                    LifetimeRibKind::Elided(LifetimeRes::Infer)
1121                                }
1122                                ClosureBinder::For { .. } => LifetimeRibKind::AnonymousReportError,
1123                            },
1124                            |this| visit::walk_fn_ret_ty(this, &declaration.output),
1125                        );
1126
1127                        // Ignore errors in function bodies if this is rustdoc
1128                        // Be sure not to set this until the function signature has been resolved.
1129                        let previous_state = replace(&mut this.in_func_body, true);
1130                        // Resolve the function body, potentially inside the body of an async closure
1131                        this.with_lifetime_rib(
1132                            LifetimeRibKind::Elided(LifetimeRes::Infer),
1133                            |this| this.visit_expr(body),
1134                        );
1135
1136                        debug!("(resolving function) leaving function");
1137                        this.in_func_body = previous_state;
1138                    }
1139                }
1140            })
1141        });
1142        self.diag_metadata.current_function = previous_value;
1143    }
1144
1145    fn visit_lifetime(&mut self, lifetime: &'ast Lifetime, use_ctxt: visit::LifetimeCtxt) {
1146        self.resolve_lifetime(lifetime, use_ctxt)
1147    }
1148
1149    fn visit_precise_capturing_arg(&mut self, arg: &'ast PreciseCapturingArg) {
1150        match arg {
1151            // Lower the lifetime regularly; we'll resolve the lifetime and check
1152            // it's a parameter later on in HIR lowering.
1153            PreciseCapturingArg::Lifetime(_) => {}
1154
1155            PreciseCapturingArg::Arg(path, id) => {
1156                // we want `impl use<C>` to try to resolve `C` as both a type parameter or
1157                // a const parameter. Since the resolver specifically doesn't allow having
1158                // two generic params with the same name, even if they're a different namespace,
1159                // it doesn't really matter which we try resolving first, but just like
1160                // `Ty::Param` we just fall back to the value namespace only if it's missing
1161                // from the type namespace.
1162                let mut check_ns = |ns| {
1163                    self.maybe_resolve_ident_in_lexical_scope(path.segments[0].ident, ns).is_some()
1164                };
1165                // Like `Ty::Param`, we try resolving this as both a const and a type.
1166                if !check_ns(TypeNS) && check_ns(ValueNS) {
1167                    self.smart_resolve_path(
1168                        *id,
1169                        &None,
1170                        path,
1171                        PathSource::PreciseCapturingArg(ValueNS),
1172                    );
1173                } else {
1174                    self.smart_resolve_path(
1175                        *id,
1176                        &None,
1177                        path,
1178                        PathSource::PreciseCapturingArg(TypeNS),
1179                    );
1180                }
1181            }
1182        }
1183
1184        visit::walk_precise_capturing_arg(self, arg)
1185    }
1186
1187    fn visit_generics(&mut self, generics: &'ast Generics) {
1188        self.visit_generic_params(&generics.params, self.diag_metadata.current_self_item.is_some());
1189        for p in &generics.where_clause.predicates {
1190            self.visit_where_predicate(p);
1191        }
1192    }
1193
1194    fn visit_closure_binder(&mut self, b: &'ast ClosureBinder) {
1195        match b {
1196            ClosureBinder::NotPresent => {}
1197            ClosureBinder::For { generic_params, .. } => {
1198                self.visit_generic_params(
1199                    generic_params,
1200                    self.diag_metadata.current_self_item.is_some(),
1201                );
1202            }
1203        }
1204    }
1205
1206    fn visit_generic_arg(&mut self, arg: &'ast GenericArg) {
1207        debug!("visit_generic_arg({:?})", arg);
1208        let prev = replace(&mut self.diag_metadata.currently_processing_generic_args, true);
1209        match arg {
1210            GenericArg::Type(ty) => {
1211                // We parse const arguments as path types as we cannot distinguish them during
1212                // parsing. We try to resolve that ambiguity by attempting resolution the type
1213                // namespace first, and if that fails we try again in the value namespace. If
1214                // resolution in the value namespace succeeds, we have an generic const argument on
1215                // our hands.
1216                if let TyKind::Path(None, ref path) = ty.kind
1217                    // We cannot disambiguate multi-segment paths right now as that requires type
1218                    // checking.
1219                    && path.is_potential_trivial_const_arg(false)
1220                {
1221                    let mut check_ns = |ns| {
1222                        self.maybe_resolve_ident_in_lexical_scope(path.segments[0].ident, ns)
1223                            .is_some()
1224                    };
1225                    if !check_ns(TypeNS) && check_ns(ValueNS) {
1226                        self.resolve_anon_const_manual(
1227                            true,
1228                            AnonConstKind::ConstArg(IsRepeatExpr::No),
1229                            |this| {
1230                                this.smart_resolve_path(ty.id, &None, path, PathSource::Expr(None));
1231                                this.visit_path(path);
1232                            },
1233                        );
1234
1235                        self.diag_metadata.currently_processing_generic_args = prev;
1236                        return;
1237                    }
1238                }
1239
1240                self.visit_ty(ty);
1241            }
1242            GenericArg::Lifetime(lt) => self.visit_lifetime(lt, visit::LifetimeCtxt::GenericArg),
1243            GenericArg::Const(ct) => {
1244                self.resolve_anon_const(ct, AnonConstKind::ConstArg(IsRepeatExpr::No))
1245            }
1246        }
1247        self.diag_metadata.currently_processing_generic_args = prev;
1248    }
1249
1250    fn visit_assoc_item_constraint(&mut self, constraint: &'ast AssocItemConstraint) {
1251        self.visit_ident(&constraint.ident);
1252        if let Some(ref gen_args) = constraint.gen_args {
1253            // Forbid anonymous lifetimes in GAT parameters until proper semantics are decided.
1254            self.with_lifetime_rib(LifetimeRibKind::AnonymousReportError, |this| {
1255                this.visit_generic_args(gen_args)
1256            });
1257        }
1258        match constraint.kind {
1259            AssocItemConstraintKind::Equality { ref term } => match term {
1260                Term::Ty(ty) => self.visit_ty(ty),
1261                Term::Const(c) => {
1262                    self.resolve_anon_const(c, AnonConstKind::ConstArg(IsRepeatExpr::No))
1263                }
1264            },
1265            AssocItemConstraintKind::Bound { ref bounds } => {
1266                walk_list!(self, visit_param_bound, bounds, BoundKind::Bound);
1267            }
1268        }
1269    }
1270
1271    fn visit_path_segment(&mut self, path_segment: &'ast PathSegment) {
1272        let Some(ref args) = path_segment.args else {
1273            return;
1274        };
1275
1276        match &**args {
1277            GenericArgs::AngleBracketed(..) => visit::walk_generic_args(self, args),
1278            GenericArgs::Parenthesized(p_args) => {
1279                // Probe the lifetime ribs to know how to behave.
1280                for rib in self.lifetime_ribs.iter().rev() {
1281                    match rib.kind {
1282                        // We are inside a `PolyTraitRef`. The lifetimes are
1283                        // to be introduced in that (maybe implicit) `for<>` binder.
1284                        LifetimeRibKind::Generics {
1285                            binder,
1286                            kind: LifetimeBinderKind::PolyTrait,
1287                            ..
1288                        } => {
1289                            self.resolve_fn_signature(
1290                                binder,
1291                                false,
1292                                p_args.inputs.iter().map(|ty| (None, &**ty)),
1293                                &p_args.output,
1294                                false,
1295                            );
1296                            break;
1297                        }
1298                        // We have nowhere to introduce generics. Code is malformed,
1299                        // so use regular lifetime resolution to avoid spurious errors.
1300                        LifetimeRibKind::Item | LifetimeRibKind::Generics { .. } => {
1301                            visit::walk_generic_args(self, args);
1302                            break;
1303                        }
1304                        LifetimeRibKind::AnonymousCreateParameter { .. }
1305                        | LifetimeRibKind::AnonymousReportError
1306                        | LifetimeRibKind::StaticIfNoLifetimeInScope { .. }
1307                        | LifetimeRibKind::Elided(_)
1308                        | LifetimeRibKind::ElisionFailure
1309                        | LifetimeRibKind::ConcreteAnonConst(_)
1310                        | LifetimeRibKind::ConstParamTy => {}
1311                    }
1312                }
1313            }
1314            GenericArgs::ParenthesizedElided(_) => {}
1315        }
1316    }
1317
1318    fn visit_where_predicate(&mut self, p: &'ast WherePredicate) {
1319        debug!("visit_where_predicate {:?}", p);
1320        let previous_value = replace(&mut self.diag_metadata.current_where_predicate, Some(p));
1321        self.with_lifetime_rib(LifetimeRibKind::AnonymousReportError, |this| {
1322            if let WherePredicateKind::BoundPredicate(WhereBoundPredicate {
1323                bounded_ty,
1324                bounds,
1325                bound_generic_params,
1326                ..
1327            }) = &p.kind
1328            {
1329                let span = p.span.shrink_to_lo().to(bounded_ty.span.shrink_to_lo());
1330                this.with_generic_param_rib(
1331                    bound_generic_params,
1332                    RibKind::Normal,
1333                    bounded_ty.id,
1334                    LifetimeBinderKind::WhereBound,
1335                    span,
1336                    |this| {
1337                        this.visit_generic_params(bound_generic_params, false);
1338                        this.visit_ty(bounded_ty);
1339                        for bound in bounds {
1340                            this.visit_param_bound(bound, BoundKind::Bound)
1341                        }
1342                    },
1343                );
1344            } else {
1345                visit::walk_where_predicate(this, p);
1346            }
1347        });
1348        self.diag_metadata.current_where_predicate = previous_value;
1349    }
1350
1351    fn visit_inline_asm(&mut self, asm: &'ast InlineAsm) {
1352        for (op, _) in &asm.operands {
1353            match op {
1354                InlineAsmOperand::In { expr, .. }
1355                | InlineAsmOperand::Out { expr: Some(expr), .. }
1356                | InlineAsmOperand::InOut { expr, .. } => self.visit_expr(expr),
1357                InlineAsmOperand::Out { expr: None, .. } => {}
1358                InlineAsmOperand::SplitInOut { in_expr, out_expr, .. } => {
1359                    self.visit_expr(in_expr);
1360                    if let Some(out_expr) = out_expr {
1361                        self.visit_expr(out_expr);
1362                    }
1363                }
1364                InlineAsmOperand::Const { anon_const, .. } => {
1365                    // Although this is `DefKind::AnonConst`, it is allowed to reference outer
1366                    // generic parameters like an inline const.
1367                    self.resolve_anon_const(anon_const, AnonConstKind::InlineConst);
1368                }
1369                InlineAsmOperand::Sym { sym } => self.visit_inline_asm_sym(sym),
1370                InlineAsmOperand::Label { block } => self.visit_block(block),
1371            }
1372        }
1373    }
1374
1375    fn visit_inline_asm_sym(&mut self, sym: &'ast InlineAsmSym) {
1376        // This is similar to the code for AnonConst.
1377        self.with_rib(ValueNS, RibKind::InlineAsmSym, |this| {
1378            this.with_rib(TypeNS, RibKind::InlineAsmSym, |this| {
1379                this.with_label_rib(RibKind::InlineAsmSym, |this| {
1380                    this.smart_resolve_path(sym.id, &sym.qself, &sym.path, PathSource::Expr(None));
1381                    visit::walk_inline_asm_sym(this, sym);
1382                });
1383            })
1384        });
1385    }
1386
1387    fn visit_variant(&mut self, v: &'ast Variant) {
1388        self.resolve_doc_links(&v.attrs, MaybeExported::Ok(v.id));
1389        self.visit_id(v.id);
1390        walk_list!(self, visit_attribute, &v.attrs);
1391        self.visit_vis(&v.vis);
1392        self.visit_ident(&v.ident);
1393        self.visit_variant_data(&v.data);
1394        if let Some(discr) = &v.disr_expr {
1395            self.resolve_anon_const(discr, AnonConstKind::EnumDiscriminant);
1396        }
1397    }
1398
1399    fn visit_field_def(&mut self, f: &'ast FieldDef) {
1400        self.resolve_doc_links(&f.attrs, MaybeExported::Ok(f.id));
1401        let FieldDef {
1402            attrs,
1403            id: _,
1404            span: _,
1405            vis,
1406            ident,
1407            ty,
1408            is_placeholder: _,
1409            default,
1410            safety: _,
1411        } = f;
1412        walk_list!(self, visit_attribute, attrs);
1413        try_visit!(self.visit_vis(vis));
1414        visit_opt!(self, visit_ident, ident);
1415        try_visit!(self.visit_ty(ty));
1416        if let Some(v) = &default {
1417            self.resolve_anon_const(v, AnonConstKind::FieldDefaultValue);
1418        }
1419    }
1420}
1421
1422impl<'a, 'ast, 'ra, 'tcx> LateResolutionVisitor<'a, 'ast, 'ra, 'tcx> {
1423    fn new(resolver: &'a mut Resolver<'ra, 'tcx>) -> LateResolutionVisitor<'a, 'ast, 'ra, 'tcx> {
1424        // During late resolution we only track the module component of the parent scope,
1425        // although it may be useful to track other components as well for diagnostics.
1426        let graph_root = resolver.graph_root;
1427        let parent_scope = ParentScope::module(graph_root, resolver.arenas);
1428        let start_rib_kind = RibKind::Module(graph_root);
1429        LateResolutionVisitor {
1430            r: resolver,
1431            parent_scope,
1432            ribs: PerNS {
1433                value_ns: vec![Rib::new(start_rib_kind)],
1434                type_ns: vec![Rib::new(start_rib_kind)],
1435                macro_ns: vec![Rib::new(start_rib_kind)],
1436            },
1437            last_block_rib: None,
1438            label_ribs: Vec::new(),
1439            lifetime_ribs: Vec::new(),
1440            lifetime_elision_candidates: None,
1441            current_trait_ref: None,
1442            diag_metadata: Default::default(),
1443            // errors at module scope should always be reported
1444            in_func_body: false,
1445            lifetime_uses: Default::default(),
1446        }
1447    }
1448
1449    fn maybe_resolve_ident_in_lexical_scope(
1450        &mut self,
1451        ident: Ident,
1452        ns: Namespace,
1453    ) -> Option<LexicalScopeBinding<'ra>> {
1454        self.r.resolve_ident_in_lexical_scope(
1455            ident,
1456            ns,
1457            &self.parent_scope,
1458            None,
1459            &self.ribs[ns],
1460            None,
1461        )
1462    }
1463
1464    fn resolve_ident_in_lexical_scope(
1465        &mut self,
1466        ident: Ident,
1467        ns: Namespace,
1468        finalize: Option<Finalize>,
1469        ignore_binding: Option<NameBinding<'ra>>,
1470    ) -> Option<LexicalScopeBinding<'ra>> {
1471        self.r.resolve_ident_in_lexical_scope(
1472            ident,
1473            ns,
1474            &self.parent_scope,
1475            finalize,
1476            &self.ribs[ns],
1477            ignore_binding,
1478        )
1479    }
1480
1481    fn resolve_path(
1482        &mut self,
1483        path: &[Segment],
1484        opt_ns: Option<Namespace>, // `None` indicates a module path in import
1485        finalize: Option<Finalize>,
1486    ) -> PathResult<'ra> {
1487        self.r.cm().resolve_path_with_ribs(
1488            path,
1489            opt_ns,
1490            &self.parent_scope,
1491            finalize,
1492            Some(&self.ribs),
1493            None,
1494            None,
1495        )
1496    }
1497
1498    // AST resolution
1499    //
1500    // We maintain a list of value ribs and type ribs.
1501    //
1502    // Simultaneously, we keep track of the current position in the module
1503    // graph in the `parent_scope.module` pointer. When we go to resolve a name in
1504    // the value or type namespaces, we first look through all the ribs and
1505    // then query the module graph. When we resolve a name in the module
1506    // namespace, we can skip all the ribs (since nested modules are not
1507    // allowed within blocks in Rust) and jump straight to the current module
1508    // graph node.
1509    //
1510    // Named implementations are handled separately. When we find a method
1511    // call, we consult the module node to find all of the implementations in
1512    // scope. This information is lazily cached in the module node. We then
1513    // generate a fake "implementation scope" containing all the
1514    // implementations thus found, for compatibility with old resolve pass.
1515
1516    /// Do some `work` within a new innermost rib of the given `kind` in the given namespace (`ns`).
1517    fn with_rib<T>(
1518        &mut self,
1519        ns: Namespace,
1520        kind: RibKind<'ra>,
1521        work: impl FnOnce(&mut Self) -> T,
1522    ) -> T {
1523        self.ribs[ns].push(Rib::new(kind));
1524        let ret = work(self);
1525        self.ribs[ns].pop();
1526        ret
1527    }
1528
1529    fn with_mod_rib<T>(&mut self, id: NodeId, f: impl FnOnce(&mut Self) -> T) -> T {
1530        let module = self.r.expect_module(self.r.local_def_id(id).to_def_id());
1531        // Move down in the graph.
1532        let orig_module = replace(&mut self.parent_scope.module, module);
1533        self.with_rib(ValueNS, RibKind::Module(module), |this| {
1534            this.with_rib(TypeNS, RibKind::Module(module), |this| {
1535                let ret = f(this);
1536                this.parent_scope.module = orig_module;
1537                ret
1538            })
1539        })
1540    }
1541
1542    fn visit_generic_params(&mut self, params: &'ast [GenericParam], add_self_upper: bool) {
1543        // For type parameter defaults, we have to ban access
1544        // to following type parameters, as the GenericArgs can only
1545        // provide previous type parameters as they're built. We
1546        // put all the parameters on the ban list and then remove
1547        // them one by one as they are processed and become available.
1548        let mut forward_ty_ban_rib =
1549            Rib::new(RibKind::ForwardGenericParamBan(ForwardGenericParamBanReason::Default));
1550        let mut forward_const_ban_rib =
1551            Rib::new(RibKind::ForwardGenericParamBan(ForwardGenericParamBanReason::Default));
1552        for param in params.iter() {
1553            match param.kind {
1554                GenericParamKind::Type { .. } => {
1555                    forward_ty_ban_rib
1556                        .bindings
1557                        .insert(Ident::with_dummy_span(param.ident.name), Res::Err);
1558                }
1559                GenericParamKind::Const { .. } => {
1560                    forward_const_ban_rib
1561                        .bindings
1562                        .insert(Ident::with_dummy_span(param.ident.name), Res::Err);
1563                }
1564                GenericParamKind::Lifetime => {}
1565            }
1566        }
1567
1568        // rust-lang/rust#61631: The type `Self` is essentially
1569        // another type parameter. For ADTs, we consider it
1570        // well-defined only after all of the ADT type parameters have
1571        // been provided. Therefore, we do not allow use of `Self`
1572        // anywhere in ADT type parameter defaults.
1573        //
1574        // (We however cannot ban `Self` for defaults on *all* generic
1575        // lists; e.g. trait generics can usefully refer to `Self`,
1576        // such as in the case of `trait Add<Rhs = Self>`.)
1577        if add_self_upper {
1578            // (`Some` if + only if we are in ADT's generics.)
1579            forward_ty_ban_rib.bindings.insert(Ident::with_dummy_span(kw::SelfUpper), Res::Err);
1580        }
1581
1582        // NOTE: We use different ribs here not for a technical reason, but just
1583        // for better diagnostics.
1584        let mut forward_ty_ban_rib_const_param_ty = Rib {
1585            bindings: forward_ty_ban_rib.bindings.clone(),
1586            patterns_with_skipped_bindings: Default::default(),
1587            kind: RibKind::ForwardGenericParamBan(ForwardGenericParamBanReason::ConstParamTy),
1588        };
1589        let mut forward_const_ban_rib_const_param_ty = Rib {
1590            bindings: forward_const_ban_rib.bindings.clone(),
1591            patterns_with_skipped_bindings: Default::default(),
1592            kind: RibKind::ForwardGenericParamBan(ForwardGenericParamBanReason::ConstParamTy),
1593        };
1594        // We'll ban these with a `ConstParamTy` rib, so just clear these ribs for better
1595        // diagnostics, so we don't mention anything about const param tys having generics at all.
1596        if !self.r.tcx.features().generic_const_parameter_types() {
1597            forward_ty_ban_rib_const_param_ty.bindings.clear();
1598            forward_const_ban_rib_const_param_ty.bindings.clear();
1599        }
1600
1601        self.with_lifetime_rib(LifetimeRibKind::AnonymousReportError, |this| {
1602            for param in params {
1603                match param.kind {
1604                    GenericParamKind::Lifetime => {
1605                        for bound in &param.bounds {
1606                            this.visit_param_bound(bound, BoundKind::Bound);
1607                        }
1608                    }
1609                    GenericParamKind::Type { ref default } => {
1610                        for bound in &param.bounds {
1611                            this.visit_param_bound(bound, BoundKind::Bound);
1612                        }
1613
1614                        if let Some(ty) = default {
1615                            this.ribs[TypeNS].push(forward_ty_ban_rib);
1616                            this.ribs[ValueNS].push(forward_const_ban_rib);
1617                            this.visit_ty(ty);
1618                            forward_const_ban_rib = this.ribs[ValueNS].pop().unwrap();
1619                            forward_ty_ban_rib = this.ribs[TypeNS].pop().unwrap();
1620                        }
1621
1622                        // Allow all following defaults to refer to this type parameter.
1623                        let i = &Ident::with_dummy_span(param.ident.name);
1624                        forward_ty_ban_rib.bindings.swap_remove(i);
1625                        forward_ty_ban_rib_const_param_ty.bindings.swap_remove(i);
1626                    }
1627                    GenericParamKind::Const { ref ty, span: _, ref default } => {
1628                        // Const parameters can't have param bounds.
1629                        assert!(param.bounds.is_empty());
1630
1631                        this.ribs[TypeNS].push(forward_ty_ban_rib_const_param_ty);
1632                        this.ribs[ValueNS].push(forward_const_ban_rib_const_param_ty);
1633                        if this.r.tcx.features().generic_const_parameter_types() {
1634                            this.visit_ty(ty)
1635                        } else {
1636                            this.ribs[TypeNS].push(Rib::new(RibKind::ConstParamTy));
1637                            this.ribs[ValueNS].push(Rib::new(RibKind::ConstParamTy));
1638                            this.with_lifetime_rib(LifetimeRibKind::ConstParamTy, |this| {
1639                                this.visit_ty(ty)
1640                            });
1641                            this.ribs[TypeNS].pop().unwrap();
1642                            this.ribs[ValueNS].pop().unwrap();
1643                        }
1644                        forward_const_ban_rib_const_param_ty = this.ribs[ValueNS].pop().unwrap();
1645                        forward_ty_ban_rib_const_param_ty = this.ribs[TypeNS].pop().unwrap();
1646
1647                        if let Some(expr) = default {
1648                            this.ribs[TypeNS].push(forward_ty_ban_rib);
1649                            this.ribs[ValueNS].push(forward_const_ban_rib);
1650                            this.resolve_anon_const(
1651                                expr,
1652                                AnonConstKind::ConstArg(IsRepeatExpr::No),
1653                            );
1654                            forward_const_ban_rib = this.ribs[ValueNS].pop().unwrap();
1655                            forward_ty_ban_rib = this.ribs[TypeNS].pop().unwrap();
1656                        }
1657
1658                        // Allow all following defaults to refer to this const parameter.
1659                        let i = &Ident::with_dummy_span(param.ident.name);
1660                        forward_const_ban_rib.bindings.swap_remove(i);
1661                        forward_const_ban_rib_const_param_ty.bindings.swap_remove(i);
1662                    }
1663                }
1664            }
1665        })
1666    }
1667
1668    #[instrument(level = "debug", skip(self, work))]
1669    fn with_lifetime_rib<T>(
1670        &mut self,
1671        kind: LifetimeRibKind,
1672        work: impl FnOnce(&mut Self) -> T,
1673    ) -> T {
1674        self.lifetime_ribs.push(LifetimeRib::new(kind));
1675        let outer_elision_candidates = self.lifetime_elision_candidates.take();
1676        let ret = work(self);
1677        self.lifetime_elision_candidates = outer_elision_candidates;
1678        self.lifetime_ribs.pop();
1679        ret
1680    }
1681
1682    #[instrument(level = "debug", skip(self))]
1683    fn resolve_lifetime(&mut self, lifetime: &'ast Lifetime, use_ctxt: visit::LifetimeCtxt) {
1684        let ident = lifetime.ident;
1685
1686        if ident.name == kw::StaticLifetime {
1687            self.record_lifetime_res(
1688                lifetime.id,
1689                LifetimeRes::Static,
1690                LifetimeElisionCandidate::Named,
1691            );
1692            return;
1693        }
1694
1695        if ident.name == kw::UnderscoreLifetime {
1696            return self.resolve_anonymous_lifetime(lifetime, lifetime.id, false);
1697        }
1698
1699        let mut lifetime_rib_iter = self.lifetime_ribs.iter().rev();
1700        while let Some(rib) = lifetime_rib_iter.next() {
1701            let normalized_ident = ident.normalize_to_macros_2_0();
1702            if let Some(&(_, res)) = rib.bindings.get(&normalized_ident) {
1703                self.record_lifetime_res(lifetime.id, res, LifetimeElisionCandidate::Named);
1704
1705                if let LifetimeRes::Param { param, binder } = res {
1706                    match self.lifetime_uses.entry(param) {
1707                        Entry::Vacant(v) => {
1708                            debug!("First use of {:?} at {:?}", res, ident.span);
1709                            let use_set = self
1710                                .lifetime_ribs
1711                                .iter()
1712                                .rev()
1713                                .find_map(|rib| match rib.kind {
1714                                    // Do not suggest eliding a lifetime where an anonymous
1715                                    // lifetime would be illegal.
1716                                    LifetimeRibKind::Item
1717                                    | LifetimeRibKind::AnonymousReportError
1718                                    | LifetimeRibKind::StaticIfNoLifetimeInScope { .. }
1719                                    | LifetimeRibKind::ElisionFailure => Some(LifetimeUseSet::Many),
1720                                    // An anonymous lifetime is legal here, and bound to the right
1721                                    // place, go ahead.
1722                                    LifetimeRibKind::AnonymousCreateParameter {
1723                                        binder: anon_binder,
1724                                        ..
1725                                    } => Some(if binder == anon_binder {
1726                                        LifetimeUseSet::One { use_span: ident.span, use_ctxt }
1727                                    } else {
1728                                        LifetimeUseSet::Many
1729                                    }),
1730                                    // Only report if eliding the lifetime would have the same
1731                                    // semantics.
1732                                    LifetimeRibKind::Elided(r) => Some(if res == r {
1733                                        LifetimeUseSet::One { use_span: ident.span, use_ctxt }
1734                                    } else {
1735                                        LifetimeUseSet::Many
1736                                    }),
1737                                    LifetimeRibKind::Generics { .. }
1738                                    | LifetimeRibKind::ConstParamTy => None,
1739                                    LifetimeRibKind::ConcreteAnonConst(_) => {
1740                                        span_bug!(ident.span, "unexpected rib kind: {:?}", rib.kind)
1741                                    }
1742                                })
1743                                .unwrap_or(LifetimeUseSet::Many);
1744                            debug!(?use_ctxt, ?use_set);
1745                            v.insert(use_set);
1746                        }
1747                        Entry::Occupied(mut o) => {
1748                            debug!("Many uses of {:?} at {:?}", res, ident.span);
1749                            *o.get_mut() = LifetimeUseSet::Many;
1750                        }
1751                    }
1752                }
1753                return;
1754            }
1755
1756            match rib.kind {
1757                LifetimeRibKind::Item => break,
1758                LifetimeRibKind::ConstParamTy => {
1759                    self.emit_non_static_lt_in_const_param_ty_error(lifetime);
1760                    self.record_lifetime_res(
1761                        lifetime.id,
1762                        LifetimeRes::Error,
1763                        LifetimeElisionCandidate::Ignore,
1764                    );
1765                    return;
1766                }
1767                LifetimeRibKind::ConcreteAnonConst(cause) => {
1768                    self.emit_forbidden_non_static_lifetime_error(cause, lifetime);
1769                    self.record_lifetime_res(
1770                        lifetime.id,
1771                        LifetimeRes::Error,
1772                        LifetimeElisionCandidate::Ignore,
1773                    );
1774                    return;
1775                }
1776                LifetimeRibKind::AnonymousCreateParameter { .. }
1777                | LifetimeRibKind::Elided(_)
1778                | LifetimeRibKind::Generics { .. }
1779                | LifetimeRibKind::ElisionFailure
1780                | LifetimeRibKind::AnonymousReportError
1781                | LifetimeRibKind::StaticIfNoLifetimeInScope { .. } => {}
1782            }
1783        }
1784
1785        let normalized_ident = ident.normalize_to_macros_2_0();
1786        let outer_res = lifetime_rib_iter
1787            .find_map(|rib| rib.bindings.get_key_value(&normalized_ident).map(|(&outer, _)| outer));
1788
1789        self.emit_undeclared_lifetime_error(lifetime, outer_res);
1790        self.record_lifetime_res(lifetime.id, LifetimeRes::Error, LifetimeElisionCandidate::Named);
1791    }
1792
1793    #[instrument(level = "debug", skip(self))]
1794    fn resolve_anonymous_lifetime(
1795        &mut self,
1796        lifetime: &Lifetime,
1797        id_for_lint: NodeId,
1798        elided: bool,
1799    ) {
1800        debug_assert_eq!(lifetime.ident.name, kw::UnderscoreLifetime);
1801
1802        let kind =
1803            if elided { MissingLifetimeKind::Ampersand } else { MissingLifetimeKind::Underscore };
1804        let missing_lifetime = MissingLifetime {
1805            id: lifetime.id,
1806            span: lifetime.ident.span,
1807            kind,
1808            count: 1,
1809            id_for_lint,
1810        };
1811        let elision_candidate = LifetimeElisionCandidate::Missing(missing_lifetime);
1812        for (i, rib) in self.lifetime_ribs.iter().enumerate().rev() {
1813            debug!(?rib.kind);
1814            match rib.kind {
1815                LifetimeRibKind::AnonymousCreateParameter { binder, .. } => {
1816                    let res = self.create_fresh_lifetime(lifetime.ident, binder, kind);
1817                    self.record_lifetime_res(lifetime.id, res, elision_candidate);
1818                    return;
1819                }
1820                LifetimeRibKind::StaticIfNoLifetimeInScope { lint_id: node_id, emit_lint } => {
1821                    let mut lifetimes_in_scope = vec![];
1822                    for rib in self.lifetime_ribs[..i].iter().rev() {
1823                        lifetimes_in_scope.extend(rib.bindings.iter().map(|(ident, _)| ident.span));
1824                        // Consider any anonymous lifetimes, too
1825                        if let LifetimeRibKind::AnonymousCreateParameter { binder, .. } = rib.kind
1826                            && let Some(extra) = self.r.extra_lifetime_params_map.get(&binder)
1827                        {
1828                            lifetimes_in_scope.extend(extra.iter().map(|(ident, _, _)| ident.span));
1829                        }
1830                        if let LifetimeRibKind::Item = rib.kind {
1831                            break;
1832                        }
1833                    }
1834                    if lifetimes_in_scope.is_empty() {
1835                        self.record_lifetime_res(
1836                            lifetime.id,
1837                            LifetimeRes::Static,
1838                            elision_candidate,
1839                        );
1840                        return;
1841                    } else if emit_lint {
1842                        self.r.lint_buffer.buffer_lint(
1843                            lint::builtin::ELIDED_LIFETIMES_IN_ASSOCIATED_CONSTANT,
1844                            node_id,
1845                            lifetime.ident.span,
1846                            lint::BuiltinLintDiag::AssociatedConstElidedLifetime {
1847                                elided,
1848                                span: lifetime.ident.span,
1849                                lifetimes_in_scope: lifetimes_in_scope.into(),
1850                            },
1851                        );
1852                    }
1853                }
1854                LifetimeRibKind::AnonymousReportError => {
1855                    if elided {
1856                        let suggestion = self.lifetime_ribs[i..].iter().rev().find_map(|rib| {
1857                            if let LifetimeRibKind::Generics {
1858                                span,
1859                                kind: LifetimeBinderKind::PolyTrait | LifetimeBinderKind::WhereBound,
1860                                ..
1861                            } = rib.kind
1862                            {
1863                                Some(errors::ElidedAnonymousLifetimeReportErrorSuggestion {
1864                                    lo: span.shrink_to_lo(),
1865                                    hi: lifetime.ident.span.shrink_to_hi(),
1866                                })
1867                            } else {
1868                                None
1869                            }
1870                        });
1871                        // are we trying to use an anonymous lifetime
1872                        // on a non GAT associated trait type?
1873                        if !self.in_func_body
1874                            && let Some((module, _)) = &self.current_trait_ref
1875                            && let Some(ty) = &self.diag_metadata.current_self_type
1876                            && Some(true) == self.diag_metadata.in_non_gat_assoc_type
1877                            && let crate::ModuleKind::Def(DefKind::Trait, trait_id, _) = module.kind
1878                        {
1879                            if def_id_matches_path(
1880                                self.r.tcx,
1881                                trait_id,
1882                                &["core", "iter", "traits", "iterator", "Iterator"],
1883                            ) {
1884                                self.r.dcx().emit_err(errors::LendingIteratorReportError {
1885                                    lifetime: lifetime.ident.span,
1886                                    ty: ty.span,
1887                                });
1888                            } else {
1889                                self.r.dcx().emit_err(errors::AnonymousLifetimeNonGatReportError {
1890                                    lifetime: lifetime.ident.span,
1891                                });
1892                            }
1893                        } else {
1894                            self.r.dcx().emit_err(errors::ElidedAnonymousLifetimeReportError {
1895                                span: lifetime.ident.span,
1896                                suggestion,
1897                            });
1898                        }
1899                    } else {
1900                        self.r.dcx().emit_err(errors::ExplicitAnonymousLifetimeReportError {
1901                            span: lifetime.ident.span,
1902                        });
1903                    };
1904                    self.record_lifetime_res(lifetime.id, LifetimeRes::Error, elision_candidate);
1905                    return;
1906                }
1907                LifetimeRibKind::Elided(res) => {
1908                    self.record_lifetime_res(lifetime.id, res, elision_candidate);
1909                    return;
1910                }
1911                LifetimeRibKind::ElisionFailure => {
1912                    self.diag_metadata.current_elision_failures.push(missing_lifetime);
1913                    self.record_lifetime_res(lifetime.id, LifetimeRes::Error, elision_candidate);
1914                    return;
1915                }
1916                LifetimeRibKind::Item => break,
1917                LifetimeRibKind::Generics { .. } | LifetimeRibKind::ConstParamTy => {}
1918                LifetimeRibKind::ConcreteAnonConst(_) => {
1919                    // There is always an `Elided(LifetimeRes::Infer)` inside an `AnonConst`.
1920                    span_bug!(lifetime.ident.span, "unexpected rib kind: {:?}", rib.kind)
1921                }
1922            }
1923        }
1924        self.record_lifetime_res(lifetime.id, LifetimeRes::Error, elision_candidate);
1925        self.report_missing_lifetime_specifiers(vec![missing_lifetime], None);
1926    }
1927
1928    #[instrument(level = "debug", skip(self))]
1929    fn resolve_elided_lifetime(&mut self, anchor_id: NodeId, span: Span) {
1930        let id = self.r.next_node_id();
1931        let lt = Lifetime { id, ident: Ident::new(kw::UnderscoreLifetime, span) };
1932
1933        self.record_lifetime_res(
1934            anchor_id,
1935            LifetimeRes::ElidedAnchor { start: id, end: id + 1 },
1936            LifetimeElisionCandidate::Ignore,
1937        );
1938        self.resolve_anonymous_lifetime(&lt, anchor_id, true);
1939    }
1940
1941    #[instrument(level = "debug", skip(self))]
1942    fn create_fresh_lifetime(
1943        &mut self,
1944        ident: Ident,
1945        binder: NodeId,
1946        kind: MissingLifetimeKind,
1947    ) -> LifetimeRes {
1948        debug_assert_eq!(ident.name, kw::UnderscoreLifetime);
1949        debug!(?ident.span);
1950
1951        // Leave the responsibility to create the `LocalDefId` to lowering.
1952        let param = self.r.next_node_id();
1953        let res = LifetimeRes::Fresh { param, binder, kind };
1954        self.record_lifetime_param(param, res);
1955
1956        // Record the created lifetime parameter so lowering can pick it up and add it to HIR.
1957        self.r
1958            .extra_lifetime_params_map
1959            .entry(binder)
1960            .or_insert_with(Vec::new)
1961            .push((ident, param, res));
1962        res
1963    }
1964
1965    #[instrument(level = "debug", skip(self))]
1966    fn resolve_elided_lifetimes_in_path(
1967        &mut self,
1968        partial_res: PartialRes,
1969        path: &[Segment],
1970        source: PathSource<'_, '_, '_>,
1971        path_span: Span,
1972    ) {
1973        let proj_start = path.len() - partial_res.unresolved_segments();
1974        for (i, segment) in path.iter().enumerate() {
1975            if segment.has_lifetime_args {
1976                continue;
1977            }
1978            let Some(segment_id) = segment.id else {
1979                continue;
1980            };
1981
1982            // Figure out if this is a type/trait segment,
1983            // which may need lifetime elision performed.
1984            let type_def_id = match partial_res.base_res() {
1985                Res::Def(DefKind::AssocTy, def_id) if i + 2 == proj_start => {
1986                    self.r.tcx.parent(def_id)
1987                }
1988                Res::Def(DefKind::Variant, def_id) if i + 1 == proj_start => {
1989                    self.r.tcx.parent(def_id)
1990                }
1991                Res::Def(DefKind::Struct, def_id)
1992                | Res::Def(DefKind::Union, def_id)
1993                | Res::Def(DefKind::Enum, def_id)
1994                | Res::Def(DefKind::TyAlias, def_id)
1995                | Res::Def(DefKind::Trait, def_id)
1996                    if i + 1 == proj_start =>
1997                {
1998                    def_id
1999                }
2000                _ => continue,
2001            };
2002
2003            let expected_lifetimes = self.r.item_generics_num_lifetimes(type_def_id);
2004            if expected_lifetimes == 0 {
2005                continue;
2006            }
2007
2008            let node_ids = self.r.next_node_ids(expected_lifetimes);
2009            self.record_lifetime_res(
2010                segment_id,
2011                LifetimeRes::ElidedAnchor { start: node_ids.start, end: node_ids.end },
2012                LifetimeElisionCandidate::Ignore,
2013            );
2014
2015            let inferred = match source {
2016                PathSource::Trait(..)
2017                | PathSource::TraitItem(..)
2018                | PathSource::Type
2019                | PathSource::PreciseCapturingArg(..)
2020                | PathSource::ReturnTypeNotation => false,
2021                PathSource::Expr(..)
2022                | PathSource::Pat
2023                | PathSource::Struct
2024                | PathSource::TupleStruct(..)
2025                | PathSource::DefineOpaques
2026                | PathSource::Delegation => true,
2027            };
2028            if inferred {
2029                // Do not create a parameter for patterns and expressions: type checking can infer
2030                // the appropriate lifetime for us.
2031                for id in node_ids {
2032                    self.record_lifetime_res(
2033                        id,
2034                        LifetimeRes::Infer,
2035                        LifetimeElisionCandidate::Named,
2036                    );
2037                }
2038                continue;
2039            }
2040
2041            let elided_lifetime_span = if segment.has_generic_args {
2042                // If there are brackets, but not generic arguments, then use the opening bracket
2043                segment.args_span.with_hi(segment.args_span.lo() + BytePos(1))
2044            } else {
2045                // If there are no brackets, use the identifier span.
2046                // HACK: we use find_ancestor_inside to properly suggest elided spans in paths
2047                // originating from macros, since the segment's span might be from a macro arg.
2048                segment.ident.span.find_ancestor_inside(path_span).unwrap_or(path_span)
2049            };
2050            let ident = Ident::new(kw::UnderscoreLifetime, elided_lifetime_span);
2051
2052            let kind = if segment.has_generic_args {
2053                MissingLifetimeKind::Comma
2054            } else {
2055                MissingLifetimeKind::Brackets
2056            };
2057            let missing_lifetime = MissingLifetime {
2058                id: node_ids.start,
2059                id_for_lint: segment_id,
2060                span: elided_lifetime_span,
2061                kind,
2062                count: expected_lifetimes,
2063            };
2064            let mut should_lint = true;
2065            for rib in self.lifetime_ribs.iter().rev() {
2066                match rib.kind {
2067                    // In create-parameter mode we error here because we don't want to support
2068                    // deprecated impl elision in new features like impl elision and `async fn`,
2069                    // both of which work using the `CreateParameter` mode:
2070                    //
2071                    //     impl Foo for std::cell::Ref<u32> // note lack of '_
2072                    //     async fn foo(_: std::cell::Ref<u32>) { ... }
2073                    LifetimeRibKind::AnonymousCreateParameter { report_in_path: true, .. }
2074                    | LifetimeRibKind::StaticIfNoLifetimeInScope { .. } => {
2075                        let sess = self.r.tcx.sess;
2076                        let subdiag = rustc_errors::elided_lifetime_in_path_suggestion(
2077                            sess.source_map(),
2078                            expected_lifetimes,
2079                            path_span,
2080                            !segment.has_generic_args,
2081                            elided_lifetime_span,
2082                        );
2083                        self.r.dcx().emit_err(errors::ImplicitElidedLifetimeNotAllowedHere {
2084                            span: path_span,
2085                            subdiag,
2086                        });
2087                        should_lint = false;
2088
2089                        for id in node_ids {
2090                            self.record_lifetime_res(
2091                                id,
2092                                LifetimeRes::Error,
2093                                LifetimeElisionCandidate::Named,
2094                            );
2095                        }
2096                        break;
2097                    }
2098                    // Do not create a parameter for patterns and expressions.
2099                    LifetimeRibKind::AnonymousCreateParameter { binder, .. } => {
2100                        // Group all suggestions into the first record.
2101                        let mut candidate = LifetimeElisionCandidate::Missing(missing_lifetime);
2102                        for id in node_ids {
2103                            let res = self.create_fresh_lifetime(ident, binder, kind);
2104                            self.record_lifetime_res(
2105                                id,
2106                                res,
2107                                replace(&mut candidate, LifetimeElisionCandidate::Named),
2108                            );
2109                        }
2110                        break;
2111                    }
2112                    LifetimeRibKind::Elided(res) => {
2113                        let mut candidate = LifetimeElisionCandidate::Missing(missing_lifetime);
2114                        for id in node_ids {
2115                            self.record_lifetime_res(
2116                                id,
2117                                res,
2118                                replace(&mut candidate, LifetimeElisionCandidate::Ignore),
2119                            );
2120                        }
2121                        break;
2122                    }
2123                    LifetimeRibKind::ElisionFailure => {
2124                        self.diag_metadata.current_elision_failures.push(missing_lifetime);
2125                        for id in node_ids {
2126                            self.record_lifetime_res(
2127                                id,
2128                                LifetimeRes::Error,
2129                                LifetimeElisionCandidate::Ignore,
2130                            );
2131                        }
2132                        break;
2133                    }
2134                    // `LifetimeRes::Error`, which would usually be used in the case of
2135                    // `ReportError`, is unsuitable here, as we don't emit an error yet. Instead,
2136                    // we simply resolve to an implicit lifetime, which will be checked later, at
2137                    // which point a suitable error will be emitted.
2138                    LifetimeRibKind::AnonymousReportError | LifetimeRibKind::Item => {
2139                        for id in node_ids {
2140                            self.record_lifetime_res(
2141                                id,
2142                                LifetimeRes::Error,
2143                                LifetimeElisionCandidate::Ignore,
2144                            );
2145                        }
2146                        self.report_missing_lifetime_specifiers(vec![missing_lifetime], None);
2147                        break;
2148                    }
2149                    LifetimeRibKind::Generics { .. } | LifetimeRibKind::ConstParamTy => {}
2150                    LifetimeRibKind::ConcreteAnonConst(_) => {
2151                        // There is always an `Elided(LifetimeRes::Infer)` inside an `AnonConst`.
2152                        span_bug!(elided_lifetime_span, "unexpected rib kind: {:?}", rib.kind)
2153                    }
2154                }
2155            }
2156
2157            if should_lint {
2158                self.r.lint_buffer.buffer_lint(
2159                    lint::builtin::ELIDED_LIFETIMES_IN_PATHS,
2160                    segment_id,
2161                    elided_lifetime_span,
2162                    lint::BuiltinLintDiag::ElidedLifetimesInPaths(
2163                        expected_lifetimes,
2164                        path_span,
2165                        !segment.has_generic_args,
2166                        elided_lifetime_span,
2167                    ),
2168                );
2169            }
2170        }
2171    }
2172
2173    #[instrument(level = "debug", skip(self))]
2174    fn record_lifetime_res(
2175        &mut self,
2176        id: NodeId,
2177        res: LifetimeRes,
2178        candidate: LifetimeElisionCandidate,
2179    ) {
2180        if let Some(prev_res) = self.r.lifetimes_res_map.insert(id, res) {
2181            panic!("lifetime {id:?} resolved multiple times ({prev_res:?} before, {res:?} now)")
2182        }
2183
2184        match res {
2185            LifetimeRes::Param { .. } | LifetimeRes::Fresh { .. } | LifetimeRes::Static { .. } => {
2186                if let Some(ref mut candidates) = self.lifetime_elision_candidates {
2187                    candidates.push((res, candidate));
2188                }
2189            }
2190            LifetimeRes::Infer | LifetimeRes::Error | LifetimeRes::ElidedAnchor { .. } => {}
2191        }
2192    }
2193
2194    #[instrument(level = "debug", skip(self))]
2195    fn record_lifetime_param(&mut self, id: NodeId, res: LifetimeRes) {
2196        if let Some(prev_res) = self.r.lifetimes_res_map.insert(id, res) {
2197            panic!(
2198                "lifetime parameter {id:?} resolved multiple times ({prev_res:?} before, {res:?} now)"
2199            )
2200        }
2201    }
2202
2203    /// Perform resolution of a function signature, accounting for lifetime elision.
2204    #[instrument(level = "debug", skip(self, inputs))]
2205    fn resolve_fn_signature(
2206        &mut self,
2207        fn_id: NodeId,
2208        has_self: bool,
2209        inputs: impl Iterator<Item = (Option<&'ast Pat>, &'ast Ty)> + Clone,
2210        output_ty: &'ast FnRetTy,
2211        report_elided_lifetimes_in_path: bool,
2212    ) {
2213        let rib = LifetimeRibKind::AnonymousCreateParameter {
2214            binder: fn_id,
2215            report_in_path: report_elided_lifetimes_in_path,
2216        };
2217        self.with_lifetime_rib(rib, |this| {
2218            // Add each argument to the rib.
2219            let elision_lifetime = this.resolve_fn_params(has_self, inputs);
2220            debug!(?elision_lifetime);
2221
2222            let outer_failures = take(&mut this.diag_metadata.current_elision_failures);
2223            let output_rib = if let Ok(res) = elision_lifetime.as_ref() {
2224                this.r.lifetime_elision_allowed.insert(fn_id);
2225                LifetimeRibKind::Elided(*res)
2226            } else {
2227                LifetimeRibKind::ElisionFailure
2228            };
2229            this.with_lifetime_rib(output_rib, |this| visit::walk_fn_ret_ty(this, output_ty));
2230            let elision_failures =
2231                replace(&mut this.diag_metadata.current_elision_failures, outer_failures);
2232            if !elision_failures.is_empty() {
2233                let Err(failure_info) = elision_lifetime else { bug!() };
2234                this.report_missing_lifetime_specifiers(elision_failures, Some(failure_info));
2235            }
2236        });
2237    }
2238
2239    /// Resolve inside function parameters and parameter types.
2240    /// Returns the lifetime for elision in fn return type,
2241    /// or diagnostic information in case of elision failure.
2242    fn resolve_fn_params(
2243        &mut self,
2244        has_self: bool,
2245        inputs: impl Iterator<Item = (Option<&'ast Pat>, &'ast Ty)> + Clone,
2246    ) -> Result<LifetimeRes, (Vec<MissingLifetime>, Vec<ElisionFnParameter>)> {
2247        enum Elision {
2248            /// We have not found any candidate.
2249            None,
2250            /// We have a candidate bound to `self`.
2251            Self_(LifetimeRes),
2252            /// We have a candidate bound to a parameter.
2253            Param(LifetimeRes),
2254            /// We failed elision.
2255            Err,
2256        }
2257
2258        // Save elision state to reinstate it later.
2259        let outer_candidates = self.lifetime_elision_candidates.take();
2260
2261        // Result of elision.
2262        let mut elision_lifetime = Elision::None;
2263        // Information for diagnostics.
2264        let mut parameter_info = Vec::new();
2265        let mut all_candidates = Vec::new();
2266
2267        // Resolve and apply bindings first so diagnostics can see if they're used in types.
2268        let mut bindings = smallvec![(PatBoundCtx::Product, Default::default())];
2269        for (pat, _) in inputs.clone() {
2270            debug!("resolving bindings in pat = {pat:?}");
2271            self.with_lifetime_rib(LifetimeRibKind::Elided(LifetimeRes::Infer), |this| {
2272                if let Some(pat) = pat {
2273                    this.resolve_pattern(pat, PatternSource::FnParam, &mut bindings);
2274                }
2275            });
2276        }
2277        self.apply_pattern_bindings(bindings);
2278
2279        for (index, (pat, ty)) in inputs.enumerate() {
2280            debug!("resolving type for pat = {pat:?}, ty = {ty:?}");
2281            // Record elision candidates only for this parameter.
2282            debug_assert_matches!(self.lifetime_elision_candidates, None);
2283            self.lifetime_elision_candidates = Some(Default::default());
2284            self.visit_ty(ty);
2285            let local_candidates = self.lifetime_elision_candidates.take();
2286
2287            if let Some(candidates) = local_candidates {
2288                let distinct: UnordSet<_> = candidates.iter().map(|(res, _)| *res).collect();
2289                let lifetime_count = distinct.len();
2290                if lifetime_count != 0 {
2291                    parameter_info.push(ElisionFnParameter {
2292                        index,
2293                        ident: if let Some(pat) = pat
2294                            && let PatKind::Ident(_, ident, _) = pat.kind
2295                        {
2296                            Some(ident)
2297                        } else {
2298                            None
2299                        },
2300                        lifetime_count,
2301                        span: ty.span,
2302                    });
2303                    all_candidates.extend(candidates.into_iter().filter_map(|(_, candidate)| {
2304                        match candidate {
2305                            LifetimeElisionCandidate::Ignore | LifetimeElisionCandidate::Named => {
2306                                None
2307                            }
2308                            LifetimeElisionCandidate::Missing(missing) => Some(missing),
2309                        }
2310                    }));
2311                }
2312                if !distinct.is_empty() {
2313                    match elision_lifetime {
2314                        // We are the first parameter to bind lifetimes.
2315                        Elision::None => {
2316                            if let Some(res) = distinct.get_only() {
2317                                // We have a single lifetime => success.
2318                                elision_lifetime = Elision::Param(*res)
2319                            } else {
2320                                // We have multiple lifetimes => error.
2321                                elision_lifetime = Elision::Err;
2322                            }
2323                        }
2324                        // We have 2 parameters that bind lifetimes => error.
2325                        Elision::Param(_) => elision_lifetime = Elision::Err,
2326                        // `self` elision takes precedence over everything else.
2327                        Elision::Self_(_) | Elision::Err => {}
2328                    }
2329                }
2330            }
2331
2332            // Handle `self` specially.
2333            if index == 0 && has_self {
2334                let self_lifetime = self.find_lifetime_for_self(ty);
2335                elision_lifetime = match self_lifetime {
2336                    // We found `self` elision.
2337                    Set1::One(lifetime) => Elision::Self_(lifetime),
2338                    // `self` itself had ambiguous lifetimes, e.g.
2339                    // &Box<&Self>. In this case we won't consider
2340                    // taking an alternative parameter lifetime; just avoid elision
2341                    // entirely.
2342                    Set1::Many => Elision::Err,
2343                    // We do not have `self` elision: disregard the `Elision::Param` that we may
2344                    // have found.
2345                    Set1::Empty => Elision::None,
2346                }
2347            }
2348            debug!("(resolving function / closure) recorded parameter");
2349        }
2350
2351        // Reinstate elision state.
2352        debug_assert_matches!(self.lifetime_elision_candidates, None);
2353        self.lifetime_elision_candidates = outer_candidates;
2354
2355        if let Elision::Param(res) | Elision::Self_(res) = elision_lifetime {
2356            return Ok(res);
2357        }
2358
2359        // We do not have a candidate.
2360        Err((all_candidates, parameter_info))
2361    }
2362
2363    /// List all the lifetimes that appear in the provided type.
2364    fn find_lifetime_for_self(&self, ty: &'ast Ty) -> Set1<LifetimeRes> {
2365        /// Visits a type to find all the &references, and determines the
2366        /// set of lifetimes for all of those references where the referent
2367        /// contains Self.
2368        struct FindReferenceVisitor<'a, 'ra, 'tcx> {
2369            r: &'a Resolver<'ra, 'tcx>,
2370            impl_self: Option<Res>,
2371            lifetime: Set1<LifetimeRes>,
2372        }
2373
2374        impl<'ra> Visitor<'ra> for FindReferenceVisitor<'_, '_, '_> {
2375            fn visit_ty(&mut self, ty: &'ra Ty) {
2376                trace!("FindReferenceVisitor considering ty={:?}", ty);
2377                if let TyKind::Ref(lt, _) | TyKind::PinnedRef(lt, _) = ty.kind {
2378                    // See if anything inside the &thing contains Self
2379                    let mut visitor =
2380                        SelfVisitor { r: self.r, impl_self: self.impl_self, self_found: false };
2381                    visitor.visit_ty(ty);
2382                    trace!("FindReferenceVisitor: SelfVisitor self_found={:?}", visitor.self_found);
2383                    if visitor.self_found {
2384                        let lt_id = if let Some(lt) = lt {
2385                            lt.id
2386                        } else {
2387                            let res = self.r.lifetimes_res_map[&ty.id];
2388                            let LifetimeRes::ElidedAnchor { start, .. } = res else { bug!() };
2389                            start
2390                        };
2391                        let lt_res = self.r.lifetimes_res_map[&lt_id];
2392                        trace!("FindReferenceVisitor inserting res={:?}", lt_res);
2393                        self.lifetime.insert(lt_res);
2394                    }
2395                }
2396                visit::walk_ty(self, ty)
2397            }
2398
2399            // A type may have an expression as a const generic argument.
2400            // We do not want to recurse into those.
2401            fn visit_expr(&mut self, _: &'ra Expr) {}
2402        }
2403
2404        /// Visitor which checks the referent of a &Thing to see if the
2405        /// Thing contains Self
2406        struct SelfVisitor<'a, 'ra, 'tcx> {
2407            r: &'a Resolver<'ra, 'tcx>,
2408            impl_self: Option<Res>,
2409            self_found: bool,
2410        }
2411
2412        impl SelfVisitor<'_, '_, '_> {
2413            // Look for `self: &'a Self` - also desugared from `&'a self`
2414            fn is_self_ty(&self, ty: &Ty) -> bool {
2415                match ty.kind {
2416                    TyKind::ImplicitSelf => true,
2417                    TyKind::Path(None, _) => {
2418                        let path_res = self.r.partial_res_map[&ty.id].full_res();
2419                        if let Some(Res::SelfTyParam { .. } | Res::SelfTyAlias { .. }) = path_res {
2420                            return true;
2421                        }
2422                        self.impl_self.is_some() && path_res == self.impl_self
2423                    }
2424                    _ => false,
2425                }
2426            }
2427        }
2428
2429        impl<'ra> Visitor<'ra> for SelfVisitor<'_, '_, '_> {
2430            fn visit_ty(&mut self, ty: &'ra Ty) {
2431                trace!("SelfVisitor considering ty={:?}", ty);
2432                if self.is_self_ty(ty) {
2433                    trace!("SelfVisitor found Self");
2434                    self.self_found = true;
2435                }
2436                visit::walk_ty(self, ty)
2437            }
2438
2439            // A type may have an expression as a const generic argument.
2440            // We do not want to recurse into those.
2441            fn visit_expr(&mut self, _: &'ra Expr) {}
2442        }
2443
2444        let impl_self = self
2445            .diag_metadata
2446            .current_self_type
2447            .as_ref()
2448            .and_then(|ty| {
2449                if let TyKind::Path(None, _) = ty.kind {
2450                    self.r.partial_res_map.get(&ty.id)
2451                } else {
2452                    None
2453                }
2454            })
2455            .and_then(|res| res.full_res())
2456            .filter(|res| {
2457                // Permit the types that unambiguously always
2458                // result in the same type constructor being used
2459                // (it can't differ between `Self` and `self`).
2460                matches!(
2461                    res,
2462                    Res::Def(DefKind::Struct | DefKind::Union | DefKind::Enum, _,) | Res::PrimTy(_)
2463                )
2464            });
2465        let mut visitor = FindReferenceVisitor { r: self.r, impl_self, lifetime: Set1::Empty };
2466        visitor.visit_ty(ty);
2467        trace!("FindReferenceVisitor found={:?}", visitor.lifetime);
2468        visitor.lifetime
2469    }
2470
2471    /// Searches the current set of local scopes for labels. Returns the `NodeId` of the resolved
2472    /// label and reports an error if the label is not found or is unreachable.
2473    fn resolve_label(&self, mut label: Ident) -> Result<(NodeId, Span), ResolutionError<'ra>> {
2474        let mut suggestion = None;
2475
2476        for i in (0..self.label_ribs.len()).rev() {
2477            let rib = &self.label_ribs[i];
2478
2479            if let RibKind::MacroDefinition(def) = rib.kind
2480                // If an invocation of this macro created `ident`, give up on `ident`
2481                // and switch to `ident`'s source from the macro definition.
2482                && def == self.r.macro_def(label.span.ctxt())
2483            {
2484                label.span.remove_mark();
2485            }
2486
2487            let ident = label.normalize_to_macro_rules();
2488            if let Some((ident, id)) = rib.bindings.get_key_value(&ident) {
2489                let definition_span = ident.span;
2490                return if self.is_label_valid_from_rib(i) {
2491                    Ok((*id, definition_span))
2492                } else {
2493                    Err(ResolutionError::UnreachableLabel {
2494                        name: label.name,
2495                        definition_span,
2496                        suggestion,
2497                    })
2498                };
2499            }
2500
2501            // Diagnostics: Check if this rib contains a label with a similar name, keep track of
2502            // the first such label that is encountered.
2503            suggestion = suggestion.or_else(|| self.suggestion_for_label_in_rib(i, label));
2504        }
2505
2506        Err(ResolutionError::UndeclaredLabel { name: label.name, suggestion })
2507    }
2508
2509    /// Determine whether or not a label from the `rib_index`th label rib is reachable.
2510    fn is_label_valid_from_rib(&self, rib_index: usize) -> bool {
2511        let ribs = &self.label_ribs[rib_index + 1..];
2512        ribs.iter().all(|rib| !rib.kind.is_label_barrier())
2513    }
2514
2515    fn resolve_adt(&mut self, item: &'ast Item, generics: &'ast Generics) {
2516        debug!("resolve_adt");
2517        let kind = self.r.local_def_kind(item.id);
2518        self.with_current_self_item(item, |this| {
2519            this.with_generic_param_rib(
2520                &generics.params,
2521                RibKind::Item(HasGenericParams::Yes(generics.span), kind),
2522                item.id,
2523                LifetimeBinderKind::Item,
2524                generics.span,
2525                |this| {
2526                    let item_def_id = this.r.local_def_id(item.id).to_def_id();
2527                    this.with_self_rib(
2528                        Res::SelfTyAlias {
2529                            alias_to: item_def_id,
2530                            forbid_generic: false,
2531                            is_trait_impl: false,
2532                        },
2533                        |this| {
2534                            visit::walk_item(this, item);
2535                        },
2536                    );
2537                },
2538            );
2539        });
2540    }
2541
2542    fn future_proof_import(&mut self, use_tree: &UseTree) {
2543        if let [segment, rest @ ..] = use_tree.prefix.segments.as_slice() {
2544            let ident = segment.ident;
2545            if ident.is_path_segment_keyword() || ident.span.is_rust_2015() {
2546                return;
2547            }
2548
2549            let nss = match use_tree.kind {
2550                UseTreeKind::Simple(..) if rest.is_empty() => &[TypeNS, ValueNS][..],
2551                _ => &[TypeNS],
2552            };
2553            let report_error = |this: &Self, ns| {
2554                if this.should_report_errs() {
2555                    let what = if ns == TypeNS { "type parameters" } else { "local variables" };
2556                    this.r.dcx().emit_err(errors::ImportsCannotReferTo { span: ident.span, what });
2557                }
2558            };
2559
2560            for &ns in nss {
2561                match self.maybe_resolve_ident_in_lexical_scope(ident, ns) {
2562                    Some(LexicalScopeBinding::Res(..)) => {
2563                        report_error(self, ns);
2564                    }
2565                    Some(LexicalScopeBinding::Item(binding)) => {
2566                        if let Some(LexicalScopeBinding::Res(..)) =
2567                            self.resolve_ident_in_lexical_scope(ident, ns, None, Some(binding))
2568                        {
2569                            report_error(self, ns);
2570                        }
2571                    }
2572                    None => {}
2573                }
2574            }
2575        } else if let UseTreeKind::Nested { items, .. } = &use_tree.kind {
2576            for (use_tree, _) in items {
2577                self.future_proof_import(use_tree);
2578            }
2579        }
2580    }
2581
2582    fn resolve_item(&mut self, item: &'ast Item) {
2583        let mod_inner_docs =
2584            matches!(item.kind, ItemKind::Mod(..)) && rustdoc::inner_docs(&item.attrs);
2585        if !mod_inner_docs && !matches!(item.kind, ItemKind::Impl(..) | ItemKind::Use(..)) {
2586            self.resolve_doc_links(&item.attrs, MaybeExported::Ok(item.id));
2587        }
2588
2589        debug!("(resolving item) resolving {:?} ({:?})", item.kind.ident(), item.kind);
2590
2591        let def_kind = self.r.local_def_kind(item.id);
2592        match item.kind {
2593            ItemKind::TyAlias(box TyAlias { ref generics, .. }) => {
2594                self.with_generic_param_rib(
2595                    &generics.params,
2596                    RibKind::Item(HasGenericParams::Yes(generics.span), def_kind),
2597                    item.id,
2598                    LifetimeBinderKind::Item,
2599                    generics.span,
2600                    |this| visit::walk_item(this, item),
2601                );
2602            }
2603
2604            ItemKind::Fn(box Fn { ref generics, ref define_opaque, .. }) => {
2605                self.with_generic_param_rib(
2606                    &generics.params,
2607                    RibKind::Item(HasGenericParams::Yes(generics.span), def_kind),
2608                    item.id,
2609                    LifetimeBinderKind::Function,
2610                    generics.span,
2611                    |this| visit::walk_item(this, item),
2612                );
2613                self.resolve_define_opaques(define_opaque);
2614            }
2615
2616            ItemKind::Enum(_, ref generics, _)
2617            | ItemKind::Struct(_, ref generics, _)
2618            | ItemKind::Union(_, ref generics, _) => {
2619                self.resolve_adt(item, generics);
2620            }
2621
2622            ItemKind::Impl(box Impl {
2623                ref generics,
2624                ref of_trait,
2625                ref self_ty,
2626                items: ref impl_items,
2627                ..
2628            }) => {
2629                self.diag_metadata.current_impl_items = Some(impl_items);
2630                self.resolve_implementation(
2631                    &item.attrs,
2632                    generics,
2633                    of_trait,
2634                    self_ty,
2635                    item.id,
2636                    impl_items,
2637                );
2638                self.diag_metadata.current_impl_items = None;
2639            }
2640
2641            ItemKind::Trait(box Trait { ref generics, ref bounds, ref items, .. }) => {
2642                // Create a new rib for the trait-wide type parameters.
2643                self.with_generic_param_rib(
2644                    &generics.params,
2645                    RibKind::Item(HasGenericParams::Yes(generics.span), def_kind),
2646                    item.id,
2647                    LifetimeBinderKind::Item,
2648                    generics.span,
2649                    |this| {
2650                        let local_def_id = this.r.local_def_id(item.id).to_def_id();
2651                        this.with_self_rib(Res::SelfTyParam { trait_: local_def_id }, |this| {
2652                            this.visit_generics(generics);
2653                            walk_list!(this, visit_param_bound, bounds, BoundKind::SuperTraits);
2654                            this.resolve_trait_items(items);
2655                        });
2656                    },
2657                );
2658            }
2659
2660            ItemKind::TraitAlias(_, ref generics, ref bounds) => {
2661                // Create a new rib for the trait-wide type parameters.
2662                self.with_generic_param_rib(
2663                    &generics.params,
2664                    RibKind::Item(HasGenericParams::Yes(generics.span), def_kind),
2665                    item.id,
2666                    LifetimeBinderKind::Item,
2667                    generics.span,
2668                    |this| {
2669                        let local_def_id = this.r.local_def_id(item.id).to_def_id();
2670                        this.with_self_rib(Res::SelfTyParam { trait_: local_def_id }, |this| {
2671                            this.visit_generics(generics);
2672                            walk_list!(this, visit_param_bound, bounds, BoundKind::Bound);
2673                        });
2674                    },
2675                );
2676            }
2677
2678            ItemKind::Mod(..) => {
2679                self.with_mod_rib(item.id, |this| {
2680                    if mod_inner_docs {
2681                        this.resolve_doc_links(&item.attrs, MaybeExported::Ok(item.id));
2682                    }
2683                    let old_macro_rules = this.parent_scope.macro_rules;
2684                    visit::walk_item(this, item);
2685                    // Maintain macro_rules scopes in the same way as during early resolution
2686                    // for diagnostics and doc links.
2687                    if item.attrs.iter().all(|attr| {
2688                        !attr.has_name(sym::macro_use) && !attr.has_name(sym::macro_escape)
2689                    }) {
2690                        this.parent_scope.macro_rules = old_macro_rules;
2691                    }
2692                });
2693            }
2694
2695            ItemKind::Static(box ast::StaticItem {
2696                ident,
2697                ref ty,
2698                ref expr,
2699                ref define_opaque,
2700                ..
2701            }) => {
2702                self.with_static_rib(def_kind, |this| {
2703                    this.with_lifetime_rib(LifetimeRibKind::Elided(LifetimeRes::Static), |this| {
2704                        this.visit_ty(ty);
2705                    });
2706                    if let Some(expr) = expr {
2707                        // We already forbid generic params because of the above item rib,
2708                        // so it doesn't matter whether this is a trivial constant.
2709                        this.resolve_const_body(expr, Some((ident, ConstantItemKind::Static)));
2710                    }
2711                });
2712                self.resolve_define_opaques(define_opaque);
2713            }
2714
2715            ItemKind::Const(box ast::ConstItem {
2716                ident,
2717                ref generics,
2718                ref ty,
2719                ref expr,
2720                ref define_opaque,
2721                ..
2722            }) => {
2723                self.with_generic_param_rib(
2724                    &generics.params,
2725                    RibKind::Item(
2726                        if self.r.tcx.features().generic_const_items() {
2727                            HasGenericParams::Yes(generics.span)
2728                        } else {
2729                            HasGenericParams::No
2730                        },
2731                        def_kind,
2732                    ),
2733                    item.id,
2734                    LifetimeBinderKind::ConstItem,
2735                    generics.span,
2736                    |this| {
2737                        this.visit_generics(generics);
2738
2739                        this.with_lifetime_rib(
2740                            LifetimeRibKind::Elided(LifetimeRes::Static),
2741                            |this| this.visit_ty(ty),
2742                        );
2743
2744                        if let Some(expr) = expr {
2745                            this.resolve_const_body(expr, Some((ident, ConstantItemKind::Const)));
2746                        }
2747                    },
2748                );
2749                self.resolve_define_opaques(define_opaque);
2750            }
2751
2752            ItemKind::Use(ref use_tree) => {
2753                let maybe_exported = match use_tree.kind {
2754                    UseTreeKind::Simple(_) | UseTreeKind::Glob => MaybeExported::Ok(item.id),
2755                    UseTreeKind::Nested { .. } => MaybeExported::NestedUse(&item.vis),
2756                };
2757                self.resolve_doc_links(&item.attrs, maybe_exported);
2758
2759                self.future_proof_import(use_tree);
2760            }
2761
2762            ItemKind::MacroDef(_, ref macro_def) => {
2763                // Maintain macro_rules scopes in the same way as during early resolution
2764                // for diagnostics and doc links.
2765                if macro_def.macro_rules {
2766                    let def_id = self.r.local_def_id(item.id);
2767                    self.parent_scope.macro_rules = self.r.macro_rules_scopes[&def_id];
2768                }
2769            }
2770
2771            ItemKind::ForeignMod(_) | ItemKind::GlobalAsm(_) => {
2772                visit::walk_item(self, item);
2773            }
2774
2775            ItemKind::Delegation(ref delegation) => {
2776                let span = delegation.path.segments.last().unwrap().ident.span;
2777                self.with_generic_param_rib(
2778                    &[],
2779                    RibKind::Item(HasGenericParams::Yes(span), def_kind),
2780                    item.id,
2781                    LifetimeBinderKind::Function,
2782                    span,
2783                    |this| this.resolve_delegation(delegation),
2784                );
2785            }
2786
2787            ItemKind::ExternCrate(..) => {}
2788
2789            ItemKind::MacCall(_) | ItemKind::DelegationMac(..) => {
2790                panic!("unexpanded macro in resolve!")
2791            }
2792        }
2793    }
2794
2795    fn with_generic_param_rib<'c, F>(
2796        &'c mut self,
2797        params: &'c [GenericParam],
2798        kind: RibKind<'ra>,
2799        binder: NodeId,
2800        generics_kind: LifetimeBinderKind,
2801        generics_span: Span,
2802        f: F,
2803    ) where
2804        F: FnOnce(&mut Self),
2805    {
2806        debug!("with_generic_param_rib");
2807        let lifetime_kind =
2808            LifetimeRibKind::Generics { binder, span: generics_span, kind: generics_kind };
2809
2810        let mut function_type_rib = Rib::new(kind);
2811        let mut function_value_rib = Rib::new(kind);
2812        let mut function_lifetime_rib = LifetimeRib::new(lifetime_kind);
2813
2814        // Only check for shadowed bindings if we're declaring new params.
2815        if !params.is_empty() {
2816            let mut seen_bindings = FxHashMap::default();
2817            // Store all seen lifetimes names from outer scopes.
2818            let mut seen_lifetimes = FxHashSet::default();
2819
2820            // We also can't shadow bindings from associated parent items.
2821            for ns in [ValueNS, TypeNS] {
2822                for parent_rib in self.ribs[ns].iter().rev() {
2823                    // Break at mod level, to account for nested items which are
2824                    // allowed to shadow generic param names.
2825                    if matches!(parent_rib.kind, RibKind::Module(..)) {
2826                        break;
2827                    }
2828
2829                    seen_bindings
2830                        .extend(parent_rib.bindings.keys().map(|ident| (*ident, ident.span)));
2831                }
2832            }
2833
2834            // Forbid shadowing lifetime bindings
2835            for rib in self.lifetime_ribs.iter().rev() {
2836                seen_lifetimes.extend(rib.bindings.iter().map(|(ident, _)| *ident));
2837                if let LifetimeRibKind::Item = rib.kind {
2838                    break;
2839                }
2840            }
2841
2842            for param in params {
2843                let ident = param.ident.normalize_to_macros_2_0();
2844                debug!("with_generic_param_rib: {}", param.id);
2845
2846                if let GenericParamKind::Lifetime = param.kind
2847                    && let Some(&original) = seen_lifetimes.get(&ident)
2848                {
2849                    diagnostics::signal_lifetime_shadowing(self.r.tcx.sess, original, param.ident);
2850                    // Record lifetime res, so lowering knows there is something fishy.
2851                    self.record_lifetime_param(param.id, LifetimeRes::Error);
2852                    continue;
2853                }
2854
2855                match seen_bindings.entry(ident) {
2856                    Entry::Occupied(entry) => {
2857                        let span = *entry.get();
2858                        let err = ResolutionError::NameAlreadyUsedInParameterList(ident, span);
2859                        self.report_error(param.ident.span, err);
2860                        let rib = match param.kind {
2861                            GenericParamKind::Lifetime => {
2862                                // Record lifetime res, so lowering knows there is something fishy.
2863                                self.record_lifetime_param(param.id, LifetimeRes::Error);
2864                                continue;
2865                            }
2866                            GenericParamKind::Type { .. } => &mut function_type_rib,
2867                            GenericParamKind::Const { .. } => &mut function_value_rib,
2868                        };
2869
2870                        // Taint the resolution in case of errors to prevent follow up errors in typeck
2871                        self.r.record_partial_res(param.id, PartialRes::new(Res::Err));
2872                        rib.bindings.insert(ident, Res::Err);
2873                        continue;
2874                    }
2875                    Entry::Vacant(entry) => {
2876                        entry.insert(param.ident.span);
2877                    }
2878                }
2879
2880                if param.ident.name == kw::UnderscoreLifetime {
2881                    // To avoid emitting two similar errors,
2882                    // we need to check if the span is a raw underscore lifetime, see issue #143152
2883                    let is_raw_underscore_lifetime = self
2884                        .r
2885                        .tcx
2886                        .sess
2887                        .psess
2888                        .raw_identifier_spans
2889                        .iter()
2890                        .any(|span| span == param.span());
2891
2892                    self.r
2893                        .dcx()
2894                        .create_err(errors::UnderscoreLifetimeIsReserved { span: param.ident.span })
2895                        .emit_unless_delay(is_raw_underscore_lifetime);
2896                    // Record lifetime res, so lowering knows there is something fishy.
2897                    self.record_lifetime_param(param.id, LifetimeRes::Error);
2898                    continue;
2899                }
2900
2901                if param.ident.name == kw::StaticLifetime {
2902                    self.r.dcx().emit_err(errors::StaticLifetimeIsReserved {
2903                        span: param.ident.span,
2904                        lifetime: param.ident,
2905                    });
2906                    // Record lifetime res, so lowering knows there is something fishy.
2907                    self.record_lifetime_param(param.id, LifetimeRes::Error);
2908                    continue;
2909                }
2910
2911                let def_id = self.r.local_def_id(param.id);
2912
2913                // Plain insert (no renaming).
2914                let (rib, def_kind) = match param.kind {
2915                    GenericParamKind::Type { .. } => (&mut function_type_rib, DefKind::TyParam),
2916                    GenericParamKind::Const { .. } => {
2917                        (&mut function_value_rib, DefKind::ConstParam)
2918                    }
2919                    GenericParamKind::Lifetime => {
2920                        let res = LifetimeRes::Param { param: def_id, binder };
2921                        self.record_lifetime_param(param.id, res);
2922                        function_lifetime_rib.bindings.insert(ident, (param.id, res));
2923                        continue;
2924                    }
2925                };
2926
2927                let res = match kind {
2928                    RibKind::Item(..) | RibKind::AssocItem => {
2929                        Res::Def(def_kind, def_id.to_def_id())
2930                    }
2931                    RibKind::Normal => {
2932                        // FIXME(non_lifetime_binders): Stop special-casing
2933                        // const params to error out here.
2934                        if self.r.tcx.features().non_lifetime_binders()
2935                            && matches!(param.kind, GenericParamKind::Type { .. })
2936                        {
2937                            Res::Def(def_kind, def_id.to_def_id())
2938                        } else {
2939                            Res::Err
2940                        }
2941                    }
2942                    _ => span_bug!(param.ident.span, "Unexpected rib kind {:?}", kind),
2943                };
2944                self.r.record_partial_res(param.id, PartialRes::new(res));
2945                rib.bindings.insert(ident, res);
2946            }
2947        }
2948
2949        self.lifetime_ribs.push(function_lifetime_rib);
2950        self.ribs[ValueNS].push(function_value_rib);
2951        self.ribs[TypeNS].push(function_type_rib);
2952
2953        f(self);
2954
2955        self.ribs[TypeNS].pop();
2956        self.ribs[ValueNS].pop();
2957        let function_lifetime_rib = self.lifetime_ribs.pop().unwrap();
2958
2959        // Do not account for the parameters we just bound for function lifetime elision.
2960        if let Some(ref mut candidates) = self.lifetime_elision_candidates {
2961            for (_, res) in function_lifetime_rib.bindings.values() {
2962                candidates.retain(|(r, _)| r != res);
2963            }
2964        }
2965
2966        if let LifetimeBinderKind::FnPtrType
2967        | LifetimeBinderKind::WhereBound
2968        | LifetimeBinderKind::Function
2969        | LifetimeBinderKind::ImplBlock = generics_kind
2970        {
2971            self.maybe_report_lifetime_uses(generics_span, params)
2972        }
2973    }
2974
2975    fn with_label_rib(&mut self, kind: RibKind<'ra>, f: impl FnOnce(&mut Self)) {
2976        self.label_ribs.push(Rib::new(kind));
2977        f(self);
2978        self.label_ribs.pop();
2979    }
2980
2981    fn with_static_rib(&mut self, def_kind: DefKind, f: impl FnOnce(&mut Self)) {
2982        let kind = RibKind::Item(HasGenericParams::No, def_kind);
2983        self.with_rib(ValueNS, kind, |this| this.with_rib(TypeNS, kind, f))
2984    }
2985
2986    // HACK(min_const_generics, generic_const_exprs): We
2987    // want to keep allowing `[0; size_of::<*mut T>()]`
2988    // with a future compat lint for now. We do this by adding an
2989    // additional special case for repeat expressions.
2990    //
2991    // Note that we intentionally still forbid `[0; N + 1]` during
2992    // name resolution so that we don't extend the future
2993    // compat lint to new cases.
2994    #[instrument(level = "debug", skip(self, f))]
2995    fn with_constant_rib(
2996        &mut self,
2997        is_repeat: IsRepeatExpr,
2998        may_use_generics: ConstantHasGenerics,
2999        item: Option<(Ident, ConstantItemKind)>,
3000        f: impl FnOnce(&mut Self),
3001    ) {
3002        let f = |this: &mut Self| {
3003            this.with_rib(ValueNS, RibKind::ConstantItem(may_use_generics, item), |this| {
3004                this.with_rib(
3005                    TypeNS,
3006                    RibKind::ConstantItem(
3007                        may_use_generics.force_yes_if(is_repeat == IsRepeatExpr::Yes),
3008                        item,
3009                    ),
3010                    |this| {
3011                        this.with_label_rib(RibKind::ConstantItem(may_use_generics, item), f);
3012                    },
3013                )
3014            })
3015        };
3016
3017        if let ConstantHasGenerics::No(cause) = may_use_generics {
3018            self.with_lifetime_rib(LifetimeRibKind::ConcreteAnonConst(cause), f)
3019        } else {
3020            f(self)
3021        }
3022    }
3023
3024    fn with_current_self_type<T>(&mut self, self_type: &Ty, f: impl FnOnce(&mut Self) -> T) -> T {
3025        // Handle nested impls (inside fn bodies)
3026        let previous_value =
3027            replace(&mut self.diag_metadata.current_self_type, Some(self_type.clone()));
3028        let result = f(self);
3029        self.diag_metadata.current_self_type = previous_value;
3030        result
3031    }
3032
3033    fn with_current_self_item<T>(&mut self, self_item: &Item, f: impl FnOnce(&mut Self) -> T) -> T {
3034        let previous_value = replace(&mut self.diag_metadata.current_self_item, Some(self_item.id));
3035        let result = f(self);
3036        self.diag_metadata.current_self_item = previous_value;
3037        result
3038    }
3039
3040    /// When evaluating a `trait` use its associated types' idents for suggestions in E0412.
3041    fn resolve_trait_items(&mut self, trait_items: &'ast [P<AssocItem>]) {
3042        let trait_assoc_items =
3043            replace(&mut self.diag_metadata.current_trait_assoc_items, Some(trait_items));
3044
3045        let walk_assoc_item =
3046            |this: &mut Self, generics: &Generics, kind, item: &'ast AssocItem| {
3047                this.with_generic_param_rib(
3048                    &generics.params,
3049                    RibKind::AssocItem,
3050                    item.id,
3051                    kind,
3052                    generics.span,
3053                    |this| visit::walk_assoc_item(this, item, AssocCtxt::Trait),
3054                );
3055            };
3056
3057        for item in trait_items {
3058            self.resolve_doc_links(&item.attrs, MaybeExported::Ok(item.id));
3059            match &item.kind {
3060                AssocItemKind::Const(box ast::ConstItem {
3061                    generics,
3062                    ty,
3063                    expr,
3064                    define_opaque,
3065                    ..
3066                }) => {
3067                    self.with_generic_param_rib(
3068                        &generics.params,
3069                        RibKind::AssocItem,
3070                        item.id,
3071                        LifetimeBinderKind::ConstItem,
3072                        generics.span,
3073                        |this| {
3074                            this.with_lifetime_rib(
3075                                LifetimeRibKind::StaticIfNoLifetimeInScope {
3076                                    lint_id: item.id,
3077                                    emit_lint: false,
3078                                },
3079                                |this| {
3080                                    this.visit_generics(generics);
3081                                    this.visit_ty(ty);
3082
3083                                    // Only impose the restrictions of `ConstRibKind` for an
3084                                    // actual constant expression in a provided default.
3085                                    if let Some(expr) = expr {
3086                                        // We allow arbitrary const expressions inside of associated consts,
3087                                        // even if they are potentially not const evaluatable.
3088                                        //
3089                                        // Type parameters can already be used and as associated consts are
3090                                        // not used as part of the type system, this is far less surprising.
3091                                        this.resolve_const_body(expr, None);
3092                                    }
3093                                },
3094                            )
3095                        },
3096                    );
3097
3098                    self.resolve_define_opaques(define_opaque);
3099                }
3100                AssocItemKind::Fn(box Fn { generics, define_opaque, .. }) => {
3101                    walk_assoc_item(self, generics, LifetimeBinderKind::Function, item);
3102
3103                    self.resolve_define_opaques(define_opaque);
3104                }
3105                AssocItemKind::Delegation(delegation) => {
3106                    self.with_generic_param_rib(
3107                        &[],
3108                        RibKind::AssocItem,
3109                        item.id,
3110                        LifetimeBinderKind::Function,
3111                        delegation.path.segments.last().unwrap().ident.span,
3112                        |this| this.resolve_delegation(delegation),
3113                    );
3114                }
3115                AssocItemKind::Type(box TyAlias { generics, .. }) => self
3116                    .with_lifetime_rib(LifetimeRibKind::AnonymousReportError, |this| {
3117                        walk_assoc_item(this, generics, LifetimeBinderKind::Item, item)
3118                    }),
3119                AssocItemKind::MacCall(_) | AssocItemKind::DelegationMac(..) => {
3120                    panic!("unexpanded macro in resolve!")
3121                }
3122            };
3123        }
3124
3125        self.diag_metadata.current_trait_assoc_items = trait_assoc_items;
3126    }
3127
3128    /// This is called to resolve a trait reference from an `impl` (i.e., `impl Trait for Foo`).
3129    fn with_optional_trait_ref<T>(
3130        &mut self,
3131        opt_trait_ref: Option<&TraitRef>,
3132        self_type: &'ast Ty,
3133        f: impl FnOnce(&mut Self, Option<DefId>) -> T,
3134    ) -> T {
3135        let mut new_val = None;
3136        let mut new_id = None;
3137        if let Some(trait_ref) = opt_trait_ref {
3138            let path: Vec<_> = Segment::from_path(&trait_ref.path);
3139            self.diag_metadata.currently_processing_impl_trait =
3140                Some((trait_ref.clone(), self_type.clone()));
3141            let res = self.smart_resolve_path_fragment(
3142                &None,
3143                &path,
3144                PathSource::Trait(AliasPossibility::No),
3145                Finalize::new(trait_ref.ref_id, trait_ref.path.span),
3146                RecordPartialRes::Yes,
3147                None,
3148            );
3149            self.diag_metadata.currently_processing_impl_trait = None;
3150            if let Some(def_id) = res.expect_full_res().opt_def_id() {
3151                new_id = Some(def_id);
3152                new_val = Some((self.r.expect_module(def_id), trait_ref.clone()));
3153            }
3154        }
3155        let original_trait_ref = replace(&mut self.current_trait_ref, new_val);
3156        let result = f(self, new_id);
3157        self.current_trait_ref = original_trait_ref;
3158        result
3159    }
3160
3161    fn with_self_rib_ns(&mut self, ns: Namespace, self_res: Res, f: impl FnOnce(&mut Self)) {
3162        let mut self_type_rib = Rib::new(RibKind::Normal);
3163
3164        // Plain insert (no renaming, since types are not currently hygienic)
3165        self_type_rib.bindings.insert(Ident::with_dummy_span(kw::SelfUpper), self_res);
3166        self.ribs[ns].push(self_type_rib);
3167        f(self);
3168        self.ribs[ns].pop();
3169    }
3170
3171    fn with_self_rib(&mut self, self_res: Res, f: impl FnOnce(&mut Self)) {
3172        self.with_self_rib_ns(TypeNS, self_res, f)
3173    }
3174
3175    fn resolve_implementation(
3176        &mut self,
3177        attrs: &[ast::Attribute],
3178        generics: &'ast Generics,
3179        opt_trait_reference: &'ast Option<TraitRef>,
3180        self_type: &'ast Ty,
3181        item_id: NodeId,
3182        impl_items: &'ast [P<AssocItem>],
3183    ) {
3184        debug!("resolve_implementation");
3185        // If applicable, create a rib for the type parameters.
3186        self.with_generic_param_rib(
3187            &generics.params,
3188            RibKind::Item(HasGenericParams::Yes(generics.span), self.r.local_def_kind(item_id)),
3189            item_id,
3190            LifetimeBinderKind::ImplBlock,
3191            generics.span,
3192            |this| {
3193                // Dummy self type for better errors if `Self` is used in the trait path.
3194                this.with_self_rib(Res::SelfTyParam { trait_: LOCAL_CRATE.as_def_id() }, |this| {
3195                    this.with_lifetime_rib(
3196                        LifetimeRibKind::AnonymousCreateParameter {
3197                            binder: item_id,
3198                            report_in_path: true
3199                        },
3200                        |this| {
3201                            // Resolve the trait reference, if necessary.
3202                            this.with_optional_trait_ref(
3203                                opt_trait_reference.as_ref(),
3204                                self_type,
3205                                |this, trait_id| {
3206                                    this.resolve_doc_links(attrs, MaybeExported::Impl(trait_id));
3207
3208                                    let item_def_id = this.r.local_def_id(item_id);
3209
3210                                    // Register the trait definitions from here.
3211                                    if let Some(trait_id) = trait_id {
3212                                        this.r
3213                                            .trait_impls
3214                                            .entry(trait_id)
3215                                            .or_default()
3216                                            .push(item_def_id);
3217                                    }
3218
3219                                    let item_def_id = item_def_id.to_def_id();
3220                                    let res = Res::SelfTyAlias {
3221                                        alias_to: item_def_id,
3222                                        forbid_generic: false,
3223                                        is_trait_impl: trait_id.is_some()
3224                                    };
3225                                    this.with_self_rib(res, |this| {
3226                                        if let Some(trait_ref) = opt_trait_reference.as_ref() {
3227                                            // Resolve type arguments in the trait path.
3228                                            visit::walk_trait_ref(this, trait_ref);
3229                                        }
3230                                        // Resolve the self type.
3231                                        this.visit_ty(self_type);
3232                                        // Resolve the generic parameters.
3233                                        this.visit_generics(generics);
3234
3235                                        // Resolve the items within the impl.
3236                                        this.with_current_self_type(self_type, |this| {
3237                                            this.with_self_rib_ns(ValueNS, Res::SelfCtor(item_def_id), |this| {
3238                                                debug!("resolve_implementation with_self_rib_ns(ValueNS, ...)");
3239                                                let mut seen_trait_items = Default::default();
3240                                                for item in impl_items {
3241                                                    this.resolve_impl_item(&**item, &mut seen_trait_items, trait_id);
3242                                                }
3243                                            });
3244                                        });
3245                                    });
3246                                },
3247                            )
3248                        },
3249                    );
3250                });
3251            },
3252        );
3253    }
3254
3255    fn resolve_impl_item(
3256        &mut self,
3257        item: &'ast AssocItem,
3258        seen_trait_items: &mut FxHashMap<DefId, Span>,
3259        trait_id: Option<DefId>,
3260    ) {
3261        use crate::ResolutionError::*;
3262        self.resolve_doc_links(&item.attrs, MaybeExported::ImplItem(trait_id.ok_or(&item.vis)));
3263        match &item.kind {
3264            AssocItemKind::Const(box ast::ConstItem {
3265                ident,
3266                generics,
3267                ty,
3268                expr,
3269                define_opaque,
3270                ..
3271            }) => {
3272                debug!("resolve_implementation AssocItemKind::Const");
3273                self.with_generic_param_rib(
3274                    &generics.params,
3275                    RibKind::AssocItem,
3276                    item.id,
3277                    LifetimeBinderKind::ConstItem,
3278                    generics.span,
3279                    |this| {
3280                        this.with_lifetime_rib(
3281                            // Until these are a hard error, we need to create them within the
3282                            // correct binder, Otherwise the lifetimes of this assoc const think
3283                            // they are lifetimes of the trait.
3284                            LifetimeRibKind::AnonymousCreateParameter {
3285                                binder: item.id,
3286                                report_in_path: true,
3287                            },
3288                            |this| {
3289                                this.with_lifetime_rib(
3290                                    LifetimeRibKind::StaticIfNoLifetimeInScope {
3291                                        lint_id: item.id,
3292                                        // In impls, it's not a hard error yet due to backcompat.
3293                                        emit_lint: true,
3294                                    },
3295                                    |this| {
3296                                        // If this is a trait impl, ensure the const
3297                                        // exists in trait
3298                                        this.check_trait_item(
3299                                            item.id,
3300                                            *ident,
3301                                            &item.kind,
3302                                            ValueNS,
3303                                            item.span,
3304                                            seen_trait_items,
3305                                            |i, s, c| ConstNotMemberOfTrait(i, s, c),
3306                                        );
3307
3308                                        this.visit_generics(generics);
3309                                        this.visit_ty(ty);
3310                                        if let Some(expr) = expr {
3311                                            // We allow arbitrary const expressions inside of associated consts,
3312                                            // even if they are potentially not const evaluatable.
3313                                            //
3314                                            // Type parameters can already be used and as associated consts are
3315                                            // not used as part of the type system, this is far less surprising.
3316                                            this.resolve_const_body(expr, None);
3317                                        }
3318                                    },
3319                                )
3320                            },
3321                        );
3322                    },
3323                );
3324                self.resolve_define_opaques(define_opaque);
3325            }
3326            AssocItemKind::Fn(box Fn { ident, generics, define_opaque, .. }) => {
3327                debug!("resolve_implementation AssocItemKind::Fn");
3328                // We also need a new scope for the impl item type parameters.
3329                self.with_generic_param_rib(
3330                    &generics.params,
3331                    RibKind::AssocItem,
3332                    item.id,
3333                    LifetimeBinderKind::Function,
3334                    generics.span,
3335                    |this| {
3336                        // If this is a trait impl, ensure the method
3337                        // exists in trait
3338                        this.check_trait_item(
3339                            item.id,
3340                            *ident,
3341                            &item.kind,
3342                            ValueNS,
3343                            item.span,
3344                            seen_trait_items,
3345                            |i, s, c| MethodNotMemberOfTrait(i, s, c),
3346                        );
3347
3348                        visit::walk_assoc_item(this, item, AssocCtxt::Impl { of_trait: true })
3349                    },
3350                );
3351
3352                self.resolve_define_opaques(define_opaque);
3353            }
3354            AssocItemKind::Type(box TyAlias { ident, generics, .. }) => {
3355                self.diag_metadata.in_non_gat_assoc_type = Some(generics.params.is_empty());
3356                debug!("resolve_implementation AssocItemKind::Type");
3357                // We also need a new scope for the impl item type parameters.
3358                self.with_generic_param_rib(
3359                    &generics.params,
3360                    RibKind::AssocItem,
3361                    item.id,
3362                    LifetimeBinderKind::Item,
3363                    generics.span,
3364                    |this| {
3365                        this.with_lifetime_rib(LifetimeRibKind::AnonymousReportError, |this| {
3366                            // If this is a trait impl, ensure the type
3367                            // exists in trait
3368                            this.check_trait_item(
3369                                item.id,
3370                                *ident,
3371                                &item.kind,
3372                                TypeNS,
3373                                item.span,
3374                                seen_trait_items,
3375                                |i, s, c| TypeNotMemberOfTrait(i, s, c),
3376                            );
3377
3378                            visit::walk_assoc_item(this, item, AssocCtxt::Impl { of_trait: true })
3379                        });
3380                    },
3381                );
3382                self.diag_metadata.in_non_gat_assoc_type = None;
3383            }
3384            AssocItemKind::Delegation(box delegation) => {
3385                debug!("resolve_implementation AssocItemKind::Delegation");
3386                self.with_generic_param_rib(
3387                    &[],
3388                    RibKind::AssocItem,
3389                    item.id,
3390                    LifetimeBinderKind::Function,
3391                    delegation.path.segments.last().unwrap().ident.span,
3392                    |this| {
3393                        this.check_trait_item(
3394                            item.id,
3395                            delegation.ident,
3396                            &item.kind,
3397                            ValueNS,
3398                            item.span,
3399                            seen_trait_items,
3400                            |i, s, c| MethodNotMemberOfTrait(i, s, c),
3401                        );
3402
3403                        this.resolve_delegation(delegation)
3404                    },
3405                );
3406            }
3407            AssocItemKind::MacCall(_) | AssocItemKind::DelegationMac(..) => {
3408                panic!("unexpanded macro in resolve!")
3409            }
3410        }
3411    }
3412
3413    fn check_trait_item<F>(
3414        &mut self,
3415        id: NodeId,
3416        mut ident: Ident,
3417        kind: &AssocItemKind,
3418        ns: Namespace,
3419        span: Span,
3420        seen_trait_items: &mut FxHashMap<DefId, Span>,
3421        err: F,
3422    ) where
3423        F: FnOnce(Ident, String, Option<Symbol>) -> ResolutionError<'ra>,
3424    {
3425        // If there is a TraitRef in scope for an impl, then the method must be in the trait.
3426        let Some((module, _)) = self.current_trait_ref else {
3427            return;
3428        };
3429        ident.span.normalize_to_macros_2_0_and_adjust(module.expansion);
3430        let key = BindingKey::new(ident, ns);
3431        let mut binding = self.r.resolution(module, key).and_then(|r| r.best_binding());
3432        debug!(?binding);
3433        if binding.is_none() {
3434            // We could not find the trait item in the correct namespace.
3435            // Check the other namespace to report an error.
3436            let ns = match ns {
3437                ValueNS => TypeNS,
3438                TypeNS => ValueNS,
3439                _ => ns,
3440            };
3441            let key = BindingKey::new(ident, ns);
3442            binding = self.r.resolution(module, key).and_then(|r| r.best_binding());
3443            debug!(?binding);
3444        }
3445
3446        let feed_visibility = |this: &mut Self, def_id| {
3447            let vis = this.r.tcx.visibility(def_id);
3448            let vis = if vis.is_visible_locally() {
3449                vis.expect_local()
3450            } else {
3451                this.r.dcx().span_delayed_bug(
3452                    span,
3453                    "error should be emitted when an unexpected trait item is used",
3454                );
3455                Visibility::Public
3456            };
3457            this.r.feed_visibility(this.r.feed(id), vis);
3458        };
3459
3460        let Some(binding) = binding else {
3461            // We could not find the method: report an error.
3462            let candidate = self.find_similarly_named_assoc_item(ident.name, kind);
3463            let path = &self.current_trait_ref.as_ref().unwrap().1.path;
3464            let path_names = path_names_to_string(path);
3465            self.report_error(span, err(ident, path_names, candidate));
3466            feed_visibility(self, module.def_id());
3467            return;
3468        };
3469
3470        let res = binding.res();
3471        let Res::Def(def_kind, id_in_trait) = res else { bug!() };
3472        feed_visibility(self, id_in_trait);
3473
3474        match seen_trait_items.entry(id_in_trait) {
3475            Entry::Occupied(entry) => {
3476                self.report_error(
3477                    span,
3478                    ResolutionError::TraitImplDuplicate {
3479                        name: ident,
3480                        old_span: *entry.get(),
3481                        trait_item_span: binding.span,
3482                    },
3483                );
3484                return;
3485            }
3486            Entry::Vacant(entry) => {
3487                entry.insert(span);
3488            }
3489        };
3490
3491        match (def_kind, kind) {
3492            (DefKind::AssocTy, AssocItemKind::Type(..))
3493            | (DefKind::AssocFn, AssocItemKind::Fn(..))
3494            | (DefKind::AssocConst, AssocItemKind::Const(..))
3495            | (DefKind::AssocFn, AssocItemKind::Delegation(..)) => {
3496                self.r.record_partial_res(id, PartialRes::new(res));
3497                return;
3498            }
3499            _ => {}
3500        }
3501
3502        // The method kind does not correspond to what appeared in the trait, report.
3503        let path = &self.current_trait_ref.as_ref().unwrap().1.path;
3504        let (code, kind) = match kind {
3505            AssocItemKind::Const(..) => (E0323, "const"),
3506            AssocItemKind::Fn(..) => (E0324, "method"),
3507            AssocItemKind::Type(..) => (E0325, "type"),
3508            AssocItemKind::Delegation(..) => (E0324, "method"),
3509            AssocItemKind::MacCall(..) | AssocItemKind::DelegationMac(..) => {
3510                span_bug!(span, "unexpanded macro")
3511            }
3512        };
3513        let trait_path = path_names_to_string(path);
3514        self.report_error(
3515            span,
3516            ResolutionError::TraitImplMismatch {
3517                name: ident,
3518                kind,
3519                code,
3520                trait_path,
3521                trait_item_span: binding.span,
3522            },
3523        );
3524    }
3525
3526    fn resolve_const_body(&mut self, expr: &'ast Expr, item: Option<(Ident, ConstantItemKind)>) {
3527        self.with_lifetime_rib(LifetimeRibKind::Elided(LifetimeRes::Infer), |this| {
3528            this.with_constant_rib(IsRepeatExpr::No, ConstantHasGenerics::Yes, item, |this| {
3529                this.visit_expr(expr)
3530            });
3531        })
3532    }
3533
3534    fn resolve_delegation(&mut self, delegation: &'ast Delegation) {
3535        self.smart_resolve_path(
3536            delegation.id,
3537            &delegation.qself,
3538            &delegation.path,
3539            PathSource::Delegation,
3540        );
3541        if let Some(qself) = &delegation.qself {
3542            self.visit_ty(&qself.ty);
3543        }
3544        self.visit_path(&delegation.path);
3545        let Some(body) = &delegation.body else { return };
3546        self.with_rib(ValueNS, RibKind::FnOrCoroutine, |this| {
3547            let span = delegation.path.segments.last().unwrap().ident.span;
3548            let ident = Ident::new(kw::SelfLower, span.normalize_to_macro_rules());
3549            let res = Res::Local(delegation.id);
3550            this.innermost_rib_bindings(ValueNS).insert(ident, res);
3551            this.visit_block(body);
3552        });
3553    }
3554
3555    fn resolve_params(&mut self, params: &'ast [Param]) {
3556        let mut bindings = smallvec![(PatBoundCtx::Product, Default::default())];
3557        self.with_lifetime_rib(LifetimeRibKind::Elided(LifetimeRes::Infer), |this| {
3558            for Param { pat, .. } in params {
3559                this.resolve_pattern(pat, PatternSource::FnParam, &mut bindings);
3560            }
3561            this.apply_pattern_bindings(bindings);
3562        });
3563        for Param { ty, .. } in params {
3564            self.visit_ty(ty);
3565        }
3566    }
3567
3568    fn resolve_local(&mut self, local: &'ast Local) {
3569        debug!("resolving local ({:?})", local);
3570        // Resolve the type.
3571        visit_opt!(self, visit_ty, &local.ty);
3572
3573        // Resolve the initializer.
3574        if let Some((init, els)) = local.kind.init_else_opt() {
3575            self.visit_expr(init);
3576
3577            // Resolve the `else` block
3578            if let Some(els) = els {
3579                self.visit_block(els);
3580            }
3581        }
3582
3583        // Resolve the pattern.
3584        self.resolve_pattern_top(&local.pat, PatternSource::Let);
3585    }
3586
3587    /// Build a map from pattern identifiers to binding-info's, and check the bindings are
3588    /// consistent when encountering or-patterns and never patterns.
3589    /// This is done hygienically: this could arise for a macro that expands into an or-pattern
3590    /// where one 'x' was from the user and one 'x' came from the macro.
3591    ///
3592    /// A never pattern by definition indicates an unreachable case. For example, matching on
3593    /// `Result<T, &!>` could look like:
3594    /// ```rust
3595    /// # #![feature(never_type)]
3596    /// # #![feature(never_patterns)]
3597    /// # fn bar(_x: u32) {}
3598    /// let foo: Result<u32, &!> = Ok(0);
3599    /// match foo {
3600    ///     Ok(x) => bar(x),
3601    ///     Err(&!),
3602    /// }
3603    /// ```
3604    /// This extends to product types: `(x, !)` is likewise unreachable. So it doesn't make sense to
3605    /// have a binding here, and we tell the user to use `_` instead.
3606    fn compute_and_check_binding_map(
3607        &mut self,
3608        pat: &Pat,
3609    ) -> Result<FxIndexMap<Ident, BindingInfo>, IsNeverPattern> {
3610        let mut binding_map = FxIndexMap::default();
3611        let mut is_never_pat = false;
3612
3613        pat.walk(&mut |pat| {
3614            match pat.kind {
3615                PatKind::Ident(annotation, ident, ref sub_pat)
3616                    if sub_pat.is_some() || self.is_base_res_local(pat.id) =>
3617                {
3618                    binding_map.insert(ident, BindingInfo { span: ident.span, annotation });
3619                }
3620                PatKind::Or(ref ps) => {
3621                    // Check the consistency of this or-pattern and
3622                    // then add all bindings to the larger map.
3623                    match self.compute_and_check_or_pat_binding_map(ps) {
3624                        Ok(bm) => binding_map.extend(bm),
3625                        Err(IsNeverPattern) => is_never_pat = true,
3626                    }
3627                    return false;
3628                }
3629                PatKind::Never => is_never_pat = true,
3630                _ => {}
3631            }
3632
3633            true
3634        });
3635
3636        if is_never_pat {
3637            for (_, binding) in binding_map {
3638                self.report_error(binding.span, ResolutionError::BindingInNeverPattern);
3639            }
3640            Err(IsNeverPattern)
3641        } else {
3642            Ok(binding_map)
3643        }
3644    }
3645
3646    fn is_base_res_local(&self, nid: NodeId) -> bool {
3647        matches!(
3648            self.r.partial_res_map.get(&nid).map(|res| res.expect_full_res()),
3649            Some(Res::Local(..))
3650        )
3651    }
3652
3653    /// Compute the binding map for an or-pattern. Checks that all of the arms in the or-pattern
3654    /// have exactly the same set of bindings, with the same binding modes for each.
3655    /// Returns the computed binding map and a boolean indicating whether the pattern is a never
3656    /// pattern.
3657    ///
3658    /// A never pattern by definition indicates an unreachable case. For example, destructuring a
3659    /// `Result<T, &!>` could look like:
3660    /// ```rust
3661    /// # #![feature(never_type)]
3662    /// # #![feature(never_patterns)]
3663    /// # fn foo() -> Result<bool, &'static !> { Ok(true) }
3664    /// let (Ok(x) | Err(&!)) = foo();
3665    /// # let _ = x;
3666    /// ```
3667    /// Because the `Err(&!)` branch is never reached, it does not need to have the same bindings as
3668    /// the other branches of the or-pattern. So we must ignore never pattern when checking the
3669    /// bindings of an or-pattern.
3670    /// Moreover, if all the subpatterns are never patterns (e.g. `Ok(!) | Err(!)`), then the
3671    /// pattern as a whole counts as a never pattern (since it's definitionallly unreachable).
3672    fn compute_and_check_or_pat_binding_map(
3673        &mut self,
3674        pats: &[P<Pat>],
3675    ) -> Result<FxIndexMap<Ident, BindingInfo>, IsNeverPattern> {
3676        let mut missing_vars = FxIndexMap::default();
3677        let mut inconsistent_vars = FxIndexMap::default();
3678
3679        // 1) Compute the binding maps of all arms; we must ignore never patterns here.
3680        let not_never_pats = pats
3681            .iter()
3682            .filter_map(|pat| {
3683                let binding_map = self.compute_and_check_binding_map(pat).ok()?;
3684                Some((binding_map, pat))
3685            })
3686            .collect::<Vec<_>>();
3687
3688        // 2) Record any missing bindings or binding mode inconsistencies.
3689        for (map_outer, pat_outer) in not_never_pats.iter() {
3690            // Check against all arms except for the same pattern which is always self-consistent.
3691            let inners = not_never_pats
3692                .iter()
3693                .filter(|(_, pat)| pat.id != pat_outer.id)
3694                .flat_map(|(map, _)| map);
3695
3696            for (&name, binding_inner) in inners {
3697                match map_outer.get(&name) {
3698                    None => {
3699                        // The inner binding is missing in the outer.
3700                        let binding_error =
3701                            missing_vars.entry(name).or_insert_with(|| BindingError {
3702                                name,
3703                                origin: BTreeSet::new(),
3704                                target: BTreeSet::new(),
3705                                could_be_path: name.as_str().starts_with(char::is_uppercase),
3706                            });
3707                        binding_error.origin.insert(binding_inner.span);
3708                        binding_error.target.insert(pat_outer.span);
3709                    }
3710                    Some(binding_outer) => {
3711                        if binding_outer.annotation != binding_inner.annotation {
3712                            // The binding modes in the outer and inner bindings differ.
3713                            inconsistent_vars
3714                                .entry(name)
3715                                .or_insert((binding_inner.span, binding_outer.span));
3716                        }
3717                    }
3718                }
3719            }
3720        }
3721
3722        // 3) Report all missing variables we found.
3723        for (name, mut v) in missing_vars {
3724            if inconsistent_vars.contains_key(&name) {
3725                v.could_be_path = false;
3726            }
3727            self.report_error(
3728                *v.origin.iter().next().unwrap(),
3729                ResolutionError::VariableNotBoundInPattern(v, self.parent_scope),
3730            );
3731        }
3732
3733        // 4) Report all inconsistencies in binding modes we found.
3734        for (name, v) in inconsistent_vars {
3735            self.report_error(v.0, ResolutionError::VariableBoundWithDifferentMode(name, v.1));
3736        }
3737
3738        // 5) Bubble up the final binding map.
3739        if not_never_pats.is_empty() {
3740            // All the patterns are never patterns, so the whole or-pattern is one too.
3741            Err(IsNeverPattern)
3742        } else {
3743            let mut binding_map = FxIndexMap::default();
3744            for (bm, _) in not_never_pats {
3745                binding_map.extend(bm);
3746            }
3747            Ok(binding_map)
3748        }
3749    }
3750
3751    /// Check the consistency of bindings wrt or-patterns and never patterns.
3752    fn check_consistent_bindings(&mut self, pat: &'ast Pat) {
3753        let mut is_or_or_never = false;
3754        pat.walk(&mut |pat| match pat.kind {
3755            PatKind::Or(..) | PatKind::Never => {
3756                is_or_or_never = true;
3757                false
3758            }
3759            _ => true,
3760        });
3761        if is_or_or_never {
3762            let _ = self.compute_and_check_binding_map(pat);
3763        }
3764    }
3765
3766    fn resolve_arm(&mut self, arm: &'ast Arm) {
3767        self.with_rib(ValueNS, RibKind::Normal, |this| {
3768            this.resolve_pattern_top(&arm.pat, PatternSource::Match);
3769            visit_opt!(this, visit_expr, &arm.guard);
3770            visit_opt!(this, visit_expr, &arm.body);
3771        });
3772    }
3773
3774    /// Arising from `source`, resolve a top level pattern.
3775    fn resolve_pattern_top(&mut self, pat: &'ast Pat, pat_src: PatternSource) {
3776        let mut bindings = smallvec![(PatBoundCtx::Product, Default::default())];
3777        self.resolve_pattern(pat, pat_src, &mut bindings);
3778        self.apply_pattern_bindings(bindings);
3779    }
3780
3781    /// Apply the bindings from a pattern to the innermost rib of the current scope.
3782    fn apply_pattern_bindings(&mut self, mut pat_bindings: PatternBindings) {
3783        let rib_bindings = self.innermost_rib_bindings(ValueNS);
3784        let Some((_, pat_bindings)) = pat_bindings.pop() else {
3785            bug!("tried applying nonexistent bindings from pattern");
3786        };
3787
3788        if rib_bindings.is_empty() {
3789            // Often, such as for match arms, the bindings are introduced into a new rib.
3790            // In this case, we can move the bindings over directly.
3791            *rib_bindings = pat_bindings;
3792        } else {
3793            rib_bindings.extend(pat_bindings);
3794        }
3795    }
3796
3797    /// Resolve bindings in a pattern. `apply_pattern_bindings` must be called after to introduce
3798    /// the bindings into scope.
3799    fn resolve_pattern(
3800        &mut self,
3801        pat: &'ast Pat,
3802        pat_src: PatternSource,
3803        bindings: &mut PatternBindings,
3804    ) {
3805        // We walk the pattern before declaring the pattern's inner bindings,
3806        // so that we avoid resolving a literal expression to a binding defined
3807        // by the pattern.
3808        // NB: `Self::visit_pat` must be used rather than `visit::walk_pat` to avoid resolving guard
3809        // patterns' guard expressions multiple times (#141265).
3810        self.visit_pat(pat);
3811        self.resolve_pattern_inner(pat, pat_src, bindings);
3812        // This has to happen *after* we determine which pat_idents are variants:
3813        self.check_consistent_bindings(pat);
3814    }
3815
3816    /// Resolve bindings in a pattern. This is a helper to `resolve_pattern`.
3817    ///
3818    /// ### `bindings`
3819    ///
3820    /// A stack of sets of bindings accumulated.
3821    ///
3822    /// In each set, `PatBoundCtx::Product` denotes that a found binding in it should
3823    /// be interpreted as re-binding an already bound binding. This results in an error.
3824    /// Meanwhile, `PatBound::Or` denotes that a found binding in the set should result
3825    /// in reusing this binding rather than creating a fresh one.
3826    ///
3827    /// When called at the top level, the stack must have a single element
3828    /// with `PatBound::Product`. Otherwise, pushing to the stack happens as
3829    /// or-patterns (`p_0 | ... | p_n`) are encountered and the context needs
3830    /// to be switched to `PatBoundCtx::Or` and then `PatBoundCtx::Product` for each `p_i`.
3831    /// When each `p_i` has been dealt with, the top set is merged with its parent.
3832    /// When a whole or-pattern has been dealt with, the thing happens.
3833    ///
3834    /// See the implementation and `fresh_binding` for more details.
3835    #[tracing::instrument(skip(self, bindings), level = "debug")]
3836    fn resolve_pattern_inner(
3837        &mut self,
3838        pat: &'ast Pat,
3839        pat_src: PatternSource,
3840        bindings: &mut PatternBindings,
3841    ) {
3842        // Visit all direct subpatterns of this pattern.
3843        pat.walk(&mut |pat| {
3844            match pat.kind {
3845                PatKind::Ident(bmode, ident, ref sub) => {
3846                    // First try to resolve the identifier as some existing entity,
3847                    // then fall back to a fresh binding.
3848                    let has_sub = sub.is_some();
3849                    let res = self
3850                        .try_resolve_as_non_binding(pat_src, bmode, ident, has_sub)
3851                        .unwrap_or_else(|| self.fresh_binding(ident, pat.id, pat_src, bindings));
3852                    self.r.record_partial_res(pat.id, PartialRes::new(res));
3853                    self.r.record_pat_span(pat.id, pat.span);
3854                }
3855                PatKind::TupleStruct(ref qself, ref path, ref sub_patterns) => {
3856                    self.smart_resolve_path(
3857                        pat.id,
3858                        qself,
3859                        path,
3860                        PathSource::TupleStruct(
3861                            pat.span,
3862                            self.r.arenas.alloc_pattern_spans(sub_patterns.iter().map(|p| p.span)),
3863                        ),
3864                    );
3865                }
3866                PatKind::Path(ref qself, ref path) => {
3867                    self.smart_resolve_path(pat.id, qself, path, PathSource::Pat);
3868                }
3869                PatKind::Struct(ref qself, ref path, ref _fields, ref rest) => {
3870                    self.smart_resolve_path(pat.id, qself, path, PathSource::Struct);
3871                    self.record_patterns_with_skipped_bindings(pat, rest);
3872                }
3873                PatKind::Or(ref ps) => {
3874                    // Add a new set of bindings to the stack. `Or` here records that when a
3875                    // binding already exists in this set, it should not result in an error because
3876                    // `V1(a) | V2(a)` must be allowed and are checked for consistency later.
3877                    bindings.push((PatBoundCtx::Or, Default::default()));
3878                    for p in ps {
3879                        // Now we need to switch back to a product context so that each
3880                        // part of the or-pattern internally rejects already bound names.
3881                        // For example, `V1(a) | V2(a, a)` and `V1(a, a) | V2(a)` are bad.
3882                        bindings.push((PatBoundCtx::Product, Default::default()));
3883                        self.resolve_pattern_inner(p, pat_src, bindings);
3884                        // Move up the non-overlapping bindings to the or-pattern.
3885                        // Existing bindings just get "merged".
3886                        let collected = bindings.pop().unwrap().1;
3887                        bindings.last_mut().unwrap().1.extend(collected);
3888                    }
3889                    // This or-pattern itself can itself be part of a product,
3890                    // e.g. `(V1(a) | V2(a), a)` or `(a, V1(a) | V2(a))`.
3891                    // Both cases bind `a` again in a product pattern and must be rejected.
3892                    let collected = bindings.pop().unwrap().1;
3893                    bindings.last_mut().unwrap().1.extend(collected);
3894
3895                    // Prevent visiting `ps` as we've already done so above.
3896                    return false;
3897                }
3898                PatKind::Guard(ref subpat, ref guard) => {
3899                    // Add a new set of bindings to the stack to collect bindings in `subpat`.
3900                    bindings.push((PatBoundCtx::Product, Default::default()));
3901                    // Resolving `subpat` adds bindings onto the newly-pushed context. After, the
3902                    // total number of contexts on the stack should be the same as before.
3903                    let binding_ctx_stack_len = bindings.len();
3904                    self.resolve_pattern_inner(subpat, pat_src, bindings);
3905                    assert_eq!(bindings.len(), binding_ctx_stack_len);
3906                    // These bindings, but none from the surrounding pattern, are visible in the
3907                    // guard; put them in scope and resolve `guard`.
3908                    let subpat_bindings = bindings.pop().unwrap().1;
3909                    self.with_rib(ValueNS, RibKind::Normal, |this| {
3910                        *this.innermost_rib_bindings(ValueNS) = subpat_bindings.clone();
3911                        this.resolve_expr(guard, None);
3912                    });
3913                    // Propagate the subpattern's bindings upwards.
3914                    // FIXME(guard_patterns): For `if let` guards, we'll also need to get the
3915                    // bindings introduced by the guard from its rib and propagate them upwards.
3916                    // This will require checking the identifiers for overlaps with `bindings`, like
3917                    // what `fresh_binding` does (ideally sharing its logic). To keep them separate
3918                    // from `subpat_bindings`, we can introduce a fresh rib for the guard.
3919                    bindings.last_mut().unwrap().1.extend(subpat_bindings);
3920                    // Prevent visiting `subpat` as we've already done so above.
3921                    return false;
3922                }
3923                _ => {}
3924            }
3925            true
3926        });
3927    }
3928
3929    fn record_patterns_with_skipped_bindings(&mut self, pat: &Pat, rest: &ast::PatFieldsRest) {
3930        match rest {
3931            ast::PatFieldsRest::Rest | ast::PatFieldsRest::Recovered(_) => {
3932                // Record that the pattern doesn't introduce all the bindings it could.
3933                if let Some(partial_res) = self.r.partial_res_map.get(&pat.id)
3934                    && let Some(res) = partial_res.full_res()
3935                    && let Some(def_id) = res.opt_def_id()
3936                {
3937                    self.ribs[ValueNS]
3938                        .last_mut()
3939                        .unwrap()
3940                        .patterns_with_skipped_bindings
3941                        .entry(def_id)
3942                        .or_default()
3943                        .push((
3944                            pat.span,
3945                            match rest {
3946                                ast::PatFieldsRest::Recovered(guar) => Err(*guar),
3947                                _ => Ok(()),
3948                            },
3949                        ));
3950                }
3951            }
3952            ast::PatFieldsRest::None => {}
3953        }
3954    }
3955
3956    fn fresh_binding(
3957        &mut self,
3958        ident: Ident,
3959        pat_id: NodeId,
3960        pat_src: PatternSource,
3961        bindings: &mut PatternBindings,
3962    ) -> Res {
3963        // Add the binding to the bindings map, if it doesn't already exist.
3964        // (We must not add it if it's in the bindings map because that breaks the assumptions
3965        // later passes make about or-patterns.)
3966        let ident = ident.normalize_to_macro_rules();
3967
3968        // Already bound in a product pattern? e.g. `(a, a)` which is not allowed.
3969        let already_bound_and = bindings
3970            .iter()
3971            .any(|(ctx, map)| *ctx == PatBoundCtx::Product && map.contains_key(&ident));
3972        if already_bound_and {
3973            // Overlap in a product pattern somewhere; report an error.
3974            use ResolutionError::*;
3975            let error = match pat_src {
3976                // `fn f(a: u8, a: u8)`:
3977                PatternSource::FnParam => IdentifierBoundMoreThanOnceInParameterList,
3978                // `Variant(a, a)`:
3979                _ => IdentifierBoundMoreThanOnceInSamePattern,
3980            };
3981            self.report_error(ident.span, error(ident));
3982        }
3983
3984        // Already bound in an or-pattern? e.g. `V1(a) | V2(a)`.
3985        // This is *required* for consistency which is checked later.
3986        let already_bound_or = bindings
3987            .iter()
3988            .find_map(|(ctx, map)| if *ctx == PatBoundCtx::Or { map.get(&ident) } else { None });
3989        let res = if let Some(&res) = already_bound_or {
3990            // `Variant1(a) | Variant2(a)`, ok
3991            // Reuse definition from the first `a`.
3992            res
3993        } else {
3994            // A completely fresh binding is added to the map.
3995            Res::Local(pat_id)
3996        };
3997
3998        // Record as bound.
3999        bindings.last_mut().unwrap().1.insert(ident, res);
4000        res
4001    }
4002
4003    fn innermost_rib_bindings(&mut self, ns: Namespace) -> &mut FxIndexMap<Ident, Res> {
4004        &mut self.ribs[ns].last_mut().unwrap().bindings
4005    }
4006
4007    fn try_resolve_as_non_binding(
4008        &mut self,
4009        pat_src: PatternSource,
4010        ann: BindingMode,
4011        ident: Ident,
4012        has_sub: bool,
4013    ) -> Option<Res> {
4014        // An immutable (no `mut`) by-value (no `ref`) binding pattern without
4015        // a sub pattern (no `@ $pat`) is syntactically ambiguous as it could
4016        // also be interpreted as a path to e.g. a constant, variant, etc.
4017        let is_syntactic_ambiguity = !has_sub && ann == BindingMode::NONE;
4018
4019        let ls_binding = self.maybe_resolve_ident_in_lexical_scope(ident, ValueNS)?;
4020        let (res, binding) = match ls_binding {
4021            LexicalScopeBinding::Item(binding)
4022                if is_syntactic_ambiguity && binding.is_ambiguity_recursive() =>
4023            {
4024                // For ambiguous bindings we don't know all their definitions and cannot check
4025                // whether they can be shadowed by fresh bindings or not, so force an error.
4026                // issues/33118#issuecomment-233962221 (see below) still applies here,
4027                // but we have to ignore it for backward compatibility.
4028                self.r.record_use(ident, binding, Used::Other);
4029                return None;
4030            }
4031            LexicalScopeBinding::Item(binding) => (binding.res(), Some(binding)),
4032            LexicalScopeBinding::Res(res) => (res, None),
4033        };
4034
4035        match res {
4036            Res::SelfCtor(_) // See #70549.
4037            | Res::Def(
4038                DefKind::Ctor(_, CtorKind::Const) | DefKind::Const | DefKind::AssocConst | DefKind::ConstParam,
4039                _,
4040            ) if is_syntactic_ambiguity => {
4041                // Disambiguate in favor of a unit struct/variant or constant pattern.
4042                if let Some(binding) = binding {
4043                    self.r.record_use(ident, binding, Used::Other);
4044                }
4045                Some(res)
4046            }
4047            Res::Def(DefKind::Ctor(..) | DefKind::Const | DefKind::AssocConst | DefKind::Static { .. }, _) => {
4048                // This is unambiguously a fresh binding, either syntactically
4049                // (e.g., `IDENT @ PAT` or `ref IDENT`) or because `IDENT` resolves
4050                // to something unusable as a pattern (e.g., constructor function),
4051                // but we still conservatively report an error, see
4052                // issues/33118#issuecomment-233962221 for one reason why.
4053                let binding = binding.expect("no binding for a ctor or static");
4054                self.report_error(
4055                    ident.span,
4056                    ResolutionError::BindingShadowsSomethingUnacceptable {
4057                        shadowing_binding: pat_src,
4058                        name: ident.name,
4059                        participle: if binding.is_import() { "imported" } else { "defined" },
4060                        article: binding.res().article(),
4061                        shadowed_binding: binding.res(),
4062                        shadowed_binding_span: binding.span,
4063                    },
4064                );
4065                None
4066            }
4067            Res::Def(DefKind::ConstParam, def_id) => {
4068                // Same as for DefKind::Const above, but here, `binding` is `None`, so we
4069                // have to construct the error differently
4070                self.report_error(
4071                    ident.span,
4072                    ResolutionError::BindingShadowsSomethingUnacceptable {
4073                        shadowing_binding: pat_src,
4074                        name: ident.name,
4075                        participle: "defined",
4076                        article: res.article(),
4077                        shadowed_binding: res,
4078                        shadowed_binding_span: self.r.def_span(def_id),
4079                    }
4080                );
4081                None
4082            }
4083            Res::Def(DefKind::Fn | DefKind::AssocFn, _) | Res::Local(..) | Res::Err => {
4084                // These entities are explicitly allowed to be shadowed by fresh bindings.
4085                None
4086            }
4087            Res::SelfCtor(_) => {
4088                // We resolve `Self` in pattern position as an ident sometimes during recovery,
4089                // so delay a bug instead of ICEing.
4090                self.r.dcx().span_delayed_bug(
4091                    ident.span,
4092                    "unexpected `SelfCtor` in pattern, expected identifier"
4093                );
4094                None
4095            }
4096            _ => span_bug!(
4097                ident.span,
4098                "unexpected resolution for an identifier in pattern: {:?}",
4099                res,
4100            ),
4101        }
4102    }
4103
4104    // High-level and context dependent path resolution routine.
4105    // Resolves the path and records the resolution into definition map.
4106    // If resolution fails tries several techniques to find likely
4107    // resolution candidates, suggest imports or other help, and report
4108    // errors in user friendly way.
4109    fn smart_resolve_path(
4110        &mut self,
4111        id: NodeId,
4112        qself: &Option<P<QSelf>>,
4113        path: &Path,
4114        source: PathSource<'_, 'ast, '_>,
4115    ) {
4116        self.smart_resolve_path_fragment(
4117            qself,
4118            &Segment::from_path(path),
4119            source,
4120            Finalize::new(id, path.span),
4121            RecordPartialRes::Yes,
4122            None,
4123        );
4124    }
4125
4126    #[instrument(level = "debug", skip(self))]
4127    fn smart_resolve_path_fragment(
4128        &mut self,
4129        qself: &Option<P<QSelf>>,
4130        path: &[Segment],
4131        source: PathSource<'_, 'ast, '_>,
4132        finalize: Finalize,
4133        record_partial_res: RecordPartialRes,
4134        parent_qself: Option<&QSelf>,
4135    ) -> PartialRes {
4136        let ns = source.namespace();
4137
4138        let Finalize { node_id, path_span, .. } = finalize;
4139        let report_errors = |this: &mut Self, res: Option<Res>| {
4140            if this.should_report_errs() {
4141                let (err, candidates) = this.smart_resolve_report_errors(
4142                    path,
4143                    None,
4144                    path_span,
4145                    source,
4146                    res,
4147                    parent_qself,
4148                );
4149
4150                let def_id = this.parent_scope.module.nearest_parent_mod();
4151                let instead = res.is_some();
4152                let suggestion = if let Some((start, end)) = this.diag_metadata.in_range
4153                    && path[0].ident.span.lo() == end.span.lo()
4154                    && !matches!(start.kind, ExprKind::Lit(_))
4155                {
4156                    let mut sugg = ".";
4157                    let mut span = start.span.between(end.span);
4158                    if span.lo() + BytePos(2) == span.hi() {
4159                        // There's no space between the start, the range op and the end, suggest
4160                        // removal which will look better.
4161                        span = span.with_lo(span.lo() + BytePos(1));
4162                        sugg = "";
4163                    }
4164                    Some((
4165                        span,
4166                        "you might have meant to write `.` instead of `..`",
4167                        sugg.to_string(),
4168                        Applicability::MaybeIncorrect,
4169                    ))
4170                } else if res.is_none()
4171                    && let PathSource::Type
4172                    | PathSource::Expr(_)
4173                    | PathSource::PreciseCapturingArg(..) = source
4174                {
4175                    this.suggest_adding_generic_parameter(path, source)
4176                } else {
4177                    None
4178                };
4179
4180                let ue = UseError {
4181                    err,
4182                    candidates,
4183                    def_id,
4184                    instead,
4185                    suggestion,
4186                    path: path.into(),
4187                    is_call: source.is_call(),
4188                };
4189
4190                this.r.use_injections.push(ue);
4191            }
4192
4193            PartialRes::new(Res::Err)
4194        };
4195
4196        // For paths originating from calls (like in `HashMap::new()`), tries
4197        // to enrich the plain `failed to resolve: ...` message with hints
4198        // about possible missing imports.
4199        //
4200        // Similar thing, for types, happens in `report_errors` above.
4201        let report_errors_for_call =
4202            |this: &mut Self, parent_err: Spanned<ResolutionError<'ra>>| {
4203                // Before we start looking for candidates, we have to get our hands
4204                // on the type user is trying to perform invocation on; basically:
4205                // we're transforming `HashMap::new` into just `HashMap`.
4206                let (following_seg, prefix_path) = match path.split_last() {
4207                    Some((last, path)) if !path.is_empty() => (Some(last), path),
4208                    _ => return Some(parent_err),
4209                };
4210
4211                let (mut err, candidates) = this.smart_resolve_report_errors(
4212                    prefix_path,
4213                    following_seg,
4214                    path_span,
4215                    PathSource::Type,
4216                    None,
4217                    parent_qself,
4218                );
4219
4220                // There are two different error messages user might receive at
4221                // this point:
4222                // - E0412 cannot find type `{}` in this scope
4223                // - E0433 failed to resolve: use of undeclared type or module `{}`
4224                //
4225                // The first one is emitted for paths in type-position, and the
4226                // latter one - for paths in expression-position.
4227                //
4228                // Thus (since we're in expression-position at this point), not to
4229                // confuse the user, we want to keep the *message* from E0433 (so
4230                // `parent_err`), but we want *hints* from E0412 (so `err`).
4231                //
4232                // And that's what happens below - we're just mixing both messages
4233                // into a single one.
4234                let failed_to_resolve = match parent_err.node {
4235                    ResolutionError::FailedToResolve { .. } => true,
4236                    _ => false,
4237                };
4238                let mut parent_err = this.r.into_struct_error(parent_err.span, parent_err.node);
4239
4240                // overwrite all properties with the parent's error message
4241                err.messages = take(&mut parent_err.messages);
4242                err.code = take(&mut parent_err.code);
4243                swap(&mut err.span, &mut parent_err.span);
4244                if failed_to_resolve {
4245                    err.children = take(&mut parent_err.children);
4246                } else {
4247                    err.children.append(&mut parent_err.children);
4248                }
4249                err.sort_span = parent_err.sort_span;
4250                err.is_lint = parent_err.is_lint.clone();
4251
4252                // merge the parent_err's suggestions with the typo (err's) suggestions
4253                match &mut err.suggestions {
4254                    Suggestions::Enabled(typo_suggestions) => match &mut parent_err.suggestions {
4255                        Suggestions::Enabled(parent_suggestions) => {
4256                            // If both suggestions are enabled, append parent_err's suggestions to err's suggestions.
4257                            typo_suggestions.append(parent_suggestions)
4258                        }
4259                        Suggestions::Sealed(_) | Suggestions::Disabled => {
4260                            // If the parent's suggestions are either sealed or disabled, it signifies that
4261                            // new suggestions cannot be added or removed from the diagnostic. Therefore,
4262                            // we assign both types of suggestions to err's suggestions and discard the
4263                            // existing suggestions in err.
4264                            err.suggestions = std::mem::take(&mut parent_err.suggestions);
4265                        }
4266                    },
4267                    Suggestions::Sealed(_) | Suggestions::Disabled => (),
4268                }
4269
4270                parent_err.cancel();
4271
4272                let def_id = this.parent_scope.module.nearest_parent_mod();
4273
4274                if this.should_report_errs() {
4275                    if candidates.is_empty() {
4276                        if path.len() == 2
4277                            && let [segment] = prefix_path
4278                        {
4279                            // Delay to check whether methond name is an associated function or not
4280                            // ```
4281                            // let foo = Foo {};
4282                            // foo::bar(); // possibly suggest to foo.bar();
4283                            //```
4284                            err.stash(segment.ident.span, rustc_errors::StashKey::CallAssocMethod);
4285                        } else {
4286                            // When there is no suggested imports, we can just emit the error
4287                            // and suggestions immediately. Note that we bypass the usually error
4288                            // reporting routine (ie via `self.r.report_error`) because we need
4289                            // to post-process the `ResolutionError` above.
4290                            err.emit();
4291                        }
4292                    } else {
4293                        // If there are suggested imports, the error reporting is delayed
4294                        this.r.use_injections.push(UseError {
4295                            err,
4296                            candidates,
4297                            def_id,
4298                            instead: false,
4299                            suggestion: None,
4300                            path: prefix_path.into(),
4301                            is_call: source.is_call(),
4302                        });
4303                    }
4304                } else {
4305                    err.cancel();
4306                }
4307
4308                // We don't return `Some(parent_err)` here, because the error will
4309                // be already printed either immediately or as part of the `use` injections
4310                None
4311            };
4312
4313        let partial_res = match self.resolve_qpath_anywhere(
4314            qself,
4315            path,
4316            ns,
4317            path_span,
4318            source.defer_to_typeck(),
4319            finalize,
4320            source,
4321        ) {
4322            Ok(Some(partial_res)) if let Some(res) = partial_res.full_res() => {
4323                // if we also have an associated type that matches the ident, stash a suggestion
4324                if let Some(items) = self.diag_metadata.current_trait_assoc_items
4325                    && let [Segment { ident, .. }] = path
4326                    && items.iter().any(|item| {
4327                        if let AssocItemKind::Type(alias) = &item.kind
4328                            && alias.ident == *ident
4329                        {
4330                            true
4331                        } else {
4332                            false
4333                        }
4334                    })
4335                {
4336                    let mut diag = self.r.tcx.dcx().struct_allow("");
4337                    diag.span_suggestion_verbose(
4338                        path_span.shrink_to_lo(),
4339                        "there is an associated type with the same name",
4340                        "Self::",
4341                        Applicability::MaybeIncorrect,
4342                    );
4343                    diag.stash(path_span, StashKey::AssociatedTypeSuggestion);
4344                }
4345
4346                if source.is_expected(res) || res == Res::Err {
4347                    partial_res
4348                } else {
4349                    report_errors(self, Some(res))
4350                }
4351            }
4352
4353            Ok(Some(partial_res)) if source.defer_to_typeck() => {
4354                // Not fully resolved associated item `T::A::B` or `<T as Tr>::A::B`
4355                // or `<T>::A::B`. If `B` should be resolved in value namespace then
4356                // it needs to be added to the trait map.
4357                if ns == ValueNS {
4358                    let item_name = path.last().unwrap().ident;
4359                    let traits = self.traits_in_scope(item_name, ns);
4360                    self.r.trait_map.insert(node_id, traits);
4361                }
4362
4363                if PrimTy::from_name(path[0].ident.name).is_some() {
4364                    let mut std_path = Vec::with_capacity(1 + path.len());
4365
4366                    std_path.push(Segment::from_ident(Ident::with_dummy_span(sym::std)));
4367                    std_path.extend(path);
4368                    if let PathResult::Module(_) | PathResult::NonModule(_) =
4369                        self.resolve_path(&std_path, Some(ns), None)
4370                    {
4371                        // Check if we wrote `str::from_utf8` instead of `std::str::from_utf8`
4372                        let item_span =
4373                            path.iter().last().map_or(path_span, |segment| segment.ident.span);
4374
4375                        self.r.confused_type_with_std_module.insert(item_span, path_span);
4376                        self.r.confused_type_with_std_module.insert(path_span, path_span);
4377                    }
4378                }
4379
4380                partial_res
4381            }
4382
4383            Err(err) => {
4384                if let Some(err) = report_errors_for_call(self, err) {
4385                    self.report_error(err.span, err.node);
4386                }
4387
4388                PartialRes::new(Res::Err)
4389            }
4390
4391            _ => report_errors(self, None),
4392        };
4393
4394        if record_partial_res == RecordPartialRes::Yes {
4395            // Avoid recording definition of `A::B` in `<T as A>::B::C`.
4396            self.r.record_partial_res(node_id, partial_res);
4397            self.resolve_elided_lifetimes_in_path(partial_res, path, source, path_span);
4398            self.lint_unused_qualifications(path, ns, finalize);
4399        }
4400
4401        partial_res
4402    }
4403
4404    fn self_type_is_available(&mut self) -> bool {
4405        let binding = self
4406            .maybe_resolve_ident_in_lexical_scope(Ident::with_dummy_span(kw::SelfUpper), TypeNS);
4407        if let Some(LexicalScopeBinding::Res(res)) = binding { res != Res::Err } else { false }
4408    }
4409
4410    fn self_value_is_available(&mut self, self_span: Span) -> bool {
4411        let ident = Ident::new(kw::SelfLower, self_span);
4412        let binding = self.maybe_resolve_ident_in_lexical_scope(ident, ValueNS);
4413        if let Some(LexicalScopeBinding::Res(res)) = binding { res != Res::Err } else { false }
4414    }
4415
4416    /// A wrapper around [`Resolver::report_error`].
4417    ///
4418    /// This doesn't emit errors for function bodies if this is rustdoc.
4419    fn report_error(&mut self, span: Span, resolution_error: ResolutionError<'ra>) {
4420        if self.should_report_errs() {
4421            self.r.report_error(span, resolution_error);
4422        }
4423    }
4424
4425    #[inline]
4426    /// If we're actually rustdoc then avoid giving a name resolution error for `cfg()` items or
4427    // an invalid `use foo::*;` was found, which can cause unbounded amounts of "item not found"
4428    // errors. We silence them all.
4429    fn should_report_errs(&self) -> bool {
4430        !(self.r.tcx.sess.opts.actually_rustdoc && self.in_func_body)
4431            && !self.r.glob_error.is_some()
4432    }
4433
4434    // Resolve in alternative namespaces if resolution in the primary namespace fails.
4435    fn resolve_qpath_anywhere(
4436        &mut self,
4437        qself: &Option<P<QSelf>>,
4438        path: &[Segment],
4439        primary_ns: Namespace,
4440        span: Span,
4441        defer_to_typeck: bool,
4442        finalize: Finalize,
4443        source: PathSource<'_, 'ast, '_>,
4444    ) -> Result<Option<PartialRes>, Spanned<ResolutionError<'ra>>> {
4445        let mut fin_res = None;
4446
4447        for (i, &ns) in [primary_ns, TypeNS, ValueNS].iter().enumerate() {
4448            if i == 0 || ns != primary_ns {
4449                match self.resolve_qpath(qself, path, ns, finalize, source)? {
4450                    Some(partial_res)
4451                        if partial_res.unresolved_segments() == 0 || defer_to_typeck =>
4452                    {
4453                        return Ok(Some(partial_res));
4454                    }
4455                    partial_res => {
4456                        if fin_res.is_none() {
4457                            fin_res = partial_res;
4458                        }
4459                    }
4460                }
4461            }
4462        }
4463
4464        assert!(primary_ns != MacroNS);
4465
4466        if qself.is_none() {
4467            let path_seg = |seg: &Segment| PathSegment::from_ident(seg.ident);
4468            let path = Path { segments: path.iter().map(path_seg).collect(), span, tokens: None };
4469            if let Ok((_, res)) = self.r.cm().resolve_macro_path(
4470                &path,
4471                None,
4472                &self.parent_scope,
4473                false,
4474                false,
4475                None,
4476                None,
4477            ) {
4478                return Ok(Some(PartialRes::new(res)));
4479            }
4480        }
4481
4482        Ok(fin_res)
4483    }
4484
4485    /// Handles paths that may refer to associated items.
4486    fn resolve_qpath(
4487        &mut self,
4488        qself: &Option<P<QSelf>>,
4489        path: &[Segment],
4490        ns: Namespace,
4491        finalize: Finalize,
4492        source: PathSource<'_, 'ast, '_>,
4493    ) -> Result<Option<PartialRes>, Spanned<ResolutionError<'ra>>> {
4494        debug!(
4495            "resolve_qpath(qself={:?}, path={:?}, ns={:?}, finalize={:?})",
4496            qself, path, ns, finalize,
4497        );
4498
4499        if let Some(qself) = qself {
4500            if qself.position == 0 {
4501                // This is a case like `<T>::B`, where there is no
4502                // trait to resolve. In that case, we leave the `B`
4503                // segment to be resolved by type-check.
4504                return Ok(Some(PartialRes::with_unresolved_segments(
4505                    Res::Def(DefKind::Mod, CRATE_DEF_ID.to_def_id()),
4506                    path.len(),
4507                )));
4508            }
4509
4510            let num_privacy_errors = self.r.privacy_errors.len();
4511            // Make sure that `A` in `<T as A>::B::C` is a trait.
4512            let trait_res = self.smart_resolve_path_fragment(
4513                &None,
4514                &path[..qself.position],
4515                PathSource::Trait(AliasPossibility::No),
4516                Finalize::new(finalize.node_id, qself.path_span),
4517                RecordPartialRes::No,
4518                Some(&qself),
4519            );
4520
4521            if trait_res.expect_full_res() == Res::Err {
4522                return Ok(Some(trait_res));
4523            }
4524
4525            // Truncate additional privacy errors reported above,
4526            // because they'll be recomputed below.
4527            self.r.privacy_errors.truncate(num_privacy_errors);
4528
4529            // Make sure `A::B` in `<T as A>::B::C` is a trait item.
4530            //
4531            // Currently, `path` names the full item (`A::B::C`, in
4532            // our example). so we extract the prefix of that that is
4533            // the trait (the slice upto and including
4534            // `qself.position`). And then we recursively resolve that,
4535            // but with `qself` set to `None`.
4536            let ns = if qself.position + 1 == path.len() { ns } else { TypeNS };
4537            let partial_res = self.smart_resolve_path_fragment(
4538                &None,
4539                &path[..=qself.position],
4540                PathSource::TraitItem(ns, &source),
4541                Finalize::with_root_span(finalize.node_id, finalize.path_span, qself.path_span),
4542                RecordPartialRes::No,
4543                Some(&qself),
4544            );
4545
4546            // The remaining segments (the `C` in our example) will
4547            // have to be resolved by type-check, since that requires doing
4548            // trait resolution.
4549            return Ok(Some(PartialRes::with_unresolved_segments(
4550                partial_res.base_res(),
4551                partial_res.unresolved_segments() + path.len() - qself.position - 1,
4552            )));
4553        }
4554
4555        let result = match self.resolve_path(path, Some(ns), Some(finalize)) {
4556            PathResult::NonModule(path_res) => path_res,
4557            PathResult::Module(ModuleOrUniformRoot::Module(module)) if !module.is_normal() => {
4558                PartialRes::new(module.res().unwrap())
4559            }
4560            // A part of this path references a `mod` that had a parse error. To avoid resolution
4561            // errors for each reference to that module, we don't emit an error for them until the
4562            // `mod` is fixed. this can have a significant cascade effect.
4563            PathResult::Failed { error_implied_by_parse_error: true, .. } => {
4564                PartialRes::new(Res::Err)
4565            }
4566            // In `a(::assoc_item)*` `a` cannot be a module. If `a` does resolve to a module we
4567            // don't report an error right away, but try to fallback to a primitive type.
4568            // So, we are still able to successfully resolve something like
4569            //
4570            // use std::u8; // bring module u8 in scope
4571            // fn f() -> u8 { // OK, resolves to primitive u8, not to std::u8
4572            //     u8::max_value() // OK, resolves to associated function <u8>::max_value,
4573            //                     // not to nonexistent std::u8::max_value
4574            // }
4575            //
4576            // Such behavior is required for backward compatibility.
4577            // The same fallback is used when `a` resolves to nothing.
4578            PathResult::Module(ModuleOrUniformRoot::Module(_)) | PathResult::Failed { .. }
4579                if (ns == TypeNS || path.len() > 1)
4580                    && PrimTy::from_name(path[0].ident.name).is_some() =>
4581            {
4582                let prim = PrimTy::from_name(path[0].ident.name).unwrap();
4583                let tcx = self.r.tcx();
4584
4585                let gate_err_sym_msg = match prim {
4586                    PrimTy::Float(FloatTy::F16) if !tcx.features().f16() => {
4587                        Some((sym::f16, "the type `f16` is unstable"))
4588                    }
4589                    PrimTy::Float(FloatTy::F128) if !tcx.features().f128() => {
4590                        Some((sym::f128, "the type `f128` is unstable"))
4591                    }
4592                    _ => None,
4593                };
4594
4595                if let Some((sym, msg)) = gate_err_sym_msg {
4596                    let span = path[0].ident.span;
4597                    if !span.allows_unstable(sym) {
4598                        feature_err(tcx.sess, sym, span, msg).emit();
4599                    }
4600                };
4601
4602                // Fix up partial res of segment from `resolve_path` call.
4603                if let Some(id) = path[0].id {
4604                    self.r.partial_res_map.insert(id, PartialRes::new(Res::PrimTy(prim)));
4605                }
4606
4607                PartialRes::with_unresolved_segments(Res::PrimTy(prim), path.len() - 1)
4608            }
4609            PathResult::Module(ModuleOrUniformRoot::Module(module)) => {
4610                PartialRes::new(module.res().unwrap())
4611            }
4612            PathResult::Failed {
4613                is_error_from_last_segment: false,
4614                span,
4615                label,
4616                suggestion,
4617                module,
4618                segment_name,
4619                error_implied_by_parse_error: _,
4620            } => {
4621                return Err(respan(
4622                    span,
4623                    ResolutionError::FailedToResolve {
4624                        segment: Some(segment_name),
4625                        label,
4626                        suggestion,
4627                        module,
4628                    },
4629                ));
4630            }
4631            PathResult::Module(..) | PathResult::Failed { .. } => return Ok(None),
4632            PathResult::Indeterminate => bug!("indeterminate path result in resolve_qpath"),
4633        };
4634
4635        Ok(Some(result))
4636    }
4637
4638    fn with_resolved_label(&mut self, label: Option<Label>, id: NodeId, f: impl FnOnce(&mut Self)) {
4639        if let Some(label) = label {
4640            if label.ident.as_str().as_bytes()[1] != b'_' {
4641                self.diag_metadata.unused_labels.insert(id, label.ident.span);
4642            }
4643
4644            if let Ok((_, orig_span)) = self.resolve_label(label.ident) {
4645                diagnostics::signal_label_shadowing(self.r.tcx.sess, orig_span, label.ident)
4646            }
4647
4648            self.with_label_rib(RibKind::Normal, |this| {
4649                let ident = label.ident.normalize_to_macro_rules();
4650                this.label_ribs.last_mut().unwrap().bindings.insert(ident, id);
4651                f(this);
4652            });
4653        } else {
4654            f(self);
4655        }
4656    }
4657
4658    fn resolve_labeled_block(&mut self, label: Option<Label>, id: NodeId, block: &'ast Block) {
4659        self.with_resolved_label(label, id, |this| this.visit_block(block));
4660    }
4661
4662    fn resolve_block(&mut self, block: &'ast Block) {
4663        debug!("(resolving block) entering block");
4664        // Move down in the graph, if there's an anonymous module rooted here.
4665        let orig_module = self.parent_scope.module;
4666        let anonymous_module = self.r.block_map.get(&block.id).cloned(); // clones a reference
4667
4668        let mut num_macro_definition_ribs = 0;
4669        if let Some(anonymous_module) = anonymous_module {
4670            debug!("(resolving block) found anonymous module, moving down");
4671            self.ribs[ValueNS].push(Rib::new(RibKind::Module(anonymous_module)));
4672            self.ribs[TypeNS].push(Rib::new(RibKind::Module(anonymous_module)));
4673            self.parent_scope.module = anonymous_module;
4674        } else {
4675            self.ribs[ValueNS].push(Rib::new(RibKind::Normal));
4676        }
4677
4678        // Descend into the block.
4679        for stmt in &block.stmts {
4680            if let StmtKind::Item(ref item) = stmt.kind
4681                && let ItemKind::MacroDef(..) = item.kind
4682            {
4683                num_macro_definition_ribs += 1;
4684                let res = self.r.local_def_id(item.id).to_def_id();
4685                self.ribs[ValueNS].push(Rib::new(RibKind::MacroDefinition(res)));
4686                self.label_ribs.push(Rib::new(RibKind::MacroDefinition(res)));
4687            }
4688
4689            self.visit_stmt(stmt);
4690        }
4691
4692        // Move back up.
4693        self.parent_scope.module = orig_module;
4694        for _ in 0..num_macro_definition_ribs {
4695            self.ribs[ValueNS].pop();
4696            self.label_ribs.pop();
4697        }
4698        self.last_block_rib = self.ribs[ValueNS].pop();
4699        if anonymous_module.is_some() {
4700            self.ribs[TypeNS].pop();
4701        }
4702        debug!("(resolving block) leaving block");
4703    }
4704
4705    fn resolve_anon_const(&mut self, constant: &'ast AnonConst, anon_const_kind: AnonConstKind) {
4706        debug!(
4707            "resolve_anon_const(constant: {:?}, anon_const_kind: {:?})",
4708            constant, anon_const_kind
4709        );
4710
4711        let is_trivial_const_arg = constant
4712            .value
4713            .is_potential_trivial_const_arg(self.r.tcx.features().min_generic_const_args());
4714        self.resolve_anon_const_manual(is_trivial_const_arg, anon_const_kind, |this| {
4715            this.resolve_expr(&constant.value, None)
4716        })
4717    }
4718
4719    /// There are a few places that we need to resolve an anon const but we did not parse an
4720    /// anon const so cannot provide an `&'ast AnonConst`. Right now this is just unbraced
4721    /// const arguments that were parsed as type arguments, and `legacy_const_generics` which
4722    /// parse as normal function argument expressions. To avoid duplicating the code for resolving
4723    /// an anon const we have this function which lets the caller manually call `resolve_expr` or
4724    /// `smart_resolve_path`.
4725    fn resolve_anon_const_manual(
4726        &mut self,
4727        is_trivial_const_arg: bool,
4728        anon_const_kind: AnonConstKind,
4729        resolve_expr: impl FnOnce(&mut Self),
4730    ) {
4731        let is_repeat_expr = match anon_const_kind {
4732            AnonConstKind::ConstArg(is_repeat_expr) => is_repeat_expr,
4733            _ => IsRepeatExpr::No,
4734        };
4735
4736        let may_use_generics = match anon_const_kind {
4737            AnonConstKind::EnumDiscriminant => {
4738                ConstantHasGenerics::No(NoConstantGenericsReason::IsEnumDiscriminant)
4739            }
4740            AnonConstKind::FieldDefaultValue => ConstantHasGenerics::Yes,
4741            AnonConstKind::InlineConst => ConstantHasGenerics::Yes,
4742            AnonConstKind::ConstArg(_) => {
4743                if self.r.tcx.features().generic_const_exprs() || is_trivial_const_arg {
4744                    ConstantHasGenerics::Yes
4745                } else {
4746                    ConstantHasGenerics::No(NoConstantGenericsReason::NonTrivialConstArg)
4747                }
4748            }
4749        };
4750
4751        self.with_constant_rib(is_repeat_expr, may_use_generics, None, |this| {
4752            this.with_lifetime_rib(LifetimeRibKind::Elided(LifetimeRes::Infer), |this| {
4753                resolve_expr(this);
4754            });
4755        });
4756    }
4757
4758    fn resolve_expr_field(&mut self, f: &'ast ExprField, e: &'ast Expr) {
4759        self.resolve_expr(&f.expr, Some(e));
4760        self.visit_ident(&f.ident);
4761        walk_list!(self, visit_attribute, f.attrs.iter());
4762    }
4763
4764    fn resolve_expr(&mut self, expr: &'ast Expr, parent: Option<&'ast Expr>) {
4765        // First, record candidate traits for this expression if it could
4766        // result in the invocation of a method call.
4767
4768        self.record_candidate_traits_for_expr_if_necessary(expr);
4769
4770        // Next, resolve the node.
4771        match expr.kind {
4772            ExprKind::Path(ref qself, ref path) => {
4773                self.smart_resolve_path(expr.id, qself, path, PathSource::Expr(parent));
4774                visit::walk_expr(self, expr);
4775            }
4776
4777            ExprKind::Struct(ref se) => {
4778                self.smart_resolve_path(expr.id, &se.qself, &se.path, PathSource::Struct);
4779                // This is the same as `visit::walk_expr(self, expr);`, but we want to pass the
4780                // parent in for accurate suggestions when encountering `Foo { bar }` that should
4781                // have been `Foo { bar: self.bar }`.
4782                if let Some(qself) = &se.qself {
4783                    self.visit_ty(&qself.ty);
4784                }
4785                self.visit_path(&se.path);
4786                walk_list!(self, resolve_expr_field, &se.fields, expr);
4787                match &se.rest {
4788                    StructRest::Base(expr) => self.visit_expr(expr),
4789                    StructRest::Rest(_span) => {}
4790                    StructRest::None => {}
4791                }
4792            }
4793
4794            ExprKind::Break(Some(label), _) | ExprKind::Continue(Some(label)) => {
4795                match self.resolve_label(label.ident) {
4796                    Ok((node_id, _)) => {
4797                        // Since this res is a label, it is never read.
4798                        self.r.label_res_map.insert(expr.id, node_id);
4799                        self.diag_metadata.unused_labels.swap_remove(&node_id);
4800                    }
4801                    Err(error) => {
4802                        self.report_error(label.ident.span, error);
4803                    }
4804                }
4805
4806                // visit `break` argument if any
4807                visit::walk_expr(self, expr);
4808            }
4809
4810            ExprKind::Break(None, Some(ref e)) => {
4811                // We use this instead of `visit::walk_expr` to keep the parent expr around for
4812                // better diagnostics.
4813                self.resolve_expr(e, Some(expr));
4814            }
4815
4816            ExprKind::Let(ref pat, ref scrutinee, _, Recovered::No) => {
4817                self.visit_expr(scrutinee);
4818                self.resolve_pattern_top(pat, PatternSource::Let);
4819            }
4820
4821            ExprKind::Let(ref pat, ref scrutinee, _, Recovered::Yes(_)) => {
4822                self.visit_expr(scrutinee);
4823                // This is basically a tweaked, inlined `resolve_pattern_top`.
4824                let mut bindings = smallvec![(PatBoundCtx::Product, Default::default())];
4825                self.resolve_pattern(pat, PatternSource::Let, &mut bindings);
4826                // We still collect the bindings in this `let` expression which is in
4827                // an invalid position (and therefore shouldn't declare variables into
4828                // its parent scope). To avoid unnecessary errors though, we do just
4829                // reassign the resolutions to `Res::Err`.
4830                for (_, bindings) in &mut bindings {
4831                    for (_, binding) in bindings {
4832                        *binding = Res::Err;
4833                    }
4834                }
4835                self.apply_pattern_bindings(bindings);
4836            }
4837
4838            ExprKind::If(ref cond, ref then, ref opt_else) => {
4839                self.with_rib(ValueNS, RibKind::Normal, |this| {
4840                    let old = this.diag_metadata.in_if_condition.replace(cond);
4841                    this.visit_expr(cond);
4842                    this.diag_metadata.in_if_condition = old;
4843                    this.visit_block(then);
4844                });
4845                if let Some(expr) = opt_else {
4846                    self.visit_expr(expr);
4847                }
4848            }
4849
4850            ExprKind::Loop(ref block, label, _) => {
4851                self.resolve_labeled_block(label, expr.id, block)
4852            }
4853
4854            ExprKind::While(ref cond, ref block, label) => {
4855                self.with_resolved_label(label, expr.id, |this| {
4856                    this.with_rib(ValueNS, RibKind::Normal, |this| {
4857                        let old = this.diag_metadata.in_if_condition.replace(cond);
4858                        this.visit_expr(cond);
4859                        this.diag_metadata.in_if_condition = old;
4860                        this.visit_block(block);
4861                    })
4862                });
4863            }
4864
4865            ExprKind::ForLoop { ref pat, ref iter, ref body, label, kind: _ } => {
4866                self.visit_expr(iter);
4867                self.with_rib(ValueNS, RibKind::Normal, |this| {
4868                    this.resolve_pattern_top(pat, PatternSource::For);
4869                    this.resolve_labeled_block(label, expr.id, body);
4870                });
4871            }
4872
4873            ExprKind::Block(ref block, label) => self.resolve_labeled_block(label, block.id, block),
4874
4875            // Equivalent to `visit::walk_expr` + passing some context to children.
4876            ExprKind::Field(ref subexpression, _) => {
4877                self.resolve_expr(subexpression, Some(expr));
4878            }
4879            ExprKind::MethodCall(box MethodCall { ref seg, ref receiver, ref args, .. }) => {
4880                self.resolve_expr(receiver, Some(expr));
4881                for arg in args {
4882                    self.resolve_expr(arg, None);
4883                }
4884                self.visit_path_segment(seg);
4885            }
4886
4887            ExprKind::Call(ref callee, ref arguments) => {
4888                self.resolve_expr(callee, Some(expr));
4889                let const_args = self.r.legacy_const_generic_args(callee).unwrap_or_default();
4890                for (idx, argument) in arguments.iter().enumerate() {
4891                    // Constant arguments need to be treated as AnonConst since
4892                    // that is how they will be later lowered to HIR.
4893                    if const_args.contains(&idx) {
4894                        let is_trivial_const_arg = argument.is_potential_trivial_const_arg(
4895                            self.r.tcx.features().min_generic_const_args(),
4896                        );
4897                        self.resolve_anon_const_manual(
4898                            is_trivial_const_arg,
4899                            AnonConstKind::ConstArg(IsRepeatExpr::No),
4900                            |this| this.resolve_expr(argument, None),
4901                        );
4902                    } else {
4903                        self.resolve_expr(argument, None);
4904                    }
4905                }
4906            }
4907            ExprKind::Type(ref _type_expr, ref _ty) => {
4908                visit::walk_expr(self, expr);
4909            }
4910            // For closures, RibKind::FnOrCoroutine is added in visit_fn
4911            ExprKind::Closure(box ast::Closure {
4912                binder: ClosureBinder::For { ref generic_params, span },
4913                ..
4914            }) => {
4915                self.with_generic_param_rib(
4916                    generic_params,
4917                    RibKind::Normal,
4918                    expr.id,
4919                    LifetimeBinderKind::Closure,
4920                    span,
4921                    |this| visit::walk_expr(this, expr),
4922                );
4923            }
4924            ExprKind::Closure(..) => visit::walk_expr(self, expr),
4925            ExprKind::Gen(..) => {
4926                self.with_label_rib(RibKind::FnOrCoroutine, |this| visit::walk_expr(this, expr));
4927            }
4928            ExprKind::Repeat(ref elem, ref ct) => {
4929                self.visit_expr(elem);
4930                self.resolve_anon_const(ct, AnonConstKind::ConstArg(IsRepeatExpr::Yes));
4931            }
4932            ExprKind::ConstBlock(ref ct) => {
4933                self.resolve_anon_const(ct, AnonConstKind::InlineConst);
4934            }
4935            ExprKind::Index(ref elem, ref idx, _) => {
4936                self.resolve_expr(elem, Some(expr));
4937                self.visit_expr(idx);
4938            }
4939            ExprKind::Assign(ref lhs, ref rhs, _) => {
4940                if !self.diag_metadata.is_assign_rhs {
4941                    self.diag_metadata.in_assignment = Some(expr);
4942                }
4943                self.visit_expr(lhs);
4944                self.diag_metadata.is_assign_rhs = true;
4945                self.diag_metadata.in_assignment = None;
4946                self.visit_expr(rhs);
4947                self.diag_metadata.is_assign_rhs = false;
4948            }
4949            ExprKind::Range(Some(ref start), Some(ref end), RangeLimits::HalfOpen) => {
4950                self.diag_metadata.in_range = Some((start, end));
4951                self.resolve_expr(start, Some(expr));
4952                self.resolve_expr(end, Some(expr));
4953                self.diag_metadata.in_range = None;
4954            }
4955            _ => {
4956                visit::walk_expr(self, expr);
4957            }
4958        }
4959    }
4960
4961    fn record_candidate_traits_for_expr_if_necessary(&mut self, expr: &'ast Expr) {
4962        match expr.kind {
4963            ExprKind::Field(_, ident) => {
4964                // #6890: Even though you can't treat a method like a field,
4965                // we need to add any trait methods we find that match the
4966                // field name so that we can do some nice error reporting
4967                // later on in typeck.
4968                let traits = self.traits_in_scope(ident, ValueNS);
4969                self.r.trait_map.insert(expr.id, traits);
4970            }
4971            ExprKind::MethodCall(ref call) => {
4972                debug!("(recording candidate traits for expr) recording traits for {}", expr.id);
4973                let traits = self.traits_in_scope(call.seg.ident, ValueNS);
4974                self.r.trait_map.insert(expr.id, traits);
4975            }
4976            _ => {
4977                // Nothing to do.
4978            }
4979        }
4980    }
4981
4982    fn traits_in_scope(&mut self, ident: Ident, ns: Namespace) -> Vec<TraitCandidate> {
4983        self.r.traits_in_scope(
4984            self.current_trait_ref.as_ref().map(|(module, _)| *module),
4985            &self.parent_scope,
4986            ident.span.ctxt(),
4987            Some((ident.name, ns)),
4988        )
4989    }
4990
4991    fn resolve_and_cache_rustdoc_path(&mut self, path_str: &str, ns: Namespace) -> Option<Res> {
4992        // FIXME: This caching may be incorrect in case of multiple `macro_rules`
4993        // items with the same name in the same module.
4994        // Also hygiene is not considered.
4995        let mut doc_link_resolutions = std::mem::take(&mut self.r.doc_link_resolutions);
4996        let res = *doc_link_resolutions
4997            .entry(self.parent_scope.module.nearest_parent_mod().expect_local())
4998            .or_default()
4999            .entry((Symbol::intern(path_str), ns))
5000            .or_insert_with_key(|(path, ns)| {
5001                let res = self.r.resolve_rustdoc_path(path.as_str(), *ns, self.parent_scope);
5002                if let Some(res) = res
5003                    && let Some(def_id) = res.opt_def_id()
5004                    && self.is_invalid_proc_macro_item_for_doc(def_id)
5005                {
5006                    // Encoding def ids in proc macro crate metadata will ICE,
5007                    // because it will only store proc macros for it.
5008                    return None;
5009                }
5010                res
5011            });
5012        self.r.doc_link_resolutions = doc_link_resolutions;
5013        res
5014    }
5015
5016    fn is_invalid_proc_macro_item_for_doc(&self, did: DefId) -> bool {
5017        if !matches!(self.r.tcx.sess.opts.resolve_doc_links, ResolveDocLinks::ExportedMetadata)
5018            || !self.r.tcx.crate_types().contains(&CrateType::ProcMacro)
5019        {
5020            return false;
5021        }
5022        let Some(local_did) = did.as_local() else { return true };
5023        !self.r.proc_macros.contains(&local_did)
5024    }
5025
5026    fn resolve_doc_links(&mut self, attrs: &[Attribute], maybe_exported: MaybeExported<'_>) {
5027        match self.r.tcx.sess.opts.resolve_doc_links {
5028            ResolveDocLinks::None => return,
5029            ResolveDocLinks::ExportedMetadata
5030                if !self.r.tcx.crate_types().iter().copied().any(CrateType::has_metadata)
5031                    || !maybe_exported.eval(self.r) =>
5032            {
5033                return;
5034            }
5035            ResolveDocLinks::Exported
5036                if !maybe_exported.eval(self.r)
5037                    && !rustdoc::has_primitive_or_keyword_docs(attrs) =>
5038            {
5039                return;
5040            }
5041            ResolveDocLinks::ExportedMetadata
5042            | ResolveDocLinks::Exported
5043            | ResolveDocLinks::All => {}
5044        }
5045
5046        if !attrs.iter().any(|attr| attr.may_have_doc_links()) {
5047            return;
5048        }
5049
5050        let mut need_traits_in_scope = false;
5051        for path_str in rustdoc::attrs_to_preprocessed_links(attrs) {
5052            // Resolve all namespaces due to no disambiguator or for diagnostics.
5053            let mut any_resolved = false;
5054            let mut need_assoc = false;
5055            for ns in [TypeNS, ValueNS, MacroNS] {
5056                if let Some(res) = self.resolve_and_cache_rustdoc_path(&path_str, ns) {
5057                    // Rustdoc ignores tool attribute resolutions and attempts
5058                    // to resolve their prefixes for diagnostics.
5059                    any_resolved = !matches!(res, Res::NonMacroAttr(NonMacroAttrKind::Tool));
5060                } else if ns != MacroNS {
5061                    need_assoc = true;
5062                }
5063            }
5064
5065            // Resolve all prefixes for type-relative resolution or for diagnostics.
5066            if need_assoc || !any_resolved {
5067                let mut path = &path_str[..];
5068                while let Some(idx) = path.rfind("::") {
5069                    path = &path[..idx];
5070                    need_traits_in_scope = true;
5071                    for ns in [TypeNS, ValueNS, MacroNS] {
5072                        self.resolve_and_cache_rustdoc_path(path, ns);
5073                    }
5074                }
5075            }
5076        }
5077
5078        if need_traits_in_scope {
5079            // FIXME: hygiene is not considered.
5080            let mut doc_link_traits_in_scope = std::mem::take(&mut self.r.doc_link_traits_in_scope);
5081            doc_link_traits_in_scope
5082                .entry(self.parent_scope.module.nearest_parent_mod().expect_local())
5083                .or_insert_with(|| {
5084                    self.r
5085                        .traits_in_scope(None, &self.parent_scope, SyntaxContext::root(), None)
5086                        .into_iter()
5087                        .filter_map(|tr| {
5088                            if self.is_invalid_proc_macro_item_for_doc(tr.def_id) {
5089                                // Encoding def ids in proc macro crate metadata will ICE.
5090                                // because it will only store proc macros for it.
5091                                return None;
5092                            }
5093                            Some(tr.def_id)
5094                        })
5095                        .collect()
5096                });
5097            self.r.doc_link_traits_in_scope = doc_link_traits_in_scope;
5098        }
5099    }
5100
5101    fn lint_unused_qualifications(&mut self, path: &[Segment], ns: Namespace, finalize: Finalize) {
5102        // Don't lint on global paths because the user explicitly wrote out the full path.
5103        if let Some(seg) = path.first()
5104            && seg.ident.name == kw::PathRoot
5105        {
5106            return;
5107        }
5108
5109        if finalize.path_span.from_expansion()
5110            || path.iter().any(|seg| seg.ident.span.from_expansion())
5111        {
5112            return;
5113        }
5114
5115        let end_pos =
5116            path.iter().position(|seg| seg.has_generic_args).map_or(path.len(), |pos| pos + 1);
5117        let unqualified = path[..end_pos].iter().enumerate().skip(1).rev().find_map(|(i, seg)| {
5118            // Preserve the current namespace for the final path segment, but use the type
5119            // namespace for all preceding segments
5120            //
5121            // e.g. for `std::env::args` check the `ValueNS` for `args` but the `TypeNS` for
5122            // `std` and `env`
5123            //
5124            // If the final path segment is beyond `end_pos` all the segments to check will
5125            // use the type namespace
5126            let ns = if i + 1 == path.len() { ns } else { TypeNS };
5127            let res = self.r.partial_res_map.get(&seg.id?)?.full_res()?;
5128            let binding = self.resolve_ident_in_lexical_scope(seg.ident, ns, None, None)?;
5129            (res == binding.res()).then_some((seg, binding))
5130        });
5131
5132        if let Some((seg, binding)) = unqualified {
5133            self.r.potentially_unnecessary_qualifications.push(UnnecessaryQualification {
5134                binding,
5135                node_id: finalize.node_id,
5136                path_span: finalize.path_span,
5137                removal_span: path[0].ident.span.until(seg.ident.span),
5138            });
5139        }
5140    }
5141
5142    fn resolve_define_opaques(&mut self, define_opaque: &Option<ThinVec<(NodeId, Path)>>) {
5143        if let Some(define_opaque) = define_opaque {
5144            for (id, path) in define_opaque {
5145                self.smart_resolve_path(*id, &None, path, PathSource::DefineOpaques);
5146            }
5147        }
5148    }
5149}
5150
5151/// Walks the whole crate in DFS order, visiting each item, counting the declared number of
5152/// lifetime generic parameters and function parameters.
5153struct ItemInfoCollector<'a, 'ra, 'tcx> {
5154    r: &'a mut Resolver<'ra, 'tcx>,
5155}
5156
5157impl ItemInfoCollector<'_, '_, '_> {
5158    fn collect_fn_info(
5159        &mut self,
5160        header: FnHeader,
5161        decl: &FnDecl,
5162        id: NodeId,
5163        attrs: &[Attribute],
5164    ) {
5165        let sig = DelegationFnSig {
5166            header,
5167            param_count: decl.inputs.len(),
5168            has_self: decl.has_self(),
5169            c_variadic: decl.c_variadic(),
5170            target_feature: attrs.iter().any(|attr| attr.has_name(sym::target_feature)),
5171        };
5172        self.r.delegation_fn_sigs.insert(self.r.local_def_id(id), sig);
5173    }
5174}
5175
5176impl<'ast> Visitor<'ast> for ItemInfoCollector<'_, '_, '_> {
5177    fn visit_item(&mut self, item: &'ast Item) {
5178        match &item.kind {
5179            ItemKind::TyAlias(box TyAlias { generics, .. })
5180            | ItemKind::Const(box ConstItem { generics, .. })
5181            | ItemKind::Fn(box Fn { generics, .. })
5182            | ItemKind::Enum(_, generics, _)
5183            | ItemKind::Struct(_, generics, _)
5184            | ItemKind::Union(_, generics, _)
5185            | ItemKind::Impl(box Impl { generics, .. })
5186            | ItemKind::Trait(box Trait { generics, .. })
5187            | ItemKind::TraitAlias(_, generics, _) => {
5188                if let ItemKind::Fn(box Fn { sig, .. }) = &item.kind {
5189                    self.collect_fn_info(sig.header, &sig.decl, item.id, &item.attrs);
5190                }
5191
5192                let def_id = self.r.local_def_id(item.id);
5193                let count = generics
5194                    .params
5195                    .iter()
5196                    .filter(|param| matches!(param.kind, ast::GenericParamKind::Lifetime { .. }))
5197                    .count();
5198                self.r.item_generics_num_lifetimes.insert(def_id, count);
5199            }
5200
5201            ItemKind::ForeignMod(ForeignMod { extern_span, safety: _, abi, items }) => {
5202                for foreign_item in items {
5203                    if let ForeignItemKind::Fn(box Fn { sig, .. }) = &foreign_item.kind {
5204                        let new_header =
5205                            FnHeader { ext: Extern::from_abi(*abi, *extern_span), ..sig.header };
5206                        self.collect_fn_info(new_header, &sig.decl, foreign_item.id, &item.attrs);
5207                    }
5208                }
5209            }
5210
5211            ItemKind::Mod(..)
5212            | ItemKind::Static(..)
5213            | ItemKind::Use(..)
5214            | ItemKind::ExternCrate(..)
5215            | ItemKind::MacroDef(..)
5216            | ItemKind::GlobalAsm(..)
5217            | ItemKind::MacCall(..)
5218            | ItemKind::DelegationMac(..) => {}
5219            ItemKind::Delegation(..) => {
5220                // Delegated functions have lifetimes, their count is not necessarily zero.
5221                // But skipping the delegation items here doesn't mean that the count will be considered zero,
5222                // it means there will be a panic when retrieving the count,
5223                // but for delegation items we are never actually retrieving that count in practice.
5224            }
5225        }
5226        visit::walk_item(self, item)
5227    }
5228
5229    fn visit_assoc_item(&mut self, item: &'ast AssocItem, ctxt: AssocCtxt) {
5230        if let AssocItemKind::Fn(box Fn { sig, .. }) = &item.kind {
5231            self.collect_fn_info(sig.header, &sig.decl, item.id, &item.attrs);
5232        }
5233        visit::walk_assoc_item(self, item, ctxt);
5234    }
5235}
5236
5237impl<'ra, 'tcx> Resolver<'ra, 'tcx> {
5238    pub(crate) fn late_resolve_crate(&mut self, krate: &Crate) {
5239        visit::walk_crate(&mut ItemInfoCollector { r: self }, krate);
5240        let mut late_resolution_visitor = LateResolutionVisitor::new(self);
5241        late_resolution_visitor.resolve_doc_links(&krate.attrs, MaybeExported::Ok(CRATE_NODE_ID));
5242        visit::walk_crate(&mut late_resolution_visitor, krate);
5243        for (id, span) in late_resolution_visitor.diag_metadata.unused_labels.iter() {
5244            self.lint_buffer.buffer_lint(
5245                lint::builtin::UNUSED_LABELS,
5246                *id,
5247                *span,
5248                BuiltinLintDiag::UnusedLabel,
5249            );
5250        }
5251    }
5252}
5253
5254/// Check if definition matches a path
5255fn def_id_matches_path(tcx: TyCtxt<'_>, mut def_id: DefId, expected_path: &[&str]) -> bool {
5256    let mut path = expected_path.iter().rev();
5257    while let (Some(parent), Some(next_step)) = (tcx.opt_parent(def_id), path.next()) {
5258        if !tcx.opt_item_name(def_id).is_some_and(|n| n.as_str() == *next_step) {
5259            return false;
5260        }
5261        def_id = parent;
5262    }
5263    true
5264}