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, Decl, Finalize, LateDecl, Module, ModuleOrUniformRoot, ParentScope,
47    PathResult, ResolutionError, Resolver, Segment, Stage, TyCtxt, UseError, Used, errors,
48    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 decl: LateDecl<'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<LateDecl<'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_decl: Option<Decl<'ra>>,
1493    ) -> Option<LateDecl<'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_decl,
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.map(|finalize| Finalize { stage: Stage::Late, ..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 { alias_to: item_def_id, is_trait_impl: false },
2659                        |this| {
2660                            visit::walk_item(this, item);
2661                        },
2662                    );
2663                },
2664            );
2665        });
2666    }
2667
2668    fn future_proof_import(&mut self, use_tree: &UseTree) {
2669        if let [segment, rest @ ..] = use_tree.prefix.segments.as_slice() {
2670            let ident = segment.ident;
2671            if ident.is_path_segment_keyword() || ident.span.is_rust_2015() {
2672                return;
2673            }
2674
2675            let nss = match use_tree.kind {
2676                UseTreeKind::Simple(..) if rest.is_empty() => &[TypeNS, ValueNS][..],
2677                _ => &[TypeNS],
2678            };
2679            let report_error = |this: &Self, ns| {
2680                if this.should_report_errs() {
2681                    let what = if ns == TypeNS { "type parameters" } else { "local variables" };
2682                    this.r.dcx().emit_err(errors::ImportsCannotReferTo { span: ident.span, what });
2683                }
2684            };
2685
2686            for &ns in nss {
2687                match self.maybe_resolve_ident_in_lexical_scope(ident, ns) {
2688                    Some(LateDecl::RibDef(..)) => {
2689                        report_error(self, ns);
2690                    }
2691                    Some(LateDecl::Decl(binding)) => {
2692                        if let Some(LateDecl::RibDef(..)) =
2693                            self.resolve_ident_in_lexical_scope(ident, ns, None, Some(binding))
2694                        {
2695                            report_error(self, ns);
2696                        }
2697                    }
2698                    None => {}
2699                }
2700            }
2701        } else if let UseTreeKind::Nested { items, .. } = &use_tree.kind {
2702            for (use_tree, _) in items {
2703                self.future_proof_import(use_tree);
2704            }
2705        }
2706    }
2707
2708    fn resolve_item(&mut self, item: &'ast Item) {
2709        let mod_inner_docs =
2710            matches!(item.kind, ItemKind::Mod(..)) && rustdoc::inner_docs(&item.attrs);
2711        if !mod_inner_docs && !matches!(item.kind, ItemKind::Impl(..) | ItemKind::Use(..)) {
2712            self.resolve_doc_links(&item.attrs, MaybeExported::Ok(item.id));
2713        }
2714
2715        debug!("(resolving item) resolving {:?} ({:?})", item.kind.ident(), item.kind);
2716
2717        let def_kind = self.r.local_def_kind(item.id);
2718        match item.kind {
2719            ItemKind::TyAlias(box TyAlias { ref generics, .. }) => {
2720                self.with_generic_param_rib(
2721                    &generics.params,
2722                    RibKind::Item(HasGenericParams::Yes(generics.span), def_kind),
2723                    item.id,
2724                    LifetimeBinderKind::Item,
2725                    generics.span,
2726                    |this| visit::walk_item(this, item),
2727                );
2728            }
2729
2730            ItemKind::Fn(box Fn { ref generics, ref define_opaque, .. }) => {
2731                self.with_generic_param_rib(
2732                    &generics.params,
2733                    RibKind::Item(HasGenericParams::Yes(generics.span), def_kind),
2734                    item.id,
2735                    LifetimeBinderKind::Function,
2736                    generics.span,
2737                    |this| visit::walk_item(this, item),
2738                );
2739                self.resolve_define_opaques(define_opaque);
2740            }
2741
2742            ItemKind::Enum(_, ref generics, _)
2743            | ItemKind::Struct(_, ref generics, _)
2744            | ItemKind::Union(_, ref generics, _) => {
2745                self.resolve_adt(item, generics);
2746            }
2747
2748            ItemKind::Impl(Impl {
2749                ref generics,
2750                ref of_trait,
2751                ref self_ty,
2752                items: ref impl_items,
2753                ..
2754            }) => {
2755                self.diag_metadata.current_impl_items = Some(impl_items);
2756                self.resolve_implementation(
2757                    &item.attrs,
2758                    generics,
2759                    of_trait.as_deref(),
2760                    self_ty,
2761                    item.id,
2762                    impl_items,
2763                );
2764                self.diag_metadata.current_impl_items = None;
2765            }
2766
2767            ItemKind::Trait(box Trait { ref generics, ref bounds, ref items, .. }) => {
2768                // Create a new rib for the trait-wide type parameters.
2769                self.with_generic_param_rib(
2770                    &generics.params,
2771                    RibKind::Item(HasGenericParams::Yes(generics.span), def_kind),
2772                    item.id,
2773                    LifetimeBinderKind::Item,
2774                    generics.span,
2775                    |this| {
2776                        let local_def_id = this.r.local_def_id(item.id).to_def_id();
2777                        this.with_self_rib(Res::SelfTyParam { trait_: local_def_id }, |this| {
2778                            this.visit_generics(generics);
2779                            walk_list!(this, visit_param_bound, bounds, BoundKind::SuperTraits);
2780                            this.resolve_trait_items(items);
2781                        });
2782                    },
2783                );
2784            }
2785
2786            ItemKind::TraitAlias(box TraitAlias { ref generics, ref bounds, .. }) => {
2787                // Create a new rib for the trait-wide type parameters.
2788                self.with_generic_param_rib(
2789                    &generics.params,
2790                    RibKind::Item(HasGenericParams::Yes(generics.span), def_kind),
2791                    item.id,
2792                    LifetimeBinderKind::Item,
2793                    generics.span,
2794                    |this| {
2795                        let local_def_id = this.r.local_def_id(item.id).to_def_id();
2796                        this.with_self_rib(Res::SelfTyParam { trait_: local_def_id }, |this| {
2797                            this.visit_generics(generics);
2798                            walk_list!(this, visit_param_bound, bounds, BoundKind::Bound);
2799                        });
2800                    },
2801                );
2802            }
2803
2804            ItemKind::Mod(..) => {
2805                let module = self.r.expect_module(self.r.local_def_id(item.id).to_def_id());
2806                let orig_module = replace(&mut self.parent_scope.module, module);
2807                self.with_rib(ValueNS, RibKind::Module(module), |this| {
2808                    this.with_rib(TypeNS, RibKind::Module(module), |this| {
2809                        if mod_inner_docs {
2810                            this.resolve_doc_links(&item.attrs, MaybeExported::Ok(item.id));
2811                        }
2812                        let old_macro_rules = this.parent_scope.macro_rules;
2813                        visit::walk_item(this, item);
2814                        // Maintain macro_rules scopes in the same way as during early resolution
2815                        // for diagnostics and doc links.
2816                        if item.attrs.iter().all(|attr| {
2817                            !attr.has_name(sym::macro_use) && !attr.has_name(sym::macro_escape)
2818                        }) {
2819                            this.parent_scope.macro_rules = old_macro_rules;
2820                        }
2821                    })
2822                });
2823                self.parent_scope.module = orig_module;
2824            }
2825
2826            ItemKind::Static(box ast::StaticItem {
2827                ident,
2828                ref ty,
2829                ref expr,
2830                ref define_opaque,
2831                ..
2832            }) => {
2833                self.with_static_rib(def_kind, |this| {
2834                    this.with_lifetime_rib(LifetimeRibKind::Elided(LifetimeRes::Static), |this| {
2835                        this.visit_ty(ty);
2836                    });
2837                    if let Some(expr) = expr {
2838                        // We already forbid generic params because of the above item rib,
2839                        // so it doesn't matter whether this is a trivial constant.
2840                        this.resolve_static_body(expr, Some((ident, ConstantItemKind::Static)));
2841                    }
2842                });
2843                self.resolve_define_opaques(define_opaque);
2844            }
2845
2846            ItemKind::Const(box ast::ConstItem {
2847                ident,
2848                ref generics,
2849                ref ty,
2850                ref rhs,
2851                ref define_opaque,
2852                ..
2853            }) => {
2854                let is_type_const = attr::contains_name(&item.attrs, sym::type_const);
2855                self.with_generic_param_rib(
2856                    &generics.params,
2857                    RibKind::Item(
2858                        if self.r.tcx.features().generic_const_items() {
2859                            HasGenericParams::Yes(generics.span)
2860                        } else {
2861                            HasGenericParams::No
2862                        },
2863                        def_kind,
2864                    ),
2865                    item.id,
2866                    LifetimeBinderKind::ConstItem,
2867                    generics.span,
2868                    |this| {
2869                        this.visit_generics(generics);
2870
2871                        this.with_lifetime_rib(
2872                            LifetimeRibKind::Elided(LifetimeRes::Static),
2873                            |this| {
2874                                if is_type_const
2875                                    && !this.r.tcx.features().generic_const_parameter_types()
2876                                {
2877                                    this.with_rib(TypeNS, RibKind::ConstParamTy, |this| {
2878                                        this.with_rib(ValueNS, RibKind::ConstParamTy, |this| {
2879                                            this.with_lifetime_rib(
2880                                                LifetimeRibKind::ConstParamTy,
2881                                                |this| this.visit_ty(ty),
2882                                            )
2883                                        })
2884                                    });
2885                                } else {
2886                                    this.visit_ty(ty);
2887                                }
2888                            },
2889                        );
2890
2891                        if let Some(rhs) = rhs {
2892                            this.resolve_const_item_rhs(
2893                                rhs,
2894                                Some((ident, ConstantItemKind::Const)),
2895                            );
2896                        }
2897                    },
2898                );
2899                self.resolve_define_opaques(define_opaque);
2900            }
2901
2902            ItemKind::Use(ref use_tree) => {
2903                let maybe_exported = match use_tree.kind {
2904                    UseTreeKind::Simple(_) | UseTreeKind::Glob => MaybeExported::Ok(item.id),
2905                    UseTreeKind::Nested { .. } => MaybeExported::NestedUse(&item.vis),
2906                };
2907                self.resolve_doc_links(&item.attrs, maybe_exported);
2908
2909                self.future_proof_import(use_tree);
2910            }
2911
2912            ItemKind::MacroDef(_, ref macro_def) => {
2913                // Maintain macro_rules scopes in the same way as during early resolution
2914                // for diagnostics and doc links.
2915                if macro_def.macro_rules {
2916                    let def_id = self.r.local_def_id(item.id);
2917                    self.parent_scope.macro_rules = self.r.macro_rules_scopes[&def_id];
2918                }
2919
2920                if let Some(EiiExternTarget { extern_item_path, impl_unsafe: _, span: _ }) =
2921                    &macro_def.eii_extern_target
2922                {
2923                    self.smart_resolve_path(
2924                        item.id,
2925                        &None,
2926                        extern_item_path,
2927                        PathSource::Expr(None),
2928                    );
2929                }
2930            }
2931
2932            ItemKind::ForeignMod(_) | ItemKind::GlobalAsm(_) => {
2933                visit::walk_item(self, item);
2934            }
2935
2936            ItemKind::Delegation(ref delegation) => {
2937                let span = delegation.path.segments.last().unwrap().ident.span;
2938                self.with_generic_param_rib(
2939                    &[],
2940                    RibKind::Item(HasGenericParams::Yes(span), def_kind),
2941                    item.id,
2942                    LifetimeBinderKind::Function,
2943                    span,
2944                    |this| this.resolve_delegation(delegation, item.id, false, &item.attrs),
2945                );
2946            }
2947
2948            ItemKind::ExternCrate(..) => {}
2949
2950            ItemKind::MacCall(_) | ItemKind::DelegationMac(..) => {
2951                panic!("unexpanded macro in resolve!")
2952            }
2953        }
2954    }
2955
2956    fn with_generic_param_rib<F>(
2957        &mut self,
2958        params: &[GenericParam],
2959        kind: RibKind<'ra>,
2960        binder: NodeId,
2961        generics_kind: LifetimeBinderKind,
2962        generics_span: Span,
2963        f: F,
2964    ) where
2965        F: FnOnce(&mut Self),
2966    {
2967        debug!("with_generic_param_rib");
2968        let lifetime_kind =
2969            LifetimeRibKind::Generics { binder, span: generics_span, kind: generics_kind };
2970
2971        let mut function_type_rib = Rib::new(kind);
2972        let mut function_value_rib = Rib::new(kind);
2973        let mut function_lifetime_rib = LifetimeRib::new(lifetime_kind);
2974
2975        // Only check for shadowed bindings if we're declaring new params.
2976        if !params.is_empty() {
2977            let mut seen_bindings = FxHashMap::default();
2978            // Store all seen lifetimes names from outer scopes.
2979            let mut seen_lifetimes = FxHashSet::default();
2980
2981            // We also can't shadow bindings from associated parent items.
2982            for ns in [ValueNS, TypeNS] {
2983                for parent_rib in self.ribs[ns].iter().rev() {
2984                    // Break at module or block level, to account for nested items which are
2985                    // allowed to shadow generic param names.
2986                    if matches!(parent_rib.kind, RibKind::Module(..) | RibKind::Block(..)) {
2987                        break;
2988                    }
2989
2990                    seen_bindings
2991                        .extend(parent_rib.bindings.keys().map(|ident| (*ident, ident.span)));
2992                }
2993            }
2994
2995            // Forbid shadowing lifetime bindings
2996            for rib in self.lifetime_ribs.iter().rev() {
2997                seen_lifetimes.extend(rib.bindings.iter().map(|(ident, _)| *ident));
2998                if let LifetimeRibKind::Item = rib.kind {
2999                    break;
3000                }
3001            }
3002
3003            for param in params {
3004                let ident = param.ident.normalize_to_macros_2_0();
3005                debug!("with_generic_param_rib: {}", param.id);
3006
3007                if let GenericParamKind::Lifetime = param.kind
3008                    && let Some(&original) = seen_lifetimes.get(&ident)
3009                {
3010                    diagnostics::signal_lifetime_shadowing(self.r.tcx.sess, original, param.ident);
3011                    // Record lifetime res, so lowering knows there is something fishy.
3012                    self.record_lifetime_param(param.id, LifetimeRes::Error);
3013                    continue;
3014                }
3015
3016                match seen_bindings.entry(ident) {
3017                    Entry::Occupied(entry) => {
3018                        let span = *entry.get();
3019                        let err = ResolutionError::NameAlreadyUsedInParameterList(ident, span);
3020                        self.report_error(param.ident.span, err);
3021                        let rib = match param.kind {
3022                            GenericParamKind::Lifetime => {
3023                                // Record lifetime res, so lowering knows there is something fishy.
3024                                self.record_lifetime_param(param.id, LifetimeRes::Error);
3025                                continue;
3026                            }
3027                            GenericParamKind::Type { .. } => &mut function_type_rib,
3028                            GenericParamKind::Const { .. } => &mut function_value_rib,
3029                        };
3030
3031                        // Taint the resolution in case of errors to prevent follow up errors in typeck
3032                        self.r.record_partial_res(param.id, PartialRes::new(Res::Err));
3033                        rib.bindings.insert(ident, Res::Err);
3034                        continue;
3035                    }
3036                    Entry::Vacant(entry) => {
3037                        entry.insert(param.ident.span);
3038                    }
3039                }
3040
3041                if param.ident.name == kw::UnderscoreLifetime {
3042                    // To avoid emitting two similar errors,
3043                    // we need to check if the span is a raw underscore lifetime, see issue #143152
3044                    let is_raw_underscore_lifetime = self
3045                        .r
3046                        .tcx
3047                        .sess
3048                        .psess
3049                        .raw_identifier_spans
3050                        .iter()
3051                        .any(|span| span == param.span());
3052
3053                    self.r
3054                        .dcx()
3055                        .create_err(errors::UnderscoreLifetimeIsReserved { span: param.ident.span })
3056                        .emit_unless_delay(is_raw_underscore_lifetime);
3057                    // Record lifetime res, so lowering knows there is something fishy.
3058                    self.record_lifetime_param(param.id, LifetimeRes::Error);
3059                    continue;
3060                }
3061
3062                if param.ident.name == kw::StaticLifetime {
3063                    self.r.dcx().emit_err(errors::StaticLifetimeIsReserved {
3064                        span: param.ident.span,
3065                        lifetime: param.ident,
3066                    });
3067                    // Record lifetime res, so lowering knows there is something fishy.
3068                    self.record_lifetime_param(param.id, LifetimeRes::Error);
3069                    continue;
3070                }
3071
3072                let def_id = self.r.local_def_id(param.id);
3073
3074                // Plain insert (no renaming).
3075                let (rib, def_kind) = match param.kind {
3076                    GenericParamKind::Type { .. } => (&mut function_type_rib, DefKind::TyParam),
3077                    GenericParamKind::Const { .. } => {
3078                        (&mut function_value_rib, DefKind::ConstParam)
3079                    }
3080                    GenericParamKind::Lifetime => {
3081                        let res = LifetimeRes::Param { param: def_id, binder };
3082                        self.record_lifetime_param(param.id, res);
3083                        function_lifetime_rib.bindings.insert(ident, (param.id, res));
3084                        continue;
3085                    }
3086                };
3087
3088                let res = match kind {
3089                    RibKind::Item(..) | RibKind::AssocItem => {
3090                        Res::Def(def_kind, def_id.to_def_id())
3091                    }
3092                    RibKind::Normal => {
3093                        // FIXME(non_lifetime_binders): Stop special-casing
3094                        // const params to error out here.
3095                        if self.r.tcx.features().non_lifetime_binders()
3096                            && matches!(param.kind, GenericParamKind::Type { .. })
3097                        {
3098                            Res::Def(def_kind, def_id.to_def_id())
3099                        } else {
3100                            Res::Err
3101                        }
3102                    }
3103                    _ => span_bug!(param.ident.span, "Unexpected rib kind {:?}", kind),
3104                };
3105                self.r.record_partial_res(param.id, PartialRes::new(res));
3106                rib.bindings.insert(ident, res);
3107            }
3108        }
3109
3110        self.lifetime_ribs.push(function_lifetime_rib);
3111        self.ribs[ValueNS].push(function_value_rib);
3112        self.ribs[TypeNS].push(function_type_rib);
3113
3114        f(self);
3115
3116        self.ribs[TypeNS].pop();
3117        self.ribs[ValueNS].pop();
3118        let function_lifetime_rib = self.lifetime_ribs.pop().unwrap();
3119
3120        // Do not account for the parameters we just bound for function lifetime elision.
3121        if let Some(ref mut candidates) = self.lifetime_elision_candidates {
3122            for (_, res) in function_lifetime_rib.bindings.values() {
3123                candidates.retain(|(r, _)| r != res);
3124            }
3125        }
3126
3127        if let LifetimeBinderKind::FnPtrType
3128        | LifetimeBinderKind::WhereBound
3129        | LifetimeBinderKind::Function
3130        | LifetimeBinderKind::ImplBlock = generics_kind
3131        {
3132            self.maybe_report_lifetime_uses(generics_span, params)
3133        }
3134    }
3135
3136    fn with_label_rib(&mut self, kind: RibKind<'ra>, f: impl FnOnce(&mut Self)) {
3137        self.label_ribs.push(Rib::new(kind));
3138        f(self);
3139        self.label_ribs.pop();
3140    }
3141
3142    fn with_static_rib(&mut self, def_kind: DefKind, f: impl FnOnce(&mut Self)) {
3143        let kind = RibKind::Item(HasGenericParams::No, def_kind);
3144        self.with_rib(ValueNS, kind, |this| this.with_rib(TypeNS, kind, f))
3145    }
3146
3147    // HACK(min_const_generics, generic_const_exprs): We
3148    // want to keep allowing `[0; size_of::<*mut T>()]`
3149    // with a future compat lint for now. We do this by adding an
3150    // additional special case for repeat expressions.
3151    //
3152    // Note that we intentionally still forbid `[0; N + 1]` during
3153    // name resolution so that we don't extend the future
3154    // compat lint to new cases.
3155    #[instrument(level = "debug", skip(self, f))]
3156    fn with_constant_rib(
3157        &mut self,
3158        is_repeat: IsRepeatExpr,
3159        may_use_generics: ConstantHasGenerics,
3160        item: Option<(Ident, ConstantItemKind)>,
3161        f: impl FnOnce(&mut Self),
3162    ) {
3163        let f = |this: &mut Self| {
3164            this.with_rib(ValueNS, RibKind::ConstantItem(may_use_generics, item), |this| {
3165                this.with_rib(
3166                    TypeNS,
3167                    RibKind::ConstantItem(
3168                        may_use_generics.force_yes_if(is_repeat == IsRepeatExpr::Yes),
3169                        item,
3170                    ),
3171                    |this| {
3172                        this.with_label_rib(RibKind::ConstantItem(may_use_generics, item), f);
3173                    },
3174                )
3175            })
3176        };
3177
3178        if let ConstantHasGenerics::No(cause) = may_use_generics {
3179            self.with_lifetime_rib(LifetimeRibKind::ConcreteAnonConst(cause), f)
3180        } else {
3181            f(self)
3182        }
3183    }
3184
3185    fn with_current_self_type<T>(&mut self, self_type: &Ty, f: impl FnOnce(&mut Self) -> T) -> T {
3186        // Handle nested impls (inside fn bodies)
3187        let previous_value =
3188            replace(&mut self.diag_metadata.current_self_type, Some(self_type.clone()));
3189        let result = f(self);
3190        self.diag_metadata.current_self_type = previous_value;
3191        result
3192    }
3193
3194    fn with_current_self_item<T>(&mut self, self_item: &Item, f: impl FnOnce(&mut Self) -> T) -> T {
3195        let previous_value = replace(&mut self.diag_metadata.current_self_item, Some(self_item.id));
3196        let result = f(self);
3197        self.diag_metadata.current_self_item = previous_value;
3198        result
3199    }
3200
3201    /// When evaluating a `trait` use its associated types' idents for suggestions in E0425.
3202    fn resolve_trait_items(&mut self, trait_items: &'ast [Box<AssocItem>]) {
3203        let trait_assoc_items =
3204            replace(&mut self.diag_metadata.current_trait_assoc_items, Some(trait_items));
3205
3206        let walk_assoc_item =
3207            |this: &mut Self, generics: &Generics, kind, item: &'ast AssocItem| {
3208                this.with_generic_param_rib(
3209                    &generics.params,
3210                    RibKind::AssocItem,
3211                    item.id,
3212                    kind,
3213                    generics.span,
3214                    |this| visit::walk_assoc_item(this, item, AssocCtxt::Trait),
3215                );
3216            };
3217
3218        for item in trait_items {
3219            self.resolve_doc_links(&item.attrs, MaybeExported::Ok(item.id));
3220            match &item.kind {
3221                AssocItemKind::Const(box ast::ConstItem {
3222                    generics,
3223                    ty,
3224                    rhs,
3225                    define_opaque,
3226                    ..
3227                }) => {
3228                    let is_type_const = attr::contains_name(&item.attrs, sym::type_const);
3229                    self.with_generic_param_rib(
3230                        &generics.params,
3231                        RibKind::AssocItem,
3232                        item.id,
3233                        LifetimeBinderKind::ConstItem,
3234                        generics.span,
3235                        |this| {
3236                            this.with_lifetime_rib(
3237                                LifetimeRibKind::StaticIfNoLifetimeInScope {
3238                                    lint_id: item.id,
3239                                    emit_lint: false,
3240                                },
3241                                |this| {
3242                                    this.visit_generics(generics);
3243                                    if is_type_const
3244                                        && !this.r.tcx.features().generic_const_parameter_types()
3245                                    {
3246                                        this.with_rib(TypeNS, RibKind::ConstParamTy, |this| {
3247                                            this.with_rib(ValueNS, RibKind::ConstParamTy, |this| {
3248                                                this.with_lifetime_rib(
3249                                                    LifetimeRibKind::ConstParamTy,
3250                                                    |this| this.visit_ty(ty),
3251                                                )
3252                                            })
3253                                        });
3254                                    } else {
3255                                        this.visit_ty(ty);
3256                                    }
3257
3258                                    // Only impose the restrictions of `ConstRibKind` for an
3259                                    // actual constant expression in a provided default.
3260                                    if let Some(rhs) = rhs {
3261                                        // We allow arbitrary const expressions inside of associated consts,
3262                                        // even if they are potentially not const evaluatable.
3263                                        //
3264                                        // Type parameters can already be used and as associated consts are
3265                                        // not used as part of the type system, this is far less surprising.
3266                                        this.resolve_const_item_rhs(rhs, None);
3267                                    }
3268                                },
3269                            )
3270                        },
3271                    );
3272
3273                    self.resolve_define_opaques(define_opaque);
3274                }
3275                AssocItemKind::Fn(box Fn { generics, define_opaque, .. }) => {
3276                    walk_assoc_item(self, generics, LifetimeBinderKind::Function, item);
3277
3278                    self.resolve_define_opaques(define_opaque);
3279                }
3280                AssocItemKind::Delegation(delegation) => {
3281                    self.with_generic_param_rib(
3282                        &[],
3283                        RibKind::AssocItem,
3284                        item.id,
3285                        LifetimeBinderKind::Function,
3286                        delegation.path.segments.last().unwrap().ident.span,
3287                        |this| this.resolve_delegation(delegation, item.id, false, &item.attrs),
3288                    );
3289                }
3290                AssocItemKind::Type(box TyAlias { generics, .. }) => self
3291                    .with_lifetime_rib(LifetimeRibKind::AnonymousReportError, |this| {
3292                        walk_assoc_item(this, generics, LifetimeBinderKind::Item, item)
3293                    }),
3294                AssocItemKind::MacCall(_) | AssocItemKind::DelegationMac(..) => {
3295                    panic!("unexpanded macro in resolve!")
3296                }
3297            };
3298        }
3299
3300        self.diag_metadata.current_trait_assoc_items = trait_assoc_items;
3301    }
3302
3303    /// This is called to resolve a trait reference from an `impl` (i.e., `impl Trait for Foo`).
3304    fn with_optional_trait_ref<T>(
3305        &mut self,
3306        opt_trait_ref: Option<&TraitRef>,
3307        self_type: &'ast Ty,
3308        f: impl FnOnce(&mut Self, Option<DefId>) -> T,
3309    ) -> T {
3310        let mut new_val = None;
3311        let mut new_id = None;
3312        if let Some(trait_ref) = opt_trait_ref {
3313            let path: Vec<_> = Segment::from_path(&trait_ref.path);
3314            self.diag_metadata.currently_processing_impl_trait =
3315                Some((trait_ref.clone(), self_type.clone()));
3316            let res = self.smart_resolve_path_fragment(
3317                &None,
3318                &path,
3319                PathSource::Trait(AliasPossibility::No),
3320                Finalize::new(trait_ref.ref_id, trait_ref.path.span),
3321                RecordPartialRes::Yes,
3322                None,
3323            );
3324            self.diag_metadata.currently_processing_impl_trait = None;
3325            if let Some(def_id) = res.expect_full_res().opt_def_id() {
3326                new_id = Some(def_id);
3327                new_val = Some((self.r.expect_module(def_id), trait_ref.clone()));
3328            }
3329        }
3330        let original_trait_ref = replace(&mut self.current_trait_ref, new_val);
3331        let result = f(self, new_id);
3332        self.current_trait_ref = original_trait_ref;
3333        result
3334    }
3335
3336    fn with_self_rib_ns(&mut self, ns: Namespace, self_res: Res, f: impl FnOnce(&mut Self)) {
3337        let mut self_type_rib = Rib::new(RibKind::Normal);
3338
3339        // Plain insert (no renaming, since types are not currently hygienic)
3340        self_type_rib.bindings.insert(Ident::with_dummy_span(kw::SelfUpper), self_res);
3341        self.ribs[ns].push(self_type_rib);
3342        f(self);
3343        self.ribs[ns].pop();
3344    }
3345
3346    fn with_self_rib(&mut self, self_res: Res, f: impl FnOnce(&mut Self)) {
3347        self.with_self_rib_ns(TypeNS, self_res, f)
3348    }
3349
3350    fn resolve_implementation(
3351        &mut self,
3352        attrs: &[ast::Attribute],
3353        generics: &'ast Generics,
3354        of_trait: Option<&'ast ast::TraitImplHeader>,
3355        self_type: &'ast Ty,
3356        item_id: NodeId,
3357        impl_items: &'ast [Box<AssocItem>],
3358    ) {
3359        debug!("resolve_implementation");
3360        // If applicable, create a rib for the type parameters.
3361        self.with_generic_param_rib(
3362            &generics.params,
3363            RibKind::Item(HasGenericParams::Yes(generics.span), self.r.local_def_kind(item_id)),
3364            item_id,
3365            LifetimeBinderKind::ImplBlock,
3366            generics.span,
3367            |this| {
3368                // Dummy self type for better errors if `Self` is used in the trait path.
3369                this.with_self_rib(Res::SelfTyParam { trait_: LOCAL_CRATE.as_def_id() }, |this| {
3370                    this.with_lifetime_rib(
3371                        LifetimeRibKind::AnonymousCreateParameter {
3372                            binder: item_id,
3373                            report_in_path: true
3374                        },
3375                        |this| {
3376                            // Resolve the trait reference, if necessary.
3377                            this.with_optional_trait_ref(
3378                                of_trait.map(|t| &t.trait_ref),
3379                                self_type,
3380                                |this, trait_id| {
3381                                    this.resolve_doc_links(attrs, MaybeExported::Impl(trait_id));
3382
3383                                    let item_def_id = this.r.local_def_id(item_id);
3384
3385                                    // Register the trait definitions from here.
3386                                    if let Some(trait_id) = trait_id {
3387                                        this.r
3388                                            .trait_impls
3389                                            .entry(trait_id)
3390                                            .or_default()
3391                                            .push(item_def_id);
3392                                    }
3393
3394                                    let item_def_id = item_def_id.to_def_id();
3395                                    let res = Res::SelfTyAlias {
3396                                        alias_to: item_def_id,
3397                                        is_trait_impl: trait_id.is_some(),
3398                                    };
3399                                    this.with_self_rib(res, |this| {
3400                                        if let Some(of_trait) = of_trait {
3401                                            // Resolve type arguments in the trait path.
3402                                            visit::walk_trait_ref(this, &of_trait.trait_ref);
3403                                        }
3404                                        // Resolve the self type.
3405                                        this.visit_ty(self_type);
3406                                        // Resolve the generic parameters.
3407                                        this.visit_generics(generics);
3408
3409                                        // Resolve the items within the impl.
3410                                        this.with_current_self_type(self_type, |this| {
3411                                            this.with_self_rib_ns(ValueNS, Res::SelfCtor(item_def_id), |this| {
3412                                                debug!("resolve_implementation with_self_rib_ns(ValueNS, ...)");
3413                                                let mut seen_trait_items = Default::default();
3414                                                for item in impl_items {
3415                                                    this.resolve_impl_item(&**item, &mut seen_trait_items, trait_id, of_trait.is_some());
3416                                                }
3417                                            });
3418                                        });
3419                                    });
3420                                },
3421                            )
3422                        },
3423                    );
3424                });
3425            },
3426        );
3427    }
3428
3429    fn resolve_impl_item(
3430        &mut self,
3431        item: &'ast AssocItem,
3432        seen_trait_items: &mut FxHashMap<DefId, Span>,
3433        trait_id: Option<DefId>,
3434        is_in_trait_impl: bool,
3435    ) {
3436        use crate::ResolutionError::*;
3437        self.resolve_doc_links(&item.attrs, MaybeExported::ImplItem(trait_id.ok_or(&item.vis)));
3438        let prev = self.diag_metadata.current_impl_item.take();
3439        self.diag_metadata.current_impl_item = Some(&item);
3440        match &item.kind {
3441            AssocItemKind::Const(box ast::ConstItem {
3442                ident,
3443                generics,
3444                ty,
3445                rhs,
3446                define_opaque,
3447                ..
3448            }) => {
3449                debug!("resolve_implementation AssocItemKind::Const");
3450                let is_type_const = attr::contains_name(&item.attrs, sym::type_const);
3451                self.with_generic_param_rib(
3452                    &generics.params,
3453                    RibKind::AssocItem,
3454                    item.id,
3455                    LifetimeBinderKind::ConstItem,
3456                    generics.span,
3457                    |this| {
3458                        this.with_lifetime_rib(
3459                            // Until these are a hard error, we need to create them within the
3460                            // correct binder, Otherwise the lifetimes of this assoc const think
3461                            // they are lifetimes of the trait.
3462                            LifetimeRibKind::AnonymousCreateParameter {
3463                                binder: item.id,
3464                                report_in_path: true,
3465                            },
3466                            |this| {
3467                                this.with_lifetime_rib(
3468                                    LifetimeRibKind::StaticIfNoLifetimeInScope {
3469                                        lint_id: item.id,
3470                                        // In impls, it's not a hard error yet due to backcompat.
3471                                        emit_lint: true,
3472                                    },
3473                                    |this| {
3474                                        // If this is a trait impl, ensure the const
3475                                        // exists in trait
3476                                        this.check_trait_item(
3477                                            item.id,
3478                                            *ident,
3479                                            &item.kind,
3480                                            ValueNS,
3481                                            item.span,
3482                                            seen_trait_items,
3483                                            |i, s, c| ConstNotMemberOfTrait(i, s, c),
3484                                        );
3485
3486                                        this.visit_generics(generics);
3487                                        if is_type_const
3488                                            && !this
3489                                                .r
3490                                                .tcx
3491                                                .features()
3492                                                .generic_const_parameter_types()
3493                                        {
3494                                            this.with_rib(TypeNS, RibKind::ConstParamTy, |this| {
3495                                                this.with_rib(
3496                                                    ValueNS,
3497                                                    RibKind::ConstParamTy,
3498                                                    |this| {
3499                                                        this.with_lifetime_rib(
3500                                                            LifetimeRibKind::ConstParamTy,
3501                                                            |this| this.visit_ty(ty),
3502                                                        )
3503                                                    },
3504                                                )
3505                                            });
3506                                        } else {
3507                                            this.visit_ty(ty);
3508                                        }
3509                                        if let Some(rhs) = rhs {
3510                                            // We allow arbitrary const expressions inside of associated consts,
3511                                            // even if they are potentially not const evaluatable.
3512                                            //
3513                                            // Type parameters can already be used and as associated consts are
3514                                            // not used as part of the type system, this is far less surprising.
3515                                            this.resolve_const_item_rhs(rhs, None);
3516                                        }
3517                                    },
3518                                )
3519                            },
3520                        );
3521                    },
3522                );
3523                self.resolve_define_opaques(define_opaque);
3524            }
3525            AssocItemKind::Fn(box Fn { ident, generics, define_opaque, .. }) => {
3526                debug!("resolve_implementation AssocItemKind::Fn");
3527                // We also need a new scope for the impl item type parameters.
3528                self.with_generic_param_rib(
3529                    &generics.params,
3530                    RibKind::AssocItem,
3531                    item.id,
3532                    LifetimeBinderKind::Function,
3533                    generics.span,
3534                    |this| {
3535                        // If this is a trait impl, ensure the method
3536                        // exists in trait
3537                        this.check_trait_item(
3538                            item.id,
3539                            *ident,
3540                            &item.kind,
3541                            ValueNS,
3542                            item.span,
3543                            seen_trait_items,
3544                            |i, s, c| MethodNotMemberOfTrait(i, s, c),
3545                        );
3546
3547                        visit::walk_assoc_item(this, item, AssocCtxt::Impl { of_trait: true })
3548                    },
3549                );
3550
3551                self.resolve_define_opaques(define_opaque);
3552            }
3553            AssocItemKind::Type(box TyAlias { ident, generics, .. }) => {
3554                self.diag_metadata.in_non_gat_assoc_type = Some(generics.params.is_empty());
3555                debug!("resolve_implementation AssocItemKind::Type");
3556                // We also need a new scope for the impl item type parameters.
3557                self.with_generic_param_rib(
3558                    &generics.params,
3559                    RibKind::AssocItem,
3560                    item.id,
3561                    LifetimeBinderKind::ImplAssocType,
3562                    generics.span,
3563                    |this| {
3564                        this.with_lifetime_rib(LifetimeRibKind::AnonymousReportError, |this| {
3565                            // If this is a trait impl, ensure the type
3566                            // exists in trait
3567                            this.check_trait_item(
3568                                item.id,
3569                                *ident,
3570                                &item.kind,
3571                                TypeNS,
3572                                item.span,
3573                                seen_trait_items,
3574                                |i, s, c| TypeNotMemberOfTrait(i, s, c),
3575                            );
3576
3577                            visit::walk_assoc_item(this, item, AssocCtxt::Impl { of_trait: true })
3578                        });
3579                    },
3580                );
3581                self.diag_metadata.in_non_gat_assoc_type = None;
3582            }
3583            AssocItemKind::Delegation(box delegation) => {
3584                debug!("resolve_implementation AssocItemKind::Delegation");
3585                self.with_generic_param_rib(
3586                    &[],
3587                    RibKind::AssocItem,
3588                    item.id,
3589                    LifetimeBinderKind::Function,
3590                    delegation.path.segments.last().unwrap().ident.span,
3591                    |this| {
3592                        this.check_trait_item(
3593                            item.id,
3594                            delegation.ident,
3595                            &item.kind,
3596                            ValueNS,
3597                            item.span,
3598                            seen_trait_items,
3599                            |i, s, c| MethodNotMemberOfTrait(i, s, c),
3600                        );
3601
3602                        // Here we don't use `trait_id`, as we can process unresolved trait, however
3603                        // in this case we are still in a trait impl, https://github.com/rust-lang/rust/issues/150152
3604                        this.resolve_delegation(delegation, item.id, is_in_trait_impl, &item.attrs);
3605                    },
3606                );
3607            }
3608            AssocItemKind::MacCall(_) | AssocItemKind::DelegationMac(..) => {
3609                panic!("unexpanded macro in resolve!")
3610            }
3611        }
3612        self.diag_metadata.current_impl_item = prev;
3613    }
3614
3615    fn check_trait_item<F>(
3616        &mut self,
3617        id: NodeId,
3618        mut ident: Ident,
3619        kind: &AssocItemKind,
3620        ns: Namespace,
3621        span: Span,
3622        seen_trait_items: &mut FxHashMap<DefId, Span>,
3623        err: F,
3624    ) where
3625        F: FnOnce(Ident, String, Option<Symbol>) -> ResolutionError<'ra>,
3626    {
3627        // If there is a TraitRef in scope for an impl, then the method must be in the trait.
3628        let Some((module, _)) = self.current_trait_ref else {
3629            return;
3630        };
3631        ident.span.normalize_to_macros_2_0_and_adjust(module.expansion);
3632        let key = BindingKey::new(ident, ns);
3633        let mut decl = self.r.resolution(module, key).and_then(|r| r.best_decl());
3634        debug!(?decl);
3635        if decl.is_none() {
3636            // We could not find the trait item in the correct namespace.
3637            // Check the other namespace to report an error.
3638            let ns = match ns {
3639                ValueNS => TypeNS,
3640                TypeNS => ValueNS,
3641                _ => ns,
3642            };
3643            let key = BindingKey::new(ident, ns);
3644            decl = self.r.resolution(module, key).and_then(|r| r.best_decl());
3645            debug!(?decl);
3646        }
3647
3648        let feed_visibility = |this: &mut Self, def_id| {
3649            let vis = this.r.tcx.visibility(def_id);
3650            let vis = if vis.is_visible_locally() {
3651                vis.expect_local()
3652            } else {
3653                this.r.dcx().span_delayed_bug(
3654                    span,
3655                    "error should be emitted when an unexpected trait item is used",
3656                );
3657                Visibility::Public
3658            };
3659            this.r.feed_visibility(this.r.feed(id), vis);
3660        };
3661
3662        let Some(decl) = decl else {
3663            // We could not find the method: report an error.
3664            let candidate = self.find_similarly_named_assoc_item(ident.name, kind);
3665            let path = &self.current_trait_ref.as_ref().unwrap().1.path;
3666            let path_names = path_names_to_string(path);
3667            self.report_error(span, err(ident, path_names, candidate));
3668            feed_visibility(self, module.def_id());
3669            return;
3670        };
3671
3672        let res = decl.res();
3673        let Res::Def(def_kind, id_in_trait) = res else { bug!() };
3674        feed_visibility(self, id_in_trait);
3675
3676        match seen_trait_items.entry(id_in_trait) {
3677            Entry::Occupied(entry) => {
3678                self.report_error(
3679                    span,
3680                    ResolutionError::TraitImplDuplicate {
3681                        name: ident,
3682                        old_span: *entry.get(),
3683                        trait_item_span: decl.span,
3684                    },
3685                );
3686                return;
3687            }
3688            Entry::Vacant(entry) => {
3689                entry.insert(span);
3690            }
3691        };
3692
3693        match (def_kind, kind) {
3694            (DefKind::AssocTy, AssocItemKind::Type(..))
3695            | (DefKind::AssocFn, AssocItemKind::Fn(..))
3696            | (DefKind::AssocConst, AssocItemKind::Const(..))
3697            | (DefKind::AssocFn, AssocItemKind::Delegation(..)) => {
3698                self.r.record_partial_res(id, PartialRes::new(res));
3699                return;
3700            }
3701            _ => {}
3702        }
3703
3704        // The method kind does not correspond to what appeared in the trait, report.
3705        let path = &self.current_trait_ref.as_ref().unwrap().1.path;
3706        let (code, kind) = match kind {
3707            AssocItemKind::Const(..) => (E0323, "const"),
3708            AssocItemKind::Fn(..) => (E0324, "method"),
3709            AssocItemKind::Type(..) => (E0325, "type"),
3710            AssocItemKind::Delegation(..) => (E0324, "method"),
3711            AssocItemKind::MacCall(..) | AssocItemKind::DelegationMac(..) => {
3712                span_bug!(span, "unexpanded macro")
3713            }
3714        };
3715        let trait_path = path_names_to_string(path);
3716        self.report_error(
3717            span,
3718            ResolutionError::TraitImplMismatch {
3719                name: ident,
3720                kind,
3721                code,
3722                trait_path,
3723                trait_item_span: decl.span,
3724            },
3725        );
3726    }
3727
3728    fn resolve_static_body(&mut self, expr: &'ast Expr, item: Option<(Ident, ConstantItemKind)>) {
3729        self.with_lifetime_rib(LifetimeRibKind::Elided(LifetimeRes::Infer), |this| {
3730            this.with_constant_rib(IsRepeatExpr::No, ConstantHasGenerics::Yes, item, |this| {
3731                this.visit_expr(expr)
3732            });
3733        })
3734    }
3735
3736    fn resolve_const_item_rhs(
3737        &mut self,
3738        rhs: &'ast ConstItemRhs,
3739        item: Option<(Ident, ConstantItemKind)>,
3740    ) {
3741        self.with_lifetime_rib(LifetimeRibKind::Elided(LifetimeRes::Infer), |this| match rhs {
3742            ConstItemRhs::TypeConst(anon_const) => {
3743                this.resolve_anon_const(anon_const, AnonConstKind::ConstArg(IsRepeatExpr::No));
3744            }
3745            ConstItemRhs::Body(expr) => {
3746                this.with_constant_rib(IsRepeatExpr::No, ConstantHasGenerics::Yes, item, |this| {
3747                    this.visit_expr(expr)
3748                });
3749            }
3750        })
3751    }
3752
3753    fn resolve_delegation(
3754        &mut self,
3755        delegation: &'ast Delegation,
3756        item_id: NodeId,
3757        is_in_trait_impl: bool,
3758        attrs: &[Attribute],
3759    ) {
3760        self.smart_resolve_path(
3761            delegation.id,
3762            &delegation.qself,
3763            &delegation.path,
3764            PathSource::Delegation,
3765        );
3766
3767        if let Some(qself) = &delegation.qself {
3768            self.visit_ty(&qself.ty);
3769        }
3770
3771        self.visit_path(&delegation.path);
3772
3773        self.r.delegation_infos.insert(
3774            self.r.local_def_id(item_id),
3775            DelegationInfo {
3776                attrs: create_delegation_attrs(attrs),
3777                resolution_node: if is_in_trait_impl { item_id } else { delegation.id },
3778            },
3779        );
3780
3781        let Some(body) = &delegation.body else { return };
3782        self.with_rib(ValueNS, RibKind::FnOrCoroutine, |this| {
3783            let span = delegation.path.segments.last().unwrap().ident.span;
3784            let ident = Ident::new(kw::SelfLower, span.normalize_to_macro_rules());
3785            let res = Res::Local(delegation.id);
3786            this.innermost_rib_bindings(ValueNS).insert(ident, res);
3787
3788            //As we lower target_expr_template body to a body of a function we need a label rib (#148889)
3789            this.with_label_rib(RibKind::FnOrCoroutine, |this| {
3790                this.visit_block(body);
3791            });
3792        });
3793    }
3794
3795    fn resolve_params(&mut self, params: &'ast [Param]) {
3796        let mut bindings = smallvec![(PatBoundCtx::Product, Default::default())];
3797        self.with_lifetime_rib(LifetimeRibKind::Elided(LifetimeRes::Infer), |this| {
3798            for Param { pat, .. } in params {
3799                this.resolve_pattern(pat, PatternSource::FnParam, &mut bindings);
3800            }
3801            this.apply_pattern_bindings(bindings);
3802        });
3803        for Param { ty, .. } in params {
3804            self.visit_ty(ty);
3805        }
3806    }
3807
3808    fn resolve_local(&mut self, local: &'ast Local) {
3809        debug!("resolving local ({:?})", local);
3810        // Resolve the type.
3811        visit_opt!(self, visit_ty, &local.ty);
3812
3813        // Resolve the initializer.
3814        if let Some((init, els)) = local.kind.init_else_opt() {
3815            self.visit_expr(init);
3816
3817            // Resolve the `else` block
3818            if let Some(els) = els {
3819                self.visit_block(els);
3820            }
3821        }
3822
3823        // Resolve the pattern.
3824        self.resolve_pattern_top(&local.pat, PatternSource::Let);
3825    }
3826
3827    /// Build a map from pattern identifiers to binding-info's, and check the bindings are
3828    /// consistent when encountering or-patterns and never patterns.
3829    /// This is done hygienically: this could arise for a macro that expands into an or-pattern
3830    /// where one 'x' was from the user and one 'x' came from the macro.
3831    ///
3832    /// A never pattern by definition indicates an unreachable case. For example, matching on
3833    /// `Result<T, &!>` could look like:
3834    /// ```rust
3835    /// # #![feature(never_type)]
3836    /// # #![feature(never_patterns)]
3837    /// # fn bar(_x: u32) {}
3838    /// let foo: Result<u32, &!> = Ok(0);
3839    /// match foo {
3840    ///     Ok(x) => bar(x),
3841    ///     Err(&!),
3842    /// }
3843    /// ```
3844    /// This extends to product types: `(x, !)` is likewise unreachable. So it doesn't make sense to
3845    /// have a binding here, and we tell the user to use `_` instead.
3846    fn compute_and_check_binding_map(
3847        &mut self,
3848        pat: &Pat,
3849    ) -> Result<FxIndexMap<Ident, BindingInfo>, IsNeverPattern> {
3850        let mut binding_map = FxIndexMap::default();
3851        let mut is_never_pat = false;
3852
3853        pat.walk(&mut |pat| {
3854            match pat.kind {
3855                PatKind::Ident(annotation, ident, ref sub_pat)
3856                    if sub_pat.is_some() || self.is_base_res_local(pat.id) =>
3857                {
3858                    binding_map.insert(ident, BindingInfo { span: ident.span, annotation });
3859                }
3860                PatKind::Or(ref ps) => {
3861                    // Check the consistency of this or-pattern and
3862                    // then add all bindings to the larger map.
3863                    match self.compute_and_check_or_pat_binding_map(ps) {
3864                        Ok(bm) => binding_map.extend(bm),
3865                        Err(IsNeverPattern) => is_never_pat = true,
3866                    }
3867                    return false;
3868                }
3869                PatKind::Never => is_never_pat = true,
3870                _ => {}
3871            }
3872
3873            true
3874        });
3875
3876        if is_never_pat {
3877            for (_, binding) in binding_map {
3878                self.report_error(binding.span, ResolutionError::BindingInNeverPattern);
3879            }
3880            Err(IsNeverPattern)
3881        } else {
3882            Ok(binding_map)
3883        }
3884    }
3885
3886    fn is_base_res_local(&self, nid: NodeId) -> bool {
3887        matches!(
3888            self.r.partial_res_map.get(&nid).map(|res| res.expect_full_res()),
3889            Some(Res::Local(..))
3890        )
3891    }
3892
3893    /// Compute the binding map for an or-pattern. Checks that all of the arms in the or-pattern
3894    /// have exactly the same set of bindings, with the same binding modes for each.
3895    /// Returns the computed binding map and a boolean indicating whether the pattern is a never
3896    /// pattern.
3897    ///
3898    /// A never pattern by definition indicates an unreachable case. For example, destructuring a
3899    /// `Result<T, &!>` could look like:
3900    /// ```rust
3901    /// # #![feature(never_type)]
3902    /// # #![feature(never_patterns)]
3903    /// # fn foo() -> Result<bool, &'static !> { Ok(true) }
3904    /// let (Ok(x) | Err(&!)) = foo();
3905    /// # let _ = x;
3906    /// ```
3907    /// Because the `Err(&!)` branch is never reached, it does not need to have the same bindings as
3908    /// the other branches of the or-pattern. So we must ignore never pattern when checking the
3909    /// bindings of an or-pattern.
3910    /// Moreover, if all the subpatterns are never patterns (e.g. `Ok(!) | Err(!)`), then the
3911    /// pattern as a whole counts as a never pattern (since it's definitionallly unreachable).
3912    fn compute_and_check_or_pat_binding_map(
3913        &mut self,
3914        pats: &[Pat],
3915    ) -> Result<FxIndexMap<Ident, BindingInfo>, IsNeverPattern> {
3916        let mut missing_vars = FxIndexMap::default();
3917        let mut inconsistent_vars = FxIndexMap::default();
3918
3919        // 1) Compute the binding maps of all arms; we must ignore never patterns here.
3920        let not_never_pats = pats
3921            .iter()
3922            .filter_map(|pat| {
3923                let binding_map = self.compute_and_check_binding_map(pat).ok()?;
3924                Some((binding_map, pat))
3925            })
3926            .collect::<Vec<_>>();
3927
3928        // 2) Record any missing bindings or binding mode inconsistencies.
3929        for &(ref map_outer, pat_outer) in not_never_pats.iter() {
3930            // Check against all arms except for the same pattern which is always self-consistent.
3931            let inners = not_never_pats.iter().filter(|(_, pat)| pat.id != pat_outer.id);
3932
3933            for &(ref map, pat) in inners {
3934                for (&name, binding_inner) in map {
3935                    match map_outer.get(&name) {
3936                        None => {
3937                            // The inner binding is missing in the outer.
3938                            let binding_error =
3939                                missing_vars.entry(name).or_insert_with(|| BindingError {
3940                                    name,
3941                                    origin: Default::default(),
3942                                    target: Default::default(),
3943                                    could_be_path: name.as_str().starts_with(char::is_uppercase),
3944                                });
3945                            binding_error.origin.push((binding_inner.span, pat.clone()));
3946                            binding_error.target.push(pat_outer.clone());
3947                        }
3948                        Some(binding_outer) => {
3949                            if binding_outer.annotation != binding_inner.annotation {
3950                                // The binding modes in the outer and inner bindings differ.
3951                                inconsistent_vars
3952                                    .entry(name)
3953                                    .or_insert((binding_inner.span, binding_outer.span));
3954                            }
3955                        }
3956                    }
3957                }
3958            }
3959        }
3960
3961        // 3) Report all missing variables we found.
3962        for (name, mut v) in missing_vars {
3963            if inconsistent_vars.contains_key(&name) {
3964                v.could_be_path = false;
3965            }
3966            self.report_error(
3967                v.origin.iter().next().unwrap().0,
3968                ResolutionError::VariableNotBoundInPattern(v, self.parent_scope),
3969            );
3970        }
3971
3972        // 4) Report all inconsistencies in binding modes we found.
3973        for (name, v) in inconsistent_vars {
3974            self.report_error(v.0, ResolutionError::VariableBoundWithDifferentMode(name, v.1));
3975        }
3976
3977        // 5) Bubble up the final binding map.
3978        if not_never_pats.is_empty() {
3979            // All the patterns are never patterns, so the whole or-pattern is one too.
3980            Err(IsNeverPattern)
3981        } else {
3982            let mut binding_map = FxIndexMap::default();
3983            for (bm, _) in not_never_pats {
3984                binding_map.extend(bm);
3985            }
3986            Ok(binding_map)
3987        }
3988    }
3989
3990    /// Check the consistency of bindings wrt or-patterns and never patterns.
3991    fn check_consistent_bindings(&mut self, pat: &'ast Pat) {
3992        let mut is_or_or_never = false;
3993        pat.walk(&mut |pat| match pat.kind {
3994            PatKind::Or(..) | PatKind::Never => {
3995                is_or_or_never = true;
3996                false
3997            }
3998            _ => true,
3999        });
4000        if is_or_or_never {
4001            let _ = self.compute_and_check_binding_map(pat);
4002        }
4003    }
4004
4005    fn resolve_arm(&mut self, arm: &'ast Arm) {
4006        self.with_rib(ValueNS, RibKind::Normal, |this| {
4007            this.resolve_pattern_top(&arm.pat, PatternSource::Match);
4008            visit_opt!(this, visit_expr, &arm.guard);
4009            visit_opt!(this, visit_expr, &arm.body);
4010        });
4011    }
4012
4013    /// Arising from `source`, resolve a top level pattern.
4014    fn resolve_pattern_top(&mut self, pat: &'ast Pat, pat_src: PatternSource) {
4015        let mut bindings = smallvec![(PatBoundCtx::Product, Default::default())];
4016        self.resolve_pattern(pat, pat_src, &mut bindings);
4017        self.apply_pattern_bindings(bindings);
4018    }
4019
4020    /// Apply the bindings from a pattern to the innermost rib of the current scope.
4021    fn apply_pattern_bindings(&mut self, mut pat_bindings: PatternBindings) {
4022        let rib_bindings = self.innermost_rib_bindings(ValueNS);
4023        let Some((_, pat_bindings)) = pat_bindings.pop() else {
4024            bug!("tried applying nonexistent bindings from pattern");
4025        };
4026
4027        if rib_bindings.is_empty() {
4028            // Often, such as for match arms, the bindings are introduced into a new rib.
4029            // In this case, we can move the bindings over directly.
4030            *rib_bindings = pat_bindings;
4031        } else {
4032            rib_bindings.extend(pat_bindings);
4033        }
4034    }
4035
4036    /// Resolve bindings in a pattern. `apply_pattern_bindings` must be called after to introduce
4037    /// the bindings into scope.
4038    fn resolve_pattern(
4039        &mut self,
4040        pat: &'ast Pat,
4041        pat_src: PatternSource,
4042        bindings: &mut PatternBindings,
4043    ) {
4044        // We walk the pattern before declaring the pattern's inner bindings,
4045        // so that we avoid resolving a literal expression to a binding defined
4046        // by the pattern.
4047        // NB: `Self::visit_pat` must be used rather than `visit::walk_pat` to avoid resolving guard
4048        // patterns' guard expressions multiple times (#141265).
4049        self.visit_pat(pat);
4050        self.resolve_pattern_inner(pat, pat_src, bindings);
4051        // This has to happen *after* we determine which pat_idents are variants:
4052        self.check_consistent_bindings(pat);
4053    }
4054
4055    /// Resolve bindings in a pattern. This is a helper to `resolve_pattern`.
4056    ///
4057    /// ### `bindings`
4058    ///
4059    /// A stack of sets of bindings accumulated.
4060    ///
4061    /// In each set, `PatBoundCtx::Product` denotes that a found binding in it should
4062    /// be interpreted as re-binding an already bound binding. This results in an error.
4063    /// Meanwhile, `PatBound::Or` denotes that a found binding in the set should result
4064    /// in reusing this binding rather than creating a fresh one.
4065    ///
4066    /// When called at the top level, the stack must have a single element
4067    /// with `PatBound::Product`. Otherwise, pushing to the stack happens as
4068    /// or-patterns (`p_0 | ... | p_n`) are encountered and the context needs
4069    /// to be switched to `PatBoundCtx::Or` and then `PatBoundCtx::Product` for each `p_i`.
4070    /// When each `p_i` has been dealt with, the top set is merged with its parent.
4071    /// When a whole or-pattern has been dealt with, the thing happens.
4072    ///
4073    /// See the implementation and `fresh_binding` for more details.
4074    #[tracing::instrument(skip(self, bindings), level = "debug")]
4075    fn resolve_pattern_inner(
4076        &mut self,
4077        pat: &'ast Pat,
4078        pat_src: PatternSource,
4079        bindings: &mut PatternBindings,
4080    ) {
4081        // Visit all direct subpatterns of this pattern.
4082        pat.walk(&mut |pat| {
4083            match pat.kind {
4084                PatKind::Ident(bmode, ident, ref sub) => {
4085                    // First try to resolve the identifier as some existing entity,
4086                    // then fall back to a fresh binding.
4087                    let has_sub = sub.is_some();
4088                    let res = self
4089                        .try_resolve_as_non_binding(pat_src, bmode, ident, has_sub)
4090                        .unwrap_or_else(|| self.fresh_binding(ident, pat.id, pat_src, bindings));
4091                    self.r.record_partial_res(pat.id, PartialRes::new(res));
4092                    self.r.record_pat_span(pat.id, pat.span);
4093                }
4094                PatKind::TupleStruct(ref qself, ref path, ref sub_patterns) => {
4095                    self.smart_resolve_path(
4096                        pat.id,
4097                        qself,
4098                        path,
4099                        PathSource::TupleStruct(
4100                            pat.span,
4101                            self.r.arenas.alloc_pattern_spans(sub_patterns.iter().map(|p| p.span)),
4102                        ),
4103                    );
4104                }
4105                PatKind::Path(ref qself, ref path) => {
4106                    self.smart_resolve_path(pat.id, qself, path, PathSource::Pat);
4107                }
4108                PatKind::Struct(ref qself, ref path, ref _fields, ref rest) => {
4109                    self.smart_resolve_path(pat.id, qself, path, PathSource::Struct(None));
4110                    self.record_patterns_with_skipped_bindings(pat, rest);
4111                }
4112                PatKind::Or(ref ps) => {
4113                    // Add a new set of bindings to the stack. `Or` here records that when a
4114                    // binding already exists in this set, it should not result in an error because
4115                    // `V1(a) | V2(a)` must be allowed and are checked for consistency later.
4116                    bindings.push((PatBoundCtx::Or, Default::default()));
4117                    for p in ps {
4118                        // Now we need to switch back to a product context so that each
4119                        // part of the or-pattern internally rejects already bound names.
4120                        // For example, `V1(a) | V2(a, a)` and `V1(a, a) | V2(a)` are bad.
4121                        bindings.push((PatBoundCtx::Product, Default::default()));
4122                        self.resolve_pattern_inner(p, pat_src, bindings);
4123                        // Move up the non-overlapping bindings to the or-pattern.
4124                        // Existing bindings just get "merged".
4125                        let collected = bindings.pop().unwrap().1;
4126                        bindings.last_mut().unwrap().1.extend(collected);
4127                    }
4128                    // This or-pattern itself can itself be part of a product,
4129                    // e.g. `(V1(a) | V2(a), a)` or `(a, V1(a) | V2(a))`.
4130                    // Both cases bind `a` again in a product pattern and must be rejected.
4131                    let collected = bindings.pop().unwrap().1;
4132                    bindings.last_mut().unwrap().1.extend(collected);
4133
4134                    // Prevent visiting `ps` as we've already done so above.
4135                    return false;
4136                }
4137                PatKind::Guard(ref subpat, ref guard) => {
4138                    // Add a new set of bindings to the stack to collect bindings in `subpat`.
4139                    bindings.push((PatBoundCtx::Product, Default::default()));
4140                    // Resolving `subpat` adds bindings onto the newly-pushed context. After, the
4141                    // total number of contexts on the stack should be the same as before.
4142                    let binding_ctx_stack_len = bindings.len();
4143                    self.resolve_pattern_inner(subpat, pat_src, bindings);
4144                    assert_eq!(bindings.len(), binding_ctx_stack_len);
4145                    // These bindings, but none from the surrounding pattern, are visible in the
4146                    // guard; put them in scope and resolve `guard`.
4147                    let subpat_bindings = bindings.pop().unwrap().1;
4148                    self.with_rib(ValueNS, RibKind::Normal, |this| {
4149                        *this.innermost_rib_bindings(ValueNS) = subpat_bindings.clone();
4150                        this.resolve_expr(guard, None);
4151                    });
4152                    // Propagate the subpattern's bindings upwards.
4153                    // FIXME(guard_patterns): For `if let` guards, we'll also need to get the
4154                    // bindings introduced by the guard from its rib and propagate them upwards.
4155                    // This will require checking the identifiers for overlaps with `bindings`, like
4156                    // what `fresh_binding` does (ideally sharing its logic). To keep them separate
4157                    // from `subpat_bindings`, we can introduce a fresh rib for the guard.
4158                    bindings.last_mut().unwrap().1.extend(subpat_bindings);
4159                    // Prevent visiting `subpat` as we've already done so above.
4160                    return false;
4161                }
4162                _ => {}
4163            }
4164            true
4165        });
4166    }
4167
4168    fn record_patterns_with_skipped_bindings(&mut self, pat: &Pat, rest: &ast::PatFieldsRest) {
4169        match rest {
4170            ast::PatFieldsRest::Rest(_) | ast::PatFieldsRest::Recovered(_) => {
4171                // Record that the pattern doesn't introduce all the bindings it could.
4172                if let Some(partial_res) = self.r.partial_res_map.get(&pat.id)
4173                    && let Some(res) = partial_res.full_res()
4174                    && let Some(def_id) = res.opt_def_id()
4175                {
4176                    self.ribs[ValueNS]
4177                        .last_mut()
4178                        .unwrap()
4179                        .patterns_with_skipped_bindings
4180                        .entry(def_id)
4181                        .or_default()
4182                        .push((
4183                            pat.span,
4184                            match rest {
4185                                ast::PatFieldsRest::Recovered(guar) => Err(*guar),
4186                                _ => Ok(()),
4187                            },
4188                        ));
4189                }
4190            }
4191            ast::PatFieldsRest::None => {}
4192        }
4193    }
4194
4195    fn fresh_binding(
4196        &mut self,
4197        ident: Ident,
4198        pat_id: NodeId,
4199        pat_src: PatternSource,
4200        bindings: &mut PatternBindings,
4201    ) -> Res {
4202        // Add the binding to the bindings map, if it doesn't already exist.
4203        // (We must not add it if it's in the bindings map because that breaks the assumptions
4204        // later passes make about or-patterns.)
4205        let ident = ident.normalize_to_macro_rules();
4206
4207        // Already bound in a product pattern? e.g. `(a, a)` which is not allowed.
4208        let already_bound_and = bindings
4209            .iter()
4210            .any(|(ctx, map)| *ctx == PatBoundCtx::Product && map.contains_key(&ident));
4211        if already_bound_and {
4212            // Overlap in a product pattern somewhere; report an error.
4213            use ResolutionError::*;
4214            let error = match pat_src {
4215                // `fn f(a: u8, a: u8)`:
4216                PatternSource::FnParam => IdentifierBoundMoreThanOnceInParameterList,
4217                // `Variant(a, a)`:
4218                _ => IdentifierBoundMoreThanOnceInSamePattern,
4219            };
4220            self.report_error(ident.span, error(ident));
4221        }
4222
4223        // Already bound in an or-pattern? e.g. `V1(a) | V2(a)`.
4224        // This is *required* for consistency which is checked later.
4225        let already_bound_or = bindings
4226            .iter()
4227            .find_map(|(ctx, map)| if *ctx == PatBoundCtx::Or { map.get(&ident) } else { None });
4228        let res = if let Some(&res) = already_bound_or {
4229            // `Variant1(a) | Variant2(a)`, ok
4230            // Reuse definition from the first `a`.
4231            res
4232        } else {
4233            // A completely fresh binding is added to the map.
4234            Res::Local(pat_id)
4235        };
4236
4237        // Record as bound.
4238        bindings.last_mut().unwrap().1.insert(ident, res);
4239        res
4240    }
4241
4242    fn innermost_rib_bindings(&mut self, ns: Namespace) -> &mut FxIndexMap<Ident, Res> {
4243        &mut self.ribs[ns].last_mut().unwrap().bindings
4244    }
4245
4246    fn try_resolve_as_non_binding(
4247        &mut self,
4248        pat_src: PatternSource,
4249        ann: BindingMode,
4250        ident: Ident,
4251        has_sub: bool,
4252    ) -> Option<Res> {
4253        // An immutable (no `mut`) by-value (no `ref`) binding pattern without
4254        // a sub pattern (no `@ $pat`) is syntactically ambiguous as it could
4255        // also be interpreted as a path to e.g. a constant, variant, etc.
4256        let is_syntactic_ambiguity = !has_sub && ann == BindingMode::NONE;
4257
4258        let ls_binding = self.maybe_resolve_ident_in_lexical_scope(ident, ValueNS)?;
4259        let (res, binding) = match ls_binding {
4260            LateDecl::Decl(binding)
4261                if is_syntactic_ambiguity && binding.is_ambiguity_recursive() =>
4262            {
4263                // For ambiguous bindings we don't know all their definitions and cannot check
4264                // whether they can be shadowed by fresh bindings or not, so force an error.
4265                // issues/33118#issuecomment-233962221 (see below) still applies here,
4266                // but we have to ignore it for backward compatibility.
4267                self.r.record_use(ident, binding, Used::Other);
4268                return None;
4269            }
4270            LateDecl::Decl(binding) => (binding.res(), Some(binding)),
4271            LateDecl::RibDef(res) => (res, None),
4272        };
4273
4274        match res {
4275            Res::SelfCtor(_) // See #70549.
4276            | Res::Def(
4277                DefKind::Ctor(_, CtorKind::Const) | DefKind::Const | DefKind::AssocConst | DefKind::ConstParam,
4278                _,
4279            ) if is_syntactic_ambiguity => {
4280                // Disambiguate in favor of a unit struct/variant or constant pattern.
4281                if let Some(binding) = binding {
4282                    self.r.record_use(ident, binding, Used::Other);
4283                }
4284                Some(res)
4285            }
4286            Res::Def(DefKind::Ctor(..) | DefKind::Const | DefKind::AssocConst | DefKind::Static { .. }, _) => {
4287                // This is unambiguously a fresh binding, either syntactically
4288                // (e.g., `IDENT @ PAT` or `ref IDENT`) or because `IDENT` resolves
4289                // to something unusable as a pattern (e.g., constructor function),
4290                // but we still conservatively report an error, see
4291                // issues/33118#issuecomment-233962221 for one reason why.
4292                let binding = binding.expect("no binding for a ctor or static");
4293                self.report_error(
4294                    ident.span,
4295                    ResolutionError::BindingShadowsSomethingUnacceptable {
4296                        shadowing_binding: pat_src,
4297                        name: ident.name,
4298                        participle: if binding.is_import() { "imported" } else { "defined" },
4299                        article: binding.res().article(),
4300                        shadowed_binding: binding.res(),
4301                        shadowed_binding_span: binding.span,
4302                    },
4303                );
4304                None
4305            }
4306            Res::Def(DefKind::ConstParam, def_id) => {
4307                // Same as for DefKind::Const above, but here, `binding` is `None`, so we
4308                // have to construct the error differently
4309                self.report_error(
4310                    ident.span,
4311                    ResolutionError::BindingShadowsSomethingUnacceptable {
4312                        shadowing_binding: pat_src,
4313                        name: ident.name,
4314                        participle: "defined",
4315                        article: res.article(),
4316                        shadowed_binding: res,
4317                        shadowed_binding_span: self.r.def_span(def_id),
4318                    }
4319                );
4320                None
4321            }
4322            Res::Def(DefKind::Fn | DefKind::AssocFn, _) | Res::Local(..) | Res::Err => {
4323                // These entities are explicitly allowed to be shadowed by fresh bindings.
4324                None
4325            }
4326            Res::SelfCtor(_) => {
4327                // We resolve `Self` in pattern position as an ident sometimes during recovery,
4328                // so delay a bug instead of ICEing.
4329                self.r.dcx().span_delayed_bug(
4330                    ident.span,
4331                    "unexpected `SelfCtor` in pattern, expected identifier"
4332                );
4333                None
4334            }
4335            _ => span_bug!(
4336                ident.span,
4337                "unexpected resolution for an identifier in pattern: {:?}",
4338                res,
4339            ),
4340        }
4341    }
4342
4343    // High-level and context dependent path resolution routine.
4344    // Resolves the path and records the resolution into definition map.
4345    // If resolution fails tries several techniques to find likely
4346    // resolution candidates, suggest imports or other help, and report
4347    // errors in user friendly way.
4348    fn smart_resolve_path(
4349        &mut self,
4350        id: NodeId,
4351        qself: &Option<Box<QSelf>>,
4352        path: &Path,
4353        source: PathSource<'_, 'ast, 'ra>,
4354    ) {
4355        self.smart_resolve_path_fragment(
4356            qself,
4357            &Segment::from_path(path),
4358            source,
4359            Finalize::new(id, path.span),
4360            RecordPartialRes::Yes,
4361            None,
4362        );
4363    }
4364
4365    fn smart_resolve_path_fragment(
4366        &mut self,
4367        qself: &Option<Box<QSelf>>,
4368        path: &[Segment],
4369        source: PathSource<'_, 'ast, 'ra>,
4370        finalize: Finalize,
4371        record_partial_res: RecordPartialRes,
4372        parent_qself: Option<&QSelf>,
4373    ) -> PartialRes {
4374        let ns = source.namespace();
4375
4376        let Finalize { node_id, path_span, .. } = finalize;
4377        let report_errors = |this: &mut Self, res: Option<Res>| {
4378            if this.should_report_errs() {
4379                let (err, candidates) = this.smart_resolve_report_errors(
4380                    path,
4381                    None,
4382                    path_span,
4383                    source,
4384                    res,
4385                    parent_qself,
4386                );
4387
4388                let def_id = this.parent_scope.module.nearest_parent_mod();
4389                let instead = res.is_some();
4390                let suggestion = if let Some((start, end)) = this.diag_metadata.in_range
4391                    && path[0].ident.span.lo() == end.span.lo()
4392                    && !matches!(start.kind, ExprKind::Lit(_))
4393                {
4394                    let mut sugg = ".";
4395                    let mut span = start.span.between(end.span);
4396                    if span.lo() + BytePos(2) == span.hi() {
4397                        // There's no space between the start, the range op and the end, suggest
4398                        // removal which will look better.
4399                        span = span.with_lo(span.lo() + BytePos(1));
4400                        sugg = "";
4401                    }
4402                    Some((
4403                        span,
4404                        "you might have meant to write `.` instead of `..`",
4405                        sugg.to_string(),
4406                        Applicability::MaybeIncorrect,
4407                    ))
4408                } else if res.is_none()
4409                    && let PathSource::Type
4410                    | PathSource::Expr(_)
4411                    | PathSource::PreciseCapturingArg(..) = source
4412                {
4413                    this.suggest_adding_generic_parameter(path, source)
4414                } else {
4415                    None
4416                };
4417
4418                let ue = UseError {
4419                    err,
4420                    candidates,
4421                    def_id,
4422                    instead,
4423                    suggestion,
4424                    path: path.into(),
4425                    is_call: source.is_call(),
4426                };
4427
4428                this.r.use_injections.push(ue);
4429            }
4430
4431            PartialRes::new(Res::Err)
4432        };
4433
4434        // For paths originating from calls (like in `HashMap::new()`), tries
4435        // to enrich the plain `failed to resolve: ...` message with hints
4436        // about possible missing imports.
4437        //
4438        // Similar thing, for types, happens in `report_errors` above.
4439        let report_errors_for_call =
4440            |this: &mut Self, parent_err: Spanned<ResolutionError<'ra>>| {
4441                // Before we start looking for candidates, we have to get our hands
4442                // on the type user is trying to perform invocation on; basically:
4443                // we're transforming `HashMap::new` into just `HashMap`.
4444                let (following_seg, prefix_path) = match path.split_last() {
4445                    Some((last, path)) if !path.is_empty() => (Some(last), path),
4446                    _ => return Some(parent_err),
4447                };
4448
4449                let (mut err, candidates) = this.smart_resolve_report_errors(
4450                    prefix_path,
4451                    following_seg,
4452                    path_span,
4453                    PathSource::Type,
4454                    None,
4455                    parent_qself,
4456                );
4457
4458                // There are two different error messages user might receive at
4459                // this point:
4460                // - E0425 cannot find type `{}` in this scope
4461                // - E0433 failed to resolve: use of undeclared type or module `{}`
4462                //
4463                // The first one is emitted for paths in type-position, and the
4464                // latter one - for paths in expression-position.
4465                //
4466                // Thus (since we're in expression-position at this point), not to
4467                // confuse the user, we want to keep the *message* from E0433 (so
4468                // `parent_err`), but we want *hints* from E0425 (so `err`).
4469                //
4470                // And that's what happens below - we're just mixing both messages
4471                // into a single one.
4472                let failed_to_resolve = match parent_err.node {
4473                    ResolutionError::FailedToResolve { .. } => true,
4474                    _ => false,
4475                };
4476                let mut parent_err = this.r.into_struct_error(parent_err.span, parent_err.node);
4477
4478                // overwrite all properties with the parent's error message
4479                err.messages = take(&mut parent_err.messages);
4480                err.code = take(&mut parent_err.code);
4481                swap(&mut err.span, &mut parent_err.span);
4482                if failed_to_resolve {
4483                    err.children = take(&mut parent_err.children);
4484                } else {
4485                    err.children.append(&mut parent_err.children);
4486                }
4487                err.sort_span = parent_err.sort_span;
4488                err.is_lint = parent_err.is_lint.clone();
4489
4490                // merge the parent_err's suggestions with the typo (err's) suggestions
4491                match &mut err.suggestions {
4492                    Suggestions::Enabled(typo_suggestions) => match &mut parent_err.suggestions {
4493                        Suggestions::Enabled(parent_suggestions) => {
4494                            // If both suggestions are enabled, append parent_err's suggestions to err's suggestions.
4495                            typo_suggestions.append(parent_suggestions)
4496                        }
4497                        Suggestions::Sealed(_) | Suggestions::Disabled => {
4498                            // If the parent's suggestions are either sealed or disabled, it signifies that
4499                            // new suggestions cannot be added or removed from the diagnostic. Therefore,
4500                            // we assign both types of suggestions to err's suggestions and discard the
4501                            // existing suggestions in err.
4502                            err.suggestions = std::mem::take(&mut parent_err.suggestions);
4503                        }
4504                    },
4505                    Suggestions::Sealed(_) | Suggestions::Disabled => (),
4506                }
4507
4508                parent_err.cancel();
4509
4510                let def_id = this.parent_scope.module.nearest_parent_mod();
4511
4512                if this.should_report_errs() {
4513                    if candidates.is_empty() {
4514                        if path.len() == 2
4515                            && let [segment] = prefix_path
4516                        {
4517                            // Delay to check whether method name is an associated function or not
4518                            // ```
4519                            // let foo = Foo {};
4520                            // foo::bar(); // possibly suggest to foo.bar();
4521                            //```
4522                            err.stash(segment.ident.span, rustc_errors::StashKey::CallAssocMethod);
4523                        } else {
4524                            // When there is no suggested imports, we can just emit the error
4525                            // and suggestions immediately. Note that we bypass the usually error
4526                            // reporting routine (ie via `self.r.report_error`) because we need
4527                            // to post-process the `ResolutionError` above.
4528                            err.emit();
4529                        }
4530                    } else {
4531                        // If there are suggested imports, the error reporting is delayed
4532                        this.r.use_injections.push(UseError {
4533                            err,
4534                            candidates,
4535                            def_id,
4536                            instead: false,
4537                            suggestion: None,
4538                            path: prefix_path.into(),
4539                            is_call: source.is_call(),
4540                        });
4541                    }
4542                } else {
4543                    err.cancel();
4544                }
4545
4546                // We don't return `Some(parent_err)` here, because the error will
4547                // be already printed either immediately or as part of the `use` injections
4548                None
4549            };
4550
4551        let partial_res = match self.resolve_qpath_anywhere(
4552            qself,
4553            path,
4554            ns,
4555            source.defer_to_typeck(),
4556            finalize,
4557            source,
4558        ) {
4559            Ok(Some(partial_res)) if let Some(res) = partial_res.full_res() => {
4560                // if we also have an associated type that matches the ident, stash a suggestion
4561                if let Some(items) = self.diag_metadata.current_trait_assoc_items
4562                    && let [Segment { ident, .. }] = path
4563                    && items.iter().any(|item| {
4564                        if let AssocItemKind::Type(alias) = &item.kind
4565                            && alias.ident == *ident
4566                        {
4567                            true
4568                        } else {
4569                            false
4570                        }
4571                    })
4572                {
4573                    let mut diag = self.r.tcx.dcx().struct_allow("");
4574                    diag.span_suggestion_verbose(
4575                        path_span.shrink_to_lo(),
4576                        "there is an associated type with the same name",
4577                        "Self::",
4578                        Applicability::MaybeIncorrect,
4579                    );
4580                    diag.stash(path_span, StashKey::AssociatedTypeSuggestion);
4581                }
4582
4583                if source.is_expected(res) || res == Res::Err {
4584                    partial_res
4585                } else {
4586                    report_errors(self, Some(res))
4587                }
4588            }
4589
4590            Ok(Some(partial_res)) if source.defer_to_typeck() => {
4591                // Not fully resolved associated item `T::A::B` or `<T as Tr>::A::B`
4592                // or `<T>::A::B`. If `B` should be resolved in value namespace then
4593                // it needs to be added to the trait map.
4594                if ns == ValueNS {
4595                    let item_name = path.last().unwrap().ident;
4596                    let traits = self.traits_in_scope(item_name, ns);
4597                    self.r.trait_map.insert(node_id, traits);
4598                }
4599
4600                if PrimTy::from_name(path[0].ident.name).is_some() {
4601                    let mut std_path = Vec::with_capacity(1 + path.len());
4602
4603                    std_path.push(Segment::from_ident(Ident::with_dummy_span(sym::std)));
4604                    std_path.extend(path);
4605                    if let PathResult::Module(_) | PathResult::NonModule(_) =
4606                        self.resolve_path(&std_path, Some(ns), None, source)
4607                    {
4608                        // Check if we wrote `str::from_utf8` instead of `std::str::from_utf8`
4609                        let item_span =
4610                            path.iter().last().map_or(path_span, |segment| segment.ident.span);
4611
4612                        self.r.confused_type_with_std_module.insert(item_span, path_span);
4613                        self.r.confused_type_with_std_module.insert(path_span, path_span);
4614                    }
4615                }
4616
4617                partial_res
4618            }
4619
4620            Err(err) => {
4621                if let Some(err) = report_errors_for_call(self, err) {
4622                    self.report_error(err.span, err.node);
4623                }
4624
4625                PartialRes::new(Res::Err)
4626            }
4627
4628            _ => report_errors(self, None),
4629        };
4630
4631        if record_partial_res == RecordPartialRes::Yes {
4632            // Avoid recording definition of `A::B` in `<T as A>::B::C`.
4633            self.r.record_partial_res(node_id, partial_res);
4634            self.resolve_elided_lifetimes_in_path(partial_res, path, source, path_span);
4635            self.lint_unused_qualifications(path, ns, finalize);
4636        }
4637
4638        partial_res
4639    }
4640
4641    fn self_type_is_available(&mut self) -> bool {
4642        let binding = self
4643            .maybe_resolve_ident_in_lexical_scope(Ident::with_dummy_span(kw::SelfUpper), TypeNS);
4644        if let Some(LateDecl::RibDef(res)) = binding { res != Res::Err } else { false }
4645    }
4646
4647    fn self_value_is_available(&mut self, self_span: Span) -> bool {
4648        let ident = Ident::new(kw::SelfLower, self_span);
4649        let binding = self.maybe_resolve_ident_in_lexical_scope(ident, ValueNS);
4650        if let Some(LateDecl::RibDef(res)) = binding { res != Res::Err } else { false }
4651    }
4652
4653    /// A wrapper around [`Resolver::report_error`].
4654    ///
4655    /// This doesn't emit errors for function bodies if this is rustdoc.
4656    fn report_error(&mut self, span: Span, resolution_error: ResolutionError<'ra>) {
4657        if self.should_report_errs() {
4658            self.r.report_error(span, resolution_error);
4659        }
4660    }
4661
4662    #[inline]
4663    /// If we're actually rustdoc then avoid giving a name resolution error for `cfg()` items or
4664    // an invalid `use foo::*;` was found, which can cause unbounded amounts of "item not found"
4665    // errors. We silence them all.
4666    fn should_report_errs(&self) -> bool {
4667        !(self.r.tcx.sess.opts.actually_rustdoc && self.in_func_body)
4668            && !self.r.glob_error.is_some()
4669    }
4670
4671    // Resolve in alternative namespaces if resolution in the primary namespace fails.
4672    fn resolve_qpath_anywhere(
4673        &mut self,
4674        qself: &Option<Box<QSelf>>,
4675        path: &[Segment],
4676        primary_ns: Namespace,
4677        defer_to_typeck: bool,
4678        finalize: Finalize,
4679        source: PathSource<'_, 'ast, 'ra>,
4680    ) -> Result<Option<PartialRes>, Spanned<ResolutionError<'ra>>> {
4681        let mut fin_res = None;
4682
4683        for (i, &ns) in [primary_ns, TypeNS, ValueNS].iter().enumerate() {
4684            if i == 0 || ns != primary_ns {
4685                match self.resolve_qpath(qself, path, ns, finalize, source)? {
4686                    Some(partial_res)
4687                        if partial_res.unresolved_segments() == 0 || defer_to_typeck =>
4688                    {
4689                        return Ok(Some(partial_res));
4690                    }
4691                    partial_res => {
4692                        if fin_res.is_none() {
4693                            fin_res = partial_res;
4694                        }
4695                    }
4696                }
4697            }
4698        }
4699
4700        assert!(primary_ns != MacroNS);
4701        if qself.is_none()
4702            && let PathResult::NonModule(res) =
4703                self.r.cm().maybe_resolve_path(path, Some(MacroNS), &self.parent_scope, None)
4704        {
4705            return Ok(Some(res));
4706        }
4707
4708        Ok(fin_res)
4709    }
4710
4711    /// Handles paths that may refer to associated items.
4712    fn resolve_qpath(
4713        &mut self,
4714        qself: &Option<Box<QSelf>>,
4715        path: &[Segment],
4716        ns: Namespace,
4717        finalize: Finalize,
4718        source: PathSource<'_, 'ast, 'ra>,
4719    ) -> Result<Option<PartialRes>, Spanned<ResolutionError<'ra>>> {
4720        debug!(
4721            "resolve_qpath(qself={:?}, path={:?}, ns={:?}, finalize={:?})",
4722            qself, path, ns, finalize,
4723        );
4724
4725        if let Some(qself) = qself {
4726            if qself.position == 0 {
4727                // This is a case like `<T>::B`, where there is no
4728                // trait to resolve. In that case, we leave the `B`
4729                // segment to be resolved by type-check.
4730                return Ok(Some(PartialRes::with_unresolved_segments(
4731                    Res::Def(DefKind::Mod, CRATE_DEF_ID.to_def_id()),
4732                    path.len(),
4733                )));
4734            }
4735
4736            let num_privacy_errors = self.r.privacy_errors.len();
4737            // Make sure that `A` in `<T as A>::B::C` is a trait.
4738            let trait_res = self.smart_resolve_path_fragment(
4739                &None,
4740                &path[..qself.position],
4741                PathSource::Trait(AliasPossibility::No),
4742                Finalize::new(finalize.node_id, qself.path_span),
4743                RecordPartialRes::No,
4744                Some(&qself),
4745            );
4746
4747            if trait_res.expect_full_res() == Res::Err {
4748                return Ok(Some(trait_res));
4749            }
4750
4751            // Truncate additional privacy errors reported above,
4752            // because they'll be recomputed below.
4753            self.r.privacy_errors.truncate(num_privacy_errors);
4754
4755            // Make sure `A::B` in `<T as A>::B::C` is a trait item.
4756            //
4757            // Currently, `path` names the full item (`A::B::C`, in
4758            // our example). so we extract the prefix of that that is
4759            // the trait (the slice upto and including
4760            // `qself.position`). And then we recursively resolve that,
4761            // but with `qself` set to `None`.
4762            let ns = if qself.position + 1 == path.len() { ns } else { TypeNS };
4763            let partial_res = self.smart_resolve_path_fragment(
4764                &None,
4765                &path[..=qself.position],
4766                PathSource::TraitItem(ns, &source),
4767                Finalize::with_root_span(finalize.node_id, finalize.path_span, qself.path_span),
4768                RecordPartialRes::No,
4769                Some(&qself),
4770            );
4771
4772            // The remaining segments (the `C` in our example) will
4773            // have to be resolved by type-check, since that requires doing
4774            // trait resolution.
4775            return Ok(Some(PartialRes::with_unresolved_segments(
4776                partial_res.base_res(),
4777                partial_res.unresolved_segments() + path.len() - qself.position - 1,
4778            )));
4779        }
4780
4781        let result = match self.resolve_path(path, Some(ns), Some(finalize), source) {
4782            PathResult::NonModule(path_res) => path_res,
4783            PathResult::Module(ModuleOrUniformRoot::Module(module)) if !module.is_normal() => {
4784                PartialRes::new(module.res().unwrap())
4785            }
4786            // A part of this path references a `mod` that had a parse error. To avoid resolution
4787            // errors for each reference to that module, we don't emit an error for them until the
4788            // `mod` is fixed. this can have a significant cascade effect.
4789            PathResult::Failed { error_implied_by_parse_error: true, .. } => {
4790                PartialRes::new(Res::Err)
4791            }
4792            // In `a(::assoc_item)*` `a` cannot be a module. If `a` does resolve to a module we
4793            // don't report an error right away, but try to fallback to a primitive type.
4794            // So, we are still able to successfully resolve something like
4795            //
4796            // use std::u8; // bring module u8 in scope
4797            // fn f() -> u8 { // OK, resolves to primitive u8, not to std::u8
4798            //     u8::max_value() // OK, resolves to associated function <u8>::max_value,
4799            //                     // not to nonexistent std::u8::max_value
4800            // }
4801            //
4802            // Such behavior is required for backward compatibility.
4803            // The same fallback is used when `a` resolves to nothing.
4804            PathResult::Module(ModuleOrUniformRoot::Module(_)) | PathResult::Failed { .. }
4805                if (ns == TypeNS || path.len() > 1)
4806                    && PrimTy::from_name(path[0].ident.name).is_some() =>
4807            {
4808                let prim = PrimTy::from_name(path[0].ident.name).unwrap();
4809                let tcx = self.r.tcx();
4810
4811                let gate_err_sym_msg = match prim {
4812                    PrimTy::Float(FloatTy::F16) if !tcx.features().f16() => {
4813                        Some((sym::f16, "the type `f16` is unstable"))
4814                    }
4815                    PrimTy::Float(FloatTy::F128) if !tcx.features().f128() => {
4816                        Some((sym::f128, "the type `f128` is unstable"))
4817                    }
4818                    _ => None,
4819                };
4820
4821                if let Some((sym, msg)) = gate_err_sym_msg {
4822                    let span = path[0].ident.span;
4823                    if !span.allows_unstable(sym) {
4824                        feature_err(tcx.sess, sym, span, msg).emit();
4825                    }
4826                };
4827
4828                // Fix up partial res of segment from `resolve_path` call.
4829                if let Some(id) = path[0].id {
4830                    self.r.partial_res_map.insert(id, PartialRes::new(Res::PrimTy(prim)));
4831                }
4832
4833                PartialRes::with_unresolved_segments(Res::PrimTy(prim), path.len() - 1)
4834            }
4835            PathResult::Module(ModuleOrUniformRoot::Module(module)) => {
4836                PartialRes::new(module.res().unwrap())
4837            }
4838            PathResult::Failed {
4839                is_error_from_last_segment: false,
4840                span,
4841                label,
4842                suggestion,
4843                module,
4844                segment_name,
4845                error_implied_by_parse_error: _,
4846            } => {
4847                return Err(respan(
4848                    span,
4849                    ResolutionError::FailedToResolve {
4850                        segment: Some(segment_name),
4851                        label,
4852                        suggestion,
4853                        module,
4854                    },
4855                ));
4856            }
4857            PathResult::Module(..) | PathResult::Failed { .. } => return Ok(None),
4858            PathResult::Indeterminate => bug!("indeterminate path result in resolve_qpath"),
4859        };
4860
4861        Ok(Some(result))
4862    }
4863
4864    fn with_resolved_label(&mut self, label: Option<Label>, id: NodeId, f: impl FnOnce(&mut Self)) {
4865        if let Some(label) = label {
4866            if label.ident.as_str().as_bytes()[1] != b'_' {
4867                self.diag_metadata.unused_labels.insert(id, label.ident.span);
4868            }
4869
4870            if let Ok((_, orig_span)) = self.resolve_label(label.ident) {
4871                diagnostics::signal_label_shadowing(self.r.tcx.sess, orig_span, label.ident)
4872            }
4873
4874            self.with_label_rib(RibKind::Normal, |this| {
4875                let ident = label.ident.normalize_to_macro_rules();
4876                this.label_ribs.last_mut().unwrap().bindings.insert(ident, id);
4877                f(this);
4878            });
4879        } else {
4880            f(self);
4881        }
4882    }
4883
4884    fn resolve_labeled_block(&mut self, label: Option<Label>, id: NodeId, block: &'ast Block) {
4885        self.with_resolved_label(label, id, |this| this.visit_block(block));
4886    }
4887
4888    fn resolve_block(&mut self, block: &'ast Block) {
4889        debug!("(resolving block) entering block");
4890        // Move down in the graph, if there's an anonymous module rooted here.
4891        let orig_module = self.parent_scope.module;
4892        let anonymous_module = self.r.block_map.get(&block.id).copied();
4893
4894        let mut num_macro_definition_ribs = 0;
4895        if let Some(anonymous_module) = anonymous_module {
4896            debug!("(resolving block) found anonymous module, moving down");
4897            self.ribs[ValueNS].push(Rib::new(RibKind::Block(Some(anonymous_module))));
4898            self.ribs[TypeNS].push(Rib::new(RibKind::Block(Some(anonymous_module))));
4899            self.parent_scope.module = anonymous_module;
4900        } else {
4901            self.ribs[ValueNS].push(Rib::new(RibKind::Block(None)));
4902        }
4903
4904        // Descend into the block.
4905        for stmt in &block.stmts {
4906            if let StmtKind::Item(ref item) = stmt.kind
4907                && let ItemKind::MacroDef(..) = item.kind
4908            {
4909                num_macro_definition_ribs += 1;
4910                let res = self.r.local_def_id(item.id).to_def_id();
4911                self.ribs[ValueNS].push(Rib::new(RibKind::MacroDefinition(res)));
4912                self.label_ribs.push(Rib::new(RibKind::MacroDefinition(res)));
4913            }
4914
4915            self.visit_stmt(stmt);
4916        }
4917
4918        // Move back up.
4919        self.parent_scope.module = orig_module;
4920        for _ in 0..num_macro_definition_ribs {
4921            self.ribs[ValueNS].pop();
4922            self.label_ribs.pop();
4923        }
4924        self.last_block_rib = self.ribs[ValueNS].pop();
4925        if anonymous_module.is_some() {
4926            self.ribs[TypeNS].pop();
4927        }
4928        debug!("(resolving block) leaving block");
4929    }
4930
4931    fn resolve_anon_const(&mut self, constant: &'ast AnonConst, anon_const_kind: AnonConstKind) {
4932        debug!(
4933            "resolve_anon_const(constant: {:?}, anon_const_kind: {:?})",
4934            constant, anon_const_kind
4935        );
4936
4937        let is_trivial_const_arg = constant.value.is_potential_trivial_const_arg();
4938        self.resolve_anon_const_manual(is_trivial_const_arg, anon_const_kind, |this| {
4939            this.resolve_expr(&constant.value, None)
4940        })
4941    }
4942
4943    /// There are a few places that we need to resolve an anon const but we did not parse an
4944    /// anon const so cannot provide an `&'ast AnonConst`. Right now this is just unbraced
4945    /// const arguments that were parsed as type arguments, and `legacy_const_generics` which
4946    /// parse as normal function argument expressions. To avoid duplicating the code for resolving
4947    /// an anon const we have this function which lets the caller manually call `resolve_expr` or
4948    /// `smart_resolve_path`.
4949    fn resolve_anon_const_manual(
4950        &mut self,
4951        is_trivial_const_arg: bool,
4952        anon_const_kind: AnonConstKind,
4953        resolve_expr: impl FnOnce(&mut Self),
4954    ) {
4955        let is_repeat_expr = match anon_const_kind {
4956            AnonConstKind::ConstArg(is_repeat_expr) => is_repeat_expr,
4957            _ => IsRepeatExpr::No,
4958        };
4959
4960        let may_use_generics = match anon_const_kind {
4961            AnonConstKind::EnumDiscriminant => {
4962                ConstantHasGenerics::No(NoConstantGenericsReason::IsEnumDiscriminant)
4963            }
4964            AnonConstKind::FieldDefaultValue => ConstantHasGenerics::Yes,
4965            AnonConstKind::InlineConst => ConstantHasGenerics::Yes,
4966            AnonConstKind::ConstArg(_) => {
4967                if self.r.tcx.features().generic_const_exprs()
4968                    || self.r.tcx.features().min_generic_const_args()
4969                    || is_trivial_const_arg
4970                {
4971                    ConstantHasGenerics::Yes
4972                } else {
4973                    ConstantHasGenerics::No(NoConstantGenericsReason::NonTrivialConstArg)
4974                }
4975            }
4976        };
4977
4978        self.with_constant_rib(is_repeat_expr, may_use_generics, None, |this| {
4979            this.with_lifetime_rib(LifetimeRibKind::Elided(LifetimeRes::Infer), |this| {
4980                resolve_expr(this);
4981            });
4982        });
4983    }
4984
4985    fn resolve_expr_field(&mut self, f: &'ast ExprField, e: &'ast Expr) {
4986        self.resolve_expr(&f.expr, Some(e));
4987        self.visit_ident(&f.ident);
4988        walk_list!(self, visit_attribute, f.attrs.iter());
4989    }
4990
4991    fn resolve_expr(&mut self, expr: &'ast Expr, parent: Option<&'ast Expr>) {
4992        // First, record candidate traits for this expression if it could
4993        // result in the invocation of a method call.
4994
4995        self.record_candidate_traits_for_expr_if_necessary(expr);
4996
4997        // Next, resolve the node.
4998        match expr.kind {
4999            ExprKind::Path(ref qself, ref path) => {
5000                self.smart_resolve_path(expr.id, qself, path, PathSource::Expr(parent));
5001                visit::walk_expr(self, expr);
5002            }
5003
5004            ExprKind::Struct(ref se) => {
5005                self.smart_resolve_path(expr.id, &se.qself, &se.path, PathSource::Struct(parent));
5006                // This is the same as `visit::walk_expr(self, expr);`, but we want to pass the
5007                // parent in for accurate suggestions when encountering `Foo { bar }` that should
5008                // have been `Foo { bar: self.bar }`.
5009                if let Some(qself) = &se.qself {
5010                    self.visit_ty(&qself.ty);
5011                }
5012                self.visit_path(&se.path);
5013                walk_list!(self, resolve_expr_field, &se.fields, expr);
5014                match &se.rest {
5015                    StructRest::Base(expr) => self.visit_expr(expr),
5016                    StructRest::Rest(_span) => {}
5017                    StructRest::None => {}
5018                }
5019            }
5020
5021            ExprKind::Break(Some(label), _) | ExprKind::Continue(Some(label)) => {
5022                match self.resolve_label(label.ident) {
5023                    Ok((node_id, _)) => {
5024                        // Since this res is a label, it is never read.
5025                        self.r.label_res_map.insert(expr.id, node_id);
5026                        self.diag_metadata.unused_labels.swap_remove(&node_id);
5027                    }
5028                    Err(error) => {
5029                        self.report_error(label.ident.span, error);
5030                    }
5031                }
5032
5033                // visit `break` argument if any
5034                visit::walk_expr(self, expr);
5035            }
5036
5037            ExprKind::Break(None, Some(ref e)) => {
5038                // We use this instead of `visit::walk_expr` to keep the parent expr around for
5039                // better diagnostics.
5040                self.resolve_expr(e, Some(expr));
5041            }
5042
5043            ExprKind::Let(ref pat, ref scrutinee, _, Recovered::No) => {
5044                self.visit_expr(scrutinee);
5045                self.resolve_pattern_top(pat, PatternSource::Let);
5046            }
5047
5048            ExprKind::Let(ref pat, ref scrutinee, _, Recovered::Yes(_)) => {
5049                self.visit_expr(scrutinee);
5050                // This is basically a tweaked, inlined `resolve_pattern_top`.
5051                let mut bindings = smallvec![(PatBoundCtx::Product, Default::default())];
5052                self.resolve_pattern(pat, PatternSource::Let, &mut bindings);
5053                // We still collect the bindings in this `let` expression which is in
5054                // an invalid position (and therefore shouldn't declare variables into
5055                // its parent scope). To avoid unnecessary errors though, we do just
5056                // reassign the resolutions to `Res::Err`.
5057                for (_, bindings) in &mut bindings {
5058                    for (_, binding) in bindings {
5059                        *binding = Res::Err;
5060                    }
5061                }
5062                self.apply_pattern_bindings(bindings);
5063            }
5064
5065            ExprKind::If(ref cond, ref then, ref opt_else) => {
5066                self.with_rib(ValueNS, RibKind::Normal, |this| {
5067                    let old = this.diag_metadata.in_if_condition.replace(cond);
5068                    this.visit_expr(cond);
5069                    this.diag_metadata.in_if_condition = old;
5070                    this.visit_block(then);
5071                });
5072                if let Some(expr) = opt_else {
5073                    self.visit_expr(expr);
5074                }
5075            }
5076
5077            ExprKind::Loop(ref block, label, _) => {
5078                self.resolve_labeled_block(label, expr.id, block)
5079            }
5080
5081            ExprKind::While(ref cond, ref block, label) => {
5082                self.with_resolved_label(label, expr.id, |this| {
5083                    this.with_rib(ValueNS, RibKind::Normal, |this| {
5084                        let old = this.diag_metadata.in_if_condition.replace(cond);
5085                        this.visit_expr(cond);
5086                        this.diag_metadata.in_if_condition = old;
5087                        this.visit_block(block);
5088                    })
5089                });
5090            }
5091
5092            ExprKind::ForLoop { ref pat, ref iter, ref body, label, kind: _ } => {
5093                self.visit_expr(iter);
5094                self.with_rib(ValueNS, RibKind::Normal, |this| {
5095                    this.resolve_pattern_top(pat, PatternSource::For);
5096                    this.resolve_labeled_block(label, expr.id, body);
5097                });
5098            }
5099
5100            ExprKind::Block(ref block, label) => self.resolve_labeled_block(label, block.id, block),
5101
5102            // Equivalent to `visit::walk_expr` + passing some context to children.
5103            ExprKind::Field(ref subexpression, _) => {
5104                self.resolve_expr(subexpression, Some(expr));
5105            }
5106            ExprKind::MethodCall(box MethodCall { ref seg, ref receiver, ref args, .. }) => {
5107                self.resolve_expr(receiver, Some(expr));
5108                for arg in args {
5109                    self.resolve_expr(arg, None);
5110                }
5111                self.visit_path_segment(seg);
5112            }
5113
5114            ExprKind::Call(ref callee, ref arguments) => {
5115                self.resolve_expr(callee, Some(expr));
5116                let const_args = self.r.legacy_const_generic_args(callee).unwrap_or_default();
5117                for (idx, argument) in arguments.iter().enumerate() {
5118                    // Constant arguments need to be treated as AnonConst since
5119                    // that is how they will be later lowered to HIR.
5120                    if const_args.contains(&idx) {
5121                        // FIXME(mgca): legacy const generics doesn't support mgca but maybe
5122                        // that's okay.
5123                        let is_trivial_const_arg = argument.is_potential_trivial_const_arg();
5124                        self.resolve_anon_const_manual(
5125                            is_trivial_const_arg,
5126                            AnonConstKind::ConstArg(IsRepeatExpr::No),
5127                            |this| this.resolve_expr(argument, None),
5128                        );
5129                    } else {
5130                        self.resolve_expr(argument, None);
5131                    }
5132                }
5133            }
5134            ExprKind::Type(ref _type_expr, ref _ty) => {
5135                visit::walk_expr(self, expr);
5136            }
5137            // For closures, RibKind::FnOrCoroutine is added in visit_fn
5138            ExprKind::Closure(box ast::Closure {
5139                binder: ClosureBinder::For { ref generic_params, span },
5140                ..
5141            }) => {
5142                self.with_generic_param_rib(
5143                    generic_params,
5144                    RibKind::Normal,
5145                    expr.id,
5146                    LifetimeBinderKind::Closure,
5147                    span,
5148                    |this| visit::walk_expr(this, expr),
5149                );
5150            }
5151            ExprKind::Closure(..) => visit::walk_expr(self, expr),
5152            ExprKind::Gen(..) => {
5153                self.with_label_rib(RibKind::FnOrCoroutine, |this| visit::walk_expr(this, expr));
5154            }
5155            ExprKind::Repeat(ref elem, ref ct) => {
5156                self.visit_expr(elem);
5157                self.resolve_anon_const(ct, AnonConstKind::ConstArg(IsRepeatExpr::Yes));
5158            }
5159            ExprKind::ConstBlock(ref ct) => {
5160                self.resolve_anon_const(ct, AnonConstKind::InlineConst);
5161            }
5162            ExprKind::Index(ref elem, ref idx, _) => {
5163                self.resolve_expr(elem, Some(expr));
5164                self.visit_expr(idx);
5165            }
5166            ExprKind::Assign(ref lhs, ref rhs, _) => {
5167                if !self.diag_metadata.is_assign_rhs {
5168                    self.diag_metadata.in_assignment = Some(expr);
5169                }
5170                self.visit_expr(lhs);
5171                self.diag_metadata.is_assign_rhs = true;
5172                self.diag_metadata.in_assignment = None;
5173                self.visit_expr(rhs);
5174                self.diag_metadata.is_assign_rhs = false;
5175            }
5176            ExprKind::Range(Some(ref start), Some(ref end), RangeLimits::HalfOpen) => {
5177                self.diag_metadata.in_range = Some((start, end));
5178                self.resolve_expr(start, Some(expr));
5179                self.resolve_expr(end, Some(expr));
5180                self.diag_metadata.in_range = None;
5181            }
5182            _ => {
5183                visit::walk_expr(self, expr);
5184            }
5185        }
5186    }
5187
5188    fn record_candidate_traits_for_expr_if_necessary(&mut self, expr: &'ast Expr) {
5189        match expr.kind {
5190            ExprKind::Field(_, ident) => {
5191                // #6890: Even though you can't treat a method like a field,
5192                // we need to add any trait methods we find that match the
5193                // field name so that we can do some nice error reporting
5194                // later on in typeck.
5195                let traits = self.traits_in_scope(ident, ValueNS);
5196                self.r.trait_map.insert(expr.id, traits);
5197            }
5198            ExprKind::MethodCall(ref call) => {
5199                debug!("(recording candidate traits for expr) recording traits for {}", expr.id);
5200                let traits = self.traits_in_scope(call.seg.ident, ValueNS);
5201                self.r.trait_map.insert(expr.id, traits);
5202            }
5203            _ => {
5204                // Nothing to do.
5205            }
5206        }
5207    }
5208
5209    fn traits_in_scope(&mut self, ident: Ident, ns: Namespace) -> Vec<TraitCandidate> {
5210        self.r.traits_in_scope(
5211            self.current_trait_ref.as_ref().map(|(module, _)| *module),
5212            &self.parent_scope,
5213            ident.span.ctxt(),
5214            Some((ident.name, ns)),
5215        )
5216    }
5217
5218    fn resolve_and_cache_rustdoc_path(&mut self, path_str: &str, ns: Namespace) -> Option<Res> {
5219        // FIXME: This caching may be incorrect in case of multiple `macro_rules`
5220        // items with the same name in the same module.
5221        // Also hygiene is not considered.
5222        let mut doc_link_resolutions = std::mem::take(&mut self.r.doc_link_resolutions);
5223        let res = *doc_link_resolutions
5224            .entry(self.parent_scope.module.nearest_parent_mod().expect_local())
5225            .or_default()
5226            .entry((Symbol::intern(path_str), ns))
5227            .or_insert_with_key(|(path, ns)| {
5228                let res = self.r.resolve_rustdoc_path(path.as_str(), *ns, self.parent_scope);
5229                if let Some(res) = res
5230                    && let Some(def_id) = res.opt_def_id()
5231                    && self.is_invalid_proc_macro_item_for_doc(def_id)
5232                {
5233                    // Encoding def ids in proc macro crate metadata will ICE,
5234                    // because it will only store proc macros for it.
5235                    return None;
5236                }
5237                res
5238            });
5239        self.r.doc_link_resolutions = doc_link_resolutions;
5240        res
5241    }
5242
5243    fn is_invalid_proc_macro_item_for_doc(&self, did: DefId) -> bool {
5244        if !matches!(self.r.tcx.sess.opts.resolve_doc_links, ResolveDocLinks::ExportedMetadata)
5245            || !self.r.tcx.crate_types().contains(&CrateType::ProcMacro)
5246        {
5247            return false;
5248        }
5249        let Some(local_did) = did.as_local() else { return true };
5250        !self.r.proc_macros.contains(&local_did)
5251    }
5252
5253    fn resolve_doc_links(&mut self, attrs: &[Attribute], maybe_exported: MaybeExported<'_>) {
5254        match self.r.tcx.sess.opts.resolve_doc_links {
5255            ResolveDocLinks::None => return,
5256            ResolveDocLinks::ExportedMetadata
5257                if !self.r.tcx.crate_types().iter().copied().any(CrateType::has_metadata)
5258                    || !maybe_exported.eval(self.r) =>
5259            {
5260                return;
5261            }
5262            ResolveDocLinks::Exported
5263                if !maybe_exported.eval(self.r)
5264                    && !rustdoc::has_primitive_or_keyword_or_attribute_docs(attrs) =>
5265            {
5266                return;
5267            }
5268            ResolveDocLinks::ExportedMetadata
5269            | ResolveDocLinks::Exported
5270            | ResolveDocLinks::All => {}
5271        }
5272
5273        if !attrs.iter().any(|attr| attr.may_have_doc_links()) {
5274            return;
5275        }
5276
5277        let mut need_traits_in_scope = false;
5278        for path_str in rustdoc::attrs_to_preprocessed_links(attrs) {
5279            // Resolve all namespaces due to no disambiguator or for diagnostics.
5280            let mut any_resolved = false;
5281            let mut need_assoc = false;
5282            for ns in [TypeNS, ValueNS, MacroNS] {
5283                if let Some(res) = self.resolve_and_cache_rustdoc_path(&path_str, ns) {
5284                    // Rustdoc ignores tool attribute resolutions and attempts
5285                    // to resolve their prefixes for diagnostics.
5286                    any_resolved = !matches!(res, Res::NonMacroAttr(NonMacroAttrKind::Tool));
5287                } else if ns != MacroNS {
5288                    need_assoc = true;
5289                }
5290            }
5291
5292            // Resolve all prefixes for type-relative resolution or for diagnostics.
5293            if need_assoc || !any_resolved {
5294                let mut path = &path_str[..];
5295                while let Some(idx) = path.rfind("::") {
5296                    path = &path[..idx];
5297                    need_traits_in_scope = true;
5298                    for ns in [TypeNS, ValueNS, MacroNS] {
5299                        self.resolve_and_cache_rustdoc_path(path, ns);
5300                    }
5301                }
5302            }
5303        }
5304
5305        if need_traits_in_scope {
5306            // FIXME: hygiene is not considered.
5307            let mut doc_link_traits_in_scope = std::mem::take(&mut self.r.doc_link_traits_in_scope);
5308            doc_link_traits_in_scope
5309                .entry(self.parent_scope.module.nearest_parent_mod().expect_local())
5310                .or_insert_with(|| {
5311                    self.r
5312                        .traits_in_scope(None, &self.parent_scope, SyntaxContext::root(), None)
5313                        .into_iter()
5314                        .filter_map(|tr| {
5315                            if self.is_invalid_proc_macro_item_for_doc(tr.def_id) {
5316                                // Encoding def ids in proc macro crate metadata will ICE.
5317                                // because it will only store proc macros for it.
5318                                return None;
5319                            }
5320                            Some(tr.def_id)
5321                        })
5322                        .collect()
5323                });
5324            self.r.doc_link_traits_in_scope = doc_link_traits_in_scope;
5325        }
5326    }
5327
5328    fn lint_unused_qualifications(&mut self, path: &[Segment], ns: Namespace, finalize: Finalize) {
5329        // Don't lint on global paths because the user explicitly wrote out the full path.
5330        if let Some(seg) = path.first()
5331            && seg.ident.name == kw::PathRoot
5332        {
5333            return;
5334        }
5335
5336        if finalize.path_span.from_expansion()
5337            || path.iter().any(|seg| seg.ident.span.from_expansion())
5338        {
5339            return;
5340        }
5341
5342        let end_pos =
5343            path.iter().position(|seg| seg.has_generic_args).map_or(path.len(), |pos| pos + 1);
5344        let unqualified = path[..end_pos].iter().enumerate().skip(1).rev().find_map(|(i, seg)| {
5345            // Preserve the current namespace for the final path segment, but use the type
5346            // namespace for all preceding segments
5347            //
5348            // e.g. for `std::env::args` check the `ValueNS` for `args` but the `TypeNS` for
5349            // `std` and `env`
5350            //
5351            // If the final path segment is beyond `end_pos` all the segments to check will
5352            // use the type namespace
5353            let ns = if i + 1 == path.len() { ns } else { TypeNS };
5354            let res = self.r.partial_res_map.get(&seg.id?)?.full_res()?;
5355            let binding = self.resolve_ident_in_lexical_scope(seg.ident, ns, None, None)?;
5356            (res == binding.res()).then_some((seg, binding))
5357        });
5358
5359        if let Some((seg, decl)) = unqualified {
5360            self.r.potentially_unnecessary_qualifications.push(UnnecessaryQualification {
5361                decl,
5362                node_id: finalize.node_id,
5363                path_span: finalize.path_span,
5364                removal_span: path[0].ident.span.until(seg.ident.span),
5365            });
5366        }
5367    }
5368
5369    fn resolve_define_opaques(&mut self, define_opaque: &Option<ThinVec<(NodeId, Path)>>) {
5370        if let Some(define_opaque) = define_opaque {
5371            for (id, path) in define_opaque {
5372                self.smart_resolve_path(*id, &None, path, PathSource::DefineOpaques);
5373            }
5374        }
5375    }
5376}
5377
5378/// Walks the whole crate in DFS order, visiting each item, counting the declared number of
5379/// lifetime generic parameters and function parameters.
5380struct ItemInfoCollector<'a, 'ra, 'tcx> {
5381    r: &'a mut Resolver<'ra, 'tcx>,
5382}
5383
5384impl ItemInfoCollector<'_, '_, '_> {
5385    fn collect_fn_info(
5386        &mut self,
5387        header: FnHeader,
5388        decl: &FnDecl,
5389        id: NodeId,
5390        attrs: &[Attribute],
5391    ) {
5392        self.r.delegation_fn_sigs.insert(
5393            self.r.local_def_id(id),
5394            DelegationFnSig {
5395                header,
5396                param_count: decl.inputs.len(),
5397                has_self: decl.has_self(),
5398                c_variadic: decl.c_variadic(),
5399                attrs: create_delegation_attrs(attrs),
5400            },
5401        );
5402    }
5403}
5404
5405fn create_delegation_attrs(attrs: &[Attribute]) -> DelegationAttrs {
5406    static NAMES_TO_FLAGS: &[(Symbol, DelegationFnSigAttrs)] = &[
5407        (sym::target_feature, DelegationFnSigAttrs::TARGET_FEATURE),
5408        (sym::must_use, DelegationFnSigAttrs::MUST_USE),
5409    ];
5410
5411    let mut to_inherit_attrs = AttrVec::new();
5412    let mut flags = DelegationFnSigAttrs::empty();
5413
5414    'attrs_loop: for attr in attrs {
5415        for &(name, flag) in NAMES_TO_FLAGS {
5416            if attr.has_name(name) {
5417                flags.set(flag, true);
5418
5419                if flag.bits() >= DELEGATION_INHERIT_ATTRS_START.bits() {
5420                    to_inherit_attrs.push(attr.clone());
5421                }
5422
5423                continue 'attrs_loop;
5424            }
5425        }
5426    }
5427
5428    DelegationAttrs { flags, to_inherit: to_inherit_attrs }
5429}
5430
5431impl<'ast> Visitor<'ast> for ItemInfoCollector<'_, '_, '_> {
5432    fn visit_item(&mut self, item: &'ast Item) {
5433        match &item.kind {
5434            ItemKind::TyAlias(box TyAlias { generics, .. })
5435            | ItemKind::Const(box ConstItem { generics, .. })
5436            | ItemKind::Fn(box Fn { generics, .. })
5437            | ItemKind::Enum(_, generics, _)
5438            | ItemKind::Struct(_, generics, _)
5439            | ItemKind::Union(_, generics, _)
5440            | ItemKind::Impl(Impl { generics, .. })
5441            | ItemKind::Trait(box Trait { generics, .. })
5442            | ItemKind::TraitAlias(box TraitAlias { generics, .. }) => {
5443                if let ItemKind::Fn(box Fn { sig, .. }) = &item.kind {
5444                    self.collect_fn_info(sig.header, &sig.decl, item.id, &item.attrs);
5445                }
5446
5447                let def_id = self.r.local_def_id(item.id);
5448                let count = generics
5449                    .params
5450                    .iter()
5451                    .filter(|param| matches!(param.kind, ast::GenericParamKind::Lifetime { .. }))
5452                    .count();
5453                self.r.item_generics_num_lifetimes.insert(def_id, count);
5454            }
5455
5456            ItemKind::ForeignMod(ForeignMod { extern_span, safety: _, abi, items }) => {
5457                for foreign_item in items {
5458                    if let ForeignItemKind::Fn(box Fn { sig, .. }) = &foreign_item.kind {
5459                        let new_header =
5460                            FnHeader { ext: Extern::from_abi(*abi, *extern_span), ..sig.header };
5461                        self.collect_fn_info(new_header, &sig.decl, foreign_item.id, &item.attrs);
5462                    }
5463                }
5464            }
5465
5466            ItemKind::Mod(..)
5467            | ItemKind::Static(..)
5468            | ItemKind::Use(..)
5469            | ItemKind::ExternCrate(..)
5470            | ItemKind::MacroDef(..)
5471            | ItemKind::GlobalAsm(..)
5472            | ItemKind::MacCall(..)
5473            | ItemKind::DelegationMac(..) => {}
5474            ItemKind::Delegation(..) => {
5475                // Delegated functions have lifetimes, their count is not necessarily zero.
5476                // But skipping the delegation items here doesn't mean that the count will be considered zero,
5477                // it means there will be a panic when retrieving the count,
5478                // but for delegation items we are never actually retrieving that count in practice.
5479            }
5480        }
5481        visit::walk_item(self, item)
5482    }
5483
5484    fn visit_assoc_item(&mut self, item: &'ast AssocItem, ctxt: AssocCtxt) {
5485        if let AssocItemKind::Fn(box Fn { sig, .. }) = &item.kind {
5486            self.collect_fn_info(sig.header, &sig.decl, item.id, &item.attrs);
5487        }
5488        visit::walk_assoc_item(self, item, ctxt);
5489    }
5490}
5491
5492impl<'ra, 'tcx> Resolver<'ra, 'tcx> {
5493    pub(crate) fn late_resolve_crate(&mut self, krate: &Crate) {
5494        visit::walk_crate(&mut ItemInfoCollector { r: self }, krate);
5495        let mut late_resolution_visitor = LateResolutionVisitor::new(self);
5496        late_resolution_visitor.resolve_doc_links(&krate.attrs, MaybeExported::Ok(CRATE_NODE_ID));
5497        visit::walk_crate(&mut late_resolution_visitor, krate);
5498        for (id, span) in late_resolution_visitor.diag_metadata.unused_labels.iter() {
5499            self.lint_buffer.buffer_lint(
5500                lint::builtin::UNUSED_LABELS,
5501                *id,
5502                *span,
5503                errors::UnusedLabel,
5504            );
5505        }
5506    }
5507}
5508
5509/// Check if definition matches a path
5510fn def_id_matches_path(tcx: TyCtxt<'_>, mut def_id: DefId, expected_path: &[&str]) -> bool {
5511    let mut path = expected_path.iter().rev();
5512    while let (Some(parent), Some(next_step)) = (tcx.opt_parent(def_id), path.next()) {
5513        if !tcx.opt_item_name(def_id).is_some_and(|n| n.as_str() == *next_step) {
5514            return false;
5515        }
5516        def_id = parent;
5517    }
5518    true
5519}