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