1 // ignore-tidy-filelength
2 //! "Late resolution" is the pass that resolves most of names in a crate beside imports and macros.
3 //! It runs when the crate is fully expanded and its module structure is fully built.
4 //! So it just walks through the crate and resolves all the expressions, types, etc.
6 //! If you wonder why there's no `early.rs`, that's because it's split into three files -
7 //! `build_reduced_graph.rs`, `macros.rs` and `imports.rs`.
11 use crate::{path_names_to_string, BindingError, Finalize, LexicalScopeBinding};
12 use crate::{Module, ModuleOrUniformRoot, NameBinding, ParentScope, PathResult};
13 use crate::{ResolutionError, Resolver, Segment, UseError};
15 use rustc_ast::ptr::P;
16 use rustc_ast::visit::{self, AssocCtxt, BoundKind, FnCtxt, FnKind, Visitor};
18 use rustc_data_structures::fx::{FxHashMap, FxHashSet, FxIndexMap};
19 use rustc_errors::DiagnosticId;
20 use rustc_hir::def::Namespace::{self, *};
21 use rustc_hir::def::{self, CtorKind, DefKind, LifetimeRes, PartialRes, PerNS};
22 use rustc_hir::def_id::{DefId, LocalDefId, CRATE_DEF_ID};
23 use rustc_hir::{PrimTy, TraitCandidate};
24 use rustc_middle::middle::resolve_lifetime::Set1;
25 use rustc_middle::ty::DefIdTree;
26 use rustc_middle::{bug, span_bug};
27 use rustc_session::lint;
28 use rustc_span::symbol::{kw, sym, Ident, Symbol};
29 use rustc_span::{BytePos, Span};
30 use smallvec::{smallvec, SmallVec};
32 use rustc_span::source_map::{respan, Spanned};
33 use std::collections::{hash_map::Entry, BTreeSet};
34 use std::mem::{replace, take};
38 pub(crate) mod lifetimes;
40 type Res = def::Res<NodeId>;
42 type IdentMap<T> = FxHashMap<Ident, T>;
44 /// Map from the name in a pattern to its binding mode.
45 type BindingMap = IdentMap<BindingInfo>;
48 ElisionFnParameter, LifetimeElisionCandidate, MissingLifetime, MissingLifetimeKind,
51 #[derive(Copy, Clone, Debug)]
54 binding_mode: BindingMode,
57 #[derive(Copy, Clone, PartialEq, Eq, Debug)]
58 pub enum PatternSource {
65 #[derive(Copy, Clone, Debug, PartialEq, Eq)]
72 pub fn descr(self) -> &'static str {
74 PatternSource::Match => "match binding",
75 PatternSource::Let => "let binding",
76 PatternSource::For => "for binding",
77 PatternSource::FnParam => "function parameter",
82 /// Denotes whether the context for the set of already bound bindings is a `Product`
83 /// or `Or` context. This is used in e.g., `fresh_binding` and `resolve_pattern_inner`.
84 /// See those functions for more information.
87 /// A product pattern context, e.g., `Variant(a, b)`.
89 /// An or-pattern context, e.g., `p_0 | ... | p_n`.
93 /// Does this the item (from the item rib scope) allow generic parameters?
94 #[derive(Copy, Clone, Debug, Eq, PartialEq)]
95 pub(crate) enum HasGenericParams {
100 impl HasGenericParams {
101 fn force_yes_if(self, b: bool) -> Self {
102 if b { Self::Yes } else { self }
106 #[derive(Copy, Clone, Debug, Eq, PartialEq)]
107 pub(crate) enum ConstantItemKind {
112 /// The rib kind restricts certain accesses,
113 /// e.g. to a `Res::Local` of an outer item.
114 #[derive(Copy, Clone, Debug)]
115 pub(crate) enum RibKind<'a> {
116 /// No restriction needs to be applied.
119 /// We passed through an impl or trait and are now in one of its
120 /// methods or associated types. Allow references to ty params that impl or trait
121 /// binds. Disallow any other upvars (including other ty params that are
125 /// We passed through a closure. Disallow labels.
126 ClosureOrAsyncRibKind,
128 /// We passed through a function definition. Disallow upvars.
129 /// Permit only those const parameters that are specified in the function's generics.
132 /// We passed through an item scope. Disallow upvars.
133 ItemRibKind(HasGenericParams),
135 /// We're in a constant item. Can't refer to dynamic stuff.
137 /// The item may reference generic parameters in trivial constant expressions.
138 /// All other constants aren't allowed to use generic params at all.
139 ConstantItemRibKind(HasGenericParams, Option<(Ident, ConstantItemKind)>),
141 /// We passed through a module.
142 ModuleRibKind(Module<'a>),
144 /// We passed through a `macro_rules!` statement
145 MacroDefinition(DefId),
147 /// All bindings in this rib are generic parameters that can't be used
148 /// from the default of a generic parameter because they're not declared
149 /// before said generic parameter. Also see the `visit_generics` override.
150 ForwardGenericParamBanRibKind,
152 /// We are inside of the type of a const parameter. Can't refer to any
156 /// We are inside a `sym` inline assembly operand. Can only refer to
162 /// Whether this rib kind contains generic parameters, as opposed to local
164 pub(crate) fn contains_params(&self) -> bool {
167 | ClosureOrAsyncRibKind
169 | ConstantItemRibKind(..)
172 | ConstParamTyRibKind
173 | InlineAsmSymRibKind => false,
174 AssocItemRibKind | ItemRibKind(_) | ForwardGenericParamBanRibKind => true,
178 /// This rib forbids referring to labels defined in upwards ribs.
179 fn is_label_barrier(self) -> bool {
181 NormalRibKind | MacroDefinition(..) => false,
184 | ClosureOrAsyncRibKind
187 | ConstantItemRibKind(..)
189 | ForwardGenericParamBanRibKind
190 | ConstParamTyRibKind
191 | InlineAsmSymRibKind => true,
196 /// A single local scope.
198 /// A rib represents a scope names can live in. Note that these appear in many places, not just
199 /// around braces. At any place where the list of accessible names (of the given namespace)
200 /// changes or a new restrictions on the name accessibility are introduced, a new rib is put onto a
201 /// stack. This may be, for example, a `let` statement (because it introduces variables), a macro,
204 /// Different [rib kinds](enum@RibKind) are transparent for different names.
206 /// The resolution keeps a separate stack of ribs as it traverses the AST for each namespace. When
207 /// resolving, the name is looked up from inside out.
209 pub(crate) struct Rib<'a, R = Res> {
210 pub bindings: IdentMap<R>,
211 pub kind: RibKind<'a>,
214 impl<'a, R> Rib<'a, R> {
215 fn new(kind: RibKind<'a>) -> Rib<'a, R> {
216 Rib { bindings: Default::default(), kind }
220 #[derive(Clone, Copy, Debug)]
221 enum LifetimeUseSet {
222 One { use_span: Span, use_ctxt: visit::LifetimeCtxt },
226 #[derive(Copy, Clone, Debug)]
227 enum LifetimeRibKind {
228 /// This rib acts as a barrier to forbid reference to lifetimes of a parent item.
231 /// This rib declares generic parameters.
232 Generics { binder: NodeId, span: Span, kind: LifetimeBinderKind },
234 /// FIXME(const_generics): This patches over an ICE caused by non-'static lifetimes in const
235 /// generics. We are disallowing this until we can decide on how we want to handle non-'static
236 /// lifetimes in const generics. See issue #74052 for discussion.
239 /// Non-static lifetimes are prohibited in anonymous constants under `min_const_generics`.
240 /// This function will emit an error if `generic_const_exprs` is not enabled, the body identified by
241 /// `body_id` is an anonymous constant and `lifetime_ref` is non-static.
244 /// Create a new anonymous lifetime parameter and reference it.
246 /// If `report_in_path`, report an error when encountering lifetime elision in a path:
248 /// struct Foo<'a> { x: &'a () }
249 /// async fn foo(x: Foo) {}
252 /// Note: the error should not trigger when the elided lifetime is in a pattern or
253 /// expression-position path:
255 /// struct Foo<'a> { x: &'a () }
256 /// async fn foo(Foo { x: _ }: Foo<'_>) {}
258 AnonymousCreateParameter { binder: NodeId, report_in_path: bool },
260 /// Give a hard error when either `&` or `'_` is written. Used to
261 /// rule out things like `where T: Foo<'_>`. Does not imply an
262 /// error on default object bounds (e.g., `Box<dyn Foo>`).
263 AnonymousReportError,
265 /// Replace all anonymous lifetimes by provided lifetime.
268 /// Signal we cannot find which should be the anonymous lifetime.
272 #[derive(Copy, Clone, Debug)]
273 enum LifetimeBinderKind {
283 impl LifetimeBinderKind {
284 fn descr(self) -> &'static str {
285 use LifetimeBinderKind::*;
287 BareFnType => "type",
288 PolyTrait => "bound",
289 WhereBound => "bound",
291 ImplBlock => "impl block",
292 Function => "function",
293 Closure => "closure",
300 kind: LifetimeRibKind,
301 // We need to preserve insertion order for async fns.
302 bindings: FxIndexMap<Ident, (NodeId, LifetimeRes)>,
306 fn new(kind: LifetimeRibKind) -> LifetimeRib {
307 LifetimeRib { bindings: Default::default(), kind }
311 #[derive(Copy, Clone, PartialEq, Eq, Debug)]
312 pub(crate) enum AliasPossibility {
317 #[derive(Copy, Clone, Debug)]
318 pub(crate) enum PathSource<'a> {
319 // Type paths `Path`.
321 // Trait paths in bounds or impls.
322 Trait(AliasPossibility),
323 // Expression paths `path`, with optional parent context.
324 Expr(Option<&'a Expr>),
325 // Paths in path patterns `Path`.
327 // Paths in struct expressions and patterns `Path { .. }`.
329 // Paths in tuple struct patterns `Path(..)`.
330 TupleStruct(Span, &'a [Span]),
331 // `m::A::B` in `<T as m::A>::B::C`.
332 TraitItem(Namespace),
335 impl<'a> PathSource<'a> {
336 fn namespace(self) -> Namespace {
338 PathSource::Type | PathSource::Trait(_) | PathSource::Struct => TypeNS,
339 PathSource::Expr(..) | PathSource::Pat | PathSource::TupleStruct(..) => ValueNS,
340 PathSource::TraitItem(ns) => ns,
344 fn defer_to_typeck(self) -> bool {
347 | PathSource::Expr(..)
350 | PathSource::TupleStruct(..) => true,
351 PathSource::Trait(_) | PathSource::TraitItem(..) => false,
355 fn descr_expected(self) -> &'static str {
357 PathSource::Type => "type",
358 PathSource::Trait(_) => "trait",
359 PathSource::Pat => "unit struct, unit variant or constant",
360 PathSource::Struct => "struct, variant or union type",
361 PathSource::TupleStruct(..) => "tuple struct or tuple variant",
362 PathSource::TraitItem(ns) => match ns {
363 TypeNS => "associated type",
364 ValueNS => "method or associated constant",
365 MacroNS => bug!("associated macro"),
367 PathSource::Expr(parent) => match parent.as_ref().map(|p| &p.kind) {
368 // "function" here means "anything callable" rather than `DefKind::Fn`,
369 // this is not precise but usually more helpful than just "value".
370 Some(ExprKind::Call(call_expr, _)) => match &call_expr.kind {
371 // the case of `::some_crate()`
372 ExprKind::Path(_, path)
373 if path.segments.len() == 2
374 && path.segments[0].ident.name == kw::PathRoot =>
378 ExprKind::Path(_, path) => {
379 let mut msg = "function";
380 if let Some(segment) = path.segments.iter().last() {
381 if let Some(c) = segment.ident.to_string().chars().next() {
382 if c.is_uppercase() {
383 msg = "function, tuple struct or tuple variant";
396 fn is_call(self) -> bool {
397 matches!(self, PathSource::Expr(Some(&Expr { kind: ExprKind::Call(..), .. })))
400 pub(crate) fn is_expected(self, res: Res) -> bool {
402 PathSource::Type => matches!(
409 | DefKind::TraitAlias
414 | DefKind::ForeignTy,
419 PathSource::Trait(AliasPossibility::No) => matches!(res, Res::Def(DefKind::Trait, _)),
420 PathSource::Trait(AliasPossibility::Maybe) => {
421 matches!(res, Res::Def(DefKind::Trait | DefKind::TraitAlias, _))
423 PathSource::Expr(..) => matches!(
426 DefKind::Ctor(_, CtorKind::Const | CtorKind::Fn)
431 | DefKind::AssocConst
432 | DefKind::ConstParam,
438 res.expected_in_unit_struct_pat()
439 || matches!(res, Res::Def(DefKind::Const | DefKind::AssocConst, _))
441 PathSource::TupleStruct(..) => res.expected_in_tuple_struct_pat(),
442 PathSource::Struct => matches!(
451 ) | Res::SelfTy { .. }
453 PathSource::TraitItem(ns) => match res {
454 Res::Def(DefKind::AssocConst | DefKind::AssocFn, _) if ns == ValueNS => true,
455 Res::Def(DefKind::AssocTy, _) if ns == TypeNS => true,
461 fn error_code(self, has_unexpected_resolution: bool) -> DiagnosticId {
462 use rustc_errors::error_code;
463 match (self, has_unexpected_resolution) {
464 (PathSource::Trait(_), true) => error_code!(E0404),
465 (PathSource::Trait(_), false) => error_code!(E0405),
466 (PathSource::Type, true) => error_code!(E0573),
467 (PathSource::Type, false) => error_code!(E0412),
468 (PathSource::Struct, true) => error_code!(E0574),
469 (PathSource::Struct, false) => error_code!(E0422),
470 (PathSource::Expr(..), true) => error_code!(E0423),
471 (PathSource::Expr(..), false) => error_code!(E0425),
472 (PathSource::Pat | PathSource::TupleStruct(..), true) => error_code!(E0532),
473 (PathSource::Pat | PathSource::TupleStruct(..), false) => error_code!(E0531),
474 (PathSource::TraitItem(..), true) => error_code!(E0575),
475 (PathSource::TraitItem(..), false) => error_code!(E0576),
481 struct DiagnosticMetadata<'ast> {
482 /// The current trait's associated items' ident, used for diagnostic suggestions.
483 current_trait_assoc_items: Option<&'ast [P<AssocItem>]>,
485 /// The current self type if inside an impl (used for better errors).
486 current_self_type: Option<Ty>,
488 /// The current self item if inside an ADT (used for better errors).
489 current_self_item: Option<NodeId>,
491 /// The current trait (used to suggest).
492 current_item: Option<&'ast Item>,
494 /// When processing generics and encountering a type not found, suggest introducing a type
496 currently_processing_generics: bool,
498 /// The current enclosing (non-closure) function (used for better errors).
499 current_function: Option<(FnKind<'ast>, Span)>,
501 /// A list of labels as of yet unused. Labels will be removed from this map when
502 /// they are used (in a `break` or `continue` statement)
503 unused_labels: FxHashMap<NodeId, Span>,
505 /// Only used for better errors on `fn(): fn()`.
506 current_type_ascription: Vec<Span>,
508 /// Only used for better errors on `let x = { foo: bar };`.
509 /// In the case of a parse error with `let x = { foo: bar, };`, this isn't needed, it's only
510 /// needed for cases where this parses as a correct type ascription.
511 current_block_could_be_bare_struct_literal: Option<Span>,
513 /// Only used for better errors on `let <pat>: <expr, not type>;`.
514 current_let_binding: Option<(Span, Option<Span>, Option<Span>)>,
516 /// Used to detect possible `if let` written without `let` and to provide structured suggestion.
517 in_if_condition: Option<&'ast Expr>,
519 /// If we are currently in a trait object definition. Used to point at the bounds when
520 /// encountering a struct or enum.
521 current_trait_object: Option<&'ast [ast::GenericBound]>,
523 /// Given `where <T as Bar>::Baz: String`, suggest `where T: Bar<Baz = String>`.
524 current_where_predicate: Option<&'ast WherePredicate>,
526 current_type_path: Option<&'ast Ty>,
528 /// The current impl items (used to suggest).
529 current_impl_items: Option<&'ast [P<AssocItem>]>,
531 /// When processing impl trait
532 currently_processing_impl_trait: Option<(TraitRef, Ty)>,
534 /// Accumulate the errors due to missed lifetime elision,
535 /// and report them all at once for each function.
536 current_elision_failures: Vec<MissingLifetime>,
539 struct LateResolutionVisitor<'a, 'b, 'ast> {
540 r: &'b mut Resolver<'a>,
542 /// The module that represents the current item scope.
543 parent_scope: ParentScope<'a>,
545 /// The current set of local scopes for types and values.
546 /// FIXME #4948: Reuse ribs to avoid allocation.
547 ribs: PerNS<Vec<Rib<'a>>>,
549 /// The current set of local scopes, for labels.
550 label_ribs: Vec<Rib<'a, NodeId>>,
552 /// The current set of local scopes for lifetimes.
553 lifetime_ribs: Vec<LifetimeRib>,
555 /// We are looking for lifetimes in an elision context.
556 /// The set contains all the resolutions that we encountered so far.
557 /// They will be used to determine the correct lifetime for the fn return type.
558 /// The `LifetimeElisionCandidate` is used for diagnostics, to suggest introducing named
560 lifetime_elision_candidates: Option<FxIndexMap<LifetimeRes, LifetimeElisionCandidate>>,
562 /// The trait that the current context can refer to.
563 current_trait_ref: Option<(Module<'a>, TraitRef)>,
565 /// Fields used to add information to diagnostic errors.
566 diagnostic_metadata: Box<DiagnosticMetadata<'ast>>,
568 /// State used to know whether to ignore resolution errors for function bodies.
570 /// In particular, rustdoc uses this to avoid giving errors for `cfg()` items.
571 /// In most cases this will be `None`, in which case errors will always be reported.
572 /// If it is `true`, then it will be updated when entering a nested function or trait body.
575 /// Count the number of places a lifetime is used.
576 lifetime_uses: FxHashMap<LocalDefId, LifetimeUseSet>,
579 /// Walks the whole crate in DFS order, visiting each item, resolving names as it goes.
580 impl<'a: 'ast, 'ast> Visitor<'ast> for LateResolutionVisitor<'a, '_, 'ast> {
581 fn visit_attribute(&mut self, _: &'ast Attribute) {
582 // We do not want to resolve expressions that appear in attributes,
583 // as they do not correspond to actual code.
585 fn visit_item(&mut self, item: &'ast Item) {
586 let prev = replace(&mut self.diagnostic_metadata.current_item, Some(item));
587 // Always report errors in items we just entered.
588 let old_ignore = replace(&mut self.in_func_body, false);
589 self.with_lifetime_rib(LifetimeRibKind::Item, |this| this.resolve_item(item));
590 self.in_func_body = old_ignore;
591 self.diagnostic_metadata.current_item = prev;
593 fn visit_arm(&mut self, arm: &'ast Arm) {
594 self.resolve_arm(arm);
596 fn visit_block(&mut self, block: &'ast Block) {
597 self.resolve_block(block);
599 fn visit_anon_const(&mut self, constant: &'ast AnonConst) {
600 // We deal with repeat expressions explicitly in `resolve_expr`.
601 self.with_lifetime_rib(LifetimeRibKind::AnonConst, |this| {
602 this.with_lifetime_rib(LifetimeRibKind::Elided(LifetimeRes::Static), |this| {
603 this.resolve_anon_const(constant, IsRepeatExpr::No);
607 fn visit_expr(&mut self, expr: &'ast Expr) {
608 self.resolve_expr(expr, None);
610 fn visit_local(&mut self, local: &'ast Local) {
611 let local_spans = match local.pat.kind {
612 // We check for this to avoid tuple struct fields.
613 PatKind::Wild => None,
616 local.ty.as_ref().map(|ty| ty.span),
617 local.kind.init().map(|init| init.span),
620 let original = replace(&mut self.diagnostic_metadata.current_let_binding, local_spans);
621 self.resolve_local(local);
622 self.diagnostic_metadata.current_let_binding = original;
624 fn visit_ty(&mut self, ty: &'ast Ty) {
625 let prev = self.diagnostic_metadata.current_trait_object;
626 let prev_ty = self.diagnostic_metadata.current_type_path;
628 TyKind::Rptr(None, _) => {
629 // Elided lifetime in reference: we resolve as if there was some lifetime `'_` with
631 // This span will be used in case of elision failure.
632 let span = self.r.session.source_map().next_point(ty.span.shrink_to_lo());
633 self.resolve_elided_lifetime(ty.id, span);
634 visit::walk_ty(self, ty);
636 TyKind::Path(ref qself, ref path) => {
637 self.diagnostic_metadata.current_type_path = Some(ty);
638 self.smart_resolve_path(ty.id, qself.as_ref(), path, PathSource::Type);
640 // Check whether we should interpret this as a bare trait object.
642 && let Some(partial_res) = self.r.partial_res_map.get(&ty.id)
643 && partial_res.unresolved_segments() == 0
644 && let Res::Def(DefKind::Trait | DefKind::TraitAlias, _) = partial_res.base_res()
646 // This path is actually a bare trait object. In case of a bare `Fn`-trait
647 // object with anonymous lifetimes, we need this rib to correctly place the
648 // synthetic lifetimes.
649 let span = ty.span.shrink_to_lo().to(path.span.shrink_to_lo());
650 self.with_generic_param_rib(
653 LifetimeRibKind::Generics {
655 kind: LifetimeBinderKind::PolyTrait,
658 |this| this.visit_path(&path, ty.id),
661 visit::walk_ty(self, ty)
664 TyKind::ImplicitSelf => {
665 let self_ty = Ident::with_dummy_span(kw::SelfUpper);
667 .resolve_ident_in_lexical_scope(
670 Some(Finalize::new(ty.id, ty.span)),
673 .map_or(Res::Err, |d| d.res());
674 self.r.record_partial_res(ty.id, PartialRes::new(res));
675 visit::walk_ty(self, ty)
677 TyKind::ImplTrait(..) => {
678 let candidates = self.lifetime_elision_candidates.take();
679 visit::walk_ty(self, ty);
680 self.lifetime_elision_candidates = candidates;
682 TyKind::TraitObject(ref bounds, ..) => {
683 self.diagnostic_metadata.current_trait_object = Some(&bounds[..]);
684 visit::walk_ty(self, ty)
686 TyKind::BareFn(ref bare_fn) => {
687 let span = ty.span.shrink_to_lo().to(bare_fn.decl_span.shrink_to_lo());
688 self.with_generic_param_rib(
689 &bare_fn.generic_params,
691 LifetimeRibKind::Generics {
693 kind: LifetimeBinderKind::BareFnType,
697 this.visit_generic_params(&bare_fn.generic_params, false);
698 this.with_lifetime_rib(
699 LifetimeRibKind::AnonymousCreateParameter {
701 report_in_path: false,
704 this.resolve_fn_signature(
707 // We don't need to deal with patterns in parameters, because
708 // they are not possible for foreign or bodiless functions.
713 .map(|Param { ty, .. }| (None, &**ty)),
714 &bare_fn.decl.output,
721 _ => visit::walk_ty(self, ty),
723 self.diagnostic_metadata.current_trait_object = prev;
724 self.diagnostic_metadata.current_type_path = prev_ty;
726 fn visit_poly_trait_ref(&mut self, tref: &'ast PolyTraitRef, _: &'ast TraitBoundModifier) {
727 let span = tref.span.shrink_to_lo().to(tref.trait_ref.path.span.shrink_to_lo());
728 self.with_generic_param_rib(
729 &tref.bound_generic_params,
731 LifetimeRibKind::Generics {
732 binder: tref.trait_ref.ref_id,
733 kind: LifetimeBinderKind::PolyTrait,
737 this.visit_generic_params(&tref.bound_generic_params, false);
738 this.smart_resolve_path(
739 tref.trait_ref.ref_id,
741 &tref.trait_ref.path,
742 PathSource::Trait(AliasPossibility::Maybe),
744 this.visit_trait_ref(&tref.trait_ref);
748 fn visit_foreign_item(&mut self, foreign_item: &'ast ForeignItem) {
749 match foreign_item.kind {
750 ForeignItemKind::TyAlias(box TyAlias { ref generics, .. }) => {
751 self.with_lifetime_rib(LifetimeRibKind::Item, |this| {
752 this.with_generic_param_rib(
754 ItemRibKind(HasGenericParams::Yes),
755 LifetimeRibKind::Generics {
756 binder: foreign_item.id,
757 kind: LifetimeBinderKind::Item,
760 |this| visit::walk_foreign_item(this, foreign_item),
764 ForeignItemKind::Fn(box Fn { ref generics, .. }) => {
765 self.with_lifetime_rib(LifetimeRibKind::Item, |this| {
766 this.with_generic_param_rib(
768 ItemRibKind(HasGenericParams::Yes),
769 LifetimeRibKind::Generics {
770 binder: foreign_item.id,
771 kind: LifetimeBinderKind::Function,
774 |this| visit::walk_foreign_item(this, foreign_item),
778 ForeignItemKind::Static(..) => {
779 self.with_item_rib(|this| {
780 visit::walk_foreign_item(this, foreign_item);
783 ForeignItemKind::MacCall(..) => {
784 panic!("unexpanded macro in resolve!")
788 fn visit_fn(&mut self, fn_kind: FnKind<'ast>, sp: Span, fn_id: NodeId) {
789 let rib_kind = match fn_kind {
790 // Bail if the function is foreign, and thus cannot validly have
791 // a body, or if there's no body for some other reason.
792 FnKind::Fn(FnCtxt::Foreign, _, sig, _, generics, _)
793 | FnKind::Fn(_, _, sig, _, generics, None) => {
794 self.visit_fn_header(&sig.header);
795 self.visit_generics(generics);
796 self.with_lifetime_rib(
797 LifetimeRibKind::AnonymousCreateParameter {
799 report_in_path: false,
802 this.resolve_fn_signature(
805 sig.decl.inputs.iter().map(|Param { ty, .. }| (None, &**ty)),
812 FnKind::Fn(FnCtxt::Free, ..) => FnItemRibKind,
813 FnKind::Fn(FnCtxt::Assoc(_), ..) => NormalRibKind,
814 FnKind::Closure(..) => ClosureOrAsyncRibKind,
816 let previous_value = self.diagnostic_metadata.current_function;
817 if matches!(fn_kind, FnKind::Fn(..)) {
818 self.diagnostic_metadata.current_function = Some((fn_kind, sp));
820 debug!("(resolving function) entering function");
822 // Create a value rib for the function.
823 self.with_rib(ValueNS, rib_kind, |this| {
824 // Create a label rib for the function.
825 this.with_label_rib(FnItemRibKind, |this| {
827 FnKind::Fn(_, _, sig, _, generics, body) => {
828 this.visit_generics(generics);
830 let declaration = &sig.decl;
831 let async_node_id = sig.header.asyncness.opt_return_id();
833 this.with_lifetime_rib(
834 LifetimeRibKind::AnonymousCreateParameter {
836 report_in_path: async_node_id.is_some(),
839 this.resolve_fn_signature(
841 declaration.has_self(),
845 .map(|Param { pat, ty, .. }| (Some(&**pat), &**ty)),
851 // Construct the list of in-scope lifetime parameters for async lowering.
852 // We include all lifetime parameters, either named or "Fresh".
853 // The order of those parameters does not matter, as long as it is
855 if let Some(async_node_id) = async_node_id {
856 let mut extra_lifetime_params = this
858 .extra_lifetime_params_map
861 .unwrap_or_default();
862 for rib in this.lifetime_ribs.iter().rev() {
863 extra_lifetime_params.extend(
866 .map(|(&ident, &(node_id, res))| (ident, node_id, res)),
869 LifetimeRibKind::Item => break,
870 LifetimeRibKind::AnonymousCreateParameter {
873 if let Some(earlier_fresh) =
874 this.r.extra_lifetime_params_map.get(&binder)
876 extra_lifetime_params.extend(earlier_fresh);
883 .extra_lifetime_params_map
884 .insert(async_node_id, extra_lifetime_params);
887 if let Some(body) = body {
888 // Ignore errors in function bodies if this is rustdoc
889 // Be sure not to set this until the function signature has been resolved.
890 let previous_state = replace(&mut this.in_func_body, true);
891 // Resolve the function body, potentially inside the body of an async closure
892 this.with_lifetime_rib(
893 LifetimeRibKind::Elided(LifetimeRes::Infer),
894 |this| this.visit_block(body),
897 debug!("(resolving function) leaving function");
898 this.in_func_body = previous_state;
901 FnKind::Closure(binder, declaration, body) => {
902 this.visit_closure_binder(binder);
904 this.with_lifetime_rib(
906 // We do not have any explicit generic lifetime parameter.
907 ClosureBinder::NotPresent => {
908 LifetimeRibKind::AnonymousCreateParameter {
910 report_in_path: false,
913 ClosureBinder::For { .. } => LifetimeRibKind::AnonymousReportError,
915 // Add each argument to the rib.
916 |this| this.resolve_params(&declaration.inputs),
918 this.with_lifetime_rib(
920 ClosureBinder::NotPresent => {
921 LifetimeRibKind::Elided(LifetimeRes::Infer)
923 ClosureBinder::For { .. } => LifetimeRibKind::AnonymousReportError,
925 |this| visit::walk_fn_ret_ty(this, &declaration.output),
928 // Ignore errors in function bodies if this is rustdoc
929 // Be sure not to set this until the function signature has been resolved.
930 let previous_state = replace(&mut this.in_func_body, true);
931 // Resolve the function body, potentially inside the body of an async closure
932 this.with_lifetime_rib(
933 LifetimeRibKind::Elided(LifetimeRes::Infer),
934 |this| this.visit_expr(body),
937 debug!("(resolving function) leaving function");
938 this.in_func_body = previous_state;
943 self.diagnostic_metadata.current_function = previous_value;
945 fn visit_lifetime(&mut self, lifetime: &'ast Lifetime, use_ctxt: visit::LifetimeCtxt) {
946 self.resolve_lifetime(lifetime, use_ctxt)
949 fn visit_generics(&mut self, generics: &'ast Generics) {
950 self.visit_generic_params(
952 self.diagnostic_metadata.current_self_item.is_some(),
954 for p in &generics.where_clause.predicates {
955 self.visit_where_predicate(p);
959 fn visit_closure_binder(&mut self, b: &'ast ClosureBinder) {
961 ClosureBinder::NotPresent => {}
962 ClosureBinder::For { generic_params, .. } => {
963 self.visit_generic_params(
965 self.diagnostic_metadata.current_self_item.is_some(),
971 fn visit_generic_arg(&mut self, arg: &'ast GenericArg) {
972 debug!("visit_generic_arg({:?})", arg);
973 let prev = replace(&mut self.diagnostic_metadata.currently_processing_generics, true);
975 GenericArg::Type(ref ty) => {
976 // We parse const arguments as path types as we cannot distinguish them during
977 // parsing. We try to resolve that ambiguity by attempting resolution the type
978 // namespace first, and if that fails we try again in the value namespace. If
979 // resolution in the value namespace succeeds, we have an generic const argument on
981 if let TyKind::Path(ref qself, ref path) = ty.kind {
982 // We cannot disambiguate multi-segment paths right now as that requires type
984 if path.segments.len() == 1 && path.segments[0].args.is_none() {
985 let mut check_ns = |ns| {
986 self.maybe_resolve_ident_in_lexical_scope(path.segments[0].ident, ns)
989 if !check_ns(TypeNS) && check_ns(ValueNS) {
990 // This must be equivalent to `visit_anon_const`, but we cannot call it
991 // directly due to visitor lifetimes so we have to copy-paste some code.
993 // Note that we might not be inside of an repeat expression here,
994 // but considering that `IsRepeatExpr` is only relevant for
995 // non-trivial constants this is doesn't matter.
996 self.with_constant_rib(
998 HasGenericParams::Yes,
1001 this.smart_resolve_path(
1005 PathSource::Expr(None),
1008 if let Some(ref qself) = *qself {
1009 this.visit_ty(&qself.ty);
1011 this.visit_path(path, ty.id);
1015 self.diagnostic_metadata.currently_processing_generics = prev;
1023 GenericArg::Lifetime(lt) => self.visit_lifetime(lt, visit::LifetimeCtxt::GenericArg),
1024 GenericArg::Const(ct) => self.visit_anon_const(ct),
1026 self.diagnostic_metadata.currently_processing_generics = prev;
1029 fn visit_assoc_constraint(&mut self, constraint: &'ast AssocConstraint) {
1030 self.visit_ident(constraint.ident);
1031 if let Some(ref gen_args) = constraint.gen_args {
1032 // Forbid anonymous lifetimes in GAT parameters until proper semantics are decided.
1033 self.with_lifetime_rib(LifetimeRibKind::AnonymousReportError, |this| {
1034 this.visit_generic_args(gen_args.span(), gen_args)
1037 match constraint.kind {
1038 AssocConstraintKind::Equality { ref term } => match term {
1039 Term::Ty(ty) => self.visit_ty(ty),
1040 Term::Const(c) => self.visit_anon_const(c),
1042 AssocConstraintKind::Bound { ref bounds } => {
1043 walk_list!(self, visit_param_bound, bounds, BoundKind::Bound);
1048 fn visit_path_segment(&mut self, path_span: Span, path_segment: &'ast PathSegment) {
1049 if let Some(ref args) = path_segment.args {
1051 GenericArgs::AngleBracketed(..) => visit::walk_generic_args(self, path_span, args),
1052 GenericArgs::Parenthesized(p_args) => {
1053 // Probe the lifetime ribs to know how to behave.
1054 for rib in self.lifetime_ribs.iter().rev() {
1056 // We are inside a `PolyTraitRef`. The lifetimes are
1057 // to be intoduced in that (maybe implicit) `for<>` binder.
1058 LifetimeRibKind::Generics {
1060 kind: LifetimeBinderKind::PolyTrait,
1063 self.with_lifetime_rib(
1064 LifetimeRibKind::AnonymousCreateParameter {
1066 report_in_path: false,
1069 this.resolve_fn_signature(
1072 p_args.inputs.iter().map(|ty| (None, &**ty)),
1079 // We have nowhere to introduce generics. Code is malformed,
1080 // so use regular lifetime resolution to avoid spurious errors.
1081 LifetimeRibKind::Item | LifetimeRibKind::Generics { .. } => {
1082 visit::walk_generic_args(self, path_span, args);
1085 LifetimeRibKind::AnonymousCreateParameter { .. }
1086 | LifetimeRibKind::AnonymousReportError
1087 | LifetimeRibKind::Elided(_)
1088 | LifetimeRibKind::ElisionFailure
1089 | LifetimeRibKind::AnonConst
1090 | LifetimeRibKind::ConstGeneric => {}
1098 fn visit_where_predicate(&mut self, p: &'ast WherePredicate) {
1099 debug!("visit_where_predicate {:?}", p);
1100 let previous_value =
1101 replace(&mut self.diagnostic_metadata.current_where_predicate, Some(p));
1102 self.with_lifetime_rib(LifetimeRibKind::AnonymousReportError, |this| {
1103 if let WherePredicate::BoundPredicate(WhereBoundPredicate {
1106 ref bound_generic_params,
1107 span: predicate_span,
1111 let span = predicate_span.shrink_to_lo().to(bounded_ty.span.shrink_to_lo());
1112 this.with_generic_param_rib(
1113 &bound_generic_params,
1115 LifetimeRibKind::Generics {
1116 binder: bounded_ty.id,
1117 kind: LifetimeBinderKind::WhereBound,
1121 this.visit_generic_params(&bound_generic_params, false);
1122 this.visit_ty(bounded_ty);
1123 for bound in bounds {
1124 this.visit_param_bound(bound, BoundKind::Bound)
1129 visit::walk_where_predicate(this, p);
1132 self.diagnostic_metadata.current_where_predicate = previous_value;
1135 fn visit_inline_asm(&mut self, asm: &'ast InlineAsm) {
1136 for (op, _) in &asm.operands {
1138 InlineAsmOperand::In { expr, .. }
1139 | InlineAsmOperand::Out { expr: Some(expr), .. }
1140 | InlineAsmOperand::InOut { expr, .. } => self.visit_expr(expr),
1141 InlineAsmOperand::Out { expr: None, .. } => {}
1142 InlineAsmOperand::SplitInOut { in_expr, out_expr, .. } => {
1143 self.visit_expr(in_expr);
1144 if let Some(out_expr) = out_expr {
1145 self.visit_expr(out_expr);
1148 InlineAsmOperand::Const { anon_const, .. } => {
1149 // Although this is `DefKind::AnonConst`, it is allowed to reference outer
1150 // generic parameters like an inline const.
1151 self.resolve_inline_const(anon_const);
1153 InlineAsmOperand::Sym { sym } => self.visit_inline_asm_sym(sym),
1158 fn visit_inline_asm_sym(&mut self, sym: &'ast InlineAsmSym) {
1159 // This is similar to the code for AnonConst.
1160 self.with_rib(ValueNS, InlineAsmSymRibKind, |this| {
1161 this.with_rib(TypeNS, InlineAsmSymRibKind, |this| {
1162 this.with_label_rib(InlineAsmSymRibKind, |this| {
1163 this.smart_resolve_path(
1167 PathSource::Expr(None),
1169 visit::walk_inline_asm_sym(this, sym);
1176 impl<'a: 'ast, 'b, 'ast> LateResolutionVisitor<'a, 'b, 'ast> {
1177 fn new(resolver: &'b mut Resolver<'a>) -> LateResolutionVisitor<'a, 'b, 'ast> {
1178 // During late resolution we only track the module component of the parent scope,
1179 // although it may be useful to track other components as well for diagnostics.
1180 let graph_root = resolver.graph_root;
1181 let parent_scope = ParentScope::module(graph_root, resolver);
1182 let start_rib_kind = ModuleRibKind(graph_root);
1183 LateResolutionVisitor {
1187 value_ns: vec![Rib::new(start_rib_kind)],
1188 type_ns: vec![Rib::new(start_rib_kind)],
1189 macro_ns: vec![Rib::new(start_rib_kind)],
1191 label_ribs: Vec::new(),
1192 lifetime_ribs: Vec::new(),
1193 lifetime_elision_candidates: None,
1194 current_trait_ref: None,
1195 diagnostic_metadata: Box::new(DiagnosticMetadata::default()),
1196 // errors at module scope should always be reported
1197 in_func_body: false,
1198 lifetime_uses: Default::default(),
1202 fn maybe_resolve_ident_in_lexical_scope(
1206 ) -> Option<LexicalScopeBinding<'a>> {
1207 self.r.resolve_ident_in_lexical_scope(
1217 fn resolve_ident_in_lexical_scope(
1221 finalize: Option<Finalize>,
1222 ignore_binding: Option<&'a NameBinding<'a>>,
1223 ) -> Option<LexicalScopeBinding<'a>> {
1224 self.r.resolve_ident_in_lexical_scope(
1237 opt_ns: Option<Namespace>, // `None` indicates a module path in import
1238 finalize: Option<Finalize>,
1239 ) -> PathResult<'a> {
1240 self.r.resolve_path_with_ribs(
1252 // We maintain a list of value ribs and type ribs.
1254 // Simultaneously, we keep track of the current position in the module
1255 // graph in the `parent_scope.module` pointer. When we go to resolve a name in
1256 // the value or type namespaces, we first look through all the ribs and
1257 // then query the module graph. When we resolve a name in the module
1258 // namespace, we can skip all the ribs (since nested modules are not
1259 // allowed within blocks in Rust) and jump straight to the current module
1262 // Named implementations are handled separately. When we find a method
1263 // call, we consult the module node to find all of the implementations in
1264 // scope. This information is lazily cached in the module node. We then
1265 // generate a fake "implementation scope" containing all the
1266 // implementations thus found, for compatibility with old resolve pass.
1268 /// Do some `work` within a new innermost rib of the given `kind` in the given namespace (`ns`).
1273 work: impl FnOnce(&mut Self) -> T,
1275 self.ribs[ns].push(Rib::new(kind));
1276 let ret = work(self);
1277 self.ribs[ns].pop();
1281 fn with_scope<T>(&mut self, id: NodeId, f: impl FnOnce(&mut Self) -> T) -> T {
1282 if let Some(module) = self.r.get_module(self.r.local_def_id(id).to_def_id()) {
1283 // Move down in the graph.
1284 let orig_module = replace(&mut self.parent_scope.module, module);
1285 self.with_rib(ValueNS, ModuleRibKind(module), |this| {
1286 this.with_rib(TypeNS, ModuleRibKind(module), |this| {
1288 this.parent_scope.module = orig_module;
1297 fn visit_generic_params(&mut self, params: &'ast [GenericParam], add_self_upper: bool) {
1298 // For type parameter defaults, we have to ban access
1299 // to following type parameters, as the InternalSubsts can only
1300 // provide previous type parameters as they're built. We
1301 // put all the parameters on the ban list and then remove
1302 // them one by one as they are processed and become available.
1303 let mut forward_ty_ban_rib = Rib::new(ForwardGenericParamBanRibKind);
1304 let mut forward_const_ban_rib = Rib::new(ForwardGenericParamBanRibKind);
1305 for param in params.iter() {
1307 GenericParamKind::Type { .. } => {
1310 .insert(Ident::with_dummy_span(param.ident.name), Res::Err);
1312 GenericParamKind::Const { .. } => {
1313 forward_const_ban_rib
1315 .insert(Ident::with_dummy_span(param.ident.name), Res::Err);
1317 GenericParamKind::Lifetime => {}
1321 // rust-lang/rust#61631: The type `Self` is essentially
1322 // another type parameter. For ADTs, we consider it
1323 // well-defined only after all of the ADT type parameters have
1324 // been provided. Therefore, we do not allow use of `Self`
1325 // anywhere in ADT type parameter defaults.
1327 // (We however cannot ban `Self` for defaults on *all* generic
1328 // lists; e.g. trait generics can usefully refer to `Self`,
1329 // such as in the case of `trait Add<Rhs = Self>`.)
1331 // (`Some` if + only if we are in ADT's generics.)
1332 forward_ty_ban_rib.bindings.insert(Ident::with_dummy_span(kw::SelfUpper), Res::Err);
1335 self.with_lifetime_rib(LifetimeRibKind::AnonymousReportError, |this| {
1336 for param in params {
1338 GenericParamKind::Lifetime => {
1339 for bound in ¶m.bounds {
1340 this.visit_param_bound(bound, BoundKind::Bound);
1343 GenericParamKind::Type { ref default } => {
1344 for bound in ¶m.bounds {
1345 this.visit_param_bound(bound, BoundKind::Bound);
1348 if let Some(ref ty) = default {
1349 this.ribs[TypeNS].push(forward_ty_ban_rib);
1350 this.ribs[ValueNS].push(forward_const_ban_rib);
1352 forward_const_ban_rib = this.ribs[ValueNS].pop().unwrap();
1353 forward_ty_ban_rib = this.ribs[TypeNS].pop().unwrap();
1356 // Allow all following defaults to refer to this type parameter.
1359 .remove(&Ident::with_dummy_span(param.ident.name));
1361 GenericParamKind::Const { ref ty, kw_span: _, ref default } => {
1362 // Const parameters can't have param bounds.
1363 assert!(param.bounds.is_empty());
1365 this.ribs[TypeNS].push(Rib::new(ConstParamTyRibKind));
1366 this.ribs[ValueNS].push(Rib::new(ConstParamTyRibKind));
1367 this.with_lifetime_rib(LifetimeRibKind::ConstGeneric, |this| {
1370 this.ribs[TypeNS].pop().unwrap();
1371 this.ribs[ValueNS].pop().unwrap();
1373 if let Some(ref expr) = default {
1374 this.ribs[TypeNS].push(forward_ty_ban_rib);
1375 this.ribs[ValueNS].push(forward_const_ban_rib);
1376 this.with_lifetime_rib(LifetimeRibKind::ConstGeneric, |this| {
1377 this.resolve_anon_const(expr, IsRepeatExpr::No)
1379 forward_const_ban_rib = this.ribs[ValueNS].pop().unwrap();
1380 forward_ty_ban_rib = this.ribs[TypeNS].pop().unwrap();
1383 // Allow all following defaults to refer to this const parameter.
1384 forward_const_ban_rib
1386 .remove(&Ident::with_dummy_span(param.ident.name));
1393 #[tracing::instrument(level = "debug", skip(self, work))]
1394 fn with_lifetime_rib<T>(
1396 kind: LifetimeRibKind,
1397 work: impl FnOnce(&mut Self) -> T,
1399 self.lifetime_ribs.push(LifetimeRib::new(kind));
1400 let outer_elision_candidates = self.lifetime_elision_candidates.take();
1401 let ret = work(self);
1402 self.lifetime_elision_candidates = outer_elision_candidates;
1403 self.lifetime_ribs.pop();
1407 #[tracing::instrument(level = "debug", skip(self))]
1408 fn resolve_lifetime(&mut self, lifetime: &'ast Lifetime, use_ctxt: visit::LifetimeCtxt) {
1409 let ident = lifetime.ident;
1411 if ident.name == kw::StaticLifetime {
1412 self.record_lifetime_res(
1414 LifetimeRes::Static,
1415 LifetimeElisionCandidate::Named,
1420 if ident.name == kw::UnderscoreLifetime {
1421 return self.resolve_anonymous_lifetime(lifetime, false);
1424 let mut indices = (0..self.lifetime_ribs.len()).rev();
1425 for i in &mut indices {
1426 let rib = &self.lifetime_ribs[i];
1427 let normalized_ident = ident.normalize_to_macros_2_0();
1428 if let Some(&(_, res)) = rib.bindings.get(&normalized_ident) {
1429 self.record_lifetime_res(lifetime.id, res, LifetimeElisionCandidate::Named);
1431 if let LifetimeRes::Param { param, .. } = res {
1432 match self.lifetime_uses.entry(param) {
1433 Entry::Vacant(v) => {
1434 debug!("First use of {:?} at {:?}", res, ident.span);
1439 .find_map(|rib| match rib.kind {
1440 // Do not suggest eliding a lifetime where an anonymous
1441 // lifetime would be illegal.
1442 LifetimeRibKind::Item
1443 | LifetimeRibKind::AnonymousReportError
1444 | LifetimeRibKind::ElisionFailure => Some(LifetimeUseSet::Many),
1445 // An anonymous lifetime is legal here, go ahead.
1446 LifetimeRibKind::AnonymousCreateParameter { .. } => {
1447 Some(LifetimeUseSet::One { use_span: ident.span, use_ctxt })
1449 // Only report if eliding the lifetime would have the same
1451 LifetimeRibKind::Elided(r) => Some(if res == r {
1452 LifetimeUseSet::One { use_span: ident.span, use_ctxt }
1454 LifetimeUseSet::Many
1456 LifetimeRibKind::Generics { .. }
1457 | LifetimeRibKind::ConstGeneric
1458 | LifetimeRibKind::AnonConst => None,
1460 .unwrap_or(LifetimeUseSet::Many);
1461 debug!(?use_ctxt, ?use_set);
1464 Entry::Occupied(mut o) => {
1465 debug!("Many uses of {:?} at {:?}", res, ident.span);
1466 *o.get_mut() = LifetimeUseSet::Many;
1474 LifetimeRibKind::Item => break,
1475 LifetimeRibKind::ConstGeneric => {
1476 self.emit_non_static_lt_in_const_generic_error(lifetime);
1477 self.record_lifetime_res(
1480 LifetimeElisionCandidate::Ignore,
1484 LifetimeRibKind::AnonConst => {
1485 self.maybe_emit_forbidden_non_static_lifetime_error(lifetime);
1486 self.record_lifetime_res(
1489 LifetimeElisionCandidate::Ignore,
1497 let mut outer_res = None;
1499 let rib = &self.lifetime_ribs[i];
1500 let normalized_ident = ident.normalize_to_macros_2_0();
1501 if let Some((&outer, _)) = rib.bindings.get_key_value(&normalized_ident) {
1502 outer_res = Some(outer);
1507 self.emit_undeclared_lifetime_error(lifetime, outer_res);
1508 self.record_lifetime_res(lifetime.id, LifetimeRes::Error, LifetimeElisionCandidate::Named);
1511 #[tracing::instrument(level = "debug", skip(self))]
1512 fn resolve_anonymous_lifetime(&mut self, lifetime: &Lifetime, elided: bool) {
1513 debug_assert_eq!(lifetime.ident.name, kw::UnderscoreLifetime);
1515 let missing_lifetime = MissingLifetime {
1517 span: lifetime.ident.span,
1519 MissingLifetimeKind::Ampersand
1521 MissingLifetimeKind::Underscore
1525 let elision_candidate = LifetimeElisionCandidate::Missing(missing_lifetime);
1526 for i in (0..self.lifetime_ribs.len()).rev() {
1527 let rib = &mut self.lifetime_ribs[i];
1530 LifetimeRibKind::AnonymousCreateParameter { binder, .. } => {
1531 let res = self.create_fresh_lifetime(lifetime.id, lifetime.ident, binder);
1532 self.record_lifetime_res(lifetime.id, res, elision_candidate);
1535 LifetimeRibKind::AnonymousReportError => {
1536 let (msg, note) = if elided {
1538 "`&` without an explicit lifetime name cannot be used here",
1539 "explicit lifetime name needed here",
1542 ("`'_` cannot be used here", "`'_` is a reserved lifetime name")
1544 rustc_errors::struct_span_err!(
1546 lifetime.ident.span,
1551 .span_label(lifetime.ident.span, note)
1554 self.record_lifetime_res(lifetime.id, LifetimeRes::Error, elision_candidate);
1557 LifetimeRibKind::Elided(res) => {
1558 self.record_lifetime_res(lifetime.id, res, elision_candidate);
1561 LifetimeRibKind::ElisionFailure => {
1562 self.diagnostic_metadata.current_elision_failures.push(missing_lifetime);
1563 self.record_lifetime_res(lifetime.id, LifetimeRes::Error, elision_candidate);
1566 LifetimeRibKind::Item => break,
1567 LifetimeRibKind::Generics { .. }
1568 | LifetimeRibKind::ConstGeneric
1569 | LifetimeRibKind::AnonConst => {}
1572 self.record_lifetime_res(lifetime.id, LifetimeRes::Error, elision_candidate);
1573 self.report_missing_lifetime_specifiers(vec![missing_lifetime], None);
1576 #[tracing::instrument(level = "debug", skip(self))]
1577 fn resolve_elided_lifetime(&mut self, anchor_id: NodeId, span: Span) {
1578 let id = self.r.next_node_id();
1579 let lt = Lifetime { id, ident: Ident::new(kw::UnderscoreLifetime, span) };
1581 self.record_lifetime_res(
1583 LifetimeRes::ElidedAnchor { start: id, end: NodeId::from_u32(id.as_u32() + 1) },
1584 LifetimeElisionCandidate::Ignore,
1586 self.resolve_anonymous_lifetime(<, true);
1589 #[tracing::instrument(level = "debug", skip(self))]
1590 fn create_fresh_lifetime(&mut self, id: NodeId, ident: Ident, binder: NodeId) -> LifetimeRes {
1591 debug_assert_eq!(ident.name, kw::UnderscoreLifetime);
1592 debug!(?ident.span);
1594 // Leave the responsibility to create the `LocalDefId` to lowering.
1595 let param = self.r.next_node_id();
1596 let res = LifetimeRes::Fresh { param, binder };
1598 // Record the created lifetime parameter so lowering can pick it up and add it to HIR.
1600 .extra_lifetime_params_map
1602 .or_insert_with(Vec::new)
1603 .push((ident, param, res));
1607 #[tracing::instrument(level = "debug", skip(self))]
1608 fn resolve_elided_lifetimes_in_path(
1611 partial_res: PartialRes,
1613 source: PathSource<'_>,
1616 let proj_start = path.len() - partial_res.unresolved_segments();
1617 for (i, segment) in path.iter().enumerate() {
1618 if segment.has_lifetime_args {
1621 let Some(segment_id) = segment.id else {
1625 // Figure out if this is a type/trait segment,
1626 // which may need lifetime elision performed.
1627 let type_def_id = match partial_res.base_res() {
1628 Res::Def(DefKind::AssocTy, def_id) if i + 2 == proj_start => self.r.parent(def_id),
1629 Res::Def(DefKind::Variant, def_id) if i + 1 == proj_start => self.r.parent(def_id),
1630 Res::Def(DefKind::Struct, def_id)
1631 | Res::Def(DefKind::Union, def_id)
1632 | Res::Def(DefKind::Enum, def_id)
1633 | Res::Def(DefKind::TyAlias, def_id)
1634 | Res::Def(DefKind::Trait, def_id)
1635 if i + 1 == proj_start =>
1642 let expected_lifetimes = self.r.item_generics_num_lifetimes(type_def_id);
1643 if expected_lifetimes == 0 {
1647 let missing = match source {
1648 PathSource::Trait(..) | PathSource::TraitItem(..) | PathSource::Type => true,
1649 PathSource::Expr(..)
1651 | PathSource::Struct
1652 | PathSource::TupleStruct(..) => false,
1654 if !missing && !segment.has_generic_args {
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 node_ids = self.r.next_node_ids(expected_lifetimes);
1670 self.record_lifetime_res(
1672 LifetimeRes::ElidedAnchor { start: node_ids.start, end: node_ids.end },
1673 LifetimeElisionCandidate::Ignore,
1677 // Do not create a parameter for patterns and expressions.
1678 for id in node_ids {
1679 self.record_lifetime_res(
1682 LifetimeElisionCandidate::Named,
1688 let missing_lifetime = MissingLifetime {
1690 span: elided_lifetime_span,
1691 kind: if segment.has_generic_args {
1692 MissingLifetimeKind::Comma
1694 MissingLifetimeKind::Brackets
1696 count: expected_lifetimes,
1698 let mut should_lint = true;
1699 for rib in self.lifetime_ribs.iter().rev() {
1701 // In create-parameter mode we error here because we don't want to support
1702 // deprecated impl elision in new features like impl elision and `async fn`,
1703 // both of which work using the `CreateParameter` mode:
1705 // impl Foo for std::cell::Ref<u32> // note lack of '_
1706 // async fn foo(_: std::cell::Ref<u32>) { ... }
1707 LifetimeRibKind::AnonymousCreateParameter { report_in_path: true, .. } => {
1708 let sess = self.r.session;
1709 let mut err = rustc_errors::struct_span_err!(
1713 "implicit elided lifetime not allowed here"
1715 rustc_errors::add_elided_lifetime_in_path_suggestion(
1720 !segment.has_generic_args,
1721 elided_lifetime_span,
1723 err.note("assuming a `'static` lifetime...");
1725 should_lint = false;
1727 for id in node_ids {
1728 self.record_lifetime_res(
1731 LifetimeElisionCandidate::Named,
1736 // Do not create a parameter for patterns and expressions.
1737 LifetimeRibKind::AnonymousCreateParameter { binder, .. } => {
1738 // Group all suggestions into the first record.
1739 let mut candidate = LifetimeElisionCandidate::Missing(missing_lifetime);
1740 for id in node_ids {
1741 let res = self.create_fresh_lifetime(id, ident, binder);
1742 self.record_lifetime_res(
1745 replace(&mut candidate, LifetimeElisionCandidate::Named),
1750 LifetimeRibKind::Elided(res) => {
1751 let mut candidate = LifetimeElisionCandidate::Missing(missing_lifetime);
1752 for id in node_ids {
1753 self.record_lifetime_res(
1756 replace(&mut candidate, LifetimeElisionCandidate::Ignore),
1761 LifetimeRibKind::ElisionFailure => {
1762 self.diagnostic_metadata.current_elision_failures.push(missing_lifetime);
1763 for id in node_ids {
1764 self.record_lifetime_res(
1767 LifetimeElisionCandidate::Ignore,
1772 // `LifetimeRes::Error`, which would usually be used in the case of
1773 // `ReportError`, is unsuitable here, as we don't emit an error yet. Instead,
1774 // we simply resolve to an implicit lifetime, which will be checked later, at
1775 // which point a suitable error will be emitted.
1776 LifetimeRibKind::AnonymousReportError | LifetimeRibKind::Item => {
1777 for id in node_ids {
1778 self.record_lifetime_res(
1781 LifetimeElisionCandidate::Ignore,
1784 self.report_missing_lifetime_specifiers(vec![missing_lifetime], None);
1787 LifetimeRibKind::Generics { .. }
1788 | LifetimeRibKind::ConstGeneric
1789 | LifetimeRibKind::AnonConst => {}
1794 self.r.lint_buffer.buffer_lint_with_diagnostic(
1795 lint::builtin::ELIDED_LIFETIMES_IN_PATHS,
1797 elided_lifetime_span,
1798 "hidden lifetime parameters in types are deprecated",
1799 lint::BuiltinLintDiagnostics::ElidedLifetimesInPaths(
1802 !segment.has_generic_args,
1803 elided_lifetime_span,
1810 #[tracing::instrument(level = "debug", skip(self))]
1811 fn record_lifetime_res(
1815 candidate: LifetimeElisionCandidate,
1817 if let Some(prev_res) = self.r.lifetimes_res_map.insert(id, res) {
1819 "lifetime {:?} resolved multiple times ({:?} before, {:?} now)",
1824 LifetimeRes::Param { .. } | LifetimeRes::Fresh { .. } | LifetimeRes::Static => {
1825 if let Some(ref mut candidates) = self.lifetime_elision_candidates {
1826 candidates.insert(res, candidate);
1829 LifetimeRes::Infer | LifetimeRes::Error | LifetimeRes::ElidedAnchor { .. } => {}
1833 #[tracing::instrument(level = "debug", skip(self))]
1834 fn record_lifetime_param(&mut self, id: NodeId, res: LifetimeRes) {
1835 if let Some(prev_res) = self.r.lifetimes_res_map.insert(id, res) {
1837 "lifetime parameter {:?} resolved multiple times ({:?} before, {:?} now)",
1843 /// Perform resolution of a function signature, accounting for lifetime elision.
1844 #[tracing::instrument(level = "debug", skip(self, inputs))]
1845 fn resolve_fn_signature(
1849 inputs: impl Iterator<Item = (Option<&'ast Pat>, &'ast Ty)> + Clone,
1850 output_ty: &'ast FnRetTy,
1852 // Add each argument to the rib.
1853 let elision_lifetime = self.resolve_fn_params(has_self, inputs);
1854 debug!(?elision_lifetime);
1856 let outer_failures = take(&mut self.diagnostic_metadata.current_elision_failures);
1857 let output_rib = if let Ok(res) = elision_lifetime.as_ref() {
1858 LifetimeRibKind::Elided(*res)
1860 LifetimeRibKind::ElisionFailure
1862 self.with_lifetime_rib(output_rib, |this| visit::walk_fn_ret_ty(this, &output_ty));
1863 let elision_failures =
1864 replace(&mut self.diagnostic_metadata.current_elision_failures, outer_failures);
1865 if !elision_failures.is_empty() {
1866 let Err(failure_info) = elision_lifetime else { bug!() };
1867 self.report_missing_lifetime_specifiers(elision_failures, Some(failure_info));
1871 /// Resolve inside function parameters and parameter types.
1872 /// Returns the lifetime for elision in fn return type,
1873 /// or diagnostic information in case of elision failure.
1874 fn resolve_fn_params(
1877 inputs: impl Iterator<Item = (Option<&'ast Pat>, &'ast Ty)>,
1878 ) -> Result<LifetimeRes, (Vec<MissingLifetime>, Vec<ElisionFnParameter>)> {
1879 let outer_candidates =
1880 replace(&mut self.lifetime_elision_candidates, Some(Default::default()));
1882 let mut elision_lifetime = None;
1883 let mut lifetime_count = 0;
1884 let mut parameter_info = Vec::new();
1886 let mut bindings = smallvec![(PatBoundCtx::Product, Default::default())];
1887 for (index, (pat, ty)) in inputs.enumerate() {
1889 if let Some(pat) = pat {
1890 self.resolve_pattern(pat, PatternSource::FnParam, &mut bindings);
1894 if let Some(ref candidates) = self.lifetime_elision_candidates {
1895 let new_count = candidates.len();
1896 let local_count = new_count - lifetime_count;
1897 if local_count != 0 {
1898 parameter_info.push(ElisionFnParameter {
1900 ident: if let Some(pat) = pat && let PatKind::Ident(_, ident, _) = pat.kind {
1905 lifetime_count: local_count,
1909 lifetime_count = new_count;
1912 // Handle `self` specially.
1913 if index == 0 && has_self {
1914 let self_lifetime = self.find_lifetime_for_self(ty);
1915 if let Set1::One(lifetime) = self_lifetime {
1916 elision_lifetime = Some(lifetime);
1917 self.lifetime_elision_candidates = None;
1919 self.lifetime_elision_candidates = Some(Default::default());
1923 debug!("(resolving function / closure) recorded parameter");
1926 let all_candidates = replace(&mut self.lifetime_elision_candidates, outer_candidates);
1927 debug!(?all_candidates);
1929 if let Some(res) = elision_lifetime {
1933 // We do not have a `self` candidate, look at the full list.
1934 let all_candidates = all_candidates.unwrap();
1935 if all_candidates.len() == 1 {
1936 Ok(*all_candidates.first().unwrap().0)
1938 let all_candidates = all_candidates
1940 .filter_map(|(_, candidate)| match candidate {
1941 LifetimeElisionCandidate::Ignore | LifetimeElisionCandidate::Named => None,
1942 LifetimeElisionCandidate::Missing(missing) => Some(missing),
1945 Err((all_candidates, parameter_info))
1949 /// List all the lifetimes that appear in the provided type.
1950 fn find_lifetime_for_self(&self, ty: &'ast Ty) -> Set1<LifetimeRes> {
1951 struct SelfVisitor<'r, 'a> {
1952 r: &'r Resolver<'a>,
1953 impl_self: Option<Res>,
1954 lifetime: Set1<LifetimeRes>,
1957 impl SelfVisitor<'_, '_> {
1958 // Look for `self: &'a Self` - also desugared from `&'a self`,
1959 // and if that matches, use it for elision and return early.
1960 fn is_self_ty(&self, ty: &Ty) -> bool {
1962 TyKind::ImplicitSelf => true,
1963 TyKind::Path(None, _) => {
1964 let path_res = self.r.partial_res_map[&ty.id].base_res();
1965 if let Res::SelfTy { .. } = path_res {
1968 Some(path_res) == self.impl_self
1975 impl<'a> Visitor<'a> for SelfVisitor<'_, '_> {
1976 fn visit_ty(&mut self, ty: &'a Ty) {
1977 trace!("SelfVisitor considering ty={:?}", ty);
1978 if let TyKind::Rptr(lt, ref mt) = ty.kind && self.is_self_ty(&mt.ty) {
1979 let lt_id = if let Some(lt) = lt {
1982 let res = self.r.lifetimes_res_map[&ty.id];
1983 let LifetimeRes::ElidedAnchor { start, .. } = res else { bug!() };
1986 let lt_res = self.r.lifetimes_res_map[<_id];
1987 trace!("SelfVisitor inserting res={:?}", lt_res);
1988 self.lifetime.insert(lt_res);
1990 visit::walk_ty(self, ty)
1994 let impl_self = self
1995 .diagnostic_metadata
1999 if let TyKind::Path(None, _) = ty.kind {
2000 self.r.partial_res_map.get(&ty.id)
2005 .map(|res| res.base_res())
2007 // Permit the types that unambiguously always
2008 // result in the same type constructor being used
2009 // (it can't differ between `Self` and `self`).
2012 Res::Def(DefKind::Struct | DefKind::Union | DefKind::Enum, _,) | Res::PrimTy(_)
2015 let mut visitor = SelfVisitor { r: self.r, impl_self, lifetime: Set1::Empty };
2016 visitor.visit_ty(ty);
2017 trace!("SelfVisitor found={:?}", visitor.lifetime);
2021 /// Searches the current set of local scopes for labels. Returns the `NodeId` of the resolved
2022 /// label and reports an error if the label is not found or is unreachable.
2023 fn resolve_label(&mut self, mut label: Ident) -> Result<(NodeId, Span), ResolutionError<'a>> {
2024 let mut suggestion = None;
2026 for i in (0..self.label_ribs.len()).rev() {
2027 let rib = &self.label_ribs[i];
2029 if let MacroDefinition(def) = rib.kind {
2030 // If an invocation of this macro created `ident`, give up on `ident`
2031 // and switch to `ident`'s source from the macro definition.
2032 if def == self.r.macro_def(label.span.ctxt()) {
2033 label.span.remove_mark();
2037 let ident = label.normalize_to_macro_rules();
2038 if let Some((ident, id)) = rib.bindings.get_key_value(&ident) {
2039 let definition_span = ident.span;
2040 return if self.is_label_valid_from_rib(i) {
2041 Ok((*id, definition_span))
2043 Err(ResolutionError::UnreachableLabel {
2051 // Diagnostics: Check if this rib contains a label with a similar name, keep track of
2052 // the first such label that is encountered.
2053 suggestion = suggestion.or_else(|| self.suggestion_for_label_in_rib(i, label));
2056 Err(ResolutionError::UndeclaredLabel { name: label.name, suggestion })
2059 /// Determine whether or not a label from the `rib_index`th label rib is reachable.
2060 fn is_label_valid_from_rib(&self, rib_index: usize) -> bool {
2061 let ribs = &self.label_ribs[rib_index + 1..];
2064 if rib.kind.is_label_barrier() {
2072 fn resolve_adt(&mut self, item: &'ast Item, generics: &'ast Generics) {
2073 debug!("resolve_adt");
2074 self.with_current_self_item(item, |this| {
2075 this.with_generic_param_rib(
2077 ItemRibKind(HasGenericParams::Yes),
2078 LifetimeRibKind::Generics {
2080 kind: LifetimeBinderKind::Item,
2081 span: generics.span,
2084 let item_def_id = this.r.local_def_id(item.id).to_def_id();
2086 Res::SelfTy { trait_: None, alias_to: Some((item_def_id, false)) },
2088 visit::walk_item(this, item);
2096 fn future_proof_import(&mut self, use_tree: &UseTree) {
2097 let segments = &use_tree.prefix.segments;
2098 if !segments.is_empty() {
2099 let ident = segments[0].ident;
2100 if ident.is_path_segment_keyword() || ident.span.rust_2015() {
2104 let nss = match use_tree.kind {
2105 UseTreeKind::Simple(..) if segments.len() == 1 => &[TypeNS, ValueNS][..],
2108 let report_error = |this: &Self, ns| {
2109 let what = if ns == TypeNS { "type parameters" } else { "local variables" };
2110 if this.should_report_errs() {
2113 .span_err(ident.span, &format!("imports cannot refer to {}", what));
2118 match self.maybe_resolve_ident_in_lexical_scope(ident, ns) {
2119 Some(LexicalScopeBinding::Res(..)) => {
2120 report_error(self, ns);
2122 Some(LexicalScopeBinding::Item(binding)) => {
2123 if let Some(LexicalScopeBinding::Res(..)) =
2124 self.resolve_ident_in_lexical_scope(ident, ns, None, Some(binding))
2126 report_error(self, ns);
2132 } else if let UseTreeKind::Nested(use_trees) = &use_tree.kind {
2133 for (use_tree, _) in use_trees {
2134 self.future_proof_import(use_tree);
2139 fn resolve_item(&mut self, item: &'ast Item) {
2140 let name = item.ident.name;
2141 debug!("(resolving item) resolving {} ({:?})", name, item.kind);
2144 ItemKind::TyAlias(box TyAlias { ref generics, .. }) => {
2145 self.with_generic_param_rib(
2147 ItemRibKind(HasGenericParams::Yes),
2148 LifetimeRibKind::Generics {
2150 kind: LifetimeBinderKind::Item,
2151 span: generics.span,
2153 |this| visit::walk_item(this, item),
2157 ItemKind::Fn(box Fn { ref generics, .. }) => {
2158 self.with_generic_param_rib(
2160 ItemRibKind(HasGenericParams::Yes),
2161 LifetimeRibKind::Generics {
2163 kind: LifetimeBinderKind::Function,
2164 span: generics.span,
2166 |this| visit::walk_item(this, item),
2170 ItemKind::Enum(_, ref generics)
2171 | ItemKind::Struct(_, ref generics)
2172 | ItemKind::Union(_, ref generics) => {
2173 self.resolve_adt(item, generics);
2176 ItemKind::Impl(box Impl {
2180 items: ref impl_items,
2183 self.diagnostic_metadata.current_impl_items = Some(impl_items);
2184 self.resolve_implementation(generics, of_trait, &self_ty, item.id, impl_items);
2185 self.diagnostic_metadata.current_impl_items = None;
2188 ItemKind::Trait(box Trait { ref generics, ref bounds, ref items, .. }) => {
2189 // Create a new rib for the trait-wide type parameters.
2190 self.with_generic_param_rib(
2192 ItemRibKind(HasGenericParams::Yes),
2193 LifetimeRibKind::Generics {
2195 kind: LifetimeBinderKind::Item,
2196 span: generics.span,
2199 let local_def_id = this.r.local_def_id(item.id).to_def_id();
2201 Res::SelfTy { trait_: Some(local_def_id), alias_to: None },
2203 this.visit_generics(generics);
2204 walk_list!(this, visit_param_bound, bounds, BoundKind::SuperTraits);
2205 this.resolve_trait_items(items);
2212 ItemKind::TraitAlias(ref generics, ref bounds) => {
2213 // Create a new rib for the trait-wide type parameters.
2214 self.with_generic_param_rib(
2216 ItemRibKind(HasGenericParams::Yes),
2217 LifetimeRibKind::Generics {
2219 kind: LifetimeBinderKind::Item,
2220 span: generics.span,
2223 let local_def_id = this.r.local_def_id(item.id).to_def_id();
2225 Res::SelfTy { trait_: Some(local_def_id), alias_to: None },
2227 this.visit_generics(generics);
2228 walk_list!(this, visit_param_bound, bounds, BoundKind::Bound);
2235 ItemKind::Mod(..) | ItemKind::ForeignMod(_) => {
2236 self.with_scope(item.id, |this| {
2237 visit::walk_item(this, item);
2241 ItemKind::Static(ref ty, _, ref expr) | ItemKind::Const(_, ref ty, ref expr) => {
2242 self.with_item_rib(|this| {
2243 this.with_lifetime_rib(LifetimeRibKind::Elided(LifetimeRes::Static), |this| {
2246 this.with_lifetime_rib(LifetimeRibKind::Elided(LifetimeRes::Infer), |this| {
2247 if let Some(expr) = expr {
2248 let constant_item_kind = match item.kind {
2249 ItemKind::Const(..) => ConstantItemKind::Const,
2250 ItemKind::Static(..) => ConstantItemKind::Static,
2251 _ => unreachable!(),
2253 // We already forbid generic params because of the above item rib,
2254 // so it doesn't matter whether this is a trivial constant.
2255 this.with_constant_rib(
2257 HasGenericParams::Yes,
2258 Some((item.ident, constant_item_kind)),
2259 |this| this.visit_expr(expr),
2266 ItemKind::Use(ref use_tree) => {
2267 self.future_proof_import(use_tree);
2270 ItemKind::ExternCrate(..) | ItemKind::MacroDef(..) => {
2271 // do nothing, these are just around to be encoded
2274 ItemKind::GlobalAsm(_) => {
2275 visit::walk_item(self, item);
2278 ItemKind::MacCall(_) => panic!("unexpanded macro in resolve!"),
2282 fn with_generic_param_rib<'c, F>(
2284 params: &'c [GenericParam],
2286 lifetime_kind: LifetimeRibKind,
2289 F: FnOnce(&mut Self),
2291 debug!("with_generic_param_rib");
2292 let LifetimeRibKind::Generics { binder, span: generics_span, kind: generics_kind, .. }
2293 = lifetime_kind else { panic!() };
2295 let mut function_type_rib = Rib::new(kind);
2296 let mut function_value_rib = Rib::new(kind);
2297 let mut function_lifetime_rib = LifetimeRib::new(lifetime_kind);
2298 let mut seen_bindings = FxHashMap::default();
2299 // Store all seen lifetimes names from outer scopes.
2300 let mut seen_lifetimes = FxHashSet::default();
2302 // We also can't shadow bindings from the parent item
2303 if let AssocItemRibKind = kind {
2304 let mut add_bindings_for_ns = |ns| {
2305 let parent_rib = self.ribs[ns]
2307 .rfind(|r| matches!(r.kind, ItemRibKind(_)))
2308 .expect("associated item outside of an item");
2310 .extend(parent_rib.bindings.iter().map(|(ident, _)| (*ident, ident.span)));
2312 add_bindings_for_ns(ValueNS);
2313 add_bindings_for_ns(TypeNS);
2316 // Forbid shadowing lifetime bindings
2317 for rib in self.lifetime_ribs.iter().rev() {
2318 seen_lifetimes.extend(rib.bindings.iter().map(|(ident, _)| *ident));
2319 if let LifetimeRibKind::Item = rib.kind {
2324 for param in params {
2325 let ident = param.ident.normalize_to_macros_2_0();
2326 debug!("with_generic_param_rib: {}", param.id);
2328 if let GenericParamKind::Lifetime = param.kind
2329 && let Some(&original) = seen_lifetimes.get(&ident)
2331 diagnostics::signal_lifetime_shadowing(self.r.session, original, param.ident);
2332 // Record lifetime res, so lowering knows there is something fishy.
2333 self.record_lifetime_param(param.id, LifetimeRes::Error);
2337 match seen_bindings.entry(ident) {
2338 Entry::Occupied(entry) => {
2339 let span = *entry.get();
2340 let err = ResolutionError::NameAlreadyUsedInParameterList(ident.name, span);
2341 self.report_error(param.ident.span, err);
2342 if let GenericParamKind::Lifetime = param.kind {
2343 // Record lifetime res, so lowering knows there is something fishy.
2344 self.record_lifetime_param(param.id, LifetimeRes::Error);
2348 Entry::Vacant(entry) => {
2349 entry.insert(param.ident.span);
2353 if param.ident.name == kw::UnderscoreLifetime {
2354 rustc_errors::struct_span_err!(
2358 "`'_` cannot be used here"
2360 .span_label(param.ident.span, "`'_` is a reserved lifetime name")
2362 // Record lifetime res, so lowering knows there is something fishy.
2363 self.record_lifetime_param(param.id, LifetimeRes::Error);
2367 if param.ident.name == kw::StaticLifetime {
2368 rustc_errors::struct_span_err!(
2372 "invalid lifetime parameter name: `{}`",
2375 .span_label(param.ident.span, "'static is a reserved lifetime name")
2377 // Record lifetime res, so lowering knows there is something fishy.
2378 self.record_lifetime_param(param.id, LifetimeRes::Error);
2382 let def_id = self.r.local_def_id(param.id);
2384 // Plain insert (no renaming).
2385 let (rib, def_kind) = match param.kind {
2386 GenericParamKind::Type { .. } => (&mut function_type_rib, DefKind::TyParam),
2387 GenericParamKind::Const { .. } => (&mut function_value_rib, DefKind::ConstParam),
2388 GenericParamKind::Lifetime => {
2389 let res = LifetimeRes::Param { param: def_id, binder };
2390 self.record_lifetime_param(param.id, res);
2391 function_lifetime_rib.bindings.insert(ident, (param.id, res));
2396 let res = match kind {
2397 ItemRibKind(..) | AssocItemRibKind => Res::Def(def_kind, def_id.to_def_id()),
2398 NormalRibKind => Res::Err,
2399 _ => span_bug!(param.ident.span, "Unexpected rib kind {:?}", kind),
2401 self.r.record_partial_res(param.id, PartialRes::new(res));
2402 rib.bindings.insert(ident, res);
2405 self.lifetime_ribs.push(function_lifetime_rib);
2406 self.ribs[ValueNS].push(function_value_rib);
2407 self.ribs[TypeNS].push(function_type_rib);
2411 self.ribs[TypeNS].pop();
2412 self.ribs[ValueNS].pop();
2413 let function_lifetime_rib = self.lifetime_ribs.pop().unwrap();
2415 // Do not account for the parameters we just bound for function lifetime elision.
2416 if let Some(ref mut candidates) = self.lifetime_elision_candidates {
2417 for (_, res) in function_lifetime_rib.bindings.values() {
2418 candidates.remove(res);
2422 if let LifetimeBinderKind::BareFnType
2423 | LifetimeBinderKind::WhereBound
2424 | LifetimeBinderKind::Function
2425 | LifetimeBinderKind::ImplBlock = generics_kind
2427 self.maybe_report_lifetime_uses(generics_span, params)
2431 fn with_label_rib(&mut self, kind: RibKind<'a>, f: impl FnOnce(&mut Self)) {
2432 self.label_ribs.push(Rib::new(kind));
2434 self.label_ribs.pop();
2437 fn with_item_rib(&mut self, f: impl FnOnce(&mut Self)) {
2438 let kind = ItemRibKind(HasGenericParams::No);
2439 self.with_lifetime_rib(LifetimeRibKind::Item, |this| {
2440 this.with_rib(ValueNS, kind, |this| this.with_rib(TypeNS, kind, f))
2444 // HACK(min_const_generics,const_evaluatable_unchecked): We
2445 // want to keep allowing `[0; std::mem::size_of::<*mut T>()]`
2446 // with a future compat lint for now. We do this by adding an
2447 // additional special case for repeat expressions.
2449 // Note that we intentionally still forbid `[0; N + 1]` during
2450 // name resolution so that we don't extend the future
2451 // compat lint to new cases.
2452 #[instrument(level = "debug", skip(self, f))]
2453 fn with_constant_rib(
2455 is_repeat: IsRepeatExpr,
2456 may_use_generics: HasGenericParams,
2457 item: Option<(Ident, ConstantItemKind)>,
2458 f: impl FnOnce(&mut Self),
2460 self.with_rib(ValueNS, ConstantItemRibKind(may_use_generics, item), |this| {
2463 ConstantItemRibKind(
2464 may_use_generics.force_yes_if(is_repeat == IsRepeatExpr::Yes),
2468 this.with_label_rib(ConstantItemRibKind(may_use_generics, item), f);
2474 fn with_current_self_type<T>(&mut self, self_type: &Ty, f: impl FnOnce(&mut Self) -> T) -> T {
2475 // Handle nested impls (inside fn bodies)
2476 let previous_value =
2477 replace(&mut self.diagnostic_metadata.current_self_type, Some(self_type.clone()));
2478 let result = f(self);
2479 self.diagnostic_metadata.current_self_type = previous_value;
2483 fn with_current_self_item<T>(&mut self, self_item: &Item, f: impl FnOnce(&mut Self) -> T) -> T {
2484 let previous_value =
2485 replace(&mut self.diagnostic_metadata.current_self_item, Some(self_item.id));
2486 let result = f(self);
2487 self.diagnostic_metadata.current_self_item = previous_value;
2491 /// When evaluating a `trait` use its associated types' idents for suggestions in E0412.
2492 fn resolve_trait_items(&mut self, trait_items: &'ast [P<AssocItem>]) {
2493 let trait_assoc_items =
2494 replace(&mut self.diagnostic_metadata.current_trait_assoc_items, Some(&trait_items));
2496 let walk_assoc_item =
2497 |this: &mut Self, generics: &Generics, kind, item: &'ast AssocItem| {
2498 this.with_generic_param_rib(
2501 LifetimeRibKind::Generics { binder: item.id, span: generics.span, kind },
2502 |this| visit::walk_assoc_item(this, item, AssocCtxt::Trait),
2506 for item in trait_items {
2508 AssocItemKind::Const(_, ty, default) => {
2510 // Only impose the restrictions of `ConstRibKind` for an
2511 // actual constant expression in a provided default.
2512 if let Some(expr) = default {
2513 // We allow arbitrary const expressions inside of associated consts,
2514 // even if they are potentially not const evaluatable.
2516 // Type parameters can already be used and as associated consts are
2517 // not used as part of the type system, this is far less surprising.
2518 self.with_lifetime_rib(
2519 LifetimeRibKind::Elided(LifetimeRes::Infer),
2521 this.with_constant_rib(
2523 HasGenericParams::Yes,
2525 |this| this.visit_expr(expr),
2531 AssocItemKind::Fn(box Fn { generics, .. }) => {
2532 walk_assoc_item(self, generics, LifetimeBinderKind::Function, item);
2534 AssocItemKind::TyAlias(box TyAlias { generics, .. }) => self
2535 .with_lifetime_rib(LifetimeRibKind::AnonymousReportError, |this| {
2536 walk_assoc_item(this, generics, LifetimeBinderKind::Item, item)
2538 AssocItemKind::MacCall(_) => {
2539 panic!("unexpanded macro in resolve!")
2544 self.diagnostic_metadata.current_trait_assoc_items = trait_assoc_items;
2547 /// This is called to resolve a trait reference from an `impl` (i.e., `impl Trait for Foo`).
2548 fn with_optional_trait_ref<T>(
2550 opt_trait_ref: Option<&TraitRef>,
2551 self_type: &'ast Ty,
2552 f: impl FnOnce(&mut Self, Option<DefId>) -> T,
2554 let mut new_val = None;
2555 let mut new_id = None;
2556 if let Some(trait_ref) = opt_trait_ref {
2557 let path: Vec<_> = Segment::from_path(&trait_ref.path);
2558 self.diagnostic_metadata.currently_processing_impl_trait =
2559 Some((trait_ref.clone(), self_type.clone()));
2560 let res = self.smart_resolve_path_fragment(
2563 PathSource::Trait(AliasPossibility::No),
2564 Finalize::new(trait_ref.ref_id, trait_ref.path.span),
2566 self.diagnostic_metadata.currently_processing_impl_trait = None;
2567 if let Some(def_id) = res.base_res().opt_def_id() {
2568 new_id = Some(def_id);
2569 new_val = Some((self.r.expect_module(def_id), trait_ref.clone()));
2572 let original_trait_ref = replace(&mut self.current_trait_ref, new_val);
2573 let result = f(self, new_id);
2574 self.current_trait_ref = original_trait_ref;
2578 fn with_self_rib_ns(&mut self, ns: Namespace, self_res: Res, f: impl FnOnce(&mut Self)) {
2579 let mut self_type_rib = Rib::new(NormalRibKind);
2581 // Plain insert (no renaming, since types are not currently hygienic)
2582 self_type_rib.bindings.insert(Ident::with_dummy_span(kw::SelfUpper), self_res);
2583 self.ribs[ns].push(self_type_rib);
2585 self.ribs[ns].pop();
2588 fn with_self_rib(&mut self, self_res: Res, f: impl FnOnce(&mut Self)) {
2589 self.with_self_rib_ns(TypeNS, self_res, f)
2592 fn resolve_implementation(
2594 generics: &'ast Generics,
2595 opt_trait_reference: &'ast Option<TraitRef>,
2596 self_type: &'ast Ty,
2598 impl_items: &'ast [P<AssocItem>],
2600 debug!("resolve_implementation");
2601 // If applicable, create a rib for the type parameters.
2602 self.with_generic_param_rib(
2604 ItemRibKind(HasGenericParams::Yes),
2605 LifetimeRibKind::Generics {
2606 span: generics.span,
2608 kind: LifetimeBinderKind::ImplBlock,
2611 // Dummy self type for better errors if `Self` is used in the trait path.
2612 this.with_self_rib(Res::SelfTy { trait_: None, alias_to: None }, |this| {
2613 this.with_lifetime_rib(
2614 LifetimeRibKind::AnonymousCreateParameter {
2616 report_in_path: true
2619 // Resolve the trait reference, if necessary.
2620 this.with_optional_trait_ref(
2621 opt_trait_reference.as_ref(),
2624 let item_def_id = this.r.local_def_id(item_id);
2626 // Register the trait definitions from here.
2627 if let Some(trait_id) = trait_id {
2635 let item_def_id = item_def_id.to_def_id();
2636 let res = Res::SelfTy {
2638 alias_to: Some((item_def_id, false)),
2640 this.with_self_rib(res, |this| {
2641 if let Some(trait_ref) = opt_trait_reference.as_ref() {
2642 // Resolve type arguments in the trait path.
2643 visit::walk_trait_ref(this, trait_ref);
2645 // Resolve the self type.
2646 this.visit_ty(self_type);
2647 // Resolve the generic parameters.
2648 this.visit_generics(generics);
2650 // Resolve the items within the impl.
2651 this.with_current_self_type(self_type, |this| {
2652 this.with_self_rib_ns(ValueNS, Res::SelfCtor(item_def_id), |this| {
2653 debug!("resolve_implementation with_self_rib_ns(ValueNS, ...)");
2654 for item in impl_items {
2655 this.resolve_impl_item(&**item);
2669 fn resolve_impl_item(&mut self, item: &'ast AssocItem) {
2670 use crate::ResolutionError::*;
2672 AssocItemKind::Const(_, ty, default) => {
2673 debug!("resolve_implementation AssocItemKind::Const");
2674 // If this is a trait impl, ensure the const
2676 self.check_trait_item(
2682 |i, s, c| ConstNotMemberOfTrait(i, s, c),
2686 if let Some(expr) = default {
2687 // We allow arbitrary const expressions inside of associated consts,
2688 // even if they are potentially not const evaluatable.
2690 // Type parameters can already be used and as associated consts are
2691 // not used as part of the type system, this is far less surprising.
2692 self.with_lifetime_rib(LifetimeRibKind::Elided(LifetimeRes::Infer), |this| {
2693 this.with_constant_rib(
2695 HasGenericParams::Yes,
2697 |this| this.visit_expr(expr),
2702 AssocItemKind::Fn(box Fn { generics, .. }) => {
2703 debug!("resolve_implementation AssocItemKind::Fn");
2704 // We also need a new scope for the impl item type parameters.
2705 self.with_generic_param_rib(
2708 LifetimeRibKind::Generics {
2710 span: generics.span,
2711 kind: LifetimeBinderKind::Function,
2714 // If this is a trait impl, ensure the method
2716 this.check_trait_item(
2722 |i, s, c| MethodNotMemberOfTrait(i, s, c),
2725 visit::walk_assoc_item(this, item, AssocCtxt::Impl)
2729 AssocItemKind::TyAlias(box TyAlias { generics, .. }) => {
2730 debug!("resolve_implementation AssocItemKind::TyAlias");
2731 // We also need a new scope for the impl item type parameters.
2732 self.with_generic_param_rib(
2735 LifetimeRibKind::Generics {
2737 span: generics.span,
2738 kind: LifetimeBinderKind::Item,
2741 this.with_lifetime_rib(LifetimeRibKind::AnonymousReportError, |this| {
2742 // If this is a trait impl, ensure the type
2744 this.check_trait_item(
2750 |i, s, c| TypeNotMemberOfTrait(i, s, c),
2753 visit::walk_assoc_item(this, item, AssocCtxt::Impl)
2758 AssocItemKind::MacCall(_) => {
2759 panic!("unexpanded macro in resolve!")
2764 fn check_trait_item<F>(
2768 kind: &AssocItemKind,
2773 F: FnOnce(Ident, String, Option<Symbol>) -> ResolutionError<'a>,
2775 // If there is a TraitRef in scope for an impl, then the method must be in the trait.
2776 let Some((module, _)) = &self.current_trait_ref else { return; };
2777 ident.span.normalize_to_macros_2_0_and_adjust(module.expansion);
2778 let key = self.r.new_key(ident, ns);
2779 let mut binding = self.r.resolution(module, key).try_borrow().ok().and_then(|r| r.binding);
2781 if binding.is_none() {
2782 // We could not find the trait item in the correct namespace.
2783 // Check the other namespace to report an error.
2789 let key = self.r.new_key(ident, ns);
2790 binding = self.r.resolution(module, key).try_borrow().ok().and_then(|r| r.binding);
2793 let Some(binding) = binding else {
2794 // We could not find the method: report an error.
2795 let candidate = self.find_similarly_named_assoc_item(ident.name, kind);
2796 let path = &self.current_trait_ref.as_ref().unwrap().1.path;
2797 let path_names = path_names_to_string(path);
2798 self.report_error(span, err(ident, path_names, candidate));
2802 let res = binding.res();
2803 let Res::Def(def_kind, _) = res else { bug!() };
2804 match (def_kind, kind) {
2805 (DefKind::AssocTy, AssocItemKind::TyAlias(..))
2806 | (DefKind::AssocFn, AssocItemKind::Fn(..))
2807 | (DefKind::AssocConst, AssocItemKind::Const(..)) => {
2808 self.r.record_partial_res(id, PartialRes::new(res));
2814 // The method kind does not correspond to what appeared in the trait, report.
2815 let path = &self.current_trait_ref.as_ref().unwrap().1.path;
2816 let (code, kind) = match kind {
2817 AssocItemKind::Const(..) => (rustc_errors::error_code!(E0323), "const"),
2818 AssocItemKind::Fn(..) => (rustc_errors::error_code!(E0324), "method"),
2819 AssocItemKind::TyAlias(..) => (rustc_errors::error_code!(E0325), "type"),
2820 AssocItemKind::MacCall(..) => span_bug!(span, "unexpanded macro"),
2822 let trait_path = path_names_to_string(path);
2825 ResolutionError::TraitImplMismatch {
2830 trait_item_span: binding.span,
2835 fn resolve_params(&mut self, params: &'ast [Param]) {
2836 let mut bindings = smallvec![(PatBoundCtx::Product, Default::default())];
2837 for Param { pat, ty, .. } in params {
2838 self.resolve_pattern(pat, PatternSource::FnParam, &mut bindings);
2840 debug!("(resolving function / closure) recorded parameter");
2844 fn resolve_local(&mut self, local: &'ast Local) {
2845 debug!("resolving local ({:?})", local);
2846 // Resolve the type.
2847 walk_list!(self, visit_ty, &local.ty);
2849 // Resolve the initializer.
2850 if let Some((init, els)) = local.kind.init_else_opt() {
2851 self.visit_expr(init);
2853 // Resolve the `else` block
2854 if let Some(els) = els {
2855 self.visit_block(els);
2859 // Resolve the pattern.
2860 self.resolve_pattern_top(&local.pat, PatternSource::Let);
2863 /// build a map from pattern identifiers to binding-info's.
2864 /// this is done hygienically. This could arise for a macro
2865 /// that expands into an or-pattern where one 'x' was from the
2866 /// user and one 'x' came from the macro.
2867 fn binding_mode_map(&mut self, pat: &Pat) -> BindingMap {
2868 let mut binding_map = FxHashMap::default();
2870 pat.walk(&mut |pat| {
2872 PatKind::Ident(binding_mode, ident, ref sub_pat)
2873 if sub_pat.is_some() || self.is_base_res_local(pat.id) =>
2875 binding_map.insert(ident, BindingInfo { span: ident.span, binding_mode });
2877 PatKind::Or(ref ps) => {
2878 // Check the consistency of this or-pattern and
2879 // then add all bindings to the larger map.
2880 for bm in self.check_consistent_bindings(ps) {
2881 binding_map.extend(bm);
2894 fn is_base_res_local(&self, nid: NodeId) -> bool {
2895 matches!(self.r.partial_res_map.get(&nid).map(|res| res.base_res()), Some(Res::Local(..)))
2898 /// Checks that all of the arms in an or-pattern have exactly the
2899 /// same set of bindings, with the same binding modes for each.
2900 fn check_consistent_bindings(&mut self, pats: &[P<Pat>]) -> Vec<BindingMap> {
2901 let mut missing_vars = FxHashMap::default();
2902 let mut inconsistent_vars = FxHashMap::default();
2904 // 1) Compute the binding maps of all arms.
2905 let maps = pats.iter().map(|pat| self.binding_mode_map(pat)).collect::<Vec<_>>();
2907 // 2) Record any missing bindings or binding mode inconsistencies.
2908 for (map_outer, pat_outer) in pats.iter().enumerate().map(|(idx, pat)| (&maps[idx], pat)) {
2909 // Check against all arms except for the same pattern which is always self-consistent.
2913 .filter(|(_, pat)| pat.id != pat_outer.id)
2914 .flat_map(|(idx, _)| maps[idx].iter())
2915 .map(|(key, binding)| (key.name, map_outer.get(&key), binding));
2917 for (name, info, &binding_inner) in inners {
2920 // The inner binding is missing in the outer.
2922 missing_vars.entry(name).or_insert_with(|| BindingError {
2924 origin: BTreeSet::new(),
2925 target: BTreeSet::new(),
2926 could_be_path: name.as_str().starts_with(char::is_uppercase),
2928 binding_error.origin.insert(binding_inner.span);
2929 binding_error.target.insert(pat_outer.span);
2931 Some(binding_outer) => {
2932 if binding_outer.binding_mode != binding_inner.binding_mode {
2933 // The binding modes in the outer and inner bindings differ.
2936 .or_insert((binding_inner.span, binding_outer.span));
2943 // 3) Report all missing variables we found.
2944 let mut missing_vars = missing_vars.into_iter().collect::<Vec<_>>();
2945 missing_vars.sort_by_key(|&(sym, ref _err)| sym);
2947 for (name, mut v) in missing_vars.into_iter() {
2948 if inconsistent_vars.contains_key(&name) {
2949 v.could_be_path = false;
2952 *v.origin.iter().next().unwrap(),
2953 ResolutionError::VariableNotBoundInPattern(v, self.parent_scope),
2957 // 4) Report all inconsistencies in binding modes we found.
2958 let mut inconsistent_vars = inconsistent_vars.iter().collect::<Vec<_>>();
2959 inconsistent_vars.sort();
2960 for (name, v) in inconsistent_vars {
2961 self.report_error(v.0, ResolutionError::VariableBoundWithDifferentMode(*name, v.1));
2964 // 5) Finally bubble up all the binding maps.
2968 /// Check the consistency of the outermost or-patterns.
2969 fn check_consistent_bindings_top(&mut self, pat: &'ast Pat) {
2970 pat.walk(&mut |pat| match pat.kind {
2971 PatKind::Or(ref ps) => {
2972 self.check_consistent_bindings(ps);
2979 fn resolve_arm(&mut self, arm: &'ast Arm) {
2980 self.with_rib(ValueNS, NormalRibKind, |this| {
2981 this.resolve_pattern_top(&arm.pat, PatternSource::Match);
2982 walk_list!(this, visit_expr, &arm.guard);
2983 this.visit_expr(&arm.body);
2987 /// Arising from `source`, resolve a top level pattern.
2988 fn resolve_pattern_top(&mut self, pat: &'ast Pat, pat_src: PatternSource) {
2989 let mut bindings = smallvec![(PatBoundCtx::Product, Default::default())];
2990 self.resolve_pattern(pat, pat_src, &mut bindings);
2996 pat_src: PatternSource,
2997 bindings: &mut SmallVec<[(PatBoundCtx, FxHashSet<Ident>); 1]>,
2999 // We walk the pattern before declaring the pattern's inner bindings,
3000 // so that we avoid resolving a literal expression to a binding defined
3002 visit::walk_pat(self, pat);
3003 self.resolve_pattern_inner(pat, pat_src, bindings);
3004 // This has to happen *after* we determine which pat_idents are variants:
3005 self.check_consistent_bindings_top(pat);
3008 /// Resolve bindings in a pattern. This is a helper to `resolve_pattern`.
3012 /// A stack of sets of bindings accumulated.
3014 /// In each set, `PatBoundCtx::Product` denotes that a found binding in it should
3015 /// be interpreted as re-binding an already bound binding. This results in an error.
3016 /// Meanwhile, `PatBound::Or` denotes that a found binding in the set should result
3017 /// in reusing this binding rather than creating a fresh one.
3019 /// When called at the top level, the stack must have a single element
3020 /// with `PatBound::Product`. Otherwise, pushing to the stack happens as
3021 /// or-patterns (`p_0 | ... | p_n`) are encountered and the context needs
3022 /// to be switched to `PatBoundCtx::Or` and then `PatBoundCtx::Product` for each `p_i`.
3023 /// When each `p_i` has been dealt with, the top set is merged with its parent.
3024 /// When a whole or-pattern has been dealt with, the thing happens.
3026 /// See the implementation and `fresh_binding` for more details.
3027 fn resolve_pattern_inner(
3030 pat_src: PatternSource,
3031 bindings: &mut SmallVec<[(PatBoundCtx, FxHashSet<Ident>); 1]>,
3033 // Visit all direct subpatterns of this pattern.
3034 pat.walk(&mut |pat| {
3035 debug!("resolve_pattern pat={:?} node={:?}", pat, pat.kind);
3037 PatKind::Ident(bmode, ident, ref sub) => {
3038 // First try to resolve the identifier as some existing entity,
3039 // then fall back to a fresh binding.
3040 let has_sub = sub.is_some();
3042 .try_resolve_as_non_binding(pat_src, bmode, ident, has_sub)
3043 .unwrap_or_else(|| self.fresh_binding(ident, pat.id, pat_src, bindings));
3044 self.r.record_partial_res(pat.id, PartialRes::new(res));
3045 self.r.record_pat_span(pat.id, pat.span);
3047 PatKind::TupleStruct(ref qself, ref path, ref sub_patterns) => {
3048 self.smart_resolve_path(
3052 PathSource::TupleStruct(
3054 self.r.arenas.alloc_pattern_spans(sub_patterns.iter().map(|p| p.span)),
3058 PatKind::Path(ref qself, ref path) => {
3059 self.smart_resolve_path(pat.id, qself.as_ref(), path, PathSource::Pat);
3061 PatKind::Struct(ref qself, ref path, ..) => {
3062 self.smart_resolve_path(pat.id, qself.as_ref(), path, PathSource::Struct);
3064 PatKind::Or(ref ps) => {
3065 // Add a new set of bindings to the stack. `Or` here records that when a
3066 // binding already exists in this set, it should not result in an error because
3067 // `V1(a) | V2(a)` must be allowed and are checked for consistency later.
3068 bindings.push((PatBoundCtx::Or, Default::default()));
3070 // Now we need to switch back to a product context so that each
3071 // part of the or-pattern internally rejects already bound names.
3072 // For example, `V1(a) | V2(a, a)` and `V1(a, a) | V2(a)` are bad.
3073 bindings.push((PatBoundCtx::Product, Default::default()));
3074 self.resolve_pattern_inner(p, pat_src, bindings);
3075 // Move up the non-overlapping bindings to the or-pattern.
3076 // Existing bindings just get "merged".
3077 let collected = bindings.pop().unwrap().1;
3078 bindings.last_mut().unwrap().1.extend(collected);
3080 // This or-pattern itself can itself be part of a product,
3081 // e.g. `(V1(a) | V2(a), a)` or `(a, V1(a) | V2(a))`.
3082 // Both cases bind `a` again in a product pattern and must be rejected.
3083 let collected = bindings.pop().unwrap().1;
3084 bindings.last_mut().unwrap().1.extend(collected);
3086 // Prevent visiting `ps` as we've already done so above.
3099 pat_src: PatternSource,
3100 bindings: &mut SmallVec<[(PatBoundCtx, FxHashSet<Ident>); 1]>,
3102 // Add the binding to the local ribs, if it doesn't already exist in the bindings map.
3103 // (We must not add it if it's in the bindings map because that breaks the assumptions
3104 // later passes make about or-patterns.)
3105 let ident = ident.normalize_to_macro_rules();
3107 let mut bound_iter = bindings.iter().filter(|(_, set)| set.contains(&ident));
3108 // Already bound in a product pattern? e.g. `(a, a)` which is not allowed.
3109 let already_bound_and = bound_iter.clone().any(|(ctx, _)| *ctx == PatBoundCtx::Product);
3110 // Already bound in an or-pattern? e.g. `V1(a) | V2(a)`.
3111 // This is *required* for consistency which is checked later.
3112 let already_bound_or = bound_iter.any(|(ctx, _)| *ctx == PatBoundCtx::Or);
3114 if already_bound_and {
3115 // Overlap in a product pattern somewhere; report an error.
3116 use ResolutionError::*;
3117 let error = match pat_src {
3118 // `fn f(a: u8, a: u8)`:
3119 PatternSource::FnParam => IdentifierBoundMoreThanOnceInParameterList,
3121 _ => IdentifierBoundMoreThanOnceInSamePattern,
3123 self.report_error(ident.span, error(ident.name));
3126 // Record as bound if it's valid:
3127 let ident_valid = ident.name != kw::Empty;
3129 bindings.last_mut().unwrap().1.insert(ident);
3132 if already_bound_or {
3133 // `Variant1(a) | Variant2(a)`, ok
3134 // Reuse definition from the first `a`.
3135 self.innermost_rib_bindings(ValueNS)[&ident]
3137 let res = Res::Local(pat_id);
3139 // A completely fresh binding add to the set if it's valid.
3140 self.innermost_rib_bindings(ValueNS).insert(ident, res);
3146 fn innermost_rib_bindings(&mut self, ns: Namespace) -> &mut IdentMap<Res> {
3147 &mut self.ribs[ns].last_mut().unwrap().bindings
3150 fn try_resolve_as_non_binding(
3152 pat_src: PatternSource,
3157 // An immutable (no `mut`) by-value (no `ref`) binding pattern without
3158 // a sub pattern (no `@ $pat`) is syntactically ambiguous as it could
3159 // also be interpreted as a path to e.g. a constant, variant, etc.
3160 let is_syntactic_ambiguity = !has_sub && bm == BindingMode::ByValue(Mutability::Not);
3162 let ls_binding = self.maybe_resolve_ident_in_lexical_scope(ident, ValueNS)?;
3163 let (res, binding) = match ls_binding {
3164 LexicalScopeBinding::Item(binding)
3165 if is_syntactic_ambiguity && binding.is_ambiguity() =>
3167 // For ambiguous bindings we don't know all their definitions and cannot check
3168 // whether they can be shadowed by fresh bindings or not, so force an error.
3169 // issues/33118#issuecomment-233962221 (see below) still applies here,
3170 // but we have to ignore it for backward compatibility.
3171 self.r.record_use(ident, binding, false);
3174 LexicalScopeBinding::Item(binding) => (binding.res(), Some(binding)),
3175 LexicalScopeBinding::Res(res) => (res, None),
3179 Res::SelfCtor(_) // See #70549.
3181 DefKind::Ctor(_, CtorKind::Const) | DefKind::Const | DefKind::ConstParam,
3183 ) if is_syntactic_ambiguity => {
3184 // Disambiguate in favor of a unit struct/variant or constant pattern.
3185 if let Some(binding) = binding {
3186 self.r.record_use(ident, binding, false);
3190 Res::Def(DefKind::Ctor(..) | DefKind::Const | DefKind::Static(_), _) => {
3191 // This is unambiguously a fresh binding, either syntactically
3192 // (e.g., `IDENT @ PAT` or `ref IDENT`) or because `IDENT` resolves
3193 // to something unusable as a pattern (e.g., constructor function),
3194 // but we still conservatively report an error, see
3195 // issues/33118#issuecomment-233962221 for one reason why.
3196 let binding = binding.expect("no binding for a ctor or static");
3199 ResolutionError::BindingShadowsSomethingUnacceptable {
3200 shadowing_binding: pat_src,
3202 participle: if binding.is_import() { "imported" } else { "defined" },
3203 article: binding.res().article(),
3204 shadowed_binding: binding.res(),
3205 shadowed_binding_span: binding.span,
3210 Res::Def(DefKind::ConstParam, def_id) => {
3211 // Same as for DefKind::Const above, but here, `binding` is `None`, so we
3212 // have to construct the error differently
3215 ResolutionError::BindingShadowsSomethingUnacceptable {
3216 shadowing_binding: pat_src,
3218 participle: "defined",
3219 article: res.article(),
3220 shadowed_binding: res,
3221 shadowed_binding_span: self.r.opt_span(def_id).expect("const parameter defined outside of local crate"),
3226 Res::Def(DefKind::Fn, _) | Res::Local(..) | Res::Err => {
3227 // These entities are explicitly allowed to be shadowed by fresh bindings.
3230 Res::SelfCtor(_) => {
3231 // We resolve `Self` in pattern position as an ident sometimes during recovery,
3232 // so delay a bug instead of ICEing.
3233 self.r.session.delay_span_bug(
3235 "unexpected `SelfCtor` in pattern, expected identifier"
3241 "unexpected resolution for an identifier in pattern: {:?}",
3247 // High-level and context dependent path resolution routine.
3248 // Resolves the path and records the resolution into definition map.
3249 // If resolution fails tries several techniques to find likely
3250 // resolution candidates, suggest imports or other help, and report
3251 // errors in user friendly way.
3252 fn smart_resolve_path(
3255 qself: Option<&QSelf>,
3257 source: PathSource<'ast>,
3259 self.smart_resolve_path_fragment(
3261 &Segment::from_path(path),
3263 Finalize::new(id, path.span),
3267 fn smart_resolve_path_fragment(
3269 qself: Option<&QSelf>,
3271 source: PathSource<'ast>,
3275 "smart_resolve_path_fragment(qself={:?}, path={:?}, finalize={:?})",
3280 let ns = source.namespace();
3282 let Finalize { node_id, path_span, .. } = finalize;
3283 let report_errors = |this: &mut Self, res: Option<Res>| {
3284 if this.should_report_errs() {
3285 let (err, candidates) =
3286 this.smart_resolve_report_errors(path, path_span, source, res);
3288 let def_id = this.parent_scope.module.nearest_parent_mod();
3289 let instead = res.is_some();
3291 if res.is_none() { this.report_missing_type_error(path) } else { None };
3293 this.r.use_injections.push(UseError {
3303 PartialRes::new(Res::Err)
3306 // For paths originating from calls (like in `HashMap::new()`), tries
3307 // to enrich the plain `failed to resolve: ...` message with hints
3308 // about possible missing imports.
3310 // Similar thing, for types, happens in `report_errors` above.
3311 let report_errors_for_call = |this: &mut Self, parent_err: Spanned<ResolutionError<'a>>| {
3312 if !source.is_call() {
3313 return Some(parent_err);
3316 // Before we start looking for candidates, we have to get our hands
3317 // on the type user is trying to perform invocation on; basically:
3318 // we're transforming `HashMap::new` into just `HashMap`.
3319 let path = match path.split_last() {
3320 Some((_, path)) if !path.is_empty() => path,
3321 _ => return Some(parent_err),
3324 let (mut err, candidates) =
3325 this.smart_resolve_report_errors(path, path_span, PathSource::Type, None);
3327 if candidates.is_empty() {
3329 return Some(parent_err);
3332 // There are two different error messages user might receive at
3334 // - E0412 cannot find type `{}` in this scope
3335 // - E0433 failed to resolve: use of undeclared type or module `{}`
3337 // The first one is emitted for paths in type-position, and the
3338 // latter one - for paths in expression-position.
3340 // Thus (since we're in expression-position at this point), not to
3341 // confuse the user, we want to keep the *message* from E0432 (so
3342 // `parent_err`), but we want *hints* from E0412 (so `err`).
3344 // And that's what happens below - we're just mixing both messages
3345 // into a single one.
3346 let mut parent_err = this.r.into_struct_error(parent_err.span, parent_err.node);
3348 err.message = take(&mut parent_err.message);
3349 err.code = take(&mut parent_err.code);
3350 err.children = take(&mut parent_err.children);
3352 parent_err.cancel();
3354 let def_id = this.parent_scope.module.nearest_parent_mod();
3356 if this.should_report_errs() {
3357 this.r.use_injections.push(UseError {
3369 // We don't return `Some(parent_err)` here, because the error will
3370 // be already printed as part of the `use` injections
3374 let partial_res = match self.resolve_qpath_anywhere(
3379 source.defer_to_typeck(),
3382 Ok(Some(partial_res)) if partial_res.unresolved_segments() == 0 => {
3383 if source.is_expected(partial_res.base_res()) || partial_res.base_res() == Res::Err
3387 report_errors(self, Some(partial_res.base_res()))
3391 Ok(Some(partial_res)) if source.defer_to_typeck() => {
3392 // Not fully resolved associated item `T::A::B` or `<T as Tr>::A::B`
3393 // or `<T>::A::B`. If `B` should be resolved in value namespace then
3394 // it needs to be added to the trait map.
3396 let item_name = path.last().unwrap().ident;
3397 let traits = self.traits_in_scope(item_name, ns);
3398 self.r.trait_map.insert(node_id, traits);
3401 if PrimTy::from_name(path[0].ident.name).is_some() {
3402 let mut std_path = Vec::with_capacity(1 + path.len());
3404 std_path.push(Segment::from_ident(Ident::with_dummy_span(sym::std)));
3405 std_path.extend(path);
3406 if let PathResult::Module(_) | PathResult::NonModule(_) =
3407 self.resolve_path(&std_path, Some(ns), None)
3409 // Check if we wrote `str::from_utf8` instead of `std::str::from_utf8`
3411 path.iter().last().map_or(path_span, |segment| segment.ident.span);
3413 self.r.confused_type_with_std_module.insert(item_span, path_span);
3414 self.r.confused_type_with_std_module.insert(path_span, path_span);
3422 if let Some(err) = report_errors_for_call(self, err) {
3423 self.report_error(err.span, err.node);
3426 PartialRes::new(Res::Err)
3429 _ => report_errors(self, None),
3432 if !matches!(source, PathSource::TraitItem(..)) {
3433 // Avoid recording definition of `A::B` in `<T as A>::B::C`.
3434 self.r.record_partial_res(node_id, partial_res);
3435 self.resolve_elided_lifetimes_in_path(node_id, partial_res, path, source, path_span);
3441 fn self_type_is_available(&mut self) -> bool {
3443 .maybe_resolve_ident_in_lexical_scope(Ident::with_dummy_span(kw::SelfUpper), TypeNS);
3444 if let Some(LexicalScopeBinding::Res(res)) = binding { res != Res::Err } else { false }
3447 fn self_value_is_available(&mut self, self_span: Span) -> bool {
3448 let ident = Ident::new(kw::SelfLower, self_span);
3449 let binding = self.maybe_resolve_ident_in_lexical_scope(ident, ValueNS);
3450 if let Some(LexicalScopeBinding::Res(res)) = binding { res != Res::Err } else { false }
3453 /// A wrapper around [`Resolver::report_error`].
3455 /// This doesn't emit errors for function bodies if this is rustdoc.
3456 fn report_error(&mut self, span: Span, resolution_error: ResolutionError<'a>) {
3457 if self.should_report_errs() {
3458 self.r.report_error(span, resolution_error);
3463 /// If we're actually rustdoc then avoid giving a name resolution error for `cfg()` items.
3464 fn should_report_errs(&self) -> bool {
3465 !(self.r.session.opts.actually_rustdoc && self.in_func_body)
3468 // Resolve in alternative namespaces if resolution in the primary namespace fails.
3469 fn resolve_qpath_anywhere(
3471 qself: Option<&QSelf>,
3473 primary_ns: Namespace,
3475 defer_to_typeck: bool,
3477 ) -> Result<Option<PartialRes>, Spanned<ResolutionError<'a>>> {
3478 let mut fin_res = None;
3480 for (i, &ns) in [primary_ns, TypeNS, ValueNS].iter().enumerate() {
3481 if i == 0 || ns != primary_ns {
3482 match self.resolve_qpath(qself, path, ns, finalize)? {
3484 if partial_res.unresolved_segments() == 0 || defer_to_typeck =>
3486 return Ok(Some(partial_res));
3489 if fin_res.is_none() {
3490 fin_res = partial_res;
3497 assert!(primary_ns != MacroNS);
3499 if qself.is_none() {
3500 let path_seg = |seg: &Segment| PathSegment::from_ident(seg.ident);
3501 let path = Path { segments: path.iter().map(path_seg).collect(), span, tokens: None };
3502 if let Ok((_, res)) =
3503 self.r.resolve_macro_path(&path, None, &self.parent_scope, false, false)
3505 return Ok(Some(PartialRes::new(res)));
3512 /// Handles paths that may refer to associated items.
3515 qself: Option<&QSelf>,
3519 ) -> Result<Option<PartialRes>, Spanned<ResolutionError<'a>>> {
3521 "resolve_qpath(qself={:?}, path={:?}, ns={:?}, finalize={:?})",
3522 qself, path, ns, finalize,
3525 if let Some(qself) = qself {
3526 if qself.position == 0 {
3527 // This is a case like `<T>::B`, where there is no
3528 // trait to resolve. In that case, we leave the `B`
3529 // segment to be resolved by type-check.
3530 return Ok(Some(PartialRes::with_unresolved_segments(
3531 Res::Def(DefKind::Mod, CRATE_DEF_ID.to_def_id()),
3536 // Make sure `A::B` in `<T as A::B>::C` is a trait item.
3538 // Currently, `path` names the full item (`A::B::C`, in
3539 // our example). so we extract the prefix of that that is
3540 // the trait (the slice upto and including
3541 // `qself.position`). And then we recursively resolve that,
3542 // but with `qself` set to `None`.
3543 let ns = if qself.position + 1 == path.len() { ns } else { TypeNS };
3544 let partial_res = self.smart_resolve_path_fragment(
3546 &path[..=qself.position],
3547 PathSource::TraitItem(ns),
3548 Finalize::with_root_span(finalize.node_id, finalize.path_span, qself.path_span),
3551 // The remaining segments (the `C` in our example) will
3552 // have to be resolved by type-check, since that requires doing
3553 // trait resolution.
3554 return Ok(Some(PartialRes::with_unresolved_segments(
3555 partial_res.base_res(),
3556 partial_res.unresolved_segments() + path.len() - qself.position - 1,
3560 let result = match self.resolve_path(&path, Some(ns), Some(finalize)) {
3561 PathResult::NonModule(path_res) => path_res,
3562 PathResult::Module(ModuleOrUniformRoot::Module(module)) if !module.is_normal() => {
3563 PartialRes::new(module.res().unwrap())
3565 // In `a(::assoc_item)*` `a` cannot be a module. If `a` does resolve to a module we
3566 // don't report an error right away, but try to fallback to a primitive type.
3567 // So, we are still able to successfully resolve something like
3569 // use std::u8; // bring module u8 in scope
3570 // fn f() -> u8 { // OK, resolves to primitive u8, not to std::u8
3571 // u8::max_value() // OK, resolves to associated function <u8>::max_value,
3572 // // not to non-existent std::u8::max_value
3575 // Such behavior is required for backward compatibility.
3576 // The same fallback is used when `a` resolves to nothing.
3577 PathResult::Module(ModuleOrUniformRoot::Module(_)) | PathResult::Failed { .. }
3578 if (ns == TypeNS || path.len() > 1)
3579 && PrimTy::from_name(path[0].ident.name).is_some() =>
3581 let prim = PrimTy::from_name(path[0].ident.name).unwrap();
3582 PartialRes::with_unresolved_segments(Res::PrimTy(prim), path.len() - 1)
3584 PathResult::Module(ModuleOrUniformRoot::Module(module)) => {
3585 PartialRes::new(module.res().unwrap())
3587 PathResult::Failed { is_error_from_last_segment: false, span, label, suggestion } => {
3588 return Err(respan(span, ResolutionError::FailedToResolve { label, suggestion }));
3590 PathResult::Module(..) | PathResult::Failed { .. } => return Ok(None),
3591 PathResult::Indeterminate => bug!("indeterminate path result in resolve_qpath"),
3595 && result.base_res() != Res::Err
3596 && path[0].ident.name != kw::PathRoot
3597 && path[0].ident.name != kw::DollarCrate
3599 let unqualified_result = {
3600 match self.resolve_path(&[*path.last().unwrap()], Some(ns), None) {
3601 PathResult::NonModule(path_res) => path_res.base_res(),
3602 PathResult::Module(ModuleOrUniformRoot::Module(module)) => {
3603 module.res().unwrap()
3605 _ => return Ok(Some(result)),
3608 if result.base_res() == unqualified_result {
3609 let lint = lint::builtin::UNUSED_QUALIFICATIONS;
3610 self.r.lint_buffer.buffer_lint(
3614 "unnecessary qualification",
3622 fn with_resolved_label(&mut self, label: Option<Label>, id: NodeId, f: impl FnOnce(&mut Self)) {
3623 if let Some(label) = label {
3624 if label.ident.as_str().as_bytes()[1] != b'_' {
3625 self.diagnostic_metadata.unused_labels.insert(id, label.ident.span);
3628 if let Ok((_, orig_span)) = self.resolve_label(label.ident) {
3629 diagnostics::signal_label_shadowing(self.r.session, orig_span, label.ident)
3632 self.with_label_rib(NormalRibKind, |this| {
3633 let ident = label.ident.normalize_to_macro_rules();
3634 this.label_ribs.last_mut().unwrap().bindings.insert(ident, id);
3642 fn resolve_labeled_block(&mut self, label: Option<Label>, id: NodeId, block: &'ast Block) {
3643 self.with_resolved_label(label, id, |this| this.visit_block(block));
3646 fn resolve_block(&mut self, block: &'ast Block) {
3647 debug!("(resolving block) entering block");
3648 // Move down in the graph, if there's an anonymous module rooted here.
3649 let orig_module = self.parent_scope.module;
3650 let anonymous_module = self.r.block_map.get(&block.id).cloned(); // clones a reference
3652 let mut num_macro_definition_ribs = 0;
3653 if let Some(anonymous_module) = anonymous_module {
3654 debug!("(resolving block) found anonymous module, moving down");
3655 self.ribs[ValueNS].push(Rib::new(ModuleRibKind(anonymous_module)));
3656 self.ribs[TypeNS].push(Rib::new(ModuleRibKind(anonymous_module)));
3657 self.parent_scope.module = anonymous_module;
3659 self.ribs[ValueNS].push(Rib::new(NormalRibKind));
3662 let prev = self.diagnostic_metadata.current_block_could_be_bare_struct_literal.take();
3663 if let (true, [Stmt { kind: StmtKind::Expr(expr), .. }]) =
3664 (block.could_be_bare_literal, &block.stmts[..])
3665 && let ExprKind::Type(..) = expr.kind
3667 self.diagnostic_metadata.current_block_could_be_bare_struct_literal =
3670 // Descend into the block.
3671 for stmt in &block.stmts {
3672 if let StmtKind::Item(ref item) = stmt.kind
3673 && let ItemKind::MacroDef(..) = item.kind {
3674 num_macro_definition_ribs += 1;
3675 let res = self.r.local_def_id(item.id).to_def_id();
3676 self.ribs[ValueNS].push(Rib::new(MacroDefinition(res)));
3677 self.label_ribs.push(Rib::new(MacroDefinition(res)));
3680 self.visit_stmt(stmt);
3682 self.diagnostic_metadata.current_block_could_be_bare_struct_literal = prev;
3685 self.parent_scope.module = orig_module;
3686 for _ in 0..num_macro_definition_ribs {
3687 self.ribs[ValueNS].pop();
3688 self.label_ribs.pop();
3690 self.ribs[ValueNS].pop();
3691 if anonymous_module.is_some() {
3692 self.ribs[TypeNS].pop();
3694 debug!("(resolving block) leaving block");
3697 fn resolve_anon_const(&mut self, constant: &'ast AnonConst, is_repeat: IsRepeatExpr) {
3698 debug!("resolve_anon_const {:?} is_repeat: {:?}", constant, is_repeat);
3699 self.with_constant_rib(
3701 if constant.value.is_potential_trivial_const_param() {
3702 HasGenericParams::Yes
3704 HasGenericParams::No
3707 |this| visit::walk_anon_const(this, constant),
3711 fn resolve_inline_const(&mut self, constant: &'ast AnonConst) {
3712 debug!("resolve_anon_const {constant:?}");
3713 self.with_constant_rib(IsRepeatExpr::No, HasGenericParams::Yes, None, |this| {
3714 visit::walk_anon_const(this, constant);
3718 fn resolve_expr(&mut self, expr: &'ast Expr, parent: Option<&'ast Expr>) {
3719 // First, record candidate traits for this expression if it could
3720 // result in the invocation of a method call.
3722 self.record_candidate_traits_for_expr_if_necessary(expr);
3724 // Next, resolve the node.
3726 ExprKind::Path(ref qself, ref path) => {
3727 self.smart_resolve_path(expr.id, qself.as_ref(), path, PathSource::Expr(parent));
3728 visit::walk_expr(self, expr);
3731 ExprKind::Struct(ref se) => {
3732 self.smart_resolve_path(expr.id, se.qself.as_ref(), &se.path, PathSource::Struct);
3733 visit::walk_expr(self, expr);
3736 ExprKind::Break(Some(label), _) | ExprKind::Continue(Some(label)) => {
3737 match self.resolve_label(label.ident) {
3738 Ok((node_id, _)) => {
3739 // Since this res is a label, it is never read.
3740 self.r.label_res_map.insert(expr.id, node_id);
3741 self.diagnostic_metadata.unused_labels.remove(&node_id);
3744 self.report_error(label.ident.span, error);
3748 // visit `break` argument if any
3749 visit::walk_expr(self, expr);
3752 ExprKind::Break(None, Some(ref e)) => {
3753 // We use this instead of `visit::walk_expr` to keep the parent expr around for
3754 // better diagnostics.
3755 self.resolve_expr(e, Some(&expr));
3758 ExprKind::Let(ref pat, ref scrutinee, _) => {
3759 self.visit_expr(scrutinee);
3760 self.resolve_pattern_top(pat, PatternSource::Let);
3763 ExprKind::If(ref cond, ref then, ref opt_else) => {
3764 self.with_rib(ValueNS, NormalRibKind, |this| {
3765 let old = this.diagnostic_metadata.in_if_condition.replace(cond);
3766 this.visit_expr(cond);
3767 this.diagnostic_metadata.in_if_condition = old;
3768 this.visit_block(then);
3770 if let Some(expr) = opt_else {
3771 self.visit_expr(expr);
3775 ExprKind::Loop(ref block, label) => self.resolve_labeled_block(label, expr.id, &block),
3777 ExprKind::While(ref cond, ref block, label) => {
3778 self.with_resolved_label(label, expr.id, |this| {
3779 this.with_rib(ValueNS, NormalRibKind, |this| {
3780 let old = this.diagnostic_metadata.in_if_condition.replace(cond);
3781 this.visit_expr(cond);
3782 this.diagnostic_metadata.in_if_condition = old;
3783 this.visit_block(block);
3788 ExprKind::ForLoop(ref pat, ref iter_expr, ref block, label) => {
3789 self.visit_expr(iter_expr);
3790 self.with_rib(ValueNS, NormalRibKind, |this| {
3791 this.resolve_pattern_top(pat, PatternSource::For);
3792 this.resolve_labeled_block(label, expr.id, block);
3796 ExprKind::Block(ref block, label) => self.resolve_labeled_block(label, block.id, block),
3798 // Equivalent to `visit::walk_expr` + passing some context to children.
3799 ExprKind::Field(ref subexpression, _) => {
3800 self.resolve_expr(subexpression, Some(expr));
3802 ExprKind::MethodCall(ref segment, ref arguments, _) => {
3803 let mut arguments = arguments.iter();
3804 self.resolve_expr(arguments.next().unwrap(), Some(expr));
3805 for argument in arguments {
3806 self.resolve_expr(argument, None);
3808 self.visit_path_segment(expr.span, segment);
3811 ExprKind::Call(ref callee, ref arguments) => {
3812 self.resolve_expr(callee, Some(expr));
3813 let const_args = self.r.legacy_const_generic_args(callee).unwrap_or_default();
3814 for (idx, argument) in arguments.iter().enumerate() {
3815 // Constant arguments need to be treated as AnonConst since
3816 // that is how they will be later lowered to HIR.
3817 if const_args.contains(&idx) {
3818 self.with_constant_rib(
3820 if argument.is_potential_trivial_const_param() {
3821 HasGenericParams::Yes
3823 HasGenericParams::No
3827 this.resolve_expr(argument, None);
3831 self.resolve_expr(argument, None);
3835 ExprKind::Type(ref type_expr, ref ty) => {
3836 // `ParseSess::type_ascription_path_suggestions` keeps spans of colon tokens in
3837 // type ascription. Here we are trying to retrieve the span of the colon token as
3838 // well, but only if it's written without spaces `expr:Ty` and therefore confusable
3839 // with `expr::Ty`, only in this case it will match the span from
3840 // `type_ascription_path_suggestions`.
3841 self.diagnostic_metadata
3842 .current_type_ascription
3843 .push(type_expr.span.between(ty.span));
3844 visit::walk_expr(self, expr);
3845 self.diagnostic_metadata.current_type_ascription.pop();
3847 // `async |x| ...` gets desugared to `|x| future_from_generator(|| ...)`, so we need to
3848 // resolve the arguments within the proper scopes so that usages of them inside the
3849 // closure are detected as upvars rather than normal closure arg usages.
3850 ExprKind::Closure(_, _, Async::Yes { .. }, _, ref fn_decl, ref body, _span) => {
3851 self.with_rib(ValueNS, NormalRibKind, |this| {
3852 this.with_label_rib(ClosureOrAsyncRibKind, |this| {
3853 // Resolve arguments:
3854 this.resolve_params(&fn_decl.inputs);
3855 // No need to resolve return type --
3856 // the outer closure return type is `FnRetTy::Default`.
3858 // Now resolve the inner closure
3860 // No need to resolve arguments: the inner closure has none.
3861 // Resolve the return type:
3862 visit::walk_fn_ret_ty(this, &fn_decl.output);
3864 this.visit_expr(body);
3869 // For closures, ClosureOrAsyncRibKind is added in visit_fn
3870 ExprKind::Closure(ClosureBinder::For { ref generic_params, span }, ..) => {
3871 self.with_generic_param_rib(
3874 LifetimeRibKind::Generics {
3876 kind: LifetimeBinderKind::Closure,
3879 |this| visit::walk_expr(this, expr),
3882 ExprKind::Closure(..) => visit::walk_expr(self, expr),
3883 ExprKind::Async(..) => {
3884 self.with_label_rib(ClosureOrAsyncRibKind, |this| visit::walk_expr(this, expr));
3886 ExprKind::Repeat(ref elem, ref ct) => {
3887 self.visit_expr(elem);
3888 self.with_lifetime_rib(LifetimeRibKind::AnonConst, |this| {
3889 this.with_lifetime_rib(LifetimeRibKind::Elided(LifetimeRes::Static), |this| {
3890 this.resolve_anon_const(ct, IsRepeatExpr::Yes)
3894 ExprKind::ConstBlock(ref ct) => {
3895 self.resolve_inline_const(ct);
3897 ExprKind::Index(ref elem, ref idx) => {
3898 self.resolve_expr(elem, Some(expr));
3899 self.visit_expr(idx);
3902 visit::walk_expr(self, expr);
3907 fn record_candidate_traits_for_expr_if_necessary(&mut self, expr: &'ast Expr) {
3909 ExprKind::Field(_, ident) => {
3910 // FIXME(#6890): Even though you can't treat a method like a
3911 // field, we need to add any trait methods we find that match
3912 // the field name so that we can do some nice error reporting
3913 // later on in typeck.
3914 let traits = self.traits_in_scope(ident, ValueNS);
3915 self.r.trait_map.insert(expr.id, traits);
3917 ExprKind::MethodCall(ref segment, ..) => {
3918 debug!("(recording candidate traits for expr) recording traits for {}", expr.id);
3919 let traits = self.traits_in_scope(segment.ident, ValueNS);
3920 self.r.trait_map.insert(expr.id, traits);
3928 fn traits_in_scope(&mut self, ident: Ident, ns: Namespace) -> Vec<TraitCandidate> {
3929 self.r.traits_in_scope(
3930 self.current_trait_ref.as_ref().map(|(module, _)| *module),
3933 Some((ident.name, ns)),
3938 struct LifetimeCountVisitor<'a, 'b> {
3939 r: &'b mut Resolver<'a>,
3942 /// Walks the whole crate in DFS order, visiting each item, counting the declared number of
3943 /// lifetime generic parameters.
3944 impl<'ast> Visitor<'ast> for LifetimeCountVisitor<'_, '_> {
3945 fn visit_item(&mut self, item: &'ast Item) {
3947 ItemKind::TyAlias(box TyAlias { ref generics, .. })
3948 | ItemKind::Fn(box Fn { ref generics, .. })
3949 | ItemKind::Enum(_, ref generics)
3950 | ItemKind::Struct(_, ref generics)
3951 | ItemKind::Union(_, ref generics)
3952 | ItemKind::Impl(box Impl { ref generics, .. })
3953 | ItemKind::Trait(box Trait { ref generics, .. })
3954 | ItemKind::TraitAlias(ref generics, _) => {
3955 let def_id = self.r.local_def_id(item.id);
3956 let count = generics
3959 .filter(|param| matches!(param.kind, ast::GenericParamKind::Lifetime { .. }))
3961 self.r.item_generics_num_lifetimes.insert(def_id, count);
3965 | ItemKind::ForeignMod(..)
3966 | ItemKind::Static(..)
3967 | ItemKind::Const(..)
3969 | ItemKind::ExternCrate(..)
3970 | ItemKind::MacroDef(..)
3971 | ItemKind::GlobalAsm(..)
3972 | ItemKind::MacCall(..) => {}
3974 visit::walk_item(self, item)
3978 impl<'a> Resolver<'a> {
3979 pub(crate) fn late_resolve_crate(&mut self, krate: &Crate) {
3980 visit::walk_crate(&mut LifetimeCountVisitor { r: self }, krate);
3981 let mut late_resolution_visitor = LateResolutionVisitor::new(self);
3982 visit::walk_crate(&mut late_resolution_visitor, krate);
3983 for (id, span) in late_resolution_visitor.diagnostic_metadata.unused_labels.iter() {
3984 self.lint_buffer.buffer_lint(lint::builtin::UNUSED_LABELS, *id, *span, "unused label");