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