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