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