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, NameBindingKind, ParentScope, PathResult};
12 use crate::{ResolutionError, Resolver, Segment, UseError};
14 use rustc_ast::ast::*;
15 use rustc_ast::ptr::P;
16 use rustc_ast::visit::{self, AssocCtxt, FnCtxt, FnKind, Visitor};
17 use rustc_ast::{unwrap_or, walk_list};
18 use rustc_ast_lowering::ResolverAstLowering;
19 use rustc_data_structures::fx::{FxHashMap, FxHashSet};
20 use rustc_errors::DiagnosticId;
21 use rustc_hir::def::Namespace::{self, *};
22 use rustc_hir::def::{self, CtorKind, DefKind, PartialRes, PerNS};
23 use rustc_hir::def_id::{DefId, CRATE_DEF_INDEX};
24 use rustc_hir::TraitCandidate;
25 use rustc_middle::{bug, span_bug};
26 use rustc_session::lint;
27 use rustc_span::def_id::LocalDefId;
28 use rustc_span::symbol::{kw, sym, Ident, Symbol};
30 use smallvec::{smallvec, SmallVec};
33 use rustc_span::source_map::{respan, Spanned};
34 use std::collections::BTreeSet;
35 use std::mem::{replace, take};
40 type Res = def::Res<NodeId>;
42 type IdentMap<T> = FxHashMap<Ident, T>;
44 /// Map from the name in a pattern to its binding mode.
45 type BindingMap = IdentMap<BindingInfo>;
47 #[derive(Copy, Clone, Debug)]
50 binding_mode: BindingMode,
53 #[derive(Copy, Clone, PartialEq, Eq, Debug)]
62 fn descr(self) -> &'static str {
64 PatternSource::Match => "match binding",
65 PatternSource::Let => "let binding",
66 PatternSource::For => "for binding",
67 PatternSource::FnParam => "function parameter",
72 /// Denotes whether the context for the set of already bound bindings is a `Product`
73 /// or `Or` context. This is used in e.g., `fresh_binding` and `resolve_pattern_inner`.
74 /// See those functions for more information.
77 /// A product pattern context, e.g., `Variant(a, b)`.
79 /// An or-pattern context, e.g., `p_0 | ... | p_n`.
83 /// Does this the item (from the item rib scope) allow generic parameters?
84 #[derive(Copy, Clone, Debug, Eq, PartialEq)]
85 crate enum HasGenericParams {
90 /// The rib kind restricts certain accesses,
91 /// e.g. to a `Res::Local` of an outer item.
92 #[derive(Copy, Clone, Debug)]
93 crate enum RibKind<'a> {
94 /// No restriction needs to be applied.
97 /// We passed through an impl or trait and are now in one of its
98 /// methods or associated types. Allow references to ty params that impl or trait
99 /// binds. Disallow any other upvars (including other ty params that are
103 /// We passed through a closure. Disallow labels.
104 ClosureOrAsyncRibKind,
106 /// We passed through a function definition. Disallow upvars.
107 /// Permit only those const parameters that are specified in the function's generics.
110 /// We passed through an item scope. Disallow upvars.
111 ItemRibKind(HasGenericParams),
113 /// We're in a constant item. Can't refer to dynamic stuff.
114 ConstantItemRibKind(bool),
116 /// We passed through a module.
117 ModuleRibKind(Module<'a>),
119 /// We passed through a `macro_rules!` statement
120 MacroDefinition(DefId),
122 /// All bindings in this rib are type parameters that can't be used
123 /// from the default of a type parameter because they're not declared
124 /// before said type parameter. Also see the `visit_generics` override.
125 ForwardTyParamBanRibKind,
127 /// We are inside of the type of a const parameter. Can't refer to any
133 /// Whether this rib kind contains generic parameters, as opposed to local
135 crate fn contains_params(&self) -> bool {
138 | ClosureOrAsyncRibKind
140 | ConstantItemRibKind(_)
143 | ConstParamTyRibKind => false,
144 AssocItemRibKind | ItemRibKind(_) | ForwardTyParamBanRibKind => true,
149 /// A single local scope.
151 /// A rib represents a scope names can live in. Note that these appear in many places, not just
152 /// around braces. At any place where the list of accessible names (of the given namespace)
153 /// changes or a new restrictions on the name accessibility are introduced, a new rib is put onto a
154 /// stack. This may be, for example, a `let` statement (because it introduces variables), a macro,
157 /// Different [rib kinds](enum.RibKind) are transparent for different names.
159 /// The resolution keeps a separate stack of ribs as it traverses the AST for each namespace. When
160 /// resolving, the name is looked up from inside out.
162 crate struct Rib<'a, R = Res> {
163 pub bindings: IdentMap<R>,
164 pub kind: RibKind<'a>,
167 impl<'a, R> Rib<'a, R> {
168 fn new(kind: RibKind<'a>) -> Rib<'a, R> {
169 Rib { bindings: Default::default(), kind }
173 #[derive(Copy, Clone, PartialEq, Eq, Debug)]
174 crate enum AliasPossibility {
179 #[derive(Copy, Clone, Debug)]
180 crate enum PathSource<'a> {
181 // Type paths `Path`.
183 // Trait paths in bounds or impls.
184 Trait(AliasPossibility),
185 // Expression paths `path`, with optional parent context.
186 Expr(Option<&'a Expr>),
187 // Paths in path patterns `Path`.
189 // Paths in struct expressions and patterns `Path { .. }`.
191 // Paths in tuple struct patterns `Path(..)`.
193 // `m::A::B` in `<T as m::A>::B::C`.
194 TraitItem(Namespace),
197 impl<'a> PathSource<'a> {
198 fn namespace(self) -> Namespace {
200 PathSource::Type | PathSource::Trait(_) | PathSource::Struct => TypeNS,
201 PathSource::Expr(..) | PathSource::Pat | PathSource::TupleStruct(_) => ValueNS,
202 PathSource::TraitItem(ns) => ns,
206 fn defer_to_typeck(self) -> bool {
209 | PathSource::Expr(..)
212 | PathSource::TupleStruct(_) => true,
213 PathSource::Trait(_) | PathSource::TraitItem(..) => false,
217 fn descr_expected(self) -> &'static str {
219 PathSource::Type => "type",
220 PathSource::Trait(_) => "trait",
221 PathSource::Pat => "unit struct, unit variant or constant",
222 PathSource::Struct => "struct, variant or union type",
223 PathSource::TupleStruct(_) => "tuple struct or tuple variant",
224 PathSource::TraitItem(ns) => match ns {
225 TypeNS => "associated type",
226 ValueNS => "method or associated constant",
227 MacroNS => bug!("associated macro"),
229 PathSource::Expr(parent) => match parent.as_ref().map(|p| &p.kind) {
230 // "function" here means "anything callable" rather than `DefKind::Fn`,
231 // this is not precise but usually more helpful than just "value".
232 Some(ExprKind::Call(call_expr, _)) => match &call_expr.kind {
233 ExprKind::Path(_, path) => {
234 let mut msg = "function";
235 if let Some(segment) = path.segments.iter().last() {
236 if let Some(c) = segment.ident.to_string().chars().next() {
237 if c.is_uppercase() {
238 msg = "function, tuple struct or tuple variant";
251 fn is_call(self) -> bool {
253 PathSource::Expr(Some(&Expr { kind: ExprKind::Call(..), .. })) => true,
258 crate fn is_expected(self, res: Res) -> bool {
260 PathSource::Type => match res {
266 | DefKind::TraitAlias
271 | DefKind::ForeignTy,
275 | Res::SelfTy(..) => true,
278 PathSource::Trait(AliasPossibility::No) => match res {
279 Res::Def(DefKind::Trait, _) => true,
282 PathSource::Trait(AliasPossibility::Maybe) => match res {
283 Res::Def(DefKind::Trait | DefKind::TraitAlias, _) => true,
286 PathSource::Expr(..) => match res {
288 DefKind::Ctor(_, CtorKind::Const | CtorKind::Fn)
293 | DefKind::AssocConst
294 | DefKind::ConstParam,
298 | Res::SelfCtor(..) => true,
301 PathSource::Pat => match res {
303 DefKind::Ctor(_, CtorKind::Const) | DefKind::Const | DefKind::AssocConst,
306 | Res::SelfCtor(..) => true,
309 PathSource::TupleStruct(_) => match res {
310 Res::Def(DefKind::Ctor(_, CtorKind::Fn), _) | Res::SelfCtor(..) => true,
313 PathSource::Struct => match res {
322 | Res::SelfTy(..) => true,
325 PathSource::TraitItem(ns) => match res {
326 Res::Def(DefKind::AssocConst | DefKind::AssocFn, _) if ns == ValueNS => true,
327 Res::Def(DefKind::AssocTy, _) if ns == TypeNS => true,
333 fn error_code(self, has_unexpected_resolution: bool) -> DiagnosticId {
334 use rustc_errors::error_code;
335 match (self, has_unexpected_resolution) {
336 (PathSource::Trait(_), true) => error_code!(E0404),
337 (PathSource::Trait(_), false) => error_code!(E0405),
338 (PathSource::Type, true) => error_code!(E0573),
339 (PathSource::Type, false) => error_code!(E0412),
340 (PathSource::Struct, true) => error_code!(E0574),
341 (PathSource::Struct, false) => error_code!(E0422),
342 (PathSource::Expr(..), true) => error_code!(E0423),
343 (PathSource::Expr(..), false) => error_code!(E0425),
344 (PathSource::Pat | PathSource::TupleStruct(_), true) => error_code!(E0532),
345 (PathSource::Pat | PathSource::TupleStruct(_), false) => error_code!(E0531),
346 (PathSource::TraitItem(..), true) => error_code!(E0575),
347 (PathSource::TraitItem(..), false) => error_code!(E0576),
353 struct DiagnosticMetadata<'ast> {
354 /// The current trait's associated types' ident, used for diagnostic suggestions.
355 current_trait_assoc_types: Vec<Ident>,
357 /// The current self type if inside an impl (used for better errors).
358 current_self_type: Option<Ty>,
360 /// The current self item if inside an ADT (used for better errors).
361 current_self_item: Option<NodeId>,
363 /// The current trait (used to suggest).
364 current_item: Option<&'ast Item>,
366 /// When processing generics and encountering a type not found, suggest introducing a type
368 currently_processing_generics: bool,
370 /// The current enclosing function (used for better errors).
371 current_function: Option<(FnKind<'ast>, Span)>,
373 /// A list of labels as of yet unused. Labels will be removed from this map when
374 /// they are used (in a `break` or `continue` statement)
375 unused_labels: FxHashMap<NodeId, Span>,
377 /// Only used for better errors on `fn(): fn()`.
378 current_type_ascription: Vec<Span>,
380 /// Only used for better errors on `let <pat>: <expr, not type>;`.
381 current_let_binding: Option<(Span, Option<Span>, Option<Span>)>,
384 struct LateResolutionVisitor<'a, 'b, 'ast> {
385 r: &'b mut Resolver<'a>,
387 /// The module that represents the current item scope.
388 parent_scope: ParentScope<'a>,
390 /// The current set of local scopes for types and values.
391 /// FIXME #4948: Reuse ribs to avoid allocation.
392 ribs: PerNS<Vec<Rib<'a>>>,
394 /// The current set of local scopes, for labels.
395 label_ribs: Vec<Rib<'a, NodeId>>,
397 /// The trait that the current context can refer to.
398 current_trait_ref: Option<(Module<'a>, TraitRef)>,
400 /// Fields used to add information to diagnostic errors.
401 diagnostic_metadata: DiagnosticMetadata<'ast>,
403 /// State used to know whether to ignore resolution errors for function bodies.
405 /// In particular, rustdoc uses this to avoid giving errors for `cfg()` items.
406 /// In most cases this will be `None`, in which case errors will always be reported.
407 /// If it is `Some(_)`, then it will be updated when entering a nested function or trait body.
411 /// Walks the whole crate in DFS order, visiting each item, resolving names as it goes.
412 impl<'a, 'ast> Visitor<'ast> for LateResolutionVisitor<'a, '_, 'ast> {
413 fn visit_item(&mut self, item: &'ast Item) {
414 let prev = replace(&mut self.diagnostic_metadata.current_item, Some(item));
415 // Always report errors in items we just entered.
416 let old_ignore = replace(&mut self.in_func_body, false);
417 self.resolve_item(item);
418 self.in_func_body = old_ignore;
419 self.diagnostic_metadata.current_item = prev;
421 fn visit_arm(&mut self, arm: &'ast Arm) {
422 self.resolve_arm(arm);
424 fn visit_block(&mut self, block: &'ast Block) {
425 self.resolve_block(block);
427 fn visit_anon_const(&mut self, constant: &'ast AnonConst) {
428 debug!("visit_anon_const {:?}", constant);
429 self.with_constant_rib(constant.value.is_potential_trivial_const_param(), |this| {
430 visit::walk_anon_const(this, constant);
433 fn visit_expr(&mut self, expr: &'ast Expr) {
434 self.resolve_expr(expr, None);
436 fn visit_local(&mut self, local: &'ast Local) {
437 let local_spans = match local.pat.kind {
438 // We check for this to avoid tuple struct fields.
439 PatKind::Wild => None,
442 local.ty.as_ref().map(|ty| ty.span),
443 local.init.as_ref().map(|init| init.span),
446 let original = replace(&mut self.diagnostic_metadata.current_let_binding, local_spans);
447 self.resolve_local(local);
448 self.diagnostic_metadata.current_let_binding = original;
450 fn visit_ty(&mut self, ty: &'ast Ty) {
452 TyKind::Path(ref qself, ref path) => {
453 self.smart_resolve_path(ty.id, qself.as_ref(), path, PathSource::Type);
455 TyKind::ImplicitSelf => {
456 let self_ty = Ident::with_dummy_span(kw::SelfUpper);
458 .resolve_ident_in_lexical_scope(self_ty, TypeNS, Some(ty.id), ty.span)
459 .map_or(Res::Err, |d| d.res());
460 self.r.record_partial_res(ty.id, PartialRes::new(res));
464 visit::walk_ty(self, ty);
466 fn visit_poly_trait_ref(&mut self, tref: &'ast PolyTraitRef, m: &'ast TraitBoundModifier) {
467 self.smart_resolve_path(
468 tref.trait_ref.ref_id,
470 &tref.trait_ref.path,
471 PathSource::Trait(AliasPossibility::Maybe),
473 visit::walk_poly_trait_ref(self, tref, m);
475 fn visit_foreign_item(&mut self, foreign_item: &'ast ForeignItem) {
476 match foreign_item.kind {
477 ForeignItemKind::Fn(_, _, ref generics, _)
478 | ForeignItemKind::TyAlias(_, ref generics, ..) => {
479 self.with_generic_param_rib(generics, ItemRibKind(HasGenericParams::Yes), |this| {
480 visit::walk_foreign_item(this, foreign_item);
483 ForeignItemKind::Static(..) => {
484 self.with_item_rib(HasGenericParams::No, |this| {
485 visit::walk_foreign_item(this, foreign_item);
488 ForeignItemKind::MacCall(..) => {
489 visit::walk_foreign_item(self, foreign_item);
493 fn visit_fn(&mut self, fn_kind: FnKind<'ast>, sp: Span, _: NodeId) {
494 let rib_kind = match fn_kind {
495 // Bail if there's no body.
496 FnKind::Fn(.., None) => return visit::walk_fn(self, fn_kind, sp),
497 FnKind::Fn(FnCtxt::Free | FnCtxt::Foreign, ..) => FnItemRibKind,
498 FnKind::Fn(FnCtxt::Assoc(_), ..) => NormalRibKind,
499 FnKind::Closure(..) => ClosureOrAsyncRibKind,
502 replace(&mut self.diagnostic_metadata.current_function, Some((fn_kind, sp)));
503 debug!("(resolving function) entering function");
504 let declaration = fn_kind.decl();
506 // Create a value rib for the function.
507 self.with_rib(ValueNS, rib_kind, |this| {
508 // Create a label rib for the function.
509 this.with_label_rib(rib_kind, |this| {
510 // Add each argument to the rib.
511 this.resolve_params(&declaration.inputs);
513 visit::walk_fn_ret_ty(this, &declaration.output);
515 // Ignore errors in function bodies if this is rustdoc
516 // Be sure not to set this until the function signature has been resolved.
517 let previous_state = replace(&mut this.in_func_body, true);
518 // Resolve the function body, potentially inside the body of an async closure
520 FnKind::Fn(.., body) => walk_list!(this, visit_block, body),
521 FnKind::Closure(_, body) => this.visit_expr(body),
524 debug!("(resolving function) leaving function");
525 this.in_func_body = previous_state;
528 self.diagnostic_metadata.current_function = previous_value;
531 fn visit_generics(&mut self, generics: &'ast Generics) {
532 // For type parameter defaults, we have to ban access
533 // to following type parameters, as the InternalSubsts can only
534 // provide previous type parameters as they're built. We
535 // put all the parameters on the ban list and then remove
536 // them one by one as they are processed and become available.
537 let mut default_ban_rib = Rib::new(ForwardTyParamBanRibKind);
538 let mut found_default = false;
539 default_ban_rib.bindings.extend(generics.params.iter().filter_map(
540 |param| match param.kind {
541 GenericParamKind::Const { .. } | GenericParamKind::Lifetime { .. } => None,
542 GenericParamKind::Type { ref default, .. } => {
543 found_default |= default.is_some();
544 found_default.then_some((Ident::with_dummy_span(param.ident.name), Res::Err))
549 // rust-lang/rust#61631: The type `Self` is essentially
550 // another type parameter. For ADTs, we consider it
551 // well-defined only after all of the ADT type parameters have
552 // been provided. Therefore, we do not allow use of `Self`
553 // anywhere in ADT type parameter defaults.
555 // (We however cannot ban `Self` for defaults on *all* generic
556 // lists; e.g. trait generics can usefully refer to `Self`,
557 // such as in the case of `trait Add<Rhs = Self>`.)
558 if self.diagnostic_metadata.current_self_item.is_some() {
559 // (`Some` if + only if we are in ADT's generics.)
560 default_ban_rib.bindings.insert(Ident::with_dummy_span(kw::SelfUpper), Res::Err);
563 for param in &generics.params {
565 GenericParamKind::Lifetime => self.visit_generic_param(param),
566 GenericParamKind::Type { ref default } => {
567 for bound in ¶m.bounds {
568 self.visit_param_bound(bound);
571 if let Some(ref ty) = default {
572 self.ribs[TypeNS].push(default_ban_rib);
573 self.with_rib(ValueNS, ForwardTyParamBanRibKind, |this| {
574 // HACK: We use an empty `ForwardTyParamBanRibKind` here which
575 // is only used to forbid the use of const parameters inside of
578 // While the rib name doesn't really fit here, it does allow us to use the same
579 // code for both const and type parameters.
582 default_ban_rib = self.ribs[TypeNS].pop().unwrap();
585 // Allow all following defaults to refer to this type parameter.
586 default_ban_rib.bindings.remove(&Ident::with_dummy_span(param.ident.name));
588 GenericParamKind::Const { ref ty, kw_span: _ } => {
589 for bound in ¶m.bounds {
590 self.visit_param_bound(bound);
592 self.ribs[TypeNS].push(Rib::new(ConstParamTyRibKind));
593 self.ribs[ValueNS].push(Rib::new(ConstParamTyRibKind));
595 self.ribs[TypeNS].pop().unwrap();
596 self.ribs[ValueNS].pop().unwrap();
600 for p in &generics.where_clause.predicates {
601 self.visit_where_predicate(p);
605 fn visit_generic_arg(&mut self, arg: &'ast GenericArg) {
606 debug!("visit_generic_arg({:?})", arg);
607 let prev = replace(&mut self.diagnostic_metadata.currently_processing_generics, true);
609 GenericArg::Type(ref ty) => {
610 // We parse const arguments as path types as we cannot distinguish them during
611 // parsing. We try to resolve that ambiguity by attempting resolution the type
612 // namespace first, and if that fails we try again in the value namespace. If
613 // resolution in the value namespace succeeds, we have an generic const argument on
615 if let TyKind::Path(ref qself, ref path) = ty.kind {
616 // We cannot disambiguate multi-segment paths right now as that requires type
618 if path.segments.len() == 1 && path.segments[0].args.is_none() {
619 let mut check_ns = |ns| {
620 self.resolve_ident_in_lexical_scope(
621 path.segments[0].ident,
628 if !check_ns(TypeNS) && check_ns(ValueNS) {
629 // This must be equivalent to `visit_anon_const`, but we cannot call it
630 // directly due to visitor lifetimes so we have to copy-paste some code.
631 self.with_constant_rib(true, |this| {
632 this.smart_resolve_path(
636 PathSource::Expr(None),
639 if let Some(ref qself) = *qself {
640 this.visit_ty(&qself.ty);
642 this.visit_path(path, ty.id);
645 self.diagnostic_metadata.currently_processing_generics = prev;
653 GenericArg::Lifetime(lt) => self.visit_lifetime(lt),
654 GenericArg::Const(ct) => self.visit_anon_const(ct),
656 self.diagnostic_metadata.currently_processing_generics = prev;
660 impl<'a, 'b, 'ast> LateResolutionVisitor<'a, 'b, 'ast> {
661 fn new(resolver: &'b mut Resolver<'a>) -> LateResolutionVisitor<'a, 'b, 'ast> {
662 // During late resolution we only track the module component of the parent scope,
663 // although it may be useful to track other components as well for diagnostics.
664 let graph_root = resolver.graph_root;
665 let parent_scope = ParentScope::module(graph_root);
666 let start_rib_kind = ModuleRibKind(graph_root);
667 LateResolutionVisitor {
671 value_ns: vec![Rib::new(start_rib_kind)],
672 type_ns: vec![Rib::new(start_rib_kind)],
673 macro_ns: vec![Rib::new(start_rib_kind)],
675 label_ribs: Vec::new(),
676 current_trait_ref: None,
677 diagnostic_metadata: DiagnosticMetadata::default(),
678 // errors at module scope should always be reported
683 fn resolve_ident_in_lexical_scope(
687 record_used_id: Option<NodeId>,
689 ) -> Option<LexicalScopeBinding<'a>> {
690 self.r.resolve_ident_in_lexical_scope(
703 opt_ns: Option<Namespace>, // `None` indicates a module path in import
706 crate_lint: CrateLint,
707 ) -> PathResult<'a> {
708 self.r.resolve_path_with_ribs(
721 // We maintain a list of value ribs and type ribs.
723 // Simultaneously, we keep track of the current position in the module
724 // graph in the `parent_scope.module` pointer. When we go to resolve a name in
725 // the value or type namespaces, we first look through all the ribs and
726 // then query the module graph. When we resolve a name in the module
727 // namespace, we can skip all the ribs (since nested modules are not
728 // allowed within blocks in Rust) and jump straight to the current module
731 // Named implementations are handled separately. When we find a method
732 // call, we consult the module node to find all of the implementations in
733 // scope. This information is lazily cached in the module node. We then
734 // generate a fake "implementation scope" containing all the
735 // implementations thus found, for compatibility with old resolve pass.
737 /// Do some `work` within a new innermost rib of the given `kind` in the given namespace (`ns`).
742 work: impl FnOnce(&mut Self) -> T,
744 self.ribs[ns].push(Rib::new(kind));
745 let ret = work(self);
750 fn with_scope<T>(&mut self, id: NodeId, f: impl FnOnce(&mut Self) -> T) -> T {
751 let id = self.r.local_def_id(id);
752 let module = self.r.module_map.get(&id).cloned(); // clones a reference
753 if let Some(module) = module {
754 // Move down in the graph.
755 let orig_module = replace(&mut self.parent_scope.module, module);
756 self.with_rib(ValueNS, ModuleRibKind(module), |this| {
757 this.with_rib(TypeNS, ModuleRibKind(module), |this| {
759 this.parent_scope.module = orig_module;
768 /// Searches the current set of local scopes for labels. Returns the `NodeId` of the resolved
769 /// label and reports an error if the label is not found or is unreachable.
770 fn resolve_label(&self, mut label: Ident) -> Option<NodeId> {
771 let mut suggestion = None;
773 // Preserve the original span so that errors contain "in this macro invocation"
775 let original_span = label.span;
777 for i in (0..self.label_ribs.len()).rev() {
778 let rib = &self.label_ribs[i];
780 if let MacroDefinition(def) = rib.kind {
781 // If an invocation of this macro created `ident`, give up on `ident`
782 // and switch to `ident`'s source from the macro definition.
783 if def == self.r.macro_def(label.span.ctxt()) {
784 label.span.remove_mark();
788 let ident = label.normalize_to_macro_rules();
789 if let Some((ident, id)) = rib.bindings.get_key_value(&ident) {
790 return if self.is_label_valid_from_rib(i) {
795 ResolutionError::UnreachableLabel {
797 definition_span: ident.span,
806 // Diagnostics: Check if this rib contains a label with a similar name, keep track of
807 // the first such label that is encountered.
808 suggestion = suggestion.or_else(|| self.suggestion_for_label_in_rib(i, label));
813 ResolutionError::UndeclaredLabel { name: label.name, suggestion },
818 /// Determine whether or not a label from the `rib_index`th label rib is reachable.
819 fn is_label_valid_from_rib(&self, rib_index: usize) -> bool {
820 let ribs = &self.label_ribs[rib_index + 1..];
824 NormalRibKind | MacroDefinition(..) => {
825 // Nothing to do. Continue.
829 | ClosureOrAsyncRibKind
832 | ConstantItemRibKind(_)
834 | ForwardTyParamBanRibKind
835 | ConstParamTyRibKind => {
844 fn resolve_adt(&mut self, item: &'ast Item, generics: &'ast Generics) {
845 debug!("resolve_adt");
846 self.with_current_self_item(item, |this| {
847 this.with_generic_param_rib(generics, ItemRibKind(HasGenericParams::Yes), |this| {
848 let item_def_id = this.r.local_def_id(item.id).to_def_id();
849 this.with_self_rib(Res::SelfTy(None, Some(item_def_id)), |this| {
850 visit::walk_item(this, item);
856 fn future_proof_import(&mut self, use_tree: &UseTree) {
857 let segments = &use_tree.prefix.segments;
858 if !segments.is_empty() {
859 let ident = segments[0].ident;
860 if ident.is_path_segment_keyword() || ident.span.rust_2015() {
864 let nss = match use_tree.kind {
865 UseTreeKind::Simple(..) if segments.len() == 1 => &[TypeNS, ValueNS][..],
868 let report_error = |this: &Self, ns| {
869 let what = if ns == TypeNS { "type parameters" } else { "local variables" };
870 if this.should_report_errs() {
873 .span_err(ident.span, &format!("imports cannot refer to {}", what));
878 match self.resolve_ident_in_lexical_scope(ident, ns, None, use_tree.prefix.span) {
879 Some(LexicalScopeBinding::Res(..)) => {
880 report_error(self, ns);
882 Some(LexicalScopeBinding::Item(binding)) => {
883 let orig_unusable_binding =
884 replace(&mut self.r.unusable_binding, Some(binding));
885 if let Some(LexicalScopeBinding::Res(..)) = self
886 .resolve_ident_in_lexical_scope(ident, ns, None, use_tree.prefix.span)
888 report_error(self, ns);
890 self.r.unusable_binding = orig_unusable_binding;
895 } else if let UseTreeKind::Nested(use_trees) = &use_tree.kind {
896 for (use_tree, _) in use_trees {
897 self.future_proof_import(use_tree);
902 fn resolve_item(&mut self, item: &'ast Item) {
903 let name = item.ident.name;
904 debug!("(resolving item) resolving {} ({:?})", name, item.kind);
907 ItemKind::TyAlias(_, ref generics, _, _) | ItemKind::Fn(_, _, ref generics, _) => {
908 self.with_generic_param_rib(generics, ItemRibKind(HasGenericParams::Yes), |this| {
909 visit::walk_item(this, item)
913 ItemKind::Enum(_, ref generics)
914 | ItemKind::Struct(_, ref generics)
915 | ItemKind::Union(_, ref generics) => {
916 self.resolve_adt(item, generics);
923 items: ref impl_items,
926 self.resolve_implementation(generics, of_trait, &self_ty, item.id, impl_items);
929 ItemKind::Trait(.., ref generics, ref bounds, ref trait_items) => {
930 // Create a new rib for the trait-wide type parameters.
931 self.with_generic_param_rib(generics, ItemRibKind(HasGenericParams::Yes), |this| {
932 let local_def_id = this.r.local_def_id(item.id).to_def_id();
933 this.with_self_rib(Res::SelfTy(Some(local_def_id), None), |this| {
934 this.visit_generics(generics);
935 walk_list!(this, visit_param_bound, bounds);
937 let walk_assoc_item = |this: &mut Self, generics, item| {
938 this.with_generic_param_rib(generics, AssocItemRibKind, |this| {
939 visit::walk_assoc_item(this, item, AssocCtxt::Trait)
943 for item in trait_items {
944 this.with_trait_items(trait_items, |this| {
946 AssocItemKind::Const(_, ty, default) => {
948 // Only impose the restrictions of `ConstRibKind` for an
949 // actual constant expression in a provided default.
950 if let Some(expr) = default {
951 // We allow arbitrary const expressions inside of associated consts,
952 // even if they are potentially not const evaluatable.
954 // Type parameters can already be used and as associated consts are
955 // not used as part of the type system, this is far less surprising.
956 this.with_constant_rib(true, |this| {
957 this.visit_expr(expr)
961 AssocItemKind::Fn(_, _, generics, _) => {
962 walk_assoc_item(this, generics, item);
964 AssocItemKind::TyAlias(_, generics, _, _) => {
965 walk_assoc_item(this, generics, item);
967 AssocItemKind::MacCall(_) => {
968 panic!("unexpanded macro in resolve!")
977 ItemKind::TraitAlias(ref generics, ref bounds) => {
978 // Create a new rib for the trait-wide type parameters.
979 self.with_generic_param_rib(generics, ItemRibKind(HasGenericParams::Yes), |this| {
980 let local_def_id = this.r.local_def_id(item.id).to_def_id();
981 this.with_self_rib(Res::SelfTy(Some(local_def_id), None), |this| {
982 this.visit_generics(generics);
983 walk_list!(this, visit_param_bound, bounds);
988 ItemKind::Mod(_) | ItemKind::ForeignMod(_) => {
989 self.with_scope(item.id, |this| {
990 visit::walk_item(this, item);
994 ItemKind::Static(ref ty, _, ref expr) | ItemKind::Const(_, ref ty, ref expr) => {
995 debug!("resolve_item ItemKind::Const");
996 self.with_item_rib(HasGenericParams::No, |this| {
998 if let Some(expr) = expr {
999 this.with_constant_rib(expr.is_potential_trivial_const_param(), |this| {
1000 this.visit_expr(expr)
1006 ItemKind::Use(ref use_tree) => {
1007 self.future_proof_import(use_tree);
1010 ItemKind::ExternCrate(..) | ItemKind::MacroDef(..) | ItemKind::GlobalAsm(..) => {
1011 // do nothing, these are just around to be encoded
1014 ItemKind::MacCall(_) => panic!("unexpanded macro in resolve!"),
1018 fn with_generic_param_rib<'c, F>(&'c mut self, generics: &'c Generics, kind: RibKind<'a>, f: F)
1020 F: FnOnce(&mut Self),
1022 debug!("with_generic_param_rib");
1023 let mut function_type_rib = Rib::new(kind);
1024 let mut function_value_rib = Rib::new(kind);
1025 let mut seen_bindings = FxHashMap::default();
1027 // We also can't shadow bindings from the parent item
1028 if let AssocItemRibKind = kind {
1029 let mut add_bindings_for_ns = |ns| {
1030 let parent_rib = self.ribs[ns]
1032 .rfind(|r| if let ItemRibKind(_) = r.kind { true } else { false })
1033 .expect("associated item outside of an item");
1035 .extend(parent_rib.bindings.iter().map(|(ident, _)| (*ident, ident.span)));
1037 add_bindings_for_ns(ValueNS);
1038 add_bindings_for_ns(TypeNS);
1041 for param in &generics.params {
1042 if let GenericParamKind::Lifetime { .. } = param.kind {
1046 let def_kind = match param.kind {
1047 GenericParamKind::Type { .. } => DefKind::TyParam,
1048 GenericParamKind::Const { .. } => DefKind::ConstParam,
1049 _ => unreachable!(),
1052 let ident = param.ident.normalize_to_macros_2_0();
1053 debug!("with_generic_param_rib: {}", param.id);
1055 if seen_bindings.contains_key(&ident) {
1056 let span = seen_bindings.get(&ident).unwrap();
1057 let err = ResolutionError::NameAlreadyUsedInParameterList(ident.name, *span);
1058 self.report_error(param.ident.span, err);
1060 seen_bindings.entry(ident).or_insert(param.ident.span);
1062 // Plain insert (no renaming).
1063 let res = Res::Def(def_kind, self.r.local_def_id(param.id).to_def_id());
1066 GenericParamKind::Type { .. } => {
1067 function_type_rib.bindings.insert(ident, res);
1068 self.r.record_partial_res(param.id, PartialRes::new(res));
1070 GenericParamKind::Const { .. } => {
1071 function_value_rib.bindings.insert(ident, res);
1072 self.r.record_partial_res(param.id, PartialRes::new(res));
1074 _ => unreachable!(),
1078 self.ribs[ValueNS].push(function_value_rib);
1079 self.ribs[TypeNS].push(function_type_rib);
1083 self.ribs[TypeNS].pop();
1084 self.ribs[ValueNS].pop();
1087 fn with_label_rib(&mut self, kind: RibKind<'a>, f: impl FnOnce(&mut Self)) {
1088 self.label_ribs.push(Rib::new(kind));
1090 self.label_ribs.pop();
1093 fn with_item_rib(&mut self, has_generic_params: HasGenericParams, f: impl FnOnce(&mut Self)) {
1094 let kind = ItemRibKind(has_generic_params);
1095 self.with_rib(ValueNS, kind, |this| this.with_rib(TypeNS, kind, f))
1098 fn with_constant_rib(&mut self, trivial: bool, f: impl FnOnce(&mut Self)) {
1099 debug!("with_constant_rib");
1100 self.with_rib(ValueNS, ConstantItemRibKind(trivial), |this| {
1101 this.with_rib(TypeNS, ConstantItemRibKind(trivial), |this| {
1102 this.with_label_rib(ConstantItemRibKind(trivial), f);
1107 fn with_current_self_type<T>(&mut self, self_type: &Ty, f: impl FnOnce(&mut Self) -> T) -> T {
1108 // Handle nested impls (inside fn bodies)
1109 let previous_value =
1110 replace(&mut self.diagnostic_metadata.current_self_type, Some(self_type.clone()));
1111 let result = f(self);
1112 self.diagnostic_metadata.current_self_type = previous_value;
1116 fn with_current_self_item<T>(&mut self, self_item: &Item, f: impl FnOnce(&mut Self) -> T) -> T {
1117 let previous_value =
1118 replace(&mut self.diagnostic_metadata.current_self_item, Some(self_item.id));
1119 let result = f(self);
1120 self.diagnostic_metadata.current_self_item = previous_value;
1124 /// When evaluating a `trait` use its associated types' idents for suggestionsa in E0412.
1125 fn with_trait_items<T>(
1127 trait_items: &Vec<P<AssocItem>>,
1128 f: impl FnOnce(&mut Self) -> T,
1130 let trait_assoc_types = replace(
1131 &mut self.diagnostic_metadata.current_trait_assoc_types,
1134 .filter_map(|item| match &item.kind {
1135 AssocItemKind::TyAlias(_, _, bounds, _) if bounds.is_empty() => {
1142 let result = f(self);
1143 self.diagnostic_metadata.current_trait_assoc_types = trait_assoc_types;
1147 /// This is called to resolve a trait reference from an `impl` (i.e., `impl Trait for Foo`).
1148 fn with_optional_trait_ref<T>(
1150 opt_trait_ref: Option<&TraitRef>,
1151 f: impl FnOnce(&mut Self, Option<DefId>) -> T,
1153 let mut new_val = None;
1154 let mut new_id = None;
1155 if let Some(trait_ref) = opt_trait_ref {
1156 let path: Vec<_> = Segment::from_path(&trait_ref.path);
1157 let res = self.smart_resolve_path_fragment(
1161 trait_ref.path.span,
1162 PathSource::Trait(AliasPossibility::No),
1163 CrateLint::SimplePath(trait_ref.ref_id),
1165 let res = res.base_res();
1166 if res != Res::Err {
1167 new_id = Some(res.def_id());
1168 let span = trait_ref.path.span;
1169 if let PathResult::Module(ModuleOrUniformRoot::Module(module)) = self.resolve_path(
1174 CrateLint::SimplePath(trait_ref.ref_id),
1176 new_val = Some((module, trait_ref.clone()));
1180 let original_trait_ref = replace(&mut self.current_trait_ref, new_val);
1181 let result = f(self, new_id);
1182 self.current_trait_ref = original_trait_ref;
1186 fn with_self_rib_ns(&mut self, ns: Namespace, self_res: Res, f: impl FnOnce(&mut Self)) {
1187 let mut self_type_rib = Rib::new(NormalRibKind);
1189 // Plain insert (no renaming, since types are not currently hygienic)
1190 self_type_rib.bindings.insert(Ident::with_dummy_span(kw::SelfUpper), self_res);
1191 self.ribs[ns].push(self_type_rib);
1193 self.ribs[ns].pop();
1196 fn with_self_rib(&mut self, self_res: Res, f: impl FnOnce(&mut Self)) {
1197 self.with_self_rib_ns(TypeNS, self_res, f)
1200 fn resolve_implementation(
1202 generics: &'ast Generics,
1203 opt_trait_reference: &'ast Option<TraitRef>,
1204 self_type: &'ast Ty,
1206 impl_items: &'ast [P<AssocItem>],
1208 debug!("resolve_implementation");
1209 // If applicable, create a rib for the type parameters.
1210 self.with_generic_param_rib(generics, ItemRibKind(HasGenericParams::Yes), |this| {
1211 // Dummy self type for better errors if `Self` is used in the trait path.
1212 this.with_self_rib(Res::SelfTy(None, None), |this| {
1213 // Resolve the trait reference, if necessary.
1214 this.with_optional_trait_ref(opt_trait_reference.as_ref(), |this, trait_id| {
1215 let item_def_id = this.r.local_def_id(item_id).to_def_id();
1216 this.with_self_rib(Res::SelfTy(trait_id, Some(item_def_id)), |this| {
1217 if let Some(trait_ref) = opt_trait_reference.as_ref() {
1218 // Resolve type arguments in the trait path.
1219 visit::walk_trait_ref(this, trait_ref);
1221 // Resolve the self type.
1222 this.visit_ty(self_type);
1223 // Resolve the generic parameters.
1224 this.visit_generics(generics);
1225 // Resolve the items within the impl.
1226 this.with_current_self_type(self_type, |this| {
1227 this.with_self_rib_ns(ValueNS, Res::SelfCtor(item_def_id), |this| {
1228 debug!("resolve_implementation with_self_rib_ns(ValueNS, ...)");
1229 for item in impl_items {
1230 use crate::ResolutionError::*;
1232 AssocItemKind::Const(_default, _ty, _expr) => {
1233 debug!("resolve_implementation AssocItemKind::Const",);
1234 // If this is a trait impl, ensure the const
1236 this.check_trait_item(
1240 |n, s| ConstNotMemberOfTrait(n, s),
1243 // We allow arbitrary const expressions inside of associated consts,
1244 // even if they are potentially not const evaluatable.
1246 // Type parameters can already be used and as associated consts are
1247 // not used as part of the type system, this is far less surprising.
1248 this.with_constant_rib(true, |this| {
1249 visit::walk_assoc_item(this, item, AssocCtxt::Impl)
1252 AssocItemKind::Fn(_, _, generics, _) => {
1253 // We also need a new scope for the impl item type parameters.
1254 this.with_generic_param_rib(
1258 // If this is a trait impl, ensure the method
1260 this.check_trait_item(
1264 |n, s| MethodNotMemberOfTrait(n, s),
1267 visit::walk_assoc_item(
1275 AssocItemKind::TyAlias(_, generics, _, _) => {
1276 // We also need a new scope for the impl item type parameters.
1277 this.with_generic_param_rib(
1281 // If this is a trait impl, ensure the type
1283 this.check_trait_item(
1287 |n, s| TypeNotMemberOfTrait(n, s),
1290 visit::walk_assoc_item(
1298 AssocItemKind::MacCall(_) => {
1299 panic!("unexpanded macro in resolve!")
1311 fn check_trait_item<F>(&mut self, ident: Ident, ns: Namespace, span: Span, err: F)
1313 F: FnOnce(Symbol, &str) -> ResolutionError<'_>,
1315 // If there is a TraitRef in scope for an impl, then the method must be in the
1317 if let Some((module, _)) = self.current_trait_ref {
1320 .resolve_ident_in_module(
1321 ModuleOrUniformRoot::Module(module),
1330 let path = &self.current_trait_ref.as_ref().unwrap().1.path;
1331 self.report_error(span, err(ident.name, &path_names_to_string(path)));
1336 fn resolve_params(&mut self, params: &'ast [Param]) {
1337 let mut bindings = smallvec![(PatBoundCtx::Product, Default::default())];
1338 for Param { pat, ty, .. } in params {
1339 self.resolve_pattern(pat, PatternSource::FnParam, &mut bindings);
1341 debug!("(resolving function / closure) recorded parameter");
1345 fn resolve_local(&mut self, local: &'ast Local) {
1346 debug!("resolving local ({:?})", local);
1347 // Resolve the type.
1348 walk_list!(self, visit_ty, &local.ty);
1350 // Resolve the initializer.
1351 walk_list!(self, visit_expr, &local.init);
1353 // Resolve the pattern.
1354 self.resolve_pattern_top(&local.pat, PatternSource::Let);
1357 /// build a map from pattern identifiers to binding-info's.
1358 /// this is done hygienically. This could arise for a macro
1359 /// that expands into an or-pattern where one 'x' was from the
1360 /// user and one 'x' came from the macro.
1361 fn binding_mode_map(&mut self, pat: &Pat) -> BindingMap {
1362 let mut binding_map = FxHashMap::default();
1364 pat.walk(&mut |pat| {
1366 PatKind::Ident(binding_mode, ident, ref sub_pat)
1367 if sub_pat.is_some() || self.is_base_res_local(pat.id) =>
1369 binding_map.insert(ident, BindingInfo { span: ident.span, binding_mode });
1371 PatKind::Or(ref ps) => {
1372 // Check the consistency of this or-pattern and
1373 // then add all bindings to the larger map.
1374 for bm in self.check_consistent_bindings(ps) {
1375 binding_map.extend(bm);
1388 fn is_base_res_local(&self, nid: NodeId) -> bool {
1389 match self.r.partial_res_map.get(&nid).map(|res| res.base_res()) {
1390 Some(Res::Local(..)) => true,
1395 /// Checks that all of the arms in an or-pattern have exactly the
1396 /// same set of bindings, with the same binding modes for each.
1397 fn check_consistent_bindings(&mut self, pats: &[P<Pat>]) -> Vec<BindingMap> {
1398 let mut missing_vars = FxHashMap::default();
1399 let mut inconsistent_vars = FxHashMap::default();
1401 // 1) Compute the binding maps of all arms.
1402 let maps = pats.iter().map(|pat| self.binding_mode_map(pat)).collect::<Vec<_>>();
1404 // 2) Record any missing bindings or binding mode inconsistencies.
1405 for (map_outer, pat_outer) in pats.iter().enumerate().map(|(idx, pat)| (&maps[idx], pat)) {
1406 // Check against all arms except for the same pattern which is always self-consistent.
1410 .filter(|(_, pat)| pat.id != pat_outer.id)
1411 .flat_map(|(idx, _)| maps[idx].iter())
1412 .map(|(key, binding)| (key.name, map_outer.get(&key), binding));
1414 for (name, info, &binding_inner) in inners {
1417 // The inner binding is missing in the outer.
1419 missing_vars.entry(name).or_insert_with(|| BindingError {
1421 origin: BTreeSet::new(),
1422 target: BTreeSet::new(),
1423 could_be_path: name.as_str().starts_with(char::is_uppercase),
1425 binding_error.origin.insert(binding_inner.span);
1426 binding_error.target.insert(pat_outer.span);
1428 Some(binding_outer) => {
1429 if binding_outer.binding_mode != binding_inner.binding_mode {
1430 // The binding modes in the outer and inner bindings differ.
1433 .or_insert((binding_inner.span, binding_outer.span));
1440 // 3) Report all missing variables we found.
1441 let mut missing_vars = missing_vars.iter_mut().collect::<Vec<_>>();
1442 missing_vars.sort_by_key(|(sym, _err)| sym.as_str());
1444 for (name, mut v) in missing_vars {
1445 if inconsistent_vars.contains_key(name) {
1446 v.could_be_path = false;
1449 *v.origin.iter().next().unwrap(),
1450 ResolutionError::VariableNotBoundInPattern(v),
1454 // 4) Report all inconsistencies in binding modes we found.
1455 let mut inconsistent_vars = inconsistent_vars.iter().collect::<Vec<_>>();
1456 inconsistent_vars.sort();
1457 for (name, v) in inconsistent_vars {
1458 self.report_error(v.0, ResolutionError::VariableBoundWithDifferentMode(*name, v.1));
1461 // 5) Finally bubble up all the binding maps.
1465 /// Check the consistency of the outermost or-patterns.
1466 fn check_consistent_bindings_top(&mut self, pat: &'ast Pat) {
1467 pat.walk(&mut |pat| match pat.kind {
1468 PatKind::Or(ref ps) => {
1469 self.check_consistent_bindings(ps);
1476 fn resolve_arm(&mut self, arm: &'ast Arm) {
1477 self.with_rib(ValueNS, NormalRibKind, |this| {
1478 this.resolve_pattern_top(&arm.pat, PatternSource::Match);
1479 walk_list!(this, visit_expr, &arm.guard);
1480 this.visit_expr(&arm.body);
1484 /// Arising from `source`, resolve a top level pattern.
1485 fn resolve_pattern_top(&mut self, pat: &'ast Pat, pat_src: PatternSource) {
1486 let mut bindings = smallvec![(PatBoundCtx::Product, Default::default())];
1487 self.resolve_pattern(pat, pat_src, &mut bindings);
1493 pat_src: PatternSource,
1494 bindings: &mut SmallVec<[(PatBoundCtx, FxHashSet<Ident>); 1]>,
1496 self.resolve_pattern_inner(pat, pat_src, bindings);
1497 // This has to happen *after* we determine which pat_idents are variants:
1498 self.check_consistent_bindings_top(pat);
1499 visit::walk_pat(self, pat);
1502 /// Resolve bindings in a pattern. This is a helper to `resolve_pattern`.
1506 /// A stack of sets of bindings accumulated.
1508 /// In each set, `PatBoundCtx::Product` denotes that a found binding in it should
1509 /// be interpreted as re-binding an already bound binding. This results in an error.
1510 /// Meanwhile, `PatBound::Or` denotes that a found binding in the set should result
1511 /// in reusing this binding rather than creating a fresh one.
1513 /// When called at the top level, the stack must have a single element
1514 /// with `PatBound::Product`. Otherwise, pushing to the stack happens as
1515 /// or-patterns (`p_0 | ... | p_n`) are encountered and the context needs
1516 /// to be switched to `PatBoundCtx::Or` and then `PatBoundCtx::Product` for each `p_i`.
1517 /// When each `p_i` has been dealt with, the top set is merged with its parent.
1518 /// When a whole or-pattern has been dealt with, the thing happens.
1520 /// See the implementation and `fresh_binding` for more details.
1521 fn resolve_pattern_inner(
1524 pat_src: PatternSource,
1525 bindings: &mut SmallVec<[(PatBoundCtx, FxHashSet<Ident>); 1]>,
1527 // Visit all direct subpatterns of this pattern.
1528 pat.walk(&mut |pat| {
1529 debug!("resolve_pattern pat={:?} node={:?}", pat, pat.kind);
1531 PatKind::Ident(bmode, ident, ref sub) => {
1532 // First try to resolve the identifier as some existing entity,
1533 // then fall back to a fresh binding.
1534 let has_sub = sub.is_some();
1536 .try_resolve_as_non_binding(pat_src, pat, bmode, ident, has_sub)
1537 .unwrap_or_else(|| self.fresh_binding(ident, pat.id, pat_src, bindings));
1538 self.r.record_partial_res(pat.id, PartialRes::new(res));
1540 PatKind::TupleStruct(ref path, ..) => {
1541 self.smart_resolve_path(pat.id, None, path, PathSource::TupleStruct(pat.span));
1543 PatKind::Path(ref qself, ref path) => {
1544 self.smart_resolve_path(pat.id, qself.as_ref(), path, PathSource::Pat);
1546 PatKind::Struct(ref path, ..) => {
1547 self.smart_resolve_path(pat.id, None, path, PathSource::Struct);
1549 PatKind::Or(ref ps) => {
1550 // Add a new set of bindings to the stack. `Or` here records that when a
1551 // binding already exists in this set, it should not result in an error because
1552 // `V1(a) | V2(a)` must be allowed and are checked for consistency later.
1553 bindings.push((PatBoundCtx::Or, Default::default()));
1555 // Now we need to switch back to a product context so that each
1556 // part of the or-pattern internally rejects already bound names.
1557 // For example, `V1(a) | V2(a, a)` and `V1(a, a) | V2(a)` are bad.
1558 bindings.push((PatBoundCtx::Product, Default::default()));
1559 self.resolve_pattern_inner(p, pat_src, bindings);
1560 // Move up the non-overlapping bindings to the or-pattern.
1561 // Existing bindings just get "merged".
1562 let collected = bindings.pop().unwrap().1;
1563 bindings.last_mut().unwrap().1.extend(collected);
1565 // This or-pattern itself can itself be part of a product,
1566 // e.g. `(V1(a) | V2(a), a)` or `(a, V1(a) | V2(a))`.
1567 // Both cases bind `a` again in a product pattern and must be rejected.
1568 let collected = bindings.pop().unwrap().1;
1569 bindings.last_mut().unwrap().1.extend(collected);
1571 // Prevent visiting `ps` as we've already done so above.
1584 pat_src: PatternSource,
1585 bindings: &mut SmallVec<[(PatBoundCtx, FxHashSet<Ident>); 1]>,
1587 // Add the binding to the local ribs, if it doesn't already exist in the bindings map.
1588 // (We must not add it if it's in the bindings map because that breaks the assumptions
1589 // later passes make about or-patterns.)
1590 let ident = ident.normalize_to_macro_rules();
1592 let mut bound_iter = bindings.iter().filter(|(_, set)| set.contains(&ident));
1593 // Already bound in a product pattern? e.g. `(a, a)` which is not allowed.
1594 let already_bound_and = bound_iter.clone().any(|(ctx, _)| *ctx == PatBoundCtx::Product);
1595 // Already bound in an or-pattern? e.g. `V1(a) | V2(a)`.
1596 // This is *required* for consistency which is checked later.
1597 let already_bound_or = bound_iter.any(|(ctx, _)| *ctx == PatBoundCtx::Or);
1599 if already_bound_and {
1600 // Overlap in a product pattern somewhere; report an error.
1601 use ResolutionError::*;
1602 let error = match pat_src {
1603 // `fn f(a: u8, a: u8)`:
1604 PatternSource::FnParam => IdentifierBoundMoreThanOnceInParameterList,
1606 _ => IdentifierBoundMoreThanOnceInSamePattern,
1608 self.report_error(ident.span, error(ident.name));
1611 // Record as bound if it's valid:
1612 let ident_valid = ident.name != kw::Invalid;
1614 bindings.last_mut().unwrap().1.insert(ident);
1617 if already_bound_or {
1618 // `Variant1(a) | Variant2(a)`, ok
1619 // Reuse definition from the first `a`.
1620 self.innermost_rib_bindings(ValueNS)[&ident]
1622 let res = Res::Local(pat_id);
1624 // A completely fresh binding add to the set if it's valid.
1625 self.innermost_rib_bindings(ValueNS).insert(ident, res);
1631 fn innermost_rib_bindings(&mut self, ns: Namespace) -> &mut IdentMap<Res> {
1632 &mut self.ribs[ns].last_mut().unwrap().bindings
1635 fn try_resolve_as_non_binding(
1637 pat_src: PatternSource,
1643 // An immutable (no `mut`) by-value (no `ref`) binding pattern without
1644 // a sub pattern (no `@ $pat`) is syntactically ambiguous as it could
1645 // also be interpreted as a path to e.g. a constant, variant, etc.
1646 let is_syntactic_ambiguity = !has_sub && bm == BindingMode::ByValue(Mutability::Not);
1648 let ls_binding = self.resolve_ident_in_lexical_scope(ident, ValueNS, None, pat.span)?;
1649 let (res, binding) = match ls_binding {
1650 LexicalScopeBinding::Item(binding)
1651 if is_syntactic_ambiguity && binding.is_ambiguity() =>
1653 // For ambiguous bindings we don't know all their definitions and cannot check
1654 // whether they can be shadowed by fresh bindings or not, so force an error.
1655 // issues/33118#issuecomment-233962221 (see below) still applies here,
1656 // but we have to ignore it for backward compatibility.
1657 self.r.record_use(ident, ValueNS, binding, false);
1660 LexicalScopeBinding::Item(binding) => (binding.res(), Some(binding)),
1661 LexicalScopeBinding::Res(res) => (res, None),
1665 Res::SelfCtor(_) // See #70549.
1667 DefKind::Ctor(_, CtorKind::Const) | DefKind::Const | DefKind::ConstParam,
1669 ) if is_syntactic_ambiguity => {
1670 // Disambiguate in favor of a unit struct/variant or constant pattern.
1671 if let Some(binding) = binding {
1672 self.r.record_use(ident, ValueNS, binding, false);
1676 Res::Def(DefKind::Ctor(..) | DefKind::Const | DefKind::Static, _) => {
1677 // This is unambiguously a fresh binding, either syntactically
1678 // (e.g., `IDENT @ PAT` or `ref IDENT`) or because `IDENT` resolves
1679 // to something unusable as a pattern (e.g., constructor function),
1680 // but we still conservatively report an error, see
1681 // issues/33118#issuecomment-233962221 for one reason why.
1684 ResolutionError::BindingShadowsSomethingUnacceptable(
1687 binding.expect("no binding for a ctor or static"),
1692 Res::Def(DefKind::Fn, _) | Res::Local(..) | Res::Err => {
1693 // These entities are explicitly allowed to be shadowed by fresh bindings.
1698 "unexpected resolution for an identifier in pattern: {:?}",
1704 // High-level and context dependent path resolution routine.
1705 // Resolves the path and records the resolution into definition map.
1706 // If resolution fails tries several techniques to find likely
1707 // resolution candidates, suggest imports or other help, and report
1708 // errors in user friendly way.
1709 fn smart_resolve_path(
1712 qself: Option<&QSelf>,
1714 source: PathSource<'ast>,
1716 self.smart_resolve_path_fragment(
1719 &Segment::from_path(path),
1722 CrateLint::SimplePath(id),
1726 fn smart_resolve_path_fragment(
1729 qself: Option<&QSelf>,
1732 source: PathSource<'ast>,
1733 crate_lint: CrateLint,
1735 log::debug!("smart_resolve_path_fragment(id={:?},qself={:?},path={:?}", id, qself, path);
1736 let ns = source.namespace();
1737 let is_expected = &|res| source.is_expected(res);
1739 let report_errors = |this: &mut Self, res: Option<Res>| {
1740 if this.should_report_errs() {
1741 let (err, candidates) = this.smart_resolve_report_errors(path, span, source, res);
1743 let def_id = this.parent_scope.module.normal_ancestor_id;
1744 let instead = res.is_some();
1746 if res.is_none() { this.report_missing_type_error(path) } else { None };
1748 this.r.use_injections.push(UseError {
1757 PartialRes::new(Res::Err)
1760 // For paths originating from calls (like in `HashMap::new()`), tries
1761 // to enrich the plain `failed to resolve: ...` message with hints
1762 // about possible missing imports.
1764 // Similar thing, for types, happens in `report_errors` above.
1765 let report_errors_for_call = |this: &mut Self, parent_err: Spanned<ResolutionError<'a>>| {
1766 if !source.is_call() {
1767 return Some(parent_err);
1770 // Before we start looking for candidates, we have to get our hands
1771 // on the type user is trying to perform invocation on; basically:
1772 // we're transforming `HashMap::new` into just `HashMap`
1773 let path = if let Some((_, path)) = path.split_last() {
1776 return Some(parent_err);
1779 let (mut err, candidates) =
1780 this.smart_resolve_report_errors(path, span, PathSource::Type, None);
1782 if candidates.is_empty() {
1784 return Some(parent_err);
1787 // There are two different error messages user might receive at
1789 // - E0412 cannot find type `{}` in this scope
1790 // - E0433 failed to resolve: use of undeclared type or module `{}`
1792 // The first one is emitted for paths in type-position, and the
1793 // latter one - for paths in expression-position.
1795 // Thus (since we're in expression-position at this point), not to
1796 // confuse the user, we want to keep the *message* from E0432 (so
1797 // `parent_err`), but we want *hints* from E0412 (so `err`).
1799 // And that's what happens below - we're just mixing both messages
1800 // into a single one.
1801 let mut parent_err = this.r.into_struct_error(parent_err.span, parent_err.node);
1803 parent_err.cancel();
1805 err.message = take(&mut parent_err.message);
1806 err.code = take(&mut parent_err.code);
1807 err.children = take(&mut parent_err.children);
1811 let def_id = this.parent_scope.module.normal_ancestor_id;
1813 if this.should_report_errs() {
1814 this.r.use_injections.push(UseError {
1825 // We don't return `Some(parent_err)` here, because the error will
1826 // be already printed as part of the `use` injections
1830 let partial_res = match self.resolve_qpath_anywhere(
1836 source.defer_to_typeck(),
1839 Ok(Some(partial_res)) if partial_res.unresolved_segments() == 0 => {
1840 if is_expected(partial_res.base_res()) || partial_res.base_res() == Res::Err {
1843 report_errors(self, Some(partial_res.base_res()))
1847 Ok(Some(partial_res)) if source.defer_to_typeck() => {
1848 // Not fully resolved associated item `T::A::B` or `<T as Tr>::A::B`
1849 // or `<T>::A::B`. If `B` should be resolved in value namespace then
1850 // it needs to be added to the trait map.
1852 let item_name = path.last().unwrap().ident;
1853 let traits = self.get_traits_containing_item(item_name, ns);
1854 self.r.trait_map.insert(id, traits);
1857 let mut std_path = vec![Segment::from_ident(Ident::with_dummy_span(sym::std))];
1859 std_path.extend(path);
1861 if self.r.primitive_type_table.primitive_types.contains_key(&path[0].ident.name) {
1862 if let PathResult::Module(_) | PathResult::NonModule(_) =
1863 self.resolve_path(&std_path, Some(ns), false, span, CrateLint::No)
1865 // Check if we wrote `str::from_utf8` instead of `std::str::from_utf8`
1867 path.iter().last().map(|segment| segment.ident.span).unwrap_or(span);
1869 let mut hm = self.r.session.confused_type_with_std_module.borrow_mut();
1870 hm.insert(item_span, span);
1871 hm.insert(span, span);
1879 if let Some(err) = report_errors_for_call(self, err) {
1880 self.report_error(err.span, err.node);
1883 PartialRes::new(Res::Err)
1886 _ => report_errors(self, None),
1889 if let PathSource::TraitItem(..) = source {
1891 // Avoid recording definition of `A::B` in `<T as A>::B::C`.
1892 self.r.record_partial_res(id, partial_res);
1898 fn self_type_is_available(&mut self, span: Span) -> bool {
1899 let binding = self.resolve_ident_in_lexical_scope(
1900 Ident::with_dummy_span(kw::SelfUpper),
1905 if let Some(LexicalScopeBinding::Res(res)) = binding { res != Res::Err } else { false }
1908 fn self_value_is_available(&mut self, self_span: Span, path_span: Span) -> bool {
1909 let ident = Ident::new(kw::SelfLower, self_span);
1910 let binding = self.resolve_ident_in_lexical_scope(ident, ValueNS, None, path_span);
1911 if let Some(LexicalScopeBinding::Res(res)) = binding { res != Res::Err } else { false }
1914 /// A wrapper around [`Resolver::report_error`].
1916 /// This doesn't emit errors for function bodies if this is rustdoc.
1917 fn report_error(&self, span: Span, resolution_error: ResolutionError<'_>) {
1918 if self.should_report_errs() {
1919 self.r.report_error(span, resolution_error);
1924 /// If we're actually rustdoc then avoid giving a name resolution error for `cfg()` items.
1925 fn should_report_errs(&self) -> bool {
1926 !(self.r.session.opts.actually_rustdoc && self.in_func_body)
1929 // Resolve in alternative namespaces if resolution in the primary namespace fails.
1930 fn resolve_qpath_anywhere(
1933 qself: Option<&QSelf>,
1935 primary_ns: Namespace,
1937 defer_to_typeck: bool,
1938 crate_lint: CrateLint,
1939 ) -> Result<Option<PartialRes>, Spanned<ResolutionError<'a>>> {
1940 let mut fin_res = None;
1942 for (i, ns) in [primary_ns, TypeNS, ValueNS].iter().cloned().enumerate() {
1943 if i == 0 || ns != primary_ns {
1944 match self.resolve_qpath(id, qself, path, ns, span, crate_lint)? {
1946 if partial_res.unresolved_segments() == 0 || defer_to_typeck =>
1948 return Ok(Some(partial_res));
1951 if fin_res.is_none() {
1952 fin_res = partial_res
1959 assert!(primary_ns != MacroNS);
1961 if qself.is_none() {
1962 let path_seg = |seg: &Segment| PathSegment::from_ident(seg.ident);
1963 let path = Path { segments: path.iter().map(path_seg).collect(), span };
1964 if let Ok((_, res)) =
1965 self.r.resolve_macro_path(&path, None, &self.parent_scope, false, false)
1967 return Ok(Some(PartialRes::new(res)));
1974 /// Handles paths that may refer to associated items.
1978 qself: Option<&QSelf>,
1982 crate_lint: CrateLint,
1983 ) -> Result<Option<PartialRes>, Spanned<ResolutionError<'a>>> {
1985 "resolve_qpath(id={:?}, qself={:?}, path={:?}, ns={:?}, span={:?})",
1986 id, qself, path, ns, span,
1989 if let Some(qself) = qself {
1990 if qself.position == 0 {
1991 // This is a case like `<T>::B`, where there is no
1992 // trait to resolve. In that case, we leave the `B`
1993 // segment to be resolved by type-check.
1994 return Ok(Some(PartialRes::with_unresolved_segments(
1995 Res::Def(DefKind::Mod, DefId::local(CRATE_DEF_INDEX)),
2000 // Make sure `A::B` in `<T as A::B>::C` is a trait item.
2002 // Currently, `path` names the full item (`A::B::C`, in
2003 // our example). so we extract the prefix of that that is
2004 // the trait (the slice upto and including
2005 // `qself.position`). And then we recursively resolve that,
2006 // but with `qself` set to `None`.
2008 // However, setting `qself` to none (but not changing the
2009 // span) loses the information about where this path
2010 // *actually* appears, so for the purposes of the crate
2011 // lint we pass along information that this is the trait
2012 // name from a fully qualified path, and this also
2013 // contains the full span (the `CrateLint::QPathTrait`).
2014 let ns = if qself.position + 1 == path.len() { ns } else { TypeNS };
2015 let partial_res = self.smart_resolve_path_fragment(
2018 &path[..=qself.position],
2020 PathSource::TraitItem(ns),
2021 CrateLint::QPathTrait { qpath_id: id, qpath_span: qself.path_span },
2024 // The remaining segments (the `C` in our example) will
2025 // have to be resolved by type-check, since that requires doing
2026 // trait resolution.
2027 return Ok(Some(PartialRes::with_unresolved_segments(
2028 partial_res.base_res(),
2029 partial_res.unresolved_segments() + path.len() - qself.position - 1,
2033 let result = match self.resolve_path(&path, Some(ns), true, span, crate_lint) {
2034 PathResult::NonModule(path_res) => path_res,
2035 PathResult::Module(ModuleOrUniformRoot::Module(module)) if !module.is_normal() => {
2036 PartialRes::new(module.res().unwrap())
2038 // In `a(::assoc_item)*` `a` cannot be a module. If `a` does resolve to a module we
2039 // don't report an error right away, but try to fallback to a primitive type.
2040 // So, we are still able to successfully resolve something like
2042 // use std::u8; // bring module u8 in scope
2043 // fn f() -> u8 { // OK, resolves to primitive u8, not to std::u8
2044 // u8::max_value() // OK, resolves to associated function <u8>::max_value,
2045 // // not to non-existent std::u8::max_value
2048 // Such behavior is required for backward compatibility.
2049 // The same fallback is used when `a` resolves to nothing.
2050 PathResult::Module(ModuleOrUniformRoot::Module(_)) | PathResult::Failed { .. }
2051 if (ns == TypeNS || path.len() > 1)
2054 .primitive_type_table
2056 .contains_key(&path[0].ident.name) =>
2058 let prim = self.r.primitive_type_table.primitive_types[&path[0].ident.name];
2059 PartialRes::with_unresolved_segments(Res::PrimTy(prim), path.len() - 1)
2061 PathResult::Module(ModuleOrUniformRoot::Module(module)) => {
2062 PartialRes::new(module.res().unwrap())
2064 PathResult::Failed { is_error_from_last_segment: false, span, label, suggestion } => {
2065 return Err(respan(span, ResolutionError::FailedToResolve { label, suggestion }));
2067 PathResult::Module(..) | PathResult::Failed { .. } => return Ok(None),
2068 PathResult::Indeterminate => bug!("indeterminate path result in resolve_qpath"),
2072 && result.base_res() != Res::Err
2073 && path[0].ident.name != kw::PathRoot
2074 && path[0].ident.name != kw::DollarCrate
2076 let unqualified_result = {
2077 match self.resolve_path(
2078 &[*path.last().unwrap()],
2084 PathResult::NonModule(path_res) => path_res.base_res(),
2085 PathResult::Module(ModuleOrUniformRoot::Module(module)) => {
2086 module.res().unwrap()
2088 _ => return Ok(Some(result)),
2091 if result.base_res() == unqualified_result {
2092 let lint = lint::builtin::UNUSED_QUALIFICATIONS;
2093 self.r.lint_buffer.buffer_lint(lint, id, span, "unnecessary qualification")
2100 fn with_resolved_label(&mut self, label: Option<Label>, id: NodeId, f: impl FnOnce(&mut Self)) {
2101 if let Some(label) = label {
2102 if label.ident.as_str().as_bytes()[1] != b'_' {
2103 self.diagnostic_metadata.unused_labels.insert(id, label.ident.span);
2105 self.with_label_rib(NormalRibKind, |this| {
2106 let ident = label.ident.normalize_to_macro_rules();
2107 this.label_ribs.last_mut().unwrap().bindings.insert(ident, id);
2115 fn resolve_labeled_block(&mut self, label: Option<Label>, id: NodeId, block: &'ast Block) {
2116 self.with_resolved_label(label, id, |this| this.visit_block(block));
2119 fn resolve_block(&mut self, block: &'ast Block) {
2120 debug!("(resolving block) entering block");
2121 // Move down in the graph, if there's an anonymous module rooted here.
2122 let orig_module = self.parent_scope.module;
2123 let anonymous_module = self.r.block_map.get(&block.id).cloned(); // clones a reference
2125 let mut num_macro_definition_ribs = 0;
2126 if let Some(anonymous_module) = anonymous_module {
2127 debug!("(resolving block) found anonymous module, moving down");
2128 self.ribs[ValueNS].push(Rib::new(ModuleRibKind(anonymous_module)));
2129 self.ribs[TypeNS].push(Rib::new(ModuleRibKind(anonymous_module)));
2130 self.parent_scope.module = anonymous_module;
2132 self.ribs[ValueNS].push(Rib::new(NormalRibKind));
2135 // Descend into the block.
2136 for stmt in &block.stmts {
2137 if let StmtKind::Item(ref item) = stmt.kind {
2138 if let ItemKind::MacroDef(..) = item.kind {
2139 num_macro_definition_ribs += 1;
2140 let res = self.r.local_def_id(item.id).to_def_id();
2141 self.ribs[ValueNS].push(Rib::new(MacroDefinition(res)));
2142 self.label_ribs.push(Rib::new(MacroDefinition(res)));
2146 self.visit_stmt(stmt);
2150 self.parent_scope.module = orig_module;
2151 for _ in 0..num_macro_definition_ribs {
2152 self.ribs[ValueNS].pop();
2153 self.label_ribs.pop();
2155 self.ribs[ValueNS].pop();
2156 if anonymous_module.is_some() {
2157 self.ribs[TypeNS].pop();
2159 debug!("(resolving block) leaving block");
2162 fn resolve_expr(&mut self, expr: &'ast Expr, parent: Option<&'ast Expr>) {
2163 // First, record candidate traits for this expression if it could
2164 // result in the invocation of a method call.
2166 self.record_candidate_traits_for_expr_if_necessary(expr);
2168 // Next, resolve the node.
2170 ExprKind::Path(ref qself, ref path) => {
2171 self.smart_resolve_path(expr.id, qself.as_ref(), path, PathSource::Expr(parent));
2172 visit::walk_expr(self, expr);
2175 ExprKind::Struct(ref path, ..) => {
2176 self.smart_resolve_path(expr.id, None, path, PathSource::Struct);
2177 visit::walk_expr(self, expr);
2180 ExprKind::Break(Some(label), _) | ExprKind::Continue(Some(label)) => {
2181 if let Some(node_id) = self.resolve_label(label.ident) {
2182 // Since this res is a label, it is never read.
2183 self.r.label_res_map.insert(expr.id, node_id);
2184 self.diagnostic_metadata.unused_labels.remove(&node_id);
2187 // visit `break` argument if any
2188 visit::walk_expr(self, expr);
2191 ExprKind::Let(ref pat, ref scrutinee) => {
2192 self.visit_expr(scrutinee);
2193 self.resolve_pattern_top(pat, PatternSource::Let);
2196 ExprKind::If(ref cond, ref then, ref opt_else) => {
2197 self.with_rib(ValueNS, NormalRibKind, |this| {
2198 this.visit_expr(cond);
2199 this.visit_block(then);
2201 if let Some(expr) = opt_else {
2202 self.visit_expr(expr);
2206 ExprKind::Loop(ref block, label) => self.resolve_labeled_block(label, expr.id, &block),
2208 ExprKind::While(ref cond, ref block, label) => {
2209 self.with_resolved_label(label, expr.id, |this| {
2210 this.with_rib(ValueNS, NormalRibKind, |this| {
2211 this.visit_expr(cond);
2212 this.visit_block(block);
2217 ExprKind::ForLoop(ref pat, ref iter_expr, ref block, label) => {
2218 self.visit_expr(iter_expr);
2219 self.with_rib(ValueNS, NormalRibKind, |this| {
2220 this.resolve_pattern_top(pat, PatternSource::For);
2221 this.resolve_labeled_block(label, expr.id, block);
2225 ExprKind::Block(ref block, label) => self.resolve_labeled_block(label, block.id, block),
2227 // Equivalent to `visit::walk_expr` + passing some context to children.
2228 ExprKind::Field(ref subexpression, _) => {
2229 self.resolve_expr(subexpression, Some(expr));
2231 ExprKind::MethodCall(ref segment, ref arguments, _) => {
2232 let mut arguments = arguments.iter();
2233 self.resolve_expr(arguments.next().unwrap(), Some(expr));
2234 for argument in arguments {
2235 self.resolve_expr(argument, None);
2237 self.visit_path_segment(expr.span, segment);
2240 ExprKind::Call(ref callee, ref arguments) => {
2241 self.resolve_expr(callee, Some(expr));
2242 for argument in arguments {
2243 self.resolve_expr(argument, None);
2246 ExprKind::Type(ref type_expr, ref ty) => {
2247 // `ParseSess::type_ascription_path_suggestions` keeps spans of colon tokens in
2248 // type ascription. Here we are trying to retrieve the span of the colon token as
2249 // well, but only if it's written without spaces `expr:Ty` and therefore confusable
2250 // with `expr::Ty`, only in this case it will match the span from
2251 // `type_ascription_path_suggestions`.
2252 self.diagnostic_metadata
2253 .current_type_ascription
2254 .push(type_expr.span.between(ty.span));
2255 visit::walk_expr(self, expr);
2256 self.diagnostic_metadata.current_type_ascription.pop();
2258 // `async |x| ...` gets desugared to `|x| future_from_generator(|| ...)`, so we need to
2259 // resolve the arguments within the proper scopes so that usages of them inside the
2260 // closure are detected as upvars rather than normal closure arg usages.
2261 ExprKind::Closure(_, Async::Yes { .. }, _, ref fn_decl, ref body, _span) => {
2262 self.with_rib(ValueNS, NormalRibKind, |this| {
2263 this.with_label_rib(ClosureOrAsyncRibKind, |this| {
2264 // Resolve arguments:
2265 this.resolve_params(&fn_decl.inputs);
2266 // No need to resolve return type --
2267 // the outer closure return type is `FnRetTy::Default`.
2269 // Now resolve the inner closure
2271 // No need to resolve arguments: the inner closure has none.
2272 // Resolve the return type:
2273 visit::walk_fn_ret_ty(this, &fn_decl.output);
2275 this.visit_expr(body);
2280 ExprKind::Async(..) | ExprKind::Closure(..) => {
2281 self.with_label_rib(ClosureOrAsyncRibKind, |this| visit::walk_expr(this, expr));
2284 visit::walk_expr(self, expr);
2289 fn record_candidate_traits_for_expr_if_necessary(&mut self, expr: &'ast Expr) {
2291 ExprKind::Field(_, ident) => {
2292 // FIXME(#6890): Even though you can't treat a method like a
2293 // field, we need to add any trait methods we find that match
2294 // the field name so that we can do some nice error reporting
2295 // later on in typeck.
2296 let traits = self.get_traits_containing_item(ident, ValueNS);
2297 self.r.trait_map.insert(expr.id, traits);
2299 ExprKind::MethodCall(ref segment, ..) => {
2300 debug!("(recording candidate traits for expr) recording traits for {}", expr.id);
2301 let traits = self.get_traits_containing_item(segment.ident, ValueNS);
2302 self.r.trait_map.insert(expr.id, traits);
2310 fn get_traits_containing_item(
2314 ) -> Vec<TraitCandidate> {
2315 debug!("(getting traits containing item) looking for '{}'", ident.name);
2317 let mut found_traits = Vec::new();
2318 // Look for the current trait.
2319 if let Some((module, _)) = self.current_trait_ref {
2322 .resolve_ident_in_module(
2323 ModuleOrUniformRoot::Module(module),
2332 let def_id = module.def_id().unwrap();
2333 found_traits.push(TraitCandidate { def_id, import_ids: smallvec![] });
2337 ident.span = ident.span.normalize_to_macros_2_0();
2338 let mut search_module = self.parent_scope.module;
2340 self.get_traits_in_module_containing_item(ident, ns, search_module, &mut found_traits);
2342 unwrap_or!(self.r.hygienic_lexical_parent(search_module, &mut ident.span), break);
2345 if let Some(prelude) = self.r.prelude {
2346 if !search_module.no_implicit_prelude {
2347 self.get_traits_in_module_containing_item(ident, ns, prelude, &mut found_traits);
2354 fn get_traits_in_module_containing_item(
2359 found_traits: &mut Vec<TraitCandidate>,
2361 assert!(ns == TypeNS || ns == ValueNS);
2362 let mut traits = module.traits.borrow_mut();
2363 if traits.is_none() {
2364 let mut collected_traits = Vec::new();
2365 module.for_each_child(self.r, |_, name, ns, binding| {
2369 match binding.res() {
2370 Res::Def(DefKind::Trait | DefKind::TraitAlias, _) => {
2371 collected_traits.push((name, binding))
2376 *traits = Some(collected_traits.into_boxed_slice());
2379 for &(trait_name, binding) in traits.as_ref().unwrap().iter() {
2380 // Traits have pseudo-modules that can be used to search for the given ident.
2381 if let Some(module) = binding.module() {
2382 let mut ident = ident;
2383 if ident.span.glob_adjust(module.expansion, binding.span).is_none() {
2388 .resolve_ident_in_module_unadjusted(
2389 ModuleOrUniformRoot::Module(module),
2398 let import_ids = self.find_transitive_imports(&binding.kind, trait_name);
2399 let trait_def_id = module.def_id().unwrap();
2400 found_traits.push(TraitCandidate { def_id: trait_def_id, import_ids });
2402 } else if let Res::Def(DefKind::TraitAlias, _) = binding.res() {
2403 // For now, just treat all trait aliases as possible candidates, since we don't
2404 // know if the ident is somewhere in the transitive bounds.
2405 let import_ids = self.find_transitive_imports(&binding.kind, trait_name);
2406 let trait_def_id = binding.res().def_id();
2407 found_traits.push(TraitCandidate { def_id: trait_def_id, import_ids });
2409 bug!("candidate is not trait or trait alias?")
2414 fn find_transitive_imports(
2416 mut kind: &NameBindingKind<'_>,
2418 ) -> SmallVec<[LocalDefId; 1]> {
2419 let mut import_ids = smallvec![];
2420 while let NameBindingKind::Import { import, binding, .. } = kind {
2421 let id = self.r.local_def_id(import.id);
2422 self.r.maybe_unused_trait_imports.insert(id);
2423 self.r.add_to_glob_map(&import, trait_name);
2424 import_ids.push(id);
2425 kind = &binding.kind;
2431 impl<'a> Resolver<'a> {
2432 pub(crate) fn late_resolve_crate(&mut self, krate: &Crate) {
2433 let mut late_resolution_visitor = LateResolutionVisitor::new(self);
2434 visit::walk_crate(&mut late_resolution_visitor, krate);
2435 for (id, span) in late_resolution_visitor.diagnostic_metadata.unused_labels.iter() {
2436 self.lint_buffer.buffer_lint(lint::builtin::UNUSED_LABELS, *id, *span, "unused label");