1 //! "Late resolution" is the pass that resolves most of names in a crate beside imports and macros.
2 //! It runs when the crate is fully expanded and its module structure is fully built.
3 //! So it just walks through the crate and resolves all the expressions, types, etc.
5 //! If you wonder why there's no `early.rs`, that's because it's split into three files -
6 //! `build_reduced_graph.rs`, `macros.rs` and `imports.rs`.
10 use crate::{path_names_to_string, BindingError, CrateLint, LexicalScopeBinding};
11 use crate::{Module, ModuleOrUniformRoot, ParentScope, PathResult};
12 use crate::{ResolutionError, Resolver, Segment, UseError};
14 use rustc_ast::ptr::P;
15 use rustc_ast::visit::{self, AssocCtxt, FnCtxt, FnKind, Visitor};
17 use rustc_ast_lowering::ResolverAstLowering;
18 use rustc_data_structures::fx::{FxHashMap, FxHashSet};
19 use rustc_errors::DiagnosticId;
20 use rustc_hir::def::Namespace::{self, *};
21 use rustc_hir::def::{self, CtorKind, DefKind, PartialRes, PerNS};
22 use rustc_hir::def_id::{DefId, CRATE_DEF_INDEX};
23 use rustc_hir::{PrimTy, TraitCandidate};
24 use rustc_middle::{bug, span_bug};
25 use rustc_session::lint;
26 use rustc_span::symbol::{kw, sym, Ident, Symbol};
28 use smallvec::{smallvec, SmallVec};
30 use rustc_span::source_map::{respan, Spanned};
31 use std::collections::{hash_map::Entry, BTreeSet};
32 use std::mem::{replace, take};
38 type Res = def::Res<NodeId>;
40 type IdentMap<T> = FxHashMap<Ident, T>;
42 /// Map from the name in a pattern to its binding mode.
43 type BindingMap = IdentMap<BindingInfo>;
45 #[derive(Copy, Clone, Debug)]
48 binding_mode: BindingMode,
51 #[derive(Copy, Clone, PartialEq, Eq, Debug)]
59 #[derive(Copy, Clone, Debug, PartialEq, Eq)]
66 fn descr(self) -> &'static str {
68 PatternSource::Match => "match binding",
69 PatternSource::Let => "let binding",
70 PatternSource::For => "for binding",
71 PatternSource::FnParam => "function parameter",
76 /// Denotes whether the context for the set of already bound bindings is a `Product`
77 /// or `Or` context. This is used in e.g., `fresh_binding` and `resolve_pattern_inner`.
78 /// See those functions for more information.
81 /// A product pattern context, e.g., `Variant(a, b)`.
83 /// An or-pattern context, e.g., `p_0 | ... | p_n`.
87 /// Does this the item (from the item rib scope) allow generic parameters?
88 #[derive(Copy, Clone, Debug, Eq, PartialEq)]
89 crate enum HasGenericParams {
94 #[derive(Copy, Clone, Debug, Eq, PartialEq)]
95 crate enum ConstantItemKind {
100 /// The rib kind restricts certain accesses,
101 /// e.g. to a `Res::Local` of an outer item.
102 #[derive(Copy, Clone, Debug)]
103 crate enum RibKind<'a> {
104 /// No restriction needs to be applied.
107 /// We passed through an impl or trait and are now in one of its
108 /// methods or associated types. Allow references to ty params that impl or trait
109 /// binds. Disallow any other upvars (including other ty params that are
113 /// We passed through a closure. Disallow labels.
114 ClosureOrAsyncRibKind,
116 /// We passed through a function definition. Disallow upvars.
117 /// Permit only those const parameters that are specified in the function's generics.
120 /// We passed through an item scope. Disallow upvars.
121 ItemRibKind(HasGenericParams),
123 /// We're in a constant item. Can't refer to dynamic stuff.
125 /// The `bool` indicates if this constant may reference generic parameters
126 /// and is used to only allow generic parameters to be used in trivial constant expressions.
127 ConstantItemRibKind(bool, Option<(Ident, ConstantItemKind)>),
129 /// We passed through a module.
130 ModuleRibKind(Module<'a>),
132 /// We passed through a `macro_rules!` statement
133 MacroDefinition(DefId),
135 /// All bindings in this rib are generic parameters that can't be used
136 /// from the default of a generic parameter because they're not declared
137 /// before said generic parameter. Also see the `visit_generics` override.
138 ForwardGenericParamBanRibKind,
140 /// We are inside of the type of a const parameter. Can't refer to any
146 /// Whether this rib kind contains generic parameters, as opposed to local
148 crate fn contains_params(&self) -> bool {
151 | ClosureOrAsyncRibKind
153 | ConstantItemRibKind(..)
156 | ConstParamTyRibKind => false,
157 AssocItemRibKind | ItemRibKind(_) | ForwardGenericParamBanRibKind => true,
162 /// A single local scope.
164 /// A rib represents a scope names can live in. Note that these appear in many places, not just
165 /// around braces. At any place where the list of accessible names (of the given namespace)
166 /// changes or a new restrictions on the name accessibility are introduced, a new rib is put onto a
167 /// stack. This may be, for example, a `let` statement (because it introduces variables), a macro,
170 /// Different [rib kinds](enum.RibKind) are transparent for different names.
172 /// The resolution keeps a separate stack of ribs as it traverses the AST for each namespace. When
173 /// resolving, the name is looked up from inside out.
175 crate struct Rib<'a, R = Res> {
176 pub bindings: IdentMap<R>,
177 pub kind: RibKind<'a>,
180 impl<'a, R> Rib<'a, R> {
181 fn new(kind: RibKind<'a>) -> Rib<'a, R> {
182 Rib { bindings: Default::default(), kind }
186 #[derive(Copy, Clone, PartialEq, Eq, Debug)]
187 crate enum AliasPossibility {
192 #[derive(Copy, Clone, Debug)]
193 crate enum PathSource<'a> {
194 // Type paths `Path`.
196 // Trait paths in bounds or impls.
197 Trait(AliasPossibility),
198 // Expression paths `path`, with optional parent context.
199 Expr(Option<&'a Expr>),
200 // Paths in path patterns `Path`.
202 // Paths in struct expressions and patterns `Path { .. }`.
204 // Paths in tuple struct patterns `Path(..)`.
205 TupleStruct(Span, &'a [Span]),
206 // `m::A::B` in `<T as m::A>::B::C`.
207 TraitItem(Namespace),
210 impl<'a> PathSource<'a> {
211 fn namespace(self) -> Namespace {
213 PathSource::Type | PathSource::Trait(_) | PathSource::Struct => TypeNS,
214 PathSource::Expr(..) | PathSource::Pat | PathSource::TupleStruct(..) => ValueNS,
215 PathSource::TraitItem(ns) => ns,
219 fn defer_to_typeck(self) -> bool {
222 | PathSource::Expr(..)
225 | PathSource::TupleStruct(..) => true,
226 PathSource::Trait(_) | PathSource::TraitItem(..) => false,
230 fn descr_expected(self) -> &'static str {
232 PathSource::Type => "type",
233 PathSource::Trait(_) => "trait",
234 PathSource::Pat => "unit struct, unit variant or constant",
235 PathSource::Struct => "struct, variant or union type",
236 PathSource::TupleStruct(..) => "tuple struct or tuple variant",
237 PathSource::TraitItem(ns) => match ns {
238 TypeNS => "associated type",
239 ValueNS => "method or associated constant",
240 MacroNS => bug!("associated macro"),
242 PathSource::Expr(parent) => match parent.as_ref().map(|p| &p.kind) {
243 // "function" here means "anything callable" rather than `DefKind::Fn`,
244 // this is not precise but usually more helpful than just "value".
245 Some(ExprKind::Call(call_expr, _)) => match &call_expr.kind {
246 // the case of `::some_crate()`
247 ExprKind::Path(_, path)
248 if path.segments.len() == 2
249 && path.segments[0].ident.name == kw::PathRoot =>
253 ExprKind::Path(_, path) => {
254 let mut msg = "function";
255 if let Some(segment) = path.segments.iter().last() {
256 if let Some(c) = segment.ident.to_string().chars().next() {
257 if c.is_uppercase() {
258 msg = "function, tuple struct or tuple variant";
271 fn is_call(self) -> bool {
272 matches!(self, PathSource::Expr(Some(&Expr { kind: ExprKind::Call(..), .. })))
275 crate fn is_expected(self, res: Res) -> bool {
277 PathSource::Type => matches!(
284 | DefKind::TraitAlias
289 | DefKind::ForeignTy,
294 PathSource::Trait(AliasPossibility::No) => matches!(res, Res::Def(DefKind::Trait, _)),
295 PathSource::Trait(AliasPossibility::Maybe) => {
296 matches!(res, Res::Def(DefKind::Trait | DefKind::TraitAlias, _))
298 PathSource::Expr(..) => matches!(
301 DefKind::Ctor(_, CtorKind::Const | CtorKind::Fn)
306 | DefKind::AssocConst
307 | DefKind::ConstParam,
312 PathSource::Pat => matches!(
315 DefKind::Ctor(_, CtorKind::Const) | DefKind::Const | DefKind::AssocConst,
317 ) | Res::SelfCtor(..)
319 PathSource::TupleStruct(..) => res.expected_in_tuple_struct_pat(),
320 PathSource::Struct => matches!(
329 ) | Res::SelfTy { .. }
331 PathSource::TraitItem(ns) => match res {
332 Res::Def(DefKind::AssocConst | DefKind::AssocFn, _) if ns == ValueNS => true,
333 Res::Def(DefKind::AssocTy, _) if ns == TypeNS => true,
339 fn error_code(self, has_unexpected_resolution: bool) -> DiagnosticId {
340 use rustc_errors::error_code;
341 match (self, has_unexpected_resolution) {
342 (PathSource::Trait(_), true) => error_code!(E0404),
343 (PathSource::Trait(_), false) => error_code!(E0405),
344 (PathSource::Type, true) => error_code!(E0573),
345 (PathSource::Type, false) => error_code!(E0412),
346 (PathSource::Struct, true) => error_code!(E0574),
347 (PathSource::Struct, false) => error_code!(E0422),
348 (PathSource::Expr(..), true) => error_code!(E0423),
349 (PathSource::Expr(..), false) => error_code!(E0425),
350 (PathSource::Pat | PathSource::TupleStruct(..), true) => error_code!(E0532),
351 (PathSource::Pat | PathSource::TupleStruct(..), false) => error_code!(E0531),
352 (PathSource::TraitItem(..), true) => error_code!(E0575),
353 (PathSource::TraitItem(..), false) => error_code!(E0576),
359 struct DiagnosticMetadata<'ast> {
360 /// The current trait's associated items' ident, used for diagnostic suggestions.
361 current_trait_assoc_items: Option<&'ast [P<AssocItem>]>,
363 /// The current self type if inside an impl (used for better errors).
364 current_self_type: Option<Ty>,
366 /// The current self item if inside an ADT (used for better errors).
367 current_self_item: Option<NodeId>,
369 /// The current trait (used to suggest).
370 current_item: Option<&'ast Item>,
372 /// When processing generics and encountering a type not found, suggest introducing a type
374 currently_processing_generics: bool,
376 /// The current enclosing (non-closure) function (used for better errors).
377 current_function: Option<(FnKind<'ast>, Span)>,
379 /// A list of labels as of yet unused. Labels will be removed from this map when
380 /// they are used (in a `break` or `continue` statement)
381 unused_labels: FxHashMap<NodeId, Span>,
383 /// Only used for better errors on `fn(): fn()`.
384 current_type_ascription: Vec<Span>,
386 /// Only used for better errors on `let x = { foo: bar };`.
387 /// In the case of a parse error with `let x = { foo: bar, };`, this isn't needed, it's only
388 /// needed for cases where this parses as a correct type ascription.
389 current_block_could_be_bare_struct_literal: Option<Span>,
391 /// Only used for better errors on `let <pat>: <expr, not type>;`.
392 current_let_binding: Option<(Span, Option<Span>, Option<Span>)>,
394 /// Used to detect possible `if let` written without `let` and to provide structured suggestion.
395 in_if_condition: Option<&'ast Expr>,
397 /// If we are currently in a trait object definition. Used to point at the bounds when
398 /// encountering a struct or enum.
399 current_trait_object: Option<&'ast [ast::GenericBound]>,
401 /// Given `where <T as Bar>::Baz: String`, suggest `where T: Bar<Baz = String>`.
402 current_where_predicate: Option<&'ast WherePredicate>,
404 current_type_path: Option<&'ast Ty>,
407 struct LateResolutionVisitor<'a, 'b, 'ast> {
408 r: &'b mut Resolver<'a>,
410 /// The module that represents the current item scope.
411 parent_scope: ParentScope<'a>,
413 /// The current set of local scopes for types and values.
414 /// FIXME #4948: Reuse ribs to avoid allocation.
415 ribs: PerNS<Vec<Rib<'a>>>,
417 /// The current set of local scopes, for labels.
418 label_ribs: Vec<Rib<'a, NodeId>>,
420 /// The trait that the current context can refer to.
421 current_trait_ref: Option<(Module<'a>, TraitRef)>,
423 /// Fields used to add information to diagnostic errors.
424 diagnostic_metadata: DiagnosticMetadata<'ast>,
426 /// State used to know whether to ignore resolution errors for function bodies.
428 /// In particular, rustdoc uses this to avoid giving errors for `cfg()` items.
429 /// In most cases this will be `None`, in which case errors will always be reported.
430 /// If it is `true`, then it will be updated when entering a nested function or trait body.
434 /// Walks the whole crate in DFS order, visiting each item, resolving names as it goes.
435 impl<'a: 'ast, 'ast> Visitor<'ast> for LateResolutionVisitor<'a, '_, 'ast> {
436 fn visit_attribute(&mut self, _: &'ast Attribute) {
437 // We do not want to resolve expressions that appear in attributes,
438 // as they do not correspond to actual code.
440 fn visit_item(&mut self, item: &'ast Item) {
441 let prev = replace(&mut self.diagnostic_metadata.current_item, Some(item));
442 // Always report errors in items we just entered.
443 let old_ignore = replace(&mut self.in_func_body, false);
444 self.resolve_item(item);
445 self.in_func_body = old_ignore;
446 self.diagnostic_metadata.current_item = prev;
448 fn visit_arm(&mut self, arm: &'ast Arm) {
449 self.resolve_arm(arm);
451 fn visit_block(&mut self, block: &'ast Block) {
452 self.resolve_block(block);
454 fn visit_anon_const(&mut self, constant: &'ast AnonConst) {
455 // We deal with repeat expressions explicitly in `resolve_expr`.
456 self.resolve_anon_const(constant, IsRepeatExpr::No);
458 fn visit_expr(&mut self, expr: &'ast Expr) {
459 self.resolve_expr(expr, None);
461 fn visit_local(&mut self, local: &'ast Local) {
462 let local_spans = match local.pat.kind {
463 // We check for this to avoid tuple struct fields.
464 PatKind::Wild => None,
467 local.ty.as_ref().map(|ty| ty.span),
468 local.kind.init().map(|init| init.span),
471 let original = replace(&mut self.diagnostic_metadata.current_let_binding, local_spans);
472 self.resolve_local(local);
473 self.diagnostic_metadata.current_let_binding = original;
475 fn visit_ty(&mut self, ty: &'ast Ty) {
476 let prev = self.diagnostic_metadata.current_trait_object;
477 let prev_ty = self.diagnostic_metadata.current_type_path;
479 TyKind::Path(ref qself, ref path) => {
480 self.diagnostic_metadata.current_type_path = Some(ty);
481 self.smart_resolve_path(ty.id, qself.as_ref(), path, PathSource::Type);
483 TyKind::ImplicitSelf => {
484 let self_ty = Ident::with_dummy_span(kw::SelfUpper);
486 .resolve_ident_in_lexical_scope(self_ty, TypeNS, Some(ty.id), ty.span)
487 .map_or(Res::Err, |d| d.res());
488 self.r.record_partial_res(ty.id, PartialRes::new(res));
490 TyKind::TraitObject(ref bounds, ..) => {
491 self.diagnostic_metadata.current_trait_object = Some(&bounds[..]);
495 visit::walk_ty(self, ty);
496 self.diagnostic_metadata.current_trait_object = prev;
497 self.diagnostic_metadata.current_type_path = prev_ty;
499 fn visit_poly_trait_ref(&mut self, tref: &'ast PolyTraitRef, m: &'ast TraitBoundModifier) {
500 self.smart_resolve_path(
501 tref.trait_ref.ref_id,
503 &tref.trait_ref.path,
504 PathSource::Trait(AliasPossibility::Maybe),
506 visit::walk_poly_trait_ref(self, tref, m);
508 fn visit_foreign_item(&mut self, foreign_item: &'ast ForeignItem) {
509 match foreign_item.kind {
510 ForeignItemKind::Fn(box Fn { ref generics, .. })
511 | ForeignItemKind::TyAlias(box TyAlias { ref generics, .. }) => {
512 self.with_generic_param_rib(generics, ItemRibKind(HasGenericParams::Yes), |this| {
513 visit::walk_foreign_item(this, foreign_item);
516 ForeignItemKind::Static(..) => {
517 self.with_item_rib(HasGenericParams::No, |this| {
518 visit::walk_foreign_item(this, foreign_item);
521 ForeignItemKind::MacCall(..) => {
522 visit::walk_foreign_item(self, foreign_item);
526 fn visit_fn(&mut self, fn_kind: FnKind<'ast>, sp: Span, _: NodeId) {
527 let rib_kind = match fn_kind {
528 // Bail if the function is foreign, and thus cannot validly have
529 // a body, or if there's no body for some other reason.
530 FnKind::Fn(FnCtxt::Foreign, _, sig, ..) | FnKind::Fn(_, _, sig, .., None) => {
531 // We don't need to deal with patterns in parameters, because
532 // they are not possible for foreign or bodiless functions.
533 self.visit_fn_header(&sig.header);
534 visit::walk_fn_decl(self, &sig.decl);
537 FnKind::Fn(FnCtxt::Free, ..) => FnItemRibKind,
538 FnKind::Fn(FnCtxt::Assoc(_), ..) => NormalRibKind,
539 FnKind::Closure(..) => ClosureOrAsyncRibKind,
541 let previous_value = self.diagnostic_metadata.current_function;
542 if matches!(fn_kind, FnKind::Fn(..)) {
543 self.diagnostic_metadata.current_function = Some((fn_kind, sp));
545 debug!("(resolving function) entering function");
546 let declaration = fn_kind.decl();
548 // Create a value rib for the function.
549 self.with_rib(ValueNS, rib_kind, |this| {
550 // Create a label rib for the function.
551 this.with_label_rib(rib_kind, |this| {
552 // Add each argument to the rib.
553 this.resolve_params(&declaration.inputs);
555 visit::walk_fn_ret_ty(this, &declaration.output);
557 // Ignore errors in function bodies if this is rustdoc
558 // Be sure not to set this until the function signature has been resolved.
559 let previous_state = replace(&mut this.in_func_body, true);
560 // Resolve the function body, potentially inside the body of an async closure
562 FnKind::Fn(.., body) => walk_list!(this, visit_block, body),
563 FnKind::Closure(_, body) => this.visit_expr(body),
566 debug!("(resolving function) leaving function");
567 this.in_func_body = previous_state;
570 self.diagnostic_metadata.current_function = previous_value;
573 fn visit_generics(&mut self, generics: &'ast Generics) {
574 // For type parameter defaults, we have to ban access
575 // to following type parameters, as the InternalSubsts can only
576 // provide previous type parameters as they're built. We
577 // put all the parameters on the ban list and then remove
578 // them one by one as they are processed and become available.
579 let mut forward_ty_ban_rib = Rib::new(ForwardGenericParamBanRibKind);
580 let mut forward_const_ban_rib = Rib::new(ForwardGenericParamBanRibKind);
581 for param in generics.params.iter() {
583 GenericParamKind::Type { .. } => {
586 .insert(Ident::with_dummy_span(param.ident.name), Res::Err);
588 GenericParamKind::Const { .. } => {
589 forward_const_ban_rib
591 .insert(Ident::with_dummy_span(param.ident.name), Res::Err);
593 GenericParamKind::Lifetime => {}
597 // rust-lang/rust#61631: The type `Self` is essentially
598 // another type parameter. For ADTs, we consider it
599 // well-defined only after all of the ADT type parameters have
600 // been provided. Therefore, we do not allow use of `Self`
601 // anywhere in ADT type parameter defaults.
603 // (We however cannot ban `Self` for defaults on *all* generic
604 // lists; e.g. trait generics can usefully refer to `Self`,
605 // such as in the case of `trait Add<Rhs = Self>`.)
606 if self.diagnostic_metadata.current_self_item.is_some() {
607 // (`Some` if + only if we are in ADT's generics.)
608 forward_ty_ban_rib.bindings.insert(Ident::with_dummy_span(kw::SelfUpper), Res::Err);
611 for param in &generics.params {
613 GenericParamKind::Lifetime => self.visit_generic_param(param),
614 GenericParamKind::Type { ref default } => {
615 for bound in ¶m.bounds {
616 self.visit_param_bound(bound);
619 if let Some(ref ty) = default {
620 self.ribs[TypeNS].push(forward_ty_ban_rib);
621 self.ribs[ValueNS].push(forward_const_ban_rib);
623 forward_const_ban_rib = self.ribs[ValueNS].pop().unwrap();
624 forward_ty_ban_rib = self.ribs[TypeNS].pop().unwrap();
627 // Allow all following defaults to refer to this type parameter.
628 forward_ty_ban_rib.bindings.remove(&Ident::with_dummy_span(param.ident.name));
630 GenericParamKind::Const { ref ty, kw_span: _, ref default } => {
631 // Const parameters can't have param bounds.
632 assert!(param.bounds.is_empty());
634 self.ribs[TypeNS].push(Rib::new(ConstParamTyRibKind));
635 self.ribs[ValueNS].push(Rib::new(ConstParamTyRibKind));
637 self.ribs[TypeNS].pop().unwrap();
638 self.ribs[ValueNS].pop().unwrap();
640 if let Some(ref expr) = default {
641 self.ribs[TypeNS].push(forward_ty_ban_rib);
642 self.ribs[ValueNS].push(forward_const_ban_rib);
643 self.visit_anon_const(expr);
644 forward_const_ban_rib = self.ribs[ValueNS].pop().unwrap();
645 forward_ty_ban_rib = self.ribs[TypeNS].pop().unwrap();
648 // Allow all following defaults to refer to this const parameter.
649 forward_const_ban_rib
651 .remove(&Ident::with_dummy_span(param.ident.name));
655 for p in &generics.where_clause.predicates {
656 self.visit_where_predicate(p);
660 fn visit_generic_arg(&mut self, arg: &'ast GenericArg) {
661 debug!("visit_generic_arg({:?})", arg);
662 let prev = replace(&mut self.diagnostic_metadata.currently_processing_generics, true);
664 GenericArg::Type(ref ty) => {
665 // We parse const arguments as path types as we cannot distinguish them during
666 // parsing. We try to resolve that ambiguity by attempting resolution the type
667 // namespace first, and if that fails we try again in the value namespace. If
668 // resolution in the value namespace succeeds, we have an generic const argument on
670 if let TyKind::Path(ref qself, ref path) = ty.kind {
671 // We cannot disambiguate multi-segment paths right now as that requires type
673 if path.segments.len() == 1 && path.segments[0].args.is_none() {
674 let mut check_ns = |ns| {
675 self.resolve_ident_in_lexical_scope(
676 path.segments[0].ident,
683 if !check_ns(TypeNS) && check_ns(ValueNS) {
684 // This must be equivalent to `visit_anon_const`, but we cannot call it
685 // directly due to visitor lifetimes so we have to copy-paste some code.
687 // Note that we might not be inside of an repeat expression here,
688 // but considering that `IsRepeatExpr` is only relevant for
689 // non-trivial constants this is doesn't matter.
690 self.with_constant_rib(IsRepeatExpr::No, true, None, |this| {
691 this.smart_resolve_path(
695 PathSource::Expr(None),
698 if let Some(ref qself) = *qself {
699 this.visit_ty(&qself.ty);
701 this.visit_path(path, ty.id);
704 self.diagnostic_metadata.currently_processing_generics = prev;
712 GenericArg::Lifetime(lt) => self.visit_lifetime(lt),
713 GenericArg::Const(ct) => self.visit_anon_const(ct),
715 self.diagnostic_metadata.currently_processing_generics = prev;
718 fn visit_where_predicate(&mut self, p: &'ast WherePredicate) {
719 debug!("visit_where_predicate {:?}", p);
721 replace(&mut self.diagnostic_metadata.current_where_predicate, Some(p));
722 visit::walk_where_predicate(self, p);
723 self.diagnostic_metadata.current_where_predicate = previous_value;
727 impl<'a: 'ast, 'b, 'ast> LateResolutionVisitor<'a, 'b, 'ast> {
728 fn new(resolver: &'b mut Resolver<'a>) -> LateResolutionVisitor<'a, 'b, 'ast> {
729 // During late resolution we only track the module component of the parent scope,
730 // although it may be useful to track other components as well for diagnostics.
731 let graph_root = resolver.graph_root;
732 let parent_scope = ParentScope::module(graph_root, resolver);
733 let start_rib_kind = ModuleRibKind(graph_root);
734 LateResolutionVisitor {
738 value_ns: vec![Rib::new(start_rib_kind)],
739 type_ns: vec![Rib::new(start_rib_kind)],
740 macro_ns: vec![Rib::new(start_rib_kind)],
742 label_ribs: Vec::new(),
743 current_trait_ref: None,
744 diagnostic_metadata: DiagnosticMetadata::default(),
745 // errors at module scope should always be reported
750 fn resolve_ident_in_lexical_scope(
754 record_used_id: Option<NodeId>,
756 ) -> Option<LexicalScopeBinding<'a>> {
757 self.r.resolve_ident_in_lexical_scope(
770 opt_ns: Option<Namespace>, // `None` indicates a module path in import
773 crate_lint: CrateLint,
774 ) -> PathResult<'a> {
775 self.r.resolve_path_with_ribs(
788 // We maintain a list of value ribs and type ribs.
790 // Simultaneously, we keep track of the current position in the module
791 // graph in the `parent_scope.module` pointer. When we go to resolve a name in
792 // the value or type namespaces, we first look through all the ribs and
793 // then query the module graph. When we resolve a name in the module
794 // namespace, we can skip all the ribs (since nested modules are not
795 // allowed within blocks in Rust) and jump straight to the current module
798 // Named implementations are handled separately. When we find a method
799 // call, we consult the module node to find all of the implementations in
800 // scope. This information is lazily cached in the module node. We then
801 // generate a fake "implementation scope" containing all the
802 // implementations thus found, for compatibility with old resolve pass.
804 /// Do some `work` within a new innermost rib of the given `kind` in the given namespace (`ns`).
809 work: impl FnOnce(&mut Self) -> T,
811 self.ribs[ns].push(Rib::new(kind));
812 let ret = work(self);
817 fn with_scope<T>(&mut self, id: NodeId, f: impl FnOnce(&mut Self) -> T) -> T {
818 if let Some(module) = self.r.get_module(self.r.local_def_id(id).to_def_id()) {
819 // Move down in the graph.
820 let orig_module = replace(&mut self.parent_scope.module, module);
821 self.with_rib(ValueNS, ModuleRibKind(module), |this| {
822 this.with_rib(TypeNS, ModuleRibKind(module), |this| {
824 this.parent_scope.module = orig_module;
833 /// Searches the current set of local scopes for labels. Returns the `NodeId` of the resolved
834 /// label and reports an error if the label is not found or is unreachable.
835 fn resolve_label(&self, mut label: Ident) -> Option<NodeId> {
836 let mut suggestion = None;
838 // Preserve the original span so that errors contain "in this macro invocation"
840 let original_span = label.span;
842 for i in (0..self.label_ribs.len()).rev() {
843 let rib = &self.label_ribs[i];
845 if let MacroDefinition(def) = rib.kind {
846 // If an invocation of this macro created `ident`, give up on `ident`
847 // and switch to `ident`'s source from the macro definition.
848 if def == self.r.macro_def(label.span.ctxt()) {
849 label.span.remove_mark();
853 let ident = label.normalize_to_macro_rules();
854 if let Some((ident, id)) = rib.bindings.get_key_value(&ident) {
855 return if self.is_label_valid_from_rib(i) {
860 ResolutionError::UnreachableLabel {
862 definition_span: ident.span,
871 // Diagnostics: Check if this rib contains a label with a similar name, keep track of
872 // the first such label that is encountered.
873 suggestion = suggestion.or_else(|| self.suggestion_for_label_in_rib(i, label));
878 ResolutionError::UndeclaredLabel { name: label.name, suggestion },
883 /// Determine whether or not a label from the `rib_index`th label rib is reachable.
884 fn is_label_valid_from_rib(&self, rib_index: usize) -> bool {
885 let ribs = &self.label_ribs[rib_index + 1..];
889 NormalRibKind | MacroDefinition(..) => {
890 // Nothing to do. Continue.
894 | ClosureOrAsyncRibKind
897 | ConstantItemRibKind(..)
899 | ForwardGenericParamBanRibKind
900 | ConstParamTyRibKind => {
909 fn resolve_adt(&mut self, item: &'ast Item, generics: &'ast Generics) {
910 debug!("resolve_adt");
911 self.with_current_self_item(item, |this| {
912 this.with_generic_param_rib(generics, ItemRibKind(HasGenericParams::Yes), |this| {
913 let item_def_id = this.r.local_def_id(item.id).to_def_id();
915 Res::SelfTy { trait_: None, alias_to: Some((item_def_id, false)) },
917 visit::walk_item(this, item);
924 fn future_proof_import(&mut self, use_tree: &UseTree) {
925 let segments = &use_tree.prefix.segments;
926 if !segments.is_empty() {
927 let ident = segments[0].ident;
928 if ident.is_path_segment_keyword() || ident.span.rust_2015() {
932 let nss = match use_tree.kind {
933 UseTreeKind::Simple(..) if segments.len() == 1 => &[TypeNS, ValueNS][..],
936 let report_error = |this: &Self, ns| {
937 let what = if ns == TypeNS { "type parameters" } else { "local variables" };
938 if this.should_report_errs() {
941 .span_err(ident.span, &format!("imports cannot refer to {}", what));
946 match self.resolve_ident_in_lexical_scope(ident, ns, None, use_tree.prefix.span) {
947 Some(LexicalScopeBinding::Res(..)) => {
948 report_error(self, ns);
950 Some(LexicalScopeBinding::Item(binding)) => {
951 let orig_unusable_binding =
952 replace(&mut self.r.unusable_binding, Some(binding));
953 if let Some(LexicalScopeBinding::Res(..)) = self
954 .resolve_ident_in_lexical_scope(ident, ns, None, use_tree.prefix.span)
956 report_error(self, ns);
958 self.r.unusable_binding = orig_unusable_binding;
963 } else if let UseTreeKind::Nested(use_trees) = &use_tree.kind {
964 for (use_tree, _) in use_trees {
965 self.future_proof_import(use_tree);
970 fn resolve_item(&mut self, item: &'ast Item) {
971 let name = item.ident.name;
972 debug!("(resolving item) resolving {} ({:?})", name, item.kind);
975 ItemKind::TyAlias(box TyAlias { ref generics, .. })
976 | ItemKind::Fn(box Fn { ref generics, .. }) => {
977 self.compute_num_lifetime_params(item.id, generics);
978 self.with_generic_param_rib(generics, ItemRibKind(HasGenericParams::Yes), |this| {
979 visit::walk_item(this, item)
983 ItemKind::Enum(_, ref generics)
984 | ItemKind::Struct(_, ref generics)
985 | ItemKind::Union(_, ref generics) => {
986 self.compute_num_lifetime_params(item.id, generics);
987 self.resolve_adt(item, generics);
990 ItemKind::Impl(box Impl {
994 items: ref impl_items,
997 self.compute_num_lifetime_params(item.id, generics);
998 self.resolve_implementation(generics, of_trait, &self_ty, item.id, impl_items);
1001 ItemKind::Trait(box Trait { ref generics, ref bounds, ref items, .. }) => {
1002 self.compute_num_lifetime_params(item.id, generics);
1003 // Create a new rib for the trait-wide type parameters.
1004 self.with_generic_param_rib(generics, ItemRibKind(HasGenericParams::Yes), |this| {
1005 let def = this.r.local_def_id(item.id).to_def_id();
1006 this.with_self_rib(Res::SelfTy { trait_: Some(def), alias_to: None }, |this| {
1007 this.visit_generics(generics);
1008 walk_list!(this, visit_param_bound, bounds);
1010 let walk_assoc_item = |this: &mut Self, generics, item| {
1011 this.with_generic_param_rib(generics, AssocItemRibKind, |this| {
1012 visit::walk_assoc_item(this, item, AssocCtxt::Trait)
1016 this.with_trait_items(items, |this| {
1019 AssocItemKind::Const(_, ty, default) => {
1021 // Only impose the restrictions of `ConstRibKind` for an
1022 // actual constant expression in a provided default.
1023 if let Some(expr) = default {
1024 // We allow arbitrary const expressions inside of associated consts,
1025 // even if they are potentially not const evaluatable.
1027 // Type parameters can already be used and as associated consts are
1028 // not used as part of the type system, this is far less surprising.
1029 this.with_constant_rib(
1033 |this| this.visit_expr(expr),
1037 AssocItemKind::Fn(box Fn { generics, .. }) => {
1038 walk_assoc_item(this, generics, item);
1040 AssocItemKind::TyAlias(box TyAlias { generics, .. }) => {
1041 walk_assoc_item(this, generics, item);
1043 AssocItemKind::MacCall(_) => {
1044 panic!("unexpanded macro in resolve!")
1053 ItemKind::TraitAlias(ref generics, ref bounds) => {
1054 self.compute_num_lifetime_params(item.id, generics);
1055 // Create a new rib for the trait-wide type parameters.
1056 self.with_generic_param_rib(generics, ItemRibKind(HasGenericParams::Yes), |this| {
1057 let def = this.r.local_def_id(item.id).to_def_id();
1058 this.with_self_rib(Res::SelfTy { trait_: Some(def), alias_to: None }, |this| {
1059 this.visit_generics(generics);
1060 walk_list!(this, visit_param_bound, bounds);
1065 ItemKind::Mod(..) | ItemKind::ForeignMod(_) => {
1066 self.with_scope(item.id, |this| {
1067 visit::walk_item(this, item);
1071 ItemKind::Static(ref ty, _, ref expr) | ItemKind::Const(_, ref ty, ref expr) => {
1072 self.with_item_rib(HasGenericParams::No, |this| {
1074 if let Some(expr) = expr {
1075 let constant_item_kind = match item.kind {
1076 ItemKind::Const(..) => ConstantItemKind::Const,
1077 ItemKind::Static(..) => ConstantItemKind::Static,
1078 _ => unreachable!(),
1080 // We already forbid generic params because of the above item rib,
1081 // so it doesn't matter whether this is a trivial constant.
1082 this.with_constant_rib(
1085 Some((item.ident, constant_item_kind)),
1086 |this| this.visit_expr(expr),
1092 ItemKind::Use(ref use_tree) => {
1093 self.future_proof_import(use_tree);
1096 ItemKind::ExternCrate(..) | ItemKind::MacroDef(..) => {
1097 // do nothing, these are just around to be encoded
1100 ItemKind::GlobalAsm(_) => {
1101 visit::walk_item(self, item);
1104 ItemKind::MacCall(_) => panic!("unexpanded macro in resolve!"),
1108 fn with_generic_param_rib<'c, F>(&'c mut self, generics: &'c Generics, kind: RibKind<'a>, f: F)
1110 F: FnOnce(&mut Self),
1112 debug!("with_generic_param_rib");
1113 let mut function_type_rib = Rib::new(kind);
1114 let mut function_value_rib = Rib::new(kind);
1115 let mut seen_bindings = FxHashMap::default();
1117 // We also can't shadow bindings from the parent item
1118 if let AssocItemRibKind = kind {
1119 let mut add_bindings_for_ns = |ns| {
1120 let parent_rib = self.ribs[ns]
1122 .rfind(|r| matches!(r.kind, ItemRibKind(_)))
1123 .expect("associated item outside of an item");
1125 .extend(parent_rib.bindings.iter().map(|(ident, _)| (*ident, ident.span)));
1127 add_bindings_for_ns(ValueNS);
1128 add_bindings_for_ns(TypeNS);
1131 for param in &generics.params {
1132 if let GenericParamKind::Lifetime { .. } = param.kind {
1136 let ident = param.ident.normalize_to_macros_2_0();
1137 debug!("with_generic_param_rib: {}", param.id);
1139 match seen_bindings.entry(ident) {
1140 Entry::Occupied(entry) => {
1141 let span = *entry.get();
1142 let err = ResolutionError::NameAlreadyUsedInParameterList(ident.name, span);
1143 self.report_error(param.ident.span, err);
1145 Entry::Vacant(entry) => {
1146 entry.insert(param.ident.span);
1150 // Plain insert (no renaming).
1151 let (rib, def_kind) = match param.kind {
1152 GenericParamKind::Type { .. } => (&mut function_type_rib, DefKind::TyParam),
1153 GenericParamKind::Const { .. } => (&mut function_value_rib, DefKind::ConstParam),
1154 _ => unreachable!(),
1156 let res = Res::Def(def_kind, self.r.local_def_id(param.id).to_def_id());
1157 self.r.record_partial_res(param.id, PartialRes::new(res));
1158 rib.bindings.insert(ident, res);
1161 self.ribs[ValueNS].push(function_value_rib);
1162 self.ribs[TypeNS].push(function_type_rib);
1166 self.ribs[TypeNS].pop();
1167 self.ribs[ValueNS].pop();
1170 fn with_label_rib(&mut self, kind: RibKind<'a>, f: impl FnOnce(&mut Self)) {
1171 self.label_ribs.push(Rib::new(kind));
1173 self.label_ribs.pop();
1176 fn with_item_rib(&mut self, has_generic_params: HasGenericParams, f: impl FnOnce(&mut Self)) {
1177 let kind = ItemRibKind(has_generic_params);
1178 self.with_rib(ValueNS, kind, |this| this.with_rib(TypeNS, kind, f))
1181 // HACK(min_const_generics,const_evaluatable_unchecked): We
1182 // want to keep allowing `[0; std::mem::size_of::<*mut T>()]`
1183 // with a future compat lint for now. We do this by adding an
1184 // additional special case for repeat expressions.
1186 // Note that we intentionally still forbid `[0; N + 1]` during
1187 // name resolution so that we don't extend the future
1188 // compat lint to new cases.
1189 fn with_constant_rib(
1191 is_repeat: IsRepeatExpr,
1193 item: Option<(Ident, ConstantItemKind)>,
1194 f: impl FnOnce(&mut Self),
1196 debug!("with_constant_rib: is_repeat={:?} is_trivial={}", is_repeat, is_trivial);
1197 self.with_rib(ValueNS, ConstantItemRibKind(is_trivial, item), |this| {
1200 ConstantItemRibKind(is_repeat == IsRepeatExpr::Yes || is_trivial, item),
1202 this.with_label_rib(ConstantItemRibKind(is_trivial, item), f);
1208 fn with_current_self_type<T>(&mut self, self_type: &Ty, f: impl FnOnce(&mut Self) -> T) -> T {
1209 // Handle nested impls (inside fn bodies)
1210 let previous_value =
1211 replace(&mut self.diagnostic_metadata.current_self_type, Some(self_type.clone()));
1212 let result = f(self);
1213 self.diagnostic_metadata.current_self_type = previous_value;
1217 fn with_current_self_item<T>(&mut self, self_item: &Item, f: impl FnOnce(&mut Self) -> T) -> T {
1218 let previous_value =
1219 replace(&mut self.diagnostic_metadata.current_self_item, Some(self_item.id));
1220 let result = f(self);
1221 self.diagnostic_metadata.current_self_item = previous_value;
1225 /// When evaluating a `trait` use its associated types' idents for suggestions in E0412.
1226 fn with_trait_items<T>(
1228 trait_items: &'ast [P<AssocItem>],
1229 f: impl FnOnce(&mut Self) -> T,
1231 let trait_assoc_items =
1232 replace(&mut self.diagnostic_metadata.current_trait_assoc_items, Some(&trait_items));
1233 let result = f(self);
1234 self.diagnostic_metadata.current_trait_assoc_items = trait_assoc_items;
1238 /// This is called to resolve a trait reference from an `impl` (i.e., `impl Trait for Foo`).
1239 fn with_optional_trait_ref<T>(
1241 opt_trait_ref: Option<&TraitRef>,
1242 f: impl FnOnce(&mut Self, Option<DefId>) -> T,
1244 let mut new_val = None;
1245 let mut new_id = None;
1246 if let Some(trait_ref) = opt_trait_ref {
1247 let path: Vec<_> = Segment::from_path(&trait_ref.path);
1248 let res = self.smart_resolve_path_fragment(
1252 trait_ref.path.span,
1253 PathSource::Trait(AliasPossibility::No),
1254 CrateLint::SimplePath(trait_ref.ref_id),
1256 let res = res.base_res();
1257 if res != Res::Err {
1258 if let PathResult::Module(ModuleOrUniformRoot::Module(module)) = self.resolve_path(
1262 trait_ref.path.span,
1263 CrateLint::SimplePath(trait_ref.ref_id),
1265 new_id = Some(res.def_id());
1266 new_val = Some((module, trait_ref.clone()));
1270 let original_trait_ref = replace(&mut self.current_trait_ref, new_val);
1271 let result = f(self, new_id);
1272 self.current_trait_ref = original_trait_ref;
1276 fn with_self_rib_ns(&mut self, ns: Namespace, self_res: Res, f: impl FnOnce(&mut Self)) {
1277 let mut self_type_rib = Rib::new(NormalRibKind);
1279 // Plain insert (no renaming, since types are not currently hygienic)
1280 self_type_rib.bindings.insert(Ident::with_dummy_span(kw::SelfUpper), self_res);
1281 self.ribs[ns].push(self_type_rib);
1283 self.ribs[ns].pop();
1286 fn with_self_rib(&mut self, self_res: Res, f: impl FnOnce(&mut Self)) {
1287 self.with_self_rib_ns(TypeNS, self_res, f)
1290 fn resolve_implementation(
1292 generics: &'ast Generics,
1293 opt_trait_reference: &'ast Option<TraitRef>,
1294 self_type: &'ast Ty,
1296 impl_items: &'ast [P<AssocItem>],
1298 debug!("resolve_implementation");
1299 // If applicable, create a rib for the type parameters.
1300 self.with_generic_param_rib(generics, ItemRibKind(HasGenericParams::Yes), |this| {
1301 // Dummy self type for better errors if `Self` is used in the trait path.
1302 this.with_self_rib(Res::SelfTy { trait_: None, alias_to: None }, |this| {
1303 // Resolve the trait reference, if necessary.
1304 this.with_optional_trait_ref(opt_trait_reference.as_ref(), |this, trait_id| {
1305 let item_def_id = this.r.local_def_id(item_id);
1307 // Register the trait definitions from here.
1308 if let Some(trait_id) = trait_id {
1309 this.r.trait_impls.entry(trait_id).or_default().push(item_def_id);
1312 let item_def_id = item_def_id.to_def_id();
1314 Res::SelfTy { trait_: trait_id, alias_to: Some((item_def_id, false)) };
1315 this.with_self_rib(res, |this| {
1316 if let Some(trait_ref) = opt_trait_reference.as_ref() {
1317 // Resolve type arguments in the trait path.
1318 visit::walk_trait_ref(this, trait_ref);
1320 // Resolve the self type.
1321 this.visit_ty(self_type);
1322 // Resolve the generic parameters.
1323 this.visit_generics(generics);
1324 // Resolve the items within the impl.
1325 this.with_current_self_type(self_type, |this| {
1326 this.with_self_rib_ns(ValueNS, Res::SelfCtor(item_def_id), |this| {
1327 debug!("resolve_implementation with_self_rib_ns(ValueNS, ...)");
1328 for item in impl_items {
1329 use crate::ResolutionError::*;
1331 AssocItemKind::Const(_default, _ty, _expr) => {
1332 debug!("resolve_implementation AssocItemKind::Const");
1333 // If this is a trait impl, ensure the const
1335 this.check_trait_item(
1341 |i, s, c| ConstNotMemberOfTrait(i, s, c),
1344 // We allow arbitrary const expressions inside of associated consts,
1345 // even if they are potentially not const evaluatable.
1347 // Type parameters can already be used and as associated consts are
1348 // not used as part of the type system, this is far less surprising.
1349 this.with_constant_rib(
1354 visit::walk_assoc_item(
1362 AssocItemKind::Fn(box Fn { generics, .. }) => {
1363 debug!("resolve_implementation AssocItemKind::Fn");
1364 // We also need a new scope for the impl item type parameters.
1365 this.with_generic_param_rib(
1369 // If this is a trait impl, ensure the method
1371 this.check_trait_item(
1377 |i, s, c| MethodNotMemberOfTrait(i, s, c),
1380 visit::walk_assoc_item(
1388 AssocItemKind::TyAlias(box TyAlias {
1391 debug!("resolve_implementation AssocItemKind::TyAlias");
1392 // We also need a new scope for the impl item type parameters.
1393 this.with_generic_param_rib(
1397 // If this is a trait impl, ensure the type
1399 this.check_trait_item(
1405 |i, s, c| TypeNotMemberOfTrait(i, s, c),
1408 visit::walk_assoc_item(
1416 AssocItemKind::MacCall(_) => {
1417 panic!("unexpanded macro in resolve!")
1429 fn check_trait_item<F>(
1433 kind: &AssocItemKind,
1438 F: FnOnce(Ident, &str, Option<Symbol>) -> ResolutionError<'_>,
1440 // If there is a TraitRef in scope for an impl, then the method must be in the trait.
1441 let Some((module, _)) = &self.current_trait_ref else { return; };
1442 ident.span.normalize_to_macros_2_0_and_adjust(module.expansion);
1443 let key = self.r.new_key(ident, ns);
1444 let mut binding = self.r.resolution(module, key).try_borrow().ok().and_then(|r| r.binding);
1446 if binding.is_none() {
1447 // We could not find the trait item in the correct namespace.
1448 // Check the other namespace to report an error.
1454 let key = self.r.new_key(ident, ns);
1455 binding = self.r.resolution(module, key).try_borrow().ok().and_then(|r| r.binding);
1458 let Some(binding) = binding else {
1459 // We could not find the method: report an error.
1460 let candidate = self.find_similarly_named_assoc_item(ident.name, kind);
1461 let path = &self.current_trait_ref.as_ref().unwrap().1.path;
1462 self.report_error(span, err(ident, &path_names_to_string(path), candidate));
1466 let res = binding.res();
1467 let Res::Def(def_kind, _) = res else { bug!() };
1468 match (def_kind, kind) {
1469 (DefKind::AssocTy, AssocItemKind::TyAlias(..))
1470 | (DefKind::AssocFn, AssocItemKind::Fn(..))
1471 | (DefKind::AssocConst, AssocItemKind::Const(..)) => {
1472 self.r.record_partial_res(id, PartialRes::new(res));
1478 // The method kind does not correspond to what appeared in the trait, report.
1479 let path = &self.current_trait_ref.as_ref().unwrap().1.path;
1480 let (code, kind) = match kind {
1481 AssocItemKind::Const(..) => (rustc_errors::error_code!(E0323), "const"),
1482 AssocItemKind::Fn(..) => (rustc_errors::error_code!(E0324), "method"),
1483 AssocItemKind::TyAlias(..) => (rustc_errors::error_code!(E0325), "type"),
1484 AssocItemKind::MacCall(..) => span_bug!(span, "unexpanded macro"),
1488 ResolutionError::TraitImplMismatch {
1492 trait_path: path_names_to_string(path),
1493 trait_item_span: binding.span,
1498 fn resolve_params(&mut self, params: &'ast [Param]) {
1499 let mut bindings = smallvec![(PatBoundCtx::Product, Default::default())];
1500 for Param { pat, ty, .. } in params {
1501 self.resolve_pattern(pat, PatternSource::FnParam, &mut bindings);
1503 debug!("(resolving function / closure) recorded parameter");
1507 fn resolve_local(&mut self, local: &'ast Local) {
1508 debug!("resolving local ({:?})", local);
1509 // Resolve the type.
1510 walk_list!(self, visit_ty, &local.ty);
1512 // Resolve the initializer.
1513 if let Some((init, els)) = local.kind.init_else_opt() {
1514 self.visit_expr(init);
1516 // Resolve the `else` block
1517 if let Some(els) = els {
1518 self.visit_block(els);
1522 // Resolve the pattern.
1523 self.resolve_pattern_top(&local.pat, PatternSource::Let);
1526 /// build a map from pattern identifiers to binding-info's.
1527 /// this is done hygienically. This could arise for a macro
1528 /// that expands into an or-pattern where one 'x' was from the
1529 /// user and one 'x' came from the macro.
1530 fn binding_mode_map(&mut self, pat: &Pat) -> BindingMap {
1531 let mut binding_map = FxHashMap::default();
1533 pat.walk(&mut |pat| {
1535 PatKind::Ident(binding_mode, ident, ref sub_pat)
1536 if sub_pat.is_some() || self.is_base_res_local(pat.id) =>
1538 binding_map.insert(ident, BindingInfo { span: ident.span, binding_mode });
1540 PatKind::Or(ref ps) => {
1541 // Check the consistency of this or-pattern and
1542 // then add all bindings to the larger map.
1543 for bm in self.check_consistent_bindings(ps) {
1544 binding_map.extend(bm);
1557 fn is_base_res_local(&self, nid: NodeId) -> bool {
1558 matches!(self.r.partial_res_map.get(&nid).map(|res| res.base_res()), Some(Res::Local(..)))
1561 /// Checks that all of the arms in an or-pattern have exactly the
1562 /// same set of bindings, with the same binding modes for each.
1563 fn check_consistent_bindings(&mut self, pats: &[P<Pat>]) -> Vec<BindingMap> {
1564 let mut missing_vars = FxHashMap::default();
1565 let mut inconsistent_vars = FxHashMap::default();
1567 // 1) Compute the binding maps of all arms.
1568 let maps = pats.iter().map(|pat| self.binding_mode_map(pat)).collect::<Vec<_>>();
1570 // 2) Record any missing bindings or binding mode inconsistencies.
1571 for (map_outer, pat_outer) in pats.iter().enumerate().map(|(idx, pat)| (&maps[idx], pat)) {
1572 // Check against all arms except for the same pattern which is always self-consistent.
1576 .filter(|(_, pat)| pat.id != pat_outer.id)
1577 .flat_map(|(idx, _)| maps[idx].iter())
1578 .map(|(key, binding)| (key.name, map_outer.get(&key), binding));
1580 for (name, info, &binding_inner) in inners {
1583 // The inner binding is missing in the outer.
1585 missing_vars.entry(name).or_insert_with(|| BindingError {
1587 origin: BTreeSet::new(),
1588 target: BTreeSet::new(),
1589 could_be_path: name.as_str().starts_with(char::is_uppercase),
1591 binding_error.origin.insert(binding_inner.span);
1592 binding_error.target.insert(pat_outer.span);
1594 Some(binding_outer) => {
1595 if binding_outer.binding_mode != binding_inner.binding_mode {
1596 // The binding modes in the outer and inner bindings differ.
1599 .or_insert((binding_inner.span, binding_outer.span));
1606 // 3) Report all missing variables we found.
1607 let mut missing_vars = missing_vars.iter_mut().collect::<Vec<_>>();
1608 missing_vars.sort_by_key(|(sym, _err)| sym.as_str());
1610 for (name, mut v) in missing_vars {
1611 if inconsistent_vars.contains_key(name) {
1612 v.could_be_path = false;
1615 *v.origin.iter().next().unwrap(),
1616 ResolutionError::VariableNotBoundInPattern(v),
1620 // 4) Report all inconsistencies in binding modes we found.
1621 let mut inconsistent_vars = inconsistent_vars.iter().collect::<Vec<_>>();
1622 inconsistent_vars.sort();
1623 for (name, v) in inconsistent_vars {
1624 self.report_error(v.0, ResolutionError::VariableBoundWithDifferentMode(*name, v.1));
1627 // 5) Finally bubble up all the binding maps.
1631 /// Check the consistency of the outermost or-patterns.
1632 fn check_consistent_bindings_top(&mut self, pat: &'ast Pat) {
1633 pat.walk(&mut |pat| match pat.kind {
1634 PatKind::Or(ref ps) => {
1635 self.check_consistent_bindings(ps);
1642 fn resolve_arm(&mut self, arm: &'ast Arm) {
1643 self.with_rib(ValueNS, NormalRibKind, |this| {
1644 this.resolve_pattern_top(&arm.pat, PatternSource::Match);
1645 walk_list!(this, visit_expr, &arm.guard);
1646 this.visit_expr(&arm.body);
1650 /// Arising from `source`, resolve a top level pattern.
1651 fn resolve_pattern_top(&mut self, pat: &'ast Pat, pat_src: PatternSource) {
1652 let mut bindings = smallvec![(PatBoundCtx::Product, Default::default())];
1653 self.resolve_pattern(pat, pat_src, &mut bindings);
1659 pat_src: PatternSource,
1660 bindings: &mut SmallVec<[(PatBoundCtx, FxHashSet<Ident>); 1]>,
1662 // We walk the pattern before declaring the pattern's inner bindings,
1663 // so that we avoid resolving a literal expression to a binding defined
1665 visit::walk_pat(self, pat);
1666 self.resolve_pattern_inner(pat, pat_src, bindings);
1667 // This has to happen *after* we determine which pat_idents are variants:
1668 self.check_consistent_bindings_top(pat);
1671 /// Resolve bindings in a pattern. This is a helper to `resolve_pattern`.
1675 /// A stack of sets of bindings accumulated.
1677 /// In each set, `PatBoundCtx::Product` denotes that a found binding in it should
1678 /// be interpreted as re-binding an already bound binding. This results in an error.
1679 /// Meanwhile, `PatBound::Or` denotes that a found binding in the set should result
1680 /// in reusing this binding rather than creating a fresh one.
1682 /// When called at the top level, the stack must have a single element
1683 /// with `PatBound::Product`. Otherwise, pushing to the stack happens as
1684 /// or-patterns (`p_0 | ... | p_n`) are encountered and the context needs
1685 /// to be switched to `PatBoundCtx::Or` and then `PatBoundCtx::Product` for each `p_i`.
1686 /// When each `p_i` has been dealt with, the top set is merged with its parent.
1687 /// When a whole or-pattern has been dealt with, the thing happens.
1689 /// See the implementation and `fresh_binding` for more details.
1690 fn resolve_pattern_inner(
1693 pat_src: PatternSource,
1694 bindings: &mut SmallVec<[(PatBoundCtx, FxHashSet<Ident>); 1]>,
1696 // Visit all direct subpatterns of this pattern.
1697 pat.walk(&mut |pat| {
1698 debug!("resolve_pattern pat={:?} node={:?}", pat, pat.kind);
1700 PatKind::Ident(bmode, ident, ref sub) => {
1701 // First try to resolve the identifier as some existing entity,
1702 // then fall back to a fresh binding.
1703 let has_sub = sub.is_some();
1705 .try_resolve_as_non_binding(pat_src, pat, bmode, ident, has_sub)
1706 .unwrap_or_else(|| self.fresh_binding(ident, pat.id, pat_src, bindings));
1707 self.r.record_partial_res(pat.id, PartialRes::new(res));
1708 self.r.record_pat_span(pat.id, pat.span);
1710 PatKind::TupleStruct(ref qself, ref path, ref sub_patterns) => {
1711 self.smart_resolve_path(
1715 PathSource::TupleStruct(
1717 self.r.arenas.alloc_pattern_spans(sub_patterns.iter().map(|p| p.span)),
1721 PatKind::Path(ref qself, ref path) => {
1722 self.smart_resolve_path(pat.id, qself.as_ref(), path, PathSource::Pat);
1724 PatKind::Struct(ref qself, ref path, ..) => {
1725 self.smart_resolve_path(pat.id, qself.as_ref(), path, PathSource::Struct);
1727 PatKind::Or(ref ps) => {
1728 // Add a new set of bindings to the stack. `Or` here records that when a
1729 // binding already exists in this set, it should not result in an error because
1730 // `V1(a) | V2(a)` must be allowed and are checked for consistency later.
1731 bindings.push((PatBoundCtx::Or, Default::default()));
1733 // Now we need to switch back to a product context so that each
1734 // part of the or-pattern internally rejects already bound names.
1735 // For example, `V1(a) | V2(a, a)` and `V1(a, a) | V2(a)` are bad.
1736 bindings.push((PatBoundCtx::Product, Default::default()));
1737 self.resolve_pattern_inner(p, pat_src, bindings);
1738 // Move up the non-overlapping bindings to the or-pattern.
1739 // Existing bindings just get "merged".
1740 let collected = bindings.pop().unwrap().1;
1741 bindings.last_mut().unwrap().1.extend(collected);
1743 // This or-pattern itself can itself be part of a product,
1744 // e.g. `(V1(a) | V2(a), a)` or `(a, V1(a) | V2(a))`.
1745 // Both cases bind `a` again in a product pattern and must be rejected.
1746 let collected = bindings.pop().unwrap().1;
1747 bindings.last_mut().unwrap().1.extend(collected);
1749 // Prevent visiting `ps` as we've already done so above.
1762 pat_src: PatternSource,
1763 bindings: &mut SmallVec<[(PatBoundCtx, FxHashSet<Ident>); 1]>,
1765 // Add the binding to the local ribs, if it doesn't already exist in the bindings map.
1766 // (We must not add it if it's in the bindings map because that breaks the assumptions
1767 // later passes make about or-patterns.)
1768 let ident = ident.normalize_to_macro_rules();
1770 let mut bound_iter = bindings.iter().filter(|(_, set)| set.contains(&ident));
1771 // Already bound in a product pattern? e.g. `(a, a)` which is not allowed.
1772 let already_bound_and = bound_iter.clone().any(|(ctx, _)| *ctx == PatBoundCtx::Product);
1773 // Already bound in an or-pattern? e.g. `V1(a) | V2(a)`.
1774 // This is *required* for consistency which is checked later.
1775 let already_bound_or = bound_iter.any(|(ctx, _)| *ctx == PatBoundCtx::Or);
1777 if already_bound_and {
1778 // Overlap in a product pattern somewhere; report an error.
1779 use ResolutionError::*;
1780 let error = match pat_src {
1781 // `fn f(a: u8, a: u8)`:
1782 PatternSource::FnParam => IdentifierBoundMoreThanOnceInParameterList,
1784 _ => IdentifierBoundMoreThanOnceInSamePattern,
1786 self.report_error(ident.span, error(ident.name));
1789 // Record as bound if it's valid:
1790 let ident_valid = ident.name != kw::Empty;
1792 bindings.last_mut().unwrap().1.insert(ident);
1795 if already_bound_or {
1796 // `Variant1(a) | Variant2(a)`, ok
1797 // Reuse definition from the first `a`.
1798 self.innermost_rib_bindings(ValueNS)[&ident]
1800 let res = Res::Local(pat_id);
1802 // A completely fresh binding add to the set if it's valid.
1803 self.innermost_rib_bindings(ValueNS).insert(ident, res);
1809 fn innermost_rib_bindings(&mut self, ns: Namespace) -> &mut IdentMap<Res> {
1810 &mut self.ribs[ns].last_mut().unwrap().bindings
1813 fn try_resolve_as_non_binding(
1815 pat_src: PatternSource,
1821 // An immutable (no `mut`) by-value (no `ref`) binding pattern without
1822 // a sub pattern (no `@ $pat`) is syntactically ambiguous as it could
1823 // also be interpreted as a path to e.g. a constant, variant, etc.
1824 let is_syntactic_ambiguity = !has_sub && bm == BindingMode::ByValue(Mutability::Not);
1826 let ls_binding = self.resolve_ident_in_lexical_scope(ident, ValueNS, None, pat.span)?;
1827 let (res, binding) = match ls_binding {
1828 LexicalScopeBinding::Item(binding)
1829 if is_syntactic_ambiguity && binding.is_ambiguity() =>
1831 // For ambiguous bindings we don't know all their definitions and cannot check
1832 // whether they can be shadowed by fresh bindings or not, so force an error.
1833 // issues/33118#issuecomment-233962221 (see below) still applies here,
1834 // but we have to ignore it for backward compatibility.
1835 self.r.record_use(ident, binding, false);
1838 LexicalScopeBinding::Item(binding) => (binding.res(), Some(binding)),
1839 LexicalScopeBinding::Res(res) => (res, None),
1843 Res::SelfCtor(_) // See #70549.
1845 DefKind::Ctor(_, CtorKind::Const) | DefKind::Const | DefKind::ConstParam,
1847 ) if is_syntactic_ambiguity => {
1848 // Disambiguate in favor of a unit struct/variant or constant pattern.
1849 if let Some(binding) = binding {
1850 self.r.record_use(ident, binding, false);
1854 Res::Def(DefKind::Ctor(..) | DefKind::Const | DefKind::Static, _) => {
1855 // This is unambiguously a fresh binding, either syntactically
1856 // (e.g., `IDENT @ PAT` or `ref IDENT`) or because `IDENT` resolves
1857 // to something unusable as a pattern (e.g., constructor function),
1858 // but we still conservatively report an error, see
1859 // issues/33118#issuecomment-233962221 for one reason why.
1860 let binding = binding.expect("no binding for a ctor or static");
1863 ResolutionError::BindingShadowsSomethingUnacceptable {
1864 shadowing_binding_descr: pat_src.descr(),
1866 participle: if binding.is_import() { "imported" } else { "defined" },
1867 article: binding.res().article(),
1868 shadowed_binding_descr: binding.res().descr(),
1869 shadowed_binding_span: binding.span,
1874 Res::Def(DefKind::ConstParam, def_id) => {
1875 // Same as for DefKind::Const above, but here, `binding` is `None`, so we
1876 // have to construct the error differently
1879 ResolutionError::BindingShadowsSomethingUnacceptable {
1880 shadowing_binding_descr: pat_src.descr(),
1882 participle: "defined",
1883 article: res.article(),
1884 shadowed_binding_descr: res.descr(),
1885 shadowed_binding_span: self.r.opt_span(def_id).expect("const parameter defined outside of local crate"),
1890 Res::Def(DefKind::Fn, _) | Res::Local(..) | Res::Err => {
1891 // These entities are explicitly allowed to be shadowed by fresh bindings.
1896 "unexpected resolution for an identifier in pattern: {:?}",
1902 // High-level and context dependent path resolution routine.
1903 // Resolves the path and records the resolution into definition map.
1904 // If resolution fails tries several techniques to find likely
1905 // resolution candidates, suggest imports or other help, and report
1906 // errors in user friendly way.
1907 fn smart_resolve_path(
1910 qself: Option<&QSelf>,
1912 source: PathSource<'ast>,
1914 self.smart_resolve_path_fragment(
1917 &Segment::from_path(path),
1920 CrateLint::SimplePath(id),
1924 fn smart_resolve_path_fragment(
1927 qself: Option<&QSelf>,
1930 source: PathSource<'ast>,
1931 crate_lint: CrateLint,
1934 "smart_resolve_path_fragment(id={:?}, qself={:?}, path={:?})",
1939 let ns = source.namespace();
1941 let report_errors = |this: &mut Self, res: Option<Res>| {
1942 if this.should_report_errs() {
1943 let (err, candidates) = this.smart_resolve_report_errors(path, span, source, res);
1945 let def_id = this.parent_scope.module.nearest_parent_mod();
1946 let instead = res.is_some();
1948 if res.is_none() { this.report_missing_type_error(path) } else { None };
1950 this.r.use_injections.push(UseError {
1959 PartialRes::new(Res::Err)
1962 // For paths originating from calls (like in `HashMap::new()`), tries
1963 // to enrich the plain `failed to resolve: ...` message with hints
1964 // about possible missing imports.
1966 // Similar thing, for types, happens in `report_errors` above.
1967 let report_errors_for_call = |this: &mut Self, parent_err: Spanned<ResolutionError<'a>>| {
1968 if !source.is_call() {
1969 return Some(parent_err);
1972 // Before we start looking for candidates, we have to get our hands
1973 // on the type user is trying to perform invocation on; basically:
1974 // we're transforming `HashMap::new` into just `HashMap`.
1975 let path = match path.split_last() {
1976 Some((_, path)) if !path.is_empty() => path,
1977 _ => return Some(parent_err),
1980 let (mut err, candidates) =
1981 this.smart_resolve_report_errors(path, span, PathSource::Type, None);
1983 if candidates.is_empty() {
1985 return Some(parent_err);
1988 // There are two different error messages user might receive at
1990 // - E0412 cannot find type `{}` in this scope
1991 // - E0433 failed to resolve: use of undeclared type or module `{}`
1993 // The first one is emitted for paths in type-position, and the
1994 // latter one - for paths in expression-position.
1996 // Thus (since we're in expression-position at this point), not to
1997 // confuse the user, we want to keep the *message* from E0432 (so
1998 // `parent_err`), but we want *hints* from E0412 (so `err`).
2000 // And that's what happens below - we're just mixing both messages
2001 // into a single one.
2002 let mut parent_err = this.r.into_struct_error(parent_err.span, parent_err.node);
2004 err.message = take(&mut parent_err.message);
2005 err.code = take(&mut parent_err.code);
2006 err.children = take(&mut parent_err.children);
2008 parent_err.cancel();
2010 let def_id = this.parent_scope.module.nearest_parent_mod();
2012 if this.should_report_errs() {
2013 this.r.use_injections.push(UseError {
2024 // We don't return `Some(parent_err)` here, because the error will
2025 // be already printed as part of the `use` injections
2029 let partial_res = match self.resolve_qpath_anywhere(
2035 source.defer_to_typeck(),
2038 Ok(Some(partial_res)) if partial_res.unresolved_segments() == 0 => {
2039 if source.is_expected(partial_res.base_res()) || partial_res.base_res() == Res::Err
2043 report_errors(self, Some(partial_res.base_res()))
2047 Ok(Some(partial_res)) if source.defer_to_typeck() => {
2048 // Not fully resolved associated item `T::A::B` or `<T as Tr>::A::B`
2049 // or `<T>::A::B`. If `B` should be resolved in value namespace then
2050 // it needs to be added to the trait map.
2052 let item_name = path.last().unwrap().ident;
2053 let traits = self.traits_in_scope(item_name, ns);
2054 self.r.trait_map.insert(id, traits);
2057 if PrimTy::from_name(path[0].ident.name).is_some() {
2058 let mut std_path = Vec::with_capacity(1 + path.len());
2060 std_path.push(Segment::from_ident(Ident::with_dummy_span(sym::std)));
2061 std_path.extend(path);
2062 if let PathResult::Module(_) | PathResult::NonModule(_) =
2063 self.resolve_path(&std_path, Some(ns), false, span, CrateLint::No)
2065 // Check if we wrote `str::from_utf8` instead of `std::str::from_utf8`
2067 path.iter().last().map_or(span, |segment| segment.ident.span);
2069 self.r.confused_type_with_std_module.insert(item_span, span);
2070 self.r.confused_type_with_std_module.insert(span, span);
2078 if let Some(err) = report_errors_for_call(self, err) {
2079 self.report_error(err.span, err.node);
2082 PartialRes::new(Res::Err)
2085 _ => report_errors(self, None),
2088 if !matches!(source, PathSource::TraitItem(..)) {
2089 // Avoid recording definition of `A::B` in `<T as A>::B::C`.
2090 self.r.record_partial_res(id, partial_res);
2096 fn self_type_is_available(&mut self, span: Span) -> bool {
2097 let binding = self.resolve_ident_in_lexical_scope(
2098 Ident::with_dummy_span(kw::SelfUpper),
2103 if let Some(LexicalScopeBinding::Res(res)) = binding { res != Res::Err } else { false }
2106 fn self_value_is_available(&mut self, self_span: Span, path_span: Span) -> bool {
2107 let ident = Ident::new(kw::SelfLower, self_span);
2108 let binding = self.resolve_ident_in_lexical_scope(ident, ValueNS, None, path_span);
2109 if let Some(LexicalScopeBinding::Res(res)) = binding { res != Res::Err } else { false }
2112 /// A wrapper around [`Resolver::report_error`].
2114 /// This doesn't emit errors for function bodies if this is rustdoc.
2115 fn report_error(&self, span: Span, resolution_error: ResolutionError<'_>) {
2116 if self.should_report_errs() {
2117 self.r.report_error(span, resolution_error);
2122 /// If we're actually rustdoc then avoid giving a name resolution error for `cfg()` items.
2123 fn should_report_errs(&self) -> bool {
2124 !(self.r.session.opts.actually_rustdoc && self.in_func_body)
2127 // Resolve in alternative namespaces if resolution in the primary namespace fails.
2128 fn resolve_qpath_anywhere(
2131 qself: Option<&QSelf>,
2133 primary_ns: Namespace,
2135 defer_to_typeck: bool,
2136 crate_lint: CrateLint,
2137 ) -> Result<Option<PartialRes>, Spanned<ResolutionError<'a>>> {
2138 let mut fin_res = None;
2140 for (i, &ns) in [primary_ns, TypeNS, ValueNS].iter().enumerate() {
2141 if i == 0 || ns != primary_ns {
2142 match self.resolve_qpath(id, qself, path, ns, span, crate_lint)? {
2144 if partial_res.unresolved_segments() == 0 || defer_to_typeck =>
2146 return Ok(Some(partial_res));
2149 if fin_res.is_none() {
2150 fin_res = partial_res;
2157 assert!(primary_ns != MacroNS);
2159 if qself.is_none() {
2160 let path_seg = |seg: &Segment| PathSegment::from_ident(seg.ident);
2161 let path = Path { segments: path.iter().map(path_seg).collect(), span, tokens: None };
2162 if let Ok((_, res)) =
2163 self.r.resolve_macro_path(&path, None, &self.parent_scope, false, false)
2165 return Ok(Some(PartialRes::new(res)));
2172 /// Handles paths that may refer to associated items.
2176 qself: Option<&QSelf>,
2180 crate_lint: CrateLint,
2181 ) -> Result<Option<PartialRes>, Spanned<ResolutionError<'a>>> {
2183 "resolve_qpath(id={:?}, qself={:?}, path={:?}, ns={:?}, span={:?})",
2184 id, qself, path, ns, span,
2187 if let Some(qself) = qself {
2188 if qself.position == 0 {
2189 // This is a case like `<T>::B`, where there is no
2190 // trait to resolve. In that case, we leave the `B`
2191 // segment to be resolved by type-check.
2192 return Ok(Some(PartialRes::with_unresolved_segments(
2193 Res::Def(DefKind::Mod, DefId::local(CRATE_DEF_INDEX)),
2198 // Make sure `A::B` in `<T as A::B>::C` is a trait item.
2200 // Currently, `path` names the full item (`A::B::C`, in
2201 // our example). so we extract the prefix of that that is
2202 // the trait (the slice upto and including
2203 // `qself.position`). And then we recursively resolve that,
2204 // but with `qself` set to `None`.
2206 // However, setting `qself` to none (but not changing the
2207 // span) loses the information about where this path
2208 // *actually* appears, so for the purposes of the crate
2209 // lint we pass along information that this is the trait
2210 // name from a fully qualified path, and this also
2211 // contains the full span (the `CrateLint::QPathTrait`).
2212 let ns = if qself.position + 1 == path.len() { ns } else { TypeNS };
2213 let partial_res = self.smart_resolve_path_fragment(
2216 &path[..=qself.position],
2218 PathSource::TraitItem(ns),
2219 CrateLint::QPathTrait { qpath_id: id, qpath_span: qself.path_span },
2222 // The remaining segments (the `C` in our example) will
2223 // have to be resolved by type-check, since that requires doing
2224 // trait resolution.
2225 return Ok(Some(PartialRes::with_unresolved_segments(
2226 partial_res.base_res(),
2227 partial_res.unresolved_segments() + path.len() - qself.position - 1,
2231 let result = match self.resolve_path(&path, Some(ns), true, span, crate_lint) {
2232 PathResult::NonModule(path_res) => path_res,
2233 PathResult::Module(ModuleOrUniformRoot::Module(module)) if !module.is_normal() => {
2234 PartialRes::new(module.res().unwrap())
2236 // In `a(::assoc_item)*` `a` cannot be a module. If `a` does resolve to a module we
2237 // don't report an error right away, but try to fallback to a primitive type.
2238 // So, we are still able to successfully resolve something like
2240 // use std::u8; // bring module u8 in scope
2241 // fn f() -> u8 { // OK, resolves to primitive u8, not to std::u8
2242 // u8::max_value() // OK, resolves to associated function <u8>::max_value,
2243 // // not to non-existent std::u8::max_value
2246 // Such behavior is required for backward compatibility.
2247 // The same fallback is used when `a` resolves to nothing.
2248 PathResult::Module(ModuleOrUniformRoot::Module(_)) | PathResult::Failed { .. }
2249 if (ns == TypeNS || path.len() > 1)
2250 && PrimTy::from_name(path[0].ident.name).is_some() =>
2252 let prim = PrimTy::from_name(path[0].ident.name).unwrap();
2253 PartialRes::with_unresolved_segments(Res::PrimTy(prim), path.len() - 1)
2255 PathResult::Module(ModuleOrUniformRoot::Module(module)) => {
2256 PartialRes::new(module.res().unwrap())
2258 PathResult::Failed { is_error_from_last_segment: false, span, label, suggestion } => {
2259 return Err(respan(span, ResolutionError::FailedToResolve { label, suggestion }));
2261 PathResult::Module(..) | PathResult::Failed { .. } => return Ok(None),
2262 PathResult::Indeterminate => bug!("indeterminate path result in resolve_qpath"),
2266 && result.base_res() != Res::Err
2267 && path[0].ident.name != kw::PathRoot
2268 && path[0].ident.name != kw::DollarCrate
2270 let unqualified_result = {
2271 match self.resolve_path(
2272 &[*path.last().unwrap()],
2278 PathResult::NonModule(path_res) => path_res.base_res(),
2279 PathResult::Module(ModuleOrUniformRoot::Module(module)) => {
2280 module.res().unwrap()
2282 _ => return Ok(Some(result)),
2285 if result.base_res() == unqualified_result {
2286 let lint = lint::builtin::UNUSED_QUALIFICATIONS;
2287 self.r.lint_buffer.buffer_lint(lint, id, span, "unnecessary qualification")
2294 fn with_resolved_label(&mut self, label: Option<Label>, id: NodeId, f: impl FnOnce(&mut Self)) {
2295 if let Some(label) = label {
2296 if label.ident.as_str().as_bytes()[1] != b'_' {
2297 self.diagnostic_metadata.unused_labels.insert(id, label.ident.span);
2299 self.with_label_rib(NormalRibKind, |this| {
2300 let ident = label.ident.normalize_to_macro_rules();
2301 this.label_ribs.last_mut().unwrap().bindings.insert(ident, id);
2309 fn resolve_labeled_block(&mut self, label: Option<Label>, id: NodeId, block: &'ast Block) {
2310 self.with_resolved_label(label, id, |this| this.visit_block(block));
2313 fn resolve_block(&mut self, block: &'ast Block) {
2314 debug!("(resolving block) entering block");
2315 // Move down in the graph, if there's an anonymous module rooted here.
2316 let orig_module = self.parent_scope.module;
2317 let anonymous_module = self.r.block_map.get(&block.id).cloned(); // clones a reference
2319 let mut num_macro_definition_ribs = 0;
2320 if let Some(anonymous_module) = anonymous_module {
2321 debug!("(resolving block) found anonymous module, moving down");
2322 self.ribs[ValueNS].push(Rib::new(ModuleRibKind(anonymous_module)));
2323 self.ribs[TypeNS].push(Rib::new(ModuleRibKind(anonymous_module)));
2324 self.parent_scope.module = anonymous_module;
2326 self.ribs[ValueNS].push(Rib::new(NormalRibKind));
2329 let prev = self.diagnostic_metadata.current_block_could_be_bare_struct_literal.take();
2330 if let (true, [Stmt { kind: StmtKind::Expr(expr), .. }]) =
2331 (block.could_be_bare_literal, &block.stmts[..])
2333 if let ExprKind::Type(..) = expr.kind {
2334 self.diagnostic_metadata.current_block_could_be_bare_struct_literal =
2338 // Descend into the block.
2339 for stmt in &block.stmts {
2340 if let StmtKind::Item(ref item) = stmt.kind {
2341 if let ItemKind::MacroDef(..) = item.kind {
2342 num_macro_definition_ribs += 1;
2343 let res = self.r.local_def_id(item.id).to_def_id();
2344 self.ribs[ValueNS].push(Rib::new(MacroDefinition(res)));
2345 self.label_ribs.push(Rib::new(MacroDefinition(res)));
2349 self.visit_stmt(stmt);
2351 self.diagnostic_metadata.current_block_could_be_bare_struct_literal = prev;
2354 self.parent_scope.module = orig_module;
2355 for _ in 0..num_macro_definition_ribs {
2356 self.ribs[ValueNS].pop();
2357 self.label_ribs.pop();
2359 self.ribs[ValueNS].pop();
2360 if anonymous_module.is_some() {
2361 self.ribs[TypeNS].pop();
2363 debug!("(resolving block) leaving block");
2366 fn resolve_anon_const(&mut self, constant: &'ast AnonConst, is_repeat: IsRepeatExpr) {
2367 debug!("resolve_anon_const {:?} is_repeat: {:?}", constant, is_repeat);
2368 self.with_constant_rib(
2370 constant.value.is_potential_trivial_const_param(),
2373 visit::walk_anon_const(this, constant);
2378 fn resolve_expr(&mut self, expr: &'ast Expr, parent: Option<&'ast Expr>) {
2379 // First, record candidate traits for this expression if it could
2380 // result in the invocation of a method call.
2382 self.record_candidate_traits_for_expr_if_necessary(expr);
2384 // Next, resolve the node.
2386 ExprKind::Path(ref qself, ref path) => {
2387 self.smart_resolve_path(expr.id, qself.as_ref(), path, PathSource::Expr(parent));
2388 visit::walk_expr(self, expr);
2391 ExprKind::Struct(ref se) => {
2392 self.smart_resolve_path(expr.id, se.qself.as_ref(), &se.path, PathSource::Struct);
2393 visit::walk_expr(self, expr);
2396 ExprKind::Break(Some(label), _) | ExprKind::Continue(Some(label)) => {
2397 if let Some(node_id) = self.resolve_label(label.ident) {
2398 // Since this res is a label, it is never read.
2399 self.r.label_res_map.insert(expr.id, node_id);
2400 self.diagnostic_metadata.unused_labels.remove(&node_id);
2403 // visit `break` argument if any
2404 visit::walk_expr(self, expr);
2407 ExprKind::Break(None, Some(ref e)) => {
2408 // We use this instead of `visit::walk_expr` to keep the parent expr around for
2409 // better diagnostics.
2410 self.resolve_expr(e, Some(&expr));
2413 ExprKind::Let(ref pat, ref scrutinee, _) => {
2414 self.visit_expr(scrutinee);
2415 self.resolve_pattern_top(pat, PatternSource::Let);
2418 ExprKind::If(ref cond, ref then, ref opt_else) => {
2419 self.with_rib(ValueNS, NormalRibKind, |this| {
2420 let old = this.diagnostic_metadata.in_if_condition.replace(cond);
2421 this.visit_expr(cond);
2422 this.diagnostic_metadata.in_if_condition = old;
2423 this.visit_block(then);
2425 if let Some(expr) = opt_else {
2426 self.visit_expr(expr);
2430 ExprKind::Loop(ref block, label) => self.resolve_labeled_block(label, expr.id, &block),
2432 ExprKind::While(ref cond, ref block, label) => {
2433 self.with_resolved_label(label, expr.id, |this| {
2434 this.with_rib(ValueNS, NormalRibKind, |this| {
2435 let old = this.diagnostic_metadata.in_if_condition.replace(cond);
2436 this.visit_expr(cond);
2437 this.diagnostic_metadata.in_if_condition = old;
2438 this.visit_block(block);
2443 ExprKind::ForLoop(ref pat, ref iter_expr, ref block, label) => {
2444 self.visit_expr(iter_expr);
2445 self.with_rib(ValueNS, NormalRibKind, |this| {
2446 this.resolve_pattern_top(pat, PatternSource::For);
2447 this.resolve_labeled_block(label, expr.id, block);
2451 ExprKind::Block(ref block, label) => self.resolve_labeled_block(label, block.id, block),
2453 // Equivalent to `visit::walk_expr` + passing some context to children.
2454 ExprKind::Field(ref subexpression, _) => {
2455 self.resolve_expr(subexpression, Some(expr));
2457 ExprKind::MethodCall(ref segment, ref arguments, _) => {
2458 let mut arguments = arguments.iter();
2459 self.resolve_expr(arguments.next().unwrap(), Some(expr));
2460 for argument in arguments {
2461 self.resolve_expr(argument, None);
2463 self.visit_path_segment(expr.span, segment);
2466 ExprKind::Call(ref callee, ref arguments) => {
2467 self.resolve_expr(callee, Some(expr));
2468 let const_args = self.r.legacy_const_generic_args(callee).unwrap_or_default();
2469 for (idx, argument) in arguments.iter().enumerate() {
2470 // Constant arguments need to be treated as AnonConst since
2471 // that is how they will be later lowered to HIR.
2472 if const_args.contains(&idx) {
2473 self.with_constant_rib(
2475 argument.is_potential_trivial_const_param(),
2478 this.resolve_expr(argument, None);
2482 self.resolve_expr(argument, None);
2486 ExprKind::Type(ref type_expr, ref ty) => {
2487 // `ParseSess::type_ascription_path_suggestions` keeps spans of colon tokens in
2488 // type ascription. Here we are trying to retrieve the span of the colon token as
2489 // well, but only if it's written without spaces `expr:Ty` and therefore confusable
2490 // with `expr::Ty`, only in this case it will match the span from
2491 // `type_ascription_path_suggestions`.
2492 self.diagnostic_metadata
2493 .current_type_ascription
2494 .push(type_expr.span.between(ty.span));
2495 visit::walk_expr(self, expr);
2496 self.diagnostic_metadata.current_type_ascription.pop();
2498 // `async |x| ...` gets desugared to `|x| future_from_generator(|| ...)`, so we need to
2499 // resolve the arguments within the proper scopes so that usages of them inside the
2500 // closure are detected as upvars rather than normal closure arg usages.
2501 ExprKind::Closure(_, Async::Yes { .. }, _, ref fn_decl, ref body, _span) => {
2502 self.with_rib(ValueNS, NormalRibKind, |this| {
2503 this.with_label_rib(ClosureOrAsyncRibKind, |this| {
2504 // Resolve arguments:
2505 this.resolve_params(&fn_decl.inputs);
2506 // No need to resolve return type --
2507 // the outer closure return type is `FnRetTy::Default`.
2509 // Now resolve the inner closure
2511 // No need to resolve arguments: the inner closure has none.
2512 // Resolve the return type:
2513 visit::walk_fn_ret_ty(this, &fn_decl.output);
2515 this.visit_expr(body);
2520 ExprKind::Async(..) | ExprKind::Closure(..) => {
2521 self.with_label_rib(ClosureOrAsyncRibKind, |this| visit::walk_expr(this, expr));
2523 ExprKind::Repeat(ref elem, ref ct) => {
2524 self.visit_expr(elem);
2525 self.resolve_anon_const(ct, IsRepeatExpr::Yes);
2527 ExprKind::Index(ref elem, ref idx) => {
2528 self.resolve_expr(elem, Some(expr));
2529 self.visit_expr(idx);
2532 visit::walk_expr(self, expr);
2537 fn record_candidate_traits_for_expr_if_necessary(&mut self, expr: &'ast Expr) {
2539 ExprKind::Field(_, ident) => {
2540 // FIXME(#6890): Even though you can't treat a method like a
2541 // field, we need to add any trait methods we find that match
2542 // the field name so that we can do some nice error reporting
2543 // later on in typeck.
2544 let traits = self.traits_in_scope(ident, ValueNS);
2545 self.r.trait_map.insert(expr.id, traits);
2547 ExprKind::MethodCall(ref segment, ..) => {
2548 debug!("(recording candidate traits for expr) recording traits for {}", expr.id);
2549 let traits = self.traits_in_scope(segment.ident, ValueNS);
2550 self.r.trait_map.insert(expr.id, traits);
2558 fn traits_in_scope(&mut self, ident: Ident, ns: Namespace) -> Vec<TraitCandidate> {
2559 self.r.traits_in_scope(
2560 self.current_trait_ref.as_ref().map(|(module, _)| *module),
2563 Some((ident.name, ns)),
2567 fn compute_num_lifetime_params(&mut self, id: NodeId, generics: &Generics) {
2568 let def_id = self.r.local_def_id(id);
2569 let count = generics
2572 .filter(|param| matches!(param.kind, ast::GenericParamKind::Lifetime { .. }))
2574 self.r.item_generics_num_lifetimes.insert(def_id, count);
2578 impl<'a> Resolver<'a> {
2579 pub(crate) fn late_resolve_crate(&mut self, krate: &Crate) {
2580 let mut late_resolution_visitor = LateResolutionVisitor::new(self);
2581 visit::walk_crate(&mut late_resolution_visitor, krate);
2582 for (id, span) in late_resolution_visitor.diagnostic_metadata.unused_labels.iter() {
2583 self.lint_buffer.buffer_lint(lint::builtin::UNUSED_LABELS, *id, *span, "unused label");