1 // Copyright 2012-2015 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
11 // Do not remove on snapshot creation. Needed for bootstrap. (Issue #22364)
12 #![cfg_attr(stage0, feature(custom_attribute))]
13 #![crate_name = "rustc_resolve"]
14 #![unstable(feature = "rustc_private", issue = "27812")]
15 #![cfg_attr(stage0, staged_api)]
16 #![crate_type = "dylib"]
17 #![crate_type = "rlib"]
18 #![doc(html_logo_url = "https://www.rust-lang.org/logos/rust-logo-128x128-blk-v2.png",
19 html_favicon_url = "https://doc.rust-lang.org/favicon.ico",
20 html_root_url = "https://doc.rust-lang.org/nightly/")]
22 #![feature(associated_consts)]
23 #![feature(borrow_state)]
24 #![feature(rustc_diagnostic_macros)]
25 #![feature(rustc_private)]
26 #![feature(staged_api)]
34 extern crate rustc_bitflags;
35 extern crate rustc_front;
39 use self::PatternBindingMode::*;
40 use self::Namespace::*;
41 use self::NamespaceResult::*;
42 use self::ResolveResult::*;
43 use self::FallbackSuggestion::*;
44 use self::TypeParameters::*;
46 use self::UseLexicalScopeFlag::*;
47 use self::ModulePrefixResult::*;
48 use self::AssocItemResolveResult::*;
49 use self::NameSearchType::*;
50 use self::BareIdentifierPatternResolution::*;
51 use self::ParentLink::*;
52 use self::FallbackChecks::*;
54 use rustc::front::map as hir_map;
55 use rustc::session::Session;
57 use rustc::middle::cstore::{CrateStore, DefLike, DlDef};
58 use rustc::middle::def::*;
59 use rustc::middle::def_id::DefId;
60 use rustc::middle::pat_util::pat_bindings_hygienic;
61 use rustc::middle::privacy::*;
62 use rustc::middle::subst::{ParamSpace, FnSpace, TypeSpace};
63 use rustc::middle::ty::{Freevar, FreevarMap, TraitMap, GlobMap};
64 use rustc::util::nodemap::{NodeMap, DefIdSet, FnvHashMap};
67 use syntax::ast::{CRATE_NODE_ID, Ident, Name, NodeId, CrateNum, TyIs, TyI8, TyI16, TyI32, TyI64};
68 use syntax::ast::{TyUs, TyU8, TyU16, TyU32, TyU64, TyF64, TyF32};
69 use syntax::attr::AttrMetaMethods;
70 use syntax::ext::mtwt;
71 use syntax::parse::token::{self, special_names, special_idents};
73 use syntax::codemap::{self, Span, Pos};
74 use syntax::util::lev_distance::{lev_distance, max_suggestion_distance};
76 use rustc_front::intravisit::{self, FnKind, Visitor};
78 use rustc_front::hir::{Arm, BindByRef, BindByValue, BindingMode, Block};
79 use rustc_front::hir::Crate;
80 use rustc_front::hir::{Expr, ExprAgain, ExprBreak, ExprField};
81 use rustc_front::hir::{ExprLoop, ExprWhile, ExprMethodCall};
82 use rustc_front::hir::{ExprPath, ExprStruct, FnDecl};
83 use rustc_front::hir::{ForeignItemFn, ForeignItemStatic, Generics};
84 use rustc_front::hir::{ImplItem, Item, ItemConst, ItemEnum, ItemExternCrate};
85 use rustc_front::hir::{ItemFn, ItemForeignMod, ItemImpl, ItemMod, ItemStatic, ItemDefaultImpl};
86 use rustc_front::hir::{ItemStruct, ItemTrait, ItemTy, ItemUse};
87 use rustc_front::hir::Local;
88 use rustc_front::hir::{Pat, PatEnum, PatIdent, PatLit, PatQPath};
89 use rustc_front::hir::{PatRange, PatStruct, Path, PrimTy};
90 use rustc_front::hir::{TraitRef, Ty, TyBool, TyChar, TyFloat, TyInt};
91 use rustc_front::hir::{TyRptr, TyStr, TyUint, TyPath, TyPtr};
92 use rustc_front::util::walk_pat;
94 use std::collections::{HashMap, HashSet};
95 use std::cell::{Cell, RefCell};
97 use std::mem::replace;
98 use std::rc::{Rc, Weak};
101 use resolve_imports::{Target, ImportDirective, ImportResolution};
102 use resolve_imports::Shadowable;
104 // NB: This module needs to be declared first so diagnostics are
105 // registered before they are used.
110 mod build_reduced_graph;
113 // Perform the callback, not walking deeper if the return is true
114 macro_rules! execute_callback {
115 ($node: expr, $walker: expr) => (
116 if let Some(ref callback) = $walker.callback {
117 if callback($node, &mut $walker.resolved) {
124 enum SuggestionType {
130 pub enum ResolutionError<'a> {
131 /// error E0401: can't use type parameters from outer function
132 TypeParametersFromOuterFunction,
133 /// error E0402: cannot use an outer type parameter in this context
134 OuterTypeParameterContext,
135 /// error E0403: the name is already used for a type parameter in this type parameter list
136 NameAlreadyUsedInTypeParameterList(Name),
137 /// error E0404: is not a trait
138 IsNotATrait(&'a str),
139 /// error E0405: use of undeclared trait name
140 UndeclaredTraitName(&'a str),
141 /// error E0406: undeclared associated type
142 UndeclaredAssociatedType,
143 /// error E0407: method is not a member of trait
144 MethodNotMemberOfTrait(Name, &'a str),
145 /// error E0437: type is not a member of trait
146 TypeNotMemberOfTrait(Name, &'a str),
147 /// error E0438: const is not a member of trait
148 ConstNotMemberOfTrait(Name, &'a str),
149 /// error E0408: variable `{}` from pattern #1 is not bound in pattern
150 VariableNotBoundInPattern(Name, usize),
151 /// error E0409: variable is bound with different mode in pattern #{} than in pattern #1
152 VariableBoundWithDifferentMode(Name, usize),
153 /// error E0410: variable from pattern is not bound in pattern #1
154 VariableNotBoundInParentPattern(Name, usize),
155 /// error E0411: use of `Self` outside of an impl or trait
156 SelfUsedOutsideImplOrTrait,
157 /// error E0412: use of undeclared
158 UseOfUndeclared(&'a str, &'a str),
159 /// error E0413: declaration shadows an enum variant or unit-like struct in scope
160 DeclarationShadowsEnumVariantOrUnitLikeStruct(Name),
161 /// error E0414: only irrefutable patterns allowed here
162 OnlyIrrefutablePatternsAllowedHere(DefId, Name),
163 /// error E0415: identifier is bound more than once in this parameter list
164 IdentifierBoundMoreThanOnceInParameterList(&'a str),
165 /// error E0416: identifier is bound more than once in the same pattern
166 IdentifierBoundMoreThanOnceInSamePattern(&'a str),
167 /// error E0417: static variables cannot be referenced in a pattern
168 StaticVariableReference,
169 /// error E0418: is not an enum variant, struct or const
170 NotAnEnumVariantStructOrConst(&'a str),
171 /// error E0419: unresolved enum variant, struct or const
172 UnresolvedEnumVariantStructOrConst(&'a str),
173 /// error E0420: is not an associated const
174 NotAnAssociatedConst(&'a str),
175 /// error E0421: unresolved associated const
176 UnresolvedAssociatedConst(&'a str),
177 /// error E0422: does not name a struct
178 DoesNotNameAStruct(&'a str),
179 /// error E0423: is a struct variant name, but this expression uses it like a function name
180 StructVariantUsedAsFunction(&'a str),
181 /// error E0424: `self` is not available in a static method
182 SelfNotAvailableInStaticMethod,
183 /// error E0425: unresolved name
184 UnresolvedName(&'a str, &'a str),
185 /// error E0426: use of undeclared label
186 UndeclaredLabel(&'a str),
187 /// error E0427: cannot use `ref` binding mode with ...
188 CannotUseRefBindingModeWith(&'a str),
189 /// error E0428: duplicate definition
190 DuplicateDefinition(&'a str, Name),
191 /// error E0429: `self` imports are only allowed within a { } list
192 SelfImportsOnlyAllowedWithin,
193 /// error E0430: `self` import can only appear once in the list
194 SelfImportCanOnlyAppearOnceInTheList,
195 /// error E0431: `self` import can only appear in an import list with a non-empty prefix
196 SelfImportOnlyInImportListWithNonEmptyPrefix,
197 /// error E0432: unresolved import
198 UnresolvedImport(Option<(&'a str, &'a str)>),
199 /// error E0433: failed to resolve
200 FailedToResolve(&'a str),
201 /// error E0434: can't capture dynamic environment in a fn item
202 CannotCaptureDynamicEnvironmentInFnItem,
203 /// error E0435: attempt to use a non-constant value in a constant
204 AttemptToUseNonConstantValueInConstant,
207 fn resolve_error<'b, 'a: 'b, 'tcx: 'a>(resolver: &'b Resolver<'a, 'tcx>,
208 span: syntax::codemap::Span,
209 resolution_error: ResolutionError<'b>) {
210 if !resolver.emit_errors {
213 match resolution_error {
214 ResolutionError::TypeParametersFromOuterFunction => {
215 span_err!(resolver.session,
218 "can't use type parameters from outer function; try using a local type \
221 ResolutionError::OuterTypeParameterContext => {
222 span_err!(resolver.session,
225 "cannot use an outer type parameter in this context");
227 ResolutionError::NameAlreadyUsedInTypeParameterList(name) => {
228 span_err!(resolver.session,
231 "the name `{}` is already used for a type parameter in this type parameter \
235 ResolutionError::IsNotATrait(name) => {
236 span_err!(resolver.session, span, E0404, "`{}` is not a trait", name);
238 ResolutionError::UndeclaredTraitName(name) => {
239 span_err!(resolver.session,
242 "use of undeclared trait name `{}`",
245 ResolutionError::UndeclaredAssociatedType => {
246 span_err!(resolver.session, span, E0406, "undeclared associated type");
248 ResolutionError::MethodNotMemberOfTrait(method, trait_) => {
249 span_err!(resolver.session,
252 "method `{}` is not a member of trait `{}`",
256 ResolutionError::TypeNotMemberOfTrait(type_, trait_) => {
257 span_err!(resolver.session,
260 "type `{}` is not a member of trait `{}`",
264 ResolutionError::ConstNotMemberOfTrait(const_, trait_) => {
265 span_err!(resolver.session,
268 "const `{}` is not a member of trait `{}`",
272 ResolutionError::VariableNotBoundInPattern(variable_name, pattern_number) => {
273 span_err!(resolver.session,
276 "variable `{}` from pattern #1 is not bound in pattern #{}",
280 ResolutionError::VariableBoundWithDifferentMode(variable_name, pattern_number) => {
281 span_err!(resolver.session,
284 "variable `{}` is bound with different mode in pattern #{} than in pattern \
289 ResolutionError::VariableNotBoundInParentPattern(variable_name, pattern_number) => {
290 span_err!(resolver.session,
293 "variable `{}` from pattern #{} is not bound in pattern #1",
297 ResolutionError::SelfUsedOutsideImplOrTrait => {
298 span_err!(resolver.session,
301 "use of `Self` outside of an impl or trait");
303 ResolutionError::UseOfUndeclared(kind, name) => {
304 span_err!(resolver.session,
307 "use of undeclared {} `{}`",
311 ResolutionError::DeclarationShadowsEnumVariantOrUnitLikeStruct(name) => {
312 span_err!(resolver.session,
315 "declaration of `{}` shadows an enum variant or unit-like struct in scope",
318 ResolutionError::OnlyIrrefutablePatternsAllowedHere(did, name) => {
319 span_err!(resolver.session,
322 "only irrefutable patterns allowed here");
323 resolver.session.span_note(span,
324 "there already is a constant in scope sharing the same \
325 name as this pattern");
326 if let Some(sp) = resolver.ast_map.span_if_local(did) {
327 resolver.session.span_note(sp, "constant defined here");
329 if let Some(directive) = resolver.current_module
333 let item = resolver.ast_map.expect_item(directive.value_id);
334 resolver.session.span_note(item.span, "constant imported here");
337 ResolutionError::IdentifierBoundMoreThanOnceInParameterList(identifier) => {
338 span_err!(resolver.session,
341 "identifier `{}` is bound more than once in this parameter list",
344 ResolutionError::IdentifierBoundMoreThanOnceInSamePattern(identifier) => {
345 span_err!(resolver.session,
348 "identifier `{}` is bound more than once in the same pattern",
351 ResolutionError::StaticVariableReference => {
352 span_err!(resolver.session,
355 "static variables cannot be referenced in a pattern, use a `const` instead");
357 ResolutionError::NotAnEnumVariantStructOrConst(name) => {
358 span_err!(resolver.session,
361 "`{}` is not an enum variant, struct or const",
364 ResolutionError::UnresolvedEnumVariantStructOrConst(name) => {
365 span_err!(resolver.session,
368 "unresolved enum variant, struct or const `{}`",
371 ResolutionError::NotAnAssociatedConst(name) => {
372 span_err!(resolver.session,
375 "`{}` is not an associated const",
378 ResolutionError::UnresolvedAssociatedConst(name) => {
379 span_err!(resolver.session,
382 "unresolved associated const `{}`",
385 ResolutionError::DoesNotNameAStruct(name) => {
386 span_err!(resolver.session,
389 "`{}` does not name a structure",
392 ResolutionError::StructVariantUsedAsFunction(path_name) => {
393 span_err!(resolver.session,
396 "`{}` is the name of a struct or struct variant, but this expression uses \
397 it like a function name",
400 ResolutionError::SelfNotAvailableInStaticMethod => {
401 span_err!(resolver.session,
404 "`self` is not available in a static method. Maybe a `self` argument is \
407 ResolutionError::UnresolvedName(path, name) => {
408 span_err!(resolver.session,
411 "unresolved name `{}`{}",
415 ResolutionError::UndeclaredLabel(name) => {
416 span_err!(resolver.session,
419 "use of undeclared label `{}`",
422 ResolutionError::CannotUseRefBindingModeWith(descr) => {
423 span_err!(resolver.session,
426 "cannot use `ref` binding mode with {}",
429 ResolutionError::DuplicateDefinition(namespace, name) => {
430 span_err!(resolver.session,
433 "duplicate definition of {} `{}`",
437 ResolutionError::SelfImportsOnlyAllowedWithin => {
438 span_err!(resolver.session,
442 "`self` imports are only allowed within a { } list");
444 ResolutionError::SelfImportCanOnlyAppearOnceInTheList => {
445 span_err!(resolver.session,
448 "`self` import can only appear once in the list");
450 ResolutionError::SelfImportOnlyInImportListWithNonEmptyPrefix => {
451 span_err!(resolver.session,
454 "`self` import can only appear in an import list with a non-empty prefix");
456 ResolutionError::UnresolvedImport(name) => {
457 let msg = match name {
458 Some((n, p)) => format!("unresolved import `{}`{}", n, p),
459 None => "unresolved import".to_owned(),
461 span_err!(resolver.session, span, E0432, "{}", msg);
463 ResolutionError::FailedToResolve(msg) => {
464 span_err!(resolver.session, span, E0433, "failed to resolve. {}", msg);
466 ResolutionError::CannotCaptureDynamicEnvironmentInFnItem => {
467 span_err!(resolver.session,
471 "can't capture dynamic environment in a fn item; use the || { ... } \
472 closure form instead");
474 ResolutionError::AttemptToUseNonConstantValueInConstant => {
475 span_err!(resolver.session,
478 "attempt to use a non-constant value in a constant");
483 #[derive(Copy, Clone)]
486 binding_mode: BindingMode,
489 // Map from the name in a pattern to its binding mode.
490 type BindingMap = HashMap<Name, BindingInfo>;
492 #[derive(Copy, Clone, PartialEq)]
493 enum PatternBindingMode {
495 LocalIrrefutableMode,
496 ArgumentIrrefutableMode,
499 #[derive(Copy, Clone, PartialEq, Eq, Hash, Debug)]
505 /// A NamespaceResult represents the result of resolving an import in
506 /// a particular namespace. The result is either definitely-resolved,
507 /// definitely- unresolved, or unknown.
509 enum NamespaceResult {
510 /// Means that resolve hasn't gathered enough information yet to determine
511 /// whether the name is bound in this namespace. (That is, it hasn't
512 /// resolved all `use` directives yet.)
514 /// Means that resolve has determined that the name is definitely
515 /// not bound in the namespace.
517 /// Means that resolve has determined that the name is bound in the Module
518 /// argument, and specified by the NameBinding argument.
519 BoundResult(Rc<Module>, NameBinding),
522 impl NamespaceResult {
523 fn is_unknown(&self) -> bool {
525 UnknownResult => true,
529 fn is_unbound(&self) -> bool {
531 UnboundResult => true,
537 impl<'a, 'v, 'tcx> Visitor<'v> for Resolver<'a, 'tcx> {
538 fn visit_nested_item(&mut self, item: hir::ItemId) {
539 self.visit_item(self.ast_map.expect_item(item.id))
541 fn visit_item(&mut self, item: &Item) {
542 execute_callback!(hir_map::Node::NodeItem(item), self);
543 self.resolve_item(item);
545 fn visit_arm(&mut self, arm: &Arm) {
546 self.resolve_arm(arm);
548 fn visit_block(&mut self, block: &Block) {
549 execute_callback!(hir_map::Node::NodeBlock(block), self);
550 self.resolve_block(block);
552 fn visit_expr(&mut self, expr: &Expr) {
553 execute_callback!(hir_map::Node::NodeExpr(expr), self);
554 self.resolve_expr(expr);
556 fn visit_local(&mut self, local: &Local) {
557 execute_callback!(hir_map::Node::NodeLocal(&*local.pat), self);
558 self.resolve_local(local);
560 fn visit_ty(&mut self, ty: &Ty) {
561 self.resolve_type(ty);
563 fn visit_generics(&mut self, generics: &Generics) {
564 self.resolve_generics(generics);
566 fn visit_poly_trait_ref(&mut self, tref: &hir::PolyTraitRef, m: &hir::TraitBoundModifier) {
567 match self.resolve_trait_reference(tref.trait_ref.ref_id, &tref.trait_ref.path, 0) {
568 Ok(def) => self.record_def(tref.trait_ref.ref_id, def),
570 // error already reported
573 intravisit::walk_poly_trait_ref(self, tref, m);
575 fn visit_variant(&mut self,
576 variant: &hir::Variant,
578 item_id: ast::NodeId) {
579 execute_callback!(hir_map::Node::NodeVariant(variant), self);
580 if let Some(ref dis_expr) = variant.node.disr_expr {
581 // resolve the discriminator expr as a constant
582 self.with_constant_rib(|this| {
583 this.visit_expr(dis_expr);
587 // `intravisit::walk_variant` without the discriminant expression.
588 self.visit_variant_data(&variant.node.data,
594 fn visit_foreign_item(&mut self, foreign_item: &hir::ForeignItem) {
595 execute_callback!(hir_map::Node::NodeForeignItem(foreign_item), self);
596 let type_parameters = match foreign_item.node {
597 ForeignItemFn(_, ref generics) => {
598 HasTypeParameters(generics, FnSpace, ItemRibKind)
600 ForeignItemStatic(..) => NoTypeParameters,
602 self.with_type_parameter_rib(type_parameters, |this| {
603 intravisit::walk_foreign_item(this, foreign_item);
606 fn visit_fn(&mut self,
607 function_kind: FnKind<'v>,
608 declaration: &'v FnDecl,
612 let rib_kind = match function_kind {
613 FnKind::ItemFn(_, generics, _, _, _, _) => {
614 self.visit_generics(generics);
617 FnKind::Method(_, sig, _) => {
618 self.visit_generics(&sig.generics);
619 self.visit_explicit_self(&sig.explicit_self);
622 FnKind::Closure => ClosureRibKind(node_id),
624 self.resolve_function(rib_kind, declaration, block);
628 type ErrorMessage = Option<(Span, String)>;
630 enum ResolveResult<T> {
631 Failed(ErrorMessage), // Failed to resolve the name, optional helpful error message.
632 Indeterminate, // Couldn't determine due to unresolved globs.
633 Success(T), // Successfully resolved the import.
636 impl<T> ResolveResult<T> {
637 fn success(&self) -> bool {
645 enum FallbackSuggestion {
650 StaticMethod(String),
654 #[derive(Copy, Clone)]
655 enum TypeParameters<'a> {
657 HasTypeParameters(// Type parameters.
660 // Identifies the things that these parameters
661 // were declared on (type, fn, etc)
664 // The kind of the rib used for type parameters.
668 // The rib kind controls the translation of local
669 // definitions (`DefLocal`) to upvars (`DefUpvar`).
670 #[derive(Copy, Clone, Debug)]
672 // No translation needs to be applied.
675 // We passed through a closure scope at the given node ID.
676 // Translate upvars as appropriate.
677 ClosureRibKind(NodeId /* func id */),
679 // We passed through an impl or trait and are now in one of its
680 // methods. Allow references to ty params that impl or trait
681 // binds. Disallow any other upvars (including other ty params that are
685 // We passed through an item scope. Disallow upvars.
688 // We're in a constant item. Can't refer to dynamic stuff.
692 #[derive(Copy, Clone)]
693 enum UseLexicalScopeFlag {
698 enum ModulePrefixResult {
700 PrefixFound(Rc<Module>, usize),
703 #[derive(Copy, Clone)]
704 enum AssocItemResolveResult {
705 /// Syntax such as `<T>::item`, which can't be resolved until type
708 /// We should have been able to resolve the associated item.
709 ResolveAttempt(Option<PathResolution>),
712 #[derive(Copy, Clone, PartialEq)]
713 enum NameSearchType {
714 /// We're doing a name search in order to resolve a `use` directive.
717 /// We're doing a name search in order to resolve a path type, a path
718 /// expression, or a path pattern.
722 #[derive(Copy, Clone)]
723 enum BareIdentifierPatternResolution {
724 FoundStructOrEnumVariant(Def, LastPrivate),
725 FoundConst(Def, LastPrivate, Name),
726 BareIdentifierPatternUnresolved,
732 bindings: HashMap<Name, DefLike>,
737 fn new(kind: RibKind) -> Rib {
739 bindings: HashMap::new(),
745 /// A definition along with the index of the rib it was found on
747 ribs: Option<(Namespace, usize)>,
752 fn from_def(def: Def) -> Self {
760 /// The link from a module up to its nearest parent node.
761 #[derive(Clone,Debug)]
764 ModuleParentLink(Weak<Module>, Name),
765 BlockParentLink(Weak<Module>, NodeId),
768 /// One node in the tree of modules.
770 parent_link: ParentLink,
771 def: Cell<Option<Def>>,
774 children: RefCell<HashMap<Name, NameBindings>>,
775 imports: RefCell<Vec<ImportDirective>>,
777 // The external module children of this node that were declared with
779 external_module_children: RefCell<HashMap<Name, Rc<Module>>>,
781 // The anonymous children of this node. Anonymous children are pseudo-
782 // modules that are implicitly created around items contained within
785 // For example, if we have this:
793 // There will be an anonymous module created around `g` with the ID of the
794 // entry block for `f`.
795 anonymous_children: RefCell<NodeMap<Rc<Module>>>,
797 // The status of resolving each import in this module.
798 import_resolutions: RefCell<HashMap<Name, ImportResolution>>,
800 // The number of unresolved globs that this module exports.
801 glob_count: Cell<usize>,
803 // The number of unresolved pub imports (both regular and globs) in this module
804 pub_count: Cell<usize>,
806 // The number of unresolved pub glob imports in this module
807 pub_glob_count: Cell<usize>,
809 // The index of the import we're resolving.
810 resolved_import_count: Cell<usize>,
812 // Whether this module is populated. If not populated, any attempt to
813 // access the children must be preceded with a
814 // `populate_module_if_necessary` call.
815 populated: Cell<bool>,
819 fn new(parent_link: ParentLink,
825 parent_link: parent_link,
827 is_public: is_public,
828 children: RefCell::new(HashMap::new()),
829 imports: RefCell::new(Vec::new()),
830 external_module_children: RefCell::new(HashMap::new()),
831 anonymous_children: RefCell::new(NodeMap()),
832 import_resolutions: RefCell::new(HashMap::new()),
833 glob_count: Cell::new(0),
834 pub_count: Cell::new(0),
835 pub_glob_count: Cell::new(0),
836 resolved_import_count: Cell::new(0),
837 populated: Cell::new(!external),
841 fn def_id(&self) -> Option<DefId> {
842 self.def.get().as_ref().map(Def::def_id)
845 fn is_normal(&self) -> bool {
846 match self.def.get() {
847 Some(DefMod(_)) | Some(DefForeignMod(_)) => true,
852 fn is_trait(&self) -> bool {
853 match self.def.get() {
854 Some(DefTrait(_)) => true,
859 fn all_imports_resolved(&self) -> bool {
860 if self.imports.borrow_state() == ::std::cell::BorrowState::Writing {
861 // it is currently being resolved ! so nope
864 self.imports.borrow().len() == self.resolved_import_count.get()
870 pub fn inc_glob_count(&self) {
871 self.glob_count.set(self.glob_count.get() + 1);
873 pub fn dec_glob_count(&self) {
874 assert!(self.glob_count.get() > 0);
875 self.glob_count.set(self.glob_count.get() - 1);
877 pub fn inc_pub_count(&self) {
878 self.pub_count.set(self.pub_count.get() + 1);
880 pub fn dec_pub_count(&self) {
881 assert!(self.pub_count.get() > 0);
882 self.pub_count.set(self.pub_count.get() - 1);
884 pub fn inc_pub_glob_count(&self) {
885 self.pub_glob_count.set(self.pub_glob_count.get() + 1);
887 pub fn dec_pub_glob_count(&self) {
888 assert!(self.pub_glob_count.get() > 0);
889 self.pub_glob_count.set(self.pub_glob_count.get() - 1);
893 impl fmt::Debug for Module {
894 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
908 flags DefModifiers: u8 {
909 const PUBLIC = 1 << 0,
910 const IMPORTABLE = 1 << 1,
914 // Records a possibly-private value, type, or module definition.
917 modifiers: DefModifiers, // see note in ImportResolution about how to use this
918 def_or_module: DefOrModule,
929 fn create_from_module(module: Rc<Module>, span: Option<Span>) -> Self {
930 let modifiers = if module.is_public {
933 DefModifiers::empty()
934 } | DefModifiers::IMPORTABLE;
936 NsDef { modifiers: modifiers, def_or_module: DefOrModule::Module(module), span: span }
939 fn create_from_def(def: Def, modifiers: DefModifiers, span: Option<Span>) -> Self {
940 NsDef { modifiers: modifiers, def_or_module: DefOrModule::Def(def), span: span }
943 fn module(&self) -> Option<Rc<Module>> {
944 match self.def_or_module {
945 DefOrModule::Module(ref module) => Some(module.clone()),
946 DefOrModule::Def(_) => None,
950 fn def(&self) -> Option<Def> {
951 match self.def_or_module {
952 DefOrModule::Def(def) => Some(def),
953 DefOrModule::Module(ref module) => module.def.get(),
958 // Records at most one definition that a name in a namespace is bound to
959 #[derive(Clone,Debug)]
960 pub struct NameBinding(Rc<RefCell<Option<NsDef>>>);
964 NameBinding(Rc::new(RefCell::new(None)))
967 fn create_from_module(module: Rc<Module>) -> Self {
968 NameBinding(Rc::new(RefCell::new(Some(NsDef::create_from_module(module, None)))))
971 fn set(&self, ns_def: NsDef) {
972 *self.0.borrow_mut() = Some(ns_def);
975 fn set_modifiers(&self, modifiers: DefModifiers) {
976 if let Some(ref mut ns_def) = *self.0.borrow_mut() {
977 ns_def.modifiers = modifiers
981 fn borrow(&self) -> ::std::cell::Ref<Option<NsDef>> {
985 // Lifted versions of the NsDef methods and fields
986 fn def(&self) -> Option<Def> {
987 self.borrow().as_ref().and_then(NsDef::def)
989 fn module(&self) -> Option<Rc<Module>> {
990 self.borrow().as_ref().and_then(NsDef::module)
992 fn span(&self) -> Option<Span> {
993 self.borrow().as_ref().and_then(|def| def.span)
995 fn modifiers(&self) -> Option<DefModifiers> {
996 self.borrow().as_ref().and_then(|def| Some(def.modifiers))
999 fn defined(&self) -> bool {
1000 self.borrow().is_some()
1003 fn defined_with(&self, modifiers: DefModifiers) -> bool {
1004 self.modifiers().map(|m| m.contains(modifiers)).unwrap_or(false)
1007 fn is_public(&self) -> bool {
1008 self.defined_with(DefModifiers::PUBLIC)
1011 fn def_and_lp(&self) -> (Def, LastPrivate) {
1012 let def = self.def().unwrap();
1013 (def, LastMod(if self.is_public() { AllPublic } else { DependsOn(def.def_id()) }))
1017 // Records the definitions (at most one for each namespace) that a name is
1019 #[derive(Clone,Debug)]
1020 pub struct NameBindings {
1021 type_ns: NameBinding, // < Meaning in type namespace.
1022 value_ns: NameBinding, // < Meaning in value namespace.
1025 impl ::std::ops::Index<Namespace> for NameBindings {
1026 type Output = NameBinding;
1027 fn index(&self, namespace: Namespace) -> &NameBinding {
1028 match namespace { TypeNS => &self.type_ns, ValueNS => &self.value_ns }
1033 fn new() -> NameBindings {
1035 type_ns: NameBinding::new(),
1036 value_ns: NameBinding::new(),
1040 /// Creates a new module in this set of name bindings.
1041 fn define_module(&self, module: Rc<Module>, sp: Span) {
1042 self.type_ns.set(NsDef::create_from_module(module, Some(sp)));
1045 /// Records a type definition.
1046 fn define_type(&self, def: Def, sp: Span, modifiers: DefModifiers) {
1047 debug!("defining type for def {:?} with modifiers {:?}", def, modifiers);
1048 self.type_ns.set(NsDef::create_from_def(def, modifiers, Some(sp)));
1051 /// Records a value definition.
1052 fn define_value(&self, def: Def, sp: Span, modifiers: DefModifiers) {
1053 debug!("defining value for def {:?} with modifiers {:?}", def, modifiers);
1054 self.value_ns.set(NsDef::create_from_def(def, modifiers, Some(sp)));
1058 /// Interns the names of the primitive types.
1059 struct PrimitiveTypeTable {
1060 primitive_types: HashMap<Name, PrimTy>,
1063 impl PrimitiveTypeTable {
1064 fn new() -> PrimitiveTypeTable {
1065 let mut table = PrimitiveTypeTable { primitive_types: HashMap::new() };
1067 table.intern("bool", TyBool);
1068 table.intern("char", TyChar);
1069 table.intern("f32", TyFloat(TyF32));
1070 table.intern("f64", TyFloat(TyF64));
1071 table.intern("isize", TyInt(TyIs));
1072 table.intern("i8", TyInt(TyI8));
1073 table.intern("i16", TyInt(TyI16));
1074 table.intern("i32", TyInt(TyI32));
1075 table.intern("i64", TyInt(TyI64));
1076 table.intern("str", TyStr);
1077 table.intern("usize", TyUint(TyUs));
1078 table.intern("u8", TyUint(TyU8));
1079 table.intern("u16", TyUint(TyU16));
1080 table.intern("u32", TyUint(TyU32));
1081 table.intern("u64", TyUint(TyU64));
1086 fn intern(&mut self, string: &str, primitive_type: PrimTy) {
1087 self.primitive_types.insert(token::intern(string), primitive_type);
1091 /// The main resolver class.
1092 pub struct Resolver<'a, 'tcx: 'a> {
1093 session: &'a Session,
1095 ast_map: &'a hir_map::Map<'tcx>,
1097 graph_root: Rc<Module>,
1099 trait_item_map: FnvHashMap<(Name, DefId), DefId>,
1101 structs: FnvHashMap<DefId, Vec<Name>>,
1103 // The number of imports that are currently unresolved.
1104 unresolved_imports: usize,
1106 // The module that represents the current item scope.
1107 current_module: Rc<Module>,
1109 // The current set of local scopes, for values.
1110 // FIXME #4948: Reuse ribs to avoid allocation.
1111 value_ribs: Vec<Rib>,
1113 // The current set of local scopes, for types.
1114 type_ribs: Vec<Rib>,
1116 // The current set of local scopes, for labels.
1117 label_ribs: Vec<Rib>,
1119 // The trait that the current context can refer to.
1120 current_trait_ref: Option<(DefId, TraitRef)>,
1122 // The current self type if inside an impl (used for better errors).
1123 current_self_type: Option<Ty>,
1125 // The idents for the primitive types.
1126 primitive_type_table: PrimitiveTypeTable,
1128 def_map: RefCell<DefMap>,
1129 freevars: FreevarMap,
1130 freevars_seen: NodeMap<NodeMap<usize>>,
1131 export_map: ExportMap,
1132 trait_map: TraitMap,
1133 external_exports: ExternalExports,
1135 // Whether or not to print error messages. Can be set to true
1136 // when getting additional info for error message suggestions,
1137 // so as to avoid printing duplicate errors
1140 make_glob_map: bool,
1141 // Maps imports to the names of items actually imported (this actually maps
1142 // all imports, but only glob imports are actually interesting).
1145 used_imports: HashSet<(NodeId, Namespace)>,
1146 used_crates: HashSet<CrateNum>,
1148 // Callback function for intercepting walks
1149 callback: Option<Box<Fn(hir_map::Node, &mut bool) -> bool>>,
1150 // The intention is that the callback modifies this flag.
1151 // Once set, the resolver falls out of the walk, preserving the ribs.
1155 #[derive(PartialEq)]
1156 enum FallbackChecks {
1158 OnlyTraitAndStatics,
1161 impl<'a, 'tcx> Resolver<'a, 'tcx> {
1162 fn new(session: &'a Session,
1163 ast_map: &'a hir_map::Map<'tcx>,
1164 make_glob_map: MakeGlobMap)
1165 -> Resolver<'a, 'tcx> {
1166 let root_def_id = ast_map.local_def_id(CRATE_NODE_ID);
1167 let graph_root = Module::new(NoParentLink, Some(DefMod(root_def_id)), false, true);
1174 // The outermost module has def ID 0; this is not reflected in the
1176 graph_root: graph_root.clone(),
1178 trait_item_map: FnvHashMap(),
1179 structs: FnvHashMap(),
1181 unresolved_imports: 0,
1183 current_module: graph_root,
1184 value_ribs: Vec::new(),
1185 type_ribs: Vec::new(),
1186 label_ribs: Vec::new(),
1188 current_trait_ref: None,
1189 current_self_type: None,
1191 primitive_type_table: PrimitiveTypeTable::new(),
1193 def_map: RefCell::new(NodeMap()),
1194 freevars: NodeMap(),
1195 freevars_seen: NodeMap(),
1196 export_map: NodeMap(),
1197 trait_map: NodeMap(),
1198 used_imports: HashSet::new(),
1199 used_crates: HashSet::new(),
1200 external_exports: DefIdSet(),
1203 make_glob_map: make_glob_map == MakeGlobMap::Yes,
1204 glob_map: HashMap::new(),
1212 fn record_import_use(&mut self, import_id: NodeId, name: Name) {
1213 if !self.make_glob_map {
1216 if self.glob_map.contains_key(&import_id) {
1217 self.glob_map.get_mut(&import_id).unwrap().insert(name);
1221 let mut new_set = HashSet::new();
1222 new_set.insert(name);
1223 self.glob_map.insert(import_id, new_set);
1226 fn get_trait_name(&self, did: DefId) -> Name {
1227 if let Some(node_id) = self.ast_map.as_local_node_id(did) {
1228 self.ast_map.expect_item(node_id).name
1230 self.session.cstore.item_name(did)
1234 /// Checks that the names of external crates don't collide with other
1235 /// external crates.
1236 fn check_for_conflicts_between_external_crates(&self,
1240 if module.external_module_children.borrow().contains_key(&name) {
1241 span_err!(self.session,
1244 "an external crate named `{}` has already been imported into this module",
1249 /// Checks that the names of items don't collide with external crates.
1250 fn check_for_conflicts_between_external_crates_and_items(&self,
1254 if module.external_module_children.borrow().contains_key(&name) {
1255 span_err!(self.session,
1258 "the name `{}` conflicts with an external crate that has been imported \
1264 /// Resolves the given module path from the given root `module_`.
1265 fn resolve_module_path_from_root(&mut self,
1266 module_: Rc<Module>,
1267 module_path: &[Name],
1270 name_search_type: NameSearchType,
1272 -> ResolveResult<(Rc<Module>, LastPrivate)> {
1273 fn search_parent_externals(needle: Name, module: &Rc<Module>) -> Option<Rc<Module>> {
1274 match module.external_module_children.borrow().get(&needle) {
1275 Some(_) => Some(module.clone()),
1276 None => match module.parent_link {
1277 ModuleParentLink(ref parent, _) => {
1278 search_parent_externals(needle, &parent.upgrade().unwrap())
1285 let mut search_module = module_;
1286 let mut index = index;
1287 let module_path_len = module_path.len();
1288 let mut closest_private = lp;
1290 // Resolve the module part of the path. This does not involve looking
1291 // upward though scope chains; we simply resolve names directly in
1292 // modules as we go.
1293 while index < module_path_len {
1294 let name = module_path[index];
1295 match self.resolve_name_in_module(search_module.clone(),
1301 let segment_name = name.as_str();
1302 let module_name = module_to_string(&*search_module);
1303 let mut span = span;
1304 let msg = if "???" == &module_name[..] {
1305 span.hi = span.lo + Pos::from_usize(segment_name.len());
1307 match search_parent_externals(name, &self.current_module) {
1309 let path_str = names_to_string(module_path);
1310 let target_mod_str = module_to_string(&*module);
1311 let current_mod_str = module_to_string(&*self.current_module);
1313 let prefix = if target_mod_str == current_mod_str {
1314 "self::".to_string()
1316 format!("{}::", target_mod_str)
1319 format!("Did you mean `{}{}`?", prefix, path_str)
1321 None => format!("Maybe a missing `extern crate {}`?", segment_name),
1324 format!("Could not find `{}` in `{}`", segment_name, module_name)
1327 return Failed(Some((span, msg)));
1329 Failed(err) => return Failed(err),
1331 debug!("(resolving module path for import) module resolution is \
1334 return Indeterminate;
1336 Success((target, used_proxy)) => {
1337 // Check to see whether there are type bindings, and, if
1338 // so, whether there is a module within.
1339 if let Some(module_def) = target.binding.module() {
1340 // track extern crates for unused_extern_crate lint
1341 if let Some(did) = module_def.def_id() {
1342 self.used_crates.insert(did.krate);
1345 search_module = module_def;
1347 // Keep track of the closest private module used
1348 // when resolving this import chain.
1349 if !used_proxy && !search_module.is_public {
1350 if let Some(did) = search_module.def_id() {
1351 closest_private = LastMod(DependsOn(did));
1355 let msg = format!("Not a module `{}`", name);
1356 return Failed(Some((span, msg)));
1364 return Success((search_module, closest_private));
1367 /// Attempts to resolve the module part of an import directive or path
1368 /// rooted at the given module.
1370 /// On success, returns the resolved module, and the closest *private*
1371 /// module found to the destination when resolving this path.
1372 fn resolve_module_path(&mut self,
1373 module_: Rc<Module>,
1374 module_path: &[Name],
1375 use_lexical_scope: UseLexicalScopeFlag,
1377 name_search_type: NameSearchType)
1378 -> ResolveResult<(Rc<Module>, LastPrivate)> {
1379 let module_path_len = module_path.len();
1380 assert!(module_path_len > 0);
1382 debug!("(resolving module path for import) processing `{}` rooted at `{}`",
1383 names_to_string(module_path),
1384 module_to_string(&*module_));
1386 // Resolve the module prefix, if any.
1387 let module_prefix_result = self.resolve_module_prefix(module_.clone(), module_path);
1392 match module_prefix_result {
1394 let mpath = names_to_string(module_path);
1395 let mpath = &mpath[..];
1396 match mpath.rfind(':') {
1398 let msg = format!("Could not find `{}` in `{}`",
1399 // idx +- 1 to account for the
1400 // colons on either side
1403 return Failed(Some((span, msg)));
1406 return Failed(None);
1410 Failed(err) => return Failed(err),
1412 debug!("(resolving module path for import) indeterminate; bailing");
1413 return Indeterminate;
1415 Success(NoPrefixFound) => {
1416 // There was no prefix, so we're considering the first element
1417 // of the path. How we handle this depends on whether we were
1418 // instructed to use lexical scope or not.
1419 match use_lexical_scope {
1420 DontUseLexicalScope => {
1421 // This is a crate-relative path. We will start the
1422 // resolution process at index zero.
1423 search_module = self.graph_root.clone();
1425 last_private = LastMod(AllPublic);
1427 UseLexicalScope => {
1428 // This is not a crate-relative path. We resolve the
1429 // first component of the path in the current lexical
1430 // scope and then proceed to resolve below that.
1431 match self.resolve_module_in_lexical_scope(module_, module_path[0]) {
1432 Failed(err) => return Failed(err),
1434 debug!("(resolving module path for import) indeterminate; bailing");
1435 return Indeterminate;
1437 Success(containing_module) => {
1438 search_module = containing_module;
1440 last_private = LastMod(AllPublic);
1446 Success(PrefixFound(ref containing_module, index)) => {
1447 search_module = containing_module.clone();
1448 start_index = index;
1449 last_private = LastMod(DependsOn(containing_module.def_id()
1454 self.resolve_module_path_from_root(search_module,
1462 /// Invariant: This must only be called during main resolution, not during
1463 /// import resolution.
1464 fn resolve_item_in_lexical_scope(&mut self,
1465 module_: Rc<Module>,
1467 namespace: Namespace)
1468 -> ResolveResult<(Target, bool)> {
1469 debug!("(resolving item in lexical scope) resolving `{}` in namespace {:?} in `{}`",
1472 module_to_string(&*module_));
1474 // The current module node is handled specially. First, check for
1475 // its immediate children.
1476 build_reduced_graph::populate_module_if_necessary(self, &module_);
1478 match module_.children.borrow().get(&name) {
1479 Some(name_bindings) if name_bindings[namespace].defined() => {
1480 debug!("top name bindings succeeded");
1481 return Success((Target::new(module_.clone(),
1482 name_bindings[namespace].clone(),
1487 // Not found; continue.
1491 // Now check for its import directives. We don't have to have resolved
1492 // all its imports in the usual way; this is because chains of
1493 // adjacent import statements are processed as though they mutated the
1495 if let Some(import_resolution) = module_.import_resolutions.borrow().get(&name) {
1496 match (*import_resolution).target_for_namespace(namespace) {
1498 // Not found; continue.
1499 debug!("(resolving item in lexical scope) found import resolution, but not \
1504 debug!("(resolving item in lexical scope) using import resolution");
1505 // track used imports and extern crates as well
1506 let id = import_resolution.id(namespace);
1507 self.used_imports.insert((id, namespace));
1508 self.record_import_use(id, name);
1509 if let Some(DefId{krate: kid, ..}) = target.target_module.def_id() {
1510 self.used_crates.insert(kid);
1512 return Success((target, false));
1517 // Search for external modules.
1518 if namespace == TypeNS {
1519 // FIXME (21114): In principle unclear `child` *has* to be lifted.
1520 let child = module_.external_module_children.borrow().get(&name).cloned();
1521 if let Some(module) = child {
1522 let name_binding = NameBinding::create_from_module(module);
1523 debug!("lower name bindings succeeded");
1524 return Success((Target::new(module_, name_binding, Shadowable::Never),
1529 // Finally, proceed up the scope chain looking for parent modules.
1530 let mut search_module = module_;
1532 // Go to the next parent.
1533 match search_module.parent_link.clone() {
1535 // No more parents. This module was unresolved.
1536 debug!("(resolving item in lexical scope) unresolved module");
1537 return Failed(None);
1539 ModuleParentLink(parent_module_node, _) => {
1540 if search_module.is_normal() {
1541 // We stop the search here.
1542 debug!("(resolving item in lexical scope) unresolved module: not \
1543 searching through module parents");
1544 return Failed(None);
1546 search_module = parent_module_node.upgrade().unwrap();
1549 BlockParentLink(ref parent_module_node, _) => {
1550 search_module = parent_module_node.upgrade().unwrap();
1554 // Resolve the name in the parent module.
1555 match self.resolve_name_in_module(search_module.clone(),
1560 Failed(Some((span, msg))) => {
1561 resolve_error(self, span, ResolutionError::FailedToResolve(&*msg));
1563 Failed(None) => (), // Continue up the search chain.
1565 // We couldn't see through the higher scope because of an
1566 // unresolved import higher up. Bail.
1568 debug!("(resolving item in lexical scope) indeterminate higher scope; bailing");
1569 return Indeterminate;
1571 Success((target, used_reexport)) => {
1572 // We found the module.
1573 debug!("(resolving item in lexical scope) found name in module, done");
1574 return Success((target, used_reexport));
1580 /// Resolves a module name in the current lexical scope.
1581 fn resolve_module_in_lexical_scope(&mut self,
1582 module_: Rc<Module>,
1584 -> ResolveResult<Rc<Module>> {
1585 // If this module is an anonymous module, resolve the item in the
1586 // lexical scope. Otherwise, resolve the item from the crate root.
1587 let resolve_result = self.resolve_item_in_lexical_scope(module_, name, TypeNS);
1588 match resolve_result {
1589 Success((target, _)) => {
1590 if let Some(module_def) = target.binding.module() {
1591 return Success(module_def)
1593 debug!("!!! (resolving module in lexical scope) module \
1594 wasn't actually a module!");
1595 return Failed(None);
1599 debug!("(resolving module in lexical scope) indeterminate; bailing");
1600 return Indeterminate;
1603 debug!("(resolving module in lexical scope) failed to resolve");
1609 /// Returns the nearest normal module parent of the given module.
1610 fn get_nearest_normal_module_parent(&mut self, module_: Rc<Module>) -> Option<Rc<Module>> {
1611 let mut module_ = module_;
1613 match module_.parent_link.clone() {
1614 NoParentLink => return None,
1615 ModuleParentLink(new_module, _) |
1616 BlockParentLink(new_module, _) => {
1617 let new_module = new_module.upgrade().unwrap();
1618 if new_module.is_normal() {
1619 return Some(new_module);
1621 module_ = new_module;
1627 /// Returns the nearest normal module parent of the given module, or the
1628 /// module itself if it is a normal module.
1629 fn get_nearest_normal_module_parent_or_self(&mut self, module_: Rc<Module>) -> Rc<Module> {
1630 if module_.is_normal() {
1633 match self.get_nearest_normal_module_parent(module_.clone()) {
1635 Some(new_module) => new_module,
1639 /// Resolves a "module prefix". A module prefix is one or both of (a) `self::`;
1640 /// (b) some chain of `super::`.
1641 /// grammar: (SELF MOD_SEP ) ? (SUPER MOD_SEP) *
1642 fn resolve_module_prefix(&mut self,
1643 module_: Rc<Module>,
1644 module_path: &[Name])
1645 -> ResolveResult<ModulePrefixResult> {
1646 // Start at the current module if we see `self` or `super`, or at the
1647 // top of the crate otherwise.
1648 let mut i = match &*module_path[0].as_str() {
1651 _ => return Success(NoPrefixFound),
1653 let mut containing_module = self.get_nearest_normal_module_parent_or_self(module_);
1655 // Now loop through all the `super`s we find.
1656 while i < module_path.len() && "super" == module_path[i].as_str() {
1657 debug!("(resolving module prefix) resolving `super` at {}",
1658 module_to_string(&*containing_module));
1659 match self.get_nearest_normal_module_parent(containing_module) {
1660 None => return Failed(None),
1661 Some(new_module) => {
1662 containing_module = new_module;
1668 debug!("(resolving module prefix) finished resolving prefix at {}",
1669 module_to_string(&*containing_module));
1671 return Success(PrefixFound(containing_module, i));
1674 /// Attempts to resolve the supplied name in the given module for the
1675 /// given namespace. If successful, returns the target corresponding to
1678 /// The boolean returned on success is an indicator of whether this lookup
1679 /// passed through a public re-export proxy.
1680 fn resolve_name_in_module(&mut self,
1681 module_: Rc<Module>,
1683 namespace: Namespace,
1684 name_search_type: NameSearchType,
1685 allow_private_imports: bool)
1686 -> ResolveResult<(Target, bool)> {
1687 debug!("(resolving name in module) resolving `{}` in `{}`",
1689 module_to_string(&*module_));
1691 // First, check the direct children of the module.
1692 build_reduced_graph::populate_module_if_necessary(self, &module_);
1694 match module_.children.borrow().get(&name) {
1695 Some(name_bindings) if name_bindings[namespace].defined() => {
1696 debug!("(resolving name in module) found node as child");
1697 return Success((Target::new(module_.clone(),
1698 name_bindings[namespace].clone(),
1707 // Next, check the module's imports if necessary.
1709 // If this is a search of all imports, we should be done with glob
1710 // resolution at this point.
1711 if name_search_type == PathSearch {
1712 assert_eq!(module_.glob_count.get(), 0);
1715 // Check the list of resolved imports.
1716 match module_.import_resolutions.borrow().get(&name) {
1717 Some(import_resolution) if allow_private_imports || import_resolution.is_public => {
1719 if import_resolution.is_public && import_resolution.outstanding_references != 0 {
1720 debug!("(resolving name in module) import unresolved; bailing out");
1721 return Indeterminate;
1723 match import_resolution.target_for_namespace(namespace) {
1725 debug!("(resolving name in module) name found, but not in namespace {:?}",
1729 debug!("(resolving name in module) resolved to import");
1730 // track used imports and extern crates as well
1731 let id = import_resolution.id(namespace);
1732 self.used_imports.insert((id, namespace));
1733 self.record_import_use(id, name);
1734 if let Some(DefId{krate: kid, ..}) = target.target_module.def_id() {
1735 self.used_crates.insert(kid);
1737 return Success((target, true));
1741 Some(..) | None => {} // Continue.
1744 // Finally, search through external children.
1745 if namespace == TypeNS {
1746 // FIXME (21114): In principle unclear `child` *has* to be lifted.
1747 let child = module_.external_module_children.borrow().get(&name).cloned();
1748 if let Some(module) = child {
1749 let name_binding = NameBinding::create_from_module(module);
1750 return Success((Target::new(module_, name_binding, Shadowable::Never),
1755 // We're out of luck.
1756 debug!("(resolving name in module) failed to resolve `{}`", name);
1757 return Failed(None);
1760 fn report_unresolved_imports(&mut self, module_: Rc<Module>) {
1761 let index = module_.resolved_import_count.get();
1762 let imports = module_.imports.borrow();
1763 let import_count = imports.len();
1764 if index != import_count {
1766 (*imports)[index].span,
1767 ResolutionError::UnresolvedImport(None));
1770 // Descend into children and anonymous children.
1771 build_reduced_graph::populate_module_if_necessary(self, &module_);
1773 for (_, child_node) in module_.children.borrow().iter() {
1774 match child_node.type_ns.module() {
1778 Some(child_module) => {
1779 self.report_unresolved_imports(child_module);
1784 for (_, module_) in module_.anonymous_children.borrow().iter() {
1785 self.report_unresolved_imports(module_.clone());
1791 // We maintain a list of value ribs and type ribs.
1793 // Simultaneously, we keep track of the current position in the module
1794 // graph in the `current_module` pointer. When we go to resolve a name in
1795 // the value or type namespaces, we first look through all the ribs and
1796 // then query the module graph. When we resolve a name in the module
1797 // namespace, we can skip all the ribs (since nested modules are not
1798 // allowed within blocks in Rust) and jump straight to the current module
1801 // Named implementations are handled separately. When we find a method
1802 // call, we consult the module node to find all of the implementations in
1803 // scope. This information is lazily cached in the module node. We then
1804 // generate a fake "implementation scope" containing all the
1805 // implementations thus found, for compatibility with old resolve pass.
1807 fn with_scope<F>(&mut self, name: Option<Name>, f: F)
1808 where F: FnOnce(&mut Resolver)
1810 let orig_module = self.current_module.clone();
1812 // Move down in the graph.
1818 build_reduced_graph::populate_module_if_necessary(self, &orig_module);
1820 match orig_module.children.borrow().get(&name) {
1822 debug!("!!! (with scope) didn't find `{}` in `{}`",
1824 module_to_string(&*orig_module));
1826 Some(name_bindings) => {
1827 match name_bindings.type_ns.module() {
1829 debug!("!!! (with scope) didn't find module for `{}` in `{}`",
1831 module_to_string(&*orig_module));
1834 self.current_module = module_;
1844 self.current_module = orig_module;
1847 /// Searches the current set of local scopes for labels.
1848 /// Stops after meeting a closure.
1849 fn search_label(&self, name: Name) -> Option<DefLike> {
1850 for rib in self.label_ribs.iter().rev() {
1856 // Do not resolve labels across function boundary
1860 let result = rib.bindings.get(&name).cloned();
1861 if result.is_some() {
1868 fn resolve_crate(&mut self, krate: &hir::Crate) {
1869 debug!("(resolving crate) starting");
1871 intravisit::walk_crate(self, krate);
1874 fn check_if_primitive_type_name(&self, name: Name, span: Span) {
1875 if let Some(_) = self.primitive_type_table.primitive_types.get(&name) {
1876 span_err!(self.session,
1879 "user-defined types or type parameters cannot shadow the primitive types");
1883 fn resolve_item(&mut self, item: &Item) {
1884 let name = item.name;
1886 debug!("(resolving item) resolving {}", name);
1889 ItemEnum(_, ref generics) |
1890 ItemTy(_, ref generics) |
1891 ItemStruct(_, ref generics) => {
1892 self.check_if_primitive_type_name(name, item.span);
1894 self.with_type_parameter_rib(HasTypeParameters(generics, TypeSpace, ItemRibKind),
1895 |this| intravisit::walk_item(this, item));
1897 ItemFn(_, _, _, _, ref generics, _) => {
1898 self.with_type_parameter_rib(HasTypeParameters(generics, FnSpace, ItemRibKind),
1899 |this| intravisit::walk_item(this, item));
1902 ItemDefaultImpl(_, ref trait_ref) => {
1903 self.with_optional_trait_ref(Some(trait_ref), |_, _| {});
1905 ItemImpl(_, _, ref generics, ref opt_trait_ref, ref self_type, ref impl_items) => {
1906 self.resolve_implementation(generics,
1913 ItemTrait(_, ref generics, ref bounds, ref trait_items) => {
1914 self.check_if_primitive_type_name(name, item.span);
1916 // Create a new rib for the trait-wide type parameters.
1917 self.with_type_parameter_rib(HasTypeParameters(generics,
1921 let local_def_id = this.ast_map.local_def_id(item.id);
1922 this.with_self_rib(DefSelfTy(Some(local_def_id), None), |this| {
1923 this.visit_generics(generics);
1924 walk_list!(this, visit_ty_param_bound, bounds);
1926 for trait_item in trait_items {
1927 match trait_item.node {
1928 hir::ConstTraitItem(_, ref default) => {
1929 // Only impose the restrictions of
1930 // ConstRibKind if there's an actual constant
1931 // expression in a provided default.
1932 if default.is_some() {
1933 this.with_constant_rib(|this| {
1934 intravisit::walk_trait_item(this, trait_item)
1937 intravisit::walk_trait_item(this, trait_item)
1940 hir::MethodTraitItem(ref sig, _) => {
1941 let type_parameters =
1942 HasTypeParameters(&sig.generics,
1945 this.with_type_parameter_rib(type_parameters, |this| {
1946 intravisit::walk_trait_item(this, trait_item)
1949 hir::TypeTraitItem(..) => {
1950 this.check_if_primitive_type_name(trait_item.name,
1952 this.with_type_parameter_rib(NoTypeParameters, |this| {
1953 intravisit::walk_trait_item(this, trait_item)
1962 ItemMod(_) | ItemForeignMod(_) => {
1963 self.with_scope(Some(name), |this| {
1964 intravisit::walk_item(this, item);
1968 ItemConst(..) | ItemStatic(..) => {
1969 self.with_constant_rib(|this| {
1970 intravisit::walk_item(this, item);
1974 ItemUse(ref view_path) => {
1975 // check for imports shadowing primitive types
1976 let check_rename = |this: &Self, id, name| {
1977 match this.def_map.borrow().get(&id).map(|d| d.full_def()) {
1978 Some(DefTy(..)) | Some(DefStruct(..)) | Some(DefTrait(..)) | None => {
1979 this.check_if_primitive_type_name(name, item.span);
1985 match view_path.node {
1986 hir::ViewPathSimple(name, _) => {
1987 check_rename(self, item.id, name);
1989 hir::ViewPathList(ref prefix, ref items) => {
1991 if let Some(name) = item.node.rename() {
1992 check_rename(self, item.node.id(), name);
1996 // Resolve prefix of an import with empty braces (issue #28388)
1997 if items.is_empty() && !prefix.segments.is_empty() {
1998 match self.resolve_crate_relative_path(prefix.span,
2002 self.record_def(item.id, PathResolution::new(def, lp, 0)),
2006 ResolutionError::FailedToResolve(
2007 &path_names_to_string(prefix, 0)));
2016 ItemExternCrate(_) => {
2017 // do nothing, these are just around to be encoded
2022 fn with_type_parameter_rib<F>(&mut self, type_parameters: TypeParameters, f: F)
2023 where F: FnOnce(&mut Resolver)
2025 match type_parameters {
2026 HasTypeParameters(generics, space, rib_kind) => {
2027 let mut function_type_rib = Rib::new(rib_kind);
2028 let mut seen_bindings = HashSet::new();
2029 for (index, type_parameter) in generics.ty_params.iter().enumerate() {
2030 let name = type_parameter.name;
2031 debug!("with_type_parameter_rib: {}", type_parameter.id);
2033 if seen_bindings.contains(&name) {
2035 type_parameter.span,
2036 ResolutionError::NameAlreadyUsedInTypeParameterList(name));
2038 seen_bindings.insert(name);
2040 // plain insert (no renaming)
2041 function_type_rib.bindings
2043 DlDef(DefTyParam(space,
2046 .local_def_id(type_parameter.id),
2049 self.type_ribs.push(function_type_rib);
2052 NoTypeParameters => {
2059 match type_parameters {
2060 HasTypeParameters(..) => {
2062 self.type_ribs.pop();
2065 NoTypeParameters => {}
2069 fn with_label_rib<F>(&mut self, f: F)
2070 where F: FnOnce(&mut Resolver)
2072 self.label_ribs.push(Rib::new(NormalRibKind));
2075 self.label_ribs.pop();
2079 fn with_constant_rib<F>(&mut self, f: F)
2080 where F: FnOnce(&mut Resolver)
2082 self.value_ribs.push(Rib::new(ConstantItemRibKind));
2083 self.type_ribs.push(Rib::new(ConstantItemRibKind));
2086 self.type_ribs.pop();
2087 self.value_ribs.pop();
2091 fn resolve_function(&mut self, rib_kind: RibKind, declaration: &FnDecl, block: &Block) {
2092 // Create a value rib for the function.
2093 self.value_ribs.push(Rib::new(rib_kind));
2095 // Create a label rib for the function.
2096 self.label_ribs.push(Rib::new(rib_kind));
2098 // Add each argument to the rib.
2099 let mut bindings_list = HashMap::new();
2100 for argument in &declaration.inputs {
2101 self.resolve_pattern(&*argument.pat, ArgumentIrrefutableMode, &mut bindings_list);
2103 self.visit_ty(&*argument.ty);
2105 debug!("(resolving function) recorded argument");
2107 intravisit::walk_fn_ret_ty(self, &declaration.output);
2109 // Resolve the function body.
2110 self.visit_block(block);
2112 debug!("(resolving function) leaving function");
2115 self.label_ribs.pop();
2116 self.value_ribs.pop();
2120 fn resolve_trait_reference(&mut self,
2124 -> Result<PathResolution, ()> {
2125 if let Some(path_res) = self.resolve_path(id, trait_path, path_depth, TypeNS, true) {
2126 if let DefTrait(_) = path_res.base_def {
2127 debug!("(resolving trait) found trait def: {:?}", path_res);
2132 ResolutionError::IsNotATrait(&*path_names_to_string(trait_path,
2135 // If it's a typedef, give a note
2136 if let DefTy(..) = path_res.base_def {
2138 .span_note(trait_path.span, "`type` aliases cannot be used for traits");
2145 ResolutionError::UndeclaredTraitName(&*path_names_to_string(trait_path,
2151 fn resolve_generics(&mut self, generics: &Generics) {
2152 for type_parameter in generics.ty_params.iter() {
2153 self.check_if_primitive_type_name(type_parameter.name, type_parameter.span);
2155 for predicate in &generics.where_clause.predicates {
2157 &hir::WherePredicate::BoundPredicate(_) |
2158 &hir::WherePredicate::RegionPredicate(_) => {}
2159 &hir::WherePredicate::EqPredicate(ref eq_pred) => {
2160 let path_res = self.resolve_path(eq_pred.id, &eq_pred.path, 0, TypeNS, true);
2161 if let Some(PathResolution { base_def: DefTyParam(..), .. }) = path_res {
2162 self.record_def(eq_pred.id, path_res.unwrap());
2166 ResolutionError::UndeclaredAssociatedType);
2171 intravisit::walk_generics(self, generics);
2174 fn with_current_self_type<T, F>(&mut self, self_type: &Ty, f: F) -> T
2175 where F: FnOnce(&mut Resolver) -> T
2177 // Handle nested impls (inside fn bodies)
2178 let previous_value = replace(&mut self.current_self_type, Some(self_type.clone()));
2179 let result = f(self);
2180 self.current_self_type = previous_value;
2184 fn with_optional_trait_ref<T, F>(&mut self, opt_trait_ref: Option<&TraitRef>, f: F) -> T
2185 where F: FnOnce(&mut Resolver, Option<DefId>) -> T
2187 let mut new_val = None;
2188 let mut new_id = None;
2189 if let Some(trait_ref) = opt_trait_ref {
2190 if let Ok(path_res) = self.resolve_trait_reference(trait_ref.ref_id,
2193 assert!(path_res.depth == 0);
2194 self.record_def(trait_ref.ref_id, path_res);
2195 new_val = Some((path_res.base_def.def_id(), trait_ref.clone()));
2196 new_id = Some(path_res.base_def.def_id());
2198 intravisit::walk_trait_ref(self, trait_ref);
2200 let original_trait_ref = replace(&mut self.current_trait_ref, new_val);
2201 let result = f(self, new_id);
2202 self.current_trait_ref = original_trait_ref;
2206 fn with_self_rib<F>(&mut self, self_def: Def, f: F)
2207 where F: FnOnce(&mut Resolver)
2209 let mut self_type_rib = Rib::new(NormalRibKind);
2211 // plain insert (no renaming, types are not currently hygienic....)
2212 let name = special_names::type_self;
2213 self_type_rib.bindings.insert(name, DlDef(self_def));
2214 self.type_ribs.push(self_type_rib);
2217 self.type_ribs.pop();
2221 fn resolve_implementation(&mut self,
2222 generics: &Generics,
2223 opt_trait_reference: &Option<TraitRef>,
2226 impl_items: &[P<ImplItem>]) {
2227 // If applicable, create a rib for the type parameters.
2228 self.with_type_parameter_rib(HasTypeParameters(generics,
2232 // Resolve the type parameters.
2233 this.visit_generics(generics);
2235 // Resolve the trait reference, if necessary.
2236 this.with_optional_trait_ref(opt_trait_reference.as_ref(), |this, trait_id| {
2237 // Resolve the self type.
2238 this.visit_ty(self_type);
2240 this.with_self_rib(DefSelfTy(trait_id, Some((item_id, self_type.id))), |this| {
2241 this.with_current_self_type(self_type, |this| {
2242 for impl_item in impl_items {
2243 match impl_item.node {
2244 hir::ImplItemKind::Const(..) => {
2245 // If this is a trait impl, ensure the const
2247 this.check_trait_item(impl_item.name,
2249 |n, s| ResolutionError::ConstNotMemberOfTrait(n, s));
2250 this.with_constant_rib(|this| {
2251 intravisit::walk_impl_item(this, impl_item);
2254 hir::ImplItemKind::Method(ref sig, _) => {
2255 // If this is a trait impl, ensure the method
2257 this.check_trait_item(impl_item.name,
2259 |n, s| ResolutionError::MethodNotMemberOfTrait(n, s));
2261 // We also need a new scope for the method-
2262 // specific type parameters.
2263 let type_parameters =
2264 HasTypeParameters(&sig.generics,
2267 this.with_type_parameter_rib(type_parameters, |this| {
2268 intravisit::walk_impl_item(this, impl_item);
2271 hir::ImplItemKind::Type(ref ty) => {
2272 // If this is a trait impl, ensure the type
2274 this.check_trait_item(impl_item.name,
2276 |n, s| ResolutionError::TypeNotMemberOfTrait(n, s));
2288 fn check_trait_item<F>(&self, name: Name, span: Span, err: F)
2289 where F: FnOnce(Name, &str) -> ResolutionError
2291 // If there is a TraitRef in scope for an impl, then the method must be in the
2293 if let Some((did, ref trait_ref)) = self.current_trait_ref {
2294 if !self.trait_item_map.contains_key(&(name, did)) {
2295 let path_str = path_names_to_string(&trait_ref.path, 0);
2296 resolve_error(self, span, err(name, &*path_str));
2301 fn resolve_local(&mut self, local: &Local) {
2302 // Resolve the type.
2303 walk_list!(self, visit_ty, &local.ty);
2305 // Resolve the initializer.
2306 walk_list!(self, visit_expr, &local.init);
2308 // Resolve the pattern.
2309 self.resolve_pattern(&*local.pat, LocalIrrefutableMode, &mut HashMap::new());
2312 // build a map from pattern identifiers to binding-info's.
2313 // this is done hygienically. This could arise for a macro
2314 // that expands into an or-pattern where one 'x' was from the
2315 // user and one 'x' came from the macro.
2316 fn binding_mode_map(&mut self, pat: &Pat) -> BindingMap {
2317 let mut result = HashMap::new();
2318 pat_bindings_hygienic(&self.def_map, pat, |binding_mode, _id, sp, path1| {
2319 let name = mtwt::resolve(path1.node);
2323 binding_mode: binding_mode,
2329 // check that all of the arms in an or-pattern have exactly the
2330 // same set of bindings, with the same binding modes for each.
2331 fn check_consistent_bindings(&mut self, arm: &Arm) {
2332 if arm.pats.is_empty() {
2335 let map_0 = self.binding_mode_map(&*arm.pats[0]);
2336 for (i, p) in arm.pats.iter().enumerate() {
2337 let map_i = self.binding_mode_map(&**p);
2339 for (&key, &binding_0) in &map_0 {
2340 match map_i.get(&key) {
2344 ResolutionError::VariableNotBoundInPattern(key, i + 1));
2346 Some(binding_i) => {
2347 if binding_0.binding_mode != binding_i.binding_mode {
2350 ResolutionError::VariableBoundWithDifferentMode(key,
2357 for (&key, &binding) in &map_i {
2358 if !map_0.contains_key(&key) {
2361 ResolutionError::VariableNotBoundInParentPattern(key, i + 1));
2367 fn resolve_arm(&mut self, arm: &Arm) {
2368 self.value_ribs.push(Rib::new(NormalRibKind));
2370 let mut bindings_list = HashMap::new();
2371 for pattern in &arm.pats {
2372 self.resolve_pattern(&**pattern, RefutableMode, &mut bindings_list);
2375 // This has to happen *after* we determine which
2376 // pat_idents are variants
2377 self.check_consistent_bindings(arm);
2379 walk_list!(self, visit_expr, &arm.guard);
2380 self.visit_expr(&*arm.body);
2383 self.value_ribs.pop();
2387 fn resolve_block(&mut self, block: &Block) {
2388 debug!("(resolving block) entering block");
2389 self.value_ribs.push(Rib::new(NormalRibKind));
2391 // Move down in the graph, if there's an anonymous module rooted here.
2392 let orig_module = self.current_module.clone();
2393 match orig_module.anonymous_children.borrow().get(&block.id) {
2397 Some(anonymous_module) => {
2398 debug!("(resolving block) found anonymous module, moving down");
2399 self.current_module = anonymous_module.clone();
2403 // Check for imports appearing after non-item statements.
2404 let mut found_non_item = false;
2405 for statement in &block.stmts {
2406 if let hir::StmtDecl(ref declaration, _) = statement.node {
2407 if let hir::DeclItem(i) = declaration.node {
2408 let i = self.ast_map.expect_item(i.id);
2410 ItemExternCrate(_) | ItemUse(_) if found_non_item => {
2411 span_err!(self.session,
2414 "imports are not allowed after non-item statements");
2419 found_non_item = true
2422 found_non_item = true;
2426 // Descend into the block.
2427 intravisit::walk_block(self, block);
2431 self.current_module = orig_module;
2432 self.value_ribs.pop();
2434 debug!("(resolving block) leaving block");
2437 fn resolve_type(&mut self, ty: &Ty) {
2439 TyPath(ref maybe_qself, ref path) => {
2440 let resolution = match self.resolve_possibly_assoc_item(ty.id,
2441 maybe_qself.as_ref(),
2445 // `<T>::a::b::c` is resolved by typeck alone.
2446 TypecheckRequired => {
2447 // Resolve embedded types.
2448 intravisit::walk_ty(self, ty);
2451 ResolveAttempt(resolution) => resolution,
2454 // This is a path in the type namespace. Walk through scopes
2458 // Write the result into the def map.
2459 debug!("(resolving type) writing resolution for `{}` (id {}) = {:?}",
2460 path_names_to_string(path, 0),
2463 self.record_def(ty.id, def);
2466 // Keep reporting some errors even if they're ignored above.
2467 self.resolve_path(ty.id, path, 0, TypeNS, true);
2469 let kind = if maybe_qself.is_some() {
2475 let self_type_name = special_idents::type_self.name;
2476 let is_invalid_self_type_name = path.segments.len() > 0 &&
2477 maybe_qself.is_none() &&
2478 path.segments[0].identifier.name ==
2480 if is_invalid_self_type_name {
2483 ResolutionError::SelfUsedOutsideImplOrTrait);
2487 ResolutionError::UseOfUndeclared(
2489 &*path_names_to_string(path,
2498 // Resolve embedded types.
2499 intravisit::walk_ty(self, ty);
2502 fn resolve_pattern(&mut self,
2504 mode: PatternBindingMode,
2505 // Maps idents to the node ID for the (outermost)
2506 // pattern that binds them
2507 bindings_list: &mut HashMap<Name, NodeId>) {
2508 let pat_id = pattern.id;
2509 walk_pat(pattern, |pattern| {
2510 match pattern.node {
2511 PatIdent(binding_mode, ref path1, ref at_rhs) => {
2512 // The meaning of PatIdent with no type parameters
2513 // depends on whether an enum variant or unit-like struct
2514 // with that name is in scope. The probing lookup has to
2515 // be careful not to emit spurious errors. Only matching
2516 // patterns (match) can match nullary variants or
2517 // unit-like structs. For binding patterns (let
2518 // and the LHS of @-patterns), matching such a value is
2519 // simply disallowed (since it's rarely what you want).
2520 let const_ok = mode == RefutableMode && at_rhs.is_none();
2522 let ident = path1.node;
2523 let renamed = mtwt::resolve(ident);
2525 match self.resolve_bare_identifier_pattern(ident.name, pattern.span) {
2526 FoundStructOrEnumVariant(def, lp) if const_ok => {
2527 debug!("(resolving pattern) resolving `{}` to struct or enum variant",
2530 self.enforce_default_binding_mode(pattern,
2533 self.record_def(pattern.id,
2540 FoundStructOrEnumVariant(..) => {
2544 ResolutionError::DeclarationShadowsEnumVariantOrUnitLikeStruct(
2548 FoundConst(def, lp, _) if const_ok => {
2549 debug!("(resolving pattern) resolving `{}` to constant", renamed);
2551 self.enforce_default_binding_mode(pattern, binding_mode, "a constant");
2552 self.record_def(pattern.id,
2559 FoundConst(def, _, name) => {
2563 ResolutionError::OnlyIrrefutablePatternsAllowedHere(def.def_id(),
2567 BareIdentifierPatternUnresolved => {
2568 debug!("(resolving pattern) binding `{}`", renamed);
2570 let def_id = self.ast_map.local_def_id(pattern.id);
2571 let def = DefLocal(def_id, pattern.id);
2573 // Record the definition so that later passes
2574 // will be able to distinguish variants from
2575 // locals in patterns.
2577 self.record_def(pattern.id,
2580 last_private: LastMod(AllPublic),
2584 // Add the binding to the local ribs, if it
2585 // doesn't already exist in the bindings list. (We
2586 // must not add it if it's in the bindings list
2587 // because that breaks the assumptions later
2588 // passes make about or-patterns.)
2589 if !bindings_list.contains_key(&renamed) {
2590 let this = &mut *self;
2591 let last_rib = this.value_ribs.last_mut().unwrap();
2592 last_rib.bindings.insert(renamed, DlDef(def));
2593 bindings_list.insert(renamed, pat_id);
2594 } else if mode == ArgumentIrrefutableMode &&
2595 bindings_list.contains_key(&renamed) {
2596 // Forbid duplicate bindings in the same
2601 ResolutionError::IdentifierBoundMoreThanOnceInParameterList(
2602 &ident.name.as_str())
2604 } else if bindings_list.get(&renamed) == Some(&pat_id) {
2605 // Then this is a duplicate variable in the
2606 // same disjunction, which is an error.
2610 ResolutionError::IdentifierBoundMoreThanOnceInSamePattern(
2611 &ident.name.as_str())
2614 // Else, not bound in the same pattern: do
2620 PatEnum(ref path, _) => {
2621 // This must be an enum variant, struct or const.
2622 let resolution = match self.resolve_possibly_assoc_item(pat_id,
2627 // The below shouldn't happen because all
2628 // qualified paths should be in PatQPath.
2629 TypecheckRequired =>
2630 self.session.span_bug(path.span,
2631 "resolve_possibly_assoc_item claimed
2633 that a path in PatEnum requires typecheck
2635 to resolve, but qualified paths should be
2638 ResolveAttempt(resolution) => resolution,
2640 if let Some(path_res) = resolution {
2641 match path_res.base_def {
2642 DefVariant(..) | DefStruct(..) | DefConst(..) => {
2643 self.record_def(pattern.id, path_res);
2646 resolve_error(&self,
2648 ResolutionError::StaticVariableReference);
2651 // If anything ends up here entirely resolved,
2652 // it's an error. If anything ends up here
2653 // partially resolved, that's OK, because it may
2654 // be a `T::CONST` that typeck will resolve.
2655 if path_res.depth == 0 {
2659 ResolutionError::NotAnEnumVariantStructOrConst(
2668 let const_name = path.segments
2673 let traits = self.get_traits_containing_item(const_name);
2674 self.trait_map.insert(pattern.id, traits);
2675 self.record_def(pattern.id, path_res);
2683 ResolutionError::UnresolvedEnumVariantStructOrConst(
2684 &path.segments.last().unwrap().identifier.name.as_str())
2687 intravisit::walk_path(self, path);
2690 PatQPath(ref qself, ref path) => {
2691 // Associated constants only.
2692 let resolution = match self.resolve_possibly_assoc_item(pat_id,
2697 TypecheckRequired => {
2698 // All `<T>::CONST` should end up here, and will
2699 // require use of the trait map to resolve
2700 // during typechecking.
2701 let const_name = path.segments
2706 let traits = self.get_traits_containing_item(const_name);
2707 self.trait_map.insert(pattern.id, traits);
2708 intravisit::walk_pat(self, pattern);
2711 ResolveAttempt(resolution) => resolution,
2713 if let Some(path_res) = resolution {
2714 match path_res.base_def {
2715 // All `<T as Trait>::CONST` should end up here, and
2716 // have the trait already selected.
2717 DefAssociatedConst(..) => {
2718 self.record_def(pattern.id, path_res);
2724 ResolutionError::NotAnAssociatedConst(
2725 &path.segments.last().unwrap().identifier.name.as_str()
2733 ResolutionError::UnresolvedAssociatedConst(&path.segments
2740 intravisit::walk_pat(self, pattern);
2743 PatStruct(ref path, _, _) => {
2744 match self.resolve_path(pat_id, path, 0, TypeNS, false) {
2745 Some(definition) => {
2746 self.record_def(pattern.id, definition);
2749 debug!("(resolving pattern) didn't find struct def: {:?}", result);
2753 ResolutionError::DoesNotNameAStruct(
2754 &*path_names_to_string(path, 0))
2758 intravisit::walk_path(self, path);
2761 PatLit(_) | PatRange(..) => {
2762 intravisit::walk_pat(self, pattern);
2773 fn resolve_bare_identifier_pattern(&mut self,
2776 -> BareIdentifierPatternResolution {
2777 let module = self.current_module.clone();
2778 match self.resolve_item_in_lexical_scope(module, name, ValueNS) {
2779 Success((target, _)) => {
2780 debug!("(resolve bare identifier pattern) succeeded in finding {} at {:?}",
2782 target.binding.borrow());
2783 match target.binding.def() {
2785 panic!("resolved name in the value namespace to a set of name bindings \
2788 // For the two success cases, this lookup can be
2789 // considered as not having a private component because
2790 // the lookup happened only within the current module.
2791 Some(def @ DefVariant(..)) | Some(def @ DefStruct(..)) => {
2792 return FoundStructOrEnumVariant(def, LastMod(AllPublic));
2794 Some(def @ DefConst(..)) | Some(def @ DefAssociatedConst(..)) => {
2795 return FoundConst(def, LastMod(AllPublic), name);
2797 Some(DefStatic(..)) => {
2798 resolve_error(self, span, ResolutionError::StaticVariableReference);
2799 return BareIdentifierPatternUnresolved;
2801 _ => return BareIdentifierPatternUnresolved
2806 panic!("unexpected indeterminate result");
2810 Some((span, msg)) => {
2811 resolve_error(self, span, ResolutionError::FailedToResolve(&*msg));
2816 debug!("(resolve bare identifier pattern) failed to find {}", name);
2817 return BareIdentifierPatternUnresolved;
2822 /// Handles paths that may refer to associated items
2823 fn resolve_possibly_assoc_item(&mut self,
2825 maybe_qself: Option<&hir::QSelf>,
2827 namespace: Namespace,
2829 -> AssocItemResolveResult {
2830 let max_assoc_types;
2834 if qself.position == 0 {
2835 return TypecheckRequired;
2837 max_assoc_types = path.segments.len() - qself.position;
2838 // Make sure the trait is valid.
2839 let _ = self.resolve_trait_reference(id, path, max_assoc_types);
2842 max_assoc_types = path.segments.len();
2846 let mut resolution = self.with_no_errors(|this| {
2847 this.resolve_path(id, path, 0, namespace, check_ribs)
2849 for depth in 1..max_assoc_types {
2850 if resolution.is_some() {
2853 self.with_no_errors(|this| {
2854 resolution = this.resolve_path(id, path, depth, TypeNS, true);
2857 if let Some(DefMod(_)) = resolution.map(|r| r.base_def) {
2858 // A module is not a valid type or value.
2861 ResolveAttempt(resolution)
2864 /// If `check_ribs` is true, checks the local definitions first; i.e.
2865 /// doesn't skip straight to the containing module.
2866 /// Skips `path_depth` trailing segments, which is also reflected in the
2867 /// returned value. See `middle::def::PathResolution` for more info.
2868 pub fn resolve_path(&mut self,
2872 namespace: Namespace,
2874 -> Option<PathResolution> {
2875 let span = path.span;
2876 let segments = &path.segments[..path.segments.len() - path_depth];
2878 let mk_res = |(def, lp)| PathResolution::new(def, lp, path_depth);
2881 let def = self.resolve_crate_relative_path(span, segments, namespace);
2882 return def.map(mk_res);
2885 // Try to find a path to an item in a module.
2886 let unqualified_def = self.resolve_identifier(segments.last().unwrap().identifier,
2890 if segments.len() <= 1 {
2891 return unqualified_def.and_then(|def| self.adjust_local_def(def, span))
2893 PathResolution::new(def, LastMod(AllPublic), path_depth)
2897 let def = self.resolve_module_relative_path(span, segments, namespace);
2898 match (def, unqualified_def) {
2899 (Some((ref d, _)), Some(ref ud)) if *d == ud.def => {
2901 .add_lint(lint::builtin::UNUSED_QUALIFICATIONS,
2904 "unnecessary qualification".to_string());
2912 // Resolve a single identifier
2913 fn resolve_identifier(&mut self,
2915 namespace: Namespace,
2917 -> Option<LocalDef> {
2918 // First, check to see whether the name is a primitive type.
2919 if namespace == TypeNS {
2920 if let Some(&prim_ty) = self.primitive_type_table
2922 .get(&identifier.name) {
2923 return Some(LocalDef::from_def(DefPrimTy(prim_ty)));
2928 if let Some(def) = self.resolve_identifier_in_local_ribs(identifier, namespace) {
2933 self.resolve_item_by_name_in_lexical_scope(identifier.name, namespace)
2934 .map(LocalDef::from_def)
2937 // Resolve a local definition, potentially adjusting for closures.
2938 fn adjust_local_def(&mut self, local_def: LocalDef, span: Span) -> Option<Def> {
2939 let ribs = match local_def.ribs {
2940 Some((TypeNS, i)) => &self.type_ribs[i + 1..],
2941 Some((ValueNS, i)) => &self.value_ribs[i + 1..],
2944 let mut def = local_def.def;
2947 self.session.span_bug(span, &format!("unexpected {:?} in bindings", def))
2949 DefLocal(_, node_id) => {
2953 // Nothing to do. Continue.
2955 ClosureRibKind(function_id) => {
2957 let node_def_id = self.ast_map.local_def_id(node_id);
2959 let seen = self.freevars_seen
2961 .or_insert_with(|| NodeMap());
2962 if let Some(&index) = seen.get(&node_id) {
2963 def = DefUpvar(node_def_id, node_id, index, function_id);
2966 let vec = self.freevars
2968 .or_insert_with(|| vec![]);
2969 let depth = vec.len();
2975 def = DefUpvar(node_def_id, node_id, depth, function_id);
2976 seen.insert(node_id, depth);
2978 ItemRibKind | MethodRibKind => {
2979 // This was an attempt to access an upvar inside a
2980 // named function item. This is not allowed, so we
2984 ResolutionError::CannotCaptureDynamicEnvironmentInFnItem);
2987 ConstantItemRibKind => {
2988 // Still doesn't deal with upvars
2991 ResolutionError::AttemptToUseNonConstantValueInConstant);
2997 DefTyParam(..) | DefSelfTy(..) => {
3000 NormalRibKind | MethodRibKind | ClosureRibKind(..) => {
3001 // Nothing to do. Continue.
3004 // This was an attempt to use a type parameter outside
3009 ResolutionError::TypeParametersFromOuterFunction);
3012 ConstantItemRibKind => {
3014 resolve_error(self, span, ResolutionError::OuterTypeParameterContext);
3025 // resolve a "module-relative" path, e.g. a::b::c
3026 fn resolve_module_relative_path(&mut self,
3028 segments: &[hir::PathSegment],
3029 namespace: Namespace)
3030 -> Option<(Def, LastPrivate)> {
3031 let module_path = segments.split_last()
3035 .map(|ps| ps.identifier.name)
3036 .collect::<Vec<_>>();
3038 let containing_module;
3040 let current_module = self.current_module.clone();
3041 match self.resolve_module_path(current_module,
3047 let (span, msg) = match err {
3048 Some((span, msg)) => (span, msg),
3050 let msg = format!("Use of undeclared type or module `{}`",
3051 names_to_string(&module_path));
3056 resolve_error(self, span, ResolutionError::FailedToResolve(&*msg));
3059 Indeterminate => panic!("indeterminate unexpected"),
3060 Success((resulting_module, resulting_last_private)) => {
3061 containing_module = resulting_module;
3062 last_private = resulting_last_private;
3066 let name = segments.last().unwrap().identifier.name;
3067 let def = match self.resolve_name_in_module(containing_module.clone(),
3070 NameSearchType::PathSearch,
3072 Success((Target { binding, .. }, _)) => {
3073 let (def, lp) = binding.def_and_lp();
3074 (def, last_private.or(lp))
3078 if let Some(DefId{krate: kid, ..}) = containing_module.def_id() {
3079 self.used_crates.insert(kid);
3084 /// Invariant: This must be called only during main resolution, not during
3085 /// import resolution.
3086 fn resolve_crate_relative_path(&mut self,
3088 segments: &[hir::PathSegment],
3089 namespace: Namespace)
3090 -> Option<(Def, LastPrivate)> {
3091 let module_path = segments.split_last()
3095 .map(|ps| ps.identifier.name)
3096 .collect::<Vec<_>>();
3098 let root_module = self.graph_root.clone();
3100 let containing_module;
3102 match self.resolve_module_path_from_root(root_module,
3107 LastMod(AllPublic)) {
3109 let (span, msg) = match err {
3110 Some((span, msg)) => (span, msg),
3112 let msg = format!("Use of undeclared module `::{}`",
3113 names_to_string(&module_path[..]));
3118 resolve_error(self, span, ResolutionError::FailedToResolve(&*msg));
3123 panic!("indeterminate unexpected");
3126 Success((resulting_module, resulting_last_private)) => {
3127 containing_module = resulting_module;
3128 last_private = resulting_last_private;
3132 let name = segments.last().unwrap().identifier.name;
3133 match self.resolve_name_in_module(containing_module,
3136 NameSearchType::PathSearch,
3138 Success((Target { binding, .. }, _)) => {
3139 let (def, lp) = binding.def_and_lp();
3140 Some((def, last_private.or(lp)))
3146 fn resolve_identifier_in_local_ribs(&mut self,
3148 namespace: Namespace)
3149 -> Option<LocalDef> {
3150 // Check the local set of ribs.
3151 let (name, ribs) = match namespace {
3152 ValueNS => (mtwt::resolve(ident), &self.value_ribs),
3153 TypeNS => (ident.name, &self.type_ribs),
3156 for (i, rib) in ribs.iter().enumerate().rev() {
3157 if let Some(def_like) = rib.bindings.get(&name).cloned() {
3160 debug!("(resolving path in local ribs) resolved `{}` to {:?} at {}",
3164 return Some(LocalDef {
3165 ribs: Some((namespace, i)),
3170 debug!("(resolving path in local ribs) resolved `{}` to pseudo-def {:?}",
3182 fn resolve_item_by_name_in_lexical_scope(&mut self,
3184 namespace: Namespace)
3187 let module = self.current_module.clone();
3188 match self.resolve_item_in_lexical_scope(module, name, namespace) {
3189 Success((target, _)) => {
3190 match target.binding.def() {
3192 // This can happen if we were looking for a type and
3193 // found a module instead. Modules don't have defs.
3194 debug!("(resolving item path by identifier in lexical scope) failed to \
3195 resolve {} after success...",
3200 debug!("(resolving item path in lexical scope) resolved `{}` to item",
3202 // This lookup is "all public" because it only searched
3203 // for one identifier in the current module (couldn't
3204 // have passed through reexports or anything like that.
3210 panic!("unexpected indeterminate result");
3213 debug!("(resolving item path by identifier in lexical scope) failed to resolve {}",
3216 if let Some((span, msg)) = err {
3217 resolve_error(self, span, ResolutionError::FailedToResolve(&*msg))
3225 fn with_no_errors<T, F>(&mut self, f: F) -> T
3226 where F: FnOnce(&mut Resolver) -> T
3228 self.emit_errors = false;
3230 self.emit_errors = true;
3234 fn find_fallback_in_self_type(&mut self, name: Name) -> FallbackSuggestion {
3235 fn extract_path_and_node_id(t: &Ty,
3236 allow: FallbackChecks)
3237 -> Option<(Path, NodeId, FallbackChecks)> {
3239 TyPath(None, ref path) => Some((path.clone(), t.id, allow)),
3240 TyPtr(ref mut_ty) => extract_path_and_node_id(&*mut_ty.ty, OnlyTraitAndStatics),
3241 TyRptr(_, ref mut_ty) => extract_path_and_node_id(&*mut_ty.ty, allow),
3242 // This doesn't handle the remaining `Ty` variants as they are not
3243 // that commonly the self_type, it might be interesting to provide
3244 // support for those in future.
3249 fn get_module(this: &mut Resolver,
3251 name_path: &[ast::Name])
3252 -> Option<Rc<Module>> {
3253 let root = this.current_module.clone();
3254 let last_name = name_path.last().unwrap();
3256 if name_path.len() == 1 {
3257 match this.primitive_type_table.primitive_types.get(last_name) {
3260 match this.current_module.children.borrow().get(last_name) {
3261 Some(child) => child.type_ns.module(),
3267 match this.resolve_module_path(root,
3272 Success((module, _)) => Some(module),
3278 fn is_static_method(this: &Resolver, did: DefId) -> bool {
3279 if let Some(node_id) = this.ast_map.as_local_node_id(did) {
3280 let sig = match this.ast_map.get(node_id) {
3281 hir_map::NodeTraitItem(trait_item) => match trait_item.node {
3282 hir::MethodTraitItem(ref sig, _) => sig,
3285 hir_map::NodeImplItem(impl_item) => match impl_item.node {
3286 hir::ImplItemKind::Method(ref sig, _) => sig,
3291 sig.explicit_self.node == hir::SelfStatic
3293 this.session.cstore.is_static_method(did)
3297 let (path, node_id, allowed) = match self.current_self_type {
3298 Some(ref ty) => match extract_path_and_node_id(ty, Everything) {
3300 None => return NoSuggestion,
3302 None => return NoSuggestion,
3305 if allowed == Everything {
3306 // Look for a field with the same name in the current self_type.
3307 match self.def_map.borrow().get(&node_id).map(|d| d.full_def()) {
3308 Some(DefTy(did, _)) |
3309 Some(DefStruct(did)) |
3310 Some(DefVariant(_, did, _)) => match self.structs.get(&did) {
3313 if fields.iter().any(|&field_name| name == field_name) {
3318 _ => {} // Self type didn't resolve properly
3322 let name_path = path.segments.iter().map(|seg| seg.identifier.name).collect::<Vec<_>>();
3324 // Look for a method in the current self type's impl module.
3325 if let Some(module) = get_module(self, path.span, &name_path) {
3326 if let Some(binding) = module.children.borrow().get(&name) {
3327 if let Some(DefMethod(did)) = binding.value_ns.def() {
3328 if is_static_method(self, did) {
3329 return StaticMethod(path_names_to_string(&path, 0));
3331 if self.current_trait_ref.is_some() {
3333 } else if allowed == Everything {
3340 // Look for a method in the current trait.
3341 if let Some((trait_did, ref trait_ref)) = self.current_trait_ref {
3342 if let Some(&did) = self.trait_item_map.get(&(name, trait_did)) {
3343 if is_static_method(self, did) {
3344 return TraitMethod(path_names_to_string(&trait_ref.path, 0));
3354 fn find_best_match_for_name(&mut self, name: &str) -> SuggestionType {
3355 let mut maybes: Vec<token::InternedString> = Vec::new();
3356 let mut values: Vec<usize> = Vec::new();
3358 if let Some(macro_name) = self.session.available_macros
3359 .borrow().iter().find(|n| n.as_str() == name) {
3360 return SuggestionType::Macro(format!("{}!", macro_name));
3363 for rib in self.value_ribs.iter().rev() {
3364 for (&k, _) in &rib.bindings {
3365 maybes.push(k.as_str());
3366 values.push(usize::MAX);
3370 let mut smallest = 0;
3371 for (i, other) in maybes.iter().enumerate() {
3372 values[i] = lev_distance(name, &other);
3374 if values[i] <= values[smallest] {
3379 let max_distance = max_suggestion_distance(name);
3380 if !values.is_empty() && values[smallest] <= max_distance && name != &maybes[smallest][..] {
3382 SuggestionType::Function(maybes[smallest].to_string())
3385 SuggestionType::NotFound
3389 fn resolve_expr(&mut self, expr: &Expr) {
3390 // First, record candidate traits for this expression if it could
3391 // result in the invocation of a method call.
3393 self.record_candidate_traits_for_expr_if_necessary(expr);
3395 // Next, resolve the node.
3397 ExprPath(ref maybe_qself, ref path) => {
3398 let resolution = match self.resolve_possibly_assoc_item(expr.id,
3399 maybe_qself.as_ref(),
3403 // `<T>::a::b::c` is resolved by typeck alone.
3404 TypecheckRequired => {
3405 let method_name = path.segments.last().unwrap().identifier.name;
3406 let traits = self.get_traits_containing_item(method_name);
3407 self.trait_map.insert(expr.id, traits);
3408 intravisit::walk_expr(self, expr);
3411 ResolveAttempt(resolution) => resolution,
3414 // This is a local path in the value namespace. Walk through
3415 // scopes looking for it.
3416 if let Some(path_res) = resolution {
3417 // Check if struct variant
3418 if let DefVariant(_, _, true) = path_res.base_def {
3419 let path_name = path_names_to_string(path, 0);
3423 ResolutionError::StructVariantUsedAsFunction(&*path_name));
3425 let msg = format!("did you mean to write: `{} {{ /* fields */ }}`?",
3427 if self.emit_errors {
3428 self.session.fileline_help(expr.span, &msg);
3430 self.session.span_help(expr.span, &msg);
3433 // Write the result into the def map.
3434 debug!("(resolving expr) resolved `{}`",
3435 path_names_to_string(path, 0));
3437 // Partial resolutions will need the set of traits in scope,
3438 // so they can be completed during typeck.
3439 if path_res.depth != 0 {
3440 let method_name = path.segments.last().unwrap().identifier.name;
3441 let traits = self.get_traits_containing_item(method_name);
3442 self.trait_map.insert(expr.id, traits);
3445 self.record_def(expr.id, path_res);
3448 // Be helpful if the name refers to a struct
3449 // (The pattern matching def_tys where the id is in self.structs
3450 // matches on regular structs while excluding tuple- and enum-like
3451 // structs, which wouldn't result in this error.)
3452 let path_name = path_names_to_string(path, 0);
3453 let type_res = self.with_no_errors(|this| {
3454 this.resolve_path(expr.id, path, 0, TypeNS, false)
3456 match type_res.map(|r| r.base_def) {
3457 Some(DefTy(struct_id, _)) if self.structs.contains_key(&struct_id) => {
3461 ResolutionError::StructVariantUsedAsFunction(
3465 let msg = format!("did you mean to write: `{} {{ /* fields */ }}`?",
3467 if self.emit_errors {
3468 self.session.fileline_help(expr.span, &msg);
3470 self.session.span_help(expr.span, &msg);
3474 // Keep reporting some errors even if they're ignored above.
3475 self.resolve_path(expr.id, path, 0, ValueNS, true);
3477 let mut method_scope = false;
3478 self.value_ribs.iter().rev().all(|rib| {
3479 method_scope = match rib.kind {
3480 MethodRibKind => true,
3481 ItemRibKind | ConstantItemRibKind => false,
3482 _ => return true, // Keep advancing
3484 false // Stop advancing
3487 if method_scope && special_names::self_.as_str() == &path_name[..] {
3490 ResolutionError::SelfNotAvailableInStaticMethod);
3492 let last_name = path.segments.last().unwrap().identifier.name;
3493 let mut msg = match self.find_fallback_in_self_type(last_name) {
3495 // limit search to 5 to reduce the number
3496 // of stupid suggestions
3497 match self.find_best_match_for_name(&path_name) {
3498 SuggestionType::Macro(s) => {
3499 format!("the macro `{}`", s)
3501 SuggestionType::Function(s) => format!("`{}`", s),
3502 SuggestionType::NotFound => "".to_string(),
3505 Field => format!("`self.{}`", path_name),
3507 TraitItem => format!("to call `self.{}`", path_name),
3508 TraitMethod(path_str) |
3509 StaticMethod(path_str) =>
3510 format!("to call `{}::{}`", path_str, path_name),
3513 if !msg.is_empty() {
3514 msg = format!(". Did you mean {}?", msg)
3519 ResolutionError::UnresolvedName(&*path_name, &*msg));
3525 intravisit::walk_expr(self, expr);
3528 ExprStruct(ref path, _, _) => {
3529 // Resolve the path to the structure it goes to. We don't
3530 // check to ensure that the path is actually a structure; that
3531 // is checked later during typeck.
3532 match self.resolve_path(expr.id, path, 0, TypeNS, false) {
3533 Some(definition) => self.record_def(expr.id, definition),
3535 debug!("(resolving expression) didn't find struct def",);
3539 ResolutionError::DoesNotNameAStruct(
3540 &*path_names_to_string(path, 0))
3545 intravisit::walk_expr(self, expr);
3548 ExprLoop(_, Some(label)) | ExprWhile(_, _, Some(label)) => {
3549 self.with_label_rib(|this| {
3550 let def_like = DlDef(DefLabel(expr.id));
3553 let rib = this.label_ribs.last_mut().unwrap();
3554 let renamed = mtwt::resolve(label);
3555 rib.bindings.insert(renamed, def_like);
3558 intravisit::walk_expr(this, expr);
3562 ExprBreak(Some(label)) | ExprAgain(Some(label)) => {
3563 let renamed = mtwt::resolve(label.node);
3564 match self.search_label(renamed) {
3568 ResolutionError::UndeclaredLabel(&label.node.name.as_str()))
3570 Some(DlDef(def @ DefLabel(_))) => {
3571 // Since this def is a label, it is never read.
3572 self.record_def(expr.id,
3575 last_private: LastMod(AllPublic),
3580 self.session.span_bug(expr.span, "label wasn't mapped to a label def!")
3586 intravisit::walk_expr(self, expr);
3591 fn record_candidate_traits_for_expr_if_necessary(&mut self, expr: &Expr) {
3593 ExprField(_, name) => {
3594 // FIXME(#6890): Even though you can't treat a method like a
3595 // field, we need to add any trait methods we find that match
3596 // the field name so that we can do some nice error reporting
3597 // later on in typeck.
3598 let traits = self.get_traits_containing_item(name.node);
3599 self.trait_map.insert(expr.id, traits);
3601 ExprMethodCall(name, _, _) => {
3602 debug!("(recording candidate traits for expr) recording traits for {}",
3604 let traits = self.get_traits_containing_item(name.node);
3605 self.trait_map.insert(expr.id, traits);
3613 fn get_traits_containing_item(&mut self, name: Name) -> Vec<DefId> {
3614 debug!("(getting traits containing item) looking for '{}'", name);
3616 fn add_trait_info(found_traits: &mut Vec<DefId>, trait_def_id: DefId, name: Name) {
3617 debug!("(adding trait info) found trait {:?} for method '{}'",
3620 found_traits.push(trait_def_id);
3623 let mut found_traits = Vec::new();
3624 let mut search_module = self.current_module.clone();
3626 // Look for the current trait.
3627 match self.current_trait_ref {
3628 Some((trait_def_id, _)) => {
3629 if self.trait_item_map.contains_key(&(name, trait_def_id)) {
3630 add_trait_info(&mut found_traits, trait_def_id, name);
3633 None => {} // Nothing to do.
3636 // Look for trait children.
3637 build_reduced_graph::populate_module_if_necessary(self, &search_module);
3640 for (_, child_names) in search_module.children.borrow().iter() {
3641 let def = match child_names.type_ns.def() {
3645 let trait_def_id = match def {
3646 DefTrait(trait_def_id) => trait_def_id,
3649 if self.trait_item_map.contains_key(&(name, trait_def_id)) {
3650 add_trait_info(&mut found_traits, trait_def_id, name);
3655 // Look for imports.
3656 for (_, import) in search_module.import_resolutions.borrow().iter() {
3657 let target = match import.target_for_namespace(TypeNS) {
3659 Some(target) => target,
3661 let did = match target.binding.def() {
3662 Some(DefTrait(trait_def_id)) => trait_def_id,
3663 Some(..) | None => continue,
3665 if self.trait_item_map.contains_key(&(name, did)) {
3666 add_trait_info(&mut found_traits, did, name);
3667 let id = import.type_id;
3668 self.used_imports.insert((id, TypeNS));
3669 let trait_name = self.get_trait_name(did);
3670 self.record_import_use(id, trait_name);
3671 if let Some(DefId{krate: kid, ..}) = target.target_module.def_id() {
3672 self.used_crates.insert(kid);
3677 match search_module.parent_link.clone() {
3678 NoParentLink | ModuleParentLink(..) => break,
3679 BlockParentLink(parent_module, _) => {
3680 search_module = parent_module.upgrade().unwrap();
3688 fn record_def(&mut self, node_id: NodeId, resolution: PathResolution) {
3689 debug!("(recording def) recording {:?} for {}", resolution, node_id);
3690 assert!(match resolution.last_private {
3691 LastImport{..} => false,
3694 "Import should only be used for `use` directives");
3696 if let Some(prev_res) = self.def_map.borrow_mut().insert(node_id, resolution) {
3697 let span = self.ast_map.opt_span(node_id).unwrap_or(codemap::DUMMY_SP);
3698 self.session.span_bug(span,
3699 &format!("path resolved multiple times ({:?} before, {:?} now)",
3705 fn enforce_default_binding_mode(&mut self,
3707 pat_binding_mode: BindingMode,
3709 match pat_binding_mode {
3710 BindByValue(_) => {}
3714 ResolutionError::CannotUseRefBindingModeWith(descr));
3722 // Diagnostics are not particularly efficient, because they're rarely
3726 #[allow(dead_code)] // useful for debugging
3727 fn dump_module(&mut self, module_: Rc<Module>) {
3728 debug!("Dump of module `{}`:", module_to_string(&*module_));
3730 debug!("Children:");
3731 build_reduced_graph::populate_module_if_necessary(self, &module_);
3732 for (&name, _) in module_.children.borrow().iter() {
3733 debug!("* {}", name);
3736 debug!("Import resolutions:");
3737 let import_resolutions = module_.import_resolutions.borrow();
3738 for (&name, import_resolution) in import_resolutions.iter() {
3740 match import_resolution.target_for_namespace(ValueNS) {
3742 value_repr = "".to_string();
3745 value_repr = " value:?".to_string();
3751 match import_resolution.target_for_namespace(TypeNS) {
3753 type_repr = "".to_string();
3756 type_repr = " type:?".to_string();
3761 debug!("* {}:{}{}", name, value_repr, type_repr);
3767 fn names_to_string(names: &[Name]) -> String {
3768 let mut first = true;
3769 let mut result = String::new();
3774 result.push_str("::")
3776 result.push_str(&name.as_str());
3781 fn path_names_to_string(path: &Path, depth: usize) -> String {
3782 let names: Vec<ast::Name> = path.segments[..path.segments.len() - depth]
3784 .map(|seg| seg.identifier.name)
3786 names_to_string(&names[..])
3789 /// A somewhat inefficient routine to obtain the name of a module.
3790 fn module_to_string(module: &Module) -> String {
3791 let mut names = Vec::new();
3793 fn collect_mod(names: &mut Vec<ast::Name>, module: &Module) {
3794 match module.parent_link {
3796 ModuleParentLink(ref module, name) => {
3798 collect_mod(names, &*module.upgrade().unwrap());
3800 BlockParentLink(ref module, _) => {
3801 // danger, shouldn't be ident?
3802 names.push(special_idents::opaque.name);
3803 collect_mod(names, &*module.upgrade().unwrap());
3807 collect_mod(&mut names, module);
3809 if names.is_empty() {
3810 return "???".to_string();
3812 names_to_string(&names.into_iter().rev().collect::<Vec<ast::Name>>())
3816 pub struct CrateMap {
3817 pub def_map: RefCell<DefMap>,
3818 pub freevars: FreevarMap,
3819 pub export_map: ExportMap,
3820 pub trait_map: TraitMap,
3821 pub external_exports: ExternalExports,
3822 pub glob_map: Option<GlobMap>,
3825 #[derive(PartialEq,Copy, Clone)]
3826 pub enum MakeGlobMap {
3831 /// Entry point to crate resolution.
3832 pub fn resolve_crate<'a, 'tcx>(session: &'a Session,
3833 ast_map: &'a hir_map::Map<'tcx>,
3834 make_glob_map: MakeGlobMap)
3836 let krate = ast_map.krate();
3837 let mut resolver = create_resolver(session, ast_map, krate, make_glob_map, None);
3839 resolver.resolve_crate(krate);
3840 session.abort_if_errors();
3842 check_unused::check_crate(&mut resolver, krate);
3845 def_map: resolver.def_map,
3846 freevars: resolver.freevars,
3847 export_map: resolver.export_map,
3848 trait_map: resolver.trait_map,
3849 external_exports: resolver.external_exports,
3850 glob_map: if resolver.make_glob_map {
3851 Some(resolver.glob_map)
3858 /// Builds a name resolution walker to be used within this module,
3859 /// or used externally, with an optional callback function.
3861 /// The callback takes a &mut bool which allows callbacks to end a
3862 /// walk when set to true, passing through the rest of the walk, while
3863 /// preserving the ribs + current module. This allows resolve_path
3864 /// calls to be made with the correct scope info. The node in the
3865 /// callback corresponds to the current node in the walk.
3866 pub fn create_resolver<'a, 'tcx>(session: &'a Session,
3867 ast_map: &'a hir_map::Map<'tcx>,
3869 make_glob_map: MakeGlobMap,
3870 callback: Option<Box<Fn(hir_map::Node, &mut bool) -> bool>>)
3871 -> Resolver<'a, 'tcx> {
3872 let mut resolver = Resolver::new(session, ast_map, make_glob_map);
3874 resolver.callback = callback;
3876 build_reduced_graph::build_reduced_graph(&mut resolver, krate);
3877 session.abort_if_errors();
3879 resolve_imports::resolve_imports(&mut resolver);
3880 session.abort_if_errors();
3882 record_exports::record(&mut resolver);
3883 session.abort_if_errors();
3888 __build_diagnostic_array! { librustc_resolve, DIAGNOSTICS }