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, Visibility};
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 ast::Visibility>),
642    NestedUse(&'a ast::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(&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                    // To avoid emitting two similar errors,
2903                    // we need to check if the span is a raw underscore lifetime, see issue #143152
2904                    let is_raw_underscore_lifetime = self
2905                        .r
2906                        .tcx
2907                        .sess
2908                        .psess
2909                        .raw_identifier_spans
2910                        .iter()
2911                        .any(|span| span == param.span());
2912
2913                    self.r
2914                        .dcx()
2915                        .create_err(errors::UnderscoreLifetimeIsReserved { span: param.ident.span })
2916                        .emit_unless_delay(is_raw_underscore_lifetime);
2917                    // Record lifetime res, so lowering knows there is something fishy.
2918                    self.record_lifetime_param(param.id, LifetimeRes::Error);
2919                    continue;
2920                }
2921
2922                if param.ident.name == kw::StaticLifetime {
2923                    self.r.dcx().emit_err(errors::StaticLifetimeIsReserved {
2924                        span: param.ident.span,
2925                        lifetime: param.ident,
2926                    });
2927                    // Record lifetime res, so lowering knows there is something fishy.
2928                    self.record_lifetime_param(param.id, LifetimeRes::Error);
2929                    continue;
2930                }
2931
2932                let def_id = self.r.local_def_id(param.id);
2933
2934                // Plain insert (no renaming).
2935                let (rib, def_kind) = match param.kind {
2936                    GenericParamKind::Type { .. } => (&mut function_type_rib, DefKind::TyParam),
2937                    GenericParamKind::Const { .. } => {
2938                        (&mut function_value_rib, DefKind::ConstParam)
2939                    }
2940                    GenericParamKind::Lifetime => {
2941                        let res = LifetimeRes::Param { param: def_id, binder };
2942                        self.record_lifetime_param(param.id, res);
2943                        function_lifetime_rib.bindings.insert(ident, (param.id, res));
2944                        continue;
2945                    }
2946                };
2947
2948                let res = match kind {
2949                    RibKind::Item(..) | RibKind::AssocItem => {
2950                        Res::Def(def_kind, def_id.to_def_id())
2951                    }
2952                    RibKind::Normal => {
2953                        // FIXME(non_lifetime_binders): Stop special-casing
2954                        // const params to error out here.
2955                        if self.r.tcx.features().non_lifetime_binders()
2956                            && matches!(param.kind, GenericParamKind::Type { .. })
2957                        {
2958                            Res::Def(def_kind, def_id.to_def_id())
2959                        } else {
2960                            Res::Err
2961                        }
2962                    }
2963                    _ => span_bug!(param.ident.span, "Unexpected rib kind {:?}", kind),
2964                };
2965                self.r.record_partial_res(param.id, PartialRes::new(res));
2966                rib.bindings.insert(ident, res);
2967            }
2968        }
2969
2970        self.lifetime_ribs.push(function_lifetime_rib);
2971        self.ribs[ValueNS].push(function_value_rib);
2972        self.ribs[TypeNS].push(function_type_rib);
2973
2974        f(self);
2975
2976        self.ribs[TypeNS].pop();
2977        self.ribs[ValueNS].pop();
2978        let function_lifetime_rib = self.lifetime_ribs.pop().unwrap();
2979
2980        // Do not account for the parameters we just bound for function lifetime elision.
2981        if let Some(ref mut candidates) = self.lifetime_elision_candidates {
2982            for (_, res) in function_lifetime_rib.bindings.values() {
2983                candidates.retain(|(r, _)| r != res);
2984            }
2985        }
2986
2987        if let LifetimeBinderKind::FnPtrType
2988        | LifetimeBinderKind::WhereBound
2989        | LifetimeBinderKind::Function
2990        | LifetimeBinderKind::ImplBlock = generics_kind
2991        {
2992            self.maybe_report_lifetime_uses(generics_span, params)
2993        }
2994    }
2995
2996    fn with_label_rib(&mut self, kind: RibKind<'ra>, f: impl FnOnce(&mut Self)) {
2997        self.label_ribs.push(Rib::new(kind));
2998        f(self);
2999        self.label_ribs.pop();
3000    }
3001
3002    fn with_static_rib(&mut self, def_kind: DefKind, f: impl FnOnce(&mut Self)) {
3003        let kind = RibKind::Item(HasGenericParams::No, def_kind);
3004        self.with_rib(ValueNS, kind, |this| this.with_rib(TypeNS, kind, f))
3005    }
3006
3007    // HACK(min_const_generics, generic_const_exprs): We
3008    // want to keep allowing `[0; size_of::<*mut T>()]`
3009    // with a future compat lint for now. We do this by adding an
3010    // additional special case for repeat expressions.
3011    //
3012    // Note that we intentionally still forbid `[0; N + 1]` during
3013    // name resolution so that we don't extend the future
3014    // compat lint to new cases.
3015    #[instrument(level = "debug", skip(self, f))]
3016    fn with_constant_rib(
3017        &mut self,
3018        is_repeat: IsRepeatExpr,
3019        may_use_generics: ConstantHasGenerics,
3020        item: Option<(Ident, ConstantItemKind)>,
3021        f: impl FnOnce(&mut Self),
3022    ) {
3023        let f = |this: &mut Self| {
3024            this.with_rib(ValueNS, RibKind::ConstantItem(may_use_generics, item), |this| {
3025                this.with_rib(
3026                    TypeNS,
3027                    RibKind::ConstantItem(
3028                        may_use_generics.force_yes_if(is_repeat == IsRepeatExpr::Yes),
3029                        item,
3030                    ),
3031                    |this| {
3032                        this.with_label_rib(RibKind::ConstantItem(may_use_generics, item), f);
3033                    },
3034                )
3035            })
3036        };
3037
3038        if let ConstantHasGenerics::No(cause) = may_use_generics {
3039            self.with_lifetime_rib(LifetimeRibKind::ConcreteAnonConst(cause), f)
3040        } else {
3041            f(self)
3042        }
3043    }
3044
3045    fn with_current_self_type<T>(&mut self, self_type: &Ty, f: impl FnOnce(&mut Self) -> T) -> T {
3046        // Handle nested impls (inside fn bodies)
3047        let previous_value =
3048            replace(&mut self.diag_metadata.current_self_type, Some(self_type.clone()));
3049        let result = f(self);
3050        self.diag_metadata.current_self_type = previous_value;
3051        result
3052    }
3053
3054    fn with_current_self_item<T>(&mut self, self_item: &Item, f: impl FnOnce(&mut Self) -> T) -> T {
3055        let previous_value = replace(&mut self.diag_metadata.current_self_item, Some(self_item.id));
3056        let result = f(self);
3057        self.diag_metadata.current_self_item = previous_value;
3058        result
3059    }
3060
3061    /// When evaluating a `trait` use its associated types' idents for suggestions in E0412.
3062    fn resolve_trait_items(&mut self, trait_items: &'ast [P<AssocItem>]) {
3063        let trait_assoc_items =
3064            replace(&mut self.diag_metadata.current_trait_assoc_items, Some(trait_items));
3065
3066        let walk_assoc_item =
3067            |this: &mut Self, generics: &Generics, kind, item: &'ast AssocItem| {
3068                this.with_generic_param_rib(
3069                    &generics.params,
3070                    RibKind::AssocItem,
3071                    item.id,
3072                    kind,
3073                    generics.span,
3074                    |this| visit::walk_assoc_item(this, item, AssocCtxt::Trait),
3075                );
3076            };
3077
3078        for item in trait_items {
3079            self.resolve_doc_links(&item.attrs, MaybeExported::Ok(item.id));
3080            match &item.kind {
3081                AssocItemKind::Const(box ast::ConstItem {
3082                    generics,
3083                    ty,
3084                    expr,
3085                    define_opaque,
3086                    ..
3087                }) => {
3088                    self.with_generic_param_rib(
3089                        &generics.params,
3090                        RibKind::AssocItem,
3091                        item.id,
3092                        LifetimeBinderKind::ConstItem,
3093                        generics.span,
3094                        |this| {
3095                            this.with_lifetime_rib(
3096                                LifetimeRibKind::StaticIfNoLifetimeInScope {
3097                                    lint_id: item.id,
3098                                    emit_lint: false,
3099                                },
3100                                |this| {
3101                                    this.visit_generics(generics);
3102                                    this.visit_ty(ty);
3103
3104                                    // Only impose the restrictions of `ConstRibKind` for an
3105                                    // actual constant expression in a provided default.
3106                                    if let Some(expr) = expr {
3107                                        // We allow arbitrary const expressions inside of associated consts,
3108                                        // even if they are potentially not const evaluatable.
3109                                        //
3110                                        // Type parameters can already be used and as associated consts are
3111                                        // not used as part of the type system, this is far less surprising.
3112                                        this.resolve_const_body(expr, None);
3113                                    }
3114                                },
3115                            )
3116                        },
3117                    );
3118
3119                    self.resolve_define_opaques(define_opaque);
3120                }
3121                AssocItemKind::Fn(box Fn { generics, define_opaque, .. }) => {
3122                    walk_assoc_item(self, generics, LifetimeBinderKind::Function, item);
3123
3124                    self.resolve_define_opaques(define_opaque);
3125                }
3126                AssocItemKind::Delegation(delegation) => {
3127                    self.with_generic_param_rib(
3128                        &[],
3129                        RibKind::AssocItem,
3130                        item.id,
3131                        LifetimeBinderKind::Function,
3132                        delegation.path.segments.last().unwrap().ident.span,
3133                        |this| this.resolve_delegation(delegation),
3134                    );
3135                }
3136                AssocItemKind::Type(box TyAlias { generics, .. }) => self
3137                    .with_lifetime_rib(LifetimeRibKind::AnonymousReportError, |this| {
3138                        walk_assoc_item(this, generics, LifetimeBinderKind::Item, item)
3139                    }),
3140                AssocItemKind::MacCall(_) | AssocItemKind::DelegationMac(..) => {
3141                    panic!("unexpanded macro in resolve!")
3142                }
3143            };
3144        }
3145
3146        self.diag_metadata.current_trait_assoc_items = trait_assoc_items;
3147    }
3148
3149    /// This is called to resolve a trait reference from an `impl` (i.e., `impl Trait for Foo`).
3150    fn with_optional_trait_ref<T>(
3151        &mut self,
3152        opt_trait_ref: Option<&TraitRef>,
3153        self_type: &'ast Ty,
3154        f: impl FnOnce(&mut Self, Option<DefId>) -> T,
3155    ) -> T {
3156        let mut new_val = None;
3157        let mut new_id = None;
3158        if let Some(trait_ref) = opt_trait_ref {
3159            let path: Vec<_> = Segment::from_path(&trait_ref.path);
3160            self.diag_metadata.currently_processing_impl_trait =
3161                Some((trait_ref.clone(), self_type.clone()));
3162            let res = self.smart_resolve_path_fragment(
3163                &None,
3164                &path,
3165                PathSource::Trait(AliasPossibility::No),
3166                Finalize::new(trait_ref.ref_id, trait_ref.path.span),
3167                RecordPartialRes::Yes,
3168                None,
3169            );
3170            self.diag_metadata.currently_processing_impl_trait = None;
3171            if let Some(def_id) = res.expect_full_res().opt_def_id() {
3172                new_id = Some(def_id);
3173                new_val = Some((self.r.expect_module(def_id), trait_ref.clone()));
3174            }
3175        }
3176        let original_trait_ref = replace(&mut self.current_trait_ref, new_val);
3177        let result = f(self, new_id);
3178        self.current_trait_ref = original_trait_ref;
3179        result
3180    }
3181
3182    fn with_self_rib_ns(&mut self, ns: Namespace, self_res: Res, f: impl FnOnce(&mut Self)) {
3183        let mut self_type_rib = Rib::new(RibKind::Normal);
3184
3185        // Plain insert (no renaming, since types are not currently hygienic)
3186        self_type_rib.bindings.insert(Ident::with_dummy_span(kw::SelfUpper), self_res);
3187        self.ribs[ns].push(self_type_rib);
3188        f(self);
3189        self.ribs[ns].pop();
3190    }
3191
3192    fn with_self_rib(&mut self, self_res: Res, f: impl FnOnce(&mut Self)) {
3193        self.with_self_rib_ns(TypeNS, self_res, f)
3194    }
3195
3196    fn resolve_implementation(
3197        &mut self,
3198        attrs: &[ast::Attribute],
3199        generics: &'ast Generics,
3200        opt_trait_reference: &'ast Option<TraitRef>,
3201        self_type: &'ast Ty,
3202        item_id: NodeId,
3203        impl_items: &'ast [P<AssocItem>],
3204    ) {
3205        debug!("resolve_implementation");
3206        // If applicable, create a rib for the type parameters.
3207        self.with_generic_param_rib(
3208            &generics.params,
3209            RibKind::Item(HasGenericParams::Yes(generics.span), self.r.local_def_kind(item_id)),
3210            item_id,
3211            LifetimeBinderKind::ImplBlock,
3212            generics.span,
3213            |this| {
3214                // Dummy self type for better errors if `Self` is used in the trait path.
3215                this.with_self_rib(Res::SelfTyParam { trait_: LOCAL_CRATE.as_def_id() }, |this| {
3216                    this.with_lifetime_rib(
3217                        LifetimeRibKind::AnonymousCreateParameter {
3218                            binder: item_id,
3219                            report_in_path: true
3220                        },
3221                        |this| {
3222                            // Resolve the trait reference, if necessary.
3223                            this.with_optional_trait_ref(
3224                                opt_trait_reference.as_ref(),
3225                                self_type,
3226                                |this, trait_id| {
3227                                    this.resolve_doc_links(attrs, MaybeExported::Impl(trait_id));
3228
3229                                    let item_def_id = this.r.local_def_id(item_id);
3230
3231                                    // Register the trait definitions from here.
3232                                    if let Some(trait_id) = trait_id {
3233                                        this.r
3234                                            .trait_impls
3235                                            .entry(trait_id)
3236                                            .or_default()
3237                                            .push(item_def_id);
3238                                    }
3239
3240                                    let item_def_id = item_def_id.to_def_id();
3241                                    let res = Res::SelfTyAlias {
3242                                        alias_to: item_def_id,
3243                                        forbid_generic: false,
3244                                        is_trait_impl: trait_id.is_some()
3245                                    };
3246                                    this.with_self_rib(res, |this| {
3247                                        if let Some(trait_ref) = opt_trait_reference.as_ref() {
3248                                            // Resolve type arguments in the trait path.
3249                                            visit::walk_trait_ref(this, trait_ref);
3250                                        }
3251                                        // Resolve the self type.
3252                                        this.visit_ty(self_type);
3253                                        // Resolve the generic parameters.
3254                                        this.visit_generics(generics);
3255
3256                                        // Resolve the items within the impl.
3257                                        this.with_current_self_type(self_type, |this| {
3258                                            this.with_self_rib_ns(ValueNS, Res::SelfCtor(item_def_id), |this| {
3259                                                debug!("resolve_implementation with_self_rib_ns(ValueNS, ...)");
3260                                                let mut seen_trait_items = Default::default();
3261                                                for item in impl_items {
3262                                                    this.resolve_impl_item(&**item, &mut seen_trait_items, trait_id);
3263                                                }
3264                                            });
3265                                        });
3266                                    });
3267                                },
3268                            )
3269                        },
3270                    );
3271                });
3272            },
3273        );
3274    }
3275
3276    fn resolve_impl_item(
3277        &mut self,
3278        item: &'ast AssocItem,
3279        seen_trait_items: &mut FxHashMap<DefId, Span>,
3280        trait_id: Option<DefId>,
3281    ) {
3282        use crate::ResolutionError::*;
3283        self.resolve_doc_links(&item.attrs, MaybeExported::ImplItem(trait_id.ok_or(&item.vis)));
3284        match &item.kind {
3285            AssocItemKind::Const(box ast::ConstItem {
3286                ident,
3287                generics,
3288                ty,
3289                expr,
3290                define_opaque,
3291                ..
3292            }) => {
3293                debug!("resolve_implementation AssocItemKind::Const");
3294                self.with_generic_param_rib(
3295                    &generics.params,
3296                    RibKind::AssocItem,
3297                    item.id,
3298                    LifetimeBinderKind::ConstItem,
3299                    generics.span,
3300                    |this| {
3301                        this.with_lifetime_rib(
3302                            // Until these are a hard error, we need to create them within the
3303                            // correct binder, Otherwise the lifetimes of this assoc const think
3304                            // they are lifetimes of the trait.
3305                            LifetimeRibKind::AnonymousCreateParameter {
3306                                binder: item.id,
3307                                report_in_path: true,
3308                            },
3309                            |this| {
3310                                this.with_lifetime_rib(
3311                                    LifetimeRibKind::StaticIfNoLifetimeInScope {
3312                                        lint_id: item.id,
3313                                        // In impls, it's not a hard error yet due to backcompat.
3314                                        emit_lint: true,
3315                                    },
3316                                    |this| {
3317                                        // If this is a trait impl, ensure the const
3318                                        // exists in trait
3319                                        this.check_trait_item(
3320                                            item.id,
3321                                            *ident,
3322                                            &item.kind,
3323                                            ValueNS,
3324                                            item.span,
3325                                            seen_trait_items,
3326                                            |i, s, c| ConstNotMemberOfTrait(i, s, c),
3327                                        );
3328
3329                                        this.visit_generics(generics);
3330                                        this.visit_ty(ty);
3331                                        if let Some(expr) = expr {
3332                                            // We allow arbitrary const expressions inside of associated consts,
3333                                            // even if they are potentially not const evaluatable.
3334                                            //
3335                                            // Type parameters can already be used and as associated consts are
3336                                            // not used as part of the type system, this is far less surprising.
3337                                            this.resolve_const_body(expr, None);
3338                                        }
3339                                    },
3340                                )
3341                            },
3342                        );
3343                    },
3344                );
3345                self.resolve_define_opaques(define_opaque);
3346            }
3347            AssocItemKind::Fn(box Fn { ident, generics, define_opaque, .. }) => {
3348                debug!("resolve_implementation AssocItemKind::Fn");
3349                // We also need a new scope for the impl item type parameters.
3350                self.with_generic_param_rib(
3351                    &generics.params,
3352                    RibKind::AssocItem,
3353                    item.id,
3354                    LifetimeBinderKind::Function,
3355                    generics.span,
3356                    |this| {
3357                        // If this is a trait impl, ensure the method
3358                        // exists in trait
3359                        this.check_trait_item(
3360                            item.id,
3361                            *ident,
3362                            &item.kind,
3363                            ValueNS,
3364                            item.span,
3365                            seen_trait_items,
3366                            |i, s, c| MethodNotMemberOfTrait(i, s, c),
3367                        );
3368
3369                        visit::walk_assoc_item(this, item, AssocCtxt::Impl { of_trait: true })
3370                    },
3371                );
3372
3373                self.resolve_define_opaques(define_opaque);
3374            }
3375            AssocItemKind::Type(box TyAlias { ident, generics, .. }) => {
3376                self.diag_metadata.in_non_gat_assoc_type = Some(generics.params.is_empty());
3377                debug!("resolve_implementation AssocItemKind::Type");
3378                // We also need a new scope for the impl item type parameters.
3379                self.with_generic_param_rib(
3380                    &generics.params,
3381                    RibKind::AssocItem,
3382                    item.id,
3383                    LifetimeBinderKind::Item,
3384                    generics.span,
3385                    |this| {
3386                        this.with_lifetime_rib(LifetimeRibKind::AnonymousReportError, |this| {
3387                            // If this is a trait impl, ensure the type
3388                            // exists in trait
3389                            this.check_trait_item(
3390                                item.id,
3391                                *ident,
3392                                &item.kind,
3393                                TypeNS,
3394                                item.span,
3395                                seen_trait_items,
3396                                |i, s, c| TypeNotMemberOfTrait(i, s, c),
3397                            );
3398
3399                            visit::walk_assoc_item(this, item, AssocCtxt::Impl { of_trait: true })
3400                        });
3401                    },
3402                );
3403                self.diag_metadata.in_non_gat_assoc_type = None;
3404            }
3405            AssocItemKind::Delegation(box delegation) => {
3406                debug!("resolve_implementation AssocItemKind::Delegation");
3407                self.with_generic_param_rib(
3408                    &[],
3409                    RibKind::AssocItem,
3410                    item.id,
3411                    LifetimeBinderKind::Function,
3412                    delegation.path.segments.last().unwrap().ident.span,
3413                    |this| {
3414                        this.check_trait_item(
3415                            item.id,
3416                            delegation.ident,
3417                            &item.kind,
3418                            ValueNS,
3419                            item.span,
3420                            seen_trait_items,
3421                            |i, s, c| MethodNotMemberOfTrait(i, s, c),
3422                        );
3423
3424                        this.resolve_delegation(delegation)
3425                    },
3426                );
3427            }
3428            AssocItemKind::MacCall(_) | AssocItemKind::DelegationMac(..) => {
3429                panic!("unexpanded macro in resolve!")
3430            }
3431        }
3432    }
3433
3434    fn check_trait_item<F>(
3435        &mut self,
3436        id: NodeId,
3437        mut ident: Ident,
3438        kind: &AssocItemKind,
3439        ns: Namespace,
3440        span: Span,
3441        seen_trait_items: &mut FxHashMap<DefId, Span>,
3442        err: F,
3443    ) where
3444        F: FnOnce(Ident, String, Option<Symbol>) -> ResolutionError<'ra>,
3445    {
3446        // If there is a TraitRef in scope for an impl, then the method must be in the trait.
3447        let Some((module, _)) = self.current_trait_ref else {
3448            return;
3449        };
3450        ident.span.normalize_to_macros_2_0_and_adjust(module.expansion);
3451        let key = BindingKey::new(ident, ns);
3452        let mut binding =
3453            self.r.resolution(module, key).try_borrow().ok().and_then(|r| r.best_binding());
3454        debug!(?binding);
3455        if binding.is_none() {
3456            // We could not find the trait item in the correct namespace.
3457            // Check the other namespace to report an error.
3458            let ns = match ns {
3459                ValueNS => TypeNS,
3460                TypeNS => ValueNS,
3461                _ => ns,
3462            };
3463            let key = BindingKey::new(ident, ns);
3464            binding =
3465                self.r.resolution(module, key).try_borrow().ok().and_then(|r| r.best_binding());
3466            debug!(?binding);
3467        }
3468
3469        let feed_visibility = |this: &mut Self, def_id| {
3470            let vis = this.r.tcx.visibility(def_id);
3471            let vis = if vis.is_visible_locally() {
3472                vis.expect_local()
3473            } else {
3474                this.r.dcx().span_delayed_bug(
3475                    span,
3476                    "error should be emitted when an unexpected trait item is used",
3477                );
3478                Visibility::Public
3479            };
3480            this.r.feed_visibility(this.r.feed(id), vis);
3481        };
3482
3483        let Some(binding) = binding else {
3484            // We could not find the method: report an error.
3485            let candidate = self.find_similarly_named_assoc_item(ident.name, kind);
3486            let path = &self.current_trait_ref.as_ref().unwrap().1.path;
3487            let path_names = path_names_to_string(path);
3488            self.report_error(span, err(ident, path_names, candidate));
3489            feed_visibility(self, module.def_id());
3490            return;
3491        };
3492
3493        let res = binding.res();
3494        let Res::Def(def_kind, id_in_trait) = res else { bug!() };
3495        feed_visibility(self, id_in_trait);
3496
3497        match seen_trait_items.entry(id_in_trait) {
3498            Entry::Occupied(entry) => {
3499                self.report_error(
3500                    span,
3501                    ResolutionError::TraitImplDuplicate {
3502                        name: ident,
3503                        old_span: *entry.get(),
3504                        trait_item_span: binding.span,
3505                    },
3506                );
3507                return;
3508            }
3509            Entry::Vacant(entry) => {
3510                entry.insert(span);
3511            }
3512        };
3513
3514        match (def_kind, kind) {
3515            (DefKind::AssocTy, AssocItemKind::Type(..))
3516            | (DefKind::AssocFn, AssocItemKind::Fn(..))
3517            | (DefKind::AssocConst, AssocItemKind::Const(..))
3518            | (DefKind::AssocFn, AssocItemKind::Delegation(..)) => {
3519                self.r.record_partial_res(id, PartialRes::new(res));
3520                return;
3521            }
3522            _ => {}
3523        }
3524
3525        // The method kind does not correspond to what appeared in the trait, report.
3526        let path = &self.current_trait_ref.as_ref().unwrap().1.path;
3527        let (code, kind) = match kind {
3528            AssocItemKind::Const(..) => (E0323, "const"),
3529            AssocItemKind::Fn(..) => (E0324, "method"),
3530            AssocItemKind::Type(..) => (E0325, "type"),
3531            AssocItemKind::Delegation(..) => (E0324, "method"),
3532            AssocItemKind::MacCall(..) | AssocItemKind::DelegationMac(..) => {
3533                span_bug!(span, "unexpanded macro")
3534            }
3535        };
3536        let trait_path = path_names_to_string(path);
3537        self.report_error(
3538            span,
3539            ResolutionError::TraitImplMismatch {
3540                name: ident,
3541                kind,
3542                code,
3543                trait_path,
3544                trait_item_span: binding.span,
3545            },
3546        );
3547    }
3548
3549    fn resolve_const_body(&mut self, expr: &'ast Expr, item: Option<(Ident, ConstantItemKind)>) {
3550        self.with_lifetime_rib(LifetimeRibKind::Elided(LifetimeRes::Infer), |this| {
3551            this.with_constant_rib(IsRepeatExpr::No, ConstantHasGenerics::Yes, item, |this| {
3552                this.visit_expr(expr)
3553            });
3554        })
3555    }
3556
3557    fn resolve_delegation(&mut self, delegation: &'ast Delegation) {
3558        self.smart_resolve_path(
3559            delegation.id,
3560            &delegation.qself,
3561            &delegation.path,
3562            PathSource::Delegation,
3563        );
3564        if let Some(qself) = &delegation.qself {
3565            self.visit_ty(&qself.ty);
3566        }
3567        self.visit_path(&delegation.path);
3568        let Some(body) = &delegation.body else { return };
3569        self.with_rib(ValueNS, RibKind::FnOrCoroutine, |this| {
3570            let span = delegation.path.segments.last().unwrap().ident.span;
3571            let ident = Ident::new(kw::SelfLower, span.normalize_to_macro_rules());
3572            let res = Res::Local(delegation.id);
3573            this.innermost_rib_bindings(ValueNS).insert(ident, res);
3574            this.visit_block(body);
3575        });
3576    }
3577
3578    fn resolve_params(&mut self, params: &'ast [Param]) {
3579        let mut bindings = smallvec![(PatBoundCtx::Product, Default::default())];
3580        self.with_lifetime_rib(LifetimeRibKind::Elided(LifetimeRes::Infer), |this| {
3581            for Param { pat, .. } in params {
3582                this.resolve_pattern(pat, PatternSource::FnParam, &mut bindings);
3583            }
3584            this.apply_pattern_bindings(bindings);
3585        });
3586        for Param { ty, .. } in params {
3587            self.visit_ty(ty);
3588        }
3589    }
3590
3591    fn resolve_local(&mut self, local: &'ast Local) {
3592        debug!("resolving local ({:?})", local);
3593        // Resolve the type.
3594        visit_opt!(self, visit_ty, &local.ty);
3595
3596        // Resolve the initializer.
3597        if let Some((init, els)) = local.kind.init_else_opt() {
3598            self.visit_expr(init);
3599
3600            // Resolve the `else` block
3601            if let Some(els) = els {
3602                self.visit_block(els);
3603            }
3604        }
3605
3606        // Resolve the pattern.
3607        self.resolve_pattern_top(&local.pat, PatternSource::Let);
3608    }
3609
3610    /// Build a map from pattern identifiers to binding-info's, and check the bindings are
3611    /// consistent when encountering or-patterns and never patterns.
3612    /// This is done hygienically: this could arise for a macro that expands into an or-pattern
3613    /// where one 'x' was from the user and one 'x' came from the macro.
3614    ///
3615    /// A never pattern by definition indicates an unreachable case. For example, matching on
3616    /// `Result<T, &!>` could look like:
3617    /// ```rust
3618    /// # #![feature(never_type)]
3619    /// # #![feature(never_patterns)]
3620    /// # fn bar(_x: u32) {}
3621    /// let foo: Result<u32, &!> = Ok(0);
3622    /// match foo {
3623    ///     Ok(x) => bar(x),
3624    ///     Err(&!),
3625    /// }
3626    /// ```
3627    /// This extends to product types: `(x, !)` is likewise unreachable. So it doesn't make sense to
3628    /// have a binding here, and we tell the user to use `_` instead.
3629    fn compute_and_check_binding_map(
3630        &mut self,
3631        pat: &Pat,
3632    ) -> Result<FxIndexMap<Ident, BindingInfo>, IsNeverPattern> {
3633        let mut binding_map = FxIndexMap::default();
3634        let mut is_never_pat = false;
3635
3636        pat.walk(&mut |pat| {
3637            match pat.kind {
3638                PatKind::Ident(annotation, ident, ref sub_pat)
3639                    if sub_pat.is_some() || self.is_base_res_local(pat.id) =>
3640                {
3641                    binding_map.insert(ident, BindingInfo { span: ident.span, annotation });
3642                }
3643                PatKind::Or(ref ps) => {
3644                    // Check the consistency of this or-pattern and
3645                    // then add all bindings to the larger map.
3646                    match self.compute_and_check_or_pat_binding_map(ps) {
3647                        Ok(bm) => binding_map.extend(bm),
3648                        Err(IsNeverPattern) => is_never_pat = true,
3649                    }
3650                    return false;
3651                }
3652                PatKind::Never => is_never_pat = true,
3653                _ => {}
3654            }
3655
3656            true
3657        });
3658
3659        if is_never_pat {
3660            for (_, binding) in binding_map {
3661                self.report_error(binding.span, ResolutionError::BindingInNeverPattern);
3662            }
3663            Err(IsNeverPattern)
3664        } else {
3665            Ok(binding_map)
3666        }
3667    }
3668
3669    fn is_base_res_local(&self, nid: NodeId) -> bool {
3670        matches!(
3671            self.r.partial_res_map.get(&nid).map(|res| res.expect_full_res()),
3672            Some(Res::Local(..))
3673        )
3674    }
3675
3676    /// Compute the binding map for an or-pattern. Checks that all of the arms in the or-pattern
3677    /// have exactly the same set of bindings, with the same binding modes for each.
3678    /// Returns the computed binding map and a boolean indicating whether the pattern is a never
3679    /// pattern.
3680    ///
3681    /// A never pattern by definition indicates an unreachable case. For example, destructuring a
3682    /// `Result<T, &!>` could look like:
3683    /// ```rust
3684    /// # #![feature(never_type)]
3685    /// # #![feature(never_patterns)]
3686    /// # fn foo() -> Result<bool, &'static !> { Ok(true) }
3687    /// let (Ok(x) | Err(&!)) = foo();
3688    /// # let _ = x;
3689    /// ```
3690    /// Because the `Err(&!)` branch is never reached, it does not need to have the same bindings as
3691    /// the other branches of the or-pattern. So we must ignore never pattern when checking the
3692    /// bindings of an or-pattern.
3693    /// Moreover, if all the subpatterns are never patterns (e.g. `Ok(!) | Err(!)`), then the
3694    /// pattern as a whole counts as a never pattern (since it's definitionallly unreachable).
3695    fn compute_and_check_or_pat_binding_map(
3696        &mut self,
3697        pats: &[P<Pat>],
3698    ) -> Result<FxIndexMap<Ident, BindingInfo>, IsNeverPattern> {
3699        let mut missing_vars = FxIndexMap::default();
3700        let mut inconsistent_vars = FxIndexMap::default();
3701
3702        // 1) Compute the binding maps of all arms; we must ignore never patterns here.
3703        let not_never_pats = pats
3704            .iter()
3705            .filter_map(|pat| {
3706                let binding_map = self.compute_and_check_binding_map(pat).ok()?;
3707                Some((binding_map, pat))
3708            })
3709            .collect::<Vec<_>>();
3710
3711        // 2) Record any missing bindings or binding mode inconsistencies.
3712        for (map_outer, pat_outer) in not_never_pats.iter() {
3713            // Check against all arms except for the same pattern which is always self-consistent.
3714            let inners = not_never_pats
3715                .iter()
3716                .filter(|(_, pat)| pat.id != pat_outer.id)
3717                .flat_map(|(map, _)| map);
3718
3719            for (&name, binding_inner) in inners {
3720                match map_outer.get(&name) {
3721                    None => {
3722                        // The inner binding is missing in the outer.
3723                        let binding_error =
3724                            missing_vars.entry(name).or_insert_with(|| BindingError {
3725                                name,
3726                                origin: BTreeSet::new(),
3727                                target: BTreeSet::new(),
3728                                could_be_path: name.as_str().starts_with(char::is_uppercase),
3729                            });
3730                        binding_error.origin.insert(binding_inner.span);
3731                        binding_error.target.insert(pat_outer.span);
3732                    }
3733                    Some(binding_outer) => {
3734                        if binding_outer.annotation != binding_inner.annotation {
3735                            // The binding modes in the outer and inner bindings differ.
3736                            inconsistent_vars
3737                                .entry(name)
3738                                .or_insert((binding_inner.span, binding_outer.span));
3739                        }
3740                    }
3741                }
3742            }
3743        }
3744
3745        // 3) Report all missing variables we found.
3746        for (name, mut v) in missing_vars {
3747            if inconsistent_vars.contains_key(&name) {
3748                v.could_be_path = false;
3749            }
3750            self.report_error(
3751                *v.origin.iter().next().unwrap(),
3752                ResolutionError::VariableNotBoundInPattern(v, self.parent_scope),
3753            );
3754        }
3755
3756        // 4) Report all inconsistencies in binding modes we found.
3757        for (name, v) in inconsistent_vars {
3758            self.report_error(v.0, ResolutionError::VariableBoundWithDifferentMode(name, v.1));
3759        }
3760
3761        // 5) Bubble up the final binding map.
3762        if not_never_pats.is_empty() {
3763            // All the patterns are never patterns, so the whole or-pattern is one too.
3764            Err(IsNeverPattern)
3765        } else {
3766            let mut binding_map = FxIndexMap::default();
3767            for (bm, _) in not_never_pats {
3768                binding_map.extend(bm);
3769            }
3770            Ok(binding_map)
3771        }
3772    }
3773
3774    /// Check the consistency of bindings wrt or-patterns and never patterns.
3775    fn check_consistent_bindings(&mut self, pat: &'ast Pat) {
3776        let mut is_or_or_never = false;
3777        pat.walk(&mut |pat| match pat.kind {
3778            PatKind::Or(..) | PatKind::Never => {
3779                is_or_or_never = true;
3780                false
3781            }
3782            _ => true,
3783        });
3784        if is_or_or_never {
3785            let _ = self.compute_and_check_binding_map(pat);
3786        }
3787    }
3788
3789    fn resolve_arm(&mut self, arm: &'ast Arm) {
3790        self.with_rib(ValueNS, RibKind::Normal, |this| {
3791            this.resolve_pattern_top(&arm.pat, PatternSource::Match);
3792            visit_opt!(this, visit_expr, &arm.guard);
3793            visit_opt!(this, visit_expr, &arm.body);
3794        });
3795    }
3796
3797    /// Arising from `source`, resolve a top level pattern.
3798    fn resolve_pattern_top(&mut self, pat: &'ast Pat, pat_src: PatternSource) {
3799        let mut bindings = smallvec![(PatBoundCtx::Product, Default::default())];
3800        self.resolve_pattern(pat, pat_src, &mut bindings);
3801        self.apply_pattern_bindings(bindings);
3802    }
3803
3804    /// Apply the bindings from a pattern to the innermost rib of the current scope.
3805    fn apply_pattern_bindings(&mut self, mut pat_bindings: PatternBindings) {
3806        let rib_bindings = self.innermost_rib_bindings(ValueNS);
3807        let Some((_, pat_bindings)) = pat_bindings.pop() else {
3808            bug!("tried applying nonexistent bindings from pattern");
3809        };
3810
3811        if rib_bindings.is_empty() {
3812            // Often, such as for match arms, the bindings are introduced into a new rib.
3813            // In this case, we can move the bindings over directly.
3814            *rib_bindings = pat_bindings;
3815        } else {
3816            rib_bindings.extend(pat_bindings);
3817        }
3818    }
3819
3820    /// Resolve bindings in a pattern. `apply_pattern_bindings` must be called after to introduce
3821    /// the bindings into scope.
3822    fn resolve_pattern(
3823        &mut self,
3824        pat: &'ast Pat,
3825        pat_src: PatternSource,
3826        bindings: &mut PatternBindings,
3827    ) {
3828        // We walk the pattern before declaring the pattern's inner bindings,
3829        // so that we avoid resolving a literal expression to a binding defined
3830        // by the pattern.
3831        // NB: `Self::visit_pat` must be used rather than `visit::walk_pat` to avoid resolving guard
3832        // patterns' guard expressions multiple times (#141265).
3833        self.visit_pat(pat);
3834        self.resolve_pattern_inner(pat, pat_src, bindings);
3835        // This has to happen *after* we determine which pat_idents are variants:
3836        self.check_consistent_bindings(pat);
3837    }
3838
3839    /// Resolve bindings in a pattern. This is a helper to `resolve_pattern`.
3840    ///
3841    /// ### `bindings`
3842    ///
3843    /// A stack of sets of bindings accumulated.
3844    ///
3845    /// In each set, `PatBoundCtx::Product` denotes that a found binding in it should
3846    /// be interpreted as re-binding an already bound binding. This results in an error.
3847    /// Meanwhile, `PatBound::Or` denotes that a found binding in the set should result
3848    /// in reusing this binding rather than creating a fresh one.
3849    ///
3850    /// When called at the top level, the stack must have a single element
3851    /// with `PatBound::Product`. Otherwise, pushing to the stack happens as
3852    /// or-patterns (`p_0 | ... | p_n`) are encountered and the context needs
3853    /// to be switched to `PatBoundCtx::Or` and then `PatBoundCtx::Product` for each `p_i`.
3854    /// When each `p_i` has been dealt with, the top set is merged with its parent.
3855    /// When a whole or-pattern has been dealt with, the thing happens.
3856    ///
3857    /// See the implementation and `fresh_binding` for more details.
3858    #[tracing::instrument(skip(self, bindings), level = "debug")]
3859    fn resolve_pattern_inner(
3860        &mut self,
3861        pat: &'ast Pat,
3862        pat_src: PatternSource,
3863        bindings: &mut PatternBindings,
3864    ) {
3865        // Visit all direct subpatterns of this pattern.
3866        pat.walk(&mut |pat| {
3867            match pat.kind {
3868                PatKind::Ident(bmode, ident, ref sub) => {
3869                    // First try to resolve the identifier as some existing entity,
3870                    // then fall back to a fresh binding.
3871                    let has_sub = sub.is_some();
3872                    let res = self
3873                        .try_resolve_as_non_binding(pat_src, bmode, ident, has_sub)
3874                        .unwrap_or_else(|| self.fresh_binding(ident, pat.id, pat_src, bindings));
3875                    self.r.record_partial_res(pat.id, PartialRes::new(res));
3876                    self.r.record_pat_span(pat.id, pat.span);
3877                }
3878                PatKind::TupleStruct(ref qself, ref path, ref sub_patterns) => {
3879                    self.smart_resolve_path(
3880                        pat.id,
3881                        qself,
3882                        path,
3883                        PathSource::TupleStruct(
3884                            pat.span,
3885                            self.r.arenas.alloc_pattern_spans(sub_patterns.iter().map(|p| p.span)),
3886                        ),
3887                    );
3888                }
3889                PatKind::Path(ref qself, ref path) => {
3890                    self.smart_resolve_path(pat.id, qself, path, PathSource::Pat);
3891                }
3892                PatKind::Struct(ref qself, ref path, ref _fields, ref rest) => {
3893                    self.smart_resolve_path(pat.id, qself, path, PathSource::Struct);
3894                    self.record_patterns_with_skipped_bindings(pat, rest);
3895                }
3896                PatKind::Or(ref ps) => {
3897                    // Add a new set of bindings to the stack. `Or` here records that when a
3898                    // binding already exists in this set, it should not result in an error because
3899                    // `V1(a) | V2(a)` must be allowed and are checked for consistency later.
3900                    bindings.push((PatBoundCtx::Or, Default::default()));
3901                    for p in ps {
3902                        // Now we need to switch back to a product context so that each
3903                        // part of the or-pattern internally rejects already bound names.
3904                        // For example, `V1(a) | V2(a, a)` and `V1(a, a) | V2(a)` are bad.
3905                        bindings.push((PatBoundCtx::Product, Default::default()));
3906                        self.resolve_pattern_inner(p, pat_src, bindings);
3907                        // Move up the non-overlapping bindings to the or-pattern.
3908                        // Existing bindings just get "merged".
3909                        let collected = bindings.pop().unwrap().1;
3910                        bindings.last_mut().unwrap().1.extend(collected);
3911                    }
3912                    // This or-pattern itself can itself be part of a product,
3913                    // e.g. `(V1(a) | V2(a), a)` or `(a, V1(a) | V2(a))`.
3914                    // Both cases bind `a` again in a product pattern and must be rejected.
3915                    let collected = bindings.pop().unwrap().1;
3916                    bindings.last_mut().unwrap().1.extend(collected);
3917
3918                    // Prevent visiting `ps` as we've already done so above.
3919                    return false;
3920                }
3921                PatKind::Guard(ref subpat, ref guard) => {
3922                    // Add a new set of bindings to the stack to collect bindings in `subpat`.
3923                    bindings.push((PatBoundCtx::Product, Default::default()));
3924                    // Resolving `subpat` adds bindings onto the newly-pushed context. After, the
3925                    // total number of contexts on the stack should be the same as before.
3926                    let binding_ctx_stack_len = bindings.len();
3927                    self.resolve_pattern_inner(subpat, pat_src, bindings);
3928                    assert_eq!(bindings.len(), binding_ctx_stack_len);
3929                    // These bindings, but none from the surrounding pattern, are visible in the
3930                    // guard; put them in scope and resolve `guard`.
3931                    let subpat_bindings = bindings.pop().unwrap().1;
3932                    self.with_rib(ValueNS, RibKind::Normal, |this| {
3933                        *this.innermost_rib_bindings(ValueNS) = subpat_bindings.clone();
3934                        this.resolve_expr(guard, None);
3935                    });
3936                    // Propagate the subpattern's bindings upwards.
3937                    // FIXME(guard_patterns): For `if let` guards, we'll also need to get the
3938                    // bindings introduced by the guard from its rib and propagate them upwards.
3939                    // This will require checking the identifiers for overlaps with `bindings`, like
3940                    // what `fresh_binding` does (ideally sharing its logic). To keep them separate
3941                    // from `subpat_bindings`, we can introduce a fresh rib for the guard.
3942                    bindings.last_mut().unwrap().1.extend(subpat_bindings);
3943                    // Prevent visiting `subpat` as we've already done so above.
3944                    return false;
3945                }
3946                _ => {}
3947            }
3948            true
3949        });
3950    }
3951
3952    fn record_patterns_with_skipped_bindings(&mut self, pat: &Pat, rest: &ast::PatFieldsRest) {
3953        match rest {
3954            ast::PatFieldsRest::Rest | ast::PatFieldsRest::Recovered(_) => {
3955                // Record that the pattern doesn't introduce all the bindings it could.
3956                if let Some(partial_res) = self.r.partial_res_map.get(&pat.id)
3957                    && let Some(res) = partial_res.full_res()
3958                    && let Some(def_id) = res.opt_def_id()
3959                {
3960                    self.ribs[ValueNS]
3961                        .last_mut()
3962                        .unwrap()
3963                        .patterns_with_skipped_bindings
3964                        .entry(def_id)
3965                        .or_default()
3966                        .push((
3967                            pat.span,
3968                            match rest {
3969                                ast::PatFieldsRest::Recovered(guar) => Err(*guar),
3970                                _ => Ok(()),
3971                            },
3972                        ));
3973                }
3974            }
3975            ast::PatFieldsRest::None => {}
3976        }
3977    }
3978
3979    fn fresh_binding(
3980        &mut self,
3981        ident: Ident,
3982        pat_id: NodeId,
3983        pat_src: PatternSource,
3984        bindings: &mut PatternBindings,
3985    ) -> Res {
3986        // Add the binding to the bindings map, if it doesn't already exist.
3987        // (We must not add it if it's in the bindings map because that breaks the assumptions
3988        // later passes make about or-patterns.)
3989        let ident = ident.normalize_to_macro_rules();
3990
3991        // Already bound in a product pattern? e.g. `(a, a)` which is not allowed.
3992        let already_bound_and = bindings
3993            .iter()
3994            .any(|(ctx, map)| *ctx == PatBoundCtx::Product && map.contains_key(&ident));
3995        if already_bound_and {
3996            // Overlap in a product pattern somewhere; report an error.
3997            use ResolutionError::*;
3998            let error = match pat_src {
3999                // `fn f(a: u8, a: u8)`:
4000                PatternSource::FnParam => IdentifierBoundMoreThanOnceInParameterList,
4001                // `Variant(a, a)`:
4002                _ => IdentifierBoundMoreThanOnceInSamePattern,
4003            };
4004            self.report_error(ident.span, error(ident));
4005        }
4006
4007        // Already bound in an or-pattern? e.g. `V1(a) | V2(a)`.
4008        // This is *required* for consistency which is checked later.
4009        let already_bound_or = bindings
4010            .iter()
4011            .find_map(|(ctx, map)| if *ctx == PatBoundCtx::Or { map.get(&ident) } else { None });
4012        let res = if let Some(&res) = already_bound_or {
4013            // `Variant1(a) | Variant2(a)`, ok
4014            // Reuse definition from the first `a`.
4015            res
4016        } else {
4017            // A completely fresh binding is added to the map.
4018            Res::Local(pat_id)
4019        };
4020
4021        // Record as bound.
4022        bindings.last_mut().unwrap().1.insert(ident, res);
4023        res
4024    }
4025
4026    fn innermost_rib_bindings(&mut self, ns: Namespace) -> &mut FxIndexMap<Ident, Res> {
4027        &mut self.ribs[ns].last_mut().unwrap().bindings
4028    }
4029
4030    fn try_resolve_as_non_binding(
4031        &mut self,
4032        pat_src: PatternSource,
4033        ann: BindingMode,
4034        ident: Ident,
4035        has_sub: bool,
4036    ) -> Option<Res> {
4037        // An immutable (no `mut`) by-value (no `ref`) binding pattern without
4038        // a sub pattern (no `@ $pat`) is syntactically ambiguous as it could
4039        // also be interpreted as a path to e.g. a constant, variant, etc.
4040        let is_syntactic_ambiguity = !has_sub && ann == BindingMode::NONE;
4041
4042        let ls_binding = self.maybe_resolve_ident_in_lexical_scope(ident, ValueNS)?;
4043        let (res, binding) = match ls_binding {
4044            LexicalScopeBinding::Item(binding)
4045                if is_syntactic_ambiguity && binding.is_ambiguity_recursive() =>
4046            {
4047                // For ambiguous bindings we don't know all their definitions and cannot check
4048                // whether they can be shadowed by fresh bindings or not, so force an error.
4049                // issues/33118#issuecomment-233962221 (see below) still applies here,
4050                // but we have to ignore it for backward compatibility.
4051                self.r.record_use(ident, binding, Used::Other);
4052                return None;
4053            }
4054            LexicalScopeBinding::Item(binding) => (binding.res(), Some(binding)),
4055            LexicalScopeBinding::Res(res) => (res, None),
4056        };
4057
4058        match res {
4059            Res::SelfCtor(_) // See #70549.
4060            | Res::Def(
4061                DefKind::Ctor(_, CtorKind::Const) | DefKind::Const | DefKind::AssocConst | DefKind::ConstParam,
4062                _,
4063            ) if is_syntactic_ambiguity => {
4064                // Disambiguate in favor of a unit struct/variant or constant pattern.
4065                if let Some(binding) = binding {
4066                    self.r.record_use(ident, binding, Used::Other);
4067                }
4068                Some(res)
4069            }
4070            Res::Def(DefKind::Ctor(..) | DefKind::Const | DefKind::AssocConst | DefKind::Static { .. }, _) => {
4071                // This is unambiguously a fresh binding, either syntactically
4072                // (e.g., `IDENT @ PAT` or `ref IDENT`) or because `IDENT` resolves
4073                // to something unusable as a pattern (e.g., constructor function),
4074                // but we still conservatively report an error, see
4075                // issues/33118#issuecomment-233962221 for one reason why.
4076                let binding = binding.expect("no binding for a ctor or static");
4077                self.report_error(
4078                    ident.span,
4079                    ResolutionError::BindingShadowsSomethingUnacceptable {
4080                        shadowing_binding: pat_src,
4081                        name: ident.name,
4082                        participle: if binding.is_import() { "imported" } else { "defined" },
4083                        article: binding.res().article(),
4084                        shadowed_binding: binding.res(),
4085                        shadowed_binding_span: binding.span,
4086                    },
4087                );
4088                None
4089            }
4090            Res::Def(DefKind::ConstParam, def_id) => {
4091                // Same as for DefKind::Const above, but here, `binding` is `None`, so we
4092                // have to construct the error differently
4093                self.report_error(
4094                    ident.span,
4095                    ResolutionError::BindingShadowsSomethingUnacceptable {
4096                        shadowing_binding: pat_src,
4097                        name: ident.name,
4098                        participle: "defined",
4099                        article: res.article(),
4100                        shadowed_binding: res,
4101                        shadowed_binding_span: self.r.def_span(def_id),
4102                    }
4103                );
4104                None
4105            }
4106            Res::Def(DefKind::Fn | DefKind::AssocFn, _) | Res::Local(..) | Res::Err => {
4107                // These entities are explicitly allowed to be shadowed by fresh bindings.
4108                None
4109            }
4110            Res::SelfCtor(_) => {
4111                // We resolve `Self` in pattern position as an ident sometimes during recovery,
4112                // so delay a bug instead of ICEing.
4113                self.r.dcx().span_delayed_bug(
4114                    ident.span,
4115                    "unexpected `SelfCtor` in pattern, expected identifier"
4116                );
4117                None
4118            }
4119            _ => span_bug!(
4120                ident.span,
4121                "unexpected resolution for an identifier in pattern: {:?}",
4122                res,
4123            ),
4124        }
4125    }
4126
4127    // High-level and context dependent path resolution routine.
4128    // Resolves the path and records the resolution into definition map.
4129    // If resolution fails tries several techniques to find likely
4130    // resolution candidates, suggest imports or other help, and report
4131    // errors in user friendly way.
4132    fn smart_resolve_path(
4133        &mut self,
4134        id: NodeId,
4135        qself: &Option<P<QSelf>>,
4136        path: &Path,
4137        source: PathSource<'_, 'ast, '_>,
4138    ) {
4139        self.smart_resolve_path_fragment(
4140            qself,
4141            &Segment::from_path(path),
4142            source,
4143            Finalize::new(id, path.span),
4144            RecordPartialRes::Yes,
4145            None,
4146        );
4147    }
4148
4149    #[instrument(level = "debug", skip(self))]
4150    fn smart_resolve_path_fragment(
4151        &mut self,
4152        qself: &Option<P<QSelf>>,
4153        path: &[Segment],
4154        source: PathSource<'_, 'ast, '_>,
4155        finalize: Finalize,
4156        record_partial_res: RecordPartialRes,
4157        parent_qself: Option<&QSelf>,
4158    ) -> PartialRes {
4159        let ns = source.namespace();
4160
4161        let Finalize { node_id, path_span, .. } = finalize;
4162        let report_errors = |this: &mut Self, res: Option<Res>| {
4163            if this.should_report_errs() {
4164                let (err, candidates) = this.smart_resolve_report_errors(
4165                    path,
4166                    None,
4167                    path_span,
4168                    source,
4169                    res,
4170                    parent_qself,
4171                );
4172
4173                let def_id = this.parent_scope.module.nearest_parent_mod();
4174                let instead = res.is_some();
4175                let suggestion = if let Some((start, end)) = this.diag_metadata.in_range
4176                    && path[0].ident.span.lo() == end.span.lo()
4177                    && !matches!(start.kind, ExprKind::Lit(_))
4178                {
4179                    let mut sugg = ".";
4180                    let mut span = start.span.between(end.span);
4181                    if span.lo() + BytePos(2) == span.hi() {
4182                        // There's no space between the start, the range op and the end, suggest
4183                        // removal which will look better.
4184                        span = span.with_lo(span.lo() + BytePos(1));
4185                        sugg = "";
4186                    }
4187                    Some((
4188                        span,
4189                        "you might have meant to write `.` instead of `..`",
4190                        sugg.to_string(),
4191                        Applicability::MaybeIncorrect,
4192                    ))
4193                } else if res.is_none()
4194                    && let PathSource::Type
4195                    | PathSource::Expr(_)
4196                    | PathSource::PreciseCapturingArg(..) = source
4197                {
4198                    this.suggest_adding_generic_parameter(path, source)
4199                } else {
4200                    None
4201                };
4202
4203                let ue = UseError {
4204                    err,
4205                    candidates,
4206                    def_id,
4207                    instead,
4208                    suggestion,
4209                    path: path.into(),
4210                    is_call: source.is_call(),
4211                };
4212
4213                this.r.use_injections.push(ue);
4214            }
4215
4216            PartialRes::new(Res::Err)
4217        };
4218
4219        // For paths originating from calls (like in `HashMap::new()`), tries
4220        // to enrich the plain `failed to resolve: ...` message with hints
4221        // about possible missing imports.
4222        //
4223        // Similar thing, for types, happens in `report_errors` above.
4224        let report_errors_for_call =
4225            |this: &mut Self, parent_err: Spanned<ResolutionError<'ra>>| {
4226                // Before we start looking for candidates, we have to get our hands
4227                // on the type user is trying to perform invocation on; basically:
4228                // we're transforming `HashMap::new` into just `HashMap`.
4229                let (following_seg, prefix_path) = match path.split_last() {
4230                    Some((last, path)) if !path.is_empty() => (Some(last), path),
4231                    _ => return Some(parent_err),
4232                };
4233
4234                let (mut err, candidates) = this.smart_resolve_report_errors(
4235                    prefix_path,
4236                    following_seg,
4237                    path_span,
4238                    PathSource::Type,
4239                    None,
4240                    parent_qself,
4241                );
4242
4243                // There are two different error messages user might receive at
4244                // this point:
4245                // - E0412 cannot find type `{}` in this scope
4246                // - E0433 failed to resolve: use of undeclared type or module `{}`
4247                //
4248                // The first one is emitted for paths in type-position, and the
4249                // latter one - for paths in expression-position.
4250                //
4251                // Thus (since we're in expression-position at this point), not to
4252                // confuse the user, we want to keep the *message* from E0433 (so
4253                // `parent_err`), but we want *hints* from E0412 (so `err`).
4254                //
4255                // And that's what happens below - we're just mixing both messages
4256                // into a single one.
4257                let mut parent_err = this.r.into_struct_error(parent_err.span, parent_err.node);
4258
4259                // overwrite all properties with the parent's error message
4260                err.messages = take(&mut parent_err.messages);
4261                err.code = take(&mut parent_err.code);
4262                swap(&mut err.span, &mut parent_err.span);
4263                err.children = take(&mut parent_err.children);
4264                err.sort_span = parent_err.sort_span;
4265                err.is_lint = parent_err.is_lint.clone();
4266
4267                // merge the parent_err's suggestions with the typo (err's) suggestions
4268                match &mut err.suggestions {
4269                    Suggestions::Enabled(typo_suggestions) => match &mut parent_err.suggestions {
4270                        Suggestions::Enabled(parent_suggestions) => {
4271                            // If both suggestions are enabled, append parent_err's suggestions to err's suggestions.
4272                            typo_suggestions.append(parent_suggestions)
4273                        }
4274                        Suggestions::Sealed(_) | Suggestions::Disabled => {
4275                            // If the parent's suggestions are either sealed or disabled, it signifies that
4276                            // new suggestions cannot be added or removed from the diagnostic. Therefore,
4277                            // we assign both types of suggestions to err's suggestions and discard the
4278                            // existing suggestions in err.
4279                            err.suggestions = std::mem::take(&mut parent_err.suggestions);
4280                        }
4281                    },
4282                    Suggestions::Sealed(_) | Suggestions::Disabled => (),
4283                }
4284
4285                parent_err.cancel();
4286
4287                let def_id = this.parent_scope.module.nearest_parent_mod();
4288
4289                if this.should_report_errs() {
4290                    if candidates.is_empty() {
4291                        if path.len() == 2
4292                            && let [segment] = prefix_path
4293                        {
4294                            // Delay to check whether methond name is an associated function or not
4295                            // ```
4296                            // let foo = Foo {};
4297                            // foo::bar(); // possibly suggest to foo.bar();
4298                            //```
4299                            err.stash(segment.ident.span, rustc_errors::StashKey::CallAssocMethod);
4300                        } else {
4301                            // When there is no suggested imports, we can just emit the error
4302                            // and suggestions immediately. Note that we bypass the usually error
4303                            // reporting routine (ie via `self.r.report_error`) because we need
4304                            // to post-process the `ResolutionError` above.
4305                            err.emit();
4306                        }
4307                    } else {
4308                        // If there are suggested imports, the error reporting is delayed
4309                        this.r.use_injections.push(UseError {
4310                            err,
4311                            candidates,
4312                            def_id,
4313                            instead: false,
4314                            suggestion: None,
4315                            path: prefix_path.into(),
4316                            is_call: source.is_call(),
4317                        });
4318                    }
4319                } else {
4320                    err.cancel();
4321                }
4322
4323                // We don't return `Some(parent_err)` here, because the error will
4324                // be already printed either immediately or as part of the `use` injections
4325                None
4326            };
4327
4328        let partial_res = match self.resolve_qpath_anywhere(
4329            qself,
4330            path,
4331            ns,
4332            path_span,
4333            source.defer_to_typeck(),
4334            finalize,
4335            source,
4336        ) {
4337            Ok(Some(partial_res)) if let Some(res) = partial_res.full_res() => {
4338                // if we also have an associated type that matches the ident, stash a suggestion
4339                if let Some(items) = self.diag_metadata.current_trait_assoc_items
4340                    && let [Segment { ident, .. }] = path
4341                    && items.iter().any(|item| {
4342                        if let AssocItemKind::Type(alias) = &item.kind
4343                            && alias.ident == *ident
4344                        {
4345                            true
4346                        } else {
4347                            false
4348                        }
4349                    })
4350                {
4351                    let mut diag = self.r.tcx.dcx().struct_allow("");
4352                    diag.span_suggestion_verbose(
4353                        path_span.shrink_to_lo(),
4354                        "there is an associated type with the same name",
4355                        "Self::",
4356                        Applicability::MaybeIncorrect,
4357                    );
4358                    diag.stash(path_span, StashKey::AssociatedTypeSuggestion);
4359                }
4360
4361                if source.is_expected(res) || res == Res::Err {
4362                    partial_res
4363                } else {
4364                    report_errors(self, Some(res))
4365                }
4366            }
4367
4368            Ok(Some(partial_res)) if source.defer_to_typeck() => {
4369                // Not fully resolved associated item `T::A::B` or `<T as Tr>::A::B`
4370                // or `<T>::A::B`. If `B` should be resolved in value namespace then
4371                // it needs to be added to the trait map.
4372                if ns == ValueNS {
4373                    let item_name = path.last().unwrap().ident;
4374                    let traits = self.traits_in_scope(item_name, ns);
4375                    self.r.trait_map.insert(node_id, traits);
4376                }
4377
4378                if PrimTy::from_name(path[0].ident.name).is_some() {
4379                    let mut std_path = Vec::with_capacity(1 + path.len());
4380
4381                    std_path.push(Segment::from_ident(Ident::with_dummy_span(sym::std)));
4382                    std_path.extend(path);
4383                    if let PathResult::Module(_) | PathResult::NonModule(_) =
4384                        self.resolve_path(&std_path, Some(ns), None)
4385                    {
4386                        // Check if we wrote `str::from_utf8` instead of `std::str::from_utf8`
4387                        let item_span =
4388                            path.iter().last().map_or(path_span, |segment| segment.ident.span);
4389
4390                        self.r.confused_type_with_std_module.insert(item_span, path_span);
4391                        self.r.confused_type_with_std_module.insert(path_span, path_span);
4392                    }
4393                }
4394
4395                partial_res
4396            }
4397
4398            Err(err) => {
4399                if let Some(err) = report_errors_for_call(self, err) {
4400                    self.report_error(err.span, err.node);
4401                }
4402
4403                PartialRes::new(Res::Err)
4404            }
4405
4406            _ => report_errors(self, None),
4407        };
4408
4409        if record_partial_res == RecordPartialRes::Yes {
4410            // Avoid recording definition of `A::B` in `<T as A>::B::C`.
4411            self.r.record_partial_res(node_id, partial_res);
4412            self.resolve_elided_lifetimes_in_path(partial_res, path, source, path_span);
4413            self.lint_unused_qualifications(path, ns, finalize);
4414        }
4415
4416        partial_res
4417    }
4418
4419    fn self_type_is_available(&mut self) -> bool {
4420        let binding = self
4421            .maybe_resolve_ident_in_lexical_scope(Ident::with_dummy_span(kw::SelfUpper), TypeNS);
4422        if let Some(LexicalScopeBinding::Res(res)) = binding { res != Res::Err } else { false }
4423    }
4424
4425    fn self_value_is_available(&mut self, self_span: Span) -> bool {
4426        let ident = Ident::new(kw::SelfLower, self_span);
4427        let binding = self.maybe_resolve_ident_in_lexical_scope(ident, ValueNS);
4428        if let Some(LexicalScopeBinding::Res(res)) = binding { res != Res::Err } else { false }
4429    }
4430
4431    /// A wrapper around [`Resolver::report_error`].
4432    ///
4433    /// This doesn't emit errors for function bodies if this is rustdoc.
4434    fn report_error(&mut self, span: Span, resolution_error: ResolutionError<'ra>) {
4435        if self.should_report_errs() {
4436            self.r.report_error(span, resolution_error);
4437        }
4438    }
4439
4440    #[inline]
4441    /// If we're actually rustdoc then avoid giving a name resolution error for `cfg()` items or
4442    // an invalid `use foo::*;` was found, which can cause unbounded amounts of "item not found"
4443    // errors. We silence them all.
4444    fn should_report_errs(&self) -> bool {
4445        !(self.r.tcx.sess.opts.actually_rustdoc && self.in_func_body)
4446            && !self.r.glob_error.is_some()
4447    }
4448
4449    // Resolve in alternative namespaces if resolution in the primary namespace fails.
4450    fn resolve_qpath_anywhere(
4451        &mut self,
4452        qself: &Option<P<QSelf>>,
4453        path: &[Segment],
4454        primary_ns: Namespace,
4455        span: Span,
4456        defer_to_typeck: bool,
4457        finalize: Finalize,
4458        source: PathSource<'_, 'ast, '_>,
4459    ) -> Result<Option<PartialRes>, Spanned<ResolutionError<'ra>>> {
4460        let mut fin_res = None;
4461
4462        for (i, &ns) in [primary_ns, TypeNS, ValueNS].iter().enumerate() {
4463            if i == 0 || ns != primary_ns {
4464                match self.resolve_qpath(qself, path, ns, finalize, source)? {
4465                    Some(partial_res)
4466                        if partial_res.unresolved_segments() == 0 || defer_to_typeck =>
4467                    {
4468                        return Ok(Some(partial_res));
4469                    }
4470                    partial_res => {
4471                        if fin_res.is_none() {
4472                            fin_res = partial_res;
4473                        }
4474                    }
4475                }
4476            }
4477        }
4478
4479        assert!(primary_ns != MacroNS);
4480
4481        if qself.is_none() {
4482            let path_seg = |seg: &Segment| PathSegment::from_ident(seg.ident);
4483            let path = Path { segments: path.iter().map(path_seg).collect(), span, tokens: None };
4484            if let Ok((_, res)) =
4485                self.r.resolve_macro_path(&path, None, &self.parent_scope, false, false, None, None)
4486            {
4487                return Ok(Some(PartialRes::new(res)));
4488            }
4489        }
4490
4491        Ok(fin_res)
4492    }
4493
4494    /// Handles paths that may refer to associated items.
4495    fn resolve_qpath(
4496        &mut self,
4497        qself: &Option<P<QSelf>>,
4498        path: &[Segment],
4499        ns: Namespace,
4500        finalize: Finalize,
4501        source: PathSource<'_, 'ast, '_>,
4502    ) -> Result<Option<PartialRes>, Spanned<ResolutionError<'ra>>> {
4503        debug!(
4504            "resolve_qpath(qself={:?}, path={:?}, ns={:?}, finalize={:?})",
4505            qself, path, ns, finalize,
4506        );
4507
4508        if let Some(qself) = qself {
4509            if qself.position == 0 {
4510                // This is a case like `<T>::B`, where there is no
4511                // trait to resolve. In that case, we leave the `B`
4512                // segment to be resolved by type-check.
4513                return Ok(Some(PartialRes::with_unresolved_segments(
4514                    Res::Def(DefKind::Mod, CRATE_DEF_ID.to_def_id()),
4515                    path.len(),
4516                )));
4517            }
4518
4519            let num_privacy_errors = self.r.privacy_errors.len();
4520            // Make sure that `A` in `<T as A>::B::C` is a trait.
4521            let trait_res = self.smart_resolve_path_fragment(
4522                &None,
4523                &path[..qself.position],
4524                PathSource::Trait(AliasPossibility::No),
4525                Finalize::new(finalize.node_id, qself.path_span),
4526                RecordPartialRes::No,
4527                Some(&qself),
4528            );
4529
4530            if trait_res.expect_full_res() == Res::Err {
4531                return Ok(Some(trait_res));
4532            }
4533
4534            // Truncate additional privacy errors reported above,
4535            // because they'll be recomputed below.
4536            self.r.privacy_errors.truncate(num_privacy_errors);
4537
4538            // Make sure `A::B` in `<T as A>::B::C` is a trait item.
4539            //
4540            // Currently, `path` names the full item (`A::B::C`, in
4541            // our example). so we extract the prefix of that that is
4542            // the trait (the slice upto and including
4543            // `qself.position`). And then we recursively resolve that,
4544            // but with `qself` set to `None`.
4545            let ns = if qself.position + 1 == path.len() { ns } else { TypeNS };
4546            let partial_res = self.smart_resolve_path_fragment(
4547                &None,
4548                &path[..=qself.position],
4549                PathSource::TraitItem(ns, &source),
4550                Finalize::with_root_span(finalize.node_id, finalize.path_span, qself.path_span),
4551                RecordPartialRes::No,
4552                Some(&qself),
4553            );
4554
4555            // The remaining segments (the `C` in our example) will
4556            // have to be resolved by type-check, since that requires doing
4557            // trait resolution.
4558            return Ok(Some(PartialRes::with_unresolved_segments(
4559                partial_res.base_res(),
4560                partial_res.unresolved_segments() + path.len() - qself.position - 1,
4561            )));
4562        }
4563
4564        let result = match self.resolve_path(path, Some(ns), Some(finalize)) {
4565            PathResult::NonModule(path_res) => path_res,
4566            PathResult::Module(ModuleOrUniformRoot::Module(module)) if !module.is_normal() => {
4567                PartialRes::new(module.res().unwrap())
4568            }
4569            // A part of this path references a `mod` that had a parse error. To avoid resolution
4570            // errors for each reference to that module, we don't emit an error for them until the
4571            // `mod` is fixed. this can have a significant cascade effect.
4572            PathResult::Failed { error_implied_by_parse_error: true, .. } => {
4573                PartialRes::new(Res::Err)
4574            }
4575            // In `a(::assoc_item)*` `a` cannot be a module. If `a` does resolve to a module we
4576            // don't report an error right away, but try to fallback to a primitive type.
4577            // So, we are still able to successfully resolve something like
4578            //
4579            // use std::u8; // bring module u8 in scope
4580            // fn f() -> u8 { // OK, resolves to primitive u8, not to std::u8
4581            //     u8::max_value() // OK, resolves to associated function <u8>::max_value,
4582            //                     // not to nonexistent std::u8::max_value
4583            // }
4584            //
4585            // Such behavior is required for backward compatibility.
4586            // The same fallback is used when `a` resolves to nothing.
4587            PathResult::Module(ModuleOrUniformRoot::Module(_)) | PathResult::Failed { .. }
4588                if (ns == TypeNS || path.len() > 1)
4589                    && PrimTy::from_name(path[0].ident.name).is_some() =>
4590            {
4591                let prim = PrimTy::from_name(path[0].ident.name).unwrap();
4592                let tcx = self.r.tcx();
4593
4594                let gate_err_sym_msg = match prim {
4595                    PrimTy::Float(FloatTy::F16) if !tcx.features().f16() => {
4596                        Some((sym::f16, "the type `f16` is unstable"))
4597                    }
4598                    PrimTy::Float(FloatTy::F128) if !tcx.features().f128() => {
4599                        Some((sym::f128, "the type `f128` is unstable"))
4600                    }
4601                    _ => None,
4602                };
4603
4604                if let Some((sym, msg)) = gate_err_sym_msg {
4605                    let span = path[0].ident.span;
4606                    if !span.allows_unstable(sym) {
4607                        feature_err(tcx.sess, sym, span, msg).emit();
4608                    }
4609                };
4610
4611                // Fix up partial res of segment from `resolve_path` call.
4612                if let Some(id) = path[0].id {
4613                    self.r.partial_res_map.insert(id, PartialRes::new(Res::PrimTy(prim)));
4614                }
4615
4616                PartialRes::with_unresolved_segments(Res::PrimTy(prim), path.len() - 1)
4617            }
4618            PathResult::Module(ModuleOrUniformRoot::Module(module)) => {
4619                PartialRes::new(module.res().unwrap())
4620            }
4621            PathResult::Failed {
4622                is_error_from_last_segment: false,
4623                span,
4624                label,
4625                suggestion,
4626                module,
4627                segment_name,
4628                error_implied_by_parse_error: _,
4629            } => {
4630                return Err(respan(
4631                    span,
4632                    ResolutionError::FailedToResolve {
4633                        segment: Some(segment_name),
4634                        label,
4635                        suggestion,
4636                        module,
4637                    },
4638                ));
4639            }
4640            PathResult::Module(..) | PathResult::Failed { .. } => return Ok(None),
4641            PathResult::Indeterminate => bug!("indeterminate path result in resolve_qpath"),
4642        };
4643
4644        Ok(Some(result))
4645    }
4646
4647    fn with_resolved_label(&mut self, label: Option<Label>, id: NodeId, f: impl FnOnce(&mut Self)) {
4648        if let Some(label) = label {
4649            if label.ident.as_str().as_bytes()[1] != b'_' {
4650                self.diag_metadata.unused_labels.insert(id, label.ident.span);
4651            }
4652
4653            if let Ok((_, orig_span)) = self.resolve_label(label.ident) {
4654                diagnostics::signal_label_shadowing(self.r.tcx.sess, orig_span, label.ident)
4655            }
4656
4657            self.with_label_rib(RibKind::Normal, |this| {
4658                let ident = label.ident.normalize_to_macro_rules();
4659                this.label_ribs.last_mut().unwrap().bindings.insert(ident, id);
4660                f(this);
4661            });
4662        } else {
4663            f(self);
4664        }
4665    }
4666
4667    fn resolve_labeled_block(&mut self, label: Option<Label>, id: NodeId, block: &'ast Block) {
4668        self.with_resolved_label(label, id, |this| this.visit_block(block));
4669    }
4670
4671    fn resolve_block(&mut self, block: &'ast Block) {
4672        debug!("(resolving block) entering block");
4673        // Move down in the graph, if there's an anonymous module rooted here.
4674        let orig_module = self.parent_scope.module;
4675        let anonymous_module = self.r.block_map.get(&block.id).cloned(); // clones a reference
4676
4677        let mut num_macro_definition_ribs = 0;
4678        if let Some(anonymous_module) = anonymous_module {
4679            debug!("(resolving block) found anonymous module, moving down");
4680            self.ribs[ValueNS].push(Rib::new(RibKind::Module(anonymous_module)));
4681            self.ribs[TypeNS].push(Rib::new(RibKind::Module(anonymous_module)));
4682            self.parent_scope.module = anonymous_module;
4683        } else {
4684            self.ribs[ValueNS].push(Rib::new(RibKind::Normal));
4685        }
4686
4687        // Descend into the block.
4688        for stmt in &block.stmts {
4689            if let StmtKind::Item(ref item) = stmt.kind
4690                && let ItemKind::MacroDef(..) = item.kind
4691            {
4692                num_macro_definition_ribs += 1;
4693                let res = self.r.local_def_id(item.id).to_def_id();
4694                self.ribs[ValueNS].push(Rib::new(RibKind::MacroDefinition(res)));
4695                self.label_ribs.push(Rib::new(RibKind::MacroDefinition(res)));
4696            }
4697
4698            self.visit_stmt(stmt);
4699        }
4700
4701        // Move back up.
4702        self.parent_scope.module = orig_module;
4703        for _ in 0..num_macro_definition_ribs {
4704            self.ribs[ValueNS].pop();
4705            self.label_ribs.pop();
4706        }
4707        self.last_block_rib = self.ribs[ValueNS].pop();
4708        if anonymous_module.is_some() {
4709            self.ribs[TypeNS].pop();
4710        }
4711        debug!("(resolving block) leaving block");
4712    }
4713
4714    fn resolve_anon_const(&mut self, constant: &'ast AnonConst, anon_const_kind: AnonConstKind) {
4715        debug!(
4716            "resolve_anon_const(constant: {:?}, anon_const_kind: {:?})",
4717            constant, anon_const_kind
4718        );
4719
4720        let is_trivial_const_arg = constant
4721            .value
4722            .is_potential_trivial_const_arg(self.r.tcx.features().min_generic_const_args());
4723        self.resolve_anon_const_manual(is_trivial_const_arg, anon_const_kind, |this| {
4724            this.resolve_expr(&constant.value, None)
4725        })
4726    }
4727
4728    /// There are a few places that we need to resolve an anon const but we did not parse an
4729    /// anon const so cannot provide an `&'ast AnonConst`. Right now this is just unbraced
4730    /// const arguments that were parsed as type arguments, and `legacy_const_generics` which
4731    /// parse as normal function argument expressions. To avoid duplicating the code for resolving
4732    /// an anon const we have this function which lets the caller manually call `resolve_expr` or
4733    /// `smart_resolve_path`.
4734    fn resolve_anon_const_manual(
4735        &mut self,
4736        is_trivial_const_arg: bool,
4737        anon_const_kind: AnonConstKind,
4738        resolve_expr: impl FnOnce(&mut Self),
4739    ) {
4740        let is_repeat_expr = match anon_const_kind {
4741            AnonConstKind::ConstArg(is_repeat_expr) => is_repeat_expr,
4742            _ => IsRepeatExpr::No,
4743        };
4744
4745        let may_use_generics = match anon_const_kind {
4746            AnonConstKind::EnumDiscriminant => {
4747                ConstantHasGenerics::No(NoConstantGenericsReason::IsEnumDiscriminant)
4748            }
4749            AnonConstKind::FieldDefaultValue => ConstantHasGenerics::Yes,
4750            AnonConstKind::InlineConst => ConstantHasGenerics::Yes,
4751            AnonConstKind::ConstArg(_) => {
4752                if self.r.tcx.features().generic_const_exprs() || is_trivial_const_arg {
4753                    ConstantHasGenerics::Yes
4754                } else {
4755                    ConstantHasGenerics::No(NoConstantGenericsReason::NonTrivialConstArg)
4756                }
4757            }
4758        };
4759
4760        self.with_constant_rib(is_repeat_expr, may_use_generics, None, |this| {
4761            this.with_lifetime_rib(LifetimeRibKind::Elided(LifetimeRes::Infer), |this| {
4762                resolve_expr(this);
4763            });
4764        });
4765    }
4766
4767    fn resolve_expr_field(&mut self, f: &'ast ExprField, e: &'ast Expr) {
4768        self.resolve_expr(&f.expr, Some(e));
4769        self.visit_ident(&f.ident);
4770        walk_list!(self, visit_attribute, f.attrs.iter());
4771    }
4772
4773    fn resolve_expr(&mut self, expr: &'ast Expr, parent: Option<&'ast Expr>) {
4774        // First, record candidate traits for this expression if it could
4775        // result in the invocation of a method call.
4776
4777        self.record_candidate_traits_for_expr_if_necessary(expr);
4778
4779        // Next, resolve the node.
4780        match expr.kind {
4781            ExprKind::Path(ref qself, ref path) => {
4782                self.smart_resolve_path(expr.id, qself, path, PathSource::Expr(parent));
4783                visit::walk_expr(self, expr);
4784            }
4785
4786            ExprKind::Struct(ref se) => {
4787                self.smart_resolve_path(expr.id, &se.qself, &se.path, PathSource::Struct);
4788                // This is the same as `visit::walk_expr(self, expr);`, but we want to pass the
4789                // parent in for accurate suggestions when encountering `Foo { bar }` that should
4790                // have been `Foo { bar: self.bar }`.
4791                if let Some(qself) = &se.qself {
4792                    self.visit_ty(&qself.ty);
4793                }
4794                self.visit_path(&se.path);
4795                walk_list!(self, resolve_expr_field, &se.fields, expr);
4796                match &se.rest {
4797                    StructRest::Base(expr) => self.visit_expr(expr),
4798                    StructRest::Rest(_span) => {}
4799                    StructRest::None => {}
4800                }
4801            }
4802
4803            ExprKind::Break(Some(label), _) | ExprKind::Continue(Some(label)) => {
4804                match self.resolve_label(label.ident) {
4805                    Ok((node_id, _)) => {
4806                        // Since this res is a label, it is never read.
4807                        self.r.label_res_map.insert(expr.id, node_id);
4808                        self.diag_metadata.unused_labels.swap_remove(&node_id);
4809                    }
4810                    Err(error) => {
4811                        self.report_error(label.ident.span, error);
4812                    }
4813                }
4814
4815                // visit `break` argument if any
4816                visit::walk_expr(self, expr);
4817            }
4818
4819            ExprKind::Break(None, Some(ref e)) => {
4820                // We use this instead of `visit::walk_expr` to keep the parent expr around for
4821                // better diagnostics.
4822                self.resolve_expr(e, Some(expr));
4823            }
4824
4825            ExprKind::Let(ref pat, ref scrutinee, _, Recovered::No) => {
4826                self.visit_expr(scrutinee);
4827                self.resolve_pattern_top(pat, PatternSource::Let);
4828            }
4829
4830            ExprKind::Let(ref pat, ref scrutinee, _, Recovered::Yes(_)) => {
4831                self.visit_expr(scrutinee);
4832                // This is basically a tweaked, inlined `resolve_pattern_top`.
4833                let mut bindings = smallvec![(PatBoundCtx::Product, Default::default())];
4834                self.resolve_pattern(pat, PatternSource::Let, &mut bindings);
4835                // We still collect the bindings in this `let` expression which is in
4836                // an invalid position (and therefore shouldn't declare variables into
4837                // its parent scope). To avoid unnecessary errors though, we do just
4838                // reassign the resolutions to `Res::Err`.
4839                for (_, bindings) in &mut bindings {
4840                    for (_, binding) in bindings {
4841                        *binding = Res::Err;
4842                    }
4843                }
4844                self.apply_pattern_bindings(bindings);
4845            }
4846
4847            ExprKind::If(ref cond, ref then, ref opt_else) => {
4848                self.with_rib(ValueNS, RibKind::Normal, |this| {
4849                    let old = this.diag_metadata.in_if_condition.replace(cond);
4850                    this.visit_expr(cond);
4851                    this.diag_metadata.in_if_condition = old;
4852                    this.visit_block(then);
4853                });
4854                if let Some(expr) = opt_else {
4855                    self.visit_expr(expr);
4856                }
4857            }
4858
4859            ExprKind::Loop(ref block, label, _) => {
4860                self.resolve_labeled_block(label, expr.id, block)
4861            }
4862
4863            ExprKind::While(ref cond, ref block, label) => {
4864                self.with_resolved_label(label, expr.id, |this| {
4865                    this.with_rib(ValueNS, RibKind::Normal, |this| {
4866                        let old = this.diag_metadata.in_if_condition.replace(cond);
4867                        this.visit_expr(cond);
4868                        this.diag_metadata.in_if_condition = old;
4869                        this.visit_block(block);
4870                    })
4871                });
4872            }
4873
4874            ExprKind::ForLoop { ref pat, ref iter, ref body, label, kind: _ } => {
4875                self.visit_expr(iter);
4876                self.with_rib(ValueNS, RibKind::Normal, |this| {
4877                    this.resolve_pattern_top(pat, PatternSource::For);
4878                    this.resolve_labeled_block(label, expr.id, body);
4879                });
4880            }
4881
4882            ExprKind::Block(ref block, label) => self.resolve_labeled_block(label, block.id, block),
4883
4884            // Equivalent to `visit::walk_expr` + passing some context to children.
4885            ExprKind::Field(ref subexpression, _) => {
4886                self.resolve_expr(subexpression, Some(expr));
4887            }
4888            ExprKind::MethodCall(box MethodCall { ref seg, ref receiver, ref args, .. }) => {
4889                self.resolve_expr(receiver, Some(expr));
4890                for arg in args {
4891                    self.resolve_expr(arg, None);
4892                }
4893                self.visit_path_segment(seg);
4894            }
4895
4896            ExprKind::Call(ref callee, ref arguments) => {
4897                self.resolve_expr(callee, Some(expr));
4898                let const_args = self.r.legacy_const_generic_args(callee).unwrap_or_default();
4899                for (idx, argument) in arguments.iter().enumerate() {
4900                    // Constant arguments need to be treated as AnonConst since
4901                    // that is how they will be later lowered to HIR.
4902                    if const_args.contains(&idx) {
4903                        let is_trivial_const_arg = argument.is_potential_trivial_const_arg(
4904                            self.r.tcx.features().min_generic_const_args(),
4905                        );
4906                        self.resolve_anon_const_manual(
4907                            is_trivial_const_arg,
4908                            AnonConstKind::ConstArg(IsRepeatExpr::No),
4909                            |this| this.resolve_expr(argument, None),
4910                        );
4911                    } else {
4912                        self.resolve_expr(argument, None);
4913                    }
4914                }
4915            }
4916            ExprKind::Type(ref _type_expr, ref _ty) => {
4917                visit::walk_expr(self, expr);
4918            }
4919            // For closures, RibKind::FnOrCoroutine is added in visit_fn
4920            ExprKind::Closure(box ast::Closure {
4921                binder: ClosureBinder::For { ref generic_params, span },
4922                ..
4923            }) => {
4924                self.with_generic_param_rib(
4925                    generic_params,
4926                    RibKind::Normal,
4927                    expr.id,
4928                    LifetimeBinderKind::Closure,
4929                    span,
4930                    |this| visit::walk_expr(this, expr),
4931                );
4932            }
4933            ExprKind::Closure(..) => visit::walk_expr(self, expr),
4934            ExprKind::Gen(..) => {
4935                self.with_label_rib(RibKind::FnOrCoroutine, |this| visit::walk_expr(this, expr));
4936            }
4937            ExprKind::Repeat(ref elem, ref ct) => {
4938                self.visit_expr(elem);
4939                self.resolve_anon_const(ct, AnonConstKind::ConstArg(IsRepeatExpr::Yes));
4940            }
4941            ExprKind::ConstBlock(ref ct) => {
4942                self.resolve_anon_const(ct, AnonConstKind::InlineConst);
4943            }
4944            ExprKind::Index(ref elem, ref idx, _) => {
4945                self.resolve_expr(elem, Some(expr));
4946                self.visit_expr(idx);
4947            }
4948            ExprKind::Assign(ref lhs, ref rhs, _) => {
4949                if !self.diag_metadata.is_assign_rhs {
4950                    self.diag_metadata.in_assignment = Some(expr);
4951                }
4952                self.visit_expr(lhs);
4953                self.diag_metadata.is_assign_rhs = true;
4954                self.diag_metadata.in_assignment = None;
4955                self.visit_expr(rhs);
4956                self.diag_metadata.is_assign_rhs = false;
4957            }
4958            ExprKind::Range(Some(ref start), Some(ref end), RangeLimits::HalfOpen) => {
4959                self.diag_metadata.in_range = Some((start, end));
4960                self.resolve_expr(start, Some(expr));
4961                self.resolve_expr(end, Some(expr));
4962                self.diag_metadata.in_range = None;
4963            }
4964            _ => {
4965                visit::walk_expr(self, expr);
4966            }
4967        }
4968    }
4969
4970    fn record_candidate_traits_for_expr_if_necessary(&mut self, expr: &'ast Expr) {
4971        match expr.kind {
4972            ExprKind::Field(_, ident) => {
4973                // #6890: Even though you can't treat a method like a field,
4974                // we need to add any trait methods we find that match the
4975                // field name so that we can do some nice error reporting
4976                // later on in typeck.
4977                let traits = self.traits_in_scope(ident, ValueNS);
4978                self.r.trait_map.insert(expr.id, traits);
4979            }
4980            ExprKind::MethodCall(ref call) => {
4981                debug!("(recording candidate traits for expr) recording traits for {}", expr.id);
4982                let traits = self.traits_in_scope(call.seg.ident, ValueNS);
4983                self.r.trait_map.insert(expr.id, traits);
4984            }
4985            _ => {
4986                // Nothing to do.
4987            }
4988        }
4989    }
4990
4991    fn traits_in_scope(&mut self, ident: Ident, ns: Namespace) -> Vec<TraitCandidate> {
4992        self.r.traits_in_scope(
4993            self.current_trait_ref.as_ref().map(|(module, _)| *module),
4994            &self.parent_scope,
4995            ident.span.ctxt(),
4996            Some((ident.name, ns)),
4997        )
4998    }
4999
5000    fn resolve_and_cache_rustdoc_path(&mut self, path_str: &str, ns: Namespace) -> Option<Res> {
5001        // FIXME: This caching may be incorrect in case of multiple `macro_rules`
5002        // items with the same name in the same module.
5003        // Also hygiene is not considered.
5004        let mut doc_link_resolutions = std::mem::take(&mut self.r.doc_link_resolutions);
5005        let res = *doc_link_resolutions
5006            .entry(self.parent_scope.module.nearest_parent_mod().expect_local())
5007            .or_default()
5008            .entry((Symbol::intern(path_str), ns))
5009            .or_insert_with_key(|(path, ns)| {
5010                let res = self.r.resolve_rustdoc_path(path.as_str(), *ns, self.parent_scope);
5011                if let Some(res) = res
5012                    && let Some(def_id) = res.opt_def_id()
5013                    && self.is_invalid_proc_macro_item_for_doc(def_id)
5014                {
5015                    // Encoding def ids in proc macro crate metadata will ICE,
5016                    // because it will only store proc macros for it.
5017                    return None;
5018                }
5019                res
5020            });
5021        self.r.doc_link_resolutions = doc_link_resolutions;
5022        res
5023    }
5024
5025    fn is_invalid_proc_macro_item_for_doc(&self, did: DefId) -> bool {
5026        if !matches!(self.r.tcx.sess.opts.resolve_doc_links, ResolveDocLinks::ExportedMetadata)
5027            || !self.r.tcx.crate_types().contains(&CrateType::ProcMacro)
5028        {
5029            return false;
5030        }
5031        let Some(local_did) = did.as_local() else { return true };
5032        !self.r.proc_macros.contains(&local_did)
5033    }
5034
5035    fn resolve_doc_links(&mut self, attrs: &[Attribute], maybe_exported: MaybeExported<'_>) {
5036        match self.r.tcx.sess.opts.resolve_doc_links {
5037            ResolveDocLinks::None => return,
5038            ResolveDocLinks::ExportedMetadata
5039                if !self.r.tcx.crate_types().iter().copied().any(CrateType::has_metadata)
5040                    || !maybe_exported.eval(self.r) =>
5041            {
5042                return;
5043            }
5044            ResolveDocLinks::Exported
5045                if !maybe_exported.eval(self.r)
5046                    && !rustdoc::has_primitive_or_keyword_docs(attrs) =>
5047            {
5048                return;
5049            }
5050            ResolveDocLinks::ExportedMetadata
5051            | ResolveDocLinks::Exported
5052            | ResolveDocLinks::All => {}
5053        }
5054
5055        if !attrs.iter().any(|attr| attr.may_have_doc_links()) {
5056            return;
5057        }
5058
5059        let mut need_traits_in_scope = false;
5060        for path_str in rustdoc::attrs_to_preprocessed_links(attrs) {
5061            // Resolve all namespaces due to no disambiguator or for diagnostics.
5062            let mut any_resolved = false;
5063            let mut need_assoc = false;
5064            for ns in [TypeNS, ValueNS, MacroNS] {
5065                if let Some(res) = self.resolve_and_cache_rustdoc_path(&path_str, ns) {
5066                    // Rustdoc ignores tool attribute resolutions and attempts
5067                    // to resolve their prefixes for diagnostics.
5068                    any_resolved = !matches!(res, Res::NonMacroAttr(NonMacroAttrKind::Tool));
5069                } else if ns != MacroNS {
5070                    need_assoc = true;
5071                }
5072            }
5073
5074            // Resolve all prefixes for type-relative resolution or for diagnostics.
5075            if need_assoc || !any_resolved {
5076                let mut path = &path_str[..];
5077                while let Some(idx) = path.rfind("::") {
5078                    path = &path[..idx];
5079                    need_traits_in_scope = true;
5080                    for ns in [TypeNS, ValueNS, MacroNS] {
5081                        self.resolve_and_cache_rustdoc_path(path, ns);
5082                    }
5083                }
5084            }
5085        }
5086
5087        if need_traits_in_scope {
5088            // FIXME: hygiene is not considered.
5089            let mut doc_link_traits_in_scope = std::mem::take(&mut self.r.doc_link_traits_in_scope);
5090            doc_link_traits_in_scope
5091                .entry(self.parent_scope.module.nearest_parent_mod().expect_local())
5092                .or_insert_with(|| {
5093                    self.r
5094                        .traits_in_scope(None, &self.parent_scope, SyntaxContext::root(), None)
5095                        .into_iter()
5096                        .filter_map(|tr| {
5097                            if self.is_invalid_proc_macro_item_for_doc(tr.def_id) {
5098                                // Encoding def ids in proc macro crate metadata will ICE.
5099                                // because it will only store proc macros for it.
5100                                return None;
5101                            }
5102                            Some(tr.def_id)
5103                        })
5104                        .collect()
5105                });
5106            self.r.doc_link_traits_in_scope = doc_link_traits_in_scope;
5107        }
5108    }
5109
5110    fn lint_unused_qualifications(&mut self, path: &[Segment], ns: Namespace, finalize: Finalize) {
5111        // Don't lint on global paths because the user explicitly wrote out the full path.
5112        if let Some(seg) = path.first()
5113            && seg.ident.name == kw::PathRoot
5114        {
5115            return;
5116        }
5117
5118        if finalize.path_span.from_expansion()
5119            || path.iter().any(|seg| seg.ident.span.from_expansion())
5120        {
5121            return;
5122        }
5123
5124        let end_pos =
5125            path.iter().position(|seg| seg.has_generic_args).map_or(path.len(), |pos| pos + 1);
5126        let unqualified = path[..end_pos].iter().enumerate().skip(1).rev().find_map(|(i, seg)| {
5127            // Preserve the current namespace for the final path segment, but use the type
5128            // namespace for all preceding segments
5129            //
5130            // e.g. for `std::env::args` check the `ValueNS` for `args` but the `TypeNS` for
5131            // `std` and `env`
5132            //
5133            // If the final path segment is beyond `end_pos` all the segments to check will
5134            // use the type namespace
5135            let ns = if i + 1 == path.len() { ns } else { TypeNS };
5136            let res = self.r.partial_res_map.get(&seg.id?)?.full_res()?;
5137            let binding = self.resolve_ident_in_lexical_scope(seg.ident, ns, None, None)?;
5138            (res == binding.res()).then_some((seg, binding))
5139        });
5140
5141        if let Some((seg, binding)) = unqualified {
5142            self.r.potentially_unnecessary_qualifications.push(UnnecessaryQualification {
5143                binding,
5144                node_id: finalize.node_id,
5145                path_span: finalize.path_span,
5146                removal_span: path[0].ident.span.until(seg.ident.span),
5147            });
5148        }
5149    }
5150
5151    fn resolve_define_opaques(&mut self, define_opaque: &Option<ThinVec<(NodeId, Path)>>) {
5152        if let Some(define_opaque) = define_opaque {
5153            for (id, path) in define_opaque {
5154                self.smart_resolve_path(*id, &None, path, PathSource::DefineOpaques);
5155            }
5156        }
5157    }
5158}
5159
5160/// Walks the whole crate in DFS order, visiting each item, counting the declared number of
5161/// lifetime generic parameters and function parameters.
5162struct ItemInfoCollector<'a, 'ra, 'tcx> {
5163    r: &'a mut Resolver<'ra, 'tcx>,
5164}
5165
5166impl ItemInfoCollector<'_, '_, '_> {
5167    fn collect_fn_info(
5168        &mut self,
5169        header: FnHeader,
5170        decl: &FnDecl,
5171        id: NodeId,
5172        attrs: &[Attribute],
5173    ) {
5174        let sig = DelegationFnSig {
5175            header,
5176            param_count: decl.inputs.len(),
5177            has_self: decl.has_self(),
5178            c_variadic: decl.c_variadic(),
5179            target_feature: attrs.iter().any(|attr| attr.has_name(sym::target_feature)),
5180        };
5181        self.r.delegation_fn_sigs.insert(self.r.local_def_id(id), sig);
5182    }
5183}
5184
5185impl<'ast> Visitor<'ast> for ItemInfoCollector<'_, '_, '_> {
5186    fn visit_item(&mut self, item: &'ast Item) {
5187        match &item.kind {
5188            ItemKind::TyAlias(box TyAlias { generics, .. })
5189            | ItemKind::Const(box ConstItem { generics, .. })
5190            | ItemKind::Fn(box Fn { generics, .. })
5191            | ItemKind::Enum(_, generics, _)
5192            | ItemKind::Struct(_, generics, _)
5193            | ItemKind::Union(_, generics, _)
5194            | ItemKind::Impl(box Impl { generics, .. })
5195            | ItemKind::Trait(box Trait { generics, .. })
5196            | ItemKind::TraitAlias(_, generics, _) => {
5197                if let ItemKind::Fn(box Fn { sig, .. }) = &item.kind {
5198                    self.collect_fn_info(sig.header, &sig.decl, item.id, &item.attrs);
5199                }
5200
5201                let def_id = self.r.local_def_id(item.id);
5202                let count = generics
5203                    .params
5204                    .iter()
5205                    .filter(|param| matches!(param.kind, ast::GenericParamKind::Lifetime { .. }))
5206                    .count();
5207                self.r.item_generics_num_lifetimes.insert(def_id, count);
5208            }
5209
5210            ItemKind::ForeignMod(ForeignMod { extern_span, safety: _, abi, items }) => {
5211                for foreign_item in items {
5212                    if let ForeignItemKind::Fn(box Fn { sig, .. }) = &foreign_item.kind {
5213                        let new_header =
5214                            FnHeader { ext: Extern::from_abi(*abi, *extern_span), ..sig.header };
5215                        self.collect_fn_info(new_header, &sig.decl, foreign_item.id, &item.attrs);
5216                    }
5217                }
5218            }
5219
5220            ItemKind::Mod(..)
5221            | ItemKind::Static(..)
5222            | ItemKind::Use(..)
5223            | ItemKind::ExternCrate(..)
5224            | ItemKind::MacroDef(..)
5225            | ItemKind::GlobalAsm(..)
5226            | ItemKind::MacCall(..)
5227            | ItemKind::DelegationMac(..) => {}
5228            ItemKind::Delegation(..) => {
5229                // Delegated functions have lifetimes, their count is not necessarily zero.
5230                // But skipping the delegation items here doesn't mean that the count will be considered zero,
5231                // it means there will be a panic when retrieving the count,
5232                // but for delegation items we are never actually retrieving that count in practice.
5233            }
5234        }
5235        visit::walk_item(self, item)
5236    }
5237
5238    fn visit_assoc_item(&mut self, item: &'ast AssocItem, ctxt: AssocCtxt) {
5239        if let AssocItemKind::Fn(box Fn { sig, .. }) = &item.kind {
5240            self.collect_fn_info(sig.header, &sig.decl, item.id, &item.attrs);
5241        }
5242        visit::walk_assoc_item(self, item, ctxt);
5243    }
5244}
5245
5246impl<'ra, 'tcx> Resolver<'ra, 'tcx> {
5247    pub(crate) fn late_resolve_crate(&mut self, krate: &Crate) {
5248        visit::walk_crate(&mut ItemInfoCollector { r: self }, krate);
5249        let mut late_resolution_visitor = LateResolutionVisitor::new(self);
5250        late_resolution_visitor.resolve_doc_links(&krate.attrs, MaybeExported::Ok(CRATE_NODE_ID));
5251        visit::walk_crate(&mut late_resolution_visitor, krate);
5252        for (id, span) in late_resolution_visitor.diag_metadata.unused_labels.iter() {
5253            self.lint_buffer.buffer_lint(
5254                lint::builtin::UNUSED_LABELS,
5255                *id,
5256                *span,
5257                BuiltinLintDiag::UnusedLabel,
5258            );
5259        }
5260    }
5261}
5262
5263/// Check if definition matches a path
5264fn def_id_matches_path(tcx: TyCtxt<'_>, mut def_id: DefId, expected_path: &[&str]) -> bool {
5265    let mut path = expected_path.iter().rev();
5266    while let (Some(parent), Some(next_step)) = (tcx.opt_parent(def_id), path.next()) {
5267        if !tcx.opt_item_name(def_id).is_some_and(|n| n.as_str() == *next_step) {
5268            return false;
5269        }
5270        def_id = parent;
5271    }
5272    true
5273}