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, ty.id),
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, ty.id);
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 { suppress_elision_warning: false },
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                            // We are inside a const item, so do not warn.
1881                            LifetimeRes::Static { suppress_elision_warning: true },
1882                            elision_candidate,
1883                        );
1884                        return;
1885                    } else if emit_lint {
1886                        self.r.lint_buffer.buffer_lint(
1887                            lint::builtin::ELIDED_LIFETIMES_IN_ASSOCIATED_CONSTANT,
1888                            node_id,
1889                            lifetime.ident.span,
1890                            lint::BuiltinLintDiag::AssociatedConstElidedLifetime {
1891                                elided,
1892                                span: lifetime.ident.span,
1893                                lifetimes_in_scope: lifetimes_in_scope.into(),
1894                            },
1895                        );
1896                    }
1897                }
1898                LifetimeRibKind::AnonymousReportError => {
1899                    if elided {
1900                        let suggestion = self.lifetime_ribs[i..].iter().rev().find_map(|rib| {
1901                            if let LifetimeRibKind::Generics {
1902                                span,
1903                                kind: LifetimeBinderKind::PolyTrait | LifetimeBinderKind::WhereBound,
1904                                ..
1905                            } = rib.kind
1906                            {
1907                                Some(errors::ElidedAnonymousLivetimeReportErrorSuggestion {
1908                                    lo: span.shrink_to_lo(),
1909                                    hi: lifetime.ident.span.shrink_to_hi(),
1910                                })
1911                            } else {
1912                                None
1913                            }
1914                        });
1915                        // are we trying to use an anonymous lifetime
1916                        // on a non GAT associated trait type?
1917                        if !self.in_func_body
1918                            && let Some((module, _)) = &self.current_trait_ref
1919                            && let Some(ty) = &self.diag_metadata.current_self_type
1920                            && Some(true) == self.diag_metadata.in_non_gat_assoc_type
1921                            && let crate::ModuleKind::Def(DefKind::Trait, trait_id, _) = module.kind
1922                        {
1923                            if def_id_matches_path(
1924                                self.r.tcx,
1925                                trait_id,
1926                                &["core", "iter", "traits", "iterator", "Iterator"],
1927                            ) {
1928                                self.r.dcx().emit_err(errors::LendingIteratorReportError {
1929                                    lifetime: lifetime.ident.span,
1930                                    ty: ty.span,
1931                                });
1932                            } else {
1933                                self.r.dcx().emit_err(errors::AnonymousLivetimeNonGatReportError {
1934                                    lifetime: lifetime.ident.span,
1935                                });
1936                            }
1937                        } else {
1938                            self.r.dcx().emit_err(errors::ElidedAnonymousLivetimeReportError {
1939                                span: lifetime.ident.span,
1940                                suggestion,
1941                            });
1942                        }
1943                    } else {
1944                        self.r.dcx().emit_err(errors::ExplicitAnonymousLivetimeReportError {
1945                            span: lifetime.ident.span,
1946                        });
1947                    };
1948                    self.record_lifetime_res(lifetime.id, LifetimeRes::Error, elision_candidate);
1949                    return;
1950                }
1951                LifetimeRibKind::Elided(res) => {
1952                    self.record_lifetime_res(lifetime.id, res, elision_candidate);
1953                    return;
1954                }
1955                LifetimeRibKind::ElisionFailure => {
1956                    self.diag_metadata.current_elision_failures.push(missing_lifetime);
1957                    self.record_lifetime_res(lifetime.id, LifetimeRes::Error, elision_candidate);
1958                    return;
1959                }
1960                LifetimeRibKind::Item => break,
1961                LifetimeRibKind::Generics { .. } | LifetimeRibKind::ConstParamTy => {}
1962                LifetimeRibKind::ConcreteAnonConst(_) => {
1963                    // There is always an `Elided(LifetimeRes::Infer)` inside an `AnonConst`.
1964                    span_bug!(lifetime.ident.span, "unexpected rib kind: {:?}", rib.kind)
1965                }
1966            }
1967        }
1968        self.record_lifetime_res(lifetime.id, LifetimeRes::Error, elision_candidate);
1969        self.report_missing_lifetime_specifiers(vec![missing_lifetime], None);
1970    }
1971
1972    #[instrument(level = "debug", skip(self))]
1973    fn resolve_elided_lifetime(&mut self, anchor_id: NodeId, span: Span) {
1974        let id = self.r.next_node_id();
1975        let lt = Lifetime { id, ident: Ident::new(kw::UnderscoreLifetime, span) };
1976
1977        self.record_lifetime_res(
1978            anchor_id,
1979            LifetimeRes::ElidedAnchor { start: id, end: id + 1 },
1980            LifetimeElisionCandidate::Ignore,
1981        );
1982        self.resolve_anonymous_lifetime(&lt, anchor_id, true);
1983    }
1984
1985    #[instrument(level = "debug", skip(self))]
1986    fn create_fresh_lifetime(
1987        &mut self,
1988        ident: Ident,
1989        binder: NodeId,
1990        kind: MissingLifetimeKind,
1991    ) -> LifetimeRes {
1992        debug_assert_eq!(ident.name, kw::UnderscoreLifetime);
1993        debug!(?ident.span);
1994
1995        // Leave the responsibility to create the `LocalDefId` to lowering.
1996        let param = self.r.next_node_id();
1997        let res = LifetimeRes::Fresh { param, binder, kind };
1998        self.record_lifetime_param(param, res);
1999
2000        // Record the created lifetime parameter so lowering can pick it up and add it to HIR.
2001        self.r
2002            .extra_lifetime_params_map
2003            .entry(binder)
2004            .or_insert_with(Vec::new)
2005            .push((ident, param, res));
2006        res
2007    }
2008
2009    #[instrument(level = "debug", skip(self))]
2010    fn resolve_elided_lifetimes_in_path(
2011        &mut self,
2012        partial_res: PartialRes,
2013        path: &[Segment],
2014        source: PathSource<'_, '_>,
2015        path_span: Span,
2016    ) {
2017        let proj_start = path.len() - partial_res.unresolved_segments();
2018        for (i, segment) in path.iter().enumerate() {
2019            if segment.has_lifetime_args {
2020                continue;
2021            }
2022            let Some(segment_id) = segment.id else {
2023                continue;
2024            };
2025
2026            // Figure out if this is a type/trait segment,
2027            // which may need lifetime elision performed.
2028            let type_def_id = match partial_res.base_res() {
2029                Res::Def(DefKind::AssocTy, def_id) if i + 2 == proj_start => {
2030                    self.r.tcx.parent(def_id)
2031                }
2032                Res::Def(DefKind::Variant, def_id) if i + 1 == proj_start => {
2033                    self.r.tcx.parent(def_id)
2034                }
2035                Res::Def(DefKind::Struct, def_id)
2036                | Res::Def(DefKind::Union, def_id)
2037                | Res::Def(DefKind::Enum, def_id)
2038                | Res::Def(DefKind::TyAlias, def_id)
2039                | Res::Def(DefKind::Trait, def_id)
2040                    if i + 1 == proj_start =>
2041                {
2042                    def_id
2043                }
2044                _ => continue,
2045            };
2046
2047            let expected_lifetimes = self.r.item_generics_num_lifetimes(type_def_id);
2048            if expected_lifetimes == 0 {
2049                continue;
2050            }
2051
2052            let node_ids = self.r.next_node_ids(expected_lifetimes);
2053            self.record_lifetime_res(
2054                segment_id,
2055                LifetimeRes::ElidedAnchor { start: node_ids.start, end: node_ids.end },
2056                LifetimeElisionCandidate::Ignore,
2057            );
2058
2059            let inferred = match source {
2060                PathSource::Trait(..)
2061                | PathSource::TraitItem(..)
2062                | PathSource::Type
2063                | PathSource::PreciseCapturingArg(..)
2064                | PathSource::ReturnTypeNotation => false,
2065                PathSource::Expr(..)
2066                | PathSource::Pat
2067                | PathSource::Struct
2068                | PathSource::TupleStruct(..)
2069                | PathSource::DefineOpaques
2070                | PathSource::Delegation => true,
2071            };
2072            if inferred {
2073                // Do not create a parameter for patterns and expressions: type checking can infer
2074                // the appropriate lifetime for us.
2075                for id in node_ids {
2076                    self.record_lifetime_res(
2077                        id,
2078                        LifetimeRes::Infer,
2079                        LifetimeElisionCandidate::Named,
2080                    );
2081                }
2082                continue;
2083            }
2084
2085            let elided_lifetime_span = if segment.has_generic_args {
2086                // If there are brackets, but not generic arguments, then use the opening bracket
2087                segment.args_span.with_hi(segment.args_span.lo() + BytePos(1))
2088            } else {
2089                // If there are no brackets, use the identifier span.
2090                // HACK: we use find_ancestor_inside to properly suggest elided spans in paths
2091                // originating from macros, since the segment's span might be from a macro arg.
2092                segment.ident.span.find_ancestor_inside(path_span).unwrap_or(path_span)
2093            };
2094            let ident = Ident::new(kw::UnderscoreLifetime, elided_lifetime_span);
2095
2096            let kind = if segment.has_generic_args {
2097                MissingLifetimeKind::Comma
2098            } else {
2099                MissingLifetimeKind::Brackets
2100            };
2101            let missing_lifetime = MissingLifetime {
2102                id: node_ids.start,
2103                id_for_lint: segment_id,
2104                span: elided_lifetime_span,
2105                kind,
2106                count: expected_lifetimes,
2107            };
2108            let mut should_lint = true;
2109            for rib in self.lifetime_ribs.iter().rev() {
2110                match rib.kind {
2111                    // In create-parameter mode we error here because we don't want to support
2112                    // deprecated impl elision in new features like impl elision and `async fn`,
2113                    // both of which work using the `CreateParameter` mode:
2114                    //
2115                    //     impl Foo for std::cell::Ref<u32> // note lack of '_
2116                    //     async fn foo(_: std::cell::Ref<u32>) { ... }
2117                    LifetimeRibKind::AnonymousCreateParameter { report_in_path: true, .. }
2118                    | LifetimeRibKind::StaticIfNoLifetimeInScope { .. } => {
2119                        let sess = self.r.tcx.sess;
2120                        let subdiag = rustc_errors::elided_lifetime_in_path_suggestion(
2121                            sess.source_map(),
2122                            expected_lifetimes,
2123                            path_span,
2124                            !segment.has_generic_args,
2125                            elided_lifetime_span,
2126                        );
2127                        self.r.dcx().emit_err(errors::ImplicitElidedLifetimeNotAllowedHere {
2128                            span: path_span,
2129                            subdiag,
2130                        });
2131                        should_lint = false;
2132
2133                        for id in node_ids {
2134                            self.record_lifetime_res(
2135                                id,
2136                                LifetimeRes::Error,
2137                                LifetimeElisionCandidate::Named,
2138                            );
2139                        }
2140                        break;
2141                    }
2142                    // Do not create a parameter for patterns and expressions.
2143                    LifetimeRibKind::AnonymousCreateParameter { binder, .. } => {
2144                        // Group all suggestions into the first record.
2145                        let mut candidate = LifetimeElisionCandidate::Missing(missing_lifetime);
2146                        for id in node_ids {
2147                            let res = self.create_fresh_lifetime(ident, binder, kind);
2148                            self.record_lifetime_res(
2149                                id,
2150                                res,
2151                                replace(&mut candidate, LifetimeElisionCandidate::Named),
2152                            );
2153                        }
2154                        break;
2155                    }
2156                    LifetimeRibKind::Elided(res) => {
2157                        let mut candidate = LifetimeElisionCandidate::Missing(missing_lifetime);
2158                        for id in node_ids {
2159                            self.record_lifetime_res(
2160                                id,
2161                                res,
2162                                replace(&mut candidate, LifetimeElisionCandidate::Ignore),
2163                            );
2164                        }
2165                        break;
2166                    }
2167                    LifetimeRibKind::ElisionFailure => {
2168                        self.diag_metadata.current_elision_failures.push(missing_lifetime);
2169                        for id in node_ids {
2170                            self.record_lifetime_res(
2171                                id,
2172                                LifetimeRes::Error,
2173                                LifetimeElisionCandidate::Ignore,
2174                            );
2175                        }
2176                        break;
2177                    }
2178                    // `LifetimeRes::Error`, which would usually be used in the case of
2179                    // `ReportError`, is unsuitable here, as we don't emit an error yet. Instead,
2180                    // we simply resolve to an implicit lifetime, which will be checked later, at
2181                    // which point a suitable error will be emitted.
2182                    LifetimeRibKind::AnonymousReportError | LifetimeRibKind::Item => {
2183                        for id in node_ids {
2184                            self.record_lifetime_res(
2185                                id,
2186                                LifetimeRes::Error,
2187                                LifetimeElisionCandidate::Ignore,
2188                            );
2189                        }
2190                        self.report_missing_lifetime_specifiers(vec![missing_lifetime], None);
2191                        break;
2192                    }
2193                    LifetimeRibKind::Generics { .. } | LifetimeRibKind::ConstParamTy => {}
2194                    LifetimeRibKind::ConcreteAnonConst(_) => {
2195                        // There is always an `Elided(LifetimeRes::Infer)` inside an `AnonConst`.
2196                        span_bug!(elided_lifetime_span, "unexpected rib kind: {:?}", rib.kind)
2197                    }
2198                }
2199            }
2200
2201            if should_lint {
2202                self.r.lint_buffer.buffer_lint(
2203                    lint::builtin::ELIDED_LIFETIMES_IN_PATHS,
2204                    segment_id,
2205                    elided_lifetime_span,
2206                    lint::BuiltinLintDiag::ElidedLifetimesInPaths(
2207                        expected_lifetimes,
2208                        path_span,
2209                        !segment.has_generic_args,
2210                        elided_lifetime_span,
2211                    ),
2212                );
2213            }
2214        }
2215    }
2216
2217    #[instrument(level = "debug", skip(self))]
2218    fn record_lifetime_res(
2219        &mut self,
2220        id: NodeId,
2221        res: LifetimeRes,
2222        candidate: LifetimeElisionCandidate,
2223    ) {
2224        if let Some(prev_res) = self.r.lifetimes_res_map.insert(id, res) {
2225            panic!("lifetime {id:?} resolved multiple times ({prev_res:?} before, {res:?} now)")
2226        }
2227
2228        match candidate {
2229            LifetimeElisionCandidate::Missing(missing @ MissingLifetime { .. }) => {
2230                debug_assert_eq!(id, missing.id);
2231                match res {
2232                    LifetimeRes::Static { suppress_elision_warning } => {
2233                        if !suppress_elision_warning {
2234                            self.r.lint_buffer.buffer_lint(
2235                                lint::builtin::ELIDED_NAMED_LIFETIMES,
2236                                missing.id_for_lint,
2237                                missing.span,
2238                                BuiltinLintDiag::ElidedNamedLifetimes {
2239                                    elided: (missing.span, missing.kind),
2240                                    resolution: lint::ElidedLifetimeResolution::Static,
2241                                },
2242                            );
2243                        }
2244                    }
2245                    LifetimeRes::Param { param, binder: _ } => {
2246                        let tcx = self.r.tcx();
2247                        self.r.lint_buffer.buffer_lint(
2248                            lint::builtin::ELIDED_NAMED_LIFETIMES,
2249                            missing.id_for_lint,
2250                            missing.span,
2251                            BuiltinLintDiag::ElidedNamedLifetimes {
2252                                elided: (missing.span, missing.kind),
2253                                resolution: lint::ElidedLifetimeResolution::Param(
2254                                    tcx.item_name(param.into()),
2255                                    tcx.source_span(param),
2256                                ),
2257                            },
2258                        );
2259                    }
2260                    LifetimeRes::Fresh { .. }
2261                    | LifetimeRes::Infer
2262                    | LifetimeRes::Error
2263                    | LifetimeRes::ElidedAnchor { .. } => {}
2264                }
2265            }
2266            LifetimeElisionCandidate::Ignore | LifetimeElisionCandidate::Named => {}
2267        }
2268
2269        match res {
2270            LifetimeRes::Param { .. } | LifetimeRes::Fresh { .. } | LifetimeRes::Static { .. } => {
2271                if let Some(ref mut candidates) = self.lifetime_elision_candidates {
2272                    candidates.push((res, candidate));
2273                }
2274            }
2275            LifetimeRes::Infer | LifetimeRes::Error | LifetimeRes::ElidedAnchor { .. } => {}
2276        }
2277    }
2278
2279    #[instrument(level = "debug", skip(self))]
2280    fn record_lifetime_param(&mut self, id: NodeId, res: LifetimeRes) {
2281        if let Some(prev_res) = self.r.lifetimes_res_map.insert(id, res) {
2282            panic!(
2283                "lifetime parameter {id:?} resolved multiple times ({prev_res:?} before, {res:?} now)"
2284            )
2285        }
2286    }
2287
2288    /// Perform resolution of a function signature, accounting for lifetime elision.
2289    #[instrument(level = "debug", skip(self, inputs))]
2290    fn resolve_fn_signature(
2291        &mut self,
2292        fn_id: NodeId,
2293        has_self: bool,
2294        inputs: impl Iterator<Item = (Option<&'ast Pat>, &'ast Ty)> + Clone,
2295        output_ty: &'ast FnRetTy,
2296    ) {
2297        // Add each argument to the rib.
2298        let elision_lifetime = self.resolve_fn_params(has_self, inputs);
2299        debug!(?elision_lifetime);
2300
2301        let outer_failures = take(&mut self.diag_metadata.current_elision_failures);
2302        let output_rib = if let Ok(res) = elision_lifetime.as_ref() {
2303            self.r.lifetime_elision_allowed.insert(fn_id);
2304            LifetimeRibKind::Elided(*res)
2305        } else {
2306            LifetimeRibKind::ElisionFailure
2307        };
2308        self.with_lifetime_rib(output_rib, |this| visit::walk_fn_ret_ty(this, output_ty));
2309        let elision_failures =
2310            replace(&mut self.diag_metadata.current_elision_failures, outer_failures);
2311        if !elision_failures.is_empty() {
2312            let Err(failure_info) = elision_lifetime else { bug!() };
2313            self.report_missing_lifetime_specifiers(elision_failures, Some(failure_info));
2314        }
2315    }
2316
2317    /// Resolve inside function parameters and parameter types.
2318    /// Returns the lifetime for elision in fn return type,
2319    /// or diagnostic information in case of elision failure.
2320    fn resolve_fn_params(
2321        &mut self,
2322        has_self: bool,
2323        inputs: impl Iterator<Item = (Option<&'ast Pat>, &'ast Ty)> + Clone,
2324    ) -> Result<LifetimeRes, (Vec<MissingLifetime>, Vec<ElisionFnParameter>)> {
2325        enum Elision {
2326            /// We have not found any candidate.
2327            None,
2328            /// We have a candidate bound to `self`.
2329            Self_(LifetimeRes),
2330            /// We have a candidate bound to a parameter.
2331            Param(LifetimeRes),
2332            /// We failed elision.
2333            Err,
2334        }
2335
2336        // Save elision state to reinstate it later.
2337        let outer_candidates = self.lifetime_elision_candidates.take();
2338
2339        // Result of elision.
2340        let mut elision_lifetime = Elision::None;
2341        // Information for diagnostics.
2342        let mut parameter_info = Vec::new();
2343        let mut all_candidates = Vec::new();
2344
2345        // Resolve and apply bindings first so diagnostics can see if they're used in types.
2346        let mut bindings = smallvec![(PatBoundCtx::Product, Default::default())];
2347        for (pat, _) in inputs.clone() {
2348            debug!("resolving bindings in pat = {pat:?}");
2349            self.with_lifetime_rib(LifetimeRibKind::Elided(LifetimeRes::Infer), |this| {
2350                if let Some(pat) = pat {
2351                    this.resolve_pattern(pat, PatternSource::FnParam, &mut bindings);
2352                }
2353            });
2354        }
2355        self.apply_pattern_bindings(bindings);
2356
2357        for (index, (pat, ty)) in inputs.enumerate() {
2358            debug!("resolving type for pat = {pat:?}, ty = {ty:?}");
2359            // Record elision candidates only for this parameter.
2360            debug_assert_matches!(self.lifetime_elision_candidates, None);
2361            self.lifetime_elision_candidates = Some(Default::default());
2362            self.visit_ty(ty);
2363            let local_candidates = self.lifetime_elision_candidates.take();
2364
2365            if let Some(candidates) = local_candidates {
2366                let distinct: UnordSet<_> = candidates.iter().map(|(res, _)| *res).collect();
2367                let lifetime_count = distinct.len();
2368                if lifetime_count != 0 {
2369                    parameter_info.push(ElisionFnParameter {
2370                        index,
2371                        ident: if let Some(pat) = pat
2372                            && let PatKind::Ident(_, ident, _) = pat.kind
2373                        {
2374                            Some(ident)
2375                        } else {
2376                            None
2377                        },
2378                        lifetime_count,
2379                        span: ty.span,
2380                    });
2381                    all_candidates.extend(candidates.into_iter().filter_map(|(_, candidate)| {
2382                        match candidate {
2383                            LifetimeElisionCandidate::Ignore | LifetimeElisionCandidate::Named => {
2384                                None
2385                            }
2386                            LifetimeElisionCandidate::Missing(missing) => Some(missing),
2387                        }
2388                    }));
2389                }
2390                if !distinct.is_empty() {
2391                    match elision_lifetime {
2392                        // We are the first parameter to bind lifetimes.
2393                        Elision::None => {
2394                            if let Some(res) = distinct.get_only() {
2395                                // We have a single lifetime => success.
2396                                elision_lifetime = Elision::Param(*res)
2397                            } else {
2398                                // We have multiple lifetimes => error.
2399                                elision_lifetime = Elision::Err;
2400                            }
2401                        }
2402                        // We have 2 parameters that bind lifetimes => error.
2403                        Elision::Param(_) => elision_lifetime = Elision::Err,
2404                        // `self` elision takes precedence over everything else.
2405                        Elision::Self_(_) | Elision::Err => {}
2406                    }
2407                }
2408            }
2409
2410            // Handle `self` specially.
2411            if index == 0 && has_self {
2412                let self_lifetime = self.find_lifetime_for_self(ty);
2413                elision_lifetime = match self_lifetime {
2414                    // We found `self` elision.
2415                    Set1::One(lifetime) => Elision::Self_(lifetime),
2416                    // `self` itself had ambiguous lifetimes, e.g.
2417                    // &Box<&Self>. In this case we won't consider
2418                    // taking an alternative parameter lifetime; just avoid elision
2419                    // entirely.
2420                    Set1::Many => Elision::Err,
2421                    // We do not have `self` elision: disregard the `Elision::Param` that we may
2422                    // have found.
2423                    Set1::Empty => Elision::None,
2424                }
2425            }
2426            debug!("(resolving function / closure) recorded parameter");
2427        }
2428
2429        // Reinstate elision state.
2430        debug_assert_matches!(self.lifetime_elision_candidates, None);
2431        self.lifetime_elision_candidates = outer_candidates;
2432
2433        if let Elision::Param(res) | Elision::Self_(res) = elision_lifetime {
2434            return Ok(res);
2435        }
2436
2437        // We do not have a candidate.
2438        Err((all_candidates, parameter_info))
2439    }
2440
2441    /// List all the lifetimes that appear in the provided type.
2442    fn find_lifetime_for_self(&self, ty: &'ast Ty) -> Set1<LifetimeRes> {
2443        /// Visits a type to find all the &references, and determines the
2444        /// set of lifetimes for all of those references where the referent
2445        /// contains Self.
2446        struct FindReferenceVisitor<'a, 'ra, 'tcx> {
2447            r: &'a Resolver<'ra, 'tcx>,
2448            impl_self: Option<Res>,
2449            lifetime: Set1<LifetimeRes>,
2450        }
2451
2452        impl<'ra> Visitor<'ra> for FindReferenceVisitor<'_, '_, '_> {
2453            fn visit_ty(&mut self, ty: &'ra Ty) {
2454                trace!("FindReferenceVisitor considering ty={:?}", ty);
2455                if let TyKind::Ref(lt, _) | TyKind::PinnedRef(lt, _) = ty.kind {
2456                    // See if anything inside the &thing contains Self
2457                    let mut visitor =
2458                        SelfVisitor { r: self.r, impl_self: self.impl_self, self_found: false };
2459                    visitor.visit_ty(ty);
2460                    trace!("FindReferenceVisitor: SelfVisitor self_found={:?}", visitor.self_found);
2461                    if visitor.self_found {
2462                        let lt_id = if let Some(lt) = lt {
2463                            lt.id
2464                        } else {
2465                            let res = self.r.lifetimes_res_map[&ty.id];
2466                            let LifetimeRes::ElidedAnchor { start, .. } = res else { bug!() };
2467                            start
2468                        };
2469                        let lt_res = self.r.lifetimes_res_map[&lt_id];
2470                        trace!("FindReferenceVisitor inserting res={:?}", lt_res);
2471                        self.lifetime.insert(lt_res);
2472                    }
2473                }
2474                visit::walk_ty(self, ty)
2475            }
2476
2477            // A type may have an expression as a const generic argument.
2478            // We do not want to recurse into those.
2479            fn visit_expr(&mut self, _: &'ra Expr) {}
2480        }
2481
2482        /// Visitor which checks the referent of a &Thing to see if the
2483        /// Thing contains Self
2484        struct SelfVisitor<'a, 'ra, 'tcx> {
2485            r: &'a Resolver<'ra, 'tcx>,
2486            impl_self: Option<Res>,
2487            self_found: bool,
2488        }
2489
2490        impl SelfVisitor<'_, '_, '_> {
2491            // Look for `self: &'a Self` - also desugared from `&'a self`
2492            fn is_self_ty(&self, ty: &Ty) -> bool {
2493                match ty.kind {
2494                    TyKind::ImplicitSelf => true,
2495                    TyKind::Path(None, _) => {
2496                        let path_res = self.r.partial_res_map[&ty.id].full_res();
2497                        if let Some(Res::SelfTyParam { .. } | Res::SelfTyAlias { .. }) = path_res {
2498                            return true;
2499                        }
2500                        self.impl_self.is_some() && path_res == self.impl_self
2501                    }
2502                    _ => false,
2503                }
2504            }
2505        }
2506
2507        impl<'ra> Visitor<'ra> for SelfVisitor<'_, '_, '_> {
2508            fn visit_ty(&mut self, ty: &'ra Ty) {
2509                trace!("SelfVisitor considering ty={:?}", ty);
2510                if self.is_self_ty(ty) {
2511                    trace!("SelfVisitor found Self");
2512                    self.self_found = true;
2513                }
2514                visit::walk_ty(self, ty)
2515            }
2516
2517            // A type may have an expression as a const generic argument.
2518            // We do not want to recurse into those.
2519            fn visit_expr(&mut self, _: &'ra Expr) {}
2520        }
2521
2522        let impl_self = self
2523            .diag_metadata
2524            .current_self_type
2525            .as_ref()
2526            .and_then(|ty| {
2527                if let TyKind::Path(None, _) = ty.kind {
2528                    self.r.partial_res_map.get(&ty.id)
2529                } else {
2530                    None
2531                }
2532            })
2533            .and_then(|res| res.full_res())
2534            .filter(|res| {
2535                // Permit the types that unambiguously always
2536                // result in the same type constructor being used
2537                // (it can't differ between `Self` and `self`).
2538                matches!(
2539                    res,
2540                    Res::Def(DefKind::Struct | DefKind::Union | DefKind::Enum, _,) | Res::PrimTy(_)
2541                )
2542            });
2543        let mut visitor = FindReferenceVisitor { r: self.r, impl_self, lifetime: Set1::Empty };
2544        visitor.visit_ty(ty);
2545        trace!("FindReferenceVisitor found={:?}", visitor.lifetime);
2546        visitor.lifetime
2547    }
2548
2549    /// Searches the current set of local scopes for labels. Returns the `NodeId` of the resolved
2550    /// label and reports an error if the label is not found or is unreachable.
2551    fn resolve_label(&mut self, mut label: Ident) -> Result<(NodeId, Span), ResolutionError<'ra>> {
2552        let mut suggestion = None;
2553
2554        for i in (0..self.label_ribs.len()).rev() {
2555            let rib = &self.label_ribs[i];
2556
2557            if let RibKind::MacroDefinition(def) = rib.kind
2558                // If an invocation of this macro created `ident`, give up on `ident`
2559                // and switch to `ident`'s source from the macro definition.
2560                && def == self.r.macro_def(label.span.ctxt())
2561            {
2562                label.span.remove_mark();
2563            }
2564
2565            let ident = label.normalize_to_macro_rules();
2566            if let Some((ident, id)) = rib.bindings.get_key_value(&ident) {
2567                let definition_span = ident.span;
2568                return if self.is_label_valid_from_rib(i) {
2569                    Ok((*id, definition_span))
2570                } else {
2571                    Err(ResolutionError::UnreachableLabel {
2572                        name: label.name,
2573                        definition_span,
2574                        suggestion,
2575                    })
2576                };
2577            }
2578
2579            // Diagnostics: Check if this rib contains a label with a similar name, keep track of
2580            // the first such label that is encountered.
2581            suggestion = suggestion.or_else(|| self.suggestion_for_label_in_rib(i, label));
2582        }
2583
2584        Err(ResolutionError::UndeclaredLabel { name: label.name, suggestion })
2585    }
2586
2587    /// Determine whether or not a label from the `rib_index`th label rib is reachable.
2588    fn is_label_valid_from_rib(&self, rib_index: usize) -> bool {
2589        let ribs = &self.label_ribs[rib_index + 1..];
2590        ribs.iter().all(|rib| !rib.kind.is_label_barrier())
2591    }
2592
2593    fn resolve_adt(&mut self, item: &'ast Item, generics: &'ast Generics) {
2594        debug!("resolve_adt");
2595        let kind = self.r.local_def_kind(item.id);
2596        self.with_current_self_item(item, |this| {
2597            this.with_generic_param_rib(
2598                &generics.params,
2599                RibKind::Item(HasGenericParams::Yes(generics.span), kind),
2600                LifetimeRibKind::Generics {
2601                    binder: item.id,
2602                    kind: LifetimeBinderKind::Item,
2603                    span: generics.span,
2604                },
2605                |this| {
2606                    let item_def_id = this.r.local_def_id(item.id).to_def_id();
2607                    this.with_self_rib(
2608                        Res::SelfTyAlias {
2609                            alias_to: item_def_id,
2610                            forbid_generic: false,
2611                            is_trait_impl: false,
2612                        },
2613                        |this| {
2614                            visit::walk_item(this, item);
2615                        },
2616                    );
2617                },
2618            );
2619        });
2620    }
2621
2622    fn future_proof_import(&mut self, use_tree: &UseTree) {
2623        if let [segment, rest @ ..] = use_tree.prefix.segments.as_slice() {
2624            let ident = segment.ident;
2625            if ident.is_path_segment_keyword() || ident.span.is_rust_2015() {
2626                return;
2627            }
2628
2629            let nss = match use_tree.kind {
2630                UseTreeKind::Simple(..) if rest.is_empty() => &[TypeNS, ValueNS][..],
2631                _ => &[TypeNS],
2632            };
2633            let report_error = |this: &Self, ns| {
2634                if this.should_report_errs() {
2635                    let what = if ns == TypeNS { "type parameters" } else { "local variables" };
2636                    this.r.dcx().emit_err(errors::ImportsCannotReferTo { span: ident.span, what });
2637                }
2638            };
2639
2640            for &ns in nss {
2641                match self.maybe_resolve_ident_in_lexical_scope(ident, ns) {
2642                    Some(LexicalScopeBinding::Res(..)) => {
2643                        report_error(self, ns);
2644                    }
2645                    Some(LexicalScopeBinding::Item(binding)) => {
2646                        if let Some(LexicalScopeBinding::Res(..)) =
2647                            self.resolve_ident_in_lexical_scope(ident, ns, None, Some(binding))
2648                        {
2649                            report_error(self, ns);
2650                        }
2651                    }
2652                    None => {}
2653                }
2654            }
2655        } else if let UseTreeKind::Nested { items, .. } = &use_tree.kind {
2656            for (use_tree, _) in items {
2657                self.future_proof_import(use_tree);
2658            }
2659        }
2660    }
2661
2662    fn resolve_item(&mut self, item: &'ast Item) {
2663        let mod_inner_docs =
2664            matches!(item.kind, ItemKind::Mod(..)) && rustdoc::inner_docs(&item.attrs);
2665        if !mod_inner_docs && !matches!(item.kind, ItemKind::Impl(..) | ItemKind::Use(..)) {
2666            self.resolve_doc_links(&item.attrs, MaybeExported::Ok(item.id));
2667        }
2668
2669        debug!("(resolving item) resolving {:?} ({:?})", item.kind.ident(), item.kind);
2670
2671        let def_kind = self.r.local_def_kind(item.id);
2672        match item.kind {
2673            ItemKind::TyAlias(box TyAlias { ref generics, .. }) => {
2674                self.with_generic_param_rib(
2675                    &generics.params,
2676                    RibKind::Item(HasGenericParams::Yes(generics.span), def_kind),
2677                    LifetimeRibKind::Generics {
2678                        binder: item.id,
2679                        kind: LifetimeBinderKind::Item,
2680                        span: generics.span,
2681                    },
2682                    |this| visit::walk_item(this, item),
2683                );
2684            }
2685
2686            ItemKind::Fn(box Fn { ref generics, ref define_opaque, .. }) => {
2687                self.with_generic_param_rib(
2688                    &generics.params,
2689                    RibKind::Item(HasGenericParams::Yes(generics.span), def_kind),
2690                    LifetimeRibKind::Generics {
2691                        binder: item.id,
2692                        kind: LifetimeBinderKind::Function,
2693                        span: generics.span,
2694                    },
2695                    |this| visit::walk_item(this, item),
2696                );
2697                self.resolve_define_opaques(define_opaque);
2698            }
2699
2700            ItemKind::Enum(_, ref generics, _)
2701            | ItemKind::Struct(_, ref generics, _)
2702            | ItemKind::Union(_, ref generics, _) => {
2703                self.resolve_adt(item, generics);
2704            }
2705
2706            ItemKind::Impl(box Impl {
2707                ref generics,
2708                ref of_trait,
2709                ref self_ty,
2710                items: ref impl_items,
2711                ..
2712            }) => {
2713                self.diag_metadata.current_impl_items = Some(impl_items);
2714                self.resolve_implementation(
2715                    &item.attrs,
2716                    generics,
2717                    of_trait,
2718                    self_ty,
2719                    item.id,
2720                    impl_items,
2721                );
2722                self.diag_metadata.current_impl_items = None;
2723            }
2724
2725            ItemKind::Trait(box Trait { ref generics, ref bounds, ref items, .. }) => {
2726                // Create a new rib for the trait-wide type parameters.
2727                self.with_generic_param_rib(
2728                    &generics.params,
2729                    RibKind::Item(HasGenericParams::Yes(generics.span), def_kind),
2730                    LifetimeRibKind::Generics {
2731                        binder: item.id,
2732                        kind: LifetimeBinderKind::Item,
2733                        span: generics.span,
2734                    },
2735                    |this| {
2736                        let local_def_id = this.r.local_def_id(item.id).to_def_id();
2737                        this.with_self_rib(Res::SelfTyParam { trait_: local_def_id }, |this| {
2738                            this.visit_generics(generics);
2739                            walk_list!(this, visit_param_bound, bounds, BoundKind::SuperTraits);
2740                            this.resolve_trait_items(items);
2741                        });
2742                    },
2743                );
2744            }
2745
2746            ItemKind::TraitAlias(_, ref generics, ref bounds) => {
2747                // Create a new rib for the trait-wide type parameters.
2748                self.with_generic_param_rib(
2749                    &generics.params,
2750                    RibKind::Item(HasGenericParams::Yes(generics.span), def_kind),
2751                    LifetimeRibKind::Generics {
2752                        binder: item.id,
2753                        kind: LifetimeBinderKind::Item,
2754                        span: generics.span,
2755                    },
2756                    |this| {
2757                        let local_def_id = this.r.local_def_id(item.id).to_def_id();
2758                        this.with_self_rib(Res::SelfTyParam { trait_: local_def_id }, |this| {
2759                            this.visit_generics(generics);
2760                            walk_list!(this, visit_param_bound, bounds, BoundKind::Bound);
2761                        });
2762                    },
2763                );
2764            }
2765
2766            ItemKind::Mod(..) => {
2767                self.with_mod_rib(item.id, |this| {
2768                    if mod_inner_docs {
2769                        this.resolve_doc_links(&item.attrs, MaybeExported::Ok(item.id));
2770                    }
2771                    let old_macro_rules = this.parent_scope.macro_rules;
2772                    visit::walk_item(this, item);
2773                    // Maintain macro_rules scopes in the same way as during early resolution
2774                    // for diagnostics and doc links.
2775                    if item.attrs.iter().all(|attr| {
2776                        !attr.has_name(sym::macro_use) && !attr.has_name(sym::macro_escape)
2777                    }) {
2778                        this.parent_scope.macro_rules = old_macro_rules;
2779                    }
2780                });
2781            }
2782
2783            ItemKind::Static(box ast::StaticItem {
2784                ident,
2785                ref ty,
2786                ref expr,
2787                ref define_opaque,
2788                ..
2789            }) => {
2790                self.with_static_rib(def_kind, |this| {
2791                    this.with_lifetime_rib(
2792                        LifetimeRibKind::Elided(LifetimeRes::Static {
2793                            suppress_elision_warning: true,
2794                        }),
2795                        |this| {
2796                            this.visit_ty(ty);
2797                        },
2798                    );
2799                    if let Some(expr) = expr {
2800                        // We already forbid generic params because of the above item rib,
2801                        // so it doesn't matter whether this is a trivial constant.
2802                        this.resolve_const_body(expr, Some((ident, ConstantItemKind::Static)));
2803                    }
2804                });
2805                self.resolve_define_opaques(define_opaque);
2806            }
2807
2808            ItemKind::Const(box ast::ConstItem {
2809                ident,
2810                ref generics,
2811                ref ty,
2812                ref expr,
2813                ref define_opaque,
2814                ..
2815            }) => {
2816                self.with_generic_param_rib(
2817                    &generics.params,
2818                    RibKind::Item(
2819                        if self.r.tcx.features().generic_const_items() {
2820                            HasGenericParams::Yes(generics.span)
2821                        } else {
2822                            HasGenericParams::No
2823                        },
2824                        def_kind,
2825                    ),
2826                    LifetimeRibKind::Generics {
2827                        binder: item.id,
2828                        kind: LifetimeBinderKind::ConstItem,
2829                        span: generics.span,
2830                    },
2831                    |this| {
2832                        this.visit_generics(generics);
2833
2834                        this.with_lifetime_rib(
2835                            LifetimeRibKind::Elided(LifetimeRes::Static {
2836                                suppress_elision_warning: true,
2837                            }),
2838                            |this| this.visit_ty(ty),
2839                        );
2840
2841                        if let Some(expr) = expr {
2842                            this.resolve_const_body(expr, Some((ident, ConstantItemKind::Const)));
2843                        }
2844                    },
2845                );
2846                self.resolve_define_opaques(define_opaque);
2847            }
2848
2849            ItemKind::Use(ref use_tree) => {
2850                let maybe_exported = match use_tree.kind {
2851                    UseTreeKind::Simple(_) | UseTreeKind::Glob => MaybeExported::Ok(item.id),
2852                    UseTreeKind::Nested { .. } => MaybeExported::NestedUse(&item.vis),
2853                };
2854                self.resolve_doc_links(&item.attrs, maybe_exported);
2855
2856                self.future_proof_import(use_tree);
2857            }
2858
2859            ItemKind::MacroDef(_, ref macro_def) => {
2860                // Maintain macro_rules scopes in the same way as during early resolution
2861                // for diagnostics and doc links.
2862                if macro_def.macro_rules {
2863                    let def_id = self.r.local_def_id(item.id);
2864                    self.parent_scope.macro_rules = self.r.macro_rules_scopes[&def_id];
2865                }
2866            }
2867
2868            ItemKind::ForeignMod(_) | ItemKind::GlobalAsm(_) => {
2869                visit::walk_item(self, item);
2870            }
2871
2872            ItemKind::Delegation(ref delegation) => {
2873                let span = delegation.path.segments.last().unwrap().ident.span;
2874                self.with_generic_param_rib(
2875                    &[],
2876                    RibKind::Item(HasGenericParams::Yes(span), def_kind),
2877                    LifetimeRibKind::Generics {
2878                        binder: item.id,
2879                        kind: LifetimeBinderKind::Function,
2880                        span,
2881                    },
2882                    |this| this.resolve_delegation(delegation),
2883                );
2884            }
2885
2886            ItemKind::ExternCrate(..) => {}
2887
2888            ItemKind::MacCall(_) | ItemKind::DelegationMac(..) => {
2889                panic!("unexpanded macro in resolve!")
2890            }
2891        }
2892    }
2893
2894    fn with_generic_param_rib<'c, F>(
2895        &'c mut self,
2896        params: &'c [GenericParam],
2897        kind: RibKind<'ra>,
2898        lifetime_kind: LifetimeRibKind,
2899        f: F,
2900    ) where
2901        F: FnOnce(&mut Self),
2902    {
2903        debug!("with_generic_param_rib");
2904        let LifetimeRibKind::Generics { binder, span: generics_span, kind: generics_kind, .. } =
2905            lifetime_kind
2906        else {
2907            panic!()
2908        };
2909
2910        let mut function_type_rib = Rib::new(kind);
2911        let mut function_value_rib = Rib::new(kind);
2912        let mut function_lifetime_rib = LifetimeRib::new(lifetime_kind);
2913
2914        // Only check for shadowed bindings if we're declaring new params.
2915        if !params.is_empty() {
2916            let mut seen_bindings = FxHashMap::default();
2917            // Store all seen lifetimes names from outer scopes.
2918            let mut seen_lifetimes = FxHashSet::default();
2919
2920            // We also can't shadow bindings from associated parent items.
2921            for ns in [ValueNS, TypeNS] {
2922                for parent_rib in self.ribs[ns].iter().rev() {
2923                    // Break at mod level, to account for nested items which are
2924                    // allowed to shadow generic param names.
2925                    if matches!(parent_rib.kind, RibKind::Module(..)) {
2926                        break;
2927                    }
2928
2929                    seen_bindings
2930                        .extend(parent_rib.bindings.keys().map(|ident| (*ident, ident.span)));
2931                }
2932            }
2933
2934            // Forbid shadowing lifetime bindings
2935            for rib in self.lifetime_ribs.iter().rev() {
2936                seen_lifetimes.extend(rib.bindings.iter().map(|(ident, _)| *ident));
2937                if let LifetimeRibKind::Item = rib.kind {
2938                    break;
2939                }
2940            }
2941
2942            for param in params {
2943                let ident = param.ident.normalize_to_macros_2_0();
2944                debug!("with_generic_param_rib: {}", param.id);
2945
2946                if let GenericParamKind::Lifetime = param.kind
2947                    && let Some(&original) = seen_lifetimes.get(&ident)
2948                {
2949                    diagnostics::signal_lifetime_shadowing(self.r.tcx.sess, original, param.ident);
2950                    // Record lifetime res, so lowering knows there is something fishy.
2951                    self.record_lifetime_param(param.id, LifetimeRes::Error);
2952                    continue;
2953                }
2954
2955                match seen_bindings.entry(ident) {
2956                    Entry::Occupied(entry) => {
2957                        let span = *entry.get();
2958                        let err = ResolutionError::NameAlreadyUsedInParameterList(ident, span);
2959                        self.report_error(param.ident.span, err);
2960                        let rib = match param.kind {
2961                            GenericParamKind::Lifetime => {
2962                                // Record lifetime res, so lowering knows there is something fishy.
2963                                self.record_lifetime_param(param.id, LifetimeRes::Error);
2964                                continue;
2965                            }
2966                            GenericParamKind::Type { .. } => &mut function_type_rib,
2967                            GenericParamKind::Const { .. } => &mut function_value_rib,
2968                        };
2969
2970                        // Taint the resolution in case of errors to prevent follow up errors in typeck
2971                        self.r.record_partial_res(param.id, PartialRes::new(Res::Err));
2972                        rib.bindings.insert(ident, Res::Err);
2973                        continue;
2974                    }
2975                    Entry::Vacant(entry) => {
2976                        entry.insert(param.ident.span);
2977                    }
2978                }
2979
2980                if param.ident.name == kw::UnderscoreLifetime {
2981                    self.r
2982                        .dcx()
2983                        .emit_err(errors::UnderscoreLifetimeIsReserved { span: param.ident.span });
2984                    // Record lifetime res, so lowering knows there is something fishy.
2985                    self.record_lifetime_param(param.id, LifetimeRes::Error);
2986                    continue;
2987                }
2988
2989                if param.ident.name == kw::StaticLifetime {
2990                    self.r.dcx().emit_err(errors::StaticLifetimeIsReserved {
2991                        span: param.ident.span,
2992                        lifetime: param.ident,
2993                    });
2994                    // Record lifetime res, so lowering knows there is something fishy.
2995                    self.record_lifetime_param(param.id, LifetimeRes::Error);
2996                    continue;
2997                }
2998
2999                let def_id = self.r.local_def_id(param.id);
3000
3001                // Plain insert (no renaming).
3002                let (rib, def_kind) = match param.kind {
3003                    GenericParamKind::Type { .. } => (&mut function_type_rib, DefKind::TyParam),
3004                    GenericParamKind::Const { .. } => {
3005                        (&mut function_value_rib, DefKind::ConstParam)
3006                    }
3007                    GenericParamKind::Lifetime => {
3008                        let res = LifetimeRes::Param { param: def_id, binder };
3009                        self.record_lifetime_param(param.id, res);
3010                        function_lifetime_rib.bindings.insert(ident, (param.id, res));
3011                        continue;
3012                    }
3013                };
3014
3015                let res = match kind {
3016                    RibKind::Item(..) | RibKind::AssocItem => {
3017                        Res::Def(def_kind, def_id.to_def_id())
3018                    }
3019                    RibKind::Normal => {
3020                        // FIXME(non_lifetime_binders): Stop special-casing
3021                        // const params to error out here.
3022                        if self.r.tcx.features().non_lifetime_binders()
3023                            && matches!(param.kind, GenericParamKind::Type { .. })
3024                        {
3025                            Res::Def(def_kind, def_id.to_def_id())
3026                        } else {
3027                            Res::Err
3028                        }
3029                    }
3030                    _ => span_bug!(param.ident.span, "Unexpected rib kind {:?}", kind),
3031                };
3032                self.r.record_partial_res(param.id, PartialRes::new(res));
3033                rib.bindings.insert(ident, res);
3034            }
3035        }
3036
3037        self.lifetime_ribs.push(function_lifetime_rib);
3038        self.ribs[ValueNS].push(function_value_rib);
3039        self.ribs[TypeNS].push(function_type_rib);
3040
3041        f(self);
3042
3043        self.ribs[TypeNS].pop();
3044        self.ribs[ValueNS].pop();
3045        let function_lifetime_rib = self.lifetime_ribs.pop().unwrap();
3046
3047        // Do not account for the parameters we just bound for function lifetime elision.
3048        if let Some(ref mut candidates) = self.lifetime_elision_candidates {
3049            for (_, res) in function_lifetime_rib.bindings.values() {
3050                candidates.retain(|(r, _)| r != res);
3051            }
3052        }
3053
3054        if let LifetimeBinderKind::BareFnType
3055        | LifetimeBinderKind::WhereBound
3056        | LifetimeBinderKind::Function
3057        | LifetimeBinderKind::ImplBlock = generics_kind
3058        {
3059            self.maybe_report_lifetime_uses(generics_span, params)
3060        }
3061    }
3062
3063    fn with_label_rib(&mut self, kind: RibKind<'ra>, f: impl FnOnce(&mut Self)) {
3064        self.label_ribs.push(Rib::new(kind));
3065        f(self);
3066        self.label_ribs.pop();
3067    }
3068
3069    fn with_static_rib(&mut self, def_kind: DefKind, f: impl FnOnce(&mut Self)) {
3070        let kind = RibKind::Item(HasGenericParams::No, def_kind);
3071        self.with_rib(ValueNS, kind, |this| this.with_rib(TypeNS, kind, f))
3072    }
3073
3074    // HACK(min_const_generics, generic_const_exprs): We
3075    // want to keep allowing `[0; size_of::<*mut T>()]`
3076    // with a future compat lint for now. We do this by adding an
3077    // additional special case for repeat expressions.
3078    //
3079    // Note that we intentionally still forbid `[0; N + 1]` during
3080    // name resolution so that we don't extend the future
3081    // compat lint to new cases.
3082    #[instrument(level = "debug", skip(self, f))]
3083    fn with_constant_rib(
3084        &mut self,
3085        is_repeat: IsRepeatExpr,
3086        may_use_generics: ConstantHasGenerics,
3087        item: Option<(Ident, ConstantItemKind)>,
3088        f: impl FnOnce(&mut Self),
3089    ) {
3090        let f = |this: &mut Self| {
3091            this.with_rib(ValueNS, RibKind::ConstantItem(may_use_generics, item), |this| {
3092                this.with_rib(
3093                    TypeNS,
3094                    RibKind::ConstantItem(
3095                        may_use_generics.force_yes_if(is_repeat == IsRepeatExpr::Yes),
3096                        item,
3097                    ),
3098                    |this| {
3099                        this.with_label_rib(RibKind::ConstantItem(may_use_generics, item), f);
3100                    },
3101                )
3102            })
3103        };
3104
3105        if let ConstantHasGenerics::No(cause) = may_use_generics {
3106            self.with_lifetime_rib(LifetimeRibKind::ConcreteAnonConst(cause), f)
3107        } else {
3108            f(self)
3109        }
3110    }
3111
3112    fn with_current_self_type<T>(&mut self, self_type: &Ty, f: impl FnOnce(&mut Self) -> T) -> T {
3113        // Handle nested impls (inside fn bodies)
3114        let previous_value =
3115            replace(&mut self.diag_metadata.current_self_type, Some(self_type.clone()));
3116        let result = f(self);
3117        self.diag_metadata.current_self_type = previous_value;
3118        result
3119    }
3120
3121    fn with_current_self_item<T>(&mut self, self_item: &Item, f: impl FnOnce(&mut Self) -> T) -> T {
3122        let previous_value = replace(&mut self.diag_metadata.current_self_item, Some(self_item.id));
3123        let result = f(self);
3124        self.diag_metadata.current_self_item = previous_value;
3125        result
3126    }
3127
3128    /// When evaluating a `trait` use its associated types' idents for suggestions in E0412.
3129    fn resolve_trait_items(&mut self, trait_items: &'ast [P<AssocItem>]) {
3130        let trait_assoc_items =
3131            replace(&mut self.diag_metadata.current_trait_assoc_items, Some(trait_items));
3132
3133        let walk_assoc_item =
3134            |this: &mut Self, generics: &Generics, kind, item: &'ast AssocItem| {
3135                this.with_generic_param_rib(
3136                    &generics.params,
3137                    RibKind::AssocItem,
3138                    LifetimeRibKind::Generics { binder: item.id, span: generics.span, kind },
3139                    |this| visit::walk_assoc_item(this, item, AssocCtxt::Trait),
3140                );
3141            };
3142
3143        for item in trait_items {
3144            self.resolve_doc_links(&item.attrs, MaybeExported::Ok(item.id));
3145            match &item.kind {
3146                AssocItemKind::Const(box ast::ConstItem {
3147                    generics,
3148                    ty,
3149                    expr,
3150                    define_opaque,
3151                    ..
3152                }) => {
3153                    self.with_generic_param_rib(
3154                        &generics.params,
3155                        RibKind::AssocItem,
3156                        LifetimeRibKind::Generics {
3157                            binder: item.id,
3158                            span: generics.span,
3159                            kind: LifetimeBinderKind::ConstItem,
3160                        },
3161                        |this| {
3162                            this.with_lifetime_rib(
3163                                LifetimeRibKind::StaticIfNoLifetimeInScope {
3164                                    lint_id: item.id,
3165                                    emit_lint: false,
3166                                },
3167                                |this| {
3168                                    this.visit_generics(generics);
3169                                    this.visit_ty(ty);
3170
3171                                    // Only impose the restrictions of `ConstRibKind` for an
3172                                    // actual constant expression in a provided default.
3173                                    if let Some(expr) = expr {
3174                                        // We allow arbitrary const expressions inside of associated consts,
3175                                        // even if they are potentially not const evaluatable.
3176                                        //
3177                                        // Type parameters can already be used and as associated consts are
3178                                        // not used as part of the type system, this is far less surprising.
3179                                        this.resolve_const_body(expr, None);
3180                                    }
3181                                },
3182                            )
3183                        },
3184                    );
3185
3186                    self.resolve_define_opaques(define_opaque);
3187                }
3188                AssocItemKind::Fn(box Fn { generics, define_opaque, .. }) => {
3189                    walk_assoc_item(self, generics, LifetimeBinderKind::Function, item);
3190
3191                    self.resolve_define_opaques(define_opaque);
3192                }
3193                AssocItemKind::Delegation(delegation) => {
3194                    self.with_generic_param_rib(
3195                        &[],
3196                        RibKind::AssocItem,
3197                        LifetimeRibKind::Generics {
3198                            binder: item.id,
3199                            kind: LifetimeBinderKind::Function,
3200                            span: delegation.path.segments.last().unwrap().ident.span,
3201                        },
3202                        |this| this.resolve_delegation(delegation),
3203                    );
3204                }
3205                AssocItemKind::Type(box TyAlias { generics, .. }) => self
3206                    .with_lifetime_rib(LifetimeRibKind::AnonymousReportError, |this| {
3207                        walk_assoc_item(this, generics, LifetimeBinderKind::Item, item)
3208                    }),
3209                AssocItemKind::MacCall(_) | AssocItemKind::DelegationMac(..) => {
3210                    panic!("unexpanded macro in resolve!")
3211                }
3212            };
3213        }
3214
3215        self.diag_metadata.current_trait_assoc_items = trait_assoc_items;
3216    }
3217
3218    /// This is called to resolve a trait reference from an `impl` (i.e., `impl Trait for Foo`).
3219    fn with_optional_trait_ref<T>(
3220        &mut self,
3221        opt_trait_ref: Option<&TraitRef>,
3222        self_type: &'ast Ty,
3223        f: impl FnOnce(&mut Self, Option<DefId>) -> T,
3224    ) -> T {
3225        let mut new_val = None;
3226        let mut new_id = None;
3227        if let Some(trait_ref) = opt_trait_ref {
3228            let path: Vec<_> = Segment::from_path(&trait_ref.path);
3229            self.diag_metadata.currently_processing_impl_trait =
3230                Some((trait_ref.clone(), self_type.clone()));
3231            let res = self.smart_resolve_path_fragment(
3232                &None,
3233                &path,
3234                PathSource::Trait(AliasPossibility::No),
3235                Finalize::new(trait_ref.ref_id, trait_ref.path.span),
3236                RecordPartialRes::Yes,
3237                None,
3238            );
3239            self.diag_metadata.currently_processing_impl_trait = None;
3240            if let Some(def_id) = res.expect_full_res().opt_def_id() {
3241                new_id = Some(def_id);
3242                new_val = Some((self.r.expect_module(def_id), trait_ref.clone()));
3243            }
3244        }
3245        let original_trait_ref = replace(&mut self.current_trait_ref, new_val);
3246        let result = f(self, new_id);
3247        self.current_trait_ref = original_trait_ref;
3248        result
3249    }
3250
3251    fn with_self_rib_ns(&mut self, ns: Namespace, self_res: Res, f: impl FnOnce(&mut Self)) {
3252        let mut self_type_rib = Rib::new(RibKind::Normal);
3253
3254        // Plain insert (no renaming, since types are not currently hygienic)
3255        self_type_rib.bindings.insert(Ident::with_dummy_span(kw::SelfUpper), self_res);
3256        self.ribs[ns].push(self_type_rib);
3257        f(self);
3258        self.ribs[ns].pop();
3259    }
3260
3261    fn with_self_rib(&mut self, self_res: Res, f: impl FnOnce(&mut Self)) {
3262        self.with_self_rib_ns(TypeNS, self_res, f)
3263    }
3264
3265    fn resolve_implementation(
3266        &mut self,
3267        attrs: &[ast::Attribute],
3268        generics: &'ast Generics,
3269        opt_trait_reference: &'ast Option<TraitRef>,
3270        self_type: &'ast Ty,
3271        item_id: NodeId,
3272        impl_items: &'ast [P<AssocItem>],
3273    ) {
3274        debug!("resolve_implementation");
3275        // If applicable, create a rib for the type parameters.
3276        self.with_generic_param_rib(
3277            &generics.params,
3278            RibKind::Item(HasGenericParams::Yes(generics.span), self.r.local_def_kind(item_id)),
3279            LifetimeRibKind::Generics {
3280                span: generics.span,
3281                binder: item_id,
3282                kind: LifetimeBinderKind::ImplBlock,
3283            },
3284            |this| {
3285                // Dummy self type for better errors if `Self` is used in the trait path.
3286                this.with_self_rib(Res::SelfTyParam { trait_: LOCAL_CRATE.as_def_id() }, |this| {
3287                    this.with_lifetime_rib(
3288                        LifetimeRibKind::AnonymousCreateParameter {
3289                            binder: item_id,
3290                            report_in_path: true
3291                        },
3292                        |this| {
3293                            // Resolve the trait reference, if necessary.
3294                            this.with_optional_trait_ref(
3295                                opt_trait_reference.as_ref(),
3296                                self_type,
3297                                |this, trait_id| {
3298                                    this.resolve_doc_links(attrs, MaybeExported::Impl(trait_id));
3299
3300                                    let item_def_id = this.r.local_def_id(item_id);
3301
3302                                    // Register the trait definitions from here.
3303                                    if let Some(trait_id) = trait_id {
3304                                        this.r
3305                                            .trait_impls
3306                                            .entry(trait_id)
3307                                            .or_default()
3308                                            .push(item_def_id);
3309                                    }
3310
3311                                    let item_def_id = item_def_id.to_def_id();
3312                                    let res = Res::SelfTyAlias {
3313                                        alias_to: item_def_id,
3314                                        forbid_generic: false,
3315                                        is_trait_impl: trait_id.is_some()
3316                                    };
3317                                    this.with_self_rib(res, |this| {
3318                                        if let Some(trait_ref) = opt_trait_reference.as_ref() {
3319                                            // Resolve type arguments in the trait path.
3320                                            visit::walk_trait_ref(this, trait_ref);
3321                                        }
3322                                        // Resolve the self type.
3323                                        this.visit_ty(self_type);
3324                                        // Resolve the generic parameters.
3325                                        this.visit_generics(generics);
3326
3327                                        // Resolve the items within the impl.
3328                                        this.with_current_self_type(self_type, |this| {
3329                                            this.with_self_rib_ns(ValueNS, Res::SelfCtor(item_def_id), |this| {
3330                                                debug!("resolve_implementation with_self_rib_ns(ValueNS, ...)");
3331                                                let mut seen_trait_items = Default::default();
3332                                                for item in impl_items {
3333                                                    this.resolve_impl_item(&**item, &mut seen_trait_items, trait_id);
3334                                                }
3335                                            });
3336                                        });
3337                                    });
3338                                },
3339                            )
3340                        },
3341                    );
3342                });
3343            },
3344        );
3345    }
3346
3347    fn resolve_impl_item(
3348        &mut self,
3349        item: &'ast AssocItem,
3350        seen_trait_items: &mut FxHashMap<DefId, Span>,
3351        trait_id: Option<DefId>,
3352    ) {
3353        use crate::ResolutionError::*;
3354        self.resolve_doc_links(&item.attrs, MaybeExported::ImplItem(trait_id.ok_or(&item.vis)));
3355        match &item.kind {
3356            AssocItemKind::Const(box ast::ConstItem {
3357                ident,
3358                generics,
3359                ty,
3360                expr,
3361                define_opaque,
3362                ..
3363            }) => {
3364                debug!("resolve_implementation AssocItemKind::Const");
3365                self.with_generic_param_rib(
3366                    &generics.params,
3367                    RibKind::AssocItem,
3368                    LifetimeRibKind::Generics {
3369                        binder: item.id,
3370                        span: generics.span,
3371                        kind: LifetimeBinderKind::ConstItem,
3372                    },
3373                    |this| {
3374                        this.with_lifetime_rib(
3375                            // Until these are a hard error, we need to create them within the correct binder,
3376                            // Otherwise the lifetimes of this assoc const think they are lifetimes of the trait.
3377                            LifetimeRibKind::AnonymousCreateParameter {
3378                                binder: item.id,
3379                                report_in_path: true,
3380                            },
3381                            |this| {
3382                                this.with_lifetime_rib(
3383                                    LifetimeRibKind::StaticIfNoLifetimeInScope {
3384                                        lint_id: item.id,
3385                                        // In impls, it's not a hard error yet due to backcompat.
3386                                        emit_lint: true,
3387                                    },
3388                                    |this| {
3389                                        // If this is a trait impl, ensure the const
3390                                        // exists in trait
3391                                        this.check_trait_item(
3392                                            item.id,
3393                                            *ident,
3394                                            &item.kind,
3395                                            ValueNS,
3396                                            item.span,
3397                                            seen_trait_items,
3398                                            |i, s, c| ConstNotMemberOfTrait(i, s, c),
3399                                        );
3400
3401                                        this.visit_generics(generics);
3402                                        this.visit_ty(ty);
3403                                        if let Some(expr) = expr {
3404                                            // We allow arbitrary const expressions inside of associated consts,
3405                                            // even if they are potentially not const evaluatable.
3406                                            //
3407                                            // Type parameters can already be used and as associated consts are
3408                                            // not used as part of the type system, this is far less surprising.
3409                                            this.resolve_const_body(expr, None);
3410                                        }
3411                                    },
3412                                )
3413                            },
3414                        );
3415                    },
3416                );
3417                self.resolve_define_opaques(define_opaque);
3418            }
3419            AssocItemKind::Fn(box Fn { ident, generics, define_opaque, .. }) => {
3420                debug!("resolve_implementation AssocItemKind::Fn");
3421                // We also need a new scope for the impl item type parameters.
3422                self.with_generic_param_rib(
3423                    &generics.params,
3424                    RibKind::AssocItem,
3425                    LifetimeRibKind::Generics {
3426                        binder: item.id,
3427                        span: generics.span,
3428                        kind: LifetimeBinderKind::Function,
3429                    },
3430                    |this| {
3431                        // If this is a trait impl, ensure the method
3432                        // exists in trait
3433                        this.check_trait_item(
3434                            item.id,
3435                            *ident,
3436                            &item.kind,
3437                            ValueNS,
3438                            item.span,
3439                            seen_trait_items,
3440                            |i, s, c| MethodNotMemberOfTrait(i, s, c),
3441                        );
3442
3443                        visit::walk_assoc_item(this, item, AssocCtxt::Impl { of_trait: true })
3444                    },
3445                );
3446
3447                self.resolve_define_opaques(define_opaque);
3448            }
3449            AssocItemKind::Type(box TyAlias { ident, generics, .. }) => {
3450                self.diag_metadata.in_non_gat_assoc_type = Some(generics.params.is_empty());
3451                debug!("resolve_implementation AssocItemKind::Type");
3452                // We also need a new scope for the impl item type parameters.
3453                self.with_generic_param_rib(
3454                    &generics.params,
3455                    RibKind::AssocItem,
3456                    LifetimeRibKind::Generics {
3457                        binder: item.id,
3458                        span: generics.span,
3459                        kind: LifetimeBinderKind::Item,
3460                    },
3461                    |this| {
3462                        this.with_lifetime_rib(LifetimeRibKind::AnonymousReportError, |this| {
3463                            // If this is a trait impl, ensure the type
3464                            // exists in trait
3465                            this.check_trait_item(
3466                                item.id,
3467                                *ident,
3468                                &item.kind,
3469                                TypeNS,
3470                                item.span,
3471                                seen_trait_items,
3472                                |i, s, c| TypeNotMemberOfTrait(i, s, c),
3473                            );
3474
3475                            visit::walk_assoc_item(this, item, AssocCtxt::Impl { of_trait: true })
3476                        });
3477                    },
3478                );
3479                self.diag_metadata.in_non_gat_assoc_type = None;
3480            }
3481            AssocItemKind::Delegation(box delegation) => {
3482                debug!("resolve_implementation AssocItemKind::Delegation");
3483                self.with_generic_param_rib(
3484                    &[],
3485                    RibKind::AssocItem,
3486                    LifetimeRibKind::Generics {
3487                        binder: item.id,
3488                        kind: LifetimeBinderKind::Function,
3489                        span: delegation.path.segments.last().unwrap().ident.span,
3490                    },
3491                    |this| {
3492                        this.check_trait_item(
3493                            item.id,
3494                            delegation.ident,
3495                            &item.kind,
3496                            ValueNS,
3497                            item.span,
3498                            seen_trait_items,
3499                            |i, s, c| MethodNotMemberOfTrait(i, s, c),
3500                        );
3501
3502                        this.resolve_delegation(delegation)
3503                    },
3504                );
3505            }
3506            AssocItemKind::MacCall(_) | AssocItemKind::DelegationMac(..) => {
3507                panic!("unexpanded macro in resolve!")
3508            }
3509        }
3510    }
3511
3512    fn check_trait_item<F>(
3513        &mut self,
3514        id: NodeId,
3515        mut ident: Ident,
3516        kind: &AssocItemKind,
3517        ns: Namespace,
3518        span: Span,
3519        seen_trait_items: &mut FxHashMap<DefId, Span>,
3520        err: F,
3521    ) where
3522        F: FnOnce(Ident, String, Option<Symbol>) -> ResolutionError<'ra>,
3523    {
3524        // If there is a TraitRef in scope for an impl, then the method must be in the trait.
3525        let Some((module, _)) = self.current_trait_ref else {
3526            return;
3527        };
3528        ident.span.normalize_to_macros_2_0_and_adjust(module.expansion);
3529        let key = BindingKey::new(ident, ns);
3530        let mut binding = self.r.resolution(module, key).try_borrow().ok().and_then(|r| r.binding);
3531        debug!(?binding);
3532        if binding.is_none() {
3533            // We could not find the trait item in the correct namespace.
3534            // Check the other namespace to report an error.
3535            let ns = match ns {
3536                ValueNS => TypeNS,
3537                TypeNS => ValueNS,
3538                _ => ns,
3539            };
3540            let key = BindingKey::new(ident, ns);
3541            binding = self.r.resolution(module, key).try_borrow().ok().and_then(|r| r.binding);
3542            debug!(?binding);
3543        }
3544
3545        let feed_visibility = |this: &mut Self, def_id| {
3546            let vis = this.r.tcx.visibility(def_id);
3547            let vis = if vis.is_visible_locally() {
3548                vis.expect_local()
3549            } else {
3550                this.r.dcx().span_delayed_bug(
3551                    span,
3552                    "error should be emitted when an unexpected trait item is used",
3553                );
3554                rustc_middle::ty::Visibility::Public
3555            };
3556            this.r.feed_visibility(this.r.feed(id), vis);
3557        };
3558
3559        let Some(binding) = binding else {
3560            // We could not find the method: report an error.
3561            let candidate = self.find_similarly_named_assoc_item(ident.name, kind);
3562            let path = &self.current_trait_ref.as_ref().unwrap().1.path;
3563            let path_names = path_names_to_string(path);
3564            self.report_error(span, err(ident, path_names, candidate));
3565            feed_visibility(self, module.def_id());
3566            return;
3567        };
3568
3569        let res = binding.res();
3570        let Res::Def(def_kind, id_in_trait) = res else { bug!() };
3571        feed_visibility(self, id_in_trait);
3572
3573        match seen_trait_items.entry(id_in_trait) {
3574            Entry::Occupied(entry) => {
3575                self.report_error(
3576                    span,
3577                    ResolutionError::TraitImplDuplicate {
3578                        name: ident,
3579                        old_span: *entry.get(),
3580                        trait_item_span: binding.span,
3581                    },
3582                );
3583                return;
3584            }
3585            Entry::Vacant(entry) => {
3586                entry.insert(span);
3587            }
3588        };
3589
3590        match (def_kind, kind) {
3591            (DefKind::AssocTy, AssocItemKind::Type(..))
3592            | (DefKind::AssocFn, AssocItemKind::Fn(..))
3593            | (DefKind::AssocConst, AssocItemKind::Const(..))
3594            | (DefKind::AssocFn, AssocItemKind::Delegation(..)) => {
3595                self.r.record_partial_res(id, PartialRes::new(res));
3596                return;
3597            }
3598            _ => {}
3599        }
3600
3601        // The method kind does not correspond to what appeared in the trait, report.
3602        let path = &self.current_trait_ref.as_ref().unwrap().1.path;
3603        let (code, kind) = match kind {
3604            AssocItemKind::Const(..) => (E0323, "const"),
3605            AssocItemKind::Fn(..) => (E0324, "method"),
3606            AssocItemKind::Type(..) => (E0325, "type"),
3607            AssocItemKind::Delegation(..) => (E0324, "method"),
3608            AssocItemKind::MacCall(..) | AssocItemKind::DelegationMac(..) => {
3609                span_bug!(span, "unexpanded macro")
3610            }
3611        };
3612        let trait_path = path_names_to_string(path);
3613        self.report_error(
3614            span,
3615            ResolutionError::TraitImplMismatch {
3616                name: ident,
3617                kind,
3618                code,
3619                trait_path,
3620                trait_item_span: binding.span,
3621            },
3622        );
3623    }
3624
3625    fn resolve_const_body(&mut self, expr: &'ast Expr, item: Option<(Ident, ConstantItemKind)>) {
3626        self.with_lifetime_rib(LifetimeRibKind::Elided(LifetimeRes::Infer), |this| {
3627            this.with_constant_rib(IsRepeatExpr::No, ConstantHasGenerics::Yes, item, |this| {
3628                this.visit_expr(expr)
3629            });
3630        })
3631    }
3632
3633    fn resolve_delegation(&mut self, delegation: &'ast Delegation) {
3634        self.smart_resolve_path(
3635            delegation.id,
3636            &delegation.qself,
3637            &delegation.path,
3638            PathSource::Delegation,
3639        );
3640        if let Some(qself) = &delegation.qself {
3641            self.visit_ty(&qself.ty);
3642        }
3643        self.visit_path(&delegation.path, delegation.id);
3644        let Some(body) = &delegation.body else { return };
3645        self.with_rib(ValueNS, RibKind::FnOrCoroutine, |this| {
3646            let span = delegation.path.segments.last().unwrap().ident.span;
3647            let ident = Ident::new(kw::SelfLower, span.normalize_to_macro_rules());
3648            let res = Res::Local(delegation.id);
3649            this.innermost_rib_bindings(ValueNS).insert(ident, res);
3650            this.visit_block(body);
3651        });
3652    }
3653
3654    fn resolve_params(&mut self, params: &'ast [Param]) {
3655        let mut bindings = smallvec![(PatBoundCtx::Product, Default::default())];
3656        self.with_lifetime_rib(LifetimeRibKind::Elided(LifetimeRes::Infer), |this| {
3657            for Param { pat, .. } in params {
3658                this.resolve_pattern(pat, PatternSource::FnParam, &mut bindings);
3659            }
3660            this.apply_pattern_bindings(bindings);
3661        });
3662        for Param { ty, .. } in params {
3663            self.visit_ty(ty);
3664        }
3665    }
3666
3667    fn resolve_local(&mut self, local: &'ast Local) {
3668        debug!("resolving local ({:?})", local);
3669        // Resolve the type.
3670        visit_opt!(self, visit_ty, &local.ty);
3671
3672        // Resolve the initializer.
3673        if let Some((init, els)) = local.kind.init_else_opt() {
3674            self.visit_expr(init);
3675
3676            // Resolve the `else` block
3677            if let Some(els) = els {
3678                self.visit_block(els);
3679            }
3680        }
3681
3682        // Resolve the pattern.
3683        self.resolve_pattern_top(&local.pat, PatternSource::Let);
3684    }
3685
3686    /// Build a map from pattern identifiers to binding-info's, and check the bindings are
3687    /// consistent when encountering or-patterns and never patterns.
3688    /// This is done hygienically: this could arise for a macro that expands into an or-pattern
3689    /// where one 'x' was from the user and one 'x' came from the macro.
3690    ///
3691    /// A never pattern by definition indicates an unreachable case. For example, matching on
3692    /// `Result<T, &!>` could look like:
3693    /// ```rust
3694    /// # #![feature(never_type)]
3695    /// # #![feature(never_patterns)]
3696    /// # fn bar(_x: u32) {}
3697    /// let foo: Result<u32, &!> = Ok(0);
3698    /// match foo {
3699    ///     Ok(x) => bar(x),
3700    ///     Err(&!),
3701    /// }
3702    /// ```
3703    /// This extends to product types: `(x, !)` is likewise unreachable. So it doesn't make sense to
3704    /// have a binding here, and we tell the user to use `_` instead.
3705    fn compute_and_check_binding_map(
3706        &mut self,
3707        pat: &Pat,
3708    ) -> Result<FxIndexMap<Ident, BindingInfo>, IsNeverPattern> {
3709        let mut binding_map = FxIndexMap::default();
3710        let mut is_never_pat = false;
3711
3712        pat.walk(&mut |pat| {
3713            match pat.kind {
3714                PatKind::Ident(annotation, ident, ref sub_pat)
3715                    if sub_pat.is_some() || self.is_base_res_local(pat.id) =>
3716                {
3717                    binding_map.insert(ident, BindingInfo { span: ident.span, annotation });
3718                }
3719                PatKind::Or(ref ps) => {
3720                    // Check the consistency of this or-pattern and
3721                    // then add all bindings to the larger map.
3722                    match self.compute_and_check_or_pat_binding_map(ps) {
3723                        Ok(bm) => binding_map.extend(bm),
3724                        Err(IsNeverPattern) => is_never_pat = true,
3725                    }
3726                    return false;
3727                }
3728                PatKind::Never => is_never_pat = true,
3729                _ => {}
3730            }
3731
3732            true
3733        });
3734
3735        if is_never_pat {
3736            for (_, binding) in binding_map {
3737                self.report_error(binding.span, ResolutionError::BindingInNeverPattern);
3738            }
3739            Err(IsNeverPattern)
3740        } else {
3741            Ok(binding_map)
3742        }
3743    }
3744
3745    fn is_base_res_local(&self, nid: NodeId) -> bool {
3746        matches!(
3747            self.r.partial_res_map.get(&nid).map(|res| res.expect_full_res()),
3748            Some(Res::Local(..))
3749        )
3750    }
3751
3752    /// Compute the binding map for an or-pattern. Checks that all of the arms in the or-pattern
3753    /// have exactly the same set of bindings, with the same binding modes for each.
3754    /// Returns the computed binding map and a boolean indicating whether the pattern is a never
3755    /// pattern.
3756    ///
3757    /// A never pattern by definition indicates an unreachable case. For example, destructuring a
3758    /// `Result<T, &!>` could look like:
3759    /// ```rust
3760    /// # #![feature(never_type)]
3761    /// # #![feature(never_patterns)]
3762    /// # fn foo() -> Result<bool, &'static !> { Ok(true) }
3763    /// let (Ok(x) | Err(&!)) = foo();
3764    /// # let _ = x;
3765    /// ```
3766    /// Because the `Err(&!)` branch is never reached, it does not need to have the same bindings as
3767    /// the other branches of the or-pattern. So we must ignore never pattern when checking the
3768    /// bindings of an or-pattern.
3769    /// Moreover, if all the subpatterns are never patterns (e.g. `Ok(!) | Err(!)`), then the
3770    /// pattern as a whole counts as a never pattern (since it's definitionallly unreachable).
3771    fn compute_and_check_or_pat_binding_map(
3772        &mut self,
3773        pats: &[P<Pat>],
3774    ) -> Result<FxIndexMap<Ident, BindingInfo>, IsNeverPattern> {
3775        let mut missing_vars = FxIndexMap::default();
3776        let mut inconsistent_vars = FxIndexMap::default();
3777
3778        // 1) Compute the binding maps of all arms; we must ignore never patterns here.
3779        let not_never_pats = pats
3780            .iter()
3781            .filter_map(|pat| {
3782                let binding_map = self.compute_and_check_binding_map(pat).ok()?;
3783                Some((binding_map, pat))
3784            })
3785            .collect::<Vec<_>>();
3786
3787        // 2) Record any missing bindings or binding mode inconsistencies.
3788        for (map_outer, pat_outer) in not_never_pats.iter() {
3789            // Check against all arms except for the same pattern which is always self-consistent.
3790            let inners = not_never_pats
3791                .iter()
3792                .filter(|(_, pat)| pat.id != pat_outer.id)
3793                .flat_map(|(map, _)| map);
3794
3795            for (&name, binding_inner) in inners {
3796                match map_outer.get(&name) {
3797                    None => {
3798                        // The inner binding is missing in the outer.
3799                        let binding_error =
3800                            missing_vars.entry(name).or_insert_with(|| BindingError {
3801                                name,
3802                                origin: BTreeSet::new(),
3803                                target: BTreeSet::new(),
3804                                could_be_path: name.as_str().starts_with(char::is_uppercase),
3805                            });
3806                        binding_error.origin.insert(binding_inner.span);
3807                        binding_error.target.insert(pat_outer.span);
3808                    }
3809                    Some(binding_outer) => {
3810                        if binding_outer.annotation != binding_inner.annotation {
3811                            // The binding modes in the outer and inner bindings differ.
3812                            inconsistent_vars
3813                                .entry(name)
3814                                .or_insert((binding_inner.span, binding_outer.span));
3815                        }
3816                    }
3817                }
3818            }
3819        }
3820
3821        // 3) Report all missing variables we found.
3822        for (name, mut v) in missing_vars {
3823            if inconsistent_vars.contains_key(&name) {
3824                v.could_be_path = false;
3825            }
3826            self.report_error(
3827                *v.origin.iter().next().unwrap(),
3828                ResolutionError::VariableNotBoundInPattern(v, self.parent_scope),
3829            );
3830        }
3831
3832        // 4) Report all inconsistencies in binding modes we found.
3833        for (name, v) in inconsistent_vars {
3834            self.report_error(v.0, ResolutionError::VariableBoundWithDifferentMode(name, v.1));
3835        }
3836
3837        // 5) Bubble up the final binding map.
3838        if not_never_pats.is_empty() {
3839            // All the patterns are never patterns, so the whole or-pattern is one too.
3840            Err(IsNeverPattern)
3841        } else {
3842            let mut binding_map = FxIndexMap::default();
3843            for (bm, _) in not_never_pats {
3844                binding_map.extend(bm);
3845            }
3846            Ok(binding_map)
3847        }
3848    }
3849
3850    /// Check the consistency of bindings wrt or-patterns and never patterns.
3851    fn check_consistent_bindings(&mut self, pat: &'ast Pat) {
3852        let mut is_or_or_never = false;
3853        pat.walk(&mut |pat| match pat.kind {
3854            PatKind::Or(..) | PatKind::Never => {
3855                is_or_or_never = true;
3856                false
3857            }
3858            _ => true,
3859        });
3860        if is_or_or_never {
3861            let _ = self.compute_and_check_binding_map(pat);
3862        }
3863    }
3864
3865    fn resolve_arm(&mut self, arm: &'ast Arm) {
3866        self.with_rib(ValueNS, RibKind::Normal, |this| {
3867            this.resolve_pattern_top(&arm.pat, PatternSource::Match);
3868            visit_opt!(this, visit_expr, &arm.guard);
3869            visit_opt!(this, visit_expr, &arm.body);
3870        });
3871    }
3872
3873    /// Arising from `source`, resolve a top level pattern.
3874    fn resolve_pattern_top(&mut self, pat: &'ast Pat, pat_src: PatternSource) {
3875        let mut bindings = smallvec![(PatBoundCtx::Product, Default::default())];
3876        self.resolve_pattern(pat, pat_src, &mut bindings);
3877        self.apply_pattern_bindings(bindings);
3878    }
3879
3880    /// Apply the bindings from a pattern to the innermost rib of the current scope.
3881    fn apply_pattern_bindings(&mut self, mut pat_bindings: PatternBindings) {
3882        let rib_bindings = self.innermost_rib_bindings(ValueNS);
3883        let Some((_, pat_bindings)) = pat_bindings.pop() else {
3884            bug!("tried applying nonexistent bindings from pattern");
3885        };
3886
3887        if rib_bindings.is_empty() {
3888            // Often, such as for match arms, the bindings are introduced into a new rib.
3889            // In this case, we can move the bindings over directly.
3890            *rib_bindings = pat_bindings;
3891        } else {
3892            rib_bindings.extend(pat_bindings);
3893        }
3894    }
3895
3896    /// Resolve bindings in a pattern. `apply_pattern_bindings` must be called after to introduce
3897    /// the bindings into scope.
3898    fn resolve_pattern(
3899        &mut self,
3900        pat: &'ast Pat,
3901        pat_src: PatternSource,
3902        bindings: &mut PatternBindings,
3903    ) {
3904        // We walk the pattern before declaring the pattern's inner bindings,
3905        // so that we avoid resolving a literal expression to a binding defined
3906        // by the pattern.
3907        // NB: `Self::visit_pat` must be used rather than `visit::walk_pat` to avoid resolving guard
3908        // patterns' guard expressions multiple times (#141265).
3909        self.visit_pat(pat);
3910        self.resolve_pattern_inner(pat, pat_src, bindings);
3911        // This has to happen *after* we determine which pat_idents are variants:
3912        self.check_consistent_bindings(pat);
3913    }
3914
3915    /// Resolve bindings in a pattern. This is a helper to `resolve_pattern`.
3916    ///
3917    /// ### `bindings`
3918    ///
3919    /// A stack of sets of bindings accumulated.
3920    ///
3921    /// In each set, `PatBoundCtx::Product` denotes that a found binding in it should
3922    /// be interpreted as re-binding an already bound binding. This results in an error.
3923    /// Meanwhile, `PatBound::Or` denotes that a found binding in the set should result
3924    /// in reusing this binding rather than creating a fresh one.
3925    ///
3926    /// When called at the top level, the stack must have a single element
3927    /// with `PatBound::Product`. Otherwise, pushing to the stack happens as
3928    /// or-patterns (`p_0 | ... | p_n`) are encountered and the context needs
3929    /// to be switched to `PatBoundCtx::Or` and then `PatBoundCtx::Product` for each `p_i`.
3930    /// When each `p_i` has been dealt with, the top set is merged with its parent.
3931    /// When a whole or-pattern has been dealt with, the thing happens.
3932    ///
3933    /// See the implementation and `fresh_binding` for more details.
3934    #[tracing::instrument(skip(self, bindings), level = "debug")]
3935    fn resolve_pattern_inner(
3936        &mut self,
3937        pat: &'ast Pat,
3938        pat_src: PatternSource,
3939        bindings: &mut PatternBindings,
3940    ) {
3941        // Visit all direct subpatterns of this pattern.
3942        pat.walk(&mut |pat| {
3943            match pat.kind {
3944                PatKind::Ident(bmode, ident, ref sub) => {
3945                    // First try to resolve the identifier as some existing entity,
3946                    // then fall back to a fresh binding.
3947                    let has_sub = sub.is_some();
3948                    let res = self
3949                        .try_resolve_as_non_binding(pat_src, bmode, ident, has_sub)
3950                        .unwrap_or_else(|| self.fresh_binding(ident, pat.id, pat_src, bindings));
3951                    self.r.record_partial_res(pat.id, PartialRes::new(res));
3952                    self.r.record_pat_span(pat.id, pat.span);
3953                }
3954                PatKind::TupleStruct(ref qself, ref path, ref sub_patterns) => {
3955                    self.smart_resolve_path(
3956                        pat.id,
3957                        qself,
3958                        path,
3959                        PathSource::TupleStruct(
3960                            pat.span,
3961                            self.r.arenas.alloc_pattern_spans(sub_patterns.iter().map(|p| p.span)),
3962                        ),
3963                    );
3964                }
3965                PatKind::Path(ref qself, ref path) => {
3966                    self.smart_resolve_path(pat.id, qself, path, PathSource::Pat);
3967                }
3968                PatKind::Struct(ref qself, ref path, ref _fields, ref rest) => {
3969                    self.smart_resolve_path(pat.id, qself, path, PathSource::Struct);
3970                    self.record_patterns_with_skipped_bindings(pat, rest);
3971                }
3972                PatKind::Or(ref ps) => {
3973                    // Add a new set of bindings to the stack. `Or` here records that when a
3974                    // binding already exists in this set, it should not result in an error because
3975                    // `V1(a) | V2(a)` must be allowed and are checked for consistency later.
3976                    bindings.push((PatBoundCtx::Or, Default::default()));
3977                    for p in ps {
3978                        // Now we need to switch back to a product context so that each
3979                        // part of the or-pattern internally rejects already bound names.
3980                        // For example, `V1(a) | V2(a, a)` and `V1(a, a) | V2(a)` are bad.
3981                        bindings.push((PatBoundCtx::Product, Default::default()));
3982                        self.resolve_pattern_inner(p, pat_src, bindings);
3983                        // Move up the non-overlapping bindings to the or-pattern.
3984                        // Existing bindings just get "merged".
3985                        let collected = bindings.pop().unwrap().1;
3986                        bindings.last_mut().unwrap().1.extend(collected);
3987                    }
3988                    // This or-pattern itself can itself be part of a product,
3989                    // e.g. `(V1(a) | V2(a), a)` or `(a, V1(a) | V2(a))`.
3990                    // Both cases bind `a` again in a product pattern and must be rejected.
3991                    let collected = bindings.pop().unwrap().1;
3992                    bindings.last_mut().unwrap().1.extend(collected);
3993
3994                    // Prevent visiting `ps` as we've already done so above.
3995                    return false;
3996                }
3997                PatKind::Guard(ref subpat, ref guard) => {
3998                    // Add a new set of bindings to the stack to collect bindings in `subpat`.
3999                    bindings.push((PatBoundCtx::Product, Default::default()));
4000                    // Resolving `subpat` adds bindings onto the newly-pushed context. After, the
4001                    // total number of contexts on the stack should be the same as before.
4002                    let binding_ctx_stack_len = bindings.len();
4003                    self.resolve_pattern_inner(subpat, pat_src, bindings);
4004                    assert_eq!(bindings.len(), binding_ctx_stack_len);
4005                    // These bindings, but none from the surrounding pattern, are visible in the
4006                    // guard; put them in scope and resolve `guard`.
4007                    let subpat_bindings = bindings.pop().unwrap().1;
4008                    self.with_rib(ValueNS, RibKind::Normal, |this| {
4009                        *this.innermost_rib_bindings(ValueNS) = subpat_bindings.clone();
4010                        this.resolve_expr(guard, None);
4011                    });
4012                    // Propagate the subpattern's bindings upwards.
4013                    // FIXME(guard_patterns): For `if let` guards, we'll also need to get the
4014                    // bindings introduced by the guard from its rib and propagate them upwards.
4015                    // This will require checking the identifiers for overlaps with `bindings`, like
4016                    // what `fresh_binding` does (ideally sharing its logic). To keep them separate
4017                    // from `subpat_bindings`, we can introduce a fresh rib for the guard.
4018                    bindings.last_mut().unwrap().1.extend(subpat_bindings);
4019                    // Prevent visiting `subpat` as we've already done so above.
4020                    return false;
4021                }
4022                _ => {}
4023            }
4024            true
4025        });
4026    }
4027
4028    fn record_patterns_with_skipped_bindings(&mut self, pat: &Pat, rest: &ast::PatFieldsRest) {
4029        match rest {
4030            ast::PatFieldsRest::Rest | ast::PatFieldsRest::Recovered(_) => {
4031                // Record that the pattern doesn't introduce all the bindings it could.
4032                if let Some(partial_res) = self.r.partial_res_map.get(&pat.id)
4033                    && let Some(res) = partial_res.full_res()
4034                    && let Some(def_id) = res.opt_def_id()
4035                {
4036                    self.ribs[ValueNS]
4037                        .last_mut()
4038                        .unwrap()
4039                        .patterns_with_skipped_bindings
4040                        .entry(def_id)
4041                        .or_default()
4042                        .push((
4043                            pat.span,
4044                            match rest {
4045                                ast::PatFieldsRest::Recovered(guar) => Err(*guar),
4046                                _ => Ok(()),
4047                            },
4048                        ));
4049                }
4050            }
4051            ast::PatFieldsRest::None => {}
4052        }
4053    }
4054
4055    fn fresh_binding(
4056        &mut self,
4057        ident: Ident,
4058        pat_id: NodeId,
4059        pat_src: PatternSource,
4060        bindings: &mut PatternBindings,
4061    ) -> Res {
4062        // Add the binding to the bindings map, if it doesn't already exist.
4063        // (We must not add it if it's in the bindings map because that breaks the assumptions
4064        // later passes make about or-patterns.)
4065        let ident = ident.normalize_to_macro_rules();
4066
4067        // Already bound in a product pattern? e.g. `(a, a)` which is not allowed.
4068        let already_bound_and = bindings
4069            .iter()
4070            .any(|(ctx, map)| *ctx == PatBoundCtx::Product && map.contains_key(&ident));
4071        if already_bound_and {
4072            // Overlap in a product pattern somewhere; report an error.
4073            use ResolutionError::*;
4074            let error = match pat_src {
4075                // `fn f(a: u8, a: u8)`:
4076                PatternSource::FnParam => IdentifierBoundMoreThanOnceInParameterList,
4077                // `Variant(a, a)`:
4078                _ => IdentifierBoundMoreThanOnceInSamePattern,
4079            };
4080            self.report_error(ident.span, error(ident));
4081        }
4082
4083        // Already bound in an or-pattern? e.g. `V1(a) | V2(a)`.
4084        // This is *required* for consistency which is checked later.
4085        let already_bound_or = bindings
4086            .iter()
4087            .find_map(|(ctx, map)| if *ctx == PatBoundCtx::Or { map.get(&ident) } else { None });
4088        let res = if let Some(&res) = already_bound_or {
4089            // `Variant1(a) | Variant2(a)`, ok
4090            // Reuse definition from the first `a`.
4091            res
4092        } else {
4093            // A completely fresh binding is added to the map.
4094            Res::Local(pat_id)
4095        };
4096
4097        // Record as bound.
4098        bindings.last_mut().unwrap().1.insert(ident, res);
4099        res
4100    }
4101
4102    fn innermost_rib_bindings(&mut self, ns: Namespace) -> &mut FxIndexMap<Ident, Res> {
4103        &mut self.ribs[ns].last_mut().unwrap().bindings
4104    }
4105
4106    fn try_resolve_as_non_binding(
4107        &mut self,
4108        pat_src: PatternSource,
4109        ann: BindingMode,
4110        ident: Ident,
4111        has_sub: bool,
4112    ) -> Option<Res> {
4113        // An immutable (no `mut`) by-value (no `ref`) binding pattern without
4114        // a sub pattern (no `@ $pat`) is syntactically ambiguous as it could
4115        // also be interpreted as a path to e.g. a constant, variant, etc.
4116        let is_syntactic_ambiguity = !has_sub && ann == BindingMode::NONE;
4117
4118        let ls_binding = self.maybe_resolve_ident_in_lexical_scope(ident, ValueNS)?;
4119        let (res, binding) = match ls_binding {
4120            LexicalScopeBinding::Item(binding)
4121                if is_syntactic_ambiguity && binding.is_ambiguity_recursive() =>
4122            {
4123                // For ambiguous bindings we don't know all their definitions and cannot check
4124                // whether they can be shadowed by fresh bindings or not, so force an error.
4125                // issues/33118#issuecomment-233962221 (see below) still applies here,
4126                // but we have to ignore it for backward compatibility.
4127                self.r.record_use(ident, binding, Used::Other);
4128                return None;
4129            }
4130            LexicalScopeBinding::Item(binding) => (binding.res(), Some(binding)),
4131            LexicalScopeBinding::Res(res) => (res, None),
4132        };
4133
4134        match res {
4135            Res::SelfCtor(_) // See #70549.
4136            | Res::Def(
4137                DefKind::Ctor(_, CtorKind::Const) | DefKind::Const | DefKind::AssocConst | DefKind::ConstParam,
4138                _,
4139            ) if is_syntactic_ambiguity => {
4140                // Disambiguate in favor of a unit struct/variant or constant pattern.
4141                if let Some(binding) = binding {
4142                    self.r.record_use(ident, binding, Used::Other);
4143                }
4144                Some(res)
4145            }
4146            Res::Def(DefKind::Ctor(..) | DefKind::Const | DefKind::AssocConst | DefKind::Static { .. }, _) => {
4147                // This is unambiguously a fresh binding, either syntactically
4148                // (e.g., `IDENT @ PAT` or `ref IDENT`) or because `IDENT` resolves
4149                // to something unusable as a pattern (e.g., constructor function),
4150                // but we still conservatively report an error, see
4151                // issues/33118#issuecomment-233962221 for one reason why.
4152                let binding = binding.expect("no binding for a ctor or static");
4153                self.report_error(
4154                    ident.span,
4155                    ResolutionError::BindingShadowsSomethingUnacceptable {
4156                        shadowing_binding: pat_src,
4157                        name: ident.name,
4158                        participle: if binding.is_import() { "imported" } else { "defined" },
4159                        article: binding.res().article(),
4160                        shadowed_binding: binding.res(),
4161                        shadowed_binding_span: binding.span,
4162                    },
4163                );
4164                None
4165            }
4166            Res::Def(DefKind::ConstParam, def_id) => {
4167                // Same as for DefKind::Const above, but here, `binding` is `None`, so we
4168                // have to construct the error differently
4169                self.report_error(
4170                    ident.span,
4171                    ResolutionError::BindingShadowsSomethingUnacceptable {
4172                        shadowing_binding: pat_src,
4173                        name: ident.name,
4174                        participle: "defined",
4175                        article: res.article(),
4176                        shadowed_binding: res,
4177                        shadowed_binding_span: self.r.def_span(def_id),
4178                    }
4179                );
4180                None
4181            }
4182            Res::Def(DefKind::Fn | DefKind::AssocFn, _) | Res::Local(..) | Res::Err => {
4183                // These entities are explicitly allowed to be shadowed by fresh bindings.
4184                None
4185            }
4186            Res::SelfCtor(_) => {
4187                // We resolve `Self` in pattern position as an ident sometimes during recovery,
4188                // so delay a bug instead of ICEing.
4189                self.r.dcx().span_delayed_bug(
4190                    ident.span,
4191                    "unexpected `SelfCtor` in pattern, expected identifier"
4192                );
4193                None
4194            }
4195            _ => span_bug!(
4196                ident.span,
4197                "unexpected resolution for an identifier in pattern: {:?}",
4198                res,
4199            ),
4200        }
4201    }
4202
4203    // High-level and context dependent path resolution routine.
4204    // Resolves the path and records the resolution into definition map.
4205    // If resolution fails tries several techniques to find likely
4206    // resolution candidates, suggest imports or other help, and report
4207    // errors in user friendly way.
4208    fn smart_resolve_path(
4209        &mut self,
4210        id: NodeId,
4211        qself: &Option<P<QSelf>>,
4212        path: &Path,
4213        source: PathSource<'ast, '_>,
4214    ) {
4215        self.smart_resolve_path_fragment(
4216            qself,
4217            &Segment::from_path(path),
4218            source,
4219            Finalize::new(id, path.span),
4220            RecordPartialRes::Yes,
4221            None,
4222        );
4223    }
4224
4225    #[instrument(level = "debug", skip(self))]
4226    fn smart_resolve_path_fragment(
4227        &mut self,
4228        qself: &Option<P<QSelf>>,
4229        path: &[Segment],
4230        source: PathSource<'ast, '_>,
4231        finalize: Finalize,
4232        record_partial_res: RecordPartialRes,
4233        parent_qself: Option<&QSelf>,
4234    ) -> PartialRes {
4235        let ns = source.namespace();
4236
4237        let Finalize { node_id, path_span, .. } = finalize;
4238        let report_errors = |this: &mut Self, res: Option<Res>| {
4239            if this.should_report_errs() {
4240                let (err, candidates) = this.smart_resolve_report_errors(
4241                    path,
4242                    None,
4243                    path_span,
4244                    source,
4245                    res,
4246                    parent_qself,
4247                );
4248
4249                let def_id = this.parent_scope.module.nearest_parent_mod();
4250                let instead = res.is_some();
4251                let suggestion = if let Some((start, end)) = this.diag_metadata.in_range
4252                    && path[0].ident.span.lo() == end.span.lo()
4253                    && !matches!(start.kind, ExprKind::Lit(_))
4254                {
4255                    let mut sugg = ".";
4256                    let mut span = start.span.between(end.span);
4257                    if span.lo() + BytePos(2) == span.hi() {
4258                        // There's no space between the start, the range op and the end, suggest
4259                        // removal which will look better.
4260                        span = span.with_lo(span.lo() + BytePos(1));
4261                        sugg = "";
4262                    }
4263                    Some((
4264                        span,
4265                        "you might have meant to write `.` instead of `..`",
4266                        sugg.to_string(),
4267                        Applicability::MaybeIncorrect,
4268                    ))
4269                } else if res.is_none()
4270                    && let PathSource::Type
4271                    | PathSource::Expr(_)
4272                    | PathSource::PreciseCapturingArg(..) = source
4273                {
4274                    this.suggest_adding_generic_parameter(path, source)
4275                } else {
4276                    None
4277                };
4278
4279                let ue = UseError {
4280                    err,
4281                    candidates,
4282                    def_id,
4283                    instead,
4284                    suggestion,
4285                    path: path.into(),
4286                    is_call: source.is_call(),
4287                };
4288
4289                this.r.use_injections.push(ue);
4290            }
4291
4292            PartialRes::new(Res::Err)
4293        };
4294
4295        // For paths originating from calls (like in `HashMap::new()`), tries
4296        // to enrich the plain `failed to resolve: ...` message with hints
4297        // about possible missing imports.
4298        //
4299        // Similar thing, for types, happens in `report_errors` above.
4300        let report_errors_for_call =
4301            |this: &mut Self, parent_err: Spanned<ResolutionError<'ra>>| {
4302                // Before we start looking for candidates, we have to get our hands
4303                // on the type user is trying to perform invocation on; basically:
4304                // we're transforming `HashMap::new` into just `HashMap`.
4305                let (following_seg, prefix_path) = match path.split_last() {
4306                    Some((last, path)) if !path.is_empty() => (Some(last), path),
4307                    _ => return Some(parent_err),
4308                };
4309
4310                let (mut err, candidates) = this.smart_resolve_report_errors(
4311                    prefix_path,
4312                    following_seg,
4313                    path_span,
4314                    PathSource::Type,
4315                    None,
4316                    parent_qself,
4317                );
4318
4319                // There are two different error messages user might receive at
4320                // this point:
4321                // - E0412 cannot find type `{}` in this scope
4322                // - E0433 failed to resolve: use of undeclared type or module `{}`
4323                //
4324                // The first one is emitted for paths in type-position, and the
4325                // latter one - for paths in expression-position.
4326                //
4327                // Thus (since we're in expression-position at this point), not to
4328                // confuse the user, we want to keep the *message* from E0433 (so
4329                // `parent_err`), but we want *hints* from E0412 (so `err`).
4330                //
4331                // And that's what happens below - we're just mixing both messages
4332                // into a single one.
4333                let mut parent_err = this.r.into_struct_error(parent_err.span, parent_err.node);
4334
4335                // overwrite all properties with the parent's error message
4336                err.messages = take(&mut parent_err.messages);
4337                err.code = take(&mut parent_err.code);
4338                swap(&mut err.span, &mut parent_err.span);
4339                err.children = take(&mut parent_err.children);
4340                err.sort_span = parent_err.sort_span;
4341                err.is_lint = parent_err.is_lint.clone();
4342
4343                // merge the parent_err's suggestions with the typo (err's) suggestions
4344                match &mut err.suggestions {
4345                    Suggestions::Enabled(typo_suggestions) => match &mut parent_err.suggestions {
4346                        Suggestions::Enabled(parent_suggestions) => {
4347                            // If both suggestions are enabled, append parent_err's suggestions to err's suggestions.
4348                            typo_suggestions.append(parent_suggestions)
4349                        }
4350                        Suggestions::Sealed(_) | Suggestions::Disabled => {
4351                            // If the parent's suggestions are either sealed or disabled, it signifies that
4352                            // new suggestions cannot be added or removed from the diagnostic. Therefore,
4353                            // we assign both types of suggestions to err's suggestions and discard the
4354                            // existing suggestions in err.
4355                            err.suggestions = std::mem::take(&mut parent_err.suggestions);
4356                        }
4357                    },
4358                    Suggestions::Sealed(_) | Suggestions::Disabled => (),
4359                }
4360
4361                parent_err.cancel();
4362
4363                let def_id = this.parent_scope.module.nearest_parent_mod();
4364
4365                if this.should_report_errs() {
4366                    if candidates.is_empty() {
4367                        if path.len() == 2
4368                            && let [segment] = prefix_path
4369                        {
4370                            // Delay to check whether methond name is an associated function or not
4371                            // ```
4372                            // let foo = Foo {};
4373                            // foo::bar(); // possibly suggest to foo.bar();
4374                            //```
4375                            err.stash(segment.ident.span, rustc_errors::StashKey::CallAssocMethod);
4376                        } else {
4377                            // When there is no suggested imports, we can just emit the error
4378                            // and suggestions immediately. Note that we bypass the usually error
4379                            // reporting routine (ie via `self.r.report_error`) because we need
4380                            // to post-process the `ResolutionError` above.
4381                            err.emit();
4382                        }
4383                    } else {
4384                        // If there are suggested imports, the error reporting is delayed
4385                        this.r.use_injections.push(UseError {
4386                            err,
4387                            candidates,
4388                            def_id,
4389                            instead: false,
4390                            suggestion: None,
4391                            path: prefix_path.into(),
4392                            is_call: source.is_call(),
4393                        });
4394                    }
4395                } else {
4396                    err.cancel();
4397                }
4398
4399                // We don't return `Some(parent_err)` here, because the error will
4400                // be already printed either immediately or as part of the `use` injections
4401                None
4402            };
4403
4404        let partial_res = match self.resolve_qpath_anywhere(
4405            qself,
4406            path,
4407            ns,
4408            path_span,
4409            source.defer_to_typeck(),
4410            finalize,
4411            source,
4412        ) {
4413            Ok(Some(partial_res)) if let Some(res) = partial_res.full_res() => {
4414                // if we also have an associated type that matches the ident, stash a suggestion
4415                if let Some(items) = self.diag_metadata.current_trait_assoc_items
4416                    && let [Segment { ident, .. }] = path
4417                    && items.iter().any(|item| {
4418                        if let AssocItemKind::Type(alias) = &item.kind
4419                            && alias.ident == *ident
4420                        {
4421                            true
4422                        } else {
4423                            false
4424                        }
4425                    })
4426                {
4427                    let mut diag = self.r.tcx.dcx().struct_allow("");
4428                    diag.span_suggestion_verbose(
4429                        path_span.shrink_to_lo(),
4430                        "there is an associated type with the same name",
4431                        "Self::",
4432                        Applicability::MaybeIncorrect,
4433                    );
4434                    diag.stash(path_span, StashKey::AssociatedTypeSuggestion);
4435                }
4436
4437                if source.is_expected(res) || res == Res::Err {
4438                    partial_res
4439                } else {
4440                    report_errors(self, Some(res))
4441                }
4442            }
4443
4444            Ok(Some(partial_res)) if source.defer_to_typeck() => {
4445                // Not fully resolved associated item `T::A::B` or `<T as Tr>::A::B`
4446                // or `<T>::A::B`. If `B` should be resolved in value namespace then
4447                // it needs to be added to the trait map.
4448                if ns == ValueNS {
4449                    let item_name = path.last().unwrap().ident;
4450                    let traits = self.traits_in_scope(item_name, ns);
4451                    self.r.trait_map.insert(node_id, traits);
4452                }
4453
4454                if PrimTy::from_name(path[0].ident.name).is_some() {
4455                    let mut std_path = Vec::with_capacity(1 + path.len());
4456
4457                    std_path.push(Segment::from_ident(Ident::with_dummy_span(sym::std)));
4458                    std_path.extend(path);
4459                    if let PathResult::Module(_) | PathResult::NonModule(_) =
4460                        self.resolve_path(&std_path, Some(ns), None)
4461                    {
4462                        // Check if we wrote `str::from_utf8` instead of `std::str::from_utf8`
4463                        let item_span =
4464                            path.iter().last().map_or(path_span, |segment| segment.ident.span);
4465
4466                        self.r.confused_type_with_std_module.insert(item_span, path_span);
4467                        self.r.confused_type_with_std_module.insert(path_span, path_span);
4468                    }
4469                }
4470
4471                partial_res
4472            }
4473
4474            Err(err) => {
4475                if let Some(err) = report_errors_for_call(self, err) {
4476                    self.report_error(err.span, err.node);
4477                }
4478
4479                PartialRes::new(Res::Err)
4480            }
4481
4482            _ => report_errors(self, None),
4483        };
4484
4485        if record_partial_res == RecordPartialRes::Yes {
4486            // Avoid recording definition of `A::B` in `<T as A>::B::C`.
4487            self.r.record_partial_res(node_id, partial_res);
4488            self.resolve_elided_lifetimes_in_path(partial_res, path, source, path_span);
4489            self.lint_unused_qualifications(path, ns, finalize);
4490        }
4491
4492        partial_res
4493    }
4494
4495    fn self_type_is_available(&mut self) -> bool {
4496        let binding = self
4497            .maybe_resolve_ident_in_lexical_scope(Ident::with_dummy_span(kw::SelfUpper), TypeNS);
4498        if let Some(LexicalScopeBinding::Res(res)) = binding { res != Res::Err } else { false }
4499    }
4500
4501    fn self_value_is_available(&mut self, self_span: Span) -> bool {
4502        let ident = Ident::new(kw::SelfLower, self_span);
4503        let binding = self.maybe_resolve_ident_in_lexical_scope(ident, ValueNS);
4504        if let Some(LexicalScopeBinding::Res(res)) = binding { res != Res::Err } else { false }
4505    }
4506
4507    /// A wrapper around [`Resolver::report_error`].
4508    ///
4509    /// This doesn't emit errors for function bodies if this is rustdoc.
4510    fn report_error(&mut self, span: Span, resolution_error: ResolutionError<'ra>) {
4511        if self.should_report_errs() {
4512            self.r.report_error(span, resolution_error);
4513        }
4514    }
4515
4516    #[inline]
4517    /// If we're actually rustdoc then avoid giving a name resolution error for `cfg()` items or
4518    // an invalid `use foo::*;` was found, which can cause unbounded amounts of "item not found"
4519    // errors. We silence them all.
4520    fn should_report_errs(&self) -> bool {
4521        !(self.r.tcx.sess.opts.actually_rustdoc && self.in_func_body)
4522            && !self.r.glob_error.is_some()
4523    }
4524
4525    // Resolve in alternative namespaces if resolution in the primary namespace fails.
4526    fn resolve_qpath_anywhere(
4527        &mut self,
4528        qself: &Option<P<QSelf>>,
4529        path: &[Segment],
4530        primary_ns: Namespace,
4531        span: Span,
4532        defer_to_typeck: bool,
4533        finalize: Finalize,
4534        source: PathSource<'ast, '_>,
4535    ) -> Result<Option<PartialRes>, Spanned<ResolutionError<'ra>>> {
4536        let mut fin_res = None;
4537
4538        for (i, &ns) in [primary_ns, TypeNS, ValueNS].iter().enumerate() {
4539            if i == 0 || ns != primary_ns {
4540                match self.resolve_qpath(qself, path, ns, finalize, source)? {
4541                    Some(partial_res)
4542                        if partial_res.unresolved_segments() == 0 || defer_to_typeck =>
4543                    {
4544                        return Ok(Some(partial_res));
4545                    }
4546                    partial_res => {
4547                        if fin_res.is_none() {
4548                            fin_res = partial_res;
4549                        }
4550                    }
4551                }
4552            }
4553        }
4554
4555        assert!(primary_ns != MacroNS);
4556
4557        if qself.is_none() {
4558            let path_seg = |seg: &Segment| PathSegment::from_ident(seg.ident);
4559            let path = Path { segments: path.iter().map(path_seg).collect(), span, tokens: None };
4560            if let Ok((_, res)) =
4561                self.r.resolve_macro_path(&path, None, &self.parent_scope, false, false, None)
4562            {
4563                return Ok(Some(PartialRes::new(res)));
4564            }
4565        }
4566
4567        Ok(fin_res)
4568    }
4569
4570    /// Handles paths that may refer to associated items.
4571    fn resolve_qpath(
4572        &mut self,
4573        qself: &Option<P<QSelf>>,
4574        path: &[Segment],
4575        ns: Namespace,
4576        finalize: Finalize,
4577        source: PathSource<'ast, '_>,
4578    ) -> Result<Option<PartialRes>, Spanned<ResolutionError<'ra>>> {
4579        debug!(
4580            "resolve_qpath(qself={:?}, path={:?}, ns={:?}, finalize={:?})",
4581            qself, path, ns, finalize,
4582        );
4583
4584        if let Some(qself) = qself {
4585            if qself.position == 0 {
4586                // This is a case like `<T>::B`, where there is no
4587                // trait to resolve. In that case, we leave the `B`
4588                // segment to be resolved by type-check.
4589                return Ok(Some(PartialRes::with_unresolved_segments(
4590                    Res::Def(DefKind::Mod, CRATE_DEF_ID.to_def_id()),
4591                    path.len(),
4592                )));
4593            }
4594
4595            let num_privacy_errors = self.r.privacy_errors.len();
4596            // Make sure that `A` in `<T as A>::B::C` is a trait.
4597            let trait_res = self.smart_resolve_path_fragment(
4598                &None,
4599                &path[..qself.position],
4600                PathSource::Trait(AliasPossibility::No),
4601                Finalize::new(finalize.node_id, qself.path_span),
4602                RecordPartialRes::No,
4603                Some(&qself),
4604            );
4605
4606            if trait_res.expect_full_res() == Res::Err {
4607                return Ok(Some(trait_res));
4608            }
4609
4610            // Truncate additional privacy errors reported above,
4611            // because they'll be recomputed below.
4612            self.r.privacy_errors.truncate(num_privacy_errors);
4613
4614            // Make sure `A::B` in `<T as A>::B::C` is a trait item.
4615            //
4616            // Currently, `path` names the full item (`A::B::C`, in
4617            // our example). so we extract the prefix of that that is
4618            // the trait (the slice upto and including
4619            // `qself.position`). And then we recursively resolve that,
4620            // but with `qself` set to `None`.
4621            let ns = if qself.position + 1 == path.len() { ns } else { TypeNS };
4622            let partial_res = self.smart_resolve_path_fragment(
4623                &None,
4624                &path[..=qself.position],
4625                PathSource::TraitItem(ns, &source),
4626                Finalize::with_root_span(finalize.node_id, finalize.path_span, qself.path_span),
4627                RecordPartialRes::No,
4628                Some(&qself),
4629            );
4630
4631            // The remaining segments (the `C` in our example) will
4632            // have to be resolved by type-check, since that requires doing
4633            // trait resolution.
4634            return Ok(Some(PartialRes::with_unresolved_segments(
4635                partial_res.base_res(),
4636                partial_res.unresolved_segments() + path.len() - qself.position - 1,
4637            )));
4638        }
4639
4640        let result = match self.resolve_path(path, Some(ns), Some(finalize)) {
4641            PathResult::NonModule(path_res) => path_res,
4642            PathResult::Module(ModuleOrUniformRoot::Module(module)) if !module.is_normal() => {
4643                PartialRes::new(module.res().unwrap())
4644            }
4645            // A part of this path references a `mod` that had a parse error. To avoid resolution
4646            // errors for each reference to that module, we don't emit an error for them until the
4647            // `mod` is fixed. this can have a significant cascade effect.
4648            PathResult::Failed { error_implied_by_parse_error: true, .. } => {
4649                PartialRes::new(Res::Err)
4650            }
4651            // In `a(::assoc_item)*` `a` cannot be a module. If `a` does resolve to a module we
4652            // don't report an error right away, but try to fallback to a primitive type.
4653            // So, we are still able to successfully resolve something like
4654            //
4655            // use std::u8; // bring module u8 in scope
4656            // fn f() -> u8 { // OK, resolves to primitive u8, not to std::u8
4657            //     u8::max_value() // OK, resolves to associated function <u8>::max_value,
4658            //                     // not to nonexistent std::u8::max_value
4659            // }
4660            //
4661            // Such behavior is required for backward compatibility.
4662            // The same fallback is used when `a` resolves to nothing.
4663            PathResult::Module(ModuleOrUniformRoot::Module(_)) | PathResult::Failed { .. }
4664                if (ns == TypeNS || path.len() > 1)
4665                    && PrimTy::from_name(path[0].ident.name).is_some() =>
4666            {
4667                let prim = PrimTy::from_name(path[0].ident.name).unwrap();
4668                let tcx = self.r.tcx();
4669
4670                let gate_err_sym_msg = match prim {
4671                    PrimTy::Float(FloatTy::F16) if !tcx.features().f16() => {
4672                        Some((sym::f16, "the type `f16` is unstable"))
4673                    }
4674                    PrimTy::Float(FloatTy::F128) if !tcx.features().f128() => {
4675                        Some((sym::f128, "the type `f128` is unstable"))
4676                    }
4677                    _ => None,
4678                };
4679
4680                if let Some((sym, msg)) = gate_err_sym_msg {
4681                    let span = path[0].ident.span;
4682                    if !span.allows_unstable(sym) {
4683                        feature_err(tcx.sess, sym, span, msg).emit();
4684                    }
4685                };
4686
4687                // Fix up partial res of segment from `resolve_path` call.
4688                if let Some(id) = path[0].id {
4689                    self.r.partial_res_map.insert(id, PartialRes::new(Res::PrimTy(prim)));
4690                }
4691
4692                PartialRes::with_unresolved_segments(Res::PrimTy(prim), path.len() - 1)
4693            }
4694            PathResult::Module(ModuleOrUniformRoot::Module(module)) => {
4695                PartialRes::new(module.res().unwrap())
4696            }
4697            PathResult::Failed {
4698                is_error_from_last_segment: false,
4699                span,
4700                label,
4701                suggestion,
4702                module,
4703                segment_name,
4704                error_implied_by_parse_error: _,
4705            } => {
4706                return Err(respan(
4707                    span,
4708                    ResolutionError::FailedToResolve {
4709                        segment: Some(segment_name),
4710                        label,
4711                        suggestion,
4712                        module,
4713                    },
4714                ));
4715            }
4716            PathResult::Module(..) | PathResult::Failed { .. } => return Ok(None),
4717            PathResult::Indeterminate => bug!("indeterminate path result in resolve_qpath"),
4718        };
4719
4720        Ok(Some(result))
4721    }
4722
4723    fn with_resolved_label(&mut self, label: Option<Label>, id: NodeId, f: impl FnOnce(&mut Self)) {
4724        if let Some(label) = label {
4725            if label.ident.as_str().as_bytes()[1] != b'_' {
4726                self.diag_metadata.unused_labels.insert(id, label.ident.span);
4727            }
4728
4729            if let Ok((_, orig_span)) = self.resolve_label(label.ident) {
4730                diagnostics::signal_label_shadowing(self.r.tcx.sess, orig_span, label.ident)
4731            }
4732
4733            self.with_label_rib(RibKind::Normal, |this| {
4734                let ident = label.ident.normalize_to_macro_rules();
4735                this.label_ribs.last_mut().unwrap().bindings.insert(ident, id);
4736                f(this);
4737            });
4738        } else {
4739            f(self);
4740        }
4741    }
4742
4743    fn resolve_labeled_block(&mut self, label: Option<Label>, id: NodeId, block: &'ast Block) {
4744        self.with_resolved_label(label, id, |this| this.visit_block(block));
4745    }
4746
4747    fn resolve_block(&mut self, block: &'ast Block) {
4748        debug!("(resolving block) entering block");
4749        // Move down in the graph, if there's an anonymous module rooted here.
4750        let orig_module = self.parent_scope.module;
4751        let anonymous_module = self.r.block_map.get(&block.id).cloned(); // clones a reference
4752
4753        let mut num_macro_definition_ribs = 0;
4754        if let Some(anonymous_module) = anonymous_module {
4755            debug!("(resolving block) found anonymous module, moving down");
4756            self.ribs[ValueNS].push(Rib::new(RibKind::Module(anonymous_module)));
4757            self.ribs[TypeNS].push(Rib::new(RibKind::Module(anonymous_module)));
4758            self.parent_scope.module = anonymous_module;
4759        } else {
4760            self.ribs[ValueNS].push(Rib::new(RibKind::Normal));
4761        }
4762
4763        // Descend into the block.
4764        for stmt in &block.stmts {
4765            if let StmtKind::Item(ref item) = stmt.kind
4766                && let ItemKind::MacroDef(..) = item.kind
4767            {
4768                num_macro_definition_ribs += 1;
4769                let res = self.r.local_def_id(item.id).to_def_id();
4770                self.ribs[ValueNS].push(Rib::new(RibKind::MacroDefinition(res)));
4771                self.label_ribs.push(Rib::new(RibKind::MacroDefinition(res)));
4772            }
4773
4774            self.visit_stmt(stmt);
4775        }
4776
4777        // Move back up.
4778        self.parent_scope.module = orig_module;
4779        for _ in 0..num_macro_definition_ribs {
4780            self.ribs[ValueNS].pop();
4781            self.label_ribs.pop();
4782        }
4783        self.last_block_rib = self.ribs[ValueNS].pop();
4784        if anonymous_module.is_some() {
4785            self.ribs[TypeNS].pop();
4786        }
4787        debug!("(resolving block) leaving block");
4788    }
4789
4790    fn resolve_anon_const(&mut self, constant: &'ast AnonConst, anon_const_kind: AnonConstKind) {
4791        debug!(
4792            "resolve_anon_const(constant: {:?}, anon_const_kind: {:?})",
4793            constant, anon_const_kind
4794        );
4795
4796        let is_trivial_const_arg = constant
4797            .value
4798            .is_potential_trivial_const_arg(self.r.tcx.features().min_generic_const_args());
4799        self.resolve_anon_const_manual(is_trivial_const_arg, anon_const_kind, |this| {
4800            this.resolve_expr(&constant.value, None)
4801        })
4802    }
4803
4804    /// There are a few places that we need to resolve an anon const but we did not parse an
4805    /// anon const so cannot provide an `&'ast AnonConst`. Right now this is just unbraced
4806    /// const arguments that were parsed as type arguments, and `legacy_const_generics` which
4807    /// parse as normal function argument expressions. To avoid duplicating the code for resolving
4808    /// an anon const we have this function which lets the caller manually call `resolve_expr` or
4809    /// `smart_resolve_path`.
4810    fn resolve_anon_const_manual(
4811        &mut self,
4812        is_trivial_const_arg: bool,
4813        anon_const_kind: AnonConstKind,
4814        resolve_expr: impl FnOnce(&mut Self),
4815    ) {
4816        let is_repeat_expr = match anon_const_kind {
4817            AnonConstKind::ConstArg(is_repeat_expr) => is_repeat_expr,
4818            _ => IsRepeatExpr::No,
4819        };
4820
4821        let may_use_generics = match anon_const_kind {
4822            AnonConstKind::EnumDiscriminant => {
4823                ConstantHasGenerics::No(NoConstantGenericsReason::IsEnumDiscriminant)
4824            }
4825            AnonConstKind::FieldDefaultValue => ConstantHasGenerics::Yes,
4826            AnonConstKind::InlineConst => ConstantHasGenerics::Yes,
4827            AnonConstKind::ConstArg(_) => {
4828                if self.r.tcx.features().generic_const_exprs() || is_trivial_const_arg {
4829                    ConstantHasGenerics::Yes
4830                } else {
4831                    ConstantHasGenerics::No(NoConstantGenericsReason::NonTrivialConstArg)
4832                }
4833            }
4834        };
4835
4836        self.with_constant_rib(is_repeat_expr, may_use_generics, None, |this| {
4837            this.with_lifetime_rib(LifetimeRibKind::Elided(LifetimeRes::Infer), |this| {
4838                resolve_expr(this);
4839            });
4840        });
4841    }
4842
4843    fn resolve_expr_field(&mut self, f: &'ast ExprField, e: &'ast Expr) {
4844        self.resolve_expr(&f.expr, Some(e));
4845        self.visit_ident(&f.ident);
4846        walk_list!(self, visit_attribute, f.attrs.iter());
4847    }
4848
4849    fn resolve_expr(&mut self, expr: &'ast Expr, parent: Option<&'ast Expr>) {
4850        // First, record candidate traits for this expression if it could
4851        // result in the invocation of a method call.
4852
4853        self.record_candidate_traits_for_expr_if_necessary(expr);
4854
4855        // Next, resolve the node.
4856        match expr.kind {
4857            ExprKind::Path(ref qself, ref path) => {
4858                self.smart_resolve_path(expr.id, qself, path, PathSource::Expr(parent));
4859                visit::walk_expr(self, expr);
4860            }
4861
4862            ExprKind::Struct(ref se) => {
4863                self.smart_resolve_path(expr.id, &se.qself, &se.path, PathSource::Struct);
4864                // This is the same as `visit::walk_expr(self, expr);`, but we want to pass the
4865                // parent in for accurate suggestions when encountering `Foo { bar }` that should
4866                // have been `Foo { bar: self.bar }`.
4867                if let Some(qself) = &se.qself {
4868                    self.visit_ty(&qself.ty);
4869                }
4870                self.visit_path(&se.path, expr.id);
4871                walk_list!(self, resolve_expr_field, &se.fields, expr);
4872                match &se.rest {
4873                    StructRest::Base(expr) => self.visit_expr(expr),
4874                    StructRest::Rest(_span) => {}
4875                    StructRest::None => {}
4876                }
4877            }
4878
4879            ExprKind::Break(Some(label), _) | ExprKind::Continue(Some(label)) => {
4880                match self.resolve_label(label.ident) {
4881                    Ok((node_id, _)) => {
4882                        // Since this res is a label, it is never read.
4883                        self.r.label_res_map.insert(expr.id, node_id);
4884                        self.diag_metadata.unused_labels.swap_remove(&node_id);
4885                    }
4886                    Err(error) => {
4887                        self.report_error(label.ident.span, error);
4888                    }
4889                }
4890
4891                // visit `break` argument if any
4892                visit::walk_expr(self, expr);
4893            }
4894
4895            ExprKind::Break(None, Some(ref e)) => {
4896                // We use this instead of `visit::walk_expr` to keep the parent expr around for
4897                // better diagnostics.
4898                self.resolve_expr(e, Some(expr));
4899            }
4900
4901            ExprKind::Let(ref pat, ref scrutinee, _, _) => {
4902                self.visit_expr(scrutinee);
4903                self.resolve_pattern_top(pat, PatternSource::Let);
4904            }
4905
4906            ExprKind::If(ref cond, ref then, ref opt_else) => {
4907                self.with_rib(ValueNS, RibKind::Normal, |this| {
4908                    let old = this.diag_metadata.in_if_condition.replace(cond);
4909                    this.visit_expr(cond);
4910                    this.diag_metadata.in_if_condition = old;
4911                    this.visit_block(then);
4912                });
4913                if let Some(expr) = opt_else {
4914                    self.visit_expr(expr);
4915                }
4916            }
4917
4918            ExprKind::Loop(ref block, label, _) => {
4919                self.resolve_labeled_block(label, expr.id, block)
4920            }
4921
4922            ExprKind::While(ref cond, ref block, label) => {
4923                self.with_resolved_label(label, expr.id, |this| {
4924                    this.with_rib(ValueNS, RibKind::Normal, |this| {
4925                        let old = this.diag_metadata.in_if_condition.replace(cond);
4926                        this.visit_expr(cond);
4927                        this.diag_metadata.in_if_condition = old;
4928                        this.visit_block(block);
4929                    })
4930                });
4931            }
4932
4933            ExprKind::ForLoop { ref pat, ref iter, ref body, label, kind: _ } => {
4934                self.visit_expr(iter);
4935                self.with_rib(ValueNS, RibKind::Normal, |this| {
4936                    this.resolve_pattern_top(pat, PatternSource::For);
4937                    this.resolve_labeled_block(label, expr.id, body);
4938                });
4939            }
4940
4941            ExprKind::Block(ref block, label) => self.resolve_labeled_block(label, block.id, block),
4942
4943            // Equivalent to `visit::walk_expr` + passing some context to children.
4944            ExprKind::Field(ref subexpression, _) => {
4945                self.resolve_expr(subexpression, Some(expr));
4946            }
4947            ExprKind::MethodCall(box MethodCall { ref seg, ref receiver, ref args, .. }) => {
4948                self.resolve_expr(receiver, Some(expr));
4949                for arg in args {
4950                    self.resolve_expr(arg, None);
4951                }
4952                self.visit_path_segment(seg);
4953            }
4954
4955            ExprKind::Call(ref callee, ref arguments) => {
4956                self.resolve_expr(callee, Some(expr));
4957                let const_args = self.r.legacy_const_generic_args(callee).unwrap_or_default();
4958                for (idx, argument) in arguments.iter().enumerate() {
4959                    // Constant arguments need to be treated as AnonConst since
4960                    // that is how they will be later lowered to HIR.
4961                    if const_args.contains(&idx) {
4962                        let is_trivial_const_arg = argument.is_potential_trivial_const_arg(
4963                            self.r.tcx.features().min_generic_const_args(),
4964                        );
4965                        self.resolve_anon_const_manual(
4966                            is_trivial_const_arg,
4967                            AnonConstKind::ConstArg(IsRepeatExpr::No),
4968                            |this| this.resolve_expr(argument, None),
4969                        );
4970                    } else {
4971                        self.resolve_expr(argument, None);
4972                    }
4973                }
4974            }
4975            ExprKind::Type(ref _type_expr, ref _ty) => {
4976                visit::walk_expr(self, expr);
4977            }
4978            // For closures, RibKind::FnOrCoroutine is added in visit_fn
4979            ExprKind::Closure(box ast::Closure {
4980                binder: ClosureBinder::For { ref generic_params, span },
4981                ..
4982            }) => {
4983                self.with_generic_param_rib(
4984                    generic_params,
4985                    RibKind::Normal,
4986                    LifetimeRibKind::Generics {
4987                        binder: expr.id,
4988                        kind: LifetimeBinderKind::Closure,
4989                        span,
4990                    },
4991                    |this| visit::walk_expr(this, expr),
4992                );
4993            }
4994            ExprKind::Closure(..) => visit::walk_expr(self, expr),
4995            ExprKind::Gen(..) => {
4996                self.with_label_rib(RibKind::FnOrCoroutine, |this| visit::walk_expr(this, expr));
4997            }
4998            ExprKind::Repeat(ref elem, ref ct) => {
4999                self.visit_expr(elem);
5000                self.resolve_anon_const(ct, AnonConstKind::ConstArg(IsRepeatExpr::Yes));
5001            }
5002            ExprKind::ConstBlock(ref ct) => {
5003                self.resolve_anon_const(ct, AnonConstKind::InlineConst);
5004            }
5005            ExprKind::Index(ref elem, ref idx, _) => {
5006                self.resolve_expr(elem, Some(expr));
5007                self.visit_expr(idx);
5008            }
5009            ExprKind::Assign(ref lhs, ref rhs, _) => {
5010                if !self.diag_metadata.is_assign_rhs {
5011                    self.diag_metadata.in_assignment = Some(expr);
5012                }
5013                self.visit_expr(lhs);
5014                self.diag_metadata.is_assign_rhs = true;
5015                self.diag_metadata.in_assignment = None;
5016                self.visit_expr(rhs);
5017                self.diag_metadata.is_assign_rhs = false;
5018            }
5019            ExprKind::Range(Some(ref start), Some(ref end), RangeLimits::HalfOpen) => {
5020                self.diag_metadata.in_range = Some((start, end));
5021                self.resolve_expr(start, Some(expr));
5022                self.resolve_expr(end, Some(expr));
5023                self.diag_metadata.in_range = None;
5024            }
5025            _ => {
5026                visit::walk_expr(self, expr);
5027            }
5028        }
5029    }
5030
5031    fn record_candidate_traits_for_expr_if_necessary(&mut self, expr: &'ast Expr) {
5032        match expr.kind {
5033            ExprKind::Field(_, ident) => {
5034                // #6890: Even though you can't treat a method like a field,
5035                // we need to add any trait methods we find that match the
5036                // field name so that we can do some nice error reporting
5037                // later on in typeck.
5038                let traits = self.traits_in_scope(ident, ValueNS);
5039                self.r.trait_map.insert(expr.id, traits);
5040            }
5041            ExprKind::MethodCall(ref call) => {
5042                debug!("(recording candidate traits for expr) recording traits for {}", expr.id);
5043                let traits = self.traits_in_scope(call.seg.ident, ValueNS);
5044                self.r.trait_map.insert(expr.id, traits);
5045            }
5046            _ => {
5047                // Nothing to do.
5048            }
5049        }
5050    }
5051
5052    fn traits_in_scope(&mut self, ident: Ident, ns: Namespace) -> Vec<TraitCandidate> {
5053        self.r.traits_in_scope(
5054            self.current_trait_ref.as_ref().map(|(module, _)| *module),
5055            &self.parent_scope,
5056            ident.span.ctxt(),
5057            Some((ident.name, ns)),
5058        )
5059    }
5060
5061    fn resolve_and_cache_rustdoc_path(&mut self, path_str: &str, ns: Namespace) -> Option<Res> {
5062        // FIXME: This caching may be incorrect in case of multiple `macro_rules`
5063        // items with the same name in the same module.
5064        // Also hygiene is not considered.
5065        let mut doc_link_resolutions = std::mem::take(&mut self.r.doc_link_resolutions);
5066        let res = *doc_link_resolutions
5067            .entry(self.parent_scope.module.nearest_parent_mod().expect_local())
5068            .or_default()
5069            .entry((Symbol::intern(path_str), ns))
5070            .or_insert_with_key(|(path, ns)| {
5071                let res = self.r.resolve_rustdoc_path(path.as_str(), *ns, self.parent_scope);
5072                if let Some(res) = res
5073                    && let Some(def_id) = res.opt_def_id()
5074                    && self.is_invalid_proc_macro_item_for_doc(def_id)
5075                {
5076                    // Encoding def ids in proc macro crate metadata will ICE,
5077                    // because it will only store proc macros for it.
5078                    return None;
5079                }
5080                res
5081            });
5082        self.r.doc_link_resolutions = doc_link_resolutions;
5083        res
5084    }
5085
5086    fn is_invalid_proc_macro_item_for_doc(&self, did: DefId) -> bool {
5087        if !matches!(self.r.tcx.sess.opts.resolve_doc_links, ResolveDocLinks::ExportedMetadata)
5088            || !self.r.tcx.crate_types().contains(&CrateType::ProcMacro)
5089        {
5090            return false;
5091        }
5092        let Some(local_did) = did.as_local() else { return true };
5093        !self.r.proc_macros.contains(&local_did)
5094    }
5095
5096    fn resolve_doc_links(&mut self, attrs: &[Attribute], maybe_exported: MaybeExported<'_>) {
5097        match self.r.tcx.sess.opts.resolve_doc_links {
5098            ResolveDocLinks::None => return,
5099            ResolveDocLinks::ExportedMetadata
5100                if !self.r.tcx.crate_types().iter().copied().any(CrateType::has_metadata)
5101                    || !maybe_exported.eval(self.r) =>
5102            {
5103                return;
5104            }
5105            ResolveDocLinks::Exported
5106                if !maybe_exported.eval(self.r)
5107                    && !rustdoc::has_primitive_or_keyword_docs(attrs) =>
5108            {
5109                return;
5110            }
5111            ResolveDocLinks::ExportedMetadata
5112            | ResolveDocLinks::Exported
5113            | ResolveDocLinks::All => {}
5114        }
5115
5116        if !attrs.iter().any(|attr| attr.may_have_doc_links()) {
5117            return;
5118        }
5119
5120        let mut need_traits_in_scope = false;
5121        for path_str in rustdoc::attrs_to_preprocessed_links(attrs) {
5122            // Resolve all namespaces due to no disambiguator or for diagnostics.
5123            let mut any_resolved = false;
5124            let mut need_assoc = false;
5125            for ns in [TypeNS, ValueNS, MacroNS] {
5126                if let Some(res) = self.resolve_and_cache_rustdoc_path(&path_str, ns) {
5127                    // Rustdoc ignores tool attribute resolutions and attempts
5128                    // to resolve their prefixes for diagnostics.
5129                    any_resolved = !matches!(res, Res::NonMacroAttr(NonMacroAttrKind::Tool));
5130                } else if ns != MacroNS {
5131                    need_assoc = true;
5132                }
5133            }
5134
5135            // Resolve all prefixes for type-relative resolution or for diagnostics.
5136            if need_assoc || !any_resolved {
5137                let mut path = &path_str[..];
5138                while let Some(idx) = path.rfind("::") {
5139                    path = &path[..idx];
5140                    need_traits_in_scope = true;
5141                    for ns in [TypeNS, ValueNS, MacroNS] {
5142                        self.resolve_and_cache_rustdoc_path(path, ns);
5143                    }
5144                }
5145            }
5146        }
5147
5148        if need_traits_in_scope {
5149            // FIXME: hygiene is not considered.
5150            let mut doc_link_traits_in_scope = std::mem::take(&mut self.r.doc_link_traits_in_scope);
5151            doc_link_traits_in_scope
5152                .entry(self.parent_scope.module.nearest_parent_mod().expect_local())
5153                .or_insert_with(|| {
5154                    self.r
5155                        .traits_in_scope(None, &self.parent_scope, SyntaxContext::root(), None)
5156                        .into_iter()
5157                        .filter_map(|tr| {
5158                            if self.is_invalid_proc_macro_item_for_doc(tr.def_id) {
5159                                // Encoding def ids in proc macro crate metadata will ICE.
5160                                // because it will only store proc macros for it.
5161                                return None;
5162                            }
5163                            Some(tr.def_id)
5164                        })
5165                        .collect()
5166                });
5167            self.r.doc_link_traits_in_scope = doc_link_traits_in_scope;
5168        }
5169    }
5170
5171    fn lint_unused_qualifications(&mut self, path: &[Segment], ns: Namespace, finalize: Finalize) {
5172        // Don't lint on global paths because the user explicitly wrote out the full path.
5173        if let Some(seg) = path.first()
5174            && seg.ident.name == kw::PathRoot
5175        {
5176            return;
5177        }
5178
5179        if finalize.path_span.from_expansion()
5180            || path.iter().any(|seg| seg.ident.span.from_expansion())
5181        {
5182            return;
5183        }
5184
5185        let end_pos =
5186            path.iter().position(|seg| seg.has_generic_args).map_or(path.len(), |pos| pos + 1);
5187        let unqualified = path[..end_pos].iter().enumerate().skip(1).rev().find_map(|(i, seg)| {
5188            // Preserve the current namespace for the final path segment, but use the type
5189            // namespace for all preceding segments
5190            //
5191            // e.g. for `std::env::args` check the `ValueNS` for `args` but the `TypeNS` for
5192            // `std` and `env`
5193            //
5194            // If the final path segment is beyond `end_pos` all the segments to check will
5195            // use the type namespace
5196            let ns = if i + 1 == path.len() { ns } else { TypeNS };
5197            let res = self.r.partial_res_map.get(&seg.id?)?.full_res()?;
5198            let binding = self.resolve_ident_in_lexical_scope(seg.ident, ns, None, None)?;
5199            (res == binding.res()).then_some((seg, binding))
5200        });
5201
5202        if let Some((seg, binding)) = unqualified {
5203            self.r.potentially_unnecessary_qualifications.push(UnnecessaryQualification {
5204                binding,
5205                node_id: finalize.node_id,
5206                path_span: finalize.path_span,
5207                removal_span: path[0].ident.span.until(seg.ident.span),
5208            });
5209        }
5210    }
5211
5212    fn resolve_define_opaques(&mut self, define_opaque: &Option<ThinVec<(NodeId, Path)>>) {
5213        if let Some(define_opaque) = define_opaque {
5214            for (id, path) in define_opaque {
5215                self.smart_resolve_path(*id, &None, path, PathSource::DefineOpaques);
5216            }
5217        }
5218    }
5219}
5220
5221/// Walks the whole crate in DFS order, visiting each item, counting the declared number of
5222/// lifetime generic parameters and function parameters.
5223struct ItemInfoCollector<'a, 'ra, 'tcx> {
5224    r: &'a mut Resolver<'ra, 'tcx>,
5225}
5226
5227impl ItemInfoCollector<'_, '_, '_> {
5228    fn collect_fn_info(
5229        &mut self,
5230        header: FnHeader,
5231        decl: &FnDecl,
5232        id: NodeId,
5233        attrs: &[Attribute],
5234    ) {
5235        let sig = DelegationFnSig {
5236            header,
5237            param_count: decl.inputs.len(),
5238            has_self: decl.has_self(),
5239            c_variadic: decl.c_variadic(),
5240            target_feature: attrs.iter().any(|attr| attr.has_name(sym::target_feature)),
5241        };
5242        self.r.delegation_fn_sigs.insert(self.r.local_def_id(id), sig);
5243    }
5244}
5245
5246impl<'ast> Visitor<'ast> for ItemInfoCollector<'_, '_, '_> {
5247    fn visit_item(&mut self, item: &'ast Item) {
5248        match &item.kind {
5249            ItemKind::TyAlias(box TyAlias { generics, .. })
5250            | ItemKind::Const(box ConstItem { generics, .. })
5251            | ItemKind::Fn(box Fn { generics, .. })
5252            | ItemKind::Enum(_, generics, _)
5253            | ItemKind::Struct(_, generics, _)
5254            | ItemKind::Union(_, generics, _)
5255            | ItemKind::Impl(box Impl { generics, .. })
5256            | ItemKind::Trait(box Trait { generics, .. })
5257            | ItemKind::TraitAlias(_, generics, _) => {
5258                if let ItemKind::Fn(box Fn { sig, .. }) = &item.kind {
5259                    self.collect_fn_info(sig.header, &sig.decl, item.id, &item.attrs);
5260                }
5261
5262                let def_id = self.r.local_def_id(item.id);
5263                let count = generics
5264                    .params
5265                    .iter()
5266                    .filter(|param| matches!(param.kind, ast::GenericParamKind::Lifetime { .. }))
5267                    .count();
5268                self.r.item_generics_num_lifetimes.insert(def_id, count);
5269            }
5270
5271            ItemKind::ForeignMod(ForeignMod { extern_span, safety: _, abi, items }) => {
5272                for foreign_item in items {
5273                    if let ForeignItemKind::Fn(box Fn { sig, .. }) = &foreign_item.kind {
5274                        let new_header =
5275                            FnHeader { ext: Extern::from_abi(*abi, *extern_span), ..sig.header };
5276                        self.collect_fn_info(new_header, &sig.decl, foreign_item.id, &item.attrs);
5277                    }
5278                }
5279            }
5280
5281            ItemKind::Mod(..)
5282            | ItemKind::Static(..)
5283            | ItemKind::Use(..)
5284            | ItemKind::ExternCrate(..)
5285            | ItemKind::MacroDef(..)
5286            | ItemKind::GlobalAsm(..)
5287            | ItemKind::MacCall(..)
5288            | ItemKind::DelegationMac(..) => {}
5289            ItemKind::Delegation(..) => {
5290                // Delegated functions have lifetimes, their count is not necessarily zero.
5291                // But skipping the delegation items here doesn't mean that the count will be considered zero,
5292                // it means there will be a panic when retrieving the count,
5293                // but for delegation items we are never actually retrieving that count in practice.
5294            }
5295        }
5296        visit::walk_item(self, item)
5297    }
5298
5299    fn visit_assoc_item(&mut self, item: &'ast AssocItem, ctxt: AssocCtxt) {
5300        if let AssocItemKind::Fn(box Fn { sig, .. }) = &item.kind {
5301            self.collect_fn_info(sig.header, &sig.decl, item.id, &item.attrs);
5302        }
5303        visit::walk_assoc_item(self, item, ctxt);
5304    }
5305}
5306
5307impl<'ra, 'tcx> Resolver<'ra, 'tcx> {
5308    pub(crate) fn late_resolve_crate(&mut self, krate: &Crate) {
5309        visit::walk_crate(&mut ItemInfoCollector { r: self }, krate);
5310        let mut late_resolution_visitor = LateResolutionVisitor::new(self);
5311        late_resolution_visitor.resolve_doc_links(&krate.attrs, MaybeExported::Ok(CRATE_NODE_ID));
5312        visit::walk_crate(&mut late_resolution_visitor, krate);
5313        for (id, span) in late_resolution_visitor.diag_metadata.unused_labels.iter() {
5314            self.lint_buffer.buffer_lint(
5315                lint::builtin::UNUSED_LABELS,
5316                *id,
5317                *span,
5318                BuiltinLintDiag::UnusedLabel,
5319            );
5320        }
5321    }
5322}
5323
5324/// Check if definition matches a path
5325fn def_id_matches_path(tcx: TyCtxt<'_>, mut def_id: DefId, expected_path: &[&str]) -> bool {
5326    let mut path = expected_path.iter().rev();
5327    while let (Some(parent), Some(next_step)) = (tcx.opt_parent(def_id), path.next()) {
5328        if !tcx.opt_item_name(def_id).is_some_and(|n| n.as_str() == *next_step) {
5329            return false;
5330        }
5331        def_id = parent;
5332    }
5333    true
5334}