compiler/rustc_resolve/src/late.rs RUST 5,764 lines View on github.com → Search inside
File is large — showing lines 1–2,000 of 5,764.
1// ignore-tidy-filelength2//! "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`.89use std::borrow::Cow;10use std::collections::hash_map::Entry;11use std::debug_assert_matches;12use std::mem::{replace, swap, take};13use std::ops::{ControlFlow, Range};1415use rustc_ast::visit::{16    AssocCtxt, BoundKind, FnCtxt, FnKind, Visitor, try_visit, visit_opt, walk_list,17};18use rustc_ast::*;19use rustc_data_structures::either::Either;20use rustc_data_structures::fx::{FxHashMap, FxHashSet, FxIndexMap};21use rustc_data_structures::unord::{UnordMap, UnordSet};22use rustc_errors::codes::*;23use rustc_errors::{24    Applicability, Diag, DiagArgValue, Diagnostic, ErrorGuaranteed, IntoDiagArg, MultiSpan,25    StashKey, Suggestions, elided_lifetime_in_path_suggestion, pluralize,26};27use rustc_hir::def::Namespace::{self, *};28use rustc_hir::def::{CtorKind, DefKind, LifetimeRes, NonMacroAttrKind, PartialRes, PerNS};29use rustc_hir::def_id::{CRATE_DEF_ID, DefId, LOCAL_CRATE, LocalDefId};30use rustc_hir::{MissingLifetimeKind, PrimTy};31use rustc_middle::middle::resolve_bound_vars::Set1;32use rustc_middle::ty::{AssocTag, DelegationInfo, Visibility};33use rustc_middle::{bug, span_bug};34use rustc_session::config::{CrateType, ResolveDocLinks};35use rustc_session::errors::feature_err;36use rustc_session::lint;37use rustc_span::{BytePos, DUMMY_SP, Ident, Span, Spanned, Symbol, kw, respan, sym};38use smallvec::{SmallVec, smallvec};39use thin_vec::ThinVec;40use tracing::{debug, instrument, trace};4142use crate::{43    BindingError, BindingKey, Decl, DelegationFnSig, Finalize, IdentKey, LateDecl, LocalModule,44    Module, ModuleOrUniformRoot, ParentScope, PathResult, Res, ResolutionError, Resolver, Segment,45    Stage, TyCtxt, UseError, Used, path_names_to_string, rustdoc, with_owner,46};4748mod diagnostics;4950use diagnostics::{ElisionFnParameter, LifetimeElisionCandidate, MissingLifetime};5152#[derive(Copy, Clone, Debug)]53struct BindingInfo {54    span: Span,55    annotation: BindingMode,56}5758#[derive(Copy, Clone, PartialEq, Eq, Debug)]59pub(crate) enum PatternSource {60    Match,61    Let,62    For,63    FnParam,64}6566#[derive(Copy, Clone, Debug, PartialEq, Eq)]67enum IsRepeatExpr {68    No,69    Yes,70}7172struct IsNeverPattern;7374/// Describes whether an `AnonConst` is a type level const arg or75/// some other form of anon const (i.e. inline consts or enum discriminants)76#[derive(Copy, Clone, Debug, PartialEq, Eq)]77enum AnonConstKind {78    EnumDiscriminant,79    FieldDefaultValue,80    InlineConst,81    ConstArg(IsRepeatExpr),82}8384impl PatternSource {85    fn descr(self) -> &'static str {86        match self {87            PatternSource::Match => "match binding",88            PatternSource::Let => "let binding",89            PatternSource::For => "for binding",90            PatternSource::FnParam => "function parameter",91        }92    }93}9495impl IntoDiagArg for PatternSource {96    fn into_diag_arg(self, _: &mut Option<std::path::PathBuf>) -> DiagArgValue {97        DiagArgValue::Str(Cow::Borrowed(self.descr()))98    }99}100101/// Denotes whether the context for the set of already bound bindings is a `Product`102/// or `Or` context. This is used in e.g., `fresh_binding` and `resolve_pattern_inner`.103/// See those functions for more information.104#[derive(PartialEq)]105enum PatBoundCtx {106    /// A product pattern context, e.g., `Variant(a, b)`.107    Product,108    /// An or-pattern context, e.g., `p_0 | ... | p_n`.109    Or,110}111112/// Tracks bindings resolved within a pattern. This serves two purposes:113///114/// - This tracks when identifiers are bound multiple times within a pattern. In a product context,115///   this is an error. In an or-pattern, this lets us reuse the same resolution for each instance.116///   See `fresh_binding` and `resolve_pattern_inner` for more information.117///118/// - The guard expression of a guard pattern may use bindings from within the guard pattern, but119///   not from elsewhere in the pattern containing it. This allows us to isolate the bindings in the120///   subpattern to construct the scope for the guard.121///122/// Each identifier must map to at most one distinct [`Res`].123type PatternBindings = SmallVec<[(PatBoundCtx, FxIndexMap<Ident, Res>); 1]>;124125/// Does this the item (from the item rib scope) allow generic parameters?126#[derive(Copy, Clone, Debug)]127pub(crate) enum HasGenericParams {128    Yes(Span),129    No,130}131132/// May this constant have generics?133#[derive(Copy, Clone, Debug, Eq, PartialEq)]134pub(crate) enum ConstantHasGenerics {135    Yes,136    No(NoConstantGenericsReason),137}138139impl ConstantHasGenerics {140    fn force_yes_if(self, b: bool) -> Self {141        if b { Self::Yes } else { self }142    }143}144145/// Reason for why an anon const is not allowed to reference generic parameters146#[derive(Copy, Clone, Debug, Eq, PartialEq)]147pub(crate) enum NoConstantGenericsReason {148    /// Const arguments are only allowed to use generic parameters when:149    /// - `feature(generic_const_exprs)` is enabled150    /// or151    /// - the const argument is a sole const generic parameter, i.e. `foo::<{ N }>()`152    ///153    /// If neither of the above are true then this is used as the cause.154    NonTrivialConstArg,155    /// Enum discriminants are not allowed to reference generic parameters ever, this156    /// is used when an anon const is in the following position:157    ///158    /// ```rust,compile_fail159    /// enum Foo<const N: isize> {160    ///     Variant = { N }, // this anon const is not allowed to use generics161    /// }162    /// ```163    IsEnumDiscriminant,164}165166#[derive(Copy, Clone, Debug, Eq, PartialEq)]167pub(crate) enum ConstantItemKind {168    Const,169    Static,170}171172impl ConstantItemKind {173    pub(crate) fn as_str(&self) -> &'static str {174        match self {175            Self::Const => "const",176            Self::Static => "static",177        }178    }179}180181#[derive(Debug, Copy, Clone, PartialEq, Eq)]182enum RecordPartialRes {183    Yes,184    No,185}186187/// The rib kind restricts certain accesses,188/// e.g. to a `Res::Local` of an outer item.189#[derive(Copy, Clone, Debug)]190pub(crate) enum RibKind<'ra> {191    /// No restriction needs to be applied.192    Normal,193194    /// We passed through an `ast::Block`.195    /// Behaves like `Normal`, but also partially like `Module` if the block contains items.196    /// `Block(None)` must be always processed in the same way as `Block(Some(module))`197    /// with empty `module`. The module can be `None` only because creation of some definitely198    /// empty modules is skipped as an optimization.199    Block(Option<LocalModule<'ra>>),200201    /// We passed through an impl or trait and are now in one of its202    /// methods or associated types. Allow references to ty params that impl or trait203    /// binds. Disallow any other upvars (including other ty params that are204    /// upvars).205    AssocItem,206207    /// We passed through a function, closure or coroutine signature. Disallow labels.208    FnOrCoroutine,209210    /// We passed through an item scope. Disallow upvars.211    Item(HasGenericParams, DefKind),212213    /// We're in a constant item. Can't refer to dynamic stuff.214    ///215    /// The item may reference generic parameters in trivial constant expressions.216    /// All other constants aren't allowed to use generic params at all.217    ConstantItem(ConstantHasGenerics, Option<(Ident, ConstantItemKind)>),218219    /// We passed through a module item.220    Module(LocalModule<'ra>),221222    /// We passed through a `macro_rules!` statement223    MacroDefinition(DefId),224225    /// All bindings in this rib are generic parameters that can't be used226    /// from the default of a generic parameter because they're not declared227    /// before said generic parameter. Also see the `visit_generics` override.228    ForwardGenericParamBan(ForwardGenericParamBanReason),229230    /// We are inside of the type of a const parameter. Can't refer to any231    /// parameters.232    ConstParamTy,233234    /// We are inside a `sym` inline assembly operand. Can only refer to235    /// globals.236    InlineAsmSym,237}238239#[derive(Copy, Clone, PartialEq, Eq, Debug)]240pub(crate) enum ForwardGenericParamBanReason {241    Default,242    ConstParamTy,243}244245impl RibKind<'_> {246    /// Whether this rib kind contains generic parameters, as opposed to local247    /// variables.248    pub(crate) fn contains_params(&self) -> bool {249        match self {250            RibKind::Normal251            | RibKind::Block(..)252            | RibKind::FnOrCoroutine253            | RibKind::ConstantItem(..)254            | RibKind::Module(_)255            | RibKind::MacroDefinition(_)256            | RibKind::InlineAsmSym => false,257            RibKind::ConstParamTy258            | RibKind::AssocItem259            | RibKind::Item(..)260            | RibKind::ForwardGenericParamBan(_) => true,261        }262    }263264    /// This rib forbids referring to labels defined in upwards ribs.265    fn is_label_barrier(self) -> bool {266        match self {267            RibKind::Normal | RibKind::MacroDefinition(..) => false,268            RibKind::FnOrCoroutine | RibKind::ConstantItem(..) => true,269            kind => bug!("unexpected rib kind: {kind:?}"),270        }271    }272}273274/// A single local scope.275///276/// A rib represents a scope names can live in. Note that these appear in many places, not just277/// 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 a279/// 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. When285/// 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}292293impl<'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}302303#[derive(Clone, Copy, Debug)]304enum LifetimeUseSet {305    One { use_span: Span, use_ctxt: visit::LifetimeCtxt },306    Many,307}308309#[derive(Copy, Clone, Debug)]310enum LifetimeRibKind {311    // -- Ribs introducing named lifetimes312    //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 },316317    // -- Ribs introducing unnamed lifetimes318    //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_fail323    /// 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 or328    /// 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 },334335    /// Replace all anonymous lifetimes by provided lifetime.336    Elided(LifetimeRes),337338    // -- 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 to341    /// rule out things like `where T: Foo<'_>`. Does not imply an342    /// error on default object bounds (e.g., `Box<dyn Foo>`).343    AnonymousReportError,344345    /// 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-bound347    /// lifetime is a bug and will be removed (if `emit_lint` is enabled).348    StaticIfNoLifetimeInScope { lint_id: NodeId, emit_lint: bool },349350    /// Signal we cannot find which should be the anonymous lifetime.351    ElisionFailure,352353    /// 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 is356    /// currently forbidden. See rust-lang/project-const-generics#28 for more info.357    ConstParamTy,358359    /// Usage of generic parameters is forbidden in various positions for anon consts:360    /// - const arguments when `generic_const_exprs` is not enabled361    /// - enum discriminant values362    ///363    /// This rib emits an error when a lifetime would resolve to a lifetime parameter.364    ConcreteAnonConst(NoConstantGenericsReason),365366    /// This rib acts as a barrier to forbid reference to lifetimes of a parent item.367    Item,368369    /// Lifetimes cannot be elided in `impl Trait` types without `#![feature(anonymous_lifetime_in_impl_trait)]`.370    ImplTrait,371}372373#[derive(Copy, Clone, Debug)]374enum LifetimeBinderKind {375    FnPtrType,376    PolyTrait,377    WhereBound,378    // Item covers foreign items, ADTs, type aliases, trait associated items and379    // trait alias associated items.380    Item,381    ConstItem,382    Function,383    Closure,384    ImplBlock,385    // Covers only `impl` associated types.386    ImplAssocType,387}388389impl LifetimeBinderKind {390    fn descr(self) -> &'static str {391        use LifetimeBinderKind::*;392        match self {393            FnPtrType => "type",394            PolyTrait => "bound",395            WhereBound => "bound",396            Item | ConstItem => "item",397            ImplAssocType => "associated type",398            ImplBlock => "impl block",399            Function => "function",400            Closure => "closure",401        }402    }403}404405#[derive(Debug)]406struct LifetimeRib {407    kind: LifetimeRibKind,408    // We need to preserve insertion order for async fns.409    bindings: FxIndexMap<Ident, (NodeId, LifetimeRes)>,410}411412impl LifetimeRib {413    fn new(kind: LifetimeRibKind) -> LifetimeRib {414        LifetimeRib { bindings: Default::default(), kind }415    }416}417418#[derive(Copy, Clone, PartialEq, Eq, Debug)]419pub(crate) enum AliasPossibility {420    No,421    Maybe,422}423424#[derive(Copy, Clone, Debug)]425pub(crate) enum PathSource<'a, 'ast, 'ra> {426    /// Type paths `Path`.427    Type,428    /// Trait paths in bounds or impls.429    Trait(AliasPossibility),430    /// Expression paths `path`, with optional parent context.431    Expr(Option<&'ast Expr>),432    /// Paths in path patterns `Path`.433    Pat,434    /// Paths in struct expressions and patterns `Path { .. }`.435    Struct(Option<&'a Expr>),436    /// Paths in tuple struct patterns `Path(..)`.437    TupleStruct(Span, &'ra [Span]),438    /// `m::A::B` in `<T as m::A>::B::C`.439    ///440    /// Second field holds the "cause" of this one, i.e. the context within441    /// which the trait item is resolved. Used for diagnostics.442    TraitItem(Namespace, &'a PathSource<'a, 'ast, 'ra>),443    /// Paths in delegation item444    Delegation,445    /// Paths in externally implementable item declarations.446    ExternItemImpl,447    /// An arg in a `use<'a, N>` precise-capturing bound.448    PreciseCapturingArg(Namespace),449    /// Paths that end with `(..)`, for return type notation.450    ReturnTypeNotation,451    /// Paths from `#[define_opaque]` attributes452    DefineOpaques,453    /// Resolving a macro454    Macro,455    /// Paths for module or crate root. Used for restrictions.456    Module,457}458459impl PathSource<'_, '_, '_> {460    fn namespace(self) -> Namespace {461        match self {462            PathSource::Type463            | PathSource::Trait(_)464            | PathSource::Struct(_)465            | PathSource::DefineOpaques466            | PathSource::Module => TypeNS,467            PathSource::Expr(..)468            | PathSource::Pat469            | PathSource::TupleStruct(..)470            | PathSource::Delegation471            | PathSource::ExternItemImpl472            | PathSource::ReturnTypeNotation => ValueNS,473            PathSource::TraitItem(ns, _) => ns,474            PathSource::PreciseCapturingArg(ns) => ns,475            PathSource::Macro => MacroNS,476        }477    }478479    fn defer_to_typeck(self) -> bool {480        match self {481            PathSource::Type482            | PathSource::Expr(..)483            | PathSource::Pat484            | PathSource::Struct(_)485            | PathSource::TupleStruct(..)486            | PathSource::ReturnTypeNotation => true,487            PathSource::Trait(_)488            | PathSource::TraitItem(..)489            | PathSource::DefineOpaques490            | PathSource::Delegation491            | PathSource::ExternItemImpl492            | PathSource::PreciseCapturingArg(..)493            | PathSource::Macro494            | PathSource::Module => false,495        }496    }497498    fn descr_expected(self) -> &'static str {499        match &self {500            PathSource::DefineOpaques => "type alias or associated type with opaqaue types",501            PathSource::Type => "type",502            PathSource::Trait(_) => "trait",503            PathSource::Pat => "unit struct, unit variant or constant",504            PathSource::Struct(_) => "struct, variant or union type",505            PathSource::TraitItem(ValueNS, PathSource::TupleStruct(..))506            | PathSource::TupleStruct(..) => "tuple struct or tuple variant",507            PathSource::TraitItem(ns, _) => match ns {508                TypeNS => "associated type",509                ValueNS => "method or associated constant",510                MacroNS => bug!("associated macro"),511            },512            PathSource::Expr(parent) => match parent.as_ref().map(|p| &p.kind) {513                // "function" here means "anything callable" rather than `DefKind::Fn`,514                // this is not precise but usually more helpful than just "value".515                Some(ExprKind::Call(call_expr, _)) => match &call_expr.kind {516                    // the case of `::some_crate()`517                    ExprKind::Path(_, path)518                        if let [segment, _] = path.segments.as_slice()519                            && segment.ident.name == kw::PathRoot =>520                    {521                        "external crate"522                    }523                    ExprKind::Path(_, path)524                        if let Some(segment) = path.segments.last()525                            && let Some(c) = segment.ident.to_string().chars().next()526                            && c.is_uppercase() =>527                    {528                        "function, tuple struct or tuple variant"529                    }530                    _ => "function",531                },532                _ => "value",533            },534            PathSource::ReturnTypeNotation | PathSource::Delegation => "function",535            PathSource::ExternItemImpl => "function or static",536            PathSource::PreciseCapturingArg(..) => "type or const parameter",537            PathSource::Macro => "macro",538            PathSource::Module => "module",539        }540    }541542    fn is_call(self) -> bool {543        matches!(self, PathSource::Expr(Some(&Expr { kind: ExprKind::Call(..), .. })))544    }545546    pub(crate) fn is_expected(self, res: Res) -> bool {547        match self {548            PathSource::DefineOpaques => {549                matches!(550                    res,551                    Res::Def(552                        DefKind::Struct553                            | DefKind::Union554                            | DefKind::Enum555                            | DefKind::TyAlias556                            | DefKind::AssocTy,557                        _558                    ) | Res::SelfTyAlias { .. }559                )560            }561            PathSource::Type => matches!(562                res,563                Res::Def(564                    DefKind::Struct565                        | DefKind::Union566                        | DefKind::Enum567                        | DefKind::Trait568                        | DefKind::TraitAlias569                        | DefKind::TyAlias570                        | DefKind::AssocTy571                        | DefKind::TyParam572                        | DefKind::OpaqueTy573                        | DefKind::ForeignTy,574                    _,575                ) | Res::PrimTy(..)576                    | Res::SelfTyParam { .. }577                    | Res::SelfTyAlias { .. }578            ),579            PathSource::Trait(AliasPossibility::No) => matches!(res, Res::Def(DefKind::Trait, _)),580            PathSource::Trait(AliasPossibility::Maybe) => {581                matches!(res, Res::Def(DefKind::Trait | DefKind::TraitAlias, _))582            }583            PathSource::Expr(..) => matches!(584                res,585                Res::Def(586                    DefKind::Ctor(_, CtorKind::Const | CtorKind::Fn)587                        | DefKind::Const { .. }588                        | DefKind::Static { .. }589                        | DefKind::Fn590                        | DefKind::AssocFn591                        | DefKind::AssocConst { .. }592                        | DefKind::ConstParam,593                    _,594                ) | Res::Local(..)595                    | Res::SelfCtor(..)596            ),597            PathSource::Pat => {598                res.expected_in_unit_struct_pat()599                    || matches!(600                        res,601                        Res::Def(DefKind::Const { .. } | DefKind::AssocConst { .. }, _)602                    )603            }604            PathSource::TupleStruct(..) => res.expected_in_tuple_struct_pat(),605            PathSource::Struct(_) => matches!(606                res,607                Res::Def(608                    DefKind::Struct609                        | DefKind::Union610                        | DefKind::Variant611                        | DefKind::TyAlias612                        | DefKind::AssocTy,613                    _,614                ) | Res::SelfTyParam { .. }615                    | Res::SelfTyAlias { .. }616            ),617            PathSource::TraitItem(ns, _) => match res {618                Res::Def(DefKind::AssocConst { .. } | DefKind::AssocFn, _) if ns == ValueNS => true,619                Res::Def(DefKind::AssocTy, _) if ns == TypeNS => true,620                _ => false,621            },622            PathSource::ReturnTypeNotation => match res {623                Res::Def(DefKind::AssocFn, _) => true,624                _ => false,625            },626            PathSource::Delegation => matches!(res, Res::Def(DefKind::Fn | DefKind::AssocFn, _)),627            PathSource::ExternItemImpl => {628                matches!(629                    res,630                    Res::Def(631                        DefKind::Fn | DefKind::AssocFn | DefKind::Ctor(..) | DefKind::Static { .. },632                        _633                    )634                )635            }636            PathSource::PreciseCapturingArg(ValueNS) => {637                matches!(res, Res::Def(DefKind::ConstParam, _))638            }639            // We allow `SelfTyAlias` here so we can give a more descriptive error later.640            PathSource::PreciseCapturingArg(TypeNS) => matches!(641                res,642                Res::Def(DefKind::TyParam, _) | Res::SelfTyParam { .. } | Res::SelfTyAlias { .. }643            ),644            PathSource::PreciseCapturingArg(MacroNS) => false,645            PathSource::Macro => matches!(res, Res::Def(DefKind::Macro(_), _)),646            PathSource::Module => matches!(res, Res::Def(DefKind::Mod, _)),647        }648    }649650    fn error_code(self, has_unexpected_resolution: bool) -> ErrCode {651        match (self, has_unexpected_resolution) {652            (PathSource::Trait(_), true) => E0404,653            (PathSource::Trait(_), false) => E0405,654            (PathSource::Type | PathSource::DefineOpaques, true) => E0573,655            (PathSource::Type | PathSource::DefineOpaques, false) => E0425,656            (PathSource::Struct(_), true) => E0574,657            (PathSource::Struct(_), false) => E0422,658            (PathSource::Expr(..), true)659            | (PathSource::Delegation, true)660            | (PathSource::ExternItemImpl, true) => E0423,661            (PathSource::Expr(..), false)662            | (PathSource::Delegation, false)663            | (PathSource::ExternItemImpl, false) => E0425,664            (PathSource::Pat | PathSource::TupleStruct(..), true) => E0532,665            (PathSource::Pat | PathSource::TupleStruct(..), false) => E0531,666            (PathSource::TraitItem(..) | PathSource::ReturnTypeNotation, true) => E0575,667            (PathSource::TraitItem(..) | PathSource::ReturnTypeNotation, false) => E0576,668            (PathSource::PreciseCapturingArg(..), true) => E0799,669            (PathSource::PreciseCapturingArg(..), false) => E0800,670            (PathSource::Macro, _) => E0425,671            // FIXME: There is no dedicated error code for this case yet.672            // E0577 already covers the same situation for visibilities,673            // so we reuse it here for now. It may make sense to generalize674            // it for restrictions in the future.675            (PathSource::Module, true) => E0577,676            (PathSource::Module, false) => E0433,677        }678    }679}680681/// At this point for most items we can answer whether that item is exported or not,682/// but some items like impls require type information to determine exported-ness, so we make a683/// conservative estimate for them (e.g. based on nominal visibility).684#[derive(Clone, Copy)]685enum MaybeExported<'a> {686    Ok(NodeId),687    Impl(Option<DefId>),688    ImplItem(Result<DefId, &'a ast::Visibility>),689    NestedUse(&'a ast::Visibility),690}691692impl MaybeExported<'_> {693    fn eval(self, r: &Resolver<'_, '_>) -> bool {694        let def_id = match self {695            MaybeExported::Ok(node_id) => Some(if r.current_owner.id == node_id {696                r.current_owner.def_id697            } else {698                r.current_owner.node_id_to_def_id[&node_id]699            }),700            MaybeExported::Impl(Some(trait_def_id)) | MaybeExported::ImplItem(Ok(trait_def_id)) => {701                trait_def_id.as_local()702            }703            MaybeExported::Impl(None) => return true,704            MaybeExported::ImplItem(Err(vis)) | MaybeExported::NestedUse(vis) => {705                return vis.kind.is_pub();706            }707        };708        def_id.is_none_or(|def_id| r.effective_visibilities.is_exported(def_id))709    }710}711712/// Used for recording UnnecessaryQualification.713#[derive(Debug)]714pub(crate) struct UnnecessaryQualification<'ra> {715    pub decl: LateDecl<'ra>,716    pub node_id: NodeId,717    pub path_span: Span,718    pub removal_span: Span,719}720721#[derive(Default, Debug)]722pub(crate) struct DiagMetadata<'ast> {723    /// The current trait's associated items' ident, used for diagnostic suggestions.724    current_trait_assoc_items: Option<&'ast [Box<AssocItem>]>,725726    /// The current self type if inside an impl (used for better errors).727    pub(crate) current_self_type: Option<&'ast Ty>,728729    /// The current self item if inside an ADT (used for better errors).730    current_self_item: Option<NodeId>,731732    /// The current item being evaluated (used for suggestions and more detail in errors).733    pub(crate) current_item: Option<&'ast Item>,734735    /// When processing generic arguments and encountering an unresolved ident not found,736    /// suggest introducing a type or const param depending on the context.737    currently_processing_generic_args: bool,738739    /// The current enclosing (non-closure) function (used for better errors).740    current_function: Option<(FnKind<'ast>, Span)>,741742    /// A list of labels as of yet unused. Labels will be removed from this map when743    /// they are used (in a `break` or `continue` statement)744    unused_labels: FxIndexMap<NodeId, Span>,745746    /// Only used for better errors on `let <pat>: <expr, not type>;`.747    current_let_binding: Option<(Span, Option<Span>, Option<Span>)>,748749    current_pat: Option<&'ast Pat>,750751    /// Used to detect possible `if let` written without `let` and to provide structured suggestion.752    in_if_condition: Option<&'ast Expr>,753754    /// Used to detect possible new binding written without `let` and to provide structured suggestion.755    in_assignment: Option<&'ast Expr>,756    is_assign_rhs: bool,757758    /// If we are setting an associated type in trait impl, is it a non-GAT type?759    in_non_gat_assoc_type: Option<bool>,760761    /// Used to detect possible `.` -> `..` typo when calling methods.762    in_range: Option<(&'ast Expr, &'ast Expr)>,763764    /// If we are currently in a trait object definition. Used to point at the bounds when765    /// encountering a struct or enum.766    current_trait_object: Option<&'ast [ast::GenericBound]>,767768    /// Given `where <T as Bar>::Baz: String`, suggest `where T: Bar<Baz = String>`.769    current_where_predicate: Option<&'ast WherePredicate>,770771    /// Whether we are visiting an associated type equality binding like `Trait<Assoc = &T>`.772    in_assoc_ty_binding: bool,773774    current_type_path: Option<&'ast Ty>,775776    /// The current impl items (used to suggest).777    current_impl_items: Option<&'ast [Box<AssocItem>]>,778779    /// The current impl items (used to suggest).780    current_impl_item: Option<&'ast AssocItem>,781782    /// When processing impl trait783    currently_processing_impl_trait: Option<(TraitRef, Ty)>,784785    /// Accumulate the errors due to missed lifetime elision,786    /// and report them all at once for each function.787    current_elision_failures: Vec<(MissingLifetime, Either<NodeId, Range<NodeId>>)>,788}789790struct LateResolutionVisitor<'a, 'ast, 'ra, 'tcx> {791    r: &'a mut Resolver<'ra, 'tcx>,792793    /// The module that represents the current item scope.794    parent_scope: ParentScope<'ra>,795796    /// The current set of local scopes for types and values.797    ribs: PerNS<Vec<Rib<'ra>>>,798799    /// Previous popped `rib`, only used for diagnostic.800    last_block_rib: Option<Rib<'ra>>,801802    /// The current set of local scopes, for labels.803    label_ribs: Vec<Rib<'ra, NodeId>>,804805    /// The current set of local scopes for lifetimes.806    lifetime_ribs: Vec<LifetimeRib>,807808    /// We are looking for lifetimes in an elision context.809    /// The set contains all the resolutions that we encountered so far.810    /// They will be used to determine the correct lifetime for the fn return type.811    /// The `LifetimeElisionCandidate` is used for diagnostics, to suggest introducing named812    /// lifetimes.813    lifetime_elision_candidates: Option<Vec<(LifetimeRes, LifetimeElisionCandidate)>>,814815    /// The trait that the current context can refer to.816    current_trait_ref: Option<(Module<'ra>, TraitRef)>,817818    /// Fields used to add information to diagnostic errors.819    diag_metadata: Box<DiagMetadata<'ast>>,820821    /// State used to know whether to ignore resolution errors for function bodies.822    ///823    /// In particular, rustdoc uses this to avoid giving errors for `cfg()` items.824    /// In most cases this will be `None`, in which case errors will always be reported.825    /// If it is `true`, then it will be updated when entering a nested function or trait body.826    in_func_body: bool,827828    /// Count the number of places a lifetime is used.829    lifetime_uses: FxHashMap<LocalDefId, LifetimeUseSet>,830}831832impl<'ra, 'tcx> AsRef<Resolver<'ra, 'tcx>> for LateResolutionVisitor<'_, '_, 'ra, 'tcx> {833    fn as_ref(&self) -> &Resolver<'ra, 'tcx> {834        &self.r835    }836}837impl<'ra, 'tcx> AsMut<Resolver<'ra, 'tcx>> for LateResolutionVisitor<'_, '_, 'ra, 'tcx> {838    fn as_mut(&mut self) -> &mut Resolver<'ra, 'tcx> {839        &mut self.r840    }841}842843/// Walks the whole crate in DFS order, visiting each item, resolving names as it goes.844impl<'ast, 'ra, 'tcx> Visitor<'ast> for LateResolutionVisitor<'_, 'ast, 'ra, 'tcx> {845    fn visit_attribute(&mut self, _: &'ast Attribute) {846        // We do not want to resolve expressions that appear in attributes,847        // as they do not correspond to actual code.848    }849    fn visit_item(&mut self, item: &'ast Item) {850        let prev = replace(&mut self.diag_metadata.current_item, Some(item));851        // Always report errors in items we just entered.852        let old_ignore = replace(&mut self.in_func_body, false);853        with_owner(self, item.id, |this| {854            this.with_lifetime_rib(LifetimeRibKind::Item, |this| this.resolve_item(item))855        });856        self.in_func_body = old_ignore;857        self.diag_metadata.current_item = prev;858    }859    fn visit_arm(&mut self, arm: &'ast Arm) {860        self.resolve_arm(arm);861    }862    fn visit_block(&mut self, block: &'ast Block) {863        let old_macro_rules = self.parent_scope.macro_rules;864        self.resolve_block(block);865        self.parent_scope.macro_rules = old_macro_rules;866    }867    fn visit_anon_const(&mut self, constant: &'ast AnonConst) {868        bug!("encountered anon const without a manual call to `resolve_anon_const`: {constant:#?}");869    }870    fn visit_expr(&mut self, expr: &'ast Expr) {871        self.resolve_expr(expr, None);872    }873    fn visit_pat(&mut self, p: &'ast Pat) {874        let prev = self.diag_metadata.current_pat;875        self.diag_metadata.current_pat = Some(p);876877        if let PatKind::Guard(subpat, _) = &p.kind {878            // We walk the guard expression in `resolve_pattern_inner`. Don't resolve it twice.879            self.visit_pat(subpat);880        } else {881            visit::walk_pat(self, p);882        }883884        self.diag_metadata.current_pat = prev;885    }886    fn visit_local(&mut self, local: &'ast Local) {887        let local_spans = match local.pat.kind {888            // We check for this to avoid tuple struct fields.889            PatKind::Wild => None,890            _ => Some((891                local.pat.span,892                local.ty.as_ref().map(|ty| ty.span),893                local.kind.init().map(|init| init.span),894            )),895        };896        let original = replace(&mut self.diag_metadata.current_let_binding, local_spans);897        self.resolve_local(local);898        self.diag_metadata.current_let_binding = original;899    }900    fn visit_ty(&mut self, ty: &'ast Ty) {901        let prev = self.diag_metadata.current_trait_object;902        let prev_ty = self.diag_metadata.current_type_path;903        match &ty.kind {904            TyKind::Ref(None, _) | TyKind::PinnedRef(None, _) => {905                // Elided lifetime in reference: we resolve as if there was some lifetime `'_` with906                // NodeId `ty.id`.907                // This span will be used in case of elision failure.908                let span = self.r.tcx.sess.source_map().start_point(ty.span);909                self.resolve_elided_lifetime(ty.id, span);910                visit::walk_ty(self, ty);911            }912            TyKind::Path(qself, path) => {913                self.diag_metadata.current_type_path = Some(ty);914915                // If we have a path that ends with `(..)`, then it must be916                // return type notation. Resolve that path in the *value*917                // namespace.918                let source = if let Some(seg) = path.segments.last()919                    && let Some(args) = &seg.args920                    && matches!(**args, GenericArgs::ParenthesizedElided(..))921                {922                    PathSource::ReturnTypeNotation923                } else {924                    PathSource::Type925                };926927                self.smart_resolve_path(ty.id, qself, path, source);928929                // Check whether we should interpret this as a bare trait object.930                if qself.is_none()931                    && let Some(partial_res) = self.r.partial_res_map.get(&ty.id)932                    && let Some(Res::Def(DefKind::Trait | DefKind::TraitAlias, _)) =933                        partial_res.full_res()934                {935                    // This path is actually a bare trait object. In case of a bare `Fn`-trait936                    // object with anonymous lifetimes, we need this rib to correctly place the937                    // synthetic lifetimes.938                    let span = ty.span.shrink_to_lo().to(path.span.shrink_to_lo());939                    self.with_generic_param_rib(940                        &[],941                        RibKind::Normal,942                        ty.id,943                        LifetimeBinderKind::PolyTrait,944                        span,945                        |this| this.visit_path(path),946                    );947                } else {948                    visit::walk_ty(self, ty)949                }950            }951            TyKind::ImplicitSelf => {952                let self_ty = Ident::with_dummy_span(kw::SelfUpper);953                let res = self954                    .resolve_ident_in_lexical_scope(955                        self_ty,956                        TypeNS,957                        Some(Finalize::new(ty.id, ty.span)),958                        None,959                    )960                    .map_or(Res::Err, |d| d.res());961                self.r.record_partial_res(ty.id, PartialRes::new(res));962                visit::walk_ty(self, ty)963            }964            TyKind::ImplTrait(..) => {965                let candidates = self.lifetime_elision_candidates.take();966                self.with_lifetime_rib(LifetimeRibKind::ImplTrait, |this| visit::walk_ty(this, ty));967                self.lifetime_elision_candidates = candidates;968            }969            TyKind::TraitObject(bounds, ..) => {970                self.diag_metadata.current_trait_object = Some(&bounds[..]);971                visit::walk_ty(self, ty)972            }973            TyKind::FnPtr(fn_ptr) => {974                let span = ty.span.shrink_to_lo().to(fn_ptr.decl_span.shrink_to_lo());975                self.with_generic_param_rib(976                    &fn_ptr.generic_params,977                    RibKind::Normal,978                    ty.id,979                    LifetimeBinderKind::FnPtrType,980                    span,981                    |this| {982                        this.visit_generic_params(&fn_ptr.generic_params, false);983                        this.resolve_fn_signature(984                            ty.id,985                            false,986                            // We don't need to deal with patterns in parameters, because987                            // they are not possible for foreign or bodiless functions.988                            fn_ptr.decl.inputs.iter().map(|Param { ty, .. }| (None, &**ty)),989                            &fn_ptr.decl.output,990                            false,991                        )992                    },993                )994            }995            TyKind::UnsafeBinder(unsafe_binder) => {996                let span = ty.span.shrink_to_lo().to(unsafe_binder.inner_ty.span.shrink_to_lo());997                self.with_generic_param_rib(998                    &unsafe_binder.generic_params,999                    RibKind::Normal,1000                    ty.id,1001                    LifetimeBinderKind::FnPtrType,1002                    span,1003                    |this| {1004                        this.visit_generic_params(&unsafe_binder.generic_params, false);1005                        this.with_lifetime_rib(1006                            // We don't allow anonymous `unsafe &'_ ()` binders,1007                            // although I guess we could.1008                            LifetimeRibKind::AnonymousReportError,1009                            |this| this.visit_ty(&unsafe_binder.inner_ty),1010                        );1011                    },1012                )1013            }1014            TyKind::Array(element_ty, length) => {1015                self.visit_ty(element_ty);1016                self.resolve_anon_const(length, AnonConstKind::ConstArg(IsRepeatExpr::No));1017            }1018            _ => visit::walk_ty(self, ty),1019        }1020        self.diag_metadata.current_trait_object = prev;1021        self.diag_metadata.current_type_path = prev_ty;1022    }10231024    fn visit_ty_pat(&mut self, t: &'ast TyPat) -> Self::Result {1025        match &t.kind {1026            TyPatKind::Range(start, end, _) => {1027                if let Some(start) = start {1028                    self.resolve_anon_const(start, AnonConstKind::ConstArg(IsRepeatExpr::No));1029                }1030                if let Some(end) = end {1031                    self.resolve_anon_const(end, AnonConstKind::ConstArg(IsRepeatExpr::No));1032                }1033            }1034            TyPatKind::Or(patterns) => {1035                for pat in patterns {1036                    self.visit_ty_pat(pat)1037                }1038            }1039            TyPatKind::NotNull | TyPatKind::Err(_) => {}1040        }1041    }10421043    fn visit_poly_trait_ref(&mut self, tref: &'ast PolyTraitRef) {1044        let span = tref.span.shrink_to_lo().to(tref.trait_ref.path.span.shrink_to_lo());1045        self.with_generic_param_rib(1046            &tref.bound_generic_params,1047            RibKind::Normal,1048            tref.trait_ref.ref_id,1049            LifetimeBinderKind::PolyTrait,1050            span,1051            |this| {1052                this.visit_generic_params(&tref.bound_generic_params, false);1053                this.smart_resolve_path(1054                    tref.trait_ref.ref_id,1055                    &None,1056                    &tref.trait_ref.path,1057                    PathSource::Trait(AliasPossibility::Maybe),1058                );1059                this.visit_trait_ref(&tref.trait_ref);1060            },1061        );1062    }1063    fn visit_foreign_item(&mut self, foreign_item: &'ast ForeignItem) {1064        with_owner(self, foreign_item.id, |this| {1065            this.resolve_doc_links(&foreign_item.attrs, MaybeExported::Ok(foreign_item.id));1066            let def_kind = this.r.tcx.def_kind(this.r.current_owner.def_id);1067            match foreign_item.kind {1068                ForeignItemKind::TyAlias(TyAlias { ref generics, .. }) => {1069                    this.with_generic_param_rib(1070                        &generics.params,1071                        RibKind::Item(HasGenericParams::Yes(generics.span), def_kind),1072                        foreign_item.id,1073                        LifetimeBinderKind::Item,1074                        generics.span,1075                        |this| visit::walk_item(this, foreign_item),1076                    );1077                }1078                ForeignItemKind::Fn(Fn { ref generics, .. }) => {1079                    this.with_generic_param_rib(1080                        &generics.params,1081                        RibKind::Item(HasGenericParams::Yes(generics.span), def_kind),1082                        foreign_item.id,1083                        LifetimeBinderKind::Function,1084                        generics.span,1085                        |this| visit::walk_item(this, foreign_item),1086                    );1087                }1088                ForeignItemKind::Static(..) => {1089                    this.with_static_rib(def_kind, |this| visit::walk_item(this, foreign_item))1090                }1091                ForeignItemKind::MacCall(..) => {1092                    panic!("unexpanded macro in resolve!")1093                }1094            }1095        })1096    }1097    fn visit_fn(&mut self, fn_kind: FnKind<'ast>, _: &AttrVec, sp: Span, fn_id: NodeId) {1098        let previous_value = self.diag_metadata.current_function;1099        match fn_kind {1100            // Bail if the function is foreign, and thus cannot validly have1101            // a body, or if there's no body for some other reason.1102            FnKind::Fn(FnCtxt::Foreign, _, Fn { sig, ident, generics, .. })1103            | FnKind::Fn(_, _, Fn { sig, ident, generics, body: None, .. }) => {1104                self.visit_fn_header(&sig.header);1105                self.visit_ident(ident);1106                self.visit_generics(generics);1107                self.resolve_fn_signature(1108                    fn_id,1109                    sig.decl.has_self(),1110                    sig.decl.inputs.iter().map(|Param { ty, .. }| (None, &**ty)),1111                    &sig.decl.output,1112                    false,1113                );1114                return;1115            }1116            FnKind::Fn(..) => {1117                self.diag_metadata.current_function = Some((fn_kind, sp));1118            }1119            // Do not update `current_function` for closures: it suggests `self` parameters.1120            FnKind::Closure(..) => {}1121        };1122        debug!("(resolving function) entering function");11231124        if let FnKind::Fn(_, _, f) = fn_kind {1125            self.resolve_eii(&f.eii_impls);1126        }11271128        // Create a value rib for the function.1129        self.with_rib(ValueNS, RibKind::FnOrCoroutine, |this| {1130            // Create a label rib for the function.1131            this.with_label_rib(RibKind::FnOrCoroutine, |this| {1132                match fn_kind {1133                    FnKind::Fn(_, _, Fn { sig, generics, contract, body, .. }) => {1134                        this.visit_generics(generics);11351136                        let declaration = &sig.decl;1137                        let coro_node_id = sig1138                            .header1139                            .coroutine_kind1140                            .map(|coroutine_kind| coroutine_kind.return_id());11411142                        this.resolve_fn_signature(1143                            fn_id,1144                            declaration.has_self(),1145                            declaration1146                                .inputs1147                                .iter()1148                                .map(|Param { pat, ty, .. }| (Some(&**pat), &**ty)),1149                            &declaration.output,1150                            coro_node_id.is_some(),1151                        );11521153                        if let Some(contract) = contract {1154                            this.visit_contract(contract);1155                        }11561157                        if let Some(body) = body {1158                            // Ignore errors in function bodies if this is rustdoc1159                            // Be sure not to set this until the function signature has been resolved.1160                            let previous_state = replace(&mut this.in_func_body, true);1161                            // We only care block in the same function1162                            this.last_block_rib = None;1163                            // Resolve the function body, potentially inside the body of an async closure1164                            this.with_lifetime_rib(1165                                LifetimeRibKind::Elided(LifetimeRes::Infer),1166                                |this| this.visit_block(body),1167                            );11681169                            debug!("(resolving function) leaving function");1170                            this.in_func_body = previous_state;1171                        }1172                    }1173                    FnKind::Closure(binder, _, declaration, body) => {1174                        this.visit_closure_binder(binder);11751176                        this.with_lifetime_rib(1177                            match binder {1178                                // We do not have any explicit generic lifetime parameter.1179                                ClosureBinder::NotPresent => {1180                                    LifetimeRibKind::AnonymousCreateParameter {1181                                        binder: fn_id,1182                                        report_in_path: false,1183                                    }1184                                }1185                                ClosureBinder::For { .. } => LifetimeRibKind::AnonymousReportError,1186                            },1187                            // Add each argument to the rib.1188                            |this| this.resolve_params(&declaration.inputs),1189                        );1190                        this.with_lifetime_rib(1191                            match binder {1192                                ClosureBinder::NotPresent => {1193                                    LifetimeRibKind::Elided(LifetimeRes::Infer)1194                                }1195                                ClosureBinder::For { .. } => LifetimeRibKind::AnonymousReportError,1196                            },1197                            |this| visit::walk_fn_ret_ty(this, &declaration.output),1198                        );11991200                        // Ignore errors in function bodies if this is rustdoc1201                        // Be sure not to set this until the function signature has been resolved.1202                        let previous_state = replace(&mut this.in_func_body, true);1203                        // Resolve the function body, potentially inside the body of an async closure1204                        this.with_lifetime_rib(1205                            LifetimeRibKind::Elided(LifetimeRes::Infer),1206                            |this| this.visit_expr(body),1207                        );12081209                        debug!("(resolving function) leaving function");1210                        this.in_func_body = previous_state;1211                    }1212                }1213            })1214        });1215        self.diag_metadata.current_function = previous_value;1216    }12171218    fn visit_lifetime(&mut self, lifetime: &'ast Lifetime, use_ctxt: visit::LifetimeCtxt) {1219        self.resolve_lifetime(lifetime, use_ctxt)1220    }12211222    fn visit_precise_capturing_arg(&mut self, arg: &'ast PreciseCapturingArg) {1223        match arg {1224            // Lower the lifetime regularly; we'll resolve the lifetime and check1225            // it's a parameter later on in HIR lowering.1226            PreciseCapturingArg::Lifetime(_) => {}12271228            PreciseCapturingArg::Arg(path, id) => {1229                // we want `impl use<C>` to try to resolve `C` as both a type parameter or1230                // a const parameter. Since the resolver specifically doesn't allow having1231                // two generic params with the same name, even if they're a different namespace,1232                // it doesn't really matter which we try resolving first, but just like1233                // `Ty::Param` we just fall back to the value namespace only if it's missing1234                // from the type namespace.1235                let mut check_ns = |ns| {1236                    self.maybe_resolve_ident_in_lexical_scope(path.segments[0].ident, ns).is_some()1237                };1238                // Like `Ty::Param`, we try resolving this as both a const and a type.1239                if !check_ns(TypeNS) && check_ns(ValueNS) {1240                    self.smart_resolve_path(1241                        *id,1242                        &None,1243                        path,1244                        PathSource::PreciseCapturingArg(ValueNS),1245                    );1246                } else {1247                    self.smart_resolve_path(1248                        *id,1249                        &None,1250                        path,1251                        PathSource::PreciseCapturingArg(TypeNS),1252                    );1253                }1254            }1255        }12561257        visit::walk_precise_capturing_arg(self, arg)1258    }12591260    fn visit_generics(&mut self, generics: &'ast Generics) {1261        self.visit_generic_params(&generics.params, self.diag_metadata.current_self_item.is_some());1262        for p in &generics.where_clause.predicates {1263            self.visit_where_predicate(p);1264        }1265    }12661267    fn visit_closure_binder(&mut self, b: &'ast ClosureBinder) {1268        match b {1269            ClosureBinder::NotPresent => {}1270            ClosureBinder::For { generic_params, .. } => {1271                self.visit_generic_params(1272                    generic_params,1273                    self.diag_metadata.current_self_item.is_some(),1274                );1275            }1276        }1277    }12781279    fn visit_generic_arg(&mut self, arg: &'ast GenericArg) {1280        debug!("visit_generic_arg({:?})", arg);1281        let prev = replace(&mut self.diag_metadata.currently_processing_generic_args, true);1282        match arg {1283            GenericArg::Type(ty) => {1284                // We parse const arguments as path types as we cannot distinguish them during1285                // parsing. We try to resolve that ambiguity by attempting resolution the type1286                // namespace first, and if that fails we try again in the value namespace. If1287                // resolution in the value namespace succeeds, we have an generic const argument on1288                // our hands.1289                if let TyKind::Path(None, ref path) = ty.kind1290                    // We cannot disambiguate multi-segment paths right now as that requires type1291                    // checking.1292                    && path.is_potential_trivial_const_arg()1293                {1294                    let mut check_ns = |ns| {1295                        self.maybe_resolve_ident_in_lexical_scope(path.segments[0].ident, ns)1296                            .is_some()1297                    };1298                    if !check_ns(TypeNS) && check_ns(ValueNS) {1299                        self.resolve_anon_const_manual(1300                            true,1301                            AnonConstKind::ConstArg(IsRepeatExpr::No),1302                            |this| {1303                                this.smart_resolve_path(ty.id, &None, path, PathSource::Expr(None));1304                                this.visit_path(path);1305                            },1306                        );13071308                        self.diag_metadata.currently_processing_generic_args = prev;1309                        return;1310                    }1311                }13121313                self.visit_ty(ty);1314            }1315            GenericArg::Lifetime(lt) => self.visit_lifetime(lt, visit::LifetimeCtxt::GenericArg),1316            GenericArg::Const(ct) => {1317                self.resolve_anon_const(ct, AnonConstKind::ConstArg(IsRepeatExpr::No))1318            }1319        }1320        self.diag_metadata.currently_processing_generic_args = prev;1321    }13221323    fn visit_assoc_item_constraint(&mut self, constraint: &'ast AssocItemConstraint) {1324        self.visit_ident(&constraint.ident);1325        if let Some(ref gen_args) = constraint.gen_args {1326            // Forbid anonymous lifetimes in GAT parameters until proper semantics are decided.1327            self.with_lifetime_rib(LifetimeRibKind::AnonymousReportError, |this| {1328                this.visit_generic_args(gen_args)1329            });1330        }1331        match constraint.kind {1332            AssocItemConstraintKind::Equality { ref term } => match term {1333                Term::Ty(ty) => {1334                    let prev = replace(&mut self.diag_metadata.in_assoc_ty_binding, true);1335                    self.visit_ty(ty);1336                    self.diag_metadata.in_assoc_ty_binding = prev;1337                }1338                Term::Const(c) => {1339                    self.resolve_anon_const(c, AnonConstKind::ConstArg(IsRepeatExpr::No))1340                }1341            },1342            AssocItemConstraintKind::Bound { ref bounds } => {1343                walk_list!(self, visit_param_bound, bounds, BoundKind::Bound);1344            }1345        }1346    }13471348    fn visit_path_segment(&mut self, path_segment: &'ast PathSegment) {1349        let Some(ref args) = path_segment.args else {1350            return;1351        };13521353        match &**args {1354            GenericArgs::AngleBracketed(..) => visit::walk_generic_args(self, args),1355            GenericArgs::Parenthesized(p_args) => {1356                // Probe the lifetime ribs to know how to behave.1357                for rib in self.lifetime_ribs.iter().rev() {1358                    match rib.kind {1359                        // We are inside a `PolyTraitRef`. The lifetimes are1360                        // to be introduced in that (maybe implicit) `for<>` binder.1361                        LifetimeRibKind::Generics {1362                            binder,1363                            kind: LifetimeBinderKind::PolyTrait,1364                            ..1365                        } => {1366                            self.resolve_fn_signature(1367                                binder,1368                                false,1369                                p_args.inputs.iter().map(|ty| (None, &**ty)),1370                                &p_args.output,1371                                false,1372                            );1373                            break;1374                        }1375                        // We have nowhere to introduce generics. Code is malformed,1376                        // so use regular lifetime resolution to avoid spurious errors.1377                        LifetimeRibKind::Item | LifetimeRibKind::Generics { .. } => {1378                            visit::walk_generic_args(self, args);1379                            break;1380                        }1381                        LifetimeRibKind::AnonymousCreateParameter { .. }1382                        | LifetimeRibKind::AnonymousReportError1383                        | LifetimeRibKind::StaticIfNoLifetimeInScope { .. }1384                        | LifetimeRibKind::ImplTrait1385                        | LifetimeRibKind::Elided(_)1386                        | LifetimeRibKind::ElisionFailure1387                        | LifetimeRibKind::ConcreteAnonConst(_)1388                        | LifetimeRibKind::ConstParamTy => {}1389                    }1390                }1391            }1392            GenericArgs::ParenthesizedElided(_) => {}1393        }1394    }13951396    fn visit_where_predicate(&mut self, p: &'ast WherePredicate) {1397        debug!("visit_where_predicate {:?}", p);1398        let previous_value = replace(&mut self.diag_metadata.current_where_predicate, Some(p));1399        self.with_lifetime_rib(LifetimeRibKind::AnonymousReportError, |this| {1400            if let WherePredicateKind::BoundPredicate(WhereBoundPredicate {1401                bounded_ty,1402                bounds,1403                bound_generic_params,1404                ..1405            }) = &p.kind1406            {1407                let span = p.span.shrink_to_lo().to(bounded_ty.span.shrink_to_lo());1408                this.with_generic_param_rib(1409                    bound_generic_params,1410                    RibKind::Normal,1411                    bounded_ty.id,1412                    LifetimeBinderKind::WhereBound,1413                    span,1414                    |this| {1415                        this.visit_generic_params(bound_generic_params, false);1416                        this.visit_ty(bounded_ty);1417                        for bound in bounds {1418                            this.visit_param_bound(bound, BoundKind::Bound)1419                        }1420                    },1421                );1422            } else {1423                visit::walk_where_predicate(this, p);1424            }1425        });1426        self.diag_metadata.current_where_predicate = previous_value;1427    }14281429    fn visit_inline_asm(&mut self, asm: &'ast InlineAsm) {1430        for (op, _) in &asm.operands {1431            match op {1432                InlineAsmOperand::In { expr, .. }1433                | InlineAsmOperand::Out { expr: Some(expr), .. }1434                | InlineAsmOperand::InOut { expr, .. } => self.visit_expr(expr),1435                InlineAsmOperand::Out { expr: None, .. } => {}1436                InlineAsmOperand::SplitInOut { in_expr, out_expr, .. } => {1437                    self.visit_expr(in_expr);1438                    if let Some(out_expr) = out_expr {1439                        self.visit_expr(out_expr);1440                    }1441                }1442                InlineAsmOperand::Const { anon_const, .. } => {1443                    // Although this is `DefKind::AnonConst`, it is allowed to reference outer1444                    // generic parameters like an inline const.1445                    self.resolve_anon_const(anon_const, AnonConstKind::InlineConst);1446                }1447                InlineAsmOperand::Sym { sym } => self.visit_inline_asm_sym(sym),1448                InlineAsmOperand::Label { block } => self.visit_block(block),1449            }1450        }1451    }14521453    fn visit_inline_asm_sym(&mut self, sym: &'ast InlineAsmSym) {1454        // This is similar to the code for AnonConst.1455        self.with_rib(ValueNS, RibKind::InlineAsmSym, |this| {1456            this.with_rib(TypeNS, RibKind::InlineAsmSym, |this| {1457                this.with_label_rib(RibKind::InlineAsmSym, |this| {1458                    this.smart_resolve_path(sym.id, &sym.qself, &sym.path, PathSource::Expr(None));1459                    visit::walk_inline_asm_sym(this, sym);1460                });1461            })1462        });1463    }14641465    fn visit_variant(&mut self, v: &'ast Variant) {1466        self.resolve_doc_links(&v.attrs, MaybeExported::Ok(v.id));1467        self.visit_id(v.id);1468        walk_list!(self, visit_attribute, &v.attrs);1469        self.visit_vis(&v.vis);1470        self.visit_ident(&v.ident);1471        self.visit_variant_data(&v.data);1472        if let Some(discr) = &v.disr_expr {1473            self.resolve_anon_const(discr, AnonConstKind::EnumDiscriminant);1474        }1475    }14761477    fn visit_field_def(&mut self, f: &'ast FieldDef) {1478        self.resolve_doc_links(&f.attrs, MaybeExported::Ok(f.id));1479        let FieldDef {1480            attrs,1481            id: _,1482            span: _,1483            vis,1484            ident,1485            ty,1486            is_placeholder: _,1487            default,1488            mut_restriction: _,1489            safety: _,1490        } = f;1491        walk_list!(self, visit_attribute, attrs);1492        try_visit!(self.visit_vis(vis));1493        visit_opt!(self, visit_ident, ident);1494        try_visit!(self.visit_ty(ty));1495        if let Some(v) = &default {1496            self.resolve_anon_const(v, AnonConstKind::FieldDefaultValue);1497        }1498    }1499}15001501impl<'a, 'ast, 'ra, 'tcx> LateResolutionVisitor<'a, 'ast, 'ra, 'tcx> {1502    fn new(resolver: &'a mut Resolver<'ra, 'tcx>) -> LateResolutionVisitor<'a, 'ast, 'ra, 'tcx> {1503        // During late resolution we only track the module component of the parent scope,1504        // although it may be useful to track other components as well for diagnostics.1505        let graph_root = resolver.graph_root;1506        let parent_scope = ParentScope::module(graph_root, resolver.arenas);1507        let start_rib_kind = RibKind::Module(graph_root);1508        LateResolutionVisitor {1509            r: resolver,1510            parent_scope,1511            ribs: PerNS {1512                value_ns: vec![Rib::new(start_rib_kind)],1513                type_ns: vec![Rib::new(start_rib_kind)],1514                macro_ns: vec![Rib::new(start_rib_kind)],1515            },1516            last_block_rib: None,1517            label_ribs: Vec::new(),1518            lifetime_ribs: Vec::new(),1519            lifetime_elision_candidates: None,1520            current_trait_ref: None,1521            diag_metadata: Default::default(),1522            // errors at module scope should always be reported1523            in_func_body: false,1524            lifetime_uses: Default::default(),1525        }1526    }15271528    fn maybe_resolve_ident_in_lexical_scope(1529        &mut self,1530        ident: Ident,1531        ns: Namespace,1532    ) -> Option<LateDecl<'ra>> {1533        self.r.resolve_ident_in_lexical_scope(1534            ident,1535            ns,1536            &self.parent_scope,1537            None,1538            &self.ribs[ns],1539            None,1540            Some(&self.diag_metadata),1541        )1542    }15431544    fn resolve_ident_in_lexical_scope(1545        &mut self,1546        ident: Ident,1547        ns: Namespace,1548        finalize: Option<Finalize>,1549        ignore_decl: Option<Decl<'ra>>,1550    ) -> Option<LateDecl<'ra>> {1551        self.r.resolve_ident_in_lexical_scope(1552            ident,1553            ns,1554            &self.parent_scope,1555            finalize,1556            &self.ribs[ns],1557            ignore_decl,1558            Some(&self.diag_metadata),1559        )1560    }15611562    fn resolve_path(1563        &mut self,1564        path: &[Segment],1565        opt_ns: Option<Namespace>, // `None` indicates a module path in import1566        finalize: Option<Finalize>,1567        source: PathSource<'_, 'ast, 'ra>,1568    ) -> PathResult<'ra> {1569        self.r.cm().resolve_path_with_ribs(1570            path,1571            opt_ns,1572            &self.parent_scope,1573            Some(source),1574            finalize.map(|finalize| Finalize { stage: Stage::Late, ..finalize }),1575            Some(&self.ribs),1576            None,1577            None,1578            Some(&self.diag_metadata),1579        )1580    }15811582    // AST resolution1583    //1584    // We maintain a list of value ribs and type ribs.1585    //1586    // Simultaneously, we keep track of the current position in the module1587    // graph in the `parent_scope.module` pointer. When we go to resolve a name in1588    // the value or type namespaces, we first look through all the ribs and1589    // then query the module graph. When we resolve a name in the module1590    // namespace, we can skip all the ribs (since nested modules are not1591    // allowed within blocks in Rust) and jump straight to the current module1592    // graph node.1593    //1594    // Named implementations are handled separately. When we find a method1595    // call, we consult the module node to find all of the implementations in1596    // scope. This information is lazily cached in the module node. We then1597    // generate a fake "implementation scope" containing all the1598    // implementations thus found, for compatibility with old resolve pass.15991600    /// Do some `work` within a new innermost rib of the given `kind` in the given namespace (`ns`).1601    fn with_rib<T>(1602        &mut self,1603        ns: Namespace,1604        kind: RibKind<'ra>,1605        work: impl FnOnce(&mut Self) -> T,1606    ) -> T {1607        self.ribs[ns].push(Rib::new(kind));1608        let ret = work(self);1609        self.ribs[ns].pop();1610        ret1611    }16121613    fn visit_generic_params(&mut self, params: &'ast [GenericParam], add_self_upper: bool) {1614        // For type parameter defaults, we have to ban access1615        // to following type parameters, as the GenericArgs can only1616        // provide previous type parameters as they're built. We1617        // put all the parameters on the ban list and then remove1618        // them one by one as they are processed and become available.1619        let mut forward_ty_ban_rib =1620            Rib::new(RibKind::ForwardGenericParamBan(ForwardGenericParamBanReason::Default));1621        let mut forward_const_ban_rib =1622            Rib::new(RibKind::ForwardGenericParamBan(ForwardGenericParamBanReason::Default));1623        for param in params.iter() {1624            match param.kind {1625                GenericParamKind::Type { .. } => {1626                    forward_ty_ban_rib1627                        .bindings1628                        .insert(Ident::with_dummy_span(param.ident.name), Res::Err);1629                }1630                GenericParamKind::Const { .. } => {1631                    forward_const_ban_rib1632                        .bindings1633                        .insert(Ident::with_dummy_span(param.ident.name), Res::Err);1634                }1635                GenericParamKind::Lifetime => {}1636            }1637        }16381639        // rust-lang/rust#61631: The type `Self` is essentially1640        // another type parameter. For ADTs, we consider it1641        // well-defined only after all of the ADT type parameters have1642        // been provided. Therefore, we do not allow use of `Self`1643        // anywhere in ADT type parameter defaults.1644        //1645        // (We however cannot ban `Self` for defaults on *all* generic1646        // lists; e.g. trait generics can usefully refer to `Self`,1647        // such as in the case of `trait Add<Rhs = Self>`.)1648        if add_self_upper {1649            // (`Some` if + only if we are in ADT's generics.)1650            forward_ty_ban_rib.bindings.insert(Ident::with_dummy_span(kw::SelfUpper), Res::Err);1651        }16521653        // NOTE: We use different ribs here not for a technical reason, but just1654        // for better diagnostics.1655        let mut forward_ty_ban_rib_const_param_ty = Rib {1656            bindings: forward_ty_ban_rib.bindings.clone(),1657            patterns_with_skipped_bindings: Default::default(),1658            kind: RibKind::ForwardGenericParamBan(ForwardGenericParamBanReason::ConstParamTy),1659        };1660        let mut forward_const_ban_rib_const_param_ty = Rib {1661            bindings: forward_const_ban_rib.bindings.clone(),1662            patterns_with_skipped_bindings: Default::default(),1663            kind: RibKind::ForwardGenericParamBan(ForwardGenericParamBanReason::ConstParamTy),1664        };1665        // We'll ban these with a `ConstParamTy` rib, so just clear these ribs for better1666        // diagnostics, so we don't mention anything about const param tys having generics at all.1667        if !self.r.tcx.features().generic_const_parameter_types() {1668            forward_ty_ban_rib_const_param_ty.bindings.clear();1669            forward_const_ban_rib_const_param_ty.bindings.clear();1670        }16711672        self.with_lifetime_rib(LifetimeRibKind::AnonymousReportError, |this| {1673            for param in params {1674                match param.kind {1675                    GenericParamKind::Lifetime => {1676                        for bound in &param.bounds {1677                            this.visit_param_bound(bound, BoundKind::Bound);1678                        }1679                    }1680                    GenericParamKind::Type { ref default } => {1681                        for bound in &param.bounds {1682                            this.visit_param_bound(bound, BoundKind::Bound);1683                        }16841685                        if let Some(ty) = default {1686                            this.ribs[TypeNS].push(forward_ty_ban_rib);1687                            this.ribs[ValueNS].push(forward_const_ban_rib);1688                            this.visit_ty(ty);1689                            forward_const_ban_rib = this.ribs[ValueNS].pop().unwrap();1690                            forward_ty_ban_rib = this.ribs[TypeNS].pop().unwrap();1691                        }16921693                        // Allow all following defaults to refer to this type parameter.1694                        let i = &Ident::with_dummy_span(param.ident.name);1695                        forward_ty_ban_rib.bindings.swap_remove(i);1696                        forward_ty_ban_rib_const_param_ty.bindings.swap_remove(i);1697                    }1698                    GenericParamKind::Const { ref ty, span: _, ref default } => {1699                        // Const parameters can't have param bounds.1700                        assert!(param.bounds.is_empty());17011702                        this.ribs[TypeNS].push(forward_ty_ban_rib_const_param_ty);1703                        this.ribs[ValueNS].push(forward_const_ban_rib_const_param_ty);1704                        if this.r.tcx.features().generic_const_parameter_types() {1705                            this.visit_ty(ty)1706                        } else {1707                            this.ribs[TypeNS].push(Rib::new(RibKind::ConstParamTy));1708                            this.ribs[ValueNS].push(Rib::new(RibKind::ConstParamTy));1709                            this.with_lifetime_rib(LifetimeRibKind::ConstParamTy, |this| {1710                                this.visit_ty(ty)1711                            });1712                            this.ribs[TypeNS].pop().unwrap();1713                            this.ribs[ValueNS].pop().unwrap();1714                        }1715                        forward_const_ban_rib_const_param_ty = this.ribs[ValueNS].pop().unwrap();1716                        forward_ty_ban_rib_const_param_ty = this.ribs[TypeNS].pop().unwrap();17171718                        if let Some(expr) = default {1719                            this.ribs[TypeNS].push(forward_ty_ban_rib);1720                            this.ribs[ValueNS].push(forward_const_ban_rib);1721                            this.resolve_anon_const(1722                                expr,1723                                AnonConstKind::ConstArg(IsRepeatExpr::No),1724                            );1725                            forward_const_ban_rib = this.ribs[ValueNS].pop().unwrap();1726                            forward_ty_ban_rib = this.ribs[TypeNS].pop().unwrap();1727                        }17281729                        // Allow all following defaults to refer to this const parameter.1730                        let i = &Ident::with_dummy_span(param.ident.name);1731                        forward_const_ban_rib.bindings.swap_remove(i);1732                        forward_const_ban_rib_const_param_ty.bindings.swap_remove(i);1733                    }1734                }1735            }1736        })1737    }17381739    #[instrument(level = "debug", skip(self, work))]1740    fn with_lifetime_rib<T>(1741        &mut self,1742        kind: LifetimeRibKind,1743        work: impl FnOnce(&mut Self) -> T,1744    ) -> T {1745        self.lifetime_ribs.push(LifetimeRib::new(kind));1746        let outer_elision_candidates = self.lifetime_elision_candidates.take();1747        let ret = work(self);1748        self.lifetime_elision_candidates = outer_elision_candidates;1749        self.lifetime_ribs.pop();1750        ret1751    }17521753    #[instrument(level = "debug", skip(self))]1754    fn resolve_lifetime(&mut self, lifetime: &'ast Lifetime, use_ctxt: visit::LifetimeCtxt) {1755        let ident = lifetime.ident;17561757        if ident.name == kw::StaticLifetime {1758            self.record_lifetime_use(1759                lifetime.id,1760                LifetimeRes::Static,1761                LifetimeElisionCandidate::Ignore,1762            );1763            return;1764        }17651766        if ident.name == kw::UnderscoreLifetime {1767            return self.resolve_anonymous_lifetime(lifetime, lifetime.id, false);1768        }17691770        let mut lifetime_rib_iter = self.lifetime_ribs.iter().rev();1771        while let Some(rib) = lifetime_rib_iter.next() {1772            let normalized_ident = ident.normalize_to_macros_2_0();1773            if let Some(&(_, res)) = rib.bindings.get(&normalized_ident) {1774                self.record_lifetime_use(lifetime.id, res, LifetimeElisionCandidate::Ignore);17751776                if let LifetimeRes::Param { param, binder } = res {1777                    match self.lifetime_uses.entry(param) {1778                        Entry::Vacant(v) => {1779                            debug!("First use of {:?} at {:?}", res, ident.span);1780                            let use_set = self1781                                .lifetime_ribs1782                                .iter()1783                                .rev()1784                                .find_map(|rib| match rib.kind {1785                                    // Do not suggest eliding a lifetime where an anonymous1786                                    // lifetime would be illegal.1787                                    LifetimeRibKind::Item1788                                    | LifetimeRibKind::AnonymousReportError1789                                    | LifetimeRibKind::StaticIfNoLifetimeInScope { .. }1790                                    | LifetimeRibKind::ElisionFailure => Some(LifetimeUseSet::Many),1791                                    // An anonymous lifetime is legal here, and bound to the right1792                                    // place, go ahead.1793                                    LifetimeRibKind::AnonymousCreateParameter {1794                                        binder: anon_binder,1795                                        ..1796                                    } => Some(if binder == anon_binder {1797                                        LifetimeUseSet::One { use_span: ident.span, use_ctxt }1798                                    } else {1799                                        LifetimeUseSet::Many1800                                    }),1801                                    // Only report if eliding the lifetime would have the same1802                                    // semantics.1803                                    LifetimeRibKind::Elided(r) => Some(if res == r {1804                                        LifetimeUseSet::One { use_span: ident.span, use_ctxt }1805                                    } else {1806                                        LifetimeUseSet::Many1807                                    }),1808                                    LifetimeRibKind::Generics { .. }1809                                    | LifetimeRibKind::ConstParamTy => None,1810                                    LifetimeRibKind::ConcreteAnonConst(_) => {1811                                        span_bug!(ident.span, "unexpected rib kind: {:?}", rib.kind)1812                                    }18131814                                    LifetimeRibKind::ImplTrait => {1815                                        if self.r.tcx.features().anonymous_lifetime_in_impl_trait()1816                                        {1817                                            None1818                                        } else {1819                                            Some(LifetimeUseSet::Many)1820                                        }1821                                    }1822                                })1823                                .unwrap_or(LifetimeUseSet::Many);1824                            debug!(?use_ctxt, ?use_set);1825                            v.insert(use_set);1826                        }1827                        Entry::Occupied(mut o) => {1828                            debug!("Many uses of {:?} at {:?}", res, ident.span);1829                            *o.get_mut() = LifetimeUseSet::Many;1830                        }1831                    }1832                }1833                return;1834            }18351836            match rib.kind {1837                LifetimeRibKind::Item => break,1838                LifetimeRibKind::ConstParamTy => {1839                    let guar = self.emit_non_static_lt_in_const_param_ty_error(lifetime);1840                    self.record_lifetime_err(lifetime.id, guar);1841                    return;1842                }1843                LifetimeRibKind::ConcreteAnonConst(cause) => {1844                    let guar = self.emit_forbidden_non_static_lifetime_error(cause, lifetime);1845                    self.record_lifetime_err(lifetime.id, guar);1846                    return;1847                }1848                LifetimeRibKind::AnonymousCreateParameter { .. }1849                | LifetimeRibKind::Elided(_)1850                | LifetimeRibKind::Generics { .. }1851                | LifetimeRibKind::ElisionFailure1852                | LifetimeRibKind::AnonymousReportError1853                | LifetimeRibKind::ImplTrait1854                | LifetimeRibKind::StaticIfNoLifetimeInScope { .. } => {}1855            }1856        }18571858        let normalized_ident = ident.normalize_to_macros_2_0();1859        let outer_res = lifetime_rib_iter1860            .find_map(|rib| rib.bindings.get_key_value(&normalized_ident).map(|(&outer, _)| outer));18611862        let guar = self.emit_undeclared_lifetime_error(lifetime, outer_res);1863        self.record_lifetime_err(lifetime.id, guar);1864    }18651866    #[instrument(level = "debug", skip(self))]1867    fn resolve_anonymous_lifetime(1868        &mut self,1869        lifetime: &Lifetime,1870        id_for_lint: NodeId,1871        elided: bool,1872    ) {1873        debug_assert_eq!(lifetime.ident.name, kw::UnderscoreLifetime);18741875        let kind =1876            if elided { MissingLifetimeKind::Ampersand } else { MissingLifetimeKind::Underscore };1877        let missing_lifetime = MissingLifetime {1878            id: lifetime.id,1879            span: lifetime.ident.span,1880            kind,1881            count: 1,1882            id_for_lint,1883        };1884        let elision_candidate = LifetimeElisionCandidate::Missing(missing_lifetime);1885        for (i, rib) in self.lifetime_ribs.iter().enumerate().rev() {1886            debug!(?rib.kind);1887            match rib.kind {1888                LifetimeRibKind::AnonymousCreateParameter { binder, .. } => {1889                    let res = self.create_fresh_lifetime(lifetime.ident, binder, kind);1890                    self.record_lifetime_use(lifetime.id, res, elision_candidate);1891                    return;1892                }1893                LifetimeRibKind::StaticIfNoLifetimeInScope { lint_id: node_id, emit_lint } => {1894                    let mut lifetimes_in_scope = vec![];1895                    for rib in self.lifetime_ribs[..i].iter().rev() {1896                        lifetimes_in_scope.extend(rib.bindings.iter().map(|(ident, _)| ident.span));1897                        // Consider any anonymous lifetimes, too1898                        if let LifetimeRibKind::AnonymousCreateParameter { binder, .. } = rib.kind1899                            && let Some(extra) = self.r.extra_lifetime_params_map.get(&binder)1900                        {1901                            lifetimes_in_scope.extend(extra.iter().map(|(ident, _, _)| ident.span));1902                        }1903                        if let LifetimeRibKind::Item = rib.kind {1904                            break;1905                        }1906                    }1907                    if lifetimes_in_scope.is_empty() {1908                        self.record_lifetime_use(1909                            lifetime.id,1910                            LifetimeRes::Static,1911                            elision_candidate,1912                        );1913                        return;1914                    } else if emit_lint {1915                        let lt_span = if elided {1916                            lifetime.ident.span.shrink_to_hi()1917                        } else {1918                            lifetime.ident.span1919                        };1920                        let code = if elided { "'static " } else { "'static" };19211922                        self.r.lint_buffer.buffer_lint(1923                            lint::builtin::ELIDED_LIFETIMES_IN_ASSOCIATED_CONSTANT,1924                            node_id,1925                            lifetime.ident.span,1926                            crate::diagnostics::AssociatedConstElidedLifetime {1927                                elided,1928                                code,1929                                span: lt_span,1930                                lifetimes_in_scope: lifetimes_in_scope.into(),1931                            },1932                        );1933                    }1934                }1935                LifetimeRibKind::AnonymousReportError => {1936                    let guar = if elided {1937                        let suggestion = if self.diag_metadata.in_assoc_ty_binding {1938                            // In an associated type binding like `I: IntoIterator<Item = &T>`,1939                            // introducing the lifetime on the trait ref would produce1940                            // `I: for<'a> IntoIterator<Item = &'a T>`. Prefer a named lifetime1941                            // from an enclosing item instead, so the assoc-ty-binding-specific path1942                            // below builds that suggestion.1943                            None1944                        } else {1945                            self.lifetime_ribs[i..].iter().rev().find_map(|rib| {1946                                // Look for a `Generics` rib that represents a trait or where-bound1947                                // binder (`T: Trait<&U>` or `where T: Trait<&U>`), since that is1948                                // where the generic E0637 diagnostic can insert `for<'a>`.1949                                if let LifetimeRibKind::Generics {1950                                    span,1951                                    kind:1952                                        LifetimeBinderKind::PolyTrait1953                                        | LifetimeBinderKind::WhereBound,1954                                    ..1955                                } = rib.kind1956                                {1957                                    Some(crate::diagnostics::ElidedAnonymousLifetimeReportErrorSuggestion {1958                                        lo: span.shrink_to_lo(),1959                                        hi: lifetime.ident.span.shrink_to_hi(),1960                                    })1961                                } else {1962                                    None1963                                }1964                            })1965                        };1966                        // are we trying to use an anonymous lifetime1967                        // on a non GAT associated trait type?1968                        if !self.in_func_body1969                            && let Some((module, _)) = &self.current_trait_ref1970                            && let Some(ty) = &self.diag_metadata.current_self_type1971                            && Some(true) == self.diag_metadata.in_non_gat_assoc_type1972                            && let crate::ModuleKind::Def(DefKind::Trait, trait_id, _, _) =1973                                module.kind1974                        {1975                            if def_id_matches_path(1976                                self.r.tcx,1977                                trait_id,1978                                &["core", "iter", "traits", "iterator", "Iterator"],1979                            ) {1980                                self.r.dcx().emit_err(1981                                    crate::diagnostics::LendingIteratorReportError {1982                                        lifetime: lifetime.ident.span,1983                                        ty: ty.span,1984                                    },1985                                )1986                            } else {1987                                let decl = if !trait_id.is_local()1988                                    && let Some(assoc) = self.diag_metadata.current_impl_item1989                                    && let AssocItemKind::Type(_) = assoc.kind1990                                    && let assocs = self.r.tcx.associated_items(trait_id)1991                                    && let Some(ident) = assoc.kind.ident()1992                                    && let Some(assoc) = assocs.find_by_ident_and_kind(1993                                        self.r.tcx,1994                                        ident,1995                                        AssocTag::Type,1996                                        trait_id,1997                                    ) {1998                                    let mut decl: MultiSpan =1999                                        self.r.tcx.def_span(assoc.def_id).into();2000                                    decl.push_span_label(

Findings

✓ No findings reported for this file.

Get this view in your editor

Same data, no extra tab — call code_get_file + code_get_findings over MCP from Claude/Cursor/Copilot.