summaryrefslogtreecommitdiffstats
path: root/compiler/rustc_resolve/src/late
diff options
context:
space:
mode:
authorDaniel Baumann <daniel.baumann@progress-linux.org>2024-04-17 12:02:58 +0000
committerDaniel Baumann <daniel.baumann@progress-linux.org>2024-04-17 12:02:58 +0000
commit698f8c2f01ea549d77d7dc3338a12e04c11057b9 (patch)
tree173a775858bd501c378080a10dca74132f05bc50 /compiler/rustc_resolve/src/late
parentInitial commit. (diff)
downloadrustc-698f8c2f01ea549d77d7dc3338a12e04c11057b9.tar.xz
rustc-698f8c2f01ea549d77d7dc3338a12e04c11057b9.zip
Adding upstream version 1.64.0+dfsg1.upstream/1.64.0+dfsg1
Signed-off-by: Daniel Baumann <daniel.baumann@progress-linux.org>
Diffstat (limited to '')
-rw-r--r--compiler/rustc_resolve/src/late.rs3984
-rw-r--r--compiler/rustc_resolve/src/late/diagnostics.rs2369
-rw-r--r--compiler/rustc_resolve/src/late/lifetimes.rs2144
3 files changed, 8497 insertions, 0 deletions
diff --git a/compiler/rustc_resolve/src/late.rs b/compiler/rustc_resolve/src/late.rs
new file mode 100644
index 000000000..dea3eaecd
--- /dev/null
+++ b/compiler/rustc_resolve/src/late.rs
@@ -0,0 +1,3984 @@
+// ignore-tidy-filelength
+//! "Late resolution" is the pass that resolves most of names in a crate beside imports and macros.
+//! It runs when the crate is fully expanded and its module structure is fully built.
+//! So it just walks through the crate and resolves all the expressions, types, etc.
+//!
+//! If you wonder why there's no `early.rs`, that's because it's split into three files -
+//! `build_reduced_graph.rs`, `macros.rs` and `imports.rs`.
+
+use RibKind::*;
+
+use crate::{path_names_to_string, BindingError, Finalize, LexicalScopeBinding};
+use crate::{Module, ModuleOrUniformRoot, NameBinding, ParentScope, PathResult};
+use crate::{ResolutionError, Resolver, Segment, UseError};
+
+use rustc_ast::ptr::P;
+use rustc_ast::visit::{self, AssocCtxt, BoundKind, FnCtxt, FnKind, Visitor};
+use rustc_ast::*;
+use rustc_data_structures::fx::{FxHashMap, FxHashSet, FxIndexMap};
+use rustc_errors::DiagnosticId;
+use rustc_hir::def::Namespace::{self, *};
+use rustc_hir::def::{self, CtorKind, DefKind, LifetimeRes, PartialRes, PerNS};
+use rustc_hir::def_id::{DefId, LocalDefId, CRATE_DEF_ID};
+use rustc_hir::{PrimTy, TraitCandidate};
+use rustc_middle::middle::resolve_lifetime::Set1;
+use rustc_middle::ty::DefIdTree;
+use rustc_middle::{bug, span_bug};
+use rustc_session::lint;
+use rustc_span::symbol::{kw, sym, Ident, Symbol};
+use rustc_span::{BytePos, Span};
+use smallvec::{smallvec, SmallVec};
+
+use rustc_span::source_map::{respan, Spanned};
+use std::collections::{hash_map::Entry, BTreeSet};
+use std::mem::{replace, take};
+use tracing::debug;
+
+mod diagnostics;
+pub(crate) mod lifetimes;
+
+type Res = def::Res<NodeId>;
+
+type IdentMap<T> = FxHashMap<Ident, T>;
+
+/// Map from the name in a pattern to its binding mode.
+type BindingMap = IdentMap<BindingInfo>;
+
+use diagnostics::{
+ ElisionFnParameter, LifetimeElisionCandidate, MissingLifetime, MissingLifetimeKind,
+};
+
+#[derive(Copy, Clone, Debug)]
+struct BindingInfo {
+ span: Span,
+ binding_mode: BindingMode,
+}
+
+#[derive(Copy, Clone, PartialEq, Eq, Debug)]
+pub enum PatternSource {
+ Match,
+ Let,
+ For,
+ FnParam,
+}
+
+#[derive(Copy, Clone, Debug, PartialEq, Eq)]
+enum IsRepeatExpr {
+ No,
+ Yes,
+}
+
+impl PatternSource {
+ pub fn descr(self) -> &'static str {
+ match self {
+ PatternSource::Match => "match binding",
+ PatternSource::Let => "let binding",
+ PatternSource::For => "for binding",
+ PatternSource::FnParam => "function parameter",
+ }
+ }
+}
+
+/// Denotes whether the context for the set of already bound bindings is a `Product`
+/// or `Or` context. This is used in e.g., `fresh_binding` and `resolve_pattern_inner`.
+/// See those functions for more information.
+#[derive(PartialEq)]
+enum PatBoundCtx {
+ /// A product pattern context, e.g., `Variant(a, b)`.
+ Product,
+ /// An or-pattern context, e.g., `p_0 | ... | p_n`.
+ Or,
+}
+
+/// Does this the item (from the item rib scope) allow generic parameters?
+#[derive(Copy, Clone, Debug, Eq, PartialEq)]
+pub(crate) enum HasGenericParams {
+ Yes,
+ No,
+}
+
+impl HasGenericParams {
+ fn force_yes_if(self, b: bool) -> Self {
+ if b { Self::Yes } else { self }
+ }
+}
+
+#[derive(Copy, Clone, Debug, Eq, PartialEq)]
+pub(crate) enum ConstantItemKind {
+ Const,
+ Static,
+}
+
+/// The rib kind restricts certain accesses,
+/// e.g. to a `Res::Local` of an outer item.
+#[derive(Copy, Clone, Debug)]
+pub(crate) enum RibKind<'a> {
+ /// No restriction needs to be applied.
+ NormalRibKind,
+
+ /// We passed through an impl or trait and are now in one of its
+ /// methods or associated types. Allow references to ty params that impl or trait
+ /// binds. Disallow any other upvars (including other ty params that are
+ /// upvars).
+ AssocItemRibKind,
+
+ /// We passed through a closure. Disallow labels.
+ ClosureOrAsyncRibKind,
+
+ /// We passed through a function definition. Disallow upvars.
+ /// Permit only those const parameters that are specified in the function's generics.
+ FnItemRibKind,
+
+ /// We passed through an item scope. Disallow upvars.
+ ItemRibKind(HasGenericParams),
+
+ /// We're in a constant item. Can't refer to dynamic stuff.
+ ///
+ /// The item may reference generic parameters in trivial constant expressions.
+ /// All other constants aren't allowed to use generic params at all.
+ ConstantItemRibKind(HasGenericParams, Option<(Ident, ConstantItemKind)>),
+
+ /// We passed through a module.
+ ModuleRibKind(Module<'a>),
+
+ /// We passed through a `macro_rules!` statement
+ MacroDefinition(DefId),
+
+ /// All bindings in this rib are generic parameters that can't be used
+ /// from the default of a generic parameter because they're not declared
+ /// before said generic parameter. Also see the `visit_generics` override.
+ ForwardGenericParamBanRibKind,
+
+ /// We are inside of the type of a const parameter. Can't refer to any
+ /// parameters.
+ ConstParamTyRibKind,
+
+ /// We are inside a `sym` inline assembly operand. Can only refer to
+ /// globals.
+ InlineAsmSymRibKind,
+}
+
+impl RibKind<'_> {
+ /// Whether this rib kind contains generic parameters, as opposed to local
+ /// variables.
+ pub(crate) fn contains_params(&self) -> bool {
+ match self {
+ NormalRibKind
+ | ClosureOrAsyncRibKind
+ | FnItemRibKind
+ | ConstantItemRibKind(..)
+ | ModuleRibKind(_)
+ | MacroDefinition(_)
+ | ConstParamTyRibKind
+ | InlineAsmSymRibKind => false,
+ AssocItemRibKind | ItemRibKind(_) | ForwardGenericParamBanRibKind => true,
+ }
+ }
+
+ /// This rib forbids referring to labels defined in upwards ribs.
+ fn is_label_barrier(self) -> bool {
+ match self {
+ NormalRibKind | MacroDefinition(..) => false,
+
+ AssocItemRibKind
+ | ClosureOrAsyncRibKind
+ | FnItemRibKind
+ | ItemRibKind(..)
+ | ConstantItemRibKind(..)
+ | ModuleRibKind(..)
+ | ForwardGenericParamBanRibKind
+ | ConstParamTyRibKind
+ | InlineAsmSymRibKind => true,
+ }
+ }
+}
+
+/// A single local scope.
+///
+/// A rib represents a scope names can live in. Note that these appear in many places, not just
+/// around braces. At any place where the list of accessible names (of the given namespace)
+/// changes or a new restrictions on the name accessibility are introduced, a new rib is put onto a
+/// stack. This may be, for example, a `let` statement (because it introduces variables), a macro,
+/// etc.
+///
+/// Different [rib kinds](enum@RibKind) are transparent for different names.
+///
+/// The resolution keeps a separate stack of ribs as it traverses the AST for each namespace. When
+/// resolving, the name is looked up from inside out.
+#[derive(Debug)]
+pub(crate) struct Rib<'a, R = Res> {
+ pub bindings: IdentMap<R>,
+ pub kind: RibKind<'a>,
+}
+
+impl<'a, R> Rib<'a, R> {
+ fn new(kind: RibKind<'a>) -> Rib<'a, R> {
+ Rib { bindings: Default::default(), kind }
+ }
+}
+
+#[derive(Clone, Copy, Debug)]
+enum LifetimeUseSet {
+ One { use_span: Span, use_ctxt: visit::LifetimeCtxt },
+ Many,
+}
+
+#[derive(Copy, Clone, Debug)]
+enum LifetimeRibKind {
+ /// This rib acts as a barrier to forbid reference to lifetimes of a parent item.
+ Item,
+
+ /// This rib declares generic parameters.
+ Generics { binder: NodeId, span: Span, kind: LifetimeBinderKind },
+
+ /// FIXME(const_generics): This patches over an ICE caused by non-'static lifetimes in const
+ /// generics. We are disallowing this until we can decide on how we want to handle non-'static
+ /// lifetimes in const generics. See issue #74052 for discussion.
+ ConstGeneric,
+
+ /// Non-static lifetimes are prohibited in anonymous constants under `min_const_generics`.
+ /// This function will emit an error if `generic_const_exprs` is not enabled, the body identified by
+ /// `body_id` is an anonymous constant and `lifetime_ref` is non-static.
+ AnonConst,
+
+ /// Create a new anonymous lifetime parameter and reference it.
+ ///
+ /// If `report_in_path`, report an error when encountering lifetime elision in a path:
+ /// ```compile_fail
+ /// struct Foo<'a> { x: &'a () }
+ /// async fn foo(x: Foo) {}
+ /// ```
+ ///
+ /// Note: the error should not trigger when the elided lifetime is in a pattern or
+ /// expression-position path:
+ /// ```
+ /// struct Foo<'a> { x: &'a () }
+ /// async fn foo(Foo { x: _ }: Foo<'_>) {}
+ /// ```
+ AnonymousCreateParameter { binder: NodeId, report_in_path: bool },
+
+ /// Give a hard error when either `&` or `'_` is written. Used to
+ /// rule out things like `where T: Foo<'_>`. Does not imply an
+ /// error on default object bounds (e.g., `Box<dyn Foo>`).
+ AnonymousReportError,
+
+ /// Replace all anonymous lifetimes by provided lifetime.
+ Elided(LifetimeRes),
+
+ /// Signal we cannot find which should be the anonymous lifetime.
+ ElisionFailure,
+}
+
+#[derive(Copy, Clone, Debug)]
+enum LifetimeBinderKind {
+ BareFnType,
+ PolyTrait,
+ WhereBound,
+ Item,
+ Function,
+ Closure,
+ ImplBlock,
+}
+
+impl LifetimeBinderKind {
+ fn descr(self) -> &'static str {
+ use LifetimeBinderKind::*;
+ match self {
+ BareFnType => "type",
+ PolyTrait => "bound",
+ WhereBound => "bound",
+ Item => "item",
+ ImplBlock => "impl block",
+ Function => "function",
+ Closure => "closure",
+ }
+ }
+}
+
+#[derive(Debug)]
+struct LifetimeRib {
+ kind: LifetimeRibKind,
+ // We need to preserve insertion order for async fns.
+ bindings: FxIndexMap<Ident, (NodeId, LifetimeRes)>,
+}
+
+impl LifetimeRib {
+ fn new(kind: LifetimeRibKind) -> LifetimeRib {
+ LifetimeRib { bindings: Default::default(), kind }
+ }
+}
+
+#[derive(Copy, Clone, PartialEq, Eq, Debug)]
+pub(crate) enum AliasPossibility {
+ No,
+ Maybe,
+}
+
+#[derive(Copy, Clone, Debug)]
+pub(crate) enum PathSource<'a> {
+ // Type paths `Path`.
+ Type,
+ // Trait paths in bounds or impls.
+ Trait(AliasPossibility),
+ // Expression paths `path`, with optional parent context.
+ Expr(Option<&'a Expr>),
+ // Paths in path patterns `Path`.
+ Pat,
+ // Paths in struct expressions and patterns `Path { .. }`.
+ Struct,
+ // Paths in tuple struct patterns `Path(..)`.
+ TupleStruct(Span, &'a [Span]),
+ // `m::A::B` in `<T as m::A>::B::C`.
+ TraitItem(Namespace),
+}
+
+impl<'a> PathSource<'a> {
+ fn namespace(self) -> Namespace {
+ match self {
+ PathSource::Type | PathSource::Trait(_) | PathSource::Struct => TypeNS,
+ PathSource::Expr(..) | PathSource::Pat | PathSource::TupleStruct(..) => ValueNS,
+ PathSource::TraitItem(ns) => ns,
+ }
+ }
+
+ fn defer_to_typeck(self) -> bool {
+ match self {
+ PathSource::Type
+ | PathSource::Expr(..)
+ | PathSource::Pat
+ | PathSource::Struct
+ | PathSource::TupleStruct(..) => true,
+ PathSource::Trait(_) | PathSource::TraitItem(..) => false,
+ }
+ }
+
+ fn descr_expected(self) -> &'static str {
+ match &self {
+ PathSource::Type => "type",
+ PathSource::Trait(_) => "trait",
+ PathSource::Pat => "unit struct, unit variant or constant",
+ PathSource::Struct => "struct, variant or union type",
+ PathSource::TupleStruct(..) => "tuple struct or tuple variant",
+ PathSource::TraitItem(ns) => match ns {
+ TypeNS => "associated type",
+ ValueNS => "method or associated constant",
+ MacroNS => bug!("associated macro"),
+ },
+ PathSource::Expr(parent) => match parent.as_ref().map(|p| &p.kind) {
+ // "function" here means "anything callable" rather than `DefKind::Fn`,
+ // this is not precise but usually more helpful than just "value".
+ Some(ExprKind::Call(call_expr, _)) => match &call_expr.kind {
+ // the case of `::some_crate()`
+ ExprKind::Path(_, path)
+ if path.segments.len() == 2
+ && path.segments[0].ident.name == kw::PathRoot =>
+ {
+ "external crate"
+ }
+ ExprKind::Path(_, path) => {
+ let mut msg = "function";
+ if let Some(segment) = path.segments.iter().last() {
+ if let Some(c) = segment.ident.to_string().chars().next() {
+ if c.is_uppercase() {
+ msg = "function, tuple struct or tuple variant";
+ }
+ }
+ }
+ msg
+ }
+ _ => "function",
+ },
+ _ => "value",
+ },
+ }
+ }
+
+ fn is_call(self) -> bool {
+ matches!(self, PathSource::Expr(Some(&Expr { kind: ExprKind::Call(..), .. })))
+ }
+
+ pub(crate) fn is_expected(self, res: Res) -> bool {
+ match self {
+ PathSource::Type => matches!(
+ res,
+ Res::Def(
+ DefKind::Struct
+ | DefKind::Union
+ | DefKind::Enum
+ | DefKind::Trait
+ | DefKind::TraitAlias
+ | DefKind::TyAlias
+ | DefKind::AssocTy
+ | DefKind::TyParam
+ | DefKind::OpaqueTy
+ | DefKind::ForeignTy,
+ _,
+ ) | Res::PrimTy(..)
+ | Res::SelfTy { .. }
+ ),
+ PathSource::Trait(AliasPossibility::No) => matches!(res, Res::Def(DefKind::Trait, _)),
+ PathSource::Trait(AliasPossibility::Maybe) => {
+ matches!(res, Res::Def(DefKind::Trait | DefKind::TraitAlias, _))
+ }
+ PathSource::Expr(..) => matches!(
+ res,
+ Res::Def(
+ DefKind::Ctor(_, CtorKind::Const | CtorKind::Fn)
+ | DefKind::Const
+ | DefKind::Static(_)
+ | DefKind::Fn
+ | DefKind::AssocFn
+ | DefKind::AssocConst
+ | DefKind::ConstParam,
+ _,
+ ) | Res::Local(..)
+ | Res::SelfCtor(..)
+ ),
+ PathSource::Pat => {
+ res.expected_in_unit_struct_pat()
+ || matches!(res, Res::Def(DefKind::Const | DefKind::AssocConst, _))
+ }
+ PathSource::TupleStruct(..) => res.expected_in_tuple_struct_pat(),
+ PathSource::Struct => matches!(
+ res,
+ Res::Def(
+ DefKind::Struct
+ | DefKind::Union
+ | DefKind::Variant
+ | DefKind::TyAlias
+ | DefKind::AssocTy,
+ _,
+ ) | Res::SelfTy { .. }
+ ),
+ PathSource::TraitItem(ns) => match res {
+ Res::Def(DefKind::AssocConst | DefKind::AssocFn, _) if ns == ValueNS => true,
+ Res::Def(DefKind::AssocTy, _) if ns == TypeNS => true,
+ _ => false,
+ },
+ }
+ }
+
+ fn error_code(self, has_unexpected_resolution: bool) -> DiagnosticId {
+ use rustc_errors::error_code;
+ match (self, has_unexpected_resolution) {
+ (PathSource::Trait(_), true) => error_code!(E0404),
+ (PathSource::Trait(_), false) => error_code!(E0405),
+ (PathSource::Type, true) => error_code!(E0573),
+ (PathSource::Type, false) => error_code!(E0412),
+ (PathSource::Struct, true) => error_code!(E0574),
+ (PathSource::Struct, false) => error_code!(E0422),
+ (PathSource::Expr(..), true) => error_code!(E0423),
+ (PathSource::Expr(..), false) => error_code!(E0425),
+ (PathSource::Pat | PathSource::TupleStruct(..), true) => error_code!(E0532),
+ (PathSource::Pat | PathSource::TupleStruct(..), false) => error_code!(E0531),
+ (PathSource::TraitItem(..), true) => error_code!(E0575),
+ (PathSource::TraitItem(..), false) => error_code!(E0576),
+ }
+ }
+}
+
+#[derive(Default)]
+struct DiagnosticMetadata<'ast> {
+ /// The current trait's associated items' ident, used for diagnostic suggestions.
+ current_trait_assoc_items: Option<&'ast [P<AssocItem>]>,
+
+ /// The current self type if inside an impl (used for better errors).
+ current_self_type: Option<Ty>,
+
+ /// The current self item if inside an ADT (used for better errors).
+ current_self_item: Option<NodeId>,
+
+ /// The current trait (used to suggest).
+ current_item: Option<&'ast Item>,
+
+ /// When processing generics and encountering a type not found, suggest introducing a type
+ /// param.
+ currently_processing_generics: bool,
+
+ /// The current enclosing (non-closure) function (used for better errors).
+ current_function: Option<(FnKind<'ast>, Span)>,
+
+ /// A list of labels as of yet unused. Labels will be removed from this map when
+ /// they are used (in a `break` or `continue` statement)
+ unused_labels: FxHashMap<NodeId, Span>,
+
+ /// Only used for better errors on `fn(): fn()`.
+ current_type_ascription: Vec<Span>,
+
+ /// Only used for better errors on `let x = { foo: bar };`.
+ /// In the case of a parse error with `let x = { foo: bar, };`, this isn't needed, it's only
+ /// needed for cases where this parses as a correct type ascription.
+ current_block_could_be_bare_struct_literal: Option<Span>,
+
+ /// Only used for better errors on `let <pat>: <expr, not type>;`.
+ current_let_binding: Option<(Span, Option<Span>, Option<Span>)>,
+
+ /// Used to detect possible `if let` written without `let` and to provide structured suggestion.
+ in_if_condition: Option<&'ast Expr>,
+
+ /// If we are currently in a trait object definition. Used to point at the bounds when
+ /// encountering a struct or enum.
+ current_trait_object: Option<&'ast [ast::GenericBound]>,
+
+ /// Given `where <T as Bar>::Baz: String`, suggest `where T: Bar<Baz = String>`.
+ current_where_predicate: Option<&'ast WherePredicate>,
+
+ current_type_path: Option<&'ast Ty>,
+
+ /// The current impl items (used to suggest).
+ current_impl_items: Option<&'ast [P<AssocItem>]>,
+
+ /// When processing impl trait
+ currently_processing_impl_trait: Option<(TraitRef, Ty)>,
+
+ /// Accumulate the errors due to missed lifetime elision,
+ /// and report them all at once for each function.
+ current_elision_failures: Vec<MissingLifetime>,
+}
+
+struct LateResolutionVisitor<'a, 'b, 'ast> {
+ r: &'b mut Resolver<'a>,
+
+ /// The module that represents the current item scope.
+ parent_scope: ParentScope<'a>,
+
+ /// The current set of local scopes for types and values.
+ /// FIXME #4948: Reuse ribs to avoid allocation.
+ ribs: PerNS<Vec<Rib<'a>>>,
+
+ /// The current set of local scopes, for labels.
+ label_ribs: Vec<Rib<'a, NodeId>>,
+
+ /// The current set of local scopes for lifetimes.
+ lifetime_ribs: Vec<LifetimeRib>,
+
+ /// We are looking for lifetimes in an elision context.
+ /// The set contains all the resolutions that we encountered so far.
+ /// They will be used to determine the correct lifetime for the fn return type.
+ /// The `LifetimeElisionCandidate` is used for diagnostics, to suggest introducing named
+ /// lifetimes.
+ lifetime_elision_candidates: Option<FxIndexMap<LifetimeRes, LifetimeElisionCandidate>>,
+
+ /// The trait that the current context can refer to.
+ current_trait_ref: Option<(Module<'a>, TraitRef)>,
+
+ /// Fields used to add information to diagnostic errors.
+ diagnostic_metadata: Box<DiagnosticMetadata<'ast>>,
+
+ /// State used to know whether to ignore resolution errors for function bodies.
+ ///
+ /// In particular, rustdoc uses this to avoid giving errors for `cfg()` items.
+ /// In most cases this will be `None`, in which case errors will always be reported.
+ /// If it is `true`, then it will be updated when entering a nested function or trait body.
+ in_func_body: bool,
+
+ /// Count the number of places a lifetime is used.
+ lifetime_uses: FxHashMap<LocalDefId, LifetimeUseSet>,
+}
+
+/// Walks the whole crate in DFS order, visiting each item, resolving names as it goes.
+impl<'a: 'ast, 'ast> Visitor<'ast> for LateResolutionVisitor<'a, '_, 'ast> {
+ fn visit_attribute(&mut self, _: &'ast Attribute) {
+ // We do not want to resolve expressions that appear in attributes,
+ // as they do not correspond to actual code.
+ }
+ fn visit_item(&mut self, item: &'ast Item) {
+ let prev = replace(&mut self.diagnostic_metadata.current_item, Some(item));
+ // Always report errors in items we just entered.
+ let old_ignore = replace(&mut self.in_func_body, false);
+ self.with_lifetime_rib(LifetimeRibKind::Item, |this| this.resolve_item(item));
+ self.in_func_body = old_ignore;
+ self.diagnostic_metadata.current_item = prev;
+ }
+ fn visit_arm(&mut self, arm: &'ast Arm) {
+ self.resolve_arm(arm);
+ }
+ fn visit_block(&mut self, block: &'ast Block) {
+ self.resolve_block(block);
+ }
+ fn visit_anon_const(&mut self, constant: &'ast AnonConst) {
+ // We deal with repeat expressions explicitly in `resolve_expr`.
+ self.with_lifetime_rib(LifetimeRibKind::AnonConst, |this| {
+ this.with_lifetime_rib(LifetimeRibKind::Elided(LifetimeRes::Static), |this| {
+ this.resolve_anon_const(constant, IsRepeatExpr::No);
+ })
+ })
+ }
+ fn visit_expr(&mut self, expr: &'ast Expr) {
+ self.resolve_expr(expr, None);
+ }
+ fn visit_local(&mut self, local: &'ast Local) {
+ let local_spans = match local.pat.kind {
+ // We check for this to avoid tuple struct fields.
+ PatKind::Wild => None,
+ _ => Some((
+ local.pat.span,
+ local.ty.as_ref().map(|ty| ty.span),
+ local.kind.init().map(|init| init.span),
+ )),
+ };
+ let original = replace(&mut self.diagnostic_metadata.current_let_binding, local_spans);
+ self.resolve_local(local);
+ self.diagnostic_metadata.current_let_binding = original;
+ }
+ fn visit_ty(&mut self, ty: &'ast Ty) {
+ let prev = self.diagnostic_metadata.current_trait_object;
+ let prev_ty = self.diagnostic_metadata.current_type_path;
+ match ty.kind {
+ TyKind::Rptr(None, _) => {
+ // Elided lifetime in reference: we resolve as if there was some lifetime `'_` with
+ // NodeId `ty.id`.
+ // This span will be used in case of elision failure.
+ let span = self.r.session.source_map().next_point(ty.span.shrink_to_lo());
+ self.resolve_elided_lifetime(ty.id, span);
+ visit::walk_ty(self, ty);
+ }
+ TyKind::Path(ref qself, ref path) => {
+ self.diagnostic_metadata.current_type_path = Some(ty);
+ self.smart_resolve_path(ty.id, qself.as_ref(), path, PathSource::Type);
+
+ // Check whether we should interpret this as a bare trait object.
+ if qself.is_none()
+ && let Some(partial_res) = self.r.partial_res_map.get(&ty.id)
+ && partial_res.unresolved_segments() == 0
+ && let Res::Def(DefKind::Trait | DefKind::TraitAlias, _) = partial_res.base_res()
+ {
+ // This path is actually a bare trait object. In case of a bare `Fn`-trait
+ // object with anonymous lifetimes, we need this rib to correctly place the
+ // synthetic lifetimes.
+ let span = ty.span.shrink_to_lo().to(path.span.shrink_to_lo());
+ self.with_generic_param_rib(
+ &[],
+ NormalRibKind,
+ LifetimeRibKind::Generics {
+ binder: ty.id,
+ kind: LifetimeBinderKind::PolyTrait,
+ span,
+ },
+ |this| this.visit_path(&path, ty.id),
+ );
+ } else {
+ visit::walk_ty(self, ty)
+ }
+ }
+ TyKind::ImplicitSelf => {
+ let self_ty = Ident::with_dummy_span(kw::SelfUpper);
+ let res = self
+ .resolve_ident_in_lexical_scope(
+ self_ty,
+ TypeNS,
+ Some(Finalize::new(ty.id, ty.span)),
+ None,
+ )
+ .map_or(Res::Err, |d| d.res());
+ self.r.record_partial_res(ty.id, PartialRes::new(res));
+ visit::walk_ty(self, ty)
+ }
+ TyKind::ImplTrait(..) => {
+ let candidates = self.lifetime_elision_candidates.take();
+ visit::walk_ty(self, ty);
+ self.lifetime_elision_candidates = candidates;
+ }
+ TyKind::TraitObject(ref bounds, ..) => {
+ self.diagnostic_metadata.current_trait_object = Some(&bounds[..]);
+ visit::walk_ty(self, ty)
+ }
+ TyKind::BareFn(ref bare_fn) => {
+ let span = ty.span.shrink_to_lo().to(bare_fn.decl_span.shrink_to_lo());
+ self.with_generic_param_rib(
+ &bare_fn.generic_params,
+ NormalRibKind,
+ LifetimeRibKind::Generics {
+ binder: ty.id,
+ kind: LifetimeBinderKind::BareFnType,
+ span,
+ },
+ |this| {
+ this.visit_generic_params(&bare_fn.generic_params, false);
+ this.with_lifetime_rib(
+ LifetimeRibKind::AnonymousCreateParameter {
+ binder: ty.id,
+ report_in_path: false,
+ },
+ |this| {
+ this.resolve_fn_signature(
+ ty.id,
+ false,
+ // We don't need to deal with patterns in parameters, because
+ // they are not possible for foreign or bodiless functions.
+ bare_fn
+ .decl
+ .inputs
+ .iter()
+ .map(|Param { ty, .. }| (None, &**ty)),
+ &bare_fn.decl.output,
+ )
+ },
+ );
+ },
+ )
+ }
+ _ => visit::walk_ty(self, ty),
+ }
+ self.diagnostic_metadata.current_trait_object = prev;
+ self.diagnostic_metadata.current_type_path = prev_ty;
+ }
+ fn visit_poly_trait_ref(&mut self, tref: &'ast PolyTraitRef, _: &'ast TraitBoundModifier) {
+ let span = tref.span.shrink_to_lo().to(tref.trait_ref.path.span.shrink_to_lo());
+ self.with_generic_param_rib(
+ &tref.bound_generic_params,
+ NormalRibKind,
+ LifetimeRibKind::Generics {
+ binder: tref.trait_ref.ref_id,
+ kind: LifetimeBinderKind::PolyTrait,
+ span,
+ },
+ |this| {
+ this.visit_generic_params(&tref.bound_generic_params, false);
+ this.smart_resolve_path(
+ tref.trait_ref.ref_id,
+ None,
+ &tref.trait_ref.path,
+ PathSource::Trait(AliasPossibility::Maybe),
+ );
+ this.visit_trait_ref(&tref.trait_ref);
+ },
+ );
+ }
+ fn visit_foreign_item(&mut self, foreign_item: &'ast ForeignItem) {
+ match foreign_item.kind {
+ ForeignItemKind::TyAlias(box TyAlias { ref generics, .. }) => {
+ self.with_lifetime_rib(LifetimeRibKind::Item, |this| {
+ this.with_generic_param_rib(
+ &generics.params,
+ ItemRibKind(HasGenericParams::Yes),
+ LifetimeRibKind::Generics {
+ binder: foreign_item.id,
+ kind: LifetimeBinderKind::Item,
+ span: generics.span,
+ },
+ |this| visit::walk_foreign_item(this, foreign_item),
+ )
+ });
+ }
+ ForeignItemKind::Fn(box Fn { ref generics, .. }) => {
+ self.with_lifetime_rib(LifetimeRibKind::Item, |this| {
+ this.with_generic_param_rib(
+ &generics.params,
+ ItemRibKind(HasGenericParams::Yes),
+ LifetimeRibKind::Generics {
+ binder: foreign_item.id,
+ kind: LifetimeBinderKind::Function,
+ span: generics.span,
+ },
+ |this| visit::walk_foreign_item(this, foreign_item),
+ )
+ });
+ }
+ ForeignItemKind::Static(..) => {
+ self.with_item_rib(|this| {
+ visit::walk_foreign_item(this, foreign_item);
+ });
+ }
+ ForeignItemKind::MacCall(..) => {
+ panic!("unexpanded macro in resolve!")
+ }
+ }
+ }
+ fn visit_fn(&mut self, fn_kind: FnKind<'ast>, sp: Span, fn_id: NodeId) {
+ let rib_kind = match fn_kind {
+ // Bail if the function is foreign, and thus cannot validly have
+ // a body, or if there's no body for some other reason.
+ FnKind::Fn(FnCtxt::Foreign, _, sig, _, generics, _)
+ | FnKind::Fn(_, _, sig, _, generics, None) => {
+ self.visit_fn_header(&sig.header);
+ self.visit_generics(generics);
+ self.with_lifetime_rib(
+ LifetimeRibKind::AnonymousCreateParameter {
+ binder: fn_id,
+ report_in_path: false,
+ },
+ |this| {
+ this.resolve_fn_signature(
+ fn_id,
+ sig.decl.has_self(),
+ sig.decl.inputs.iter().map(|Param { ty, .. }| (None, &**ty)),
+ &sig.decl.output,
+ )
+ },
+ );
+ return;
+ }
+ FnKind::Fn(FnCtxt::Free, ..) => FnItemRibKind,
+ FnKind::Fn(FnCtxt::Assoc(_), ..) => NormalRibKind,
+ FnKind::Closure(..) => ClosureOrAsyncRibKind,
+ };
+ let previous_value = self.diagnostic_metadata.current_function;
+ if matches!(fn_kind, FnKind::Fn(..)) {
+ self.diagnostic_metadata.current_function = Some((fn_kind, sp));
+ }
+ debug!("(resolving function) entering function");
+
+ // Create a value rib for the function.
+ self.with_rib(ValueNS, rib_kind, |this| {
+ // Create a label rib for the function.
+ this.with_label_rib(FnItemRibKind, |this| {
+ match fn_kind {
+ FnKind::Fn(_, _, sig, _, generics, body) => {
+ this.visit_generics(generics);
+
+ let declaration = &sig.decl;
+ let async_node_id = sig.header.asyncness.opt_return_id();
+
+ this.with_lifetime_rib(
+ LifetimeRibKind::AnonymousCreateParameter {
+ binder: fn_id,
+ report_in_path: async_node_id.is_some(),
+ },
+ |this| {
+ this.resolve_fn_signature(
+ fn_id,
+ declaration.has_self(),
+ declaration
+ .inputs
+ .iter()
+ .map(|Param { pat, ty, .. }| (Some(&**pat), &**ty)),
+ &declaration.output,
+ )
+ },
+ );
+
+ // Construct the list of in-scope lifetime parameters for async lowering.
+ // We include all lifetime parameters, either named or "Fresh".
+ // The order of those parameters does not matter, as long as it is
+ // deterministic.
+ if let Some(async_node_id) = async_node_id {
+ let mut extra_lifetime_params = this
+ .r
+ .extra_lifetime_params_map
+ .get(&fn_id)
+ .cloned()
+ .unwrap_or_default();
+ for rib in this.lifetime_ribs.iter().rev() {
+ extra_lifetime_params.extend(
+ rib.bindings
+ .iter()
+ .map(|(&ident, &(node_id, res))| (ident, node_id, res)),
+ );
+ match rib.kind {
+ LifetimeRibKind::Item => break,
+ LifetimeRibKind::AnonymousCreateParameter {
+ binder, ..
+ } => {
+ if let Some(earlier_fresh) =
+ this.r.extra_lifetime_params_map.get(&binder)
+ {
+ extra_lifetime_params.extend(earlier_fresh);
+ }
+ }
+ _ => {}
+ }
+ }
+ this.r
+ .extra_lifetime_params_map
+ .insert(async_node_id, extra_lifetime_params);
+ }
+
+ if let Some(body) = body {
+ // Ignore errors in function bodies if this is rustdoc
+ // Be sure not to set this until the function signature has been resolved.
+ let previous_state = replace(&mut this.in_func_body, true);
+ // Resolve the function body, potentially inside the body of an async closure
+ this.with_lifetime_rib(
+ LifetimeRibKind::Elided(LifetimeRes::Infer),
+ |this| this.visit_block(body),
+ );
+
+ debug!("(resolving function) leaving function");
+ this.in_func_body = previous_state;
+ }
+ }
+ FnKind::Closure(binder, declaration, body) => {
+ this.visit_closure_binder(binder);
+
+ this.with_lifetime_rib(
+ match binder {
+ // We do not have any explicit generic lifetime parameter.
+ ClosureBinder::NotPresent => {
+ LifetimeRibKind::AnonymousCreateParameter {
+ binder: fn_id,
+ report_in_path: false,
+ }
+ }
+ ClosureBinder::For { .. } => LifetimeRibKind::AnonymousReportError,
+ },
+ // Add each argument to the rib.
+ |this| this.resolve_params(&declaration.inputs),
+ );
+ this.with_lifetime_rib(
+ match binder {
+ ClosureBinder::NotPresent => {
+ LifetimeRibKind::Elided(LifetimeRes::Infer)
+ }
+ ClosureBinder::For { .. } => LifetimeRibKind::AnonymousReportError,
+ },
+ |this| visit::walk_fn_ret_ty(this, &declaration.output),
+ );
+
+ // Ignore errors in function bodies if this is rustdoc
+ // Be sure not to set this until the function signature has been resolved.
+ let previous_state = replace(&mut this.in_func_body, true);
+ // Resolve the function body, potentially inside the body of an async closure
+ this.with_lifetime_rib(
+ LifetimeRibKind::Elided(LifetimeRes::Infer),
+ |this| this.visit_expr(body),
+ );
+
+ debug!("(resolving function) leaving function");
+ this.in_func_body = previous_state;
+ }
+ }
+ })
+ });
+ self.diagnostic_metadata.current_function = previous_value;
+ }
+ fn visit_lifetime(&mut self, lifetime: &'ast Lifetime, use_ctxt: visit::LifetimeCtxt) {
+ self.resolve_lifetime(lifetime, use_ctxt)
+ }
+
+ fn visit_generics(&mut self, generics: &'ast Generics) {
+ self.visit_generic_params(
+ &generics.params,
+ self.diagnostic_metadata.current_self_item.is_some(),
+ );
+ for p in &generics.where_clause.predicates {
+ self.visit_where_predicate(p);
+ }
+ }
+
+ fn visit_closure_binder(&mut self, b: &'ast ClosureBinder) {
+ match b {
+ ClosureBinder::NotPresent => {}
+ ClosureBinder::For { generic_params, .. } => {
+ self.visit_generic_params(
+ &generic_params,
+ self.diagnostic_metadata.current_self_item.is_some(),
+ );
+ }
+ }
+ }
+
+ fn visit_generic_arg(&mut self, arg: &'ast GenericArg) {
+ debug!("visit_generic_arg({:?})", arg);
+ let prev = replace(&mut self.diagnostic_metadata.currently_processing_generics, true);
+ match arg {
+ GenericArg::Type(ref ty) => {
+ // We parse const arguments as path types as we cannot distinguish them during
+ // parsing. We try to resolve that ambiguity by attempting resolution the type
+ // namespace first, and if that fails we try again in the value namespace. If
+ // resolution in the value namespace succeeds, we have an generic const argument on
+ // our hands.
+ if let TyKind::Path(ref qself, ref path) = ty.kind {
+ // We cannot disambiguate multi-segment paths right now as that requires type
+ // checking.
+ if path.segments.len() == 1 && path.segments[0].args.is_none() {
+ let mut check_ns = |ns| {
+ self.maybe_resolve_ident_in_lexical_scope(path.segments[0].ident, ns)
+ .is_some()
+ };
+ if !check_ns(TypeNS) && check_ns(ValueNS) {
+ // This must be equivalent to `visit_anon_const`, but we cannot call it
+ // directly due to visitor lifetimes so we have to copy-paste some code.
+ //
+ // Note that we might not be inside of an repeat expression here,
+ // but considering that `IsRepeatExpr` is only relevant for
+ // non-trivial constants this is doesn't matter.
+ self.with_constant_rib(
+ IsRepeatExpr::No,
+ HasGenericParams::Yes,
+ None,
+ |this| {
+ this.smart_resolve_path(
+ ty.id,
+ qself.as_ref(),
+ path,
+ PathSource::Expr(None),
+ );
+
+ if let Some(ref qself) = *qself {
+ this.visit_ty(&qself.ty);
+ }
+ this.visit_path(path, ty.id);
+ },
+ );
+
+ self.diagnostic_metadata.currently_processing_generics = prev;
+ return;
+ }
+ }
+ }
+
+ self.visit_ty(ty);
+ }
+ GenericArg::Lifetime(lt) => self.visit_lifetime(lt, visit::LifetimeCtxt::GenericArg),
+ GenericArg::Const(ct) => self.visit_anon_const(ct),
+ }
+ self.diagnostic_metadata.currently_processing_generics = prev;
+ }
+
+ fn visit_assoc_constraint(&mut self, constraint: &'ast AssocConstraint) {
+ self.visit_ident(constraint.ident);
+ if let Some(ref gen_args) = constraint.gen_args {
+ // Forbid anonymous lifetimes in GAT parameters until proper semantics are decided.
+ self.with_lifetime_rib(LifetimeRibKind::AnonymousReportError, |this| {
+ this.visit_generic_args(gen_args.span(), gen_args)
+ });
+ }
+ match constraint.kind {
+ AssocConstraintKind::Equality { ref term } => match term {
+ Term::Ty(ty) => self.visit_ty(ty),
+ Term::Const(c) => self.visit_anon_const(c),
+ },
+ AssocConstraintKind::Bound { ref bounds } => {
+ walk_list!(self, visit_param_bound, bounds, BoundKind::Bound);
+ }
+ }
+ }
+
+ fn visit_path_segment(&mut self, path_span: Span, path_segment: &'ast PathSegment) {
+ if let Some(ref args) = path_segment.args {
+ match &**args {
+ GenericArgs::AngleBracketed(..) => visit::walk_generic_args(self, path_span, args),
+ GenericArgs::Parenthesized(p_args) => {
+ // Probe the lifetime ribs to know how to behave.
+ for rib in self.lifetime_ribs.iter().rev() {
+ match rib.kind {
+ // We are inside a `PolyTraitRef`. The lifetimes are
+ // to be intoduced in that (maybe implicit) `for<>` binder.
+ LifetimeRibKind::Generics {
+ binder,
+ kind: LifetimeBinderKind::PolyTrait,
+ ..
+ } => {
+ self.with_lifetime_rib(
+ LifetimeRibKind::AnonymousCreateParameter {
+ binder,
+ report_in_path: false,
+ },
+ |this| {
+ this.resolve_fn_signature(
+ binder,
+ false,
+ p_args.inputs.iter().map(|ty| (None, &**ty)),
+ &p_args.output,
+ )
+ },
+ );
+ break;
+ }
+ // We have nowhere to introduce generics. Code is malformed,
+ // so use regular lifetime resolution to avoid spurious errors.
+ LifetimeRibKind::Item | LifetimeRibKind::Generics { .. } => {
+ visit::walk_generic_args(self, path_span, args);
+ break;
+ }
+ LifetimeRibKind::AnonymousCreateParameter { .. }
+ | LifetimeRibKind::AnonymousReportError
+ | LifetimeRibKind::Elided(_)
+ | LifetimeRibKind::ElisionFailure
+ | LifetimeRibKind::AnonConst
+ | LifetimeRibKind::ConstGeneric => {}
+ }
+ }
+ }
+ }
+ }
+ }
+
+ fn visit_where_predicate(&mut self, p: &'ast WherePredicate) {
+ debug!("visit_where_predicate {:?}", p);
+ let previous_value =
+ replace(&mut self.diagnostic_metadata.current_where_predicate, Some(p));
+ self.with_lifetime_rib(LifetimeRibKind::AnonymousReportError, |this| {
+ if let WherePredicate::BoundPredicate(WhereBoundPredicate {
+ ref bounded_ty,
+ ref bounds,
+ ref bound_generic_params,
+ span: predicate_span,
+ ..
+ }) = p
+ {
+ let span = predicate_span.shrink_to_lo().to(bounded_ty.span.shrink_to_lo());
+ this.with_generic_param_rib(
+ &bound_generic_params,
+ NormalRibKind,
+ LifetimeRibKind::Generics {
+ binder: bounded_ty.id,
+ kind: LifetimeBinderKind::WhereBound,
+ span,
+ },
+ |this| {
+ this.visit_generic_params(&bound_generic_params, false);
+ this.visit_ty(bounded_ty);
+ for bound in bounds {
+ this.visit_param_bound(bound, BoundKind::Bound)
+ }
+ },
+ );
+ } else {
+ visit::walk_where_predicate(this, p);
+ }
+ });
+ self.diagnostic_metadata.current_where_predicate = previous_value;
+ }
+
+ fn visit_inline_asm(&mut self, asm: &'ast InlineAsm) {
+ for (op, _) in &asm.operands {
+ match op {
+ InlineAsmOperand::In { expr, .. }
+ | InlineAsmOperand::Out { expr: Some(expr), .. }
+ | InlineAsmOperand::InOut { expr, .. } => self.visit_expr(expr),
+ InlineAsmOperand::Out { expr: None, .. } => {}
+ InlineAsmOperand::SplitInOut { in_expr, out_expr, .. } => {
+ self.visit_expr(in_expr);
+ if let Some(out_expr) = out_expr {
+ self.visit_expr(out_expr);
+ }
+ }
+ InlineAsmOperand::Const { anon_const, .. } => {
+ // Although this is `DefKind::AnonConst`, it is allowed to reference outer
+ // generic parameters like an inline const.
+ self.resolve_inline_const(anon_const);
+ }
+ InlineAsmOperand::Sym { sym } => self.visit_inline_asm_sym(sym),
+ }
+ }
+ }
+
+ fn visit_inline_asm_sym(&mut self, sym: &'ast InlineAsmSym) {
+ // This is similar to the code for AnonConst.
+ self.with_rib(ValueNS, InlineAsmSymRibKind, |this| {
+ this.with_rib(TypeNS, InlineAsmSymRibKind, |this| {
+ this.with_label_rib(InlineAsmSymRibKind, |this| {
+ this.smart_resolve_path(
+ sym.id,
+ sym.qself.as_ref(),
+ &sym.path,
+ PathSource::Expr(None),
+ );
+ visit::walk_inline_asm_sym(this, sym);
+ });
+ })
+ });
+ }
+}
+
+impl<'a: 'ast, 'b, 'ast> LateResolutionVisitor<'a, 'b, 'ast> {
+ fn new(resolver: &'b mut Resolver<'a>) -> LateResolutionVisitor<'a, 'b, 'ast> {
+ // During late resolution we only track the module component of the parent scope,
+ // although it may be useful to track other components as well for diagnostics.
+ let graph_root = resolver.graph_root;
+ let parent_scope = ParentScope::module(graph_root, resolver);
+ let start_rib_kind = ModuleRibKind(graph_root);
+ LateResolutionVisitor {
+ r: resolver,
+ parent_scope,
+ ribs: PerNS {
+ value_ns: vec![Rib::new(start_rib_kind)],
+ type_ns: vec![Rib::new(start_rib_kind)],
+ macro_ns: vec![Rib::new(start_rib_kind)],
+ },
+ label_ribs: Vec::new(),
+ lifetime_ribs: Vec::new(),
+ lifetime_elision_candidates: None,
+ current_trait_ref: None,
+ diagnostic_metadata: Box::new(DiagnosticMetadata::default()),
+ // errors at module scope should always be reported
+ in_func_body: false,
+ lifetime_uses: Default::default(),
+ }
+ }
+
+ fn maybe_resolve_ident_in_lexical_scope(
+ &mut self,
+ ident: Ident,
+ ns: Namespace,
+ ) -> Option<LexicalScopeBinding<'a>> {
+ self.r.resolve_ident_in_lexical_scope(
+ ident,
+ ns,
+ &self.parent_scope,
+ None,
+ &self.ribs[ns],
+ None,
+ )
+ }
+
+ fn resolve_ident_in_lexical_scope(
+ &mut self,
+ ident: Ident,
+ ns: Namespace,
+ finalize: Option<Finalize>,
+ ignore_binding: Option<&'a NameBinding<'a>>,
+ ) -> Option<LexicalScopeBinding<'a>> {
+ self.r.resolve_ident_in_lexical_scope(
+ ident,
+ ns,
+ &self.parent_scope,
+ finalize,
+ &self.ribs[ns],
+ ignore_binding,
+ )
+ }
+
+ fn resolve_path(
+ &mut self,
+ path: &[Segment],
+ opt_ns: Option<Namespace>, // `None` indicates a module path in import
+ finalize: Option<Finalize>,
+ ) -> PathResult<'a> {
+ self.r.resolve_path_with_ribs(
+ path,
+ opt_ns,
+ &self.parent_scope,
+ finalize,
+ Some(&self.ribs),
+ None,
+ )
+ }
+
+ // AST resolution
+ //
+ // We maintain a list of value ribs and type ribs.
+ //
+ // Simultaneously, we keep track of the current position in the module
+ // graph in the `parent_scope.module` pointer. When we go to resolve a name in
+ // the value or type namespaces, we first look through all the ribs and
+ // then query the module graph. When we resolve a name in the module
+ // namespace, we can skip all the ribs (since nested modules are not
+ // allowed within blocks in Rust) and jump straight to the current module
+ // graph node.
+ //
+ // Named implementations are handled separately. When we find a method
+ // call, we consult the module node to find all of the implementations in
+ // scope. This information is lazily cached in the module node. We then
+ // generate a fake "implementation scope" containing all the
+ // implementations thus found, for compatibility with old resolve pass.
+
+ /// Do some `work` within a new innermost rib of the given `kind` in the given namespace (`ns`).
+ fn with_rib<T>(
+ &mut self,
+ ns: Namespace,
+ kind: RibKind<'a>,
+ work: impl FnOnce(&mut Self) -> T,
+ ) -> T {
+ self.ribs[ns].push(Rib::new(kind));
+ let ret = work(self);
+ self.ribs[ns].pop();
+ ret
+ }
+
+ fn with_scope<T>(&mut self, id: NodeId, f: impl FnOnce(&mut Self) -> T) -> T {
+ if let Some(module) = self.r.get_module(self.r.local_def_id(id).to_def_id()) {
+ // Move down in the graph.
+ let orig_module = replace(&mut self.parent_scope.module, module);
+ self.with_rib(ValueNS, ModuleRibKind(module), |this| {
+ this.with_rib(TypeNS, ModuleRibKind(module), |this| {
+ let ret = f(this);
+ this.parent_scope.module = orig_module;
+ ret
+ })
+ })
+ } else {
+ f(self)
+ }
+ }
+
+ fn visit_generic_params(&mut self, params: &'ast [GenericParam], add_self_upper: bool) {
+ // For type parameter defaults, we have to ban access
+ // to following type parameters, as the InternalSubsts can only
+ // provide previous type parameters as they're built. We
+ // put all the parameters on the ban list and then remove
+ // them one by one as they are processed and become available.
+ let mut forward_ty_ban_rib = Rib::new(ForwardGenericParamBanRibKind);
+ let mut forward_const_ban_rib = Rib::new(ForwardGenericParamBanRibKind);
+ for param in params.iter() {
+ match param.kind {
+ GenericParamKind::Type { .. } => {
+ forward_ty_ban_rib
+ .bindings
+ .insert(Ident::with_dummy_span(param.ident.name), Res::Err);
+ }
+ GenericParamKind::Const { .. } => {
+ forward_const_ban_rib
+ .bindings
+ .insert(Ident::with_dummy_span(param.ident.name), Res::Err);
+ }
+ GenericParamKind::Lifetime => {}
+ }
+ }
+
+ // rust-lang/rust#61631: The type `Self` is essentially
+ // another type parameter. For ADTs, we consider it
+ // well-defined only after all of the ADT type parameters have
+ // been provided. Therefore, we do not allow use of `Self`
+ // anywhere in ADT type parameter defaults.
+ //
+ // (We however cannot ban `Self` for defaults on *all* generic
+ // lists; e.g. trait generics can usefully refer to `Self`,
+ // such as in the case of `trait Add<Rhs = Self>`.)
+ if add_self_upper {
+ // (`Some` if + only if we are in ADT's generics.)
+ forward_ty_ban_rib.bindings.insert(Ident::with_dummy_span(kw::SelfUpper), Res::Err);
+ }
+
+ self.with_lifetime_rib(LifetimeRibKind::AnonymousReportError, |this| {
+ for param in params {
+ match param.kind {
+ GenericParamKind::Lifetime => {
+ for bound in &param.bounds {
+ this.visit_param_bound(bound, BoundKind::Bound);
+ }
+ }
+ GenericParamKind::Type { ref default } => {
+ for bound in &param.bounds {
+ this.visit_param_bound(bound, BoundKind::Bound);
+ }
+
+ if let Some(ref ty) = default {
+ this.ribs[TypeNS].push(forward_ty_ban_rib);
+ this.ribs[ValueNS].push(forward_const_ban_rib);
+ this.visit_ty(ty);
+ forward_const_ban_rib = this.ribs[ValueNS].pop().unwrap();
+ forward_ty_ban_rib = this.ribs[TypeNS].pop().unwrap();
+ }
+
+ // Allow all following defaults to refer to this type parameter.
+ forward_ty_ban_rib
+ .bindings
+ .remove(&Ident::with_dummy_span(param.ident.name));
+ }
+ GenericParamKind::Const { ref ty, kw_span: _, ref default } => {
+ // Const parameters can't have param bounds.
+ assert!(param.bounds.is_empty());
+
+ this.ribs[TypeNS].push(Rib::new(ConstParamTyRibKind));
+ this.ribs[ValueNS].push(Rib::new(ConstParamTyRibKind));
+ this.with_lifetime_rib(LifetimeRibKind::ConstGeneric, |this| {
+ this.visit_ty(ty)
+ });
+ this.ribs[TypeNS].pop().unwrap();
+ this.ribs[ValueNS].pop().unwrap();
+
+ if let Some(ref expr) = default {
+ this.ribs[TypeNS].push(forward_ty_ban_rib);
+ this.ribs[ValueNS].push(forward_const_ban_rib);
+ this.with_lifetime_rib(LifetimeRibKind::ConstGeneric, |this| {
+ this.resolve_anon_const(expr, IsRepeatExpr::No)
+ });
+ forward_const_ban_rib = this.ribs[ValueNS].pop().unwrap();
+ forward_ty_ban_rib = this.ribs[TypeNS].pop().unwrap();
+ }
+
+ // Allow all following defaults to refer to this const parameter.
+ forward_const_ban_rib
+ .bindings
+ .remove(&Ident::with_dummy_span(param.ident.name));
+ }
+ }
+ }
+ })
+ }
+
+ #[tracing::instrument(level = "debug", skip(self, work))]
+ fn with_lifetime_rib<T>(
+ &mut self,
+ kind: LifetimeRibKind,
+ work: impl FnOnce(&mut Self) -> T,
+ ) -> T {
+ self.lifetime_ribs.push(LifetimeRib::new(kind));
+ let outer_elision_candidates = self.lifetime_elision_candidates.take();
+ let ret = work(self);
+ self.lifetime_elision_candidates = outer_elision_candidates;
+ self.lifetime_ribs.pop();
+ ret
+ }
+
+ #[tracing::instrument(level = "debug", skip(self))]
+ fn resolve_lifetime(&mut self, lifetime: &'ast Lifetime, use_ctxt: visit::LifetimeCtxt) {
+ let ident = lifetime.ident;
+
+ if ident.name == kw::StaticLifetime {
+ self.record_lifetime_res(
+ lifetime.id,
+ LifetimeRes::Static,
+ LifetimeElisionCandidate::Named,
+ );
+ return;
+ }
+
+ if ident.name == kw::UnderscoreLifetime {
+ return self.resolve_anonymous_lifetime(lifetime, false);
+ }
+
+ let mut indices = (0..self.lifetime_ribs.len()).rev();
+ for i in &mut indices {
+ let rib = &self.lifetime_ribs[i];
+ let normalized_ident = ident.normalize_to_macros_2_0();
+ if let Some(&(_, res)) = rib.bindings.get(&normalized_ident) {
+ self.record_lifetime_res(lifetime.id, res, LifetimeElisionCandidate::Named);
+
+ if let LifetimeRes::Param { param, .. } = res {
+ match self.lifetime_uses.entry(param) {
+ Entry::Vacant(v) => {
+ debug!("First use of {:?} at {:?}", res, ident.span);
+ let use_set = self
+ .lifetime_ribs
+ .iter()
+ .rev()
+ .find_map(|rib| match rib.kind {
+ // Do not suggest eliding a lifetime where an anonymous
+ // lifetime would be illegal.
+ LifetimeRibKind::Item
+ | LifetimeRibKind::AnonymousReportError
+ | LifetimeRibKind::ElisionFailure => Some(LifetimeUseSet::Many),
+ // An anonymous lifetime is legal here, go ahead.
+ LifetimeRibKind::AnonymousCreateParameter { .. } => {
+ Some(LifetimeUseSet::One { use_span: ident.span, use_ctxt })
+ }
+ // Only report if eliding the lifetime would have the same
+ // semantics.
+ LifetimeRibKind::Elided(r) => Some(if res == r {
+ LifetimeUseSet::One { use_span: ident.span, use_ctxt }
+ } else {
+ LifetimeUseSet::Many
+ }),
+ LifetimeRibKind::Generics { .. }
+ | LifetimeRibKind::ConstGeneric
+ | LifetimeRibKind::AnonConst => None,
+ })
+ .unwrap_or(LifetimeUseSet::Many);
+ debug!(?use_ctxt, ?use_set);
+ v.insert(use_set);
+ }
+ Entry::Occupied(mut o) => {
+ debug!("Many uses of {:?} at {:?}", res, ident.span);
+ *o.get_mut() = LifetimeUseSet::Many;
+ }
+ }
+ }
+ return;
+ }
+
+ match rib.kind {
+ LifetimeRibKind::Item => break,
+ LifetimeRibKind::ConstGeneric => {
+ self.emit_non_static_lt_in_const_generic_error(lifetime);
+ self.record_lifetime_res(
+ lifetime.id,
+ LifetimeRes::Error,
+ LifetimeElisionCandidate::Ignore,
+ );
+ return;
+ }
+ LifetimeRibKind::AnonConst => {
+ self.maybe_emit_forbidden_non_static_lifetime_error(lifetime);
+ self.record_lifetime_res(
+ lifetime.id,
+ LifetimeRes::Error,
+ LifetimeElisionCandidate::Ignore,
+ );
+ return;
+ }
+ _ => {}
+ }
+ }
+
+ let mut outer_res = None;
+ for i in indices {
+ let rib = &self.lifetime_ribs[i];
+ let normalized_ident = ident.normalize_to_macros_2_0();
+ if let Some((&outer, _)) = rib.bindings.get_key_value(&normalized_ident) {
+ outer_res = Some(outer);
+ break;
+ }
+ }
+
+ self.emit_undeclared_lifetime_error(lifetime, outer_res);
+ self.record_lifetime_res(lifetime.id, LifetimeRes::Error, LifetimeElisionCandidate::Named);
+ }
+
+ #[tracing::instrument(level = "debug", skip(self))]
+ fn resolve_anonymous_lifetime(&mut self, lifetime: &Lifetime, elided: bool) {
+ debug_assert_eq!(lifetime.ident.name, kw::UnderscoreLifetime);
+
+ let missing_lifetime = MissingLifetime {
+ id: lifetime.id,
+ span: lifetime.ident.span,
+ kind: if elided {
+ MissingLifetimeKind::Ampersand
+ } else {
+ MissingLifetimeKind::Underscore
+ },
+ count: 1,
+ };
+ let elision_candidate = LifetimeElisionCandidate::Missing(missing_lifetime);
+ for i in (0..self.lifetime_ribs.len()).rev() {
+ let rib = &mut self.lifetime_ribs[i];
+ debug!(?rib.kind);
+ match rib.kind {
+ LifetimeRibKind::AnonymousCreateParameter { binder, .. } => {
+ let res = self.create_fresh_lifetime(lifetime.id, lifetime.ident, binder);
+ self.record_lifetime_res(lifetime.id, res, elision_candidate);
+ return;
+ }
+ LifetimeRibKind::AnonymousReportError => {
+ let (msg, note) = if elided {
+ (
+ "`&` without an explicit lifetime name cannot be used here",
+ "explicit lifetime name needed here",
+ )
+ } else {
+ ("`'_` cannot be used here", "`'_` is a reserved lifetime name")
+ };
+ rustc_errors::struct_span_err!(
+ self.r.session,
+ lifetime.ident.span,
+ E0637,
+ "{}",
+ msg,
+ )
+ .span_label(lifetime.ident.span, note)
+ .emit();
+
+ self.record_lifetime_res(lifetime.id, LifetimeRes::Error, elision_candidate);
+ return;
+ }
+ LifetimeRibKind::Elided(res) => {
+ self.record_lifetime_res(lifetime.id, res, elision_candidate);
+ return;
+ }
+ LifetimeRibKind::ElisionFailure => {
+ self.diagnostic_metadata.current_elision_failures.push(missing_lifetime);
+ self.record_lifetime_res(lifetime.id, LifetimeRes::Error, elision_candidate);
+ return;
+ }
+ LifetimeRibKind::Item => break,
+ LifetimeRibKind::Generics { .. }
+ | LifetimeRibKind::ConstGeneric
+ | LifetimeRibKind::AnonConst => {}
+ }
+ }
+ self.record_lifetime_res(lifetime.id, LifetimeRes::Error, elision_candidate);
+ self.report_missing_lifetime_specifiers(vec![missing_lifetime], None);
+ }
+
+ #[tracing::instrument(level = "debug", skip(self))]
+ fn resolve_elided_lifetime(&mut self, anchor_id: NodeId, span: Span) {
+ let id = self.r.next_node_id();
+ let lt = Lifetime { id, ident: Ident::new(kw::UnderscoreLifetime, span) };
+
+ self.record_lifetime_res(
+ anchor_id,
+ LifetimeRes::ElidedAnchor { start: id, end: NodeId::from_u32(id.as_u32() + 1) },
+ LifetimeElisionCandidate::Ignore,
+ );
+ self.resolve_anonymous_lifetime(&lt, true);
+ }
+
+ #[tracing::instrument(level = "debug", skip(self))]
+ fn create_fresh_lifetime(&mut self, id: NodeId, ident: Ident, binder: NodeId) -> LifetimeRes {
+ debug_assert_eq!(ident.name, kw::UnderscoreLifetime);
+ debug!(?ident.span);
+
+ // Leave the responsibility to create the `LocalDefId` to lowering.
+ let param = self.r.next_node_id();
+ let res = LifetimeRes::Fresh { param, binder };
+
+ // Record the created lifetime parameter so lowering can pick it up and add it to HIR.
+ self.r
+ .extra_lifetime_params_map
+ .entry(binder)
+ .or_insert_with(Vec::new)
+ .push((ident, param, res));
+ res
+ }
+
+ #[tracing::instrument(level = "debug", skip(self))]
+ fn resolve_elided_lifetimes_in_path(
+ &mut self,
+ path_id: NodeId,
+ partial_res: PartialRes,
+ path: &[Segment],
+ source: PathSource<'_>,
+ path_span: Span,
+ ) {
+ let proj_start = path.len() - partial_res.unresolved_segments();
+ for (i, segment) in path.iter().enumerate() {
+ if segment.has_lifetime_args {
+ continue;
+ }
+ let Some(segment_id) = segment.id else {
+ continue;
+ };
+
+ // Figure out if this is a type/trait segment,
+ // which may need lifetime elision performed.
+ let type_def_id = match partial_res.base_res() {
+ Res::Def(DefKind::AssocTy, def_id) if i + 2 == proj_start => self.r.parent(def_id),
+ Res::Def(DefKind::Variant, def_id) if i + 1 == proj_start => self.r.parent(def_id),
+ Res::Def(DefKind::Struct, def_id)
+ | Res::Def(DefKind::Union, def_id)
+ | Res::Def(DefKind::Enum, def_id)
+ | Res::Def(DefKind::TyAlias, def_id)
+ | Res::Def(DefKind::Trait, def_id)
+ if i + 1 == proj_start =>
+ {
+ def_id
+ }
+ _ => continue,
+ };
+
+ let expected_lifetimes = self.r.item_generics_num_lifetimes(type_def_id);
+ if expected_lifetimes == 0 {
+ continue;
+ }
+
+ let node_ids = self.r.next_node_ids(expected_lifetimes);
+ self.record_lifetime_res(
+ segment_id,
+ LifetimeRes::ElidedAnchor { start: node_ids.start, end: node_ids.end },
+ LifetimeElisionCandidate::Ignore,
+ );
+
+ let inferred = match source {
+ PathSource::Trait(..) | PathSource::TraitItem(..) | PathSource::Type => false,
+ PathSource::Expr(..)
+ | PathSource::Pat
+ | PathSource::Struct
+ | PathSource::TupleStruct(..) => true,
+ };
+ if inferred {
+ // Do not create a parameter for patterns and expressions: type checking can infer
+ // the appropriate lifetime for us.
+ for id in node_ids {
+ self.record_lifetime_res(
+ id,
+ LifetimeRes::Infer,
+ LifetimeElisionCandidate::Named,
+ );
+ }
+ continue;
+ }
+
+ let elided_lifetime_span = if segment.has_generic_args {
+ // If there are brackets, but not generic arguments, then use the opening bracket
+ segment.args_span.with_hi(segment.args_span.lo() + BytePos(1))
+ } else {
+ // If there are no brackets, use the identifier span.
+ // HACK: we use find_ancestor_inside to properly suggest elided spans in paths
+ // originating from macros, since the segment's span might be from a macro arg.
+ segment.ident.span.find_ancestor_inside(path_span).unwrap_or(path_span)
+ };
+ let ident = Ident::new(kw::UnderscoreLifetime, elided_lifetime_span);
+
+ let missing_lifetime = MissingLifetime {
+ id: node_ids.start,
+ span: elided_lifetime_span,
+ kind: if segment.has_generic_args {
+ MissingLifetimeKind::Comma
+ } else {
+ MissingLifetimeKind::Brackets
+ },
+ count: expected_lifetimes,
+ };
+ let mut should_lint = true;
+ for rib in self.lifetime_ribs.iter().rev() {
+ match rib.kind {
+ // In create-parameter mode we error here because we don't want to support
+ // deprecated impl elision in new features like impl elision and `async fn`,
+ // both of which work using the `CreateParameter` mode:
+ //
+ // impl Foo for std::cell::Ref<u32> // note lack of '_
+ // async fn foo(_: std::cell::Ref<u32>) { ... }
+ LifetimeRibKind::AnonymousCreateParameter { report_in_path: true, .. } => {
+ let sess = self.r.session;
+ let mut err = rustc_errors::struct_span_err!(
+ sess,
+ path_span,
+ E0726,
+ "implicit elided lifetime not allowed here"
+ );
+ rustc_errors::add_elided_lifetime_in_path_suggestion(
+ sess.source_map(),
+ &mut err,
+ expected_lifetimes,
+ path_span,
+ !segment.has_generic_args,
+ elided_lifetime_span,
+ );
+ err.note("assuming a `'static` lifetime...");
+ err.emit();
+ should_lint = false;
+
+ for id in node_ids {
+ self.record_lifetime_res(
+ id,
+ LifetimeRes::Error,
+ LifetimeElisionCandidate::Named,
+ );
+ }
+ break;
+ }
+ // Do not create a parameter for patterns and expressions.
+ LifetimeRibKind::AnonymousCreateParameter { binder, .. } => {
+ // Group all suggestions into the first record.
+ let mut candidate = LifetimeElisionCandidate::Missing(missing_lifetime);
+ for id in node_ids {
+ let res = self.create_fresh_lifetime(id, ident, binder);
+ self.record_lifetime_res(
+ id,
+ res,
+ replace(&mut candidate, LifetimeElisionCandidate::Named),
+ );
+ }
+ break;
+ }
+ LifetimeRibKind::Elided(res) => {
+ let mut candidate = LifetimeElisionCandidate::Missing(missing_lifetime);
+ for id in node_ids {
+ self.record_lifetime_res(
+ id,
+ res,
+ replace(&mut candidate, LifetimeElisionCandidate::Ignore),
+ );
+ }
+ break;
+ }
+ LifetimeRibKind::ElisionFailure => {
+ self.diagnostic_metadata.current_elision_failures.push(missing_lifetime);
+ for id in node_ids {
+ self.record_lifetime_res(
+ id,
+ LifetimeRes::Error,
+ LifetimeElisionCandidate::Ignore,
+ );
+ }
+ break;
+ }
+ // `LifetimeRes::Error`, which would usually be used in the case of
+ // `ReportError`, is unsuitable here, as we don't emit an error yet. Instead,
+ // we simply resolve to an implicit lifetime, which will be checked later, at
+ // which point a suitable error will be emitted.
+ LifetimeRibKind::AnonymousReportError | LifetimeRibKind::Item => {
+ for id in node_ids {
+ self.record_lifetime_res(
+ id,
+ LifetimeRes::Error,
+ LifetimeElisionCandidate::Ignore,
+ );
+ }
+ self.report_missing_lifetime_specifiers(vec![missing_lifetime], None);
+ break;
+ }
+ LifetimeRibKind::Generics { .. }
+ | LifetimeRibKind::ConstGeneric
+ | LifetimeRibKind::AnonConst => {}
+ }
+ }
+
+ if should_lint {
+ self.r.lint_buffer.buffer_lint_with_diagnostic(
+ lint::builtin::ELIDED_LIFETIMES_IN_PATHS,
+ segment_id,
+ elided_lifetime_span,
+ "hidden lifetime parameters in types are deprecated",
+ lint::BuiltinLintDiagnostics::ElidedLifetimesInPaths(
+ expected_lifetimes,
+ path_span,
+ !segment.has_generic_args,
+ elided_lifetime_span,
+ ),
+ );
+ }
+ }
+ }
+
+ #[tracing::instrument(level = "debug", skip(self))]
+ fn record_lifetime_res(
+ &mut self,
+ id: NodeId,
+ res: LifetimeRes,
+ candidate: LifetimeElisionCandidate,
+ ) {
+ if let Some(prev_res) = self.r.lifetimes_res_map.insert(id, res) {
+ panic!(
+ "lifetime {:?} resolved multiple times ({:?} before, {:?} now)",
+ id, prev_res, res
+ )
+ }
+ match res {
+ LifetimeRes::Param { .. } | LifetimeRes::Fresh { .. } | LifetimeRes::Static => {
+ if let Some(ref mut candidates) = self.lifetime_elision_candidates {
+ candidates.insert(res, candidate);
+ }
+ }
+ LifetimeRes::Infer | LifetimeRes::Error | LifetimeRes::ElidedAnchor { .. } => {}
+ }
+ }
+
+ #[tracing::instrument(level = "debug", skip(self))]
+ fn record_lifetime_param(&mut self, id: NodeId, res: LifetimeRes) {
+ if let Some(prev_res) = self.r.lifetimes_res_map.insert(id, res) {
+ panic!(
+ "lifetime parameter {:?} resolved multiple times ({:?} before, {:?} now)",
+ id, prev_res, res
+ )
+ }
+ }
+
+ /// Perform resolution of a function signature, accounting for lifetime elision.
+ #[tracing::instrument(level = "debug", skip(self, inputs))]
+ fn resolve_fn_signature(
+ &mut self,
+ fn_id: NodeId,
+ has_self: bool,
+ inputs: impl Iterator<Item = (Option<&'ast Pat>, &'ast Ty)> + Clone,
+ output_ty: &'ast FnRetTy,
+ ) {
+ // Add each argument to the rib.
+ let elision_lifetime = self.resolve_fn_params(has_self, inputs);
+ debug!(?elision_lifetime);
+
+ let outer_failures = take(&mut self.diagnostic_metadata.current_elision_failures);
+ let output_rib = if let Ok(res) = elision_lifetime.as_ref() {
+ LifetimeRibKind::Elided(*res)
+ } else {
+ LifetimeRibKind::ElisionFailure
+ };
+ self.with_lifetime_rib(output_rib, |this| visit::walk_fn_ret_ty(this, &output_ty));
+ let elision_failures =
+ replace(&mut self.diagnostic_metadata.current_elision_failures, outer_failures);
+ if !elision_failures.is_empty() {
+ let Err(failure_info) = elision_lifetime else { bug!() };
+ self.report_missing_lifetime_specifiers(elision_failures, Some(failure_info));
+ }
+ }
+
+ /// Resolve inside function parameters and parameter types.
+ /// Returns the lifetime for elision in fn return type,
+ /// or diagnostic information in case of elision failure.
+ fn resolve_fn_params(
+ &mut self,
+ has_self: bool,
+ inputs: impl Iterator<Item = (Option<&'ast Pat>, &'ast Ty)>,
+ ) -> Result<LifetimeRes, (Vec<MissingLifetime>, Vec<ElisionFnParameter>)> {
+ let outer_candidates =
+ replace(&mut self.lifetime_elision_candidates, Some(Default::default()));
+
+ let mut elision_lifetime = None;
+ let mut lifetime_count = 0;
+ let mut parameter_info = Vec::new();
+
+ let mut bindings = smallvec![(PatBoundCtx::Product, Default::default())];
+ for (index, (pat, ty)) in inputs.enumerate() {
+ debug!(?pat, ?ty);
+ if let Some(pat) = pat {
+ self.resolve_pattern(pat, PatternSource::FnParam, &mut bindings);
+ }
+ self.visit_ty(ty);
+
+ if let Some(ref candidates) = self.lifetime_elision_candidates {
+ let new_count = candidates.len();
+ let local_count = new_count - lifetime_count;
+ if local_count != 0 {
+ parameter_info.push(ElisionFnParameter {
+ index,
+ ident: if let Some(pat) = pat && let PatKind::Ident(_, ident, _) = pat.kind {
+ Some(ident)
+ } else {
+ None
+ },
+ lifetime_count: local_count,
+ span: ty.span,
+ });
+ }
+ lifetime_count = new_count;
+ }
+
+ // Handle `self` specially.
+ if index == 0 && has_self {
+ let self_lifetime = self.find_lifetime_for_self(ty);
+ if let Set1::One(lifetime) = self_lifetime {
+ elision_lifetime = Some(lifetime);
+ self.lifetime_elision_candidates = None;
+ } else {
+ self.lifetime_elision_candidates = Some(Default::default());
+ lifetime_count = 0;
+ }
+ }
+ debug!("(resolving function / closure) recorded parameter");
+ }
+
+ let all_candidates = replace(&mut self.lifetime_elision_candidates, outer_candidates);
+ debug!(?all_candidates);
+
+ if let Some(res) = elision_lifetime {
+ return Ok(res);
+ }
+
+ // We do not have a `self` candidate, look at the full list.
+ let all_candidates = all_candidates.unwrap();
+ if all_candidates.len() == 1 {
+ Ok(*all_candidates.first().unwrap().0)
+ } else {
+ let all_candidates = all_candidates
+ .into_iter()
+ .filter_map(|(_, candidate)| match candidate {
+ LifetimeElisionCandidate::Ignore | LifetimeElisionCandidate::Named => None,
+ LifetimeElisionCandidate::Missing(missing) => Some(missing),
+ })
+ .collect();
+ Err((all_candidates, parameter_info))
+ }
+ }
+
+ /// List all the lifetimes that appear in the provided type.
+ fn find_lifetime_for_self(&self, ty: &'ast Ty) -> Set1<LifetimeRes> {
+ struct SelfVisitor<'r, 'a> {
+ r: &'r Resolver<'a>,
+ impl_self: Option<Res>,
+ lifetime: Set1<LifetimeRes>,
+ }
+
+ impl SelfVisitor<'_, '_> {
+ // Look for `self: &'a Self` - also desugared from `&'a self`,
+ // and if that matches, use it for elision and return early.
+ fn is_self_ty(&self, ty: &Ty) -> bool {
+ match ty.kind {
+ TyKind::ImplicitSelf => true,
+ TyKind::Path(None, _) => {
+ let path_res = self.r.partial_res_map[&ty.id].base_res();
+ if let Res::SelfTy { .. } = path_res {
+ return true;
+ }
+ Some(path_res) == self.impl_self
+ }
+ _ => false,
+ }
+ }
+ }
+
+ impl<'a> Visitor<'a> for SelfVisitor<'_, '_> {
+ fn visit_ty(&mut self, ty: &'a Ty) {
+ trace!("SelfVisitor considering ty={:?}", ty);
+ if let TyKind::Rptr(lt, ref mt) = ty.kind && self.is_self_ty(&mt.ty) {
+ let lt_id = if let Some(lt) = lt {
+ lt.id
+ } else {
+ let res = self.r.lifetimes_res_map[&ty.id];
+ let LifetimeRes::ElidedAnchor { start, .. } = res else { bug!() };
+ start
+ };
+ let lt_res = self.r.lifetimes_res_map[&lt_id];
+ trace!("SelfVisitor inserting res={:?}", lt_res);
+ self.lifetime.insert(lt_res);
+ }
+ visit::walk_ty(self, ty)
+ }
+ }
+
+ let impl_self = self
+ .diagnostic_metadata
+ .current_self_type
+ .as_ref()
+ .and_then(|ty| {
+ if let TyKind::Path(None, _) = ty.kind {
+ self.r.partial_res_map.get(&ty.id)
+ } else {
+ None
+ }
+ })
+ .map(|res| res.base_res())
+ .filter(|res| {
+ // Permit the types that unambiguously always
+ // result in the same type constructor being used
+ // (it can't differ between `Self` and `self`).
+ matches!(
+ res,
+ Res::Def(DefKind::Struct | DefKind::Union | DefKind::Enum, _,) | Res::PrimTy(_)
+ )
+ });
+ let mut visitor = SelfVisitor { r: self.r, impl_self, lifetime: Set1::Empty };
+ visitor.visit_ty(ty);
+ trace!("SelfVisitor found={:?}", visitor.lifetime);
+ visitor.lifetime
+ }
+
+ /// Searches the current set of local scopes for labels. Returns the `NodeId` of the resolved
+ /// label and reports an error if the label is not found or is unreachable.
+ fn resolve_label(&mut self, mut label: Ident) -> Result<(NodeId, Span), ResolutionError<'a>> {
+ let mut suggestion = None;
+
+ for i in (0..self.label_ribs.len()).rev() {
+ let rib = &self.label_ribs[i];
+
+ if let MacroDefinition(def) = rib.kind {
+ // If an invocation of this macro created `ident`, give up on `ident`
+ // and switch to `ident`'s source from the macro definition.
+ if def == self.r.macro_def(label.span.ctxt()) {
+ label.span.remove_mark();
+ }
+ }
+
+ let ident = label.normalize_to_macro_rules();
+ if let Some((ident, id)) = rib.bindings.get_key_value(&ident) {
+ let definition_span = ident.span;
+ return if self.is_label_valid_from_rib(i) {
+ Ok((*id, definition_span))
+ } else {
+ Err(ResolutionError::UnreachableLabel {
+ name: label.name,
+ definition_span,
+ suggestion,
+ })
+ };
+ }
+
+ // Diagnostics: Check if this rib contains a label with a similar name, keep track of
+ // the first such label that is encountered.
+ suggestion = suggestion.or_else(|| self.suggestion_for_label_in_rib(i, label));
+ }
+
+ Err(ResolutionError::UndeclaredLabel { name: label.name, suggestion })
+ }
+
+ /// Determine whether or not a label from the `rib_index`th label rib is reachable.
+ fn is_label_valid_from_rib(&self, rib_index: usize) -> bool {
+ let ribs = &self.label_ribs[rib_index + 1..];
+
+ for rib in ribs {
+ if rib.kind.is_label_barrier() {
+ return false;
+ }
+ }
+
+ true
+ }
+
+ fn resolve_adt(&mut self, item: &'ast Item, generics: &'ast Generics) {
+ debug!("resolve_adt");
+ self.with_current_self_item(item, |this| {
+ this.with_generic_param_rib(
+ &generics.params,
+ ItemRibKind(HasGenericParams::Yes),
+ LifetimeRibKind::Generics {
+ binder: item.id,
+ kind: LifetimeBinderKind::Item,
+ span: generics.span,
+ },
+ |this| {
+ let item_def_id = this.r.local_def_id(item.id).to_def_id();
+ this.with_self_rib(
+ Res::SelfTy { trait_: None, alias_to: Some((item_def_id, false)) },
+ |this| {
+ visit::walk_item(this, item);
+ },
+ );
+ },
+ );
+ });
+ }
+
+ fn future_proof_import(&mut self, use_tree: &UseTree) {
+ let segments = &use_tree.prefix.segments;
+ if !segments.is_empty() {
+ let ident = segments[0].ident;
+ if ident.is_path_segment_keyword() || ident.span.rust_2015() {
+ return;
+ }
+
+ let nss = match use_tree.kind {
+ UseTreeKind::Simple(..) if segments.len() == 1 => &[TypeNS, ValueNS][..],
+ _ => &[TypeNS],
+ };
+ let report_error = |this: &Self, ns| {
+ let what = if ns == TypeNS { "type parameters" } else { "local variables" };
+ if this.should_report_errs() {
+ this.r
+ .session
+ .span_err(ident.span, &format!("imports cannot refer to {}", what));
+ }
+ };
+
+ for &ns in nss {
+ match self.maybe_resolve_ident_in_lexical_scope(ident, ns) {
+ Some(LexicalScopeBinding::Res(..)) => {
+ report_error(self, ns);
+ }
+ Some(LexicalScopeBinding::Item(binding)) => {
+ if let Some(LexicalScopeBinding::Res(..)) =
+ self.resolve_ident_in_lexical_scope(ident, ns, None, Some(binding))
+ {
+ report_error(self, ns);
+ }
+ }
+ None => {}
+ }
+ }
+ } else if let UseTreeKind::Nested(use_trees) = &use_tree.kind {
+ for (use_tree, _) in use_trees {
+ self.future_proof_import(use_tree);
+ }
+ }
+ }
+
+ fn resolve_item(&mut self, item: &'ast Item) {
+ let name = item.ident.name;
+ debug!("(resolving item) resolving {} ({:?})", name, item.kind);
+
+ match item.kind {
+ ItemKind::TyAlias(box TyAlias { ref generics, .. }) => {
+ self.with_generic_param_rib(
+ &generics.params,
+ ItemRibKind(HasGenericParams::Yes),
+ LifetimeRibKind::Generics {
+ binder: item.id,
+ kind: LifetimeBinderKind::Item,
+ span: generics.span,
+ },
+ |this| visit::walk_item(this, item),
+ );
+ }
+
+ ItemKind::Fn(box Fn { ref generics, .. }) => {
+ self.with_generic_param_rib(
+ &generics.params,
+ ItemRibKind(HasGenericParams::Yes),
+ LifetimeRibKind::Generics {
+ binder: item.id,
+ kind: LifetimeBinderKind::Function,
+ span: generics.span,
+ },
+ |this| visit::walk_item(this, item),
+ );
+ }
+
+ ItemKind::Enum(_, ref generics)
+ | ItemKind::Struct(_, ref generics)
+ | ItemKind::Union(_, ref generics) => {
+ self.resolve_adt(item, generics);
+ }
+
+ ItemKind::Impl(box Impl {
+ ref generics,
+ ref of_trait,
+ ref self_ty,
+ items: ref impl_items,
+ ..
+ }) => {
+ self.diagnostic_metadata.current_impl_items = Some(impl_items);
+ self.resolve_implementation(generics, of_trait, &self_ty, item.id, impl_items);
+ self.diagnostic_metadata.current_impl_items = None;
+ }
+
+ ItemKind::Trait(box Trait { ref generics, ref bounds, ref items, .. }) => {
+ // Create a new rib for the trait-wide type parameters.
+ self.with_generic_param_rib(
+ &generics.params,
+ ItemRibKind(HasGenericParams::Yes),
+ LifetimeRibKind::Generics {
+ binder: item.id,
+ kind: LifetimeBinderKind::Item,
+ span: generics.span,
+ },
+ |this| {
+ let local_def_id = this.r.local_def_id(item.id).to_def_id();
+ this.with_self_rib(
+ Res::SelfTy { trait_: Some(local_def_id), alias_to: None },
+ |this| {
+ this.visit_generics(generics);
+ walk_list!(this, visit_param_bound, bounds, BoundKind::SuperTraits);
+ this.resolve_trait_items(items);
+ },
+ );
+ },
+ );
+ }
+
+ ItemKind::TraitAlias(ref generics, ref bounds) => {
+ // Create a new rib for the trait-wide type parameters.
+ self.with_generic_param_rib(
+ &generics.params,
+ ItemRibKind(HasGenericParams::Yes),
+ LifetimeRibKind::Generics {
+ binder: item.id,
+ kind: LifetimeBinderKind::Item,
+ span: generics.span,
+ },
+ |this| {
+ let local_def_id = this.r.local_def_id(item.id).to_def_id();
+ this.with_self_rib(
+ Res::SelfTy { trait_: Some(local_def_id), alias_to: None },
+ |this| {
+ this.visit_generics(generics);
+ walk_list!(this, visit_param_bound, bounds, BoundKind::Bound);
+ },
+ );
+ },
+ );
+ }
+
+ ItemKind::Mod(..) | ItemKind::ForeignMod(_) => {
+ self.with_scope(item.id, |this| {
+ visit::walk_item(this, item);
+ });
+ }
+
+ ItemKind::Static(ref ty, _, ref expr) | ItemKind::Const(_, ref ty, ref expr) => {
+ self.with_item_rib(|this| {
+ this.with_lifetime_rib(LifetimeRibKind::Elided(LifetimeRes::Static), |this| {
+ this.visit_ty(ty);
+ });
+ this.with_lifetime_rib(LifetimeRibKind::Elided(LifetimeRes::Infer), |this| {
+ if let Some(expr) = expr {
+ let constant_item_kind = match item.kind {
+ ItemKind::Const(..) => ConstantItemKind::Const,
+ ItemKind::Static(..) => ConstantItemKind::Static,
+ _ => unreachable!(),
+ };
+ // We already forbid generic params because of the above item rib,
+ // so it doesn't matter whether this is a trivial constant.
+ this.with_constant_rib(
+ IsRepeatExpr::No,
+ HasGenericParams::Yes,
+ Some((item.ident, constant_item_kind)),
+ |this| this.visit_expr(expr),
+ );
+ }
+ });
+ });
+ }
+
+ ItemKind::Use(ref use_tree) => {
+ self.future_proof_import(use_tree);
+ }
+
+ ItemKind::ExternCrate(..) | ItemKind::MacroDef(..) => {
+ // do nothing, these are just around to be encoded
+ }
+
+ ItemKind::GlobalAsm(_) => {
+ visit::walk_item(self, item);
+ }
+
+ ItemKind::MacCall(_) => panic!("unexpanded macro in resolve!"),
+ }
+ }
+
+ fn with_generic_param_rib<'c, F>(
+ &'c mut self,
+ params: &'c [GenericParam],
+ kind: RibKind<'a>,
+ lifetime_kind: LifetimeRibKind,
+ f: F,
+ ) where
+ F: FnOnce(&mut Self),
+ {
+ debug!("with_generic_param_rib");
+ let LifetimeRibKind::Generics { binder, span: generics_span, kind: generics_kind, .. }
+ = lifetime_kind else { panic!() };
+
+ let mut function_type_rib = Rib::new(kind);
+ let mut function_value_rib = Rib::new(kind);
+ let mut function_lifetime_rib = LifetimeRib::new(lifetime_kind);
+ let mut seen_bindings = FxHashMap::default();
+ // Store all seen lifetimes names from outer scopes.
+ let mut seen_lifetimes = FxHashSet::default();
+
+ // We also can't shadow bindings from the parent item
+ if let AssocItemRibKind = kind {
+ let mut add_bindings_for_ns = |ns| {
+ let parent_rib = self.ribs[ns]
+ .iter()
+ .rfind(|r| matches!(r.kind, ItemRibKind(_)))
+ .expect("associated item outside of an item");
+ seen_bindings
+ .extend(parent_rib.bindings.iter().map(|(ident, _)| (*ident, ident.span)));
+ };
+ add_bindings_for_ns(ValueNS);
+ add_bindings_for_ns(TypeNS);
+ }
+
+ // Forbid shadowing lifetime bindings
+ for rib in self.lifetime_ribs.iter().rev() {
+ seen_lifetimes.extend(rib.bindings.iter().map(|(ident, _)| *ident));
+ if let LifetimeRibKind::Item = rib.kind {
+ break;
+ }
+ }
+
+ for param in params {
+ let ident = param.ident.normalize_to_macros_2_0();
+ debug!("with_generic_param_rib: {}", param.id);
+
+ if let GenericParamKind::Lifetime = param.kind
+ && let Some(&original) = seen_lifetimes.get(&ident)
+ {
+ diagnostics::signal_lifetime_shadowing(self.r.session, original, param.ident);
+ // Record lifetime res, so lowering knows there is something fishy.
+ self.record_lifetime_param(param.id, LifetimeRes::Error);
+ continue;
+ }
+
+ match seen_bindings.entry(ident) {
+ Entry::Occupied(entry) => {
+ let span = *entry.get();
+ let err = ResolutionError::NameAlreadyUsedInParameterList(ident.name, span);
+ self.report_error(param.ident.span, err);
+ if let GenericParamKind::Lifetime = param.kind {
+ // Record lifetime res, so lowering knows there is something fishy.
+ self.record_lifetime_param(param.id, LifetimeRes::Error);
+ continue;
+ }
+ }
+ Entry::Vacant(entry) => {
+ entry.insert(param.ident.span);
+ }
+ }
+
+ if param.ident.name == kw::UnderscoreLifetime {
+ rustc_errors::struct_span_err!(
+ self.r.session,
+ param.ident.span,
+ E0637,
+ "`'_` cannot be used here"
+ )
+ .span_label(param.ident.span, "`'_` is a reserved lifetime name")
+ .emit();
+ // Record lifetime res, so lowering knows there is something fishy.
+ self.record_lifetime_param(param.id, LifetimeRes::Error);
+ continue;
+ }
+
+ if param.ident.name == kw::StaticLifetime {
+ rustc_errors::struct_span_err!(
+ self.r.session,
+ param.ident.span,
+ E0262,
+ "invalid lifetime parameter name: `{}`",
+ param.ident,
+ )
+ .span_label(param.ident.span, "'static is a reserved lifetime name")
+ .emit();
+ // Record lifetime res, so lowering knows there is something fishy.
+ self.record_lifetime_param(param.id, LifetimeRes::Error);
+ continue;
+ }
+
+ let def_id = self.r.local_def_id(param.id);
+
+ // Plain insert (no renaming).
+ let (rib, def_kind) = match param.kind {
+ GenericParamKind::Type { .. } => (&mut function_type_rib, DefKind::TyParam),
+ GenericParamKind::Const { .. } => (&mut function_value_rib, DefKind::ConstParam),
+ GenericParamKind::Lifetime => {
+ let res = LifetimeRes::Param { param: def_id, binder };
+ self.record_lifetime_param(param.id, res);
+ function_lifetime_rib.bindings.insert(ident, (param.id, res));
+ continue;
+ }
+ };
+
+ let res = match kind {
+ ItemRibKind(..) | AssocItemRibKind => Res::Def(def_kind, def_id.to_def_id()),
+ NormalRibKind => Res::Err,
+ _ => span_bug!(param.ident.span, "Unexpected rib kind {:?}", kind),
+ };
+ self.r.record_partial_res(param.id, PartialRes::new(res));
+ rib.bindings.insert(ident, res);
+ }
+
+ self.lifetime_ribs.push(function_lifetime_rib);
+ self.ribs[ValueNS].push(function_value_rib);
+ self.ribs[TypeNS].push(function_type_rib);
+
+ f(self);
+
+ self.ribs[TypeNS].pop();
+ self.ribs[ValueNS].pop();
+ let function_lifetime_rib = self.lifetime_ribs.pop().unwrap();
+
+ // Do not account for the parameters we just bound for function lifetime elision.
+ if let Some(ref mut candidates) = self.lifetime_elision_candidates {
+ for (_, res) in function_lifetime_rib.bindings.values() {
+ candidates.remove(res);
+ }
+ }
+
+ if let LifetimeBinderKind::BareFnType
+ | LifetimeBinderKind::WhereBound
+ | LifetimeBinderKind::Function
+ | LifetimeBinderKind::ImplBlock = generics_kind
+ {
+ self.maybe_report_lifetime_uses(generics_span, params)
+ }
+ }
+
+ fn with_label_rib(&mut self, kind: RibKind<'a>, f: impl FnOnce(&mut Self)) {
+ self.label_ribs.push(Rib::new(kind));
+ f(self);
+ self.label_ribs.pop();
+ }
+
+ fn with_item_rib(&mut self, f: impl FnOnce(&mut Self)) {
+ let kind = ItemRibKind(HasGenericParams::No);
+ self.with_lifetime_rib(LifetimeRibKind::Item, |this| {
+ this.with_rib(ValueNS, kind, |this| this.with_rib(TypeNS, kind, f))
+ })
+ }
+
+ // HACK(min_const_generics,const_evaluatable_unchecked): We
+ // want to keep allowing `[0; std::mem::size_of::<*mut T>()]`
+ // with a future compat lint for now. We do this by adding an
+ // additional special case for repeat expressions.
+ //
+ // Note that we intentionally still forbid `[0; N + 1]` during
+ // name resolution so that we don't extend the future
+ // compat lint to new cases.
+ #[instrument(level = "debug", skip(self, f))]
+ fn with_constant_rib(
+ &mut self,
+ is_repeat: IsRepeatExpr,
+ may_use_generics: HasGenericParams,
+ item: Option<(Ident, ConstantItemKind)>,
+ f: impl FnOnce(&mut Self),
+ ) {
+ self.with_rib(ValueNS, ConstantItemRibKind(may_use_generics, item), |this| {
+ this.with_rib(
+ TypeNS,
+ ConstantItemRibKind(
+ may_use_generics.force_yes_if(is_repeat == IsRepeatExpr::Yes),
+ item,
+ ),
+ |this| {
+ this.with_label_rib(ConstantItemRibKind(may_use_generics, item), f);
+ },
+ )
+ });
+ }
+
+ fn with_current_self_type<T>(&mut self, self_type: &Ty, f: impl FnOnce(&mut Self) -> T) -> T {
+ // Handle nested impls (inside fn bodies)
+ let previous_value =
+ replace(&mut self.diagnostic_metadata.current_self_type, Some(self_type.clone()));
+ let result = f(self);
+ self.diagnostic_metadata.current_self_type = previous_value;
+ result
+ }
+
+ fn with_current_self_item<T>(&mut self, self_item: &Item, f: impl FnOnce(&mut Self) -> T) -> T {
+ let previous_value =
+ replace(&mut self.diagnostic_metadata.current_self_item, Some(self_item.id));
+ let result = f(self);
+ self.diagnostic_metadata.current_self_item = previous_value;
+ result
+ }
+
+ /// When evaluating a `trait` use its associated types' idents for suggestions in E0412.
+ fn resolve_trait_items(&mut self, trait_items: &'ast [P<AssocItem>]) {
+ let trait_assoc_items =
+ replace(&mut self.diagnostic_metadata.current_trait_assoc_items, Some(&trait_items));
+
+ let walk_assoc_item =
+ |this: &mut Self, generics: &Generics, kind, item: &'ast AssocItem| {
+ this.with_generic_param_rib(
+ &generics.params,
+ AssocItemRibKind,
+ LifetimeRibKind::Generics { binder: item.id, span: generics.span, kind },
+ |this| visit::walk_assoc_item(this, item, AssocCtxt::Trait),
+ );
+ };
+
+ for item in trait_items {
+ match &item.kind {
+ AssocItemKind::Const(_, ty, default) => {
+ self.visit_ty(ty);
+ // Only impose the restrictions of `ConstRibKind` for an
+ // actual constant expression in a provided default.
+ if let Some(expr) = default {
+ // We allow arbitrary const expressions inside of associated consts,
+ // even if they are potentially not const evaluatable.
+ //
+ // Type parameters can already be used and as associated consts are
+ // not used as part of the type system, this is far less surprising.
+ self.with_lifetime_rib(
+ LifetimeRibKind::Elided(LifetimeRes::Infer),
+ |this| {
+ this.with_constant_rib(
+ IsRepeatExpr::No,
+ HasGenericParams::Yes,
+ None,
+ |this| this.visit_expr(expr),
+ )
+ },
+ );
+ }
+ }
+ AssocItemKind::Fn(box Fn { generics, .. }) => {
+ walk_assoc_item(self, generics, LifetimeBinderKind::Function, item);
+ }
+ AssocItemKind::TyAlias(box TyAlias { generics, .. }) => self
+ .with_lifetime_rib(LifetimeRibKind::AnonymousReportError, |this| {
+ walk_assoc_item(this, generics, LifetimeBinderKind::Item, item)
+ }),
+ AssocItemKind::MacCall(_) => {
+ panic!("unexpanded macro in resolve!")
+ }
+ };
+ }
+
+ self.diagnostic_metadata.current_trait_assoc_items = trait_assoc_items;
+ }
+
+ /// This is called to resolve a trait reference from an `impl` (i.e., `impl Trait for Foo`).
+ fn with_optional_trait_ref<T>(
+ &mut self,
+ opt_trait_ref: Option<&TraitRef>,
+ self_type: &'ast Ty,
+ f: impl FnOnce(&mut Self, Option<DefId>) -> T,
+ ) -> T {
+ let mut new_val = None;
+ let mut new_id = None;
+ if let Some(trait_ref) = opt_trait_ref {
+ let path: Vec<_> = Segment::from_path(&trait_ref.path);
+ self.diagnostic_metadata.currently_processing_impl_trait =
+ Some((trait_ref.clone(), self_type.clone()));
+ let res = self.smart_resolve_path_fragment(
+ None,
+ &path,
+ PathSource::Trait(AliasPossibility::No),
+ Finalize::new(trait_ref.ref_id, trait_ref.path.span),
+ );
+ self.diagnostic_metadata.currently_processing_impl_trait = None;
+ if let Some(def_id) = res.base_res().opt_def_id() {
+ new_id = Some(def_id);
+ new_val = Some((self.r.expect_module(def_id), trait_ref.clone()));
+ }
+ }
+ let original_trait_ref = replace(&mut self.current_trait_ref, new_val);
+ let result = f(self, new_id);
+ self.current_trait_ref = original_trait_ref;
+ result
+ }
+
+ fn with_self_rib_ns(&mut self, ns: Namespace, self_res: Res, f: impl FnOnce(&mut Self)) {
+ let mut self_type_rib = Rib::new(NormalRibKind);
+
+ // Plain insert (no renaming, since types are not currently hygienic)
+ self_type_rib.bindings.insert(Ident::with_dummy_span(kw::SelfUpper), self_res);
+ self.ribs[ns].push(self_type_rib);
+ f(self);
+ self.ribs[ns].pop();
+ }
+
+ fn with_self_rib(&mut self, self_res: Res, f: impl FnOnce(&mut Self)) {
+ self.with_self_rib_ns(TypeNS, self_res, f)
+ }
+
+ fn resolve_implementation(
+ &mut self,
+ generics: &'ast Generics,
+ opt_trait_reference: &'ast Option<TraitRef>,
+ self_type: &'ast Ty,
+ item_id: NodeId,
+ impl_items: &'ast [P<AssocItem>],
+ ) {
+ debug!("resolve_implementation");
+ // If applicable, create a rib for the type parameters.
+ self.with_generic_param_rib(
+ &generics.params,
+ ItemRibKind(HasGenericParams::Yes),
+ LifetimeRibKind::Generics {
+ span: generics.span,
+ binder: item_id,
+ kind: LifetimeBinderKind::ImplBlock,
+ },
+ |this| {
+ // Dummy self type for better errors if `Self` is used in the trait path.
+ this.with_self_rib(Res::SelfTy { trait_: None, alias_to: None }, |this| {
+ this.with_lifetime_rib(
+ LifetimeRibKind::AnonymousCreateParameter {
+ binder: item_id,
+ report_in_path: true
+ },
+ |this| {
+ // Resolve the trait reference, if necessary.
+ this.with_optional_trait_ref(
+ opt_trait_reference.as_ref(),
+ self_type,
+ |this, trait_id| {
+ let item_def_id = this.r.local_def_id(item_id);
+
+ // Register the trait definitions from here.
+ if let Some(trait_id) = trait_id {
+ this.r
+ .trait_impls
+ .entry(trait_id)
+ .or_default()
+ .push(item_def_id);
+ }
+
+ let item_def_id = item_def_id.to_def_id();
+ let res = Res::SelfTy {
+ trait_: trait_id,
+ alias_to: Some((item_def_id, false)),
+ };
+ this.with_self_rib(res, |this| {
+ if let Some(trait_ref) = opt_trait_reference.as_ref() {
+ // Resolve type arguments in the trait path.
+ visit::walk_trait_ref(this, trait_ref);
+ }
+ // Resolve the self type.
+ this.visit_ty(self_type);
+ // Resolve the generic parameters.
+ this.visit_generics(generics);
+
+ // Resolve the items within the impl.
+ this.with_current_self_type(self_type, |this| {
+ this.with_self_rib_ns(ValueNS, Res::SelfCtor(item_def_id), |this| {
+ debug!("resolve_implementation with_self_rib_ns(ValueNS, ...)");
+ for item in impl_items {
+ this.resolve_impl_item(&**item);
+ }
+ });
+ });
+ });
+ },
+ )
+ },
+ );
+ });
+ },
+ );
+ }
+
+ fn resolve_impl_item(&mut self, item: &'ast AssocItem) {
+ use crate::ResolutionError::*;
+ match &item.kind {
+ AssocItemKind::Const(_, ty, default) => {
+ debug!("resolve_implementation AssocItemKind::Const");
+ // If this is a trait impl, ensure the const
+ // exists in trait
+ self.check_trait_item(
+ item.id,
+ item.ident,
+ &item.kind,
+ ValueNS,
+ item.span,
+ |i, s, c| ConstNotMemberOfTrait(i, s, c),
+ );
+
+ self.visit_ty(ty);
+ if let Some(expr) = default {
+ // We allow arbitrary const expressions inside of associated consts,
+ // even if they are potentially not const evaluatable.
+ //
+ // Type parameters can already be used and as associated consts are
+ // not used as part of the type system, this is far less surprising.
+ self.with_lifetime_rib(LifetimeRibKind::Elided(LifetimeRes::Infer), |this| {
+ this.with_constant_rib(
+ IsRepeatExpr::No,
+ HasGenericParams::Yes,
+ None,
+ |this| this.visit_expr(expr),
+ )
+ });
+ }
+ }
+ AssocItemKind::Fn(box Fn { generics, .. }) => {
+ debug!("resolve_implementation AssocItemKind::Fn");
+ // We also need a new scope for the impl item type parameters.
+ self.with_generic_param_rib(
+ &generics.params,
+ AssocItemRibKind,
+ LifetimeRibKind::Generics {
+ binder: item.id,
+ span: generics.span,
+ kind: LifetimeBinderKind::Function,
+ },
+ |this| {
+ // If this is a trait impl, ensure the method
+ // exists in trait
+ this.check_trait_item(
+ item.id,
+ item.ident,
+ &item.kind,
+ ValueNS,
+ item.span,
+ |i, s, c| MethodNotMemberOfTrait(i, s, c),
+ );
+
+ visit::walk_assoc_item(this, item, AssocCtxt::Impl)
+ },
+ );
+ }
+ AssocItemKind::TyAlias(box TyAlias { generics, .. }) => {
+ debug!("resolve_implementation AssocItemKind::TyAlias");
+ // We also need a new scope for the impl item type parameters.
+ self.with_generic_param_rib(
+ &generics.params,
+ AssocItemRibKind,
+ LifetimeRibKind::Generics {
+ binder: item.id,
+ span: generics.span,
+ kind: LifetimeBinderKind::Item,
+ },
+ |this| {
+ this.with_lifetime_rib(LifetimeRibKind::AnonymousReportError, |this| {
+ // If this is a trait impl, ensure the type
+ // exists in trait
+ this.check_trait_item(
+ item.id,
+ item.ident,
+ &item.kind,
+ TypeNS,
+ item.span,
+ |i, s, c| TypeNotMemberOfTrait(i, s, c),
+ );
+
+ visit::walk_assoc_item(this, item, AssocCtxt::Impl)
+ });
+ },
+ );
+ }
+ AssocItemKind::MacCall(_) => {
+ panic!("unexpanded macro in resolve!")
+ }
+ }
+ }
+
+ fn check_trait_item<F>(
+ &mut self,
+ id: NodeId,
+ mut ident: Ident,
+ kind: &AssocItemKind,
+ ns: Namespace,
+ span: Span,
+ err: F,
+ ) where
+ F: FnOnce(Ident, String, Option<Symbol>) -> ResolutionError<'a>,
+ {
+ // If there is a TraitRef in scope for an impl, then the method must be in the trait.
+ let Some((module, _)) = &self.current_trait_ref else { return; };
+ ident.span.normalize_to_macros_2_0_and_adjust(module.expansion);
+ let key = self.r.new_key(ident, ns);
+ let mut binding = self.r.resolution(module, key).try_borrow().ok().and_then(|r| r.binding);
+ debug!(?binding);
+ if binding.is_none() {
+ // We could not find the trait item in the correct namespace.
+ // Check the other namespace to report an error.
+ let ns = match ns {
+ ValueNS => TypeNS,
+ TypeNS => ValueNS,
+ _ => ns,
+ };
+ let key = self.r.new_key(ident, ns);
+ binding = self.r.resolution(module, key).try_borrow().ok().and_then(|r| r.binding);
+ debug!(?binding);
+ }
+ let Some(binding) = binding else {
+ // We could not find the method: report an error.
+ let candidate = self.find_similarly_named_assoc_item(ident.name, kind);
+ let path = &self.current_trait_ref.as_ref().unwrap().1.path;
+ let path_names = path_names_to_string(path);
+ self.report_error(span, err(ident, path_names, candidate));
+ return;
+ };
+
+ let res = binding.res();
+ let Res::Def(def_kind, _) = res else { bug!() };
+ match (def_kind, kind) {
+ (DefKind::AssocTy, AssocItemKind::TyAlias(..))
+ | (DefKind::AssocFn, AssocItemKind::Fn(..))
+ | (DefKind::AssocConst, AssocItemKind::Const(..)) => {
+ self.r.record_partial_res(id, PartialRes::new(res));
+ return;
+ }
+ _ => {}
+ }
+
+ // The method kind does not correspond to what appeared in the trait, report.
+ let path = &self.current_trait_ref.as_ref().unwrap().1.path;
+ let (code, kind) = match kind {
+ AssocItemKind::Const(..) => (rustc_errors::error_code!(E0323), "const"),
+ AssocItemKind::Fn(..) => (rustc_errors::error_code!(E0324), "method"),
+ AssocItemKind::TyAlias(..) => (rustc_errors::error_code!(E0325), "type"),
+ AssocItemKind::MacCall(..) => span_bug!(span, "unexpanded macro"),
+ };
+ let trait_path = path_names_to_string(path);
+ self.report_error(
+ span,
+ ResolutionError::TraitImplMismatch {
+ name: ident.name,
+ kind,
+ code,
+ trait_path,
+ trait_item_span: binding.span,
+ },
+ );
+ }
+
+ fn resolve_params(&mut self, params: &'ast [Param]) {
+ let mut bindings = smallvec![(PatBoundCtx::Product, Default::default())];
+ for Param { pat, ty, .. } in params {
+ self.resolve_pattern(pat, PatternSource::FnParam, &mut bindings);
+ self.visit_ty(ty);
+ debug!("(resolving function / closure) recorded parameter");
+ }
+ }
+
+ fn resolve_local(&mut self, local: &'ast Local) {
+ debug!("resolving local ({:?})", local);
+ // Resolve the type.
+ walk_list!(self, visit_ty, &local.ty);
+
+ // Resolve the initializer.
+ if let Some((init, els)) = local.kind.init_else_opt() {
+ self.visit_expr(init);
+
+ // Resolve the `else` block
+ if let Some(els) = els {
+ self.visit_block(els);
+ }
+ }
+
+ // Resolve the pattern.
+ self.resolve_pattern_top(&local.pat, PatternSource::Let);
+ }
+
+ /// build a map from pattern identifiers to binding-info's.
+ /// this is done hygienically. This could arise for a macro
+ /// that expands into an or-pattern where one 'x' was from the
+ /// user and one 'x' came from the macro.
+ fn binding_mode_map(&mut self, pat: &Pat) -> BindingMap {
+ let mut binding_map = FxHashMap::default();
+
+ pat.walk(&mut |pat| {
+ match pat.kind {
+ PatKind::Ident(binding_mode, ident, ref sub_pat)
+ if sub_pat.is_some() || self.is_base_res_local(pat.id) =>
+ {
+ binding_map.insert(ident, BindingInfo { span: ident.span, binding_mode });
+ }
+ PatKind::Or(ref ps) => {
+ // Check the consistency of this or-pattern and
+ // then add all bindings to the larger map.
+ for bm in self.check_consistent_bindings(ps) {
+ binding_map.extend(bm);
+ }
+ return false;
+ }
+ _ => {}
+ }
+
+ true
+ });
+
+ binding_map
+ }
+
+ fn is_base_res_local(&self, nid: NodeId) -> bool {
+ matches!(self.r.partial_res_map.get(&nid).map(|res| res.base_res()), Some(Res::Local(..)))
+ }
+
+ /// Checks that all of the arms in an or-pattern have exactly the
+ /// same set of bindings, with the same binding modes for each.
+ fn check_consistent_bindings(&mut self, pats: &[P<Pat>]) -> Vec<BindingMap> {
+ let mut missing_vars = FxHashMap::default();
+ let mut inconsistent_vars = FxHashMap::default();
+
+ // 1) Compute the binding maps of all arms.
+ let maps = pats.iter().map(|pat| self.binding_mode_map(pat)).collect::<Vec<_>>();
+
+ // 2) Record any missing bindings or binding mode inconsistencies.
+ for (map_outer, pat_outer) in pats.iter().enumerate().map(|(idx, pat)| (&maps[idx], pat)) {
+ // Check against all arms except for the same pattern which is always self-consistent.
+ let inners = pats
+ .iter()
+ .enumerate()
+ .filter(|(_, pat)| pat.id != pat_outer.id)
+ .flat_map(|(idx, _)| maps[idx].iter())
+ .map(|(key, binding)| (key.name, map_outer.get(&key), binding));
+
+ for (name, info, &binding_inner) in inners {
+ match info {
+ None => {
+ // The inner binding is missing in the outer.
+ let binding_error =
+ missing_vars.entry(name).or_insert_with(|| BindingError {
+ name,
+ origin: BTreeSet::new(),
+ target: BTreeSet::new(),
+ could_be_path: name.as_str().starts_with(char::is_uppercase),
+ });
+ binding_error.origin.insert(binding_inner.span);
+ binding_error.target.insert(pat_outer.span);
+ }
+ Some(binding_outer) => {
+ if binding_outer.binding_mode != binding_inner.binding_mode {
+ // The binding modes in the outer and inner bindings differ.
+ inconsistent_vars
+ .entry(name)
+ .or_insert((binding_inner.span, binding_outer.span));
+ }
+ }
+ }
+ }
+ }
+
+ // 3) Report all missing variables we found.
+ let mut missing_vars = missing_vars.into_iter().collect::<Vec<_>>();
+ missing_vars.sort_by_key(|&(sym, ref _err)| sym);
+
+ for (name, mut v) in missing_vars.into_iter() {
+ if inconsistent_vars.contains_key(&name) {
+ v.could_be_path = false;
+ }
+ self.report_error(
+ *v.origin.iter().next().unwrap(),
+ ResolutionError::VariableNotBoundInPattern(v, self.parent_scope),
+ );
+ }
+
+ // 4) Report all inconsistencies in binding modes we found.
+ let mut inconsistent_vars = inconsistent_vars.iter().collect::<Vec<_>>();
+ inconsistent_vars.sort();
+ for (name, v) in inconsistent_vars {
+ self.report_error(v.0, ResolutionError::VariableBoundWithDifferentMode(*name, v.1));
+ }
+
+ // 5) Finally bubble up all the binding maps.
+ maps
+ }
+
+ /// Check the consistency of the outermost or-patterns.
+ fn check_consistent_bindings_top(&mut self, pat: &'ast Pat) {
+ pat.walk(&mut |pat| match pat.kind {
+ PatKind::Or(ref ps) => {
+ self.check_consistent_bindings(ps);
+ false
+ }
+ _ => true,
+ })
+ }
+
+ fn resolve_arm(&mut self, arm: &'ast Arm) {
+ self.with_rib(ValueNS, NormalRibKind, |this| {
+ this.resolve_pattern_top(&arm.pat, PatternSource::Match);
+ walk_list!(this, visit_expr, &arm.guard);
+ this.visit_expr(&arm.body);
+ });
+ }
+
+ /// Arising from `source`, resolve a top level pattern.
+ fn resolve_pattern_top(&mut self, pat: &'ast Pat, pat_src: PatternSource) {
+ let mut bindings = smallvec![(PatBoundCtx::Product, Default::default())];
+ self.resolve_pattern(pat, pat_src, &mut bindings);
+ }
+
+ fn resolve_pattern(
+ &mut self,
+ pat: &'ast Pat,
+ pat_src: PatternSource,
+ bindings: &mut SmallVec<[(PatBoundCtx, FxHashSet<Ident>); 1]>,
+ ) {
+ // We walk the pattern before declaring the pattern's inner bindings,
+ // so that we avoid resolving a literal expression to a binding defined
+ // by the pattern.
+ visit::walk_pat(self, pat);
+ self.resolve_pattern_inner(pat, pat_src, bindings);
+ // This has to happen *after* we determine which pat_idents are variants:
+ self.check_consistent_bindings_top(pat);
+ }
+
+ /// Resolve bindings in a pattern. This is a helper to `resolve_pattern`.
+ ///
+ /// ### `bindings`
+ ///
+ /// A stack of sets of bindings accumulated.
+ ///
+ /// In each set, `PatBoundCtx::Product` denotes that a found binding in it should
+ /// be interpreted as re-binding an already bound binding. This results in an error.
+ /// Meanwhile, `PatBound::Or` denotes that a found binding in the set should result
+ /// in reusing this binding rather than creating a fresh one.
+ ///
+ /// When called at the top level, the stack must have a single element
+ /// with `PatBound::Product`. Otherwise, pushing to the stack happens as
+ /// or-patterns (`p_0 | ... | p_n`) are encountered and the context needs
+ /// to be switched to `PatBoundCtx::Or` and then `PatBoundCtx::Product` for each `p_i`.
+ /// When each `p_i` has been dealt with, the top set is merged with its parent.
+ /// When a whole or-pattern has been dealt with, the thing happens.
+ ///
+ /// See the implementation and `fresh_binding` for more details.
+ fn resolve_pattern_inner(
+ &mut self,
+ pat: &Pat,
+ pat_src: PatternSource,
+ bindings: &mut SmallVec<[(PatBoundCtx, FxHashSet<Ident>); 1]>,
+ ) {
+ // Visit all direct subpatterns of this pattern.
+ pat.walk(&mut |pat| {
+ debug!("resolve_pattern pat={:?} node={:?}", pat, pat.kind);
+ match pat.kind {
+ PatKind::Ident(bmode, ident, ref sub) => {
+ // First try to resolve the identifier as some existing entity,
+ // then fall back to a fresh binding.
+ let has_sub = sub.is_some();
+ let res = self
+ .try_resolve_as_non_binding(pat_src, bmode, ident, has_sub)
+ .unwrap_or_else(|| self.fresh_binding(ident, pat.id, pat_src, bindings));
+ self.r.record_partial_res(pat.id, PartialRes::new(res));
+ self.r.record_pat_span(pat.id, pat.span);
+ }
+ PatKind::TupleStruct(ref qself, ref path, ref sub_patterns) => {
+ self.smart_resolve_path(
+ pat.id,
+ qself.as_ref(),
+ path,
+ PathSource::TupleStruct(
+ pat.span,
+ self.r.arenas.alloc_pattern_spans(sub_patterns.iter().map(|p| p.span)),
+ ),
+ );
+ }
+ PatKind::Path(ref qself, ref path) => {
+ self.smart_resolve_path(pat.id, qself.as_ref(), path, PathSource::Pat);
+ }
+ PatKind::Struct(ref qself, ref path, ..) => {
+ self.smart_resolve_path(pat.id, qself.as_ref(), path, PathSource::Struct);
+ }
+ PatKind::Or(ref ps) => {
+ // Add a new set of bindings to the stack. `Or` here records that when a
+ // binding already exists in this set, it should not result in an error because
+ // `V1(a) | V2(a)` must be allowed and are checked for consistency later.
+ bindings.push((PatBoundCtx::Or, Default::default()));
+ for p in ps {
+ // Now we need to switch back to a product context so that each
+ // part of the or-pattern internally rejects already bound names.
+ // For example, `V1(a) | V2(a, a)` and `V1(a, a) | V2(a)` are bad.
+ bindings.push((PatBoundCtx::Product, Default::default()));
+ self.resolve_pattern_inner(p, pat_src, bindings);
+ // Move up the non-overlapping bindings to the or-pattern.
+ // Existing bindings just get "merged".
+ let collected = bindings.pop().unwrap().1;
+ bindings.last_mut().unwrap().1.extend(collected);
+ }
+ // This or-pattern itself can itself be part of a product,
+ // e.g. `(V1(a) | V2(a), a)` or `(a, V1(a) | V2(a))`.
+ // Both cases bind `a` again in a product pattern and must be rejected.
+ let collected = bindings.pop().unwrap().1;
+ bindings.last_mut().unwrap().1.extend(collected);
+
+ // Prevent visiting `ps` as we've already done so above.
+ return false;
+ }
+ _ => {}
+ }
+ true
+ });
+ }
+
+ fn fresh_binding(
+ &mut self,
+ ident: Ident,
+ pat_id: NodeId,
+ pat_src: PatternSource,
+ bindings: &mut SmallVec<[(PatBoundCtx, FxHashSet<Ident>); 1]>,
+ ) -> Res {
+ // Add the binding to the local ribs, if it doesn't already exist in the bindings map.
+ // (We must not add it if it's in the bindings map because that breaks the assumptions
+ // later passes make about or-patterns.)
+ let ident = ident.normalize_to_macro_rules();
+
+ let mut bound_iter = bindings.iter().filter(|(_, set)| set.contains(&ident));
+ // Already bound in a product pattern? e.g. `(a, a)` which is not allowed.
+ let already_bound_and = bound_iter.clone().any(|(ctx, _)| *ctx == PatBoundCtx::Product);
+ // Already bound in an or-pattern? e.g. `V1(a) | V2(a)`.
+ // This is *required* for consistency which is checked later.
+ let already_bound_or = bound_iter.any(|(ctx, _)| *ctx == PatBoundCtx::Or);
+
+ if already_bound_and {
+ // Overlap in a product pattern somewhere; report an error.
+ use ResolutionError::*;
+ let error = match pat_src {
+ // `fn f(a: u8, a: u8)`:
+ PatternSource::FnParam => IdentifierBoundMoreThanOnceInParameterList,
+ // `Variant(a, a)`:
+ _ => IdentifierBoundMoreThanOnceInSamePattern,
+ };
+ self.report_error(ident.span, error(ident.name));
+ }
+
+ // Record as bound if it's valid:
+ let ident_valid = ident.name != kw::Empty;
+ if ident_valid {
+ bindings.last_mut().unwrap().1.insert(ident);
+ }
+
+ if already_bound_or {
+ // `Variant1(a) | Variant2(a)`, ok
+ // Reuse definition from the first `a`.
+ self.innermost_rib_bindings(ValueNS)[&ident]
+ } else {
+ let res = Res::Local(pat_id);
+ if ident_valid {
+ // A completely fresh binding add to the set if it's valid.
+ self.innermost_rib_bindings(ValueNS).insert(ident, res);
+ }
+ res
+ }
+ }
+
+ fn innermost_rib_bindings(&mut self, ns: Namespace) -> &mut IdentMap<Res> {
+ &mut self.ribs[ns].last_mut().unwrap().bindings
+ }
+
+ fn try_resolve_as_non_binding(
+ &mut self,
+ pat_src: PatternSource,
+ bm: BindingMode,
+ ident: Ident,
+ has_sub: bool,
+ ) -> Option<Res> {
+ // An immutable (no `mut`) by-value (no `ref`) binding pattern without
+ // a sub pattern (no `@ $pat`) is syntactically ambiguous as it could
+ // also be interpreted as a path to e.g. a constant, variant, etc.
+ let is_syntactic_ambiguity = !has_sub && bm == BindingMode::ByValue(Mutability::Not);
+
+ let ls_binding = self.maybe_resolve_ident_in_lexical_scope(ident, ValueNS)?;
+ let (res, binding) = match ls_binding {
+ LexicalScopeBinding::Item(binding)
+ if is_syntactic_ambiguity && binding.is_ambiguity() =>
+ {
+ // For ambiguous bindings we don't know all their definitions and cannot check
+ // whether they can be shadowed by fresh bindings or not, so force an error.
+ // issues/33118#issuecomment-233962221 (see below) still applies here,
+ // but we have to ignore it for backward compatibility.
+ self.r.record_use(ident, binding, false);
+ return None;
+ }
+ LexicalScopeBinding::Item(binding) => (binding.res(), Some(binding)),
+ LexicalScopeBinding::Res(res) => (res, None),
+ };
+
+ match res {
+ Res::SelfCtor(_) // See #70549.
+ | Res::Def(
+ DefKind::Ctor(_, CtorKind::Const) | DefKind::Const | DefKind::ConstParam,
+ _,
+ ) if is_syntactic_ambiguity => {
+ // Disambiguate in favor of a unit struct/variant or constant pattern.
+ if let Some(binding) = binding {
+ self.r.record_use(ident, binding, false);
+ }
+ Some(res)
+ }
+ Res::Def(DefKind::Ctor(..) | DefKind::Const | DefKind::Static(_), _) => {
+ // This is unambiguously a fresh binding, either syntactically
+ // (e.g., `IDENT @ PAT` or `ref IDENT`) or because `IDENT` resolves
+ // to something unusable as a pattern (e.g., constructor function),
+ // but we still conservatively report an error, see
+ // issues/33118#issuecomment-233962221 for one reason why.
+ let binding = binding.expect("no binding for a ctor or static");
+ self.report_error(
+ ident.span,
+ ResolutionError::BindingShadowsSomethingUnacceptable {
+ shadowing_binding: pat_src,
+ name: ident.name,
+ participle: if binding.is_import() { "imported" } else { "defined" },
+ article: binding.res().article(),
+ shadowed_binding: binding.res(),
+ shadowed_binding_span: binding.span,
+ },
+ );
+ None
+ }
+ Res::Def(DefKind::ConstParam, def_id) => {
+ // Same as for DefKind::Const above, but here, `binding` is `None`, so we
+ // have to construct the error differently
+ self.report_error(
+ ident.span,
+ ResolutionError::BindingShadowsSomethingUnacceptable {
+ shadowing_binding: pat_src,
+ name: ident.name,
+ participle: "defined",
+ article: res.article(),
+ shadowed_binding: res,
+ shadowed_binding_span: self.r.opt_span(def_id).expect("const parameter defined outside of local crate"),
+ }
+ );
+ None
+ }
+ Res::Def(DefKind::Fn, _) | Res::Local(..) | Res::Err => {
+ // These entities are explicitly allowed to be shadowed by fresh bindings.
+ None
+ }
+ Res::SelfCtor(_) => {
+ // We resolve `Self` in pattern position as an ident sometimes during recovery,
+ // so delay a bug instead of ICEing.
+ self.r.session.delay_span_bug(
+ ident.span,
+ "unexpected `SelfCtor` in pattern, expected identifier"
+ );
+ None
+ }
+ _ => span_bug!(
+ ident.span,
+ "unexpected resolution for an identifier in pattern: {:?}",
+ res,
+ ),
+ }
+ }
+
+ // High-level and context dependent path resolution routine.
+ // Resolves the path and records the resolution into definition map.
+ // If resolution fails tries several techniques to find likely
+ // resolution candidates, suggest imports or other help, and report
+ // errors in user friendly way.
+ fn smart_resolve_path(
+ &mut self,
+ id: NodeId,
+ qself: Option<&QSelf>,
+ path: &Path,
+ source: PathSource<'ast>,
+ ) {
+ self.smart_resolve_path_fragment(
+ qself,
+ &Segment::from_path(path),
+ source,
+ Finalize::new(id, path.span),
+ );
+ }
+
+ fn smart_resolve_path_fragment(
+ &mut self,
+ qself: Option<&QSelf>,
+ path: &[Segment],
+ source: PathSource<'ast>,
+ finalize: Finalize,
+ ) -> PartialRes {
+ tracing::debug!(
+ "smart_resolve_path_fragment(qself={:?}, path={:?}, finalize={:?})",
+ qself,
+ path,
+ finalize,
+ );
+ let ns = source.namespace();
+
+ let Finalize { node_id, path_span, .. } = finalize;
+ let report_errors = |this: &mut Self, res: Option<Res>| {
+ if this.should_report_errs() {
+ let (err, candidates) =
+ this.smart_resolve_report_errors(path, path_span, source, res);
+
+ let def_id = this.parent_scope.module.nearest_parent_mod();
+ let instead = res.is_some();
+ let suggestion =
+ if res.is_none() { this.report_missing_type_error(path) } else { None };
+
+ this.r.use_injections.push(UseError {
+ err,
+ candidates,
+ def_id,
+ instead,
+ suggestion,
+ path: path.into(),
+ });
+ }
+
+ PartialRes::new(Res::Err)
+ };
+
+ // For paths originating from calls (like in `HashMap::new()`), tries
+ // to enrich the plain `failed to resolve: ...` message with hints
+ // about possible missing imports.
+ //
+ // Similar thing, for types, happens in `report_errors` above.
+ let report_errors_for_call = |this: &mut Self, parent_err: Spanned<ResolutionError<'a>>| {
+ if !source.is_call() {
+ return Some(parent_err);
+ }
+
+ // Before we start looking for candidates, we have to get our hands
+ // on the type user is trying to perform invocation on; basically:
+ // we're transforming `HashMap::new` into just `HashMap`.
+ let path = match path.split_last() {
+ Some((_, path)) if !path.is_empty() => path,
+ _ => return Some(parent_err),
+ };
+
+ let (mut err, candidates) =
+ this.smart_resolve_report_errors(path, path_span, PathSource::Type, None);
+
+ if candidates.is_empty() {
+ err.cancel();
+ return Some(parent_err);
+ }
+
+ // There are two different error messages user might receive at
+ // this point:
+ // - E0412 cannot find type `{}` in this scope
+ // - E0433 failed to resolve: use of undeclared type or module `{}`
+ //
+ // The first one is emitted for paths in type-position, and the
+ // latter one - for paths in expression-position.
+ //
+ // Thus (since we're in expression-position at this point), not to
+ // confuse the user, we want to keep the *message* from E0432 (so
+ // `parent_err`), but we want *hints* from E0412 (so `err`).
+ //
+ // And that's what happens below - we're just mixing both messages
+ // into a single one.
+ let mut parent_err = this.r.into_struct_error(parent_err.span, parent_err.node);
+
+ err.message = take(&mut parent_err.message);
+ err.code = take(&mut parent_err.code);
+ err.children = take(&mut parent_err.children);
+
+ parent_err.cancel();
+
+ let def_id = this.parent_scope.module.nearest_parent_mod();
+
+ if this.should_report_errs() {
+ this.r.use_injections.push(UseError {
+ err,
+ candidates,
+ def_id,
+ instead: false,
+ suggestion: None,
+ path: path.into(),
+ });
+ } else {
+ err.cancel();
+ }
+
+ // We don't return `Some(parent_err)` here, because the error will
+ // be already printed as part of the `use` injections
+ None
+ };
+
+ let partial_res = match self.resolve_qpath_anywhere(
+ qself,
+ path,
+ ns,
+ path_span,
+ source.defer_to_typeck(),
+ finalize,
+ ) {
+ Ok(Some(partial_res)) if partial_res.unresolved_segments() == 0 => {
+ if source.is_expected(partial_res.base_res()) || partial_res.base_res() == Res::Err
+ {
+ partial_res
+ } else {
+ report_errors(self, Some(partial_res.base_res()))
+ }
+ }
+
+ Ok(Some(partial_res)) if source.defer_to_typeck() => {
+ // Not fully resolved associated item `T::A::B` or `<T as Tr>::A::B`
+ // or `<T>::A::B`. If `B` should be resolved in value namespace then
+ // it needs to be added to the trait map.
+ if ns == ValueNS {
+ let item_name = path.last().unwrap().ident;
+ let traits = self.traits_in_scope(item_name, ns);
+ self.r.trait_map.insert(node_id, traits);
+ }
+
+ if PrimTy::from_name(path[0].ident.name).is_some() {
+ let mut std_path = Vec::with_capacity(1 + path.len());
+
+ std_path.push(Segment::from_ident(Ident::with_dummy_span(sym::std)));
+ std_path.extend(path);
+ if let PathResult::Module(_) | PathResult::NonModule(_) =
+ self.resolve_path(&std_path, Some(ns), None)
+ {
+ // Check if we wrote `str::from_utf8` instead of `std::str::from_utf8`
+ let item_span =
+ path.iter().last().map_or(path_span, |segment| segment.ident.span);
+
+ self.r.confused_type_with_std_module.insert(item_span, path_span);
+ self.r.confused_type_with_std_module.insert(path_span, path_span);
+ }
+ }
+
+ partial_res
+ }
+
+ Err(err) => {
+ if let Some(err) = report_errors_for_call(self, err) {
+ self.report_error(err.span, err.node);
+ }
+
+ PartialRes::new(Res::Err)
+ }
+
+ _ => report_errors(self, None),
+ };
+
+ if !matches!(source, PathSource::TraitItem(..)) {
+ // Avoid recording definition of `A::B` in `<T as A>::B::C`.
+ self.r.record_partial_res(node_id, partial_res);
+ self.resolve_elided_lifetimes_in_path(node_id, partial_res, path, source, path_span);
+ }
+
+ partial_res
+ }
+
+ fn self_type_is_available(&mut self) -> bool {
+ let binding = self
+ .maybe_resolve_ident_in_lexical_scope(Ident::with_dummy_span(kw::SelfUpper), TypeNS);
+ if let Some(LexicalScopeBinding::Res(res)) = binding { res != Res::Err } else { false }
+ }
+
+ fn self_value_is_available(&mut self, self_span: Span) -> bool {
+ let ident = Ident::new(kw::SelfLower, self_span);
+ let binding = self.maybe_resolve_ident_in_lexical_scope(ident, ValueNS);
+ if let Some(LexicalScopeBinding::Res(res)) = binding { res != Res::Err } else { false }
+ }
+
+ /// A wrapper around [`Resolver::report_error`].
+ ///
+ /// This doesn't emit errors for function bodies if this is rustdoc.
+ fn report_error(&mut self, span: Span, resolution_error: ResolutionError<'a>) {
+ if self.should_report_errs() {
+ self.r.report_error(span, resolution_error);
+ }
+ }
+
+ #[inline]
+ /// If we're actually rustdoc then avoid giving a name resolution error for `cfg()` items.
+ fn should_report_errs(&self) -> bool {
+ !(self.r.session.opts.actually_rustdoc && self.in_func_body)
+ }
+
+ // Resolve in alternative namespaces if resolution in the primary namespace fails.
+ fn resolve_qpath_anywhere(
+ &mut self,
+ qself: Option<&QSelf>,
+ path: &[Segment],
+ primary_ns: Namespace,
+ span: Span,
+ defer_to_typeck: bool,
+ finalize: Finalize,
+ ) -> Result<Option<PartialRes>, Spanned<ResolutionError<'a>>> {
+ let mut fin_res = None;
+
+ for (i, &ns) in [primary_ns, TypeNS, ValueNS].iter().enumerate() {
+ if i == 0 || ns != primary_ns {
+ match self.resolve_qpath(qself, path, ns, finalize)? {
+ Some(partial_res)
+ if partial_res.unresolved_segments() == 0 || defer_to_typeck =>
+ {
+ return Ok(Some(partial_res));
+ }
+ partial_res => {
+ if fin_res.is_none() {
+ fin_res = partial_res;
+ }
+ }
+ }
+ }
+ }
+
+ assert!(primary_ns != MacroNS);
+
+ if qself.is_none() {
+ let path_seg = |seg: &Segment| PathSegment::from_ident(seg.ident);
+ let path = Path { segments: path.iter().map(path_seg).collect(), span, tokens: None };
+ if let Ok((_, res)) =
+ self.r.resolve_macro_path(&path, None, &self.parent_scope, false, false)
+ {
+ return Ok(Some(PartialRes::new(res)));
+ }
+ }
+
+ Ok(fin_res)
+ }
+
+ /// Handles paths that may refer to associated items.
+ fn resolve_qpath(
+ &mut self,
+ qself: Option<&QSelf>,
+ path: &[Segment],
+ ns: Namespace,
+ finalize: Finalize,
+ ) -> Result<Option<PartialRes>, Spanned<ResolutionError<'a>>> {
+ debug!(
+ "resolve_qpath(qself={:?}, path={:?}, ns={:?}, finalize={:?})",
+ qself, path, ns, finalize,
+ );
+
+ if let Some(qself) = qself {
+ if qself.position == 0 {
+ // This is a case like `<T>::B`, where there is no
+ // trait to resolve. In that case, we leave the `B`
+ // segment to be resolved by type-check.
+ return Ok(Some(PartialRes::with_unresolved_segments(
+ Res::Def(DefKind::Mod, CRATE_DEF_ID.to_def_id()),
+ path.len(),
+ )));
+ }
+
+ // Make sure `A::B` in `<T as A::B>::C` is a trait item.
+ //
+ // Currently, `path` names the full item (`A::B::C`, in
+ // our example). so we extract the prefix of that that is
+ // the trait (the slice upto and including
+ // `qself.position`). And then we recursively resolve that,
+ // but with `qself` set to `None`.
+ let ns = if qself.position + 1 == path.len() { ns } else { TypeNS };
+ let partial_res = self.smart_resolve_path_fragment(
+ None,
+ &path[..=qself.position],
+ PathSource::TraitItem(ns),
+ Finalize::with_root_span(finalize.node_id, finalize.path_span, qself.path_span),
+ );
+
+ // The remaining segments (the `C` in our example) will
+ // have to be resolved by type-check, since that requires doing
+ // trait resolution.
+ return Ok(Some(PartialRes::with_unresolved_segments(
+ partial_res.base_res(),
+ partial_res.unresolved_segments() + path.len() - qself.position - 1,
+ )));
+ }
+
+ let result = match self.resolve_path(&path, Some(ns), Some(finalize)) {
+ PathResult::NonModule(path_res) => path_res,
+ PathResult::Module(ModuleOrUniformRoot::Module(module)) if !module.is_normal() => {
+ PartialRes::new(module.res().unwrap())
+ }
+ // In `a(::assoc_item)*` `a` cannot be a module. If `a` does resolve to a module we
+ // don't report an error right away, but try to fallback to a primitive type.
+ // So, we are still able to successfully resolve something like
+ //
+ // use std::u8; // bring module u8 in scope
+ // fn f() -> u8 { // OK, resolves to primitive u8, not to std::u8
+ // u8::max_value() // OK, resolves to associated function <u8>::max_value,
+ // // not to non-existent std::u8::max_value
+ // }
+ //
+ // Such behavior is required for backward compatibility.
+ // The same fallback is used when `a` resolves to nothing.
+ PathResult::Module(ModuleOrUniformRoot::Module(_)) | PathResult::Failed { .. }
+ if (ns == TypeNS || path.len() > 1)
+ && PrimTy::from_name(path[0].ident.name).is_some() =>
+ {
+ let prim = PrimTy::from_name(path[0].ident.name).unwrap();
+ PartialRes::with_unresolved_segments(Res::PrimTy(prim), path.len() - 1)
+ }
+ PathResult::Module(ModuleOrUniformRoot::Module(module)) => {
+ PartialRes::new(module.res().unwrap())
+ }
+ PathResult::Failed { is_error_from_last_segment: false, span, label, suggestion } => {
+ return Err(respan(span, ResolutionError::FailedToResolve { label, suggestion }));
+ }
+ PathResult::Module(..) | PathResult::Failed { .. } => return Ok(None),
+ PathResult::Indeterminate => bug!("indeterminate path result in resolve_qpath"),
+ };
+
+ if path.len() > 1
+ && result.base_res() != Res::Err
+ && path[0].ident.name != kw::PathRoot
+ && path[0].ident.name != kw::DollarCrate
+ {
+ let unqualified_result = {
+ match self.resolve_path(&[*path.last().unwrap()], Some(ns), None) {
+ PathResult::NonModule(path_res) => path_res.base_res(),
+ PathResult::Module(ModuleOrUniformRoot::Module(module)) => {
+ module.res().unwrap()
+ }
+ _ => return Ok(Some(result)),
+ }
+ };
+ if result.base_res() == unqualified_result {
+ let lint = lint::builtin::UNUSED_QUALIFICATIONS;
+ self.r.lint_buffer.buffer_lint(
+ lint,
+ finalize.node_id,
+ finalize.path_span,
+ "unnecessary qualification",
+ )
+ }
+ }
+
+ Ok(Some(result))
+ }
+
+ fn with_resolved_label(&mut self, label: Option<Label>, id: NodeId, f: impl FnOnce(&mut Self)) {
+ if let Some(label) = label {
+ if label.ident.as_str().as_bytes()[1] != b'_' {
+ self.diagnostic_metadata.unused_labels.insert(id, label.ident.span);
+ }
+
+ if let Ok((_, orig_span)) = self.resolve_label(label.ident) {
+ diagnostics::signal_label_shadowing(self.r.session, orig_span, label.ident)
+ }
+
+ self.with_label_rib(NormalRibKind, |this| {
+ let ident = label.ident.normalize_to_macro_rules();
+ this.label_ribs.last_mut().unwrap().bindings.insert(ident, id);
+ f(this);
+ });
+ } else {
+ f(self);
+ }
+ }
+
+ fn resolve_labeled_block(&mut self, label: Option<Label>, id: NodeId, block: &'ast Block) {
+ self.with_resolved_label(label, id, |this| this.visit_block(block));
+ }
+
+ fn resolve_block(&mut self, block: &'ast Block) {
+ debug!("(resolving block) entering block");
+ // Move down in the graph, if there's an anonymous module rooted here.
+ let orig_module = self.parent_scope.module;
+ let anonymous_module = self.r.block_map.get(&block.id).cloned(); // clones a reference
+
+ let mut num_macro_definition_ribs = 0;
+ if let Some(anonymous_module) = anonymous_module {
+ debug!("(resolving block) found anonymous module, moving down");
+ self.ribs[ValueNS].push(Rib::new(ModuleRibKind(anonymous_module)));
+ self.ribs[TypeNS].push(Rib::new(ModuleRibKind(anonymous_module)));
+ self.parent_scope.module = anonymous_module;
+ } else {
+ self.ribs[ValueNS].push(Rib::new(NormalRibKind));
+ }
+
+ let prev = self.diagnostic_metadata.current_block_could_be_bare_struct_literal.take();
+ if let (true, [Stmt { kind: StmtKind::Expr(expr), .. }]) =
+ (block.could_be_bare_literal, &block.stmts[..])
+ && let ExprKind::Type(..) = expr.kind
+ {
+ self.diagnostic_metadata.current_block_could_be_bare_struct_literal =
+ Some(block.span);
+ }
+ // Descend into the block.
+ for stmt in &block.stmts {
+ if let StmtKind::Item(ref item) = stmt.kind
+ && let ItemKind::MacroDef(..) = item.kind {
+ num_macro_definition_ribs += 1;
+ let res = self.r.local_def_id(item.id).to_def_id();
+ self.ribs[ValueNS].push(Rib::new(MacroDefinition(res)));
+ self.label_ribs.push(Rib::new(MacroDefinition(res)));
+ }
+
+ self.visit_stmt(stmt);
+ }
+ self.diagnostic_metadata.current_block_could_be_bare_struct_literal = prev;
+
+ // Move back up.
+ self.parent_scope.module = orig_module;
+ for _ in 0..num_macro_definition_ribs {
+ self.ribs[ValueNS].pop();
+ self.label_ribs.pop();
+ }
+ self.ribs[ValueNS].pop();
+ if anonymous_module.is_some() {
+ self.ribs[TypeNS].pop();
+ }
+ debug!("(resolving block) leaving block");
+ }
+
+ fn resolve_anon_const(&mut self, constant: &'ast AnonConst, is_repeat: IsRepeatExpr) {
+ debug!("resolve_anon_const {:?} is_repeat: {:?}", constant, is_repeat);
+ self.with_constant_rib(
+ is_repeat,
+ if constant.value.is_potential_trivial_const_param() {
+ HasGenericParams::Yes
+ } else {
+ HasGenericParams::No
+ },
+ None,
+ |this| visit::walk_anon_const(this, constant),
+ );
+ }
+
+ fn resolve_inline_const(&mut self, constant: &'ast AnonConst) {
+ debug!("resolve_anon_const {constant:?}");
+ self.with_constant_rib(IsRepeatExpr::No, HasGenericParams::Yes, None, |this| {
+ visit::walk_anon_const(this, constant);
+ });
+ }
+
+ fn resolve_expr(&mut self, expr: &'ast Expr, parent: Option<&'ast Expr>) {
+ // First, record candidate traits for this expression if it could
+ // result in the invocation of a method call.
+
+ self.record_candidate_traits_for_expr_if_necessary(expr);
+
+ // Next, resolve the node.
+ match expr.kind {
+ ExprKind::Path(ref qself, ref path) => {
+ self.smart_resolve_path(expr.id, qself.as_ref(), path, PathSource::Expr(parent));
+ visit::walk_expr(self, expr);
+ }
+
+ ExprKind::Struct(ref se) => {
+ self.smart_resolve_path(expr.id, se.qself.as_ref(), &se.path, PathSource::Struct);
+ visit::walk_expr(self, expr);
+ }
+
+ ExprKind::Break(Some(label), _) | ExprKind::Continue(Some(label)) => {
+ match self.resolve_label(label.ident) {
+ Ok((node_id, _)) => {
+ // Since this res is a label, it is never read.
+ self.r.label_res_map.insert(expr.id, node_id);
+ self.diagnostic_metadata.unused_labels.remove(&node_id);
+ }
+ Err(error) => {
+ self.report_error(label.ident.span, error);
+ }
+ }
+
+ // visit `break` argument if any
+ visit::walk_expr(self, expr);
+ }
+
+ ExprKind::Break(None, Some(ref e)) => {
+ // We use this instead of `visit::walk_expr` to keep the parent expr around for
+ // better diagnostics.
+ self.resolve_expr(e, Some(&expr));
+ }
+
+ ExprKind::Let(ref pat, ref scrutinee, _) => {
+ self.visit_expr(scrutinee);
+ self.resolve_pattern_top(pat, PatternSource::Let);
+ }
+
+ ExprKind::If(ref cond, ref then, ref opt_else) => {
+ self.with_rib(ValueNS, NormalRibKind, |this| {
+ let old = this.diagnostic_metadata.in_if_condition.replace(cond);
+ this.visit_expr(cond);
+ this.diagnostic_metadata.in_if_condition = old;
+ this.visit_block(then);
+ });
+ if let Some(expr) = opt_else {
+ self.visit_expr(expr);
+ }
+ }
+
+ ExprKind::Loop(ref block, label) => self.resolve_labeled_block(label, expr.id, &block),
+
+ ExprKind::While(ref cond, ref block, label) => {
+ self.with_resolved_label(label, expr.id, |this| {
+ this.with_rib(ValueNS, NormalRibKind, |this| {
+ let old = this.diagnostic_metadata.in_if_condition.replace(cond);
+ this.visit_expr(cond);
+ this.diagnostic_metadata.in_if_condition = old;
+ this.visit_block(block);
+ })
+ });
+ }
+
+ ExprKind::ForLoop(ref pat, ref iter_expr, ref block, label) => {
+ self.visit_expr(iter_expr);
+ self.with_rib(ValueNS, NormalRibKind, |this| {
+ this.resolve_pattern_top(pat, PatternSource::For);
+ this.resolve_labeled_block(label, expr.id, block);
+ });
+ }
+
+ ExprKind::Block(ref block, label) => self.resolve_labeled_block(label, block.id, block),
+
+ // Equivalent to `visit::walk_expr` + passing some context to children.
+ ExprKind::Field(ref subexpression, _) => {
+ self.resolve_expr(subexpression, Some(expr));
+ }
+ ExprKind::MethodCall(ref segment, ref arguments, _) => {
+ let mut arguments = arguments.iter();
+ self.resolve_expr(arguments.next().unwrap(), Some(expr));
+ for argument in arguments {
+ self.resolve_expr(argument, None);
+ }
+ self.visit_path_segment(expr.span, segment);
+ }
+
+ ExprKind::Call(ref callee, ref arguments) => {
+ self.resolve_expr(callee, Some(expr));
+ let const_args = self.r.legacy_const_generic_args(callee).unwrap_or_default();
+ for (idx, argument) in arguments.iter().enumerate() {
+ // Constant arguments need to be treated as AnonConst since
+ // that is how they will be later lowered to HIR.
+ if const_args.contains(&idx) {
+ self.with_constant_rib(
+ IsRepeatExpr::No,
+ if argument.is_potential_trivial_const_param() {
+ HasGenericParams::Yes
+ } else {
+ HasGenericParams::No
+ },
+ None,
+ |this| {
+ this.resolve_expr(argument, None);
+ },
+ );
+ } else {
+ self.resolve_expr(argument, None);
+ }
+ }
+ }
+ ExprKind::Type(ref type_expr, ref ty) => {
+ // `ParseSess::type_ascription_path_suggestions` keeps spans of colon tokens in
+ // type ascription. Here we are trying to retrieve the span of the colon token as
+ // well, but only if it's written without spaces `expr:Ty` and therefore confusable
+ // with `expr::Ty`, only in this case it will match the span from
+ // `type_ascription_path_suggestions`.
+ self.diagnostic_metadata
+ .current_type_ascription
+ .push(type_expr.span.between(ty.span));
+ visit::walk_expr(self, expr);
+ self.diagnostic_metadata.current_type_ascription.pop();
+ }
+ // `async |x| ...` gets desugared to `|x| future_from_generator(|| ...)`, so we need to
+ // resolve the arguments within the proper scopes so that usages of them inside the
+ // closure are detected as upvars rather than normal closure arg usages.
+ ExprKind::Closure(_, _, Async::Yes { .. }, _, ref fn_decl, ref body, _span) => {
+ self.with_rib(ValueNS, NormalRibKind, |this| {
+ this.with_label_rib(ClosureOrAsyncRibKind, |this| {
+ // Resolve arguments:
+ this.resolve_params(&fn_decl.inputs);
+ // No need to resolve return type --
+ // the outer closure return type is `FnRetTy::Default`.
+
+ // Now resolve the inner closure
+ {
+ // No need to resolve arguments: the inner closure has none.
+ // Resolve the return type:
+ visit::walk_fn_ret_ty(this, &fn_decl.output);
+ // Resolve the body
+ this.visit_expr(body);
+ }
+ })
+ });
+ }
+ // For closures, ClosureOrAsyncRibKind is added in visit_fn
+ ExprKind::Closure(ClosureBinder::For { ref generic_params, span }, ..) => {
+ self.with_generic_param_rib(
+ &generic_params,
+ NormalRibKind,
+ LifetimeRibKind::Generics {
+ binder: expr.id,
+ kind: LifetimeBinderKind::Closure,
+ span,
+ },
+ |this| visit::walk_expr(this, expr),
+ );
+ }
+ ExprKind::Closure(..) => visit::walk_expr(self, expr),
+ ExprKind::Async(..) => {
+ self.with_label_rib(ClosureOrAsyncRibKind, |this| visit::walk_expr(this, expr));
+ }
+ ExprKind::Repeat(ref elem, ref ct) => {
+ self.visit_expr(elem);
+ self.with_lifetime_rib(LifetimeRibKind::AnonConst, |this| {
+ this.with_lifetime_rib(LifetimeRibKind::Elided(LifetimeRes::Static), |this| {
+ this.resolve_anon_const(ct, IsRepeatExpr::Yes)
+ })
+ });
+ }
+ ExprKind::ConstBlock(ref ct) => {
+ self.resolve_inline_const(ct);
+ }
+ ExprKind::Index(ref elem, ref idx) => {
+ self.resolve_expr(elem, Some(expr));
+ self.visit_expr(idx);
+ }
+ _ => {
+ visit::walk_expr(self, expr);
+ }
+ }
+ }
+
+ fn record_candidate_traits_for_expr_if_necessary(&mut self, expr: &'ast Expr) {
+ match expr.kind {
+ ExprKind::Field(_, ident) => {
+ // FIXME(#6890): Even though you can't treat a method like a
+ // field, we need to add any trait methods we find that match
+ // the field name so that we can do some nice error reporting
+ // later on in typeck.
+ let traits = self.traits_in_scope(ident, ValueNS);
+ self.r.trait_map.insert(expr.id, traits);
+ }
+ ExprKind::MethodCall(ref segment, ..) => {
+ debug!("(recording candidate traits for expr) recording traits for {}", expr.id);
+ let traits = self.traits_in_scope(segment.ident, ValueNS);
+ self.r.trait_map.insert(expr.id, traits);
+ }
+ _ => {
+ // Nothing to do.
+ }
+ }
+ }
+
+ fn traits_in_scope(&mut self, ident: Ident, ns: Namespace) -> Vec<TraitCandidate> {
+ self.r.traits_in_scope(
+ self.current_trait_ref.as_ref().map(|(module, _)| *module),
+ &self.parent_scope,
+ ident.span.ctxt(),
+ Some((ident.name, ns)),
+ )
+ }
+}
+
+struct LifetimeCountVisitor<'a, 'b> {
+ r: &'b mut Resolver<'a>,
+}
+
+/// Walks the whole crate in DFS order, visiting each item, counting the declared number of
+/// lifetime generic parameters.
+impl<'ast> Visitor<'ast> for LifetimeCountVisitor<'_, '_> {
+ fn visit_item(&mut self, item: &'ast Item) {
+ match &item.kind {
+ ItemKind::TyAlias(box TyAlias { ref generics, .. })
+ | ItemKind::Fn(box Fn { ref generics, .. })
+ | ItemKind::Enum(_, ref generics)
+ | ItemKind::Struct(_, ref generics)
+ | ItemKind::Union(_, ref generics)
+ | ItemKind::Impl(box Impl { ref generics, .. })
+ | ItemKind::Trait(box Trait { ref generics, .. })
+ | ItemKind::TraitAlias(ref generics, _) => {
+ let def_id = self.r.local_def_id(item.id);
+ let count = generics
+ .params
+ .iter()
+ .filter(|param| matches!(param.kind, ast::GenericParamKind::Lifetime { .. }))
+ .count();
+ self.r.item_generics_num_lifetimes.insert(def_id, count);
+ }
+
+ ItemKind::Mod(..)
+ | ItemKind::ForeignMod(..)
+ | ItemKind::Static(..)
+ | ItemKind::Const(..)
+ | ItemKind::Use(..)
+ | ItemKind::ExternCrate(..)
+ | ItemKind::MacroDef(..)
+ | ItemKind::GlobalAsm(..)
+ | ItemKind::MacCall(..) => {}
+ }
+ visit::walk_item(self, item)
+ }
+}
+
+impl<'a> Resolver<'a> {
+ pub(crate) fn late_resolve_crate(&mut self, krate: &Crate) {
+ visit::walk_crate(&mut LifetimeCountVisitor { r: self }, krate);
+ let mut late_resolution_visitor = LateResolutionVisitor::new(self);
+ visit::walk_crate(&mut late_resolution_visitor, krate);
+ for (id, span) in late_resolution_visitor.diagnostic_metadata.unused_labels.iter() {
+ self.lint_buffer.buffer_lint(lint::builtin::UNUSED_LABELS, *id, *span, "unused label");
+ }
+ }
+}
diff --git a/compiler/rustc_resolve/src/late/diagnostics.rs b/compiler/rustc_resolve/src/late/diagnostics.rs
new file mode 100644
index 000000000..2b1f2b88e
--- /dev/null
+++ b/compiler/rustc_resolve/src/late/diagnostics.rs
@@ -0,0 +1,2369 @@
+use crate::diagnostics::{ImportSuggestion, LabelSuggestion, TypoSuggestion};
+use crate::late::{AliasPossibility, LateResolutionVisitor, RibKind};
+use crate::late::{LifetimeBinderKind, LifetimeRes, LifetimeRibKind, LifetimeUseSet};
+use crate::path_names_to_string;
+use crate::{Module, ModuleKind, ModuleOrUniformRoot};
+use crate::{PathResult, PathSource, Segment};
+
+use rustc_ast::visit::{FnCtxt, FnKind, LifetimeCtxt};
+use rustc_ast::{
+ self as ast, AssocItemKind, Expr, ExprKind, GenericParam, GenericParamKind, Item, ItemKind,
+ NodeId, Path, Ty, TyKind, DUMMY_NODE_ID,
+};
+use rustc_ast_pretty::pprust::path_segment_to_string;
+use rustc_data_structures::fx::FxHashSet;
+use rustc_errors::{
+ pluralize, struct_span_err, Applicability, Diagnostic, DiagnosticBuilder, ErrorGuaranteed,
+ MultiSpan,
+};
+use rustc_hir as hir;
+use rustc_hir::def::Namespace::{self, *};
+use rustc_hir::def::{self, CtorKind, CtorOf, DefKind};
+use rustc_hir::def_id::{DefId, CRATE_DEF_ID, LOCAL_CRATE};
+use rustc_hir::PrimTy;
+use rustc_session::lint;
+use rustc_session::parse::feature_err;
+use rustc_session::Session;
+use rustc_span::edition::Edition;
+use rustc_span::hygiene::MacroKind;
+use rustc_span::lev_distance::find_best_match_for_name;
+use rustc_span::symbol::{kw, sym, Ident, Symbol};
+use rustc_span::{BytePos, Span};
+
+use std::iter;
+use std::ops::Deref;
+
+use tracing::debug;
+
+type Res = def::Res<ast::NodeId>;
+
+/// A field or associated item from self type suggested in case of resolution failure.
+enum AssocSuggestion {
+ Field,
+ MethodWithSelf,
+ AssocFn,
+ AssocType,
+ AssocConst,
+}
+
+impl AssocSuggestion {
+ fn action(&self) -> &'static str {
+ match self {
+ AssocSuggestion::Field => "use the available field",
+ AssocSuggestion::MethodWithSelf => "call the method with the fully-qualified path",
+ AssocSuggestion::AssocFn => "call the associated function",
+ AssocSuggestion::AssocConst => "use the associated `const`",
+ AssocSuggestion::AssocType => "use the associated type",
+ }
+ }
+}
+
+fn is_self_type(path: &[Segment], namespace: Namespace) -> bool {
+ namespace == TypeNS && path.len() == 1 && path[0].ident.name == kw::SelfUpper
+}
+
+fn is_self_value(path: &[Segment], namespace: Namespace) -> bool {
+ namespace == ValueNS && path.len() == 1 && path[0].ident.name == kw::SelfLower
+}
+
+/// Gets the stringified path for an enum from an `ImportSuggestion` for an enum variant.
+fn import_candidate_to_enum_paths(suggestion: &ImportSuggestion) -> (String, String) {
+ let variant_path = &suggestion.path;
+ let variant_path_string = path_names_to_string(variant_path);
+
+ let path_len = suggestion.path.segments.len();
+ let enum_path = ast::Path {
+ span: suggestion.path.span,
+ segments: suggestion.path.segments[0..path_len - 1].to_vec(),
+ tokens: None,
+ };
+ let enum_path_string = path_names_to_string(&enum_path);
+
+ (variant_path_string, enum_path_string)
+}
+
+/// Description of an elided lifetime.
+#[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Debug)]
+pub(super) struct MissingLifetime {
+ /// Used to overwrite the resolution with the suggestion, to avoid cascasing errors.
+ pub id: NodeId,
+ /// Where to suggest adding the lifetime.
+ pub span: Span,
+ /// How the lifetime was introduced, to have the correct space and comma.
+ pub kind: MissingLifetimeKind,
+ /// Number of elided lifetimes, used for elision in path.
+ pub count: usize,
+}
+
+#[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Debug)]
+pub(super) enum MissingLifetimeKind {
+ /// An explicit `'_`.
+ Underscore,
+ /// An elided lifetime `&' ty`.
+ Ampersand,
+ /// An elided lifetime in brackets with written brackets.
+ Comma,
+ /// An elided lifetime with elided brackets.
+ Brackets,
+}
+
+/// Description of the lifetimes appearing in a function parameter.
+/// This is used to provide a literal explanation to the elision failure.
+#[derive(Clone, Debug)]
+pub(super) struct ElisionFnParameter {
+ /// The index of the argument in the original definition.
+ pub index: usize,
+ /// The name of the argument if it's a simple ident.
+ pub ident: Option<Ident>,
+ /// The number of lifetimes in the parameter.
+ pub lifetime_count: usize,
+ /// The span of the parameter.
+ pub span: Span,
+}
+
+/// Description of lifetimes that appear as candidates for elision.
+/// This is used to suggest introducing an explicit lifetime.
+#[derive(Debug)]
+pub(super) enum LifetimeElisionCandidate {
+ /// This is not a real lifetime.
+ Ignore,
+ /// There is a named lifetime, we won't suggest anything.
+ Named,
+ Missing(MissingLifetime),
+}
+
+impl<'a: 'ast, 'ast> LateResolutionVisitor<'a, '_, 'ast> {
+ fn def_span(&self, def_id: DefId) -> Option<Span> {
+ match def_id.krate {
+ LOCAL_CRATE => self.r.opt_span(def_id),
+ _ => Some(self.r.cstore().get_span_untracked(def_id, self.r.session)),
+ }
+ }
+
+ /// Handles error reporting for `smart_resolve_path_fragment` function.
+ /// Creates base error and amends it with one short label and possibly some longer helps/notes.
+ pub(crate) fn smart_resolve_report_errors(
+ &mut self,
+ path: &[Segment],
+ span: Span,
+ source: PathSource<'_>,
+ res: Option<Res>,
+ ) -> (DiagnosticBuilder<'a, ErrorGuaranteed>, Vec<ImportSuggestion>) {
+ let ident_span = path.last().map_or(span, |ident| ident.ident.span);
+ let ns = source.namespace();
+ let is_expected = &|res| source.is_expected(res);
+ let is_enum_variant = &|res| matches!(res, Res::Def(DefKind::Variant, _));
+
+ debug!(?res, ?source);
+
+ // Make the base error.
+ struct BaseError<'a> {
+ msg: String,
+ fallback_label: String,
+ span: Span,
+ could_be_expr: bool,
+ suggestion: Option<(Span, &'a str, String)>,
+ }
+ let mut expected = source.descr_expected();
+ let path_str = Segment::names_to_string(path);
+ let item_str = path.last().unwrap().ident;
+ let base_error = if let Some(res) = res {
+ BaseError {
+ msg: format!("expected {}, found {} `{}`", expected, res.descr(), path_str),
+ fallback_label: format!("not a {expected}"),
+ span,
+ could_be_expr: match res {
+ Res::Def(DefKind::Fn, _) => {
+ // Verify whether this is a fn call or an Fn used as a type.
+ self.r
+ .session
+ .source_map()
+ .span_to_snippet(span)
+ .map(|snippet| snippet.ends_with(')'))
+ .unwrap_or(false)
+ }
+ Res::Def(
+ DefKind::Ctor(..) | DefKind::AssocFn | DefKind::Const | DefKind::AssocConst,
+ _,
+ )
+ | Res::SelfCtor(_)
+ | Res::PrimTy(_)
+ | Res::Local(_) => true,
+ _ => false,
+ },
+ suggestion: None,
+ }
+ } else {
+ let item_span = path.last().unwrap().ident.span;
+ let (mod_prefix, mod_str, suggestion) = if path.len() == 1 {
+ debug!(?self.diagnostic_metadata.current_impl_items);
+ debug!(?self.diagnostic_metadata.current_function);
+ let suggestion = if let Some(items) = self.diagnostic_metadata.current_impl_items
+ && let Some((fn_kind, _)) = self.diagnostic_metadata.current_function
+ && self.current_trait_ref.is_none()
+ && let Some(FnCtxt::Assoc(_)) = fn_kind.ctxt()
+ && let Some(item) = items.iter().find(|i| {
+ if let AssocItemKind::Fn(fn_) = &i.kind
+ && !fn_.sig.decl.has_self()
+ && i.ident.name == item_str.name
+ {
+ debug!(?item_str.name);
+ debug!(?fn_.sig.decl.inputs);
+ return true
+ }
+ false
+ })
+ {
+ Some((
+ item_span,
+ "consider using the associated function",
+ format!("Self::{}", item.ident)
+ ))
+ } else {
+ None
+ };
+ (String::new(), "this scope".to_string(), suggestion)
+ } else if path.len() == 2 && path[0].ident.name == kw::PathRoot {
+ if self.r.session.edition() > Edition::Edition2015 {
+ // In edition 2018 onwards, the `::foo` syntax may only pull from the extern prelude
+ // which overrides all other expectations of item type
+ expected = "crate";
+ (String::new(), "the list of imported crates".to_string(), None)
+ } else {
+ (String::new(), "the crate root".to_string(), None)
+ }
+ } else if path.len() == 2 && path[0].ident.name == kw::Crate {
+ (String::new(), "the crate root".to_string(), None)
+ } else {
+ let mod_path = &path[..path.len() - 1];
+ let mod_prefix = match self.resolve_path(mod_path, Some(TypeNS), None) {
+ PathResult::Module(ModuleOrUniformRoot::Module(module)) => module.res(),
+ _ => None,
+ }
+ .map_or_else(String::new, |res| format!("{} ", res.descr()));
+ (mod_prefix, format!("`{}`", Segment::names_to_string(mod_path)), None)
+ };
+ BaseError {
+ msg: format!("cannot find {expected} `{item_str}` in {mod_prefix}{mod_str}"),
+ fallback_label: if path_str == "async" && expected.starts_with("struct") {
+ "`async` blocks are only allowed in Rust 2018 or later".to_string()
+ } else {
+ format!("not found in {mod_str}")
+ },
+ span: item_span,
+ could_be_expr: false,
+ suggestion,
+ }
+ };
+
+ let code = source.error_code(res.is_some());
+ let mut err =
+ self.r.session.struct_span_err_with_code(base_error.span, &base_error.msg, code);
+
+ self.suggest_swapping_misplaced_self_ty_and_trait(&mut err, source, res, base_error.span);
+
+ if let Some(sugg) = base_error.suggestion {
+ err.span_suggestion_verbose(sugg.0, sugg.1, sugg.2, Applicability::MaybeIncorrect);
+ }
+
+ if let Some(span) = self.diagnostic_metadata.current_block_could_be_bare_struct_literal {
+ err.multipart_suggestion(
+ "you might have meant to write a `struct` literal",
+ vec![
+ (span.shrink_to_lo(), "{ SomeStruct ".to_string()),
+ (span.shrink_to_hi(), "}".to_string()),
+ ],
+ Applicability::HasPlaceholders,
+ );
+ }
+ match (source, self.diagnostic_metadata.in_if_condition) {
+ (
+ PathSource::Expr(_),
+ Some(Expr { span: expr_span, kind: ExprKind::Assign(lhs, _, _), .. }),
+ ) => {
+ // Icky heuristic so we don't suggest:
+ // `if (i + 2) = 2` => `if let (i + 2) = 2` (approximately pattern)
+ // `if 2 = i` => `if let 2 = i` (lhs needs to contain error span)
+ if lhs.is_approximately_pattern() && lhs.span.contains(span) {
+ err.span_suggestion_verbose(
+ expr_span.shrink_to_lo(),
+ "you might have meant to use pattern matching",
+ "let ",
+ Applicability::MaybeIncorrect,
+ );
+ }
+ }
+ _ => {}
+ }
+
+ let is_assoc_fn = self.self_type_is_available();
+ // Emit help message for fake-self from other languages (e.g., `this` in Javascript).
+ if ["this", "my"].contains(&item_str.as_str()) && is_assoc_fn {
+ err.span_suggestion_short(
+ span,
+ "you might have meant to use `self` here instead",
+ "self",
+ Applicability::MaybeIncorrect,
+ );
+ if !self.self_value_is_available(path[0].ident.span) {
+ if let Some((FnKind::Fn(_, _, sig, ..), fn_span)) =
+ &self.diagnostic_metadata.current_function
+ {
+ let (span, sugg) = if let Some(param) = sig.decl.inputs.get(0) {
+ (param.span.shrink_to_lo(), "&self, ")
+ } else {
+ (
+ self.r
+ .session
+ .source_map()
+ .span_through_char(*fn_span, '(')
+ .shrink_to_hi(),
+ "&self",
+ )
+ };
+ err.span_suggestion_verbose(
+ span,
+ "if you meant to use `self`, you are also missing a `self` receiver \
+ argument",
+ sugg,
+ Applicability::MaybeIncorrect,
+ );
+ }
+ }
+ }
+
+ self.detect_assoct_type_constraint_meant_as_path(base_error.span, &mut err);
+
+ // Emit special messages for unresolved `Self` and `self`.
+ if is_self_type(path, ns) {
+ err.code(rustc_errors::error_code!(E0411));
+ err.span_label(
+ span,
+ "`Self` is only available in impls, traits, and type definitions".to_string(),
+ );
+ if let Some(item_kind) = self.diagnostic_metadata.current_item {
+ err.span_label(
+ item_kind.ident.span,
+ format!(
+ "`Self` not allowed in {} {}",
+ item_kind.kind.article(),
+ item_kind.kind.descr()
+ ),
+ );
+ }
+ return (err, Vec::new());
+ }
+ if is_self_value(path, ns) {
+ debug!("smart_resolve_path_fragment: E0424, source={:?}", source);
+
+ err.code(rustc_errors::error_code!(E0424));
+ err.span_label(span, match source {
+ PathSource::Pat => "`self` value is a keyword and may not be bound to variables or shadowed",
+ _ => "`self` value is a keyword only available in methods with a `self` parameter",
+ });
+ if let Some((fn_kind, span)) = &self.diagnostic_metadata.current_function {
+ // The current function has a `self' parameter, but we were unable to resolve
+ // a reference to `self`. This can only happen if the `self` identifier we
+ // are resolving came from a different hygiene context.
+ if fn_kind.decl().inputs.get(0).map_or(false, |p| p.is_self()) {
+ err.span_label(*span, "this function has a `self` parameter, but a macro invocation can only access identifiers it receives from parameters");
+ } else {
+ let doesnt = if is_assoc_fn {
+ let (span, sugg) = fn_kind
+ .decl()
+ .inputs
+ .get(0)
+ .map(|p| (p.span.shrink_to_lo(), "&self, "))
+ .unwrap_or_else(|| {
+ // Try to look for the "(" after the function name, if possible.
+ // This avoids placing the suggestion into the visibility specifier.
+ let span = fn_kind
+ .ident()
+ .map_or(*span, |ident| span.with_lo(ident.span.hi()));
+ (
+ self.r
+ .session
+ .source_map()
+ .span_through_char(span, '(')
+ .shrink_to_hi(),
+ "&self",
+ )
+ });
+ err.span_suggestion_verbose(
+ span,
+ "add a `self` receiver parameter to make the associated `fn` a method",
+ sugg,
+ Applicability::MaybeIncorrect,
+ );
+ "doesn't"
+ } else {
+ "can't"
+ };
+ if let Some(ident) = fn_kind.ident() {
+ err.span_label(
+ ident.span,
+ &format!("this function {} have a `self` parameter", doesnt),
+ );
+ }
+ }
+ } else if let Some(item_kind) = self.diagnostic_metadata.current_item {
+ err.span_label(
+ item_kind.ident.span,
+ format!(
+ "`self` not allowed in {} {}",
+ item_kind.kind.article(),
+ item_kind.kind.descr()
+ ),
+ );
+ }
+ return (err, Vec::new());
+ }
+
+ // Try to lookup name in more relaxed fashion for better error reporting.
+ let ident = path.last().unwrap().ident;
+ let mut candidates = self
+ .r
+ .lookup_import_candidates(ident, ns, &self.parent_scope, is_expected)
+ .into_iter()
+ .filter(|ImportSuggestion { did, .. }| {
+ match (did, res.and_then(|res| res.opt_def_id())) {
+ (Some(suggestion_did), Some(actual_did)) => *suggestion_did != actual_did,
+ _ => true,
+ }
+ })
+ .collect::<Vec<_>>();
+ let crate_def_id = CRATE_DEF_ID.to_def_id();
+ // Try to filter out intrinsics candidates, as long as we have
+ // some other candidates to suggest.
+ let intrinsic_candidates: Vec<_> = candidates
+ .drain_filter(|sugg| {
+ let path = path_names_to_string(&sugg.path);
+ path.starts_with("core::intrinsics::") || path.starts_with("std::intrinsics::")
+ })
+ .collect();
+ if candidates.is_empty() {
+ // Put them back if we have no more candidates to suggest...
+ candidates.extend(intrinsic_candidates);
+ }
+ if candidates.is_empty() && is_expected(Res::Def(DefKind::Enum, crate_def_id)) {
+ let mut enum_candidates: Vec<_> = self
+ .r
+ .lookup_import_candidates(ident, ns, &self.parent_scope, is_enum_variant)
+ .into_iter()
+ .map(|suggestion| import_candidate_to_enum_paths(&suggestion))
+ .filter(|(_, enum_ty_path)| !enum_ty_path.starts_with("std::prelude::"))
+ .collect();
+ if !enum_candidates.is_empty() {
+ if let (PathSource::Type, Some(span)) =
+ (source, self.diagnostic_metadata.current_type_ascription.last())
+ {
+ if self
+ .r
+ .session
+ .parse_sess
+ .type_ascription_path_suggestions
+ .borrow()
+ .contains(span)
+ {
+ // Already reported this issue on the lhs of the type ascription.
+ err.delay_as_bug();
+ return (err, candidates);
+ }
+ }
+
+ enum_candidates.sort();
+
+ // Contextualize for E0412 "cannot find type", but don't belabor the point
+ // (that it's a variant) for E0573 "expected type, found variant".
+ let preamble = if res.is_none() {
+ let others = match enum_candidates.len() {
+ 1 => String::new(),
+ 2 => " and 1 other".to_owned(),
+ n => format!(" and {} others", n),
+ };
+ format!("there is an enum variant `{}`{}; ", enum_candidates[0].0, others)
+ } else {
+ String::new()
+ };
+ let msg = format!("{}try using the variant's enum", preamble);
+
+ err.span_suggestions(
+ span,
+ &msg,
+ enum_candidates.into_iter().map(|(_variant_path, enum_ty_path)| enum_ty_path),
+ Applicability::MachineApplicable,
+ );
+ }
+ }
+ // Try Levenshtein algorithm.
+ let typo_sugg = self.lookup_typo_candidate(path, ns, is_expected);
+ if path.len() == 1 && self.self_type_is_available() {
+ if let Some(candidate) = self.lookup_assoc_candidate(ident, ns, is_expected) {
+ let self_is_available = self.self_value_is_available(path[0].ident.span);
+ match candidate {
+ AssocSuggestion::Field => {
+ if self_is_available {
+ err.span_suggestion(
+ span,
+ "you might have meant to use the available field",
+ format!("self.{path_str}"),
+ Applicability::MachineApplicable,
+ );
+ } else {
+ err.span_label(span, "a field by this name exists in `Self`");
+ }
+ }
+ AssocSuggestion::MethodWithSelf if self_is_available => {
+ err.span_suggestion(
+ span,
+ "you might have meant to call the method",
+ format!("self.{path_str}"),
+ Applicability::MachineApplicable,
+ );
+ }
+ AssocSuggestion::MethodWithSelf
+ | AssocSuggestion::AssocFn
+ | AssocSuggestion::AssocConst
+ | AssocSuggestion::AssocType => {
+ err.span_suggestion(
+ span,
+ &format!("you might have meant to {}", candidate.action()),
+ format!("Self::{path_str}"),
+ Applicability::MachineApplicable,
+ );
+ }
+ }
+ self.r.add_typo_suggestion(&mut err, typo_sugg, ident_span);
+ return (err, candidates);
+ }
+
+ // If the first argument in call is `self` suggest calling a method.
+ if let Some((call_span, args_span)) = self.call_has_self_arg(source) {
+ let mut args_snippet = String::new();
+ if let Some(args_span) = args_span {
+ if let Ok(snippet) = self.r.session.source_map().span_to_snippet(args_span) {
+ args_snippet = snippet;
+ }
+ }
+
+ err.span_suggestion(
+ call_span,
+ &format!("try calling `{ident}` as a method"),
+ format!("self.{path_str}({args_snippet})"),
+ Applicability::MachineApplicable,
+ );
+ return (err, candidates);
+ }
+ }
+
+ // Try context-dependent help if relaxed lookup didn't work.
+ if let Some(res) = res {
+ if self.smart_resolve_context_dependent_help(
+ &mut err,
+ span,
+ source,
+ res,
+ &path_str,
+ &base_error.fallback_label,
+ ) {
+ // We do this to avoid losing a secondary span when we override the main error span.
+ self.r.add_typo_suggestion(&mut err, typo_sugg, ident_span);
+ return (err, candidates);
+ }
+ }
+
+ let is_macro =
+ base_error.span.from_expansion() && base_error.span.desugaring_kind().is_none();
+ if !self.type_ascription_suggestion(&mut err, base_error.span) {
+ let mut fallback = false;
+ if let (
+ PathSource::Trait(AliasPossibility::Maybe),
+ Some(Res::Def(DefKind::Struct | DefKind::Enum | DefKind::Union, _)),
+ false,
+ ) = (source, res, is_macro)
+ {
+ if let Some(bounds @ [_, .., _]) = self.diagnostic_metadata.current_trait_object {
+ fallback = true;
+ let spans: Vec<Span> = bounds
+ .iter()
+ .map(|bound| bound.span())
+ .filter(|&sp| sp != base_error.span)
+ .collect();
+
+ let start_span = bounds.iter().map(|bound| bound.span()).next().unwrap();
+ // `end_span` is the end of the poly trait ref (Foo + 'baz + Bar><)
+ let end_span = bounds.iter().map(|bound| bound.span()).last().unwrap();
+ // `last_bound_span` is the last bound of the poly trait ref (Foo + >'baz< + Bar)
+ let last_bound_span = spans.last().cloned().unwrap();
+ let mut multi_span: MultiSpan = spans.clone().into();
+ for sp in spans {
+ let msg = if sp == last_bound_span {
+ format!(
+ "...because of {these} bound{s}",
+ these = pluralize!("this", bounds.len() - 1),
+ s = pluralize!(bounds.len() - 1),
+ )
+ } else {
+ String::new()
+ };
+ multi_span.push_span_label(sp, msg);
+ }
+ multi_span
+ .push_span_label(base_error.span, "expected this type to be a trait...");
+ err.span_help(
+ multi_span,
+ "`+` is used to constrain a \"trait object\" type with lifetimes or \
+ auto-traits; structs and enums can't be bound in that way",
+ );
+ if bounds.iter().all(|bound| match bound {
+ ast::GenericBound::Outlives(_) => true,
+ ast::GenericBound::Trait(tr, _) => tr.span == base_error.span,
+ }) {
+ let mut sugg = vec![];
+ if base_error.span != start_span {
+ sugg.push((start_span.until(base_error.span), String::new()));
+ }
+ if base_error.span != end_span {
+ sugg.push((base_error.span.shrink_to_hi().to(end_span), String::new()));
+ }
+
+ err.multipart_suggestion(
+ "if you meant to use a type and not a trait here, remove the bounds",
+ sugg,
+ Applicability::MaybeIncorrect,
+ );
+ }
+ }
+ }
+
+ fallback |= self.restrict_assoc_type_in_where_clause(span, &mut err);
+
+ if !self.r.add_typo_suggestion(&mut err, typo_sugg, ident_span) {
+ fallback = true;
+ match self.diagnostic_metadata.current_let_binding {
+ Some((pat_sp, Some(ty_sp), None))
+ if ty_sp.contains(base_error.span) && base_error.could_be_expr =>
+ {
+ err.span_suggestion_short(
+ pat_sp.between(ty_sp),
+ "use `=` if you meant to assign",
+ " = ",
+ Applicability::MaybeIncorrect,
+ );
+ }
+ _ => {}
+ }
+
+ // If the trait has a single item (which wasn't matched by Levenshtein), suggest it
+ let suggestion = self.get_single_associated_item(&path, &source, is_expected);
+ self.r.add_typo_suggestion(&mut err, suggestion, ident_span);
+ }
+ if fallback {
+ // Fallback label.
+ err.span_label(base_error.span, base_error.fallback_label);
+ }
+ }
+ if let Some(err_code) = &err.code {
+ if err_code == &rustc_errors::error_code!(E0425) {
+ for label_rib in &self.label_ribs {
+ for (label_ident, node_id) in &label_rib.bindings {
+ if format!("'{}", ident) == label_ident.to_string() {
+ err.span_label(label_ident.span, "a label with a similar name exists");
+ if let PathSource::Expr(Some(Expr {
+ kind: ExprKind::Break(None, Some(_)),
+ ..
+ })) = source
+ {
+ err.span_suggestion(
+ span,
+ "use the similarly named label",
+ label_ident.name,
+ Applicability::MaybeIncorrect,
+ );
+ // Do not lint against unused label when we suggest them.
+ self.diagnostic_metadata.unused_labels.remove(node_id);
+ }
+ }
+ }
+ }
+ } else if err_code == &rustc_errors::error_code!(E0412) {
+ if let Some(correct) = Self::likely_rust_type(path) {
+ err.span_suggestion(
+ span,
+ "perhaps you intended to use this type",
+ correct,
+ Applicability::MaybeIncorrect,
+ );
+ }
+ }
+ }
+
+ (err, candidates)
+ }
+
+ fn detect_assoct_type_constraint_meant_as_path(&self, base_span: Span, err: &mut Diagnostic) {
+ let Some(ty) = self.diagnostic_metadata.current_type_path else { return; };
+ let TyKind::Path(_, path) = &ty.kind else { return; };
+ for segment in &path.segments {
+ let Some(params) = &segment.args else { continue; };
+ let ast::GenericArgs::AngleBracketed(ref params) = params.deref() else { continue; };
+ for param in &params.args {
+ let ast::AngleBracketedArg::Constraint(constraint) = param else { continue; };
+ let ast::AssocConstraintKind::Bound { bounds } = &constraint.kind else {
+ continue;
+ };
+ for bound in bounds {
+ let ast::GenericBound::Trait(trait_ref, ast::TraitBoundModifier::None)
+ = bound else
+ {
+ continue;
+ };
+ if base_span == trait_ref.span {
+ err.span_suggestion_verbose(
+ constraint.ident.span.between(trait_ref.span),
+ "you might have meant to write a path instead of an associated type bound",
+ "::",
+ Applicability::MachineApplicable,
+ );
+ }
+ }
+ }
+ }
+ }
+
+ fn suggest_swapping_misplaced_self_ty_and_trait(
+ &mut self,
+ err: &mut Diagnostic,
+ source: PathSource<'_>,
+ res: Option<Res>,
+ span: Span,
+ ) {
+ if let Some((trait_ref, self_ty)) =
+ self.diagnostic_metadata.currently_processing_impl_trait.clone()
+ && let TyKind::Path(_, self_ty_path) = &self_ty.kind
+ && let PathResult::Module(ModuleOrUniformRoot::Module(module)) =
+ self.resolve_path(&Segment::from_path(self_ty_path), Some(TypeNS), None)
+ && let ModuleKind::Def(DefKind::Trait, ..) = module.kind
+ && trait_ref.path.span == span
+ && let PathSource::Trait(_) = source
+ && let Some(Res::Def(DefKind::Struct | DefKind::Enum | DefKind::Union, _)) = res
+ && let Ok(self_ty_str) =
+ self.r.session.source_map().span_to_snippet(self_ty.span)
+ && let Ok(trait_ref_str) =
+ self.r.session.source_map().span_to_snippet(trait_ref.path.span)
+ {
+ err.multipart_suggestion(
+ "`impl` items mention the trait being implemented first and the type it is being implemented for second",
+ vec![(trait_ref.path.span, self_ty_str), (self_ty.span, trait_ref_str)],
+ Applicability::MaybeIncorrect,
+ );
+ }
+ }
+
+ fn get_single_associated_item(
+ &mut self,
+ path: &[Segment],
+ source: &PathSource<'_>,
+ filter_fn: &impl Fn(Res) -> bool,
+ ) -> Option<TypoSuggestion> {
+ if let crate::PathSource::TraitItem(_) = source {
+ let mod_path = &path[..path.len() - 1];
+ if let PathResult::Module(ModuleOrUniformRoot::Module(module)) =
+ self.resolve_path(mod_path, None, None)
+ {
+ let resolutions = self.r.resolutions(module).borrow();
+ let targets: Vec<_> =
+ resolutions
+ .iter()
+ .filter_map(|(key, resolution)| {
+ resolution.borrow().binding.map(|binding| binding.res()).and_then(
+ |res| if filter_fn(res) { Some((key, res)) } else { None },
+ )
+ })
+ .collect();
+ if targets.len() == 1 {
+ let target = targets[0];
+ return Some(TypoSuggestion::single_item_from_res(
+ target.0.ident.name,
+ target.1,
+ ));
+ }
+ }
+ }
+ None
+ }
+
+ /// Given `where <T as Bar>::Baz: String`, suggest `where T: Bar<Baz = String>`.
+ fn restrict_assoc_type_in_where_clause(&mut self, span: Span, err: &mut Diagnostic) -> bool {
+ // Detect that we are actually in a `where` predicate.
+ let (bounded_ty, bounds, where_span) =
+ if let Some(ast::WherePredicate::BoundPredicate(ast::WhereBoundPredicate {
+ bounded_ty,
+ bound_generic_params,
+ bounds,
+ span,
+ })) = self.diagnostic_metadata.current_where_predicate
+ {
+ if !bound_generic_params.is_empty() {
+ return false;
+ }
+ (bounded_ty, bounds, span)
+ } else {
+ return false;
+ };
+
+ // Confirm that the target is an associated type.
+ let (ty, position, path) = if let ast::TyKind::Path(
+ Some(ast::QSelf { ty, position, .. }),
+ path,
+ ) = &bounded_ty.kind
+ {
+ // use this to verify that ident is a type param.
+ let Some(partial_res) = self.r.partial_res_map.get(&bounded_ty.id) else {
+ return false;
+ };
+ if !(matches!(
+ partial_res.base_res(),
+ hir::def::Res::Def(hir::def::DefKind::AssocTy, _)
+ ) && partial_res.unresolved_segments() == 0)
+ {
+ return false;
+ }
+ (ty, position, path)
+ } else {
+ return false;
+ };
+
+ let peeled_ty = ty.peel_refs();
+ if let ast::TyKind::Path(None, type_param_path) = &peeled_ty.kind {
+ // Confirm that the `SelfTy` is a type parameter.
+ let Some(partial_res) = self.r.partial_res_map.get(&peeled_ty.id) else {
+ return false;
+ };
+ if !(matches!(
+ partial_res.base_res(),
+ hir::def::Res::Def(hir::def::DefKind::TyParam, _)
+ ) && partial_res.unresolved_segments() == 0)
+ {
+ return false;
+ }
+ if let (
+ [ast::PathSegment { ident: constrain_ident, args: None, .. }],
+ [ast::GenericBound::Trait(poly_trait_ref, ast::TraitBoundModifier::None)],
+ ) = (&type_param_path.segments[..], &bounds[..])
+ {
+ if let [ast::PathSegment { ident, args: None, .. }] =
+ &poly_trait_ref.trait_ref.path.segments[..]
+ {
+ if ident.span == span {
+ err.span_suggestion_verbose(
+ *where_span,
+ &format!("constrain the associated type to `{}`", ident),
+ format!(
+ "{}: {}<{} = {}>",
+ self.r
+ .session
+ .source_map()
+ .span_to_snippet(ty.span) // Account for `<&'a T as Foo>::Bar`.
+ .unwrap_or_else(|_| constrain_ident.to_string()),
+ path.segments[..*position]
+ .iter()
+ .map(|segment| path_segment_to_string(segment))
+ .collect::<Vec<_>>()
+ .join("::"),
+ path.segments[*position..]
+ .iter()
+ .map(|segment| path_segment_to_string(segment))
+ .collect::<Vec<_>>()
+ .join("::"),
+ ident,
+ ),
+ Applicability::MaybeIncorrect,
+ );
+ }
+ return true;
+ }
+ }
+ }
+ false
+ }
+
+ /// Check if the source is call expression and the first argument is `self`. If true,
+ /// return the span of whole call and the span for all arguments expect the first one (`self`).
+ fn call_has_self_arg(&self, source: PathSource<'_>) -> Option<(Span, Option<Span>)> {
+ let mut has_self_arg = None;
+ if let PathSource::Expr(Some(parent)) = source {
+ match &parent.kind {
+ ExprKind::Call(_, args) if !args.is_empty() => {
+ let mut expr_kind = &args[0].kind;
+ loop {
+ match expr_kind {
+ ExprKind::Path(_, arg_name) if arg_name.segments.len() == 1 => {
+ if arg_name.segments[0].ident.name == kw::SelfLower {
+ let call_span = parent.span;
+ let tail_args_span = if args.len() > 1 {
+ Some(Span::new(
+ args[1].span.lo(),
+ args.last().unwrap().span.hi(),
+ call_span.ctxt(),
+ None,
+ ))
+ } else {
+ None
+ };
+ has_self_arg = Some((call_span, tail_args_span));
+ }
+ break;
+ }
+ ExprKind::AddrOf(_, _, expr) => expr_kind = &expr.kind,
+ _ => break,
+ }
+ }
+ }
+ _ => (),
+ }
+ };
+ has_self_arg
+ }
+
+ fn followed_by_brace(&self, span: Span) -> (bool, Option<Span>) {
+ // HACK(estebank): find a better way to figure out that this was a
+ // parser issue where a struct literal is being used on an expression
+ // where a brace being opened means a block is being started. Look
+ // ahead for the next text to see if `span` is followed by a `{`.
+ let sm = self.r.session.source_map();
+ let mut sp = span;
+ loop {
+ sp = sm.next_point(sp);
+ match sm.span_to_snippet(sp) {
+ Ok(ref snippet) => {
+ if snippet.chars().any(|c| !c.is_whitespace()) {
+ break;
+ }
+ }
+ _ => break,
+ }
+ }
+ let followed_by_brace = matches!(sm.span_to_snippet(sp), Ok(ref snippet) if snippet == "{");
+ // In case this could be a struct literal that needs to be surrounded
+ // by parentheses, find the appropriate span.
+ let mut i = 0;
+ let mut closing_brace = None;
+ loop {
+ sp = sm.next_point(sp);
+ match sm.span_to_snippet(sp) {
+ Ok(ref snippet) => {
+ if snippet == "}" {
+ closing_brace = Some(span.to(sp));
+ break;
+ }
+ }
+ _ => break,
+ }
+ i += 1;
+ // The bigger the span, the more likely we're incorrect --
+ // bound it to 100 chars long.
+ if i > 100 {
+ break;
+ }
+ }
+ (followed_by_brace, closing_brace)
+ }
+
+ /// Provides context-dependent help for errors reported by the `smart_resolve_path_fragment`
+ /// function.
+ /// Returns `true` if able to provide context-dependent help.
+ fn smart_resolve_context_dependent_help(
+ &mut self,
+ err: &mut Diagnostic,
+ span: Span,
+ source: PathSource<'_>,
+ res: Res,
+ path_str: &str,
+ fallback_label: &str,
+ ) -> bool {
+ let ns = source.namespace();
+ let is_expected = &|res| source.is_expected(res);
+
+ let path_sep = |err: &mut Diagnostic, expr: &Expr| match expr.kind {
+ ExprKind::Field(_, ident) => {
+ err.span_suggestion(
+ expr.span,
+ "use the path separator to refer to an item",
+ format!("{}::{}", path_str, ident),
+ Applicability::MaybeIncorrect,
+ );
+ true
+ }
+ ExprKind::MethodCall(ref segment, ..) => {
+ let span = expr.span.with_hi(segment.ident.span.hi());
+ err.span_suggestion(
+ span,
+ "use the path separator to refer to an item",
+ format!("{}::{}", path_str, segment.ident),
+ Applicability::MaybeIncorrect,
+ );
+ true
+ }
+ _ => false,
+ };
+
+ let find_span = |source: &PathSource<'_>, err: &mut Diagnostic| {
+ match source {
+ PathSource::Expr(Some(Expr { span, kind: ExprKind::Call(_, _), .. }))
+ | PathSource::TupleStruct(span, _) => {
+ // We want the main underline to cover the suggested code as well for
+ // cleaner output.
+ err.set_span(*span);
+ *span
+ }
+ _ => span,
+ }
+ };
+
+ let mut bad_struct_syntax_suggestion = |def_id: DefId| {
+ let (followed_by_brace, closing_brace) = self.followed_by_brace(span);
+
+ match source {
+ PathSource::Expr(Some(
+ parent @ Expr { kind: ExprKind::Field(..) | ExprKind::MethodCall(..), .. },
+ )) if path_sep(err, &parent) => {}
+ PathSource::Expr(
+ None
+ | Some(Expr {
+ kind:
+ ExprKind::Path(..)
+ | ExprKind::Binary(..)
+ | ExprKind::Unary(..)
+ | ExprKind::If(..)
+ | ExprKind::While(..)
+ | ExprKind::ForLoop(..)
+ | ExprKind::Match(..),
+ ..
+ }),
+ ) if followed_by_brace => {
+ if let Some(sp) = closing_brace {
+ err.span_label(span, fallback_label);
+ err.multipart_suggestion(
+ "surround the struct literal with parentheses",
+ vec![
+ (sp.shrink_to_lo(), "(".to_string()),
+ (sp.shrink_to_hi(), ")".to_string()),
+ ],
+ Applicability::MaybeIncorrect,
+ );
+ } else {
+ err.span_label(
+ span, // Note the parentheses surrounding the suggestion below
+ format!(
+ "you might want to surround a struct literal with parentheses: \
+ `({} {{ /* fields */ }})`?",
+ path_str
+ ),
+ );
+ }
+ }
+ PathSource::Expr(_) | PathSource::TupleStruct(..) | PathSource::Pat => {
+ let span = find_span(&source, err);
+ if let Some(span) = self.def_span(def_id) {
+ err.span_label(span, &format!("`{}` defined here", path_str));
+ }
+ let (tail, descr, applicability) = match source {
+ PathSource::Pat | PathSource::TupleStruct(..) => {
+ ("", "pattern", Applicability::MachineApplicable)
+ }
+ _ => (": val", "literal", Applicability::HasPlaceholders),
+ };
+ let (fields, applicability) = match self.r.field_names.get(&def_id) {
+ Some(fields) => (
+ fields
+ .iter()
+ .map(|f| format!("{}{}", f.node, tail))
+ .collect::<Vec<String>>()
+ .join(", "),
+ applicability,
+ ),
+ None => ("/* fields */".to_string(), Applicability::HasPlaceholders),
+ };
+ let pad = match self.r.field_names.get(&def_id) {
+ Some(fields) if fields.is_empty() => "",
+ _ => " ",
+ };
+ err.span_suggestion(
+ span,
+ &format!("use struct {} syntax instead", descr),
+ format!("{path_str} {{{pad}{fields}{pad}}}"),
+ applicability,
+ );
+ }
+ _ => {
+ err.span_label(span, fallback_label);
+ }
+ }
+ };
+
+ match (res, source) {
+ (
+ Res::Def(DefKind::Macro(MacroKind::Bang), _),
+ PathSource::Expr(Some(Expr {
+ kind: ExprKind::Index(..) | ExprKind::Call(..), ..
+ }))
+ | PathSource::Struct,
+ ) => {
+ err.span_label(span, fallback_label);
+ err.span_suggestion_verbose(
+ span.shrink_to_hi(),
+ "use `!` to invoke the macro",
+ "!",
+ Applicability::MaybeIncorrect,
+ );
+ if path_str == "try" && span.rust_2015() {
+ err.note("if you want the `try` keyword, you need Rust 2018 or later");
+ }
+ }
+ (Res::Def(DefKind::Macro(MacroKind::Bang), _), _) => {
+ err.span_label(span, fallback_label);
+ }
+ (Res::Def(DefKind::TyAlias, def_id), PathSource::Trait(_)) => {
+ err.span_label(span, "type aliases cannot be used as traits");
+ if self.r.session.is_nightly_build() {
+ let msg = "you might have meant to use `#![feature(trait_alias)]` instead of a \
+ `type` alias";
+ if let Some(span) = self.def_span(def_id) {
+ if let Ok(snip) = self.r.session.source_map().span_to_snippet(span) {
+ // The span contains a type alias so we should be able to
+ // replace `type` with `trait`.
+ let snip = snip.replacen("type", "trait", 1);
+ err.span_suggestion(span, msg, snip, Applicability::MaybeIncorrect);
+ } else {
+ err.span_help(span, msg);
+ }
+ } else {
+ err.help(msg);
+ }
+ }
+ }
+ (Res::Def(DefKind::Mod, _), PathSource::Expr(Some(parent))) => {
+ if !path_sep(err, &parent) {
+ return false;
+ }
+ }
+ (
+ Res::Def(DefKind::Enum, def_id),
+ PathSource::TupleStruct(..) | PathSource::Expr(..),
+ ) => {
+ if self
+ .diagnostic_metadata
+ .current_type_ascription
+ .last()
+ .map(|sp| {
+ self.r
+ .session
+ .parse_sess
+ .type_ascription_path_suggestions
+ .borrow()
+ .contains(&sp)
+ })
+ .unwrap_or(false)
+ {
+ err.downgrade_to_delayed_bug();
+ // We already suggested changing `:` into `::` during parsing.
+ return false;
+ }
+
+ self.suggest_using_enum_variant(err, source, def_id, span);
+ }
+ (Res::Def(DefKind::Struct, def_id), source) if ns == ValueNS => {
+ let (ctor_def, ctor_vis, fields) =
+ if let Some(struct_ctor) = self.r.struct_constructors.get(&def_id).cloned() {
+ if let PathSource::Expr(Some(parent)) = source {
+ if let ExprKind::Field(..) | ExprKind::MethodCall(..) = parent.kind {
+ bad_struct_syntax_suggestion(def_id);
+ return true;
+ }
+ }
+ struct_ctor
+ } else {
+ bad_struct_syntax_suggestion(def_id);
+ return true;
+ };
+
+ let is_accessible = self.r.is_accessible_from(ctor_vis, self.parent_scope.module);
+ if !is_expected(ctor_def) || is_accessible {
+ return true;
+ }
+
+ let field_spans = match source {
+ // e.g. `if let Enum::TupleVariant(field1, field2) = _`
+ PathSource::TupleStruct(_, pattern_spans) => {
+ err.set_primary_message(
+ "cannot match against a tuple struct which contains private fields",
+ );
+
+ // Use spans of the tuple struct pattern.
+ Some(Vec::from(pattern_spans))
+ }
+ // e.g. `let _ = Enum::TupleVariant(field1, field2);`
+ _ if source.is_call() => {
+ err.set_primary_message(
+ "cannot initialize a tuple struct which contains private fields",
+ );
+
+ // Use spans of the tuple struct definition.
+ self.r
+ .field_names
+ .get(&def_id)
+ .map(|fields| fields.iter().map(|f| f.span).collect::<Vec<_>>())
+ }
+ _ => None,
+ };
+
+ if let Some(spans) =
+ field_spans.filter(|spans| spans.len() > 0 && fields.len() == spans.len())
+ {
+ let non_visible_spans: Vec<Span> = iter::zip(&fields, &spans)
+ .filter(|(vis, _)| {
+ !self.r.is_accessible_from(**vis, self.parent_scope.module)
+ })
+ .map(|(_, span)| *span)
+ .collect();
+
+ if non_visible_spans.len() > 0 {
+ let mut m: MultiSpan = non_visible_spans.clone().into();
+ non_visible_spans
+ .into_iter()
+ .for_each(|s| m.push_span_label(s, "private field"));
+ err.span_note(m, "constructor is not visible here due to private fields");
+ }
+
+ return true;
+ }
+
+ err.span_label(span, "constructor is not visible here due to private fields");
+ }
+ (
+ Res::Def(
+ DefKind::Union | DefKind::Variant | DefKind::Ctor(_, CtorKind::Fictive),
+ def_id,
+ ),
+ _,
+ ) if ns == ValueNS => {
+ bad_struct_syntax_suggestion(def_id);
+ }
+ (Res::Def(DefKind::Ctor(_, CtorKind::Const), def_id), _) if ns == ValueNS => {
+ match source {
+ PathSource::Expr(_) | PathSource::TupleStruct(..) | PathSource::Pat => {
+ let span = find_span(&source, err);
+ if let Some(span) = self.def_span(def_id) {
+ err.span_label(span, &format!("`{}` defined here", path_str));
+ }
+ err.span_suggestion(
+ span,
+ "use this syntax instead",
+ path_str,
+ Applicability::MaybeIncorrect,
+ );
+ }
+ _ => return false,
+ }
+ }
+ (Res::Def(DefKind::Ctor(_, CtorKind::Fn), def_id), _) if ns == ValueNS => {
+ if let Some(span) = self.def_span(def_id) {
+ err.span_label(span, &format!("`{}` defined here", path_str));
+ }
+ let fields = self.r.field_names.get(&def_id).map_or_else(
+ || "/* fields */".to_string(),
+ |fields| vec!["_"; fields.len()].join(", "),
+ );
+ err.span_suggestion(
+ span,
+ "use the tuple variant pattern syntax instead",
+ format!("{}({})", path_str, fields),
+ Applicability::HasPlaceholders,
+ );
+ }
+ (Res::SelfTy { .. }, _) if ns == ValueNS => {
+ err.span_label(span, fallback_label);
+ err.note("can't use `Self` as a constructor, you must use the implemented struct");
+ }
+ (Res::Def(DefKind::TyAlias | DefKind::AssocTy, _), _) if ns == ValueNS => {
+ err.note("can't use a type alias as a constructor");
+ }
+ _ => return false,
+ }
+ true
+ }
+
+ /// Given the target `ident` and `kind`, search for the similarly named associated item
+ /// in `self.current_trait_ref`.
+ pub(crate) fn find_similarly_named_assoc_item(
+ &mut self,
+ ident: Symbol,
+ kind: &AssocItemKind,
+ ) -> Option<Symbol> {
+ let (module, _) = self.current_trait_ref.as_ref()?;
+ if ident == kw::Underscore {
+ // We do nothing for `_`.
+ return None;
+ }
+
+ let resolutions = self.r.resolutions(module);
+ let targets = resolutions
+ .borrow()
+ .iter()
+ .filter_map(|(key, res)| res.borrow().binding.map(|binding| (key, binding.res())))
+ .filter(|(_, res)| match (kind, res) {
+ (AssocItemKind::Const(..), Res::Def(DefKind::AssocConst, _)) => true,
+ (AssocItemKind::Fn(_), Res::Def(DefKind::AssocFn, _)) => true,
+ (AssocItemKind::TyAlias(..), Res::Def(DefKind::AssocTy, _)) => true,
+ _ => false,
+ })
+ .map(|(key, _)| key.ident.name)
+ .collect::<Vec<_>>();
+
+ find_best_match_for_name(&targets, ident, None)
+ }
+
+ fn lookup_assoc_candidate<FilterFn>(
+ &mut self,
+ ident: Ident,
+ ns: Namespace,
+ filter_fn: FilterFn,
+ ) -> Option<AssocSuggestion>
+ where
+ FilterFn: Fn(Res) -> bool,
+ {
+ fn extract_node_id(t: &Ty) -> Option<NodeId> {
+ match t.kind {
+ TyKind::Path(None, _) => Some(t.id),
+ TyKind::Rptr(_, ref mut_ty) => extract_node_id(&mut_ty.ty),
+ // This doesn't handle the remaining `Ty` variants as they are not
+ // that commonly the self_type, it might be interesting to provide
+ // support for those in future.
+ _ => None,
+ }
+ }
+
+ // Fields are generally expected in the same contexts as locals.
+ if filter_fn(Res::Local(ast::DUMMY_NODE_ID)) {
+ if let Some(node_id) =
+ self.diagnostic_metadata.current_self_type.as_ref().and_then(extract_node_id)
+ {
+ // Look for a field with the same name in the current self_type.
+ if let Some(resolution) = self.r.partial_res_map.get(&node_id) {
+ match resolution.base_res() {
+ Res::Def(DefKind::Struct | DefKind::Union, did)
+ if resolution.unresolved_segments() == 0 =>
+ {
+ if let Some(field_names) = self.r.field_names.get(&did) {
+ if field_names
+ .iter()
+ .any(|&field_name| ident.name == field_name.node)
+ {
+ return Some(AssocSuggestion::Field);
+ }
+ }
+ }
+ _ => {}
+ }
+ }
+ }
+ }
+
+ if let Some(items) = self.diagnostic_metadata.current_trait_assoc_items {
+ for assoc_item in items {
+ if assoc_item.ident == ident {
+ return Some(match &assoc_item.kind {
+ ast::AssocItemKind::Const(..) => AssocSuggestion::AssocConst,
+ ast::AssocItemKind::Fn(box ast::Fn { sig, .. }) if sig.decl.has_self() => {
+ AssocSuggestion::MethodWithSelf
+ }
+ ast::AssocItemKind::Fn(..) => AssocSuggestion::AssocFn,
+ ast::AssocItemKind::TyAlias(..) => AssocSuggestion::AssocType,
+ ast::AssocItemKind::MacCall(_) => continue,
+ });
+ }
+ }
+ }
+
+ // Look for associated items in the current trait.
+ if let Some((module, _)) = self.current_trait_ref {
+ if let Ok(binding) = self.r.maybe_resolve_ident_in_module(
+ ModuleOrUniformRoot::Module(module),
+ ident,
+ ns,
+ &self.parent_scope,
+ ) {
+ let res = binding.res();
+ if filter_fn(res) {
+ if self.r.has_self.contains(&res.def_id()) {
+ return Some(AssocSuggestion::MethodWithSelf);
+ } else {
+ match res {
+ Res::Def(DefKind::AssocFn, _) => return Some(AssocSuggestion::AssocFn),
+ Res::Def(DefKind::AssocConst, _) => {
+ return Some(AssocSuggestion::AssocConst);
+ }
+ Res::Def(DefKind::AssocTy, _) => {
+ return Some(AssocSuggestion::AssocType);
+ }
+ _ => {}
+ }
+ }
+ }
+ }
+ }
+
+ None
+ }
+
+ fn lookup_typo_candidate(
+ &mut self,
+ path: &[Segment],
+ ns: Namespace,
+ filter_fn: &impl Fn(Res) -> bool,
+ ) -> Option<TypoSuggestion> {
+ let mut names = Vec::new();
+ if path.len() == 1 {
+ // Search in lexical scope.
+ // Walk backwards up the ribs in scope and collect candidates.
+ for rib in self.ribs[ns].iter().rev() {
+ // Locals and type parameters
+ for (ident, &res) in &rib.bindings {
+ if filter_fn(res) {
+ names.push(TypoSuggestion::typo_from_res(ident.name, res));
+ }
+ }
+ // Items in scope
+ if let RibKind::ModuleRibKind(module) = rib.kind {
+ // Items from this module
+ self.r.add_module_candidates(module, &mut names, &filter_fn);
+
+ if let ModuleKind::Block = module.kind {
+ // We can see through blocks
+ } else {
+ // Items from the prelude
+ if !module.no_implicit_prelude {
+ let extern_prelude = self.r.extern_prelude.clone();
+ names.extend(extern_prelude.iter().flat_map(|(ident, _)| {
+ self.r.crate_loader.maybe_process_path_extern(ident.name).and_then(
+ |crate_id| {
+ let crate_mod =
+ Res::Def(DefKind::Mod, crate_id.as_def_id());
+
+ if filter_fn(crate_mod) {
+ Some(TypoSuggestion::typo_from_res(
+ ident.name, crate_mod,
+ ))
+ } else {
+ None
+ }
+ },
+ )
+ }));
+
+ if let Some(prelude) = self.r.prelude {
+ self.r.add_module_candidates(prelude, &mut names, &filter_fn);
+ }
+ }
+ break;
+ }
+ }
+ }
+ // Add primitive types to the mix
+ if filter_fn(Res::PrimTy(PrimTy::Bool)) {
+ names.extend(PrimTy::ALL.iter().map(|prim_ty| {
+ TypoSuggestion::typo_from_res(prim_ty.name(), Res::PrimTy(*prim_ty))
+ }))
+ }
+ } else {
+ // Search in module.
+ let mod_path = &path[..path.len() - 1];
+ if let PathResult::Module(ModuleOrUniformRoot::Module(module)) =
+ self.resolve_path(mod_path, Some(TypeNS), None)
+ {
+ self.r.add_module_candidates(module, &mut names, &filter_fn);
+ }
+ }
+
+ let name = path[path.len() - 1].ident.name;
+ // Make sure error reporting is deterministic.
+ names.sort_by(|a, b| a.candidate.as_str().partial_cmp(b.candidate.as_str()).unwrap());
+
+ match find_best_match_for_name(
+ &names.iter().map(|suggestion| suggestion.candidate).collect::<Vec<Symbol>>(),
+ name,
+ None,
+ ) {
+ Some(found) if found != name => {
+ names.into_iter().find(|suggestion| suggestion.candidate == found)
+ }
+ _ => None,
+ }
+ }
+
+ // Returns the name of the Rust type approximately corresponding to
+ // a type name in another programming language.
+ fn likely_rust_type(path: &[Segment]) -> Option<Symbol> {
+ let name = path[path.len() - 1].ident.as_str();
+ // Common Java types
+ Some(match name {
+ "byte" => sym::u8, // In Java, bytes are signed, but in practice one almost always wants unsigned bytes.
+ "short" => sym::i16,
+ "Bool" => sym::bool,
+ "Boolean" => sym::bool,
+ "boolean" => sym::bool,
+ "int" => sym::i32,
+ "long" => sym::i64,
+ "float" => sym::f32,
+ "double" => sym::f64,
+ _ => return None,
+ })
+ }
+
+ /// Only used in a specific case of type ascription suggestions
+ fn get_colon_suggestion_span(&self, start: Span) -> Span {
+ let sm = self.r.session.source_map();
+ start.to(sm.next_point(start))
+ }
+
+ fn type_ascription_suggestion(&self, err: &mut Diagnostic, base_span: Span) -> bool {
+ let sm = self.r.session.source_map();
+ let base_snippet = sm.span_to_snippet(base_span);
+ if let Some(&sp) = self.diagnostic_metadata.current_type_ascription.last() {
+ if let Ok(snippet) = sm.span_to_snippet(sp) {
+ let len = snippet.trim_end().len() as u32;
+ if snippet.trim() == ":" {
+ let colon_sp =
+ sp.with_lo(sp.lo() + BytePos(len - 1)).with_hi(sp.lo() + BytePos(len));
+ let mut show_label = true;
+ if sm.is_multiline(sp) {
+ err.span_suggestion_short(
+ colon_sp,
+ "maybe you meant to write `;` here",
+ ";",
+ Applicability::MaybeIncorrect,
+ );
+ } else {
+ let after_colon_sp =
+ self.get_colon_suggestion_span(colon_sp.shrink_to_hi());
+ if snippet.len() == 1 {
+ // `foo:bar`
+ err.span_suggestion(
+ colon_sp,
+ "maybe you meant to write a path separator here",
+ "::",
+ Applicability::MaybeIncorrect,
+ );
+ show_label = false;
+ if !self
+ .r
+ .session
+ .parse_sess
+ .type_ascription_path_suggestions
+ .borrow_mut()
+ .insert(colon_sp)
+ {
+ err.downgrade_to_delayed_bug();
+ }
+ }
+ if let Ok(base_snippet) = base_snippet {
+ let mut sp = after_colon_sp;
+ for _ in 0..100 {
+ // Try to find an assignment
+ sp = sm.next_point(sp);
+ let snippet = sm.span_to_snippet(sp.to(sm.next_point(sp)));
+ match snippet {
+ Ok(ref x) if x.as_str() == "=" => {
+ err.span_suggestion(
+ base_span,
+ "maybe you meant to write an assignment here",
+ format!("let {}", base_snippet),
+ Applicability::MaybeIncorrect,
+ );
+ show_label = false;
+ break;
+ }
+ Ok(ref x) if x.as_str() == "\n" => break,
+ Err(_) => break,
+ Ok(_) => {}
+ }
+ }
+ }
+ }
+ if show_label {
+ err.span_label(
+ base_span,
+ "expecting a type here because of type ascription",
+ );
+ }
+ return show_label;
+ }
+ }
+ }
+ false
+ }
+
+ fn find_module(&mut self, def_id: DefId) -> Option<(Module<'a>, ImportSuggestion)> {
+ let mut result = None;
+ let mut seen_modules = FxHashSet::default();
+ let mut worklist = vec![(self.r.graph_root, Vec::new())];
+
+ while let Some((in_module, path_segments)) = worklist.pop() {
+ // abort if the module is already found
+ if result.is_some() {
+ break;
+ }
+
+ in_module.for_each_child(self.r, |_, ident, _, name_binding| {
+ // abort if the module is already found or if name_binding is private external
+ if result.is_some() || !name_binding.vis.is_visible_locally() {
+ return;
+ }
+ if let Some(module) = name_binding.module() {
+ // form the path
+ let mut path_segments = path_segments.clone();
+ path_segments.push(ast::PathSegment::from_ident(ident));
+ let module_def_id = module.def_id();
+ if module_def_id == def_id {
+ let path =
+ Path { span: name_binding.span, segments: path_segments, tokens: None };
+ result = Some((
+ module,
+ ImportSuggestion {
+ did: Some(def_id),
+ descr: "module",
+ path,
+ accessible: true,
+ note: None,
+ },
+ ));
+ } else {
+ // add the module to the lookup
+ if seen_modules.insert(module_def_id) {
+ worklist.push((module, path_segments));
+ }
+ }
+ }
+ });
+ }
+
+ result
+ }
+
+ fn collect_enum_ctors(&mut self, def_id: DefId) -> Option<Vec<(Path, DefId, CtorKind)>> {
+ self.find_module(def_id).map(|(enum_module, enum_import_suggestion)| {
+ let mut variants = Vec::new();
+ enum_module.for_each_child(self.r, |_, ident, _, name_binding| {
+ if let Res::Def(DefKind::Ctor(CtorOf::Variant, kind), def_id) = name_binding.res() {
+ let mut segms = enum_import_suggestion.path.segments.clone();
+ segms.push(ast::PathSegment::from_ident(ident));
+ let path = Path { span: name_binding.span, segments: segms, tokens: None };
+ variants.push((path, def_id, kind));
+ }
+ });
+ variants
+ })
+ }
+
+ /// Adds a suggestion for using an enum's variant when an enum is used instead.
+ fn suggest_using_enum_variant(
+ &mut self,
+ err: &mut Diagnostic,
+ source: PathSource<'_>,
+ def_id: DefId,
+ span: Span,
+ ) {
+ let Some(variants) = self.collect_enum_ctors(def_id) else {
+ err.note("you might have meant to use one of the enum's variants");
+ return;
+ };
+
+ let suggest_only_tuple_variants =
+ matches!(source, PathSource::TupleStruct(..)) || source.is_call();
+ if suggest_only_tuple_variants {
+ // Suggest only tuple variants regardless of whether they have fields and do not
+ // suggest path with added parentheses.
+ let suggestable_variants = variants
+ .iter()
+ .filter(|(.., kind)| *kind == CtorKind::Fn)
+ .map(|(variant, ..)| path_names_to_string(variant))
+ .collect::<Vec<_>>();
+
+ let non_suggestable_variant_count = variants.len() - suggestable_variants.len();
+
+ let source_msg = if source.is_call() {
+ "to construct"
+ } else if matches!(source, PathSource::TupleStruct(..)) {
+ "to match against"
+ } else {
+ unreachable!()
+ };
+
+ if !suggestable_variants.is_empty() {
+ let msg = if non_suggestable_variant_count == 0 && suggestable_variants.len() == 1 {
+ format!("try {} the enum's variant", source_msg)
+ } else {
+ format!("try {} one of the enum's variants", source_msg)
+ };
+
+ err.span_suggestions(
+ span,
+ &msg,
+ suggestable_variants.into_iter(),
+ Applicability::MaybeIncorrect,
+ );
+ }
+
+ // If the enum has no tuple variants..
+ if non_suggestable_variant_count == variants.len() {
+ err.help(&format!("the enum has no tuple variants {}", source_msg));
+ }
+
+ // If there are also non-tuple variants..
+ if non_suggestable_variant_count == 1 {
+ err.help(&format!(
+ "you might have meant {} the enum's non-tuple variant",
+ source_msg
+ ));
+ } else if non_suggestable_variant_count >= 1 {
+ err.help(&format!(
+ "you might have meant {} one of the enum's non-tuple variants",
+ source_msg
+ ));
+ }
+ } else {
+ let needs_placeholder = |def_id: DefId, kind: CtorKind| {
+ let has_no_fields = self.r.field_names.get(&def_id).map_or(false, |f| f.is_empty());
+ match kind {
+ CtorKind::Const => false,
+ CtorKind::Fn | CtorKind::Fictive if has_no_fields => false,
+ _ => true,
+ }
+ };
+
+ let mut suggestable_variants = variants
+ .iter()
+ .filter(|(_, def_id, kind)| !needs_placeholder(*def_id, *kind))
+ .map(|(variant, _, kind)| (path_names_to_string(variant), kind))
+ .map(|(variant, kind)| match kind {
+ CtorKind::Const => variant,
+ CtorKind::Fn => format!("({}())", variant),
+ CtorKind::Fictive => format!("({} {{}})", variant),
+ })
+ .collect::<Vec<_>>();
+
+ if !suggestable_variants.is_empty() {
+ let msg = if suggestable_variants.len() == 1 {
+ "you might have meant to use the following enum variant"
+ } else {
+ "you might have meant to use one of the following enum variants"
+ };
+
+ err.span_suggestions(
+ span,
+ msg,
+ suggestable_variants.drain(..),
+ Applicability::MaybeIncorrect,
+ );
+ }
+
+ let suggestable_variants_with_placeholders = variants
+ .iter()
+ .filter(|(_, def_id, kind)| needs_placeholder(*def_id, *kind))
+ .map(|(variant, _, kind)| (path_names_to_string(variant), kind))
+ .filter_map(|(variant, kind)| match kind {
+ CtorKind::Fn => Some(format!("({}(/* fields */))", variant)),
+ CtorKind::Fictive => Some(format!("({} {{ /* fields */ }})", variant)),
+ _ => None,
+ })
+ .collect::<Vec<_>>();
+
+ if !suggestable_variants_with_placeholders.is_empty() {
+ let msg = match (
+ suggestable_variants.is_empty(),
+ suggestable_variants_with_placeholders.len(),
+ ) {
+ (true, 1) => "the following enum variant is available",
+ (true, _) => "the following enum variants are available",
+ (false, 1) => "alternatively, the following enum variant is available",
+ (false, _) => "alternatively, the following enum variants are also available",
+ };
+
+ err.span_suggestions(
+ span,
+ msg,
+ suggestable_variants_with_placeholders.into_iter(),
+ Applicability::HasPlaceholders,
+ );
+ }
+ };
+
+ if def_id.is_local() {
+ if let Some(span) = self.def_span(def_id) {
+ err.span_note(span, "the enum is defined here");
+ }
+ }
+ }
+
+ pub(crate) fn report_missing_type_error(
+ &self,
+ path: &[Segment],
+ ) -> Option<(Span, &'static str, String, Applicability)> {
+ let (ident, span) = match path {
+ [segment] if !segment.has_generic_args && segment.ident.name != kw::SelfUpper => {
+ (segment.ident.to_string(), segment.ident.span)
+ }
+ _ => return None,
+ };
+ let mut iter = ident.chars().map(|c| c.is_uppercase());
+ let single_uppercase_char =
+ matches!(iter.next(), Some(true)) && matches!(iter.next(), None);
+ if !self.diagnostic_metadata.currently_processing_generics && !single_uppercase_char {
+ return None;
+ }
+ match (self.diagnostic_metadata.current_item, single_uppercase_char, self.diagnostic_metadata.currently_processing_generics) {
+ (Some(Item { kind: ItemKind::Fn(..), ident, .. }), _, _) if ident.name == sym::main => {
+ // Ignore `fn main()` as we don't want to suggest `fn main<T>()`
+ }
+ (
+ Some(Item {
+ kind:
+ kind @ ItemKind::Fn(..)
+ | kind @ ItemKind::Enum(..)
+ | kind @ ItemKind::Struct(..)
+ | kind @ ItemKind::Union(..),
+ ..
+ }),
+ true, _
+ )
+ // Without the 2nd `true`, we'd suggest `impl <T>` for `impl T` when a type `T` isn't found
+ | (Some(Item { kind: kind @ ItemKind::Impl(..), .. }), true, true)
+ | (Some(Item { kind, .. }), false, _) => {
+ // Likely missing type parameter.
+ if let Some(generics) = kind.generics() {
+ if span.overlaps(generics.span) {
+ // Avoid the following:
+ // error[E0405]: cannot find trait `A` in this scope
+ // --> $DIR/typo-suggestion-named-underscore.rs:CC:LL
+ // |
+ // L | fn foo<T: A>(x: T) {} // Shouldn't suggest underscore
+ // | ^- help: you might be missing a type parameter: `, A`
+ // | |
+ // | not found in this scope
+ return None;
+ }
+ let msg = "you might be missing a type parameter";
+ let (span, sugg) = if let [.., param] = &generics.params[..] {
+ let span = if let [.., bound] = &param.bounds[..] {
+ bound.span()
+ } else if let GenericParam {
+ kind: GenericParamKind::Const { ty, kw_span: _, default }, ..
+ } = param {
+ default.as_ref().map(|def| def.value.span).unwrap_or(ty.span)
+ } else {
+ param.ident.span
+ };
+ (span, format!(", {}", ident))
+ } else {
+ (generics.span, format!("<{}>", ident))
+ };
+ // Do not suggest if this is coming from macro expansion.
+ if span.can_be_used_for_suggestions() {
+ return Some((
+ span.shrink_to_hi(),
+ msg,
+ sugg,
+ Applicability::MaybeIncorrect,
+ ));
+ }
+ }
+ }
+ _ => {}
+ }
+ None
+ }
+
+ /// Given the target `label`, search the `rib_index`th label rib for similarly named labels,
+ /// optionally returning the closest match and whether it is reachable.
+ pub(crate) fn suggestion_for_label_in_rib(
+ &self,
+ rib_index: usize,
+ label: Ident,
+ ) -> Option<LabelSuggestion> {
+ // Are ribs from this `rib_index` within scope?
+ let within_scope = self.is_label_valid_from_rib(rib_index);
+
+ let rib = &self.label_ribs[rib_index];
+ let names = rib
+ .bindings
+ .iter()
+ .filter(|(id, _)| id.span.eq_ctxt(label.span))
+ .map(|(id, _)| id.name)
+ .collect::<Vec<Symbol>>();
+
+ find_best_match_for_name(&names, label.name, None).map(|symbol| {
+ // Upon finding a similar name, get the ident that it was from - the span
+ // contained within helps make a useful diagnostic. In addition, determine
+ // whether this candidate is within scope.
+ let (ident, _) = rib.bindings.iter().find(|(ident, _)| ident.name == symbol).unwrap();
+ (*ident, within_scope)
+ })
+ }
+
+ pub(crate) fn maybe_report_lifetime_uses(
+ &mut self,
+ generics_span: Span,
+ params: &[ast::GenericParam],
+ ) {
+ for (param_index, param) in params.iter().enumerate() {
+ let GenericParamKind::Lifetime = param.kind else { continue };
+
+ let def_id = self.r.local_def_id(param.id);
+
+ let use_set = self.lifetime_uses.remove(&def_id);
+ debug!(
+ "Use set for {:?}({:?} at {:?}) is {:?}",
+ def_id, param.ident, param.ident.span, use_set
+ );
+
+ let deletion_span = || {
+ if params.len() == 1 {
+ // if sole lifetime, remove the entire `<>` brackets
+ generics_span
+ } else if param_index == 0 {
+ // if removing within `<>` brackets, we also want to
+ // delete a leading or trailing comma as appropriate
+ param.span().to(params[param_index + 1].span().shrink_to_lo())
+ } else {
+ // if removing within `<>` brackets, we also want to
+ // delete a leading or trailing comma as appropriate
+ params[param_index - 1].span().shrink_to_hi().to(param.span())
+ }
+ };
+ match use_set {
+ Some(LifetimeUseSet::Many) => {}
+ Some(LifetimeUseSet::One { use_span, use_ctxt }) => {
+ debug!(?param.ident, ?param.ident.span, ?use_span);
+
+ let elidable = matches!(use_ctxt, LifetimeCtxt::Rptr);
+
+ let deletion_span = deletion_span();
+ self.r.lint_buffer.buffer_lint_with_diagnostic(
+ lint::builtin::SINGLE_USE_LIFETIMES,
+ param.id,
+ param.ident.span,
+ &format!("lifetime parameter `{}` only used once", param.ident),
+ lint::BuiltinLintDiagnostics::SingleUseLifetime {
+ param_span: param.ident.span,
+ use_span: Some((use_span, elidable)),
+ deletion_span,
+ },
+ );
+ }
+ None => {
+ debug!(?param.ident, ?param.ident.span);
+
+ let deletion_span = deletion_span();
+ self.r.lint_buffer.buffer_lint_with_diagnostic(
+ lint::builtin::UNUSED_LIFETIMES,
+ param.id,
+ param.ident.span,
+ &format!("lifetime parameter `{}` never used", param.ident),
+ lint::BuiltinLintDiagnostics::SingleUseLifetime {
+ param_span: param.ident.span,
+ use_span: None,
+ deletion_span,
+ },
+ );
+ }
+ }
+ }
+ }
+
+ pub(crate) fn emit_undeclared_lifetime_error(
+ &self,
+ lifetime_ref: &ast::Lifetime,
+ outer_lifetime_ref: Option<Ident>,
+ ) {
+ debug_assert_ne!(lifetime_ref.ident.name, kw::UnderscoreLifetime);
+ let mut err = if let Some(outer) = outer_lifetime_ref {
+ let mut err = struct_span_err!(
+ self.r.session,
+ lifetime_ref.ident.span,
+ E0401,
+ "can't use generic parameters from outer item",
+ );
+ err.span_label(lifetime_ref.ident.span, "use of generic parameter from outer item");
+ err.span_label(outer.span, "lifetime parameter from outer item");
+ err
+ } else {
+ let mut err = struct_span_err!(
+ self.r.session,
+ lifetime_ref.ident.span,
+ E0261,
+ "use of undeclared lifetime name `{}`",
+ lifetime_ref.ident
+ );
+ err.span_label(lifetime_ref.ident.span, "undeclared lifetime");
+ err
+ };
+ self.suggest_introducing_lifetime(
+ &mut err,
+ Some(lifetime_ref.ident.name.as_str()),
+ |err, _, span, message, suggestion| {
+ err.span_suggestion(span, message, suggestion, Applicability::MaybeIncorrect);
+ true
+ },
+ );
+ err.emit();
+ }
+
+ fn suggest_introducing_lifetime(
+ &self,
+ err: &mut DiagnosticBuilder<'_, ErrorGuaranteed>,
+ name: Option<&str>,
+ suggest: impl Fn(&mut DiagnosticBuilder<'_, ErrorGuaranteed>, bool, Span, &str, String) -> bool,
+ ) {
+ let mut suggest_note = true;
+ for rib in self.lifetime_ribs.iter().rev() {
+ let mut should_continue = true;
+ match rib.kind {
+ LifetimeRibKind::Generics { binder: _, span, kind } => {
+ if !span.can_be_used_for_suggestions() && suggest_note && let Some(name) = name {
+ suggest_note = false; // Avoid displaying the same help multiple times.
+ err.span_label(
+ span,
+ &format!(
+ "lifetime `{}` is missing in item created through this procedural macro",
+ name,
+ ),
+ );
+ continue;
+ }
+
+ let higher_ranked = matches!(
+ kind,
+ LifetimeBinderKind::BareFnType
+ | LifetimeBinderKind::PolyTrait
+ | LifetimeBinderKind::WhereBound
+ );
+ let (span, sugg) = if span.is_empty() {
+ let sugg = format!(
+ "{}<{}>{}",
+ if higher_ranked { "for" } else { "" },
+ name.unwrap_or("'a"),
+ if higher_ranked { " " } else { "" },
+ );
+ (span, sugg)
+ } else {
+ let span =
+ self.r.session.source_map().span_through_char(span, '<').shrink_to_hi();
+ let sugg = format!("{}, ", name.unwrap_or("'a"));
+ (span, sugg)
+ };
+ if higher_ranked {
+ let message = format!(
+ "consider making the {} lifetime-generic with a new `{}` lifetime",
+ kind.descr(),
+ name.unwrap_or("'a"),
+ );
+ should_continue = suggest(err, true, span, &message, sugg);
+ err.note_once(
+ "for more information on higher-ranked polymorphism, visit \
+ https://doc.rust-lang.org/nomicon/hrtb.html",
+ );
+ } else if let Some(name) = name {
+ let message = format!("consider introducing lifetime `{}` here", name);
+ should_continue = suggest(err, false, span, &message, sugg);
+ } else {
+ let message = format!("consider introducing a named lifetime parameter");
+ should_continue = suggest(err, false, span, &message, sugg);
+ }
+ }
+ LifetimeRibKind::Item => break,
+ _ => {}
+ }
+ if !should_continue {
+ break;
+ }
+ }
+ }
+
+ pub(crate) fn emit_non_static_lt_in_const_generic_error(&self, lifetime_ref: &ast::Lifetime) {
+ struct_span_err!(
+ self.r.session,
+ lifetime_ref.ident.span,
+ E0771,
+ "use of non-static lifetime `{}` in const generic",
+ lifetime_ref.ident
+ )
+ .note(
+ "for more information, see issue #74052 \
+ <https://github.com/rust-lang/rust/issues/74052>",
+ )
+ .emit();
+ }
+
+ /// Non-static lifetimes are prohibited in anonymous constants under `min_const_generics`.
+ /// This function will emit an error if `generic_const_exprs` is not enabled, the body identified by
+ /// `body_id` is an anonymous constant and `lifetime_ref` is non-static.
+ pub(crate) fn maybe_emit_forbidden_non_static_lifetime_error(
+ &self,
+ lifetime_ref: &ast::Lifetime,
+ ) {
+ let feature_active = self.r.session.features_untracked().generic_const_exprs;
+ if !feature_active {
+ feature_err(
+ &self.r.session.parse_sess,
+ sym::generic_const_exprs,
+ lifetime_ref.ident.span,
+ "a non-static lifetime is not allowed in a `const`",
+ )
+ .emit();
+ }
+ }
+
+ pub(crate) fn report_missing_lifetime_specifiers(
+ &mut self,
+ lifetime_refs: Vec<MissingLifetime>,
+ function_param_lifetimes: Option<(Vec<MissingLifetime>, Vec<ElisionFnParameter>)>,
+ ) -> ErrorGuaranteed {
+ let num_lifetimes: usize = lifetime_refs.iter().map(|lt| lt.count).sum();
+ let spans: Vec<_> = lifetime_refs.iter().map(|lt| lt.span).collect();
+
+ let mut err = struct_span_err!(
+ self.r.session,
+ spans,
+ E0106,
+ "missing lifetime specifier{}",
+ pluralize!(num_lifetimes)
+ );
+ self.add_missing_lifetime_specifiers_label(
+ &mut err,
+ lifetime_refs,
+ function_param_lifetimes,
+ );
+ err.emit()
+ }
+
+ pub(crate) fn add_missing_lifetime_specifiers_label(
+ &mut self,
+ err: &mut DiagnosticBuilder<'_, ErrorGuaranteed>,
+ lifetime_refs: Vec<MissingLifetime>,
+ function_param_lifetimes: Option<(Vec<MissingLifetime>, Vec<ElisionFnParameter>)>,
+ ) {
+ for &lt in &lifetime_refs {
+ err.span_label(
+ lt.span,
+ format!(
+ "expected {} lifetime parameter{}",
+ if lt.count == 1 { "named".to_string() } else { lt.count.to_string() },
+ pluralize!(lt.count),
+ ),
+ );
+ }
+
+ let mut in_scope_lifetimes: Vec<_> = self
+ .lifetime_ribs
+ .iter()
+ .rev()
+ .take_while(|rib| !matches!(rib.kind, LifetimeRibKind::Item))
+ .flat_map(|rib| rib.bindings.iter())
+ .map(|(&ident, &res)| (ident, res))
+ .filter(|(ident, _)| ident.name != kw::UnderscoreLifetime)
+ .collect();
+ debug!(?in_scope_lifetimes);
+
+ debug!(?function_param_lifetimes);
+ if let Some((param_lifetimes, params)) = &function_param_lifetimes {
+ let elided_len = param_lifetimes.len();
+ let num_params = params.len();
+
+ let mut m = String::new();
+
+ for (i, info) in params.iter().enumerate() {
+ let ElisionFnParameter { ident, index, lifetime_count, span } = *info;
+ debug_assert_ne!(lifetime_count, 0);
+
+ err.span_label(span, "");
+
+ if i != 0 {
+ if i + 1 < num_params {
+ m.push_str(", ");
+ } else if num_params == 2 {
+ m.push_str(" or ");
+ } else {
+ m.push_str(", or ");
+ }
+ }
+
+ let help_name = if let Some(ident) = ident {
+ format!("`{}`", ident)
+ } else {
+ format!("argument {}", index + 1)
+ };
+
+ if lifetime_count == 1 {
+ m.push_str(&help_name[..])
+ } else {
+ m.push_str(&format!("one of {}'s {} lifetimes", help_name, lifetime_count)[..])
+ }
+ }
+
+ if num_params == 0 {
+ err.help(
+ "this function's return type contains a borrowed value, \
+ but there is no value for it to be borrowed from",
+ );
+ if in_scope_lifetimes.is_empty() {
+ in_scope_lifetimes = vec![(
+ Ident::with_dummy_span(kw::StaticLifetime),
+ (DUMMY_NODE_ID, LifetimeRes::Static),
+ )];
+ }
+ } else if elided_len == 0 {
+ err.help(
+ "this function's return type contains a borrowed value with \
+ an elided lifetime, but the lifetime cannot be derived from \
+ the arguments",
+ );
+ if in_scope_lifetimes.is_empty() {
+ in_scope_lifetimes = vec![(
+ Ident::with_dummy_span(kw::StaticLifetime),
+ (DUMMY_NODE_ID, LifetimeRes::Static),
+ )];
+ }
+ } else if num_params == 1 {
+ err.help(&format!(
+ "this function's return type contains a borrowed value, \
+ but the signature does not say which {} it is borrowed from",
+ m
+ ));
+ } else {
+ err.help(&format!(
+ "this function's return type contains a borrowed value, \
+ but the signature does not say whether it is borrowed from {}",
+ m
+ ));
+ }
+ }
+
+ let existing_name = match &in_scope_lifetimes[..] {
+ [] => Symbol::intern("'a"),
+ [(existing, _)] => existing.name,
+ _ => Symbol::intern("'lifetime"),
+ };
+
+ let mut spans_suggs: Vec<_> = Vec::new();
+ let build_sugg = |lt: MissingLifetime| match lt.kind {
+ MissingLifetimeKind::Underscore => {
+ debug_assert_eq!(lt.count, 1);
+ (lt.span, existing_name.to_string())
+ }
+ MissingLifetimeKind::Ampersand => {
+ debug_assert_eq!(lt.count, 1);
+ (lt.span.shrink_to_hi(), format!("{} ", existing_name))
+ }
+ MissingLifetimeKind::Comma => {
+ let sugg: String = std::iter::repeat([existing_name.as_str(), ", "])
+ .take(lt.count)
+ .flatten()
+ .collect();
+ (lt.span.shrink_to_hi(), sugg)
+ }
+ MissingLifetimeKind::Brackets => {
+ let sugg: String = std::iter::once("<")
+ .chain(
+ std::iter::repeat(existing_name.as_str()).take(lt.count).intersperse(", "),
+ )
+ .chain([">"])
+ .collect();
+ (lt.span.shrink_to_hi(), sugg)
+ }
+ };
+ for &lt in &lifetime_refs {
+ spans_suggs.push(build_sugg(lt));
+ }
+ debug!(?spans_suggs);
+ match in_scope_lifetimes.len() {
+ 0 => {
+ if let Some((param_lifetimes, _)) = function_param_lifetimes {
+ for lt in param_lifetimes {
+ spans_suggs.push(build_sugg(lt))
+ }
+ }
+ self.suggest_introducing_lifetime(
+ err,
+ None,
+ |err, higher_ranked, span, message, intro_sugg| {
+ err.multipart_suggestion_verbose(
+ message,
+ std::iter::once((span, intro_sugg))
+ .chain(spans_suggs.clone())
+ .collect(),
+ Applicability::MaybeIncorrect,
+ );
+ higher_ranked
+ },
+ );
+ }
+ 1 => {
+ err.multipart_suggestion_verbose(
+ &format!("consider using the `{}` lifetime", existing_name),
+ spans_suggs,
+ Applicability::MaybeIncorrect,
+ );
+
+ // Record as using the suggested resolution.
+ let (_, (_, res)) = in_scope_lifetimes[0];
+ for &lt in &lifetime_refs {
+ self.r.lifetimes_res_map.insert(lt.id, res);
+ }
+ }
+ _ => {
+ let lifetime_spans: Vec<_> =
+ in_scope_lifetimes.iter().map(|(ident, _)| ident.span).collect();
+ err.span_note(lifetime_spans, "these named lifetimes are available to use");
+
+ if spans_suggs.len() > 0 {
+ // This happens when we have `Foo<T>` where we point at the space before `T`,
+ // but this can be confusing so we give a suggestion with placeholders.
+ err.multipart_suggestion_verbose(
+ "consider using one of the available lifetimes here",
+ spans_suggs,
+ Applicability::HasPlaceholders,
+ );
+ }
+ }
+ }
+ }
+}
+
+/// Report lifetime/lifetime shadowing as an error.
+pub fn signal_lifetime_shadowing(sess: &Session, orig: Ident, shadower: Ident) {
+ let mut err = struct_span_err!(
+ sess,
+ shadower.span,
+ E0496,
+ "lifetime name `{}` shadows a lifetime name that is already in scope",
+ orig.name,
+ );
+ err.span_label(orig.span, "first declared here");
+ err.span_label(shadower.span, format!("lifetime `{}` already in scope", orig.name));
+ err.emit();
+}
+
+/// Shadowing involving a label is only a warning for historical reasons.
+//FIXME: make this a proper lint.
+pub fn signal_label_shadowing(sess: &Session, orig: Span, shadower: Ident) {
+ let name = shadower.name;
+ let shadower = shadower.span;
+ let mut err = sess.struct_span_warn(
+ shadower,
+ &format!("label name `{}` shadows a label name that is already in scope", name),
+ );
+ err.span_label(orig, "first declared here");
+ err.span_label(shadower, format!("label `{}` already in scope", name));
+ err.emit();
+}
diff --git a/compiler/rustc_resolve/src/late/lifetimes.rs b/compiler/rustc_resolve/src/late/lifetimes.rs
new file mode 100644
index 000000000..94460e33d
--- /dev/null
+++ b/compiler/rustc_resolve/src/late/lifetimes.rs
@@ -0,0 +1,2144 @@
+//! Resolution of early vs late bound lifetimes.
+//!
+//! Name resolution for lifetimes is performed on the AST and embedded into HIR. From this
+//! information, typechecking needs to transform the lifetime parameters into bound lifetimes.
+//! Lifetimes can be early-bound or late-bound. Construction of typechecking terms needs to visit
+//! the types in HIR to identify late-bound lifetimes and assign their Debruijn indices. This file
+//! is also responsible for assigning their semantics to implicit lifetimes in trait objects.
+
+use rustc_ast::walk_list;
+use rustc_data_structures::fx::{FxHashSet, FxIndexMap, FxIndexSet};
+use rustc_errors::struct_span_err;
+use rustc_hir as hir;
+use rustc_hir::def::{DefKind, Res};
+use rustc_hir::def_id::{DefIdMap, LocalDefId};
+use rustc_hir::intravisit::{self, Visitor};
+use rustc_hir::{GenericArg, GenericParam, GenericParamKind, HirIdMap, LifetimeName, Node};
+use rustc_middle::bug;
+use rustc_middle::hir::map::Map;
+use rustc_middle::hir::nested_filter;
+use rustc_middle::middle::resolve_lifetime::*;
+use rustc_middle::ty::{self, GenericParamDefKind, TyCtxt};
+use rustc_span::def_id::DefId;
+use rustc_span::symbol::{sym, Ident};
+use rustc_span::Span;
+use std::borrow::Cow;
+use std::fmt;
+use std::mem::take;
+
+trait RegionExt {
+ fn early(hir_map: Map<'_>, index: &mut u32, param: &GenericParam<'_>) -> (LocalDefId, Region);
+
+ fn late(index: u32, hir_map: Map<'_>, param: &GenericParam<'_>) -> (LocalDefId, Region);
+
+ fn id(&self) -> Option<DefId>;
+
+ fn shifted(self, amount: u32) -> Region;
+
+ fn shifted_out_to_binder(self, binder: ty::DebruijnIndex) -> Region;
+
+ fn subst<'a, L>(self, params: L, map: &NamedRegionMap) -> Option<Region>
+ where
+ L: Iterator<Item = &'a hir::Lifetime>;
+}
+
+impl RegionExt for Region {
+ fn early(hir_map: Map<'_>, index: &mut u32, param: &GenericParam<'_>) -> (LocalDefId, Region) {
+ let i = *index;
+ *index += 1;
+ let def_id = hir_map.local_def_id(param.hir_id);
+ debug!("Region::early: index={} def_id={:?}", i, def_id);
+ (def_id, Region::EarlyBound(i, def_id.to_def_id()))
+ }
+
+ fn late(idx: u32, hir_map: Map<'_>, param: &GenericParam<'_>) -> (LocalDefId, Region) {
+ let depth = ty::INNERMOST;
+ let def_id = hir_map.local_def_id(param.hir_id);
+ debug!(
+ "Region::late: idx={:?}, param={:?} depth={:?} def_id={:?}",
+ idx, param, depth, def_id,
+ );
+ (def_id, Region::LateBound(depth, idx, def_id.to_def_id()))
+ }
+
+ fn id(&self) -> Option<DefId> {
+ match *self {
+ Region::Static => None,
+
+ Region::EarlyBound(_, id) | Region::LateBound(_, _, id) | Region::Free(_, id) => {
+ Some(id)
+ }
+ }
+ }
+
+ fn shifted(self, amount: u32) -> Region {
+ match self {
+ Region::LateBound(debruijn, idx, id) => {
+ Region::LateBound(debruijn.shifted_in(amount), idx, id)
+ }
+ _ => self,
+ }
+ }
+
+ fn shifted_out_to_binder(self, binder: ty::DebruijnIndex) -> Region {
+ match self {
+ Region::LateBound(debruijn, index, id) => {
+ Region::LateBound(debruijn.shifted_out_to_binder(binder), index, id)
+ }
+ _ => self,
+ }
+ }
+
+ fn subst<'a, L>(self, mut params: L, map: &NamedRegionMap) -> Option<Region>
+ where
+ L: Iterator<Item = &'a hir::Lifetime>,
+ {
+ if let Region::EarlyBound(index, _) = self {
+ params.nth(index as usize).and_then(|lifetime| map.defs.get(&lifetime.hir_id).cloned())
+ } else {
+ Some(self)
+ }
+ }
+}
+
+/// Maps the id of each lifetime reference to the lifetime decl
+/// that it corresponds to.
+///
+/// FIXME. This struct gets converted to a `ResolveLifetimes` for
+/// actual use. It has the same data, but indexed by `LocalDefId`. This
+/// is silly.
+#[derive(Debug, Default)]
+struct NamedRegionMap {
+ // maps from every use of a named (not anonymous) lifetime to a
+ // `Region` describing how that region is bound
+ defs: HirIdMap<Region>,
+
+ // Maps relevant hir items to the bound vars on them. These include:
+ // - function defs
+ // - function pointers
+ // - closures
+ // - trait refs
+ // - bound types (like `T` in `for<'a> T<'a>: Foo`)
+ late_bound_vars: HirIdMap<Vec<ty::BoundVariableKind>>,
+}
+
+pub(crate) struct LifetimeContext<'a, 'tcx> {
+ pub(crate) tcx: TyCtxt<'tcx>,
+ map: &'a mut NamedRegionMap,
+ scope: ScopeRef<'a>,
+
+ /// Indicates that we only care about the definition of a trait. This should
+ /// be false if the `Item` we are resolving lifetimes for is not a trait or
+ /// we eventually need lifetimes resolve for trait items.
+ trait_definition_only: bool,
+
+ /// Cache for cross-crate per-definition object lifetime defaults.
+ xcrate_object_lifetime_defaults: DefIdMap<Vec<ObjectLifetimeDefault>>,
+}
+
+#[derive(Debug)]
+enum Scope<'a> {
+ /// Declares lifetimes, and each can be early-bound or late-bound.
+ /// The `DebruijnIndex` of late-bound lifetimes starts at `1` and
+ /// it should be shifted by the number of `Binder`s in between the
+ /// declaration `Binder` and the location it's referenced from.
+ Binder {
+ /// We use an IndexMap here because we want these lifetimes in order
+ /// for diagnostics.
+ lifetimes: FxIndexMap<LocalDefId, Region>,
+
+ /// if we extend this scope with another scope, what is the next index
+ /// we should use for an early-bound region?
+ next_early_index: u32,
+
+ /// Whether or not this binder would serve as the parent
+ /// binder for opaque types introduced within. For example:
+ ///
+ /// ```text
+ /// fn foo<'a>() -> impl for<'b> Trait<Item = impl Trait2<'a>>
+ /// ```
+ ///
+ /// Here, the opaque types we create for the `impl Trait`
+ /// and `impl Trait2` references will both have the `foo` item
+ /// as their parent. When we get to `impl Trait2`, we find
+ /// that it is nested within the `for<>` binder -- this flag
+ /// allows us to skip that when looking for the parent binder
+ /// of the resulting opaque type.
+ opaque_type_parent: bool,
+
+ scope_type: BinderScopeType,
+
+ /// The late bound vars for a given item are stored by `HirId` to be
+ /// queried later. However, if we enter an elision scope, we have to
+ /// later append the elided bound vars to the list and need to know what
+ /// to append to.
+ hir_id: hir::HirId,
+
+ s: ScopeRef<'a>,
+
+ /// If this binder comes from a where clause, specify how it was created.
+ /// This is used to diagnose inaccessible lifetimes in APIT:
+ /// ```ignore (illustrative)
+ /// fn foo(x: impl for<'a> Trait<'a, Assoc = impl Copy + 'a>) {}
+ /// ```
+ where_bound_origin: Option<hir::PredicateOrigin>,
+ },
+
+ /// Lifetimes introduced by a fn are scoped to the call-site for that fn,
+ /// if this is a fn body, otherwise the original definitions are used.
+ /// Unspecified lifetimes are inferred, unless an elision scope is nested,
+ /// e.g., `(&T, fn(&T) -> &T);` becomes `(&'_ T, for<'a> fn(&'a T) -> &'a T)`.
+ Body {
+ id: hir::BodyId,
+ s: ScopeRef<'a>,
+ },
+
+ /// A scope which either determines unspecified lifetimes or errors
+ /// on them (e.g., due to ambiguity).
+ Elision {
+ s: ScopeRef<'a>,
+ },
+
+ /// Use a specific lifetime (if `Some`) or leave it unset (to be
+ /// inferred in a function body or potentially error outside one),
+ /// for the default choice of lifetime in a trait object type.
+ ObjectLifetimeDefault {
+ lifetime: Option<Region>,
+ s: ScopeRef<'a>,
+ },
+
+ /// When we have nested trait refs, we concatenate late bound vars for inner
+ /// trait refs from outer ones. But we also need to include any HRTB
+ /// lifetimes encountered when identifying the trait that an associated type
+ /// is declared on.
+ Supertrait {
+ lifetimes: Vec<ty::BoundVariableKind>,
+ s: ScopeRef<'a>,
+ },
+
+ TraitRefBoundary {
+ s: ScopeRef<'a>,
+ },
+
+ Root,
+}
+
+#[derive(Copy, Clone, Debug)]
+enum BinderScopeType {
+ /// Any non-concatenating binder scopes.
+ Normal,
+ /// Within a syntactic trait ref, there may be multiple poly trait refs that
+ /// are nested (under the `associated_type_bounds` feature). The binders of
+ /// the inner poly trait refs are extended from the outer poly trait refs
+ /// and don't increase the late bound depth. If you had
+ /// `T: for<'a> Foo<Bar: for<'b> Baz<'a, 'b>>`, then the `for<'b>` scope
+ /// would be `Concatenating`. This also used in trait refs in where clauses
+ /// where we have two binders `for<> T: for<> Foo` (I've intentionally left
+ /// out any lifetimes because they aren't needed to show the two scopes).
+ /// The inner `for<>` has a scope of `Concatenating`.
+ Concatenating,
+}
+
+// A helper struct for debugging scopes without printing parent scopes
+struct TruncatedScopeDebug<'a>(&'a Scope<'a>);
+
+impl<'a> fmt::Debug for TruncatedScopeDebug<'a> {
+ fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
+ match self.0 {
+ Scope::Binder {
+ lifetimes,
+ next_early_index,
+ opaque_type_parent,
+ scope_type,
+ hir_id,
+ where_bound_origin,
+ s: _,
+ } => f
+ .debug_struct("Binder")
+ .field("lifetimes", lifetimes)
+ .field("next_early_index", next_early_index)
+ .field("opaque_type_parent", opaque_type_parent)
+ .field("scope_type", scope_type)
+ .field("hir_id", hir_id)
+ .field("where_bound_origin", where_bound_origin)
+ .field("s", &"..")
+ .finish(),
+ Scope::Body { id, s: _ } => {
+ f.debug_struct("Body").field("id", id).field("s", &"..").finish()
+ }
+ Scope::Elision { s: _ } => f.debug_struct("Elision").field("s", &"..").finish(),
+ Scope::ObjectLifetimeDefault { lifetime, s: _ } => f
+ .debug_struct("ObjectLifetimeDefault")
+ .field("lifetime", lifetime)
+ .field("s", &"..")
+ .finish(),
+ Scope::Supertrait { lifetimes, s: _ } => f
+ .debug_struct("Supertrait")
+ .field("lifetimes", lifetimes)
+ .field("s", &"..")
+ .finish(),
+ Scope::TraitRefBoundary { s: _ } => f.debug_struct("TraitRefBoundary").finish(),
+ Scope::Root => f.debug_struct("Root").finish(),
+ }
+ }
+}
+
+type ScopeRef<'a> = &'a Scope<'a>;
+
+const ROOT_SCOPE: ScopeRef<'static> = &Scope::Root;
+
+pub fn provide(providers: &mut ty::query::Providers) {
+ *providers = ty::query::Providers {
+ resolve_lifetimes_trait_definition,
+ resolve_lifetimes,
+
+ named_region_map: |tcx, id| resolve_lifetimes_for(tcx, id).defs.get(&id),
+ is_late_bound_map,
+ object_lifetime_defaults: |tcx, id| match tcx.hir().find_by_def_id(id) {
+ Some(Node::Item(item)) => compute_object_lifetime_defaults(tcx, item),
+ _ => None,
+ },
+ late_bound_vars_map: |tcx, id| resolve_lifetimes_for(tcx, id).late_bound_vars.get(&id),
+
+ ..*providers
+ };
+}
+
+/// Like `resolve_lifetimes`, but does not resolve lifetimes for trait items.
+/// Also does not generate any diagnostics.
+///
+/// This is ultimately a subset of the `resolve_lifetimes` work. It effectively
+/// resolves lifetimes only within the trait "header" -- that is, the trait
+/// and supertrait list. In contrast, `resolve_lifetimes` resolves all the
+/// lifetimes within the trait and its items. There is room to refactor this,
+/// for example to resolve lifetimes for each trait item in separate queries,
+/// but it's convenient to do the entire trait at once because the lifetimes
+/// from the trait definition are in scope within the trait items as well.
+///
+/// The reason for this separate call is to resolve what would otherwise
+/// be a cycle. Consider this example:
+///
+/// ```ignore UNSOLVED (maybe @jackh726 knows what lifetime parameter to give Sub)
+/// trait Base<'a> {
+/// type BaseItem;
+/// }
+/// trait Sub<'b>: for<'a> Base<'a> {
+/// type SubItem: Sub<BaseItem = &'b u32>;
+/// }
+/// ```
+///
+/// When we resolve `Sub` and all its items, we also have to resolve `Sub<BaseItem = &'b u32>`.
+/// To figure out the index of `'b`, we have to know about the supertraits
+/// of `Sub` so that we can determine that the `for<'a>` will be in scope.
+/// (This is because we -- currently at least -- flatten all the late-bound
+/// lifetimes into a single binder.) This requires us to resolve the
+/// *trait definition* of `Sub`; basically just enough lifetime information
+/// to look at the supertraits.
+#[tracing::instrument(level = "debug", skip(tcx))]
+fn resolve_lifetimes_trait_definition(
+ tcx: TyCtxt<'_>,
+ local_def_id: LocalDefId,
+) -> ResolveLifetimes {
+ convert_named_region_map(do_resolve(tcx, local_def_id, true))
+}
+
+/// Computes the `ResolveLifetimes` map that contains data for an entire `Item`.
+/// You should not read the result of this query directly, but rather use
+/// `named_region_map`, `is_late_bound_map`, etc.
+#[tracing::instrument(level = "debug", skip(tcx))]
+fn resolve_lifetimes(tcx: TyCtxt<'_>, local_def_id: LocalDefId) -> ResolveLifetimes {
+ convert_named_region_map(do_resolve(tcx, local_def_id, false))
+}
+
+fn do_resolve(
+ tcx: TyCtxt<'_>,
+ local_def_id: LocalDefId,
+ trait_definition_only: bool,
+) -> NamedRegionMap {
+ let item = tcx.hir().expect_item(local_def_id);
+ let mut named_region_map =
+ NamedRegionMap { defs: Default::default(), late_bound_vars: Default::default() };
+ let mut visitor = LifetimeContext {
+ tcx,
+ map: &mut named_region_map,
+ scope: ROOT_SCOPE,
+ trait_definition_only,
+ xcrate_object_lifetime_defaults: Default::default(),
+ };
+ visitor.visit_item(item);
+
+ named_region_map
+}
+
+fn convert_named_region_map(named_region_map: NamedRegionMap) -> ResolveLifetimes {
+ let mut rl = ResolveLifetimes::default();
+
+ for (hir_id, v) in named_region_map.defs {
+ let map = rl.defs.entry(hir_id.owner).or_default();
+ map.insert(hir_id.local_id, v);
+ }
+ for (hir_id, v) in named_region_map.late_bound_vars {
+ let map = rl.late_bound_vars.entry(hir_id.owner).or_default();
+ map.insert(hir_id.local_id, v);
+ }
+
+ debug!(?rl.defs);
+ rl
+}
+
+/// Given `any` owner (structs, traits, trait methods, etc.), does lifetime resolution.
+/// There are two important things this does.
+/// First, we have to resolve lifetimes for
+/// the entire *`Item`* that contains this owner, because that's the largest "scope"
+/// where we can have relevant lifetimes.
+/// Second, if we are asking for lifetimes in a trait *definition*, we use `resolve_lifetimes_trait_definition`
+/// instead of `resolve_lifetimes`, which does not descend into the trait items and does not emit diagnostics.
+/// This allows us to avoid cycles. Importantly, if we ask for lifetimes for lifetimes that have an owner
+/// other than the trait itself (like the trait methods or associated types), then we just use the regular
+/// `resolve_lifetimes`.
+fn resolve_lifetimes_for<'tcx>(tcx: TyCtxt<'tcx>, def_id: LocalDefId) -> &'tcx ResolveLifetimes {
+ let item_id = item_for(tcx, def_id);
+ if item_id == def_id {
+ let item = tcx.hir().item(hir::ItemId { def_id: item_id });
+ match item.kind {
+ hir::ItemKind::Trait(..) => tcx.resolve_lifetimes_trait_definition(item_id),
+ _ => tcx.resolve_lifetimes(item_id),
+ }
+ } else {
+ tcx.resolve_lifetimes(item_id)
+ }
+}
+
+/// Finds the `Item` that contains the given `LocalDefId`
+fn item_for(tcx: TyCtxt<'_>, local_def_id: LocalDefId) -> LocalDefId {
+ match tcx.hir().find_by_def_id(local_def_id) {
+ Some(Node::Item(item)) => {
+ return item.def_id;
+ }
+ _ => {}
+ }
+ let item = {
+ let hir_id = tcx.hir().local_def_id_to_hir_id(local_def_id);
+ let mut parent_iter = tcx.hir().parent_iter(hir_id);
+ loop {
+ let node = parent_iter.next().map(|n| n.1);
+ match node {
+ Some(hir::Node::Item(item)) => break item.def_id,
+ Some(hir::Node::Crate(_)) | None => bug!("Called `item_for` on an Item."),
+ _ => {}
+ }
+ }
+ };
+ item
+}
+
+/// In traits, there is an implicit `Self` type parameter which comes before the generics.
+/// We have to account for this when computing the index of the other generic parameters.
+/// This function returns whether there is such an implicit parameter defined on the given item.
+fn sub_items_have_self_param(node: &hir::ItemKind<'_>) -> bool {
+ matches!(*node, hir::ItemKind::Trait(..) | hir::ItemKind::TraitAlias(..))
+}
+
+fn late_region_as_bound_region<'tcx>(tcx: TyCtxt<'tcx>, region: &Region) -> ty::BoundVariableKind {
+ match region {
+ Region::LateBound(_, _, def_id) => {
+ let name = tcx.hir().name(tcx.hir().local_def_id_to_hir_id(def_id.expect_local()));
+ ty::BoundVariableKind::Region(ty::BrNamed(*def_id, name))
+ }
+ _ => bug!("{:?} is not a late region", region),
+ }
+}
+
+impl<'a, 'tcx> LifetimeContext<'a, 'tcx> {
+ /// Returns the binders in scope and the type of `Binder` that should be created for a poly trait ref.
+ fn poly_trait_ref_binder_info(&mut self) -> (Vec<ty::BoundVariableKind>, BinderScopeType) {
+ let mut scope = self.scope;
+ let mut supertrait_lifetimes = vec![];
+ loop {
+ match scope {
+ Scope::Body { .. } | Scope::Root => {
+ break (vec![], BinderScopeType::Normal);
+ }
+
+ Scope::Elision { s, .. } | Scope::ObjectLifetimeDefault { s, .. } => {
+ scope = s;
+ }
+
+ Scope::Supertrait { s, lifetimes } => {
+ supertrait_lifetimes = lifetimes.clone();
+ scope = s;
+ }
+
+ Scope::TraitRefBoundary { .. } => {
+ // We should only see super trait lifetimes if there is a `Binder` above
+ assert!(supertrait_lifetimes.is_empty());
+ break (vec![], BinderScopeType::Normal);
+ }
+
+ Scope::Binder { hir_id, .. } => {
+ // Nested poly trait refs have the binders concatenated
+ let mut full_binders =
+ self.map.late_bound_vars.entry(*hir_id).or_default().clone();
+ full_binders.extend(supertrait_lifetimes.into_iter());
+ break (full_binders, BinderScopeType::Concatenating);
+ }
+ }
+ }
+ }
+}
+impl<'a, 'tcx> Visitor<'tcx> for LifetimeContext<'a, 'tcx> {
+ type NestedFilter = nested_filter::All;
+
+ fn nested_visit_map(&mut self) -> Self::Map {
+ self.tcx.hir()
+ }
+
+ // We want to nest trait/impl items in their parent, but nothing else.
+ fn visit_nested_item(&mut self, _: hir::ItemId) {}
+
+ fn visit_trait_item_ref(&mut self, ii: &'tcx hir::TraitItemRef) {
+ if !self.trait_definition_only {
+ intravisit::walk_trait_item_ref(self, ii)
+ }
+ }
+
+ fn visit_nested_body(&mut self, body: hir::BodyId) {
+ let body = self.tcx.hir().body(body);
+ self.with(Scope::Body { id: body.id(), s: self.scope }, |this| {
+ this.visit_body(body);
+ });
+ }
+
+ fn visit_expr(&mut self, e: &'tcx hir::Expr<'tcx>) {
+ if let hir::ExprKind::Closure(hir::Closure {
+ binder, bound_generic_params, fn_decl, ..
+ }) = e.kind
+ {
+ if let &hir::ClosureBinder::For { span: for_sp, .. } = binder {
+ fn span_of_infer(ty: &hir::Ty<'_>) -> Option<Span> {
+ struct V(Option<Span>);
+
+ impl<'v> Visitor<'v> for V {
+ fn visit_ty(&mut self, t: &'v hir::Ty<'v>) {
+ match t.kind {
+ _ if self.0.is_some() => (),
+ hir::TyKind::Infer => {
+ self.0 = Some(t.span);
+ }
+ _ => intravisit::walk_ty(self, t),
+ }
+ }
+ }
+
+ let mut v = V(None);
+ v.visit_ty(ty);
+ v.0
+ }
+
+ let infer_in_rt_sp = match fn_decl.output {
+ hir::FnRetTy::DefaultReturn(sp) => Some(sp),
+ hir::FnRetTy::Return(ty) => span_of_infer(ty),
+ };
+
+ let infer_spans = fn_decl
+ .inputs
+ .into_iter()
+ .filter_map(span_of_infer)
+ .chain(infer_in_rt_sp)
+ .collect::<Vec<_>>();
+
+ if !infer_spans.is_empty() {
+ self.tcx.sess
+ .struct_span_err(
+ infer_spans,
+ "implicit types in closure signatures are forbidden when `for<...>` is present",
+ )
+ .span_label(for_sp, "`for<...>` is here")
+ .emit();
+ }
+ }
+
+ let next_early_index = self.next_early_index();
+ let (lifetimes, binders): (FxIndexMap<LocalDefId, Region>, Vec<_>) =
+ bound_generic_params
+ .iter()
+ .filter(|param| matches!(param.kind, GenericParamKind::Lifetime { .. }))
+ .enumerate()
+ .map(|(late_bound_idx, param)| {
+ let pair = Region::late(late_bound_idx as u32, self.tcx.hir(), param);
+ let r = late_region_as_bound_region(self.tcx, &pair.1);
+ (pair, r)
+ })
+ .unzip();
+
+ self.map.late_bound_vars.insert(e.hir_id, binders);
+ let scope = Scope::Binder {
+ hir_id: e.hir_id,
+ lifetimes,
+ s: self.scope,
+ next_early_index,
+ opaque_type_parent: false,
+ scope_type: BinderScopeType::Normal,
+ where_bound_origin: None,
+ };
+
+ self.with(scope, |this| {
+ // a closure has no bounds, so everything
+ // contained within is scoped within its binder.
+ intravisit::walk_expr(this, e)
+ });
+ } else {
+ intravisit::walk_expr(self, e)
+ }
+ }
+
+ fn visit_item(&mut self, item: &'tcx hir::Item<'tcx>) {
+ match &item.kind {
+ hir::ItemKind::Impl(hir::Impl { of_trait, .. }) => {
+ if let Some(of_trait) = of_trait {
+ self.map.late_bound_vars.insert(of_trait.hir_ref_id, Vec::default());
+ }
+ }
+ _ => {}
+ }
+ match item.kind {
+ hir::ItemKind::Fn(_, ref generics, _) => {
+ self.visit_early_late(None, item.hir_id(), generics, |this| {
+ intravisit::walk_item(this, item);
+ });
+ }
+
+ hir::ItemKind::ExternCrate(_)
+ | hir::ItemKind::Use(..)
+ | hir::ItemKind::Macro(..)
+ | hir::ItemKind::Mod(..)
+ | hir::ItemKind::ForeignMod { .. }
+ | hir::ItemKind::GlobalAsm(..) => {
+ // These sorts of items have no lifetime parameters at all.
+ intravisit::walk_item(self, item);
+ }
+ hir::ItemKind::Static(..) | hir::ItemKind::Const(..) => {
+ // No lifetime parameters, but implied 'static.
+ self.with(Scope::Elision { s: self.scope }, |this| {
+ intravisit::walk_item(this, item)
+ });
+ }
+ hir::ItemKind::OpaqueTy(hir::OpaqueTy { .. }) => {
+ // Opaque types are visited when we visit the
+ // `TyKind::OpaqueDef`, so that they have the lifetimes from
+ // their parent opaque_ty in scope.
+ //
+ // The core idea here is that since OpaqueTys are generated with the impl Trait as
+ // their owner, we can keep going until we find the Item that owns that. We then
+ // conservatively add all resolved lifetimes. Otherwise we run into problems in
+ // cases like `type Foo<'a> = impl Bar<As = impl Baz + 'a>`.
+ for (_hir_id, node) in
+ self.tcx.hir().parent_iter(self.tcx.hir().local_def_id_to_hir_id(item.def_id))
+ {
+ match node {
+ hir::Node::Item(parent_item) => {
+ let resolved_lifetimes: &ResolveLifetimes =
+ self.tcx.resolve_lifetimes(item_for(self.tcx, parent_item.def_id));
+ // We need to add *all* deps, since opaque tys may want them from *us*
+ for (&owner, defs) in resolved_lifetimes.defs.iter() {
+ defs.iter().for_each(|(&local_id, region)| {
+ self.map.defs.insert(hir::HirId { owner, local_id }, *region);
+ });
+ }
+ for (&owner, late_bound_vars) in
+ resolved_lifetimes.late_bound_vars.iter()
+ {
+ late_bound_vars.iter().for_each(|(&local_id, late_bound_vars)| {
+ self.map.late_bound_vars.insert(
+ hir::HirId { owner, local_id },
+ late_bound_vars.clone(),
+ );
+ });
+ }
+ break;
+ }
+ hir::Node::Crate(_) => bug!("No Item about an OpaqueTy"),
+ _ => {}
+ }
+ }
+ }
+ hir::ItemKind::TyAlias(_, ref generics)
+ | hir::ItemKind::Enum(_, ref generics)
+ | hir::ItemKind::Struct(_, ref generics)
+ | hir::ItemKind::Union(_, ref generics)
+ | hir::ItemKind::Trait(_, _, ref generics, ..)
+ | hir::ItemKind::TraitAlias(ref generics, ..)
+ | hir::ItemKind::Impl(hir::Impl { ref generics, .. }) => {
+ // These kinds of items have only early-bound lifetime parameters.
+ let mut index = if sub_items_have_self_param(&item.kind) {
+ 1 // Self comes before lifetimes
+ } else {
+ 0
+ };
+ let mut non_lifetime_count = 0;
+ let lifetimes = generics
+ .params
+ .iter()
+ .filter_map(|param| match param.kind {
+ GenericParamKind::Lifetime { .. } => {
+ Some(Region::early(self.tcx.hir(), &mut index, param))
+ }
+ GenericParamKind::Type { .. } | GenericParamKind::Const { .. } => {
+ non_lifetime_count += 1;
+ None
+ }
+ })
+ .collect();
+ self.map.late_bound_vars.insert(item.hir_id(), vec![]);
+ let scope = Scope::Binder {
+ hir_id: item.hir_id(),
+ lifetimes,
+ next_early_index: index + non_lifetime_count,
+ opaque_type_parent: true,
+ scope_type: BinderScopeType::Normal,
+ s: ROOT_SCOPE,
+ where_bound_origin: None,
+ };
+ self.with(scope, |this| {
+ let scope = Scope::TraitRefBoundary { s: this.scope };
+ this.with(scope, |this| {
+ intravisit::walk_item(this, item);
+ });
+ });
+ }
+ }
+ }
+
+ fn visit_foreign_item(&mut self, item: &'tcx hir::ForeignItem<'tcx>) {
+ match item.kind {
+ hir::ForeignItemKind::Fn(_, _, ref generics) => {
+ self.visit_early_late(None, item.hir_id(), generics, |this| {
+ intravisit::walk_foreign_item(this, item);
+ })
+ }
+ hir::ForeignItemKind::Static(..) => {
+ intravisit::walk_foreign_item(self, item);
+ }
+ hir::ForeignItemKind::Type => {
+ intravisit::walk_foreign_item(self, item);
+ }
+ }
+ }
+
+ #[tracing::instrument(level = "debug", skip(self))]
+ fn visit_ty(&mut self, ty: &'tcx hir::Ty<'tcx>) {
+ match ty.kind {
+ hir::TyKind::BareFn(ref c) => {
+ let next_early_index = self.next_early_index();
+ let (lifetimes, binders): (FxIndexMap<LocalDefId, Region>, Vec<_>) = c
+ .generic_params
+ .iter()
+ .filter(|param| matches!(param.kind, GenericParamKind::Lifetime { .. }))
+ .enumerate()
+ .map(|(late_bound_idx, param)| {
+ let pair = Region::late(late_bound_idx as u32, self.tcx.hir(), param);
+ let r = late_region_as_bound_region(self.tcx, &pair.1);
+ (pair, r)
+ })
+ .unzip();
+ self.map.late_bound_vars.insert(ty.hir_id, binders);
+ let scope = Scope::Binder {
+ hir_id: ty.hir_id,
+ lifetimes,
+ s: self.scope,
+ next_early_index,
+ opaque_type_parent: false,
+ scope_type: BinderScopeType::Normal,
+ where_bound_origin: None,
+ };
+ self.with(scope, |this| {
+ // a bare fn has no bounds, so everything
+ // contained within is scoped within its binder.
+ intravisit::walk_ty(this, ty);
+ });
+ }
+ hir::TyKind::TraitObject(bounds, ref lifetime, _) => {
+ debug!(?bounds, ?lifetime, "TraitObject");
+ let scope = Scope::TraitRefBoundary { s: self.scope };
+ self.with(scope, |this| {
+ for bound in bounds {
+ this.visit_poly_trait_ref(bound, hir::TraitBoundModifier::None);
+ }
+ });
+ match lifetime.name {
+ LifetimeName::ImplicitObjectLifetimeDefault => {
+ // If the user does not write *anything*, we
+ // use the object lifetime defaulting
+ // rules. So e.g., `Box<dyn Debug>` becomes
+ // `Box<dyn Debug + 'static>`.
+ self.resolve_object_lifetime_default(lifetime)
+ }
+ LifetimeName::Infer => {
+ // If the user writes `'_`, we use the *ordinary* elision
+ // rules. So the `'_` in e.g., `Box<dyn Debug + '_>` will be
+ // resolved the same as the `'_` in `&'_ Foo`.
+ //
+ // cc #48468
+ }
+ LifetimeName::Param(..) | LifetimeName::Static => {
+ // If the user wrote an explicit name, use that.
+ self.visit_lifetime(lifetime);
+ }
+ LifetimeName::Error => {}
+ }
+ }
+ hir::TyKind::Rptr(ref lifetime_ref, ref mt) => {
+ self.visit_lifetime(lifetime_ref);
+ let scope = Scope::ObjectLifetimeDefault {
+ lifetime: self.map.defs.get(&lifetime_ref.hir_id).cloned(),
+ s: self.scope,
+ };
+ self.with(scope, |this| this.visit_ty(&mt.ty));
+ }
+ hir::TyKind::OpaqueDef(item_id, lifetimes) => {
+ // Resolve the lifetimes in the bounds to the lifetime defs in the generics.
+ // `fn foo<'a>() -> impl MyTrait<'a> { ... }` desugars to
+ // `type MyAnonTy<'b> = impl MyTrait<'b>;`
+ // ^ ^ this gets resolved in the scope of
+ // the opaque_ty generics
+ let opaque_ty = self.tcx.hir().item(item_id);
+ let (generics, bounds) = match opaque_ty.kind {
+ hir::ItemKind::OpaqueTy(hir::OpaqueTy {
+ origin: hir::OpaqueTyOrigin::TyAlias,
+ ..
+ }) => {
+ intravisit::walk_ty(self, ty);
+
+ // Elided lifetimes are not allowed in non-return
+ // position impl Trait
+ let scope = Scope::TraitRefBoundary { s: self.scope };
+ self.with(scope, |this| {
+ let scope = Scope::Elision { s: this.scope };
+ this.with(scope, |this| {
+ intravisit::walk_item(this, opaque_ty);
+ })
+ });
+
+ return;
+ }
+ hir::ItemKind::OpaqueTy(hir::OpaqueTy {
+ origin: hir::OpaqueTyOrigin::FnReturn(..) | hir::OpaqueTyOrigin::AsyncFn(..),
+ ref generics,
+ bounds,
+ ..
+ }) => (generics, bounds),
+ ref i => bug!("`impl Trait` pointed to non-opaque type?? {:#?}", i),
+ };
+
+ // Resolve the lifetimes that are applied to the opaque type.
+ // These are resolved in the current scope.
+ // `fn foo<'a>() -> impl MyTrait<'a> { ... }` desugars to
+ // `fn foo<'a>() -> MyAnonTy<'a> { ... }`
+ // ^ ^this gets resolved in the current scope
+ for lifetime in lifetimes {
+ let hir::GenericArg::Lifetime(lifetime) = lifetime else {
+ continue
+ };
+ self.visit_lifetime(lifetime);
+
+ // Check for predicates like `impl for<'a> Trait<impl OtherTrait<'a>>`
+ // and ban them. Type variables instantiated inside binders aren't
+ // well-supported at the moment, so this doesn't work.
+ // In the future, this should be fixed and this error should be removed.
+ let def = self.map.defs.get(&lifetime.hir_id).cloned();
+ let Some(Region::LateBound(_, _, def_id)) = def else {
+ continue
+ };
+ let Some(def_id) = def_id.as_local() else {
+ continue
+ };
+ let hir_id = self.tcx.hir().local_def_id_to_hir_id(def_id);
+ // Ensure that the parent of the def is an item, not HRTB
+ let parent_id = self.tcx.hir().get_parent_node(hir_id);
+ if !parent_id.is_owner() {
+ if !self.trait_definition_only {
+ struct_span_err!(
+ self.tcx.sess,
+ lifetime.span,
+ E0657,
+ "`impl Trait` can only capture lifetimes \
+ bound at the fn or impl level"
+ )
+ .emit();
+ }
+ self.uninsert_lifetime_on_error(lifetime, def.unwrap());
+ }
+ if let hir::Node::Item(hir::Item {
+ kind: hir::ItemKind::OpaqueTy { .. }, ..
+ }) = self.tcx.hir().get(parent_id)
+ {
+ if !self.trait_definition_only {
+ let mut err = self.tcx.sess.struct_span_err(
+ lifetime.span,
+ "higher kinded lifetime bounds on nested opaque types are not supported yet",
+ );
+ err.span_note(self.tcx.def_span(def_id), "lifetime declared here");
+ err.emit();
+ }
+ self.uninsert_lifetime_on_error(lifetime, def.unwrap());
+ }
+ }
+
+ // We want to start our early-bound indices at the end of the parent scope,
+ // not including any parent `impl Trait`s.
+ let mut index = self.next_early_index_for_opaque_type();
+ debug!(?index);
+
+ let mut lifetimes = FxIndexMap::default();
+ let mut non_lifetime_count = 0;
+ debug!(?generics.params);
+ for param in generics.params {
+ match param.kind {
+ GenericParamKind::Lifetime { .. } => {
+ let (def_id, reg) = Region::early(self.tcx.hir(), &mut index, &param);
+ lifetimes.insert(def_id, reg);
+ }
+ GenericParamKind::Type { .. } | GenericParamKind::Const { .. } => {
+ non_lifetime_count += 1;
+ }
+ }
+ }
+ let next_early_index = index + non_lifetime_count;
+ self.map.late_bound_vars.insert(ty.hir_id, vec![]);
+
+ let scope = Scope::Binder {
+ hir_id: ty.hir_id,
+ lifetimes,
+ next_early_index,
+ s: self.scope,
+ opaque_type_parent: false,
+ scope_type: BinderScopeType::Normal,
+ where_bound_origin: None,
+ };
+ self.with(scope, |this| {
+ let scope = Scope::TraitRefBoundary { s: this.scope };
+ this.with(scope, |this| {
+ this.visit_generics(generics);
+ for bound in bounds {
+ this.visit_param_bound(bound);
+ }
+ })
+ });
+ }
+ _ => intravisit::walk_ty(self, ty),
+ }
+ }
+
+ fn visit_trait_item(&mut self, trait_item: &'tcx hir::TraitItem<'tcx>) {
+ use self::hir::TraitItemKind::*;
+ match trait_item.kind {
+ Fn(_, _) => {
+ let tcx = self.tcx;
+ self.visit_early_late(
+ Some(tcx.hir().get_parent_item(trait_item.hir_id())),
+ trait_item.hir_id(),
+ &trait_item.generics,
+ |this| intravisit::walk_trait_item(this, trait_item),
+ );
+ }
+ Type(bounds, ref ty) => {
+ let generics = &trait_item.generics;
+ let mut index = self.next_early_index();
+ debug!("visit_ty: index = {}", index);
+ let mut non_lifetime_count = 0;
+ let lifetimes = generics
+ .params
+ .iter()
+ .filter_map(|param| match param.kind {
+ GenericParamKind::Lifetime { .. } => {
+ Some(Region::early(self.tcx.hir(), &mut index, param))
+ }
+ GenericParamKind::Type { .. } | GenericParamKind::Const { .. } => {
+ non_lifetime_count += 1;
+ None
+ }
+ })
+ .collect();
+ self.map.late_bound_vars.insert(trait_item.hir_id(), vec![]);
+ let scope = Scope::Binder {
+ hir_id: trait_item.hir_id(),
+ lifetimes,
+ next_early_index: index + non_lifetime_count,
+ s: self.scope,
+ opaque_type_parent: true,
+ scope_type: BinderScopeType::Normal,
+ where_bound_origin: None,
+ };
+ self.with(scope, |this| {
+ let scope = Scope::TraitRefBoundary { s: this.scope };
+ this.with(scope, |this| {
+ this.visit_generics(generics);
+ for bound in bounds {
+ this.visit_param_bound(bound);
+ }
+ if let Some(ty) = ty {
+ this.visit_ty(ty);
+ }
+ })
+ });
+ }
+ Const(_, _) => {
+ // Only methods and types support generics.
+ assert!(trait_item.generics.params.is_empty());
+ intravisit::walk_trait_item(self, trait_item);
+ }
+ }
+ }
+
+ fn visit_impl_item(&mut self, impl_item: &'tcx hir::ImplItem<'tcx>) {
+ use self::hir::ImplItemKind::*;
+ match impl_item.kind {
+ Fn(..) => {
+ let tcx = self.tcx;
+ self.visit_early_late(
+ Some(tcx.hir().get_parent_item(impl_item.hir_id())),
+ impl_item.hir_id(),
+ &impl_item.generics,
+ |this| intravisit::walk_impl_item(this, impl_item),
+ );
+ }
+ TyAlias(ref ty) => {
+ let generics = &impl_item.generics;
+ let mut index = self.next_early_index();
+ let mut non_lifetime_count = 0;
+ debug!("visit_ty: index = {}", index);
+ let lifetimes: FxIndexMap<LocalDefId, Region> = generics
+ .params
+ .iter()
+ .filter_map(|param| match param.kind {
+ GenericParamKind::Lifetime { .. } => {
+ Some(Region::early(self.tcx.hir(), &mut index, param))
+ }
+ GenericParamKind::Const { .. } | GenericParamKind::Type { .. } => {
+ non_lifetime_count += 1;
+ None
+ }
+ })
+ .collect();
+ self.map.late_bound_vars.insert(ty.hir_id, vec![]);
+ let scope = Scope::Binder {
+ hir_id: ty.hir_id,
+ lifetimes,
+ next_early_index: index + non_lifetime_count,
+ s: self.scope,
+ opaque_type_parent: true,
+ scope_type: BinderScopeType::Normal,
+ where_bound_origin: None,
+ };
+ self.with(scope, |this| {
+ let scope = Scope::TraitRefBoundary { s: this.scope };
+ this.with(scope, |this| {
+ this.visit_generics(generics);
+ this.visit_ty(ty);
+ })
+ });
+ }
+ Const(_, _) => {
+ // Only methods and types support generics.
+ assert!(impl_item.generics.params.is_empty());
+ intravisit::walk_impl_item(self, impl_item);
+ }
+ }
+ }
+
+ #[tracing::instrument(level = "debug", skip(self))]
+ fn visit_lifetime(&mut self, lifetime_ref: &'tcx hir::Lifetime) {
+ match lifetime_ref.name {
+ hir::LifetimeName::Static => self.insert_lifetime(lifetime_ref, Region::Static),
+ hir::LifetimeName::Param(param_def_id, _) => {
+ self.resolve_lifetime_ref(param_def_id, lifetime_ref)
+ }
+ // If we've already reported an error, just ignore `lifetime_ref`.
+ hir::LifetimeName::Error => {}
+ // Those will be resolved by typechecking.
+ hir::LifetimeName::ImplicitObjectLifetimeDefault | hir::LifetimeName::Infer => {}
+ }
+ }
+
+ fn visit_path(&mut self, path: &'tcx hir::Path<'tcx>, _: hir::HirId) {
+ for (i, segment) in path.segments.iter().enumerate() {
+ let depth = path.segments.len() - i - 1;
+ if let Some(ref args) = segment.args {
+ self.visit_segment_args(path.res, depth, args);
+ }
+ }
+ }
+
+ fn visit_fn(
+ &mut self,
+ fk: intravisit::FnKind<'tcx>,
+ fd: &'tcx hir::FnDecl<'tcx>,
+ body_id: hir::BodyId,
+ _: Span,
+ _: hir::HirId,
+ ) {
+ let output = match fd.output {
+ hir::FnRetTy::DefaultReturn(_) => None,
+ hir::FnRetTy::Return(ref ty) => Some(&**ty),
+ };
+ self.visit_fn_like_elision(&fd.inputs, output, matches!(fk, intravisit::FnKind::Closure));
+ intravisit::walk_fn_kind(self, fk);
+ self.visit_nested_body(body_id)
+ }
+
+ fn visit_generics(&mut self, generics: &'tcx hir::Generics<'tcx>) {
+ let scope = Scope::TraitRefBoundary { s: self.scope };
+ self.with(scope, |this| {
+ for param in generics.params {
+ match param.kind {
+ GenericParamKind::Lifetime { .. } => {}
+ GenericParamKind::Type { ref default, .. } => {
+ if let Some(ref ty) = default {
+ this.visit_ty(&ty);
+ }
+ }
+ GenericParamKind::Const { ref ty, default } => {
+ this.visit_ty(&ty);
+ if let Some(default) = default {
+ this.visit_body(this.tcx.hir().body(default.body));
+ }
+ }
+ }
+ }
+ for predicate in generics.predicates {
+ match predicate {
+ &hir::WherePredicate::BoundPredicate(hir::WhereBoundPredicate {
+ ref bounded_ty,
+ bounds,
+ ref bound_generic_params,
+ origin,
+ ..
+ }) => {
+ let (lifetimes, binders): (FxIndexMap<LocalDefId, Region>, Vec<_>) =
+ bound_generic_params
+ .iter()
+ .filter(|param| {
+ matches!(param.kind, GenericParamKind::Lifetime { .. })
+ })
+ .enumerate()
+ .map(|(late_bound_idx, param)| {
+ let pair =
+ Region::late(late_bound_idx as u32, this.tcx.hir(), param);
+ let r = late_region_as_bound_region(this.tcx, &pair.1);
+ (pair, r)
+ })
+ .unzip();
+ this.map.late_bound_vars.insert(bounded_ty.hir_id, binders.clone());
+ let next_early_index = this.next_early_index();
+ // Even if there are no lifetimes defined here, we still wrap it in a binder
+ // scope. If there happens to be a nested poly trait ref (an error), that
+ // will be `Concatenating` anyways, so we don't have to worry about the depth
+ // being wrong.
+ let scope = Scope::Binder {
+ hir_id: bounded_ty.hir_id,
+ lifetimes,
+ s: this.scope,
+ next_early_index,
+ opaque_type_parent: false,
+ scope_type: BinderScopeType::Normal,
+ where_bound_origin: Some(origin),
+ };
+ this.with(scope, |this| {
+ this.visit_ty(&bounded_ty);
+ walk_list!(this, visit_param_bound, bounds);
+ })
+ }
+ &hir::WherePredicate::RegionPredicate(hir::WhereRegionPredicate {
+ ref lifetime,
+ bounds,
+ ..
+ }) => {
+ this.visit_lifetime(lifetime);
+ walk_list!(this, visit_param_bound, bounds);
+
+ if lifetime.name != hir::LifetimeName::Static {
+ for bound in bounds {
+ let hir::GenericBound::Outlives(ref lt) = bound else {
+ continue;
+ };
+ if lt.name != hir::LifetimeName::Static {
+ continue;
+ }
+ this.insert_lifetime(lt, Region::Static);
+ this.tcx
+ .sess
+ .struct_span_warn(
+ lifetime.span,
+ &format!(
+ "unnecessary lifetime parameter `{}`",
+ lifetime.name.ident(),
+ ),
+ )
+ .help(&format!(
+ "you can use the `'static` lifetime directly, in place of `{}`",
+ lifetime.name.ident(),
+ ))
+ .emit();
+ }
+ }
+ }
+ &hir::WherePredicate::EqPredicate(hir::WhereEqPredicate {
+ ref lhs_ty,
+ ref rhs_ty,
+ ..
+ }) => {
+ this.visit_ty(lhs_ty);
+ this.visit_ty(rhs_ty);
+ }
+ }
+ }
+ })
+ }
+
+ fn visit_param_bound(&mut self, bound: &'tcx hir::GenericBound<'tcx>) {
+ match bound {
+ hir::GenericBound::LangItemTrait(_, _, hir_id, _) => {
+ // FIXME(jackh726): This is pretty weird. `LangItemTrait` doesn't go
+ // through the regular poly trait ref code, so we don't get another
+ // chance to introduce a binder. For now, I'm keeping the existing logic
+ // of "if there isn't a Binder scope above us, add one", but I
+ // imagine there's a better way to go about this.
+ let (binders, scope_type) = self.poly_trait_ref_binder_info();
+
+ self.map.late_bound_vars.insert(*hir_id, binders);
+ let scope = Scope::Binder {
+ hir_id: *hir_id,
+ lifetimes: FxIndexMap::default(),
+ s: self.scope,
+ next_early_index: self.next_early_index(),
+ opaque_type_parent: false,
+ scope_type,
+ where_bound_origin: None,
+ };
+ self.with(scope, |this| {
+ intravisit::walk_param_bound(this, bound);
+ });
+ }
+ _ => intravisit::walk_param_bound(self, bound),
+ }
+ }
+
+ fn visit_poly_trait_ref(
+ &mut self,
+ trait_ref: &'tcx hir::PolyTraitRef<'tcx>,
+ _modifier: hir::TraitBoundModifier,
+ ) {
+ debug!("visit_poly_trait_ref(trait_ref={:?})", trait_ref);
+
+ let next_early_index = self.next_early_index();
+ let (mut binders, scope_type) = self.poly_trait_ref_binder_info();
+
+ let initial_bound_vars = binders.len() as u32;
+ let mut lifetimes: FxIndexMap<LocalDefId, Region> = FxIndexMap::default();
+ let binders_iter = trait_ref
+ .bound_generic_params
+ .iter()
+ .filter(|param| matches!(param.kind, GenericParamKind::Lifetime { .. }))
+ .enumerate()
+ .map(|(late_bound_idx, param)| {
+ let pair =
+ Region::late(initial_bound_vars + late_bound_idx as u32, self.tcx.hir(), param);
+ let r = late_region_as_bound_region(self.tcx, &pair.1);
+ lifetimes.insert(pair.0, pair.1);
+ r
+ });
+ binders.extend(binders_iter);
+
+ debug!(?binders);
+ self.map.late_bound_vars.insert(trait_ref.trait_ref.hir_ref_id, binders);
+
+ // Always introduce a scope here, even if this is in a where clause and
+ // we introduced the binders around the bounded Ty. In that case, we
+ // just reuse the concatenation functionality also present in nested trait
+ // refs.
+ let scope = Scope::Binder {
+ hir_id: trait_ref.trait_ref.hir_ref_id,
+ lifetimes,
+ s: self.scope,
+ next_early_index,
+ opaque_type_parent: false,
+ scope_type,
+ where_bound_origin: None,
+ };
+ self.with(scope, |this| {
+ walk_list!(this, visit_generic_param, trait_ref.bound_generic_params);
+ this.visit_trait_ref(&trait_ref.trait_ref);
+ });
+ }
+}
+
+fn compute_object_lifetime_defaults<'tcx>(
+ tcx: TyCtxt<'tcx>,
+ item: &hir::Item<'_>,
+) -> Option<&'tcx [ObjectLifetimeDefault]> {
+ match item.kind {
+ hir::ItemKind::Struct(_, ref generics)
+ | hir::ItemKind::Union(_, ref generics)
+ | hir::ItemKind::Enum(_, ref generics)
+ | hir::ItemKind::OpaqueTy(hir::OpaqueTy {
+ ref generics,
+ origin: hir::OpaqueTyOrigin::TyAlias,
+ ..
+ })
+ | hir::ItemKind::TyAlias(_, ref generics)
+ | hir::ItemKind::Trait(_, _, ref generics, ..) => {
+ let result = object_lifetime_defaults_for_item(tcx, generics);
+
+ // Debugging aid.
+ let attrs = tcx.hir().attrs(item.hir_id());
+ if tcx.sess.contains_name(attrs, sym::rustc_object_lifetime_default) {
+ let object_lifetime_default_reprs: String = result
+ .iter()
+ .map(|set| match *set {
+ Set1::Empty => "BaseDefault".into(),
+ Set1::One(Region::Static) => "'static".into(),
+ Set1::One(Region::EarlyBound(mut i, _)) => generics
+ .params
+ .iter()
+ .find_map(|param| match param.kind {
+ GenericParamKind::Lifetime { .. } => {
+ if i == 0 {
+ return Some(param.name.ident().to_string().into());
+ }
+ i -= 1;
+ None
+ }
+ _ => None,
+ })
+ .unwrap(),
+ Set1::One(_) => bug!(),
+ Set1::Many => "Ambiguous".into(),
+ })
+ .collect::<Vec<Cow<'static, str>>>()
+ .join(",");
+ tcx.sess.span_err(item.span, &object_lifetime_default_reprs);
+ }
+
+ Some(result)
+ }
+ _ => None,
+ }
+}
+
+/// Scan the bounds and where-clauses on parameters to extract bounds
+/// of the form `T:'a` so as to determine the `ObjectLifetimeDefault`
+/// for each type parameter.
+fn object_lifetime_defaults_for_item<'tcx>(
+ tcx: TyCtxt<'tcx>,
+ generics: &hir::Generics<'_>,
+) -> &'tcx [ObjectLifetimeDefault] {
+ fn add_bounds(set: &mut Set1<hir::LifetimeName>, bounds: &[hir::GenericBound<'_>]) {
+ for bound in bounds {
+ if let hir::GenericBound::Outlives(ref lifetime) = *bound {
+ set.insert(lifetime.name.normalize_to_macros_2_0());
+ }
+ }
+ }
+
+ let process_param = |param: &hir::GenericParam<'_>| match param.kind {
+ GenericParamKind::Lifetime { .. } => None,
+ GenericParamKind::Type { .. } => {
+ let mut set = Set1::Empty;
+
+ let param_def_id = tcx.hir().local_def_id(param.hir_id);
+ for predicate in generics.predicates {
+ // Look for `type: ...` where clauses.
+ let hir::WherePredicate::BoundPredicate(ref data) = *predicate else { continue };
+
+ // Ignore `for<'a> type: ...` as they can change what
+ // lifetimes mean (although we could "just" handle it).
+ if !data.bound_generic_params.is_empty() {
+ continue;
+ }
+
+ let res = match data.bounded_ty.kind {
+ hir::TyKind::Path(hir::QPath::Resolved(None, ref path)) => path.res,
+ _ => continue,
+ };
+
+ if res == Res::Def(DefKind::TyParam, param_def_id.to_def_id()) {
+ add_bounds(&mut set, &data.bounds);
+ }
+ }
+
+ Some(match set {
+ Set1::Empty => Set1::Empty,
+ Set1::One(name) => {
+ if name == hir::LifetimeName::Static {
+ Set1::One(Region::Static)
+ } else {
+ generics
+ .params
+ .iter()
+ .filter_map(|param| match param.kind {
+ GenericParamKind::Lifetime { .. } => {
+ let param_def_id = tcx.hir().local_def_id(param.hir_id);
+ Some((
+ param_def_id,
+ hir::LifetimeName::Param(param_def_id, param.name),
+ ))
+ }
+ _ => None,
+ })
+ .enumerate()
+ .find(|&(_, (_, lt_name))| lt_name == name)
+ .map_or(Set1::Many, |(i, (def_id, _))| {
+ Set1::One(Region::EarlyBound(i as u32, def_id.to_def_id()))
+ })
+ }
+ }
+ Set1::Many => Set1::Many,
+ })
+ }
+ GenericParamKind::Const { .. } => {
+ // Generic consts don't impose any constraints.
+ //
+ // We still store a dummy value here to allow generic parameters
+ // in an arbitrary order.
+ Some(Set1::Empty)
+ }
+ };
+
+ tcx.arena.alloc_from_iter(generics.params.iter().filter_map(process_param))
+}
+
+impl<'a, 'tcx> LifetimeContext<'a, 'tcx> {
+ fn with<F>(&mut self, wrap_scope: Scope<'_>, f: F)
+ where
+ F: for<'b> FnOnce(&mut LifetimeContext<'b, 'tcx>),
+ {
+ let LifetimeContext { tcx, map, .. } = self;
+ let xcrate_object_lifetime_defaults = take(&mut self.xcrate_object_lifetime_defaults);
+ let mut this = LifetimeContext {
+ tcx: *tcx,
+ map,
+ scope: &wrap_scope,
+ trait_definition_only: self.trait_definition_only,
+ xcrate_object_lifetime_defaults,
+ };
+ let span = tracing::debug_span!("scope", scope = ?TruncatedScopeDebug(&this.scope));
+ {
+ let _enter = span.enter();
+ f(&mut this);
+ }
+ self.xcrate_object_lifetime_defaults = this.xcrate_object_lifetime_defaults;
+ }
+
+ /// Visits self by adding a scope and handling recursive walk over the contents with `walk`.
+ ///
+ /// Handles visiting fns and methods. These are a bit complicated because we must distinguish
+ /// early- vs late-bound lifetime parameters. We do this by checking which lifetimes appear
+ /// within type bounds; those are early bound lifetimes, and the rest are late bound.
+ ///
+ /// For example:
+ ///
+ /// fn foo<'a,'b,'c,T:Trait<'b>>(...)
+ ///
+ /// Here `'a` and `'c` are late bound but `'b` is early bound. Note that early- and late-bound
+ /// lifetimes may be interspersed together.
+ ///
+ /// If early bound lifetimes are present, we separate them into their own list (and likewise
+ /// for late bound). They will be numbered sequentially, starting from the lowest index that is
+ /// already in scope (for a fn item, that will be 0, but for a method it might not be). Late
+ /// bound lifetimes are resolved by name and associated with a binder ID (`binder_id`), so the
+ /// ordering is not important there.
+ fn visit_early_late<F>(
+ &mut self,
+ parent_id: Option<LocalDefId>,
+ hir_id: hir::HirId,
+ generics: &'tcx hir::Generics<'tcx>,
+ walk: F,
+ ) where
+ F: for<'b, 'c> FnOnce(&'b mut LifetimeContext<'c, 'tcx>),
+ {
+ // Find the start of nested early scopes, e.g., in methods.
+ let mut next_early_index = 0;
+ if let Some(parent_id) = parent_id {
+ let parent = self.tcx.hir().expect_item(parent_id);
+ if sub_items_have_self_param(&parent.kind) {
+ next_early_index += 1; // Self comes before lifetimes
+ }
+ match parent.kind {
+ hir::ItemKind::Trait(_, _, ref generics, ..)
+ | hir::ItemKind::Impl(hir::Impl { ref generics, .. }) => {
+ next_early_index += generics.params.len() as u32;
+ }
+ _ => {}
+ }
+ }
+
+ let mut non_lifetime_count = 0;
+ let mut named_late_bound_vars = 0;
+ let lifetimes: FxIndexMap<LocalDefId, Region> = generics
+ .params
+ .iter()
+ .filter_map(|param| match param.kind {
+ GenericParamKind::Lifetime { .. } => {
+ if self.tcx.is_late_bound(param.hir_id) {
+ let late_bound_idx = named_late_bound_vars;
+ named_late_bound_vars += 1;
+ Some(Region::late(late_bound_idx, self.tcx.hir(), param))
+ } else {
+ Some(Region::early(self.tcx.hir(), &mut next_early_index, param))
+ }
+ }
+ GenericParamKind::Type { .. } | GenericParamKind::Const { .. } => {
+ non_lifetime_count += 1;
+ None
+ }
+ })
+ .collect();
+ let next_early_index = next_early_index + non_lifetime_count;
+
+ let binders: Vec<_> = generics
+ .params
+ .iter()
+ .filter(|param| {
+ matches!(param.kind, GenericParamKind::Lifetime { .. })
+ && self.tcx.is_late_bound(param.hir_id)
+ })
+ .enumerate()
+ .map(|(late_bound_idx, param)| {
+ let pair = Region::late(late_bound_idx as u32, self.tcx.hir(), param);
+ late_region_as_bound_region(self.tcx, &pair.1)
+ })
+ .collect();
+ self.map.late_bound_vars.insert(hir_id, binders);
+ let scope = Scope::Binder {
+ hir_id,
+ lifetimes,
+ next_early_index,
+ s: self.scope,
+ opaque_type_parent: true,
+ scope_type: BinderScopeType::Normal,
+ where_bound_origin: None,
+ };
+ self.with(scope, walk);
+ }
+
+ fn next_early_index_helper(&self, only_opaque_type_parent: bool) -> u32 {
+ let mut scope = self.scope;
+ loop {
+ match *scope {
+ Scope::Root => return 0,
+
+ Scope::Binder { next_early_index, opaque_type_parent, .. }
+ if (!only_opaque_type_parent || opaque_type_parent) =>
+ {
+ return next_early_index;
+ }
+
+ Scope::Binder { s, .. }
+ | Scope::Body { s, .. }
+ | Scope::Elision { s, .. }
+ | Scope::ObjectLifetimeDefault { s, .. }
+ | Scope::Supertrait { s, .. }
+ | Scope::TraitRefBoundary { s, .. } => scope = s,
+ }
+ }
+ }
+
+ /// Returns the next index one would use for an early-bound-region
+ /// if extending the current scope.
+ fn next_early_index(&self) -> u32 {
+ self.next_early_index_helper(true)
+ }
+
+ /// Returns the next index one would use for an `impl Trait` that
+ /// is being converted into an opaque type alias `impl Trait`. This will be the
+ /// next early index from the enclosing item, for the most
+ /// part. See the `opaque_type_parent` field for more info.
+ fn next_early_index_for_opaque_type(&self) -> u32 {
+ self.next_early_index_helper(false)
+ }
+
+ #[tracing::instrument(level = "debug", skip(self))]
+ fn resolve_lifetime_ref(
+ &mut self,
+ region_def_id: LocalDefId,
+ lifetime_ref: &'tcx hir::Lifetime,
+ ) {
+ // Walk up the scope chain, tracking the number of fn scopes
+ // that we pass through, until we find a lifetime with the
+ // given name or we run out of scopes.
+ // search.
+ let mut late_depth = 0;
+ let mut scope = self.scope;
+ let mut outermost_body = None;
+ let result = loop {
+ match *scope {
+ Scope::Body { id, s } => {
+ outermost_body = Some(id);
+ scope = s;
+ }
+
+ Scope::Root => {
+ break None;
+ }
+
+ Scope::Binder { ref lifetimes, scope_type, s, where_bound_origin, .. } => {
+ if let Some(&def) = lifetimes.get(&region_def_id) {
+ break Some(def.shifted(late_depth));
+ }
+ match scope_type {
+ BinderScopeType::Normal => late_depth += 1,
+ BinderScopeType::Concatenating => {}
+ }
+ // Fresh lifetimes in APIT used to be allowed in async fns and forbidden in
+ // regular fns.
+ if let Some(hir::PredicateOrigin::ImplTrait) = where_bound_origin
+ && let hir::LifetimeName::Param(_, hir::ParamName::Fresh) = lifetime_ref.name
+ && let hir::IsAsync::NotAsync = self.tcx.asyncness(lifetime_ref.hir_id.owner)
+ && !self.tcx.features().anonymous_lifetime_in_impl_trait
+ {
+ rustc_session::parse::feature_err(
+ &self.tcx.sess.parse_sess,
+ sym::anonymous_lifetime_in_impl_trait,
+ lifetime_ref.span,
+ "anonymous lifetimes in `impl Trait` are unstable",
+ ).emit();
+ return;
+ }
+ scope = s;
+ }
+
+ Scope::Elision { s, .. }
+ | Scope::ObjectLifetimeDefault { s, .. }
+ | Scope::Supertrait { s, .. }
+ | Scope::TraitRefBoundary { s, .. } => {
+ scope = s;
+ }
+ }
+ };
+
+ if let Some(mut def) = result {
+ if let Region::EarlyBound(..) = def {
+ // Do not free early-bound regions, only late-bound ones.
+ } else if let Some(body_id) = outermost_body {
+ let fn_id = self.tcx.hir().body_owner(body_id);
+ match self.tcx.hir().get(fn_id) {
+ Node::Item(&hir::Item { kind: hir::ItemKind::Fn(..), .. })
+ | Node::TraitItem(&hir::TraitItem {
+ kind: hir::TraitItemKind::Fn(..), ..
+ })
+ | Node::ImplItem(&hir::ImplItem { kind: hir::ImplItemKind::Fn(..), .. }) => {
+ let scope = self.tcx.hir().local_def_id(fn_id);
+ def = Region::Free(scope.to_def_id(), def.id().unwrap());
+ }
+ _ => {}
+ }
+ }
+
+ self.insert_lifetime(lifetime_ref, def);
+ return;
+ }
+
+ // We may fail to resolve higher-ranked lifetimes that are mentionned by APIT.
+ // AST-based resolution does not care for impl-trait desugaring, which are the
+ // responibility of lowering. This may create a mismatch between the resolution
+ // AST found (`region_def_id`) which points to HRTB, and what HIR allows.
+ // ```
+ // fn foo(x: impl for<'a> Trait<'a, Assoc = impl Copy + 'a>) {}
+ // ```
+ //
+ // In such case, walk back the binders to diagnose it properly.
+ let mut scope = self.scope;
+ loop {
+ match *scope {
+ Scope::Binder {
+ where_bound_origin: Some(hir::PredicateOrigin::ImplTrait), ..
+ } => {
+ let mut err = self.tcx.sess.struct_span_err(
+ lifetime_ref.span,
+ "`impl Trait` can only mention lifetimes bound at the fn or impl level",
+ );
+ err.span_note(self.tcx.def_span(region_def_id), "lifetime declared here");
+ err.emit();
+ return;
+ }
+ Scope::Root => break,
+ Scope::Binder { s, .. }
+ | Scope::Body { s, .. }
+ | Scope::Elision { s, .. }
+ | Scope::ObjectLifetimeDefault { s, .. }
+ | Scope::Supertrait { s, .. }
+ | Scope::TraitRefBoundary { s, .. } => {
+ scope = s;
+ }
+ }
+ }
+
+ self.tcx.sess.delay_span_bug(
+ lifetime_ref.span,
+ &format!("Could not resolve {:?} in scope {:#?}", lifetime_ref, self.scope,),
+ );
+ }
+
+ fn visit_segment_args(
+ &mut self,
+ res: Res,
+ depth: usize,
+ generic_args: &'tcx hir::GenericArgs<'tcx>,
+ ) {
+ debug!(
+ "visit_segment_args(res={:?}, depth={:?}, generic_args={:?})",
+ res, depth, generic_args,
+ );
+
+ if generic_args.parenthesized {
+ self.visit_fn_like_elision(
+ generic_args.inputs(),
+ Some(generic_args.bindings[0].ty()),
+ false,
+ );
+ return;
+ }
+
+ for arg in generic_args.args {
+ if let hir::GenericArg::Lifetime(lt) = arg {
+ self.visit_lifetime(lt);
+ }
+ }
+
+ // Figure out if this is a type/trait segment,
+ // which requires object lifetime defaults.
+ let parent_def_id = |this: &mut Self, def_id: DefId| {
+ let def_key = this.tcx.def_key(def_id);
+ DefId { krate: def_id.krate, index: def_key.parent.expect("missing parent") }
+ };
+ let type_def_id = match res {
+ Res::Def(DefKind::AssocTy, def_id) if depth == 1 => Some(parent_def_id(self, def_id)),
+ Res::Def(DefKind::Variant, def_id) if depth == 0 => Some(parent_def_id(self, def_id)),
+ Res::Def(
+ DefKind::Struct
+ | DefKind::Union
+ | DefKind::Enum
+ | DefKind::TyAlias
+ | DefKind::Trait,
+ def_id,
+ ) if depth == 0 => Some(def_id),
+ _ => None,
+ };
+
+ debug!("visit_segment_args: type_def_id={:?}", type_def_id);
+
+ // Compute a vector of defaults, one for each type parameter,
+ // per the rules given in RFCs 599 and 1156. Example:
+ //
+ // ```rust
+ // struct Foo<'a, T: 'a, U> { }
+ // ```
+ //
+ // If you have `Foo<'x, dyn Bar, dyn Baz>`, we want to default
+ // `dyn Bar` to `dyn Bar + 'x` (because of the `T: 'a` bound)
+ // and `dyn Baz` to `dyn Baz + 'static` (because there is no
+ // such bound).
+ //
+ // Therefore, we would compute `object_lifetime_defaults` to a
+ // vector like `['x, 'static]`. Note that the vector only
+ // includes type parameters.
+ let object_lifetime_defaults = type_def_id.map_or_else(Vec::new, |def_id| {
+ let in_body = {
+ let mut scope = self.scope;
+ loop {
+ match *scope {
+ Scope::Root => break false,
+
+ Scope::Body { .. } => break true,
+
+ Scope::Binder { s, .. }
+ | Scope::Elision { s, .. }
+ | Scope::ObjectLifetimeDefault { s, .. }
+ | Scope::Supertrait { s, .. }
+ | Scope::TraitRefBoundary { s, .. } => {
+ scope = s;
+ }
+ }
+ }
+ };
+
+ let map = &self.map;
+ let set_to_region = |set: &ObjectLifetimeDefault| match *set {
+ Set1::Empty => {
+ if in_body {
+ None
+ } else {
+ Some(Region::Static)
+ }
+ }
+ Set1::One(r) => {
+ let lifetimes = generic_args.args.iter().filter_map(|arg| match arg {
+ GenericArg::Lifetime(lt) => Some(lt),
+ _ => None,
+ });
+ r.subst(lifetimes, map)
+ }
+ Set1::Many => None,
+ };
+ if let Some(def_id) = def_id.as_local() {
+ let id = self.tcx.hir().local_def_id_to_hir_id(def_id);
+ self.tcx
+ .object_lifetime_defaults(id.owner)
+ .unwrap()
+ .iter()
+ .map(set_to_region)
+ .collect()
+ } else {
+ let tcx = self.tcx;
+ self.xcrate_object_lifetime_defaults
+ .entry(def_id)
+ .or_insert_with(|| {
+ tcx.generics_of(def_id)
+ .params
+ .iter()
+ .filter_map(|param| match param.kind {
+ GenericParamDefKind::Type { object_lifetime_default, .. } => {
+ Some(object_lifetime_default)
+ }
+ GenericParamDefKind::Const { .. } => Some(Set1::Empty),
+ GenericParamDefKind::Lifetime => None,
+ })
+ .collect()
+ })
+ .iter()
+ .map(set_to_region)
+ .collect()
+ }
+ });
+
+ debug!("visit_segment_args: object_lifetime_defaults={:?}", object_lifetime_defaults);
+
+ let mut i = 0;
+ for arg in generic_args.args {
+ match arg {
+ GenericArg::Lifetime(_) => {}
+ GenericArg::Type(ty) => {
+ if let Some(&lt) = object_lifetime_defaults.get(i) {
+ let scope = Scope::ObjectLifetimeDefault { lifetime: lt, s: self.scope };
+ self.with(scope, |this| this.visit_ty(ty));
+ } else {
+ self.visit_ty(ty);
+ }
+ i += 1;
+ }
+ GenericArg::Const(ct) => {
+ self.visit_anon_const(&ct.value);
+ i += 1;
+ }
+ GenericArg::Infer(inf) => {
+ self.visit_id(inf.hir_id);
+ i += 1;
+ }
+ }
+ }
+
+ // Hack: when resolving the type `XX` in binding like `dyn
+ // Foo<'b, Item = XX>`, the current object-lifetime default
+ // would be to examine the trait `Foo` to check whether it has
+ // a lifetime bound declared on `Item`. e.g., if `Foo` is
+ // declared like so, then the default object lifetime bound in
+ // `XX` should be `'b`:
+ //
+ // ```rust
+ // trait Foo<'a> {
+ // type Item: 'a;
+ // }
+ // ```
+ //
+ // but if we just have `type Item;`, then it would be
+ // `'static`. However, we don't get all of this logic correct.
+ //
+ // Instead, we do something hacky: if there are no lifetime parameters
+ // to the trait, then we simply use a default object lifetime
+ // bound of `'static`, because there is no other possibility. On the other hand,
+ // if there ARE lifetime parameters, then we require the user to give an
+ // explicit bound for now.
+ //
+ // This is intended to leave room for us to implement the
+ // correct behavior in the future.
+ let has_lifetime_parameter =
+ generic_args.args.iter().any(|arg| matches!(arg, GenericArg::Lifetime(_)));
+
+ // Resolve lifetimes found in the bindings, so either in the type `XX` in `Item = XX` or
+ // in the trait ref `YY<...>` in `Item: YY<...>`.
+ for binding in generic_args.bindings {
+ let scope = Scope::ObjectLifetimeDefault {
+ lifetime: if has_lifetime_parameter { None } else { Some(Region::Static) },
+ s: self.scope,
+ };
+ if let Some(type_def_id) = type_def_id {
+ let lifetimes = LifetimeContext::supertrait_hrtb_lifetimes(
+ self.tcx,
+ type_def_id,
+ binding.ident,
+ );
+ self.with(scope, |this| {
+ let scope = Scope::Supertrait {
+ lifetimes: lifetimes.unwrap_or_default(),
+ s: this.scope,
+ };
+ this.with(scope, |this| this.visit_assoc_type_binding(binding));
+ });
+ } else {
+ self.with(scope, |this| this.visit_assoc_type_binding(binding));
+ }
+ }
+ }
+
+ /// Returns all the late-bound vars that come into scope from supertrait HRTBs, based on the
+ /// associated type name and starting trait.
+ /// For example, imagine we have
+ /// ```ignore (illustrative)
+ /// trait Foo<'a, 'b> {
+ /// type As;
+ /// }
+ /// trait Bar<'b>: for<'a> Foo<'a, 'b> {}
+ /// trait Bar: for<'b> Bar<'b> {}
+ /// ```
+ /// In this case, if we wanted to the supertrait HRTB lifetimes for `As` on
+ /// the starting trait `Bar`, we would return `Some(['b, 'a])`.
+ fn supertrait_hrtb_lifetimes(
+ tcx: TyCtxt<'tcx>,
+ def_id: DefId,
+ assoc_name: Ident,
+ ) -> Option<Vec<ty::BoundVariableKind>> {
+ let trait_defines_associated_type_named = |trait_def_id: DefId| {
+ tcx.associated_items(trait_def_id)
+ .find_by_name_and_kind(tcx, assoc_name, ty::AssocKind::Type, trait_def_id)
+ .is_some()
+ };
+
+ use smallvec::{smallvec, SmallVec};
+ let mut stack: SmallVec<[(DefId, SmallVec<[ty::BoundVariableKind; 8]>); 8]> =
+ smallvec![(def_id, smallvec![])];
+ let mut visited: FxHashSet<DefId> = FxHashSet::default();
+ loop {
+ let Some((def_id, bound_vars)) = stack.pop() else {
+ break None;
+ };
+ // See issue #83753. If someone writes an associated type on a non-trait, just treat it as
+ // there being no supertrait HRTBs.
+ match tcx.def_kind(def_id) {
+ DefKind::Trait | DefKind::TraitAlias | DefKind::Impl => {}
+ _ => break None,
+ }
+
+ if trait_defines_associated_type_named(def_id) {
+ break Some(bound_vars.into_iter().collect());
+ }
+ let predicates =
+ tcx.super_predicates_that_define_assoc_type((def_id, Some(assoc_name)));
+ let obligations = predicates.predicates.iter().filter_map(|&(pred, _)| {
+ let bound_predicate = pred.kind();
+ match bound_predicate.skip_binder() {
+ ty::PredicateKind::Trait(data) => {
+ // The order here needs to match what we would get from `subst_supertrait`
+ let pred_bound_vars = bound_predicate.bound_vars();
+ let mut all_bound_vars = bound_vars.clone();
+ all_bound_vars.extend(pred_bound_vars.iter());
+ let super_def_id = data.trait_ref.def_id;
+ Some((super_def_id, all_bound_vars))
+ }
+ _ => None,
+ }
+ });
+
+ let obligations = obligations.filter(|o| visited.insert(o.0));
+ stack.extend(obligations);
+ }
+ }
+
+ #[tracing::instrument(level = "debug", skip(self))]
+ fn visit_fn_like_elision(
+ &mut self,
+ inputs: &'tcx [hir::Ty<'tcx>],
+ output: Option<&'tcx hir::Ty<'tcx>>,
+ in_closure: bool,
+ ) {
+ self.with(Scope::Elision { s: self.scope }, |this| {
+ for input in inputs {
+ this.visit_ty(input);
+ }
+ if !in_closure && let Some(output) = output {
+ this.visit_ty(output);
+ }
+ });
+ if in_closure && let Some(output) = output {
+ self.visit_ty(output);
+ }
+ }
+
+ fn resolve_object_lifetime_default(&mut self, lifetime_ref: &'tcx hir::Lifetime) {
+ debug!("resolve_object_lifetime_default(lifetime_ref={:?})", lifetime_ref);
+ let mut late_depth = 0;
+ let mut scope = self.scope;
+ let lifetime = loop {
+ match *scope {
+ Scope::Binder { s, scope_type, .. } => {
+ match scope_type {
+ BinderScopeType::Normal => late_depth += 1,
+ BinderScopeType::Concatenating => {}
+ }
+ scope = s;
+ }
+
+ Scope::Root | Scope::Elision { .. } => break Region::Static,
+
+ Scope::Body { .. } | Scope::ObjectLifetimeDefault { lifetime: None, .. } => return,
+
+ Scope::ObjectLifetimeDefault { lifetime: Some(l), .. } => break l,
+
+ Scope::Supertrait { s, .. } | Scope::TraitRefBoundary { s, .. } => {
+ scope = s;
+ }
+ }
+ };
+ self.insert_lifetime(lifetime_ref, lifetime.shifted(late_depth));
+ }
+
+ #[tracing::instrument(level = "debug", skip(self))]
+ fn insert_lifetime(&mut self, lifetime_ref: &'tcx hir::Lifetime, def: Region) {
+ debug!(
+ node = ?self.tcx.hir().node_to_string(lifetime_ref.hir_id),
+ span = ?self.tcx.sess.source_map().span_to_diagnostic_string(lifetime_ref.span)
+ );
+ self.map.defs.insert(lifetime_ref.hir_id, def);
+ }
+
+ /// Sometimes we resolve a lifetime, but later find that it is an
+ /// error (esp. around impl trait). In that case, we remove the
+ /// entry into `map.defs` so as not to confuse later code.
+ fn uninsert_lifetime_on_error(&mut self, lifetime_ref: &'tcx hir::Lifetime, bad_def: Region) {
+ let old_value = self.map.defs.remove(&lifetime_ref.hir_id);
+ assert_eq!(old_value, Some(bad_def));
+ }
+}
+
+/// Detects late-bound lifetimes and inserts them into
+/// `late_bound`.
+///
+/// A region declared on a fn is **late-bound** if:
+/// - it is constrained by an argument type;
+/// - it does not appear in a where-clause.
+///
+/// "Constrained" basically means that it appears in any type but
+/// not amongst the inputs to a projection. In other words, `<&'a
+/// T as Trait<''b>>::Foo` does not constrain `'a` or `'b`.
+fn is_late_bound_map(tcx: TyCtxt<'_>, def_id: LocalDefId) -> Option<&FxIndexSet<LocalDefId>> {
+ let hir_id = tcx.hir().local_def_id_to_hir_id(def_id);
+ let decl = tcx.hir().fn_decl_by_hir_id(hir_id)?;
+ let generics = tcx.hir().get_generics(def_id)?;
+
+ let mut late_bound = FxIndexSet::default();
+
+ let mut constrained_by_input = ConstrainedCollector::default();
+ for arg_ty in decl.inputs {
+ constrained_by_input.visit_ty(arg_ty);
+ }
+
+ let mut appears_in_output = AllCollector::default();
+ intravisit::walk_fn_ret_ty(&mut appears_in_output, &decl.output);
+
+ debug!(?constrained_by_input.regions);
+
+ // Walk the lifetimes that appear in where clauses.
+ //
+ // Subtle point: because we disallow nested bindings, we can just
+ // ignore binders here and scrape up all names we see.
+ let mut appears_in_where_clause = AllCollector::default();
+ appears_in_where_clause.visit_generics(generics);
+ debug!(?appears_in_where_clause.regions);
+
+ // Late bound regions are those that:
+ // - appear in the inputs
+ // - do not appear in the where-clauses
+ // - are not implicitly captured by `impl Trait`
+ for param in generics.params {
+ match param.kind {
+ hir::GenericParamKind::Lifetime { .. } => { /* fall through */ }
+
+ // Neither types nor consts are late-bound.
+ hir::GenericParamKind::Type { .. } | hir::GenericParamKind::Const { .. } => continue,
+ }
+
+ let param_def_id = tcx.hir().local_def_id(param.hir_id);
+
+ // appears in the where clauses? early-bound.
+ if appears_in_where_clause.regions.contains(&param_def_id) {
+ continue;
+ }
+
+ // does not appear in the inputs, but appears in the return type? early-bound.
+ if !constrained_by_input.regions.contains(&param_def_id)
+ && appears_in_output.regions.contains(&param_def_id)
+ {
+ continue;
+ }
+
+ debug!("lifetime {:?} with id {:?} is late-bound", param.name.ident(), param.hir_id);
+
+ let inserted = late_bound.insert(param_def_id);
+ assert!(inserted, "visited lifetime {:?} twice", param.hir_id);
+ }
+
+ debug!(?late_bound);
+ return Some(tcx.arena.alloc(late_bound));
+
+ #[derive(Default)]
+ struct ConstrainedCollector {
+ regions: FxHashSet<LocalDefId>,
+ }
+
+ impl<'v> Visitor<'v> for ConstrainedCollector {
+ fn visit_ty(&mut self, ty: &'v hir::Ty<'v>) {
+ match ty.kind {
+ hir::TyKind::Path(
+ hir::QPath::Resolved(Some(_), _) | hir::QPath::TypeRelative(..),
+ ) => {
+ // ignore lifetimes appearing in associated type
+ // projections, as they are not *constrained*
+ // (defined above)
+ }
+
+ hir::TyKind::Path(hir::QPath::Resolved(None, ref path)) => {
+ // consider only the lifetimes on the final
+ // segment; I am not sure it's even currently
+ // valid to have them elsewhere, but even if it
+ // is, those would be potentially inputs to
+ // projections
+ if let Some(last_segment) = path.segments.last() {
+ self.visit_path_segment(path.span, last_segment);
+ }
+ }
+
+ _ => {
+ intravisit::walk_ty(self, ty);
+ }
+ }
+ }
+
+ fn visit_lifetime(&mut self, lifetime_ref: &'v hir::Lifetime) {
+ if let hir::LifetimeName::Param(def_id, _) = lifetime_ref.name {
+ self.regions.insert(def_id);
+ }
+ }
+ }
+
+ #[derive(Default)]
+ struct AllCollector {
+ regions: FxHashSet<LocalDefId>,
+ }
+
+ impl<'v> Visitor<'v> for AllCollector {
+ fn visit_lifetime(&mut self, lifetime_ref: &'v hir::Lifetime) {
+ if let hir::LifetimeName::Param(def_id, _) = lifetime_ref.name {
+ self.regions.insert(def_id);
+ }
+ }
+ }
+}