1 // ignore-tidy-filelength
2 //! "Late resolution" is the pass that resolves most of names in a crate beside imports and macros.
3 //! It runs when the crate is fully expanded and its module structure is fully built.
4 //! So it just walks through the crate and resolves all the expressions, types, etc.
6 //! If you wonder why there's no `early.rs`, that's because it's split into three files -
7 //! `build_reduced_graph.rs`, `macros.rs` and `imports.rs`.
11 use crate::{path_names_to_string, BindingError, Finalize, LexicalScopeBinding};
12 use crate::{Module, ModuleOrUniformRoot, NameBinding, ParentScope, PathResult};
13 use crate::{ResolutionError, Resolver, Segment, UseError};
15 use rustc_ast::ptr::P;
16 use rustc_ast::visit::{self, AssocCtxt, BoundKind, FnCtxt, FnKind, Visitor};
18 use rustc_data_structures::fx::{FxHashMap, FxHashSet, FxIndexMap};
19 use rustc_errors::DiagnosticId;
20 use rustc_hir::def::Namespace::{self, *};
21 use rustc_hir::def::{self, CtorKind, DefKind, LifetimeRes, PartialRes, PerNS};
22 use rustc_hir::def_id::{DefId, LocalDefId, CRATE_DEF_ID};
23 use rustc_hir::{PrimTy, TraitCandidate};
24 use rustc_middle::middle::resolve_lifetime::Set1;
25 use rustc_middle::ty::DefIdTree;
26 use rustc_middle::{bug, span_bug};
27 use rustc_session::lint;
28 use rustc_span::symbol::{kw, sym, Ident, Symbol};
29 use rustc_span::{BytePos, Span};
30 use smallvec::{smallvec, SmallVec};
32 use rustc_span::source_map::{respan, Spanned};
33 use std::collections::{hash_map::Entry, BTreeSet};
34 use std::mem::{replace, take};
38 pub(crate) mod lifetimes;
40 type Res = def::Res<NodeId>;
42 type IdentMap<T> = FxHashMap<Ident, T>;
44 /// Map from the name in a pattern to its binding mode.
45 type BindingMap = IdentMap<BindingInfo>;
48 ElisionFnParameter, LifetimeElisionCandidate, MissingLifetime, MissingLifetimeKind,
51 #[derive(Copy, Clone, Debug)]
54 binding_mode: BindingMode,
57 #[derive(Copy, Clone, PartialEq, Eq, Debug)]
58 pub enum PatternSource {
65 #[derive(Copy, Clone, Debug, PartialEq, Eq)]
72 pub fn descr(self) -> &'static str {
74 PatternSource::Match => "match binding",
75 PatternSource::Let => "let binding",
76 PatternSource::For => "for binding",
77 PatternSource::FnParam => "function parameter",
82 /// Denotes whether the context for the set of already bound bindings is a `Product`
83 /// or `Or` context. This is used in e.g., `fresh_binding` and `resolve_pattern_inner`.
84 /// See those functions for more information.
87 /// A product pattern context, e.g., `Variant(a, b)`.
89 /// An or-pattern context, e.g., `p_0 | ... | p_n`.
93 /// Does this the item (from the item rib scope) allow generic parameters?
94 #[derive(Copy, Clone, Debug)]
95 pub(crate) enum HasGenericParams {
100 /// May this constant have generics?
101 #[derive(Copy, Clone, Debug, Eq, PartialEq)]
102 pub(crate) enum ConstantHasGenerics {
107 impl ConstantHasGenerics {
108 fn force_yes_if(self, b: bool) -> Self {
109 if b { Self::Yes } else { self }
113 #[derive(Copy, Clone, Debug, Eq, PartialEq)]
114 pub(crate) enum ConstantItemKind {
119 /// The rib kind restricts certain accesses,
120 /// e.g. to a `Res::Local` of an outer item.
121 #[derive(Copy, Clone, Debug)]
122 pub(crate) enum RibKind<'a> {
123 /// No restriction needs to be applied.
126 /// We passed through an impl or trait and are now in one of its
127 /// methods or associated types. Allow references to ty params that impl or trait
128 /// binds. Disallow any other upvars (including other ty params that are
132 /// We passed through a closure. Disallow labels.
133 ClosureOrAsyncRibKind,
135 /// We passed through an item scope. Disallow upvars.
136 ItemRibKind(HasGenericParams),
138 /// We're in a constant item. Can't refer to dynamic stuff.
140 /// The item may reference generic parameters in trivial constant expressions.
141 /// All other constants aren't allowed to use generic params at all.
142 ConstantItemRibKind(ConstantHasGenerics, Option<(Ident, ConstantItemKind)>),
144 /// We passed through a module.
145 ModuleRibKind(Module<'a>),
147 /// We passed through a `macro_rules!` statement
148 MacroDefinition(DefId),
150 /// All bindings in this rib are generic parameters that can't be used
151 /// from the default of a generic parameter because they're not declared
152 /// before said generic parameter. Also see the `visit_generics` override.
153 ForwardGenericParamBanRibKind,
155 /// We are inside of the type of a const parameter. Can't refer to any
159 /// We are inside a `sym` inline assembly operand. Can only refer to
165 /// Whether this rib kind contains generic parameters, as opposed to local
167 pub(crate) fn contains_params(&self) -> bool {
170 | ClosureOrAsyncRibKind
171 | ConstantItemRibKind(..)
174 | ConstParamTyRibKind
175 | InlineAsmSymRibKind => false,
176 AssocItemRibKind | ItemRibKind(_) | ForwardGenericParamBanRibKind => true,
180 /// This rib forbids referring to labels defined in upwards ribs.
181 fn is_label_barrier(self) -> bool {
183 NormalRibKind | MacroDefinition(..) => false,
186 | ClosureOrAsyncRibKind
188 | ConstantItemRibKind(..)
190 | ForwardGenericParamBanRibKind
191 | ConstParamTyRibKind
192 | InlineAsmSymRibKind => true,
197 /// A single local scope.
199 /// A rib represents a scope names can live in. Note that these appear in many places, not just
200 /// around braces. At any place where the list of accessible names (of the given namespace)
201 /// changes or a new restrictions on the name accessibility are introduced, a new rib is put onto a
202 /// stack. This may be, for example, a `let` statement (because it introduces variables), a macro,
205 /// Different [rib kinds](enum@RibKind) are transparent for different names.
207 /// The resolution keeps a separate stack of ribs as it traverses the AST for each namespace. When
208 /// resolving, the name is looked up from inside out.
210 pub(crate) struct Rib<'a, R = Res> {
211 pub bindings: IdentMap<R>,
212 pub kind: RibKind<'a>,
215 impl<'a, R> Rib<'a, R> {
216 fn new(kind: RibKind<'a>) -> Rib<'a, R> {
217 Rib { bindings: Default::default(), kind }
221 #[derive(Clone, Copy, Debug)]
222 enum LifetimeUseSet {
223 One { use_span: Span, use_ctxt: visit::LifetimeCtxt },
227 #[derive(Copy, Clone, Debug)]
228 enum LifetimeRibKind {
229 /// This rib acts as a barrier to forbid reference to lifetimes of a parent item.
232 /// This rib declares generic parameters.
233 Generics { binder: NodeId, span: Span, kind: LifetimeBinderKind },
235 /// FIXME(const_generics): This patches over an ICE caused by non-'static lifetimes in const
236 /// generics. We are disallowing this until we can decide on how we want to handle non-'static
237 /// lifetimes in const generics. See issue #74052 for discussion.
240 /// Non-static lifetimes are prohibited in anonymous constants under `min_const_generics`.
241 /// This function will emit an error if `generic_const_exprs` is not enabled, the body identified by
242 /// `body_id` is an anonymous constant and `lifetime_ref` is non-static.
245 /// Create a new anonymous lifetime parameter and reference it.
247 /// If `report_in_path`, report an error when encountering lifetime elision in a path:
249 /// struct Foo<'a> { x: &'a () }
250 /// async fn foo(x: Foo) {}
253 /// Note: the error should not trigger when the elided lifetime is in a pattern or
254 /// expression-position path:
256 /// struct Foo<'a> { x: &'a () }
257 /// async fn foo(Foo { x: _ }: Foo<'_>) {}
259 AnonymousCreateParameter { binder: NodeId, report_in_path: bool },
261 /// Give a hard error when either `&` or `'_` is written. Used to
262 /// rule out things like `where T: Foo<'_>`. Does not imply an
263 /// error on default object bounds (e.g., `Box<dyn Foo>`).
264 AnonymousReportError,
266 /// Replace all anonymous lifetimes by provided lifetime.
269 /// Signal we cannot find which should be the anonymous lifetime.
273 #[derive(Copy, Clone, Debug)]
274 enum LifetimeBinderKind {
284 impl LifetimeBinderKind {
285 fn descr(self) -> &'static str {
286 use LifetimeBinderKind::*;
288 BareFnType => "type",
289 PolyTrait => "bound",
290 WhereBound => "bound",
292 ImplBlock => "impl block",
293 Function => "function",
294 Closure => "closure",
301 kind: LifetimeRibKind,
302 // We need to preserve insertion order for async fns.
303 bindings: FxIndexMap<Ident, (NodeId, LifetimeRes)>,
307 fn new(kind: LifetimeRibKind) -> LifetimeRib {
308 LifetimeRib { bindings: Default::default(), kind }
312 #[derive(Copy, Clone, PartialEq, Eq, Debug)]
313 pub(crate) enum AliasPossibility {
318 #[derive(Copy, Clone, Debug)]
319 pub(crate) enum PathSource<'a> {
320 // Type paths `Path`.
322 // Trait paths in bounds or impls.
323 Trait(AliasPossibility),
324 // Expression paths `path`, with optional parent context.
325 Expr(Option<&'a Expr>),
326 // Paths in path patterns `Path`.
328 // Paths in struct expressions and patterns `Path { .. }`.
330 // Paths in tuple struct patterns `Path(..)`.
331 TupleStruct(Span, &'a [Span]),
332 // `m::A::B` in `<T as m::A>::B::C`.
333 TraitItem(Namespace),
336 impl<'a> PathSource<'a> {
337 fn namespace(self) -> Namespace {
339 PathSource::Type | PathSource::Trait(_) | PathSource::Struct => TypeNS,
340 PathSource::Expr(..) | PathSource::Pat | PathSource::TupleStruct(..) => ValueNS,
341 PathSource::TraitItem(ns) => ns,
345 fn defer_to_typeck(self) -> bool {
348 | PathSource::Expr(..)
351 | PathSource::TupleStruct(..) => true,
352 PathSource::Trait(_) | PathSource::TraitItem(..) => false,
356 fn descr_expected(self) -> &'static str {
358 PathSource::Type => "type",
359 PathSource::Trait(_) => "trait",
360 PathSource::Pat => "unit struct, unit variant or constant",
361 PathSource::Struct => "struct, variant or union type",
362 PathSource::TupleStruct(..) => "tuple struct or tuple variant",
363 PathSource::TraitItem(ns) => match ns {
364 TypeNS => "associated type",
365 ValueNS => "method or associated constant",
366 MacroNS => bug!("associated macro"),
368 PathSource::Expr(parent) => match parent.as_ref().map(|p| &p.kind) {
369 // "function" here means "anything callable" rather than `DefKind::Fn`,
370 // this is not precise but usually more helpful than just "value".
371 Some(ExprKind::Call(call_expr, _)) => match &call_expr.kind {
372 // the case of `::some_crate()`
373 ExprKind::Path(_, path)
374 if path.segments.len() == 2
375 && path.segments[0].ident.name == kw::PathRoot =>
379 ExprKind::Path(_, path) => {
380 let mut msg = "function";
381 if let Some(segment) = path.segments.iter().last() {
382 if let Some(c) = segment.ident.to_string().chars().next() {
383 if c.is_uppercase() {
384 msg = "function, tuple struct or tuple variant";
397 fn is_call(self) -> bool {
398 matches!(self, PathSource::Expr(Some(&Expr { kind: ExprKind::Call(..), .. })))
401 pub(crate) fn is_expected(self, res: Res) -> bool {
403 PathSource::Type => matches!(
410 | DefKind::TraitAlias
415 | DefKind::ForeignTy,
420 PathSource::Trait(AliasPossibility::No) => matches!(res, Res::Def(DefKind::Trait, _)),
421 PathSource::Trait(AliasPossibility::Maybe) => {
422 matches!(res, Res::Def(DefKind::Trait | DefKind::TraitAlias, _))
424 PathSource::Expr(..) => matches!(
427 DefKind::Ctor(_, CtorKind::Const | CtorKind::Fn)
432 | DefKind::AssocConst
433 | DefKind::ConstParam,
439 res.expected_in_unit_struct_pat()
440 || matches!(res, Res::Def(DefKind::Const | DefKind::AssocConst, _))
442 PathSource::TupleStruct(..) => res.expected_in_tuple_struct_pat(),
443 PathSource::Struct => matches!(
452 ) | Res::SelfTy { .. }
454 PathSource::TraitItem(ns) => match res {
455 Res::Def(DefKind::AssocConst | DefKind::AssocFn, _) if ns == ValueNS => true,
456 Res::Def(DefKind::AssocTy, _) if ns == TypeNS => true,
462 fn error_code(self, has_unexpected_resolution: bool) -> DiagnosticId {
463 use rustc_errors::error_code;
464 match (self, has_unexpected_resolution) {
465 (PathSource::Trait(_), true) => error_code!(E0404),
466 (PathSource::Trait(_), false) => error_code!(E0405),
467 (PathSource::Type, true) => error_code!(E0573),
468 (PathSource::Type, false) => error_code!(E0412),
469 (PathSource::Struct, true) => error_code!(E0574),
470 (PathSource::Struct, false) => error_code!(E0422),
471 (PathSource::Expr(..), true) => error_code!(E0423),
472 (PathSource::Expr(..), false) => error_code!(E0425),
473 (PathSource::Pat | PathSource::TupleStruct(..), true) => error_code!(E0532),
474 (PathSource::Pat | PathSource::TupleStruct(..), false) => error_code!(E0531),
475 (PathSource::TraitItem(..), true) => error_code!(E0575),
476 (PathSource::TraitItem(..), false) => error_code!(E0576),
482 struct DiagnosticMetadata<'ast> {
483 /// The current trait's associated items' ident, used for diagnostic suggestions.
484 current_trait_assoc_items: Option<&'ast [P<AssocItem>]>,
486 /// The current self type if inside an impl (used for better errors).
487 current_self_type: Option<Ty>,
489 /// The current self item if inside an ADT (used for better errors).
490 current_self_item: Option<NodeId>,
492 /// The current trait (used to suggest).
493 current_item: Option<&'ast Item>,
495 /// When processing generics and encountering a type not found, suggest introducing a type
497 currently_processing_generics: bool,
499 /// The current enclosing (non-closure) function (used for better errors).
500 current_function: Option<(FnKind<'ast>, Span)>,
502 /// A list of labels as of yet unused. Labels will be removed from this map when
503 /// they are used (in a `break` or `continue` statement)
504 unused_labels: FxHashMap<NodeId, Span>,
506 /// Only used for better errors on `fn(): fn()`.
507 current_type_ascription: Vec<Span>,
509 /// Only used for better errors on `let x = { foo: bar };`.
510 /// In the case of a parse error with `let x = { foo: bar, };`, this isn't needed, it's only
511 /// needed for cases where this parses as a correct type ascription.
512 current_block_could_be_bare_struct_literal: Option<Span>,
514 /// Only used for better errors on `let <pat>: <expr, not type>;`.
515 current_let_binding: Option<(Span, Option<Span>, Option<Span>)>,
517 /// Used to detect possible `if let` written without `let` and to provide structured suggestion.
518 in_if_condition: Option<&'ast Expr>,
520 /// If we are currently in a trait object definition. Used to point at the bounds when
521 /// encountering a struct or enum.
522 current_trait_object: Option<&'ast [ast::GenericBound]>,
524 /// Given `where <T as Bar>::Baz: String`, suggest `where T: Bar<Baz = String>`.
525 current_where_predicate: Option<&'ast WherePredicate>,
527 current_type_path: Option<&'ast Ty>,
529 /// The current impl items (used to suggest).
530 current_impl_items: Option<&'ast [P<AssocItem>]>,
532 /// When processing impl trait
533 currently_processing_impl_trait: Option<(TraitRef, Ty)>,
535 /// Accumulate the errors due to missed lifetime elision,
536 /// and report them all at once for each function.
537 current_elision_failures: Vec<MissingLifetime>,
540 struct LateResolutionVisitor<'a, 'b, 'ast> {
541 r: &'b mut Resolver<'a>,
543 /// The module that represents the current item scope.
544 parent_scope: ParentScope<'a>,
546 /// The current set of local scopes for types and values.
547 /// FIXME #4948: Reuse ribs to avoid allocation.
548 ribs: PerNS<Vec<Rib<'a>>>,
550 /// The current set of local scopes, for labels.
551 label_ribs: Vec<Rib<'a, NodeId>>,
553 /// The current set of local scopes for lifetimes.
554 lifetime_ribs: Vec<LifetimeRib>,
556 /// We are looking for lifetimes in an elision context.
557 /// The set contains all the resolutions that we encountered so far.
558 /// They will be used to determine the correct lifetime for the fn return type.
559 /// The `LifetimeElisionCandidate` is used for diagnostics, to suggest introducing named
561 lifetime_elision_candidates: Option<FxIndexMap<LifetimeRes, LifetimeElisionCandidate>>,
563 /// The trait that the current context can refer to.
564 current_trait_ref: Option<(Module<'a>, TraitRef)>,
566 /// Fields used to add information to diagnostic errors.
567 diagnostic_metadata: Box<DiagnosticMetadata<'ast>>,
569 /// State used to know whether to ignore resolution errors for function bodies.
571 /// In particular, rustdoc uses this to avoid giving errors for `cfg()` items.
572 /// In most cases this will be `None`, in which case errors will always be reported.
573 /// If it is `true`, then it will be updated when entering a nested function or trait body.
576 /// Count the number of places a lifetime is used.
577 lifetime_uses: FxHashMap<LocalDefId, LifetimeUseSet>,
580 /// Walks the whole crate in DFS order, visiting each item, resolving names as it goes.
581 impl<'a: 'ast, 'ast> Visitor<'ast> for LateResolutionVisitor<'a, '_, 'ast> {
582 fn visit_attribute(&mut self, _: &'ast Attribute) {
583 // We do not want to resolve expressions that appear in attributes,
584 // as they do not correspond to actual code.
586 fn visit_item(&mut self, item: &'ast Item) {
587 let prev = replace(&mut self.diagnostic_metadata.current_item, Some(item));
588 // Always report errors in items we just entered.
589 let old_ignore = replace(&mut self.in_func_body, false);
590 self.with_lifetime_rib(LifetimeRibKind::Item, |this| this.resolve_item(item));
591 self.in_func_body = old_ignore;
592 self.diagnostic_metadata.current_item = prev;
594 fn visit_arm(&mut self, arm: &'ast Arm) {
595 self.resolve_arm(arm);
597 fn visit_block(&mut self, block: &'ast Block) {
598 self.resolve_block(block);
600 fn visit_anon_const(&mut self, constant: &'ast AnonConst) {
601 // We deal with repeat expressions explicitly in `resolve_expr`.
602 self.with_lifetime_rib(LifetimeRibKind::AnonConst, |this| {
603 this.with_lifetime_rib(LifetimeRibKind::Elided(LifetimeRes::Static), |this| {
604 this.resolve_anon_const(constant, IsRepeatExpr::No);
608 fn visit_expr(&mut self, expr: &'ast Expr) {
609 self.resolve_expr(expr, None);
611 fn visit_local(&mut self, local: &'ast Local) {
612 let local_spans = match local.pat.kind {
613 // We check for this to avoid tuple struct fields.
614 PatKind::Wild => None,
617 local.ty.as_ref().map(|ty| ty.span),
618 local.kind.init().map(|init| init.span),
621 let original = replace(&mut self.diagnostic_metadata.current_let_binding, local_spans);
622 self.resolve_local(local);
623 self.diagnostic_metadata.current_let_binding = original;
625 fn visit_ty(&mut self, ty: &'ast Ty) {
626 let prev = self.diagnostic_metadata.current_trait_object;
627 let prev_ty = self.diagnostic_metadata.current_type_path;
629 TyKind::Rptr(None, _) => {
630 // Elided lifetime in reference: we resolve as if there was some lifetime `'_` with
632 // This span will be used in case of elision failure.
633 let span = self.r.session.source_map().start_point(ty.span);
634 self.resolve_elided_lifetime(ty.id, span);
635 visit::walk_ty(self, ty);
637 TyKind::Path(ref qself, ref path) => {
638 self.diagnostic_metadata.current_type_path = Some(ty);
639 self.smart_resolve_path(ty.id, qself.as_ref(), path, PathSource::Type);
641 // Check whether we should interpret this as a bare trait object.
643 && let Some(partial_res) = self.r.partial_res_map.get(&ty.id)
644 && partial_res.unresolved_segments() == 0
645 && let Res::Def(DefKind::Trait | DefKind::TraitAlias, _) = partial_res.base_res()
647 // This path is actually a bare trait object. In case of a bare `Fn`-trait
648 // object with anonymous lifetimes, we need this rib to correctly place the
649 // synthetic lifetimes.
650 let span = ty.span.shrink_to_lo().to(path.span.shrink_to_lo());
651 self.with_generic_param_rib(
654 LifetimeRibKind::Generics {
656 kind: LifetimeBinderKind::PolyTrait,
659 |this| this.visit_path(&path, ty.id),
662 visit::walk_ty(self, ty)
665 TyKind::ImplicitSelf => {
666 let self_ty = Ident::with_dummy_span(kw::SelfUpper);
668 .resolve_ident_in_lexical_scope(
671 Some(Finalize::new(ty.id, ty.span)),
674 .map_or(Res::Err, |d| d.res());
675 self.r.record_partial_res(ty.id, PartialRes::new(res));
676 visit::walk_ty(self, ty)
678 TyKind::ImplTrait(..) => {
679 let candidates = self.lifetime_elision_candidates.take();
680 visit::walk_ty(self, ty);
681 self.lifetime_elision_candidates = candidates;
683 TyKind::TraitObject(ref bounds, ..) => {
684 self.diagnostic_metadata.current_trait_object = Some(&bounds[..]);
685 visit::walk_ty(self, ty)
687 TyKind::BareFn(ref bare_fn) => {
688 let span = ty.span.shrink_to_lo().to(bare_fn.decl_span.shrink_to_lo());
689 self.with_generic_param_rib(
690 &bare_fn.generic_params,
692 LifetimeRibKind::Generics {
694 kind: LifetimeBinderKind::BareFnType,
698 this.visit_generic_params(&bare_fn.generic_params, false);
699 this.with_lifetime_rib(
700 LifetimeRibKind::AnonymousCreateParameter {
702 report_in_path: false,
705 this.resolve_fn_signature(
708 // We don't need to deal with patterns in parameters, because
709 // they are not possible for foreign or bodiless functions.
714 .map(|Param { ty, .. }| (None, &**ty)),
715 &bare_fn.decl.output,
722 _ => visit::walk_ty(self, ty),
724 self.diagnostic_metadata.current_trait_object = prev;
725 self.diagnostic_metadata.current_type_path = prev_ty;
727 fn visit_poly_trait_ref(&mut self, tref: &'ast PolyTraitRef) {
728 let span = tref.span.shrink_to_lo().to(tref.trait_ref.path.span.shrink_to_lo());
729 self.with_generic_param_rib(
730 &tref.bound_generic_params,
732 LifetimeRibKind::Generics {
733 binder: tref.trait_ref.ref_id,
734 kind: LifetimeBinderKind::PolyTrait,
738 this.visit_generic_params(&tref.bound_generic_params, false);
739 this.smart_resolve_path(
740 tref.trait_ref.ref_id,
742 &tref.trait_ref.path,
743 PathSource::Trait(AliasPossibility::Maybe),
745 this.visit_trait_ref(&tref.trait_ref);
749 fn visit_foreign_item(&mut self, foreign_item: &'ast ForeignItem) {
750 match foreign_item.kind {
751 ForeignItemKind::TyAlias(box TyAlias { ref generics, .. }) => {
752 self.with_lifetime_rib(LifetimeRibKind::Item, |this| {
753 this.with_generic_param_rib(
755 ItemRibKind(HasGenericParams::Yes(generics.span)),
756 LifetimeRibKind::Generics {
757 binder: foreign_item.id,
758 kind: LifetimeBinderKind::Item,
761 |this| visit::walk_foreign_item(this, foreign_item),
765 ForeignItemKind::Fn(box Fn { ref generics, .. }) => {
766 self.with_lifetime_rib(LifetimeRibKind::Item, |this| {
767 this.with_generic_param_rib(
769 ItemRibKind(HasGenericParams::Yes(generics.span)),
770 LifetimeRibKind::Generics {
771 binder: foreign_item.id,
772 kind: LifetimeBinderKind::Function,
775 |this| visit::walk_foreign_item(this, foreign_item),
779 ForeignItemKind::Static(..) => {
780 self.with_item_rib(|this| {
781 visit::walk_foreign_item(this, foreign_item);
784 ForeignItemKind::MacCall(..) => {
785 panic!("unexpanded macro in resolve!")
789 fn visit_fn(&mut self, fn_kind: FnKind<'ast>, sp: Span, fn_id: NodeId) {
790 let previous_value = self.diagnostic_metadata.current_function;
792 // Bail if the function is foreign, and thus cannot validly have
793 // a body, or if there's no body for some other reason.
794 FnKind::Fn(FnCtxt::Foreign, _, sig, _, generics, _)
795 | FnKind::Fn(_, _, sig, _, generics, None) => {
796 self.visit_fn_header(&sig.header);
797 self.visit_generics(generics);
798 self.with_lifetime_rib(
799 LifetimeRibKind::AnonymousCreateParameter {
801 report_in_path: false,
804 this.resolve_fn_signature(
807 sig.decl.inputs.iter().map(|Param { ty, .. }| (None, &**ty)),
815 self.diagnostic_metadata.current_function = Some((fn_kind, sp));
817 // Do not update `current_function` for closures: it suggests `self` parameters.
818 FnKind::Closure(..) => {}
820 debug!("(resolving function) entering function");
822 // Create a value rib for the function.
823 self.with_rib(ValueNS, ClosureOrAsyncRibKind, |this| {
824 // Create a label rib for the function.
825 this.with_label_rib(ClosureOrAsyncRibKind, |this| {
827 FnKind::Fn(_, _, sig, _, generics, body) => {
828 this.visit_generics(generics);
830 let declaration = &sig.decl;
831 let async_node_id = sig.header.asyncness.opt_return_id();
833 this.with_lifetime_rib(
834 LifetimeRibKind::AnonymousCreateParameter {
836 report_in_path: async_node_id.is_some(),
839 this.resolve_fn_signature(
841 declaration.has_self(),
845 .map(|Param { pat, ty, .. }| (Some(&**pat), &**ty)),
851 // Construct the list of in-scope lifetime parameters for async lowering.
852 // We include all lifetime parameters, either named or "Fresh".
853 // The order of those parameters does not matter, as long as it is
855 if let Some(async_node_id) = async_node_id {
856 let mut extra_lifetime_params = this
858 .extra_lifetime_params_map
861 .unwrap_or_default();
862 for rib in this.lifetime_ribs.iter().rev() {
863 extra_lifetime_params.extend(
866 .map(|(&ident, &(node_id, res))| (ident, node_id, res)),
869 LifetimeRibKind::Item => break,
870 LifetimeRibKind::AnonymousCreateParameter {
873 if let Some(earlier_fresh) =
874 this.r.extra_lifetime_params_map.get(&binder)
876 extra_lifetime_params.extend(earlier_fresh);
883 .extra_lifetime_params_map
884 .insert(async_node_id, extra_lifetime_params);
887 if let Some(body) = body {
888 // Ignore errors in function bodies if this is rustdoc
889 // Be sure not to set this until the function signature has been resolved.
890 let previous_state = replace(&mut this.in_func_body, true);
891 // Resolve the function body, potentially inside the body of an async closure
892 this.with_lifetime_rib(
893 LifetimeRibKind::Elided(LifetimeRes::Infer),
894 |this| this.visit_block(body),
897 debug!("(resolving function) leaving function");
898 this.in_func_body = previous_state;
901 FnKind::Closure(binder, declaration, body) => {
902 this.visit_closure_binder(binder);
904 this.with_lifetime_rib(
906 // We do not have any explicit generic lifetime parameter.
907 ClosureBinder::NotPresent => {
908 LifetimeRibKind::AnonymousCreateParameter {
910 report_in_path: false,
913 ClosureBinder::For { .. } => LifetimeRibKind::AnonymousReportError,
915 // Add each argument to the rib.
916 |this| this.resolve_params(&declaration.inputs),
918 this.with_lifetime_rib(
920 ClosureBinder::NotPresent => {
921 LifetimeRibKind::Elided(LifetimeRes::Infer)
923 ClosureBinder::For { .. } => LifetimeRibKind::AnonymousReportError,
925 |this| visit::walk_fn_ret_ty(this, &declaration.output),
928 // Ignore errors in function bodies if this is rustdoc
929 // Be sure not to set this until the function signature has been resolved.
930 let previous_state = replace(&mut this.in_func_body, true);
931 // Resolve the function body, potentially inside the body of an async closure
932 this.with_lifetime_rib(
933 LifetimeRibKind::Elided(LifetimeRes::Infer),
934 |this| this.visit_expr(body),
937 debug!("(resolving function) leaving function");
938 this.in_func_body = previous_state;
943 self.diagnostic_metadata.current_function = previous_value;
945 fn visit_lifetime(&mut self, lifetime: &'ast Lifetime, use_ctxt: visit::LifetimeCtxt) {
946 self.resolve_lifetime(lifetime, use_ctxt)
949 fn visit_generics(&mut self, generics: &'ast Generics) {
950 self.visit_generic_params(
952 self.diagnostic_metadata.current_self_item.is_some(),
954 for p in &generics.where_clause.predicates {
955 self.visit_where_predicate(p);
959 fn visit_closure_binder(&mut self, b: &'ast ClosureBinder) {
961 ClosureBinder::NotPresent => {}
962 ClosureBinder::For { generic_params, .. } => {
963 self.visit_generic_params(
965 self.diagnostic_metadata.current_self_item.is_some(),
971 fn visit_generic_arg(&mut self, arg: &'ast GenericArg) {
972 debug!("visit_generic_arg({:?})", arg);
973 let prev = replace(&mut self.diagnostic_metadata.currently_processing_generics, true);
975 GenericArg::Type(ref ty) => {
976 // We parse const arguments as path types as we cannot distinguish them during
977 // parsing. We try to resolve that ambiguity by attempting resolution the type
978 // namespace first, and if that fails we try again in the value namespace. If
979 // resolution in the value namespace succeeds, we have an generic const argument on
981 if let TyKind::Path(ref qself, ref path) = ty.kind {
982 // We cannot disambiguate multi-segment paths right now as that requires type
984 if path.segments.len() == 1 && path.segments[0].args.is_none() {
985 let mut check_ns = |ns| {
986 self.maybe_resolve_ident_in_lexical_scope(path.segments[0].ident, ns)
989 if !check_ns(TypeNS) && check_ns(ValueNS) {
990 // This must be equivalent to `visit_anon_const`, but we cannot call it
991 // directly due to visitor lifetimes so we have to copy-paste some code.
993 // Note that we might not be inside of an repeat expression here,
994 // but considering that `IsRepeatExpr` is only relevant for
995 // non-trivial constants this is doesn't matter.
996 self.with_constant_rib(
998 ConstantHasGenerics::Yes,
1001 this.smart_resolve_path(
1005 PathSource::Expr(None),
1008 if let Some(ref qself) = *qself {
1009 this.visit_ty(&qself.ty);
1011 this.visit_path(path, ty.id);
1015 self.diagnostic_metadata.currently_processing_generics = prev;
1023 GenericArg::Lifetime(lt) => self.visit_lifetime(lt, visit::LifetimeCtxt::GenericArg),
1024 GenericArg::Const(ct) => self.visit_anon_const(ct),
1026 self.diagnostic_metadata.currently_processing_generics = prev;
1029 fn visit_assoc_constraint(&mut self, constraint: &'ast AssocConstraint) {
1030 self.visit_ident(constraint.ident);
1031 if let Some(ref gen_args) = constraint.gen_args {
1032 // Forbid anonymous lifetimes in GAT parameters until proper semantics are decided.
1033 self.with_lifetime_rib(LifetimeRibKind::AnonymousReportError, |this| {
1034 this.visit_generic_args(gen_args.span(), gen_args)
1037 match constraint.kind {
1038 AssocConstraintKind::Equality { ref term } => match term {
1039 Term::Ty(ty) => self.visit_ty(ty),
1040 Term::Const(c) => self.visit_anon_const(c),
1042 AssocConstraintKind::Bound { ref bounds } => {
1043 walk_list!(self, visit_param_bound, bounds, BoundKind::Bound);
1048 fn visit_path_segment(&mut self, path_span: Span, path_segment: &'ast PathSegment) {
1049 if let Some(ref args) = path_segment.args {
1051 GenericArgs::AngleBracketed(..) => visit::walk_generic_args(self, path_span, args),
1052 GenericArgs::Parenthesized(p_args) => {
1053 // Probe the lifetime ribs to know how to behave.
1054 for rib in self.lifetime_ribs.iter().rev() {
1056 // We are inside a `PolyTraitRef`. The lifetimes are
1057 // to be intoduced in that (maybe implicit) `for<>` binder.
1058 LifetimeRibKind::Generics {
1060 kind: LifetimeBinderKind::PolyTrait,
1063 self.with_lifetime_rib(
1064 LifetimeRibKind::AnonymousCreateParameter {
1066 report_in_path: false,
1069 this.resolve_fn_signature(
1072 p_args.inputs.iter().map(|ty| (None, &**ty)),
1079 // We have nowhere to introduce generics. Code is malformed,
1080 // so use regular lifetime resolution to avoid spurious errors.
1081 LifetimeRibKind::Item | LifetimeRibKind::Generics { .. } => {
1082 visit::walk_generic_args(self, path_span, args);
1085 LifetimeRibKind::AnonymousCreateParameter { .. }
1086 | LifetimeRibKind::AnonymousReportError
1087 | LifetimeRibKind::Elided(_)
1088 | LifetimeRibKind::ElisionFailure
1089 | LifetimeRibKind::AnonConst
1090 | LifetimeRibKind::ConstGeneric => {}
1098 fn visit_where_predicate(&mut self, p: &'ast WherePredicate) {
1099 debug!("visit_where_predicate {:?}", p);
1100 let previous_value =
1101 replace(&mut self.diagnostic_metadata.current_where_predicate, Some(p));
1102 self.with_lifetime_rib(LifetimeRibKind::AnonymousReportError, |this| {
1103 if let WherePredicate::BoundPredicate(WhereBoundPredicate {
1106 ref bound_generic_params,
1107 span: predicate_span,
1111 let span = predicate_span.shrink_to_lo().to(bounded_ty.span.shrink_to_lo());
1112 this.with_generic_param_rib(
1113 &bound_generic_params,
1115 LifetimeRibKind::Generics {
1116 binder: bounded_ty.id,
1117 kind: LifetimeBinderKind::WhereBound,
1121 this.visit_generic_params(&bound_generic_params, false);
1122 this.visit_ty(bounded_ty);
1123 for bound in bounds {
1124 this.visit_param_bound(bound, BoundKind::Bound)
1129 visit::walk_where_predicate(this, p);
1132 self.diagnostic_metadata.current_where_predicate = previous_value;
1135 fn visit_inline_asm(&mut self, asm: &'ast InlineAsm) {
1136 for (op, _) in &asm.operands {
1138 InlineAsmOperand::In { expr, .. }
1139 | InlineAsmOperand::Out { expr: Some(expr), .. }
1140 | InlineAsmOperand::InOut { expr, .. } => self.visit_expr(expr),
1141 InlineAsmOperand::Out { expr: None, .. } => {}
1142 InlineAsmOperand::SplitInOut { in_expr, out_expr, .. } => {
1143 self.visit_expr(in_expr);
1144 if let Some(out_expr) = out_expr {
1145 self.visit_expr(out_expr);
1148 InlineAsmOperand::Const { anon_const, .. } => {
1149 // Although this is `DefKind::AnonConst`, it is allowed to reference outer
1150 // generic parameters like an inline const.
1151 self.resolve_inline_const(anon_const);
1153 InlineAsmOperand::Sym { sym } => self.visit_inline_asm_sym(sym),
1158 fn visit_inline_asm_sym(&mut self, sym: &'ast InlineAsmSym) {
1159 // This is similar to the code for AnonConst.
1160 self.with_rib(ValueNS, InlineAsmSymRibKind, |this| {
1161 this.with_rib(TypeNS, InlineAsmSymRibKind, |this| {
1162 this.with_label_rib(InlineAsmSymRibKind, |this| {
1163 this.smart_resolve_path(
1167 PathSource::Expr(None),
1169 visit::walk_inline_asm_sym(this, sym);
1176 impl<'a: 'ast, 'b, 'ast> LateResolutionVisitor<'a, 'b, 'ast> {
1177 fn new(resolver: &'b mut Resolver<'a>) -> LateResolutionVisitor<'a, 'b, 'ast> {
1178 // During late resolution we only track the module component of the parent scope,
1179 // although it may be useful to track other components as well for diagnostics.
1180 let graph_root = resolver.graph_root;
1181 let parent_scope = ParentScope::module(graph_root, resolver);
1182 let start_rib_kind = ModuleRibKind(graph_root);
1183 LateResolutionVisitor {
1187 value_ns: vec![Rib::new(start_rib_kind)],
1188 type_ns: vec![Rib::new(start_rib_kind)],
1189 macro_ns: vec![Rib::new(start_rib_kind)],
1191 label_ribs: Vec::new(),
1192 lifetime_ribs: Vec::new(),
1193 lifetime_elision_candidates: None,
1194 current_trait_ref: None,
1195 diagnostic_metadata: Box::new(DiagnosticMetadata::default()),
1196 // errors at module scope should always be reported
1197 in_func_body: false,
1198 lifetime_uses: Default::default(),
1202 fn maybe_resolve_ident_in_lexical_scope(
1206 ) -> Option<LexicalScopeBinding<'a>> {
1207 self.r.resolve_ident_in_lexical_scope(
1217 fn resolve_ident_in_lexical_scope(
1221 finalize: Option<Finalize>,
1222 ignore_binding: Option<&'a NameBinding<'a>>,
1223 ) -> Option<LexicalScopeBinding<'a>> {
1224 self.r.resolve_ident_in_lexical_scope(
1237 opt_ns: Option<Namespace>, // `None` indicates a module path in import
1238 finalize: Option<Finalize>,
1239 ) -> PathResult<'a> {
1240 self.r.resolve_path_with_ribs(
1252 // We maintain a list of value ribs and type ribs.
1254 // Simultaneously, we keep track of the current position in the module
1255 // graph in the `parent_scope.module` pointer. When we go to resolve a name in
1256 // the value or type namespaces, we first look through all the ribs and
1257 // then query the module graph. When we resolve a name in the module
1258 // namespace, we can skip all the ribs (since nested modules are not
1259 // allowed within blocks in Rust) and jump straight to the current module
1262 // Named implementations are handled separately. When we find a method
1263 // call, we consult the module node to find all of the implementations in
1264 // scope. This information is lazily cached in the module node. We then
1265 // generate a fake "implementation scope" containing all the
1266 // implementations thus found, for compatibility with old resolve pass.
1268 /// Do some `work` within a new innermost rib of the given `kind` in the given namespace (`ns`).
1273 work: impl FnOnce(&mut Self) -> T,
1275 self.ribs[ns].push(Rib::new(kind));
1276 let ret = work(self);
1277 self.ribs[ns].pop();
1281 fn with_scope<T>(&mut self, id: NodeId, f: impl FnOnce(&mut Self) -> T) -> T {
1282 if let Some(module) = self.r.get_module(self.r.local_def_id(id).to_def_id()) {
1283 // Move down in the graph.
1284 let orig_module = replace(&mut self.parent_scope.module, module);
1285 self.with_rib(ValueNS, ModuleRibKind(module), |this| {
1286 this.with_rib(TypeNS, ModuleRibKind(module), |this| {
1288 this.parent_scope.module = orig_module;
1297 fn visit_generic_params(&mut self, params: &'ast [GenericParam], add_self_upper: bool) {
1298 // For type parameter defaults, we have to ban access
1299 // to following type parameters, as the InternalSubsts can only
1300 // provide previous type parameters as they're built. We
1301 // put all the parameters on the ban list and then remove
1302 // them one by one as they are processed and become available.
1303 let mut forward_ty_ban_rib = Rib::new(ForwardGenericParamBanRibKind);
1304 let mut forward_const_ban_rib = Rib::new(ForwardGenericParamBanRibKind);
1305 for param in params.iter() {
1307 GenericParamKind::Type { .. } => {
1310 .insert(Ident::with_dummy_span(param.ident.name), Res::Err);
1312 GenericParamKind::Const { .. } => {
1313 forward_const_ban_rib
1315 .insert(Ident::with_dummy_span(param.ident.name), Res::Err);
1317 GenericParamKind::Lifetime => {}
1321 // rust-lang/rust#61631: The type `Self` is essentially
1322 // another type parameter. For ADTs, we consider it
1323 // well-defined only after all of the ADT type parameters have
1324 // been provided. Therefore, we do not allow use of `Self`
1325 // anywhere in ADT type parameter defaults.
1327 // (We however cannot ban `Self` for defaults on *all* generic
1328 // lists; e.g. trait generics can usefully refer to `Self`,
1329 // such as in the case of `trait Add<Rhs = Self>`.)
1331 // (`Some` if + only if we are in ADT's generics.)
1332 forward_ty_ban_rib.bindings.insert(Ident::with_dummy_span(kw::SelfUpper), Res::Err);
1335 self.with_lifetime_rib(LifetimeRibKind::AnonymousReportError, |this| {
1336 for param in params {
1338 GenericParamKind::Lifetime => {
1339 for bound in ¶m.bounds {
1340 this.visit_param_bound(bound, BoundKind::Bound);
1343 GenericParamKind::Type { ref default } => {
1344 for bound in ¶m.bounds {
1345 this.visit_param_bound(bound, BoundKind::Bound);
1348 if let Some(ref ty) = default {
1349 this.ribs[TypeNS].push(forward_ty_ban_rib);
1350 this.ribs[ValueNS].push(forward_const_ban_rib);
1352 forward_const_ban_rib = this.ribs[ValueNS].pop().unwrap();
1353 forward_ty_ban_rib = this.ribs[TypeNS].pop().unwrap();
1356 // Allow all following defaults to refer to this type parameter.
1359 .remove(&Ident::with_dummy_span(param.ident.name));
1361 GenericParamKind::Const { ref ty, kw_span: _, ref default } => {
1362 // Const parameters can't have param bounds.
1363 assert!(param.bounds.is_empty());
1365 this.ribs[TypeNS].push(Rib::new(ConstParamTyRibKind));
1366 this.ribs[ValueNS].push(Rib::new(ConstParamTyRibKind));
1367 this.with_lifetime_rib(LifetimeRibKind::ConstGeneric, |this| {
1370 this.ribs[TypeNS].pop().unwrap();
1371 this.ribs[ValueNS].pop().unwrap();
1373 if let Some(ref expr) = default {
1374 this.ribs[TypeNS].push(forward_ty_ban_rib);
1375 this.ribs[ValueNS].push(forward_const_ban_rib);
1376 this.with_lifetime_rib(LifetimeRibKind::ConstGeneric, |this| {
1377 this.resolve_anon_const(expr, IsRepeatExpr::No)
1379 forward_const_ban_rib = this.ribs[ValueNS].pop().unwrap();
1380 forward_ty_ban_rib = this.ribs[TypeNS].pop().unwrap();
1383 // Allow all following defaults to refer to this const parameter.
1384 forward_const_ban_rib
1386 .remove(&Ident::with_dummy_span(param.ident.name));
1393 #[tracing::instrument(level = "debug", skip(self, work))]
1394 fn with_lifetime_rib<T>(
1396 kind: LifetimeRibKind,
1397 work: impl FnOnce(&mut Self) -> T,
1399 self.lifetime_ribs.push(LifetimeRib::new(kind));
1400 let outer_elision_candidates = self.lifetime_elision_candidates.take();
1401 let ret = work(self);
1402 self.lifetime_elision_candidates = outer_elision_candidates;
1403 self.lifetime_ribs.pop();
1407 #[tracing::instrument(level = "debug", skip(self))]
1408 fn resolve_lifetime(&mut self, lifetime: &'ast Lifetime, use_ctxt: visit::LifetimeCtxt) {
1409 let ident = lifetime.ident;
1411 if ident.name == kw::StaticLifetime {
1412 self.record_lifetime_res(
1414 LifetimeRes::Static,
1415 LifetimeElisionCandidate::Named,
1420 if ident.name == kw::UnderscoreLifetime {
1421 return self.resolve_anonymous_lifetime(lifetime, false);
1424 let mut indices = (0..self.lifetime_ribs.len()).rev();
1425 for i in &mut indices {
1426 let rib = &self.lifetime_ribs[i];
1427 let normalized_ident = ident.normalize_to_macros_2_0();
1428 if let Some(&(_, res)) = rib.bindings.get(&normalized_ident) {
1429 self.record_lifetime_res(lifetime.id, res, LifetimeElisionCandidate::Named);
1431 if let LifetimeRes::Param { param, .. } = res {
1432 match self.lifetime_uses.entry(param) {
1433 Entry::Vacant(v) => {
1434 debug!("First use of {:?} at {:?}", res, ident.span);
1439 .find_map(|rib| match rib.kind {
1440 // Do not suggest eliding a lifetime where an anonymous
1441 // lifetime would be illegal.
1442 LifetimeRibKind::Item
1443 | LifetimeRibKind::AnonymousReportError
1444 | LifetimeRibKind::ElisionFailure => Some(LifetimeUseSet::Many),
1445 // An anonymous lifetime is legal here, go ahead.
1446 LifetimeRibKind::AnonymousCreateParameter { .. } => {
1447 Some(LifetimeUseSet::One { use_span: ident.span, use_ctxt })
1449 // Only report if eliding the lifetime would have the same
1451 LifetimeRibKind::Elided(r) => Some(if res == r {
1452 LifetimeUseSet::One { use_span: ident.span, use_ctxt }
1454 LifetimeUseSet::Many
1456 LifetimeRibKind::Generics { .. }
1457 | LifetimeRibKind::ConstGeneric
1458 | LifetimeRibKind::AnonConst => None,
1460 .unwrap_or(LifetimeUseSet::Many);
1461 debug!(?use_ctxt, ?use_set);
1464 Entry::Occupied(mut o) => {
1465 debug!("Many uses of {:?} at {:?}", res, ident.span);
1466 *o.get_mut() = LifetimeUseSet::Many;
1474 LifetimeRibKind::Item => break,
1475 LifetimeRibKind::ConstGeneric => {
1476 self.emit_non_static_lt_in_const_generic_error(lifetime);
1477 self.record_lifetime_res(
1480 LifetimeElisionCandidate::Ignore,
1484 LifetimeRibKind::AnonConst => {
1485 self.maybe_emit_forbidden_non_static_lifetime_error(lifetime);
1486 self.record_lifetime_res(
1489 LifetimeElisionCandidate::Ignore,
1497 let mut outer_res = None;
1499 let rib = &self.lifetime_ribs[i];
1500 let normalized_ident = ident.normalize_to_macros_2_0();
1501 if let Some((&outer, _)) = rib.bindings.get_key_value(&normalized_ident) {
1502 outer_res = Some(outer);
1507 self.emit_undeclared_lifetime_error(lifetime, outer_res);
1508 self.record_lifetime_res(lifetime.id, LifetimeRes::Error, LifetimeElisionCandidate::Named);
1511 #[tracing::instrument(level = "debug", skip(self))]
1512 fn resolve_anonymous_lifetime(&mut self, lifetime: &Lifetime, elided: bool) {
1513 debug_assert_eq!(lifetime.ident.name, kw::UnderscoreLifetime);
1515 let missing_lifetime = MissingLifetime {
1517 span: lifetime.ident.span,
1519 MissingLifetimeKind::Ampersand
1521 MissingLifetimeKind::Underscore
1525 let elision_candidate = LifetimeElisionCandidate::Missing(missing_lifetime);
1526 for i in (0..self.lifetime_ribs.len()).rev() {
1527 let rib = &mut self.lifetime_ribs[i];
1530 LifetimeRibKind::AnonymousCreateParameter { binder, .. } => {
1531 let res = self.create_fresh_lifetime(lifetime.id, lifetime.ident, binder);
1532 self.record_lifetime_res(lifetime.id, res, elision_candidate);
1535 LifetimeRibKind::AnonymousReportError => {
1536 let (msg, note) = if elided {
1538 "`&` without an explicit lifetime name cannot be used here",
1539 "explicit lifetime name needed here",
1542 ("`'_` cannot be used here", "`'_` is a reserved lifetime name")
1544 rustc_errors::struct_span_err!(
1546 lifetime.ident.span,
1551 .span_label(lifetime.ident.span, note)
1554 self.record_lifetime_res(lifetime.id, LifetimeRes::Error, elision_candidate);
1557 LifetimeRibKind::Elided(res) => {
1558 self.record_lifetime_res(lifetime.id, res, elision_candidate);
1561 LifetimeRibKind::ElisionFailure => {
1562 self.diagnostic_metadata.current_elision_failures.push(missing_lifetime);
1563 self.record_lifetime_res(lifetime.id, LifetimeRes::Error, elision_candidate);
1566 LifetimeRibKind::Item => break,
1567 LifetimeRibKind::Generics { .. }
1568 | LifetimeRibKind::ConstGeneric
1569 | LifetimeRibKind::AnonConst => {}
1572 self.record_lifetime_res(lifetime.id, LifetimeRes::Error, elision_candidate);
1573 self.report_missing_lifetime_specifiers(vec![missing_lifetime], None);
1576 #[tracing::instrument(level = "debug", skip(self))]
1577 fn resolve_elided_lifetime(&mut self, anchor_id: NodeId, span: Span) {
1578 let id = self.r.next_node_id();
1579 let lt = Lifetime { id, ident: Ident::new(kw::UnderscoreLifetime, span) };
1581 self.record_lifetime_res(
1583 LifetimeRes::ElidedAnchor { start: id, end: NodeId::from_u32(id.as_u32() + 1) },
1584 LifetimeElisionCandidate::Ignore,
1586 self.resolve_anonymous_lifetime(<, true);
1589 #[tracing::instrument(level = "debug", skip(self))]
1590 fn create_fresh_lifetime(&mut self, id: NodeId, ident: Ident, binder: NodeId) -> LifetimeRes {
1591 debug_assert_eq!(ident.name, kw::UnderscoreLifetime);
1592 debug!(?ident.span);
1594 // Leave the responsibility to create the `LocalDefId` to lowering.
1595 let param = self.r.next_node_id();
1596 let res = LifetimeRes::Fresh { param, binder };
1598 // Record the created lifetime parameter so lowering can pick it up and add it to HIR.
1600 .extra_lifetime_params_map
1602 .or_insert_with(Vec::new)
1603 .push((ident, param, res));
1607 #[tracing::instrument(level = "debug", skip(self))]
1608 fn resolve_elided_lifetimes_in_path(
1611 partial_res: PartialRes,
1613 source: PathSource<'_>,
1616 let proj_start = path.len() - partial_res.unresolved_segments();
1617 for (i, segment) in path.iter().enumerate() {
1618 if segment.has_lifetime_args {
1621 let Some(segment_id) = segment.id else {
1625 // Figure out if this is a type/trait segment,
1626 // which may need lifetime elision performed.
1627 let type_def_id = match partial_res.base_res() {
1628 Res::Def(DefKind::AssocTy, def_id) if i + 2 == proj_start => self.r.parent(def_id),
1629 Res::Def(DefKind::Variant, def_id) if i + 1 == proj_start => self.r.parent(def_id),
1630 Res::Def(DefKind::Struct, def_id)
1631 | Res::Def(DefKind::Union, def_id)
1632 | Res::Def(DefKind::Enum, def_id)
1633 | Res::Def(DefKind::TyAlias, def_id)
1634 | Res::Def(DefKind::Trait, def_id)
1635 if i + 1 == proj_start =>
1642 let expected_lifetimes = self.r.item_generics_num_lifetimes(type_def_id);
1643 if expected_lifetimes == 0 {
1647 let node_ids = self.r.next_node_ids(expected_lifetimes);
1648 self.record_lifetime_res(
1650 LifetimeRes::ElidedAnchor { start: node_ids.start, end: node_ids.end },
1651 LifetimeElisionCandidate::Ignore,
1654 let inferred = match source {
1655 PathSource::Trait(..) | PathSource::TraitItem(..) | PathSource::Type => false,
1656 PathSource::Expr(..)
1658 | PathSource::Struct
1659 | PathSource::TupleStruct(..) => true,
1662 // Do not create a parameter for patterns and expressions: type checking can infer
1663 // the appropriate lifetime for us.
1664 for id in node_ids {
1665 self.record_lifetime_res(
1668 LifetimeElisionCandidate::Named,
1674 let elided_lifetime_span = if segment.has_generic_args {
1675 // If there are brackets, but not generic arguments, then use the opening bracket
1676 segment.args_span.with_hi(segment.args_span.lo() + BytePos(1))
1678 // If there are no brackets, use the identifier span.
1679 // HACK: we use find_ancestor_inside to properly suggest elided spans in paths
1680 // originating from macros, since the segment's span might be from a macro arg.
1681 segment.ident.span.find_ancestor_inside(path_span).unwrap_or(path_span)
1683 let ident = Ident::new(kw::UnderscoreLifetime, elided_lifetime_span);
1685 let missing_lifetime = MissingLifetime {
1687 span: elided_lifetime_span,
1688 kind: if segment.has_generic_args {
1689 MissingLifetimeKind::Comma
1691 MissingLifetimeKind::Brackets
1693 count: expected_lifetimes,
1695 let mut should_lint = true;
1696 for rib in self.lifetime_ribs.iter().rev() {
1698 // In create-parameter mode we error here because we don't want to support
1699 // deprecated impl elision in new features like impl elision and `async fn`,
1700 // both of which work using the `CreateParameter` mode:
1702 // impl Foo for std::cell::Ref<u32> // note lack of '_
1703 // async fn foo(_: std::cell::Ref<u32>) { ... }
1704 LifetimeRibKind::AnonymousCreateParameter { report_in_path: true, .. } => {
1705 let sess = self.r.session;
1706 let mut err = rustc_errors::struct_span_err!(
1710 "implicit elided lifetime not allowed here"
1712 rustc_errors::add_elided_lifetime_in_path_suggestion(
1717 !segment.has_generic_args,
1718 elided_lifetime_span,
1720 err.note("assuming a `'static` lifetime...");
1722 should_lint = false;
1724 for id in node_ids {
1725 self.record_lifetime_res(
1728 LifetimeElisionCandidate::Named,
1733 // Do not create a parameter for patterns and expressions.
1734 LifetimeRibKind::AnonymousCreateParameter { binder, .. } => {
1735 // Group all suggestions into the first record.
1736 let mut candidate = LifetimeElisionCandidate::Missing(missing_lifetime);
1737 for id in node_ids {
1738 let res = self.create_fresh_lifetime(id, ident, binder);
1739 self.record_lifetime_res(
1742 replace(&mut candidate, LifetimeElisionCandidate::Named),
1747 LifetimeRibKind::Elided(res) => {
1748 let mut candidate = LifetimeElisionCandidate::Missing(missing_lifetime);
1749 for id in node_ids {
1750 self.record_lifetime_res(
1753 replace(&mut candidate, LifetimeElisionCandidate::Ignore),
1758 LifetimeRibKind::ElisionFailure => {
1759 self.diagnostic_metadata.current_elision_failures.push(missing_lifetime);
1760 for id in node_ids {
1761 self.record_lifetime_res(
1764 LifetimeElisionCandidate::Ignore,
1769 // `LifetimeRes::Error`, which would usually be used in the case of
1770 // `ReportError`, is unsuitable here, as we don't emit an error yet. Instead,
1771 // we simply resolve to an implicit lifetime, which will be checked later, at
1772 // which point a suitable error will be emitted.
1773 LifetimeRibKind::AnonymousReportError | LifetimeRibKind::Item => {
1774 for id in node_ids {
1775 self.record_lifetime_res(
1778 LifetimeElisionCandidate::Ignore,
1781 self.report_missing_lifetime_specifiers(vec![missing_lifetime], None);
1784 LifetimeRibKind::Generics { .. }
1785 | LifetimeRibKind::ConstGeneric
1786 | LifetimeRibKind::AnonConst => {}
1791 self.r.lint_buffer.buffer_lint_with_diagnostic(
1792 lint::builtin::ELIDED_LIFETIMES_IN_PATHS,
1794 elided_lifetime_span,
1795 "hidden lifetime parameters in types are deprecated",
1796 lint::BuiltinLintDiagnostics::ElidedLifetimesInPaths(
1799 !segment.has_generic_args,
1800 elided_lifetime_span,
1807 #[tracing::instrument(level = "debug", skip(self))]
1808 fn record_lifetime_res(
1812 candidate: LifetimeElisionCandidate,
1814 if let Some(prev_res) = self.r.lifetimes_res_map.insert(id, res) {
1816 "lifetime {:?} resolved multiple times ({:?} before, {:?} now)",
1821 LifetimeRes::Param { .. } | LifetimeRes::Fresh { .. } | LifetimeRes::Static => {
1822 if let Some(ref mut candidates) = self.lifetime_elision_candidates {
1823 candidates.insert(res, candidate);
1826 LifetimeRes::Infer | LifetimeRes::Error | LifetimeRes::ElidedAnchor { .. } => {}
1830 #[tracing::instrument(level = "debug", skip(self))]
1831 fn record_lifetime_param(&mut self, id: NodeId, res: LifetimeRes) {
1832 if let Some(prev_res) = self.r.lifetimes_res_map.insert(id, res) {
1834 "lifetime parameter {:?} resolved multiple times ({:?} before, {:?} now)",
1840 /// Perform resolution of a function signature, accounting for lifetime elision.
1841 #[tracing::instrument(level = "debug", skip(self, inputs))]
1842 fn resolve_fn_signature(
1846 inputs: impl Iterator<Item = (Option<&'ast Pat>, &'ast Ty)> + Clone,
1847 output_ty: &'ast FnRetTy,
1849 // Add each argument to the rib.
1850 let elision_lifetime = self.resolve_fn_params(has_self, inputs);
1851 debug!(?elision_lifetime);
1853 let outer_failures = take(&mut self.diagnostic_metadata.current_elision_failures);
1854 let output_rib = if let Ok(res) = elision_lifetime.as_ref() {
1855 LifetimeRibKind::Elided(*res)
1857 LifetimeRibKind::ElisionFailure
1859 self.with_lifetime_rib(output_rib, |this| visit::walk_fn_ret_ty(this, &output_ty));
1860 let elision_failures =
1861 replace(&mut self.diagnostic_metadata.current_elision_failures, outer_failures);
1862 if !elision_failures.is_empty() {
1863 let Err(failure_info) = elision_lifetime else { bug!() };
1864 self.report_missing_lifetime_specifiers(elision_failures, Some(failure_info));
1868 /// Resolve inside function parameters and parameter types.
1869 /// Returns the lifetime for elision in fn return type,
1870 /// or diagnostic information in case of elision failure.
1871 fn resolve_fn_params(
1874 inputs: impl Iterator<Item = (Option<&'ast Pat>, &'ast Ty)>,
1875 ) -> Result<LifetimeRes, (Vec<MissingLifetime>, Vec<ElisionFnParameter>)> {
1876 let outer_candidates =
1877 replace(&mut self.lifetime_elision_candidates, Some(Default::default()));
1879 let mut elision_lifetime = None;
1880 let mut lifetime_count = 0;
1881 let mut parameter_info = Vec::new();
1883 let mut bindings = smallvec![(PatBoundCtx::Product, Default::default())];
1884 for (index, (pat, ty)) in inputs.enumerate() {
1886 if let Some(pat) = pat {
1887 self.resolve_pattern(pat, PatternSource::FnParam, &mut bindings);
1891 if let Some(ref candidates) = self.lifetime_elision_candidates {
1892 let new_count = candidates.len();
1893 let local_count = new_count - lifetime_count;
1894 if local_count != 0 {
1895 parameter_info.push(ElisionFnParameter {
1897 ident: if let Some(pat) = pat && let PatKind::Ident(_, ident, _) = pat.kind {
1902 lifetime_count: local_count,
1906 lifetime_count = new_count;
1909 // Handle `self` specially.
1910 if index == 0 && has_self {
1911 let self_lifetime = self.find_lifetime_for_self(ty);
1912 if let Set1::One(lifetime) = self_lifetime {
1913 elision_lifetime = Some(lifetime);
1914 self.lifetime_elision_candidates = None;
1916 self.lifetime_elision_candidates = Some(Default::default());
1920 debug!("(resolving function / closure) recorded parameter");
1923 let all_candidates = replace(&mut self.lifetime_elision_candidates, outer_candidates);
1924 debug!(?all_candidates);
1926 if let Some(res) = elision_lifetime {
1930 // We do not have a `self` candidate, look at the full list.
1931 let all_candidates = all_candidates.unwrap();
1932 if all_candidates.len() == 1 {
1933 Ok(*all_candidates.first().unwrap().0)
1935 let all_candidates = all_candidates
1937 .filter_map(|(_, candidate)| match candidate {
1938 LifetimeElisionCandidate::Ignore | LifetimeElisionCandidate::Named => None,
1939 LifetimeElisionCandidate::Missing(missing) => Some(missing),
1942 Err((all_candidates, parameter_info))
1946 /// List all the lifetimes that appear in the provided type.
1947 fn find_lifetime_for_self(&self, ty: &'ast Ty) -> Set1<LifetimeRes> {
1948 struct SelfVisitor<'r, 'a> {
1949 r: &'r Resolver<'a>,
1950 impl_self: Option<Res>,
1951 lifetime: Set1<LifetimeRes>,
1954 impl SelfVisitor<'_, '_> {
1955 // Look for `self: &'a Self` - also desugared from `&'a self`,
1956 // and if that matches, use it for elision and return early.
1957 fn is_self_ty(&self, ty: &Ty) -> bool {
1959 TyKind::ImplicitSelf => true,
1960 TyKind::Path(None, _) => {
1961 let path_res = self.r.partial_res_map[&ty.id].base_res();
1962 if let Res::SelfTy { .. } = path_res {
1965 Some(path_res) == self.impl_self
1972 impl<'a> Visitor<'a> for SelfVisitor<'_, '_> {
1973 fn visit_ty(&mut self, ty: &'a Ty) {
1974 trace!("SelfVisitor considering ty={:?}", ty);
1975 if let TyKind::Rptr(lt, ref mt) = ty.kind && self.is_self_ty(&mt.ty) {
1976 let lt_id = if let Some(lt) = lt {
1979 let res = self.r.lifetimes_res_map[&ty.id];
1980 let LifetimeRes::ElidedAnchor { start, .. } = res else { bug!() };
1983 let lt_res = self.r.lifetimes_res_map[<_id];
1984 trace!("SelfVisitor inserting res={:?}", lt_res);
1985 self.lifetime.insert(lt_res);
1987 visit::walk_ty(self, ty)
1991 let impl_self = self
1992 .diagnostic_metadata
1996 if let TyKind::Path(None, _) = ty.kind {
1997 self.r.partial_res_map.get(&ty.id)
2002 .map(|res| res.base_res())
2004 // Permit the types that unambiguously always
2005 // result in the same type constructor being used
2006 // (it can't differ between `Self` and `self`).
2009 Res::Def(DefKind::Struct | DefKind::Union | DefKind::Enum, _,) | Res::PrimTy(_)
2012 let mut visitor = SelfVisitor { r: self.r, impl_self, lifetime: Set1::Empty };
2013 visitor.visit_ty(ty);
2014 trace!("SelfVisitor found={:?}", visitor.lifetime);
2018 /// Searches the current set of local scopes for labels. Returns the `NodeId` of the resolved
2019 /// label and reports an error if the label is not found or is unreachable.
2020 fn resolve_label(&mut self, mut label: Ident) -> Result<(NodeId, Span), ResolutionError<'a>> {
2021 let mut suggestion = None;
2023 for i in (0..self.label_ribs.len()).rev() {
2024 let rib = &self.label_ribs[i];
2026 if let MacroDefinition(def) = rib.kind {
2027 // If an invocation of this macro created `ident`, give up on `ident`
2028 // and switch to `ident`'s source from the macro definition.
2029 if def == self.r.macro_def(label.span.ctxt()) {
2030 label.span.remove_mark();
2034 let ident = label.normalize_to_macro_rules();
2035 if let Some((ident, id)) = rib.bindings.get_key_value(&ident) {
2036 let definition_span = ident.span;
2037 return if self.is_label_valid_from_rib(i) {
2038 Ok((*id, definition_span))
2040 Err(ResolutionError::UnreachableLabel {
2048 // Diagnostics: Check if this rib contains a label with a similar name, keep track of
2049 // the first such label that is encountered.
2050 suggestion = suggestion.or_else(|| self.suggestion_for_label_in_rib(i, label));
2053 Err(ResolutionError::UndeclaredLabel { name: label.name, suggestion })
2056 /// Determine whether or not a label from the `rib_index`th label rib is reachable.
2057 fn is_label_valid_from_rib(&self, rib_index: usize) -> bool {
2058 let ribs = &self.label_ribs[rib_index + 1..];
2061 if rib.kind.is_label_barrier() {
2069 fn resolve_adt(&mut self, item: &'ast Item, generics: &'ast Generics) {
2070 debug!("resolve_adt");
2071 self.with_current_self_item(item, |this| {
2072 this.with_generic_param_rib(
2074 ItemRibKind(HasGenericParams::Yes(generics.span)),
2075 LifetimeRibKind::Generics {
2077 kind: LifetimeBinderKind::Item,
2078 span: generics.span,
2081 let item_def_id = this.r.local_def_id(item.id).to_def_id();
2083 Res::SelfTy { trait_: None, alias_to: Some((item_def_id, false)) },
2085 visit::walk_item(this, item);
2093 fn future_proof_import(&mut self, use_tree: &UseTree) {
2094 let segments = &use_tree.prefix.segments;
2095 if !segments.is_empty() {
2096 let ident = segments[0].ident;
2097 if ident.is_path_segment_keyword() || ident.span.rust_2015() {
2101 let nss = match use_tree.kind {
2102 UseTreeKind::Simple(..) if segments.len() == 1 => &[TypeNS, ValueNS][..],
2105 let report_error = |this: &Self, ns| {
2106 let what = if ns == TypeNS { "type parameters" } else { "local variables" };
2107 if this.should_report_errs() {
2110 .span_err(ident.span, &format!("imports cannot refer to {}", what));
2115 match self.maybe_resolve_ident_in_lexical_scope(ident, ns) {
2116 Some(LexicalScopeBinding::Res(..)) => {
2117 report_error(self, ns);
2119 Some(LexicalScopeBinding::Item(binding)) => {
2120 if let Some(LexicalScopeBinding::Res(..)) =
2121 self.resolve_ident_in_lexical_scope(ident, ns, None, Some(binding))
2123 report_error(self, ns);
2129 } else if let UseTreeKind::Nested(use_trees) = &use_tree.kind {
2130 for (use_tree, _) in use_trees {
2131 self.future_proof_import(use_tree);
2136 fn resolve_item(&mut self, item: &'ast Item) {
2137 let name = item.ident.name;
2138 debug!("(resolving item) resolving {} ({:?})", name, item.kind);
2141 ItemKind::TyAlias(box TyAlias { ref generics, .. }) => {
2142 self.with_generic_param_rib(
2144 ItemRibKind(HasGenericParams::Yes(generics.span)),
2145 LifetimeRibKind::Generics {
2147 kind: LifetimeBinderKind::Item,
2148 span: generics.span,
2150 |this| visit::walk_item(this, item),
2154 ItemKind::Fn(box Fn { ref generics, .. }) => {
2155 self.with_generic_param_rib(
2157 ItemRibKind(HasGenericParams::Yes(generics.span)),
2158 LifetimeRibKind::Generics {
2160 kind: LifetimeBinderKind::Function,
2161 span: generics.span,
2163 |this| visit::walk_item(this, item),
2167 ItemKind::Enum(_, ref generics)
2168 | ItemKind::Struct(_, ref generics)
2169 | ItemKind::Union(_, ref generics) => {
2170 self.resolve_adt(item, generics);
2173 ItemKind::Impl(box Impl {
2177 items: ref impl_items,
2180 self.diagnostic_metadata.current_impl_items = Some(impl_items);
2181 self.resolve_implementation(generics, of_trait, &self_ty, item.id, impl_items);
2182 self.diagnostic_metadata.current_impl_items = None;
2185 ItemKind::Trait(box Trait { ref generics, ref bounds, ref items, .. }) => {
2186 // Create a new rib for the trait-wide type parameters.
2187 self.with_generic_param_rib(
2189 ItemRibKind(HasGenericParams::Yes(generics.span)),
2190 LifetimeRibKind::Generics {
2192 kind: LifetimeBinderKind::Item,
2193 span: generics.span,
2196 let local_def_id = this.r.local_def_id(item.id).to_def_id();
2198 Res::SelfTy { trait_: Some(local_def_id), alias_to: None },
2200 this.visit_generics(generics);
2201 walk_list!(this, visit_param_bound, bounds, BoundKind::SuperTraits);
2202 this.resolve_trait_items(items);
2209 ItemKind::TraitAlias(ref generics, ref bounds) => {
2210 // Create a new rib for the trait-wide type parameters.
2211 self.with_generic_param_rib(
2213 ItemRibKind(HasGenericParams::Yes(generics.span)),
2214 LifetimeRibKind::Generics {
2216 kind: LifetimeBinderKind::Item,
2217 span: generics.span,
2220 let local_def_id = this.r.local_def_id(item.id).to_def_id();
2222 Res::SelfTy { trait_: Some(local_def_id), alias_to: None },
2224 this.visit_generics(generics);
2225 walk_list!(this, visit_param_bound, bounds, BoundKind::Bound);
2232 ItemKind::Mod(..) | ItemKind::ForeignMod(_) => {
2233 self.with_scope(item.id, |this| {
2234 visit::walk_item(this, item);
2238 ItemKind::Static(ref ty, _, ref expr) | ItemKind::Const(_, ref ty, ref expr) => {
2239 self.with_item_rib(|this| {
2240 this.with_lifetime_rib(LifetimeRibKind::Elided(LifetimeRes::Static), |this| {
2243 this.with_lifetime_rib(LifetimeRibKind::Elided(LifetimeRes::Infer), |this| {
2244 if let Some(expr) = expr {
2245 let constant_item_kind = match item.kind {
2246 ItemKind::Const(..) => ConstantItemKind::Const,
2247 ItemKind::Static(..) => ConstantItemKind::Static,
2248 _ => unreachable!(),
2250 // We already forbid generic params because of the above item rib,
2251 // so it doesn't matter whether this is a trivial constant.
2252 this.with_constant_rib(
2254 ConstantHasGenerics::Yes,
2255 Some((item.ident, constant_item_kind)),
2256 |this| this.visit_expr(expr),
2263 ItemKind::Use(ref use_tree) => {
2264 self.future_proof_import(use_tree);
2267 ItemKind::ExternCrate(..) | ItemKind::MacroDef(..) => {
2268 // do nothing, these are just around to be encoded
2271 ItemKind::GlobalAsm(_) => {
2272 visit::walk_item(self, item);
2275 ItemKind::MacCall(_) => panic!("unexpanded macro in resolve!"),
2279 fn with_generic_param_rib<'c, F>(
2281 params: &'c [GenericParam],
2283 lifetime_kind: LifetimeRibKind,
2286 F: FnOnce(&mut Self),
2288 debug!("with_generic_param_rib");
2289 let LifetimeRibKind::Generics { binder, span: generics_span, kind: generics_kind, .. }
2290 = lifetime_kind else { panic!() };
2292 let mut function_type_rib = Rib::new(kind);
2293 let mut function_value_rib = Rib::new(kind);
2294 let mut function_lifetime_rib = LifetimeRib::new(lifetime_kind);
2295 let mut seen_bindings = FxHashMap::default();
2296 // Store all seen lifetimes names from outer scopes.
2297 let mut seen_lifetimes = FxHashSet::default();
2299 // We also can't shadow bindings from the parent item
2300 if let AssocItemRibKind = kind {
2301 let mut add_bindings_for_ns = |ns| {
2302 let parent_rib = self.ribs[ns]
2304 .rfind(|r| matches!(r.kind, ItemRibKind(_)))
2305 .expect("associated item outside of an item");
2307 .extend(parent_rib.bindings.iter().map(|(ident, _)| (*ident, ident.span)));
2309 add_bindings_for_ns(ValueNS);
2310 add_bindings_for_ns(TypeNS);
2313 // Forbid shadowing lifetime bindings
2314 for rib in self.lifetime_ribs.iter().rev() {
2315 seen_lifetimes.extend(rib.bindings.iter().map(|(ident, _)| *ident));
2316 if let LifetimeRibKind::Item = rib.kind {
2321 for param in params {
2322 let ident = param.ident.normalize_to_macros_2_0();
2323 debug!("with_generic_param_rib: {}", param.id);
2325 if let GenericParamKind::Lifetime = param.kind
2326 && let Some(&original) = seen_lifetimes.get(&ident)
2328 diagnostics::signal_lifetime_shadowing(self.r.session, original, param.ident);
2329 // Record lifetime res, so lowering knows there is something fishy.
2330 self.record_lifetime_param(param.id, LifetimeRes::Error);
2334 match seen_bindings.entry(ident) {
2335 Entry::Occupied(entry) => {
2336 let span = *entry.get();
2337 let err = ResolutionError::NameAlreadyUsedInParameterList(ident.name, span);
2338 self.report_error(param.ident.span, err);
2339 if let GenericParamKind::Lifetime = param.kind {
2340 // Record lifetime res, so lowering knows there is something fishy.
2341 self.record_lifetime_param(param.id, LifetimeRes::Error);
2345 Entry::Vacant(entry) => {
2346 entry.insert(param.ident.span);
2350 if param.ident.name == kw::UnderscoreLifetime {
2351 rustc_errors::struct_span_err!(
2355 "`'_` cannot be used here"
2357 .span_label(param.ident.span, "`'_` is a reserved lifetime name")
2359 // Record lifetime res, so lowering knows there is something fishy.
2360 self.record_lifetime_param(param.id, LifetimeRes::Error);
2364 if param.ident.name == kw::StaticLifetime {
2365 rustc_errors::struct_span_err!(
2369 "invalid lifetime parameter name: `{}`",
2372 .span_label(param.ident.span, "'static is a reserved lifetime name")
2374 // Record lifetime res, so lowering knows there is something fishy.
2375 self.record_lifetime_param(param.id, LifetimeRes::Error);
2379 let def_id = self.r.local_def_id(param.id);
2381 // Plain insert (no renaming).
2382 let (rib, def_kind) = match param.kind {
2383 GenericParamKind::Type { .. } => (&mut function_type_rib, DefKind::TyParam),
2384 GenericParamKind::Const { .. } => (&mut function_value_rib, DefKind::ConstParam),
2385 GenericParamKind::Lifetime => {
2386 let res = LifetimeRes::Param { param: def_id, binder };
2387 self.record_lifetime_param(param.id, res);
2388 function_lifetime_rib.bindings.insert(ident, (param.id, res));
2393 let res = match kind {
2394 ItemRibKind(..) | AssocItemRibKind => Res::Def(def_kind, def_id.to_def_id()),
2395 NormalRibKind => Res::Err,
2396 _ => span_bug!(param.ident.span, "Unexpected rib kind {:?}", kind),
2398 self.r.record_partial_res(param.id, PartialRes::new(res));
2399 rib.bindings.insert(ident, res);
2402 self.lifetime_ribs.push(function_lifetime_rib);
2403 self.ribs[ValueNS].push(function_value_rib);
2404 self.ribs[TypeNS].push(function_type_rib);
2408 self.ribs[TypeNS].pop();
2409 self.ribs[ValueNS].pop();
2410 let function_lifetime_rib = self.lifetime_ribs.pop().unwrap();
2412 // Do not account for the parameters we just bound for function lifetime elision.
2413 if let Some(ref mut candidates) = self.lifetime_elision_candidates {
2414 for (_, res) in function_lifetime_rib.bindings.values() {
2415 candidates.remove(res);
2419 if let LifetimeBinderKind::BareFnType
2420 | LifetimeBinderKind::WhereBound
2421 | LifetimeBinderKind::Function
2422 | LifetimeBinderKind::ImplBlock = generics_kind
2424 self.maybe_report_lifetime_uses(generics_span, params)
2428 fn with_label_rib(&mut self, kind: RibKind<'a>, f: impl FnOnce(&mut Self)) {
2429 self.label_ribs.push(Rib::new(kind));
2431 self.label_ribs.pop();
2434 fn with_item_rib(&mut self, f: impl FnOnce(&mut Self)) {
2435 let kind = ItemRibKind(HasGenericParams::No);
2436 self.with_lifetime_rib(LifetimeRibKind::Item, |this| {
2437 this.with_rib(ValueNS, kind, |this| this.with_rib(TypeNS, kind, f))
2441 // HACK(min_const_generics,const_evaluatable_unchecked): We
2442 // want to keep allowing `[0; std::mem::size_of::<*mut T>()]`
2443 // with a future compat lint for now. We do this by adding an
2444 // additional special case for repeat expressions.
2446 // Note that we intentionally still forbid `[0; N + 1]` during
2447 // name resolution so that we don't extend the future
2448 // compat lint to new cases.
2449 #[instrument(level = "debug", skip(self, f))]
2450 fn with_constant_rib(
2452 is_repeat: IsRepeatExpr,
2453 may_use_generics: ConstantHasGenerics,
2454 item: Option<(Ident, ConstantItemKind)>,
2455 f: impl FnOnce(&mut Self),
2457 self.with_rib(ValueNS, ConstantItemRibKind(may_use_generics, item), |this| {
2460 ConstantItemRibKind(
2461 may_use_generics.force_yes_if(is_repeat == IsRepeatExpr::Yes),
2465 this.with_label_rib(ConstantItemRibKind(may_use_generics, item), f);
2471 fn with_current_self_type<T>(&mut self, self_type: &Ty, f: impl FnOnce(&mut Self) -> T) -> T {
2472 // Handle nested impls (inside fn bodies)
2473 let previous_value =
2474 replace(&mut self.diagnostic_metadata.current_self_type, Some(self_type.clone()));
2475 let result = f(self);
2476 self.diagnostic_metadata.current_self_type = previous_value;
2480 fn with_current_self_item<T>(&mut self, self_item: &Item, f: impl FnOnce(&mut Self) -> T) -> T {
2481 let previous_value =
2482 replace(&mut self.diagnostic_metadata.current_self_item, Some(self_item.id));
2483 let result = f(self);
2484 self.diagnostic_metadata.current_self_item = previous_value;
2488 /// When evaluating a `trait` use its associated types' idents for suggestions in E0412.
2489 fn resolve_trait_items(&mut self, trait_items: &'ast [P<AssocItem>]) {
2490 let trait_assoc_items =
2491 replace(&mut self.diagnostic_metadata.current_trait_assoc_items, Some(&trait_items));
2493 let walk_assoc_item =
2494 |this: &mut Self, generics: &Generics, kind, item: &'ast AssocItem| {
2495 this.with_generic_param_rib(
2498 LifetimeRibKind::Generics { binder: item.id, span: generics.span, kind },
2499 |this| visit::walk_assoc_item(this, item, AssocCtxt::Trait),
2503 for item in trait_items {
2505 AssocItemKind::Const(_, ty, default) => {
2507 // Only impose the restrictions of `ConstRibKind` for an
2508 // actual constant expression in a provided default.
2509 if let Some(expr) = default {
2510 // We allow arbitrary const expressions inside of associated consts,
2511 // even if they are potentially not const evaluatable.
2513 // Type parameters can already be used and as associated consts are
2514 // not used as part of the type system, this is far less surprising.
2515 self.with_lifetime_rib(
2516 LifetimeRibKind::Elided(LifetimeRes::Infer),
2518 this.with_constant_rib(
2520 ConstantHasGenerics::Yes,
2522 |this| this.visit_expr(expr),
2528 AssocItemKind::Fn(box Fn { generics, .. }) => {
2529 walk_assoc_item(self, generics, LifetimeBinderKind::Function, item);
2531 AssocItemKind::TyAlias(box TyAlias { generics, .. }) => self
2532 .with_lifetime_rib(LifetimeRibKind::AnonymousReportError, |this| {
2533 walk_assoc_item(this, generics, LifetimeBinderKind::Item, item)
2535 AssocItemKind::MacCall(_) => {
2536 panic!("unexpanded macro in resolve!")
2541 self.diagnostic_metadata.current_trait_assoc_items = trait_assoc_items;
2544 /// This is called to resolve a trait reference from an `impl` (i.e., `impl Trait for Foo`).
2545 fn with_optional_trait_ref<T>(
2547 opt_trait_ref: Option<&TraitRef>,
2548 self_type: &'ast Ty,
2549 f: impl FnOnce(&mut Self, Option<DefId>) -> T,
2551 let mut new_val = None;
2552 let mut new_id = None;
2553 if let Some(trait_ref) = opt_trait_ref {
2554 let path: Vec<_> = Segment::from_path(&trait_ref.path);
2555 self.diagnostic_metadata.currently_processing_impl_trait =
2556 Some((trait_ref.clone(), self_type.clone()));
2557 let res = self.smart_resolve_path_fragment(
2560 PathSource::Trait(AliasPossibility::No),
2561 Finalize::new(trait_ref.ref_id, trait_ref.path.span),
2563 self.diagnostic_metadata.currently_processing_impl_trait = None;
2564 if let Some(def_id) = res.base_res().opt_def_id() {
2565 new_id = Some(def_id);
2566 new_val = Some((self.r.expect_module(def_id), trait_ref.clone()));
2569 let original_trait_ref = replace(&mut self.current_trait_ref, new_val);
2570 let result = f(self, new_id);
2571 self.current_trait_ref = original_trait_ref;
2575 fn with_self_rib_ns(&mut self, ns: Namespace, self_res: Res, f: impl FnOnce(&mut Self)) {
2576 let mut self_type_rib = Rib::new(NormalRibKind);
2578 // Plain insert (no renaming, since types are not currently hygienic)
2579 self_type_rib.bindings.insert(Ident::with_dummy_span(kw::SelfUpper), self_res);
2580 self.ribs[ns].push(self_type_rib);
2582 self.ribs[ns].pop();
2585 fn with_self_rib(&mut self, self_res: Res, f: impl FnOnce(&mut Self)) {
2586 self.with_self_rib_ns(TypeNS, self_res, f)
2589 fn resolve_implementation(
2591 generics: &'ast Generics,
2592 opt_trait_reference: &'ast Option<TraitRef>,
2593 self_type: &'ast Ty,
2595 impl_items: &'ast [P<AssocItem>],
2597 debug!("resolve_implementation");
2598 // If applicable, create a rib for the type parameters.
2599 self.with_generic_param_rib(
2601 ItemRibKind(HasGenericParams::Yes(generics.span)),
2602 LifetimeRibKind::Generics {
2603 span: generics.span,
2605 kind: LifetimeBinderKind::ImplBlock,
2608 // Dummy self type for better errors if `Self` is used in the trait path.
2609 this.with_self_rib(Res::SelfTy { trait_: None, alias_to: None }, |this| {
2610 this.with_lifetime_rib(
2611 LifetimeRibKind::AnonymousCreateParameter {
2613 report_in_path: true
2616 // Resolve the trait reference, if necessary.
2617 this.with_optional_trait_ref(
2618 opt_trait_reference.as_ref(),
2621 let item_def_id = this.r.local_def_id(item_id);
2623 // Register the trait definitions from here.
2624 if let Some(trait_id) = trait_id {
2632 let item_def_id = item_def_id.to_def_id();
2633 let res = Res::SelfTy {
2635 alias_to: Some((item_def_id, false)),
2637 this.with_self_rib(res, |this| {
2638 if let Some(trait_ref) = opt_trait_reference.as_ref() {
2639 // Resolve type arguments in the trait path.
2640 visit::walk_trait_ref(this, trait_ref);
2642 // Resolve the self type.
2643 this.visit_ty(self_type);
2644 // Resolve the generic parameters.
2645 this.visit_generics(generics);
2647 // Resolve the items within the impl.
2648 this.with_current_self_type(self_type, |this| {
2649 this.with_self_rib_ns(ValueNS, Res::SelfCtor(item_def_id), |this| {
2650 debug!("resolve_implementation with_self_rib_ns(ValueNS, ...)");
2651 for item in impl_items {
2652 this.resolve_impl_item(&**item);
2666 fn resolve_impl_item(&mut self, item: &'ast AssocItem) {
2667 use crate::ResolutionError::*;
2669 AssocItemKind::Const(_, ty, default) => {
2670 debug!("resolve_implementation AssocItemKind::Const");
2671 // If this is a trait impl, ensure the const
2673 self.check_trait_item(
2679 |i, s, c| ConstNotMemberOfTrait(i, s, c),
2683 if let Some(expr) = default {
2684 // We allow arbitrary const expressions inside of associated consts,
2685 // even if they are potentially not const evaluatable.
2687 // Type parameters can already be used and as associated consts are
2688 // not used as part of the type system, this is far less surprising.
2689 self.with_lifetime_rib(LifetimeRibKind::Elided(LifetimeRes::Infer), |this| {
2690 this.with_constant_rib(
2692 ConstantHasGenerics::Yes,
2694 |this| this.visit_expr(expr),
2699 AssocItemKind::Fn(box Fn { generics, .. }) => {
2700 debug!("resolve_implementation AssocItemKind::Fn");
2701 // We also need a new scope for the impl item type parameters.
2702 self.with_generic_param_rib(
2705 LifetimeRibKind::Generics {
2707 span: generics.span,
2708 kind: LifetimeBinderKind::Function,
2711 // If this is a trait impl, ensure the method
2713 this.check_trait_item(
2719 |i, s, c| MethodNotMemberOfTrait(i, s, c),
2722 visit::walk_assoc_item(this, item, AssocCtxt::Impl)
2726 AssocItemKind::TyAlias(box TyAlias { generics, .. }) => {
2727 debug!("resolve_implementation AssocItemKind::TyAlias");
2728 // We also need a new scope for the impl item type parameters.
2729 self.with_generic_param_rib(
2732 LifetimeRibKind::Generics {
2734 span: generics.span,
2735 kind: LifetimeBinderKind::Item,
2738 this.with_lifetime_rib(LifetimeRibKind::AnonymousReportError, |this| {
2739 // If this is a trait impl, ensure the type
2741 this.check_trait_item(
2747 |i, s, c| TypeNotMemberOfTrait(i, s, c),
2750 visit::walk_assoc_item(this, item, AssocCtxt::Impl)
2755 AssocItemKind::MacCall(_) => {
2756 panic!("unexpanded macro in resolve!")
2761 fn check_trait_item<F>(
2765 kind: &AssocItemKind,
2770 F: FnOnce(Ident, String, Option<Symbol>) -> ResolutionError<'a>,
2772 // If there is a TraitRef in scope for an impl, then the method must be in the trait.
2773 let Some((module, _)) = &self.current_trait_ref else { return; };
2774 ident.span.normalize_to_macros_2_0_and_adjust(module.expansion);
2775 let key = self.r.new_key(ident, ns);
2776 let mut binding = self.r.resolution(module, key).try_borrow().ok().and_then(|r| r.binding);
2778 if binding.is_none() {
2779 // We could not find the trait item in the correct namespace.
2780 // Check the other namespace to report an error.
2786 let key = self.r.new_key(ident, ns);
2787 binding = self.r.resolution(module, key).try_borrow().ok().and_then(|r| r.binding);
2790 let Some(binding) = binding else {
2791 // We could not find the method: report an error.
2792 let candidate = self.find_similarly_named_assoc_item(ident.name, kind);
2793 let path = &self.current_trait_ref.as_ref().unwrap().1.path;
2794 let path_names = path_names_to_string(path);
2795 self.report_error(span, err(ident, path_names, candidate));
2799 let res = binding.res();
2800 let Res::Def(def_kind, _) = res else { bug!() };
2801 match (def_kind, kind) {
2802 (DefKind::AssocTy, AssocItemKind::TyAlias(..))
2803 | (DefKind::AssocFn, AssocItemKind::Fn(..))
2804 | (DefKind::AssocConst, AssocItemKind::Const(..)) => {
2805 self.r.record_partial_res(id, PartialRes::new(res));
2811 // The method kind does not correspond to what appeared in the trait, report.
2812 let path = &self.current_trait_ref.as_ref().unwrap().1.path;
2813 let (code, kind) = match kind {
2814 AssocItemKind::Const(..) => (rustc_errors::error_code!(E0323), "const"),
2815 AssocItemKind::Fn(..) => (rustc_errors::error_code!(E0324), "method"),
2816 AssocItemKind::TyAlias(..) => (rustc_errors::error_code!(E0325), "type"),
2817 AssocItemKind::MacCall(..) => span_bug!(span, "unexpanded macro"),
2819 let trait_path = path_names_to_string(path);
2822 ResolutionError::TraitImplMismatch {
2827 trait_item_span: binding.span,
2832 fn resolve_params(&mut self, params: &'ast [Param]) {
2833 let mut bindings = smallvec![(PatBoundCtx::Product, Default::default())];
2834 for Param { pat, ty, .. } in params {
2835 self.resolve_pattern(pat, PatternSource::FnParam, &mut bindings);
2837 debug!("(resolving function / closure) recorded parameter");
2841 fn resolve_local(&mut self, local: &'ast Local) {
2842 debug!("resolving local ({:?})", local);
2843 // Resolve the type.
2844 walk_list!(self, visit_ty, &local.ty);
2846 // Resolve the initializer.
2847 if let Some((init, els)) = local.kind.init_else_opt() {
2848 self.visit_expr(init);
2850 // Resolve the `else` block
2851 if let Some(els) = els {
2852 self.visit_block(els);
2856 // Resolve the pattern.
2857 self.resolve_pattern_top(&local.pat, PatternSource::Let);
2860 /// build a map from pattern identifiers to binding-info's.
2861 /// this is done hygienically. This could arise for a macro
2862 /// that expands into an or-pattern where one 'x' was from the
2863 /// user and one 'x' came from the macro.
2864 fn binding_mode_map(&mut self, pat: &Pat) -> BindingMap {
2865 let mut binding_map = FxHashMap::default();
2867 pat.walk(&mut |pat| {
2869 PatKind::Ident(binding_mode, ident, ref sub_pat)
2870 if sub_pat.is_some() || self.is_base_res_local(pat.id) =>
2872 binding_map.insert(ident, BindingInfo { span: ident.span, binding_mode });
2874 PatKind::Or(ref ps) => {
2875 // Check the consistency of this or-pattern and
2876 // then add all bindings to the larger map.
2877 for bm in self.check_consistent_bindings(ps) {
2878 binding_map.extend(bm);
2891 fn is_base_res_local(&self, nid: NodeId) -> bool {
2892 matches!(self.r.partial_res_map.get(&nid).map(|res| res.base_res()), Some(Res::Local(..)))
2895 /// Checks that all of the arms in an or-pattern have exactly the
2896 /// same set of bindings, with the same binding modes for each.
2897 fn check_consistent_bindings(&mut self, pats: &[P<Pat>]) -> Vec<BindingMap> {
2898 let mut missing_vars = FxHashMap::default();
2899 let mut inconsistent_vars = FxHashMap::default();
2901 // 1) Compute the binding maps of all arms.
2902 let maps = pats.iter().map(|pat| self.binding_mode_map(pat)).collect::<Vec<_>>();
2904 // 2) Record any missing bindings or binding mode inconsistencies.
2905 for (map_outer, pat_outer) in pats.iter().enumerate().map(|(idx, pat)| (&maps[idx], pat)) {
2906 // Check against all arms except for the same pattern which is always self-consistent.
2910 .filter(|(_, pat)| pat.id != pat_outer.id)
2911 .flat_map(|(idx, _)| maps[idx].iter())
2912 .map(|(key, binding)| (key.name, map_outer.get(&key), binding));
2914 for (name, info, &binding_inner) in inners {
2917 // The inner binding is missing in the outer.
2919 missing_vars.entry(name).or_insert_with(|| BindingError {
2921 origin: BTreeSet::new(),
2922 target: BTreeSet::new(),
2923 could_be_path: name.as_str().starts_with(char::is_uppercase),
2925 binding_error.origin.insert(binding_inner.span);
2926 binding_error.target.insert(pat_outer.span);
2928 Some(binding_outer) => {
2929 if binding_outer.binding_mode != binding_inner.binding_mode {
2930 // The binding modes in the outer and inner bindings differ.
2933 .or_insert((binding_inner.span, binding_outer.span));
2940 // 3) Report all missing variables we found.
2941 let mut missing_vars = missing_vars.into_iter().collect::<Vec<_>>();
2942 missing_vars.sort_by_key(|&(sym, ref _err)| sym);
2944 for (name, mut v) in missing_vars.into_iter() {
2945 if inconsistent_vars.contains_key(&name) {
2946 v.could_be_path = false;
2949 *v.origin.iter().next().unwrap(),
2950 ResolutionError::VariableNotBoundInPattern(v, self.parent_scope),
2954 // 4) Report all inconsistencies in binding modes we found.
2955 let mut inconsistent_vars = inconsistent_vars.iter().collect::<Vec<_>>();
2956 inconsistent_vars.sort();
2957 for (name, v) in inconsistent_vars {
2958 self.report_error(v.0, ResolutionError::VariableBoundWithDifferentMode(*name, v.1));
2961 // 5) Finally bubble up all the binding maps.
2965 /// Check the consistency of the outermost or-patterns.
2966 fn check_consistent_bindings_top(&mut self, pat: &'ast Pat) {
2967 pat.walk(&mut |pat| match pat.kind {
2968 PatKind::Or(ref ps) => {
2969 self.check_consistent_bindings(ps);
2976 fn resolve_arm(&mut self, arm: &'ast Arm) {
2977 self.with_rib(ValueNS, NormalRibKind, |this| {
2978 this.resolve_pattern_top(&arm.pat, PatternSource::Match);
2979 walk_list!(this, visit_expr, &arm.guard);
2980 this.visit_expr(&arm.body);
2984 /// Arising from `source`, resolve a top level pattern.
2985 fn resolve_pattern_top(&mut self, pat: &'ast Pat, pat_src: PatternSource) {
2986 let mut bindings = smallvec![(PatBoundCtx::Product, Default::default())];
2987 self.resolve_pattern(pat, pat_src, &mut bindings);
2993 pat_src: PatternSource,
2994 bindings: &mut SmallVec<[(PatBoundCtx, FxHashSet<Ident>); 1]>,
2996 // We walk the pattern before declaring the pattern's inner bindings,
2997 // so that we avoid resolving a literal expression to a binding defined
2999 visit::walk_pat(self, pat);
3000 self.resolve_pattern_inner(pat, pat_src, bindings);
3001 // This has to happen *after* we determine which pat_idents are variants:
3002 self.check_consistent_bindings_top(pat);
3005 /// Resolve bindings in a pattern. This is a helper to `resolve_pattern`.
3009 /// A stack of sets of bindings accumulated.
3011 /// In each set, `PatBoundCtx::Product` denotes that a found binding in it should
3012 /// be interpreted as re-binding an already bound binding. This results in an error.
3013 /// Meanwhile, `PatBound::Or` denotes that a found binding in the set should result
3014 /// in reusing this binding rather than creating a fresh one.
3016 /// When called at the top level, the stack must have a single element
3017 /// with `PatBound::Product`. Otherwise, pushing to the stack happens as
3018 /// or-patterns (`p_0 | ... | p_n`) are encountered and the context needs
3019 /// to be switched to `PatBoundCtx::Or` and then `PatBoundCtx::Product` for each `p_i`.
3020 /// When each `p_i` has been dealt with, the top set is merged with its parent.
3021 /// When a whole or-pattern has been dealt with, the thing happens.
3023 /// See the implementation and `fresh_binding` for more details.
3024 fn resolve_pattern_inner(
3027 pat_src: PatternSource,
3028 bindings: &mut SmallVec<[(PatBoundCtx, FxHashSet<Ident>); 1]>,
3030 // Visit all direct subpatterns of this pattern.
3031 pat.walk(&mut |pat| {
3032 debug!("resolve_pattern pat={:?} node={:?}", pat, pat.kind);
3034 PatKind::Ident(bmode, ident, ref sub) => {
3035 // First try to resolve the identifier as some existing entity,
3036 // then fall back to a fresh binding.
3037 let has_sub = sub.is_some();
3039 .try_resolve_as_non_binding(pat_src, bmode, ident, has_sub)
3040 .unwrap_or_else(|| self.fresh_binding(ident, pat.id, pat_src, bindings));
3041 self.r.record_partial_res(pat.id, PartialRes::new(res));
3042 self.r.record_pat_span(pat.id, pat.span);
3044 PatKind::TupleStruct(ref qself, ref path, ref sub_patterns) => {
3045 self.smart_resolve_path(
3049 PathSource::TupleStruct(
3051 self.r.arenas.alloc_pattern_spans(sub_patterns.iter().map(|p| p.span)),
3055 PatKind::Path(ref qself, ref path) => {
3056 self.smart_resolve_path(pat.id, qself.as_ref(), path, PathSource::Pat);
3058 PatKind::Struct(ref qself, ref path, ..) => {
3059 self.smart_resolve_path(pat.id, qself.as_ref(), path, PathSource::Struct);
3061 PatKind::Or(ref ps) => {
3062 // Add a new set of bindings to the stack. `Or` here records that when a
3063 // binding already exists in this set, it should not result in an error because
3064 // `V1(a) | V2(a)` must be allowed and are checked for consistency later.
3065 bindings.push((PatBoundCtx::Or, Default::default()));
3067 // Now we need to switch back to a product context so that each
3068 // part of the or-pattern internally rejects already bound names.
3069 // For example, `V1(a) | V2(a, a)` and `V1(a, a) | V2(a)` are bad.
3070 bindings.push((PatBoundCtx::Product, Default::default()));
3071 self.resolve_pattern_inner(p, pat_src, bindings);
3072 // Move up the non-overlapping bindings to the or-pattern.
3073 // Existing bindings just get "merged".
3074 let collected = bindings.pop().unwrap().1;
3075 bindings.last_mut().unwrap().1.extend(collected);
3077 // This or-pattern itself can itself be part of a product,
3078 // e.g. `(V1(a) | V2(a), a)` or `(a, V1(a) | V2(a))`.
3079 // Both cases bind `a` again in a product pattern and must be rejected.
3080 let collected = bindings.pop().unwrap().1;
3081 bindings.last_mut().unwrap().1.extend(collected);
3083 // Prevent visiting `ps` as we've already done so above.
3096 pat_src: PatternSource,
3097 bindings: &mut SmallVec<[(PatBoundCtx, FxHashSet<Ident>); 1]>,
3099 // Add the binding to the local ribs, if it doesn't already exist in the bindings map.
3100 // (We must not add it if it's in the bindings map because that breaks the assumptions
3101 // later passes make about or-patterns.)
3102 let ident = ident.normalize_to_macro_rules();
3104 let mut bound_iter = bindings.iter().filter(|(_, set)| set.contains(&ident));
3105 // Already bound in a product pattern? e.g. `(a, a)` which is not allowed.
3106 let already_bound_and = bound_iter.clone().any(|(ctx, _)| *ctx == PatBoundCtx::Product);
3107 // Already bound in an or-pattern? e.g. `V1(a) | V2(a)`.
3108 // This is *required* for consistency which is checked later.
3109 let already_bound_or = bound_iter.any(|(ctx, _)| *ctx == PatBoundCtx::Or);
3111 if already_bound_and {
3112 // Overlap in a product pattern somewhere; report an error.
3113 use ResolutionError::*;
3114 let error = match pat_src {
3115 // `fn f(a: u8, a: u8)`:
3116 PatternSource::FnParam => IdentifierBoundMoreThanOnceInParameterList,
3118 _ => IdentifierBoundMoreThanOnceInSamePattern,
3120 self.report_error(ident.span, error(ident.name));
3123 // Record as bound if it's valid:
3124 let ident_valid = ident.name != kw::Empty;
3126 bindings.last_mut().unwrap().1.insert(ident);
3129 if already_bound_or {
3130 // `Variant1(a) | Variant2(a)`, ok
3131 // Reuse definition from the first `a`.
3132 self.innermost_rib_bindings(ValueNS)[&ident]
3134 let res = Res::Local(pat_id);
3136 // A completely fresh binding add to the set if it's valid.
3137 self.innermost_rib_bindings(ValueNS).insert(ident, res);
3143 fn innermost_rib_bindings(&mut self, ns: Namespace) -> &mut IdentMap<Res> {
3144 &mut self.ribs[ns].last_mut().unwrap().bindings
3147 fn try_resolve_as_non_binding(
3149 pat_src: PatternSource,
3154 // An immutable (no `mut`) by-value (no `ref`) binding pattern without
3155 // a sub pattern (no `@ $pat`) is syntactically ambiguous as it could
3156 // also be interpreted as a path to e.g. a constant, variant, etc.
3157 let is_syntactic_ambiguity = !has_sub && bm == BindingMode::ByValue(Mutability::Not);
3159 let ls_binding = self.maybe_resolve_ident_in_lexical_scope(ident, ValueNS)?;
3160 let (res, binding) = match ls_binding {
3161 LexicalScopeBinding::Item(binding)
3162 if is_syntactic_ambiguity && binding.is_ambiguity() =>
3164 // For ambiguous bindings we don't know all their definitions and cannot check
3165 // whether they can be shadowed by fresh bindings or not, so force an error.
3166 // issues/33118#issuecomment-233962221 (see below) still applies here,
3167 // but we have to ignore it for backward compatibility.
3168 self.r.record_use(ident, binding, false);
3171 LexicalScopeBinding::Item(binding) => (binding.res(), Some(binding)),
3172 LexicalScopeBinding::Res(res) => (res, None),
3176 Res::SelfCtor(_) // See #70549.
3178 DefKind::Ctor(_, CtorKind::Const) | DefKind::Const | DefKind::ConstParam,
3180 ) if is_syntactic_ambiguity => {
3181 // Disambiguate in favor of a unit struct/variant or constant pattern.
3182 if let Some(binding) = binding {
3183 self.r.record_use(ident, binding, false);
3187 Res::Def(DefKind::Ctor(..) | DefKind::Const | DefKind::Static(_), _) => {
3188 // This is unambiguously a fresh binding, either syntactically
3189 // (e.g., `IDENT @ PAT` or `ref IDENT`) or because `IDENT` resolves
3190 // to something unusable as a pattern (e.g., constructor function),
3191 // but we still conservatively report an error, see
3192 // issues/33118#issuecomment-233962221 for one reason why.
3193 let binding = binding.expect("no binding for a ctor or static");
3196 ResolutionError::BindingShadowsSomethingUnacceptable {
3197 shadowing_binding: pat_src,
3199 participle: if binding.is_import() { "imported" } else { "defined" },
3200 article: binding.res().article(),
3201 shadowed_binding: binding.res(),
3202 shadowed_binding_span: binding.span,
3207 Res::Def(DefKind::ConstParam, def_id) => {
3208 // Same as for DefKind::Const above, but here, `binding` is `None`, so we
3209 // have to construct the error differently
3212 ResolutionError::BindingShadowsSomethingUnacceptable {
3213 shadowing_binding: pat_src,
3215 participle: "defined",
3216 article: res.article(),
3217 shadowed_binding: res,
3218 shadowed_binding_span: self.r.opt_span(def_id).expect("const parameter defined outside of local crate"),
3223 Res::Def(DefKind::Fn, _) | Res::Local(..) | Res::Err => {
3224 // These entities are explicitly allowed to be shadowed by fresh bindings.
3227 Res::SelfCtor(_) => {
3228 // We resolve `Self` in pattern position as an ident sometimes during recovery,
3229 // so delay a bug instead of ICEing.
3230 self.r.session.delay_span_bug(
3232 "unexpected `SelfCtor` in pattern, expected identifier"
3238 "unexpected resolution for an identifier in pattern: {:?}",
3244 // High-level and context dependent path resolution routine.
3245 // Resolves the path and records the resolution into definition map.
3246 // If resolution fails tries several techniques to find likely
3247 // resolution candidates, suggest imports or other help, and report
3248 // errors in user friendly way.
3249 fn smart_resolve_path(
3252 qself: Option<&QSelf>,
3254 source: PathSource<'ast>,
3256 self.smart_resolve_path_fragment(
3258 &Segment::from_path(path),
3260 Finalize::new(id, path.span),
3264 fn smart_resolve_path_fragment(
3266 qself: Option<&QSelf>,
3268 source: PathSource<'ast>,
3272 "smart_resolve_path_fragment(qself={:?}, path={:?}, finalize={:?})",
3277 let ns = source.namespace();
3279 let Finalize { node_id, path_span, .. } = finalize;
3280 let report_errors = |this: &mut Self, res: Option<Res>| {
3281 if this.should_report_errs() {
3282 let (err, candidates) =
3283 this.smart_resolve_report_errors(path, path_span, source, res);
3285 let def_id = this.parent_scope.module.nearest_parent_mod();
3286 let instead = res.is_some();
3288 if res.is_none() { this.report_missing_type_error(path) } else { None };
3290 this.r.use_injections.push(UseError {
3300 PartialRes::new(Res::Err)
3303 // For paths originating from calls (like in `HashMap::new()`), tries
3304 // to enrich the plain `failed to resolve: ...` message with hints
3305 // about possible missing imports.
3307 // Similar thing, for types, happens in `report_errors` above.
3308 let report_errors_for_call = |this: &mut Self, parent_err: Spanned<ResolutionError<'a>>| {
3309 if !source.is_call() {
3310 return Some(parent_err);
3313 // Before we start looking for candidates, we have to get our hands
3314 // on the type user is trying to perform invocation on; basically:
3315 // we're transforming `HashMap::new` into just `HashMap`.
3316 let path = match path.split_last() {
3317 Some((_, path)) if !path.is_empty() => path,
3318 _ => return Some(parent_err),
3321 let (mut err, candidates) =
3322 this.smart_resolve_report_errors(path, path_span, PathSource::Type, None);
3324 if candidates.is_empty() {
3326 return Some(parent_err);
3329 // There are two different error messages user might receive at
3331 // - E0412 cannot find type `{}` in this scope
3332 // - E0433 failed to resolve: use of undeclared type or module `{}`
3334 // The first one is emitted for paths in type-position, and the
3335 // latter one - for paths in expression-position.
3337 // Thus (since we're in expression-position at this point), not to
3338 // confuse the user, we want to keep the *message* from E0432 (so
3339 // `parent_err`), but we want *hints* from E0412 (so `err`).
3341 // And that's what happens below - we're just mixing both messages
3342 // into a single one.
3343 let mut parent_err = this.r.into_struct_error(parent_err.span, parent_err.node);
3345 err.message = take(&mut parent_err.message);
3346 err.code = take(&mut parent_err.code);
3347 err.children = take(&mut parent_err.children);
3349 parent_err.cancel();
3351 let def_id = this.parent_scope.module.nearest_parent_mod();
3353 if this.should_report_errs() {
3354 this.r.use_injections.push(UseError {
3366 // We don't return `Some(parent_err)` here, because the error will
3367 // be already printed as part of the `use` injections
3371 let partial_res = match self.resolve_qpath_anywhere(
3376 source.defer_to_typeck(),
3379 Ok(Some(partial_res)) if partial_res.unresolved_segments() == 0 => {
3380 if source.is_expected(partial_res.base_res()) || partial_res.base_res() == Res::Err
3384 report_errors(self, Some(partial_res.base_res()))
3388 Ok(Some(partial_res)) if source.defer_to_typeck() => {
3389 // Not fully resolved associated item `T::A::B` or `<T as Tr>::A::B`
3390 // or `<T>::A::B`. If `B` should be resolved in value namespace then
3391 // it needs to be added to the trait map.
3393 let item_name = path.last().unwrap().ident;
3394 let traits = self.traits_in_scope(item_name, ns);
3395 self.r.trait_map.insert(node_id, traits);
3398 if PrimTy::from_name(path[0].ident.name).is_some() {
3399 let mut std_path = Vec::with_capacity(1 + path.len());
3401 std_path.push(Segment::from_ident(Ident::with_dummy_span(sym::std)));
3402 std_path.extend(path);
3403 if let PathResult::Module(_) | PathResult::NonModule(_) =
3404 self.resolve_path(&std_path, Some(ns), None)
3406 // Check if we wrote `str::from_utf8` instead of `std::str::from_utf8`
3408 path.iter().last().map_or(path_span, |segment| segment.ident.span);
3410 self.r.confused_type_with_std_module.insert(item_span, path_span);
3411 self.r.confused_type_with_std_module.insert(path_span, path_span);
3419 if let Some(err) = report_errors_for_call(self, err) {
3420 self.report_error(err.span, err.node);
3423 PartialRes::new(Res::Err)
3426 _ => report_errors(self, None),
3429 if !matches!(source, PathSource::TraitItem(..)) {
3430 // Avoid recording definition of `A::B` in `<T as A>::B::C`.
3431 self.r.record_partial_res(node_id, partial_res);
3432 self.resolve_elided_lifetimes_in_path(node_id, partial_res, path, source, path_span);
3438 fn self_type_is_available(&mut self) -> bool {
3440 .maybe_resolve_ident_in_lexical_scope(Ident::with_dummy_span(kw::SelfUpper), TypeNS);
3441 if let Some(LexicalScopeBinding::Res(res)) = binding { res != Res::Err } else { false }
3444 fn self_value_is_available(&mut self, self_span: Span) -> bool {
3445 let ident = Ident::new(kw::SelfLower, self_span);
3446 let binding = self.maybe_resolve_ident_in_lexical_scope(ident, ValueNS);
3447 if let Some(LexicalScopeBinding::Res(res)) = binding { res != Res::Err } else { false }
3450 /// A wrapper around [`Resolver::report_error`].
3452 /// This doesn't emit errors for function bodies if this is rustdoc.
3453 fn report_error(&mut self, span: Span, resolution_error: ResolutionError<'a>) {
3454 if self.should_report_errs() {
3455 self.r.report_error(span, resolution_error);
3460 /// If we're actually rustdoc then avoid giving a name resolution error for `cfg()` items.
3461 fn should_report_errs(&self) -> bool {
3462 !(self.r.session.opts.actually_rustdoc && self.in_func_body)
3465 // Resolve in alternative namespaces if resolution in the primary namespace fails.
3466 fn resolve_qpath_anywhere(
3468 qself: Option<&QSelf>,
3470 primary_ns: Namespace,
3472 defer_to_typeck: bool,
3474 ) -> Result<Option<PartialRes>, Spanned<ResolutionError<'a>>> {
3475 let mut fin_res = None;
3477 for (i, &ns) in [primary_ns, TypeNS, ValueNS].iter().enumerate() {
3478 if i == 0 || ns != primary_ns {
3479 match self.resolve_qpath(qself, path, ns, finalize)? {
3481 if partial_res.unresolved_segments() == 0 || defer_to_typeck =>
3483 return Ok(Some(partial_res));
3486 if fin_res.is_none() {
3487 fin_res = partial_res;
3494 assert!(primary_ns != MacroNS);
3496 if qself.is_none() {
3497 let path_seg = |seg: &Segment| PathSegment::from_ident(seg.ident);
3498 let path = Path { segments: path.iter().map(path_seg).collect(), span, tokens: None };
3499 if let Ok((_, res)) =
3500 self.r.resolve_macro_path(&path, None, &self.parent_scope, false, false)
3502 return Ok(Some(PartialRes::new(res)));
3509 /// Handles paths that may refer to associated items.
3512 qself: Option<&QSelf>,
3516 ) -> Result<Option<PartialRes>, Spanned<ResolutionError<'a>>> {
3518 "resolve_qpath(qself={:?}, path={:?}, ns={:?}, finalize={:?})",
3519 qself, path, ns, finalize,
3522 if let Some(qself) = qself {
3523 if qself.position == 0 {
3524 // This is a case like `<T>::B`, where there is no
3525 // trait to resolve. In that case, we leave the `B`
3526 // segment to be resolved by type-check.
3527 return Ok(Some(PartialRes::with_unresolved_segments(
3528 Res::Def(DefKind::Mod, CRATE_DEF_ID.to_def_id()),
3533 // Make sure `A::B` in `<T as A::B>::C` is a trait item.
3535 // Currently, `path` names the full item (`A::B::C`, in
3536 // our example). so we extract the prefix of that that is
3537 // the trait (the slice upto and including
3538 // `qself.position`). And then we recursively resolve that,
3539 // but with `qself` set to `None`.
3540 let ns = if qself.position + 1 == path.len() { ns } else { TypeNS };
3541 let partial_res = self.smart_resolve_path_fragment(
3543 &path[..=qself.position],
3544 PathSource::TraitItem(ns),
3545 Finalize::with_root_span(finalize.node_id, finalize.path_span, qself.path_span),
3548 // The remaining segments (the `C` in our example) will
3549 // have to be resolved by type-check, since that requires doing
3550 // trait resolution.
3551 return Ok(Some(PartialRes::with_unresolved_segments(
3552 partial_res.base_res(),
3553 partial_res.unresolved_segments() + path.len() - qself.position - 1,
3557 let result = match self.resolve_path(&path, Some(ns), Some(finalize)) {
3558 PathResult::NonModule(path_res) => path_res,
3559 PathResult::Module(ModuleOrUniformRoot::Module(module)) if !module.is_normal() => {
3560 PartialRes::new(module.res().unwrap())
3562 // In `a(::assoc_item)*` `a` cannot be a module. If `a` does resolve to a module we
3563 // don't report an error right away, but try to fallback to a primitive type.
3564 // So, we are still able to successfully resolve something like
3566 // use std::u8; // bring module u8 in scope
3567 // fn f() -> u8 { // OK, resolves to primitive u8, not to std::u8
3568 // u8::max_value() // OK, resolves to associated function <u8>::max_value,
3569 // // not to non-existent std::u8::max_value
3572 // Such behavior is required for backward compatibility.
3573 // The same fallback is used when `a` resolves to nothing.
3574 PathResult::Module(ModuleOrUniformRoot::Module(_)) | PathResult::Failed { .. }
3575 if (ns == TypeNS || path.len() > 1)
3576 && PrimTy::from_name(path[0].ident.name).is_some() =>
3578 let prim = PrimTy::from_name(path[0].ident.name).unwrap();
3579 PartialRes::with_unresolved_segments(Res::PrimTy(prim), path.len() - 1)
3581 PathResult::Module(ModuleOrUniformRoot::Module(module)) => {
3582 PartialRes::new(module.res().unwrap())
3584 PathResult::Failed { is_error_from_last_segment: false, span, label, suggestion } => {
3585 return Err(respan(span, ResolutionError::FailedToResolve { label, suggestion }));
3587 PathResult::Module(..) | PathResult::Failed { .. } => return Ok(None),
3588 PathResult::Indeterminate => bug!("indeterminate path result in resolve_qpath"),
3592 && result.base_res() != Res::Err
3593 && path[0].ident.name != kw::PathRoot
3594 && path[0].ident.name != kw::DollarCrate
3596 let unqualified_result = {
3597 match self.resolve_path(&[*path.last().unwrap()], Some(ns), None) {
3598 PathResult::NonModule(path_res) => path_res.base_res(),
3599 PathResult::Module(ModuleOrUniformRoot::Module(module)) => {
3600 module.res().unwrap()
3602 _ => return Ok(Some(result)),
3605 if result.base_res() == unqualified_result {
3606 let lint = lint::builtin::UNUSED_QUALIFICATIONS;
3607 self.r.lint_buffer.buffer_lint(
3611 "unnecessary qualification",
3619 fn with_resolved_label(&mut self, label: Option<Label>, id: NodeId, f: impl FnOnce(&mut Self)) {
3620 if let Some(label) = label {
3621 if label.ident.as_str().as_bytes()[1] != b'_' {
3622 self.diagnostic_metadata.unused_labels.insert(id, label.ident.span);
3625 if let Ok((_, orig_span)) = self.resolve_label(label.ident) {
3626 diagnostics::signal_label_shadowing(self.r.session, orig_span, label.ident)
3629 self.with_label_rib(NormalRibKind, |this| {
3630 let ident = label.ident.normalize_to_macro_rules();
3631 this.label_ribs.last_mut().unwrap().bindings.insert(ident, id);
3639 fn resolve_labeled_block(&mut self, label: Option<Label>, id: NodeId, block: &'ast Block) {
3640 self.with_resolved_label(label, id, |this| this.visit_block(block));
3643 fn resolve_block(&mut self, block: &'ast Block) {
3644 debug!("(resolving block) entering block");
3645 // Move down in the graph, if there's an anonymous module rooted here.
3646 let orig_module = self.parent_scope.module;
3647 let anonymous_module = self.r.block_map.get(&block.id).cloned(); // clones a reference
3649 let mut num_macro_definition_ribs = 0;
3650 if let Some(anonymous_module) = anonymous_module {
3651 debug!("(resolving block) found anonymous module, moving down");
3652 self.ribs[ValueNS].push(Rib::new(ModuleRibKind(anonymous_module)));
3653 self.ribs[TypeNS].push(Rib::new(ModuleRibKind(anonymous_module)));
3654 self.parent_scope.module = anonymous_module;
3656 self.ribs[ValueNS].push(Rib::new(NormalRibKind));
3659 let prev = self.diagnostic_metadata.current_block_could_be_bare_struct_literal.take();
3660 if let (true, [Stmt { kind: StmtKind::Expr(expr), .. }]) =
3661 (block.could_be_bare_literal, &block.stmts[..])
3662 && let ExprKind::Type(..) = expr.kind
3664 self.diagnostic_metadata.current_block_could_be_bare_struct_literal =
3667 // Descend into the block.
3668 for stmt in &block.stmts {
3669 if let StmtKind::Item(ref item) = stmt.kind
3670 && let ItemKind::MacroDef(..) = item.kind {
3671 num_macro_definition_ribs += 1;
3672 let res = self.r.local_def_id(item.id).to_def_id();
3673 self.ribs[ValueNS].push(Rib::new(MacroDefinition(res)));
3674 self.label_ribs.push(Rib::new(MacroDefinition(res)));
3677 self.visit_stmt(stmt);
3679 self.diagnostic_metadata.current_block_could_be_bare_struct_literal = prev;
3682 self.parent_scope.module = orig_module;
3683 for _ in 0..num_macro_definition_ribs {
3684 self.ribs[ValueNS].pop();
3685 self.label_ribs.pop();
3687 self.ribs[ValueNS].pop();
3688 if anonymous_module.is_some() {
3689 self.ribs[TypeNS].pop();
3691 debug!("(resolving block) leaving block");
3694 fn resolve_anon_const(&mut self, constant: &'ast AnonConst, is_repeat: IsRepeatExpr) {
3695 debug!("resolve_anon_const {:?} is_repeat: {:?}", constant, is_repeat);
3696 self.with_constant_rib(
3698 if constant.value.is_potential_trivial_const_param() {
3699 ConstantHasGenerics::Yes
3701 ConstantHasGenerics::No
3704 |this| visit::walk_anon_const(this, constant),
3708 fn resolve_inline_const(&mut self, constant: &'ast AnonConst) {
3709 debug!("resolve_anon_const {constant:?}");
3710 self.with_constant_rib(IsRepeatExpr::No, ConstantHasGenerics::Yes, None, |this| {
3711 visit::walk_anon_const(this, constant)
3715 fn resolve_expr(&mut self, expr: &'ast Expr, parent: Option<&'ast Expr>) {
3716 // First, record candidate traits for this expression if it could
3717 // result in the invocation of a method call.
3719 self.record_candidate_traits_for_expr_if_necessary(expr);
3721 // Next, resolve the node.
3723 ExprKind::Path(ref qself, ref path) => {
3724 self.smart_resolve_path(expr.id, qself.as_ref(), path, PathSource::Expr(parent));
3725 visit::walk_expr(self, expr);
3728 ExprKind::Struct(ref se) => {
3729 self.smart_resolve_path(expr.id, se.qself.as_ref(), &se.path, PathSource::Struct);
3730 visit::walk_expr(self, expr);
3733 ExprKind::Break(Some(label), _) | ExprKind::Continue(Some(label)) => {
3734 match self.resolve_label(label.ident) {
3735 Ok((node_id, _)) => {
3736 // Since this res is a label, it is never read.
3737 self.r.label_res_map.insert(expr.id, node_id);
3738 self.diagnostic_metadata.unused_labels.remove(&node_id);
3741 self.report_error(label.ident.span, error);
3745 // visit `break` argument if any
3746 visit::walk_expr(self, expr);
3749 ExprKind::Break(None, Some(ref e)) => {
3750 // We use this instead of `visit::walk_expr` to keep the parent expr around for
3751 // better diagnostics.
3752 self.resolve_expr(e, Some(&expr));
3755 ExprKind::Let(ref pat, ref scrutinee, _) => {
3756 self.visit_expr(scrutinee);
3757 self.resolve_pattern_top(pat, PatternSource::Let);
3760 ExprKind::If(ref cond, ref then, ref opt_else) => {
3761 self.with_rib(ValueNS, NormalRibKind, |this| {
3762 let old = this.diagnostic_metadata.in_if_condition.replace(cond);
3763 this.visit_expr(cond);
3764 this.diagnostic_metadata.in_if_condition = old;
3765 this.visit_block(then);
3767 if let Some(expr) = opt_else {
3768 self.visit_expr(expr);
3772 ExprKind::Loop(ref block, label) => self.resolve_labeled_block(label, expr.id, &block),
3774 ExprKind::While(ref cond, ref block, label) => {
3775 self.with_resolved_label(label, expr.id, |this| {
3776 this.with_rib(ValueNS, NormalRibKind, |this| {
3777 let old = this.diagnostic_metadata.in_if_condition.replace(cond);
3778 this.visit_expr(cond);
3779 this.diagnostic_metadata.in_if_condition = old;
3780 this.visit_block(block);
3785 ExprKind::ForLoop(ref pat, ref iter_expr, ref block, label) => {
3786 self.visit_expr(iter_expr);
3787 self.with_rib(ValueNS, NormalRibKind, |this| {
3788 this.resolve_pattern_top(pat, PatternSource::For);
3789 this.resolve_labeled_block(label, expr.id, block);
3793 ExprKind::Block(ref block, label) => self.resolve_labeled_block(label, block.id, block),
3795 // Equivalent to `visit::walk_expr` + passing some context to children.
3796 ExprKind::Field(ref subexpression, _) => {
3797 self.resolve_expr(subexpression, Some(expr));
3799 ExprKind::MethodCall(ref segment, ref receiver, ref arguments, _) => {
3800 self.resolve_expr(receiver, Some(expr));
3801 for argument in arguments {
3802 self.resolve_expr(argument, None);
3804 self.visit_path_segment(expr.span, segment);
3807 ExprKind::Call(ref callee, ref arguments) => {
3808 self.resolve_expr(callee, Some(expr));
3809 let const_args = self.r.legacy_const_generic_args(callee).unwrap_or_default();
3810 for (idx, argument) in arguments.iter().enumerate() {
3811 // Constant arguments need to be treated as AnonConst since
3812 // that is how they will be later lowered to HIR.
3813 if const_args.contains(&idx) {
3814 self.with_constant_rib(
3816 if argument.is_potential_trivial_const_param() {
3817 ConstantHasGenerics::Yes
3819 ConstantHasGenerics::No
3823 this.resolve_expr(argument, None);
3827 self.resolve_expr(argument, None);
3831 ExprKind::Type(ref type_expr, ref ty) => {
3832 // `ParseSess::type_ascription_path_suggestions` keeps spans of colon tokens in
3833 // type ascription. Here we are trying to retrieve the span of the colon token as
3834 // well, but only if it's written without spaces `expr:Ty` and therefore confusable
3835 // with `expr::Ty`, only in this case it will match the span from
3836 // `type_ascription_path_suggestions`.
3837 self.diagnostic_metadata
3838 .current_type_ascription
3839 .push(type_expr.span.between(ty.span));
3840 visit::walk_expr(self, expr);
3841 self.diagnostic_metadata.current_type_ascription.pop();
3843 // `async |x| ...` gets desugared to `|x| future_from_generator(|| ...)`, so we need to
3844 // resolve the arguments within the proper scopes so that usages of them inside the
3845 // closure are detected as upvars rather than normal closure arg usages.
3846 ExprKind::Closure(_, _, Async::Yes { .. }, _, ref fn_decl, ref body, _span) => {
3847 self.with_rib(ValueNS, NormalRibKind, |this| {
3848 this.with_label_rib(ClosureOrAsyncRibKind, |this| {
3849 // Resolve arguments:
3850 this.resolve_params(&fn_decl.inputs);
3851 // No need to resolve return type --
3852 // the outer closure return type is `FnRetTy::Default`.
3854 // Now resolve the inner closure
3856 // No need to resolve arguments: the inner closure has none.
3857 // Resolve the return type:
3858 visit::walk_fn_ret_ty(this, &fn_decl.output);
3860 this.visit_expr(body);
3865 // For closures, ClosureOrAsyncRibKind is added in visit_fn
3866 ExprKind::Closure(ClosureBinder::For { ref generic_params, span }, ..) => {
3867 self.with_generic_param_rib(
3870 LifetimeRibKind::Generics {
3872 kind: LifetimeBinderKind::Closure,
3875 |this| visit::walk_expr(this, expr),
3878 ExprKind::Closure(..) => visit::walk_expr(self, expr),
3879 ExprKind::Async(..) => {
3880 self.with_label_rib(ClosureOrAsyncRibKind, |this| visit::walk_expr(this, expr));
3882 ExprKind::Repeat(ref elem, ref ct) => {
3883 self.visit_expr(elem);
3884 self.with_lifetime_rib(LifetimeRibKind::AnonConst, |this| {
3885 this.with_lifetime_rib(LifetimeRibKind::Elided(LifetimeRes::Static), |this| {
3886 this.resolve_anon_const(ct, IsRepeatExpr::Yes)
3890 ExprKind::ConstBlock(ref ct) => {
3891 self.resolve_inline_const(ct);
3893 ExprKind::Index(ref elem, ref idx) => {
3894 self.resolve_expr(elem, Some(expr));
3895 self.visit_expr(idx);
3898 visit::walk_expr(self, expr);
3903 fn record_candidate_traits_for_expr_if_necessary(&mut self, expr: &'ast Expr) {
3905 ExprKind::Field(_, ident) => {
3906 // FIXME(#6890): Even though you can't treat a method like a
3907 // field, we need to add any trait methods we find that match
3908 // the field name so that we can do some nice error reporting
3909 // later on in typeck.
3910 let traits = self.traits_in_scope(ident, ValueNS);
3911 self.r.trait_map.insert(expr.id, traits);
3913 ExprKind::MethodCall(ref segment, ..) => {
3914 debug!("(recording candidate traits for expr) recording traits for {}", expr.id);
3915 let traits = self.traits_in_scope(segment.ident, ValueNS);
3916 self.r.trait_map.insert(expr.id, traits);
3924 fn traits_in_scope(&mut self, ident: Ident, ns: Namespace) -> Vec<TraitCandidate> {
3925 self.r.traits_in_scope(
3926 self.current_trait_ref.as_ref().map(|(module, _)| *module),
3929 Some((ident.name, ns)),
3934 struct LifetimeCountVisitor<'a, 'b> {
3935 r: &'b mut Resolver<'a>,
3938 /// Walks the whole crate in DFS order, visiting each item, counting the declared number of
3939 /// lifetime generic parameters.
3940 impl<'ast> Visitor<'ast> for LifetimeCountVisitor<'_, '_> {
3941 fn visit_item(&mut self, item: &'ast Item) {
3943 ItemKind::TyAlias(box TyAlias { ref generics, .. })
3944 | ItemKind::Fn(box Fn { ref generics, .. })
3945 | ItemKind::Enum(_, ref generics)
3946 | ItemKind::Struct(_, ref generics)
3947 | ItemKind::Union(_, ref generics)
3948 | ItemKind::Impl(box Impl { ref generics, .. })
3949 | ItemKind::Trait(box Trait { ref generics, .. })
3950 | ItemKind::TraitAlias(ref generics, _) => {
3951 let def_id = self.r.local_def_id(item.id);
3952 let count = generics
3955 .filter(|param| matches!(param.kind, ast::GenericParamKind::Lifetime { .. }))
3957 self.r.item_generics_num_lifetimes.insert(def_id, count);
3961 | ItemKind::ForeignMod(..)
3962 | ItemKind::Static(..)
3963 | ItemKind::Const(..)
3965 | ItemKind::ExternCrate(..)
3966 | ItemKind::MacroDef(..)
3967 | ItemKind::GlobalAsm(..)
3968 | ItemKind::MacCall(..) => {}
3970 visit::walk_item(self, item)
3974 impl<'a> Resolver<'a> {
3975 pub(crate) fn late_resolve_crate(&mut self, krate: &Crate) {
3976 visit::walk_crate(&mut LifetimeCountVisitor { r: self }, krate);
3977 let mut late_resolution_visitor = LateResolutionVisitor::new(self);
3978 visit::walk_crate(&mut late_resolution_visitor, krate);
3979 for (id, span) in late_resolution_visitor.diagnostic_metadata.unused_labels.iter() {
3980 self.lint_buffer.buffer_lint(lint::builtin::UNUSED_LABELS, *id, *span, "unused label");