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::{DiagnosticArgValue, DiagnosticId, IntoDiagnosticArg};
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::assert_matches::debug_assert_matches;
35 use std::collections::{hash_map::Entry, BTreeSet};
36 use std::mem::{replace, swap, take};
40 type Res = def::Res<NodeId>;
42 type IdentMap<T> = FxHashMap<Ident, T>;
44 /// Map from the name in a pattern to its binding mode.
45 type BindingMap = IdentMap<BindingInfo>;
48 ElisionFnParameter, LifetimeElisionCandidate, MissingLifetime, MissingLifetimeKind,
51 #[derive(Copy, Clone, Debug)]
54 annotation: BindingAnnotation,
57 #[derive(Copy, Clone, PartialEq, Eq, Debug)]
58 pub enum PatternSource {
65 #[derive(Copy, Clone, Debug, PartialEq, Eq)]
72 pub fn descr(self) -> &'static str {
74 PatternSource::Match => "match binding",
75 PatternSource::Let => "let binding",
76 PatternSource::For => "for binding",
77 PatternSource::FnParam => "function parameter",
82 impl IntoDiagnosticArg for PatternSource {
83 fn into_diagnostic_arg(self) -> DiagnosticArgValue<'static> {
84 DiagnosticArgValue::Str(Cow::Borrowed(self.descr()))
88 /// Denotes whether the context for the set of already bound bindings is a `Product`
89 /// or `Or` context. This is used in e.g., `fresh_binding` and `resolve_pattern_inner`.
90 /// See those functions for more information.
93 /// A product pattern context, e.g., `Variant(a, b)`.
95 /// An or-pattern context, e.g., `p_0 | ... | p_n`.
99 /// Does this the item (from the item rib scope) allow generic parameters?
100 #[derive(Copy, Clone, Debug)]
101 pub(crate) enum HasGenericParams {
106 /// May this constant have generics?
107 #[derive(Copy, Clone, Debug, Eq, PartialEq)]
108 pub(crate) enum ConstantHasGenerics {
113 impl ConstantHasGenerics {
114 fn force_yes_if(self, b: bool) -> Self {
115 if b { Self::Yes } else { self }
119 #[derive(Copy, Clone, Debug, Eq, PartialEq)]
120 pub(crate) enum ConstantItemKind {
125 /// The rib kind restricts certain accesses,
126 /// e.g. to a `Res::Local` of an outer item.
127 #[derive(Copy, Clone, Debug)]
128 pub(crate) enum RibKind<'a> {
129 /// No restriction needs to be applied.
132 /// We passed through an impl or trait and are now in one of its
133 /// methods or associated types. Allow references to ty params that impl or trait
134 /// binds. Disallow any other upvars (including other ty params that are
138 /// We passed through a closure. Disallow labels.
139 ClosureOrAsyncRibKind,
141 /// We passed through an item scope. Disallow upvars.
142 ItemRibKind(HasGenericParams),
144 /// We're in a constant item. Can't refer to dynamic stuff.
146 /// The item may reference generic parameters in trivial constant expressions.
147 /// All other constants aren't allowed to use generic params at all.
148 ConstantItemRibKind(ConstantHasGenerics, Option<(Ident, ConstantItemKind)>),
150 /// We passed through a module.
151 ModuleRibKind(Module<'a>),
153 /// We passed through a `macro_rules!` statement
154 MacroDefinition(DefId),
156 /// All bindings in this rib are generic parameters that can't be used
157 /// from the default of a generic parameter because they're not declared
158 /// before said generic parameter. Also see the `visit_generics` override.
159 ForwardGenericParamBanRibKind,
161 /// We are inside of the type of a const parameter. Can't refer to any
165 /// We are inside a `sym` inline assembly operand. Can only refer to
171 /// Whether this rib kind contains generic parameters, as opposed to local
173 pub(crate) fn contains_params(&self) -> bool {
176 | ClosureOrAsyncRibKind
177 | ConstantItemRibKind(..)
180 | ConstParamTyRibKind
181 | InlineAsmSymRibKind => false,
182 AssocItemRibKind | ItemRibKind(_) | ForwardGenericParamBanRibKind => true,
186 /// This rib forbids referring to labels defined in upwards ribs.
187 fn is_label_barrier(self) -> bool {
189 NormalRibKind | MacroDefinition(..) => false,
192 | ClosureOrAsyncRibKind
194 | ConstantItemRibKind(..)
196 | ForwardGenericParamBanRibKind
197 | ConstParamTyRibKind
198 | InlineAsmSymRibKind => true,
203 /// A single local scope.
205 /// A rib represents a scope names can live in. Note that these appear in many places, not just
206 /// around braces. At any place where the list of accessible names (of the given namespace)
207 /// changes or a new restrictions on the name accessibility are introduced, a new rib is put onto a
208 /// stack. This may be, for example, a `let` statement (because it introduces variables), a macro,
211 /// Different [rib kinds](enum@RibKind) are transparent for different names.
213 /// The resolution keeps a separate stack of ribs as it traverses the AST for each namespace. When
214 /// resolving, the name is looked up from inside out.
216 pub(crate) struct Rib<'a, R = Res> {
217 pub bindings: IdentMap<R>,
218 pub kind: RibKind<'a>,
221 impl<'a, R> Rib<'a, R> {
222 fn new(kind: RibKind<'a>) -> Rib<'a, R> {
223 Rib { bindings: Default::default(), kind }
227 #[derive(Clone, Copy, Debug)]
228 enum LifetimeUseSet {
229 One { use_span: Span, use_ctxt: visit::LifetimeCtxt },
233 #[derive(Copy, Clone, Debug)]
234 enum LifetimeRibKind {
235 // -- Ribs introducing named lifetimes
237 /// This rib declares generic parameters.
238 /// Only for this kind the `LifetimeRib::bindings` field can be non-empty.
239 Generics { binder: NodeId, span: Span, kind: LifetimeBinderKind },
241 // -- Ribs introducing unnamed lifetimes
243 /// Create a new anonymous lifetime parameter and reference it.
245 /// If `report_in_path`, report an error when encountering lifetime elision in a path:
247 /// struct Foo<'a> { x: &'a () }
248 /// async fn foo(x: Foo) {}
251 /// Note: the error should not trigger when the elided lifetime is in a pattern or
252 /// expression-position path:
254 /// struct Foo<'a> { x: &'a () }
255 /// async fn foo(Foo { x: _ }: Foo<'_>) {}
257 AnonymousCreateParameter { binder: NodeId, report_in_path: bool },
259 /// Replace all anonymous lifetimes by provided lifetime.
262 // -- Barrier ribs that stop lifetime lookup, or continue it but produce an error later.
264 /// Give a hard error when either `&` or `'_` is written. Used to
265 /// rule out things like `where T: Foo<'_>`. Does not imply an
266 /// error on default object bounds (e.g., `Box<dyn Foo>`).
267 AnonymousReportError,
269 /// Signal we cannot find which should be the anonymous lifetime.
272 /// FIXME(const_generics): This patches over an ICE caused by non-'static lifetimes in const
273 /// generics. We are disallowing this until we can decide on how we want to handle non-'static
274 /// lifetimes in const generics. See issue #74052 for discussion.
277 /// Non-static lifetimes are prohibited in anonymous constants under `min_const_generics`.
278 /// This function will emit an error if `generic_const_exprs` is not enabled, the body
279 /// identified by `body_id` is an anonymous constant and `lifetime_ref` is non-static.
282 /// This rib acts as a barrier to forbid reference to lifetimes of a parent item.
286 #[derive(Copy, Clone, Debug)]
287 enum LifetimeBinderKind {
297 impl LifetimeBinderKind {
298 fn descr(self) -> &'static str {
299 use LifetimeBinderKind::*;
301 BareFnType => "type",
302 PolyTrait => "bound",
303 WhereBound => "bound",
305 ImplBlock => "impl block",
306 Function => "function",
307 Closure => "closure",
314 kind: LifetimeRibKind,
315 // We need to preserve insertion order for async fns.
316 bindings: FxIndexMap<Ident, (NodeId, LifetimeRes)>,
320 fn new(kind: LifetimeRibKind) -> LifetimeRib {
321 LifetimeRib { bindings: Default::default(), kind }
325 #[derive(Copy, Clone, PartialEq, Eq, Debug)]
326 pub(crate) enum AliasPossibility {
331 #[derive(Copy, Clone, Debug)]
332 pub(crate) enum PathSource<'a> {
333 // Type paths `Path`.
335 // Trait paths in bounds or impls.
336 Trait(AliasPossibility),
337 // Expression paths `path`, with optional parent context.
338 Expr(Option<&'a Expr>),
339 // Paths in path patterns `Path`.
341 // Paths in struct expressions and patterns `Path { .. }`.
343 // Paths in tuple struct patterns `Path(..)`.
344 TupleStruct(Span, &'a [Span]),
345 // `m::A::B` in `<T as m::A>::B::C`.
346 TraitItem(Namespace),
349 impl<'a> PathSource<'a> {
350 fn namespace(self) -> Namespace {
352 PathSource::Type | PathSource::Trait(_) | PathSource::Struct => TypeNS,
353 PathSource::Expr(..) | PathSource::Pat | PathSource::TupleStruct(..) => ValueNS,
354 PathSource::TraitItem(ns) => ns,
358 fn defer_to_typeck(self) -> bool {
361 | PathSource::Expr(..)
364 | PathSource::TupleStruct(..) => true,
365 PathSource::Trait(_) | PathSource::TraitItem(..) => false,
369 fn descr_expected(self) -> &'static str {
371 PathSource::Type => "type",
372 PathSource::Trait(_) => "trait",
373 PathSource::Pat => "unit struct, unit variant or constant",
374 PathSource::Struct => "struct, variant or union type",
375 PathSource::TupleStruct(..) => "tuple struct or tuple variant",
376 PathSource::TraitItem(ns) => match ns {
377 TypeNS => "associated type",
378 ValueNS => "method or associated constant",
379 MacroNS => bug!("associated macro"),
381 PathSource::Expr(parent) => match parent.as_ref().map(|p| &p.kind) {
382 // "function" here means "anything callable" rather than `DefKind::Fn`,
383 // this is not precise but usually more helpful than just "value".
384 Some(ExprKind::Call(call_expr, _)) => match &call_expr.kind {
385 // the case of `::some_crate()`
386 ExprKind::Path(_, path)
387 if path.segments.len() == 2
388 && path.segments[0].ident.name == kw::PathRoot =>
392 ExprKind::Path(_, path) => {
393 let mut msg = "function";
394 if let Some(segment) = path.segments.iter().last() {
395 if let Some(c) = segment.ident.to_string().chars().next() {
396 if c.is_uppercase() {
397 msg = "function, tuple struct or tuple variant";
410 fn is_call(self) -> bool {
411 matches!(self, PathSource::Expr(Some(&Expr { kind: ExprKind::Call(..), .. })))
414 pub(crate) fn is_expected(self, res: Res) -> bool {
416 PathSource::Type => matches!(
423 | DefKind::TraitAlias
428 | DefKind::ForeignTy,
431 | Res::SelfTyParam { .. }
432 | Res::SelfTyAlias { .. }
434 PathSource::Trait(AliasPossibility::No) => matches!(res, Res::Def(DefKind::Trait, _)),
435 PathSource::Trait(AliasPossibility::Maybe) => {
436 matches!(res, Res::Def(DefKind::Trait | DefKind::TraitAlias, _))
438 PathSource::Expr(..) => matches!(
441 DefKind::Ctor(_, CtorKind::Const | CtorKind::Fn)
446 | DefKind::AssocConst
447 | DefKind::ConstParam,
453 res.expected_in_unit_struct_pat()
454 || matches!(res, Res::Def(DefKind::Const | DefKind::AssocConst, _))
456 PathSource::TupleStruct(..) => res.expected_in_tuple_struct_pat(),
457 PathSource::Struct => matches!(
466 ) | Res::SelfTyParam { .. }
467 | Res::SelfTyAlias { .. }
469 PathSource::TraitItem(ns) => match res {
470 Res::Def(DefKind::AssocConst | DefKind::AssocFn, _) if ns == ValueNS => true,
471 Res::Def(DefKind::AssocTy, _) if ns == TypeNS => true,
477 fn error_code(self, has_unexpected_resolution: bool) -> DiagnosticId {
478 use rustc_errors::error_code;
479 match (self, has_unexpected_resolution) {
480 (PathSource::Trait(_), true) => error_code!(E0404),
481 (PathSource::Trait(_), false) => error_code!(E0405),
482 (PathSource::Type, true) => error_code!(E0573),
483 (PathSource::Type, false) => error_code!(E0412),
484 (PathSource::Struct, true) => error_code!(E0574),
485 (PathSource::Struct, false) => error_code!(E0422),
486 (PathSource::Expr(..), true) => error_code!(E0423),
487 (PathSource::Expr(..), false) => error_code!(E0425),
488 (PathSource::Pat | PathSource::TupleStruct(..), true) => error_code!(E0532),
489 (PathSource::Pat | PathSource::TupleStruct(..), false) => error_code!(E0531),
490 (PathSource::TraitItem(..), true) => error_code!(E0575),
491 (PathSource::TraitItem(..), false) => error_code!(E0576),
497 struct DiagnosticMetadata<'ast> {
498 /// The current trait's associated items' ident, used for diagnostic suggestions.
499 current_trait_assoc_items: Option<&'ast [P<AssocItem>]>,
501 /// The current self type if inside an impl (used for better errors).
502 current_self_type: Option<Ty>,
504 /// The current self item if inside an ADT (used for better errors).
505 current_self_item: Option<NodeId>,
507 /// The current trait (used to suggest).
508 current_item: Option<&'ast Item>,
510 /// When processing generics and encountering a type not found, suggest introducing a type
512 currently_processing_generics: bool,
514 /// The current enclosing (non-closure) function (used for better errors).
515 current_function: Option<(FnKind<'ast>, Span)>,
517 /// A list of labels as of yet unused. Labels will be removed from this map when
518 /// they are used (in a `break` or `continue` statement)
519 unused_labels: FxHashMap<NodeId, Span>,
521 /// Only used for better errors on `fn(): fn()`.
522 current_type_ascription: Vec<Span>,
524 /// Only used for better errors on `let x = { foo: bar };`.
525 /// In the case of a parse error with `let x = { foo: bar, };`, this isn't needed, it's only
526 /// needed for cases where this parses as a correct type ascription.
527 current_block_could_be_bare_struct_literal: Option<Span>,
529 /// Only used for better errors on `let <pat>: <expr, not type>;`.
530 current_let_binding: Option<(Span, Option<Span>, Option<Span>)>,
532 /// Used to detect possible `if let` written without `let` and to provide structured suggestion.
533 in_if_condition: Option<&'ast Expr>,
535 /// Used to detect possible new binding written without `let` and to provide structured suggestion.
536 in_assignment: Option<&'ast Expr>,
539 /// If we are currently in a trait object definition. Used to point at the bounds when
540 /// encountering a struct or enum.
541 current_trait_object: Option<&'ast [ast::GenericBound]>,
543 /// Given `where <T as Bar>::Baz: String`, suggest `where T: Bar<Baz = String>`.
544 current_where_predicate: Option<&'ast WherePredicate>,
546 current_type_path: Option<&'ast Ty>,
548 /// The current impl items (used to suggest).
549 current_impl_items: Option<&'ast [P<AssocItem>]>,
551 /// When processing impl trait
552 currently_processing_impl_trait: Option<(TraitRef, Ty)>,
554 /// Accumulate the errors due to missed lifetime elision,
555 /// and report them all at once for each function.
556 current_elision_failures: Vec<MissingLifetime>,
559 struct LateResolutionVisitor<'a, 'b, 'ast> {
560 r: &'b mut Resolver<'a>,
562 /// The module that represents the current item scope.
563 parent_scope: ParentScope<'a>,
565 /// The current set of local scopes for types and values.
566 /// FIXME #4948: Reuse ribs to avoid allocation.
567 ribs: PerNS<Vec<Rib<'a>>>,
569 /// The current set of local scopes, for labels.
570 label_ribs: Vec<Rib<'a, NodeId>>,
572 /// The current set of local scopes for lifetimes.
573 lifetime_ribs: Vec<LifetimeRib>,
575 /// We are looking for lifetimes in an elision context.
576 /// The set contains all the resolutions that we encountered so far.
577 /// They will be used to determine the correct lifetime for the fn return type.
578 /// The `LifetimeElisionCandidate` is used for diagnostics, to suggest introducing named
580 lifetime_elision_candidates: Option<Vec<(LifetimeRes, LifetimeElisionCandidate)>>,
582 /// The trait that the current context can refer to.
583 current_trait_ref: Option<(Module<'a>, TraitRef)>,
585 /// Fields used to add information to diagnostic errors.
586 diagnostic_metadata: Box<DiagnosticMetadata<'ast>>,
588 /// State used to know whether to ignore resolution errors for function bodies.
590 /// In particular, rustdoc uses this to avoid giving errors for `cfg()` items.
591 /// In most cases this will be `None`, in which case errors will always be reported.
592 /// If it is `true`, then it will be updated when entering a nested function or trait body.
595 /// Count the number of places a lifetime is used.
596 lifetime_uses: FxHashMap<LocalDefId, LifetimeUseSet>,
599 /// Walks the whole crate in DFS order, visiting each item, resolving names as it goes.
600 impl<'a: 'ast, 'ast> Visitor<'ast> for LateResolutionVisitor<'a, '_, 'ast> {
601 fn visit_attribute(&mut self, _: &'ast Attribute) {
602 // We do not want to resolve expressions that appear in attributes,
603 // as they do not correspond to actual code.
605 fn visit_item(&mut self, item: &'ast Item) {
606 let prev = replace(&mut self.diagnostic_metadata.current_item, Some(item));
607 // Always report errors in items we just entered.
608 let old_ignore = replace(&mut self.in_func_body, false);
609 self.with_lifetime_rib(LifetimeRibKind::Item, |this| this.resolve_item(item));
610 self.in_func_body = old_ignore;
611 self.diagnostic_metadata.current_item = prev;
613 fn visit_arm(&mut self, arm: &'ast Arm) {
614 self.resolve_arm(arm);
616 fn visit_block(&mut self, block: &'ast Block) {
617 self.resolve_block(block);
619 fn visit_anon_const(&mut self, constant: &'ast AnonConst) {
620 // We deal with repeat expressions explicitly in `resolve_expr`.
621 self.with_lifetime_rib(LifetimeRibKind::AnonConst, |this| {
622 this.with_lifetime_rib(LifetimeRibKind::Elided(LifetimeRes::Static), |this| {
623 this.resolve_anon_const(constant, IsRepeatExpr::No);
627 fn visit_expr(&mut self, expr: &'ast Expr) {
628 self.resolve_expr(expr, None);
630 fn visit_local(&mut self, local: &'ast Local) {
631 let local_spans = match local.pat.kind {
632 // We check for this to avoid tuple struct fields.
633 PatKind::Wild => None,
636 local.ty.as_ref().map(|ty| ty.span),
637 local.kind.init().map(|init| init.span),
640 let original = replace(&mut self.diagnostic_metadata.current_let_binding, local_spans);
641 self.resolve_local(local);
642 self.diagnostic_metadata.current_let_binding = original;
644 fn visit_ty(&mut self, ty: &'ast Ty) {
645 let prev = self.diagnostic_metadata.current_trait_object;
646 let prev_ty = self.diagnostic_metadata.current_type_path;
648 TyKind::Rptr(None, _) => {
649 // Elided lifetime in reference: we resolve as if there was some lifetime `'_` with
651 // This span will be used in case of elision failure.
652 let span = self.r.session.source_map().start_point(ty.span);
653 self.resolve_elided_lifetime(ty.id, span);
654 visit::walk_ty(self, ty);
656 TyKind::Path(ref qself, ref path) => {
657 self.diagnostic_metadata.current_type_path = Some(ty);
658 self.smart_resolve_path(ty.id, &qself, path, PathSource::Type);
660 // Check whether we should interpret this as a bare trait object.
662 && let Some(partial_res) = self.r.partial_res_map.get(&ty.id)
663 && let Some(Res::Def(DefKind::Trait | DefKind::TraitAlias, _)) = partial_res.full_res()
665 // This path is actually a bare trait object. In case of a bare `Fn`-trait
666 // object with anonymous lifetimes, we need this rib to correctly place the
667 // synthetic lifetimes.
668 let span = ty.span.shrink_to_lo().to(path.span.shrink_to_lo());
669 self.with_generic_param_rib(
672 LifetimeRibKind::Generics {
674 kind: LifetimeBinderKind::PolyTrait,
677 |this| this.visit_path(&path, ty.id),
680 visit::walk_ty(self, ty)
683 TyKind::ImplicitSelf => {
684 let self_ty = Ident::with_dummy_span(kw::SelfUpper);
686 .resolve_ident_in_lexical_scope(
689 Some(Finalize::new(ty.id, ty.span)),
692 .map_or(Res::Err, |d| d.res());
693 self.r.record_partial_res(ty.id, PartialRes::new(res));
694 visit::walk_ty(self, ty)
696 TyKind::ImplTrait(..) => {
697 let candidates = self.lifetime_elision_candidates.take();
698 visit::walk_ty(self, ty);
699 self.lifetime_elision_candidates = candidates;
701 TyKind::TraitObject(ref bounds, ..) => {
702 self.diagnostic_metadata.current_trait_object = Some(&bounds[..]);
703 visit::walk_ty(self, ty)
705 TyKind::BareFn(ref bare_fn) => {
706 let span = ty.span.shrink_to_lo().to(bare_fn.decl_span.shrink_to_lo());
707 self.with_generic_param_rib(
708 &bare_fn.generic_params,
710 LifetimeRibKind::Generics {
712 kind: LifetimeBinderKind::BareFnType,
716 this.visit_generic_params(&bare_fn.generic_params, false);
717 this.with_lifetime_rib(
718 LifetimeRibKind::AnonymousCreateParameter {
720 report_in_path: false,
723 this.resolve_fn_signature(
726 // We don't need to deal with patterns in parameters, because
727 // they are not possible for foreign or bodiless functions.
732 .map(|Param { ty, .. }| (None, &**ty)),
733 &bare_fn.decl.output,
740 _ => visit::walk_ty(self, ty),
742 self.diagnostic_metadata.current_trait_object = prev;
743 self.diagnostic_metadata.current_type_path = prev_ty;
745 fn visit_poly_trait_ref(&mut self, tref: &'ast PolyTraitRef) {
746 let span = tref.span.shrink_to_lo().to(tref.trait_ref.path.span.shrink_to_lo());
747 self.with_generic_param_rib(
748 &tref.bound_generic_params,
750 LifetimeRibKind::Generics {
751 binder: tref.trait_ref.ref_id,
752 kind: LifetimeBinderKind::PolyTrait,
756 this.visit_generic_params(&tref.bound_generic_params, false);
757 this.smart_resolve_path(
758 tref.trait_ref.ref_id,
760 &tref.trait_ref.path,
761 PathSource::Trait(AliasPossibility::Maybe),
763 this.visit_trait_ref(&tref.trait_ref);
767 fn visit_foreign_item(&mut self, foreign_item: &'ast ForeignItem) {
768 match foreign_item.kind {
769 ForeignItemKind::TyAlias(box TyAlias { ref generics, .. }) => {
770 self.with_generic_param_rib(
772 ItemRibKind(HasGenericParams::Yes(generics.span)),
773 LifetimeRibKind::Generics {
774 binder: foreign_item.id,
775 kind: LifetimeBinderKind::Item,
778 |this| visit::walk_foreign_item(this, foreign_item),
781 ForeignItemKind::Fn(box Fn { ref generics, .. }) => {
782 self.with_generic_param_rib(
784 ItemRibKind(HasGenericParams::Yes(generics.span)),
785 LifetimeRibKind::Generics {
786 binder: foreign_item.id,
787 kind: LifetimeBinderKind::Function,
790 |this| visit::walk_foreign_item(this, foreign_item),
793 ForeignItemKind::Static(..) => {
794 self.with_static_rib(|this| {
795 visit::walk_foreign_item(this, foreign_item);
798 ForeignItemKind::MacCall(..) => {
799 panic!("unexpanded macro in resolve!")
803 fn visit_fn(&mut self, fn_kind: FnKind<'ast>, sp: Span, fn_id: NodeId) {
804 let previous_value = self.diagnostic_metadata.current_function;
806 // Bail if the function is foreign, and thus cannot validly have
807 // a body, or if there's no body for some other reason.
808 FnKind::Fn(FnCtxt::Foreign, _, sig, _, generics, _)
809 | FnKind::Fn(_, _, sig, _, generics, None) => {
810 self.visit_fn_header(&sig.header);
811 self.visit_generics(generics);
812 self.with_lifetime_rib(
813 LifetimeRibKind::AnonymousCreateParameter {
815 report_in_path: false,
818 this.resolve_fn_signature(
821 sig.decl.inputs.iter().map(|Param { ty, .. }| (None, &**ty)),
825 this.record_lifetime_params_for_async(
827 sig.header.asyncness.opt_return_id(),
834 self.diagnostic_metadata.current_function = Some((fn_kind, sp));
836 // Do not update `current_function` for closures: it suggests `self` parameters.
837 FnKind::Closure(..) => {}
839 debug!("(resolving function) entering function");
841 // Create a value rib for the function.
842 self.with_rib(ValueNS, ClosureOrAsyncRibKind, |this| {
843 // Create a label rib for the function.
844 this.with_label_rib(ClosureOrAsyncRibKind, |this| {
846 FnKind::Fn(_, _, sig, _, generics, body) => {
847 this.visit_generics(generics);
849 let declaration = &sig.decl;
850 let async_node_id = sig.header.asyncness.opt_return_id();
852 this.with_lifetime_rib(
853 LifetimeRibKind::AnonymousCreateParameter {
855 report_in_path: async_node_id.is_some(),
858 this.resolve_fn_signature(
860 declaration.has_self(),
864 .map(|Param { pat, ty, .. }| (Some(&**pat), &**ty)),
870 this.record_lifetime_params_for_async(fn_id, async_node_id);
872 if let Some(body) = body {
873 // Ignore errors in function bodies if this is rustdoc
874 // Be sure not to set this until the function signature has been resolved.
875 let previous_state = replace(&mut this.in_func_body, true);
876 // Resolve the function body, potentially inside the body of an async closure
877 this.with_lifetime_rib(
878 LifetimeRibKind::Elided(LifetimeRes::Infer),
879 |this| this.visit_block(body),
882 debug!("(resolving function) leaving function");
883 this.in_func_body = previous_state;
886 FnKind::Closure(binder, declaration, body) => {
887 this.visit_closure_binder(binder);
889 this.with_lifetime_rib(
891 // We do not have any explicit generic lifetime parameter.
892 ClosureBinder::NotPresent => {
893 LifetimeRibKind::AnonymousCreateParameter {
895 report_in_path: false,
898 ClosureBinder::For { .. } => LifetimeRibKind::AnonymousReportError,
900 // Add each argument to the rib.
901 |this| this.resolve_params(&declaration.inputs),
903 this.with_lifetime_rib(
905 ClosureBinder::NotPresent => {
906 LifetimeRibKind::Elided(LifetimeRes::Infer)
908 ClosureBinder::For { .. } => LifetimeRibKind::AnonymousReportError,
910 |this| visit::walk_fn_ret_ty(this, &declaration.output),
913 // Ignore errors in function bodies if this is rustdoc
914 // Be sure not to set this until the function signature has been resolved.
915 let previous_state = replace(&mut this.in_func_body, true);
916 // Resolve the function body, potentially inside the body of an async closure
917 this.with_lifetime_rib(
918 LifetimeRibKind::Elided(LifetimeRes::Infer),
919 |this| this.visit_expr(body),
922 debug!("(resolving function) leaving function");
923 this.in_func_body = previous_state;
928 self.diagnostic_metadata.current_function = previous_value;
930 fn visit_lifetime(&mut self, lifetime: &'ast Lifetime, use_ctxt: visit::LifetimeCtxt) {
931 self.resolve_lifetime(lifetime, use_ctxt)
934 fn visit_generics(&mut self, generics: &'ast Generics) {
935 self.visit_generic_params(
937 self.diagnostic_metadata.current_self_item.is_some(),
939 for p in &generics.where_clause.predicates {
940 self.visit_where_predicate(p);
944 fn visit_closure_binder(&mut self, b: &'ast ClosureBinder) {
946 ClosureBinder::NotPresent => {}
947 ClosureBinder::For { generic_params, .. } => {
948 self.visit_generic_params(
950 self.diagnostic_metadata.current_self_item.is_some(),
956 fn visit_generic_arg(&mut self, arg: &'ast GenericArg) {
957 debug!("visit_generic_arg({:?})", arg);
958 let prev = replace(&mut self.diagnostic_metadata.currently_processing_generics, true);
960 GenericArg::Type(ref ty) => {
961 // We parse const arguments as path types as we cannot distinguish them during
962 // parsing. We try to resolve that ambiguity by attempting resolution the type
963 // namespace first, and if that fails we try again in the value namespace. If
964 // resolution in the value namespace succeeds, we have an generic const argument on
966 if let TyKind::Path(ref qself, ref path) = ty.kind {
967 // We cannot disambiguate multi-segment paths right now as that requires type
969 if path.segments.len() == 1 && path.segments[0].args.is_none() {
970 let mut check_ns = |ns| {
971 self.maybe_resolve_ident_in_lexical_scope(path.segments[0].ident, ns)
974 if !check_ns(TypeNS) && check_ns(ValueNS) {
975 // This must be equivalent to `visit_anon_const`, but we cannot call it
976 // directly due to visitor lifetimes so we have to copy-paste some code.
978 // Note that we might not be inside of an repeat expression here,
979 // but considering that `IsRepeatExpr` is only relevant for
980 // non-trivial constants this is doesn't matter.
981 self.with_constant_rib(
983 ConstantHasGenerics::Yes,
986 this.smart_resolve_path(
990 PathSource::Expr(None),
993 if let Some(ref qself) = *qself {
994 this.visit_ty(&qself.ty);
996 this.visit_path(path, ty.id);
1000 self.diagnostic_metadata.currently_processing_generics = prev;
1008 GenericArg::Lifetime(lt) => self.visit_lifetime(lt, visit::LifetimeCtxt::GenericArg),
1009 GenericArg::Const(ct) => self.visit_anon_const(ct),
1011 self.diagnostic_metadata.currently_processing_generics = prev;
1014 fn visit_assoc_constraint(&mut self, constraint: &'ast AssocConstraint) {
1015 self.visit_ident(constraint.ident);
1016 if let Some(ref gen_args) = constraint.gen_args {
1017 // Forbid anonymous lifetimes in GAT parameters until proper semantics are decided.
1018 self.with_lifetime_rib(LifetimeRibKind::AnonymousReportError, |this| {
1019 this.visit_generic_args(gen_args)
1022 match constraint.kind {
1023 AssocConstraintKind::Equality { ref term } => match term {
1024 Term::Ty(ty) => self.visit_ty(ty),
1025 Term::Const(c) => self.visit_anon_const(c),
1027 AssocConstraintKind::Bound { ref bounds } => {
1028 walk_list!(self, visit_param_bound, bounds, BoundKind::Bound);
1033 fn visit_path_segment(&mut self, path_segment: &'ast PathSegment) {
1034 if let Some(ref args) = path_segment.args {
1036 GenericArgs::AngleBracketed(..) => visit::walk_generic_args(self, args),
1037 GenericArgs::Parenthesized(p_args) => {
1038 // Probe the lifetime ribs to know how to behave.
1039 for rib in self.lifetime_ribs.iter().rev() {
1041 // We are inside a `PolyTraitRef`. The lifetimes are
1042 // to be intoduced in that (maybe implicit) `for<>` binder.
1043 LifetimeRibKind::Generics {
1045 kind: LifetimeBinderKind::PolyTrait,
1048 self.with_lifetime_rib(
1049 LifetimeRibKind::AnonymousCreateParameter {
1051 report_in_path: false,
1054 this.resolve_fn_signature(
1057 p_args.inputs.iter().map(|ty| (None, &**ty)),
1064 // We have nowhere to introduce generics. Code is malformed,
1065 // so use regular lifetime resolution to avoid spurious errors.
1066 LifetimeRibKind::Item | LifetimeRibKind::Generics { .. } => {
1067 visit::walk_generic_args(self, args);
1070 LifetimeRibKind::AnonymousCreateParameter { .. }
1071 | LifetimeRibKind::AnonymousReportError
1072 | LifetimeRibKind::Elided(_)
1073 | LifetimeRibKind::ElisionFailure
1074 | LifetimeRibKind::AnonConst
1075 | LifetimeRibKind::ConstGeneric => {}
1083 fn visit_where_predicate(&mut self, p: &'ast WherePredicate) {
1084 debug!("visit_where_predicate {:?}", p);
1085 let previous_value =
1086 replace(&mut self.diagnostic_metadata.current_where_predicate, Some(p));
1087 self.with_lifetime_rib(LifetimeRibKind::AnonymousReportError, |this| {
1088 if let WherePredicate::BoundPredicate(WhereBoundPredicate {
1091 ref bound_generic_params,
1092 span: predicate_span,
1096 let span = predicate_span.shrink_to_lo().to(bounded_ty.span.shrink_to_lo());
1097 this.with_generic_param_rib(
1098 &bound_generic_params,
1100 LifetimeRibKind::Generics {
1101 binder: bounded_ty.id,
1102 kind: LifetimeBinderKind::WhereBound,
1106 this.visit_generic_params(&bound_generic_params, false);
1107 this.visit_ty(bounded_ty);
1108 for bound in bounds {
1109 this.visit_param_bound(bound, BoundKind::Bound)
1114 visit::walk_where_predicate(this, p);
1117 self.diagnostic_metadata.current_where_predicate = previous_value;
1120 fn visit_inline_asm(&mut self, asm: &'ast InlineAsm) {
1121 for (op, _) in &asm.operands {
1123 InlineAsmOperand::In { expr, .. }
1124 | InlineAsmOperand::Out { expr: Some(expr), .. }
1125 | InlineAsmOperand::InOut { expr, .. } => self.visit_expr(expr),
1126 InlineAsmOperand::Out { expr: None, .. } => {}
1127 InlineAsmOperand::SplitInOut { in_expr, out_expr, .. } => {
1128 self.visit_expr(in_expr);
1129 if let Some(out_expr) = out_expr {
1130 self.visit_expr(out_expr);
1133 InlineAsmOperand::Const { anon_const, .. } => {
1134 // Although this is `DefKind::AnonConst`, it is allowed to reference outer
1135 // generic parameters like an inline const.
1136 self.resolve_inline_const(anon_const);
1138 InlineAsmOperand::Sym { sym } => self.visit_inline_asm_sym(sym),
1143 fn visit_inline_asm_sym(&mut self, sym: &'ast InlineAsmSym) {
1144 // This is similar to the code for AnonConst.
1145 self.with_rib(ValueNS, InlineAsmSymRibKind, |this| {
1146 this.with_rib(TypeNS, InlineAsmSymRibKind, |this| {
1147 this.with_label_rib(InlineAsmSymRibKind, |this| {
1148 this.smart_resolve_path(sym.id, &sym.qself, &sym.path, PathSource::Expr(None));
1149 visit::walk_inline_asm_sym(this, sym);
1156 impl<'a: 'ast, 'b, 'ast> LateResolutionVisitor<'a, 'b, 'ast> {
1157 fn new(resolver: &'b mut Resolver<'a>) -> LateResolutionVisitor<'a, 'b, 'ast> {
1158 // During late resolution we only track the module component of the parent scope,
1159 // although it may be useful to track other components as well for diagnostics.
1160 let graph_root = resolver.graph_root;
1161 let parent_scope = ParentScope::module(graph_root, resolver);
1162 let start_rib_kind = ModuleRibKind(graph_root);
1163 LateResolutionVisitor {
1167 value_ns: vec![Rib::new(start_rib_kind)],
1168 type_ns: vec![Rib::new(start_rib_kind)],
1169 macro_ns: vec![Rib::new(start_rib_kind)],
1171 label_ribs: Vec::new(),
1172 lifetime_ribs: Vec::new(),
1173 lifetime_elision_candidates: None,
1174 current_trait_ref: None,
1175 diagnostic_metadata: Box::new(DiagnosticMetadata::default()),
1176 // errors at module scope should always be reported
1177 in_func_body: false,
1178 lifetime_uses: Default::default(),
1182 fn maybe_resolve_ident_in_lexical_scope(
1186 ) -> Option<LexicalScopeBinding<'a>> {
1187 self.r.resolve_ident_in_lexical_scope(
1197 fn resolve_ident_in_lexical_scope(
1201 finalize: Option<Finalize>,
1202 ignore_binding: Option<&'a NameBinding<'a>>,
1203 ) -> Option<LexicalScopeBinding<'a>> {
1204 self.r.resolve_ident_in_lexical_scope(
1217 opt_ns: Option<Namespace>, // `None` indicates a module path in import
1218 finalize: Option<Finalize>,
1219 ) -> PathResult<'a> {
1220 self.r.resolve_path_with_ribs(
1232 // We maintain a list of value ribs and type ribs.
1234 // Simultaneously, we keep track of the current position in the module
1235 // graph in the `parent_scope.module` pointer. When we go to resolve a name in
1236 // the value or type namespaces, we first look through all the ribs and
1237 // then query the module graph. When we resolve a name in the module
1238 // namespace, we can skip all the ribs (since nested modules are not
1239 // allowed within blocks in Rust) and jump straight to the current module
1242 // Named implementations are handled separately. When we find a method
1243 // call, we consult the module node to find all of the implementations in
1244 // scope. This information is lazily cached in the module node. We then
1245 // generate a fake "implementation scope" containing all the
1246 // implementations thus found, for compatibility with old resolve pass.
1248 /// Do some `work` within a new innermost rib of the given `kind` in the given namespace (`ns`).
1253 work: impl FnOnce(&mut Self) -> T,
1255 self.ribs[ns].push(Rib::new(kind));
1256 let ret = work(self);
1257 self.ribs[ns].pop();
1261 fn with_scope<T>(&mut self, id: NodeId, f: impl FnOnce(&mut Self) -> T) -> T {
1262 if let Some(module) = self.r.get_module(self.r.local_def_id(id).to_def_id()) {
1263 // Move down in the graph.
1264 let orig_module = replace(&mut self.parent_scope.module, module);
1265 self.with_rib(ValueNS, ModuleRibKind(module), |this| {
1266 this.with_rib(TypeNS, ModuleRibKind(module), |this| {
1268 this.parent_scope.module = orig_module;
1277 fn visit_generic_params(&mut self, params: &'ast [GenericParam], add_self_upper: bool) {
1278 // For type parameter defaults, we have to ban access
1279 // to following type parameters, as the InternalSubsts can only
1280 // provide previous type parameters as they're built. We
1281 // put all the parameters on the ban list and then remove
1282 // them one by one as they are processed and become available.
1283 let mut forward_ty_ban_rib = Rib::new(ForwardGenericParamBanRibKind);
1284 let mut forward_const_ban_rib = Rib::new(ForwardGenericParamBanRibKind);
1285 for param in params.iter() {
1287 GenericParamKind::Type { .. } => {
1290 .insert(Ident::with_dummy_span(param.ident.name), Res::Err);
1292 GenericParamKind::Const { .. } => {
1293 forward_const_ban_rib
1295 .insert(Ident::with_dummy_span(param.ident.name), Res::Err);
1297 GenericParamKind::Lifetime => {}
1301 // rust-lang/rust#61631: The type `Self` is essentially
1302 // another type parameter. For ADTs, we consider it
1303 // well-defined only after all of the ADT type parameters have
1304 // been provided. Therefore, we do not allow use of `Self`
1305 // anywhere in ADT type parameter defaults.
1307 // (We however cannot ban `Self` for defaults on *all* generic
1308 // lists; e.g. trait generics can usefully refer to `Self`,
1309 // such as in the case of `trait Add<Rhs = Self>`.)
1311 // (`Some` if + only if we are in ADT's generics.)
1312 forward_ty_ban_rib.bindings.insert(Ident::with_dummy_span(kw::SelfUpper), Res::Err);
1315 self.with_lifetime_rib(LifetimeRibKind::AnonymousReportError, |this| {
1316 for param in params {
1318 GenericParamKind::Lifetime => {
1319 for bound in ¶m.bounds {
1320 this.visit_param_bound(bound, BoundKind::Bound);
1323 GenericParamKind::Type { ref default } => {
1324 for bound in ¶m.bounds {
1325 this.visit_param_bound(bound, BoundKind::Bound);
1328 if let Some(ref ty) = default {
1329 this.ribs[TypeNS].push(forward_ty_ban_rib);
1330 this.ribs[ValueNS].push(forward_const_ban_rib);
1332 forward_const_ban_rib = this.ribs[ValueNS].pop().unwrap();
1333 forward_ty_ban_rib = this.ribs[TypeNS].pop().unwrap();
1336 // Allow all following defaults to refer to this type parameter.
1339 .remove(&Ident::with_dummy_span(param.ident.name));
1341 GenericParamKind::Const { ref ty, kw_span: _, ref default } => {
1342 // Const parameters can't have param bounds.
1343 assert!(param.bounds.is_empty());
1345 this.ribs[TypeNS].push(Rib::new(ConstParamTyRibKind));
1346 this.ribs[ValueNS].push(Rib::new(ConstParamTyRibKind));
1347 this.with_lifetime_rib(LifetimeRibKind::ConstGeneric, |this| {
1350 this.ribs[TypeNS].pop().unwrap();
1351 this.ribs[ValueNS].pop().unwrap();
1353 if let Some(ref expr) = default {
1354 this.ribs[TypeNS].push(forward_ty_ban_rib);
1355 this.ribs[ValueNS].push(forward_const_ban_rib);
1356 this.with_lifetime_rib(LifetimeRibKind::ConstGeneric, |this| {
1357 this.resolve_anon_const(expr, IsRepeatExpr::No)
1359 forward_const_ban_rib = this.ribs[ValueNS].pop().unwrap();
1360 forward_ty_ban_rib = this.ribs[TypeNS].pop().unwrap();
1363 // Allow all following defaults to refer to this const parameter.
1364 forward_const_ban_rib
1366 .remove(&Ident::with_dummy_span(param.ident.name));
1373 #[instrument(level = "debug", skip(self, work))]
1374 fn with_lifetime_rib<T>(
1376 kind: LifetimeRibKind,
1377 work: impl FnOnce(&mut Self) -> T,
1379 self.lifetime_ribs.push(LifetimeRib::new(kind));
1380 let outer_elision_candidates = self.lifetime_elision_candidates.take();
1381 let ret = work(self);
1382 self.lifetime_elision_candidates = outer_elision_candidates;
1383 self.lifetime_ribs.pop();
1387 #[instrument(level = "debug", skip(self))]
1388 fn resolve_lifetime(&mut self, lifetime: &'ast Lifetime, use_ctxt: visit::LifetimeCtxt) {
1389 let ident = lifetime.ident;
1391 if ident.name == kw::StaticLifetime {
1392 self.record_lifetime_res(
1394 LifetimeRes::Static,
1395 LifetimeElisionCandidate::Named,
1400 if ident.name == kw::UnderscoreLifetime {
1401 return self.resolve_anonymous_lifetime(lifetime, false);
1404 let mut lifetime_rib_iter = self.lifetime_ribs.iter().rev();
1405 while let Some(rib) = lifetime_rib_iter.next() {
1406 let normalized_ident = ident.normalize_to_macros_2_0();
1407 if let Some(&(_, res)) = rib.bindings.get(&normalized_ident) {
1408 self.record_lifetime_res(lifetime.id, res, LifetimeElisionCandidate::Named);
1410 if let LifetimeRes::Param { param, .. } = res {
1411 match self.lifetime_uses.entry(param) {
1412 Entry::Vacant(v) => {
1413 debug!("First use of {:?} at {:?}", res, ident.span);
1418 .find_map(|rib| match rib.kind {
1419 // Do not suggest eliding a lifetime where an anonymous
1420 // lifetime would be illegal.
1421 LifetimeRibKind::Item
1422 | LifetimeRibKind::AnonymousReportError
1423 | LifetimeRibKind::ElisionFailure => Some(LifetimeUseSet::Many),
1424 // An anonymous lifetime is legal here, go ahead.
1425 LifetimeRibKind::AnonymousCreateParameter { .. } => {
1426 Some(LifetimeUseSet::One { use_span: ident.span, use_ctxt })
1428 // Only report if eliding the lifetime would have the same
1430 LifetimeRibKind::Elided(r) => Some(if res == r {
1431 LifetimeUseSet::One { use_span: ident.span, use_ctxt }
1433 LifetimeUseSet::Many
1435 LifetimeRibKind::Generics { .. } => None,
1436 LifetimeRibKind::ConstGeneric | LifetimeRibKind::AnonConst => {
1437 span_bug!(ident.span, "unexpected rib kind: {:?}", rib.kind)
1440 .unwrap_or(LifetimeUseSet::Many);
1441 debug!(?use_ctxt, ?use_set);
1444 Entry::Occupied(mut o) => {
1445 debug!("Many uses of {:?} at {:?}", res, ident.span);
1446 *o.get_mut() = LifetimeUseSet::Many;
1454 LifetimeRibKind::Item => break,
1455 LifetimeRibKind::ConstGeneric => {
1456 self.emit_non_static_lt_in_const_generic_error(lifetime);
1457 self.record_lifetime_res(
1460 LifetimeElisionCandidate::Ignore,
1464 LifetimeRibKind::AnonConst => {
1465 self.maybe_emit_forbidden_non_static_lifetime_error(lifetime);
1466 self.record_lifetime_res(
1469 LifetimeElisionCandidate::Ignore,
1473 LifetimeRibKind::AnonymousCreateParameter { .. }
1474 | LifetimeRibKind::Elided(_)
1475 | LifetimeRibKind::Generics { .. }
1476 | LifetimeRibKind::ElisionFailure
1477 | LifetimeRibKind::AnonymousReportError => {}
1481 let mut outer_res = None;
1482 for rib in lifetime_rib_iter {
1483 let normalized_ident = ident.normalize_to_macros_2_0();
1484 if let Some((&outer, _)) = rib.bindings.get_key_value(&normalized_ident) {
1485 outer_res = Some(outer);
1490 self.emit_undeclared_lifetime_error(lifetime, outer_res);
1491 self.record_lifetime_res(lifetime.id, LifetimeRes::Error, LifetimeElisionCandidate::Named);
1494 #[instrument(level = "debug", skip(self))]
1495 fn resolve_anonymous_lifetime(&mut self, lifetime: &Lifetime, elided: bool) {
1496 debug_assert_eq!(lifetime.ident.name, kw::UnderscoreLifetime);
1498 let missing_lifetime = MissingLifetime {
1500 span: lifetime.ident.span,
1502 MissingLifetimeKind::Ampersand
1504 MissingLifetimeKind::Underscore
1508 let elision_candidate = LifetimeElisionCandidate::Missing(missing_lifetime);
1509 for rib in self.lifetime_ribs.iter().rev() {
1512 LifetimeRibKind::AnonymousCreateParameter { binder, .. } => {
1513 let res = self.create_fresh_lifetime(lifetime.id, lifetime.ident, binder);
1514 self.record_lifetime_res(lifetime.id, res, elision_candidate);
1517 LifetimeRibKind::AnonymousReportError => {
1518 let (msg, note) = if elided {
1520 "`&` without an explicit lifetime name cannot be used here",
1521 "explicit lifetime name needed here",
1524 ("`'_` cannot be used here", "`'_` is a reserved lifetime name")
1526 rustc_errors::struct_span_err!(
1528 lifetime.ident.span,
1533 .span_label(lifetime.ident.span, note)
1536 self.record_lifetime_res(lifetime.id, LifetimeRes::Error, elision_candidate);
1539 LifetimeRibKind::Elided(res) => {
1540 self.record_lifetime_res(lifetime.id, res, elision_candidate);
1543 LifetimeRibKind::ElisionFailure => {
1544 self.diagnostic_metadata.current_elision_failures.push(missing_lifetime);
1545 self.record_lifetime_res(lifetime.id, LifetimeRes::Error, elision_candidate);
1548 LifetimeRibKind::Item => break,
1549 LifetimeRibKind::Generics { .. } | LifetimeRibKind::ConstGeneric => {}
1550 LifetimeRibKind::AnonConst => {
1551 // There is always an `Elided(LifetimeRes::Static)` inside an `AnonConst`.
1552 span_bug!(lifetime.ident.span, "unexpected rib kind: {:?}", rib.kind)
1556 self.record_lifetime_res(lifetime.id, LifetimeRes::Error, elision_candidate);
1557 self.report_missing_lifetime_specifiers(vec![missing_lifetime], None);
1560 #[instrument(level = "debug", skip(self))]
1561 fn resolve_elided_lifetime(&mut self, anchor_id: NodeId, span: Span) {
1562 let id = self.r.next_node_id();
1563 let lt = Lifetime { id, ident: Ident::new(kw::UnderscoreLifetime, span) };
1565 self.record_lifetime_res(
1567 LifetimeRes::ElidedAnchor { start: id, end: NodeId::from_u32(id.as_u32() + 1) },
1568 LifetimeElisionCandidate::Ignore,
1570 self.resolve_anonymous_lifetime(<, true);
1573 #[instrument(level = "debug", skip(self))]
1574 fn create_fresh_lifetime(&mut self, id: NodeId, ident: Ident, binder: NodeId) -> LifetimeRes {
1575 debug_assert_eq!(ident.name, kw::UnderscoreLifetime);
1576 debug!(?ident.span);
1578 // Leave the responsibility to create the `LocalDefId` to lowering.
1579 let param = self.r.next_node_id();
1580 let res = LifetimeRes::Fresh { param, binder };
1582 // Record the created lifetime parameter so lowering can pick it up and add it to HIR.
1584 .extra_lifetime_params_map
1586 .or_insert_with(Vec::new)
1587 .push((ident, param, res));
1591 #[instrument(level = "debug", skip(self))]
1592 fn resolve_elided_lifetimes_in_path(
1595 partial_res: PartialRes,
1597 source: PathSource<'_>,
1600 let proj_start = path.len() - partial_res.unresolved_segments();
1601 for (i, segment) in path.iter().enumerate() {
1602 if segment.has_lifetime_args {
1605 let Some(segment_id) = segment.id else {
1609 // Figure out if this is a type/trait segment,
1610 // which may need lifetime elision performed.
1611 let type_def_id = match partial_res.base_res() {
1612 Res::Def(DefKind::AssocTy, def_id) if i + 2 == proj_start => self.r.parent(def_id),
1613 Res::Def(DefKind::Variant, def_id) if i + 1 == proj_start => self.r.parent(def_id),
1614 Res::Def(DefKind::Struct, def_id)
1615 | Res::Def(DefKind::Union, def_id)
1616 | Res::Def(DefKind::Enum, def_id)
1617 | Res::Def(DefKind::TyAlias, def_id)
1618 | Res::Def(DefKind::Trait, def_id)
1619 if i + 1 == proj_start =>
1626 let expected_lifetimes = self.r.item_generics_num_lifetimes(type_def_id);
1627 if expected_lifetimes == 0 {
1631 let node_ids = self.r.next_node_ids(expected_lifetimes);
1632 self.record_lifetime_res(
1634 LifetimeRes::ElidedAnchor { start: node_ids.start, end: node_ids.end },
1635 LifetimeElisionCandidate::Ignore,
1638 let inferred = match source {
1639 PathSource::Trait(..) | PathSource::TraitItem(..) | PathSource::Type => false,
1640 PathSource::Expr(..)
1642 | PathSource::Struct
1643 | PathSource::TupleStruct(..) => true,
1646 // Do not create a parameter for patterns and expressions: type checking can infer
1647 // the appropriate lifetime for us.
1648 for id in node_ids {
1649 self.record_lifetime_res(
1652 LifetimeElisionCandidate::Named,
1658 let elided_lifetime_span = if segment.has_generic_args {
1659 // If there are brackets, but not generic arguments, then use the opening bracket
1660 segment.args_span.with_hi(segment.args_span.lo() + BytePos(1))
1662 // If there are no brackets, use the identifier span.
1663 // HACK: we use find_ancestor_inside to properly suggest elided spans in paths
1664 // originating from macros, since the segment's span might be from a macro arg.
1665 segment.ident.span.find_ancestor_inside(path_span).unwrap_or(path_span)
1667 let ident = Ident::new(kw::UnderscoreLifetime, elided_lifetime_span);
1669 let missing_lifetime = MissingLifetime {
1671 span: elided_lifetime_span,
1672 kind: if segment.has_generic_args {
1673 MissingLifetimeKind::Comma
1675 MissingLifetimeKind::Brackets
1677 count: expected_lifetimes,
1679 let mut should_lint = true;
1680 for rib in self.lifetime_ribs.iter().rev() {
1682 // In create-parameter mode we error here because we don't want to support
1683 // deprecated impl elision in new features like impl elision and `async fn`,
1684 // both of which work using the `CreateParameter` mode:
1686 // impl Foo for std::cell::Ref<u32> // note lack of '_
1687 // async fn foo(_: std::cell::Ref<u32>) { ... }
1688 LifetimeRibKind::AnonymousCreateParameter { report_in_path: true, .. } => {
1689 let sess = self.r.session;
1690 let mut err = rustc_errors::struct_span_err!(
1694 "implicit elided lifetime not allowed here"
1696 rustc_errors::add_elided_lifetime_in_path_suggestion(
1701 !segment.has_generic_args,
1702 elided_lifetime_span,
1704 err.note("assuming a `'static` lifetime...");
1706 should_lint = false;
1708 for id in node_ids {
1709 self.record_lifetime_res(
1712 LifetimeElisionCandidate::Named,
1717 // Do not create a parameter for patterns and expressions.
1718 LifetimeRibKind::AnonymousCreateParameter { binder, .. } => {
1719 // Group all suggestions into the first record.
1720 let mut candidate = LifetimeElisionCandidate::Missing(missing_lifetime);
1721 for id in node_ids {
1722 let res = self.create_fresh_lifetime(id, ident, binder);
1723 self.record_lifetime_res(
1726 replace(&mut candidate, LifetimeElisionCandidate::Named),
1731 LifetimeRibKind::Elided(res) => {
1732 let mut candidate = LifetimeElisionCandidate::Missing(missing_lifetime);
1733 for id in node_ids {
1734 self.record_lifetime_res(
1737 replace(&mut candidate, LifetimeElisionCandidate::Ignore),
1742 LifetimeRibKind::ElisionFailure => {
1743 self.diagnostic_metadata.current_elision_failures.push(missing_lifetime);
1744 for id in node_ids {
1745 self.record_lifetime_res(
1748 LifetimeElisionCandidate::Ignore,
1753 // `LifetimeRes::Error`, which would usually be used in the case of
1754 // `ReportError`, is unsuitable here, as we don't emit an error yet. Instead,
1755 // we simply resolve to an implicit lifetime, which will be checked later, at
1756 // which point a suitable error will be emitted.
1757 LifetimeRibKind::AnonymousReportError | LifetimeRibKind::Item => {
1758 for id in node_ids {
1759 self.record_lifetime_res(
1762 LifetimeElisionCandidate::Ignore,
1765 self.report_missing_lifetime_specifiers(vec![missing_lifetime], None);
1768 LifetimeRibKind::Generics { .. } | LifetimeRibKind::ConstGeneric => {}
1769 LifetimeRibKind::AnonConst => {
1770 // There is always an `Elided(LifetimeRes::Static)` inside an `AnonConst`.
1771 span_bug!(elided_lifetime_span, "unexpected rib kind: {:?}", rib.kind)
1777 self.r.lint_buffer.buffer_lint_with_diagnostic(
1778 lint::builtin::ELIDED_LIFETIMES_IN_PATHS,
1780 elided_lifetime_span,
1781 "hidden lifetime parameters in types are deprecated",
1782 lint::BuiltinLintDiagnostics::ElidedLifetimesInPaths(
1785 !segment.has_generic_args,
1786 elided_lifetime_span,
1793 #[instrument(level = "debug", skip(self))]
1794 fn record_lifetime_res(
1798 candidate: LifetimeElisionCandidate,
1800 if let Some(prev_res) = self.r.lifetimes_res_map.insert(id, res) {
1802 "lifetime {:?} resolved multiple times ({:?} before, {:?} now)",
1807 LifetimeRes::Param { .. } | LifetimeRes::Fresh { .. } | LifetimeRes::Static => {
1808 if let Some(ref mut candidates) = self.lifetime_elision_candidates {
1809 candidates.push((res, candidate));
1812 LifetimeRes::Infer | LifetimeRes::Error | LifetimeRes::ElidedAnchor { .. } => {}
1816 #[instrument(level = "debug", skip(self))]
1817 fn record_lifetime_param(&mut self, id: NodeId, res: LifetimeRes) {
1818 if let Some(prev_res) = self.r.lifetimes_res_map.insert(id, res) {
1820 "lifetime parameter {:?} resolved multiple times ({:?} before, {:?} now)",
1826 /// Perform resolution of a function signature, accounting for lifetime elision.
1827 #[instrument(level = "debug", skip(self, inputs))]
1828 fn resolve_fn_signature(
1832 inputs: impl Iterator<Item = (Option<&'ast Pat>, &'ast Ty)> + Clone,
1833 output_ty: &'ast FnRetTy,
1835 // Add each argument to the rib.
1836 let elision_lifetime = self.resolve_fn_params(has_self, inputs);
1837 debug!(?elision_lifetime);
1839 let outer_failures = take(&mut self.diagnostic_metadata.current_elision_failures);
1840 let output_rib = if let Ok(res) = elision_lifetime.as_ref() {
1841 LifetimeRibKind::Elided(*res)
1843 LifetimeRibKind::ElisionFailure
1845 self.with_lifetime_rib(output_rib, |this| visit::walk_fn_ret_ty(this, &output_ty));
1846 let elision_failures =
1847 replace(&mut self.diagnostic_metadata.current_elision_failures, outer_failures);
1848 if !elision_failures.is_empty() {
1849 let Err(failure_info) = elision_lifetime else { bug!() };
1850 self.report_missing_lifetime_specifiers(elision_failures, Some(failure_info));
1854 /// Resolve inside function parameters and parameter types.
1855 /// Returns the lifetime for elision in fn return type,
1856 /// or diagnostic information in case of elision failure.
1857 fn resolve_fn_params(
1860 inputs: impl Iterator<Item = (Option<&'ast Pat>, &'ast Ty)>,
1861 ) -> Result<LifetimeRes, (Vec<MissingLifetime>, Vec<ElisionFnParameter>)> {
1863 /// We have not found any candidate.
1865 /// We have a candidate bound to `self`.
1867 /// We have a candidate bound to a parameter.
1869 /// We failed elision.
1873 // Save elision state to reinstate it later.
1874 let outer_candidates = self.lifetime_elision_candidates.take();
1876 // Result of elision.
1877 let mut elision_lifetime = Elision::None;
1878 // Information for diagnostics.
1879 let mut parameter_info = Vec::new();
1880 let mut all_candidates = Vec::new();
1882 let mut bindings = smallvec![(PatBoundCtx::Product, Default::default())];
1883 for (index, (pat, ty)) in inputs.enumerate() {
1885 self.with_lifetime_rib(LifetimeRibKind::Elided(LifetimeRes::Infer), |this| {
1886 if let Some(pat) = pat {
1887 this.resolve_pattern(pat, PatternSource::FnParam, &mut bindings);
1891 // Record elision candidates only for this parameter.
1892 debug_assert_matches!(self.lifetime_elision_candidates, None);
1893 self.lifetime_elision_candidates = Some(Default::default());
1895 let local_candidates = self.lifetime_elision_candidates.take();
1897 if let Some(candidates) = local_candidates {
1898 let distinct: FxHashSet<_> = candidates.iter().map(|(res, _)| *res).collect();
1899 let lifetime_count = distinct.len();
1900 if lifetime_count != 0 {
1901 parameter_info.push(ElisionFnParameter {
1903 ident: if let Some(pat) = pat && let PatKind::Ident(_, ident, _) = pat.kind {
1911 all_candidates.extend(candidates.into_iter().filter_map(|(_, candidate)| {
1913 LifetimeElisionCandidate::Ignore | LifetimeElisionCandidate::Named => {
1916 LifetimeElisionCandidate::Missing(missing) => Some(missing),
1920 let mut distinct_iter = distinct.into_iter();
1921 if let Some(res) = distinct_iter.next() {
1922 match elision_lifetime {
1923 // We are the first parameter to bind lifetimes.
1925 if distinct_iter.next().is_none() {
1926 // We have a single lifetime => success.
1927 elision_lifetime = Elision::Param(res)
1929 // We have have multiple lifetimes => error.
1930 elision_lifetime = Elision::Err;
1933 // We have 2 parameters that bind lifetimes => error.
1934 Elision::Param(_) => elision_lifetime = Elision::Err,
1935 // `self` elision takes precedence over everything else.
1936 Elision::Self_(_) | Elision::Err => {}
1941 // Handle `self` specially.
1942 if index == 0 && has_self {
1943 let self_lifetime = self.find_lifetime_for_self(ty);
1944 if let Set1::One(lifetime) = self_lifetime {
1945 // We found `self` elision.
1946 elision_lifetime = Elision::Self_(lifetime);
1948 // We do not have `self` elision: disregard the `Elision::Param` that we may
1950 elision_lifetime = Elision::None;
1953 debug!("(resolving function / closure) recorded parameter");
1956 // Reinstate elision state.
1957 debug_assert_matches!(self.lifetime_elision_candidates, None);
1958 self.lifetime_elision_candidates = outer_candidates;
1960 if let Elision::Param(res) | Elision::Self_(res) = elision_lifetime {
1964 // We do not have a candidate.
1965 Err((all_candidates, parameter_info))
1968 /// List all the lifetimes that appear in the provided type.
1969 fn find_lifetime_for_self(&self, ty: &'ast Ty) -> Set1<LifetimeRes> {
1970 struct SelfVisitor<'r, 'a> {
1971 r: &'r Resolver<'a>,
1972 impl_self: Option<Res>,
1973 lifetime: Set1<LifetimeRes>,
1976 impl SelfVisitor<'_, '_> {
1977 // Look for `self: &'a Self` - also desugared from `&'a self`,
1978 // and if that matches, use it for elision and return early.
1979 fn is_self_ty(&self, ty: &Ty) -> bool {
1981 TyKind::ImplicitSelf => true,
1982 TyKind::Path(None, _) => {
1983 let path_res = self.r.partial_res_map[&ty.id].full_res();
1984 if let Some(Res::SelfTyParam { .. } | Res::SelfTyAlias { .. }) = path_res {
1987 self.impl_self.is_some() && path_res == self.impl_self
1994 impl<'a> Visitor<'a> for SelfVisitor<'_, '_> {
1995 fn visit_ty(&mut self, ty: &'a Ty) {
1996 trace!("SelfVisitor considering ty={:?}", ty);
1997 if let TyKind::Rptr(lt, ref mt) = ty.kind && self.is_self_ty(&mt.ty) {
1998 let lt_id = if let Some(lt) = lt {
2001 let res = self.r.lifetimes_res_map[&ty.id];
2002 let LifetimeRes::ElidedAnchor { start, .. } = res else { bug!() };
2005 let lt_res = self.r.lifetimes_res_map[<_id];
2006 trace!("SelfVisitor inserting res={:?}", lt_res);
2007 self.lifetime.insert(lt_res);
2009 visit::walk_ty(self, ty)
2013 let impl_self = self
2014 .diagnostic_metadata
2018 if let TyKind::Path(None, _) = ty.kind {
2019 self.r.partial_res_map.get(&ty.id)
2024 .and_then(|res| res.full_res())
2026 // Permit the types that unambiguously always
2027 // result in the same type constructor being used
2028 // (it can't differ between `Self` and `self`).
2031 Res::Def(DefKind::Struct | DefKind::Union | DefKind::Enum, _,) | Res::PrimTy(_)
2034 let mut visitor = SelfVisitor { r: self.r, impl_self, lifetime: Set1::Empty };
2035 visitor.visit_ty(ty);
2036 trace!("SelfVisitor found={:?}", visitor.lifetime);
2040 /// Searches the current set of local scopes for labels. Returns the `NodeId` of the resolved
2041 /// label and reports an error if the label is not found or is unreachable.
2042 fn resolve_label(&mut self, mut label: Ident) -> Result<(NodeId, Span), ResolutionError<'a>> {
2043 let mut suggestion = None;
2045 for i in (0..self.label_ribs.len()).rev() {
2046 let rib = &self.label_ribs[i];
2048 if let MacroDefinition(def) = rib.kind {
2049 // If an invocation of this macro created `ident`, give up on `ident`
2050 // and switch to `ident`'s source from the macro definition.
2051 if def == self.r.macro_def(label.span.ctxt()) {
2052 label.span.remove_mark();
2056 let ident = label.normalize_to_macro_rules();
2057 if let Some((ident, id)) = rib.bindings.get_key_value(&ident) {
2058 let definition_span = ident.span;
2059 return if self.is_label_valid_from_rib(i) {
2060 Ok((*id, definition_span))
2062 Err(ResolutionError::UnreachableLabel {
2070 // Diagnostics: Check if this rib contains a label with a similar name, keep track of
2071 // the first such label that is encountered.
2072 suggestion = suggestion.or_else(|| self.suggestion_for_label_in_rib(i, label));
2075 Err(ResolutionError::UndeclaredLabel { name: label.name, suggestion })
2078 /// Determine whether or not a label from the `rib_index`th label rib is reachable.
2079 fn is_label_valid_from_rib(&self, rib_index: usize) -> bool {
2080 let ribs = &self.label_ribs[rib_index + 1..];
2083 if rib.kind.is_label_barrier() {
2091 fn resolve_adt(&mut self, item: &'ast Item, generics: &'ast Generics) {
2092 debug!("resolve_adt");
2093 self.with_current_self_item(item, |this| {
2094 this.with_generic_param_rib(
2096 ItemRibKind(HasGenericParams::Yes(generics.span)),
2097 LifetimeRibKind::Generics {
2099 kind: LifetimeBinderKind::Item,
2100 span: generics.span,
2103 let item_def_id = this.r.local_def_id(item.id).to_def_id();
2106 alias_to: item_def_id,
2107 forbid_generic: false,
2108 is_trait_impl: false,
2111 visit::walk_item(this, item);
2119 fn future_proof_import(&mut self, use_tree: &UseTree) {
2120 let segments = &use_tree.prefix.segments;
2121 if !segments.is_empty() {
2122 let ident = segments[0].ident;
2123 if ident.is_path_segment_keyword() || ident.span.rust_2015() {
2127 let nss = match use_tree.kind {
2128 UseTreeKind::Simple(..) if segments.len() == 1 => &[TypeNS, ValueNS][..],
2131 let report_error = |this: &Self, ns| {
2132 let what = if ns == TypeNS { "type parameters" } else { "local variables" };
2133 if this.should_report_errs() {
2136 .span_err(ident.span, &format!("imports cannot refer to {}", what));
2141 match self.maybe_resolve_ident_in_lexical_scope(ident, ns) {
2142 Some(LexicalScopeBinding::Res(..)) => {
2143 report_error(self, ns);
2145 Some(LexicalScopeBinding::Item(binding)) => {
2146 if let Some(LexicalScopeBinding::Res(..)) =
2147 self.resolve_ident_in_lexical_scope(ident, ns, None, Some(binding))
2149 report_error(self, ns);
2155 } else if let UseTreeKind::Nested(use_trees) = &use_tree.kind {
2156 for (use_tree, _) in use_trees {
2157 self.future_proof_import(use_tree);
2162 fn resolve_item(&mut self, item: &'ast Item) {
2163 let name = item.ident.name;
2164 debug!("(resolving item) resolving {} ({:?})", name, item.kind);
2167 ItemKind::TyAlias(box TyAlias { ref generics, .. }) => {
2168 self.with_generic_param_rib(
2170 ItemRibKind(HasGenericParams::Yes(generics.span)),
2171 LifetimeRibKind::Generics {
2173 kind: LifetimeBinderKind::Item,
2174 span: generics.span,
2176 |this| visit::walk_item(this, item),
2180 ItemKind::Fn(box Fn { ref generics, .. }) => {
2181 self.with_generic_param_rib(
2183 ItemRibKind(HasGenericParams::Yes(generics.span)),
2184 LifetimeRibKind::Generics {
2186 kind: LifetimeBinderKind::Function,
2187 span: generics.span,
2189 |this| visit::walk_item(this, item),
2193 ItemKind::Enum(_, ref generics)
2194 | ItemKind::Struct(_, ref generics)
2195 | ItemKind::Union(_, ref generics) => {
2196 self.resolve_adt(item, generics);
2199 ItemKind::Impl(box Impl {
2203 items: ref impl_items,
2206 self.diagnostic_metadata.current_impl_items = Some(impl_items);
2207 self.resolve_implementation(generics, of_trait, &self_ty, item.id, impl_items);
2208 self.diagnostic_metadata.current_impl_items = None;
2211 ItemKind::Trait(box Trait { ref generics, ref bounds, ref items, .. }) => {
2212 // Create a new rib for the trait-wide type parameters.
2213 self.with_generic_param_rib(
2215 ItemRibKind(HasGenericParams::Yes(generics.span)),
2216 LifetimeRibKind::Generics {
2218 kind: LifetimeBinderKind::Item,
2219 span: generics.span,
2222 let local_def_id = this.r.local_def_id(item.id).to_def_id();
2223 this.with_self_rib(Res::SelfTyParam { trait_: local_def_id }, |this| {
2224 this.visit_generics(generics);
2225 walk_list!(this, visit_param_bound, bounds, BoundKind::SuperTraits);
2226 this.resolve_trait_items(items);
2232 ItemKind::TraitAlias(ref generics, ref bounds) => {
2233 // Create a new rib for the trait-wide type parameters.
2234 self.with_generic_param_rib(
2236 ItemRibKind(HasGenericParams::Yes(generics.span)),
2237 LifetimeRibKind::Generics {
2239 kind: LifetimeBinderKind::Item,
2240 span: generics.span,
2243 let local_def_id = this.r.local_def_id(item.id).to_def_id();
2244 this.with_self_rib(Res::SelfTyParam { trait_: local_def_id }, |this| {
2245 this.visit_generics(generics);
2246 walk_list!(this, visit_param_bound, bounds, BoundKind::Bound);
2252 ItemKind::Mod(..) | ItemKind::ForeignMod(_) => {
2253 self.with_scope(item.id, |this| {
2254 visit::walk_item(this, item);
2258 ItemKind::Static(ref ty, _, ref expr) | ItemKind::Const(_, ref ty, ref expr) => {
2259 self.with_static_rib(|this| {
2260 this.with_lifetime_rib(LifetimeRibKind::Elided(LifetimeRes::Static), |this| {
2263 this.with_lifetime_rib(LifetimeRibKind::Elided(LifetimeRes::Infer), |this| {
2264 if let Some(expr) = expr {
2265 let constant_item_kind = match item.kind {
2266 ItemKind::Const(..) => ConstantItemKind::Const,
2267 ItemKind::Static(..) => ConstantItemKind::Static,
2268 _ => unreachable!(),
2270 // We already forbid generic params because of the above item rib,
2271 // so it doesn't matter whether this is a trivial constant.
2272 this.with_constant_rib(
2274 ConstantHasGenerics::Yes,
2275 Some((item.ident, constant_item_kind)),
2276 |this| this.visit_expr(expr),
2283 ItemKind::Use(ref use_tree) => {
2284 self.future_proof_import(use_tree);
2287 ItemKind::ExternCrate(..) | ItemKind::MacroDef(..) => {
2288 // do nothing, these are just around to be encoded
2291 ItemKind::GlobalAsm(_) => {
2292 visit::walk_item(self, item);
2295 ItemKind::MacCall(_) => panic!("unexpanded macro in resolve!"),
2299 fn with_generic_param_rib<'c, F>(
2301 params: &'c [GenericParam],
2303 lifetime_kind: LifetimeRibKind,
2306 F: FnOnce(&mut Self),
2308 debug!("with_generic_param_rib");
2309 let LifetimeRibKind::Generics { binder, span: generics_span, kind: generics_kind, .. }
2310 = lifetime_kind else { panic!() };
2312 let mut function_type_rib = Rib::new(kind);
2313 let mut function_value_rib = Rib::new(kind);
2314 let mut function_lifetime_rib = LifetimeRib::new(lifetime_kind);
2315 let mut seen_bindings = FxHashMap::default();
2316 // Store all seen lifetimes names from outer scopes.
2317 let mut seen_lifetimes = FxHashSet::default();
2319 // We also can't shadow bindings from the parent item
2320 if let AssocItemRibKind = kind {
2321 let mut add_bindings_for_ns = |ns| {
2322 let parent_rib = self.ribs[ns]
2324 .rfind(|r| matches!(r.kind, ItemRibKind(_)))
2325 .expect("associated item outside of an item");
2327 .extend(parent_rib.bindings.iter().map(|(ident, _)| (*ident, ident.span)));
2329 add_bindings_for_ns(ValueNS);
2330 add_bindings_for_ns(TypeNS);
2333 // Forbid shadowing lifetime bindings
2334 for rib in self.lifetime_ribs.iter().rev() {
2335 seen_lifetimes.extend(rib.bindings.iter().map(|(ident, _)| *ident));
2336 if let LifetimeRibKind::Item = rib.kind {
2341 for param in params {
2342 let ident = param.ident.normalize_to_macros_2_0();
2343 debug!("with_generic_param_rib: {}", param.id);
2345 if let GenericParamKind::Lifetime = param.kind
2346 && let Some(&original) = seen_lifetimes.get(&ident)
2348 diagnostics::signal_lifetime_shadowing(self.r.session, original, param.ident);
2349 // Record lifetime res, so lowering knows there is something fishy.
2350 self.record_lifetime_param(param.id, LifetimeRes::Error);
2354 match seen_bindings.entry(ident) {
2355 Entry::Occupied(entry) => {
2356 let span = *entry.get();
2357 let err = ResolutionError::NameAlreadyUsedInParameterList(ident.name, span);
2358 self.report_error(param.ident.span, err);
2359 if let GenericParamKind::Lifetime = param.kind {
2360 // Record lifetime res, so lowering knows there is something fishy.
2361 self.record_lifetime_param(param.id, LifetimeRes::Error);
2365 Entry::Vacant(entry) => {
2366 entry.insert(param.ident.span);
2370 if param.ident.name == kw::UnderscoreLifetime {
2371 rustc_errors::struct_span_err!(
2375 "`'_` cannot be used here"
2377 .span_label(param.ident.span, "`'_` is a reserved lifetime name")
2379 // Record lifetime res, so lowering knows there is something fishy.
2380 self.record_lifetime_param(param.id, LifetimeRes::Error);
2384 if param.ident.name == kw::StaticLifetime {
2385 rustc_errors::struct_span_err!(
2389 "invalid lifetime parameter name: `{}`",
2392 .span_label(param.ident.span, "'static is a reserved lifetime name")
2394 // Record lifetime res, so lowering knows there is something fishy.
2395 self.record_lifetime_param(param.id, LifetimeRes::Error);
2399 let def_id = self.r.local_def_id(param.id);
2401 // Plain insert (no renaming).
2402 let (rib, def_kind) = match param.kind {
2403 GenericParamKind::Type { .. } => (&mut function_type_rib, DefKind::TyParam),
2404 GenericParamKind::Const { .. } => (&mut function_value_rib, DefKind::ConstParam),
2405 GenericParamKind::Lifetime => {
2406 let res = LifetimeRes::Param { param: def_id, binder };
2407 self.record_lifetime_param(param.id, res);
2408 function_lifetime_rib.bindings.insert(ident, (param.id, res));
2413 let res = match kind {
2414 ItemRibKind(..) | AssocItemRibKind => Res::Def(def_kind, def_id.to_def_id()),
2415 NormalRibKind => Res::Err,
2416 _ => span_bug!(param.ident.span, "Unexpected rib kind {:?}", kind),
2418 self.r.record_partial_res(param.id, PartialRes::new(res));
2419 rib.bindings.insert(ident, res);
2422 self.lifetime_ribs.push(function_lifetime_rib);
2423 self.ribs[ValueNS].push(function_value_rib);
2424 self.ribs[TypeNS].push(function_type_rib);
2428 self.ribs[TypeNS].pop();
2429 self.ribs[ValueNS].pop();
2430 let function_lifetime_rib = self.lifetime_ribs.pop().unwrap();
2432 // Do not account for the parameters we just bound for function lifetime elision.
2433 if let Some(ref mut candidates) = self.lifetime_elision_candidates {
2434 for (_, res) in function_lifetime_rib.bindings.values() {
2435 candidates.retain(|(r, _)| r != res);
2439 if let LifetimeBinderKind::BareFnType
2440 | LifetimeBinderKind::WhereBound
2441 | LifetimeBinderKind::Function
2442 | LifetimeBinderKind::ImplBlock = generics_kind
2444 self.maybe_report_lifetime_uses(generics_span, params)
2448 fn with_label_rib(&mut self, kind: RibKind<'a>, f: impl FnOnce(&mut Self)) {
2449 self.label_ribs.push(Rib::new(kind));
2451 self.label_ribs.pop();
2454 fn with_static_rib(&mut self, f: impl FnOnce(&mut Self)) {
2455 let kind = ItemRibKind(HasGenericParams::No);
2456 self.with_rib(ValueNS, kind, |this| this.with_rib(TypeNS, kind, f))
2459 // HACK(min_const_generics,const_evaluatable_unchecked): We
2460 // want to keep allowing `[0; std::mem::size_of::<*mut T>()]`
2461 // with a future compat lint for now. We do this by adding an
2462 // additional special case for repeat expressions.
2464 // Note that we intentionally still forbid `[0; N + 1]` during
2465 // name resolution so that we don't extend the future
2466 // compat lint to new cases.
2467 #[instrument(level = "debug", skip(self, f))]
2468 fn with_constant_rib(
2470 is_repeat: IsRepeatExpr,
2471 may_use_generics: ConstantHasGenerics,
2472 item: Option<(Ident, ConstantItemKind)>,
2473 f: impl FnOnce(&mut Self),
2475 self.with_rib(ValueNS, ConstantItemRibKind(may_use_generics, item), |this| {
2478 ConstantItemRibKind(
2479 may_use_generics.force_yes_if(is_repeat == IsRepeatExpr::Yes),
2483 this.with_label_rib(ConstantItemRibKind(may_use_generics, item), f);
2489 fn with_current_self_type<T>(&mut self, self_type: &Ty, f: impl FnOnce(&mut Self) -> T) -> T {
2490 // Handle nested impls (inside fn bodies)
2491 let previous_value =
2492 replace(&mut self.diagnostic_metadata.current_self_type, Some(self_type.clone()));
2493 let result = f(self);
2494 self.diagnostic_metadata.current_self_type = previous_value;
2498 fn with_current_self_item<T>(&mut self, self_item: &Item, f: impl FnOnce(&mut Self) -> T) -> T {
2499 let previous_value =
2500 replace(&mut self.diagnostic_metadata.current_self_item, Some(self_item.id));
2501 let result = f(self);
2502 self.diagnostic_metadata.current_self_item = previous_value;
2506 /// When evaluating a `trait` use its associated types' idents for suggestions in E0412.
2507 fn resolve_trait_items(&mut self, trait_items: &'ast [P<AssocItem>]) {
2508 let trait_assoc_items =
2509 replace(&mut self.diagnostic_metadata.current_trait_assoc_items, Some(&trait_items));
2511 let walk_assoc_item =
2512 |this: &mut Self, generics: &Generics, kind, item: &'ast AssocItem| {
2513 this.with_generic_param_rib(
2516 LifetimeRibKind::Generics { binder: item.id, span: generics.span, kind },
2517 |this| visit::walk_assoc_item(this, item, AssocCtxt::Trait),
2521 for item in trait_items {
2523 AssocItemKind::Const(_, ty, default) => {
2525 // Only impose the restrictions of `ConstRibKind` for an
2526 // actual constant expression in a provided default.
2527 if let Some(expr) = default {
2528 // We allow arbitrary const expressions inside of associated consts,
2529 // even if they are potentially not const evaluatable.
2531 // Type parameters can already be used and as associated consts are
2532 // not used as part of the type system, this is far less surprising.
2533 self.with_lifetime_rib(
2534 LifetimeRibKind::Elided(LifetimeRes::Infer),
2536 this.with_constant_rib(
2538 ConstantHasGenerics::Yes,
2540 |this| this.visit_expr(expr),
2546 AssocItemKind::Fn(box Fn { generics, .. }) => {
2547 walk_assoc_item(self, generics, LifetimeBinderKind::Function, item);
2549 AssocItemKind::Type(box TyAlias { generics, .. }) => self
2550 .with_lifetime_rib(LifetimeRibKind::AnonymousReportError, |this| {
2551 walk_assoc_item(this, generics, LifetimeBinderKind::Item, item)
2553 AssocItemKind::MacCall(_) => {
2554 panic!("unexpanded macro in resolve!")
2559 self.diagnostic_metadata.current_trait_assoc_items = trait_assoc_items;
2562 /// This is called to resolve a trait reference from an `impl` (i.e., `impl Trait for Foo`).
2563 fn with_optional_trait_ref<T>(
2565 opt_trait_ref: Option<&TraitRef>,
2566 self_type: &'ast Ty,
2567 f: impl FnOnce(&mut Self, Option<DefId>) -> T,
2569 let mut new_val = None;
2570 let mut new_id = None;
2571 if let Some(trait_ref) = opt_trait_ref {
2572 let path: Vec<_> = Segment::from_path(&trait_ref.path);
2573 self.diagnostic_metadata.currently_processing_impl_trait =
2574 Some((trait_ref.clone(), self_type.clone()));
2575 let res = self.smart_resolve_path_fragment(
2578 PathSource::Trait(AliasPossibility::No),
2579 Finalize::new(trait_ref.ref_id, trait_ref.path.span),
2581 self.diagnostic_metadata.currently_processing_impl_trait = None;
2582 if let Some(def_id) = res.expect_full_res().opt_def_id() {
2583 new_id = Some(def_id);
2584 new_val = Some((self.r.expect_module(def_id), trait_ref.clone()));
2587 let original_trait_ref = replace(&mut self.current_trait_ref, new_val);
2588 let result = f(self, new_id);
2589 self.current_trait_ref = original_trait_ref;
2593 fn with_self_rib_ns(&mut self, ns: Namespace, self_res: Res, f: impl FnOnce(&mut Self)) {
2594 let mut self_type_rib = Rib::new(NormalRibKind);
2596 // Plain insert (no renaming, since types are not currently hygienic)
2597 self_type_rib.bindings.insert(Ident::with_dummy_span(kw::SelfUpper), self_res);
2598 self.ribs[ns].push(self_type_rib);
2600 self.ribs[ns].pop();
2603 fn with_self_rib(&mut self, self_res: Res, f: impl FnOnce(&mut Self)) {
2604 self.with_self_rib_ns(TypeNS, self_res, f)
2607 fn resolve_implementation(
2609 generics: &'ast Generics,
2610 opt_trait_reference: &'ast Option<TraitRef>,
2611 self_type: &'ast Ty,
2613 impl_items: &'ast [P<AssocItem>],
2615 debug!("resolve_implementation");
2616 // If applicable, create a rib for the type parameters.
2617 self.with_generic_param_rib(
2619 ItemRibKind(HasGenericParams::Yes(generics.span)),
2620 LifetimeRibKind::Generics {
2621 span: generics.span,
2623 kind: LifetimeBinderKind::ImplBlock,
2626 // Dummy self type for better errors if `Self` is used in the trait path.
2627 this.with_self_rib(Res::SelfTyParam { trait_: LOCAL_CRATE.as_def_id() }, |this| {
2628 this.with_lifetime_rib(
2629 LifetimeRibKind::AnonymousCreateParameter {
2631 report_in_path: true
2634 // Resolve the trait reference, if necessary.
2635 this.with_optional_trait_ref(
2636 opt_trait_reference.as_ref(),
2639 let item_def_id = this.r.local_def_id(item_id);
2641 // Register the trait definitions from here.
2642 if let Some(trait_id) = trait_id {
2650 let item_def_id = item_def_id.to_def_id();
2651 let res = Res::SelfTyAlias {
2652 alias_to: item_def_id,
2653 forbid_generic: false,
2654 is_trait_impl: trait_id.is_some()
2656 this.with_self_rib(res, |this| {
2657 if let Some(trait_ref) = opt_trait_reference.as_ref() {
2658 // Resolve type arguments in the trait path.
2659 visit::walk_trait_ref(this, trait_ref);
2661 // Resolve the self type.
2662 this.visit_ty(self_type);
2663 // Resolve the generic parameters.
2664 this.visit_generics(generics);
2666 // Resolve the items within the impl.
2667 this.with_current_self_type(self_type, |this| {
2668 this.with_self_rib_ns(ValueNS, Res::SelfCtor(item_def_id), |this| {
2669 debug!("resolve_implementation with_self_rib_ns(ValueNS, ...)");
2670 let mut seen_trait_items = Default::default();
2671 for item in impl_items {
2672 this.resolve_impl_item(&**item, &mut seen_trait_items);
2686 fn resolve_impl_item(
2688 item: &'ast AssocItem,
2689 seen_trait_items: &mut FxHashMap<DefId, Span>,
2691 use crate::ResolutionError::*;
2693 AssocItemKind::Const(_, ty, default) => {
2694 debug!("resolve_implementation AssocItemKind::Const");
2695 // If this is a trait impl, ensure the const
2697 self.check_trait_item(
2704 |i, s, c| ConstNotMemberOfTrait(i, s, c),
2708 if let Some(expr) = default {
2709 // We allow arbitrary const expressions inside of associated consts,
2710 // even if they are potentially not const evaluatable.
2712 // Type parameters can already be used and as associated consts are
2713 // not used as part of the type system, this is far less surprising.
2714 self.with_lifetime_rib(LifetimeRibKind::Elided(LifetimeRes::Infer), |this| {
2715 this.with_constant_rib(
2717 ConstantHasGenerics::Yes,
2719 |this| this.visit_expr(expr),
2724 AssocItemKind::Fn(box Fn { generics, .. }) => {
2725 debug!("resolve_implementation AssocItemKind::Fn");
2726 // We also need a new scope for the impl item type parameters.
2727 self.with_generic_param_rib(
2730 LifetimeRibKind::Generics {
2732 span: generics.span,
2733 kind: LifetimeBinderKind::Function,
2736 // If this is a trait impl, ensure the method
2738 this.check_trait_item(
2745 |i, s, c| MethodNotMemberOfTrait(i, s, c),
2748 visit::walk_assoc_item(this, item, AssocCtxt::Impl)
2752 AssocItemKind::Type(box TyAlias { generics, .. }) => {
2753 debug!("resolve_implementation AssocItemKind::Type");
2754 // We also need a new scope for the impl item type parameters.
2755 self.with_generic_param_rib(
2758 LifetimeRibKind::Generics {
2760 span: generics.span,
2761 kind: LifetimeBinderKind::Item,
2764 this.with_lifetime_rib(LifetimeRibKind::AnonymousReportError, |this| {
2765 // If this is a trait impl, ensure the type
2767 this.check_trait_item(
2774 |i, s, c| TypeNotMemberOfTrait(i, s, c),
2777 visit::walk_assoc_item(this, item, AssocCtxt::Impl)
2782 AssocItemKind::MacCall(_) => {
2783 panic!("unexpanded macro in resolve!")
2788 fn check_trait_item<F>(
2792 kind: &AssocItemKind,
2795 seen_trait_items: &mut FxHashMap<DefId, Span>,
2798 F: FnOnce(Ident, String, Option<Symbol>) -> ResolutionError<'a>,
2800 // If there is a TraitRef in scope for an impl, then the method must be in the trait.
2801 let Some((module, _)) = &self.current_trait_ref else { return; };
2802 ident.span.normalize_to_macros_2_0_and_adjust(module.expansion);
2803 let key = self.r.new_key(ident, ns);
2804 let mut binding = self.r.resolution(module, key).try_borrow().ok().and_then(|r| r.binding);
2806 if binding.is_none() {
2807 // We could not find the trait item in the correct namespace.
2808 // Check the other namespace to report an error.
2814 let key = self.r.new_key(ident, ns);
2815 binding = self.r.resolution(module, key).try_borrow().ok().and_then(|r| r.binding);
2818 let Some(binding) = binding else {
2819 // We could not find the method: report an error.
2820 let candidate = self.find_similarly_named_assoc_item(ident.name, kind);
2821 let path = &self.current_trait_ref.as_ref().unwrap().1.path;
2822 let path_names = path_names_to_string(path);
2823 self.report_error(span, err(ident, path_names, candidate));
2827 let res = binding.res();
2828 let Res::Def(def_kind, id_in_trait) = res else { bug!() };
2830 match seen_trait_items.entry(id_in_trait) {
2831 Entry::Occupied(entry) => {
2834 ResolutionError::TraitImplDuplicate {
2836 old_span: *entry.get(),
2837 trait_item_span: binding.span,
2842 Entry::Vacant(entry) => {
2847 match (def_kind, kind) {
2848 (DefKind::AssocTy, AssocItemKind::Type(..))
2849 | (DefKind::AssocFn, AssocItemKind::Fn(..))
2850 | (DefKind::AssocConst, AssocItemKind::Const(..)) => {
2851 self.r.record_partial_res(id, PartialRes::new(res));
2857 // The method kind does not correspond to what appeared in the trait, report.
2858 let path = &self.current_trait_ref.as_ref().unwrap().1.path;
2859 let (code, kind) = match kind {
2860 AssocItemKind::Const(..) => (rustc_errors::error_code!(E0323), "const"),
2861 AssocItemKind::Fn(..) => (rustc_errors::error_code!(E0324), "method"),
2862 AssocItemKind::Type(..) => (rustc_errors::error_code!(E0325), "type"),
2863 AssocItemKind::MacCall(..) => span_bug!(span, "unexpanded macro"),
2865 let trait_path = path_names_to_string(path);
2868 ResolutionError::TraitImplMismatch {
2873 trait_item_span: binding.span,
2878 fn resolve_params(&mut self, params: &'ast [Param]) {
2879 let mut bindings = smallvec![(PatBoundCtx::Product, Default::default())];
2880 self.with_lifetime_rib(LifetimeRibKind::Elided(LifetimeRes::Infer), |this| {
2881 for Param { pat, .. } in params {
2882 this.resolve_pattern(pat, PatternSource::FnParam, &mut bindings);
2885 for Param { ty, .. } in params {
2890 fn resolve_local(&mut self, local: &'ast Local) {
2891 debug!("resolving local ({:?})", local);
2892 // Resolve the type.
2893 walk_list!(self, visit_ty, &local.ty);
2895 // Resolve the initializer.
2896 if let Some((init, els)) = local.kind.init_else_opt() {
2897 self.visit_expr(init);
2899 // Resolve the `else` block
2900 if let Some(els) = els {
2901 self.visit_block(els);
2905 // Resolve the pattern.
2906 self.resolve_pattern_top(&local.pat, PatternSource::Let);
2909 /// build a map from pattern identifiers to binding-info's.
2910 /// this is done hygienically. This could arise for a macro
2911 /// that expands into an or-pattern where one 'x' was from the
2912 /// user and one 'x' came from the macro.
2913 fn binding_mode_map(&mut self, pat: &Pat) -> BindingMap {
2914 let mut binding_map = FxHashMap::default();
2916 pat.walk(&mut |pat| {
2918 PatKind::Ident(annotation, ident, ref sub_pat)
2919 if sub_pat.is_some() || self.is_base_res_local(pat.id) =>
2921 binding_map.insert(ident, BindingInfo { span: ident.span, annotation });
2923 PatKind::Or(ref ps) => {
2924 // Check the consistency of this or-pattern and
2925 // then add all bindings to the larger map.
2926 for bm in self.check_consistent_bindings(ps) {
2927 binding_map.extend(bm);
2940 fn is_base_res_local(&self, nid: NodeId) -> bool {
2942 self.r.partial_res_map.get(&nid).map(|res| res.expect_full_res()),
2943 Some(Res::Local(..))
2947 /// Checks that all of the arms in an or-pattern have exactly the
2948 /// same set of bindings, with the same binding modes for each.
2949 fn check_consistent_bindings(&mut self, pats: &[P<Pat>]) -> Vec<BindingMap> {
2950 let mut missing_vars = FxHashMap::default();
2951 let mut inconsistent_vars = FxHashMap::default();
2953 // 1) Compute the binding maps of all arms.
2954 let maps = pats.iter().map(|pat| self.binding_mode_map(pat)).collect::<Vec<_>>();
2956 // 2) Record any missing bindings or binding mode inconsistencies.
2957 for (map_outer, pat_outer) in pats.iter().enumerate().map(|(idx, pat)| (&maps[idx], pat)) {
2958 // Check against all arms except for the same pattern which is always self-consistent.
2962 .filter(|(_, pat)| pat.id != pat_outer.id)
2963 .flat_map(|(idx, _)| maps[idx].iter())
2964 .map(|(key, binding)| (key.name, map_outer.get(&key), binding));
2966 for (name, info, &binding_inner) in inners {
2969 // The inner binding is missing in the outer.
2971 missing_vars.entry(name).or_insert_with(|| BindingError {
2973 origin: BTreeSet::new(),
2974 target: BTreeSet::new(),
2975 could_be_path: name.as_str().starts_with(char::is_uppercase),
2977 binding_error.origin.insert(binding_inner.span);
2978 binding_error.target.insert(pat_outer.span);
2980 Some(binding_outer) => {
2981 if binding_outer.annotation != binding_inner.annotation {
2982 // The binding modes in the outer and inner bindings differ.
2985 .or_insert((binding_inner.span, binding_outer.span));
2992 // 3) Report all missing variables we found.
2993 let mut missing_vars = missing_vars.into_iter().collect::<Vec<_>>();
2994 missing_vars.sort_by_key(|&(sym, ref _err)| sym);
2996 for (name, mut v) in missing_vars.into_iter() {
2997 if inconsistent_vars.contains_key(&name) {
2998 v.could_be_path = false;
3001 *v.origin.iter().next().unwrap(),
3002 ResolutionError::VariableNotBoundInPattern(v, self.parent_scope),
3006 // 4) Report all inconsistencies in binding modes we found.
3007 let mut inconsistent_vars = inconsistent_vars.iter().collect::<Vec<_>>();
3008 inconsistent_vars.sort();
3009 for (name, v) in inconsistent_vars {
3010 self.report_error(v.0, ResolutionError::VariableBoundWithDifferentMode(*name, v.1));
3013 // 5) Finally bubble up all the binding maps.
3017 /// Check the consistency of the outermost or-patterns.
3018 fn check_consistent_bindings_top(&mut self, pat: &'ast Pat) {
3019 pat.walk(&mut |pat| match pat.kind {
3020 PatKind::Or(ref ps) => {
3021 self.check_consistent_bindings(ps);
3028 fn resolve_arm(&mut self, arm: &'ast Arm) {
3029 self.with_rib(ValueNS, NormalRibKind, |this| {
3030 this.resolve_pattern_top(&arm.pat, PatternSource::Match);
3031 walk_list!(this, visit_expr, &arm.guard);
3032 this.visit_expr(&arm.body);
3036 /// Arising from `source`, resolve a top level pattern.
3037 fn resolve_pattern_top(&mut self, pat: &'ast Pat, pat_src: PatternSource) {
3038 let mut bindings = smallvec![(PatBoundCtx::Product, Default::default())];
3039 self.resolve_pattern(pat, pat_src, &mut bindings);
3045 pat_src: PatternSource,
3046 bindings: &mut SmallVec<[(PatBoundCtx, FxHashSet<Ident>); 1]>,
3048 // We walk the pattern before declaring the pattern's inner bindings,
3049 // so that we avoid resolving a literal expression to a binding defined
3051 visit::walk_pat(self, pat);
3052 self.resolve_pattern_inner(pat, pat_src, bindings);
3053 // This has to happen *after* we determine which pat_idents are variants:
3054 self.check_consistent_bindings_top(pat);
3057 /// Resolve bindings in a pattern. This is a helper to `resolve_pattern`.
3061 /// A stack of sets of bindings accumulated.
3063 /// In each set, `PatBoundCtx::Product` denotes that a found binding in it should
3064 /// be interpreted as re-binding an already bound binding. This results in an error.
3065 /// Meanwhile, `PatBound::Or` denotes that a found binding in the set should result
3066 /// in reusing this binding rather than creating a fresh one.
3068 /// When called at the top level, the stack must have a single element
3069 /// with `PatBound::Product`. Otherwise, pushing to the stack happens as
3070 /// or-patterns (`p_0 | ... | p_n`) are encountered and the context needs
3071 /// to be switched to `PatBoundCtx::Or` and then `PatBoundCtx::Product` for each `p_i`.
3072 /// When each `p_i` has been dealt with, the top set is merged with its parent.
3073 /// When a whole or-pattern has been dealt with, the thing happens.
3075 /// See the implementation and `fresh_binding` for more details.
3076 fn resolve_pattern_inner(
3079 pat_src: PatternSource,
3080 bindings: &mut SmallVec<[(PatBoundCtx, FxHashSet<Ident>); 1]>,
3082 // Visit all direct subpatterns of this pattern.
3083 pat.walk(&mut |pat| {
3084 debug!("resolve_pattern pat={:?} node={:?}", pat, pat.kind);
3086 PatKind::Ident(bmode, ident, ref sub) => {
3087 // First try to resolve the identifier as some existing entity,
3088 // then fall back to a fresh binding.
3089 let has_sub = sub.is_some();
3091 .try_resolve_as_non_binding(pat_src, bmode, ident, has_sub)
3092 .unwrap_or_else(|| self.fresh_binding(ident, pat.id, pat_src, bindings));
3093 self.r.record_partial_res(pat.id, PartialRes::new(res));
3094 self.r.record_pat_span(pat.id, pat.span);
3096 PatKind::TupleStruct(ref qself, ref path, ref sub_patterns) => {
3097 self.smart_resolve_path(
3101 PathSource::TupleStruct(
3103 self.r.arenas.alloc_pattern_spans(sub_patterns.iter().map(|p| p.span)),
3107 PatKind::Path(ref qself, ref path) => {
3108 self.smart_resolve_path(pat.id, qself, path, PathSource::Pat);
3110 PatKind::Struct(ref qself, ref path, ..) => {
3111 self.smart_resolve_path(pat.id, qself, path, PathSource::Struct);
3113 PatKind::Or(ref ps) => {
3114 // Add a new set of bindings to the stack. `Or` here records that when a
3115 // binding already exists in this set, it should not result in an error because
3116 // `V1(a) | V2(a)` must be allowed and are checked for consistency later.
3117 bindings.push((PatBoundCtx::Or, Default::default()));
3119 // Now we need to switch back to a product context so that each
3120 // part of the or-pattern internally rejects already bound names.
3121 // For example, `V1(a) | V2(a, a)` and `V1(a, a) | V2(a)` are bad.
3122 bindings.push((PatBoundCtx::Product, Default::default()));
3123 self.resolve_pattern_inner(p, pat_src, bindings);
3124 // Move up the non-overlapping bindings to the or-pattern.
3125 // Existing bindings just get "merged".
3126 let collected = bindings.pop().unwrap().1;
3127 bindings.last_mut().unwrap().1.extend(collected);
3129 // This or-pattern itself can itself be part of a product,
3130 // e.g. `(V1(a) | V2(a), a)` or `(a, V1(a) | V2(a))`.
3131 // Both cases bind `a` again in a product pattern and must be rejected.
3132 let collected = bindings.pop().unwrap().1;
3133 bindings.last_mut().unwrap().1.extend(collected);
3135 // Prevent visiting `ps` as we've already done so above.
3148 pat_src: PatternSource,
3149 bindings: &mut SmallVec<[(PatBoundCtx, FxHashSet<Ident>); 1]>,
3151 // Add the binding to the local ribs, if it doesn't already exist in the bindings map.
3152 // (We must not add it if it's in the bindings map because that breaks the assumptions
3153 // later passes make about or-patterns.)
3154 let ident = ident.normalize_to_macro_rules();
3156 let mut bound_iter = bindings.iter().filter(|(_, set)| set.contains(&ident));
3157 // Already bound in a product pattern? e.g. `(a, a)` which is not allowed.
3158 let already_bound_and = bound_iter.clone().any(|(ctx, _)| *ctx == PatBoundCtx::Product);
3159 // Already bound in an or-pattern? e.g. `V1(a) | V2(a)`.
3160 // This is *required* for consistency which is checked later.
3161 let already_bound_or = bound_iter.any(|(ctx, _)| *ctx == PatBoundCtx::Or);
3163 if already_bound_and {
3164 // Overlap in a product pattern somewhere; report an error.
3165 use ResolutionError::*;
3166 let error = match pat_src {
3167 // `fn f(a: u8, a: u8)`:
3168 PatternSource::FnParam => IdentifierBoundMoreThanOnceInParameterList,
3170 _ => IdentifierBoundMoreThanOnceInSamePattern,
3172 self.report_error(ident.span, error(ident.name));
3175 // Record as bound if it's valid:
3176 let ident_valid = ident.name != kw::Empty;
3178 bindings.last_mut().unwrap().1.insert(ident);
3181 if already_bound_or {
3182 // `Variant1(a) | Variant2(a)`, ok
3183 // Reuse definition from the first `a`.
3184 self.innermost_rib_bindings(ValueNS)[&ident]
3186 let res = Res::Local(pat_id);
3188 // A completely fresh binding add to the set if it's valid.
3189 self.innermost_rib_bindings(ValueNS).insert(ident, res);
3195 fn innermost_rib_bindings(&mut self, ns: Namespace) -> &mut IdentMap<Res> {
3196 &mut self.ribs[ns].last_mut().unwrap().bindings
3199 fn try_resolve_as_non_binding(
3201 pat_src: PatternSource,
3202 ann: BindingAnnotation,
3206 // An immutable (no `mut`) by-value (no `ref`) binding pattern without
3207 // a sub pattern (no `@ $pat`) is syntactically ambiguous as it could
3208 // also be interpreted as a path to e.g. a constant, variant, etc.
3209 let is_syntactic_ambiguity = !has_sub && ann == BindingAnnotation::NONE;
3211 let ls_binding = self.maybe_resolve_ident_in_lexical_scope(ident, ValueNS)?;
3212 let (res, binding) = match ls_binding {
3213 LexicalScopeBinding::Item(binding)
3214 if is_syntactic_ambiguity && binding.is_ambiguity() =>
3216 // For ambiguous bindings we don't know all their definitions and cannot check
3217 // whether they can be shadowed by fresh bindings or not, so force an error.
3218 // issues/33118#issuecomment-233962221 (see below) still applies here,
3219 // but we have to ignore it for backward compatibility.
3220 self.r.record_use(ident, binding, false);
3223 LexicalScopeBinding::Item(binding) => (binding.res(), Some(binding)),
3224 LexicalScopeBinding::Res(res) => (res, None),
3228 Res::SelfCtor(_) // See #70549.
3230 DefKind::Ctor(_, CtorKind::Const) | DefKind::Const | DefKind::ConstParam,
3232 ) if is_syntactic_ambiguity => {
3233 // Disambiguate in favor of a unit struct/variant or constant pattern.
3234 if let Some(binding) = binding {
3235 self.r.record_use(ident, binding, false);
3239 Res::Def(DefKind::Ctor(..) | DefKind::Const | DefKind::Static(_), _) => {
3240 // This is unambiguously a fresh binding, either syntactically
3241 // (e.g., `IDENT @ PAT` or `ref IDENT`) or because `IDENT` resolves
3242 // to something unusable as a pattern (e.g., constructor function),
3243 // but we still conservatively report an error, see
3244 // issues/33118#issuecomment-233962221 for one reason why.
3245 let binding = binding.expect("no binding for a ctor or static");
3248 ResolutionError::BindingShadowsSomethingUnacceptable {
3249 shadowing_binding: pat_src,
3251 participle: if binding.is_import() { "imported" } else { "defined" },
3252 article: binding.res().article(),
3253 shadowed_binding: binding.res(),
3254 shadowed_binding_span: binding.span,
3259 Res::Def(DefKind::ConstParam, def_id) => {
3260 // Same as for DefKind::Const above, but here, `binding` is `None`, so we
3261 // have to construct the error differently
3264 ResolutionError::BindingShadowsSomethingUnacceptable {
3265 shadowing_binding: pat_src,
3267 participle: "defined",
3268 article: res.article(),
3269 shadowed_binding: res,
3270 shadowed_binding_span: self.r.opt_span(def_id).expect("const parameter defined outside of local crate"),
3275 Res::Def(DefKind::Fn, _) | Res::Local(..) | Res::Err => {
3276 // These entities are explicitly allowed to be shadowed by fresh bindings.
3279 Res::SelfCtor(_) => {
3280 // We resolve `Self` in pattern position as an ident sometimes during recovery,
3281 // so delay a bug instead of ICEing.
3282 self.r.session.delay_span_bug(
3284 "unexpected `SelfCtor` in pattern, expected identifier"
3290 "unexpected resolution for an identifier in pattern: {:?}",
3296 // High-level and context dependent path resolution routine.
3297 // Resolves the path and records the resolution into definition map.
3298 // If resolution fails tries several techniques to find likely
3299 // resolution candidates, suggest imports or other help, and report
3300 // errors in user friendly way.
3301 fn smart_resolve_path(
3304 qself: &Option<P<QSelf>>,
3306 source: PathSource<'ast>,
3308 self.smart_resolve_path_fragment(
3310 &Segment::from_path(path),
3312 Finalize::new(id, path.span),
3316 fn smart_resolve_path_fragment(
3318 qself: &Option<P<QSelf>>,
3320 source: PathSource<'ast>,
3324 "smart_resolve_path_fragment(qself={:?}, path={:?}, finalize={:?})",
3325 qself, path, finalize,
3327 let ns = source.namespace();
3329 let Finalize { node_id, path_span, .. } = finalize;
3330 let report_errors = |this: &mut Self, res: Option<Res>| {
3331 if this.should_report_errs() {
3332 let (err, candidates) =
3333 this.smart_resolve_report_errors(path, path_span, source, res);
3335 let def_id = this.parent_scope.module.nearest_parent_mod();
3336 let instead = res.is_some();
3338 if res.is_none() { this.report_missing_type_error(path) } else { None };
3340 this.r.use_injections.push(UseError {
3347 is_call: source.is_call(),
3351 PartialRes::new(Res::Err)
3354 // For paths originating from calls (like in `HashMap::new()`), tries
3355 // to enrich the plain `failed to resolve: ...` message with hints
3356 // about possible missing imports.
3358 // Similar thing, for types, happens in `report_errors` above.
3359 let report_errors_for_call = |this: &mut Self, parent_err: Spanned<ResolutionError<'a>>| {
3360 if !source.is_call() {
3361 return Some(parent_err);
3364 // Before we start looking for candidates, we have to get our hands
3365 // on the type user is trying to perform invocation on; basically:
3366 // we're transforming `HashMap::new` into just `HashMap`.
3367 let path = match path.split_last() {
3368 Some((_, path)) if !path.is_empty() => path,
3369 _ => return Some(parent_err),
3372 let (mut err, candidates) =
3373 this.smart_resolve_report_errors(path, path_span, PathSource::Type, None);
3375 // There are two different error messages user might receive at
3377 // - E0412 cannot find type `{}` in this scope
3378 // - E0433 failed to resolve: use of undeclared type or module `{}`
3380 // The first one is emitted for paths in type-position, and the
3381 // latter one - for paths in expression-position.
3383 // Thus (since we're in expression-position at this point), not to
3384 // confuse the user, we want to keep the *message* from E0433 (so
3385 // `parent_err`), but we want *hints* from E0412 (so `err`).
3387 // And that's what happens below - we're just mixing both messages
3388 // into a single one.
3389 let mut parent_err = this.r.into_struct_error(parent_err.span, parent_err.node);
3391 // overwrite all properties with the parent's error message
3392 err.message = take(&mut parent_err.message);
3393 err.code = take(&mut parent_err.code);
3394 swap(&mut err.span, &mut parent_err.span);
3395 err.children = take(&mut parent_err.children);
3396 err.sort_span = parent_err.sort_span;
3397 err.is_lint = parent_err.is_lint;
3399 // merge the parent's suggestions with the typo suggestions
3400 fn append_result<T, E>(res1: &mut Result<Vec<T>, E>, res2: Result<Vec<T>, E>) {
3402 Ok(vec1) => match res2 {
3403 Ok(mut vec2) => vec1.append(&mut vec2),
3404 Err(e) => *res1 = Err(e),
3409 append_result(&mut err.suggestions, parent_err.suggestions.clone());
3411 parent_err.cancel();
3413 let def_id = this.parent_scope.module.nearest_parent_mod();
3415 if this.should_report_errs() {
3416 if candidates.is_empty() {
3417 // When there is no suggested imports, we can just emit the error
3418 // and suggestions immediately. Note that we bypass the usually error
3419 // reporting routine (ie via `self.r.report_error`) because we need
3420 // to post-process the `ResolutionError` above.
3423 // If there are suggested imports, the error reporting is delayed
3424 this.r.use_injections.push(UseError {
3431 is_call: source.is_call(),
3438 // We don't return `Some(parent_err)` here, because the error will
3439 // be already printed either immediately or as part of the `use` injections
3443 let partial_res = match self.resolve_qpath_anywhere(
3448 source.defer_to_typeck(),
3451 Ok(Some(partial_res)) if let Some(res) = partial_res.full_res() => {
3452 if source.is_expected(res) || res == Res::Err {
3455 report_errors(self, Some(res))
3459 Ok(Some(partial_res)) if source.defer_to_typeck() => {
3460 // Not fully resolved associated item `T::A::B` or `<T as Tr>::A::B`
3461 // or `<T>::A::B`. If `B` should be resolved in value namespace then
3462 // it needs to be added to the trait map.
3464 let item_name = path.last().unwrap().ident;
3465 let traits = self.traits_in_scope(item_name, ns);
3466 self.r.trait_map.insert(node_id, traits);
3469 if PrimTy::from_name(path[0].ident.name).is_some() {
3470 let mut std_path = Vec::with_capacity(1 + path.len());
3472 std_path.push(Segment::from_ident(Ident::with_dummy_span(sym::std)));
3473 std_path.extend(path);
3474 if let PathResult::Module(_) | PathResult::NonModule(_) =
3475 self.resolve_path(&std_path, Some(ns), None)
3477 // Check if we wrote `str::from_utf8` instead of `std::str::from_utf8`
3479 path.iter().last().map_or(path_span, |segment| segment.ident.span);
3481 self.r.confused_type_with_std_module.insert(item_span, path_span);
3482 self.r.confused_type_with_std_module.insert(path_span, path_span);
3490 if let Some(err) = report_errors_for_call(self, err) {
3491 self.report_error(err.span, err.node);
3494 PartialRes::new(Res::Err)
3497 _ => report_errors(self, None),
3500 if !matches!(source, PathSource::TraitItem(..)) {
3501 // Avoid recording definition of `A::B` in `<T as A>::B::C`.
3502 self.r.record_partial_res(node_id, partial_res);
3503 self.resolve_elided_lifetimes_in_path(node_id, partial_res, path, source, path_span);
3509 fn self_type_is_available(&mut self) -> bool {
3511 .maybe_resolve_ident_in_lexical_scope(Ident::with_dummy_span(kw::SelfUpper), TypeNS);
3512 if let Some(LexicalScopeBinding::Res(res)) = binding { res != Res::Err } else { false }
3515 fn self_value_is_available(&mut self, self_span: Span) -> bool {
3516 let ident = Ident::new(kw::SelfLower, self_span);
3517 let binding = self.maybe_resolve_ident_in_lexical_scope(ident, ValueNS);
3518 if let Some(LexicalScopeBinding::Res(res)) = binding { res != Res::Err } else { false }
3521 /// A wrapper around [`Resolver::report_error`].
3523 /// This doesn't emit errors for function bodies if this is rustdoc.
3524 fn report_error(&mut self, span: Span, resolution_error: ResolutionError<'a>) {
3525 if self.should_report_errs() {
3526 self.r.report_error(span, resolution_error);
3531 /// If we're actually rustdoc then avoid giving a name resolution error for `cfg()` items.
3532 fn should_report_errs(&self) -> bool {
3533 !(self.r.session.opts.actually_rustdoc && self.in_func_body)
3536 // Resolve in alternative namespaces if resolution in the primary namespace fails.
3537 fn resolve_qpath_anywhere(
3539 qself: &Option<P<QSelf>>,
3541 primary_ns: Namespace,
3543 defer_to_typeck: bool,
3545 ) -> Result<Option<PartialRes>, Spanned<ResolutionError<'a>>> {
3546 let mut fin_res = None;
3548 for (i, &ns) in [primary_ns, TypeNS, ValueNS].iter().enumerate() {
3549 if i == 0 || ns != primary_ns {
3550 match self.resolve_qpath(qself, path, ns, finalize)? {
3552 if partial_res.unresolved_segments() == 0 || defer_to_typeck =>
3554 return Ok(Some(partial_res));
3557 if fin_res.is_none() {
3558 fin_res = partial_res;
3565 assert!(primary_ns != MacroNS);
3567 if qself.is_none() {
3568 let path_seg = |seg: &Segment| PathSegment::from_ident(seg.ident);
3569 let path = Path { segments: path.iter().map(path_seg).collect(), span, tokens: None };
3570 if let Ok((_, res)) =
3571 self.r.resolve_macro_path(&path, None, &self.parent_scope, false, false)
3573 return Ok(Some(PartialRes::new(res)));
3580 /// Handles paths that may refer to associated items.
3583 qself: &Option<P<QSelf>>,
3587 ) -> Result<Option<PartialRes>, Spanned<ResolutionError<'a>>> {
3589 "resolve_qpath(qself={:?}, path={:?}, ns={:?}, finalize={:?})",
3590 qself, path, ns, finalize,
3593 if let Some(qself) = qself {
3594 if qself.position == 0 {
3595 // This is a case like `<T>::B`, where there is no
3596 // trait to resolve. In that case, we leave the `B`
3597 // segment to be resolved by type-check.
3598 return Ok(Some(PartialRes::with_unresolved_segments(
3599 Res::Def(DefKind::Mod, CRATE_DEF_ID.to_def_id()),
3604 // Make sure `A::B` in `<T as A::B>::C` is a trait item.
3606 // Currently, `path` names the full item (`A::B::C`, in
3607 // our example). so we extract the prefix of that that is
3608 // the trait (the slice upto and including
3609 // `qself.position`). And then we recursively resolve that,
3610 // but with `qself` set to `None`.
3611 let ns = if qself.position + 1 == path.len() { ns } else { TypeNS };
3612 let partial_res = self.smart_resolve_path_fragment(
3614 &path[..=qself.position],
3615 PathSource::TraitItem(ns),
3616 Finalize::with_root_span(finalize.node_id, finalize.path_span, qself.path_span),
3619 // The remaining segments (the `C` in our example) will
3620 // have to be resolved by type-check, since that requires doing
3621 // trait resolution.
3622 return Ok(Some(PartialRes::with_unresolved_segments(
3623 partial_res.base_res(),
3624 partial_res.unresolved_segments() + path.len() - qself.position - 1,
3628 let result = match self.resolve_path(&path, Some(ns), Some(finalize)) {
3629 PathResult::NonModule(path_res) => path_res,
3630 PathResult::Module(ModuleOrUniformRoot::Module(module)) if !module.is_normal() => {
3631 PartialRes::new(module.res().unwrap())
3633 // In `a(::assoc_item)*` `a` cannot be a module. If `a` does resolve to a module we
3634 // don't report an error right away, but try to fallback to a primitive type.
3635 // So, we are still able to successfully resolve something like
3637 // use std::u8; // bring module u8 in scope
3638 // fn f() -> u8 { // OK, resolves to primitive u8, not to std::u8
3639 // u8::max_value() // OK, resolves to associated function <u8>::max_value,
3640 // // not to non-existent std::u8::max_value
3643 // Such behavior is required for backward compatibility.
3644 // The same fallback is used when `a` resolves to nothing.
3645 PathResult::Module(ModuleOrUniformRoot::Module(_)) | PathResult::Failed { .. }
3646 if (ns == TypeNS || path.len() > 1)
3647 && PrimTy::from_name(path[0].ident.name).is_some() =>
3649 let prim = PrimTy::from_name(path[0].ident.name).unwrap();
3650 PartialRes::with_unresolved_segments(Res::PrimTy(prim), path.len() - 1)
3652 PathResult::Module(ModuleOrUniformRoot::Module(module)) => {
3653 PartialRes::new(module.res().unwrap())
3655 PathResult::Failed { is_error_from_last_segment: false, span, label, suggestion } => {
3656 return Err(respan(span, ResolutionError::FailedToResolve { label, suggestion }));
3658 PathResult::Module(..) | PathResult::Failed { .. } => return Ok(None),
3659 PathResult::Indeterminate => bug!("indeterminate path result in resolve_qpath"),
3663 && let Some(res) = result.full_res()
3665 && path[0].ident.name != kw::PathRoot
3666 && path[0].ident.name != kw::DollarCrate
3668 let unqualified_result = {
3669 match self.resolve_path(&[*path.last().unwrap()], Some(ns), None) {
3670 PathResult::NonModule(path_res) => path_res.expect_full_res(),
3671 PathResult::Module(ModuleOrUniformRoot::Module(module)) => {
3672 module.res().unwrap()
3674 _ => return Ok(Some(result)),
3677 if res == unqualified_result {
3678 let lint = lint::builtin::UNUSED_QUALIFICATIONS;
3679 self.r.lint_buffer.buffer_lint(
3683 "unnecessary qualification",
3691 fn with_resolved_label(&mut self, label: Option<Label>, id: NodeId, f: impl FnOnce(&mut Self)) {
3692 if let Some(label) = label {
3693 if label.ident.as_str().as_bytes()[1] != b'_' {
3694 self.diagnostic_metadata.unused_labels.insert(id, label.ident.span);
3697 if let Ok((_, orig_span)) = self.resolve_label(label.ident) {
3698 diagnostics::signal_label_shadowing(self.r.session, orig_span, label.ident)
3701 self.with_label_rib(NormalRibKind, |this| {
3702 let ident = label.ident.normalize_to_macro_rules();
3703 this.label_ribs.last_mut().unwrap().bindings.insert(ident, id);
3711 fn resolve_labeled_block(&mut self, label: Option<Label>, id: NodeId, block: &'ast Block) {
3712 self.with_resolved_label(label, id, |this| this.visit_block(block));
3715 fn resolve_block(&mut self, block: &'ast Block) {
3716 debug!("(resolving block) entering block");
3717 // Move down in the graph, if there's an anonymous module rooted here.
3718 let orig_module = self.parent_scope.module;
3719 let anonymous_module = self.r.block_map.get(&block.id).cloned(); // clones a reference
3721 let mut num_macro_definition_ribs = 0;
3722 if let Some(anonymous_module) = anonymous_module {
3723 debug!("(resolving block) found anonymous module, moving down");
3724 self.ribs[ValueNS].push(Rib::new(ModuleRibKind(anonymous_module)));
3725 self.ribs[TypeNS].push(Rib::new(ModuleRibKind(anonymous_module)));
3726 self.parent_scope.module = anonymous_module;
3728 self.ribs[ValueNS].push(Rib::new(NormalRibKind));
3731 let prev = self.diagnostic_metadata.current_block_could_be_bare_struct_literal.take();
3732 if let (true, [Stmt { kind: StmtKind::Expr(expr), .. }]) =
3733 (block.could_be_bare_literal, &block.stmts[..])
3734 && let ExprKind::Type(..) = expr.kind
3736 self.diagnostic_metadata.current_block_could_be_bare_struct_literal =
3739 // Descend into the block.
3740 for stmt in &block.stmts {
3741 if let StmtKind::Item(ref item) = stmt.kind
3742 && let ItemKind::MacroDef(..) = item.kind {
3743 num_macro_definition_ribs += 1;
3744 let res = self.r.local_def_id(item.id).to_def_id();
3745 self.ribs[ValueNS].push(Rib::new(MacroDefinition(res)));
3746 self.label_ribs.push(Rib::new(MacroDefinition(res)));
3749 self.visit_stmt(stmt);
3751 self.diagnostic_metadata.current_block_could_be_bare_struct_literal = prev;
3754 self.parent_scope.module = orig_module;
3755 for _ in 0..num_macro_definition_ribs {
3756 self.ribs[ValueNS].pop();
3757 self.label_ribs.pop();
3759 self.ribs[ValueNS].pop();
3760 if anonymous_module.is_some() {
3761 self.ribs[TypeNS].pop();
3763 debug!("(resolving block) leaving block");
3766 fn resolve_anon_const(&mut self, constant: &'ast AnonConst, is_repeat: IsRepeatExpr) {
3767 debug!("resolve_anon_const {:?} is_repeat: {:?}", constant, is_repeat);
3768 self.with_constant_rib(
3770 if constant.value.is_potential_trivial_const_param() {
3771 ConstantHasGenerics::Yes
3773 ConstantHasGenerics::No
3776 |this| visit::walk_anon_const(this, constant),
3780 fn resolve_inline_const(&mut self, constant: &'ast AnonConst) {
3781 debug!("resolve_anon_const {constant:?}");
3782 self.with_constant_rib(IsRepeatExpr::No, ConstantHasGenerics::Yes, None, |this| {
3783 visit::walk_anon_const(this, constant)
3787 fn resolve_expr(&mut self, expr: &'ast Expr, parent: Option<&'ast Expr>) {
3788 // First, record candidate traits for this expression if it could
3789 // result in the invocation of a method call.
3791 self.record_candidate_traits_for_expr_if_necessary(expr);
3793 // Next, resolve the node.
3795 ExprKind::Path(ref qself, ref path) => {
3796 self.smart_resolve_path(expr.id, qself, path, PathSource::Expr(parent));
3797 visit::walk_expr(self, expr);
3800 ExprKind::Struct(ref se) => {
3801 self.smart_resolve_path(expr.id, &se.qself, &se.path, PathSource::Struct);
3802 visit::walk_expr(self, expr);
3805 ExprKind::Break(Some(label), _) | ExprKind::Continue(Some(label)) => {
3806 match self.resolve_label(label.ident) {
3807 Ok((node_id, _)) => {
3808 // Since this res is a label, it is never read.
3809 self.r.label_res_map.insert(expr.id, node_id);
3810 self.diagnostic_metadata.unused_labels.remove(&node_id);
3813 self.report_error(label.ident.span, error);
3817 // visit `break` argument if any
3818 visit::walk_expr(self, expr);
3821 ExprKind::Break(None, Some(ref e)) => {
3822 // We use this instead of `visit::walk_expr` to keep the parent expr around for
3823 // better diagnostics.
3824 self.resolve_expr(e, Some(&expr));
3827 ExprKind::Let(ref pat, ref scrutinee, _) => {
3828 self.visit_expr(scrutinee);
3829 self.resolve_pattern_top(pat, PatternSource::Let);
3832 ExprKind::If(ref cond, ref then, ref opt_else) => {
3833 self.with_rib(ValueNS, NormalRibKind, |this| {
3834 let old = this.diagnostic_metadata.in_if_condition.replace(cond);
3835 this.visit_expr(cond);
3836 this.diagnostic_metadata.in_if_condition = old;
3837 this.visit_block(then);
3839 if let Some(expr) = opt_else {
3840 self.visit_expr(expr);
3844 ExprKind::Loop(ref block, label, _) => {
3845 self.resolve_labeled_block(label, expr.id, &block)
3848 ExprKind::While(ref cond, ref block, label) => {
3849 self.with_resolved_label(label, expr.id, |this| {
3850 this.with_rib(ValueNS, NormalRibKind, |this| {
3851 let old = this.diagnostic_metadata.in_if_condition.replace(cond);
3852 this.visit_expr(cond);
3853 this.diagnostic_metadata.in_if_condition = old;
3854 this.visit_block(block);
3859 ExprKind::ForLoop(ref pat, ref iter_expr, ref block, label) => {
3860 self.visit_expr(iter_expr);
3861 self.with_rib(ValueNS, NormalRibKind, |this| {
3862 this.resolve_pattern_top(pat, PatternSource::For);
3863 this.resolve_labeled_block(label, expr.id, block);
3867 ExprKind::Block(ref block, label) => self.resolve_labeled_block(label, block.id, block),
3869 // Equivalent to `visit::walk_expr` + passing some context to children.
3870 ExprKind::Field(ref subexpression, _) => {
3871 self.resolve_expr(subexpression, Some(expr));
3873 ExprKind::MethodCall(box MethodCall { ref seg, ref receiver, ref args, .. }) => {
3874 self.resolve_expr(receiver, Some(expr));
3876 self.resolve_expr(arg, None);
3878 self.visit_path_segment(seg);
3881 ExprKind::Call(ref callee, ref arguments) => {
3882 self.resolve_expr(callee, Some(expr));
3883 let const_args = self.r.legacy_const_generic_args(callee).unwrap_or_default();
3884 for (idx, argument) in arguments.iter().enumerate() {
3885 // Constant arguments need to be treated as AnonConst since
3886 // that is how they will be later lowered to HIR.
3887 if const_args.contains(&idx) {
3888 self.with_constant_rib(
3890 if argument.is_potential_trivial_const_param() {
3891 ConstantHasGenerics::Yes
3893 ConstantHasGenerics::No
3897 this.resolve_expr(argument, None);
3901 self.resolve_expr(argument, None);
3905 ExprKind::Type(ref type_expr, ref ty) => {
3906 // `ParseSess::type_ascription_path_suggestions` keeps spans of colon tokens in
3907 // type ascription. Here we are trying to retrieve the span of the colon token as
3908 // well, but only if it's written without spaces `expr:Ty` and therefore confusable
3909 // with `expr::Ty`, only in this case it will match the span from
3910 // `type_ascription_path_suggestions`.
3911 self.diagnostic_metadata
3912 .current_type_ascription
3913 .push(type_expr.span.between(ty.span));
3914 visit::walk_expr(self, expr);
3915 self.diagnostic_metadata.current_type_ascription.pop();
3917 // `async |x| ...` gets desugared to `|x| async {...}`, so we need to
3918 // resolve the arguments within the proper scopes so that usages of them inside the
3919 // closure are detected as upvars rather than normal closure arg usages.
3920 ExprKind::Closure(box ast::Closure {
3921 asyncness: Async::Yes { .. },
3926 self.with_rib(ValueNS, NormalRibKind, |this| {
3927 this.with_label_rib(ClosureOrAsyncRibKind, |this| {
3928 // Resolve arguments:
3929 this.resolve_params(&fn_decl.inputs);
3930 // No need to resolve return type --
3931 // the outer closure return type is `FnRetTy::Default`.
3933 // Now resolve the inner closure
3935 // No need to resolve arguments: the inner closure has none.
3936 // Resolve the return type:
3937 visit::walk_fn_ret_ty(this, &fn_decl.output);
3939 this.visit_expr(body);
3944 // For closures, ClosureOrAsyncRibKind is added in visit_fn
3945 ExprKind::Closure(box ast::Closure {
3946 binder: ClosureBinder::For { ref generic_params, span },
3949 self.with_generic_param_rib(
3952 LifetimeRibKind::Generics {
3954 kind: LifetimeBinderKind::Closure,
3957 |this| visit::walk_expr(this, expr),
3960 ExprKind::Closure(..) => visit::walk_expr(self, expr),
3961 ExprKind::Async(..) => {
3962 self.with_label_rib(ClosureOrAsyncRibKind, |this| visit::walk_expr(this, expr));
3964 ExprKind::Repeat(ref elem, ref ct) => {
3965 self.visit_expr(elem);
3966 self.with_lifetime_rib(LifetimeRibKind::AnonConst, |this| {
3967 this.with_lifetime_rib(LifetimeRibKind::Elided(LifetimeRes::Static), |this| {
3968 this.resolve_anon_const(ct, IsRepeatExpr::Yes)
3972 ExprKind::ConstBlock(ref ct) => {
3973 self.resolve_inline_const(ct);
3975 ExprKind::Index(ref elem, ref idx) => {
3976 self.resolve_expr(elem, Some(expr));
3977 self.visit_expr(idx);
3979 ExprKind::Assign(ref lhs, ref rhs, _) => {
3980 if !self.diagnostic_metadata.is_assign_rhs {
3981 self.diagnostic_metadata.in_assignment = Some(expr);
3983 self.visit_expr(lhs);
3984 self.diagnostic_metadata.is_assign_rhs = true;
3985 self.diagnostic_metadata.in_assignment = None;
3986 self.visit_expr(rhs);
3987 self.diagnostic_metadata.is_assign_rhs = false;
3990 visit::walk_expr(self, expr);
3995 fn record_candidate_traits_for_expr_if_necessary(&mut self, expr: &'ast Expr) {
3997 ExprKind::Field(_, ident) => {
3998 // FIXME(#6890): Even though you can't treat a method like a
3999 // field, we need to add any trait methods we find that match
4000 // the field name so that we can do some nice error reporting
4001 // later on in typeck.
4002 let traits = self.traits_in_scope(ident, ValueNS);
4003 self.r.trait_map.insert(expr.id, traits);
4005 ExprKind::MethodCall(ref call) => {
4006 debug!("(recording candidate traits for expr) recording traits for {}", expr.id);
4007 let traits = self.traits_in_scope(call.seg.ident, ValueNS);
4008 self.r.trait_map.insert(expr.id, traits);
4016 fn traits_in_scope(&mut self, ident: Ident, ns: Namespace) -> Vec<TraitCandidate> {
4017 self.r.traits_in_scope(
4018 self.current_trait_ref.as_ref().map(|(module, _)| *module),
4021 Some((ident.name, ns)),
4025 /// Construct the list of in-scope lifetime parameters for async lowering.
4026 /// We include all lifetime parameters, either named or "Fresh".
4027 /// The order of those parameters does not matter, as long as it is
4029 fn record_lifetime_params_for_async(
4032 async_node_id: Option<(NodeId, Span)>,
4034 if let Some((async_node_id, span)) = async_node_id {
4035 let mut extra_lifetime_params =
4036 self.r.extra_lifetime_params_map.get(&fn_id).cloned().unwrap_or_default();
4037 for rib in self.lifetime_ribs.iter().rev() {
4038 extra_lifetime_params.extend(
4039 rib.bindings.iter().map(|(&ident, &(node_id, res))| (ident, node_id, res)),
4042 LifetimeRibKind::Item => break,
4043 LifetimeRibKind::AnonymousCreateParameter { binder, .. } => {
4044 if let Some(earlier_fresh) = self.r.extra_lifetime_params_map.get(&binder) {
4045 extra_lifetime_params.extend(earlier_fresh);
4048 LifetimeRibKind::Generics { .. } => {}
4050 // We are in a function definition. We should only find `Generics`
4051 // and `AnonymousCreateParameter` inside the innermost `Item`.
4052 span_bug!(span, "unexpected rib kind: {:?}", rib.kind)
4056 self.r.extra_lifetime_params_map.insert(async_node_id, extra_lifetime_params);
4061 struct LifetimeCountVisitor<'a, 'b> {
4062 r: &'b mut Resolver<'a>,
4065 /// Walks the whole crate in DFS order, visiting each item, counting the declared number of
4066 /// lifetime generic parameters.
4067 impl<'ast> Visitor<'ast> for LifetimeCountVisitor<'_, '_> {
4068 fn visit_item(&mut self, item: &'ast Item) {
4070 ItemKind::TyAlias(box TyAlias { ref generics, .. })
4071 | ItemKind::Fn(box Fn { ref generics, .. })
4072 | ItemKind::Enum(_, ref generics)
4073 | ItemKind::Struct(_, ref generics)
4074 | ItemKind::Union(_, ref generics)
4075 | ItemKind::Impl(box Impl { ref generics, .. })
4076 | ItemKind::Trait(box Trait { ref generics, .. })
4077 | ItemKind::TraitAlias(ref generics, _) => {
4078 let def_id = self.r.local_def_id(item.id);
4079 let count = generics
4082 .filter(|param| matches!(param.kind, ast::GenericParamKind::Lifetime { .. }))
4084 self.r.item_generics_num_lifetimes.insert(def_id, count);
4088 | ItemKind::ForeignMod(..)
4089 | ItemKind::Static(..)
4090 | ItemKind::Const(..)
4092 | ItemKind::ExternCrate(..)
4093 | ItemKind::MacroDef(..)
4094 | ItemKind::GlobalAsm(..)
4095 | ItemKind::MacCall(..) => {}
4097 visit::walk_item(self, item)
4101 impl<'a> Resolver<'a> {
4102 pub(crate) fn late_resolve_crate(&mut self, krate: &Crate) {
4103 visit::walk_crate(&mut LifetimeCountVisitor { r: self }, krate);
4104 let mut late_resolution_visitor = LateResolutionVisitor::new(self);
4105 visit::walk_crate(&mut late_resolution_visitor, krate);
4106 for (id, span) in late_resolution_visitor.diagnostic_metadata.unused_labels.iter() {
4107 self.lint_buffer.buffer_lint(lint::builtin::UNUSED_LABELS, *id, *span, "unused label");