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            _ => visit::walk_ty(self, ty),
958        }
959        self.diag_metadata.current_trait_object = prev;
960        self.diag_metadata.current_type_path = prev_ty;
961    }
962
963    fn visit_ty_pat(&mut self, t: &'ast TyPat) -> Self::Result {
964        match &t.kind {
965            TyPatKind::Range(start, end, _) => {
966                if let Some(start) = start {
967                    self.resolve_anon_const(start, AnonConstKind::ConstArg(IsRepeatExpr::No));
968                }
969                if let Some(end) = end {
970                    self.resolve_anon_const(end, AnonConstKind::ConstArg(IsRepeatExpr::No));
971                }
972            }
973            TyPatKind::Or(patterns) => {
974                for pat in patterns {
975                    self.visit_ty_pat(pat)
976                }
977            }
978            TyPatKind::NotNull | TyPatKind::Err(_) => {}
979        }
980    }
981
982    fn visit_poly_trait_ref(&mut self, tref: &'ast PolyTraitRef) {
983        let span = tref.span.shrink_to_lo().to(tref.trait_ref.path.span.shrink_to_lo());
984        self.with_generic_param_rib(
985            &tref.bound_generic_params,
986            RibKind::Normal,
987            tref.trait_ref.ref_id,
988            LifetimeBinderKind::PolyTrait,
989            span,
990            |this| {
991                this.visit_generic_params(&tref.bound_generic_params, false);
992                this.smart_resolve_path(
993                    tref.trait_ref.ref_id,
994                    &None,
995                    &tref.trait_ref.path,
996                    PathSource::Trait(AliasPossibility::Maybe),
997                );
998                this.visit_trait_ref(&tref.trait_ref);
999            },
1000        );
1001    }
1002    fn visit_foreign_item(&mut self, foreign_item: &'ast ForeignItem) {
1003        self.resolve_doc_links(&foreign_item.attrs, MaybeExported::Ok(foreign_item.id));
1004        let def_kind = self.r.local_def_kind(foreign_item.id);
1005        match foreign_item.kind {
1006            ForeignItemKind::TyAlias(box TyAlias { ref generics, .. }) => {
1007                self.with_generic_param_rib(
1008                    &generics.params,
1009                    RibKind::Item(HasGenericParams::Yes(generics.span), def_kind),
1010                    foreign_item.id,
1011                    LifetimeBinderKind::Item,
1012                    generics.span,
1013                    |this| visit::walk_item(this, foreign_item),
1014                );
1015            }
1016            ForeignItemKind::Fn(box Fn { ref generics, .. }) => {
1017                self.with_generic_param_rib(
1018                    &generics.params,
1019                    RibKind::Item(HasGenericParams::Yes(generics.span), def_kind),
1020                    foreign_item.id,
1021                    LifetimeBinderKind::Function,
1022                    generics.span,
1023                    |this| visit::walk_item(this, foreign_item),
1024                );
1025            }
1026            ForeignItemKind::Static(..) => {
1027                self.with_static_rib(def_kind, |this| visit::walk_item(this, foreign_item))
1028            }
1029            ForeignItemKind::MacCall(..) => {
1030                panic!("unexpanded macro in resolve!")
1031            }
1032        }
1033    }
1034    fn visit_fn(&mut self, fn_kind: FnKind<'ast>, _: &AttrVec, sp: Span, fn_id: NodeId) {
1035        let previous_value = self.diag_metadata.current_function;
1036        match fn_kind {
1037            // Bail if the function is foreign, and thus cannot validly have
1038            // a body, or if there's no body for some other reason.
1039            FnKind::Fn(FnCtxt::Foreign, _, Fn { sig, ident, generics, .. })
1040            | FnKind::Fn(_, _, Fn { sig, ident, generics, body: None, .. }) => {
1041                self.visit_fn_header(&sig.header);
1042                self.visit_ident(ident);
1043                self.visit_generics(generics);
1044                self.resolve_fn_signature(
1045                    fn_id,
1046                    sig.decl.has_self(),
1047                    sig.decl.inputs.iter().map(|Param { ty, .. }| (None, &**ty)),
1048                    &sig.decl.output,
1049                    false,
1050                );
1051                return;
1052            }
1053            FnKind::Fn(..) => {
1054                self.diag_metadata.current_function = Some((fn_kind, sp));
1055            }
1056            // Do not update `current_function` for closures: it suggests `self` parameters.
1057            FnKind::Closure(..) => {}
1058        };
1059        debug!("(resolving function) entering function");
1060
1061        // Create a value rib for the function.
1062        self.with_rib(ValueNS, RibKind::FnOrCoroutine, |this| {
1063            // Create a label rib for the function.
1064            this.with_label_rib(RibKind::FnOrCoroutine, |this| {
1065                match fn_kind {
1066                    FnKind::Fn(_, _, Fn { sig, generics, contract, body, .. }) => {
1067                        this.visit_generics(generics);
1068
1069                        let declaration = &sig.decl;
1070                        let coro_node_id = sig
1071                            .header
1072                            .coroutine_kind
1073                            .map(|coroutine_kind| coroutine_kind.return_id());
1074
1075                        this.resolve_fn_signature(
1076                            fn_id,
1077                            declaration.has_self(),
1078                            declaration
1079                                .inputs
1080                                .iter()
1081                                .map(|Param { pat, ty, .. }| (Some(&**pat), &**ty)),
1082                            &declaration.output,
1083                            coro_node_id.is_some(),
1084                        );
1085
1086                        if let Some(contract) = contract {
1087                            this.visit_contract(contract);
1088                        }
1089
1090                        if let Some(body) = body {
1091                            // Ignore errors in function bodies if this is rustdoc
1092                            // Be sure not to set this until the function signature has been resolved.
1093                            let previous_state = replace(&mut this.in_func_body, true);
1094                            // We only care block in the same function
1095                            this.last_block_rib = None;
1096                            // Resolve the function body, potentially inside the body of an async closure
1097                            this.with_lifetime_rib(
1098                                LifetimeRibKind::Elided(LifetimeRes::Infer),
1099                                |this| this.visit_block(body),
1100                            );
1101
1102                            debug!("(resolving function) leaving function");
1103                            this.in_func_body = previous_state;
1104                        }
1105                    }
1106                    FnKind::Closure(binder, _, declaration, body) => {
1107                        this.visit_closure_binder(binder);
1108
1109                        this.with_lifetime_rib(
1110                            match binder {
1111                                // We do not have any explicit generic lifetime parameter.
1112                                ClosureBinder::NotPresent => {
1113                                    LifetimeRibKind::AnonymousCreateParameter {
1114                                        binder: fn_id,
1115                                        report_in_path: false,
1116                                    }
1117                                }
1118                                ClosureBinder::For { .. } => LifetimeRibKind::AnonymousReportError,
1119                            },
1120                            // Add each argument to the rib.
1121                            |this| this.resolve_params(&declaration.inputs),
1122                        );
1123                        this.with_lifetime_rib(
1124                            match binder {
1125                                ClosureBinder::NotPresent => {
1126                                    LifetimeRibKind::Elided(LifetimeRes::Infer)
1127                                }
1128                                ClosureBinder::For { .. } => LifetimeRibKind::AnonymousReportError,
1129                            },
1130                            |this| visit::walk_fn_ret_ty(this, &declaration.output),
1131                        );
1132
1133                        // Ignore errors in function bodies if this is rustdoc
1134                        // Be sure not to set this until the function signature has been resolved.
1135                        let previous_state = replace(&mut this.in_func_body, true);
1136                        // Resolve the function body, potentially inside the body of an async closure
1137                        this.with_lifetime_rib(
1138                            LifetimeRibKind::Elided(LifetimeRes::Infer),
1139                            |this| this.visit_expr(body),
1140                        );
1141
1142                        debug!("(resolving function) leaving function");
1143                        this.in_func_body = previous_state;
1144                    }
1145                }
1146            })
1147        });
1148        self.diag_metadata.current_function = previous_value;
1149    }
1150
1151    fn visit_lifetime(&mut self, lifetime: &'ast Lifetime, use_ctxt: visit::LifetimeCtxt) {
1152        self.resolve_lifetime(lifetime, use_ctxt)
1153    }
1154
1155    fn visit_precise_capturing_arg(&mut self, arg: &'ast PreciseCapturingArg) {
1156        match arg {
1157            // Lower the lifetime regularly; we'll resolve the lifetime and check
1158            // it's a parameter later on in HIR lowering.
1159            PreciseCapturingArg::Lifetime(_) => {}
1160
1161            PreciseCapturingArg::Arg(path, id) => {
1162                // we want `impl use<C>` to try to resolve `C` as both a type parameter or
1163                // a const parameter. Since the resolver specifically doesn't allow having
1164                // two generic params with the same name, even if they're a different namespace,
1165                // it doesn't really matter which we try resolving first, but just like
1166                // `Ty::Param` we just fall back to the value namespace only if it's missing
1167                // from the type namespace.
1168                let mut check_ns = |ns| {
1169                    self.maybe_resolve_ident_in_lexical_scope(path.segments[0].ident, ns).is_some()
1170                };
1171                // Like `Ty::Param`, we try resolving this as both a const and a type.
1172                if !check_ns(TypeNS) && check_ns(ValueNS) {
1173                    self.smart_resolve_path(
1174                        *id,
1175                        &None,
1176                        path,
1177                        PathSource::PreciseCapturingArg(ValueNS),
1178                    );
1179                } else {
1180                    self.smart_resolve_path(
1181                        *id,
1182                        &None,
1183                        path,
1184                        PathSource::PreciseCapturingArg(TypeNS),
1185                    );
1186                }
1187            }
1188        }
1189
1190        visit::walk_precise_capturing_arg(self, arg)
1191    }
1192
1193    fn visit_generics(&mut self, generics: &'ast Generics) {
1194        self.visit_generic_params(&generics.params, self.diag_metadata.current_self_item.is_some());
1195        for p in &generics.where_clause.predicates {
1196            self.visit_where_predicate(p);
1197        }
1198    }
1199
1200    fn visit_closure_binder(&mut self, b: &'ast ClosureBinder) {
1201        match b {
1202            ClosureBinder::NotPresent => {}
1203            ClosureBinder::For { generic_params, .. } => {
1204                self.visit_generic_params(
1205                    generic_params,
1206                    self.diag_metadata.current_self_item.is_some(),
1207                );
1208            }
1209        }
1210    }
1211
1212    fn visit_generic_arg(&mut self, arg: &'ast GenericArg) {
1213        debug!("visit_generic_arg({:?})", arg);
1214        let prev = replace(&mut self.diag_metadata.currently_processing_generic_args, true);
1215        match arg {
1216            GenericArg::Type(ty) => {
1217                // We parse const arguments as path types as we cannot distinguish them during
1218                // parsing. We try to resolve that ambiguity by attempting resolution the type
1219                // namespace first, and if that fails we try again in the value namespace. If
1220                // resolution in the value namespace succeeds, we have an generic const argument on
1221                // our hands.
1222                if let TyKind::Path(None, ref path) = ty.kind
1223                    // We cannot disambiguate multi-segment paths right now as that requires type
1224                    // checking.
1225                    && path.is_potential_trivial_const_arg(false)
1226                {
1227                    let mut check_ns = |ns| {
1228                        self.maybe_resolve_ident_in_lexical_scope(path.segments[0].ident, ns)
1229                            .is_some()
1230                    };
1231                    if !check_ns(TypeNS) && check_ns(ValueNS) {
1232                        self.resolve_anon_const_manual(
1233                            true,
1234                            AnonConstKind::ConstArg(IsRepeatExpr::No),
1235                            |this| {
1236                                this.smart_resolve_path(ty.id, &None, path, PathSource::Expr(None));
1237                                this.visit_path(path);
1238                            },
1239                        );
1240
1241                        self.diag_metadata.currently_processing_generic_args = prev;
1242                        return;
1243                    }
1244                }
1245
1246                self.visit_ty(ty);
1247            }
1248            GenericArg::Lifetime(lt) => self.visit_lifetime(lt, visit::LifetimeCtxt::GenericArg),
1249            GenericArg::Const(ct) => {
1250                self.resolve_anon_const(ct, AnonConstKind::ConstArg(IsRepeatExpr::No))
1251            }
1252        }
1253        self.diag_metadata.currently_processing_generic_args = prev;
1254    }
1255
1256    fn visit_assoc_item_constraint(&mut self, constraint: &'ast AssocItemConstraint) {
1257        self.visit_ident(&constraint.ident);
1258        if let Some(ref gen_args) = constraint.gen_args {
1259            // Forbid anonymous lifetimes in GAT parameters until proper semantics are decided.
1260            self.with_lifetime_rib(LifetimeRibKind::AnonymousReportError, |this| {
1261                this.visit_generic_args(gen_args)
1262            });
1263        }
1264        match constraint.kind {
1265            AssocItemConstraintKind::Equality { ref term } => match term {
1266                Term::Ty(ty) => self.visit_ty(ty),
1267                Term::Const(c) => {
1268                    self.resolve_anon_const(c, AnonConstKind::ConstArg(IsRepeatExpr::No))
1269                }
1270            },
1271            AssocItemConstraintKind::Bound { ref bounds } => {
1272                walk_list!(self, visit_param_bound, bounds, BoundKind::Bound);
1273            }
1274        }
1275    }
1276
1277    fn visit_path_segment(&mut self, path_segment: &'ast PathSegment) {
1278        let Some(ref args) = path_segment.args else {
1279            return;
1280        };
1281
1282        match &**args {
1283            GenericArgs::AngleBracketed(..) => visit::walk_generic_args(self, args),
1284            GenericArgs::Parenthesized(p_args) => {
1285                // Probe the lifetime ribs to know how to behave.
1286                for rib in self.lifetime_ribs.iter().rev() {
1287                    match rib.kind {
1288                        // We are inside a `PolyTraitRef`. The lifetimes are
1289                        // to be introduced in that (maybe implicit) `for<>` binder.
1290                        LifetimeRibKind::Generics {
1291                            binder,
1292                            kind: LifetimeBinderKind::PolyTrait,
1293                            ..
1294                        } => {
1295                            self.resolve_fn_signature(
1296                                binder,
1297                                false,
1298                                p_args.inputs.iter().map(|ty| (None, &**ty)),
1299                                &p_args.output,
1300                                false,
1301                            );
1302                            break;
1303                        }
1304                        // We have nowhere to introduce generics. Code is malformed,
1305                        // so use regular lifetime resolution to avoid spurious errors.
1306                        LifetimeRibKind::Item | LifetimeRibKind::Generics { .. } => {
1307                            visit::walk_generic_args(self, args);
1308                            break;
1309                        }
1310                        LifetimeRibKind::AnonymousCreateParameter { .. }
1311                        | LifetimeRibKind::AnonymousReportError
1312                        | LifetimeRibKind::StaticIfNoLifetimeInScope { .. }
1313                        | LifetimeRibKind::Elided(_)
1314                        | LifetimeRibKind::ElisionFailure
1315                        | LifetimeRibKind::ConcreteAnonConst(_)
1316                        | LifetimeRibKind::ConstParamTy => {}
1317                    }
1318                }
1319            }
1320            GenericArgs::ParenthesizedElided(_) => {}
1321        }
1322    }
1323
1324    fn visit_where_predicate(&mut self, p: &'ast WherePredicate) {
1325        debug!("visit_where_predicate {:?}", p);
1326        let previous_value = replace(&mut self.diag_metadata.current_where_predicate, Some(p));
1327        self.with_lifetime_rib(LifetimeRibKind::AnonymousReportError, |this| {
1328            if let WherePredicateKind::BoundPredicate(WhereBoundPredicate {
1329                bounded_ty,
1330                bounds,
1331                bound_generic_params,
1332                ..
1333            }) = &p.kind
1334            {
1335                let span = p.span.shrink_to_lo().to(bounded_ty.span.shrink_to_lo());
1336                this.with_generic_param_rib(
1337                    bound_generic_params,
1338                    RibKind::Normal,
1339                    bounded_ty.id,
1340                    LifetimeBinderKind::WhereBound,
1341                    span,
1342                    |this| {
1343                        this.visit_generic_params(bound_generic_params, false);
1344                        this.visit_ty(bounded_ty);
1345                        for bound in bounds {
1346                            this.visit_param_bound(bound, BoundKind::Bound)
1347                        }
1348                    },
1349                );
1350            } else {
1351                visit::walk_where_predicate(this, p);
1352            }
1353        });
1354        self.diag_metadata.current_where_predicate = previous_value;
1355    }
1356
1357    fn visit_inline_asm(&mut self, asm: &'ast InlineAsm) {
1358        for (op, _) in &asm.operands {
1359            match op {
1360                InlineAsmOperand::In { expr, .. }
1361                | InlineAsmOperand::Out { expr: Some(expr), .. }
1362                | InlineAsmOperand::InOut { expr, .. } => self.visit_expr(expr),
1363                InlineAsmOperand::Out { expr: None, .. } => {}
1364                InlineAsmOperand::SplitInOut { in_expr, out_expr, .. } => {
1365                    self.visit_expr(in_expr);
1366                    if let Some(out_expr) = out_expr {
1367                        self.visit_expr(out_expr);
1368                    }
1369                }
1370                InlineAsmOperand::Const { anon_const, .. } => {
1371                    // Although this is `DefKind::AnonConst`, it is allowed to reference outer
1372                    // generic parameters like an inline const.
1373                    self.resolve_anon_const(anon_const, AnonConstKind::InlineConst);
1374                }
1375                InlineAsmOperand::Sym { sym } => self.visit_inline_asm_sym(sym),
1376                InlineAsmOperand::Label { block } => self.visit_block(block),
1377            }
1378        }
1379    }
1380
1381    fn visit_inline_asm_sym(&mut self, sym: &'ast InlineAsmSym) {
1382        // This is similar to the code for AnonConst.
1383        self.with_rib(ValueNS, RibKind::InlineAsmSym, |this| {
1384            this.with_rib(TypeNS, RibKind::InlineAsmSym, |this| {
1385                this.with_label_rib(RibKind::InlineAsmSym, |this| {
1386                    this.smart_resolve_path(sym.id, &sym.qself, &sym.path, PathSource::Expr(None));
1387                    visit::walk_inline_asm_sym(this, sym);
1388                });
1389            })
1390        });
1391    }
1392
1393    fn visit_variant(&mut self, v: &'ast Variant) {
1394        self.resolve_doc_links(&v.attrs, MaybeExported::Ok(v.id));
1395        self.visit_id(v.id);
1396        walk_list!(self, visit_attribute, &v.attrs);
1397        self.visit_vis(&v.vis);
1398        self.visit_ident(&v.ident);
1399        self.visit_variant_data(&v.data);
1400        if let Some(discr) = &v.disr_expr {
1401            self.resolve_anon_const(discr, AnonConstKind::EnumDiscriminant);
1402        }
1403    }
1404
1405    fn visit_field_def(&mut self, f: &'ast FieldDef) {
1406        self.resolve_doc_links(&f.attrs, MaybeExported::Ok(f.id));
1407        let FieldDef {
1408            attrs,
1409            id: _,
1410            span: _,
1411            vis,
1412            ident,
1413            ty,
1414            is_placeholder: _,
1415            default,
1416            safety: _,
1417        } = f;
1418        walk_list!(self, visit_attribute, attrs);
1419        try_visit!(self.visit_vis(vis));
1420        visit_opt!(self, visit_ident, ident);
1421        try_visit!(self.visit_ty(ty));
1422        if let Some(v) = &default {
1423            self.resolve_anon_const(v, AnonConstKind::FieldDefaultValue);
1424        }
1425    }
1426}
1427
1428impl<'a, 'ast, 'ra, 'tcx> LateResolutionVisitor<'a, 'ast, 'ra, 'tcx> {
1429    fn new(resolver: &'a mut Resolver<'ra, 'tcx>) -> LateResolutionVisitor<'a, 'ast, 'ra, 'tcx> {
1430        // During late resolution we only track the module component of the parent scope,
1431        // although it may be useful to track other components as well for diagnostics.
1432        let graph_root = resolver.graph_root;
1433        let parent_scope = ParentScope::module(graph_root, resolver.arenas);
1434        let start_rib_kind = RibKind::Module(graph_root);
1435        LateResolutionVisitor {
1436            r: resolver,
1437            parent_scope,
1438            ribs: PerNS {
1439                value_ns: vec![Rib::new(start_rib_kind)],
1440                type_ns: vec![Rib::new(start_rib_kind)],
1441                macro_ns: vec![Rib::new(start_rib_kind)],
1442            },
1443            last_block_rib: None,
1444            label_ribs: Vec::new(),
1445            lifetime_ribs: Vec::new(),
1446            lifetime_elision_candidates: None,
1447            current_trait_ref: None,
1448            diag_metadata: Default::default(),
1449            // errors at module scope should always be reported
1450            in_func_body: false,
1451            lifetime_uses: Default::default(),
1452        }
1453    }
1454
1455    fn maybe_resolve_ident_in_lexical_scope(
1456        &mut self,
1457        ident: Ident,
1458        ns: Namespace,
1459    ) -> Option<LexicalScopeBinding<'ra>> {
1460        self.r.resolve_ident_in_lexical_scope(
1461            ident,
1462            ns,
1463            &self.parent_scope,
1464            None,
1465            &self.ribs[ns],
1466            None,
1467            Some(&self.diag_metadata),
1468        )
1469    }
1470
1471    fn resolve_ident_in_lexical_scope(
1472        &mut self,
1473        ident: Ident,
1474        ns: Namespace,
1475        finalize: Option<Finalize>,
1476        ignore_binding: Option<NameBinding<'ra>>,
1477    ) -> Option<LexicalScopeBinding<'ra>> {
1478        self.r.resolve_ident_in_lexical_scope(
1479            ident,
1480            ns,
1481            &self.parent_scope,
1482            finalize,
1483            &self.ribs[ns],
1484            ignore_binding,
1485            Some(&self.diag_metadata),
1486        )
1487    }
1488
1489    fn resolve_path(
1490        &mut self,
1491        path: &[Segment],
1492        opt_ns: Option<Namespace>, // `None` indicates a module path in import
1493        finalize: Option<Finalize>,
1494        source: PathSource<'_, 'ast, 'ra>,
1495    ) -> PathResult<'ra> {
1496        self.r.cm().resolve_path_with_ribs(
1497            path,
1498            opt_ns,
1499            &self.parent_scope,
1500            Some(source),
1501            finalize,
1502            Some(&self.ribs),
1503            None,
1504            None,
1505            Some(&self.diag_metadata),
1506        )
1507    }
1508
1509    // AST resolution
1510    //
1511    // We maintain a list of value ribs and type ribs.
1512    //
1513    // Simultaneously, we keep track of the current position in the module
1514    // graph in the `parent_scope.module` pointer. When we go to resolve a name in
1515    // the value or type namespaces, we first look through all the ribs and
1516    // then query the module graph. When we resolve a name in the module
1517    // namespace, we can skip all the ribs (since nested modules are not
1518    // allowed within blocks in Rust) and jump straight to the current module
1519    // graph node.
1520    //
1521    // Named implementations are handled separately. When we find a method
1522    // call, we consult the module node to find all of the implementations in
1523    // scope. This information is lazily cached in the module node. We then
1524    // generate a fake "implementation scope" containing all the
1525    // implementations thus found, for compatibility with old resolve pass.
1526
1527    /// Do some `work` within a new innermost rib of the given `kind` in the given namespace (`ns`).
1528    fn with_rib<T>(
1529        &mut self,
1530        ns: Namespace,
1531        kind: RibKind<'ra>,
1532        work: impl FnOnce(&mut Self) -> T,
1533    ) -> T {
1534        self.ribs[ns].push(Rib::new(kind));
1535        let ret = work(self);
1536        self.ribs[ns].pop();
1537        ret
1538    }
1539
1540    fn visit_generic_params(&mut self, params: &'ast [GenericParam], add_self_upper: bool) {
1541        // For type parameter defaults, we have to ban access
1542        // to following type parameters, as the GenericArgs can only
1543        // provide previous type parameters as they're built. We
1544        // put all the parameters on the ban list and then remove
1545        // them one by one as they are processed and become available.
1546        let mut forward_ty_ban_rib =
1547            Rib::new(RibKind::ForwardGenericParamBan(ForwardGenericParamBanReason::Default));
1548        let mut forward_const_ban_rib =
1549            Rib::new(RibKind::ForwardGenericParamBan(ForwardGenericParamBanReason::Default));
1550        for param in params.iter() {
1551            match param.kind {
1552                GenericParamKind::Type { .. } => {
1553                    forward_ty_ban_rib
1554                        .bindings
1555                        .insert(Ident::with_dummy_span(param.ident.name), Res::Err);
1556                }
1557                GenericParamKind::Const { .. } => {
1558                    forward_const_ban_rib
1559                        .bindings
1560                        .insert(Ident::with_dummy_span(param.ident.name), Res::Err);
1561                }
1562                GenericParamKind::Lifetime => {}
1563            }
1564        }
1565
1566        // rust-lang/rust#61631: The type `Self` is essentially
1567        // another type parameter. For ADTs, we consider it
1568        // well-defined only after all of the ADT type parameters have
1569        // been provided. Therefore, we do not allow use of `Self`
1570        // anywhere in ADT type parameter defaults.
1571        //
1572        // (We however cannot ban `Self` for defaults on *all* generic
1573        // lists; e.g. trait generics can usefully refer to `Self`,
1574        // such as in the case of `trait Add<Rhs = Self>`.)
1575        if add_self_upper {
1576            // (`Some` if + only if we are in ADT's generics.)
1577            forward_ty_ban_rib.bindings.insert(Ident::with_dummy_span(kw::SelfUpper), Res::Err);
1578        }
1579
1580        // NOTE: We use different ribs here not for a technical reason, but just
1581        // for better diagnostics.
1582        let mut forward_ty_ban_rib_const_param_ty = Rib {
1583            bindings: forward_ty_ban_rib.bindings.clone(),
1584            patterns_with_skipped_bindings: Default::default(),
1585            kind: RibKind::ForwardGenericParamBan(ForwardGenericParamBanReason::ConstParamTy),
1586        };
1587        let mut forward_const_ban_rib_const_param_ty = Rib {
1588            bindings: forward_const_ban_rib.bindings.clone(),
1589            patterns_with_skipped_bindings: Default::default(),
1590            kind: RibKind::ForwardGenericParamBan(ForwardGenericParamBanReason::ConstParamTy),
1591        };
1592        // We'll ban these with a `ConstParamTy` rib, so just clear these ribs for better
1593        // diagnostics, so we don't mention anything about const param tys having generics at all.
1594        if !self.r.tcx.features().generic_const_parameter_types() {
1595            forward_ty_ban_rib_const_param_ty.bindings.clear();
1596            forward_const_ban_rib_const_param_ty.bindings.clear();
1597        }
1598
1599        self.with_lifetime_rib(LifetimeRibKind::AnonymousReportError, |this| {
1600            for param in params {
1601                match param.kind {
1602                    GenericParamKind::Lifetime => {
1603                        for bound in &param.bounds {
1604                            this.visit_param_bound(bound, BoundKind::Bound);
1605                        }
1606                    }
1607                    GenericParamKind::Type { ref default } => {
1608                        for bound in &param.bounds {
1609                            this.visit_param_bound(bound, BoundKind::Bound);
1610                        }
1611
1612                        if let Some(ty) = default {
1613                            this.ribs[TypeNS].push(forward_ty_ban_rib);
1614                            this.ribs[ValueNS].push(forward_const_ban_rib);
1615                            this.visit_ty(ty);
1616                            forward_const_ban_rib = this.ribs[ValueNS].pop().unwrap();
1617                            forward_ty_ban_rib = this.ribs[TypeNS].pop().unwrap();
1618                        }
1619
1620                        // Allow all following defaults to refer to this type parameter.
1621                        let i = &Ident::with_dummy_span(param.ident.name);
1622                        forward_ty_ban_rib.bindings.swap_remove(i);
1623                        forward_ty_ban_rib_const_param_ty.bindings.swap_remove(i);
1624                    }
1625                    GenericParamKind::Const { ref ty, span: _, ref default } => {
1626                        // Const parameters can't have param bounds.
1627                        assert!(param.bounds.is_empty());
1628
1629                        this.ribs[TypeNS].push(forward_ty_ban_rib_const_param_ty);
1630                        this.ribs[ValueNS].push(forward_const_ban_rib_const_param_ty);
1631                        if this.r.tcx.features().generic_const_parameter_types() {
1632                            this.visit_ty(ty)
1633                        } else {
1634                            this.ribs[TypeNS].push(Rib::new(RibKind::ConstParamTy));
1635                            this.ribs[ValueNS].push(Rib::new(RibKind::ConstParamTy));
1636                            this.with_lifetime_rib(LifetimeRibKind::ConstParamTy, |this| {
1637                                this.visit_ty(ty)
1638                            });
1639                            this.ribs[TypeNS].pop().unwrap();
1640                            this.ribs[ValueNS].pop().unwrap();
1641                        }
1642                        forward_const_ban_rib_const_param_ty = this.ribs[ValueNS].pop().unwrap();
1643                        forward_ty_ban_rib_const_param_ty = this.ribs[TypeNS].pop().unwrap();
1644
1645                        if let Some(expr) = default {
1646                            this.ribs[TypeNS].push(forward_ty_ban_rib);
1647                            this.ribs[ValueNS].push(forward_const_ban_rib);
1648                            this.resolve_anon_const(
1649                                expr,
1650                                AnonConstKind::ConstArg(IsRepeatExpr::No),
1651                            );
1652                            forward_const_ban_rib = this.ribs[ValueNS].pop().unwrap();
1653                            forward_ty_ban_rib = this.ribs[TypeNS].pop().unwrap();
1654                        }
1655
1656                        // Allow all following defaults to refer to this const parameter.
1657                        let i = &Ident::with_dummy_span(param.ident.name);
1658                        forward_const_ban_rib.bindings.swap_remove(i);
1659                        forward_const_ban_rib_const_param_ty.bindings.swap_remove(i);
1660                    }
1661                }
1662            }
1663        })
1664    }
1665
1666    #[instrument(level = "debug", skip(self, work))]
1667    fn with_lifetime_rib<T>(
1668        &mut self,
1669        kind: LifetimeRibKind,
1670        work: impl FnOnce(&mut Self) -> T,
1671    ) -> T {
1672        self.lifetime_ribs.push(LifetimeRib::new(kind));
1673        let outer_elision_candidates = self.lifetime_elision_candidates.take();
1674        let ret = work(self);
1675        self.lifetime_elision_candidates = outer_elision_candidates;
1676        self.lifetime_ribs.pop();
1677        ret
1678    }
1679
1680    #[instrument(level = "debug", skip(self))]
1681    fn resolve_lifetime(&mut self, lifetime: &'ast Lifetime, use_ctxt: visit::LifetimeCtxt) {
1682        let ident = lifetime.ident;
1683
1684        if ident.name == kw::StaticLifetime {
1685            self.record_lifetime_res(
1686                lifetime.id,
1687                LifetimeRes::Static,
1688                LifetimeElisionCandidate::Named,
1689            );
1690            return;
1691        }
1692
1693        if ident.name == kw::UnderscoreLifetime {
1694            return self.resolve_anonymous_lifetime(lifetime, lifetime.id, false);
1695        }
1696
1697        let mut lifetime_rib_iter = self.lifetime_ribs.iter().rev();
1698        while let Some(rib) = lifetime_rib_iter.next() {
1699            let normalized_ident = ident.normalize_to_macros_2_0();
1700            if let Some(&(_, res)) = rib.bindings.get(&normalized_ident) {
1701                self.record_lifetime_res(lifetime.id, res, LifetimeElisionCandidate::Named);
1702
1703                if let LifetimeRes::Param { param, binder } = res {
1704                    match self.lifetime_uses.entry(param) {
1705                        Entry::Vacant(v) => {
1706                            debug!("First use of {:?} at {:?}", res, ident.span);
1707                            let use_set = self
1708                                .lifetime_ribs
1709                                .iter()
1710                                .rev()
1711                                .find_map(|rib| match rib.kind {
1712                                    // Do not suggest eliding a lifetime where an anonymous
1713                                    // lifetime would be illegal.
1714                                    LifetimeRibKind::Item
1715                                    | LifetimeRibKind::AnonymousReportError
1716                                    | LifetimeRibKind::StaticIfNoLifetimeInScope { .. }
1717                                    | LifetimeRibKind::ElisionFailure => Some(LifetimeUseSet::Many),
1718                                    // An anonymous lifetime is legal here, and bound to the right
1719                                    // place, go ahead.
1720                                    LifetimeRibKind::AnonymousCreateParameter {
1721                                        binder: anon_binder,
1722                                        ..
1723                                    } => Some(if binder == anon_binder {
1724                                        LifetimeUseSet::One { use_span: ident.span, use_ctxt }
1725                                    } else {
1726                                        LifetimeUseSet::Many
1727                                    }),
1728                                    // Only report if eliding the lifetime would have the same
1729                                    // semantics.
1730                                    LifetimeRibKind::Elided(r) => Some(if res == r {
1731                                        LifetimeUseSet::One { use_span: ident.span, use_ctxt }
1732                                    } else {
1733                                        LifetimeUseSet::Many
1734                                    }),
1735                                    LifetimeRibKind::Generics { .. }
1736                                    | LifetimeRibKind::ConstParamTy => None,
1737                                    LifetimeRibKind::ConcreteAnonConst(_) => {
1738                                        span_bug!(ident.span, "unexpected rib kind: {:?}", rib.kind)
1739                                    }
1740                                })
1741                                .unwrap_or(LifetimeUseSet::Many);
1742                            debug!(?use_ctxt, ?use_set);
1743                            v.insert(use_set);
1744                        }
1745                        Entry::Occupied(mut o) => {
1746                            debug!("Many uses of {:?} at {:?}", res, ident.span);
1747                            *o.get_mut() = LifetimeUseSet::Many;
1748                        }
1749                    }
1750                }
1751                return;
1752            }
1753
1754            match rib.kind {
1755                LifetimeRibKind::Item => break,
1756                LifetimeRibKind::ConstParamTy => {
1757                    self.emit_non_static_lt_in_const_param_ty_error(lifetime);
1758                    self.record_lifetime_res(
1759                        lifetime.id,
1760                        LifetimeRes::Error,
1761                        LifetimeElisionCandidate::Ignore,
1762                    );
1763                    return;
1764                }
1765                LifetimeRibKind::ConcreteAnonConst(cause) => {
1766                    self.emit_forbidden_non_static_lifetime_error(cause, lifetime);
1767                    self.record_lifetime_res(
1768                        lifetime.id,
1769                        LifetimeRes::Error,
1770                        LifetimeElisionCandidate::Ignore,
1771                    );
1772                    return;
1773                }
1774                LifetimeRibKind::AnonymousCreateParameter { .. }
1775                | LifetimeRibKind::Elided(_)
1776                | LifetimeRibKind::Generics { .. }
1777                | LifetimeRibKind::ElisionFailure
1778                | LifetimeRibKind::AnonymousReportError
1779                | LifetimeRibKind::StaticIfNoLifetimeInScope { .. } => {}
1780            }
1781        }
1782
1783        let normalized_ident = ident.normalize_to_macros_2_0();
1784        let outer_res = lifetime_rib_iter
1785            .find_map(|rib| rib.bindings.get_key_value(&normalized_ident).map(|(&outer, _)| outer));
1786
1787        self.emit_undeclared_lifetime_error(lifetime, outer_res);
1788        self.record_lifetime_res(lifetime.id, LifetimeRes::Error, LifetimeElisionCandidate::Named);
1789    }
1790
1791    #[instrument(level = "debug", skip(self))]
1792    fn resolve_anonymous_lifetime(
1793        &mut self,
1794        lifetime: &Lifetime,
1795        id_for_lint: NodeId,
1796        elided: bool,
1797    ) {
1798        debug_assert_eq!(lifetime.ident.name, kw::UnderscoreLifetime);
1799
1800        let kind =
1801            if elided { MissingLifetimeKind::Ampersand } else { MissingLifetimeKind::Underscore };
1802        let missing_lifetime = MissingLifetime {
1803            id: lifetime.id,
1804            span: lifetime.ident.span,
1805            kind,
1806            count: 1,
1807            id_for_lint,
1808        };
1809        let elision_candidate = LifetimeElisionCandidate::Missing(missing_lifetime);
1810        for (i, rib) in self.lifetime_ribs.iter().enumerate().rev() {
1811            debug!(?rib.kind);
1812            match rib.kind {
1813                LifetimeRibKind::AnonymousCreateParameter { binder, .. } => {
1814                    let res = self.create_fresh_lifetime(lifetime.ident, binder, kind);
1815                    self.record_lifetime_res(lifetime.id, res, elision_candidate);
1816                    return;
1817                }
1818                LifetimeRibKind::StaticIfNoLifetimeInScope { lint_id: node_id, emit_lint } => {
1819                    let mut lifetimes_in_scope = vec![];
1820                    for rib in self.lifetime_ribs[..i].iter().rev() {
1821                        lifetimes_in_scope.extend(rib.bindings.iter().map(|(ident, _)| ident.span));
1822                        // Consider any anonymous lifetimes, too
1823                        if let LifetimeRibKind::AnonymousCreateParameter { binder, .. } = rib.kind
1824                            && let Some(extra) = self.r.extra_lifetime_params_map.get(&binder)
1825                        {
1826                            lifetimes_in_scope.extend(extra.iter().map(|(ident, _, _)| ident.span));
1827                        }
1828                        if let LifetimeRibKind::Item = rib.kind {
1829                            break;
1830                        }
1831                    }
1832                    if lifetimes_in_scope.is_empty() {
1833                        self.record_lifetime_res(
1834                            lifetime.id,
1835                            LifetimeRes::Static,
1836                            elision_candidate,
1837                        );
1838                        return;
1839                    } else if emit_lint {
1840                        self.r.lint_buffer.buffer_lint(
1841                            lint::builtin::ELIDED_LIFETIMES_IN_ASSOCIATED_CONSTANT,
1842                            node_id,
1843                            lifetime.ident.span,
1844                            lint::BuiltinLintDiag::AssociatedConstElidedLifetime {
1845                                elided,
1846                                span: lifetime.ident.span,
1847                                lifetimes_in_scope: lifetimes_in_scope.into(),
1848                            },
1849                        );
1850                    }
1851                }
1852                LifetimeRibKind::AnonymousReportError => {
1853                    if elided {
1854                        let suggestion = self.lifetime_ribs[i..].iter().rev().find_map(|rib| {
1855                            if let LifetimeRibKind::Generics {
1856                                span,
1857                                kind: LifetimeBinderKind::PolyTrait | LifetimeBinderKind::WhereBound,
1858                                ..
1859                            } = rib.kind
1860                            {
1861                                Some(errors::ElidedAnonymousLifetimeReportErrorSuggestion {
1862                                    lo: span.shrink_to_lo(),
1863                                    hi: lifetime.ident.span.shrink_to_hi(),
1864                                })
1865                            } else {
1866                                None
1867                            }
1868                        });
1869                        // are we trying to use an anonymous lifetime
1870                        // on a non GAT associated trait type?
1871                        if !self.in_func_body
1872                            && let Some((module, _)) = &self.current_trait_ref
1873                            && let Some(ty) = &self.diag_metadata.current_self_type
1874                            && Some(true) == self.diag_metadata.in_non_gat_assoc_type
1875                            && let crate::ModuleKind::Def(DefKind::Trait, trait_id, _) = module.kind
1876                        {
1877                            if def_id_matches_path(
1878                                self.r.tcx,
1879                                trait_id,
1880                                &["core", "iter", "traits", "iterator", "Iterator"],
1881                            ) {
1882                                self.r.dcx().emit_err(errors::LendingIteratorReportError {
1883                                    lifetime: lifetime.ident.span,
1884                                    ty: ty.span,
1885                                });
1886                            } else {
1887                                let decl = if !trait_id.is_local()
1888                                    && let Some(assoc) = self.diag_metadata.current_impl_item
1889                                    && let AssocItemKind::Type(_) = assoc.kind
1890                                    && let assocs = self.r.tcx.associated_items(trait_id)
1891                                    && let Some(ident) = assoc.kind.ident()
1892                                    && let Some(assoc) = assocs.find_by_ident_and_kind(
1893                                        self.r.tcx,
1894                                        ident,
1895                                        AssocTag::Type,
1896                                        trait_id,
1897                                    ) {
1898                                    let mut decl: MultiSpan =
1899                                        self.r.tcx.def_span(assoc.def_id).into();
1900                                    decl.push_span_label(
1901                                        self.r.tcx.def_span(trait_id),
1902                                        String::new(),
1903                                    );
1904                                    decl
1905                                } else {
1906                                    DUMMY_SP.into()
1907                                };
1908                                let mut err = self.r.dcx().create_err(
1909                                    errors::AnonymousLifetimeNonGatReportError {
1910                                        lifetime: lifetime.ident.span,
1911                                        decl,
1912                                    },
1913                                );
1914                                self.point_at_impl_lifetimes(&mut err, i, lifetime.ident.span);
1915                                err.emit();
1916                            }
1917                        } else {
1918                            self.r.dcx().emit_err(errors::ElidedAnonymousLifetimeReportError {
1919                                span: lifetime.ident.span,
1920                                suggestion,
1921                            });
1922                        }
1923                    } else {
1924                        self.r.dcx().emit_err(errors::ExplicitAnonymousLifetimeReportError {
1925                            span: lifetime.ident.span,
1926                        });
1927                    };
1928                    self.record_lifetime_res(lifetime.id, LifetimeRes::Error, elision_candidate);
1929                    return;
1930                }
1931                LifetimeRibKind::Elided(res) => {
1932                    self.record_lifetime_res(lifetime.id, res, elision_candidate);
1933                    return;
1934                }
1935                LifetimeRibKind::ElisionFailure => {
1936                    self.diag_metadata.current_elision_failures.push(missing_lifetime);
1937                    self.record_lifetime_res(lifetime.id, LifetimeRes::Error, elision_candidate);
1938                    return;
1939                }
1940                LifetimeRibKind::Item => break,
1941                LifetimeRibKind::Generics { .. } | LifetimeRibKind::ConstParamTy => {}
1942                LifetimeRibKind::ConcreteAnonConst(_) => {
1943                    // There is always an `Elided(LifetimeRes::Infer)` inside an `AnonConst`.
1944                    span_bug!(lifetime.ident.span, "unexpected rib kind: {:?}", rib.kind)
1945                }
1946            }
1947        }
1948        self.record_lifetime_res(lifetime.id, LifetimeRes::Error, elision_candidate);
1949        self.report_missing_lifetime_specifiers(vec![missing_lifetime], None);
1950    }
1951
1952    fn point_at_impl_lifetimes(&mut self, err: &mut Diag<'_>, i: usize, lifetime: Span) {
1953        let Some((rib, span)) =
1954            self.lifetime_ribs[..i].iter().rev().find_map(|rib| match rib.kind {
1955                LifetimeRibKind::Generics { span, kind: LifetimeBinderKind::ImplBlock, .. } => {
1956                    Some((rib, span))
1957                }
1958                _ => None,
1959            })
1960        else {
1961            return;
1962        };
1963        if !rib.bindings.is_empty() {
1964            err.span_label(
1965                span,
1966                format!(
1967                    "there {} named lifetime{} specified on the impl block you could use",
1968                    if rib.bindings.len() == 1 { "is a" } else { "are" },
1969                    pluralize!(rib.bindings.len()),
1970                ),
1971            );
1972            if rib.bindings.len() == 1 {
1973                err.span_suggestion_verbose(
1974                    lifetime.shrink_to_hi(),
1975                    "consider using the lifetime from the impl block",
1976                    format!("{} ", rib.bindings.keys().next().unwrap()),
1977                    Applicability::MaybeIncorrect,
1978                );
1979            }
1980        } else {
1981            struct AnonRefFinder;
1982            impl<'ast> Visitor<'ast> for AnonRefFinder {
1983                type Result = ControlFlow<Span>;
1984
1985                fn visit_ty(&mut self, ty: &'ast ast::Ty) -> Self::Result {
1986                    if let ast::TyKind::Ref(None, mut_ty) = &ty.kind {
1987                        return ControlFlow::Break(mut_ty.ty.span.shrink_to_lo());
1988                    }
1989                    visit::walk_ty(self, ty)
1990                }
1991
1992                fn visit_lifetime(
1993                    &mut self,
1994                    lt: &'ast ast::Lifetime,
1995                    _cx: visit::LifetimeCtxt,
1996                ) -> Self::Result {
1997                    if lt.ident.name == kw::UnderscoreLifetime {
1998                        return ControlFlow::Break(lt.ident.span);
1999                    }
2000                    visit::walk_lifetime(self, lt)
2001                }
2002            }
2003
2004            if let Some(ty) = &self.diag_metadata.current_self_type
2005                && let ControlFlow::Break(sp) = AnonRefFinder.visit_ty(ty)
2006            {
2007                err.multipart_suggestion_verbose(
2008                    "add a lifetime to the impl block and use it in the self type and associated \
2009                     type",
2010                    vec![
2011                        (span, "<'a>".to_string()),
2012                        (sp, "'a ".to_string()),
2013                        (lifetime.shrink_to_hi(), "'a ".to_string()),
2014                    ],
2015                    Applicability::MaybeIncorrect,
2016                );
2017            } else if let Some(item) = &self.diag_metadata.current_item
2018                && let ItemKind::Impl(impl_) = &item.kind
2019                && let Some(of_trait) = &impl_.of_trait
2020                && let ControlFlow::Break(sp) = AnonRefFinder.visit_trait_ref(&of_trait.trait_ref)
2021            {
2022                err.multipart_suggestion_verbose(
2023                    "add a lifetime to the impl block and use it in the trait and associated type",
2024                    vec![
2025                        (span, "<'a>".to_string()),
2026                        (sp, "'a".to_string()),
2027                        (lifetime.shrink_to_hi(), "'a ".to_string()),
2028                    ],
2029                    Applicability::MaybeIncorrect,
2030                );
2031            } else {
2032                err.span_label(
2033                    span,
2034                    "you could add a lifetime on the impl block, if the trait or the self type \
2035                     could have one",
2036                );
2037            }
2038        }
2039    }
2040
2041    #[instrument(level = "debug", skip(self))]
2042    fn resolve_elided_lifetime(&mut self, anchor_id: NodeId, span: Span) {
2043        let id = self.r.next_node_id();
2044        let lt = Lifetime { id, ident: Ident::new(kw::UnderscoreLifetime, span) };
2045
2046        self.record_lifetime_res(
2047            anchor_id,
2048            LifetimeRes::ElidedAnchor { start: id, end: id + 1 },
2049            LifetimeElisionCandidate::Ignore,
2050        );
2051        self.resolve_anonymous_lifetime(&lt, anchor_id, true);
2052    }
2053
2054    #[instrument(level = "debug", skip(self))]
2055    fn create_fresh_lifetime(
2056        &mut self,
2057        ident: Ident,
2058        binder: NodeId,
2059        kind: MissingLifetimeKind,
2060    ) -> LifetimeRes {
2061        debug_assert_eq!(ident.name, kw::UnderscoreLifetime);
2062        debug!(?ident.span);
2063
2064        // Leave the responsibility to create the `LocalDefId` to lowering.
2065        let param = self.r.next_node_id();
2066        let res = LifetimeRes::Fresh { param, binder, kind };
2067        self.record_lifetime_param(param, res);
2068
2069        // Record the created lifetime parameter so lowering can pick it up and add it to HIR.
2070        self.r
2071            .extra_lifetime_params_map
2072            .entry(binder)
2073            .or_insert_with(Vec::new)
2074            .push((ident, param, res));
2075        res
2076    }
2077
2078    #[instrument(level = "debug", skip(self))]
2079    fn resolve_elided_lifetimes_in_path(
2080        &mut self,
2081        partial_res: PartialRes,
2082        path: &[Segment],
2083        source: PathSource<'_, 'ast, 'ra>,
2084        path_span: Span,
2085    ) {
2086        let proj_start = path.len() - partial_res.unresolved_segments();
2087        for (i, segment) in path.iter().enumerate() {
2088            if segment.has_lifetime_args {
2089                continue;
2090            }
2091            let Some(segment_id) = segment.id else {
2092                continue;
2093            };
2094
2095            // Figure out if this is a type/trait segment,
2096            // which may need lifetime elision performed.
2097            let type_def_id = match partial_res.base_res() {
2098                Res::Def(DefKind::AssocTy, def_id) if i + 2 == proj_start => {
2099                    self.r.tcx.parent(def_id)
2100                }
2101                Res::Def(DefKind::Variant, def_id) if i + 1 == proj_start => {
2102                    self.r.tcx.parent(def_id)
2103                }
2104                Res::Def(DefKind::Struct, def_id)
2105                | Res::Def(DefKind::Union, def_id)
2106                | Res::Def(DefKind::Enum, def_id)
2107                | Res::Def(DefKind::TyAlias, def_id)
2108                | Res::Def(DefKind::Trait, def_id)
2109                    if i + 1 == proj_start =>
2110                {
2111                    def_id
2112                }
2113                _ => continue,
2114            };
2115
2116            let expected_lifetimes = self.r.item_generics_num_lifetimes(type_def_id);
2117            if expected_lifetimes == 0 {
2118                continue;
2119            }
2120
2121            let node_ids = self.r.next_node_ids(expected_lifetimes);
2122            self.record_lifetime_res(
2123                segment_id,
2124                LifetimeRes::ElidedAnchor { start: node_ids.start, end: node_ids.end },
2125                LifetimeElisionCandidate::Ignore,
2126            );
2127
2128            let inferred = match source {
2129                PathSource::Trait(..)
2130                | PathSource::TraitItem(..)
2131                | PathSource::Type
2132                | PathSource::PreciseCapturingArg(..)
2133                | PathSource::ReturnTypeNotation => false,
2134                PathSource::Expr(..)
2135                | PathSource::Pat
2136                | PathSource::Struct(_)
2137                | PathSource::TupleStruct(..)
2138                | PathSource::DefineOpaques
2139                | PathSource::Delegation => true,
2140            };
2141            if inferred {
2142                // Do not create a parameter for patterns and expressions: type checking can infer
2143                // the appropriate lifetime for us.
2144                for id in node_ids {
2145                    self.record_lifetime_res(
2146                        id,
2147                        LifetimeRes::Infer,
2148                        LifetimeElisionCandidate::Named,
2149                    );
2150                }
2151                continue;
2152            }
2153
2154            let elided_lifetime_span = if segment.has_generic_args {
2155                // If there are brackets, but not generic arguments, then use the opening bracket
2156                segment.args_span.with_hi(segment.args_span.lo() + BytePos(1))
2157            } else {
2158                // If there are no brackets, use the identifier span.
2159                // HACK: we use find_ancestor_inside to properly suggest elided spans in paths
2160                // originating from macros, since the segment's span might be from a macro arg.
2161                segment.ident.span.find_ancestor_inside(path_span).unwrap_or(path_span)
2162            };
2163            let ident = Ident::new(kw::UnderscoreLifetime, elided_lifetime_span);
2164
2165            let kind = if segment.has_generic_args {
2166                MissingLifetimeKind::Comma
2167            } else {
2168                MissingLifetimeKind::Brackets
2169            };
2170            let missing_lifetime = MissingLifetime {
2171                id: node_ids.start,
2172                id_for_lint: segment_id,
2173                span: elided_lifetime_span,
2174                kind,
2175                count: expected_lifetimes,
2176            };
2177            let mut should_lint = true;
2178            for rib in self.lifetime_ribs.iter().rev() {
2179                match rib.kind {
2180                    // In create-parameter mode we error here because we don't want to support
2181                    // deprecated impl elision in new features like impl elision and `async fn`,
2182                    // both of which work using the `CreateParameter` mode:
2183                    //
2184                    //     impl Foo for std::cell::Ref<u32> // note lack of '_
2185                    //     async fn foo(_: std::cell::Ref<u32>) { ... }
2186                    LifetimeRibKind::AnonymousCreateParameter { report_in_path: true, .. }
2187                    | LifetimeRibKind::StaticIfNoLifetimeInScope { .. } => {
2188                        let sess = self.r.tcx.sess;
2189                        let subdiag = rustc_errors::elided_lifetime_in_path_suggestion(
2190                            sess.source_map(),
2191                            expected_lifetimes,
2192                            path_span,
2193                            !segment.has_generic_args,
2194                            elided_lifetime_span,
2195                        );
2196                        self.r.dcx().emit_err(errors::ImplicitElidedLifetimeNotAllowedHere {
2197                            span: path_span,
2198                            subdiag,
2199                        });
2200                        should_lint = false;
2201
2202                        for id in node_ids {
2203                            self.record_lifetime_res(
2204                                id,
2205                                LifetimeRes::Error,
2206                                LifetimeElisionCandidate::Named,
2207                            );
2208                        }
2209                        break;
2210                    }
2211                    // Do not create a parameter for patterns and expressions.
2212                    LifetimeRibKind::AnonymousCreateParameter { binder, .. } => {
2213                        // Group all suggestions into the first record.
2214                        let mut candidate = LifetimeElisionCandidate::Missing(missing_lifetime);
2215                        for id in node_ids {
2216                            let res = self.create_fresh_lifetime(ident, binder, kind);
2217                            self.record_lifetime_res(
2218                                id,
2219                                res,
2220                                replace(&mut candidate, LifetimeElisionCandidate::Named),
2221                            );
2222                        }
2223                        break;
2224                    }
2225                    LifetimeRibKind::Elided(res) => {
2226                        let mut candidate = LifetimeElisionCandidate::Missing(missing_lifetime);
2227                        for id in node_ids {
2228                            self.record_lifetime_res(
2229                                id,
2230                                res,
2231                                replace(&mut candidate, LifetimeElisionCandidate::Ignore),
2232                            );
2233                        }
2234                        break;
2235                    }
2236                    LifetimeRibKind::ElisionFailure => {
2237                        self.diag_metadata.current_elision_failures.push(missing_lifetime);
2238                        for id in node_ids {
2239                            self.record_lifetime_res(
2240                                id,
2241                                LifetimeRes::Error,
2242                                LifetimeElisionCandidate::Ignore,
2243                            );
2244                        }
2245                        break;
2246                    }
2247                    // `LifetimeRes::Error`, which would usually be used in the case of
2248                    // `ReportError`, is unsuitable here, as we don't emit an error yet. Instead,
2249                    // we simply resolve to an implicit lifetime, which will be checked later, at
2250                    // which point a suitable error will be emitted.
2251                    LifetimeRibKind::AnonymousReportError | LifetimeRibKind::Item => {
2252                        for id in node_ids {
2253                            self.record_lifetime_res(
2254                                id,
2255                                LifetimeRes::Error,
2256                                LifetimeElisionCandidate::Ignore,
2257                            );
2258                        }
2259                        self.report_missing_lifetime_specifiers(vec![missing_lifetime], None);
2260                        break;
2261                    }
2262                    LifetimeRibKind::Generics { .. } | LifetimeRibKind::ConstParamTy => {}
2263                    LifetimeRibKind::ConcreteAnonConst(_) => {
2264                        // There is always an `Elided(LifetimeRes::Infer)` inside an `AnonConst`.
2265                        span_bug!(elided_lifetime_span, "unexpected rib kind: {:?}", rib.kind)
2266                    }
2267                }
2268            }
2269
2270            if should_lint {
2271                self.r.lint_buffer.buffer_lint(
2272                    lint::builtin::ELIDED_LIFETIMES_IN_PATHS,
2273                    segment_id,
2274                    elided_lifetime_span,
2275                    lint::BuiltinLintDiag::ElidedLifetimesInPaths(
2276                        expected_lifetimes,
2277                        path_span,
2278                        !segment.has_generic_args,
2279                        elided_lifetime_span,
2280                    ),
2281                );
2282            }
2283        }
2284    }
2285
2286    #[instrument(level = "debug", skip(self))]
2287    fn record_lifetime_res(
2288        &mut self,
2289        id: NodeId,
2290        res: LifetimeRes,
2291        candidate: LifetimeElisionCandidate,
2292    ) {
2293        if let Some(prev_res) = self.r.lifetimes_res_map.insert(id, res) {
2294            panic!("lifetime {id:?} resolved multiple times ({prev_res:?} before, {res:?} now)")
2295        }
2296
2297        match res {
2298            LifetimeRes::Param { .. } | LifetimeRes::Fresh { .. } | LifetimeRes::Static { .. } => {
2299                if let Some(ref mut candidates) = self.lifetime_elision_candidates {
2300                    candidates.push((res, candidate));
2301                }
2302            }
2303            LifetimeRes::Infer | LifetimeRes::Error | LifetimeRes::ElidedAnchor { .. } => {}
2304        }
2305    }
2306
2307    #[instrument(level = "debug", skip(self))]
2308    fn record_lifetime_param(&mut self, id: NodeId, res: LifetimeRes) {
2309        if let Some(prev_res) = self.r.lifetimes_res_map.insert(id, res) {
2310            panic!(
2311                "lifetime parameter {id:?} resolved multiple times ({prev_res:?} before, {res:?} now)"
2312            )
2313        }
2314    }
2315
2316    /// Perform resolution of a function signature, accounting for lifetime elision.
2317    #[instrument(level = "debug", skip(self, inputs))]
2318    fn resolve_fn_signature(
2319        &mut self,
2320        fn_id: NodeId,
2321        has_self: bool,
2322        inputs: impl Iterator<Item = (Option<&'ast Pat>, &'ast Ty)> + Clone,
2323        output_ty: &'ast FnRetTy,
2324        report_elided_lifetimes_in_path: bool,
2325    ) {
2326        let rib = LifetimeRibKind::AnonymousCreateParameter {
2327            binder: fn_id,
2328            report_in_path: report_elided_lifetimes_in_path,
2329        };
2330        self.with_lifetime_rib(rib, |this| {
2331            // Add each argument to the rib.
2332            let elision_lifetime = this.resolve_fn_params(has_self, inputs);
2333            debug!(?elision_lifetime);
2334
2335            let outer_failures = take(&mut this.diag_metadata.current_elision_failures);
2336            let output_rib = if let Ok(res) = elision_lifetime.as_ref() {
2337                this.r.lifetime_elision_allowed.insert(fn_id);
2338                LifetimeRibKind::Elided(*res)
2339            } else {
2340                LifetimeRibKind::ElisionFailure
2341            };
2342            this.with_lifetime_rib(output_rib, |this| visit::walk_fn_ret_ty(this, output_ty));
2343            let elision_failures =
2344                replace(&mut this.diag_metadata.current_elision_failures, outer_failures);
2345            if !elision_failures.is_empty() {
2346                let Err(failure_info) = elision_lifetime else { bug!() };
2347                this.report_missing_lifetime_specifiers(elision_failures, Some(failure_info));
2348            }
2349        });
2350    }
2351
2352    /// Resolve inside function parameters and parameter types.
2353    /// Returns the lifetime for elision in fn return type,
2354    /// or diagnostic information in case of elision failure.
2355    fn resolve_fn_params(
2356        &mut self,
2357        has_self: bool,
2358        inputs: impl Iterator<Item = (Option<&'ast Pat>, &'ast Ty)> + Clone,
2359    ) -> Result<LifetimeRes, (Vec<MissingLifetime>, Vec<ElisionFnParameter>)> {
2360        enum Elision {
2361            /// We have not found any candidate.
2362            None,
2363            /// We have a candidate bound to `self`.
2364            Self_(LifetimeRes),
2365            /// We have a candidate bound to a parameter.
2366            Param(LifetimeRes),
2367            /// We failed elision.
2368            Err,
2369        }
2370
2371        // Save elision state to reinstate it later.
2372        let outer_candidates = self.lifetime_elision_candidates.take();
2373
2374        // Result of elision.
2375        let mut elision_lifetime = Elision::None;
2376        // Information for diagnostics.
2377        let mut parameter_info = Vec::new();
2378        let mut all_candidates = Vec::new();
2379
2380        // Resolve and apply bindings first so diagnostics can see if they're used in types.
2381        let mut bindings = smallvec![(PatBoundCtx::Product, Default::default())];
2382        for (pat, _) in inputs.clone() {
2383            debug!("resolving bindings in pat = {pat:?}");
2384            self.with_lifetime_rib(LifetimeRibKind::Elided(LifetimeRes::Infer), |this| {
2385                if let Some(pat) = pat {
2386                    this.resolve_pattern(pat, PatternSource::FnParam, &mut bindings);
2387                }
2388            });
2389        }
2390        self.apply_pattern_bindings(bindings);
2391
2392        for (index, (pat, ty)) in inputs.enumerate() {
2393            debug!("resolving type for pat = {pat:?}, ty = {ty:?}");
2394            // Record elision candidates only for this parameter.
2395            debug_assert_matches!(self.lifetime_elision_candidates, None);
2396            self.lifetime_elision_candidates = Some(Default::default());
2397            self.visit_ty(ty);
2398            let local_candidates = self.lifetime_elision_candidates.take();
2399
2400            if let Some(candidates) = local_candidates {
2401                let distinct: UnordSet<_> = candidates.iter().map(|(res, _)| *res).collect();
2402                let lifetime_count = distinct.len();
2403                if lifetime_count != 0 {
2404                    parameter_info.push(ElisionFnParameter {
2405                        index,
2406                        ident: if let Some(pat) = pat
2407                            && let PatKind::Ident(_, ident, _) = pat.kind
2408                        {
2409                            Some(ident)
2410                        } else {
2411                            None
2412                        },
2413                        lifetime_count,
2414                        span: ty.span,
2415                    });
2416                    all_candidates.extend(candidates.into_iter().filter_map(|(_, candidate)| {
2417                        match candidate {
2418                            LifetimeElisionCandidate::Ignore | LifetimeElisionCandidate::Named => {
2419                                None
2420                            }
2421                            LifetimeElisionCandidate::Missing(missing) => Some(missing),
2422                        }
2423                    }));
2424                }
2425                if !distinct.is_empty() {
2426                    match elision_lifetime {
2427                        // We are the first parameter to bind lifetimes.
2428                        Elision::None => {
2429                            if let Some(res) = distinct.get_only() {
2430                                // We have a single lifetime => success.
2431                                elision_lifetime = Elision::Param(*res)
2432                            } else {
2433                                // We have multiple lifetimes => error.
2434                                elision_lifetime = Elision::Err;
2435                            }
2436                        }
2437                        // We have 2 parameters that bind lifetimes => error.
2438                        Elision::Param(_) => elision_lifetime = Elision::Err,
2439                        // `self` elision takes precedence over everything else.
2440                        Elision::Self_(_) | Elision::Err => {}
2441                    }
2442                }
2443            }
2444
2445            // Handle `self` specially.
2446            if index == 0 && has_self {
2447                let self_lifetime = self.find_lifetime_for_self(ty);
2448                elision_lifetime = match self_lifetime {
2449                    // We found `self` elision.
2450                    Set1::One(lifetime) => Elision::Self_(lifetime),
2451                    // `self` itself had ambiguous lifetimes, e.g.
2452                    // &Box<&Self>. In this case we won't consider
2453                    // taking an alternative parameter lifetime; just avoid elision
2454                    // entirely.
2455                    Set1::Many => Elision::Err,
2456                    // We do not have `self` elision: disregard the `Elision::Param` that we may
2457                    // have found.
2458                    Set1::Empty => Elision::None,
2459                }
2460            }
2461            debug!("(resolving function / closure) recorded parameter");
2462        }
2463
2464        // Reinstate elision state.
2465        debug_assert_matches!(self.lifetime_elision_candidates, None);
2466        self.lifetime_elision_candidates = outer_candidates;
2467
2468        if let Elision::Param(res) | Elision::Self_(res) = elision_lifetime {
2469            return Ok(res);
2470        }
2471
2472        // We do not have a candidate.
2473        Err((all_candidates, parameter_info))
2474    }
2475
2476    /// List all the lifetimes that appear in the provided type.
2477    fn find_lifetime_for_self(&self, ty: &'ast Ty) -> Set1<LifetimeRes> {
2478        /// Visits a type to find all the &references, and determines the
2479        /// set of lifetimes for all of those references where the referent
2480        /// contains Self.
2481        struct FindReferenceVisitor<'a, 'ra, 'tcx> {
2482            r: &'a Resolver<'ra, 'tcx>,
2483            impl_self: Option<Res>,
2484            lifetime: Set1<LifetimeRes>,
2485        }
2486
2487        impl<'ra> Visitor<'ra> for FindReferenceVisitor<'_, '_, '_> {
2488            fn visit_ty(&mut self, ty: &'ra Ty) {
2489                trace!("FindReferenceVisitor considering ty={:?}", ty);
2490                if let TyKind::Ref(lt, _) | TyKind::PinnedRef(lt, _) = ty.kind {
2491                    // See if anything inside the &thing contains Self
2492                    let mut visitor =
2493                        SelfVisitor { r: self.r, impl_self: self.impl_self, self_found: false };
2494                    visitor.visit_ty(ty);
2495                    trace!("FindReferenceVisitor: SelfVisitor self_found={:?}", visitor.self_found);
2496                    if visitor.self_found {
2497                        let lt_id = if let Some(lt) = lt {
2498                            lt.id
2499                        } else {
2500                            let res = self.r.lifetimes_res_map[&ty.id];
2501                            let LifetimeRes::ElidedAnchor { start, .. } = res else { bug!() };
2502                            start
2503                        };
2504                        let lt_res = self.r.lifetimes_res_map[&lt_id];
2505                        trace!("FindReferenceVisitor inserting res={:?}", lt_res);
2506                        self.lifetime.insert(lt_res);
2507                    }
2508                }
2509                visit::walk_ty(self, ty)
2510            }
2511
2512            // A type may have an expression as a const generic argument.
2513            // We do not want to recurse into those.
2514            fn visit_expr(&mut self, _: &'ra Expr) {}
2515        }
2516
2517        /// Visitor which checks the referent of a &Thing to see if the
2518        /// Thing contains Self
2519        struct SelfVisitor<'a, 'ra, 'tcx> {
2520            r: &'a Resolver<'ra, 'tcx>,
2521            impl_self: Option<Res>,
2522            self_found: bool,
2523        }
2524
2525        impl SelfVisitor<'_, '_, '_> {
2526            // Look for `self: &'a Self` - also desugared from `&'a self`
2527            fn is_self_ty(&self, ty: &Ty) -> bool {
2528                match ty.kind {
2529                    TyKind::ImplicitSelf => true,
2530                    TyKind::Path(None, _) => {
2531                        let path_res = self.r.partial_res_map[&ty.id].full_res();
2532                        if let Some(Res::SelfTyParam { .. } | Res::SelfTyAlias { .. }) = path_res {
2533                            return true;
2534                        }
2535                        self.impl_self.is_some() && path_res == self.impl_self
2536                    }
2537                    _ => false,
2538                }
2539            }
2540        }
2541
2542        impl<'ra> Visitor<'ra> for SelfVisitor<'_, '_, '_> {
2543            fn visit_ty(&mut self, ty: &'ra Ty) {
2544                trace!("SelfVisitor considering ty={:?}", ty);
2545                if self.is_self_ty(ty) {
2546                    trace!("SelfVisitor found Self");
2547                    self.self_found = true;
2548                }
2549                visit::walk_ty(self, ty)
2550            }
2551
2552            // A type may have an expression as a const generic argument.
2553            // We do not want to recurse into those.
2554            fn visit_expr(&mut self, _: &'ra Expr) {}
2555        }
2556
2557        let impl_self = self
2558            .diag_metadata
2559            .current_self_type
2560            .as_ref()
2561            .and_then(|ty| {
2562                if let TyKind::Path(None, _) = ty.kind {
2563                    self.r.partial_res_map.get(&ty.id)
2564                } else {
2565                    None
2566                }
2567            })
2568            .and_then(|res| res.full_res())
2569            .filter(|res| {
2570                // Permit the types that unambiguously always
2571                // result in the same type constructor being used
2572                // (it can't differ between `Self` and `self`).
2573                matches!(
2574                    res,
2575                    Res::Def(DefKind::Struct | DefKind::Union | DefKind::Enum, _,) | Res::PrimTy(_)
2576                )
2577            });
2578        let mut visitor = FindReferenceVisitor { r: self.r, impl_self, lifetime: Set1::Empty };
2579        visitor.visit_ty(ty);
2580        trace!("FindReferenceVisitor found={:?}", visitor.lifetime);
2581        visitor.lifetime
2582    }
2583
2584    /// Searches the current set of local scopes for labels. Returns the `NodeId` of the resolved
2585    /// label and reports an error if the label is not found or is unreachable.
2586    fn resolve_label(&self, mut label: Ident) -> Result<(NodeId, Span), ResolutionError<'ra>> {
2587        let mut suggestion = None;
2588
2589        for i in (0..self.label_ribs.len()).rev() {
2590            let rib = &self.label_ribs[i];
2591
2592            if let RibKind::MacroDefinition(def) = rib.kind
2593                // If an invocation of this macro created `ident`, give up on `ident`
2594                // and switch to `ident`'s source from the macro definition.
2595                && def == self.r.macro_def(label.span.ctxt())
2596            {
2597                label.span.remove_mark();
2598            }
2599
2600            let ident = label.normalize_to_macro_rules();
2601            if let Some((ident, id)) = rib.bindings.get_key_value(&ident) {
2602                let definition_span = ident.span;
2603                return if self.is_label_valid_from_rib(i) {
2604                    Ok((*id, definition_span))
2605                } else {
2606                    Err(ResolutionError::UnreachableLabel {
2607                        name: label.name,
2608                        definition_span,
2609                        suggestion,
2610                    })
2611                };
2612            }
2613
2614            // Diagnostics: Check if this rib contains a label with a similar name, keep track of
2615            // the first such label that is encountered.
2616            suggestion = suggestion.or_else(|| self.suggestion_for_label_in_rib(i, label));
2617        }
2618
2619        Err(ResolutionError::UndeclaredLabel { name: label.name, suggestion })
2620    }
2621
2622    /// Determine whether or not a label from the `rib_index`th label rib is reachable.
2623    fn is_label_valid_from_rib(&self, rib_index: usize) -> bool {
2624        let ribs = &self.label_ribs[rib_index + 1..];
2625        ribs.iter().all(|rib| !rib.kind.is_label_barrier())
2626    }
2627
2628    fn resolve_adt(&mut self, item: &'ast Item, generics: &'ast Generics) {
2629        debug!("resolve_adt");
2630        let kind = self.r.local_def_kind(item.id);
2631        self.with_current_self_item(item, |this| {
2632            this.with_generic_param_rib(
2633                &generics.params,
2634                RibKind::Item(HasGenericParams::Yes(generics.span), kind),
2635                item.id,
2636                LifetimeBinderKind::Item,
2637                generics.span,
2638                |this| {
2639                    let item_def_id = this.r.local_def_id(item.id).to_def_id();
2640                    this.with_self_rib(
2641                        Res::SelfTyAlias {
2642                            alias_to: item_def_id,
2643                            forbid_generic: false,
2644                            is_trait_impl: false,
2645                        },
2646                        |this| {
2647                            visit::walk_item(this, item);
2648                        },
2649                    );
2650                },
2651            );
2652        });
2653    }
2654
2655    fn future_proof_import(&mut self, use_tree: &UseTree) {
2656        if let [segment, rest @ ..] = use_tree.prefix.segments.as_slice() {
2657            let ident = segment.ident;
2658            if ident.is_path_segment_keyword() || ident.span.is_rust_2015() {
2659                return;
2660            }
2661
2662            let nss = match use_tree.kind {
2663                UseTreeKind::Simple(..) if rest.is_empty() => &[TypeNS, ValueNS][..],
2664                _ => &[TypeNS],
2665            };
2666            let report_error = |this: &Self, ns| {
2667                if this.should_report_errs() {
2668                    let what = if ns == TypeNS { "type parameters" } else { "local variables" };
2669                    this.r.dcx().emit_err(errors::ImportsCannotReferTo { span: ident.span, what });
2670                }
2671            };
2672
2673            for &ns in nss {
2674                match self.maybe_resolve_ident_in_lexical_scope(ident, ns) {
2675                    Some(LexicalScopeBinding::Res(..)) => {
2676                        report_error(self, ns);
2677                    }
2678                    Some(LexicalScopeBinding::Item(binding)) => {
2679                        if let Some(LexicalScopeBinding::Res(..)) =
2680                            self.resolve_ident_in_lexical_scope(ident, ns, None, Some(binding))
2681                        {
2682                            report_error(self, ns);
2683                        }
2684                    }
2685                    None => {}
2686                }
2687            }
2688        } else if let UseTreeKind::Nested { items, .. } = &use_tree.kind {
2689            for (use_tree, _) in items {
2690                self.future_proof_import(use_tree);
2691            }
2692        }
2693    }
2694
2695    fn resolve_item(&mut self, item: &'ast Item) {
2696        let mod_inner_docs =
2697            matches!(item.kind, ItemKind::Mod(..)) && rustdoc::inner_docs(&item.attrs);
2698        if !mod_inner_docs && !matches!(item.kind, ItemKind::Impl(..) | ItemKind::Use(..)) {
2699            self.resolve_doc_links(&item.attrs, MaybeExported::Ok(item.id));
2700        }
2701
2702        debug!("(resolving item) resolving {:?} ({:?})", item.kind.ident(), item.kind);
2703
2704        let def_kind = self.r.local_def_kind(item.id);
2705        match item.kind {
2706            ItemKind::TyAlias(box TyAlias { ref generics, .. }) => {
2707                self.with_generic_param_rib(
2708                    &generics.params,
2709                    RibKind::Item(HasGenericParams::Yes(generics.span), def_kind),
2710                    item.id,
2711                    LifetimeBinderKind::Item,
2712                    generics.span,
2713                    |this| visit::walk_item(this, item),
2714                );
2715            }
2716
2717            ItemKind::Fn(box Fn { ref generics, ref define_opaque, .. }) => {
2718                self.with_generic_param_rib(
2719                    &generics.params,
2720                    RibKind::Item(HasGenericParams::Yes(generics.span), def_kind),
2721                    item.id,
2722                    LifetimeBinderKind::Function,
2723                    generics.span,
2724                    |this| visit::walk_item(this, item),
2725                );
2726                self.resolve_define_opaques(define_opaque);
2727            }
2728
2729            ItemKind::Enum(_, ref generics, _)
2730            | ItemKind::Struct(_, ref generics, _)
2731            | ItemKind::Union(_, ref generics, _) => {
2732                self.resolve_adt(item, generics);
2733            }
2734
2735            ItemKind::Impl(Impl {
2736                ref generics,
2737                ref of_trait,
2738                ref self_ty,
2739                items: ref impl_items,
2740                ..
2741            }) => {
2742                self.diag_metadata.current_impl_items = Some(impl_items);
2743                self.resolve_implementation(
2744                    &item.attrs,
2745                    generics,
2746                    of_trait.as_deref(),
2747                    self_ty,
2748                    item.id,
2749                    impl_items,
2750                );
2751                self.diag_metadata.current_impl_items = None;
2752            }
2753
2754            ItemKind::Trait(box Trait { ref generics, ref bounds, ref items, .. }) => {
2755                // Create a new rib for the trait-wide type parameters.
2756                self.with_generic_param_rib(
2757                    &generics.params,
2758                    RibKind::Item(HasGenericParams::Yes(generics.span), def_kind),
2759                    item.id,
2760                    LifetimeBinderKind::Item,
2761                    generics.span,
2762                    |this| {
2763                        let local_def_id = this.r.local_def_id(item.id).to_def_id();
2764                        this.with_self_rib(Res::SelfTyParam { trait_: local_def_id }, |this| {
2765                            this.visit_generics(generics);
2766                            walk_list!(this, visit_param_bound, bounds, BoundKind::SuperTraits);
2767                            this.resolve_trait_items(items);
2768                        });
2769                    },
2770                );
2771            }
2772
2773            ItemKind::TraitAlias(box TraitAlias { ref generics, ref bounds, .. }) => {
2774                // Create a new rib for the trait-wide type parameters.
2775                self.with_generic_param_rib(
2776                    &generics.params,
2777                    RibKind::Item(HasGenericParams::Yes(generics.span), def_kind),
2778                    item.id,
2779                    LifetimeBinderKind::Item,
2780                    generics.span,
2781                    |this| {
2782                        let local_def_id = this.r.local_def_id(item.id).to_def_id();
2783                        this.with_self_rib(Res::SelfTyParam { trait_: local_def_id }, |this| {
2784                            this.visit_generics(generics);
2785                            walk_list!(this, visit_param_bound, bounds, BoundKind::Bound);
2786                        });
2787                    },
2788                );
2789            }
2790
2791            ItemKind::Mod(..) => {
2792                let module = self.r.expect_module(self.r.local_def_id(item.id).to_def_id());
2793                let orig_module = replace(&mut self.parent_scope.module, module);
2794                self.with_rib(ValueNS, RibKind::Module(module), |this| {
2795                    this.with_rib(TypeNS, RibKind::Module(module), |this| {
2796                        if mod_inner_docs {
2797                            this.resolve_doc_links(&item.attrs, MaybeExported::Ok(item.id));
2798                        }
2799                        let old_macro_rules = this.parent_scope.macro_rules;
2800                        visit::walk_item(this, item);
2801                        // Maintain macro_rules scopes in the same way as during early resolution
2802                        // for diagnostics and doc links.
2803                        if item.attrs.iter().all(|attr| {
2804                            !attr.has_name(sym::macro_use) && !attr.has_name(sym::macro_escape)
2805                        }) {
2806                            this.parent_scope.macro_rules = old_macro_rules;
2807                        }
2808                    })
2809                });
2810                self.parent_scope.module = orig_module;
2811            }
2812
2813            ItemKind::Static(box ast::StaticItem {
2814                ident,
2815                ref ty,
2816                ref expr,
2817                ref define_opaque,
2818                ..
2819            }) => {
2820                self.with_static_rib(def_kind, |this| {
2821                    this.with_lifetime_rib(LifetimeRibKind::Elided(LifetimeRes::Static), |this| {
2822                        this.visit_ty(ty);
2823                    });
2824                    if let Some(expr) = expr {
2825                        // We already forbid generic params because of the above item rib,
2826                        // so it doesn't matter whether this is a trivial constant.
2827                        this.resolve_static_body(expr, Some((ident, ConstantItemKind::Static)));
2828                    }
2829                });
2830                self.resolve_define_opaques(define_opaque);
2831            }
2832
2833            ItemKind::Const(box ast::ConstItem {
2834                ident,
2835                ref generics,
2836                ref ty,
2837                ref rhs,
2838                ref define_opaque,
2839                ..
2840            }) => {
2841                self.with_generic_param_rib(
2842                    &generics.params,
2843                    RibKind::Item(
2844                        if self.r.tcx.features().generic_const_items() {
2845                            HasGenericParams::Yes(generics.span)
2846                        } else {
2847                            HasGenericParams::No
2848                        },
2849                        def_kind,
2850                    ),
2851                    item.id,
2852                    LifetimeBinderKind::ConstItem,
2853                    generics.span,
2854                    |this| {
2855                        this.visit_generics(generics);
2856
2857                        this.with_lifetime_rib(
2858                            LifetimeRibKind::Elided(LifetimeRes::Static),
2859                            |this| this.visit_ty(ty),
2860                        );
2861
2862                        if let Some(rhs) = rhs {
2863                            this.resolve_const_item_rhs(
2864                                rhs,
2865                                Some((ident, ConstantItemKind::Const)),
2866                            );
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<F>(
2917        &mut self,
2918        params: &[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                    rhs,
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(rhs) = rhs {
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_item_rhs(rhs, 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                rhs,
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(rhs) = rhs {
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_item_rhs(rhs, 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_static_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_const_item_rhs(
3659        &mut self,
3660        rhs: &'ast ConstItemRhs,
3661        item: Option<(Ident, ConstantItemKind)>,
3662    ) {
3663        self.with_lifetime_rib(LifetimeRibKind::Elided(LifetimeRes::Infer), |this| match rhs {
3664            ConstItemRhs::TypeConst(anon_const) => {
3665                this.resolve_anon_const(anon_const, AnonConstKind::ConstArg(IsRepeatExpr::No));
3666            }
3667            ConstItemRhs::Body(expr) => {
3668                this.with_constant_rib(IsRepeatExpr::No, ConstantHasGenerics::Yes, item, |this| {
3669                    this.visit_expr(expr)
3670                });
3671            }
3672        })
3673    }
3674
3675    fn resolve_delegation(&mut self, delegation: &'ast Delegation) {
3676        self.smart_resolve_path(
3677            delegation.id,
3678            &delegation.qself,
3679            &delegation.path,
3680            PathSource::Delegation,
3681        );
3682        if let Some(qself) = &delegation.qself {
3683            self.visit_ty(&qself.ty);
3684        }
3685        self.visit_path(&delegation.path);
3686        let Some(body) = &delegation.body else { return };
3687        self.with_rib(ValueNS, RibKind::FnOrCoroutine, |this| {
3688            let span = delegation.path.segments.last().unwrap().ident.span;
3689            let ident = Ident::new(kw::SelfLower, span.normalize_to_macro_rules());
3690            let res = Res::Local(delegation.id);
3691            this.innermost_rib_bindings(ValueNS).insert(ident, res);
3692            this.visit_block(body);
3693        });
3694    }
3695
3696    fn resolve_params(&mut self, params: &'ast [Param]) {
3697        let mut bindings = smallvec![(PatBoundCtx::Product, Default::default())];
3698        self.with_lifetime_rib(LifetimeRibKind::Elided(LifetimeRes::Infer), |this| {
3699            for Param { pat, .. } in params {
3700                this.resolve_pattern(pat, PatternSource::FnParam, &mut bindings);
3701            }
3702            this.apply_pattern_bindings(bindings);
3703        });
3704        for Param { ty, .. } in params {
3705            self.visit_ty(ty);
3706        }
3707    }
3708
3709    fn resolve_local(&mut self, local: &'ast Local) {
3710        debug!("resolving local ({:?})", local);
3711        // Resolve the type.
3712        visit_opt!(self, visit_ty, &local.ty);
3713
3714        // Resolve the initializer.
3715        if let Some((init, els)) = local.kind.init_else_opt() {
3716            self.visit_expr(init);
3717
3718            // Resolve the `else` block
3719            if let Some(els) = els {
3720                self.visit_block(els);
3721            }
3722        }
3723
3724        // Resolve the pattern.
3725        self.resolve_pattern_top(&local.pat, PatternSource::Let);
3726    }
3727
3728    /// Build a map from pattern identifiers to binding-info's, and check the bindings are
3729    /// consistent when encountering or-patterns and never patterns.
3730    /// This is done hygienically: this could arise for a macro that expands into an or-pattern
3731    /// where one 'x' was from the user and one 'x' came from the macro.
3732    ///
3733    /// A never pattern by definition indicates an unreachable case. For example, matching on
3734    /// `Result<T, &!>` could look like:
3735    /// ```rust
3736    /// # #![feature(never_type)]
3737    /// # #![feature(never_patterns)]
3738    /// # fn bar(_x: u32) {}
3739    /// let foo: Result<u32, &!> = Ok(0);
3740    /// match foo {
3741    ///     Ok(x) => bar(x),
3742    ///     Err(&!),
3743    /// }
3744    /// ```
3745    /// This extends to product types: `(x, !)` is likewise unreachable. So it doesn't make sense to
3746    /// have a binding here, and we tell the user to use `_` instead.
3747    fn compute_and_check_binding_map(
3748        &mut self,
3749        pat: &Pat,
3750    ) -> Result<FxIndexMap<Ident, BindingInfo>, IsNeverPattern> {
3751        let mut binding_map = FxIndexMap::default();
3752        let mut is_never_pat = false;
3753
3754        pat.walk(&mut |pat| {
3755            match pat.kind {
3756                PatKind::Ident(annotation, ident, ref sub_pat)
3757                    if sub_pat.is_some() || self.is_base_res_local(pat.id) =>
3758                {
3759                    binding_map.insert(ident, BindingInfo { span: ident.span, annotation });
3760                }
3761                PatKind::Or(ref ps) => {
3762                    // Check the consistency of this or-pattern and
3763                    // then add all bindings to the larger map.
3764                    match self.compute_and_check_or_pat_binding_map(ps) {
3765                        Ok(bm) => binding_map.extend(bm),
3766                        Err(IsNeverPattern) => is_never_pat = true,
3767                    }
3768                    return false;
3769                }
3770                PatKind::Never => is_never_pat = true,
3771                _ => {}
3772            }
3773
3774            true
3775        });
3776
3777        if is_never_pat {
3778            for (_, binding) in binding_map {
3779                self.report_error(binding.span, ResolutionError::BindingInNeverPattern);
3780            }
3781            Err(IsNeverPattern)
3782        } else {
3783            Ok(binding_map)
3784        }
3785    }
3786
3787    fn is_base_res_local(&self, nid: NodeId) -> bool {
3788        matches!(
3789            self.r.partial_res_map.get(&nid).map(|res| res.expect_full_res()),
3790            Some(Res::Local(..))
3791        )
3792    }
3793
3794    /// Compute the binding map for an or-pattern. Checks that all of the arms in the or-pattern
3795    /// have exactly the same set of bindings, with the same binding modes for each.
3796    /// Returns the computed binding map and a boolean indicating whether the pattern is a never
3797    /// pattern.
3798    ///
3799    /// A never pattern by definition indicates an unreachable case. For example, destructuring a
3800    /// `Result<T, &!>` could look like:
3801    /// ```rust
3802    /// # #![feature(never_type)]
3803    /// # #![feature(never_patterns)]
3804    /// # fn foo() -> Result<bool, &'static !> { Ok(true) }
3805    /// let (Ok(x) | Err(&!)) = foo();
3806    /// # let _ = x;
3807    /// ```
3808    /// Because the `Err(&!)` branch is never reached, it does not need to have the same bindings as
3809    /// the other branches of the or-pattern. So we must ignore never pattern when checking the
3810    /// bindings of an or-pattern.
3811    /// Moreover, if all the subpatterns are never patterns (e.g. `Ok(!) | Err(!)`), then the
3812    /// pattern as a whole counts as a never pattern (since it's definitionallly unreachable).
3813    fn compute_and_check_or_pat_binding_map(
3814        &mut self,
3815        pats: &[Pat],
3816    ) -> Result<FxIndexMap<Ident, BindingInfo>, IsNeverPattern> {
3817        let mut missing_vars = FxIndexMap::default();
3818        let mut inconsistent_vars = FxIndexMap::default();
3819
3820        // 1) Compute the binding maps of all arms; we must ignore never patterns here.
3821        let not_never_pats = pats
3822            .iter()
3823            .filter_map(|pat| {
3824                let binding_map = self.compute_and_check_binding_map(pat).ok()?;
3825                Some((binding_map, pat))
3826            })
3827            .collect::<Vec<_>>();
3828
3829        // 2) Record any missing bindings or binding mode inconsistencies.
3830        for &(ref map_outer, pat_outer) in not_never_pats.iter() {
3831            // Check against all arms except for the same pattern which is always self-consistent.
3832            let inners = not_never_pats.iter().filter(|(_, pat)| pat.id != pat_outer.id);
3833
3834            for &(ref map, pat) in inners {
3835                for (&name, binding_inner) in map {
3836                    match map_outer.get(&name) {
3837                        None => {
3838                            // The inner binding is missing in the outer.
3839                            let binding_error =
3840                                missing_vars.entry(name).or_insert_with(|| BindingError {
3841                                    name,
3842                                    origin: Default::default(),
3843                                    target: Default::default(),
3844                                    could_be_path: name.as_str().starts_with(char::is_uppercase),
3845                                });
3846                            binding_error.origin.push((binding_inner.span, pat.clone()));
3847                            binding_error.target.push(pat_outer.clone());
3848                        }
3849                        Some(binding_outer) => {
3850                            if binding_outer.annotation != binding_inner.annotation {
3851                                // The binding modes in the outer and inner bindings differ.
3852                                inconsistent_vars
3853                                    .entry(name)
3854                                    .or_insert((binding_inner.span, binding_outer.span));
3855                            }
3856                        }
3857                    }
3858                }
3859            }
3860        }
3861
3862        // 3) Report all missing variables we found.
3863        for (name, mut v) in missing_vars {
3864            if inconsistent_vars.contains_key(&name) {
3865                v.could_be_path = false;
3866            }
3867            self.report_error(
3868                v.origin.iter().next().unwrap().0,
3869                ResolutionError::VariableNotBoundInPattern(v, self.parent_scope),
3870            );
3871        }
3872
3873        // 4) Report all inconsistencies in binding modes we found.
3874        for (name, v) in inconsistent_vars {
3875            self.report_error(v.0, ResolutionError::VariableBoundWithDifferentMode(name, v.1));
3876        }
3877
3878        // 5) Bubble up the final binding map.
3879        if not_never_pats.is_empty() {
3880            // All the patterns are never patterns, so the whole or-pattern is one too.
3881            Err(IsNeverPattern)
3882        } else {
3883            let mut binding_map = FxIndexMap::default();
3884            for (bm, _) in not_never_pats {
3885                binding_map.extend(bm);
3886            }
3887            Ok(binding_map)
3888        }
3889    }
3890
3891    /// Check the consistency of bindings wrt or-patterns and never patterns.
3892    fn check_consistent_bindings(&mut self, pat: &'ast Pat) {
3893        let mut is_or_or_never = false;
3894        pat.walk(&mut |pat| match pat.kind {
3895            PatKind::Or(..) | PatKind::Never => {
3896                is_or_or_never = true;
3897                false
3898            }
3899            _ => true,
3900        });
3901        if is_or_or_never {
3902            let _ = self.compute_and_check_binding_map(pat);
3903        }
3904    }
3905
3906    fn resolve_arm(&mut self, arm: &'ast Arm) {
3907        self.with_rib(ValueNS, RibKind::Normal, |this| {
3908            this.resolve_pattern_top(&arm.pat, PatternSource::Match);
3909            visit_opt!(this, visit_expr, &arm.guard);
3910            visit_opt!(this, visit_expr, &arm.body);
3911        });
3912    }
3913
3914    /// Arising from `source`, resolve a top level pattern.
3915    fn resolve_pattern_top(&mut self, pat: &'ast Pat, pat_src: PatternSource) {
3916        let mut bindings = smallvec![(PatBoundCtx::Product, Default::default())];
3917        self.resolve_pattern(pat, pat_src, &mut bindings);
3918        self.apply_pattern_bindings(bindings);
3919    }
3920
3921    /// Apply the bindings from a pattern to the innermost rib of the current scope.
3922    fn apply_pattern_bindings(&mut self, mut pat_bindings: PatternBindings) {
3923        let rib_bindings = self.innermost_rib_bindings(ValueNS);
3924        let Some((_, pat_bindings)) = pat_bindings.pop() else {
3925            bug!("tried applying nonexistent bindings from pattern");
3926        };
3927
3928        if rib_bindings.is_empty() {
3929            // Often, such as for match arms, the bindings are introduced into a new rib.
3930            // In this case, we can move the bindings over directly.
3931            *rib_bindings = pat_bindings;
3932        } else {
3933            rib_bindings.extend(pat_bindings);
3934        }
3935    }
3936
3937    /// Resolve bindings in a pattern. `apply_pattern_bindings` must be called after to introduce
3938    /// the bindings into scope.
3939    fn resolve_pattern(
3940        &mut self,
3941        pat: &'ast Pat,
3942        pat_src: PatternSource,
3943        bindings: &mut PatternBindings,
3944    ) {
3945        // We walk the pattern before declaring the pattern's inner bindings,
3946        // so that we avoid resolving a literal expression to a binding defined
3947        // by the pattern.
3948        // NB: `Self::visit_pat` must be used rather than `visit::walk_pat` to avoid resolving guard
3949        // patterns' guard expressions multiple times (#141265).
3950        self.visit_pat(pat);
3951        self.resolve_pattern_inner(pat, pat_src, bindings);
3952        // This has to happen *after* we determine which pat_idents are variants:
3953        self.check_consistent_bindings(pat);
3954    }
3955
3956    /// Resolve bindings in a pattern. This is a helper to `resolve_pattern`.
3957    ///
3958    /// ### `bindings`
3959    ///
3960    /// A stack of sets of bindings accumulated.
3961    ///
3962    /// In each set, `PatBoundCtx::Product` denotes that a found binding in it should
3963    /// be interpreted as re-binding an already bound binding. This results in an error.
3964    /// Meanwhile, `PatBound::Or` denotes that a found binding in the set should result
3965    /// in reusing this binding rather than creating a fresh one.
3966    ///
3967    /// When called at the top level, the stack must have a single element
3968    /// with `PatBound::Product`. Otherwise, pushing to the stack happens as
3969    /// or-patterns (`p_0 | ... | p_n`) are encountered and the context needs
3970    /// to be switched to `PatBoundCtx::Or` and then `PatBoundCtx::Product` for each `p_i`.
3971    /// When each `p_i` has been dealt with, the top set is merged with its parent.
3972    /// When a whole or-pattern has been dealt with, the thing happens.
3973    ///
3974    /// See the implementation and `fresh_binding` for more details.
3975    #[tracing::instrument(skip(self, bindings), level = "debug")]
3976    fn resolve_pattern_inner(
3977        &mut self,
3978        pat: &'ast Pat,
3979        pat_src: PatternSource,
3980        bindings: &mut PatternBindings,
3981    ) {
3982        // Visit all direct subpatterns of this pattern.
3983        pat.walk(&mut |pat| {
3984            match pat.kind {
3985                PatKind::Ident(bmode, ident, ref sub) => {
3986                    // First try to resolve the identifier as some existing entity,
3987                    // then fall back to a fresh binding.
3988                    let has_sub = sub.is_some();
3989                    let res = self
3990                        .try_resolve_as_non_binding(pat_src, bmode, ident, has_sub)
3991                        .unwrap_or_else(|| self.fresh_binding(ident, pat.id, pat_src, bindings));
3992                    self.r.record_partial_res(pat.id, PartialRes::new(res));
3993                    self.r.record_pat_span(pat.id, pat.span);
3994                }
3995                PatKind::TupleStruct(ref qself, ref path, ref sub_patterns) => {
3996                    self.smart_resolve_path(
3997                        pat.id,
3998                        qself,
3999                        path,
4000                        PathSource::TupleStruct(
4001                            pat.span,
4002                            self.r.arenas.alloc_pattern_spans(sub_patterns.iter().map(|p| p.span)),
4003                        ),
4004                    );
4005                }
4006                PatKind::Path(ref qself, ref path) => {
4007                    self.smart_resolve_path(pat.id, qself, path, PathSource::Pat);
4008                }
4009                PatKind::Struct(ref qself, ref path, ref _fields, ref rest) => {
4010                    self.smart_resolve_path(pat.id, qself, path, PathSource::Struct(None));
4011                    self.record_patterns_with_skipped_bindings(pat, rest);
4012                }
4013                PatKind::Or(ref ps) => {
4014                    // Add a new set of bindings to the stack. `Or` here records that when a
4015                    // binding already exists in this set, it should not result in an error because
4016                    // `V1(a) | V2(a)` must be allowed and are checked for consistency later.
4017                    bindings.push((PatBoundCtx::Or, Default::default()));
4018                    for p in ps {
4019                        // Now we need to switch back to a product context so that each
4020                        // part of the or-pattern internally rejects already bound names.
4021                        // For example, `V1(a) | V2(a, a)` and `V1(a, a) | V2(a)` are bad.
4022                        bindings.push((PatBoundCtx::Product, Default::default()));
4023                        self.resolve_pattern_inner(p, pat_src, bindings);
4024                        // Move up the non-overlapping bindings to the or-pattern.
4025                        // Existing bindings just get "merged".
4026                        let collected = bindings.pop().unwrap().1;
4027                        bindings.last_mut().unwrap().1.extend(collected);
4028                    }
4029                    // This or-pattern itself can itself be part of a product,
4030                    // e.g. `(V1(a) | V2(a), a)` or `(a, V1(a) | V2(a))`.
4031                    // Both cases bind `a` again in a product pattern and must be rejected.
4032                    let collected = bindings.pop().unwrap().1;
4033                    bindings.last_mut().unwrap().1.extend(collected);
4034
4035                    // Prevent visiting `ps` as we've already done so above.
4036                    return false;
4037                }
4038                PatKind::Guard(ref subpat, ref guard) => {
4039                    // Add a new set of bindings to the stack to collect bindings in `subpat`.
4040                    bindings.push((PatBoundCtx::Product, Default::default()));
4041                    // Resolving `subpat` adds bindings onto the newly-pushed context. After, the
4042                    // total number of contexts on the stack should be the same as before.
4043                    let binding_ctx_stack_len = bindings.len();
4044                    self.resolve_pattern_inner(subpat, pat_src, bindings);
4045                    assert_eq!(bindings.len(), binding_ctx_stack_len);
4046                    // These bindings, but none from the surrounding pattern, are visible in the
4047                    // guard; put them in scope and resolve `guard`.
4048                    let subpat_bindings = bindings.pop().unwrap().1;
4049                    self.with_rib(ValueNS, RibKind::Normal, |this| {
4050                        *this.innermost_rib_bindings(ValueNS) = subpat_bindings.clone();
4051                        this.resolve_expr(guard, None);
4052                    });
4053                    // Propagate the subpattern's bindings upwards.
4054                    // FIXME(guard_patterns): For `if let` guards, we'll also need to get the
4055                    // bindings introduced by the guard from its rib and propagate them upwards.
4056                    // This will require checking the identifiers for overlaps with `bindings`, like
4057                    // what `fresh_binding` does (ideally sharing its logic). To keep them separate
4058                    // from `subpat_bindings`, we can introduce a fresh rib for the guard.
4059                    bindings.last_mut().unwrap().1.extend(subpat_bindings);
4060                    // Prevent visiting `subpat` as we've already done so above.
4061                    return false;
4062                }
4063                _ => {}
4064            }
4065            true
4066        });
4067    }
4068
4069    fn record_patterns_with_skipped_bindings(&mut self, pat: &Pat, rest: &ast::PatFieldsRest) {
4070        match rest {
4071            ast::PatFieldsRest::Rest(_) | ast::PatFieldsRest::Recovered(_) => {
4072                // Record that the pattern doesn't introduce all the bindings it could.
4073                if let Some(partial_res) = self.r.partial_res_map.get(&pat.id)
4074                    && let Some(res) = partial_res.full_res()
4075                    && let Some(def_id) = res.opt_def_id()
4076                {
4077                    self.ribs[ValueNS]
4078                        .last_mut()
4079                        .unwrap()
4080                        .patterns_with_skipped_bindings
4081                        .entry(def_id)
4082                        .or_default()
4083                        .push((
4084                            pat.span,
4085                            match rest {
4086                                ast::PatFieldsRest::Recovered(guar) => Err(*guar),
4087                                _ => Ok(()),
4088                            },
4089                        ));
4090                }
4091            }
4092            ast::PatFieldsRest::None => {}
4093        }
4094    }
4095
4096    fn fresh_binding(
4097        &mut self,
4098        ident: Ident,
4099        pat_id: NodeId,
4100        pat_src: PatternSource,
4101        bindings: &mut PatternBindings,
4102    ) -> Res {
4103        // Add the binding to the bindings map, if it doesn't already exist.
4104        // (We must not add it if it's in the bindings map because that breaks the assumptions
4105        // later passes make about or-patterns.)
4106        let ident = ident.normalize_to_macro_rules();
4107
4108        // Already bound in a product pattern? e.g. `(a, a)` which is not allowed.
4109        let already_bound_and = bindings
4110            .iter()
4111            .any(|(ctx, map)| *ctx == PatBoundCtx::Product && map.contains_key(&ident));
4112        if already_bound_and {
4113            // Overlap in a product pattern somewhere; report an error.
4114            use ResolutionError::*;
4115            let error = match pat_src {
4116                // `fn f(a: u8, a: u8)`:
4117                PatternSource::FnParam => IdentifierBoundMoreThanOnceInParameterList,
4118                // `Variant(a, a)`:
4119                _ => IdentifierBoundMoreThanOnceInSamePattern,
4120            };
4121            self.report_error(ident.span, error(ident));
4122        }
4123
4124        // Already bound in an or-pattern? e.g. `V1(a) | V2(a)`.
4125        // This is *required* for consistency which is checked later.
4126        let already_bound_or = bindings
4127            .iter()
4128            .find_map(|(ctx, map)| if *ctx == PatBoundCtx::Or { map.get(&ident) } else { None });
4129        let res = if let Some(&res) = already_bound_or {
4130            // `Variant1(a) | Variant2(a)`, ok
4131            // Reuse definition from the first `a`.
4132            res
4133        } else {
4134            // A completely fresh binding is added to the map.
4135            Res::Local(pat_id)
4136        };
4137
4138        // Record as bound.
4139        bindings.last_mut().unwrap().1.insert(ident, res);
4140        res
4141    }
4142
4143    fn innermost_rib_bindings(&mut self, ns: Namespace) -> &mut FxIndexMap<Ident, Res> {
4144        &mut self.ribs[ns].last_mut().unwrap().bindings
4145    }
4146
4147    fn try_resolve_as_non_binding(
4148        &mut self,
4149        pat_src: PatternSource,
4150        ann: BindingMode,
4151        ident: Ident,
4152        has_sub: bool,
4153    ) -> Option<Res> {
4154        // An immutable (no `mut`) by-value (no `ref`) binding pattern without
4155        // a sub pattern (no `@ $pat`) is syntactically ambiguous as it could
4156        // also be interpreted as a path to e.g. a constant, variant, etc.
4157        let is_syntactic_ambiguity = !has_sub && ann == BindingMode::NONE;
4158
4159        let ls_binding = self.maybe_resolve_ident_in_lexical_scope(ident, ValueNS)?;
4160        let (res, binding) = match ls_binding {
4161            LexicalScopeBinding::Item(binding)
4162                if is_syntactic_ambiguity && binding.is_ambiguity_recursive() =>
4163            {
4164                // For ambiguous bindings we don't know all their definitions and cannot check
4165                // whether they can be shadowed by fresh bindings or not, so force an error.
4166                // issues/33118#issuecomment-233962221 (see below) still applies here,
4167                // but we have to ignore it for backward compatibility.
4168                self.r.record_use(ident, binding, Used::Other);
4169                return None;
4170            }
4171            LexicalScopeBinding::Item(binding) => (binding.res(), Some(binding)),
4172            LexicalScopeBinding::Res(res) => (res, None),
4173        };
4174
4175        match res {
4176            Res::SelfCtor(_) // See #70549.
4177            | Res::Def(
4178                DefKind::Ctor(_, CtorKind::Const) | DefKind::Const | DefKind::AssocConst | DefKind::ConstParam,
4179                _,
4180            ) if is_syntactic_ambiguity => {
4181                // Disambiguate in favor of a unit struct/variant or constant pattern.
4182                if let Some(binding) = binding {
4183                    self.r.record_use(ident, binding, Used::Other);
4184                }
4185                Some(res)
4186            }
4187            Res::Def(DefKind::Ctor(..) | DefKind::Const | DefKind::AssocConst | DefKind::Static { .. }, _) => {
4188                // This is unambiguously a fresh binding, either syntactically
4189                // (e.g., `IDENT @ PAT` or `ref IDENT`) or because `IDENT` resolves
4190                // to something unusable as a pattern (e.g., constructor function),
4191                // but we still conservatively report an error, see
4192                // issues/33118#issuecomment-233962221 for one reason why.
4193                let binding = binding.expect("no binding for a ctor or static");
4194                self.report_error(
4195                    ident.span,
4196                    ResolutionError::BindingShadowsSomethingUnacceptable {
4197                        shadowing_binding: pat_src,
4198                        name: ident.name,
4199                        participle: if binding.is_import() { "imported" } else { "defined" },
4200                        article: binding.res().article(),
4201                        shadowed_binding: binding.res(),
4202                        shadowed_binding_span: binding.span,
4203                    },
4204                );
4205                None
4206            }
4207            Res::Def(DefKind::ConstParam, def_id) => {
4208                // Same as for DefKind::Const above, but here, `binding` is `None`, so we
4209                // have to construct the error differently
4210                self.report_error(
4211                    ident.span,
4212                    ResolutionError::BindingShadowsSomethingUnacceptable {
4213                        shadowing_binding: pat_src,
4214                        name: ident.name,
4215                        participle: "defined",
4216                        article: res.article(),
4217                        shadowed_binding: res,
4218                        shadowed_binding_span: self.r.def_span(def_id),
4219                    }
4220                );
4221                None
4222            }
4223            Res::Def(DefKind::Fn | DefKind::AssocFn, _) | Res::Local(..) | Res::Err => {
4224                // These entities are explicitly allowed to be shadowed by fresh bindings.
4225                None
4226            }
4227            Res::SelfCtor(_) => {
4228                // We resolve `Self` in pattern position as an ident sometimes during recovery,
4229                // so delay a bug instead of ICEing.
4230                self.r.dcx().span_delayed_bug(
4231                    ident.span,
4232                    "unexpected `SelfCtor` in pattern, expected identifier"
4233                );
4234                None
4235            }
4236            _ => span_bug!(
4237                ident.span,
4238                "unexpected resolution for an identifier in pattern: {:?}",
4239                res,
4240            ),
4241        }
4242    }
4243
4244    // High-level and context dependent path resolution routine.
4245    // Resolves the path and records the resolution into definition map.
4246    // If resolution fails tries several techniques to find likely
4247    // resolution candidates, suggest imports or other help, and report
4248    // errors in user friendly way.
4249    fn smart_resolve_path(
4250        &mut self,
4251        id: NodeId,
4252        qself: &Option<Box<QSelf>>,
4253        path: &Path,
4254        source: PathSource<'_, 'ast, 'ra>,
4255    ) {
4256        self.smart_resolve_path_fragment(
4257            qself,
4258            &Segment::from_path(path),
4259            source,
4260            Finalize::new(id, path.span),
4261            RecordPartialRes::Yes,
4262            None,
4263        );
4264    }
4265
4266    #[instrument(level = "debug", skip(self))]
4267    fn smart_resolve_path_fragment(
4268        &mut self,
4269        qself: &Option<Box<QSelf>>,
4270        path: &[Segment],
4271        source: PathSource<'_, 'ast, 'ra>,
4272        finalize: Finalize,
4273        record_partial_res: RecordPartialRes,
4274        parent_qself: Option<&QSelf>,
4275    ) -> PartialRes {
4276        let ns = source.namespace();
4277
4278        let Finalize { node_id, path_span, .. } = finalize;
4279        let report_errors = |this: &mut Self, res: Option<Res>| {
4280            if this.should_report_errs() {
4281                let (err, candidates) = this.smart_resolve_report_errors(
4282                    path,
4283                    None,
4284                    path_span,
4285                    source,
4286                    res,
4287                    parent_qself,
4288                );
4289
4290                let def_id = this.parent_scope.module.nearest_parent_mod();
4291                let instead = res.is_some();
4292                let suggestion = if let Some((start, end)) = this.diag_metadata.in_range
4293                    && path[0].ident.span.lo() == end.span.lo()
4294                    && !matches!(start.kind, ExprKind::Lit(_))
4295                {
4296                    let mut sugg = ".";
4297                    let mut span = start.span.between(end.span);
4298                    if span.lo() + BytePos(2) == span.hi() {
4299                        // There's no space between the start, the range op and the end, suggest
4300                        // removal which will look better.
4301                        span = span.with_lo(span.lo() + BytePos(1));
4302                        sugg = "";
4303                    }
4304                    Some((
4305                        span,
4306                        "you might have meant to write `.` instead of `..`",
4307                        sugg.to_string(),
4308                        Applicability::MaybeIncorrect,
4309                    ))
4310                } else if res.is_none()
4311                    && let PathSource::Type
4312                    | PathSource::Expr(_)
4313                    | PathSource::PreciseCapturingArg(..) = source
4314                {
4315                    this.suggest_adding_generic_parameter(path, source)
4316                } else {
4317                    None
4318                };
4319
4320                let ue = UseError {
4321                    err,
4322                    candidates,
4323                    def_id,
4324                    instead,
4325                    suggestion,
4326                    path: path.into(),
4327                    is_call: source.is_call(),
4328                };
4329
4330                this.r.use_injections.push(ue);
4331            }
4332
4333            PartialRes::new(Res::Err)
4334        };
4335
4336        // For paths originating from calls (like in `HashMap::new()`), tries
4337        // to enrich the plain `failed to resolve: ...` message with hints
4338        // about possible missing imports.
4339        //
4340        // Similar thing, for types, happens in `report_errors` above.
4341        let report_errors_for_call =
4342            |this: &mut Self, parent_err: Spanned<ResolutionError<'ra>>| {
4343                // Before we start looking for candidates, we have to get our hands
4344                // on the type user is trying to perform invocation on; basically:
4345                // we're transforming `HashMap::new` into just `HashMap`.
4346                let (following_seg, prefix_path) = match path.split_last() {
4347                    Some((last, path)) if !path.is_empty() => (Some(last), path),
4348                    _ => return Some(parent_err),
4349                };
4350
4351                let (mut err, candidates) = this.smart_resolve_report_errors(
4352                    prefix_path,
4353                    following_seg,
4354                    path_span,
4355                    PathSource::Type,
4356                    None,
4357                    parent_qself,
4358                );
4359
4360                // There are two different error messages user might receive at
4361                // this point:
4362                // - E0412 cannot find type `{}` in this scope
4363                // - E0433 failed to resolve: use of undeclared type or module `{}`
4364                //
4365                // The first one is emitted for paths in type-position, and the
4366                // latter one - for paths in expression-position.
4367                //
4368                // Thus (since we're in expression-position at this point), not to
4369                // confuse the user, we want to keep the *message* from E0433 (so
4370                // `parent_err`), but we want *hints* from E0412 (so `err`).
4371                //
4372                // And that's what happens below - we're just mixing both messages
4373                // into a single one.
4374                let failed_to_resolve = match parent_err.node {
4375                    ResolutionError::FailedToResolve { .. } => true,
4376                    _ => false,
4377                };
4378                let mut parent_err = this.r.into_struct_error(parent_err.span, parent_err.node);
4379
4380                // overwrite all properties with the parent's error message
4381                err.messages = take(&mut parent_err.messages);
4382                err.code = take(&mut parent_err.code);
4383                swap(&mut err.span, &mut parent_err.span);
4384                if failed_to_resolve {
4385                    err.children = take(&mut parent_err.children);
4386                } else {
4387                    err.children.append(&mut parent_err.children);
4388                }
4389                err.sort_span = parent_err.sort_span;
4390                err.is_lint = parent_err.is_lint.clone();
4391
4392                // merge the parent_err's suggestions with the typo (err's) suggestions
4393                match &mut err.suggestions {
4394                    Suggestions::Enabled(typo_suggestions) => match &mut parent_err.suggestions {
4395                        Suggestions::Enabled(parent_suggestions) => {
4396                            // If both suggestions are enabled, append parent_err's suggestions to err's suggestions.
4397                            typo_suggestions.append(parent_suggestions)
4398                        }
4399                        Suggestions::Sealed(_) | Suggestions::Disabled => {
4400                            // If the parent's suggestions are either sealed or disabled, it signifies that
4401                            // new suggestions cannot be added or removed from the diagnostic. Therefore,
4402                            // we assign both types of suggestions to err's suggestions and discard the
4403                            // existing suggestions in err.
4404                            err.suggestions = std::mem::take(&mut parent_err.suggestions);
4405                        }
4406                    },
4407                    Suggestions::Sealed(_) | Suggestions::Disabled => (),
4408                }
4409
4410                parent_err.cancel();
4411
4412                let def_id = this.parent_scope.module.nearest_parent_mod();
4413
4414                if this.should_report_errs() {
4415                    if candidates.is_empty() {
4416                        if path.len() == 2
4417                            && let [segment] = prefix_path
4418                        {
4419                            // Delay to check whether method name is an associated function or not
4420                            // ```
4421                            // let foo = Foo {};
4422                            // foo::bar(); // possibly suggest to foo.bar();
4423                            //```
4424                            err.stash(segment.ident.span, rustc_errors::StashKey::CallAssocMethod);
4425                        } else {
4426                            // When there is no suggested imports, we can just emit the error
4427                            // and suggestions immediately. Note that we bypass the usually error
4428                            // reporting routine (ie via `self.r.report_error`) because we need
4429                            // to post-process the `ResolutionError` above.
4430                            err.emit();
4431                        }
4432                    } else {
4433                        // If there are suggested imports, the error reporting is delayed
4434                        this.r.use_injections.push(UseError {
4435                            err,
4436                            candidates,
4437                            def_id,
4438                            instead: false,
4439                            suggestion: None,
4440                            path: prefix_path.into(),
4441                            is_call: source.is_call(),
4442                        });
4443                    }
4444                } else {
4445                    err.cancel();
4446                }
4447
4448                // We don't return `Some(parent_err)` here, because the error will
4449                // be already printed either immediately or as part of the `use` injections
4450                None
4451            };
4452
4453        let partial_res = match self.resolve_qpath_anywhere(
4454            qself,
4455            path,
4456            ns,
4457            source.defer_to_typeck(),
4458            finalize,
4459            source,
4460        ) {
4461            Ok(Some(partial_res)) if let Some(res) = partial_res.full_res() => {
4462                // if we also have an associated type that matches the ident, stash a suggestion
4463                if let Some(items) = self.diag_metadata.current_trait_assoc_items
4464                    && let [Segment { ident, .. }] = path
4465                    && items.iter().any(|item| {
4466                        if let AssocItemKind::Type(alias) = &item.kind
4467                            && alias.ident == *ident
4468                        {
4469                            true
4470                        } else {
4471                            false
4472                        }
4473                    })
4474                {
4475                    let mut diag = self.r.tcx.dcx().struct_allow("");
4476                    diag.span_suggestion_verbose(
4477                        path_span.shrink_to_lo(),
4478                        "there is an associated type with the same name",
4479                        "Self::",
4480                        Applicability::MaybeIncorrect,
4481                    );
4482                    diag.stash(path_span, StashKey::AssociatedTypeSuggestion);
4483                }
4484
4485                if source.is_expected(res) || res == Res::Err {
4486                    partial_res
4487                } else {
4488                    report_errors(self, Some(res))
4489                }
4490            }
4491
4492            Ok(Some(partial_res)) if source.defer_to_typeck() => {
4493                // Not fully resolved associated item `T::A::B` or `<T as Tr>::A::B`
4494                // or `<T>::A::B`. If `B` should be resolved in value namespace then
4495                // it needs to be added to the trait map.
4496                if ns == ValueNS {
4497                    let item_name = path.last().unwrap().ident;
4498                    let traits = self.traits_in_scope(item_name, ns);
4499                    self.r.trait_map.insert(node_id, traits);
4500                }
4501
4502                if PrimTy::from_name(path[0].ident.name).is_some() {
4503                    let mut std_path = Vec::with_capacity(1 + path.len());
4504
4505                    std_path.push(Segment::from_ident(Ident::with_dummy_span(sym::std)));
4506                    std_path.extend(path);
4507                    if let PathResult::Module(_) | PathResult::NonModule(_) =
4508                        self.resolve_path(&std_path, Some(ns), None, source)
4509                    {
4510                        // Check if we wrote `str::from_utf8` instead of `std::str::from_utf8`
4511                        let item_span =
4512                            path.iter().last().map_or(path_span, |segment| segment.ident.span);
4513
4514                        self.r.confused_type_with_std_module.insert(item_span, path_span);
4515                        self.r.confused_type_with_std_module.insert(path_span, path_span);
4516                    }
4517                }
4518
4519                partial_res
4520            }
4521
4522            Err(err) => {
4523                if let Some(err) = report_errors_for_call(self, err) {
4524                    self.report_error(err.span, err.node);
4525                }
4526
4527                PartialRes::new(Res::Err)
4528            }
4529
4530            _ => report_errors(self, None),
4531        };
4532
4533        if record_partial_res == RecordPartialRes::Yes {
4534            // Avoid recording definition of `A::B` in `<T as A>::B::C`.
4535            self.r.record_partial_res(node_id, partial_res);
4536            self.resolve_elided_lifetimes_in_path(partial_res, path, source, path_span);
4537            self.lint_unused_qualifications(path, ns, finalize);
4538        }
4539
4540        partial_res
4541    }
4542
4543    fn self_type_is_available(&mut self) -> bool {
4544        let binding = self
4545            .maybe_resolve_ident_in_lexical_scope(Ident::with_dummy_span(kw::SelfUpper), TypeNS);
4546        if let Some(LexicalScopeBinding::Res(res)) = binding { res != Res::Err } else { false }
4547    }
4548
4549    fn self_value_is_available(&mut self, self_span: Span) -> bool {
4550        let ident = Ident::new(kw::SelfLower, self_span);
4551        let binding = self.maybe_resolve_ident_in_lexical_scope(ident, ValueNS);
4552        if let Some(LexicalScopeBinding::Res(res)) = binding { res != Res::Err } else { false }
4553    }
4554
4555    /// A wrapper around [`Resolver::report_error`].
4556    ///
4557    /// This doesn't emit errors for function bodies if this is rustdoc.
4558    fn report_error(&mut self, span: Span, resolution_error: ResolutionError<'ra>) {
4559        if self.should_report_errs() {
4560            self.r.report_error(span, resolution_error);
4561        }
4562    }
4563
4564    #[inline]
4565    /// If we're actually rustdoc then avoid giving a name resolution error for `cfg()` items or
4566    // an invalid `use foo::*;` was found, which can cause unbounded amounts of "item not found"
4567    // errors. We silence them all.
4568    fn should_report_errs(&self) -> bool {
4569        !(self.r.tcx.sess.opts.actually_rustdoc && self.in_func_body)
4570            && !self.r.glob_error.is_some()
4571    }
4572
4573    // Resolve in alternative namespaces if resolution in the primary namespace fails.
4574    fn resolve_qpath_anywhere(
4575        &mut self,
4576        qself: &Option<Box<QSelf>>,
4577        path: &[Segment],
4578        primary_ns: Namespace,
4579        defer_to_typeck: bool,
4580        finalize: Finalize,
4581        source: PathSource<'_, 'ast, 'ra>,
4582    ) -> Result<Option<PartialRes>, Spanned<ResolutionError<'ra>>> {
4583        let mut fin_res = None;
4584
4585        for (i, &ns) in [primary_ns, TypeNS, ValueNS].iter().enumerate() {
4586            if i == 0 || ns != primary_ns {
4587                match self.resolve_qpath(qself, path, ns, finalize, source)? {
4588                    Some(partial_res)
4589                        if partial_res.unresolved_segments() == 0 || defer_to_typeck =>
4590                    {
4591                        return Ok(Some(partial_res));
4592                    }
4593                    partial_res => {
4594                        if fin_res.is_none() {
4595                            fin_res = partial_res;
4596                        }
4597                    }
4598                }
4599            }
4600        }
4601
4602        assert!(primary_ns != MacroNS);
4603        if qself.is_none()
4604            && let PathResult::NonModule(res) =
4605                self.r.cm().maybe_resolve_path(path, Some(MacroNS), &self.parent_scope, None)
4606        {
4607            return Ok(Some(res));
4608        }
4609
4610        Ok(fin_res)
4611    }
4612
4613    /// Handles paths that may refer to associated items.
4614    fn resolve_qpath(
4615        &mut self,
4616        qself: &Option<Box<QSelf>>,
4617        path: &[Segment],
4618        ns: Namespace,
4619        finalize: Finalize,
4620        source: PathSource<'_, 'ast, 'ra>,
4621    ) -> Result<Option<PartialRes>, Spanned<ResolutionError<'ra>>> {
4622        debug!(
4623            "resolve_qpath(qself={:?}, path={:?}, ns={:?}, finalize={:?})",
4624            qself, path, ns, finalize,
4625        );
4626
4627        if let Some(qself) = qself {
4628            if qself.position == 0 {
4629                // This is a case like `<T>::B`, where there is no
4630                // trait to resolve. In that case, we leave the `B`
4631                // segment to be resolved by type-check.
4632                return Ok(Some(PartialRes::with_unresolved_segments(
4633                    Res::Def(DefKind::Mod, CRATE_DEF_ID.to_def_id()),
4634                    path.len(),
4635                )));
4636            }
4637
4638            let num_privacy_errors = self.r.privacy_errors.len();
4639            // Make sure that `A` in `<T as A>::B::C` is a trait.
4640            let trait_res = self.smart_resolve_path_fragment(
4641                &None,
4642                &path[..qself.position],
4643                PathSource::Trait(AliasPossibility::No),
4644                Finalize::new(finalize.node_id, qself.path_span),
4645                RecordPartialRes::No,
4646                Some(&qself),
4647            );
4648
4649            if trait_res.expect_full_res() == Res::Err {
4650                return Ok(Some(trait_res));
4651            }
4652
4653            // Truncate additional privacy errors reported above,
4654            // because they'll be recomputed below.
4655            self.r.privacy_errors.truncate(num_privacy_errors);
4656
4657            // Make sure `A::B` in `<T as A>::B::C` is a trait item.
4658            //
4659            // Currently, `path` names the full item (`A::B::C`, in
4660            // our example). so we extract the prefix of that that is
4661            // the trait (the slice upto and including
4662            // `qself.position`). And then we recursively resolve that,
4663            // but with `qself` set to `None`.
4664            let ns = if qself.position + 1 == path.len() { ns } else { TypeNS };
4665            let partial_res = self.smart_resolve_path_fragment(
4666                &None,
4667                &path[..=qself.position],
4668                PathSource::TraitItem(ns, &source),
4669                Finalize::with_root_span(finalize.node_id, finalize.path_span, qself.path_span),
4670                RecordPartialRes::No,
4671                Some(&qself),
4672            );
4673
4674            // The remaining segments (the `C` in our example) will
4675            // have to be resolved by type-check, since that requires doing
4676            // trait resolution.
4677            return Ok(Some(PartialRes::with_unresolved_segments(
4678                partial_res.base_res(),
4679                partial_res.unresolved_segments() + path.len() - qself.position - 1,
4680            )));
4681        }
4682
4683        let result = match self.resolve_path(path, Some(ns), Some(finalize), source) {
4684            PathResult::NonModule(path_res) => path_res,
4685            PathResult::Module(ModuleOrUniformRoot::Module(module)) if !module.is_normal() => {
4686                PartialRes::new(module.res().unwrap())
4687            }
4688            // A part of this path references a `mod` that had a parse error. To avoid resolution
4689            // errors for each reference to that module, we don't emit an error for them until the
4690            // `mod` is fixed. this can have a significant cascade effect.
4691            PathResult::Failed { error_implied_by_parse_error: true, .. } => {
4692                PartialRes::new(Res::Err)
4693            }
4694            // In `a(::assoc_item)*` `a` cannot be a module. If `a` does resolve to a module we
4695            // don't report an error right away, but try to fallback to a primitive type.
4696            // So, we are still able to successfully resolve something like
4697            //
4698            // use std::u8; // bring module u8 in scope
4699            // fn f() -> u8 { // OK, resolves to primitive u8, not to std::u8
4700            //     u8::max_value() // OK, resolves to associated function <u8>::max_value,
4701            //                     // not to nonexistent std::u8::max_value
4702            // }
4703            //
4704            // Such behavior is required for backward compatibility.
4705            // The same fallback is used when `a` resolves to nothing.
4706            PathResult::Module(ModuleOrUniformRoot::Module(_)) | PathResult::Failed { .. }
4707                if (ns == TypeNS || path.len() > 1)
4708                    && PrimTy::from_name(path[0].ident.name).is_some() =>
4709            {
4710                let prim = PrimTy::from_name(path[0].ident.name).unwrap();
4711                let tcx = self.r.tcx();
4712
4713                let gate_err_sym_msg = match prim {
4714                    PrimTy::Float(FloatTy::F16) if !tcx.features().f16() => {
4715                        Some((sym::f16, "the type `f16` is unstable"))
4716                    }
4717                    PrimTy::Float(FloatTy::F128) if !tcx.features().f128() => {
4718                        Some((sym::f128, "the type `f128` is unstable"))
4719                    }
4720                    _ => None,
4721                };
4722
4723                if let Some((sym, msg)) = gate_err_sym_msg {
4724                    let span = path[0].ident.span;
4725                    if !span.allows_unstable(sym) {
4726                        feature_err(tcx.sess, sym, span, msg).emit();
4727                    }
4728                };
4729
4730                // Fix up partial res of segment from `resolve_path` call.
4731                if let Some(id) = path[0].id {
4732                    self.r.partial_res_map.insert(id, PartialRes::new(Res::PrimTy(prim)));
4733                }
4734
4735                PartialRes::with_unresolved_segments(Res::PrimTy(prim), path.len() - 1)
4736            }
4737            PathResult::Module(ModuleOrUniformRoot::Module(module)) => {
4738                PartialRes::new(module.res().unwrap())
4739            }
4740            PathResult::Failed {
4741                is_error_from_last_segment: false,
4742                span,
4743                label,
4744                suggestion,
4745                module,
4746                segment_name,
4747                error_implied_by_parse_error: _,
4748            } => {
4749                return Err(respan(
4750                    span,
4751                    ResolutionError::FailedToResolve {
4752                        segment: Some(segment_name),
4753                        label,
4754                        suggestion,
4755                        module,
4756                    },
4757                ));
4758            }
4759            PathResult::Module(..) | PathResult::Failed { .. } => return Ok(None),
4760            PathResult::Indeterminate => bug!("indeterminate path result in resolve_qpath"),
4761        };
4762
4763        Ok(Some(result))
4764    }
4765
4766    fn with_resolved_label(&mut self, label: Option<Label>, id: NodeId, f: impl FnOnce(&mut Self)) {
4767        if let Some(label) = label {
4768            if label.ident.as_str().as_bytes()[1] != b'_' {
4769                self.diag_metadata.unused_labels.insert(id, label.ident.span);
4770            }
4771
4772            if let Ok((_, orig_span)) = self.resolve_label(label.ident) {
4773                diagnostics::signal_label_shadowing(self.r.tcx.sess, orig_span, label.ident)
4774            }
4775
4776            self.with_label_rib(RibKind::Normal, |this| {
4777                let ident = label.ident.normalize_to_macro_rules();
4778                this.label_ribs.last_mut().unwrap().bindings.insert(ident, id);
4779                f(this);
4780            });
4781        } else {
4782            f(self);
4783        }
4784    }
4785
4786    fn resolve_labeled_block(&mut self, label: Option<Label>, id: NodeId, block: &'ast Block) {
4787        self.with_resolved_label(label, id, |this| this.visit_block(block));
4788    }
4789
4790    fn resolve_block(&mut self, block: &'ast Block) {
4791        debug!("(resolving block) entering block");
4792        // Move down in the graph, if there's an anonymous module rooted here.
4793        let orig_module = self.parent_scope.module;
4794        let anonymous_module = self.r.block_map.get(&block.id).copied();
4795
4796        let mut num_macro_definition_ribs = 0;
4797        if let Some(anonymous_module) = anonymous_module {
4798            debug!("(resolving block) found anonymous module, moving down");
4799            self.ribs[ValueNS].push(Rib::new(RibKind::Block(Some(anonymous_module))));
4800            self.ribs[TypeNS].push(Rib::new(RibKind::Block(Some(anonymous_module))));
4801            self.parent_scope.module = anonymous_module;
4802        } else {
4803            self.ribs[ValueNS].push(Rib::new(RibKind::Block(None)));
4804        }
4805
4806        // Descend into the block.
4807        for stmt in &block.stmts {
4808            if let StmtKind::Item(ref item) = stmt.kind
4809                && let ItemKind::MacroDef(..) = item.kind
4810            {
4811                num_macro_definition_ribs += 1;
4812                let res = self.r.local_def_id(item.id).to_def_id();
4813                self.ribs[ValueNS].push(Rib::new(RibKind::MacroDefinition(res)));
4814                self.label_ribs.push(Rib::new(RibKind::MacroDefinition(res)));
4815            }
4816
4817            self.visit_stmt(stmt);
4818        }
4819
4820        // Move back up.
4821        self.parent_scope.module = orig_module;
4822        for _ in 0..num_macro_definition_ribs {
4823            self.ribs[ValueNS].pop();
4824            self.label_ribs.pop();
4825        }
4826        self.last_block_rib = self.ribs[ValueNS].pop();
4827        if anonymous_module.is_some() {
4828            self.ribs[TypeNS].pop();
4829        }
4830        debug!("(resolving block) leaving block");
4831    }
4832
4833    fn resolve_anon_const(&mut self, constant: &'ast AnonConst, anon_const_kind: AnonConstKind) {
4834        debug!(
4835            "resolve_anon_const(constant: {:?}, anon_const_kind: {:?})",
4836            constant, anon_const_kind
4837        );
4838
4839        let is_trivial_const_arg = constant
4840            .value
4841            .is_potential_trivial_const_arg(self.r.tcx.features().min_generic_const_args());
4842        self.resolve_anon_const_manual(is_trivial_const_arg, anon_const_kind, |this| {
4843            this.resolve_expr(&constant.value, None)
4844        })
4845    }
4846
4847    /// There are a few places that we need to resolve an anon const but we did not parse an
4848    /// anon const so cannot provide an `&'ast AnonConst`. Right now this is just unbraced
4849    /// const arguments that were parsed as type arguments, and `legacy_const_generics` which
4850    /// parse as normal function argument expressions. To avoid duplicating the code for resolving
4851    /// an anon const we have this function which lets the caller manually call `resolve_expr` or
4852    /// `smart_resolve_path`.
4853    fn resolve_anon_const_manual(
4854        &mut self,
4855        is_trivial_const_arg: bool,
4856        anon_const_kind: AnonConstKind,
4857        resolve_expr: impl FnOnce(&mut Self),
4858    ) {
4859        let is_repeat_expr = match anon_const_kind {
4860            AnonConstKind::ConstArg(is_repeat_expr) => is_repeat_expr,
4861            _ => IsRepeatExpr::No,
4862        };
4863
4864        let may_use_generics = match anon_const_kind {
4865            AnonConstKind::EnumDiscriminant => {
4866                ConstantHasGenerics::No(NoConstantGenericsReason::IsEnumDiscriminant)
4867            }
4868            AnonConstKind::FieldDefaultValue => ConstantHasGenerics::Yes,
4869            AnonConstKind::InlineConst => ConstantHasGenerics::Yes,
4870            AnonConstKind::ConstArg(_) => {
4871                if self.r.tcx.features().generic_const_exprs() || is_trivial_const_arg {
4872                    ConstantHasGenerics::Yes
4873                } else {
4874                    ConstantHasGenerics::No(NoConstantGenericsReason::NonTrivialConstArg)
4875                }
4876            }
4877        };
4878
4879        self.with_constant_rib(is_repeat_expr, may_use_generics, None, |this| {
4880            this.with_lifetime_rib(LifetimeRibKind::Elided(LifetimeRes::Infer), |this| {
4881                resolve_expr(this);
4882            });
4883        });
4884    }
4885
4886    fn resolve_expr_field(&mut self, f: &'ast ExprField, e: &'ast Expr) {
4887        self.resolve_expr(&f.expr, Some(e));
4888        self.visit_ident(&f.ident);
4889        walk_list!(self, visit_attribute, f.attrs.iter());
4890    }
4891
4892    fn resolve_expr(&mut self, expr: &'ast Expr, parent: Option<&'ast Expr>) {
4893        // First, record candidate traits for this expression if it could
4894        // result in the invocation of a method call.
4895
4896        self.record_candidate_traits_for_expr_if_necessary(expr);
4897
4898        // Next, resolve the node.
4899        match expr.kind {
4900            ExprKind::Path(ref qself, ref path) => {
4901                self.smart_resolve_path(expr.id, qself, path, PathSource::Expr(parent));
4902                visit::walk_expr(self, expr);
4903            }
4904
4905            ExprKind::Struct(ref se) => {
4906                self.smart_resolve_path(expr.id, &se.qself, &se.path, PathSource::Struct(parent));
4907                // This is the same as `visit::walk_expr(self, expr);`, but we want to pass the
4908                // parent in for accurate suggestions when encountering `Foo { bar }` that should
4909                // have been `Foo { bar: self.bar }`.
4910                if let Some(qself) = &se.qself {
4911                    self.visit_ty(&qself.ty);
4912                }
4913                self.visit_path(&se.path);
4914                walk_list!(self, resolve_expr_field, &se.fields, expr);
4915                match &se.rest {
4916                    StructRest::Base(expr) => self.visit_expr(expr),
4917                    StructRest::Rest(_span) => {}
4918                    StructRest::None => {}
4919                }
4920            }
4921
4922            ExprKind::Break(Some(label), _) | ExprKind::Continue(Some(label)) => {
4923                match self.resolve_label(label.ident) {
4924                    Ok((node_id, _)) => {
4925                        // Since this res is a label, it is never read.
4926                        self.r.label_res_map.insert(expr.id, node_id);
4927                        self.diag_metadata.unused_labels.swap_remove(&node_id);
4928                    }
4929                    Err(error) => {
4930                        self.report_error(label.ident.span, error);
4931                    }
4932                }
4933
4934                // visit `break` argument if any
4935                visit::walk_expr(self, expr);
4936            }
4937
4938            ExprKind::Break(None, Some(ref e)) => {
4939                // We use this instead of `visit::walk_expr` to keep the parent expr around for
4940                // better diagnostics.
4941                self.resolve_expr(e, Some(expr));
4942            }
4943
4944            ExprKind::Let(ref pat, ref scrutinee, _, Recovered::No) => {
4945                self.visit_expr(scrutinee);
4946                self.resolve_pattern_top(pat, PatternSource::Let);
4947            }
4948
4949            ExprKind::Let(ref pat, ref scrutinee, _, Recovered::Yes(_)) => {
4950                self.visit_expr(scrutinee);
4951                // This is basically a tweaked, inlined `resolve_pattern_top`.
4952                let mut bindings = smallvec![(PatBoundCtx::Product, Default::default())];
4953                self.resolve_pattern(pat, PatternSource::Let, &mut bindings);
4954                // We still collect the bindings in this `let` expression which is in
4955                // an invalid position (and therefore shouldn't declare variables into
4956                // its parent scope). To avoid unnecessary errors though, we do just
4957                // reassign the resolutions to `Res::Err`.
4958                for (_, bindings) in &mut bindings {
4959                    for (_, binding) in bindings {
4960                        *binding = Res::Err;
4961                    }
4962                }
4963                self.apply_pattern_bindings(bindings);
4964            }
4965
4966            ExprKind::If(ref cond, ref then, ref opt_else) => {
4967                self.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(then);
4972                });
4973                if let Some(expr) = opt_else {
4974                    self.visit_expr(expr);
4975                }
4976            }
4977
4978            ExprKind::Loop(ref block, label, _) => {
4979                self.resolve_labeled_block(label, expr.id, block)
4980            }
4981
4982            ExprKind::While(ref cond, ref block, label) => {
4983                self.with_resolved_label(label, expr.id, |this| {
4984                    this.with_rib(ValueNS, RibKind::Normal, |this| {
4985                        let old = this.diag_metadata.in_if_condition.replace(cond);
4986                        this.visit_expr(cond);
4987                        this.diag_metadata.in_if_condition = old;
4988                        this.visit_block(block);
4989                    })
4990                });
4991            }
4992
4993            ExprKind::ForLoop { ref pat, ref iter, ref body, label, kind: _ } => {
4994                self.visit_expr(iter);
4995                self.with_rib(ValueNS, RibKind::Normal, |this| {
4996                    this.resolve_pattern_top(pat, PatternSource::For);
4997                    this.resolve_labeled_block(label, expr.id, body);
4998                });
4999            }
5000
5001            ExprKind::Block(ref block, label) => self.resolve_labeled_block(label, block.id, block),
5002
5003            // Equivalent to `visit::walk_expr` + passing some context to children.
5004            ExprKind::Field(ref subexpression, _) => {
5005                self.resolve_expr(subexpression, Some(expr));
5006            }
5007            ExprKind::MethodCall(box MethodCall { ref seg, ref receiver, ref args, .. }) => {
5008                self.resolve_expr(receiver, Some(expr));
5009                for arg in args {
5010                    self.resolve_expr(arg, None);
5011                }
5012                self.visit_path_segment(seg);
5013            }
5014
5015            ExprKind::Call(ref callee, ref arguments) => {
5016                self.resolve_expr(callee, Some(expr));
5017                let const_args = self.r.legacy_const_generic_args(callee).unwrap_or_default();
5018                for (idx, argument) in arguments.iter().enumerate() {
5019                    // Constant arguments need to be treated as AnonConst since
5020                    // that is how they will be later lowered to HIR.
5021                    if const_args.contains(&idx) {
5022                        let is_trivial_const_arg = argument.is_potential_trivial_const_arg(
5023                            self.r.tcx.features().min_generic_const_args(),
5024                        );
5025                        self.resolve_anon_const_manual(
5026                            is_trivial_const_arg,
5027                            AnonConstKind::ConstArg(IsRepeatExpr::No),
5028                            |this| this.resolve_expr(argument, None),
5029                        );
5030                    } else {
5031                        self.resolve_expr(argument, None);
5032                    }
5033                }
5034            }
5035            ExprKind::Type(ref _type_expr, ref _ty) => {
5036                visit::walk_expr(self, expr);
5037            }
5038            // For closures, RibKind::FnOrCoroutine is added in visit_fn
5039            ExprKind::Closure(box ast::Closure {
5040                binder: ClosureBinder::For { ref generic_params, span },
5041                ..
5042            }) => {
5043                self.with_generic_param_rib(
5044                    generic_params,
5045                    RibKind::Normal,
5046                    expr.id,
5047                    LifetimeBinderKind::Closure,
5048                    span,
5049                    |this| visit::walk_expr(this, expr),
5050                );
5051            }
5052            ExprKind::Closure(..) => visit::walk_expr(self, expr),
5053            ExprKind::Gen(..) => {
5054                self.with_label_rib(RibKind::FnOrCoroutine, |this| visit::walk_expr(this, expr));
5055            }
5056            ExprKind::Repeat(ref elem, ref ct) => {
5057                self.visit_expr(elem);
5058                self.resolve_anon_const(ct, AnonConstKind::ConstArg(IsRepeatExpr::Yes));
5059            }
5060            ExprKind::ConstBlock(ref ct) => {
5061                self.resolve_anon_const(ct, AnonConstKind::InlineConst);
5062            }
5063            ExprKind::Index(ref elem, ref idx, _) => {
5064                self.resolve_expr(elem, Some(expr));
5065                self.visit_expr(idx);
5066            }
5067            ExprKind::Assign(ref lhs, ref rhs, _) => {
5068                if !self.diag_metadata.is_assign_rhs {
5069                    self.diag_metadata.in_assignment = Some(expr);
5070                }
5071                self.visit_expr(lhs);
5072                self.diag_metadata.is_assign_rhs = true;
5073                self.diag_metadata.in_assignment = None;
5074                self.visit_expr(rhs);
5075                self.diag_metadata.is_assign_rhs = false;
5076            }
5077            ExprKind::Range(Some(ref start), Some(ref end), RangeLimits::HalfOpen) => {
5078                self.diag_metadata.in_range = Some((start, end));
5079                self.resolve_expr(start, Some(expr));
5080                self.resolve_expr(end, Some(expr));
5081                self.diag_metadata.in_range = None;
5082            }
5083            _ => {
5084                visit::walk_expr(self, expr);
5085            }
5086        }
5087    }
5088
5089    fn record_candidate_traits_for_expr_if_necessary(&mut self, expr: &'ast Expr) {
5090        match expr.kind {
5091            ExprKind::Field(_, ident) => {
5092                // #6890: Even though you can't treat a method like a field,
5093                // we need to add any trait methods we find that match the
5094                // field name so that we can do some nice error reporting
5095                // later on in typeck.
5096                let traits = self.traits_in_scope(ident, ValueNS);
5097                self.r.trait_map.insert(expr.id, traits);
5098            }
5099            ExprKind::MethodCall(ref call) => {
5100                debug!("(recording candidate traits for expr) recording traits for {}", expr.id);
5101                let traits = self.traits_in_scope(call.seg.ident, ValueNS);
5102                self.r.trait_map.insert(expr.id, traits);
5103            }
5104            _ => {
5105                // Nothing to do.
5106            }
5107        }
5108    }
5109
5110    fn traits_in_scope(&mut self, ident: Ident, ns: Namespace) -> Vec<TraitCandidate> {
5111        self.r.traits_in_scope(
5112            self.current_trait_ref.as_ref().map(|(module, _)| *module),
5113            &self.parent_scope,
5114            ident.span.ctxt(),
5115            Some((ident.name, ns)),
5116        )
5117    }
5118
5119    fn resolve_and_cache_rustdoc_path(&mut self, path_str: &str, ns: Namespace) -> Option<Res> {
5120        // FIXME: This caching may be incorrect in case of multiple `macro_rules`
5121        // items with the same name in the same module.
5122        // Also hygiene is not considered.
5123        let mut doc_link_resolutions = std::mem::take(&mut self.r.doc_link_resolutions);
5124        let res = *doc_link_resolutions
5125            .entry(self.parent_scope.module.nearest_parent_mod().expect_local())
5126            .or_default()
5127            .entry((Symbol::intern(path_str), ns))
5128            .or_insert_with_key(|(path, ns)| {
5129                let res = self.r.resolve_rustdoc_path(path.as_str(), *ns, self.parent_scope);
5130                if let Some(res) = res
5131                    && let Some(def_id) = res.opt_def_id()
5132                    && self.is_invalid_proc_macro_item_for_doc(def_id)
5133                {
5134                    // Encoding def ids in proc macro crate metadata will ICE,
5135                    // because it will only store proc macros for it.
5136                    return None;
5137                }
5138                res
5139            });
5140        self.r.doc_link_resolutions = doc_link_resolutions;
5141        res
5142    }
5143
5144    fn is_invalid_proc_macro_item_for_doc(&self, did: DefId) -> bool {
5145        if !matches!(self.r.tcx.sess.opts.resolve_doc_links, ResolveDocLinks::ExportedMetadata)
5146            || !self.r.tcx.crate_types().contains(&CrateType::ProcMacro)
5147        {
5148            return false;
5149        }
5150        let Some(local_did) = did.as_local() else { return true };
5151        !self.r.proc_macros.contains(&local_did)
5152    }
5153
5154    fn resolve_doc_links(&mut self, attrs: &[Attribute], maybe_exported: MaybeExported<'_>) {
5155        match self.r.tcx.sess.opts.resolve_doc_links {
5156            ResolveDocLinks::None => return,
5157            ResolveDocLinks::ExportedMetadata
5158                if !self.r.tcx.crate_types().iter().copied().any(CrateType::has_metadata)
5159                    || !maybe_exported.eval(self.r) =>
5160            {
5161                return;
5162            }
5163            ResolveDocLinks::Exported
5164                if !maybe_exported.eval(self.r)
5165                    && !rustdoc::has_primitive_or_keyword_or_attribute_docs(attrs) =>
5166            {
5167                return;
5168            }
5169            ResolveDocLinks::ExportedMetadata
5170            | ResolveDocLinks::Exported
5171            | ResolveDocLinks::All => {}
5172        }
5173
5174        if !attrs.iter().any(|attr| attr.may_have_doc_links()) {
5175            return;
5176        }
5177
5178        let mut need_traits_in_scope = false;
5179        for path_str in rustdoc::attrs_to_preprocessed_links(attrs) {
5180            // Resolve all namespaces due to no disambiguator or for diagnostics.
5181            let mut any_resolved = false;
5182            let mut need_assoc = false;
5183            for ns in [TypeNS, ValueNS, MacroNS] {
5184                if let Some(res) = self.resolve_and_cache_rustdoc_path(&path_str, ns) {
5185                    // Rustdoc ignores tool attribute resolutions and attempts
5186                    // to resolve their prefixes for diagnostics.
5187                    any_resolved = !matches!(res, Res::NonMacroAttr(NonMacroAttrKind::Tool));
5188                } else if ns != MacroNS {
5189                    need_assoc = true;
5190                }
5191            }
5192
5193            // Resolve all prefixes for type-relative resolution or for diagnostics.
5194            if need_assoc || !any_resolved {
5195                let mut path = &path_str[..];
5196                while let Some(idx) = path.rfind("::") {
5197                    path = &path[..idx];
5198                    need_traits_in_scope = true;
5199                    for ns in [TypeNS, ValueNS, MacroNS] {
5200                        self.resolve_and_cache_rustdoc_path(path, ns);
5201                    }
5202                }
5203            }
5204        }
5205
5206        if need_traits_in_scope {
5207            // FIXME: hygiene is not considered.
5208            let mut doc_link_traits_in_scope = std::mem::take(&mut self.r.doc_link_traits_in_scope);
5209            doc_link_traits_in_scope
5210                .entry(self.parent_scope.module.nearest_parent_mod().expect_local())
5211                .or_insert_with(|| {
5212                    self.r
5213                        .traits_in_scope(None, &self.parent_scope, SyntaxContext::root(), None)
5214                        .into_iter()
5215                        .filter_map(|tr| {
5216                            if self.is_invalid_proc_macro_item_for_doc(tr.def_id) {
5217                                // Encoding def ids in proc macro crate metadata will ICE.
5218                                // because it will only store proc macros for it.
5219                                return None;
5220                            }
5221                            Some(tr.def_id)
5222                        })
5223                        .collect()
5224                });
5225            self.r.doc_link_traits_in_scope = doc_link_traits_in_scope;
5226        }
5227    }
5228
5229    fn lint_unused_qualifications(&mut self, path: &[Segment], ns: Namespace, finalize: Finalize) {
5230        // Don't lint on global paths because the user explicitly wrote out the full path.
5231        if let Some(seg) = path.first()
5232            && seg.ident.name == kw::PathRoot
5233        {
5234            return;
5235        }
5236
5237        if finalize.path_span.from_expansion()
5238            || path.iter().any(|seg| seg.ident.span.from_expansion())
5239        {
5240            return;
5241        }
5242
5243        let end_pos =
5244            path.iter().position(|seg| seg.has_generic_args).map_or(path.len(), |pos| pos + 1);
5245        let unqualified = path[..end_pos].iter().enumerate().skip(1).rev().find_map(|(i, seg)| {
5246            // Preserve the current namespace for the final path segment, but use the type
5247            // namespace for all preceding segments
5248            //
5249            // e.g. for `std::env::args` check the `ValueNS` for `args` but the `TypeNS` for
5250            // `std` and `env`
5251            //
5252            // If the final path segment is beyond `end_pos` all the segments to check will
5253            // use the type namespace
5254            let ns = if i + 1 == path.len() { ns } else { TypeNS };
5255            let res = self.r.partial_res_map.get(&seg.id?)?.full_res()?;
5256            let binding = self.resolve_ident_in_lexical_scope(seg.ident, ns, None, None)?;
5257            (res == binding.res()).then_some((seg, binding))
5258        });
5259
5260        if let Some((seg, binding)) = unqualified {
5261            self.r.potentially_unnecessary_qualifications.push(UnnecessaryQualification {
5262                binding,
5263                node_id: finalize.node_id,
5264                path_span: finalize.path_span,
5265                removal_span: path[0].ident.span.until(seg.ident.span),
5266            });
5267        }
5268    }
5269
5270    fn resolve_define_opaques(&mut self, define_opaque: &Option<ThinVec<(NodeId, Path)>>) {
5271        if let Some(define_opaque) = define_opaque {
5272            for (id, path) in define_opaque {
5273                self.smart_resolve_path(*id, &None, path, PathSource::DefineOpaques);
5274            }
5275        }
5276    }
5277}
5278
5279/// Walks the whole crate in DFS order, visiting each item, counting the declared number of
5280/// lifetime generic parameters and function parameters.
5281struct ItemInfoCollector<'a, 'ra, 'tcx> {
5282    r: &'a mut Resolver<'ra, 'tcx>,
5283}
5284
5285impl ItemInfoCollector<'_, '_, '_> {
5286    fn collect_fn_info(
5287        &mut self,
5288        header: FnHeader,
5289        decl: &FnDecl,
5290        id: NodeId,
5291        attrs: &[Attribute],
5292    ) {
5293        let sig = DelegationFnSig {
5294            header,
5295            param_count: decl.inputs.len(),
5296            has_self: decl.has_self(),
5297            c_variadic: decl.c_variadic(),
5298            target_feature: attrs.iter().any(|attr| attr.has_name(sym::target_feature)),
5299        };
5300        self.r.delegation_fn_sigs.insert(self.r.local_def_id(id), sig);
5301    }
5302}
5303
5304impl<'ast> Visitor<'ast> for ItemInfoCollector<'_, '_, '_> {
5305    fn visit_item(&mut self, item: &'ast Item) {
5306        match &item.kind {
5307            ItemKind::TyAlias(box TyAlias { generics, .. })
5308            | ItemKind::Const(box ConstItem { generics, .. })
5309            | ItemKind::Fn(box Fn { generics, .. })
5310            | ItemKind::Enum(_, generics, _)
5311            | ItemKind::Struct(_, generics, _)
5312            | ItemKind::Union(_, generics, _)
5313            | ItemKind::Impl(Impl { generics, .. })
5314            | ItemKind::Trait(box Trait { generics, .. })
5315            | ItemKind::TraitAlias(box TraitAlias { generics, .. }) => {
5316                if let ItemKind::Fn(box Fn { sig, .. }) = &item.kind {
5317                    self.collect_fn_info(sig.header, &sig.decl, item.id, &item.attrs);
5318                }
5319
5320                let def_id = self.r.local_def_id(item.id);
5321                let count = generics
5322                    .params
5323                    .iter()
5324                    .filter(|param| matches!(param.kind, ast::GenericParamKind::Lifetime { .. }))
5325                    .count();
5326                self.r.item_generics_num_lifetimes.insert(def_id, count);
5327            }
5328
5329            ItemKind::ForeignMod(ForeignMod { extern_span, safety: _, abi, items }) => {
5330                for foreign_item in items {
5331                    if let ForeignItemKind::Fn(box Fn { sig, .. }) = &foreign_item.kind {
5332                        let new_header =
5333                            FnHeader { ext: Extern::from_abi(*abi, *extern_span), ..sig.header };
5334                        self.collect_fn_info(new_header, &sig.decl, foreign_item.id, &item.attrs);
5335                    }
5336                }
5337            }
5338
5339            ItemKind::Mod(..)
5340            | ItemKind::Static(..)
5341            | ItemKind::Use(..)
5342            | ItemKind::ExternCrate(..)
5343            | ItemKind::MacroDef(..)
5344            | ItemKind::GlobalAsm(..)
5345            | ItemKind::MacCall(..)
5346            | ItemKind::DelegationMac(..) => {}
5347            ItemKind::Delegation(..) => {
5348                // Delegated functions have lifetimes, their count is not necessarily zero.
5349                // But skipping the delegation items here doesn't mean that the count will be considered zero,
5350                // it means there will be a panic when retrieving the count,
5351                // but for delegation items we are never actually retrieving that count in practice.
5352            }
5353        }
5354        visit::walk_item(self, item)
5355    }
5356
5357    fn visit_assoc_item(&mut self, item: &'ast AssocItem, ctxt: AssocCtxt) {
5358        if let AssocItemKind::Fn(box Fn { sig, .. }) = &item.kind {
5359            self.collect_fn_info(sig.header, &sig.decl, item.id, &item.attrs);
5360        }
5361        visit::walk_assoc_item(self, item, ctxt);
5362    }
5363}
5364
5365impl<'ra, 'tcx> Resolver<'ra, 'tcx> {
5366    pub(crate) fn late_resolve_crate(&mut self, krate: &Crate) {
5367        visit::walk_crate(&mut ItemInfoCollector { r: self }, krate);
5368        let mut late_resolution_visitor = LateResolutionVisitor::new(self);
5369        late_resolution_visitor.resolve_doc_links(&krate.attrs, MaybeExported::Ok(CRATE_NODE_ID));
5370        visit::walk_crate(&mut late_resolution_visitor, krate);
5371        for (id, span) in late_resolution_visitor.diag_metadata.unused_labels.iter() {
5372            self.lint_buffer.buffer_lint(
5373                lint::builtin::UNUSED_LABELS,
5374                *id,
5375                *span,
5376                errors::UnusedLabel,
5377            );
5378        }
5379    }
5380}
5381
5382/// Check if definition matches a path
5383fn def_id_matches_path(tcx: TyCtxt<'_>, mut def_id: DefId, expected_path: &[&str]) -> bool {
5384    let mut path = expected_path.iter().rev();
5385    while let (Some(parent), Some(next_step)) = (tcx.opt_parent(def_id), path.next()) {
5386        if !tcx.opt_item_name(def_id).is_some_and(|n| n.as_str() == *next_step) {
5387            return false;
5388        }
5389        def_id = parent;
5390    }
5391    true
5392}