rustc_resolve/
late.rs

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