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