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