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};
16 original_label, original_lifetime, original_lifetime_param, shadower_label, shadower_lifetime,
19 use rustc_ast::ptr::P;
20 use rustc_ast::visit::{self, AssocCtxt, BoundKind, FnCtxt, FnKind, Visitor};
22 use rustc_ast_lowering::{LifetimeRes, ResolverAstLowering};
23 use rustc_data_structures::fx::{FxHashMap, FxHashSet, FxIndexMap};
24 use rustc_errors::DiagnosticId;
25 use rustc_hir::def::Namespace::{self, *};
26 use rustc_hir::def::{self, CtorKind, DefKind, PartialRes, PerNS};
27 use rustc_hir::def_id::{DefId, LocalDefId, CRATE_DEF_ID};
28 use rustc_hir::definitions::DefPathData;
29 use rustc_hir::{PrimTy, TraitCandidate};
30 use rustc_index::vec::Idx;
31 use rustc_middle::ty::DefIdTree;
32 use rustc_middle::{bug, span_bug};
33 use rustc_session::lint;
34 use rustc_span::symbol::{kw, sym, Ident, Symbol};
35 use rustc_span::{BytePos, Span};
36 use smallvec::{smallvec, SmallVec};
38 use rustc_span::source_map::{respan, Spanned};
39 use std::collections::{hash_map::Entry, BTreeSet};
40 use std::mem::{replace, take};
44 pub(crate) mod lifetimes;
46 type Res = def::Res<NodeId>;
48 type IdentMap<T> = FxHashMap<Ident, T>;
50 /// Map from the name in a pattern to its binding mode.
51 type BindingMap = IdentMap<BindingInfo>;
53 #[derive(Copy, Clone, Debug)]
56 binding_mode: BindingMode,
59 #[derive(Copy, Clone, PartialEq, Eq, Debug)]
67 #[derive(Copy, Clone, Debug, PartialEq, Eq)]
74 fn descr(self) -> &'static str {
76 PatternSource::Match => "match binding",
77 PatternSource::Let => "let binding",
78 PatternSource::For => "for binding",
79 PatternSource::FnParam => "function parameter",
84 /// Denotes whether the context for the set of already bound bindings is a `Product`
85 /// or `Or` context. This is used in e.g., `fresh_binding` and `resolve_pattern_inner`.
86 /// See those functions for more information.
89 /// A product pattern context, e.g., `Variant(a, b)`.
91 /// An or-pattern context, e.g., `p_0 | ... | p_n`.
95 /// Does this the item (from the item rib scope) allow generic parameters?
96 #[derive(Copy, Clone, Debug, Eq, PartialEq)]
97 pub(crate) enum HasGenericParams {
102 impl HasGenericParams {
103 fn force_yes_if(self, b: bool) -> Self {
104 if b { Self::Yes } else { self }
108 #[derive(Copy, Clone, Debug, Eq, PartialEq)]
109 pub(crate) enum ConstantItemKind {
114 /// The rib kind restricts certain accesses,
115 /// e.g. to a `Res::Local` of an outer item.
116 #[derive(Copy, Clone, Debug)]
117 pub(crate) enum RibKind<'a> {
118 /// No restriction needs to be applied.
121 /// We passed through an impl or trait and are now in one of its
122 /// methods or associated types. Allow references to ty params that impl or trait
123 /// binds. Disallow any other upvars (including other ty params that are
127 /// We passed through a closure. Disallow labels.
128 ClosureOrAsyncRibKind,
130 /// We passed through a function definition. Disallow upvars.
131 /// Permit only those const parameters that are specified in the function's generics.
134 /// We passed through an item scope. Disallow upvars.
135 ItemRibKind(HasGenericParams),
137 /// We're in a constant item. Can't refer to dynamic stuff.
139 /// The item may reference generic parameters in trivial constant expressions.
140 /// All other constants aren't allowed to use generic params at all.
141 ConstantItemRibKind(HasGenericParams, Option<(Ident, ConstantItemKind)>),
143 /// We passed through a module.
144 ModuleRibKind(Module<'a>),
146 /// We passed through a `macro_rules!` statement
147 MacroDefinition(DefId),
149 /// All bindings in this rib are generic parameters that can't be used
150 /// from the default of a generic parameter because they're not declared
151 /// before said generic parameter. Also see the `visit_generics` override.
152 ForwardGenericParamBanRibKind,
154 /// We are inside of the type of a const parameter. Can't refer to any
158 /// We are inside a `sym` inline assembly operand. Can only refer to
164 /// Whether this rib kind contains generic parameters, as opposed to local
166 pub(crate) fn contains_params(&self) -> bool {
169 | ClosureOrAsyncRibKind
171 | ConstantItemRibKind(..)
174 | ConstParamTyRibKind
175 | InlineAsmSymRibKind => false,
176 AssocItemRibKind | ItemRibKind(_) | ForwardGenericParamBanRibKind => true,
180 /// This rib forbids referring to labels defined in upwards ribs.
181 fn is_label_barrier(self) -> bool {
183 NormalRibKind | MacroDefinition(..) => false,
186 | ClosureOrAsyncRibKind
189 | ConstantItemRibKind(..)
191 | ForwardGenericParamBanRibKind
192 | ConstParamTyRibKind
193 | InlineAsmSymRibKind => true,
198 /// A single local scope.
200 /// A rib represents a scope names can live in. Note that these appear in many places, not just
201 /// around braces. At any place where the list of accessible names (of the given namespace)
202 /// changes or a new restrictions on the name accessibility are introduced, a new rib is put onto a
203 /// stack. This may be, for example, a `let` statement (because it introduces variables), a macro,
206 /// Different [rib kinds](enum@RibKind) are transparent for different names.
208 /// The resolution keeps a separate stack of ribs as it traverses the AST for each namespace. When
209 /// resolving, the name is looked up from inside out.
211 pub(crate) struct Rib<'a, R = Res> {
212 pub bindings: IdentMap<R>,
213 pub kind: RibKind<'a>,
216 impl<'a, R> Rib<'a, R> {
217 fn new(kind: RibKind<'a>) -> Rib<'a, R> {
218 Rib { bindings: Default::default(), kind }
222 #[derive(Clone, Copy, Debug)]
223 enum LifetimeUseSet {
224 One { use_span: Span, use_ctxt: visit::LifetimeCtxt },
228 #[derive(Copy, Clone, Debug)]
229 enum LifetimeRibKind {
230 /// This rib acts as a barrier to forbid reference to lifetimes of a parent item.
233 /// This rib declares generic parameters.
234 Generics { binder: NodeId, span: Span, kind: LifetimeBinderKind },
236 /// FIXME(const_generics): This patches over an ICE caused by non-'static lifetimes in const
237 /// generics. We are disallowing this until we can decide on how we want to handle non-'static
238 /// lifetimes in const generics. See issue #74052 for discussion.
241 /// Non-static lifetimes are prohibited in anonymous constants under `min_const_generics`.
242 /// This function will emit an error if `generic_const_exprs` is not enabled, the body identified by
243 /// `body_id` is an anonymous constant and `lifetime_ref` is non-static.
246 /// For **Modern** cases, create a new anonymous region parameter
247 /// and reference that.
249 /// For **Dyn Bound** cases, pass responsibility to
250 /// `resolve_lifetime` code.
252 /// For **Deprecated** cases, report an error.
253 AnonymousCreateParameter(NodeId),
255 /// Give a hard error when either `&` or `'_` is written. Used to
256 /// rule out things like `where T: Foo<'_>`. Does not imply an
257 /// error on default object bounds (e.g., `Box<dyn Foo>`).
258 AnonymousReportError,
260 /// Pass responsibility to `resolve_lifetime` code for all cases.
261 AnonymousPassThrough(NodeId, /* in_fn_return */ bool),
264 #[derive(Copy, Clone, Debug)]
265 enum LifetimeBinderKind {
274 impl LifetimeBinderKind {
275 fn descr(self) -> &'static str {
276 use LifetimeBinderKind::*;
278 BareFnType => "type",
279 PolyTrait => "bound",
280 WhereBound => "bound",
282 ImplBlock => "impl block",
283 Function => "function",
290 kind: LifetimeRibKind,
291 // We need to preserve insertion order for async fns.
292 bindings: FxIndexMap<Ident, (NodeId, LifetimeRes)>,
296 fn new(kind: LifetimeRibKind) -> LifetimeRib {
297 LifetimeRib { bindings: Default::default(), kind }
301 #[derive(Copy, Clone, PartialEq, Eq, Debug)]
302 pub(crate) enum AliasPossibility {
307 #[derive(Copy, Clone, Debug)]
308 pub(crate) enum PathSource<'a> {
309 // Type paths `Path`.
311 // Trait paths in bounds or impls.
312 Trait(AliasPossibility),
313 // Expression paths `path`, with optional parent context.
314 Expr(Option<&'a Expr>),
315 // Paths in path patterns `Path`.
317 // Paths in struct expressions and patterns `Path { .. }`.
319 // Paths in tuple struct patterns `Path(..)`.
320 TupleStruct(Span, &'a [Span]),
321 // `m::A::B` in `<T as m::A>::B::C`.
322 TraitItem(Namespace),
325 impl<'a> PathSource<'a> {
326 fn namespace(self) -> Namespace {
328 PathSource::Type | PathSource::Trait(_) | PathSource::Struct => TypeNS,
329 PathSource::Expr(..) | PathSource::Pat | PathSource::TupleStruct(..) => ValueNS,
330 PathSource::TraitItem(ns) => ns,
334 fn defer_to_typeck(self) -> bool {
337 | PathSource::Expr(..)
340 | PathSource::TupleStruct(..) => true,
341 PathSource::Trait(_) | PathSource::TraitItem(..) => false,
345 fn descr_expected(self) -> &'static str {
347 PathSource::Type => "type",
348 PathSource::Trait(_) => "trait",
349 PathSource::Pat => "unit struct, unit variant or constant",
350 PathSource::Struct => "struct, variant or union type",
351 PathSource::TupleStruct(..) => "tuple struct or tuple variant",
352 PathSource::TraitItem(ns) => match ns {
353 TypeNS => "associated type",
354 ValueNS => "method or associated constant",
355 MacroNS => bug!("associated macro"),
357 PathSource::Expr(parent) => match parent.as_ref().map(|p| &p.kind) {
358 // "function" here means "anything callable" rather than `DefKind::Fn`,
359 // this is not precise but usually more helpful than just "value".
360 Some(ExprKind::Call(call_expr, _)) => match &call_expr.kind {
361 // the case of `::some_crate()`
362 ExprKind::Path(_, path)
363 if path.segments.len() == 2
364 && path.segments[0].ident.name == kw::PathRoot =>
368 ExprKind::Path(_, path) => {
369 let mut msg = "function";
370 if let Some(segment) = path.segments.iter().last() {
371 if let Some(c) = segment.ident.to_string().chars().next() {
372 if c.is_uppercase() {
373 msg = "function, tuple struct or tuple variant";
386 fn is_call(self) -> bool {
387 matches!(self, PathSource::Expr(Some(&Expr { kind: ExprKind::Call(..), .. })))
390 pub(crate) fn is_expected(self, res: Res) -> bool {
392 PathSource::Type => matches!(
399 | DefKind::TraitAlias
404 | DefKind::ForeignTy,
409 PathSource::Trait(AliasPossibility::No) => matches!(res, Res::Def(DefKind::Trait, _)),
410 PathSource::Trait(AliasPossibility::Maybe) => {
411 matches!(res, Res::Def(DefKind::Trait | DefKind::TraitAlias, _))
413 PathSource::Expr(..) => matches!(
416 DefKind::Ctor(_, CtorKind::Const | CtorKind::Fn)
421 | DefKind::AssocConst
422 | DefKind::ConstParam,
428 res.expected_in_unit_struct_pat()
429 || matches!(res, Res::Def(DefKind::Const | DefKind::AssocConst, _))
431 PathSource::TupleStruct(..) => res.expected_in_tuple_struct_pat(),
432 PathSource::Struct => matches!(
441 ) | Res::SelfTy { .. }
443 PathSource::TraitItem(ns) => match res {
444 Res::Def(DefKind::AssocConst | DefKind::AssocFn, _) if ns == ValueNS => true,
445 Res::Def(DefKind::AssocTy, _) if ns == TypeNS => true,
451 fn error_code(self, has_unexpected_resolution: bool) -> DiagnosticId {
452 use rustc_errors::error_code;
453 match (self, has_unexpected_resolution) {
454 (PathSource::Trait(_), true) => error_code!(E0404),
455 (PathSource::Trait(_), false) => error_code!(E0405),
456 (PathSource::Type, true) => error_code!(E0573),
457 (PathSource::Type, false) => error_code!(E0412),
458 (PathSource::Struct, true) => error_code!(E0574),
459 (PathSource::Struct, false) => error_code!(E0422),
460 (PathSource::Expr(..), true) => error_code!(E0423),
461 (PathSource::Expr(..), false) => error_code!(E0425),
462 (PathSource::Pat | PathSource::TupleStruct(..), true) => error_code!(E0532),
463 (PathSource::Pat | PathSource::TupleStruct(..), false) => error_code!(E0531),
464 (PathSource::TraitItem(..), true) => error_code!(E0575),
465 (PathSource::TraitItem(..), false) => error_code!(E0576),
471 struct DiagnosticMetadata<'ast> {
472 /// The current trait's associated items' ident, used for diagnostic suggestions.
473 current_trait_assoc_items: Option<&'ast [P<AssocItem>]>,
475 /// The current self type if inside an impl (used for better errors).
476 current_self_type: Option<Ty>,
478 /// The current self item if inside an ADT (used for better errors).
479 current_self_item: Option<NodeId>,
481 /// The current trait (used to suggest).
482 current_item: Option<&'ast Item>,
484 /// When processing generics and encountering a type not found, suggest introducing a type
486 currently_processing_generics: bool,
488 /// The current enclosing (non-closure) function (used for better errors).
489 current_function: Option<(FnKind<'ast>, Span)>,
491 /// A list of labels as of yet unused. Labels will be removed from this map when
492 /// they are used (in a `break` or `continue` statement)
493 unused_labels: FxHashMap<NodeId, Span>,
495 /// Only used for better errors on `fn(): fn()`.
496 current_type_ascription: Vec<Span>,
498 /// Only used for better errors on `let x = { foo: bar };`.
499 /// In the case of a parse error with `let x = { foo: bar, };`, this isn't needed, it's only
500 /// needed for cases where this parses as a correct type ascription.
501 current_block_could_be_bare_struct_literal: Option<Span>,
503 /// Only used for better errors on `let <pat>: <expr, not type>;`.
504 current_let_binding: Option<(Span, Option<Span>, Option<Span>)>,
506 /// Used to detect possible `if let` written without `let` and to provide structured suggestion.
507 in_if_condition: Option<&'ast Expr>,
509 /// If we are currently in a trait object definition. Used to point at the bounds when
510 /// encountering a struct or enum.
511 current_trait_object: Option<&'ast [ast::GenericBound]>,
513 /// Given `where <T as Bar>::Baz: String`, suggest `where T: Bar<Baz = String>`.
514 current_where_predicate: Option<&'ast WherePredicate>,
516 current_type_path: Option<&'ast Ty>,
518 /// The current impl items (used to suggest).
519 current_impl_items: Option<&'ast [P<AssocItem>]>,
522 struct LateResolutionVisitor<'a, 'b, 'ast> {
523 r: &'b mut Resolver<'a>,
525 /// The module that represents the current item scope.
526 parent_scope: ParentScope<'a>,
528 /// The current set of local scopes for types and values.
529 /// FIXME #4948: Reuse ribs to avoid allocation.
530 ribs: PerNS<Vec<Rib<'a>>>,
532 /// The current set of local scopes, for labels.
533 label_ribs: Vec<Rib<'a, NodeId>>,
535 /// The current set of local scopes for lifetimes.
536 lifetime_ribs: Vec<LifetimeRib>,
538 /// The trait that the current context can refer to.
539 current_trait_ref: Option<(Module<'a>, TraitRef)>,
541 /// Fields used to add information to diagnostic errors.
542 diagnostic_metadata: DiagnosticMetadata<'ast>,
544 /// State used to know whether to ignore resolution errors for function bodies.
546 /// In particular, rustdoc uses this to avoid giving errors for `cfg()` items.
547 /// In most cases this will be `None`, in which case errors will always be reported.
548 /// If it is `true`, then it will be updated when entering a nested function or trait body.
551 /// Count the number of places a lifetime is used.
552 lifetime_uses: FxHashMap<LocalDefId, LifetimeUseSet>,
555 /// Walks the whole crate in DFS order, visiting each item, resolving names as it goes.
556 impl<'a: 'ast, 'ast> Visitor<'ast> for LateResolutionVisitor<'a, '_, 'ast> {
557 fn visit_attribute(&mut self, _: &'ast Attribute) {
558 // We do not want to resolve expressions that appear in attributes,
559 // as they do not correspond to actual code.
561 fn visit_item(&mut self, item: &'ast Item) {
562 let prev = replace(&mut self.diagnostic_metadata.current_item, Some(item));
563 // Always report errors in items we just entered.
564 let old_ignore = replace(&mut self.in_func_body, false);
565 self.with_lifetime_rib(LifetimeRibKind::Item, |this| this.resolve_item(item));
566 self.in_func_body = old_ignore;
567 self.diagnostic_metadata.current_item = prev;
569 fn visit_arm(&mut self, arm: &'ast Arm) {
570 self.resolve_arm(arm);
572 fn visit_block(&mut self, block: &'ast Block) {
573 self.resolve_block(block);
575 fn visit_anon_const(&mut self, constant: &'ast AnonConst) {
576 // We deal with repeat expressions explicitly in `resolve_expr`.
577 self.with_lifetime_rib(LifetimeRibKind::AnonConst, |this| {
578 this.resolve_anon_const(constant, IsRepeatExpr::No);
581 fn visit_expr(&mut self, expr: &'ast Expr) {
582 self.resolve_expr(expr, None);
584 fn visit_local(&mut self, local: &'ast Local) {
585 let local_spans = match local.pat.kind {
586 // We check for this to avoid tuple struct fields.
587 PatKind::Wild => None,
590 local.ty.as_ref().map(|ty| ty.span),
591 local.kind.init().map(|init| init.span),
594 let original = replace(&mut self.diagnostic_metadata.current_let_binding, local_spans);
595 self.resolve_local(local);
596 self.diagnostic_metadata.current_let_binding = original;
598 fn visit_ty(&mut self, ty: &'ast Ty) {
599 let prev = self.diagnostic_metadata.current_trait_object;
600 let prev_ty = self.diagnostic_metadata.current_type_path;
602 TyKind::Rptr(None, _) => {
603 // Elided lifetime in reference: we resolve as if there was some lifetime `'_` with
605 let span = self.r.session.source_map().next_point(ty.span.shrink_to_lo());
606 self.resolve_elided_lifetime(ty.id, span);
608 TyKind::Path(ref qself, ref path) => {
609 self.diagnostic_metadata.current_type_path = Some(ty);
610 self.smart_resolve_path(ty.id, qself.as_ref(), path, PathSource::Type);
612 TyKind::ImplicitSelf => {
613 let self_ty = Ident::with_dummy_span(kw::SelfUpper);
615 .resolve_ident_in_lexical_scope(
618 Some(Finalize::new(ty.id, ty.span)),
621 .map_or(Res::Err, |d| d.res());
622 self.r.record_partial_res(ty.id, PartialRes::new(res));
624 TyKind::TraitObject(ref bounds, ..) => {
625 self.diagnostic_metadata.current_trait_object = Some(&bounds[..]);
627 TyKind::BareFn(ref bare_fn) => {
628 let span = ty.span.shrink_to_lo().to(bare_fn.decl_span.shrink_to_lo());
629 self.with_generic_param_rib(
630 &bare_fn.generic_params,
632 LifetimeRibKind::Generics {
634 kind: LifetimeBinderKind::BareFnType,
638 this.visit_generic_param_vec(&bare_fn.generic_params, false);
639 this.with_lifetime_rib(
640 LifetimeRibKind::AnonymousPassThrough(ty.id, false),
641 |this| walk_list!(this, visit_param, &bare_fn.decl.inputs),
643 this.with_lifetime_rib(
644 LifetimeRibKind::AnonymousPassThrough(ty.id, true),
645 |this| this.visit_fn_ret_ty(&bare_fn.decl.output),
649 self.diagnostic_metadata.current_trait_object = prev;
654 visit::walk_ty(self, ty);
655 self.diagnostic_metadata.current_trait_object = prev;
656 self.diagnostic_metadata.current_type_path = prev_ty;
658 fn visit_poly_trait_ref(&mut self, tref: &'ast PolyTraitRef, _: &'ast TraitBoundModifier) {
659 let span = tref.span.shrink_to_lo().to(tref.trait_ref.path.span.shrink_to_lo());
660 self.with_generic_param_rib(
661 &tref.bound_generic_params,
663 LifetimeRibKind::Generics {
664 binder: tref.trait_ref.ref_id,
665 kind: LifetimeBinderKind::PolyTrait,
669 this.visit_generic_param_vec(&tref.bound_generic_params, false);
670 this.smart_resolve_path(
671 tref.trait_ref.ref_id,
673 &tref.trait_ref.path,
674 PathSource::Trait(AliasPossibility::Maybe),
676 this.visit_trait_ref(&tref.trait_ref);
680 fn visit_foreign_item(&mut self, foreign_item: &'ast ForeignItem) {
681 match foreign_item.kind {
682 ForeignItemKind::TyAlias(box TyAlias { ref generics, .. }) => {
683 self.with_lifetime_rib(LifetimeRibKind::Item, |this| {
684 this.with_generic_param_rib(
686 ItemRibKind(HasGenericParams::Yes),
687 LifetimeRibKind::Generics {
688 binder: foreign_item.id,
689 kind: LifetimeBinderKind::Item,
692 |this| visit::walk_foreign_item(this, foreign_item),
696 ForeignItemKind::Fn(box Fn { ref generics, .. }) => {
697 self.with_lifetime_rib(LifetimeRibKind::Item, |this| {
698 this.with_generic_param_rib(
700 ItemRibKind(HasGenericParams::Yes),
701 LifetimeRibKind::Generics {
702 binder: foreign_item.id,
703 kind: LifetimeBinderKind::Function,
706 |this| visit::walk_foreign_item(this, foreign_item),
710 ForeignItemKind::Static(..) => {
711 self.with_item_rib(|this| {
712 visit::walk_foreign_item(this, foreign_item);
715 ForeignItemKind::MacCall(..) => {
716 panic!("unexpanded macro in resolve!")
720 fn visit_fn(&mut self, fn_kind: FnKind<'ast>, sp: Span, fn_id: NodeId) {
721 let rib_kind = match fn_kind {
722 // Bail if the function is foreign, and thus cannot validly have
723 // a body, or if there's no body for some other reason.
724 FnKind::Fn(FnCtxt::Foreign, _, sig, _, generics, _)
725 | FnKind::Fn(_, _, sig, _, generics, None) => {
726 // We don't need to deal with patterns in parameters, because
727 // they are not possible for foreign or bodiless functions.
728 self.with_lifetime_rib(
729 LifetimeRibKind::AnonymousPassThrough(fn_id, false),
731 this.visit_fn_header(&sig.header);
732 this.visit_generics(generics);
733 walk_list!(this, visit_param, &sig.decl.inputs);
736 self.with_lifetime_rib(
737 LifetimeRibKind::AnonymousPassThrough(fn_id, true),
738 |this| this.visit_fn_ret_ty(&sig.decl.output),
742 FnKind::Fn(FnCtxt::Free, ..) => FnItemRibKind,
743 FnKind::Fn(FnCtxt::Assoc(_), ..) => NormalRibKind,
744 FnKind::Closure(..) => ClosureOrAsyncRibKind,
746 let previous_value = self.diagnostic_metadata.current_function;
747 if matches!(fn_kind, FnKind::Fn(..)) {
748 self.diagnostic_metadata.current_function = Some((fn_kind, sp));
750 debug!("(resolving function) entering function");
751 let declaration = fn_kind.decl();
753 // Create a value rib for the function.
754 self.with_rib(ValueNS, rib_kind, |this| {
755 // Create a label rib for the function.
756 this.with_label_rib(FnItemRibKind, |this| {
757 let async_node_id = fn_kind.header().and_then(|h| h.asyncness.opt_return_id());
759 if let FnKind::Fn(_, _, _, _, generics, _) = fn_kind {
760 this.visit_generics(generics);
763 if let Some(async_node_id) = async_node_id {
764 // In `async fn`, argument-position elided lifetimes
765 // must be transformed into fresh generic parameters so that
766 // they can be applied to the opaque `impl Trait` return type.
767 this.with_lifetime_rib(
768 LifetimeRibKind::AnonymousCreateParameter(fn_id),
770 // Add each argument to the rib.
771 this.resolve_params(&declaration.inputs)
775 // Construct the list of in-scope lifetime parameters for async lowering.
776 // We include all lifetime parameters, either named or "Fresh".
777 // The order of those parameters does not matter, as long as it is
779 let mut extra_lifetime_params =
780 this.r.extra_lifetime_params_map.get(&fn_id).cloned().unwrap_or_default();
781 for rib in this.lifetime_ribs.iter().rev() {
782 extra_lifetime_params.extend(
785 .map(|(&ident, &(node_id, res))| (ident, node_id, res)),
788 LifetimeRibKind::Item => break,
789 LifetimeRibKind::AnonymousCreateParameter(id) => {
790 if let Some(earlier_fresh) =
791 this.r.extra_lifetime_params_map.get(&id)
793 extra_lifetime_params.extend(earlier_fresh);
799 this.r.extra_lifetime_params_map.insert(async_node_id, extra_lifetime_params);
801 this.with_lifetime_rib(
802 LifetimeRibKind::AnonymousPassThrough(async_node_id, true),
803 |this| visit::walk_fn_ret_ty(this, &declaration.output),
806 // Add each argument to the rib.
807 this.with_lifetime_rib(
808 LifetimeRibKind::AnonymousPassThrough(fn_id, false),
809 |this| this.resolve_params(&declaration.inputs),
811 this.with_lifetime_rib(
812 LifetimeRibKind::AnonymousPassThrough(fn_id, true),
813 |this| visit::walk_fn_ret_ty(this, &declaration.output),
817 // Ignore errors in function bodies if this is rustdoc
818 // Be sure not to set this until the function signature has been resolved.
819 let previous_state = replace(&mut this.in_func_body, true);
820 // Resolve the function body, potentially inside the body of an async closure
821 this.with_lifetime_rib(
822 LifetimeRibKind::AnonymousPassThrough(fn_id, false),
823 |this| match fn_kind {
824 FnKind::Fn(.., body) => walk_list!(this, visit_block, body),
825 FnKind::Closure(_, body) => this.visit_expr(body),
829 debug!("(resolving function) leaving function");
830 this.in_func_body = previous_state;
833 self.diagnostic_metadata.current_function = previous_value;
835 fn visit_lifetime(&mut self, lifetime: &'ast Lifetime, use_ctxt: visit::LifetimeCtxt) {
836 self.resolve_lifetime(lifetime, use_ctxt)
839 fn visit_generics(&mut self, generics: &'ast Generics) {
840 self.visit_generic_param_vec(
842 self.diagnostic_metadata.current_self_item.is_some(),
844 for p in &generics.where_clause.predicates {
845 self.visit_where_predicate(p);
849 fn visit_generic_arg(&mut self, arg: &'ast GenericArg) {
850 debug!("visit_generic_arg({:?})", arg);
851 let prev = replace(&mut self.diagnostic_metadata.currently_processing_generics, true);
853 GenericArg::Type(ref ty) => {
854 // We parse const arguments as path types as we cannot distinguish them during
855 // parsing. We try to resolve that ambiguity by attempting resolution the type
856 // namespace first, and if that fails we try again in the value namespace. If
857 // resolution in the value namespace succeeds, we have an generic const argument on
859 if let TyKind::Path(ref qself, ref path) = ty.kind {
860 // We cannot disambiguate multi-segment paths right now as that requires type
862 if path.segments.len() == 1 && path.segments[0].args.is_none() {
863 let mut check_ns = |ns| {
864 self.maybe_resolve_ident_in_lexical_scope(path.segments[0].ident, ns)
867 if !check_ns(TypeNS) && check_ns(ValueNS) {
868 // This must be equivalent to `visit_anon_const`, but we cannot call it
869 // directly due to visitor lifetimes so we have to copy-paste some code.
871 // Note that we might not be inside of an repeat expression here,
872 // but considering that `IsRepeatExpr` is only relevant for
873 // non-trivial constants this is doesn't matter.
874 self.with_constant_rib(
876 HasGenericParams::Yes,
879 this.smart_resolve_path(
883 PathSource::Expr(None),
886 if let Some(ref qself) = *qself {
887 this.visit_ty(&qself.ty);
889 this.visit_path(path, ty.id);
893 self.diagnostic_metadata.currently_processing_generics = prev;
901 GenericArg::Lifetime(lt) => self.visit_lifetime(lt, visit::LifetimeCtxt::GenericArg),
902 GenericArg::Const(ct) => self.visit_anon_const(ct),
904 self.diagnostic_metadata.currently_processing_generics = prev;
907 fn visit_path_segment(&mut self, path_span: Span, path_segment: &'ast PathSegment) {
908 if let Some(ref args) = path_segment.args {
910 GenericArgs::AngleBracketed(..) => visit::walk_generic_args(self, path_span, args),
911 GenericArgs::Parenthesized(ref data) => {
912 self.with_lifetime_rib(
913 LifetimeRibKind::AnonymousPassThrough(path_segment.id, false),
914 |this| walk_list!(this, visit_ty, &data.inputs),
916 self.with_lifetime_rib(
917 LifetimeRibKind::AnonymousPassThrough(path_segment.id, true),
918 |this| visit::walk_fn_ret_ty(this, &data.output),
925 fn visit_where_predicate(&mut self, p: &'ast WherePredicate) {
926 debug!("visit_where_predicate {:?}", p);
928 replace(&mut self.diagnostic_metadata.current_where_predicate, Some(p));
929 self.with_lifetime_rib(LifetimeRibKind::AnonymousReportError, |this| {
930 if let WherePredicate::BoundPredicate(WhereBoundPredicate {
933 ref bound_generic_params,
934 span: predicate_span,
938 let span = predicate_span.shrink_to_lo().to(bounded_ty.span.shrink_to_lo());
939 this.with_generic_param_rib(
940 &bound_generic_params,
942 LifetimeRibKind::Generics {
943 binder: bounded_ty.id,
944 kind: LifetimeBinderKind::WhereBound,
948 this.visit_generic_param_vec(&bound_generic_params, false);
949 this.visit_ty(bounded_ty);
950 for bound in bounds {
951 this.visit_param_bound(bound, BoundKind::Bound)
956 visit::walk_where_predicate(this, p);
959 self.diagnostic_metadata.current_where_predicate = previous_value;
962 fn visit_inline_asm(&mut self, asm: &'ast InlineAsm) {
963 for (op, _) in &asm.operands {
965 InlineAsmOperand::In { expr, .. }
966 | InlineAsmOperand::Out { expr: Some(expr), .. }
967 | InlineAsmOperand::InOut { expr, .. } => self.visit_expr(expr),
968 InlineAsmOperand::Out { expr: None, .. } => {}
969 InlineAsmOperand::SplitInOut { in_expr, out_expr, .. } => {
970 self.visit_expr(in_expr);
971 if let Some(out_expr) = out_expr {
972 self.visit_expr(out_expr);
975 InlineAsmOperand::Const { anon_const, .. } => {
976 // Although this is `DefKind::AnonConst`, it is allowed to reference outer
977 // generic parameters like an inline const.
978 self.resolve_inline_const(anon_const);
980 InlineAsmOperand::Sym { sym } => self.visit_inline_asm_sym(sym),
985 fn visit_inline_asm_sym(&mut self, sym: &'ast InlineAsmSym) {
986 // This is similar to the code for AnonConst.
987 self.with_rib(ValueNS, InlineAsmSymRibKind, |this| {
988 this.with_rib(TypeNS, InlineAsmSymRibKind, |this| {
989 this.with_label_rib(InlineAsmSymRibKind, |this| {
990 this.smart_resolve_path(
994 PathSource::Expr(None),
996 visit::walk_inline_asm_sym(this, sym);
1003 impl<'a: 'ast, 'b, 'ast> LateResolutionVisitor<'a, 'b, 'ast> {
1004 fn new(resolver: &'b mut Resolver<'a>) -> LateResolutionVisitor<'a, 'b, 'ast> {
1005 // During late resolution we only track the module component of the parent scope,
1006 // although it may be useful to track other components as well for diagnostics.
1007 let graph_root = resolver.graph_root;
1008 let parent_scope = ParentScope::module(graph_root, resolver);
1009 let start_rib_kind = ModuleRibKind(graph_root);
1010 LateResolutionVisitor {
1014 value_ns: vec![Rib::new(start_rib_kind)],
1015 type_ns: vec![Rib::new(start_rib_kind)],
1016 macro_ns: vec![Rib::new(start_rib_kind)],
1018 label_ribs: Vec::new(),
1019 lifetime_ribs: Vec::new(),
1020 current_trait_ref: None,
1021 diagnostic_metadata: DiagnosticMetadata::default(),
1022 // errors at module scope should always be reported
1023 in_func_body: false,
1024 lifetime_uses: Default::default(),
1028 fn maybe_resolve_ident_in_lexical_scope(
1032 ) -> Option<LexicalScopeBinding<'a>> {
1033 self.r.resolve_ident_in_lexical_scope(
1043 fn resolve_ident_in_lexical_scope(
1047 finalize: Option<Finalize>,
1048 ignore_binding: Option<&'a NameBinding<'a>>,
1049 ) -> Option<LexicalScopeBinding<'a>> {
1050 self.r.resolve_ident_in_lexical_scope(
1063 opt_ns: Option<Namespace>, // `None` indicates a module path in import
1064 finalize: Option<Finalize>,
1065 ) -> PathResult<'a> {
1066 self.r.resolve_path_with_ribs(
1078 // We maintain a list of value ribs and type ribs.
1080 // Simultaneously, we keep track of the current position in the module
1081 // graph in the `parent_scope.module` pointer. When we go to resolve a name in
1082 // the value or type namespaces, we first look through all the ribs and
1083 // then query the module graph. When we resolve a name in the module
1084 // namespace, we can skip all the ribs (since nested modules are not
1085 // allowed within blocks in Rust) and jump straight to the current module
1088 // Named implementations are handled separately. When we find a method
1089 // call, we consult the module node to find all of the implementations in
1090 // scope. This information is lazily cached in the module node. We then
1091 // generate a fake "implementation scope" containing all the
1092 // implementations thus found, for compatibility with old resolve pass.
1094 /// Do some `work` within a new innermost rib of the given `kind` in the given namespace (`ns`).
1099 work: impl FnOnce(&mut Self) -> T,
1101 self.ribs[ns].push(Rib::new(kind));
1102 let ret = work(self);
1103 self.ribs[ns].pop();
1107 fn with_scope<T>(&mut self, id: NodeId, f: impl FnOnce(&mut Self) -> T) -> T {
1108 if let Some(module) = self.r.get_module(self.r.local_def_id(id).to_def_id()) {
1109 // Move down in the graph.
1110 let orig_module = replace(&mut self.parent_scope.module, module);
1111 self.with_rib(ValueNS, ModuleRibKind(module), |this| {
1112 this.with_rib(TypeNS, ModuleRibKind(module), |this| {
1114 this.parent_scope.module = orig_module;
1123 fn visit_generic_param_vec(&mut self, params: &'ast Vec<GenericParam>, add_self_upper: bool) {
1124 // For type parameter defaults, we have to ban access
1125 // to following type parameters, as the InternalSubsts can only
1126 // provide previous type parameters as they're built. We
1127 // put all the parameters on the ban list and then remove
1128 // them one by one as they are processed and become available.
1129 let mut forward_ty_ban_rib = Rib::new(ForwardGenericParamBanRibKind);
1130 let mut forward_const_ban_rib = Rib::new(ForwardGenericParamBanRibKind);
1131 for param in params.iter() {
1133 GenericParamKind::Type { .. } => {
1136 .insert(Ident::with_dummy_span(param.ident.name), Res::Err);
1138 GenericParamKind::Const { .. } => {
1139 forward_const_ban_rib
1141 .insert(Ident::with_dummy_span(param.ident.name), Res::Err);
1143 GenericParamKind::Lifetime => {}
1147 // rust-lang/rust#61631: The type `Self` is essentially
1148 // another type parameter. For ADTs, we consider it
1149 // well-defined only after all of the ADT type parameters have
1150 // been provided. Therefore, we do not allow use of `Self`
1151 // anywhere in ADT type parameter defaults.
1153 // (We however cannot ban `Self` for defaults on *all* generic
1154 // lists; e.g. trait generics can usefully refer to `Self`,
1155 // such as in the case of `trait Add<Rhs = Self>`.)
1157 // (`Some` if + only if we are in ADT's generics.)
1158 forward_ty_ban_rib.bindings.insert(Ident::with_dummy_span(kw::SelfUpper), Res::Err);
1161 self.with_lifetime_rib(LifetimeRibKind::AnonymousReportError, |this| {
1162 for param in params {
1164 GenericParamKind::Lifetime => {
1165 for bound in ¶m.bounds {
1166 this.visit_param_bound(bound, BoundKind::Bound);
1169 GenericParamKind::Type { ref default } => {
1170 for bound in ¶m.bounds {
1171 this.visit_param_bound(bound, BoundKind::Bound);
1174 if let Some(ref ty) = default {
1175 this.ribs[TypeNS].push(forward_ty_ban_rib);
1176 this.ribs[ValueNS].push(forward_const_ban_rib);
1178 forward_const_ban_rib = this.ribs[ValueNS].pop().unwrap();
1179 forward_ty_ban_rib = this.ribs[TypeNS].pop().unwrap();
1182 // Allow all following defaults to refer to this type parameter.
1185 .remove(&Ident::with_dummy_span(param.ident.name));
1187 GenericParamKind::Const { ref ty, kw_span: _, ref default } => {
1188 // Const parameters can't have param bounds.
1189 assert!(param.bounds.is_empty());
1191 this.ribs[TypeNS].push(Rib::new(ConstParamTyRibKind));
1192 this.ribs[ValueNS].push(Rib::new(ConstParamTyRibKind));
1193 this.with_lifetime_rib(LifetimeRibKind::ConstGeneric, |this| {
1196 this.ribs[TypeNS].pop().unwrap();
1197 this.ribs[ValueNS].pop().unwrap();
1199 if let Some(ref expr) = default {
1200 this.ribs[TypeNS].push(forward_ty_ban_rib);
1201 this.ribs[ValueNS].push(forward_const_ban_rib);
1202 this.with_lifetime_rib(LifetimeRibKind::ConstGeneric, |this| {
1203 this.resolve_anon_const(expr, IsRepeatExpr::No)
1205 forward_const_ban_rib = this.ribs[ValueNS].pop().unwrap();
1206 forward_ty_ban_rib = this.ribs[TypeNS].pop().unwrap();
1209 // Allow all following defaults to refer to this const parameter.
1210 forward_const_ban_rib
1212 .remove(&Ident::with_dummy_span(param.ident.name));
1219 #[tracing::instrument(level = "debug", skip(self, work))]
1220 fn with_lifetime_rib<T>(
1222 kind: LifetimeRibKind,
1223 work: impl FnOnce(&mut Self) -> T,
1225 self.lifetime_ribs.push(LifetimeRib::new(kind));
1226 let ret = work(self);
1227 self.lifetime_ribs.pop();
1231 #[tracing::instrument(level = "debug", skip(self))]
1232 fn resolve_lifetime(&mut self, lifetime: &'ast Lifetime, use_ctxt: visit::LifetimeCtxt) {
1233 let ident = lifetime.ident;
1235 if ident.name == kw::StaticLifetime {
1236 self.record_lifetime_res(lifetime.id, LifetimeRes::Static);
1240 if ident.name == kw::UnderscoreLifetime {
1241 return self.resolve_anonymous_lifetime(lifetime, false);
1244 let mut indices = (0..self.lifetime_ribs.len()).rev();
1245 for i in &mut indices {
1246 let rib = &self.lifetime_ribs[i];
1247 let normalized_ident = ident.normalize_to_macros_2_0();
1248 if let Some(&(_, region)) = rib.bindings.get(&normalized_ident) {
1249 self.record_lifetime_res(lifetime.id, region);
1251 if let LifetimeRes::Param { param, .. } = region {
1252 match self.lifetime_uses.entry(param) {
1253 Entry::Vacant(v) => {
1254 debug!("First use of {:?} at {:?}", region, ident.span);
1259 .find_map(|rib| match rib.kind {
1260 // Do not suggest eliding a lifetime where an anonymous
1261 // lifetime would be illegal.
1262 LifetimeRibKind::Item
1263 | LifetimeRibKind::AnonymousPassThrough(_, true)
1264 | LifetimeRibKind::AnonymousReportError => {
1265 Some(LifetimeUseSet::Many)
1267 // An anonymous lifetime is legal here, go ahead.
1268 LifetimeRibKind::AnonymousPassThrough(_, false)
1269 | LifetimeRibKind::AnonymousCreateParameter(_) => {
1270 Some(LifetimeUseSet::One { use_span: ident.span, use_ctxt })
1274 .unwrap_or(LifetimeUseSet::Many);
1275 debug!(?use_ctxt, ?use_set);
1278 Entry::Occupied(mut o) => {
1279 debug!("Many uses of {:?} at {:?}", region, ident.span);
1280 *o.get_mut() = LifetimeUseSet::Many;
1288 LifetimeRibKind::Item => break,
1289 LifetimeRibKind::ConstGeneric => {
1290 self.emit_non_static_lt_in_const_generic_error(lifetime);
1291 self.r.lifetimes_res_map.insert(lifetime.id, LifetimeRes::Error);
1294 LifetimeRibKind::AnonConst => {
1295 self.maybe_emit_forbidden_non_static_lifetime_error(lifetime);
1296 self.r.lifetimes_res_map.insert(lifetime.id, LifetimeRes::Error);
1303 let mut outer_res = None;
1305 let rib = &self.lifetime_ribs[i];
1306 let normalized_ident = ident.normalize_to_macros_2_0();
1307 if let Some((&outer, _)) = rib.bindings.get_key_value(&normalized_ident) {
1308 outer_res = Some(outer);
1313 self.emit_undeclared_lifetime_error(lifetime, outer_res);
1314 self.record_lifetime_res(lifetime.id, LifetimeRes::Error);
1317 #[tracing::instrument(level = "debug", skip(self))]
1318 fn resolve_anonymous_lifetime(&mut self, lifetime: &Lifetime, elided: bool) {
1319 debug_assert_eq!(lifetime.ident.name, kw::UnderscoreLifetime);
1321 for i in (0..self.lifetime_ribs.len()).rev() {
1322 let rib = &mut self.lifetime_ribs[i];
1324 LifetimeRibKind::AnonymousCreateParameter(item_node_id) => {
1325 self.create_fresh_lifetime(lifetime.id, lifetime.ident, item_node_id);
1328 LifetimeRibKind::AnonymousReportError => {
1329 let (msg, note) = if elided {
1331 "`&` without an explicit lifetime name cannot be used here",
1332 "explicit lifetime name needed here",
1335 ("`'_` cannot be used here", "`'_` is a reserved lifetime name")
1337 rustc_errors::struct_span_err!(
1339 lifetime.ident.span,
1344 .span_label(lifetime.ident.span, note)
1347 self.record_lifetime_res(lifetime.id, LifetimeRes::Error);
1350 LifetimeRibKind::AnonymousPassThrough(node_id, _) => {
1351 self.record_lifetime_res(
1353 LifetimeRes::Anonymous { binder: node_id, elided },
1357 LifetimeRibKind::Item => break,
1361 // This resolution is wrong, it passes the work to HIR lifetime resolution.
1362 // We cannot use `LifetimeRes::Error` because we do not emit a diagnostic.
1363 self.record_lifetime_res(
1365 LifetimeRes::Anonymous { binder: DUMMY_NODE_ID, elided },
1369 #[tracing::instrument(level = "debug", skip(self))]
1370 fn resolve_elided_lifetime(&mut self, anchor_id: NodeId, span: Span) {
1371 let id = self.r.next_node_id();
1372 self.record_lifetime_res(
1374 LifetimeRes::ElidedAnchor { start: id, end: NodeId::from_u32(id.as_u32() + 1) },
1377 let lt = Lifetime { id, ident: Ident::new(kw::UnderscoreLifetime, span) };
1378 self.resolve_anonymous_lifetime(<, true);
1381 #[tracing::instrument(level = "debug", skip(self))]
1382 fn create_fresh_lifetime(&mut self, id: NodeId, ident: Ident, item_node_id: NodeId) {
1383 debug_assert_eq!(ident.name, kw::UnderscoreLifetime);
1384 debug!(?ident.span);
1385 let item_def_id = self.r.local_def_id(item_node_id);
1386 let def_node_id = self.r.next_node_id();
1387 let def_id = self.r.create_def(
1390 DefPathData::LifetimeNs(kw::UnderscoreLifetime),
1391 self.parent_scope.expansion.to_expn_id(),
1396 let region = LifetimeRes::Fresh { param: def_id, binder: item_node_id };
1397 self.record_lifetime_res(id, region);
1398 self.r.extra_lifetime_params_map.entry(item_node_id).or_insert_with(Vec::new).push((
1405 #[tracing::instrument(level = "debug", skip(self))]
1406 fn resolve_elided_lifetimes_in_path(
1409 partial_res: PartialRes,
1411 source: PathSource<'_>,
1414 let proj_start = path.len() - partial_res.unresolved_segments();
1415 for (i, segment) in path.iter().enumerate() {
1416 if segment.has_lifetime_args {
1419 let Some(segment_id) = segment.id else {
1423 // Figure out if this is a type/trait segment,
1424 // which may need lifetime elision performed.
1425 let type_def_id = match partial_res.base_res() {
1426 Res::Def(DefKind::AssocTy, def_id) if i + 2 == proj_start => self.r.parent(def_id),
1427 Res::Def(DefKind::Variant, def_id) if i + 1 == proj_start => self.r.parent(def_id),
1428 Res::Def(DefKind::Struct, def_id)
1429 | Res::Def(DefKind::Union, def_id)
1430 | Res::Def(DefKind::Enum, def_id)
1431 | Res::Def(DefKind::TyAlias, def_id)
1432 | Res::Def(DefKind::Trait, def_id)
1433 if i + 1 == proj_start =>
1440 let expected_lifetimes = self.r.item_generics_num_lifetimes(type_def_id);
1441 if expected_lifetimes == 0 {
1445 let missing = match source {
1446 PathSource::Trait(..) | PathSource::TraitItem(..) | PathSource::Type => true,
1447 PathSource::Expr(..)
1449 | PathSource::Struct
1450 | PathSource::TupleStruct(..) => false,
1452 let mut res = LifetimeRes::Error;
1453 for rib in self.lifetime_ribs.iter().rev() {
1455 // In create-parameter mode we error here because we don't want to support
1456 // deprecated impl elision in new features like impl elision and `async fn`,
1457 // both of which work using the `CreateParameter` mode:
1459 // impl Foo for std::cell::Ref<u32> // note lack of '_
1460 // async fn foo(_: std::cell::Ref<u32>) { ... }
1461 LifetimeRibKind::AnonymousCreateParameter(_) => {
1464 // `PassThrough` is the normal case.
1465 // `new_error_lifetime`, which would usually be used in the case of `ReportError`,
1466 // is unsuitable here, as these can occur from missing lifetime parameters in a
1467 // `PathSegment`, for which there is no associated `'_` or `&T` with no explicit
1468 // lifetime. Instead, we simply create an implicit lifetime, which will be checked
1469 // later, at which point a suitable error will be emitted.
1470 LifetimeRibKind::AnonymousPassThrough(binder, _) => {
1471 res = LifetimeRes::Anonymous { binder, elided: true };
1474 LifetimeRibKind::AnonymousReportError | LifetimeRibKind::Item => {
1475 // FIXME(cjgillot) This resolution is wrong, but this does not matter
1476 // since these cases are erroneous anyway. Lifetime resolution should
1477 // emit a "missing lifetime specifier" diagnostic.
1478 res = LifetimeRes::Anonymous { binder: DUMMY_NODE_ID, elided: true };
1485 let node_ids = self.r.next_node_ids(expected_lifetimes);
1486 self.record_lifetime_res(
1488 LifetimeRes::ElidedAnchor { start: node_ids.start, end: node_ids.end },
1490 for i in 0..expected_lifetimes {
1491 let id = node_ids.start.plus(i);
1492 self.record_lifetime_res(id, res);
1499 let elided_lifetime_span = if segment.has_generic_args {
1500 // If there are brackets, but not generic arguments, then use the opening bracket
1501 segment.args_span.with_hi(segment.args_span.lo() + BytePos(1))
1503 // If there are no brackets, use the identifier span.
1504 // HACK: we use find_ancestor_inside to properly suggest elided spans in paths
1505 // originating from macros, since the segment's span might be from a macro arg.
1506 segment.ident.span.find_ancestor_inside(path_span).unwrap_or(path_span)
1508 if let LifetimeRes::Error = res {
1509 let sess = self.r.session;
1510 let mut err = rustc_errors::struct_span_err!(
1514 "implicit elided lifetime not allowed here"
1516 rustc_errors::add_elided_lifetime_in_path_suggestion(
1521 !segment.has_generic_args,
1522 elided_lifetime_span,
1524 err.note("assuming a `'static` lifetime...");
1527 self.r.lint_buffer.buffer_lint_with_diagnostic(
1528 lint::builtin::ELIDED_LIFETIMES_IN_PATHS,
1530 elided_lifetime_span,
1531 "hidden lifetime parameters in types are deprecated",
1532 lint::BuiltinLintDiagnostics::ElidedLifetimesInPaths(
1535 !segment.has_generic_args,
1536 elided_lifetime_span,
1543 #[tracing::instrument(level = "debug", skip(self))]
1544 fn record_lifetime_res(&mut self, id: NodeId, res: LifetimeRes) {
1545 if let Some(prev_res) = self.r.lifetimes_res_map.insert(id, res) {
1547 "lifetime {:?} resolved multiple times ({:?} before, {:?} now)",
1553 /// Searches the current set of local scopes for labels. Returns the `NodeId` of the resolved
1554 /// label and reports an error if the label is not found or is unreachable.
1555 fn resolve_label(&mut self, mut label: Ident) -> Option<NodeId> {
1556 let mut suggestion = None;
1558 // Preserve the original span so that errors contain "in this macro invocation"
1560 let original_span = label.span;
1562 for i in (0..self.label_ribs.len()).rev() {
1563 let rib = &self.label_ribs[i];
1565 if let MacroDefinition(def) = rib.kind {
1566 // If an invocation of this macro created `ident`, give up on `ident`
1567 // and switch to `ident`'s source from the macro definition.
1568 if def == self.r.macro_def(label.span.ctxt()) {
1569 label.span.remove_mark();
1573 let ident = label.normalize_to_macro_rules();
1574 if let Some((ident, id)) = rib.bindings.get_key_value(&ident) {
1575 let definition_span = ident.span;
1576 return if self.is_label_valid_from_rib(i) {
1581 ResolutionError::UnreachableLabel {
1592 // Diagnostics: Check if this rib contains a label with a similar name, keep track of
1593 // the first such label that is encountered.
1594 suggestion = suggestion.or_else(|| self.suggestion_for_label_in_rib(i, label));
1599 ResolutionError::UndeclaredLabel { name: label.name, suggestion },
1604 /// Determine whether or not a label from the `rib_index`th label rib is reachable.
1605 fn is_label_valid_from_rib(&self, rib_index: usize) -> bool {
1606 let ribs = &self.label_ribs[rib_index + 1..];
1609 if rib.kind.is_label_barrier() {
1617 fn resolve_adt(&mut self, item: &'ast Item, generics: &'ast Generics) {
1618 debug!("resolve_adt");
1619 self.with_current_self_item(item, |this| {
1620 this.with_generic_param_rib(
1622 ItemRibKind(HasGenericParams::Yes),
1623 LifetimeRibKind::Generics {
1625 kind: LifetimeBinderKind::Item,
1626 span: generics.span,
1629 let item_def_id = this.r.local_def_id(item.id).to_def_id();
1631 Res::SelfTy { trait_: None, alias_to: Some((item_def_id, false)) },
1633 visit::walk_item(this, item);
1641 fn future_proof_import(&mut self, use_tree: &UseTree) {
1642 let segments = &use_tree.prefix.segments;
1643 if !segments.is_empty() {
1644 let ident = segments[0].ident;
1645 if ident.is_path_segment_keyword() || ident.span.rust_2015() {
1649 let nss = match use_tree.kind {
1650 UseTreeKind::Simple(..) if segments.len() == 1 => &[TypeNS, ValueNS][..],
1653 let report_error = |this: &Self, ns| {
1654 let what = if ns == TypeNS { "type parameters" } else { "local variables" };
1655 if this.should_report_errs() {
1658 .span_err(ident.span, &format!("imports cannot refer to {}", what));
1663 match self.maybe_resolve_ident_in_lexical_scope(ident, ns) {
1664 Some(LexicalScopeBinding::Res(..)) => {
1665 report_error(self, ns);
1667 Some(LexicalScopeBinding::Item(binding)) => {
1668 if let Some(LexicalScopeBinding::Res(..)) =
1669 self.resolve_ident_in_lexical_scope(ident, ns, None, Some(binding))
1671 report_error(self, ns);
1677 } else if let UseTreeKind::Nested(use_trees) = &use_tree.kind {
1678 for (use_tree, _) in use_trees {
1679 self.future_proof_import(use_tree);
1684 fn resolve_item(&mut self, item: &'ast Item) {
1685 let name = item.ident.name;
1686 debug!("(resolving item) resolving {} ({:?})", name, item.kind);
1689 ItemKind::TyAlias(box TyAlias { ref generics, .. }) => {
1690 self.with_generic_param_rib(
1692 ItemRibKind(HasGenericParams::Yes),
1693 LifetimeRibKind::Generics {
1695 kind: LifetimeBinderKind::Item,
1696 span: generics.span,
1698 |this| visit::walk_item(this, item),
1702 ItemKind::Fn(box Fn { ref generics, .. }) => {
1703 self.with_generic_param_rib(
1705 ItemRibKind(HasGenericParams::Yes),
1706 LifetimeRibKind::Generics {
1708 kind: LifetimeBinderKind::Function,
1709 span: generics.span,
1711 |this| visit::walk_item(this, item),
1715 ItemKind::Enum(_, ref generics)
1716 | ItemKind::Struct(_, ref generics)
1717 | ItemKind::Union(_, ref generics) => {
1718 self.resolve_adt(item, generics);
1721 ItemKind::Impl(box Impl {
1725 items: ref impl_items,
1728 self.diagnostic_metadata.current_impl_items = Some(impl_items);
1729 self.resolve_implementation(generics, of_trait, &self_ty, item.id, impl_items);
1730 self.diagnostic_metadata.current_impl_items = None;
1733 ItemKind::Trait(box Trait { ref generics, ref bounds, ref items, .. }) => {
1734 // Create a new rib for the trait-wide type parameters.
1735 self.with_generic_param_rib(
1737 ItemRibKind(HasGenericParams::Yes),
1738 LifetimeRibKind::Generics {
1740 kind: LifetimeBinderKind::Item,
1741 span: generics.span,
1744 let local_def_id = this.r.local_def_id(item.id).to_def_id();
1746 Res::SelfTy { trait_: Some(local_def_id), alias_to: None },
1748 this.visit_generics(generics);
1749 walk_list!(this, visit_param_bound, bounds, BoundKind::SuperTraits);
1751 let walk_assoc_item =
1753 generics: &Generics,
1755 item: &'ast AssocItem| {
1756 this.with_generic_param_rib(
1759 LifetimeRibKind::Generics {
1761 span: generics.span,
1765 visit::walk_assoc_item(this, item, AssocCtxt::Trait)
1770 this.with_trait_items(items, |this| {
1773 AssocItemKind::Const(_, ty, default) => {
1775 // Only impose the restrictions of `ConstRibKind` for an
1776 // actual constant expression in a provided default.
1777 if let Some(expr) = default {
1778 // We allow arbitrary const expressions inside of associated consts,
1779 // even if they are potentially not const evaluatable.
1781 // Type parameters can already be used and as associated consts are
1782 // not used as part of the type system, this is far less surprising.
1783 this.with_constant_rib(
1785 HasGenericParams::Yes,
1787 |this| this.visit_expr(expr),
1791 AssocItemKind::Fn(box Fn { generics, .. }) => {
1795 LifetimeBinderKind::Function,
1799 AssocItemKind::TyAlias(box TyAlias {
1806 LifetimeBinderKind::Item,
1810 AssocItemKind::MacCall(_) => {
1811 panic!("unexpanded macro in resolve!")
1822 ItemKind::TraitAlias(ref generics, ref bounds) => {
1823 // Create a new rib for the trait-wide type parameters.
1824 self.with_generic_param_rib(
1826 ItemRibKind(HasGenericParams::Yes),
1827 LifetimeRibKind::Generics {
1829 kind: LifetimeBinderKind::Item,
1830 span: generics.span,
1833 let local_def_id = this.r.local_def_id(item.id).to_def_id();
1835 Res::SelfTy { trait_: Some(local_def_id), alias_to: None },
1837 this.visit_generics(generics);
1838 walk_list!(this, visit_param_bound, bounds, BoundKind::Bound);
1845 ItemKind::Mod(..) | ItemKind::ForeignMod(_) => {
1846 self.with_scope(item.id, |this| {
1847 visit::walk_item(this, item);
1851 ItemKind::Static(ref ty, _, ref expr) | ItemKind::Const(_, ref ty, ref expr) => {
1852 self.with_item_rib(|this| {
1854 if let Some(expr) = expr {
1855 let constant_item_kind = match item.kind {
1856 ItemKind::Const(..) => ConstantItemKind::Const,
1857 ItemKind::Static(..) => ConstantItemKind::Static,
1858 _ => unreachable!(),
1860 // We already forbid generic params because of the above item rib,
1861 // so it doesn't matter whether this is a trivial constant.
1862 this.with_constant_rib(
1864 HasGenericParams::Yes,
1865 Some((item.ident, constant_item_kind)),
1866 |this| this.visit_expr(expr),
1872 ItemKind::Use(ref use_tree) => {
1873 self.future_proof_import(use_tree);
1876 ItemKind::ExternCrate(..) | ItemKind::MacroDef(..) => {
1877 // do nothing, these are just around to be encoded
1880 ItemKind::GlobalAsm(_) => {
1881 visit::walk_item(self, item);
1884 ItemKind::MacCall(_) => panic!("unexpanded macro in resolve!"),
1888 fn with_generic_param_rib<'c, F>(
1890 params: &'c Vec<GenericParam>,
1892 lifetime_kind: LifetimeRibKind,
1895 F: FnOnce(&mut Self),
1897 debug!("with_generic_param_rib");
1898 let LifetimeRibKind::Generics { binder, span: generics_span, kind: generics_kind, .. }
1899 = lifetime_kind else { panic!() };
1901 let mut function_type_rib = Rib::new(kind);
1902 let mut function_value_rib = Rib::new(kind);
1903 let mut function_lifetime_rib = LifetimeRib::new(lifetime_kind);
1904 let mut seen_bindings = FxHashMap::default();
1905 let mut seen_lifetimes = FxHashMap::default();
1907 // We also can't shadow bindings from the parent item
1908 if let AssocItemRibKind = kind {
1909 let mut add_bindings_for_ns = |ns| {
1910 let parent_rib = self.ribs[ns]
1912 .rfind(|r| matches!(r.kind, ItemRibKind(_)))
1913 .expect("associated item outside of an item");
1915 .extend(parent_rib.bindings.iter().map(|(ident, _)| (*ident, ident.span)));
1917 add_bindings_for_ns(ValueNS);
1918 add_bindings_for_ns(TypeNS);
1921 // Forbid shadowing lifetime bindings
1922 for rib in self.lifetime_ribs.iter().rev() {
1923 seen_lifetimes.extend(
1924 rib.bindings.iter().map(|(ident, _)| (*ident, original_lifetime(ident.span))),
1926 if let LifetimeRibKind::Item = rib.kind {
1930 for rib in self.label_ribs.iter().rev() {
1931 if rib.kind.is_label_barrier() {
1935 .extend(rib.bindings.iter().map(|(ident, _)| (*ident, original_label(ident.span))));
1938 for param in params {
1939 let ident = param.ident.normalize_to_macros_2_0();
1940 debug!("with_generic_param_rib: {}", param.id);
1942 if let GenericParamKind::Lifetime = param.kind {
1943 match seen_lifetimes.entry(ident) {
1944 Entry::Occupied(entry) => {
1945 let original = *entry.get();
1946 diagnostics::signal_shadowing_problem(
1950 shadower_lifetime(param.ident.span),
1953 Entry::Vacant(entry) => {
1954 entry.insert(original_lifetime_param(param.ident.span));
1958 match seen_bindings.entry(ident) {
1959 Entry::Occupied(entry) => {
1960 let span = *entry.get();
1961 let err = ResolutionError::NameAlreadyUsedInParameterList(ident.name, span);
1962 self.report_error(param.ident.span, err);
1964 Entry::Vacant(entry) => {
1965 entry.insert(param.ident.span);
1970 if param.ident.name == kw::UnderscoreLifetime {
1971 rustc_errors::struct_span_err!(
1975 "`'_` cannot be used here"
1977 .span_label(param.ident.span, "`'_` is a reserved lifetime name")
1982 if param.ident.name == kw::StaticLifetime {
1983 rustc_errors::struct_span_err!(
1987 "invalid lifetime parameter name: `{}`",
1990 .span_label(param.ident.span, "'static is a reserved lifetime name")
1995 let def_id = self.r.local_def_id(param.id);
1997 // Plain insert (no renaming).
1998 let (rib, def_kind) = match param.kind {
1999 GenericParamKind::Type { .. } => (&mut function_type_rib, DefKind::TyParam),
2000 GenericParamKind::Const { .. } => (&mut function_value_rib, DefKind::ConstParam),
2001 GenericParamKind::Lifetime => {
2002 let res = LifetimeRes::Param { param: def_id, binder };
2003 self.record_lifetime_res(param.id, res);
2004 function_lifetime_rib.bindings.insert(ident, (param.id, res));
2008 let res = Res::Def(def_kind, def_id.to_def_id());
2009 self.r.record_partial_res(param.id, PartialRes::new(res));
2010 rib.bindings.insert(ident, res);
2013 self.lifetime_ribs.push(function_lifetime_rib);
2014 self.ribs[ValueNS].push(function_value_rib);
2015 self.ribs[TypeNS].push(function_type_rib);
2019 self.ribs[TypeNS].pop();
2020 self.ribs[ValueNS].pop();
2021 self.lifetime_ribs.pop();
2023 if let LifetimeBinderKind::BareFnType
2024 | LifetimeBinderKind::WhereBound
2025 | LifetimeBinderKind::Function
2026 | LifetimeBinderKind::ImplBlock = generics_kind
2028 self.maybe_report_lifetime_uses(generics_span, params)
2032 fn with_label_rib(&mut self, kind: RibKind<'a>, f: impl FnOnce(&mut Self)) {
2033 self.label_ribs.push(Rib::new(kind));
2035 self.label_ribs.pop();
2038 fn with_item_rib(&mut self, f: impl FnOnce(&mut Self)) {
2039 let kind = ItemRibKind(HasGenericParams::No);
2040 self.with_lifetime_rib(LifetimeRibKind::Item, |this| {
2041 this.with_rib(ValueNS, kind, |this| this.with_rib(TypeNS, kind, f))
2045 // HACK(min_const_generics,const_evaluatable_unchecked): We
2046 // want to keep allowing `[0; std::mem::size_of::<*mut T>()]`
2047 // with a future compat lint for now. We do this by adding an
2048 // additional special case for repeat expressions.
2050 // Note that we intentionally still forbid `[0; N + 1]` during
2051 // name resolution so that we don't extend the future
2052 // compat lint to new cases.
2053 #[instrument(level = "debug", skip(self, f))]
2054 fn with_constant_rib(
2056 is_repeat: IsRepeatExpr,
2057 may_use_generics: HasGenericParams,
2058 item: Option<(Ident, ConstantItemKind)>,
2059 f: impl FnOnce(&mut Self),
2061 self.with_rib(ValueNS, ConstantItemRibKind(may_use_generics, item), |this| {
2064 ConstantItemRibKind(
2065 may_use_generics.force_yes_if(is_repeat == IsRepeatExpr::Yes),
2069 this.with_label_rib(ConstantItemRibKind(may_use_generics, item), f);
2075 fn with_current_self_type<T>(&mut self, self_type: &Ty, f: impl FnOnce(&mut Self) -> T) -> T {
2076 // Handle nested impls (inside fn bodies)
2077 let previous_value =
2078 replace(&mut self.diagnostic_metadata.current_self_type, Some(self_type.clone()));
2079 let result = f(self);
2080 self.diagnostic_metadata.current_self_type = previous_value;
2084 fn with_current_self_item<T>(&mut self, self_item: &Item, f: impl FnOnce(&mut Self) -> T) -> T {
2085 let previous_value =
2086 replace(&mut self.diagnostic_metadata.current_self_item, Some(self_item.id));
2087 let result = f(self);
2088 self.diagnostic_metadata.current_self_item = previous_value;
2092 /// When evaluating a `trait` use its associated types' idents for suggestions in E0412.
2093 fn with_trait_items<T>(
2095 trait_items: &'ast [P<AssocItem>],
2096 f: impl FnOnce(&mut Self) -> T,
2098 let trait_assoc_items =
2099 replace(&mut self.diagnostic_metadata.current_trait_assoc_items, Some(&trait_items));
2100 let result = f(self);
2101 self.diagnostic_metadata.current_trait_assoc_items = trait_assoc_items;
2105 /// This is called to resolve a trait reference from an `impl` (i.e., `impl Trait for Foo`).
2106 fn with_optional_trait_ref<T>(
2108 opt_trait_ref: Option<&TraitRef>,
2109 f: impl FnOnce(&mut Self, Option<DefId>) -> T,
2111 let mut new_val = None;
2112 let mut new_id = None;
2113 if let Some(trait_ref) = opt_trait_ref {
2114 let path: Vec<_> = Segment::from_path(&trait_ref.path);
2115 let res = self.smart_resolve_path_fragment(
2118 PathSource::Trait(AliasPossibility::No),
2119 Finalize::new(trait_ref.ref_id, trait_ref.path.span),
2121 if let Some(def_id) = res.base_res().opt_def_id() {
2122 new_id = Some(def_id);
2123 new_val = Some((self.r.expect_module(def_id), trait_ref.clone()));
2126 let original_trait_ref = replace(&mut self.current_trait_ref, new_val);
2127 let result = f(self, new_id);
2128 self.current_trait_ref = original_trait_ref;
2132 fn with_self_rib_ns(&mut self, ns: Namespace, self_res: Res, f: impl FnOnce(&mut Self)) {
2133 let mut self_type_rib = Rib::new(NormalRibKind);
2135 // Plain insert (no renaming, since types are not currently hygienic)
2136 self_type_rib.bindings.insert(Ident::with_dummy_span(kw::SelfUpper), self_res);
2137 self.ribs[ns].push(self_type_rib);
2139 self.ribs[ns].pop();
2142 fn with_self_rib(&mut self, self_res: Res, f: impl FnOnce(&mut Self)) {
2143 self.with_self_rib_ns(TypeNS, self_res, f)
2146 fn resolve_implementation(
2148 generics: &'ast Generics,
2149 opt_trait_reference: &'ast Option<TraitRef>,
2150 self_type: &'ast Ty,
2152 impl_items: &'ast [P<AssocItem>],
2154 debug!("resolve_implementation");
2155 // If applicable, create a rib for the type parameters.
2156 self.with_generic_param_rib(&generics.params, ItemRibKind(HasGenericParams::Yes), LifetimeRibKind::Generics { span: generics.span, binder: item_id, kind: LifetimeBinderKind::ImplBlock }, |this| {
2157 // Dummy self type for better errors if `Self` is used in the trait path.
2158 this.with_self_rib(Res::SelfTy { trait_: None, alias_to: None }, |this| {
2159 this.with_lifetime_rib(LifetimeRibKind::AnonymousCreateParameter(item_id), |this| {
2160 // Resolve the trait reference, if necessary.
2161 this.with_optional_trait_ref(opt_trait_reference.as_ref(), |this, trait_id| {
2162 let item_def_id = this.r.local_def_id(item_id);
2164 // Register the trait definitions from here.
2165 if let Some(trait_id) = trait_id {
2166 this.r.trait_impls.entry(trait_id).or_default().push(item_def_id);
2169 let item_def_id = item_def_id.to_def_id();
2171 Res::SelfTy { trait_: trait_id, alias_to: Some((item_def_id, false)) };
2172 this.with_self_rib(res, |this| {
2173 if let Some(trait_ref) = opt_trait_reference.as_ref() {
2174 // Resolve type arguments in the trait path.
2175 visit::walk_trait_ref(this, trait_ref);
2177 // Resolve the self type.
2178 this.visit_ty(self_type);
2179 // Resolve the generic parameters.
2180 this.visit_generics(generics);
2182 // Resolve the items within the impl.
2183 this.with_lifetime_rib(LifetimeRibKind::AnonymousPassThrough(item_id,false),
2185 this.with_current_self_type(self_type, |this| {
2186 this.with_self_rib_ns(ValueNS, Res::SelfCtor(item_def_id), |this| {
2187 debug!("resolve_implementation with_self_rib_ns(ValueNS, ...)");
2188 for item in impl_items {
2189 use crate::ResolutionError::*;
2191 AssocItemKind::Const(_default, _ty, _expr) => {
2192 debug!("resolve_implementation AssocItemKind::Const");
2193 // If this is a trait impl, ensure the const
2195 this.check_trait_item(
2201 |i, s, c| ConstNotMemberOfTrait(i, s, c),
2204 // We allow arbitrary const expressions inside of associated consts,
2205 // even if they are potentially not const evaluatable.
2207 // Type parameters can already be used and as associated consts are
2208 // not used as part of the type system, this is far less surprising.
2209 this.with_constant_rib(
2211 HasGenericParams::Yes,
2214 visit::walk_assoc_item(
2222 AssocItemKind::Fn(box Fn { generics, .. }) => {
2223 debug!("resolve_implementation AssocItemKind::Fn");
2224 // We also need a new scope for the impl item type parameters.
2225 this.with_generic_param_rib(
2228 LifetimeRibKind::Generics { binder: item.id, span: generics.span, kind: LifetimeBinderKind::Function },
2230 // If this is a trait impl, ensure the method
2232 this.check_trait_item(
2238 |i, s, c| MethodNotMemberOfTrait(i, s, c),
2241 visit::walk_assoc_item(
2249 AssocItemKind::TyAlias(box TyAlias {
2252 debug!("resolve_implementation AssocItemKind::TyAlias");
2253 // We also need a new scope for the impl item type parameters.
2254 this.with_generic_param_rib(
2257 LifetimeRibKind::Generics { binder: item.id, span: generics.span, kind: LifetimeBinderKind::Item },
2259 // If this is a trait impl, ensure the type
2261 this.check_trait_item(
2267 |i, s, c| TypeNotMemberOfTrait(i, s, c),
2270 visit::walk_assoc_item(
2278 AssocItemKind::MacCall(_) => {
2279 panic!("unexpanded macro in resolve!")
2294 fn check_trait_item<F>(
2298 kind: &AssocItemKind,
2303 F: FnOnce(Ident, String, Option<Symbol>) -> ResolutionError<'a>,
2305 // If there is a TraitRef in scope for an impl, then the method must be in the trait.
2306 let Some((module, _)) = &self.current_trait_ref else { return; };
2307 ident.span.normalize_to_macros_2_0_and_adjust(module.expansion);
2308 let key = self.r.new_key(ident, ns);
2309 let mut binding = self.r.resolution(module, key).try_borrow().ok().and_then(|r| r.binding);
2311 if binding.is_none() {
2312 // We could not find the trait item in the correct namespace.
2313 // Check the other namespace to report an error.
2319 let key = self.r.new_key(ident, ns);
2320 binding = self.r.resolution(module, key).try_borrow().ok().and_then(|r| r.binding);
2323 let Some(binding) = binding else {
2324 // We could not find the method: report an error.
2325 let candidate = self.find_similarly_named_assoc_item(ident.name, kind);
2326 let path = &self.current_trait_ref.as_ref().unwrap().1.path;
2327 let path_names = path_names_to_string(path);
2328 self.report_error(span, err(ident, path_names, candidate));
2332 let res = binding.res();
2333 let Res::Def(def_kind, _) = res else { bug!() };
2334 match (def_kind, kind) {
2335 (DefKind::AssocTy, AssocItemKind::TyAlias(..))
2336 | (DefKind::AssocFn, AssocItemKind::Fn(..))
2337 | (DefKind::AssocConst, AssocItemKind::Const(..)) => {
2338 self.r.record_partial_res(id, PartialRes::new(res));
2344 // The method kind does not correspond to what appeared in the trait, report.
2345 let path = &self.current_trait_ref.as_ref().unwrap().1.path;
2346 let (code, kind) = match kind {
2347 AssocItemKind::Const(..) => (rustc_errors::error_code!(E0323), "const"),
2348 AssocItemKind::Fn(..) => (rustc_errors::error_code!(E0324), "method"),
2349 AssocItemKind::TyAlias(..) => (rustc_errors::error_code!(E0325), "type"),
2350 AssocItemKind::MacCall(..) => span_bug!(span, "unexpanded macro"),
2352 let trait_path = path_names_to_string(path);
2355 ResolutionError::TraitImplMismatch {
2360 trait_item_span: binding.span,
2365 fn resolve_params(&mut self, params: &'ast [Param]) {
2366 let mut bindings = smallvec![(PatBoundCtx::Product, Default::default())];
2367 for Param { pat, ty, .. } in params {
2368 self.resolve_pattern(pat, PatternSource::FnParam, &mut bindings);
2370 debug!("(resolving function / closure) recorded parameter");
2374 fn resolve_local(&mut self, local: &'ast Local) {
2375 debug!("resolving local ({:?})", local);
2376 // Resolve the type.
2377 walk_list!(self, visit_ty, &local.ty);
2379 // Resolve the initializer.
2380 if let Some((init, els)) = local.kind.init_else_opt() {
2381 self.visit_expr(init);
2383 // Resolve the `else` block
2384 if let Some(els) = els {
2385 self.visit_block(els);
2389 // Resolve the pattern.
2390 self.resolve_pattern_top(&local.pat, PatternSource::Let);
2393 /// build a map from pattern identifiers to binding-info's.
2394 /// this is done hygienically. This could arise for a macro
2395 /// that expands into an or-pattern where one 'x' was from the
2396 /// user and one 'x' came from the macro.
2397 fn binding_mode_map(&mut self, pat: &Pat) -> BindingMap {
2398 let mut binding_map = FxHashMap::default();
2400 pat.walk(&mut |pat| {
2402 PatKind::Ident(binding_mode, ident, ref sub_pat)
2403 if sub_pat.is_some() || self.is_base_res_local(pat.id) =>
2405 binding_map.insert(ident, BindingInfo { span: ident.span, binding_mode });
2407 PatKind::Or(ref ps) => {
2408 // Check the consistency of this or-pattern and
2409 // then add all bindings to the larger map.
2410 for bm in self.check_consistent_bindings(ps) {
2411 binding_map.extend(bm);
2424 fn is_base_res_local(&self, nid: NodeId) -> bool {
2425 matches!(self.r.partial_res_map.get(&nid).map(|res| res.base_res()), Some(Res::Local(..)))
2428 /// Checks that all of the arms in an or-pattern have exactly the
2429 /// same set of bindings, with the same binding modes for each.
2430 fn check_consistent_bindings(&mut self, pats: &[P<Pat>]) -> Vec<BindingMap> {
2431 let mut missing_vars = FxHashMap::default();
2432 let mut inconsistent_vars = FxHashMap::default();
2434 // 1) Compute the binding maps of all arms.
2435 let maps = pats.iter().map(|pat| self.binding_mode_map(pat)).collect::<Vec<_>>();
2437 // 2) Record any missing bindings or binding mode inconsistencies.
2438 for (map_outer, pat_outer) in pats.iter().enumerate().map(|(idx, pat)| (&maps[idx], pat)) {
2439 // Check against all arms except for the same pattern which is always self-consistent.
2443 .filter(|(_, pat)| pat.id != pat_outer.id)
2444 .flat_map(|(idx, _)| maps[idx].iter())
2445 .map(|(key, binding)| (key.name, map_outer.get(&key), binding));
2447 for (name, info, &binding_inner) in inners {
2450 // The inner binding is missing in the outer.
2452 missing_vars.entry(name).or_insert_with(|| BindingError {
2454 origin: BTreeSet::new(),
2455 target: BTreeSet::new(),
2456 could_be_path: name.as_str().starts_with(char::is_uppercase),
2458 binding_error.origin.insert(binding_inner.span);
2459 binding_error.target.insert(pat_outer.span);
2461 Some(binding_outer) => {
2462 if binding_outer.binding_mode != binding_inner.binding_mode {
2463 // The binding modes in the outer and inner bindings differ.
2466 .or_insert((binding_inner.span, binding_outer.span));
2473 // 3) Report all missing variables we found.
2474 let mut missing_vars = missing_vars.into_iter().collect::<Vec<_>>();
2475 missing_vars.sort_by_key(|&(sym, ref _err)| sym);
2477 for (name, mut v) in missing_vars.into_iter() {
2478 if inconsistent_vars.contains_key(&name) {
2479 v.could_be_path = false;
2482 *v.origin.iter().next().unwrap(),
2483 ResolutionError::VariableNotBoundInPattern(v, self.parent_scope),
2487 // 4) Report all inconsistencies in binding modes we found.
2488 let mut inconsistent_vars = inconsistent_vars.iter().collect::<Vec<_>>();
2489 inconsistent_vars.sort();
2490 for (name, v) in inconsistent_vars {
2491 self.report_error(v.0, ResolutionError::VariableBoundWithDifferentMode(*name, v.1));
2494 // 5) Finally bubble up all the binding maps.
2498 /// Check the consistency of the outermost or-patterns.
2499 fn check_consistent_bindings_top(&mut self, pat: &'ast Pat) {
2500 pat.walk(&mut |pat| match pat.kind {
2501 PatKind::Or(ref ps) => {
2502 self.check_consistent_bindings(ps);
2509 fn resolve_arm(&mut self, arm: &'ast Arm) {
2510 self.with_rib(ValueNS, NormalRibKind, |this| {
2511 this.resolve_pattern_top(&arm.pat, PatternSource::Match);
2512 walk_list!(this, visit_expr, &arm.guard);
2513 this.visit_expr(&arm.body);
2517 /// Arising from `source`, resolve a top level pattern.
2518 fn resolve_pattern_top(&mut self, pat: &'ast Pat, pat_src: PatternSource) {
2519 let mut bindings = smallvec![(PatBoundCtx::Product, Default::default())];
2520 self.resolve_pattern(pat, pat_src, &mut bindings);
2526 pat_src: PatternSource,
2527 bindings: &mut SmallVec<[(PatBoundCtx, FxHashSet<Ident>); 1]>,
2529 // We walk the pattern before declaring the pattern's inner bindings,
2530 // so that we avoid resolving a literal expression to a binding defined
2532 visit::walk_pat(self, pat);
2533 self.resolve_pattern_inner(pat, pat_src, bindings);
2534 // This has to happen *after* we determine which pat_idents are variants:
2535 self.check_consistent_bindings_top(pat);
2538 /// Resolve bindings in a pattern. This is a helper to `resolve_pattern`.
2542 /// A stack of sets of bindings accumulated.
2544 /// In each set, `PatBoundCtx::Product` denotes that a found binding in it should
2545 /// be interpreted as re-binding an already bound binding. This results in an error.
2546 /// Meanwhile, `PatBound::Or` denotes that a found binding in the set should result
2547 /// in reusing this binding rather than creating a fresh one.
2549 /// When called at the top level, the stack must have a single element
2550 /// with `PatBound::Product`. Otherwise, pushing to the stack happens as
2551 /// or-patterns (`p_0 | ... | p_n`) are encountered and the context needs
2552 /// to be switched to `PatBoundCtx::Or` and then `PatBoundCtx::Product` for each `p_i`.
2553 /// When each `p_i` has been dealt with, the top set is merged with its parent.
2554 /// When a whole or-pattern has been dealt with, the thing happens.
2556 /// See the implementation and `fresh_binding` for more details.
2557 fn resolve_pattern_inner(
2560 pat_src: PatternSource,
2561 bindings: &mut SmallVec<[(PatBoundCtx, FxHashSet<Ident>); 1]>,
2563 // Visit all direct subpatterns of this pattern.
2564 pat.walk(&mut |pat| {
2565 debug!("resolve_pattern pat={:?} node={:?}", pat, pat.kind);
2567 PatKind::Ident(bmode, ident, ref sub) => {
2568 // First try to resolve the identifier as some existing entity,
2569 // then fall back to a fresh binding.
2570 let has_sub = sub.is_some();
2572 .try_resolve_as_non_binding(pat_src, bmode, ident, has_sub)
2573 .unwrap_or_else(|| self.fresh_binding(ident, pat.id, pat_src, bindings));
2574 self.r.record_partial_res(pat.id, PartialRes::new(res));
2575 self.r.record_pat_span(pat.id, pat.span);
2577 PatKind::TupleStruct(ref qself, ref path, ref sub_patterns) => {
2578 self.smart_resolve_path(
2582 PathSource::TupleStruct(
2584 self.r.arenas.alloc_pattern_spans(sub_patterns.iter().map(|p| p.span)),
2588 PatKind::Path(ref qself, ref path) => {
2589 self.smart_resolve_path(pat.id, qself.as_ref(), path, PathSource::Pat);
2591 PatKind::Struct(ref qself, ref path, ..) => {
2592 self.smart_resolve_path(pat.id, qself.as_ref(), path, PathSource::Struct);
2594 PatKind::Or(ref ps) => {
2595 // Add a new set of bindings to the stack. `Or` here records that when a
2596 // binding already exists in this set, it should not result in an error because
2597 // `V1(a) | V2(a)` must be allowed and are checked for consistency later.
2598 bindings.push((PatBoundCtx::Or, Default::default()));
2600 // Now we need to switch back to a product context so that each
2601 // part of the or-pattern internally rejects already bound names.
2602 // For example, `V1(a) | V2(a, a)` and `V1(a, a) | V2(a)` are bad.
2603 bindings.push((PatBoundCtx::Product, Default::default()));
2604 self.resolve_pattern_inner(p, pat_src, bindings);
2605 // Move up the non-overlapping bindings to the or-pattern.
2606 // Existing bindings just get "merged".
2607 let collected = bindings.pop().unwrap().1;
2608 bindings.last_mut().unwrap().1.extend(collected);
2610 // This or-pattern itself can itself be part of a product,
2611 // e.g. `(V1(a) | V2(a), a)` or `(a, V1(a) | V2(a))`.
2612 // Both cases bind `a` again in a product pattern and must be rejected.
2613 let collected = bindings.pop().unwrap().1;
2614 bindings.last_mut().unwrap().1.extend(collected);
2616 // Prevent visiting `ps` as we've already done so above.
2629 pat_src: PatternSource,
2630 bindings: &mut SmallVec<[(PatBoundCtx, FxHashSet<Ident>); 1]>,
2632 // Add the binding to the local ribs, if it doesn't already exist in the bindings map.
2633 // (We must not add it if it's in the bindings map because that breaks the assumptions
2634 // later passes make about or-patterns.)
2635 let ident = ident.normalize_to_macro_rules();
2637 let mut bound_iter = bindings.iter().filter(|(_, set)| set.contains(&ident));
2638 // Already bound in a product pattern? e.g. `(a, a)` which is not allowed.
2639 let already_bound_and = bound_iter.clone().any(|(ctx, _)| *ctx == PatBoundCtx::Product);
2640 // Already bound in an or-pattern? e.g. `V1(a) | V2(a)`.
2641 // This is *required* for consistency which is checked later.
2642 let already_bound_or = bound_iter.any(|(ctx, _)| *ctx == PatBoundCtx::Or);
2644 if already_bound_and {
2645 // Overlap in a product pattern somewhere; report an error.
2646 use ResolutionError::*;
2647 let error = match pat_src {
2648 // `fn f(a: u8, a: u8)`:
2649 PatternSource::FnParam => IdentifierBoundMoreThanOnceInParameterList,
2651 _ => IdentifierBoundMoreThanOnceInSamePattern,
2653 self.report_error(ident.span, error(ident.name));
2656 // Record as bound if it's valid:
2657 let ident_valid = ident.name != kw::Empty;
2659 bindings.last_mut().unwrap().1.insert(ident);
2662 if already_bound_or {
2663 // `Variant1(a) | Variant2(a)`, ok
2664 // Reuse definition from the first `a`.
2665 self.innermost_rib_bindings(ValueNS)[&ident]
2667 let res = Res::Local(pat_id);
2669 // A completely fresh binding add to the set if it's valid.
2670 self.innermost_rib_bindings(ValueNS).insert(ident, res);
2676 fn innermost_rib_bindings(&mut self, ns: Namespace) -> &mut IdentMap<Res> {
2677 &mut self.ribs[ns].last_mut().unwrap().bindings
2680 fn try_resolve_as_non_binding(
2682 pat_src: PatternSource,
2687 // An immutable (no `mut`) by-value (no `ref`) binding pattern without
2688 // a sub pattern (no `@ $pat`) is syntactically ambiguous as it could
2689 // also be interpreted as a path to e.g. a constant, variant, etc.
2690 let is_syntactic_ambiguity = !has_sub && bm == BindingMode::ByValue(Mutability::Not);
2692 let ls_binding = self.maybe_resolve_ident_in_lexical_scope(ident, ValueNS)?;
2693 let (res, binding) = match ls_binding {
2694 LexicalScopeBinding::Item(binding)
2695 if is_syntactic_ambiguity && binding.is_ambiguity() =>
2697 // For ambiguous bindings we don't know all their definitions and cannot check
2698 // whether they can be shadowed by fresh bindings or not, so force an error.
2699 // issues/33118#issuecomment-233962221 (see below) still applies here,
2700 // but we have to ignore it for backward compatibility.
2701 self.r.record_use(ident, binding, false);
2704 LexicalScopeBinding::Item(binding) => (binding.res(), Some(binding)),
2705 LexicalScopeBinding::Res(res) => (res, None),
2709 Res::SelfCtor(_) // See #70549.
2711 DefKind::Ctor(_, CtorKind::Const) | DefKind::Const | DefKind::ConstParam,
2713 ) if is_syntactic_ambiguity => {
2714 // Disambiguate in favor of a unit struct/variant or constant pattern.
2715 if let Some(binding) = binding {
2716 self.r.record_use(ident, binding, false);
2720 Res::Def(DefKind::Ctor(..) | DefKind::Const | DefKind::Static(_), _) => {
2721 // This is unambiguously a fresh binding, either syntactically
2722 // (e.g., `IDENT @ PAT` or `ref IDENT`) or because `IDENT` resolves
2723 // to something unusable as a pattern (e.g., constructor function),
2724 // but we still conservatively report an error, see
2725 // issues/33118#issuecomment-233962221 for one reason why.
2726 let binding = binding.expect("no binding for a ctor or static");
2729 ResolutionError::BindingShadowsSomethingUnacceptable {
2730 shadowing_binding_descr: pat_src.descr(),
2732 participle: if binding.is_import() { "imported" } else { "defined" },
2733 article: binding.res().article(),
2734 shadowed_binding_descr: binding.res().descr(),
2735 shadowed_binding_span: binding.span,
2740 Res::Def(DefKind::ConstParam, def_id) => {
2741 // Same as for DefKind::Const above, but here, `binding` is `None`, so we
2742 // have to construct the error differently
2745 ResolutionError::BindingShadowsSomethingUnacceptable {
2746 shadowing_binding_descr: pat_src.descr(),
2748 participle: "defined",
2749 article: res.article(),
2750 shadowed_binding_descr: res.descr(),
2751 shadowed_binding_span: self.r.opt_span(def_id).expect("const parameter defined outside of local crate"),
2756 Res::Def(DefKind::Fn, _) | Res::Local(..) | Res::Err => {
2757 // These entities are explicitly allowed to be shadowed by fresh bindings.
2760 Res::SelfCtor(_) => {
2761 // We resolve `Self` in pattern position as an ident sometimes during recovery,
2762 // so delay a bug instead of ICEing.
2763 self.r.session.delay_span_bug(
2765 "unexpected `SelfCtor` in pattern, expected identifier"
2771 "unexpected resolution for an identifier in pattern: {:?}",
2777 // High-level and context dependent path resolution routine.
2778 // Resolves the path and records the resolution into definition map.
2779 // If resolution fails tries several techniques to find likely
2780 // resolution candidates, suggest imports or other help, and report
2781 // errors in user friendly way.
2782 fn smart_resolve_path(
2785 qself: Option<&QSelf>,
2787 source: PathSource<'ast>,
2789 self.smart_resolve_path_fragment(
2791 &Segment::from_path(path),
2793 Finalize::new(id, path.span),
2797 fn smart_resolve_path_fragment(
2799 qself: Option<&QSelf>,
2801 source: PathSource<'ast>,
2805 "smart_resolve_path_fragment(qself={:?}, path={:?}, finalize={:?})",
2810 let ns = source.namespace();
2812 let Finalize { node_id, path_span, .. } = finalize;
2813 let report_errors = |this: &mut Self, res: Option<Res>| {
2814 if this.should_report_errs() {
2815 let (err, candidates) =
2816 this.smart_resolve_report_errors(path, path_span, source, res);
2818 let def_id = this.parent_scope.module.nearest_parent_mod();
2819 let instead = res.is_some();
2821 if res.is_none() { this.report_missing_type_error(path) } else { None };
2823 this.r.use_injections.push(UseError {
2833 PartialRes::new(Res::Err)
2836 // For paths originating from calls (like in `HashMap::new()`), tries
2837 // to enrich the plain `failed to resolve: ...` message with hints
2838 // about possible missing imports.
2840 // Similar thing, for types, happens in `report_errors` above.
2841 let report_errors_for_call = |this: &mut Self, parent_err: Spanned<ResolutionError<'a>>| {
2842 if !source.is_call() {
2843 return Some(parent_err);
2846 // Before we start looking for candidates, we have to get our hands
2847 // on the type user is trying to perform invocation on; basically:
2848 // we're transforming `HashMap::new` into just `HashMap`.
2849 let path = match path.split_last() {
2850 Some((_, path)) if !path.is_empty() => path,
2851 _ => return Some(parent_err),
2854 let (mut err, candidates) =
2855 this.smart_resolve_report_errors(path, path_span, PathSource::Type, None);
2857 if candidates.is_empty() {
2859 return Some(parent_err);
2862 // There are two different error messages user might receive at
2864 // - E0412 cannot find type `{}` in this scope
2865 // - E0433 failed to resolve: use of undeclared type or module `{}`
2867 // The first one is emitted for paths in type-position, and the
2868 // latter one - for paths in expression-position.
2870 // Thus (since we're in expression-position at this point), not to
2871 // confuse the user, we want to keep the *message* from E0432 (so
2872 // `parent_err`), but we want *hints* from E0412 (so `err`).
2874 // And that's what happens below - we're just mixing both messages
2875 // into a single one.
2876 let mut parent_err = this.r.into_struct_error(parent_err.span, parent_err.node);
2878 err.message = take(&mut parent_err.message);
2879 err.code = take(&mut parent_err.code);
2880 err.children = take(&mut parent_err.children);
2882 parent_err.cancel();
2884 let def_id = this.parent_scope.module.nearest_parent_mod();
2886 if this.should_report_errs() {
2887 this.r.use_injections.push(UseError {
2899 // We don't return `Some(parent_err)` here, because the error will
2900 // be already printed as part of the `use` injections
2904 let partial_res = match self.resolve_qpath_anywhere(
2909 source.defer_to_typeck(),
2912 Ok(Some(partial_res)) if partial_res.unresolved_segments() == 0 => {
2913 if source.is_expected(partial_res.base_res()) || partial_res.base_res() == Res::Err
2917 report_errors(self, Some(partial_res.base_res()))
2921 Ok(Some(partial_res)) if source.defer_to_typeck() => {
2922 // Not fully resolved associated item `T::A::B` or `<T as Tr>::A::B`
2923 // or `<T>::A::B`. If `B` should be resolved in value namespace then
2924 // it needs to be added to the trait map.
2926 let item_name = path.last().unwrap().ident;
2927 let traits = self.traits_in_scope(item_name, ns);
2928 self.r.trait_map.insert(node_id, traits);
2931 if PrimTy::from_name(path[0].ident.name).is_some() {
2932 let mut std_path = Vec::with_capacity(1 + path.len());
2934 std_path.push(Segment::from_ident(Ident::with_dummy_span(sym::std)));
2935 std_path.extend(path);
2936 if let PathResult::Module(_) | PathResult::NonModule(_) =
2937 self.resolve_path(&std_path, Some(ns), None)
2939 // Check if we wrote `str::from_utf8` instead of `std::str::from_utf8`
2941 path.iter().last().map_or(path_span, |segment| segment.ident.span);
2943 self.r.confused_type_with_std_module.insert(item_span, path_span);
2944 self.r.confused_type_with_std_module.insert(path_span, path_span);
2952 if let Some(err) = report_errors_for_call(self, err) {
2953 self.report_error(err.span, err.node);
2956 PartialRes::new(Res::Err)
2959 _ => report_errors(self, None),
2962 if !matches!(source, PathSource::TraitItem(..)) {
2963 // Avoid recording definition of `A::B` in `<T as A>::B::C`.
2964 self.r.record_partial_res(node_id, partial_res);
2965 self.resolve_elided_lifetimes_in_path(node_id, partial_res, path, source, path_span);
2971 fn self_type_is_available(&mut self) -> bool {
2973 .maybe_resolve_ident_in_lexical_scope(Ident::with_dummy_span(kw::SelfUpper), TypeNS);
2974 if let Some(LexicalScopeBinding::Res(res)) = binding { res != Res::Err } else { false }
2977 fn self_value_is_available(&mut self, self_span: Span) -> bool {
2978 let ident = Ident::new(kw::SelfLower, self_span);
2979 let binding = self.maybe_resolve_ident_in_lexical_scope(ident, ValueNS);
2980 if let Some(LexicalScopeBinding::Res(res)) = binding { res != Res::Err } else { false }
2983 /// A wrapper around [`Resolver::report_error`].
2985 /// This doesn't emit errors for function bodies if this is rustdoc.
2986 fn report_error(&mut self, span: Span, resolution_error: ResolutionError<'a>) {
2987 if self.should_report_errs() {
2988 self.r.report_error(span, resolution_error);
2993 /// If we're actually rustdoc then avoid giving a name resolution error for `cfg()` items.
2994 fn should_report_errs(&self) -> bool {
2995 !(self.r.session.opts.actually_rustdoc && self.in_func_body)
2998 // Resolve in alternative namespaces if resolution in the primary namespace fails.
2999 fn resolve_qpath_anywhere(
3001 qself: Option<&QSelf>,
3003 primary_ns: Namespace,
3005 defer_to_typeck: bool,
3007 ) -> Result<Option<PartialRes>, Spanned<ResolutionError<'a>>> {
3008 let mut fin_res = None;
3010 for (i, &ns) in [primary_ns, TypeNS, ValueNS].iter().enumerate() {
3011 if i == 0 || ns != primary_ns {
3012 match self.resolve_qpath(qself, path, ns, finalize)? {
3014 if partial_res.unresolved_segments() == 0 || defer_to_typeck =>
3016 return Ok(Some(partial_res));
3019 if fin_res.is_none() {
3020 fin_res = partial_res;
3027 assert!(primary_ns != MacroNS);
3029 if qself.is_none() {
3030 let path_seg = |seg: &Segment| PathSegment::from_ident(seg.ident);
3031 let path = Path { segments: path.iter().map(path_seg).collect(), span, tokens: None };
3032 if let Ok((_, res)) =
3033 self.r.resolve_macro_path(&path, None, &self.parent_scope, false, false)
3035 return Ok(Some(PartialRes::new(res)));
3042 /// Handles paths that may refer to associated items.
3045 qself: Option<&QSelf>,
3049 ) -> Result<Option<PartialRes>, Spanned<ResolutionError<'a>>> {
3051 "resolve_qpath(qself={:?}, path={:?}, ns={:?}, finalize={:?})",
3052 qself, path, ns, finalize,
3055 if let Some(qself) = qself {
3056 if qself.position == 0 {
3057 // This is a case like `<T>::B`, where there is no
3058 // trait to resolve. In that case, we leave the `B`
3059 // segment to be resolved by type-check.
3060 return Ok(Some(PartialRes::with_unresolved_segments(
3061 Res::Def(DefKind::Mod, CRATE_DEF_ID.to_def_id()),
3066 // Make sure `A::B` in `<T as A::B>::C` is a trait item.
3068 // Currently, `path` names the full item (`A::B::C`, in
3069 // our example). so we extract the prefix of that that is
3070 // the trait (the slice upto and including
3071 // `qself.position`). And then we recursively resolve that,
3072 // but with `qself` set to `None`.
3073 let ns = if qself.position + 1 == path.len() { ns } else { TypeNS };
3074 let partial_res = self.smart_resolve_path_fragment(
3076 &path[..=qself.position],
3077 PathSource::TraitItem(ns),
3078 Finalize::with_root_span(finalize.node_id, finalize.path_span, qself.path_span),
3081 // The remaining segments (the `C` in our example) will
3082 // have to be resolved by type-check, since that requires doing
3083 // trait resolution.
3084 return Ok(Some(PartialRes::with_unresolved_segments(
3085 partial_res.base_res(),
3086 partial_res.unresolved_segments() + path.len() - qself.position - 1,
3090 let result = match self.resolve_path(&path, Some(ns), Some(finalize)) {
3091 PathResult::NonModule(path_res) => path_res,
3092 PathResult::Module(ModuleOrUniformRoot::Module(module)) if !module.is_normal() => {
3093 PartialRes::new(module.res().unwrap())
3095 // In `a(::assoc_item)*` `a` cannot be a module. If `a` does resolve to a module we
3096 // don't report an error right away, but try to fallback to a primitive type.
3097 // So, we are still able to successfully resolve something like
3099 // use std::u8; // bring module u8 in scope
3100 // fn f() -> u8 { // OK, resolves to primitive u8, not to std::u8
3101 // u8::max_value() // OK, resolves to associated function <u8>::max_value,
3102 // // not to non-existent std::u8::max_value
3105 // Such behavior is required for backward compatibility.
3106 // The same fallback is used when `a` resolves to nothing.
3107 PathResult::Module(ModuleOrUniformRoot::Module(_)) | PathResult::Failed { .. }
3108 if (ns == TypeNS || path.len() > 1)
3109 && PrimTy::from_name(path[0].ident.name).is_some() =>
3111 let prim = PrimTy::from_name(path[0].ident.name).unwrap();
3112 PartialRes::with_unresolved_segments(Res::PrimTy(prim), path.len() - 1)
3114 PathResult::Module(ModuleOrUniformRoot::Module(module)) => {
3115 PartialRes::new(module.res().unwrap())
3117 PathResult::Failed { is_error_from_last_segment: false, span, label, suggestion } => {
3118 return Err(respan(span, ResolutionError::FailedToResolve { label, suggestion }));
3120 PathResult::Module(..) | PathResult::Failed { .. } => return Ok(None),
3121 PathResult::Indeterminate => bug!("indeterminate path result in resolve_qpath"),
3125 && result.base_res() != Res::Err
3126 && path[0].ident.name != kw::PathRoot
3127 && path[0].ident.name != kw::DollarCrate
3129 let unqualified_result = {
3130 match self.resolve_path(&[*path.last().unwrap()], Some(ns), None) {
3131 PathResult::NonModule(path_res) => path_res.base_res(),
3132 PathResult::Module(ModuleOrUniformRoot::Module(module)) => {
3133 module.res().unwrap()
3135 _ => return Ok(Some(result)),
3138 if result.base_res() == unqualified_result {
3139 let lint = lint::builtin::UNUSED_QUALIFICATIONS;
3140 self.r.lint_buffer.buffer_lint(
3144 "unnecessary qualification",
3152 fn with_resolved_label(&mut self, label: Option<Label>, id: NodeId, f: impl FnOnce(&mut Self)) {
3153 if let Some(label) = label {
3154 if label.ident.as_str().as_bytes()[1] != b'_' {
3155 self.diagnostic_metadata.unused_labels.insert(id, label.ident.span);
3158 // Forbid shadowing lifetime bindings
3159 let ident = label.ident.normalize_to_macro_rules();
3160 for rib in self.lifetime_ribs.iter().rev() {
3161 if let Some((orig_ident, _)) = rib.bindings.get_key_value(&ident) {
3162 diagnostics::signal_shadowing_problem(
3165 original_lifetime(orig_ident.span),
3166 shadower_label(label.ident.span),
3170 for rib in self.label_ribs.iter_mut().rev() {
3171 if let Some((orig_ident, _)) = rib.bindings.get_key_value(&ident) {
3172 diagnostics::signal_shadowing_problem(
3175 original_label(orig_ident.span),
3176 shadower_label(label.ident.span),
3179 if rib.kind.is_label_barrier() {
3180 rib.bindings.insert(ident, id);
3185 self.with_label_rib(NormalRibKind, |this| {
3186 this.label_ribs.last_mut().unwrap().bindings.insert(ident, id);
3194 fn resolve_labeled_block(&mut self, label: Option<Label>, id: NodeId, block: &'ast Block) {
3195 self.with_resolved_label(label, id, |this| this.visit_block(block));
3198 fn resolve_block(&mut self, block: &'ast Block) {
3199 debug!("(resolving block) entering block");
3200 // Move down in the graph, if there's an anonymous module rooted here.
3201 let orig_module = self.parent_scope.module;
3202 let anonymous_module = self.r.block_map.get(&block.id).cloned(); // clones a reference
3204 let mut num_macro_definition_ribs = 0;
3205 if let Some(anonymous_module) = anonymous_module {
3206 debug!("(resolving block) found anonymous module, moving down");
3207 self.ribs[ValueNS].push(Rib::new(ModuleRibKind(anonymous_module)));
3208 self.ribs[TypeNS].push(Rib::new(ModuleRibKind(anonymous_module)));
3209 self.parent_scope.module = anonymous_module;
3211 self.ribs[ValueNS].push(Rib::new(NormalRibKind));
3214 let prev = self.diagnostic_metadata.current_block_could_be_bare_struct_literal.take();
3215 if let (true, [Stmt { kind: StmtKind::Expr(expr), .. }]) =
3216 (block.could_be_bare_literal, &block.stmts[..])
3217 && let ExprKind::Type(..) = expr.kind
3219 self.diagnostic_metadata.current_block_could_be_bare_struct_literal =
3222 // Descend into the block.
3223 for stmt in &block.stmts {
3224 if let StmtKind::Item(ref item) = stmt.kind
3225 && let ItemKind::MacroDef(..) = item.kind {
3226 num_macro_definition_ribs += 1;
3227 let res = self.r.local_def_id(item.id).to_def_id();
3228 self.ribs[ValueNS].push(Rib::new(MacroDefinition(res)));
3229 self.label_ribs.push(Rib::new(MacroDefinition(res)));
3232 self.visit_stmt(stmt);
3234 self.diagnostic_metadata.current_block_could_be_bare_struct_literal = prev;
3237 self.parent_scope.module = orig_module;
3238 for _ in 0..num_macro_definition_ribs {
3239 self.ribs[ValueNS].pop();
3240 self.label_ribs.pop();
3242 self.ribs[ValueNS].pop();
3243 if anonymous_module.is_some() {
3244 self.ribs[TypeNS].pop();
3246 debug!("(resolving block) leaving block");
3249 fn resolve_anon_const(&mut self, constant: &'ast AnonConst, is_repeat: IsRepeatExpr) {
3250 debug!("resolve_anon_const {:?} is_repeat: {:?}", constant, is_repeat);
3251 self.with_constant_rib(
3253 if constant.value.is_potential_trivial_const_param() {
3254 HasGenericParams::Yes
3256 HasGenericParams::No
3259 |this| visit::walk_anon_const(this, constant),
3263 fn resolve_inline_const(&mut self, constant: &'ast AnonConst) {
3264 debug!("resolve_anon_const {constant:?}");
3265 self.with_constant_rib(IsRepeatExpr::No, HasGenericParams::Yes, None, |this| {
3266 visit::walk_anon_const(this, constant);
3270 fn resolve_expr(&mut self, expr: &'ast Expr, parent: Option<&'ast Expr>) {
3271 // First, record candidate traits for this expression if it could
3272 // result in the invocation of a method call.
3274 self.record_candidate_traits_for_expr_if_necessary(expr);
3276 // Next, resolve the node.
3278 ExprKind::Path(ref qself, ref path) => {
3279 self.smart_resolve_path(expr.id, qself.as_ref(), path, PathSource::Expr(parent));
3280 visit::walk_expr(self, expr);
3283 ExprKind::Struct(ref se) => {
3284 self.smart_resolve_path(expr.id, se.qself.as_ref(), &se.path, PathSource::Struct);
3285 visit::walk_expr(self, expr);
3288 ExprKind::Break(Some(label), _) | ExprKind::Continue(Some(label)) => {
3289 if let Some(node_id) = self.resolve_label(label.ident) {
3290 // Since this res is a label, it is never read.
3291 self.r.label_res_map.insert(expr.id, node_id);
3292 self.diagnostic_metadata.unused_labels.remove(&node_id);
3295 // visit `break` argument if any
3296 visit::walk_expr(self, expr);
3299 ExprKind::Break(None, Some(ref e)) => {
3300 // We use this instead of `visit::walk_expr` to keep the parent expr around for
3301 // better diagnostics.
3302 self.resolve_expr(e, Some(&expr));
3305 ExprKind::Let(ref pat, ref scrutinee, _) => {
3306 self.visit_expr(scrutinee);
3307 self.resolve_pattern_top(pat, PatternSource::Let);
3310 ExprKind::If(ref cond, ref then, ref opt_else) => {
3311 self.with_rib(ValueNS, NormalRibKind, |this| {
3312 let old = this.diagnostic_metadata.in_if_condition.replace(cond);
3313 this.visit_expr(cond);
3314 this.diagnostic_metadata.in_if_condition = old;
3315 this.visit_block(then);
3317 if let Some(expr) = opt_else {
3318 self.visit_expr(expr);
3322 ExprKind::Loop(ref block, label) => self.resolve_labeled_block(label, expr.id, &block),
3324 ExprKind::While(ref cond, ref block, label) => {
3325 self.with_resolved_label(label, expr.id, |this| {
3326 this.with_rib(ValueNS, NormalRibKind, |this| {
3327 let old = this.diagnostic_metadata.in_if_condition.replace(cond);
3328 this.visit_expr(cond);
3329 this.diagnostic_metadata.in_if_condition = old;
3330 this.visit_block(block);
3335 ExprKind::ForLoop(ref pat, ref iter_expr, ref block, label) => {
3336 self.visit_expr(iter_expr);
3337 self.with_rib(ValueNS, NormalRibKind, |this| {
3338 this.resolve_pattern_top(pat, PatternSource::For);
3339 this.resolve_labeled_block(label, expr.id, block);
3343 ExprKind::Block(ref block, label) => self.resolve_labeled_block(label, block.id, block),
3345 // Equivalent to `visit::walk_expr` + passing some context to children.
3346 ExprKind::Field(ref subexpression, _) => {
3347 self.resolve_expr(subexpression, Some(expr));
3349 ExprKind::MethodCall(ref segment, ref arguments, _) => {
3350 let mut arguments = arguments.iter();
3351 self.resolve_expr(arguments.next().unwrap(), Some(expr));
3352 for argument in arguments {
3353 self.resolve_expr(argument, None);
3355 self.visit_path_segment(expr.span, segment);
3358 ExprKind::Call(ref callee, ref arguments) => {
3359 self.resolve_expr(callee, Some(expr));
3360 let const_args = self.r.legacy_const_generic_args(callee).unwrap_or_default();
3361 for (idx, argument) in arguments.iter().enumerate() {
3362 // Constant arguments need to be treated as AnonConst since
3363 // that is how they will be later lowered to HIR.
3364 if const_args.contains(&idx) {
3365 self.with_constant_rib(
3367 if argument.is_potential_trivial_const_param() {
3368 HasGenericParams::Yes
3370 HasGenericParams::No
3374 this.resolve_expr(argument, None);
3378 self.resolve_expr(argument, None);
3382 ExprKind::Type(ref type_expr, ref ty) => {
3383 // `ParseSess::type_ascription_path_suggestions` keeps spans of colon tokens in
3384 // type ascription. Here we are trying to retrieve the span of the colon token as
3385 // well, but only if it's written without spaces `expr:Ty` and therefore confusable
3386 // with `expr::Ty`, only in this case it will match the span from
3387 // `type_ascription_path_suggestions`.
3388 self.diagnostic_metadata
3389 .current_type_ascription
3390 .push(type_expr.span.between(ty.span));
3391 visit::walk_expr(self, expr);
3392 self.diagnostic_metadata.current_type_ascription.pop();
3394 // `async |x| ...` gets desugared to `|x| future_from_generator(|| ...)`, so we need to
3395 // resolve the arguments within the proper scopes so that usages of them inside the
3396 // closure are detected as upvars rather than normal closure arg usages.
3397 ExprKind::Closure(_, Async::Yes { .. }, _, ref fn_decl, ref body, _span) => {
3398 self.with_rib(ValueNS, NormalRibKind, |this| {
3399 this.with_label_rib(ClosureOrAsyncRibKind, |this| {
3400 // Resolve arguments:
3401 this.resolve_params(&fn_decl.inputs);
3402 // No need to resolve return type --
3403 // the outer closure return type is `FnRetTy::Default`.
3405 // Now resolve the inner closure
3407 // No need to resolve arguments: the inner closure has none.
3408 // Resolve the return type:
3409 visit::walk_fn_ret_ty(this, &fn_decl.output);
3411 this.visit_expr(body);
3416 ExprKind::Async(..) | ExprKind::Closure(..) => {
3417 self.with_label_rib(ClosureOrAsyncRibKind, |this| visit::walk_expr(this, expr));
3419 ExprKind::Repeat(ref elem, ref ct) => {
3420 self.visit_expr(elem);
3421 self.with_lifetime_rib(LifetimeRibKind::AnonConst, |this| {
3422 this.resolve_anon_const(ct, IsRepeatExpr::Yes)
3425 ExprKind::ConstBlock(ref ct) => {
3426 self.resolve_inline_const(ct);
3428 ExprKind::Index(ref elem, ref idx) => {
3429 self.resolve_expr(elem, Some(expr));
3430 self.visit_expr(idx);
3433 visit::walk_expr(self, expr);
3438 fn record_candidate_traits_for_expr_if_necessary(&mut self, expr: &'ast Expr) {
3440 ExprKind::Field(_, ident) => {
3441 // FIXME(#6890): Even though you can't treat a method like a
3442 // field, we need to add any trait methods we find that match
3443 // the field name so that we can do some nice error reporting
3444 // later on in typeck.
3445 let traits = self.traits_in_scope(ident, ValueNS);
3446 self.r.trait_map.insert(expr.id, traits);
3448 ExprKind::MethodCall(ref segment, ..) => {
3449 debug!("(recording candidate traits for expr) recording traits for {}", expr.id);
3450 let traits = self.traits_in_scope(segment.ident, ValueNS);
3451 self.r.trait_map.insert(expr.id, traits);
3459 fn traits_in_scope(&mut self, ident: Ident, ns: Namespace) -> Vec<TraitCandidate> {
3460 self.r.traits_in_scope(
3461 self.current_trait_ref.as_ref().map(|(module, _)| *module),
3464 Some((ident.name, ns)),
3469 struct LifetimeCountVisitor<'a, 'b> {
3470 r: &'b mut Resolver<'a>,
3473 /// Walks the whole crate in DFS order, visiting each item, counting the declared number of
3474 /// lifetime generic parameters.
3475 impl<'ast> Visitor<'ast> for LifetimeCountVisitor<'_, '_> {
3476 fn visit_item(&mut self, item: &'ast Item) {
3478 ItemKind::TyAlias(box TyAlias { ref generics, .. })
3479 | ItemKind::Fn(box Fn { ref generics, .. })
3480 | ItemKind::Enum(_, ref generics)
3481 | ItemKind::Struct(_, ref generics)
3482 | ItemKind::Union(_, ref generics)
3483 | ItemKind::Impl(box Impl { ref generics, .. })
3484 | ItemKind::Trait(box Trait { ref generics, .. })
3485 | ItemKind::TraitAlias(ref generics, _) => {
3486 let def_id = self.r.local_def_id(item.id);
3487 let count = generics
3490 .filter(|param| matches!(param.kind, ast::GenericParamKind::Lifetime { .. }))
3492 self.r.item_generics_num_lifetimes.insert(def_id, count);
3496 | ItemKind::ForeignMod(..)
3497 | ItemKind::Static(..)
3498 | ItemKind::Const(..)
3500 | ItemKind::ExternCrate(..)
3501 | ItemKind::MacroDef(..)
3502 | ItemKind::GlobalAsm(..)
3503 | ItemKind::MacCall(..) => {}
3505 visit::walk_item(self, item)
3509 impl<'a> Resolver<'a> {
3510 pub(crate) fn late_resolve_crate(&mut self, krate: &Crate) {
3511 visit::walk_crate(&mut LifetimeCountVisitor { r: self }, krate);
3512 let mut late_resolution_visitor = LateResolutionVisitor::new(self);
3513 visit::walk_crate(&mut late_resolution_visitor, krate);
3514 for (id, span) in late_resolution_visitor.diagnostic_metadata.unused_labels.iter() {
3515 self.lint_buffer.buffer_lint(lint::builtin::UNUSED_LABELS, *id, *span, "unused label");