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, LOCAL_CRATE};
23 use rustc_hir::{BindingAnnotation, 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 type Res = def::Res<NodeId>;
40 type IdentMap<T> = FxHashMap<Ident, T>;
42 /// Map from the name in a pattern to its binding mode.
43 type BindingMap = IdentMap<BindingInfo>;
46 ElisionFnParameter, LifetimeElisionCandidate, MissingLifetime, MissingLifetimeKind,
49 #[derive(Copy, Clone, Debug)]
52 annotation: BindingAnnotation,
55 #[derive(Copy, Clone, PartialEq, Eq, Debug)]
56 pub enum PatternSource {
63 #[derive(Copy, Clone, Debug, PartialEq, Eq)]
70 pub fn descr(self) -> &'static str {
72 PatternSource::Match => "match binding",
73 PatternSource::Let => "let binding",
74 PatternSource::For => "for binding",
75 PatternSource::FnParam => "function parameter",
80 /// Denotes whether the context for the set of already bound bindings is a `Product`
81 /// or `Or` context. This is used in e.g., `fresh_binding` and `resolve_pattern_inner`.
82 /// See those functions for more information.
85 /// A product pattern context, e.g., `Variant(a, b)`.
87 /// An or-pattern context, e.g., `p_0 | ... | p_n`.
91 /// Does this the item (from the item rib scope) allow generic parameters?
92 #[derive(Copy, Clone, Debug)]
93 pub(crate) enum HasGenericParams {
98 /// May this constant have generics?
99 #[derive(Copy, Clone, Debug, Eq, PartialEq)]
100 pub(crate) enum ConstantHasGenerics {
105 impl ConstantHasGenerics {
106 fn force_yes_if(self, b: bool) -> Self {
107 if b { Self::Yes } else { self }
111 #[derive(Copy, Clone, Debug, Eq, PartialEq)]
112 pub(crate) enum ConstantItemKind {
117 /// The rib kind restricts certain accesses,
118 /// e.g. to a `Res::Local` of an outer item.
119 #[derive(Copy, Clone, Debug)]
120 pub(crate) enum RibKind<'a> {
121 /// No restriction needs to be applied.
124 /// We passed through an impl or trait and are now in one of its
125 /// methods or associated types. Allow references to ty params that impl or trait
126 /// binds. Disallow any other upvars (including other ty params that are
130 /// We passed through a closure. Disallow labels.
131 ClosureOrAsyncRibKind,
133 /// We passed through an item scope. Disallow upvars.
134 ItemRibKind(HasGenericParams),
136 /// We're in a constant item. Can't refer to dynamic stuff.
138 /// The item may reference generic parameters in trivial constant expressions.
139 /// All other constants aren't allowed to use generic params at all.
140 ConstantItemRibKind(ConstantHasGenerics, Option<(Ident, ConstantItemKind)>),
142 /// We passed through a module.
143 ModuleRibKind(Module<'a>),
145 /// We passed through a `macro_rules!` statement
146 MacroDefinition(DefId),
148 /// All bindings in this rib are generic parameters that can't be used
149 /// from the default of a generic parameter because they're not declared
150 /// before said generic parameter. Also see the `visit_generics` override.
151 ForwardGenericParamBanRibKind,
153 /// We are inside of the type of a const parameter. Can't refer to any
157 /// We are inside a `sym` inline assembly operand. Can only refer to
163 /// Whether this rib kind contains generic parameters, as opposed to local
165 pub(crate) fn contains_params(&self) -> bool {
168 | ClosureOrAsyncRibKind
169 | ConstantItemRibKind(..)
172 | ConstParamTyRibKind
173 | InlineAsmSymRibKind => false,
174 AssocItemRibKind | ItemRibKind(_) | ForwardGenericParamBanRibKind => true,
178 /// This rib forbids referring to labels defined in upwards ribs.
179 fn is_label_barrier(self) -> bool {
181 NormalRibKind | MacroDefinition(..) => false,
184 | ClosureOrAsyncRibKind
186 | ConstantItemRibKind(..)
188 | ForwardGenericParamBanRibKind
189 | ConstParamTyRibKind
190 | InlineAsmSymRibKind => true,
195 /// A single local scope.
197 /// A rib represents a scope names can live in. Note that these appear in many places, not just
198 /// around braces. At any place where the list of accessible names (of the given namespace)
199 /// changes or a new restrictions on the name accessibility are introduced, a new rib is put onto a
200 /// stack. This may be, for example, a `let` statement (because it introduces variables), a macro,
203 /// Different [rib kinds](enum@RibKind) are transparent for different names.
205 /// The resolution keeps a separate stack of ribs as it traverses the AST for each namespace. When
206 /// resolving, the name is looked up from inside out.
208 pub(crate) struct Rib<'a, R = Res> {
209 pub bindings: IdentMap<R>,
210 pub kind: RibKind<'a>,
213 impl<'a, R> Rib<'a, R> {
214 fn new(kind: RibKind<'a>) -> Rib<'a, R> {
215 Rib { bindings: Default::default(), kind }
219 #[derive(Clone, Copy, Debug)]
220 enum LifetimeUseSet {
221 One { use_span: Span, use_ctxt: visit::LifetimeCtxt },
225 #[derive(Copy, Clone, Debug)]
226 enum LifetimeRibKind {
227 // -- Ribs introducing named lifetimes
229 /// This rib declares generic parameters.
230 /// Only for this kind the `LifetimeRib::bindings` field can be non-empty.
231 Generics { binder: NodeId, span: Span, kind: LifetimeBinderKind },
233 // -- Ribs introducing unnamed lifetimes
235 /// Create a new anonymous lifetime parameter and reference it.
237 /// If `report_in_path`, report an error when encountering lifetime elision in a path:
239 /// struct Foo<'a> { x: &'a () }
240 /// async fn foo(x: Foo) {}
243 /// Note: the error should not trigger when the elided lifetime is in a pattern or
244 /// expression-position path:
246 /// struct Foo<'a> { x: &'a () }
247 /// async fn foo(Foo { x: _ }: Foo<'_>) {}
249 AnonymousCreateParameter { binder: NodeId, report_in_path: bool },
251 /// Replace all anonymous lifetimes by provided lifetime.
254 // -- Barrier ribs that stop lifetime lookup, or continue it but produce an error later.
256 /// Give a hard error when either `&` or `'_` is written. Used to
257 /// rule out things like `where T: Foo<'_>`. Does not imply an
258 /// error on default object bounds (e.g., `Box<dyn Foo>`).
259 AnonymousReportError,
261 /// Signal we cannot find which should be the anonymous lifetime.
264 /// FIXME(const_generics): This patches over an ICE caused by non-'static lifetimes in const
265 /// generics. We are disallowing this until we can decide on how we want to handle non-'static
266 /// lifetimes in const generics. See issue #74052 for discussion.
269 /// Non-static lifetimes are prohibited in anonymous constants under `min_const_generics`.
270 /// This function will emit an error if `generic_const_exprs` is not enabled, the body
271 /// identified by `body_id` is an anonymous constant and `lifetime_ref` is non-static.
274 /// This rib acts as a barrier to forbid reference to lifetimes of a parent item.
278 #[derive(Copy, Clone, Debug)]
279 enum LifetimeBinderKind {
289 impl LifetimeBinderKind {
290 fn descr(self) -> &'static str {
291 use LifetimeBinderKind::*;
293 BareFnType => "type",
294 PolyTrait => "bound",
295 WhereBound => "bound",
297 ImplBlock => "impl block",
298 Function => "function",
299 Closure => "closure",
306 kind: LifetimeRibKind,
307 // We need to preserve insertion order for async fns.
308 bindings: FxIndexMap<Ident, (NodeId, LifetimeRes)>,
312 fn new(kind: LifetimeRibKind) -> LifetimeRib {
313 LifetimeRib { bindings: Default::default(), kind }
317 #[derive(Copy, Clone, PartialEq, Eq, Debug)]
318 pub(crate) enum AliasPossibility {
323 #[derive(Copy, Clone, Debug)]
324 pub(crate) enum PathSource<'a> {
325 // Type paths `Path`.
327 // Trait paths in bounds or impls.
328 Trait(AliasPossibility),
329 // Expression paths `path`, with optional parent context.
330 Expr(Option<&'a Expr>),
331 // Paths in path patterns `Path`.
333 // Paths in struct expressions and patterns `Path { .. }`.
335 // Paths in tuple struct patterns `Path(..)`.
336 TupleStruct(Span, &'a [Span]),
337 // `m::A::B` in `<T as m::A>::B::C`.
338 TraitItem(Namespace),
341 impl<'a> PathSource<'a> {
342 fn namespace(self) -> Namespace {
344 PathSource::Type | PathSource::Trait(_) | PathSource::Struct => TypeNS,
345 PathSource::Expr(..) | PathSource::Pat | PathSource::TupleStruct(..) => ValueNS,
346 PathSource::TraitItem(ns) => ns,
350 fn defer_to_typeck(self) -> bool {
353 | PathSource::Expr(..)
356 | PathSource::TupleStruct(..) => true,
357 PathSource::Trait(_) | PathSource::TraitItem(..) => false,
361 fn descr_expected(self) -> &'static str {
363 PathSource::Type => "type",
364 PathSource::Trait(_) => "trait",
365 PathSource::Pat => "unit struct, unit variant or constant",
366 PathSource::Struct => "struct, variant or union type",
367 PathSource::TupleStruct(..) => "tuple struct or tuple variant",
368 PathSource::TraitItem(ns) => match ns {
369 TypeNS => "associated type",
370 ValueNS => "method or associated constant",
371 MacroNS => bug!("associated macro"),
373 PathSource::Expr(parent) => match parent.as_ref().map(|p| &p.kind) {
374 // "function" here means "anything callable" rather than `DefKind::Fn`,
375 // this is not precise but usually more helpful than just "value".
376 Some(ExprKind::Call(call_expr, _)) => match &call_expr.kind {
377 // the case of `::some_crate()`
378 ExprKind::Path(_, path)
379 if path.segments.len() == 2
380 && path.segments[0].ident.name == kw::PathRoot =>
384 ExprKind::Path(_, path) => {
385 let mut msg = "function";
386 if let Some(segment) = path.segments.iter().last() {
387 if let Some(c) = segment.ident.to_string().chars().next() {
388 if c.is_uppercase() {
389 msg = "function, tuple struct or tuple variant";
402 fn is_call(self) -> bool {
403 matches!(self, PathSource::Expr(Some(&Expr { kind: ExprKind::Call(..), .. })))
406 pub(crate) fn is_expected(self, res: Res) -> bool {
408 PathSource::Type => matches!(
415 | DefKind::TraitAlias
420 | DefKind::ForeignTy,
423 | Res::SelfTyParam { .. }
424 | Res::SelfTyAlias { .. }
426 PathSource::Trait(AliasPossibility::No) => matches!(res, Res::Def(DefKind::Trait, _)),
427 PathSource::Trait(AliasPossibility::Maybe) => {
428 matches!(res, Res::Def(DefKind::Trait | DefKind::TraitAlias, _))
430 PathSource::Expr(..) => matches!(
433 DefKind::Ctor(_, CtorKind::Const | CtorKind::Fn)
438 | DefKind::AssocConst
439 | DefKind::ConstParam,
445 res.expected_in_unit_struct_pat()
446 || matches!(res, Res::Def(DefKind::Const | DefKind::AssocConst, _))
448 PathSource::TupleStruct(..) => res.expected_in_tuple_struct_pat(),
449 PathSource::Struct => matches!(
458 ) | Res::SelfTyParam { .. }
459 | Res::SelfTyAlias { .. }
461 PathSource::TraitItem(ns) => match res {
462 Res::Def(DefKind::AssocConst | DefKind::AssocFn, _) if ns == ValueNS => true,
463 Res::Def(DefKind::AssocTy, _) if ns == TypeNS => true,
469 fn error_code(self, has_unexpected_resolution: bool) -> DiagnosticId {
470 use rustc_errors::error_code;
471 match (self, has_unexpected_resolution) {
472 (PathSource::Trait(_), true) => error_code!(E0404),
473 (PathSource::Trait(_), false) => error_code!(E0405),
474 (PathSource::Type, true) => error_code!(E0573),
475 (PathSource::Type, false) => error_code!(E0412),
476 (PathSource::Struct, true) => error_code!(E0574),
477 (PathSource::Struct, false) => error_code!(E0422),
478 (PathSource::Expr(..), true) => error_code!(E0423),
479 (PathSource::Expr(..), false) => error_code!(E0425),
480 (PathSource::Pat | PathSource::TupleStruct(..), true) => error_code!(E0532),
481 (PathSource::Pat | PathSource::TupleStruct(..), false) => error_code!(E0531),
482 (PathSource::TraitItem(..), true) => error_code!(E0575),
483 (PathSource::TraitItem(..), false) => error_code!(E0576),
489 struct DiagnosticMetadata<'ast> {
490 /// The current trait's associated items' ident, used for diagnostic suggestions.
491 current_trait_assoc_items: Option<&'ast [P<AssocItem>]>,
493 /// The current self type if inside an impl (used for better errors).
494 current_self_type: Option<Ty>,
496 /// The current self item if inside an ADT (used for better errors).
497 current_self_item: Option<NodeId>,
499 /// The current trait (used to suggest).
500 current_item: Option<&'ast Item>,
502 /// When processing generics and encountering a type not found, suggest introducing a type
504 currently_processing_generics: bool,
506 /// The current enclosing (non-closure) function (used for better errors).
507 current_function: Option<(FnKind<'ast>, Span)>,
509 /// A list of labels as of yet unused. Labels will be removed from this map when
510 /// they are used (in a `break` or `continue` statement)
511 unused_labels: FxHashMap<NodeId, Span>,
513 /// Only used for better errors on `fn(): fn()`.
514 current_type_ascription: Vec<Span>,
516 /// Only used for better errors on `let x = { foo: bar };`.
517 /// In the case of a parse error with `let x = { foo: bar, };`, this isn't needed, it's only
518 /// needed for cases where this parses as a correct type ascription.
519 current_block_could_be_bare_struct_literal: Option<Span>,
521 /// Only used for better errors on `let <pat>: <expr, not type>;`.
522 current_let_binding: Option<(Span, Option<Span>, Option<Span>)>,
524 /// Used to detect possible `if let` written without `let` and to provide structured suggestion.
525 in_if_condition: Option<&'ast Expr>,
527 /// Used to detect possible new binding written without `let` and to provide structured suggestion.
528 in_assignment: Option<&'ast Expr>,
530 /// If we are currently in a trait object definition. Used to point at the bounds when
531 /// encountering a struct or enum.
532 current_trait_object: Option<&'ast [ast::GenericBound]>,
534 /// Given `where <T as Bar>::Baz: String`, suggest `where T: Bar<Baz = String>`.
535 current_where_predicate: Option<&'ast WherePredicate>,
537 current_type_path: Option<&'ast Ty>,
539 /// The current impl items (used to suggest).
540 current_impl_items: Option<&'ast [P<AssocItem>]>,
542 /// When processing impl trait
543 currently_processing_impl_trait: Option<(TraitRef, Ty)>,
545 /// Accumulate the errors due to missed lifetime elision,
546 /// and report them all at once for each function.
547 current_elision_failures: Vec<MissingLifetime>,
550 struct LateResolutionVisitor<'a, 'b, 'ast> {
551 r: &'b mut Resolver<'a>,
553 /// The module that represents the current item scope.
554 parent_scope: ParentScope<'a>,
556 /// The current set of local scopes for types and values.
557 /// FIXME #4948: Reuse ribs to avoid allocation.
558 ribs: PerNS<Vec<Rib<'a>>>,
560 /// The current set of local scopes, for labels.
561 label_ribs: Vec<Rib<'a, NodeId>>,
563 /// The current set of local scopes for lifetimes.
564 lifetime_ribs: Vec<LifetimeRib>,
566 /// We are looking for lifetimes in an elision context.
567 /// The set contains all the resolutions that we encountered so far.
568 /// They will be used to determine the correct lifetime for the fn return type.
569 /// The `LifetimeElisionCandidate` is used for diagnostics, to suggest introducing named
571 lifetime_elision_candidates: Option<FxIndexMap<LifetimeRes, LifetimeElisionCandidate>>,
573 /// The trait that the current context can refer to.
574 current_trait_ref: Option<(Module<'a>, TraitRef)>,
576 /// Fields used to add information to diagnostic errors.
577 diagnostic_metadata: Box<DiagnosticMetadata<'ast>>,
579 /// State used to know whether to ignore resolution errors for function bodies.
581 /// In particular, rustdoc uses this to avoid giving errors for `cfg()` items.
582 /// In most cases this will be `None`, in which case errors will always be reported.
583 /// If it is `true`, then it will be updated when entering a nested function or trait body.
586 /// Count the number of places a lifetime is used.
587 lifetime_uses: FxHashMap<LocalDefId, LifetimeUseSet>,
590 /// Walks the whole crate in DFS order, visiting each item, resolving names as it goes.
591 impl<'a: 'ast, 'ast> Visitor<'ast> for LateResolutionVisitor<'a, '_, 'ast> {
592 fn visit_attribute(&mut self, _: &'ast Attribute) {
593 // We do not want to resolve expressions that appear in attributes,
594 // as they do not correspond to actual code.
596 fn visit_item(&mut self, item: &'ast Item) {
597 let prev = replace(&mut self.diagnostic_metadata.current_item, Some(item));
598 // Always report errors in items we just entered.
599 let old_ignore = replace(&mut self.in_func_body, false);
600 self.with_lifetime_rib(LifetimeRibKind::Item, |this| this.resolve_item(item));
601 self.in_func_body = old_ignore;
602 self.diagnostic_metadata.current_item = prev;
604 fn visit_arm(&mut self, arm: &'ast Arm) {
605 self.resolve_arm(arm);
607 fn visit_block(&mut self, block: &'ast Block) {
608 self.resolve_block(block);
610 fn visit_anon_const(&mut self, constant: &'ast AnonConst) {
611 // We deal with repeat expressions explicitly in `resolve_expr`.
612 self.with_lifetime_rib(LifetimeRibKind::AnonConst, |this| {
613 this.with_lifetime_rib(LifetimeRibKind::Elided(LifetimeRes::Static), |this| {
614 this.resolve_anon_const(constant, IsRepeatExpr::No);
618 fn visit_expr(&mut self, expr: &'ast Expr) {
619 self.resolve_expr(expr, None);
621 fn visit_local(&mut self, local: &'ast Local) {
622 let local_spans = match local.pat.kind {
623 // We check for this to avoid tuple struct fields.
624 PatKind::Wild => None,
627 local.ty.as_ref().map(|ty| ty.span),
628 local.kind.init().map(|init| init.span),
631 let original = replace(&mut self.diagnostic_metadata.current_let_binding, local_spans);
632 self.resolve_local(local);
633 self.diagnostic_metadata.current_let_binding = original;
635 fn visit_ty(&mut self, ty: &'ast Ty) {
636 let prev = self.diagnostic_metadata.current_trait_object;
637 let prev_ty = self.diagnostic_metadata.current_type_path;
639 TyKind::Rptr(None, _) => {
640 // Elided lifetime in reference: we resolve as if there was some lifetime `'_` with
642 // This span will be used in case of elision failure.
643 let span = self.r.session.source_map().start_point(ty.span);
644 self.resolve_elided_lifetime(ty.id, span);
645 visit::walk_ty(self, ty);
647 TyKind::Path(ref qself, ref path) => {
648 self.diagnostic_metadata.current_type_path = Some(ty);
649 self.smart_resolve_path(ty.id, qself.as_ref(), path, PathSource::Type);
651 // Check whether we should interpret this as a bare trait object.
653 && let Some(partial_res) = self.r.partial_res_map.get(&ty.id)
654 && let Some(Res::Def(DefKind::Trait | DefKind::TraitAlias, _)) = partial_res.full_res()
656 // This path is actually a bare trait object. In case of a bare `Fn`-trait
657 // object with anonymous lifetimes, we need this rib to correctly place the
658 // synthetic lifetimes.
659 let span = ty.span.shrink_to_lo().to(path.span.shrink_to_lo());
660 self.with_generic_param_rib(
663 LifetimeRibKind::Generics {
665 kind: LifetimeBinderKind::PolyTrait,
668 |this| this.visit_path(&path, ty.id),
671 visit::walk_ty(self, ty)
674 TyKind::ImplicitSelf => {
675 let self_ty = Ident::with_dummy_span(kw::SelfUpper);
677 .resolve_ident_in_lexical_scope(
680 Some(Finalize::new(ty.id, ty.span)),
683 .map_or(Res::Err, |d| d.res());
684 self.r.record_partial_res(ty.id, PartialRes::new(res));
685 visit::walk_ty(self, ty)
687 TyKind::ImplTrait(..) => {
688 let candidates = self.lifetime_elision_candidates.take();
689 visit::walk_ty(self, ty);
690 self.lifetime_elision_candidates = candidates;
692 TyKind::TraitObject(ref bounds, ..) => {
693 self.diagnostic_metadata.current_trait_object = Some(&bounds[..]);
694 visit::walk_ty(self, ty)
696 TyKind::BareFn(ref bare_fn) => {
697 let span = ty.span.shrink_to_lo().to(bare_fn.decl_span.shrink_to_lo());
698 self.with_generic_param_rib(
699 &bare_fn.generic_params,
701 LifetimeRibKind::Generics {
703 kind: LifetimeBinderKind::BareFnType,
707 this.visit_generic_params(&bare_fn.generic_params, false);
708 this.with_lifetime_rib(
709 LifetimeRibKind::AnonymousCreateParameter {
711 report_in_path: false,
714 this.resolve_fn_signature(
717 // We don't need to deal with patterns in parameters, because
718 // they are not possible for foreign or bodiless functions.
723 .map(|Param { ty, .. }| (None, &**ty)),
724 &bare_fn.decl.output,
731 _ => visit::walk_ty(self, ty),
733 self.diagnostic_metadata.current_trait_object = prev;
734 self.diagnostic_metadata.current_type_path = prev_ty;
736 fn visit_poly_trait_ref(&mut self, tref: &'ast PolyTraitRef) {
737 let span = tref.span.shrink_to_lo().to(tref.trait_ref.path.span.shrink_to_lo());
738 self.with_generic_param_rib(
739 &tref.bound_generic_params,
741 LifetimeRibKind::Generics {
742 binder: tref.trait_ref.ref_id,
743 kind: LifetimeBinderKind::PolyTrait,
747 this.visit_generic_params(&tref.bound_generic_params, false);
748 this.smart_resolve_path(
749 tref.trait_ref.ref_id,
751 &tref.trait_ref.path,
752 PathSource::Trait(AliasPossibility::Maybe),
754 this.visit_trait_ref(&tref.trait_ref);
758 fn visit_foreign_item(&mut self, foreign_item: &'ast ForeignItem) {
759 match foreign_item.kind {
760 ForeignItemKind::TyAlias(box TyAlias { ref generics, .. }) => {
761 self.with_generic_param_rib(
763 ItemRibKind(HasGenericParams::Yes(generics.span)),
764 LifetimeRibKind::Generics {
765 binder: foreign_item.id,
766 kind: LifetimeBinderKind::Item,
769 |this| visit::walk_foreign_item(this, foreign_item),
772 ForeignItemKind::Fn(box Fn { ref generics, .. }) => {
773 self.with_generic_param_rib(
775 ItemRibKind(HasGenericParams::Yes(generics.span)),
776 LifetimeRibKind::Generics {
777 binder: foreign_item.id,
778 kind: LifetimeBinderKind::Function,
781 |this| visit::walk_foreign_item(this, foreign_item),
784 ForeignItemKind::Static(..) => {
785 self.with_static_rib(|this| {
786 visit::walk_foreign_item(this, foreign_item);
789 ForeignItemKind::MacCall(..) => {
790 panic!("unexpanded macro in resolve!")
794 fn visit_fn(&mut self, fn_kind: FnKind<'ast>, sp: Span, fn_id: NodeId) {
795 let previous_value = self.diagnostic_metadata.current_function;
797 // Bail if the function is foreign, and thus cannot validly have
798 // a body, or if there's no body for some other reason.
799 FnKind::Fn(FnCtxt::Foreign, _, sig, _, generics, _)
800 | FnKind::Fn(_, _, sig, _, generics, None) => {
801 self.visit_fn_header(&sig.header);
802 self.visit_generics(generics);
803 self.with_lifetime_rib(
804 LifetimeRibKind::AnonymousCreateParameter {
806 report_in_path: false,
809 this.resolve_fn_signature(
812 sig.decl.inputs.iter().map(|Param { ty, .. }| (None, &**ty)),
816 this.record_lifetime_params_for_async(
818 sig.header.asyncness.opt_return_id(),
825 self.diagnostic_metadata.current_function = Some((fn_kind, sp));
827 // Do not update `current_function` for closures: it suggests `self` parameters.
828 FnKind::Closure(..) => {}
830 debug!("(resolving function) entering function");
832 // Create a value rib for the function.
833 self.with_rib(ValueNS, ClosureOrAsyncRibKind, |this| {
834 // Create a label rib for the function.
835 this.with_label_rib(ClosureOrAsyncRibKind, |this| {
837 FnKind::Fn(_, _, sig, _, generics, body) => {
838 this.visit_generics(generics);
840 let declaration = &sig.decl;
841 let async_node_id = sig.header.asyncness.opt_return_id();
843 this.with_lifetime_rib(
844 LifetimeRibKind::AnonymousCreateParameter {
846 report_in_path: async_node_id.is_some(),
849 this.resolve_fn_signature(
851 declaration.has_self(),
855 .map(|Param { pat, ty, .. }| (Some(&**pat), &**ty)),
861 this.record_lifetime_params_for_async(fn_id, async_node_id);
863 if let Some(body) = body {
864 // Ignore errors in function bodies if this is rustdoc
865 // Be sure not to set this until the function signature has been resolved.
866 let previous_state = replace(&mut this.in_func_body, true);
867 // Resolve the function body, potentially inside the body of an async closure
868 this.with_lifetime_rib(
869 LifetimeRibKind::Elided(LifetimeRes::Infer),
870 |this| this.visit_block(body),
873 debug!("(resolving function) leaving function");
874 this.in_func_body = previous_state;
877 FnKind::Closure(binder, declaration, body) => {
878 this.visit_closure_binder(binder);
880 this.with_lifetime_rib(
882 // We do not have any explicit generic lifetime parameter.
883 ClosureBinder::NotPresent => {
884 LifetimeRibKind::AnonymousCreateParameter {
886 report_in_path: false,
889 ClosureBinder::For { .. } => LifetimeRibKind::AnonymousReportError,
891 // Add each argument to the rib.
892 |this| this.resolve_params(&declaration.inputs),
894 this.with_lifetime_rib(
896 ClosureBinder::NotPresent => {
897 LifetimeRibKind::Elided(LifetimeRes::Infer)
899 ClosureBinder::For { .. } => LifetimeRibKind::AnonymousReportError,
901 |this| visit::walk_fn_ret_ty(this, &declaration.output),
904 // Ignore errors in function bodies if this is rustdoc
905 // Be sure not to set this until the function signature has been resolved.
906 let previous_state = replace(&mut this.in_func_body, true);
907 // Resolve the function body, potentially inside the body of an async closure
908 this.with_lifetime_rib(
909 LifetimeRibKind::Elided(LifetimeRes::Infer),
910 |this| this.visit_expr(body),
913 debug!("(resolving function) leaving function");
914 this.in_func_body = previous_state;
919 self.diagnostic_metadata.current_function = previous_value;
921 fn visit_lifetime(&mut self, lifetime: &'ast Lifetime, use_ctxt: visit::LifetimeCtxt) {
922 self.resolve_lifetime(lifetime, use_ctxt)
925 fn visit_generics(&mut self, generics: &'ast Generics) {
926 self.visit_generic_params(
928 self.diagnostic_metadata.current_self_item.is_some(),
930 for p in &generics.where_clause.predicates {
931 self.visit_where_predicate(p);
935 fn visit_closure_binder(&mut self, b: &'ast ClosureBinder) {
937 ClosureBinder::NotPresent => {}
938 ClosureBinder::For { generic_params, .. } => {
939 self.visit_generic_params(
941 self.diagnostic_metadata.current_self_item.is_some(),
947 fn visit_generic_arg(&mut self, arg: &'ast GenericArg) {
948 debug!("visit_generic_arg({:?})", arg);
949 let prev = replace(&mut self.diagnostic_metadata.currently_processing_generics, true);
951 GenericArg::Type(ref ty) => {
952 // We parse const arguments as path types as we cannot distinguish them during
953 // parsing. We try to resolve that ambiguity by attempting resolution the type
954 // namespace first, and if that fails we try again in the value namespace. If
955 // resolution in the value namespace succeeds, we have an generic const argument on
957 if let TyKind::Path(ref qself, ref path) = ty.kind {
958 // We cannot disambiguate multi-segment paths right now as that requires type
960 if path.segments.len() == 1 && path.segments[0].args.is_none() {
961 let mut check_ns = |ns| {
962 self.maybe_resolve_ident_in_lexical_scope(path.segments[0].ident, ns)
965 if !check_ns(TypeNS) && check_ns(ValueNS) {
966 // This must be equivalent to `visit_anon_const`, but we cannot call it
967 // directly due to visitor lifetimes so we have to copy-paste some code.
969 // Note that we might not be inside of an repeat expression here,
970 // but considering that `IsRepeatExpr` is only relevant for
971 // non-trivial constants this is doesn't matter.
972 self.with_constant_rib(
974 ConstantHasGenerics::Yes,
977 this.smart_resolve_path(
981 PathSource::Expr(None),
984 if let Some(ref qself) = *qself {
985 this.visit_ty(&qself.ty);
987 this.visit_path(path, ty.id);
991 self.diagnostic_metadata.currently_processing_generics = prev;
999 GenericArg::Lifetime(lt) => self.visit_lifetime(lt, visit::LifetimeCtxt::GenericArg),
1000 GenericArg::Const(ct) => self.visit_anon_const(ct),
1002 self.diagnostic_metadata.currently_processing_generics = prev;
1005 fn visit_assoc_constraint(&mut self, constraint: &'ast AssocConstraint) {
1006 self.visit_ident(constraint.ident);
1007 if let Some(ref gen_args) = constraint.gen_args {
1008 // Forbid anonymous lifetimes in GAT parameters until proper semantics are decided.
1009 self.with_lifetime_rib(LifetimeRibKind::AnonymousReportError, |this| {
1010 this.visit_generic_args(gen_args)
1013 match constraint.kind {
1014 AssocConstraintKind::Equality { ref term } => match term {
1015 Term::Ty(ty) => self.visit_ty(ty),
1016 Term::Const(c) => self.visit_anon_const(c),
1018 AssocConstraintKind::Bound { ref bounds } => {
1019 walk_list!(self, visit_param_bound, bounds, BoundKind::Bound);
1024 fn visit_path_segment(&mut self, path_segment: &'ast PathSegment) {
1025 if let Some(ref args) = path_segment.args {
1027 GenericArgs::AngleBracketed(..) => visit::walk_generic_args(self, args),
1028 GenericArgs::Parenthesized(p_args) => {
1029 // Probe the lifetime ribs to know how to behave.
1030 for rib in self.lifetime_ribs.iter().rev() {
1032 // We are inside a `PolyTraitRef`. The lifetimes are
1033 // to be intoduced in that (maybe implicit) `for<>` binder.
1034 LifetimeRibKind::Generics {
1036 kind: LifetimeBinderKind::PolyTrait,
1039 self.with_lifetime_rib(
1040 LifetimeRibKind::AnonymousCreateParameter {
1042 report_in_path: false,
1045 this.resolve_fn_signature(
1048 p_args.inputs.iter().map(|ty| (None, &**ty)),
1055 // We have nowhere to introduce generics. Code is malformed,
1056 // so use regular lifetime resolution to avoid spurious errors.
1057 LifetimeRibKind::Item | LifetimeRibKind::Generics { .. } => {
1058 visit::walk_generic_args(self, args);
1061 LifetimeRibKind::AnonymousCreateParameter { .. }
1062 | LifetimeRibKind::AnonymousReportError
1063 | LifetimeRibKind::Elided(_)
1064 | LifetimeRibKind::ElisionFailure
1065 | LifetimeRibKind::AnonConst
1066 | LifetimeRibKind::ConstGeneric => {}
1074 fn visit_where_predicate(&mut self, p: &'ast WherePredicate) {
1075 debug!("visit_where_predicate {:?}", p);
1076 let previous_value =
1077 replace(&mut self.diagnostic_metadata.current_where_predicate, Some(p));
1078 self.with_lifetime_rib(LifetimeRibKind::AnonymousReportError, |this| {
1079 if let WherePredicate::BoundPredicate(WhereBoundPredicate {
1082 ref bound_generic_params,
1083 span: predicate_span,
1087 let span = predicate_span.shrink_to_lo().to(bounded_ty.span.shrink_to_lo());
1088 this.with_generic_param_rib(
1089 &bound_generic_params,
1091 LifetimeRibKind::Generics {
1092 binder: bounded_ty.id,
1093 kind: LifetimeBinderKind::WhereBound,
1097 this.visit_generic_params(&bound_generic_params, false);
1098 this.visit_ty(bounded_ty);
1099 for bound in bounds {
1100 this.visit_param_bound(bound, BoundKind::Bound)
1105 visit::walk_where_predicate(this, p);
1108 self.diagnostic_metadata.current_where_predicate = previous_value;
1111 fn visit_inline_asm(&mut self, asm: &'ast InlineAsm) {
1112 for (op, _) in &asm.operands {
1114 InlineAsmOperand::In { expr, .. }
1115 | InlineAsmOperand::Out { expr: Some(expr), .. }
1116 | InlineAsmOperand::InOut { expr, .. } => self.visit_expr(expr),
1117 InlineAsmOperand::Out { expr: None, .. } => {}
1118 InlineAsmOperand::SplitInOut { in_expr, out_expr, .. } => {
1119 self.visit_expr(in_expr);
1120 if let Some(out_expr) = out_expr {
1121 self.visit_expr(out_expr);
1124 InlineAsmOperand::Const { anon_const, .. } => {
1125 // Although this is `DefKind::AnonConst`, it is allowed to reference outer
1126 // generic parameters like an inline const.
1127 self.resolve_inline_const(anon_const);
1129 InlineAsmOperand::Sym { sym } => self.visit_inline_asm_sym(sym),
1134 fn visit_inline_asm_sym(&mut self, sym: &'ast InlineAsmSym) {
1135 // This is similar to the code for AnonConst.
1136 self.with_rib(ValueNS, InlineAsmSymRibKind, |this| {
1137 this.with_rib(TypeNS, InlineAsmSymRibKind, |this| {
1138 this.with_label_rib(InlineAsmSymRibKind, |this| {
1139 this.smart_resolve_path(
1143 PathSource::Expr(None),
1145 visit::walk_inline_asm_sym(this, sym);
1152 impl<'a: 'ast, 'b, 'ast> LateResolutionVisitor<'a, 'b, 'ast> {
1153 fn new(resolver: &'b mut Resolver<'a>) -> LateResolutionVisitor<'a, 'b, 'ast> {
1154 // During late resolution we only track the module component of the parent scope,
1155 // although it may be useful to track other components as well for diagnostics.
1156 let graph_root = resolver.graph_root;
1157 let parent_scope = ParentScope::module(graph_root, resolver);
1158 let start_rib_kind = ModuleRibKind(graph_root);
1159 LateResolutionVisitor {
1163 value_ns: vec![Rib::new(start_rib_kind)],
1164 type_ns: vec![Rib::new(start_rib_kind)],
1165 macro_ns: vec![Rib::new(start_rib_kind)],
1167 label_ribs: Vec::new(),
1168 lifetime_ribs: Vec::new(),
1169 lifetime_elision_candidates: None,
1170 current_trait_ref: None,
1171 diagnostic_metadata: Box::new(DiagnosticMetadata::default()),
1172 // errors at module scope should always be reported
1173 in_func_body: false,
1174 lifetime_uses: Default::default(),
1178 fn maybe_resolve_ident_in_lexical_scope(
1182 ) -> Option<LexicalScopeBinding<'a>> {
1183 self.r.resolve_ident_in_lexical_scope(
1193 fn resolve_ident_in_lexical_scope(
1197 finalize: Option<Finalize>,
1198 ignore_binding: Option<&'a NameBinding<'a>>,
1199 ) -> Option<LexicalScopeBinding<'a>> {
1200 self.r.resolve_ident_in_lexical_scope(
1213 opt_ns: Option<Namespace>, // `None` indicates a module path in import
1214 finalize: Option<Finalize>,
1215 ) -> PathResult<'a> {
1216 self.r.resolve_path_with_ribs(
1228 // We maintain a list of value ribs and type ribs.
1230 // Simultaneously, we keep track of the current position in the module
1231 // graph in the `parent_scope.module` pointer. When we go to resolve a name in
1232 // the value or type namespaces, we first look through all the ribs and
1233 // then query the module graph. When we resolve a name in the module
1234 // namespace, we can skip all the ribs (since nested modules are not
1235 // allowed within blocks in Rust) and jump straight to the current module
1238 // Named implementations are handled separately. When we find a method
1239 // call, we consult the module node to find all of the implementations in
1240 // scope. This information is lazily cached in the module node. We then
1241 // generate a fake "implementation scope" containing all the
1242 // implementations thus found, for compatibility with old resolve pass.
1244 /// Do some `work` within a new innermost rib of the given `kind` in the given namespace (`ns`).
1249 work: impl FnOnce(&mut Self) -> T,
1251 self.ribs[ns].push(Rib::new(kind));
1252 let ret = work(self);
1253 self.ribs[ns].pop();
1257 fn with_scope<T>(&mut self, id: NodeId, f: impl FnOnce(&mut Self) -> T) -> T {
1258 if let Some(module) = self.r.get_module(self.r.local_def_id(id).to_def_id()) {
1259 // Move down in the graph.
1260 let orig_module = replace(&mut self.parent_scope.module, module);
1261 self.with_rib(ValueNS, ModuleRibKind(module), |this| {
1262 this.with_rib(TypeNS, ModuleRibKind(module), |this| {
1264 this.parent_scope.module = orig_module;
1273 fn visit_generic_params(&mut self, params: &'ast [GenericParam], add_self_upper: bool) {
1274 // For type parameter defaults, we have to ban access
1275 // to following type parameters, as the InternalSubsts can only
1276 // provide previous type parameters as they're built. We
1277 // put all the parameters on the ban list and then remove
1278 // them one by one as they are processed and become available.
1279 let mut forward_ty_ban_rib = Rib::new(ForwardGenericParamBanRibKind);
1280 let mut forward_const_ban_rib = Rib::new(ForwardGenericParamBanRibKind);
1281 for param in params.iter() {
1283 GenericParamKind::Type { .. } => {
1286 .insert(Ident::with_dummy_span(param.ident.name), Res::Err);
1288 GenericParamKind::Const { .. } => {
1289 forward_const_ban_rib
1291 .insert(Ident::with_dummy_span(param.ident.name), Res::Err);
1293 GenericParamKind::Lifetime => {}
1297 // rust-lang/rust#61631: The type `Self` is essentially
1298 // another type parameter. For ADTs, we consider it
1299 // well-defined only after all of the ADT type parameters have
1300 // been provided. Therefore, we do not allow use of `Self`
1301 // anywhere in ADT type parameter defaults.
1303 // (We however cannot ban `Self` for defaults on *all* generic
1304 // lists; e.g. trait generics can usefully refer to `Self`,
1305 // such as in the case of `trait Add<Rhs = Self>`.)
1307 // (`Some` if + only if we are in ADT's generics.)
1308 forward_ty_ban_rib.bindings.insert(Ident::with_dummy_span(kw::SelfUpper), Res::Err);
1311 self.with_lifetime_rib(LifetimeRibKind::AnonymousReportError, |this| {
1312 for param in params {
1314 GenericParamKind::Lifetime => {
1315 for bound in ¶m.bounds {
1316 this.visit_param_bound(bound, BoundKind::Bound);
1319 GenericParamKind::Type { ref default } => {
1320 for bound in ¶m.bounds {
1321 this.visit_param_bound(bound, BoundKind::Bound);
1324 if let Some(ref ty) = default {
1325 this.ribs[TypeNS].push(forward_ty_ban_rib);
1326 this.ribs[ValueNS].push(forward_const_ban_rib);
1328 forward_const_ban_rib = this.ribs[ValueNS].pop().unwrap();
1329 forward_ty_ban_rib = this.ribs[TypeNS].pop().unwrap();
1332 // Allow all following defaults to refer to this type parameter.
1335 .remove(&Ident::with_dummy_span(param.ident.name));
1337 GenericParamKind::Const { ref ty, kw_span: _, ref default } => {
1338 // Const parameters can't have param bounds.
1339 assert!(param.bounds.is_empty());
1341 this.ribs[TypeNS].push(Rib::new(ConstParamTyRibKind));
1342 this.ribs[ValueNS].push(Rib::new(ConstParamTyRibKind));
1343 this.with_lifetime_rib(LifetimeRibKind::ConstGeneric, |this| {
1346 this.ribs[TypeNS].pop().unwrap();
1347 this.ribs[ValueNS].pop().unwrap();
1349 if let Some(ref expr) = default {
1350 this.ribs[TypeNS].push(forward_ty_ban_rib);
1351 this.ribs[ValueNS].push(forward_const_ban_rib);
1352 this.with_lifetime_rib(LifetimeRibKind::ConstGeneric, |this| {
1353 this.resolve_anon_const(expr, IsRepeatExpr::No)
1355 forward_const_ban_rib = this.ribs[ValueNS].pop().unwrap();
1356 forward_ty_ban_rib = this.ribs[TypeNS].pop().unwrap();
1359 // Allow all following defaults to refer to this const parameter.
1360 forward_const_ban_rib
1362 .remove(&Ident::with_dummy_span(param.ident.name));
1369 #[instrument(level = "debug", skip(self, work))]
1370 fn with_lifetime_rib<T>(
1372 kind: LifetimeRibKind,
1373 work: impl FnOnce(&mut Self) -> T,
1375 self.lifetime_ribs.push(LifetimeRib::new(kind));
1376 let outer_elision_candidates = self.lifetime_elision_candidates.take();
1377 let ret = work(self);
1378 self.lifetime_elision_candidates = outer_elision_candidates;
1379 self.lifetime_ribs.pop();
1383 #[instrument(level = "debug", skip(self))]
1384 fn resolve_lifetime(&mut self, lifetime: &'ast Lifetime, use_ctxt: visit::LifetimeCtxt) {
1385 let ident = lifetime.ident;
1387 if ident.name == kw::StaticLifetime {
1388 self.record_lifetime_res(
1390 LifetimeRes::Static,
1391 LifetimeElisionCandidate::Named,
1396 if ident.name == kw::UnderscoreLifetime {
1397 return self.resolve_anonymous_lifetime(lifetime, false);
1400 let mut lifetime_rib_iter = self.lifetime_ribs.iter().rev();
1401 while let Some(rib) = lifetime_rib_iter.next() {
1402 let normalized_ident = ident.normalize_to_macros_2_0();
1403 if let Some(&(_, res)) = rib.bindings.get(&normalized_ident) {
1404 self.record_lifetime_res(lifetime.id, res, LifetimeElisionCandidate::Named);
1406 if let LifetimeRes::Param { param, .. } = res {
1407 match self.lifetime_uses.entry(param) {
1408 Entry::Vacant(v) => {
1409 debug!("First use of {:?} at {:?}", res, ident.span);
1414 .find_map(|rib| match rib.kind {
1415 // Do not suggest eliding a lifetime where an anonymous
1416 // lifetime would be illegal.
1417 LifetimeRibKind::Item
1418 | LifetimeRibKind::AnonymousReportError
1419 | LifetimeRibKind::ElisionFailure => Some(LifetimeUseSet::Many),
1420 // An anonymous lifetime is legal here, go ahead.
1421 LifetimeRibKind::AnonymousCreateParameter { .. } => {
1422 Some(LifetimeUseSet::One { use_span: ident.span, use_ctxt })
1424 // Only report if eliding the lifetime would have the same
1426 LifetimeRibKind::Elided(r) => Some(if res == r {
1427 LifetimeUseSet::One { use_span: ident.span, use_ctxt }
1429 LifetimeUseSet::Many
1431 LifetimeRibKind::Generics { .. } => None,
1432 LifetimeRibKind::ConstGeneric | LifetimeRibKind::AnonConst => {
1433 span_bug!(ident.span, "unexpected rib kind: {:?}", rib.kind)
1436 .unwrap_or(LifetimeUseSet::Many);
1437 debug!(?use_ctxt, ?use_set);
1440 Entry::Occupied(mut o) => {
1441 debug!("Many uses of {:?} at {:?}", res, ident.span);
1442 *o.get_mut() = LifetimeUseSet::Many;
1450 LifetimeRibKind::Item => break,
1451 LifetimeRibKind::ConstGeneric => {
1452 self.emit_non_static_lt_in_const_generic_error(lifetime);
1453 self.record_lifetime_res(
1456 LifetimeElisionCandidate::Ignore,
1460 LifetimeRibKind::AnonConst => {
1461 self.maybe_emit_forbidden_non_static_lifetime_error(lifetime);
1462 self.record_lifetime_res(
1465 LifetimeElisionCandidate::Ignore,
1469 LifetimeRibKind::AnonymousCreateParameter { .. }
1470 | LifetimeRibKind::Elided(_)
1471 | LifetimeRibKind::Generics { .. }
1472 | LifetimeRibKind::ElisionFailure
1473 | LifetimeRibKind::AnonymousReportError => {}
1477 let mut outer_res = None;
1478 for rib in lifetime_rib_iter {
1479 let normalized_ident = ident.normalize_to_macros_2_0();
1480 if let Some((&outer, _)) = rib.bindings.get_key_value(&normalized_ident) {
1481 outer_res = Some(outer);
1486 self.emit_undeclared_lifetime_error(lifetime, outer_res);
1487 self.record_lifetime_res(lifetime.id, LifetimeRes::Error, LifetimeElisionCandidate::Named);
1490 #[instrument(level = "debug", skip(self))]
1491 fn resolve_anonymous_lifetime(&mut self, lifetime: &Lifetime, elided: bool) {
1492 debug_assert_eq!(lifetime.ident.name, kw::UnderscoreLifetime);
1494 let missing_lifetime = MissingLifetime {
1496 span: lifetime.ident.span,
1498 MissingLifetimeKind::Ampersand
1500 MissingLifetimeKind::Underscore
1504 let elision_candidate = LifetimeElisionCandidate::Missing(missing_lifetime);
1505 for rib in self.lifetime_ribs.iter().rev() {
1508 LifetimeRibKind::AnonymousCreateParameter { binder, .. } => {
1509 let res = self.create_fresh_lifetime(lifetime.id, lifetime.ident, binder);
1510 self.record_lifetime_res(lifetime.id, res, elision_candidate);
1513 LifetimeRibKind::AnonymousReportError => {
1514 let (msg, note) = if elided {
1516 "`&` without an explicit lifetime name cannot be used here",
1517 "explicit lifetime name needed here",
1520 ("`'_` cannot be used here", "`'_` is a reserved lifetime name")
1522 rustc_errors::struct_span_err!(
1524 lifetime.ident.span,
1529 .span_label(lifetime.ident.span, note)
1532 self.record_lifetime_res(lifetime.id, LifetimeRes::Error, elision_candidate);
1535 LifetimeRibKind::Elided(res) => {
1536 self.record_lifetime_res(lifetime.id, res, elision_candidate);
1539 LifetimeRibKind::ElisionFailure => {
1540 self.diagnostic_metadata.current_elision_failures.push(missing_lifetime);
1541 self.record_lifetime_res(lifetime.id, LifetimeRes::Error, elision_candidate);
1544 LifetimeRibKind::Item => break,
1545 LifetimeRibKind::Generics { .. } | LifetimeRibKind::ConstGeneric => {}
1546 LifetimeRibKind::AnonConst => {
1547 // There is always an `Elided(LifetimeRes::Static)` inside an `AnonConst`.
1548 span_bug!(lifetime.ident.span, "unexpected rib kind: {:?}", rib.kind)
1552 self.record_lifetime_res(lifetime.id, LifetimeRes::Error, elision_candidate);
1553 self.report_missing_lifetime_specifiers(vec![missing_lifetime], None);
1556 #[instrument(level = "debug", skip(self))]
1557 fn resolve_elided_lifetime(&mut self, anchor_id: NodeId, span: Span) {
1558 let id = self.r.next_node_id();
1559 let lt = Lifetime { id, ident: Ident::new(kw::UnderscoreLifetime, span) };
1561 self.record_lifetime_res(
1563 LifetimeRes::ElidedAnchor { start: id, end: NodeId::from_u32(id.as_u32() + 1) },
1564 LifetimeElisionCandidate::Ignore,
1566 self.resolve_anonymous_lifetime(<, true);
1569 #[instrument(level = "debug", skip(self))]
1570 fn create_fresh_lifetime(&mut self, id: NodeId, ident: Ident, binder: NodeId) -> LifetimeRes {
1571 debug_assert_eq!(ident.name, kw::UnderscoreLifetime);
1572 debug!(?ident.span);
1574 // Leave the responsibility to create the `LocalDefId` to lowering.
1575 let param = self.r.next_node_id();
1576 let res = LifetimeRes::Fresh { param, binder };
1578 // Record the created lifetime parameter so lowering can pick it up and add it to HIR.
1580 .extra_lifetime_params_map
1582 .or_insert_with(Vec::new)
1583 .push((ident, param, res));
1587 #[instrument(level = "debug", skip(self))]
1588 fn resolve_elided_lifetimes_in_path(
1591 partial_res: PartialRes,
1593 source: PathSource<'_>,
1596 let proj_start = path.len() - partial_res.unresolved_segments();
1597 for (i, segment) in path.iter().enumerate() {
1598 if segment.has_lifetime_args {
1601 let Some(segment_id) = segment.id else {
1605 // Figure out if this is a type/trait segment,
1606 // which may need lifetime elision performed.
1607 let type_def_id = match partial_res.base_res() {
1608 Res::Def(DefKind::AssocTy, def_id) if i + 2 == proj_start => self.r.parent(def_id),
1609 Res::Def(DefKind::Variant, def_id) if i + 1 == proj_start => self.r.parent(def_id),
1610 Res::Def(DefKind::Struct, def_id)
1611 | Res::Def(DefKind::Union, def_id)
1612 | Res::Def(DefKind::Enum, def_id)
1613 | Res::Def(DefKind::TyAlias, def_id)
1614 | Res::Def(DefKind::Trait, def_id)
1615 if i + 1 == proj_start =>
1622 let expected_lifetimes = self.r.item_generics_num_lifetimes(type_def_id);
1623 if expected_lifetimes == 0 {
1627 let node_ids = self.r.next_node_ids(expected_lifetimes);
1628 self.record_lifetime_res(
1630 LifetimeRes::ElidedAnchor { start: node_ids.start, end: node_ids.end },
1631 LifetimeElisionCandidate::Ignore,
1634 let inferred = match source {
1635 PathSource::Trait(..) | PathSource::TraitItem(..) | PathSource::Type => false,
1636 PathSource::Expr(..)
1638 | PathSource::Struct
1639 | PathSource::TupleStruct(..) => true,
1642 // Do not create a parameter for patterns and expressions: type checking can infer
1643 // the appropriate lifetime for us.
1644 for id in node_ids {
1645 self.record_lifetime_res(
1648 LifetimeElisionCandidate::Named,
1654 let elided_lifetime_span = if segment.has_generic_args {
1655 // If there are brackets, but not generic arguments, then use the opening bracket
1656 segment.args_span.with_hi(segment.args_span.lo() + BytePos(1))
1658 // If there are no brackets, use the identifier span.
1659 // HACK: we use find_ancestor_inside to properly suggest elided spans in paths
1660 // originating from macros, since the segment's span might be from a macro arg.
1661 segment.ident.span.find_ancestor_inside(path_span).unwrap_or(path_span)
1663 let ident = Ident::new(kw::UnderscoreLifetime, elided_lifetime_span);
1665 let missing_lifetime = MissingLifetime {
1667 span: elided_lifetime_span,
1668 kind: if segment.has_generic_args {
1669 MissingLifetimeKind::Comma
1671 MissingLifetimeKind::Brackets
1673 count: expected_lifetimes,
1675 let mut should_lint = true;
1676 for rib in self.lifetime_ribs.iter().rev() {
1678 // In create-parameter mode we error here because we don't want to support
1679 // deprecated impl elision in new features like impl elision and `async fn`,
1680 // both of which work using the `CreateParameter` mode:
1682 // impl Foo for std::cell::Ref<u32> // note lack of '_
1683 // async fn foo(_: std::cell::Ref<u32>) { ... }
1684 LifetimeRibKind::AnonymousCreateParameter { report_in_path: true, .. } => {
1685 let sess = self.r.session;
1686 let mut err = rustc_errors::struct_span_err!(
1690 "implicit elided lifetime not allowed here"
1692 rustc_errors::add_elided_lifetime_in_path_suggestion(
1697 !segment.has_generic_args,
1698 elided_lifetime_span,
1700 err.note("assuming a `'static` lifetime...");
1702 should_lint = false;
1704 for id in node_ids {
1705 self.record_lifetime_res(
1708 LifetimeElisionCandidate::Named,
1713 // Do not create a parameter for patterns and expressions.
1714 LifetimeRibKind::AnonymousCreateParameter { binder, .. } => {
1715 // Group all suggestions into the first record.
1716 let mut candidate = LifetimeElisionCandidate::Missing(missing_lifetime);
1717 for id in node_ids {
1718 let res = self.create_fresh_lifetime(id, ident, binder);
1719 self.record_lifetime_res(
1722 replace(&mut candidate, LifetimeElisionCandidate::Named),
1727 LifetimeRibKind::Elided(res) => {
1728 let mut candidate = LifetimeElisionCandidate::Missing(missing_lifetime);
1729 for id in node_ids {
1730 self.record_lifetime_res(
1733 replace(&mut candidate, LifetimeElisionCandidate::Ignore),
1738 LifetimeRibKind::ElisionFailure => {
1739 self.diagnostic_metadata.current_elision_failures.push(missing_lifetime);
1740 for id in node_ids {
1741 self.record_lifetime_res(
1744 LifetimeElisionCandidate::Ignore,
1749 // `LifetimeRes::Error`, which would usually be used in the case of
1750 // `ReportError`, is unsuitable here, as we don't emit an error yet. Instead,
1751 // we simply resolve to an implicit lifetime, which will be checked later, at
1752 // which point a suitable error will be emitted.
1753 LifetimeRibKind::AnonymousReportError | LifetimeRibKind::Item => {
1754 for id in node_ids {
1755 self.record_lifetime_res(
1758 LifetimeElisionCandidate::Ignore,
1761 self.report_missing_lifetime_specifiers(vec![missing_lifetime], None);
1764 LifetimeRibKind::Generics { .. } | LifetimeRibKind::ConstGeneric => {}
1765 LifetimeRibKind::AnonConst => {
1766 // There is always an `Elided(LifetimeRes::Static)` inside an `AnonConst`.
1767 span_bug!(elided_lifetime_span, "unexpected rib kind: {:?}", rib.kind)
1773 self.r.lint_buffer.buffer_lint_with_diagnostic(
1774 lint::builtin::ELIDED_LIFETIMES_IN_PATHS,
1776 elided_lifetime_span,
1777 "hidden lifetime parameters in types are deprecated",
1778 lint::BuiltinLintDiagnostics::ElidedLifetimesInPaths(
1781 !segment.has_generic_args,
1782 elided_lifetime_span,
1789 #[instrument(level = "debug", skip(self))]
1790 fn record_lifetime_res(
1794 candidate: LifetimeElisionCandidate,
1796 if let Some(prev_res) = self.r.lifetimes_res_map.insert(id, res) {
1798 "lifetime {:?} resolved multiple times ({:?} before, {:?} now)",
1803 LifetimeRes::Param { .. } | LifetimeRes::Fresh { .. } | LifetimeRes::Static => {
1804 if let Some(ref mut candidates) = self.lifetime_elision_candidates {
1805 candidates.insert(res, candidate);
1808 LifetimeRes::Infer | LifetimeRes::Error | LifetimeRes::ElidedAnchor { .. } => {}
1812 #[instrument(level = "debug", skip(self))]
1813 fn record_lifetime_param(&mut self, id: NodeId, res: LifetimeRes) {
1814 if let Some(prev_res) = self.r.lifetimes_res_map.insert(id, res) {
1816 "lifetime parameter {:?} resolved multiple times ({:?} before, {:?} now)",
1822 /// Perform resolution of a function signature, accounting for lifetime elision.
1823 #[instrument(level = "debug", skip(self, inputs))]
1824 fn resolve_fn_signature(
1828 inputs: impl Iterator<Item = (Option<&'ast Pat>, &'ast Ty)> + Clone,
1829 output_ty: &'ast FnRetTy,
1831 // Add each argument to the rib.
1832 let elision_lifetime = self.resolve_fn_params(has_self, inputs);
1833 debug!(?elision_lifetime);
1835 let outer_failures = take(&mut self.diagnostic_metadata.current_elision_failures);
1836 let output_rib = if let Ok(res) = elision_lifetime.as_ref() {
1837 LifetimeRibKind::Elided(*res)
1839 LifetimeRibKind::ElisionFailure
1841 self.with_lifetime_rib(output_rib, |this| visit::walk_fn_ret_ty(this, &output_ty));
1842 let elision_failures =
1843 replace(&mut self.diagnostic_metadata.current_elision_failures, outer_failures);
1844 if !elision_failures.is_empty() {
1845 let Err(failure_info) = elision_lifetime else { bug!() };
1846 self.report_missing_lifetime_specifiers(elision_failures, Some(failure_info));
1850 /// Resolve inside function parameters and parameter types.
1851 /// Returns the lifetime for elision in fn return type,
1852 /// or diagnostic information in case of elision failure.
1853 fn resolve_fn_params(
1856 inputs: impl Iterator<Item = (Option<&'ast Pat>, &'ast Ty)>,
1857 ) -> Result<LifetimeRes, (Vec<MissingLifetime>, Vec<ElisionFnParameter>)> {
1858 let outer_candidates =
1859 replace(&mut self.lifetime_elision_candidates, Some(Default::default()));
1861 let mut elision_lifetime = None;
1862 let mut lifetime_count = 0;
1863 let mut parameter_info = Vec::new();
1865 let mut bindings = smallvec![(PatBoundCtx::Product, Default::default())];
1866 for (index, (pat, ty)) in inputs.enumerate() {
1868 self.with_lifetime_rib(LifetimeRibKind::Elided(LifetimeRes::Infer), |this| {
1869 if let Some(pat) = pat {
1870 this.resolve_pattern(pat, PatternSource::FnParam, &mut bindings);
1875 if let Some(ref candidates) = self.lifetime_elision_candidates {
1876 let new_count = candidates.len();
1877 let local_count = new_count - lifetime_count;
1878 if local_count != 0 {
1879 parameter_info.push(ElisionFnParameter {
1881 ident: if let Some(pat) = pat && let PatKind::Ident(_, ident, _) = pat.kind {
1886 lifetime_count: local_count,
1890 lifetime_count = new_count;
1893 // Handle `self` specially.
1894 if index == 0 && has_self {
1895 let self_lifetime = self.find_lifetime_for_self(ty);
1896 if let Set1::One(lifetime) = self_lifetime {
1897 elision_lifetime = Some(lifetime);
1898 self.lifetime_elision_candidates = None;
1900 self.lifetime_elision_candidates = Some(Default::default());
1904 debug!("(resolving function / closure) recorded parameter");
1907 let all_candidates = replace(&mut self.lifetime_elision_candidates, outer_candidates);
1908 debug!(?all_candidates);
1910 if let Some(res) = elision_lifetime {
1914 // We do not have a `self` candidate, look at the full list.
1915 let all_candidates = all_candidates.unwrap();
1916 if all_candidates.len() == 1 {
1917 Ok(*all_candidates.first().unwrap().0)
1919 let all_candidates = all_candidates
1921 .filter_map(|(_, candidate)| match candidate {
1922 LifetimeElisionCandidate::Ignore | LifetimeElisionCandidate::Named => None,
1923 LifetimeElisionCandidate::Missing(missing) => Some(missing),
1926 Err((all_candidates, parameter_info))
1930 /// List all the lifetimes that appear in the provided type.
1931 fn find_lifetime_for_self(&self, ty: &'ast Ty) -> Set1<LifetimeRes> {
1932 struct SelfVisitor<'r, 'a> {
1933 r: &'r Resolver<'a>,
1934 impl_self: Option<Res>,
1935 lifetime: Set1<LifetimeRes>,
1938 impl SelfVisitor<'_, '_> {
1939 // Look for `self: &'a Self` - also desugared from `&'a self`,
1940 // and if that matches, use it for elision and return early.
1941 fn is_self_ty(&self, ty: &Ty) -> bool {
1943 TyKind::ImplicitSelf => true,
1944 TyKind::Path(None, _) => {
1945 let path_res = self.r.partial_res_map[&ty.id].full_res();
1946 if let Some(Res::SelfTyParam { .. } | Res::SelfTyAlias { .. }) = path_res {
1949 self.impl_self.is_some() && path_res == self.impl_self
1956 impl<'a> Visitor<'a> for SelfVisitor<'_, '_> {
1957 fn visit_ty(&mut self, ty: &'a Ty) {
1958 trace!("SelfVisitor considering ty={:?}", ty);
1959 if let TyKind::Rptr(lt, ref mt) = ty.kind && self.is_self_ty(&mt.ty) {
1960 let lt_id = if let Some(lt) = lt {
1963 let res = self.r.lifetimes_res_map[&ty.id];
1964 let LifetimeRes::ElidedAnchor { start, .. } = res else { bug!() };
1967 let lt_res = self.r.lifetimes_res_map[<_id];
1968 trace!("SelfVisitor inserting res={:?}", lt_res);
1969 self.lifetime.insert(lt_res);
1971 visit::walk_ty(self, ty)
1975 let impl_self = self
1976 .diagnostic_metadata
1980 if let TyKind::Path(None, _) = ty.kind {
1981 self.r.partial_res_map.get(&ty.id)
1986 .and_then(|res| res.full_res())
1988 // Permit the types that unambiguously always
1989 // result in the same type constructor being used
1990 // (it can't differ between `Self` and `self`).
1993 Res::Def(DefKind::Struct | DefKind::Union | DefKind::Enum, _,) | Res::PrimTy(_)
1996 let mut visitor = SelfVisitor { r: self.r, impl_self, lifetime: Set1::Empty };
1997 visitor.visit_ty(ty);
1998 trace!("SelfVisitor found={:?}", visitor.lifetime);
2002 /// Searches the current set of local scopes for labels. Returns the `NodeId` of the resolved
2003 /// label and reports an error if the label is not found or is unreachable.
2004 fn resolve_label(&mut self, mut label: Ident) -> Result<(NodeId, Span), ResolutionError<'a>> {
2005 let mut suggestion = None;
2007 for i in (0..self.label_ribs.len()).rev() {
2008 let rib = &self.label_ribs[i];
2010 if let MacroDefinition(def) = rib.kind {
2011 // If an invocation of this macro created `ident`, give up on `ident`
2012 // and switch to `ident`'s source from the macro definition.
2013 if def == self.r.macro_def(label.span.ctxt()) {
2014 label.span.remove_mark();
2018 let ident = label.normalize_to_macro_rules();
2019 if let Some((ident, id)) = rib.bindings.get_key_value(&ident) {
2020 let definition_span = ident.span;
2021 return if self.is_label_valid_from_rib(i) {
2022 Ok((*id, definition_span))
2024 Err(ResolutionError::UnreachableLabel {
2032 // Diagnostics: Check if this rib contains a label with a similar name, keep track of
2033 // the first such label that is encountered.
2034 suggestion = suggestion.or_else(|| self.suggestion_for_label_in_rib(i, label));
2037 Err(ResolutionError::UndeclaredLabel { name: label.name, suggestion })
2040 /// Determine whether or not a label from the `rib_index`th label rib is reachable.
2041 fn is_label_valid_from_rib(&self, rib_index: usize) -> bool {
2042 let ribs = &self.label_ribs[rib_index + 1..];
2045 if rib.kind.is_label_barrier() {
2053 fn resolve_adt(&mut self, item: &'ast Item, generics: &'ast Generics) {
2054 debug!("resolve_adt");
2055 self.with_current_self_item(item, |this| {
2056 this.with_generic_param_rib(
2058 ItemRibKind(HasGenericParams::Yes(generics.span)),
2059 LifetimeRibKind::Generics {
2061 kind: LifetimeBinderKind::Item,
2062 span: generics.span,
2065 let item_def_id = this.r.local_def_id(item.id).to_def_id();
2068 alias_to: item_def_id,
2069 forbid_generic: false,
2070 is_trait_impl: false,
2073 visit::walk_item(this, item);
2081 fn future_proof_import(&mut self, use_tree: &UseTree) {
2082 let segments = &use_tree.prefix.segments;
2083 if !segments.is_empty() {
2084 let ident = segments[0].ident;
2085 if ident.is_path_segment_keyword() || ident.span.rust_2015() {
2089 let nss = match use_tree.kind {
2090 UseTreeKind::Simple(..) if segments.len() == 1 => &[TypeNS, ValueNS][..],
2093 let report_error = |this: &Self, ns| {
2094 let what = if ns == TypeNS { "type parameters" } else { "local variables" };
2095 if this.should_report_errs() {
2098 .span_err(ident.span, &format!("imports cannot refer to {}", what));
2103 match self.maybe_resolve_ident_in_lexical_scope(ident, ns) {
2104 Some(LexicalScopeBinding::Res(..)) => {
2105 report_error(self, ns);
2107 Some(LexicalScopeBinding::Item(binding)) => {
2108 if let Some(LexicalScopeBinding::Res(..)) =
2109 self.resolve_ident_in_lexical_scope(ident, ns, None, Some(binding))
2111 report_error(self, ns);
2117 } else if let UseTreeKind::Nested(use_trees) = &use_tree.kind {
2118 for (use_tree, _) in use_trees {
2119 self.future_proof_import(use_tree);
2124 fn resolve_item(&mut self, item: &'ast Item) {
2125 let name = item.ident.name;
2126 debug!("(resolving item) resolving {} ({:?})", name, item.kind);
2129 ItemKind::TyAlias(box TyAlias { ref generics, .. }) => {
2130 self.with_generic_param_rib(
2132 ItemRibKind(HasGenericParams::Yes(generics.span)),
2133 LifetimeRibKind::Generics {
2135 kind: LifetimeBinderKind::Item,
2136 span: generics.span,
2138 |this| visit::walk_item(this, item),
2142 ItemKind::Fn(box Fn { ref generics, .. }) => {
2143 self.with_generic_param_rib(
2145 ItemRibKind(HasGenericParams::Yes(generics.span)),
2146 LifetimeRibKind::Generics {
2148 kind: LifetimeBinderKind::Function,
2149 span: generics.span,
2151 |this| visit::walk_item(this, item),
2155 ItemKind::Enum(_, ref generics)
2156 | ItemKind::Struct(_, ref generics)
2157 | ItemKind::Union(_, ref generics) => {
2158 self.resolve_adt(item, generics);
2161 ItemKind::Impl(box Impl {
2165 items: ref impl_items,
2168 self.diagnostic_metadata.current_impl_items = Some(impl_items);
2169 self.resolve_implementation(generics, of_trait, &self_ty, item.id, impl_items);
2170 self.diagnostic_metadata.current_impl_items = None;
2173 ItemKind::Trait(box Trait { ref generics, ref bounds, ref items, .. }) => {
2174 // Create a new rib for the trait-wide type parameters.
2175 self.with_generic_param_rib(
2177 ItemRibKind(HasGenericParams::Yes(generics.span)),
2178 LifetimeRibKind::Generics {
2180 kind: LifetimeBinderKind::Item,
2181 span: generics.span,
2184 let local_def_id = this.r.local_def_id(item.id).to_def_id();
2185 this.with_self_rib(Res::SelfTyParam { trait_: local_def_id }, |this| {
2186 this.visit_generics(generics);
2187 walk_list!(this, visit_param_bound, bounds, BoundKind::SuperTraits);
2188 this.resolve_trait_items(items);
2194 ItemKind::TraitAlias(ref generics, ref bounds) => {
2195 // Create a new rib for the trait-wide type parameters.
2196 self.with_generic_param_rib(
2198 ItemRibKind(HasGenericParams::Yes(generics.span)),
2199 LifetimeRibKind::Generics {
2201 kind: LifetimeBinderKind::Item,
2202 span: generics.span,
2205 let local_def_id = this.r.local_def_id(item.id).to_def_id();
2206 this.with_self_rib(Res::SelfTyParam { trait_: local_def_id }, |this| {
2207 this.visit_generics(generics);
2208 walk_list!(this, visit_param_bound, bounds, BoundKind::Bound);
2214 ItemKind::Mod(..) | ItemKind::ForeignMod(_) => {
2215 self.with_scope(item.id, |this| {
2216 visit::walk_item(this, item);
2220 ItemKind::Static(ref ty, _, ref expr) | ItemKind::Const(_, ref ty, ref expr) => {
2221 self.with_static_rib(|this| {
2222 this.with_lifetime_rib(LifetimeRibKind::Elided(LifetimeRes::Static), |this| {
2225 this.with_lifetime_rib(LifetimeRibKind::Elided(LifetimeRes::Infer), |this| {
2226 if let Some(expr) = expr {
2227 let constant_item_kind = match item.kind {
2228 ItemKind::Const(..) => ConstantItemKind::Const,
2229 ItemKind::Static(..) => ConstantItemKind::Static,
2230 _ => unreachable!(),
2232 // We already forbid generic params because of the above item rib,
2233 // so it doesn't matter whether this is a trivial constant.
2234 this.with_constant_rib(
2236 ConstantHasGenerics::Yes,
2237 Some((item.ident, constant_item_kind)),
2238 |this| this.visit_expr(expr),
2245 ItemKind::Use(ref use_tree) => {
2246 self.future_proof_import(use_tree);
2249 ItemKind::ExternCrate(..) | ItemKind::MacroDef(..) => {
2250 // do nothing, these are just around to be encoded
2253 ItemKind::GlobalAsm(_) => {
2254 visit::walk_item(self, item);
2257 ItemKind::MacCall(_) => panic!("unexpanded macro in resolve!"),
2261 fn with_generic_param_rib<'c, F>(
2263 params: &'c [GenericParam],
2265 lifetime_kind: LifetimeRibKind,
2268 F: FnOnce(&mut Self),
2270 debug!("with_generic_param_rib");
2271 let LifetimeRibKind::Generics { binder, span: generics_span, kind: generics_kind, .. }
2272 = lifetime_kind else { panic!() };
2274 let mut function_type_rib = Rib::new(kind);
2275 let mut function_value_rib = Rib::new(kind);
2276 let mut function_lifetime_rib = LifetimeRib::new(lifetime_kind);
2277 let mut seen_bindings = FxHashMap::default();
2278 // Store all seen lifetimes names from outer scopes.
2279 let mut seen_lifetimes = FxHashSet::default();
2281 // We also can't shadow bindings from the parent item
2282 if let AssocItemRibKind = kind {
2283 let mut add_bindings_for_ns = |ns| {
2284 let parent_rib = self.ribs[ns]
2286 .rfind(|r| matches!(r.kind, ItemRibKind(_)))
2287 .expect("associated item outside of an item");
2289 .extend(parent_rib.bindings.iter().map(|(ident, _)| (*ident, ident.span)));
2291 add_bindings_for_ns(ValueNS);
2292 add_bindings_for_ns(TypeNS);
2295 // Forbid shadowing lifetime bindings
2296 for rib in self.lifetime_ribs.iter().rev() {
2297 seen_lifetimes.extend(rib.bindings.iter().map(|(ident, _)| *ident));
2298 if let LifetimeRibKind::Item = rib.kind {
2303 for param in params {
2304 let ident = param.ident.normalize_to_macros_2_0();
2305 debug!("with_generic_param_rib: {}", param.id);
2307 if let GenericParamKind::Lifetime = param.kind
2308 && let Some(&original) = seen_lifetimes.get(&ident)
2310 diagnostics::signal_lifetime_shadowing(self.r.session, original, param.ident);
2311 // Record lifetime res, so lowering knows there is something fishy.
2312 self.record_lifetime_param(param.id, LifetimeRes::Error);
2316 match seen_bindings.entry(ident) {
2317 Entry::Occupied(entry) => {
2318 let span = *entry.get();
2319 let err = ResolutionError::NameAlreadyUsedInParameterList(ident.name, span);
2320 self.report_error(param.ident.span, err);
2321 if let GenericParamKind::Lifetime = param.kind {
2322 // Record lifetime res, so lowering knows there is something fishy.
2323 self.record_lifetime_param(param.id, LifetimeRes::Error);
2327 Entry::Vacant(entry) => {
2328 entry.insert(param.ident.span);
2332 if param.ident.name == kw::UnderscoreLifetime {
2333 rustc_errors::struct_span_err!(
2337 "`'_` cannot be used here"
2339 .span_label(param.ident.span, "`'_` is a reserved lifetime name")
2341 // Record lifetime res, so lowering knows there is something fishy.
2342 self.record_lifetime_param(param.id, LifetimeRes::Error);
2346 if param.ident.name == kw::StaticLifetime {
2347 rustc_errors::struct_span_err!(
2351 "invalid lifetime parameter name: `{}`",
2354 .span_label(param.ident.span, "'static is a reserved lifetime name")
2356 // Record lifetime res, so lowering knows there is something fishy.
2357 self.record_lifetime_param(param.id, LifetimeRes::Error);
2361 let def_id = self.r.local_def_id(param.id);
2363 // Plain insert (no renaming).
2364 let (rib, def_kind) = match param.kind {
2365 GenericParamKind::Type { .. } => (&mut function_type_rib, DefKind::TyParam),
2366 GenericParamKind::Const { .. } => (&mut function_value_rib, DefKind::ConstParam),
2367 GenericParamKind::Lifetime => {
2368 let res = LifetimeRes::Param { param: def_id, binder };
2369 self.record_lifetime_param(param.id, res);
2370 function_lifetime_rib.bindings.insert(ident, (param.id, res));
2375 let res = match kind {
2376 ItemRibKind(..) | AssocItemRibKind => Res::Def(def_kind, def_id.to_def_id()),
2377 NormalRibKind => Res::Err,
2378 _ => span_bug!(param.ident.span, "Unexpected rib kind {:?}", kind),
2380 self.r.record_partial_res(param.id, PartialRes::new(res));
2381 rib.bindings.insert(ident, res);
2384 self.lifetime_ribs.push(function_lifetime_rib);
2385 self.ribs[ValueNS].push(function_value_rib);
2386 self.ribs[TypeNS].push(function_type_rib);
2390 self.ribs[TypeNS].pop();
2391 self.ribs[ValueNS].pop();
2392 let function_lifetime_rib = self.lifetime_ribs.pop().unwrap();
2394 // Do not account for the parameters we just bound for function lifetime elision.
2395 if let Some(ref mut candidates) = self.lifetime_elision_candidates {
2396 for (_, res) in function_lifetime_rib.bindings.values() {
2397 candidates.remove(res);
2401 if let LifetimeBinderKind::BareFnType
2402 | LifetimeBinderKind::WhereBound
2403 | LifetimeBinderKind::Function
2404 | LifetimeBinderKind::ImplBlock = generics_kind
2406 self.maybe_report_lifetime_uses(generics_span, params)
2410 fn with_label_rib(&mut self, kind: RibKind<'a>, f: impl FnOnce(&mut Self)) {
2411 self.label_ribs.push(Rib::new(kind));
2413 self.label_ribs.pop();
2416 fn with_static_rib(&mut self, f: impl FnOnce(&mut Self)) {
2417 let kind = ItemRibKind(HasGenericParams::No);
2418 self.with_rib(ValueNS, kind, |this| this.with_rib(TypeNS, kind, f))
2421 // HACK(min_const_generics,const_evaluatable_unchecked): We
2422 // want to keep allowing `[0; std::mem::size_of::<*mut T>()]`
2423 // with a future compat lint for now. We do this by adding an
2424 // additional special case for repeat expressions.
2426 // Note that we intentionally still forbid `[0; N + 1]` during
2427 // name resolution so that we don't extend the future
2428 // compat lint to new cases.
2429 #[instrument(level = "debug", skip(self, f))]
2430 fn with_constant_rib(
2432 is_repeat: IsRepeatExpr,
2433 may_use_generics: ConstantHasGenerics,
2434 item: Option<(Ident, ConstantItemKind)>,
2435 f: impl FnOnce(&mut Self),
2437 self.with_rib(ValueNS, ConstantItemRibKind(may_use_generics, item), |this| {
2440 ConstantItemRibKind(
2441 may_use_generics.force_yes_if(is_repeat == IsRepeatExpr::Yes),
2445 this.with_label_rib(ConstantItemRibKind(may_use_generics, item), f);
2451 fn with_current_self_type<T>(&mut self, self_type: &Ty, f: impl FnOnce(&mut Self) -> T) -> T {
2452 // Handle nested impls (inside fn bodies)
2453 let previous_value =
2454 replace(&mut self.diagnostic_metadata.current_self_type, Some(self_type.clone()));
2455 let result = f(self);
2456 self.diagnostic_metadata.current_self_type = previous_value;
2460 fn with_current_self_item<T>(&mut self, self_item: &Item, f: impl FnOnce(&mut Self) -> T) -> T {
2461 let previous_value =
2462 replace(&mut self.diagnostic_metadata.current_self_item, Some(self_item.id));
2463 let result = f(self);
2464 self.diagnostic_metadata.current_self_item = previous_value;
2468 /// When evaluating a `trait` use its associated types' idents for suggestions in E0412.
2469 fn resolve_trait_items(&mut self, trait_items: &'ast [P<AssocItem>]) {
2470 let trait_assoc_items =
2471 replace(&mut self.diagnostic_metadata.current_trait_assoc_items, Some(&trait_items));
2473 let walk_assoc_item =
2474 |this: &mut Self, generics: &Generics, kind, item: &'ast AssocItem| {
2475 this.with_generic_param_rib(
2478 LifetimeRibKind::Generics { binder: item.id, span: generics.span, kind },
2479 |this| visit::walk_assoc_item(this, item, AssocCtxt::Trait),
2483 for item in trait_items {
2485 AssocItemKind::Const(_, ty, default) => {
2487 // Only impose the restrictions of `ConstRibKind` for an
2488 // actual constant expression in a provided default.
2489 if let Some(expr) = default {
2490 // We allow arbitrary const expressions inside of associated consts,
2491 // even if they are potentially not const evaluatable.
2493 // Type parameters can already be used and as associated consts are
2494 // not used as part of the type system, this is far less surprising.
2495 self.with_lifetime_rib(
2496 LifetimeRibKind::Elided(LifetimeRes::Infer),
2498 this.with_constant_rib(
2500 ConstantHasGenerics::Yes,
2502 |this| this.visit_expr(expr),
2508 AssocItemKind::Fn(box Fn { generics, .. }) => {
2509 walk_assoc_item(self, generics, LifetimeBinderKind::Function, item);
2511 AssocItemKind::Type(box TyAlias { generics, .. }) => self
2512 .with_lifetime_rib(LifetimeRibKind::AnonymousReportError, |this| {
2513 walk_assoc_item(this, generics, LifetimeBinderKind::Item, item)
2515 AssocItemKind::MacCall(_) => {
2516 panic!("unexpanded macro in resolve!")
2521 self.diagnostic_metadata.current_trait_assoc_items = trait_assoc_items;
2524 /// This is called to resolve a trait reference from an `impl` (i.e., `impl Trait for Foo`).
2525 fn with_optional_trait_ref<T>(
2527 opt_trait_ref: Option<&TraitRef>,
2528 self_type: &'ast Ty,
2529 f: impl FnOnce(&mut Self, Option<DefId>) -> T,
2531 let mut new_val = None;
2532 let mut new_id = None;
2533 if let Some(trait_ref) = opt_trait_ref {
2534 let path: Vec<_> = Segment::from_path(&trait_ref.path);
2535 self.diagnostic_metadata.currently_processing_impl_trait =
2536 Some((trait_ref.clone(), self_type.clone()));
2537 let res = self.smart_resolve_path_fragment(
2540 PathSource::Trait(AliasPossibility::No),
2541 Finalize::new(trait_ref.ref_id, trait_ref.path.span),
2543 self.diagnostic_metadata.currently_processing_impl_trait = None;
2544 if let Some(def_id) = res.expect_full_res().opt_def_id() {
2545 new_id = Some(def_id);
2546 new_val = Some((self.r.expect_module(def_id), trait_ref.clone()));
2549 let original_trait_ref = replace(&mut self.current_trait_ref, new_val);
2550 let result = f(self, new_id);
2551 self.current_trait_ref = original_trait_ref;
2555 fn with_self_rib_ns(&mut self, ns: Namespace, self_res: Res, f: impl FnOnce(&mut Self)) {
2556 let mut self_type_rib = Rib::new(NormalRibKind);
2558 // Plain insert (no renaming, since types are not currently hygienic)
2559 self_type_rib.bindings.insert(Ident::with_dummy_span(kw::SelfUpper), self_res);
2560 self.ribs[ns].push(self_type_rib);
2562 self.ribs[ns].pop();
2565 fn with_self_rib(&mut self, self_res: Res, f: impl FnOnce(&mut Self)) {
2566 self.with_self_rib_ns(TypeNS, self_res, f)
2569 fn resolve_implementation(
2571 generics: &'ast Generics,
2572 opt_trait_reference: &'ast Option<TraitRef>,
2573 self_type: &'ast Ty,
2575 impl_items: &'ast [P<AssocItem>],
2577 debug!("resolve_implementation");
2578 // If applicable, create a rib for the type parameters.
2579 self.with_generic_param_rib(
2581 ItemRibKind(HasGenericParams::Yes(generics.span)),
2582 LifetimeRibKind::Generics {
2583 span: generics.span,
2585 kind: LifetimeBinderKind::ImplBlock,
2588 // Dummy self type for better errors if `Self` is used in the trait path.
2589 this.with_self_rib(Res::SelfTyParam { trait_: LOCAL_CRATE.as_def_id() }, |this| {
2590 this.with_lifetime_rib(
2591 LifetimeRibKind::AnonymousCreateParameter {
2593 report_in_path: true
2596 // Resolve the trait reference, if necessary.
2597 this.with_optional_trait_ref(
2598 opt_trait_reference.as_ref(),
2601 let item_def_id = this.r.local_def_id(item_id);
2603 // Register the trait definitions from here.
2604 if let Some(trait_id) = trait_id {
2612 let item_def_id = item_def_id.to_def_id();
2613 let res = Res::SelfTyAlias {
2614 alias_to: item_def_id,
2615 forbid_generic: false,
2616 is_trait_impl: trait_id.is_some()
2618 this.with_self_rib(res, |this| {
2619 if let Some(trait_ref) = opt_trait_reference.as_ref() {
2620 // Resolve type arguments in the trait path.
2621 visit::walk_trait_ref(this, trait_ref);
2623 // Resolve the self type.
2624 this.visit_ty(self_type);
2625 // Resolve the generic parameters.
2626 this.visit_generics(generics);
2628 // Resolve the items within the impl.
2629 this.with_current_self_type(self_type, |this| {
2630 this.with_self_rib_ns(ValueNS, Res::SelfCtor(item_def_id), |this| {
2631 debug!("resolve_implementation with_self_rib_ns(ValueNS, ...)");
2632 let mut seen_trait_items = Default::default();
2633 for item in impl_items {
2634 this.resolve_impl_item(&**item, &mut seen_trait_items);
2648 fn resolve_impl_item(
2650 item: &'ast AssocItem,
2651 seen_trait_items: &mut FxHashMap<DefId, Span>,
2653 use crate::ResolutionError::*;
2655 AssocItemKind::Const(_, ty, default) => {
2656 debug!("resolve_implementation AssocItemKind::Const");
2657 // If this is a trait impl, ensure the const
2659 self.check_trait_item(
2666 |i, s, c| ConstNotMemberOfTrait(i, s, c),
2670 if let Some(expr) = default {
2671 // We allow arbitrary const expressions inside of associated consts,
2672 // even if they are potentially not const evaluatable.
2674 // Type parameters can already be used and as associated consts are
2675 // not used as part of the type system, this is far less surprising.
2676 self.with_lifetime_rib(LifetimeRibKind::Elided(LifetimeRes::Infer), |this| {
2677 this.with_constant_rib(
2679 ConstantHasGenerics::Yes,
2681 |this| this.visit_expr(expr),
2686 AssocItemKind::Fn(box Fn { generics, .. }) => {
2687 debug!("resolve_implementation AssocItemKind::Fn");
2688 // We also need a new scope for the impl item type parameters.
2689 self.with_generic_param_rib(
2692 LifetimeRibKind::Generics {
2694 span: generics.span,
2695 kind: LifetimeBinderKind::Function,
2698 // If this is a trait impl, ensure the method
2700 this.check_trait_item(
2707 |i, s, c| MethodNotMemberOfTrait(i, s, c),
2710 visit::walk_assoc_item(this, item, AssocCtxt::Impl)
2714 AssocItemKind::Type(box TyAlias { generics, .. }) => {
2715 debug!("resolve_implementation AssocItemKind::Type");
2716 // We also need a new scope for the impl item type parameters.
2717 self.with_generic_param_rib(
2720 LifetimeRibKind::Generics {
2722 span: generics.span,
2723 kind: LifetimeBinderKind::Item,
2726 this.with_lifetime_rib(LifetimeRibKind::AnonymousReportError, |this| {
2727 // If this is a trait impl, ensure the type
2729 this.check_trait_item(
2736 |i, s, c| TypeNotMemberOfTrait(i, s, c),
2739 visit::walk_assoc_item(this, item, AssocCtxt::Impl)
2744 AssocItemKind::MacCall(_) => {
2745 panic!("unexpanded macro in resolve!")
2750 fn check_trait_item<F>(
2754 kind: &AssocItemKind,
2757 seen_trait_items: &mut FxHashMap<DefId, Span>,
2760 F: FnOnce(Ident, String, Option<Symbol>) -> ResolutionError<'a>,
2762 // If there is a TraitRef in scope for an impl, then the method must be in the trait.
2763 let Some((module, _)) = &self.current_trait_ref else { return; };
2764 ident.span.normalize_to_macros_2_0_and_adjust(module.expansion);
2765 let key = self.r.new_key(ident, ns);
2766 let mut binding = self.r.resolution(module, key).try_borrow().ok().and_then(|r| r.binding);
2768 if binding.is_none() {
2769 // We could not find the trait item in the correct namespace.
2770 // Check the other namespace to report an error.
2776 let key = self.r.new_key(ident, ns);
2777 binding = self.r.resolution(module, key).try_borrow().ok().and_then(|r| r.binding);
2780 let Some(binding) = binding else {
2781 // We could not find the method: report an error.
2782 let candidate = self.find_similarly_named_assoc_item(ident.name, kind);
2783 let path = &self.current_trait_ref.as_ref().unwrap().1.path;
2784 let path_names = path_names_to_string(path);
2785 self.report_error(span, err(ident, path_names, candidate));
2789 let res = binding.res();
2790 let Res::Def(def_kind, id_in_trait) = res else { bug!() };
2792 match seen_trait_items.entry(id_in_trait) {
2793 Entry::Occupied(entry) => {
2796 ResolutionError::TraitImplDuplicate {
2798 old_span: *entry.get(),
2799 trait_item_span: binding.span,
2804 Entry::Vacant(entry) => {
2809 match (def_kind, kind) {
2810 (DefKind::AssocTy, AssocItemKind::Type(..))
2811 | (DefKind::AssocFn, AssocItemKind::Fn(..))
2812 | (DefKind::AssocConst, AssocItemKind::Const(..)) => {
2813 self.r.record_partial_res(id, PartialRes::new(res));
2819 // The method kind does not correspond to what appeared in the trait, report.
2820 let path = &self.current_trait_ref.as_ref().unwrap().1.path;
2821 let (code, kind) = match kind {
2822 AssocItemKind::Const(..) => (rustc_errors::error_code!(E0323), "const"),
2823 AssocItemKind::Fn(..) => (rustc_errors::error_code!(E0324), "method"),
2824 AssocItemKind::Type(..) => (rustc_errors::error_code!(E0325), "type"),
2825 AssocItemKind::MacCall(..) => span_bug!(span, "unexpanded macro"),
2827 let trait_path = path_names_to_string(path);
2830 ResolutionError::TraitImplMismatch {
2835 trait_item_span: binding.span,
2840 fn resolve_params(&mut self, params: &'ast [Param]) {
2841 let mut bindings = smallvec![(PatBoundCtx::Product, Default::default())];
2842 self.with_lifetime_rib(LifetimeRibKind::Elided(LifetimeRes::Infer), |this| {
2843 for Param { pat, .. } in params {
2844 this.resolve_pattern(pat, PatternSource::FnParam, &mut bindings);
2847 for Param { ty, .. } in params {
2852 fn resolve_local(&mut self, local: &'ast Local) {
2853 debug!("resolving local ({:?})", local);
2854 // Resolve the type.
2855 walk_list!(self, visit_ty, &local.ty);
2857 // Resolve the initializer.
2858 if let Some((init, els)) = local.kind.init_else_opt() {
2859 self.visit_expr(init);
2861 // Resolve the `else` block
2862 if let Some(els) = els {
2863 self.visit_block(els);
2867 // Resolve the pattern.
2868 self.resolve_pattern_top(&local.pat, PatternSource::Let);
2871 /// build a map from pattern identifiers to binding-info's.
2872 /// this is done hygienically. This could arise for a macro
2873 /// that expands into an or-pattern where one 'x' was from the
2874 /// user and one 'x' came from the macro.
2875 fn binding_mode_map(&mut self, pat: &Pat) -> BindingMap {
2876 let mut binding_map = FxHashMap::default();
2878 pat.walk(&mut |pat| {
2880 PatKind::Ident(annotation, ident, ref sub_pat)
2881 if sub_pat.is_some() || self.is_base_res_local(pat.id) =>
2883 binding_map.insert(ident, BindingInfo { span: ident.span, annotation });
2885 PatKind::Or(ref ps) => {
2886 // Check the consistency of this or-pattern and
2887 // then add all bindings to the larger map.
2888 for bm in self.check_consistent_bindings(ps) {
2889 binding_map.extend(bm);
2902 fn is_base_res_local(&self, nid: NodeId) -> bool {
2904 self.r.partial_res_map.get(&nid).map(|res| res.expect_full_res()),
2905 Some(Res::Local(..))
2909 /// Checks that all of the arms in an or-pattern have exactly the
2910 /// same set of bindings, with the same binding modes for each.
2911 fn check_consistent_bindings(&mut self, pats: &[P<Pat>]) -> Vec<BindingMap> {
2912 let mut missing_vars = FxHashMap::default();
2913 let mut inconsistent_vars = FxHashMap::default();
2915 // 1) Compute the binding maps of all arms.
2916 let maps = pats.iter().map(|pat| self.binding_mode_map(pat)).collect::<Vec<_>>();
2918 // 2) Record any missing bindings or binding mode inconsistencies.
2919 for (map_outer, pat_outer) in pats.iter().enumerate().map(|(idx, pat)| (&maps[idx], pat)) {
2920 // Check against all arms except for the same pattern which is always self-consistent.
2924 .filter(|(_, pat)| pat.id != pat_outer.id)
2925 .flat_map(|(idx, _)| maps[idx].iter())
2926 .map(|(key, binding)| (key.name, map_outer.get(&key), binding));
2928 for (name, info, &binding_inner) in inners {
2931 // The inner binding is missing in the outer.
2933 missing_vars.entry(name).or_insert_with(|| BindingError {
2935 origin: BTreeSet::new(),
2936 target: BTreeSet::new(),
2937 could_be_path: name.as_str().starts_with(char::is_uppercase),
2939 binding_error.origin.insert(binding_inner.span);
2940 binding_error.target.insert(pat_outer.span);
2942 Some(binding_outer) => {
2943 if binding_outer.annotation != binding_inner.annotation {
2944 // The binding modes in the outer and inner bindings differ.
2947 .or_insert((binding_inner.span, binding_outer.span));
2954 // 3) Report all missing variables we found.
2955 let mut missing_vars = missing_vars.into_iter().collect::<Vec<_>>();
2956 missing_vars.sort_by_key(|&(sym, ref _err)| sym);
2958 for (name, mut v) in missing_vars.into_iter() {
2959 if inconsistent_vars.contains_key(&name) {
2960 v.could_be_path = false;
2963 *v.origin.iter().next().unwrap(),
2964 ResolutionError::VariableNotBoundInPattern(v, self.parent_scope),
2968 // 4) Report all inconsistencies in binding modes we found.
2969 let mut inconsistent_vars = inconsistent_vars.iter().collect::<Vec<_>>();
2970 inconsistent_vars.sort();
2971 for (name, v) in inconsistent_vars {
2972 self.report_error(v.0, ResolutionError::VariableBoundWithDifferentMode(*name, v.1));
2975 // 5) Finally bubble up all the binding maps.
2979 /// Check the consistency of the outermost or-patterns.
2980 fn check_consistent_bindings_top(&mut self, pat: &'ast Pat) {
2981 pat.walk(&mut |pat| match pat.kind {
2982 PatKind::Or(ref ps) => {
2983 self.check_consistent_bindings(ps);
2990 fn resolve_arm(&mut self, arm: &'ast Arm) {
2991 self.with_rib(ValueNS, NormalRibKind, |this| {
2992 this.resolve_pattern_top(&arm.pat, PatternSource::Match);
2993 walk_list!(this, visit_expr, &arm.guard);
2994 this.visit_expr(&arm.body);
2998 /// Arising from `source`, resolve a top level pattern.
2999 fn resolve_pattern_top(&mut self, pat: &'ast Pat, pat_src: PatternSource) {
3000 let mut bindings = smallvec![(PatBoundCtx::Product, Default::default())];
3001 self.resolve_pattern(pat, pat_src, &mut bindings);
3007 pat_src: PatternSource,
3008 bindings: &mut SmallVec<[(PatBoundCtx, FxHashSet<Ident>); 1]>,
3010 // We walk the pattern before declaring the pattern's inner bindings,
3011 // so that we avoid resolving a literal expression to a binding defined
3013 visit::walk_pat(self, pat);
3014 self.resolve_pattern_inner(pat, pat_src, bindings);
3015 // This has to happen *after* we determine which pat_idents are variants:
3016 self.check_consistent_bindings_top(pat);
3019 /// Resolve bindings in a pattern. This is a helper to `resolve_pattern`.
3023 /// A stack of sets of bindings accumulated.
3025 /// In each set, `PatBoundCtx::Product` denotes that a found binding in it should
3026 /// be interpreted as re-binding an already bound binding. This results in an error.
3027 /// Meanwhile, `PatBound::Or` denotes that a found binding in the set should result
3028 /// in reusing this binding rather than creating a fresh one.
3030 /// When called at the top level, the stack must have a single element
3031 /// with `PatBound::Product`. Otherwise, pushing to the stack happens as
3032 /// or-patterns (`p_0 | ... | p_n`) are encountered and the context needs
3033 /// to be switched to `PatBoundCtx::Or` and then `PatBoundCtx::Product` for each `p_i`.
3034 /// When each `p_i` has been dealt with, the top set is merged with its parent.
3035 /// When a whole or-pattern has been dealt with, the thing happens.
3037 /// See the implementation and `fresh_binding` for more details.
3038 fn resolve_pattern_inner(
3041 pat_src: PatternSource,
3042 bindings: &mut SmallVec<[(PatBoundCtx, FxHashSet<Ident>); 1]>,
3044 // Visit all direct subpatterns of this pattern.
3045 pat.walk(&mut |pat| {
3046 debug!("resolve_pattern pat={:?} node={:?}", pat, pat.kind);
3048 PatKind::Ident(bmode, ident, ref sub) => {
3049 // First try to resolve the identifier as some existing entity,
3050 // then fall back to a fresh binding.
3051 let has_sub = sub.is_some();
3053 .try_resolve_as_non_binding(pat_src, bmode, ident, has_sub)
3054 .unwrap_or_else(|| self.fresh_binding(ident, pat.id, pat_src, bindings));
3055 self.r.record_partial_res(pat.id, PartialRes::new(res));
3056 self.r.record_pat_span(pat.id, pat.span);
3058 PatKind::TupleStruct(ref qself, ref path, ref sub_patterns) => {
3059 self.smart_resolve_path(
3063 PathSource::TupleStruct(
3065 self.r.arenas.alloc_pattern_spans(sub_patterns.iter().map(|p| p.span)),
3069 PatKind::Path(ref qself, ref path) => {
3070 self.smart_resolve_path(pat.id, qself.as_ref(), path, PathSource::Pat);
3072 PatKind::Struct(ref qself, ref path, ..) => {
3073 self.smart_resolve_path(pat.id, qself.as_ref(), path, PathSource::Struct);
3075 PatKind::Or(ref ps) => {
3076 // Add a new set of bindings to the stack. `Or` here records that when a
3077 // binding already exists in this set, it should not result in an error because
3078 // `V1(a) | V2(a)` must be allowed and are checked for consistency later.
3079 bindings.push((PatBoundCtx::Or, Default::default()));
3081 // Now we need to switch back to a product context so that each
3082 // part of the or-pattern internally rejects already bound names.
3083 // For example, `V1(a) | V2(a, a)` and `V1(a, a) | V2(a)` are bad.
3084 bindings.push((PatBoundCtx::Product, Default::default()));
3085 self.resolve_pattern_inner(p, pat_src, bindings);
3086 // Move up the non-overlapping bindings to the or-pattern.
3087 // Existing bindings just get "merged".
3088 let collected = bindings.pop().unwrap().1;
3089 bindings.last_mut().unwrap().1.extend(collected);
3091 // This or-pattern itself can itself be part of a product,
3092 // e.g. `(V1(a) | V2(a), a)` or `(a, V1(a) | V2(a))`.
3093 // Both cases bind `a` again in a product pattern and must be rejected.
3094 let collected = bindings.pop().unwrap().1;
3095 bindings.last_mut().unwrap().1.extend(collected);
3097 // Prevent visiting `ps` as we've already done so above.
3110 pat_src: PatternSource,
3111 bindings: &mut SmallVec<[(PatBoundCtx, FxHashSet<Ident>); 1]>,
3113 // Add the binding to the local ribs, if it doesn't already exist in the bindings map.
3114 // (We must not add it if it's in the bindings map because that breaks the assumptions
3115 // later passes make about or-patterns.)
3116 let ident = ident.normalize_to_macro_rules();
3118 let mut bound_iter = bindings.iter().filter(|(_, set)| set.contains(&ident));
3119 // Already bound in a product pattern? e.g. `(a, a)` which is not allowed.
3120 let already_bound_and = bound_iter.clone().any(|(ctx, _)| *ctx == PatBoundCtx::Product);
3121 // Already bound in an or-pattern? e.g. `V1(a) | V2(a)`.
3122 // This is *required* for consistency which is checked later.
3123 let already_bound_or = bound_iter.any(|(ctx, _)| *ctx == PatBoundCtx::Or);
3125 if already_bound_and {
3126 // Overlap in a product pattern somewhere; report an error.
3127 use ResolutionError::*;
3128 let error = match pat_src {
3129 // `fn f(a: u8, a: u8)`:
3130 PatternSource::FnParam => IdentifierBoundMoreThanOnceInParameterList,
3132 _ => IdentifierBoundMoreThanOnceInSamePattern,
3134 self.report_error(ident.span, error(ident.name));
3137 // Record as bound if it's valid:
3138 let ident_valid = ident.name != kw::Empty;
3140 bindings.last_mut().unwrap().1.insert(ident);
3143 if already_bound_or {
3144 // `Variant1(a) | Variant2(a)`, ok
3145 // Reuse definition from the first `a`.
3146 self.innermost_rib_bindings(ValueNS)[&ident]
3148 let res = Res::Local(pat_id);
3150 // A completely fresh binding add to the set if it's valid.
3151 self.innermost_rib_bindings(ValueNS).insert(ident, res);
3157 fn innermost_rib_bindings(&mut self, ns: Namespace) -> &mut IdentMap<Res> {
3158 &mut self.ribs[ns].last_mut().unwrap().bindings
3161 fn try_resolve_as_non_binding(
3163 pat_src: PatternSource,
3164 ann: BindingAnnotation,
3168 // An immutable (no `mut`) by-value (no `ref`) binding pattern without
3169 // a sub pattern (no `@ $pat`) is syntactically ambiguous as it could
3170 // also be interpreted as a path to e.g. a constant, variant, etc.
3171 let is_syntactic_ambiguity = !has_sub && ann == BindingAnnotation::NONE;
3173 let ls_binding = self.maybe_resolve_ident_in_lexical_scope(ident, ValueNS)?;
3174 let (res, binding) = match ls_binding {
3175 LexicalScopeBinding::Item(binding)
3176 if is_syntactic_ambiguity && binding.is_ambiguity() =>
3178 // For ambiguous bindings we don't know all their definitions and cannot check
3179 // whether they can be shadowed by fresh bindings or not, so force an error.
3180 // issues/33118#issuecomment-233962221 (see below) still applies here,
3181 // but we have to ignore it for backward compatibility.
3182 self.r.record_use(ident, binding, false);
3185 LexicalScopeBinding::Item(binding) => (binding.res(), Some(binding)),
3186 LexicalScopeBinding::Res(res) => (res, None),
3190 Res::SelfCtor(_) // See #70549.
3192 DefKind::Ctor(_, CtorKind::Const) | DefKind::Const | DefKind::ConstParam,
3194 ) if is_syntactic_ambiguity => {
3195 // Disambiguate in favor of a unit struct/variant or constant pattern.
3196 if let Some(binding) = binding {
3197 self.r.record_use(ident, binding, false);
3201 Res::Def(DefKind::Ctor(..) | DefKind::Const | DefKind::Static(_), _) => {
3202 // This is unambiguously a fresh binding, either syntactically
3203 // (e.g., `IDENT @ PAT` or `ref IDENT`) or because `IDENT` resolves
3204 // to something unusable as a pattern (e.g., constructor function),
3205 // but we still conservatively report an error, see
3206 // issues/33118#issuecomment-233962221 for one reason why.
3207 let binding = binding.expect("no binding for a ctor or static");
3210 ResolutionError::BindingShadowsSomethingUnacceptable {
3211 shadowing_binding: pat_src,
3213 participle: if binding.is_import() { "imported" } else { "defined" },
3214 article: binding.res().article(),
3215 shadowed_binding: binding.res(),
3216 shadowed_binding_span: binding.span,
3221 Res::Def(DefKind::ConstParam, def_id) => {
3222 // Same as for DefKind::Const above, but here, `binding` is `None`, so we
3223 // have to construct the error differently
3226 ResolutionError::BindingShadowsSomethingUnacceptable {
3227 shadowing_binding: pat_src,
3229 participle: "defined",
3230 article: res.article(),
3231 shadowed_binding: res,
3232 shadowed_binding_span: self.r.opt_span(def_id).expect("const parameter defined outside of local crate"),
3237 Res::Def(DefKind::Fn, _) | Res::Local(..) | Res::Err => {
3238 // These entities are explicitly allowed to be shadowed by fresh bindings.
3241 Res::SelfCtor(_) => {
3242 // We resolve `Self` in pattern position as an ident sometimes during recovery,
3243 // so delay a bug instead of ICEing.
3244 self.r.session.delay_span_bug(
3246 "unexpected `SelfCtor` in pattern, expected identifier"
3252 "unexpected resolution for an identifier in pattern: {:?}",
3258 // High-level and context dependent path resolution routine.
3259 // Resolves the path and records the resolution into definition map.
3260 // If resolution fails tries several techniques to find likely
3261 // resolution candidates, suggest imports or other help, and report
3262 // errors in user friendly way.
3263 fn smart_resolve_path(
3266 qself: Option<&QSelf>,
3268 source: PathSource<'ast>,
3270 self.smart_resolve_path_fragment(
3272 &Segment::from_path(path),
3274 Finalize::new(id, path.span),
3278 fn smart_resolve_path_fragment(
3280 qself: Option<&QSelf>,
3282 source: PathSource<'ast>,
3286 "smart_resolve_path_fragment(qself={:?}, path={:?}, finalize={:?})",
3287 qself, path, finalize,
3289 let ns = source.namespace();
3291 let Finalize { node_id, path_span, .. } = finalize;
3292 let report_errors = |this: &mut Self, res: Option<Res>| {
3293 if this.should_report_errs() {
3294 let (err, candidates) =
3295 this.smart_resolve_report_errors(path, path_span, source, res);
3297 let def_id = this.parent_scope.module.nearest_parent_mod();
3298 let instead = res.is_some();
3300 if res.is_none() { this.report_missing_type_error(path) } else { None };
3302 this.r.use_injections.push(UseError {
3309 is_call: source.is_call(),
3313 PartialRes::new(Res::Err)
3316 // For paths originating from calls (like in `HashMap::new()`), tries
3317 // to enrich the plain `failed to resolve: ...` message with hints
3318 // about possible missing imports.
3320 // Similar thing, for types, happens in `report_errors` above.
3321 let report_errors_for_call = |this: &mut Self, parent_err: Spanned<ResolutionError<'a>>| {
3322 if !source.is_call() {
3323 return Some(parent_err);
3326 // Before we start looking for candidates, we have to get our hands
3327 // on the type user is trying to perform invocation on; basically:
3328 // we're transforming `HashMap::new` into just `HashMap`.
3329 let path = match path.split_last() {
3330 Some((_, path)) if !path.is_empty() => path,
3331 _ => return Some(parent_err),
3334 let (mut err, candidates) =
3335 this.smart_resolve_report_errors(path, path_span, PathSource::Type, None);
3337 if candidates.is_empty() {
3339 return Some(parent_err);
3342 // There are two different error messages user might receive at
3344 // - E0412 cannot find type `{}` in this scope
3345 // - E0433 failed to resolve: use of undeclared type or module `{}`
3347 // The first one is emitted for paths in type-position, and the
3348 // latter one - for paths in expression-position.
3350 // Thus (since we're in expression-position at this point), not to
3351 // confuse the user, we want to keep the *message* from E0432 (so
3352 // `parent_err`), but we want *hints* from E0412 (so `err`).
3354 // And that's what happens below - we're just mixing both messages
3355 // into a single one.
3356 let mut parent_err = this.r.into_struct_error(parent_err.span, parent_err.node);
3358 err.message = take(&mut parent_err.message);
3359 err.code = take(&mut parent_err.code);
3360 err.children = take(&mut parent_err.children);
3362 parent_err.cancel();
3364 let def_id = this.parent_scope.module.nearest_parent_mod();
3366 if this.should_report_errs() {
3367 this.r.use_injections.push(UseError {
3374 is_call: source.is_call(),
3380 // We don't return `Some(parent_err)` here, because the error will
3381 // be already printed as part of the `use` injections
3385 let partial_res = match self.resolve_qpath_anywhere(
3390 source.defer_to_typeck(),
3393 Ok(Some(partial_res)) if let Some(res) = partial_res.full_res() => {
3394 if source.is_expected(res) || res == Res::Err {
3397 report_errors(self, Some(res))
3401 Ok(Some(partial_res)) if source.defer_to_typeck() => {
3402 // Not fully resolved associated item `T::A::B` or `<T as Tr>::A::B`
3403 // or `<T>::A::B`. If `B` should be resolved in value namespace then
3404 // it needs to be added to the trait map.
3406 let item_name = path.last().unwrap().ident;
3407 let traits = self.traits_in_scope(item_name, ns);
3408 self.r.trait_map.insert(node_id, traits);
3411 if PrimTy::from_name(path[0].ident.name).is_some() {
3412 let mut std_path = Vec::with_capacity(1 + path.len());
3414 std_path.push(Segment::from_ident(Ident::with_dummy_span(sym::std)));
3415 std_path.extend(path);
3416 if let PathResult::Module(_) | PathResult::NonModule(_) =
3417 self.resolve_path(&std_path, Some(ns), None)
3419 // Check if we wrote `str::from_utf8` instead of `std::str::from_utf8`
3421 path.iter().last().map_or(path_span, |segment| segment.ident.span);
3423 self.r.confused_type_with_std_module.insert(item_span, path_span);
3424 self.r.confused_type_with_std_module.insert(path_span, path_span);
3432 if let Some(err) = report_errors_for_call(self, err) {
3433 self.report_error(err.span, err.node);
3436 PartialRes::new(Res::Err)
3439 _ => report_errors(self, None),
3442 if !matches!(source, PathSource::TraitItem(..)) {
3443 // Avoid recording definition of `A::B` in `<T as A>::B::C`.
3444 self.r.record_partial_res(node_id, partial_res);
3445 self.resolve_elided_lifetimes_in_path(node_id, partial_res, path, source, path_span);
3451 fn self_type_is_available(&mut self) -> bool {
3453 .maybe_resolve_ident_in_lexical_scope(Ident::with_dummy_span(kw::SelfUpper), TypeNS);
3454 if let Some(LexicalScopeBinding::Res(res)) = binding { res != Res::Err } else { false }
3457 fn self_value_is_available(&mut self, self_span: Span) -> bool {
3458 let ident = Ident::new(kw::SelfLower, self_span);
3459 let binding = self.maybe_resolve_ident_in_lexical_scope(ident, ValueNS);
3460 if let Some(LexicalScopeBinding::Res(res)) = binding { res != Res::Err } else { false }
3463 /// A wrapper around [`Resolver::report_error`].
3465 /// This doesn't emit errors for function bodies if this is rustdoc.
3466 fn report_error(&mut self, span: Span, resolution_error: ResolutionError<'a>) {
3467 if self.should_report_errs() {
3468 self.r.report_error(span, resolution_error);
3473 /// If we're actually rustdoc then avoid giving a name resolution error for `cfg()` items.
3474 fn should_report_errs(&self) -> bool {
3475 !(self.r.session.opts.actually_rustdoc && self.in_func_body)
3478 // Resolve in alternative namespaces if resolution in the primary namespace fails.
3479 fn resolve_qpath_anywhere(
3481 qself: Option<&QSelf>,
3483 primary_ns: Namespace,
3485 defer_to_typeck: bool,
3487 ) -> Result<Option<PartialRes>, Spanned<ResolutionError<'a>>> {
3488 let mut fin_res = None;
3490 for (i, &ns) in [primary_ns, TypeNS, ValueNS].iter().enumerate() {
3491 if i == 0 || ns != primary_ns {
3492 match self.resolve_qpath(qself, path, ns, finalize)? {
3494 if partial_res.unresolved_segments() == 0 || defer_to_typeck =>
3496 return Ok(Some(partial_res));
3499 if fin_res.is_none() {
3500 fin_res = partial_res;
3507 assert!(primary_ns != MacroNS);
3509 if qself.is_none() {
3510 let path_seg = |seg: &Segment| PathSegment::from_ident(seg.ident);
3511 let path = Path { segments: path.iter().map(path_seg).collect(), span, tokens: None };
3512 if let Ok((_, res)) =
3513 self.r.resolve_macro_path(&path, None, &self.parent_scope, false, false)
3515 return Ok(Some(PartialRes::new(res)));
3522 /// Handles paths that may refer to associated items.
3525 qself: Option<&QSelf>,
3529 ) -> Result<Option<PartialRes>, Spanned<ResolutionError<'a>>> {
3531 "resolve_qpath(qself={:?}, path={:?}, ns={:?}, finalize={:?})",
3532 qself, path, ns, finalize,
3535 if let Some(qself) = qself {
3536 if qself.position == 0 {
3537 // This is a case like `<T>::B`, where there is no
3538 // trait to resolve. In that case, we leave the `B`
3539 // segment to be resolved by type-check.
3540 return Ok(Some(PartialRes::with_unresolved_segments(
3541 Res::Def(DefKind::Mod, CRATE_DEF_ID.to_def_id()),
3546 // Make sure `A::B` in `<T as A::B>::C` is a trait item.
3548 // Currently, `path` names the full item (`A::B::C`, in
3549 // our example). so we extract the prefix of that that is
3550 // the trait (the slice upto and including
3551 // `qself.position`). And then we recursively resolve that,
3552 // but with `qself` set to `None`.
3553 let ns = if qself.position + 1 == path.len() { ns } else { TypeNS };
3554 let partial_res = self.smart_resolve_path_fragment(
3556 &path[..=qself.position],
3557 PathSource::TraitItem(ns),
3558 Finalize::with_root_span(finalize.node_id, finalize.path_span, qself.path_span),
3561 // The remaining segments (the `C` in our example) will
3562 // have to be resolved by type-check, since that requires doing
3563 // trait resolution.
3564 return Ok(Some(PartialRes::with_unresolved_segments(
3565 partial_res.base_res(),
3566 partial_res.unresolved_segments() + path.len() - qself.position - 1,
3570 let result = match self.resolve_path(&path, Some(ns), Some(finalize)) {
3571 PathResult::NonModule(path_res) => path_res,
3572 PathResult::Module(ModuleOrUniformRoot::Module(module)) if !module.is_normal() => {
3573 PartialRes::new(module.res().unwrap())
3575 // In `a(::assoc_item)*` `a` cannot be a module. If `a` does resolve to a module we
3576 // don't report an error right away, but try to fallback to a primitive type.
3577 // So, we are still able to successfully resolve something like
3579 // use std::u8; // bring module u8 in scope
3580 // fn f() -> u8 { // OK, resolves to primitive u8, not to std::u8
3581 // u8::max_value() // OK, resolves to associated function <u8>::max_value,
3582 // // not to non-existent std::u8::max_value
3585 // Such behavior is required for backward compatibility.
3586 // The same fallback is used when `a` resolves to nothing.
3587 PathResult::Module(ModuleOrUniformRoot::Module(_)) | PathResult::Failed { .. }
3588 if (ns == TypeNS || path.len() > 1)
3589 && PrimTy::from_name(path[0].ident.name).is_some() =>
3591 let prim = PrimTy::from_name(path[0].ident.name).unwrap();
3592 PartialRes::with_unresolved_segments(Res::PrimTy(prim), path.len() - 1)
3594 PathResult::Module(ModuleOrUniformRoot::Module(module)) => {
3595 PartialRes::new(module.res().unwrap())
3597 PathResult::Failed { is_error_from_last_segment: false, span, label, suggestion } => {
3598 return Err(respan(span, ResolutionError::FailedToResolve { label, suggestion }));
3600 PathResult::Module(..) | PathResult::Failed { .. } => return Ok(None),
3601 PathResult::Indeterminate => bug!("indeterminate path result in resolve_qpath"),
3605 && let Some(res) = result.full_res()
3607 && path[0].ident.name != kw::PathRoot
3608 && path[0].ident.name != kw::DollarCrate
3610 let unqualified_result = {
3611 match self.resolve_path(&[*path.last().unwrap()], Some(ns), None) {
3612 PathResult::NonModule(path_res) => path_res.expect_full_res(),
3613 PathResult::Module(ModuleOrUniformRoot::Module(module)) => {
3614 module.res().unwrap()
3616 _ => return Ok(Some(result)),
3619 if res == unqualified_result {
3620 let lint = lint::builtin::UNUSED_QUALIFICATIONS;
3621 self.r.lint_buffer.buffer_lint(
3625 "unnecessary qualification",
3633 fn with_resolved_label(&mut self, label: Option<Label>, id: NodeId, f: impl FnOnce(&mut Self)) {
3634 if let Some(label) = label {
3635 if label.ident.as_str().as_bytes()[1] != b'_' {
3636 self.diagnostic_metadata.unused_labels.insert(id, label.ident.span);
3639 if let Ok((_, orig_span)) = self.resolve_label(label.ident) {
3640 diagnostics::signal_label_shadowing(self.r.session, orig_span, label.ident)
3643 self.with_label_rib(NormalRibKind, |this| {
3644 let ident = label.ident.normalize_to_macro_rules();
3645 this.label_ribs.last_mut().unwrap().bindings.insert(ident, id);
3653 fn resolve_labeled_block(&mut self, label: Option<Label>, id: NodeId, block: &'ast Block) {
3654 self.with_resolved_label(label, id, |this| this.visit_block(block));
3657 fn resolve_block(&mut self, block: &'ast Block) {
3658 debug!("(resolving block) entering block");
3659 // Move down in the graph, if there's an anonymous module rooted here.
3660 let orig_module = self.parent_scope.module;
3661 let anonymous_module = self.r.block_map.get(&block.id).cloned(); // clones a reference
3663 let mut num_macro_definition_ribs = 0;
3664 if let Some(anonymous_module) = anonymous_module {
3665 debug!("(resolving block) found anonymous module, moving down");
3666 self.ribs[ValueNS].push(Rib::new(ModuleRibKind(anonymous_module)));
3667 self.ribs[TypeNS].push(Rib::new(ModuleRibKind(anonymous_module)));
3668 self.parent_scope.module = anonymous_module;
3670 self.ribs[ValueNS].push(Rib::new(NormalRibKind));
3673 let prev = self.diagnostic_metadata.current_block_could_be_bare_struct_literal.take();
3674 if let (true, [Stmt { kind: StmtKind::Expr(expr), .. }]) =
3675 (block.could_be_bare_literal, &block.stmts[..])
3676 && let ExprKind::Type(..) = expr.kind
3678 self.diagnostic_metadata.current_block_could_be_bare_struct_literal =
3681 // Descend into the block.
3682 for stmt in &block.stmts {
3683 if let StmtKind::Item(ref item) = stmt.kind
3684 && let ItemKind::MacroDef(..) = item.kind {
3685 num_macro_definition_ribs += 1;
3686 let res = self.r.local_def_id(item.id).to_def_id();
3687 self.ribs[ValueNS].push(Rib::new(MacroDefinition(res)));
3688 self.label_ribs.push(Rib::new(MacroDefinition(res)));
3691 self.visit_stmt(stmt);
3693 self.diagnostic_metadata.current_block_could_be_bare_struct_literal = prev;
3696 self.parent_scope.module = orig_module;
3697 for _ in 0..num_macro_definition_ribs {
3698 self.ribs[ValueNS].pop();
3699 self.label_ribs.pop();
3701 self.ribs[ValueNS].pop();
3702 if anonymous_module.is_some() {
3703 self.ribs[TypeNS].pop();
3705 debug!("(resolving block) leaving block");
3708 fn resolve_anon_const(&mut self, constant: &'ast AnonConst, is_repeat: IsRepeatExpr) {
3709 debug!("resolve_anon_const {:?} is_repeat: {:?}", constant, is_repeat);
3710 self.with_constant_rib(
3712 if constant.value.is_potential_trivial_const_param() {
3713 ConstantHasGenerics::Yes
3715 ConstantHasGenerics::No
3718 |this| visit::walk_anon_const(this, constant),
3722 fn resolve_inline_const(&mut self, constant: &'ast AnonConst) {
3723 debug!("resolve_anon_const {constant:?}");
3724 self.with_constant_rib(IsRepeatExpr::No, ConstantHasGenerics::Yes, None, |this| {
3725 visit::walk_anon_const(this, constant)
3729 fn resolve_expr(&mut self, expr: &'ast Expr, parent: Option<&'ast Expr>) {
3730 // First, record candidate traits for this expression if it could
3731 // result in the invocation of a method call.
3733 self.record_candidate_traits_for_expr_if_necessary(expr);
3735 // Next, resolve the node.
3737 ExprKind::Path(ref qself, ref path) => {
3738 self.smart_resolve_path(expr.id, qself.as_ref(), path, PathSource::Expr(parent));
3739 visit::walk_expr(self, expr);
3742 ExprKind::Struct(ref se) => {
3743 self.smart_resolve_path(expr.id, se.qself.as_ref(), &se.path, PathSource::Struct);
3744 visit::walk_expr(self, expr);
3747 ExprKind::Break(Some(label), _) | ExprKind::Continue(Some(label)) => {
3748 match self.resolve_label(label.ident) {
3749 Ok((node_id, _)) => {
3750 // Since this res is a label, it is never read.
3751 self.r.label_res_map.insert(expr.id, node_id);
3752 self.diagnostic_metadata.unused_labels.remove(&node_id);
3755 self.report_error(label.ident.span, error);
3759 // visit `break` argument if any
3760 visit::walk_expr(self, expr);
3763 ExprKind::Break(None, Some(ref e)) => {
3764 // We use this instead of `visit::walk_expr` to keep the parent expr around for
3765 // better diagnostics.
3766 self.resolve_expr(e, Some(&expr));
3769 ExprKind::Let(ref pat, ref scrutinee, _) => {
3770 self.visit_expr(scrutinee);
3771 self.resolve_pattern_top(pat, PatternSource::Let);
3774 ExprKind::If(ref cond, ref then, ref opt_else) => {
3775 self.with_rib(ValueNS, NormalRibKind, |this| {
3776 let old = this.diagnostic_metadata.in_if_condition.replace(cond);
3777 this.visit_expr(cond);
3778 this.diagnostic_metadata.in_if_condition = old;
3779 this.visit_block(then);
3781 if let Some(expr) = opt_else {
3782 self.visit_expr(expr);
3786 ExprKind::Loop(ref block, label) => self.resolve_labeled_block(label, expr.id, &block),
3788 ExprKind::While(ref cond, ref block, label) => {
3789 self.with_resolved_label(label, expr.id, |this| {
3790 this.with_rib(ValueNS, NormalRibKind, |this| {
3791 let old = this.diagnostic_metadata.in_if_condition.replace(cond);
3792 this.visit_expr(cond);
3793 this.diagnostic_metadata.in_if_condition = old;
3794 this.visit_block(block);
3799 ExprKind::ForLoop(ref pat, ref iter_expr, ref block, label) => {
3800 self.visit_expr(iter_expr);
3801 self.with_rib(ValueNS, NormalRibKind, |this| {
3802 this.resolve_pattern_top(pat, PatternSource::For);
3803 this.resolve_labeled_block(label, expr.id, block);
3807 ExprKind::Block(ref block, label) => self.resolve_labeled_block(label, block.id, block),
3809 // Equivalent to `visit::walk_expr` + passing some context to children.
3810 ExprKind::Field(ref subexpression, _) => {
3811 self.resolve_expr(subexpression, Some(expr));
3813 ExprKind::MethodCall(ref segment, ref receiver, ref arguments, _) => {
3814 self.resolve_expr(receiver, Some(expr));
3815 for argument in arguments {
3816 self.resolve_expr(argument, None);
3818 self.visit_path_segment(segment);
3821 ExprKind::Call(ref callee, ref arguments) => {
3822 self.resolve_expr(callee, Some(expr));
3823 let const_args = self.r.legacy_const_generic_args(callee).unwrap_or_default();
3824 for (idx, argument) in arguments.iter().enumerate() {
3825 // Constant arguments need to be treated as AnonConst since
3826 // that is how they will be later lowered to HIR.
3827 if const_args.contains(&idx) {
3828 self.with_constant_rib(
3830 if argument.is_potential_trivial_const_param() {
3831 ConstantHasGenerics::Yes
3833 ConstantHasGenerics::No
3837 this.resolve_expr(argument, None);
3841 self.resolve_expr(argument, None);
3845 ExprKind::Type(ref type_expr, ref ty) => {
3846 // `ParseSess::type_ascription_path_suggestions` keeps spans of colon tokens in
3847 // type ascription. Here we are trying to retrieve the span of the colon token as
3848 // well, but only if it's written without spaces `expr:Ty` and therefore confusable
3849 // with `expr::Ty`, only in this case it will match the span from
3850 // `type_ascription_path_suggestions`.
3851 self.diagnostic_metadata
3852 .current_type_ascription
3853 .push(type_expr.span.between(ty.span));
3854 visit::walk_expr(self, expr);
3855 self.diagnostic_metadata.current_type_ascription.pop();
3857 // `async |x| ...` gets desugared to `|x| future_from_generator(|| ...)`, so we need to
3858 // resolve the arguments within the proper scopes so that usages of them inside the
3859 // closure are detected as upvars rather than normal closure arg usages.
3860 ExprKind::Closure(_, _, Async::Yes { .. }, _, ref fn_decl, ref body, _span) => {
3861 self.with_rib(ValueNS, NormalRibKind, |this| {
3862 this.with_label_rib(ClosureOrAsyncRibKind, |this| {
3863 // Resolve arguments:
3864 this.resolve_params(&fn_decl.inputs);
3865 // No need to resolve return type --
3866 // the outer closure return type is `FnRetTy::Default`.
3868 // Now resolve the inner closure
3870 // No need to resolve arguments: the inner closure has none.
3871 // Resolve the return type:
3872 visit::walk_fn_ret_ty(this, &fn_decl.output);
3874 this.visit_expr(body);
3879 // For closures, ClosureOrAsyncRibKind is added in visit_fn
3880 ExprKind::Closure(ClosureBinder::For { ref generic_params, span }, ..) => {
3881 self.with_generic_param_rib(
3884 LifetimeRibKind::Generics {
3886 kind: LifetimeBinderKind::Closure,
3889 |this| visit::walk_expr(this, expr),
3892 ExprKind::Closure(..) => visit::walk_expr(self, expr),
3893 ExprKind::Async(..) => {
3894 self.with_label_rib(ClosureOrAsyncRibKind, |this| visit::walk_expr(this, expr));
3896 ExprKind::Repeat(ref elem, ref ct) => {
3897 self.visit_expr(elem);
3898 self.with_lifetime_rib(LifetimeRibKind::AnonConst, |this| {
3899 this.with_lifetime_rib(LifetimeRibKind::Elided(LifetimeRes::Static), |this| {
3900 this.resolve_anon_const(ct, IsRepeatExpr::Yes)
3904 ExprKind::ConstBlock(ref ct) => {
3905 self.resolve_inline_const(ct);
3907 ExprKind::Index(ref elem, ref idx) => {
3908 self.resolve_expr(elem, Some(expr));
3909 self.visit_expr(idx);
3911 ExprKind::Assign(..) => {
3912 let old = self.diagnostic_metadata.in_assignment.replace(expr);
3913 visit::walk_expr(self, expr);
3914 self.diagnostic_metadata.in_assignment = old;
3917 visit::walk_expr(self, expr);
3922 fn record_candidate_traits_for_expr_if_necessary(&mut self, expr: &'ast Expr) {
3924 ExprKind::Field(_, ident) => {
3925 // FIXME(#6890): Even though you can't treat a method like a
3926 // field, we need to add any trait methods we find that match
3927 // the field name so that we can do some nice error reporting
3928 // later on in typeck.
3929 let traits = self.traits_in_scope(ident, ValueNS);
3930 self.r.trait_map.insert(expr.id, traits);
3932 ExprKind::MethodCall(ref segment, ..) => {
3933 debug!("(recording candidate traits for expr) recording traits for {}", expr.id);
3934 let traits = self.traits_in_scope(segment.ident, ValueNS);
3935 self.r.trait_map.insert(expr.id, traits);
3943 fn traits_in_scope(&mut self, ident: Ident, ns: Namespace) -> Vec<TraitCandidate> {
3944 self.r.traits_in_scope(
3945 self.current_trait_ref.as_ref().map(|(module, _)| *module),
3948 Some((ident.name, ns)),
3952 /// Construct the list of in-scope lifetime parameters for async lowering.
3953 /// We include all lifetime parameters, either named or "Fresh".
3954 /// The order of those parameters does not matter, as long as it is
3956 fn record_lifetime_params_for_async(
3959 async_node_id: Option<(NodeId, Span)>,
3961 if let Some((async_node_id, span)) = async_node_id {
3962 let mut extra_lifetime_params =
3963 self.r.extra_lifetime_params_map.get(&fn_id).cloned().unwrap_or_default();
3964 for rib in self.lifetime_ribs.iter().rev() {
3965 extra_lifetime_params.extend(
3966 rib.bindings.iter().map(|(&ident, &(node_id, res))| (ident, node_id, res)),
3969 LifetimeRibKind::Item => break,
3970 LifetimeRibKind::AnonymousCreateParameter { binder, .. } => {
3971 if let Some(earlier_fresh) = self.r.extra_lifetime_params_map.get(&binder) {
3972 extra_lifetime_params.extend(earlier_fresh);
3975 LifetimeRibKind::Generics { .. } => {}
3977 // We are in a function definition. We should only find `Generics`
3978 // and `AnonymousCreateParameter` inside the innermost `Item`.
3979 span_bug!(span, "unexpected rib kind: {:?}", rib.kind)
3983 self.r.extra_lifetime_params_map.insert(async_node_id, extra_lifetime_params);
3988 struct LifetimeCountVisitor<'a, 'b> {
3989 r: &'b mut Resolver<'a>,
3992 /// Walks the whole crate in DFS order, visiting each item, counting the declared number of
3993 /// lifetime generic parameters.
3994 impl<'ast> Visitor<'ast> for LifetimeCountVisitor<'_, '_> {
3995 fn visit_item(&mut self, item: &'ast Item) {
3997 ItemKind::TyAlias(box TyAlias { ref generics, .. })
3998 | ItemKind::Fn(box Fn { ref generics, .. })
3999 | ItemKind::Enum(_, ref generics)
4000 | ItemKind::Struct(_, ref generics)
4001 | ItemKind::Union(_, ref generics)
4002 | ItemKind::Impl(box Impl { ref generics, .. })
4003 | ItemKind::Trait(box Trait { ref generics, .. })
4004 | ItemKind::TraitAlias(ref generics, _) => {
4005 let def_id = self.r.local_def_id(item.id);
4006 let count = generics
4009 .filter(|param| matches!(param.kind, ast::GenericParamKind::Lifetime { .. }))
4011 self.r.item_generics_num_lifetimes.insert(def_id, count);
4015 | ItemKind::ForeignMod(..)
4016 | ItemKind::Static(..)
4017 | ItemKind::Const(..)
4019 | ItemKind::ExternCrate(..)
4020 | ItemKind::MacroDef(..)
4021 | ItemKind::GlobalAsm(..)
4022 | ItemKind::MacCall(..) => {}
4024 visit::walk_item(self, item)
4028 impl<'a> Resolver<'a> {
4029 pub(crate) fn late_resolve_crate(&mut self, krate: &Crate) {
4030 visit::walk_crate(&mut LifetimeCountVisitor { r: self }, krate);
4031 let mut late_resolution_visitor = LateResolutionVisitor::new(self);
4032 visit::walk_crate(&mut late_resolution_visitor, krate);
4033 for (id, span) in late_resolution_visitor.diagnostic_metadata.unused_labels.iter() {
4034 self.lint_buffer.buffer_lint(lint::builtin::UNUSED_LABELS, *id, *span, "unused label");