1 // Copyright 2012-2014 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 #![crate_name = "rustc_resolve"]
12 #![unstable(feature = "rustc_private")]
14 #![crate_type = "dylib"]
15 #![crate_type = "rlib"]
16 #![doc(html_logo_url = "http://www.rust-lang.org/logos/rust-logo-128x128-blk-v2.png",
17 html_favicon_url = "http://www.rust-lang.org/favicon.ico",
18 html_root_url = "http://doc.rust-lang.org/nightly/")]
21 #![feature(collections)]
25 #![feature(rustc_diagnostic_macros)]
26 #![feature(rustc_private)]
27 #![feature(staged_api)]
30 #[macro_use] extern crate log;
31 #[macro_use] extern crate syntax;
32 #[macro_use] #[no_link] extern crate rustc_bitflags;
36 use self::PatternBindingMode::*;
37 use self::Namespace::*;
38 use self::NamespaceResult::*;
39 use self::NameDefinition::*;
40 use self::ImportDirectiveSubclass::*;
41 use self::ResolveResult::*;
42 use self::FallbackSuggestion::*;
43 use self::TypeParameters::*;
45 use self::MethodSort::*;
46 use self::UseLexicalScopeFlag::*;
47 use self::ModulePrefixResult::*;
48 use self::NameSearchType::*;
49 use self::BareIdentifierPatternResolution::*;
50 use self::ParentLink::*;
51 use self::ModuleKind::*;
52 use self::TraitReferenceType::*;
53 use self::FallbackChecks::*;
55 use rustc::session::Session;
57 use rustc::metadata::csearch;
58 use rustc::metadata::decoder::{DefLike, DlDef, DlField, DlImpl};
59 use rustc::middle::def::*;
60 use rustc::middle::lang_items::LanguageItems;
61 use rustc::middle::pat_util::pat_bindings;
62 use rustc::middle::privacy::*;
63 use rustc::middle::subst::{ParamSpace, FnSpace, TypeSpace};
64 use rustc::middle::ty::{Freevar, FreevarMap, TraitMap, GlobMap};
65 use rustc::util::nodemap::{NodeMap, NodeSet, DefIdSet, FnvHashMap};
66 use rustc::util::lev_distance::lev_distance;
68 use syntax::ast::{Arm, BindByRef, BindByValue, BindingMode, Block, Crate, CrateNum};
69 use syntax::ast::{DefId, Expr, ExprAgain, ExprBreak, ExprField};
70 use syntax::ast::{ExprClosure, ExprLoop, ExprWhile, ExprMethodCall};
71 use syntax::ast::{ExprPath, ExprQPath, ExprStruct, FnDecl};
72 use syntax::ast::{ForeignItemFn, ForeignItemStatic, Generics};
73 use syntax::ast::{Ident, ImplItem, Item, ItemConst, ItemEnum, ItemExternCrate};
74 use syntax::ast::{ItemFn, ItemForeignMod, ItemImpl, ItemMac, ItemMod, ItemStatic};
75 use syntax::ast::{ItemStruct, ItemTrait, ItemTy, ItemUse};
76 use syntax::ast::{Local, MethodImplItem, Mod, Name, NodeId};
77 use syntax::ast::{Pat, PatEnum, PatIdent, PatLit};
78 use syntax::ast::{PatRange, PatStruct, Path};
79 use syntax::ast::{PolyTraitRef, PrimTy, SelfExplicit};
80 use syntax::ast::{RegionTyParamBound, StructField};
81 use syntax::ast::{TraitRef, TraitTyParamBound};
82 use syntax::ast::{Ty, TyBool, TyChar, TyF32};
83 use syntax::ast::{TyF64, TyFloat, TyIs, TyI8, TyI16, TyI32, TyI64, TyInt, TyObjectSum};
84 use syntax::ast::{TyParam, TyParamBound, TyPath, TyPtr, TyPolyTraitRef, TyQPath};
85 use syntax::ast::{TyRptr, TyStr, TyUs, TyU8, TyU16, TyU32, TyU64, TyUint};
86 use syntax::ast::{TypeImplItem};
89 use syntax::ast_util::{PostExpansionMethod, local_def, walk_pat};
90 use syntax::attr::AttrMetaMethods;
91 use syntax::ext::mtwt;
92 use syntax::parse::token::{self, special_names, special_idents};
93 use syntax::codemap::{Span, Pos};
94 use syntax::owned_slice::OwnedSlice;
95 use syntax::visit::{self, Visitor};
97 use std::collections::{HashMap, HashSet};
98 use std::collections::hash_map::Entry::{Occupied, Vacant};
99 use std::cell::{Cell, RefCell};
101 use std::mem::replace;
102 use std::rc::{Rc, Weak};
105 // NB: This module needs to be declared first so diagnostics are
106 // registered before they are used.
111 mod build_reduced_graph;
116 binding_mode: BindingMode,
119 // Map from the name in a pattern to its binding mode.
120 type BindingMap = HashMap<Name, BindingInfo>;
122 #[derive(Copy, PartialEq)]
123 enum PatternBindingMode {
125 LocalIrrefutableMode,
126 ArgumentIrrefutableMode,
129 #[derive(Copy, PartialEq, Eq, Hash, Debug)]
135 /// A NamespaceResult represents the result of resolving an import in
136 /// a particular namespace. The result is either definitely-resolved,
137 /// definitely- unresolved, or unknown.
139 enum NamespaceResult {
140 /// Means that resolve hasn't gathered enough information yet to determine
141 /// whether the name is bound in this namespace. (That is, it hasn't
142 /// resolved all `use` directives yet.)
144 /// Means that resolve has determined that the name is definitely
145 /// not bound in the namespace.
147 /// Means that resolve has determined that the name is bound in the Module
148 /// argument, and specified by the NameBindings argument.
149 BoundResult(Rc<Module>, Rc<NameBindings>)
152 impl NamespaceResult {
153 fn is_unknown(&self) -> bool {
155 UnknownResult => true,
159 fn is_unbound(&self) -> bool {
161 UnboundResult => true,
167 enum NameDefinition {
168 NoNameDefinition, //< The name was unbound.
169 ChildNameDefinition(Def, LastPrivate), //< The name identifies an immediate child.
170 ImportNameDefinition(Def, LastPrivate) //< The name identifies an import.
173 impl<'a, 'v, 'tcx> Visitor<'v> for Resolver<'a, 'tcx> {
174 fn visit_item(&mut self, item: &Item) {
175 self.resolve_item(item);
177 fn visit_arm(&mut self, arm: &Arm) {
178 self.resolve_arm(arm);
180 fn visit_block(&mut self, block: &Block) {
181 self.resolve_block(block);
183 fn visit_expr(&mut self, expr: &Expr) {
184 self.resolve_expr(expr);
186 fn visit_local(&mut self, local: &Local) {
187 self.resolve_local(local);
189 fn visit_ty(&mut self, ty: &Ty) {
190 self.resolve_type(ty);
194 /// Contains data for specific types of import directives.
195 #[derive(Copy,Debug)]
196 enum ImportDirectiveSubclass {
197 SingleImport(Name /* target */, Name /* source */),
201 type ErrorMessage = Option<(Span, String)>;
203 enum ResolveResult<T> {
204 Failed(ErrorMessage), // Failed to resolve the name, optional helpful error message.
205 Indeterminate, // Couldn't determine due to unresolved globs.
206 Success(T) // Successfully resolved the import.
209 impl<T> ResolveResult<T> {
210 fn indeterminate(&self) -> bool {
211 match *self { Indeterminate => true, _ => false }
215 enum FallbackSuggestion {
220 StaticMethod(String),
225 enum TypeParameters<'a> {
231 // Identifies the things that these parameters
232 // were declared on (type, fn, etc)
235 // ID of the enclosing item.
238 // The kind of the rib used for type parameters.
242 // The rib kind controls the translation of local
243 // definitions (`DefLocal`) to upvars (`DefUpvar`).
244 #[derive(Copy, Debug)]
246 // No translation needs to be applied.
249 // We passed through a closure scope at the given node ID.
250 // Translate upvars as appropriate.
251 ClosureRibKind(NodeId /* func id */),
253 // We passed through an impl or trait and are now in one of its
254 // methods. Allow references to ty params that impl or trait
255 // binds. Disallow any other upvars (including other ty params that are
257 // parent; method itself
258 MethodRibKind(NodeId, MethodSort),
260 // We passed through an item scope. Disallow upvars.
263 // We're in a constant item. Can't refer to dynamic stuff.
267 // Methods can be required or provided. RequiredMethod methods only occur in traits.
268 #[derive(Copy, Debug)]
271 ProvidedMethod(NodeId)
275 enum UseLexicalScopeFlag {
280 enum ModulePrefixResult {
282 PrefixFound(Rc<Module>, uint)
285 #[derive(Copy, PartialEq)]
286 enum NameSearchType {
287 /// We're doing a name search in order to resolve a `use` directive.
290 /// We're doing a name search in order to resolve a path type, a path
291 /// expression, or a path pattern.
296 enum BareIdentifierPatternResolution {
297 FoundStructOrEnumVariant(Def, LastPrivate),
298 FoundConst(Def, LastPrivate),
299 BareIdentifierPatternUnresolved
305 bindings: HashMap<Name, DefLike>,
310 fn new(kind: RibKind) -> Rib {
312 bindings: HashMap::new(),
318 /// Whether an import can be shadowed by another import.
319 #[derive(Debug,PartialEq,Clone,Copy)]
325 /// One import directive.
327 struct ImportDirective {
328 module_path: Vec<Name>,
329 subclass: ImportDirectiveSubclass,
332 is_public: bool, // see note in ImportResolution about how to use this
333 shadowable: Shadowable,
336 impl ImportDirective {
337 fn new(module_path: Vec<Name> ,
338 subclass: ImportDirectiveSubclass,
342 shadowable: Shadowable)
345 module_path: module_path,
349 is_public: is_public,
350 shadowable: shadowable,
355 /// The item that an import resolves to.
356 #[derive(Clone,Debug)]
358 target_module: Rc<Module>,
359 bindings: Rc<NameBindings>,
360 shadowable: Shadowable,
364 fn new(target_module: Rc<Module>,
365 bindings: Rc<NameBindings>,
366 shadowable: Shadowable)
369 target_module: target_module,
371 shadowable: shadowable,
376 /// An ImportResolution represents a particular `use` directive.
378 struct ImportResolution {
379 /// Whether this resolution came from a `use` or a `pub use`. Note that this
380 /// should *not* be used whenever resolution is being performed, this is
381 /// only looked at for glob imports statements currently. Privacy testing
382 /// occurs during a later phase of compilation.
385 // The number of outstanding references to this name. When this reaches
386 // zero, outside modules can count on the targets being correct. Before
387 // then, all bets are off; future imports could override this name.
388 outstanding_references: uint,
390 /// The value that this `use` directive names, if there is one.
391 value_target: Option<Target>,
392 /// The source node of the `use` directive leading to the value target
396 /// The type that this `use` directive names, if there is one.
397 type_target: Option<Target>,
398 /// The source node of the `use` directive leading to the type target
403 impl ImportResolution {
404 fn new(id: NodeId, is_public: bool) -> ImportResolution {
408 outstanding_references: 0,
411 is_public: is_public,
415 fn target_for_namespace(&self, namespace: Namespace)
418 TypeNS => self.type_target.clone(),
419 ValueNS => self.value_target.clone(),
423 fn id(&self, namespace: Namespace) -> NodeId {
425 TypeNS => self.type_id,
426 ValueNS => self.value_id,
430 fn shadowable(&self, namespace: Namespace) -> Shadowable {
431 let target = self.target_for_namespace(namespace);
432 if target.is_none() {
433 return Shadowable::Always;
436 target.unwrap().shadowable
439 fn set_target_and_id(&mut self,
440 namespace: Namespace,
441 target: Option<Target>,
445 self.type_target = target;
449 self.value_target = target;
456 /// The link from a module up to its nearest parent node.
457 #[derive(Clone,Debug)]
460 ModuleParentLink(Weak<Module>, Name),
461 BlockParentLink(Weak<Module>, NodeId)
464 /// The type of module this is.
465 #[derive(Copy, PartialEq, Debug)]
475 /// One node in the tree of modules.
477 parent_link: ParentLink,
478 def_id: Cell<Option<DefId>>,
479 kind: Cell<ModuleKind>,
482 children: RefCell<HashMap<Name, Rc<NameBindings>>>,
483 imports: RefCell<Vec<ImportDirective>>,
485 // The external module children of this node that were declared with
487 external_module_children: RefCell<HashMap<Name, Rc<Module>>>,
489 // The anonymous children of this node. Anonymous children are pseudo-
490 // modules that are implicitly created around items contained within
493 // For example, if we have this:
501 // There will be an anonymous module created around `g` with the ID of the
502 // entry block for `f`.
503 anonymous_children: RefCell<NodeMap<Rc<Module>>>,
505 // The status of resolving each import in this module.
506 import_resolutions: RefCell<HashMap<Name, ImportResolution>>,
508 // The number of unresolved globs that this module exports.
509 glob_count: Cell<uint>,
511 // The index of the import we're resolving.
512 resolved_import_count: Cell<uint>,
514 // Whether this module is populated. If not populated, any attempt to
515 // access the children must be preceded with a
516 // `populate_module_if_necessary` call.
517 populated: Cell<bool>,
521 fn new(parent_link: ParentLink,
522 def_id: Option<DefId>,
528 parent_link: parent_link,
529 def_id: Cell::new(def_id),
530 kind: Cell::new(kind),
531 is_public: is_public,
532 children: RefCell::new(HashMap::new()),
533 imports: RefCell::new(Vec::new()),
534 external_module_children: RefCell::new(HashMap::new()),
535 anonymous_children: RefCell::new(NodeMap()),
536 import_resolutions: RefCell::new(HashMap::new()),
537 glob_count: Cell::new(0),
538 resolved_import_count: Cell::new(0),
539 populated: Cell::new(!external),
543 fn all_imports_resolved(&self) -> bool {
544 self.imports.borrow().len() == self.resolved_import_count.get()
548 impl fmt::Debug for Module {
549 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
550 write!(f, "{:?}, kind: {:?}, {}",
553 if self.is_public { "public" } else { "private" } )
559 flags DefModifiers: u8 {
560 const PUBLIC = 0b0000_0001,
561 const IMPORTABLE = 0b0000_0010,
565 // Records a possibly-private type definition.
566 #[derive(Clone,Debug)]
568 modifiers: DefModifiers, // see note in ImportResolution about how to use this
569 module_def: Option<Rc<Module>>,
570 type_def: Option<Def>,
571 type_span: Option<Span>
574 // Records a possibly-private value definition.
575 #[derive(Clone, Copy, Debug)]
577 modifiers: DefModifiers, // see note in ImportResolution about how to use this
579 value_span: Option<Span>,
582 // Records the definitions (at most one for each namespace) that a name is
585 struct NameBindings {
586 type_def: RefCell<Option<TypeNsDef>>, //< Meaning in type namespace.
587 value_def: RefCell<Option<ValueNsDef>>, //< Meaning in value namespace.
590 /// Ways in which a trait can be referenced
592 enum TraitReferenceType {
593 TraitImplementation, // impl SomeTrait for T { ... }
594 TraitDerivation, // trait T : SomeTrait { ... }
595 TraitBoundingTypeParameter, // fn f<T:SomeTrait>() { ... }
596 TraitObject, // Box<for<'a> SomeTrait>
597 TraitQPath, // <T as SomeTrait>::
601 fn new() -> NameBindings {
603 type_def: RefCell::new(None),
604 value_def: RefCell::new(None),
608 /// Creates a new module in this set of name bindings.
609 fn define_module(&self,
610 parent_link: ParentLink,
611 def_id: Option<DefId>,
616 // Merges the module with the existing type def or creates a new one.
617 let modifiers = if is_public { PUBLIC } else { DefModifiers::empty() } | IMPORTABLE;
618 let module_ = Rc::new(Module::new(parent_link,
623 let type_def = self.type_def.borrow().clone();
626 *self.type_def.borrow_mut() = Some(TypeNsDef {
627 modifiers: modifiers,
628 module_def: Some(module_),
634 *self.type_def.borrow_mut() = Some(TypeNsDef {
635 modifiers: modifiers,
636 module_def: Some(module_),
638 type_def: type_def.type_def
644 /// Sets the kind of the module, creating a new one if necessary.
645 fn set_module_kind(&self,
646 parent_link: ParentLink,
647 def_id: Option<DefId>,
652 let modifiers = if is_public { PUBLIC } else { DefModifiers::empty() } | IMPORTABLE;
653 let type_def = self.type_def.borrow().clone();
656 let module = Module::new(parent_link,
661 *self.type_def.borrow_mut() = Some(TypeNsDef {
662 modifiers: modifiers,
663 module_def: Some(Rc::new(module)),
669 match type_def.module_def {
671 let module = Module::new(parent_link,
676 *self.type_def.borrow_mut() = Some(TypeNsDef {
677 modifiers: modifiers,
678 module_def: Some(Rc::new(module)),
679 type_def: type_def.type_def,
683 Some(module_def) => module_def.kind.set(kind),
689 /// Records a type definition.
690 fn define_type(&self, def: Def, sp: Span, modifiers: DefModifiers) {
691 debug!("defining type for def {:?} with modifiers {:?}", def, modifiers);
692 // Merges the type with the existing type def or creates a new one.
693 let type_def = self.type_def.borrow().clone();
696 *self.type_def.borrow_mut() = Some(TypeNsDef {
700 modifiers: modifiers,
704 *self.type_def.borrow_mut() = Some(TypeNsDef {
705 module_def: type_def.module_def,
708 modifiers: modifiers,
714 /// Records a value definition.
715 fn define_value(&self, def: Def, sp: Span, modifiers: DefModifiers) {
716 debug!("defining value for def {:?} with modifiers {:?}", def, modifiers);
717 *self.value_def.borrow_mut() = Some(ValueNsDef {
719 value_span: Some(sp),
720 modifiers: modifiers,
724 /// Returns the module node if applicable.
725 fn get_module_if_available(&self) -> Option<Rc<Module>> {
726 match *self.type_def.borrow() {
727 Some(ref type_def) => type_def.module_def.clone(),
732 /// Returns the module node. Panics if this node does not have a module
734 fn get_module(&self) -> Rc<Module> {
735 match self.get_module_if_available() {
737 panic!("get_module called on a node with no module \
740 Some(module_def) => module_def
744 fn defined_in_namespace(&self, namespace: Namespace) -> bool {
746 TypeNS => return self.type_def.borrow().is_some(),
747 ValueNS => return self.value_def.borrow().is_some()
751 fn defined_in_public_namespace(&self, namespace: Namespace) -> bool {
752 self.defined_in_namespace_with(namespace, PUBLIC)
755 fn defined_in_namespace_with(&self, namespace: Namespace, modifiers: DefModifiers) -> bool {
757 TypeNS => match *self.type_def.borrow() {
758 Some(ref def) => def.modifiers.contains(modifiers), None => false
760 ValueNS => match *self.value_def.borrow() {
761 Some(ref def) => def.modifiers.contains(modifiers), None => false
766 fn def_for_namespace(&self, namespace: Namespace) -> Option<Def> {
769 match *self.type_def.borrow() {
771 Some(ref type_def) => {
772 match type_def.type_def {
773 Some(type_def) => Some(type_def),
775 match type_def.module_def {
776 Some(ref module) => {
777 match module.def_id.get() {
778 Some(did) => Some(DefMod(did)),
790 match *self.value_def.borrow() {
792 Some(value_def) => Some(value_def.def)
798 fn span_for_namespace(&self, namespace: Namespace) -> Option<Span> {
799 if self.defined_in_namespace(namespace) {
802 match *self.type_def.borrow() {
804 Some(ref type_def) => type_def.type_span
808 match *self.value_def.borrow() {
810 Some(ref value_def) => value_def.value_span
820 /// Interns the names of the primitive types.
821 struct PrimitiveTypeTable {
822 primitive_types: HashMap<Name, PrimTy>,
825 impl PrimitiveTypeTable {
826 fn new() -> PrimitiveTypeTable {
827 let mut table = PrimitiveTypeTable {
828 primitive_types: HashMap::new()
831 table.intern("bool", TyBool);
832 table.intern("char", TyChar);
833 table.intern("f32", TyFloat(TyF32));
834 table.intern("f64", TyFloat(TyF64));
835 table.intern("int", TyInt(TyIs(true)));
836 table.intern("isize", TyInt(TyIs(false)));
837 table.intern("i8", TyInt(TyI8));
838 table.intern("i16", TyInt(TyI16));
839 table.intern("i32", TyInt(TyI32));
840 table.intern("i64", TyInt(TyI64));
841 table.intern("str", TyStr);
842 table.intern("uint", TyUint(TyUs(true)));
843 table.intern("usize", TyUint(TyUs(false)));
844 table.intern("u8", TyUint(TyU8));
845 table.intern("u16", TyUint(TyU16));
846 table.intern("u32", TyUint(TyU32));
847 table.intern("u64", TyUint(TyU64));
852 fn intern(&mut self, string: &str, primitive_type: PrimTy) {
853 self.primitive_types.insert(token::intern(string), primitive_type);
857 /// The main resolver class.
858 struct Resolver<'a, 'tcx:'a> {
859 session: &'a Session,
861 ast_map: &'a ast_map::Map<'tcx>,
863 graph_root: NameBindings,
865 trait_item_map: FnvHashMap<(Name, DefId), TraitItemKind>,
867 structs: FnvHashMap<DefId, Vec<Name>>,
869 // The number of imports that are currently unresolved.
870 unresolved_imports: uint,
872 // The module that represents the current item scope.
873 current_module: Rc<Module>,
875 // The current set of local scopes, for values.
876 // FIXME #4948: Reuse ribs to avoid allocation.
877 value_ribs: Vec<Rib>,
879 // The current set of local scopes, for types.
882 // The current set of local scopes, for labels.
883 label_ribs: Vec<Rib>,
885 // The trait that the current context can refer to.
886 current_trait_ref: Option<(DefId, TraitRef)>,
888 // The current self type if inside an impl (used for better errors).
889 current_self_type: Option<Ty>,
891 // The ident for the keyword "self".
893 // The ident for the non-keyword "Self".
894 type_self_name: Name,
896 // The idents for the primitive types.
897 primitive_type_table: PrimitiveTypeTable,
900 freevars: RefCell<FreevarMap>,
901 freevars_seen: RefCell<NodeMap<NodeSet>>,
902 export_map: ExportMap,
904 external_exports: ExternalExports,
905 last_private: LastPrivateMap,
907 // Whether or not to print error messages. Can be set to true
908 // when getting additional info for error message suggestions,
909 // so as to avoid printing duplicate errors
913 // Maps imports to the names of items actually imported (this actually maps
914 // all imports, but only glob imports are actually interesting).
917 used_imports: HashSet<(NodeId, Namespace)>,
918 used_crates: HashSet<CrateNum>,
922 enum FallbackChecks {
928 impl<'a, 'tcx> Resolver<'a, 'tcx> {
929 fn new(session: &'a Session,
930 ast_map: &'a ast_map::Map<'tcx>,
932 make_glob_map: MakeGlobMap) -> Resolver<'a, 'tcx> {
933 let graph_root = NameBindings::new();
935 graph_root.define_module(NoParentLink,
936 Some(DefId { krate: 0, node: 0 }),
942 let current_module = graph_root.get_module();
949 // The outermost module has def ID 0; this is not reflected in the
952 graph_root: graph_root,
954 trait_item_map: FnvHashMap(),
955 structs: FnvHashMap(),
957 unresolved_imports: 0,
959 current_module: current_module,
960 value_ribs: Vec::new(),
961 type_ribs: Vec::new(),
962 label_ribs: Vec::new(),
964 current_trait_ref: None,
965 current_self_type: None,
967 self_name: special_names::self_,
968 type_self_name: special_names::type_self,
970 primitive_type_table: PrimitiveTypeTable::new(),
972 def_map: RefCell::new(NodeMap()),
973 freevars: RefCell::new(NodeMap()),
974 freevars_seen: RefCell::new(NodeMap()),
975 export_map: NodeMap(),
976 trait_map: NodeMap(),
977 used_imports: HashSet::new(),
978 used_crates: HashSet::new(),
979 external_exports: DefIdSet(),
980 last_private: NodeMap(),
983 make_glob_map: make_glob_map == MakeGlobMap::Yes,
984 glob_map: HashMap::new(),
990 // This is a fixed-point algorithm. We resolve imports until our efforts
991 // are stymied by an unresolved import; then we bail out of the current
992 // module and continue. We terminate successfully once no more imports
993 // remain or unsuccessfully when no forward progress in resolving imports
996 /// Resolves all imports for the crate. This method performs the fixed-
998 fn resolve_imports(&mut self) {
1000 let mut prev_unresolved_imports = 0;
1002 debug!("(resolving imports) iteration {}, {} imports left",
1003 i, self.unresolved_imports);
1005 let module_root = self.graph_root.get_module();
1006 self.resolve_imports_for_module_subtree(module_root.clone());
1008 if self.unresolved_imports == 0 {
1009 debug!("(resolving imports) success");
1013 if self.unresolved_imports == prev_unresolved_imports {
1014 self.report_unresolved_imports(module_root);
1019 prev_unresolved_imports = self.unresolved_imports;
1023 /// Attempts to resolve imports for the given module and all of its
1025 fn resolve_imports_for_module_subtree(&mut self, module_: Rc<Module>) {
1026 debug!("(resolving imports for module subtree) resolving {}",
1027 self.module_to_string(&*module_));
1028 let orig_module = replace(&mut self.current_module, module_.clone());
1029 self.resolve_imports_for_module(module_.clone());
1030 self.current_module = orig_module;
1032 build_reduced_graph::populate_module_if_necessary(self, &module_);
1033 for (_, child_node) in &*module_.children.borrow() {
1034 match child_node.get_module_if_available() {
1038 Some(child_module) => {
1039 self.resolve_imports_for_module_subtree(child_module);
1044 for (_, child_module) in &*module_.anonymous_children.borrow() {
1045 self.resolve_imports_for_module_subtree(child_module.clone());
1049 /// Attempts to resolve imports for the given module only.
1050 fn resolve_imports_for_module(&mut self, module: Rc<Module>) {
1051 if module.all_imports_resolved() {
1052 debug!("(resolving imports for module) all imports resolved for \
1054 self.module_to_string(&*module));
1058 let imports = module.imports.borrow();
1059 let import_count = imports.len();
1060 while module.resolved_import_count.get() < import_count {
1061 let import_index = module.resolved_import_count.get();
1062 let import_directive = &(*imports)[import_index];
1063 match self.resolve_import_for_module(module.clone(),
1066 let (span, help) = match err {
1067 Some((span, msg)) => (span, format!(". {}", msg)),
1068 None => (import_directive.span, String::new())
1070 let msg = format!("unresolved import `{}`{}",
1071 self.import_path_to_string(
1072 &import_directive.module_path[],
1073 import_directive.subclass),
1075 self.resolve_error(span, &msg[]);
1077 Indeterminate => break, // Bail out. We'll come around next time.
1078 Success(()) => () // Good. Continue.
1081 module.resolved_import_count
1082 .set(module.resolved_import_count.get() + 1);
1086 fn names_to_string(&self, names: &[Name]) -> String {
1087 let mut first = true;
1088 let mut result = String::new();
1093 result.push_str("::")
1095 result.push_str(&token::get_name(*name));
1100 fn path_names_to_string(&self, path: &Path) -> String {
1101 let names: Vec<ast::Name> = path.segments
1103 .map(|seg| seg.identifier.name)
1105 self.names_to_string(&names[])
1108 fn import_directive_subclass_to_string(&mut self,
1109 subclass: ImportDirectiveSubclass)
1112 SingleImport(_, source) => {
1113 token::get_name(source).to_string()
1115 GlobImport => "*".to_string()
1119 fn import_path_to_string(&mut self,
1121 subclass: ImportDirectiveSubclass)
1123 if names.is_empty() {
1124 self.import_directive_subclass_to_string(subclass)
1127 self.names_to_string(names),
1128 self.import_directive_subclass_to_string(
1129 subclass))).to_string()
1134 fn record_import_use(&mut self, import_id: NodeId, name: Name) {
1135 if !self.make_glob_map {
1138 if self.glob_map.contains_key(&import_id) {
1139 self.glob_map[import_id].insert(name);
1143 let mut new_set = HashSet::new();
1144 new_set.insert(name);
1145 self.glob_map.insert(import_id, new_set);
1148 fn get_trait_name(&self, did: DefId) -> Name {
1149 if did.krate == ast::LOCAL_CRATE {
1150 self.ast_map.expect_item(did.node).ident.name
1152 csearch::get_trait_name(&self.session.cstore, did)
1156 /// Attempts to resolve the given import. The return value indicates
1157 /// failure if we're certain the name does not exist, indeterminate if we
1158 /// don't know whether the name exists at the moment due to other
1159 /// currently-unresolved imports, or success if we know the name exists.
1160 /// If successful, the resolved bindings are written into the module.
1161 fn resolve_import_for_module(&mut self,
1162 module_: Rc<Module>,
1163 import_directive: &ImportDirective)
1164 -> ResolveResult<()> {
1165 let mut resolution_result = Failed(None);
1166 let module_path = &import_directive.module_path;
1168 debug!("(resolving import for module) resolving import `{}::...` in `{}`",
1169 self.names_to_string(&module_path[]),
1170 self.module_to_string(&*module_));
1172 // First, resolve the module path for the directive, if necessary.
1173 let container = if module_path.len() == 0 {
1174 // Use the crate root.
1175 Some((self.graph_root.get_module(), LastMod(AllPublic)))
1177 match self.resolve_module_path(module_.clone(),
1179 DontUseLexicalScope,
1180 import_directive.span,
1183 resolution_result = Failed(err);
1187 resolution_result = Indeterminate;
1190 Success(container) => Some(container),
1196 Some((containing_module, lp)) => {
1197 // We found the module that the target is contained
1198 // within. Attempt to resolve the import within it.
1200 match import_directive.subclass {
1201 SingleImport(target, source) => {
1203 self.resolve_single_import(&*module_,
1212 self.resolve_glob_import(&*module_,
1221 // Decrement the count of unresolved imports.
1222 match resolution_result {
1224 assert!(self.unresolved_imports >= 1);
1225 self.unresolved_imports -= 1;
1228 // Nothing to do here; just return the error.
1232 // Decrement the count of unresolved globs if necessary. But only if
1233 // the resolution result is indeterminate -- otherwise we'll stop
1234 // processing imports here. (See the loop in
1235 // resolve_imports_for_module.)
1237 if !resolution_result.indeterminate() {
1238 match import_directive.subclass {
1240 assert!(module_.glob_count.get() >= 1);
1241 module_.glob_count.set(module_.glob_count.get() - 1);
1243 SingleImport(..) => {
1249 return resolution_result;
1252 fn create_name_bindings_from_module(module: Rc<Module>) -> NameBindings {
1254 type_def: RefCell::new(Some(TypeNsDef {
1255 modifiers: IMPORTABLE,
1256 module_def: Some(module),
1260 value_def: RefCell::new(None),
1264 fn resolve_single_import(&mut self,
1266 containing_module: Rc<Module>,
1269 directive: &ImportDirective,
1271 -> ResolveResult<()> {
1272 debug!("(resolving single import) resolving `{}` = `{}::{}` from \
1273 `{}` id {}, last private {:?}",
1274 token::get_name(target),
1275 self.module_to_string(&*containing_module),
1276 token::get_name(source),
1277 self.module_to_string(module_),
1283 LastImport {..} => {
1285 .span_bug(directive.span,
1286 "not expecting Import here, must be LastMod")
1290 // We need to resolve both namespaces for this to succeed.
1293 let mut value_result = UnknownResult;
1294 let mut type_result = UnknownResult;
1296 // Search for direct children of the containing module.
1297 build_reduced_graph::populate_module_if_necessary(self, &containing_module);
1299 match containing_module.children.borrow().get(&source) {
1303 Some(ref child_name_bindings) => {
1304 if child_name_bindings.defined_in_namespace(ValueNS) {
1305 debug!("(resolving single import) found value binding");
1306 value_result = BoundResult(containing_module.clone(),
1307 (*child_name_bindings).clone());
1309 if child_name_bindings.defined_in_namespace(TypeNS) {
1310 debug!("(resolving single import) found type binding");
1311 type_result = BoundResult(containing_module.clone(),
1312 (*child_name_bindings).clone());
1317 // Unless we managed to find a result in both namespaces (unlikely),
1318 // search imports as well.
1319 let mut value_used_reexport = false;
1320 let mut type_used_reexport = false;
1321 match (value_result.clone(), type_result.clone()) {
1322 (BoundResult(..), BoundResult(..)) => {} // Continue.
1324 // If there is an unresolved glob at this point in the
1325 // containing module, bail out. We don't know enough to be
1326 // able to resolve this import.
1328 if containing_module.glob_count.get() > 0 {
1329 debug!("(resolving single import) unresolved glob; \
1331 return Indeterminate;
1334 // Now search the exported imports within the containing module.
1335 match containing_module.import_resolutions.borrow().get(&source) {
1337 debug!("(resolving single import) no import");
1338 // The containing module definitely doesn't have an
1339 // exported import with the name in question. We can
1340 // therefore accurately report that the names are
1343 if value_result.is_unknown() {
1344 value_result = UnboundResult;
1346 if type_result.is_unknown() {
1347 type_result = UnboundResult;
1350 Some(import_resolution)
1351 if import_resolution.outstanding_references == 0 => {
1353 fn get_binding(this: &mut Resolver,
1354 import_resolution: &ImportResolution,
1355 namespace: Namespace,
1357 -> NamespaceResult {
1359 // Import resolutions must be declared with "pub"
1360 // in order to be exported.
1361 if !import_resolution.is_public {
1362 return UnboundResult;
1365 match import_resolution.
1366 target_for_namespace(namespace) {
1368 return UnboundResult;
1375 debug!("(resolving single import) found \
1376 import in ns {:?}", namespace);
1377 let id = import_resolution.id(namespace);
1378 // track used imports and extern crates as well
1379 this.used_imports.insert((id, namespace));
1380 this.record_import_use(id, *source);
1381 match target_module.def_id.get() {
1382 Some(DefId{krate: kid, ..}) => {
1383 this.used_crates.insert(kid);
1387 return BoundResult(target_module, bindings);
1392 // The name is an import which has been fully
1393 // resolved. We can, therefore, just follow it.
1394 if value_result.is_unknown() {
1395 value_result = get_binding(self,
1399 value_used_reexport = import_resolution.is_public;
1401 if type_result.is_unknown() {
1402 type_result = get_binding(self,
1406 type_used_reexport = import_resolution.is_public;
1411 // If containing_module is the same module whose import we are resolving
1412 // and there it has an unresolved import with the same name as `source`,
1413 // then the user is actually trying to import an item that is declared
1414 // in the same scope
1417 // use self::submodule;
1418 // pub mod submodule;
1420 // In this case we continue as if we resolved the import and let the
1421 // check_for_conflicts_between_imports_and_items call below handle
1423 match (module_.def_id.get(), containing_module.def_id.get()) {
1424 (Some(id1), Some(id2)) if id1 == id2 => {
1425 if value_result.is_unknown() {
1426 value_result = UnboundResult;
1428 if type_result.is_unknown() {
1429 type_result = UnboundResult;
1433 // The import is unresolved. Bail out.
1434 debug!("(resolving single import) unresolved import; \
1436 return Indeterminate;
1444 // If we didn't find a result in the type namespace, search the
1445 // external modules.
1446 let mut value_used_public = false;
1447 let mut type_used_public = false;
1449 BoundResult(..) => {}
1451 match containing_module.external_module_children.borrow_mut()
1452 .get(&source).cloned() {
1453 None => {} // Continue.
1455 debug!("(resolving single import) found external \
1457 // track the module as used.
1458 match module.def_id.get() {
1459 Some(DefId{krate: kid, ..}) => { self.used_crates.insert(kid); },
1463 Rc::new(Resolver::create_name_bindings_from_module(
1465 type_result = BoundResult(containing_module.clone(),
1467 type_used_public = true;
1473 // We've successfully resolved the import. Write the results in.
1474 let mut import_resolutions = module_.import_resolutions.borrow_mut();
1475 let import_resolution = &mut (*import_resolutions)[target];
1477 let mut check_and_write_import = |namespace, result: &_, used_public: &mut bool| {
1478 let namespace_name = match namespace {
1484 BoundResult(ref target_module, ref name_bindings) => {
1485 debug!("(resolving single import) found {:?} target: {:?}",
1487 name_bindings.def_for_namespace(namespace));
1488 self.check_for_conflicting_import(
1489 &import_resolution.target_for_namespace(namespace),
1494 self.check_that_import_is_importable(
1500 let target = Some(Target::new(target_module.clone(),
1501 name_bindings.clone(),
1502 directive.shadowable));
1503 import_resolution.set_target_and_id(namespace, target, directive.id);
1504 import_resolution.is_public = directive.is_public;
1505 *used_public = name_bindings.defined_in_public_namespace(namespace);
1507 UnboundResult => { /* Continue. */ }
1509 panic!("{:?} result should be known at this point", namespace_name);
1513 check_and_write_import(ValueNS, &value_result, &mut value_used_public);
1514 check_and_write_import(TypeNS, &type_result, &mut type_used_public);
1517 self.check_for_conflicts_between_imports_and_items(
1523 if value_result.is_unbound() && type_result.is_unbound() {
1524 let msg = format!("There is no `{}` in `{}`",
1525 token::get_name(source),
1526 self.module_to_string(&*containing_module));
1527 return Failed(Some((directive.span, msg)));
1529 let value_used_public = value_used_reexport || value_used_public;
1530 let type_used_public = type_used_reexport || type_used_public;
1532 assert!(import_resolution.outstanding_references >= 1);
1533 import_resolution.outstanding_references -= 1;
1535 // record what this import resolves to for later uses in documentation,
1536 // this may resolve to either a value or a type, but for documentation
1537 // purposes it's good enough to just favor one over the other.
1538 let value_private = match import_resolution.value_target {
1539 Some(ref target) => {
1540 let def = target.bindings.def_for_namespace(ValueNS).unwrap();
1541 self.def_map.borrow_mut().insert(directive.id, def);
1542 let did = def.def_id();
1543 if value_used_public {Some(lp)} else {Some(DependsOn(did))}
1545 // AllPublic here and below is a dummy value, it should never be used because
1546 // _exists is false.
1549 let type_private = match import_resolution.type_target {
1550 Some(ref target) => {
1551 let def = target.bindings.def_for_namespace(TypeNS).unwrap();
1552 self.def_map.borrow_mut().insert(directive.id, def);
1553 let did = def.def_id();
1554 if type_used_public {Some(lp)} else {Some(DependsOn(did))}
1559 self.last_private.insert(directive.id, LastImport{value_priv: value_private,
1561 type_priv: type_private,
1564 debug!("(resolving single import) successfully resolved import");
1568 // Resolves a glob import. Note that this function cannot fail; it either
1569 // succeeds or bails out (as importing * from an empty module or a module
1570 // that exports nothing is valid). containing_module is the module we are
1571 // actually importing, i.e., `foo` in `use foo::*`.
1572 fn resolve_glob_import(&mut self,
1574 containing_module: Rc<Module>,
1575 import_directive: &ImportDirective,
1577 -> ResolveResult<()> {
1578 let id = import_directive.id;
1579 let is_public = import_directive.is_public;
1581 // This function works in a highly imperative manner; it eagerly adds
1582 // everything it can to the list of import resolutions of the module
1584 debug!("(resolving glob import) resolving glob import {}", id);
1586 // We must bail out if the node has unresolved imports of any kind
1587 // (including globs).
1588 if !(*containing_module).all_imports_resolved() {
1589 debug!("(resolving glob import) target module has unresolved \
1590 imports; bailing out");
1591 return Indeterminate;
1594 assert_eq!(containing_module.glob_count.get(), 0);
1596 // Add all resolved imports from the containing module.
1597 let import_resolutions = containing_module.import_resolutions.borrow();
1598 for (ident, target_import_resolution) in &*import_resolutions {
1599 debug!("(resolving glob import) writing module resolution \
1601 token::get_name(*ident),
1602 self.module_to_string(module_));
1604 if !target_import_resolution.is_public {
1605 debug!("(resolving glob import) nevermind, just kidding");
1609 // Here we merge two import resolutions.
1610 let mut import_resolutions = module_.import_resolutions.borrow_mut();
1611 match import_resolutions.get_mut(ident) {
1612 Some(dest_import_resolution) => {
1613 // Merge the two import resolutions at a finer-grained
1616 match target_import_resolution.value_target {
1620 Some(ref value_target) => {
1621 self.check_for_conflicting_import(&dest_import_resolution.value_target,
1622 import_directive.span,
1625 dest_import_resolution.value_target = Some(value_target.clone());
1628 match target_import_resolution.type_target {
1632 Some(ref type_target) => {
1633 self.check_for_conflicting_import(&dest_import_resolution.type_target,
1634 import_directive.span,
1637 dest_import_resolution.type_target = Some(type_target.clone());
1640 dest_import_resolution.is_public = is_public;
1646 // Simple: just copy the old import resolution.
1647 let mut new_import_resolution = ImportResolution::new(id, is_public);
1648 new_import_resolution.value_target =
1649 target_import_resolution.value_target.clone();
1650 new_import_resolution.type_target =
1651 target_import_resolution.type_target.clone();
1653 import_resolutions.insert(*ident, new_import_resolution);
1656 // Add all children from the containing module.
1657 build_reduced_graph::populate_module_if_necessary(self, &containing_module);
1659 for (&name, name_bindings) in &*containing_module.children.borrow() {
1660 self.merge_import_resolution(module_,
1661 containing_module.clone(),
1664 name_bindings.clone());
1668 // Add external module children from the containing module.
1669 for (&name, module) in &*containing_module.external_module_children.borrow() {
1671 Rc::new(Resolver::create_name_bindings_from_module(module.clone()));
1672 self.merge_import_resolution(module_,
1673 containing_module.clone(),
1679 // Record the destination of this import
1680 match containing_module.def_id.get() {
1682 self.def_map.borrow_mut().insert(id, DefMod(did));
1683 self.last_private.insert(id, lp);
1688 debug!("(resolving glob import) successfully resolved import");
1692 fn merge_import_resolution(&mut self,
1694 containing_module: Rc<Module>,
1695 import_directive: &ImportDirective,
1697 name_bindings: Rc<NameBindings>) {
1698 let id = import_directive.id;
1699 let is_public = import_directive.is_public;
1701 let mut import_resolutions = module_.import_resolutions.borrow_mut();
1702 let dest_import_resolution = import_resolutions.entry(name).get().unwrap_or_else(
1704 // Create a new import resolution from this child.
1705 vacant_entry.insert(ImportResolution::new(id, is_public))
1708 debug!("(resolving glob import) writing resolution `{}` in `{}` \
1710 &token::get_name(name),
1711 self.module_to_string(&*containing_module),
1712 self.module_to_string(module_));
1714 // Merge the child item into the import resolution.
1716 let mut merge_child_item = |namespace| {
1717 if name_bindings.defined_in_namespace_with(namespace, IMPORTABLE | PUBLIC) {
1718 let namespace_name = match namespace {
1722 debug!("(resolving glob import) ... for {} target", namespace_name);
1723 if dest_import_resolution.shadowable(namespace) == Shadowable::Never {
1724 let msg = format!("a {} named `{}` has already been imported \
1727 &token::get_name(name));
1728 span_err!(self.session, import_directive.span, E0251, "{}", msg);
1730 let target = Target::new(containing_module.clone(),
1731 name_bindings.clone(),
1732 import_directive.shadowable);
1733 dest_import_resolution.set_target_and_id(namespace,
1739 merge_child_item(ValueNS);
1740 merge_child_item(TypeNS);
1743 dest_import_resolution.is_public = is_public;
1745 self.check_for_conflicts_between_imports_and_items(
1747 dest_import_resolution,
1748 import_directive.span,
1752 /// Checks that imported names and items don't have the same name.
1753 fn check_for_conflicting_import(&mut self,
1754 target: &Option<Target>,
1757 namespace: Namespace) {
1758 debug!("check_for_conflicting_import: {}; target exists: {}",
1759 &token::get_name(name),
1763 Some(ref target) if target.shadowable != Shadowable::Always => {
1764 let msg = format!("a {} named `{}` has already been imported \
1770 &token::get_name(name));
1771 span_err!(self.session, import_span, E0252, "{}", &msg[]);
1773 Some(_) | None => {}
1777 /// Checks that an import is actually importable
1778 fn check_that_import_is_importable(&mut self,
1779 name_bindings: &NameBindings,
1782 namespace: Namespace) {
1783 if !name_bindings.defined_in_namespace_with(namespace, IMPORTABLE) {
1784 let msg = format!("`{}` is not directly importable",
1785 token::get_name(name));
1786 span_err!(self.session, import_span, E0253, "{}", &msg[]);
1790 /// Checks that imported names and items don't have the same name.
1791 fn check_for_conflicts_between_imports_and_items(&mut self,
1797 // First, check for conflicts between imports and `extern crate`s.
1798 if module.external_module_children
1800 .contains_key(&name) {
1801 match import_resolution.type_target {
1802 Some(ref target) if target.shadowable != Shadowable::Always => {
1803 let msg = format!("import `{0}` conflicts with imported \
1804 crate in this module \
1805 (maybe you meant `use {0}::*`?)",
1806 &token::get_name(name));
1807 span_err!(self.session, import_span, E0254, "{}", &msg[]);
1809 Some(_) | None => {}
1813 // Check for item conflicts.
1814 let children = module.children.borrow();
1815 let name_bindings = match children.get(&name) {
1817 // There can't be any conflicts.
1820 Some(ref name_bindings) => (*name_bindings).clone(),
1823 match import_resolution.value_target {
1824 Some(ref target) if target.shadowable != Shadowable::Always => {
1825 if let Some(ref value) = *name_bindings.value_def.borrow() {
1826 let msg = format!("import `{}` conflicts with value \
1828 &token::get_name(name));
1829 span_err!(self.session, import_span, E0255, "{}", &msg[]);
1830 if let Some(span) = value.value_span {
1831 self.session.span_note(span,
1832 "conflicting value here");
1836 Some(_) | None => {}
1839 match import_resolution.type_target {
1840 Some(ref target) if target.shadowable != Shadowable::Always => {
1841 if let Some(ref ty) = *name_bindings.type_def.borrow() {
1842 match ty.module_def {
1844 let msg = format!("import `{}` conflicts with type in \
1846 &token::get_name(name));
1847 span_err!(self.session, import_span, E0256, "{}", &msg[]);
1848 if let Some(span) = ty.type_span {
1849 self.session.span_note(span,
1850 "note conflicting type here")
1853 Some(ref module_def) => {
1854 match module_def.kind.get() {
1856 if let Some(span) = ty.type_span {
1857 let msg = format!("inherent implementations \
1858 are only allowed on types \
1859 defined in the current module");
1860 span_err!(self.session, span, E0257, "{}", &msg[]);
1861 self.session.span_note(import_span,
1862 "import from other module here")
1866 let msg = format!("import `{}` conflicts with existing \
1868 &token::get_name(name));
1869 span_err!(self.session, import_span, E0258, "{}", &msg[]);
1870 if let Some(span) = ty.type_span {
1871 self.session.span_note(span,
1872 "note conflicting module here")
1880 Some(_) | None => {}
1884 /// Checks that the names of external crates don't collide with other
1885 /// external crates.
1886 fn check_for_conflicts_between_external_crates(&self,
1890 if module.external_module_children.borrow().contains_key(&name) {
1891 span_err!(self.session, span, E0259,
1892 "an external crate named `{}` has already \
1893 been imported into this module",
1894 &token::get_name(name));
1898 /// Checks that the names of items don't collide with external crates.
1899 fn check_for_conflicts_between_external_crates_and_items(&self,
1903 if module.external_module_children.borrow().contains_key(&name) {
1904 span_err!(self.session, span, E0260,
1905 "the name `{}` conflicts with an external \
1906 crate that has been imported into this \
1908 &token::get_name(name));
1912 /// Resolves the given module path from the given root `module_`.
1913 fn resolve_module_path_from_root(&mut self,
1914 module_: Rc<Module>,
1915 module_path: &[Name],
1918 name_search_type: NameSearchType,
1920 -> ResolveResult<(Rc<Module>, LastPrivate)> {
1921 fn search_parent_externals(needle: Name, module: &Rc<Module>)
1922 -> Option<Rc<Module>> {
1923 module.external_module_children.borrow()
1924 .get(&needle).cloned()
1925 .map(|_| module.clone())
1927 match module.parent_link.clone() {
1928 ModuleParentLink(parent, _) => {
1929 search_parent_externals(needle,
1930 &parent.upgrade().unwrap())
1937 let mut search_module = module_;
1938 let mut index = index;
1939 let module_path_len = module_path.len();
1940 let mut closest_private = lp;
1942 // Resolve the module part of the path. This does not involve looking
1943 // upward though scope chains; we simply resolve names directly in
1944 // modules as we go.
1945 while index < module_path_len {
1946 let name = module_path[index];
1947 match self.resolve_name_in_module(search_module.clone(),
1953 let segment_name = token::get_name(name);
1954 let module_name = self.module_to_string(&*search_module);
1955 let mut span = span;
1956 let msg = if "???" == &module_name[] {
1957 span.hi = span.lo + Pos::from_usize(segment_name.len());
1959 match search_parent_externals(name,
1960 &self.current_module) {
1962 let path_str = self.names_to_string(module_path);
1963 let target_mod_str = self.module_to_string(&*module);
1964 let current_mod_str =
1965 self.module_to_string(&*self.current_module);
1967 let prefix = if target_mod_str == current_mod_str {
1968 "self::".to_string()
1970 format!("{}::", target_mod_str)
1973 format!("Did you mean `{}{}`?", prefix, path_str)
1975 None => format!("Maybe a missing `extern crate {}`?",
1979 format!("Could not find `{}` in `{}`",
1984 return Failed(Some((span, msg)));
1986 Failed(err) => return Failed(err),
1988 debug!("(resolving module path for import) module \
1989 resolution is indeterminate: {}",
1990 token::get_name(name));
1991 return Indeterminate;
1993 Success((target, used_proxy)) => {
1994 // Check to see whether there are type bindings, and, if
1995 // so, whether there is a module within.
1996 match *target.bindings.type_def.borrow() {
1997 Some(ref type_def) => {
1998 match type_def.module_def {
2000 let msg = format!("Not a module `{}`",
2001 token::get_name(name));
2003 return Failed(Some((span, msg)));
2005 Some(ref module_def) => {
2006 search_module = module_def.clone();
2008 // track extern crates for unused_extern_crate lint
2009 if let Some(did) = module_def.def_id.get() {
2010 self.used_crates.insert(did.krate);
2013 // Keep track of the closest
2014 // private module used when
2015 // resolving this import chain.
2016 if !used_proxy && !search_module.is_public {
2017 if let Some(did) = search_module.def_id.get() {
2018 closest_private = LastMod(DependsOn(did));
2025 // There are no type bindings at all.
2026 let msg = format!("Not a module `{}`",
2027 token::get_name(name));
2028 return Failed(Some((span, msg)));
2037 return Success((search_module, closest_private));
2040 /// Attempts to resolve the module part of an import directive or path
2041 /// rooted at the given module.
2043 /// On success, returns the resolved module, and the closest *private*
2044 /// module found to the destination when resolving this path.
2045 fn resolve_module_path(&mut self,
2046 module_: Rc<Module>,
2047 module_path: &[Name],
2048 use_lexical_scope: UseLexicalScopeFlag,
2050 name_search_type: NameSearchType)
2051 -> ResolveResult<(Rc<Module>, LastPrivate)> {
2052 let module_path_len = module_path.len();
2053 assert!(module_path_len > 0);
2055 debug!("(resolving module path for import) processing `{}` rooted at `{}`",
2056 self.names_to_string(module_path),
2057 self.module_to_string(&*module_));
2059 // Resolve the module prefix, if any.
2060 let module_prefix_result = self.resolve_module_prefix(module_.clone(),
2066 match module_prefix_result {
2068 let mpath = self.names_to_string(module_path);
2069 let mpath = &mpath[];
2070 match mpath.rfind(':') {
2072 let msg = format!("Could not find `{}` in `{}`",
2073 // idx +- 1 to account for the
2074 // colons on either side
2077 return Failed(Some((span, msg)));
2084 Failed(err) => return Failed(err),
2086 debug!("(resolving module path for import) indeterminate; \
2088 return Indeterminate;
2090 Success(NoPrefixFound) => {
2091 // There was no prefix, so we're considering the first element
2092 // of the path. How we handle this depends on whether we were
2093 // instructed to use lexical scope or not.
2094 match use_lexical_scope {
2095 DontUseLexicalScope => {
2096 // This is a crate-relative path. We will start the
2097 // resolution process at index zero.
2098 search_module = self.graph_root.get_module();
2100 last_private = LastMod(AllPublic);
2102 UseLexicalScope => {
2103 // This is not a crate-relative path. We resolve the
2104 // first component of the path in the current lexical
2105 // scope and then proceed to resolve below that.
2106 match self.resolve_module_in_lexical_scope(module_,
2108 Failed(err) => return Failed(err),
2110 debug!("(resolving module path for import) \
2111 indeterminate; bailing");
2112 return Indeterminate;
2114 Success(containing_module) => {
2115 search_module = containing_module;
2117 last_private = LastMod(AllPublic);
2123 Success(PrefixFound(ref containing_module, index)) => {
2124 search_module = containing_module.clone();
2125 start_index = index;
2126 last_private = LastMod(DependsOn(containing_module.def_id
2132 self.resolve_module_path_from_root(search_module,
2140 /// Invariant: This must only be called during main resolution, not during
2141 /// import resolution.
2142 fn resolve_item_in_lexical_scope(&mut self,
2143 module_: Rc<Module>,
2145 namespace: Namespace)
2146 -> ResolveResult<(Target, bool)> {
2147 debug!("(resolving item in lexical scope) resolving `{}` in \
2148 namespace {:?} in `{}`",
2149 token::get_name(name),
2151 self.module_to_string(&*module_));
2153 // The current module node is handled specially. First, check for
2154 // its immediate children.
2155 build_reduced_graph::populate_module_if_necessary(self, &module_);
2157 match module_.children.borrow().get(&name) {
2159 if name_bindings.defined_in_namespace(namespace) => {
2160 debug!("top name bindings succeeded");
2161 return Success((Target::new(module_.clone(),
2162 name_bindings.clone(),
2166 Some(_) | None => { /* Not found; continue. */ }
2169 // Now check for its import directives. We don't have to have resolved
2170 // all its imports in the usual way; this is because chains of
2171 // adjacent import statements are processed as though they mutated the
2173 if let Some(import_resolution) = module_.import_resolutions.borrow().get(&name) {
2174 match (*import_resolution).target_for_namespace(namespace) {
2176 // Not found; continue.
2177 debug!("(resolving item in lexical scope) found \
2178 import resolution, but not in namespace {:?}",
2182 debug!("(resolving item in lexical scope) using \
2183 import resolution");
2184 // track used imports and extern crates as well
2185 let id = import_resolution.id(namespace);
2186 self.used_imports.insert((id, namespace));
2187 self.record_import_use(id, name);
2188 if let Some(DefId{krate: kid, ..}) = target.target_module.def_id.get() {
2189 self.used_crates.insert(kid);
2191 return Success((target, false));
2196 // Search for external modules.
2197 if namespace == TypeNS {
2198 // FIXME (21114): In principle unclear `child` *has* to be lifted.
2199 let child = module_.external_module_children.borrow().get(&name).cloned();
2200 if let Some(module) = child {
2202 Rc::new(Resolver::create_name_bindings_from_module(module));
2203 debug!("lower name bindings succeeded");
2204 return Success((Target::new(module_,
2211 // Finally, proceed up the scope chain looking for parent modules.
2212 let mut search_module = module_;
2214 // Go to the next parent.
2215 match search_module.parent_link.clone() {
2217 // No more parents. This module was unresolved.
2218 debug!("(resolving item in lexical scope) unresolved \
2220 return Failed(None);
2222 ModuleParentLink(parent_module_node, _) => {
2223 match search_module.kind.get() {
2224 NormalModuleKind => {
2225 // We stop the search here.
2226 debug!("(resolving item in lexical \
2227 scope) unresolved module: not \
2228 searching through module \
2230 return Failed(None);
2236 AnonymousModuleKind => {
2237 search_module = parent_module_node.upgrade().unwrap();
2241 BlockParentLink(ref parent_module_node, _) => {
2242 search_module = parent_module_node.upgrade().unwrap();
2246 // Resolve the name in the parent module.
2247 match self.resolve_name_in_module(search_module.clone(),
2252 Failed(Some((span, msg))) =>
2253 self.resolve_error(span, &format!("failed to resolve. {}",
2255 Failed(None) => (), // Continue up the search chain.
2257 // We couldn't see through the higher scope because of an
2258 // unresolved import higher up. Bail.
2260 debug!("(resolving item in lexical scope) indeterminate \
2261 higher scope; bailing");
2262 return Indeterminate;
2264 Success((target, used_reexport)) => {
2265 // We found the module.
2266 debug!("(resolving item in lexical scope) found name \
2268 return Success((target, used_reexport));
2274 /// Resolves a module name in the current lexical scope.
2275 fn resolve_module_in_lexical_scope(&mut self,
2276 module_: Rc<Module>,
2278 -> ResolveResult<Rc<Module>> {
2279 // If this module is an anonymous module, resolve the item in the
2280 // lexical scope. Otherwise, resolve the item from the crate root.
2281 let resolve_result = self.resolve_item_in_lexical_scope(module_, name, TypeNS);
2282 match resolve_result {
2283 Success((target, _)) => {
2284 let bindings = &*target.bindings;
2285 match *bindings.type_def.borrow() {
2286 Some(ref type_def) => {
2287 match type_def.module_def {
2289 debug!("!!! (resolving module in lexical \
2290 scope) module wasn't actually a \
2292 return Failed(None);
2294 Some(ref module_def) => {
2295 return Success(module_def.clone());
2300 debug!("!!! (resolving module in lexical scope) module
2301 wasn't actually a module!");
2302 return Failed(None);
2307 debug!("(resolving module in lexical scope) indeterminate; \
2309 return Indeterminate;
2312 debug!("(resolving module in lexical scope) failed to resolve");
2318 /// Returns the nearest normal module parent of the given module.
2319 fn get_nearest_normal_module_parent(&mut self, module_: Rc<Module>)
2320 -> Option<Rc<Module>> {
2321 let mut module_ = module_;
2323 match module_.parent_link.clone() {
2324 NoParentLink => return None,
2325 ModuleParentLink(new_module, _) |
2326 BlockParentLink(new_module, _) => {
2327 let new_module = new_module.upgrade().unwrap();
2328 match new_module.kind.get() {
2329 NormalModuleKind => return Some(new_module),
2334 AnonymousModuleKind => module_ = new_module,
2341 /// Returns the nearest normal module parent of the given module, or the
2342 /// module itself if it is a normal module.
2343 fn get_nearest_normal_module_parent_or_self(&mut self, module_: Rc<Module>)
2345 match module_.kind.get() {
2346 NormalModuleKind => return module_,
2351 AnonymousModuleKind => {
2352 match self.get_nearest_normal_module_parent(module_.clone()) {
2354 Some(new_module) => new_module
2360 /// Resolves a "module prefix". A module prefix is one or both of (a) `self::`;
2361 /// (b) some chain of `super::`.
2362 /// grammar: (SELF MOD_SEP ) ? (SUPER MOD_SEP) *
2363 fn resolve_module_prefix(&mut self,
2364 module_: Rc<Module>,
2365 module_path: &[Name])
2366 -> ResolveResult<ModulePrefixResult> {
2367 // Start at the current module if we see `self` or `super`, or at the
2368 // top of the crate otherwise.
2369 let mut containing_module;
2371 let first_module_path_string = token::get_name(module_path[0]);
2372 if "self" == &first_module_path_string[] {
2374 self.get_nearest_normal_module_parent_or_self(module_);
2376 } else if "super" == &first_module_path_string[] {
2378 self.get_nearest_normal_module_parent_or_self(module_);
2379 i = 0; // We'll handle `super` below.
2381 return Success(NoPrefixFound);
2384 // Now loop through all the `super`s we find.
2385 while i < module_path.len() {
2386 let string = token::get_name(module_path[i]);
2387 if "super" != &string[] {
2390 debug!("(resolving module prefix) resolving `super` at {}",
2391 self.module_to_string(&*containing_module));
2392 match self.get_nearest_normal_module_parent(containing_module) {
2393 None => return Failed(None),
2394 Some(new_module) => {
2395 containing_module = new_module;
2401 debug!("(resolving module prefix) finished resolving prefix at {}",
2402 self.module_to_string(&*containing_module));
2404 return Success(PrefixFound(containing_module, i));
2407 /// Attempts to resolve the supplied name in the given module for the
2408 /// given namespace. If successful, returns the target corresponding to
2411 /// The boolean returned on success is an indicator of whether this lookup
2412 /// passed through a public re-export proxy.
2413 fn resolve_name_in_module(&mut self,
2414 module_: Rc<Module>,
2416 namespace: Namespace,
2417 name_search_type: NameSearchType,
2418 allow_private_imports: bool)
2419 -> ResolveResult<(Target, bool)> {
2420 debug!("(resolving name in module) resolving `{}` in `{}`",
2421 &token::get_name(name),
2422 self.module_to_string(&*module_));
2424 // First, check the direct children of the module.
2425 build_reduced_graph::populate_module_if_necessary(self, &module_);
2427 match module_.children.borrow().get(&name) {
2429 if name_bindings.defined_in_namespace(namespace) => {
2430 debug!("(resolving name in module) found node as child");
2431 return Success((Target::new(module_.clone(),
2432 name_bindings.clone(),
2441 // Next, check the module's imports if necessary.
2443 // If this is a search of all imports, we should be done with glob
2444 // resolution at this point.
2445 if name_search_type == PathSearch {
2446 assert_eq!(module_.glob_count.get(), 0);
2449 // Check the list of resolved imports.
2450 match module_.import_resolutions.borrow().get(&name) {
2451 Some(import_resolution) if allow_private_imports ||
2452 import_resolution.is_public => {
2454 if import_resolution.is_public &&
2455 import_resolution.outstanding_references != 0 {
2456 debug!("(resolving name in module) import \
2457 unresolved; bailing out");
2458 return Indeterminate;
2460 match import_resolution.target_for_namespace(namespace) {
2462 debug!("(resolving name in module) name found, \
2463 but not in namespace {:?}",
2467 debug!("(resolving name in module) resolved to \
2469 // track used imports and extern crates as well
2470 let id = import_resolution.id(namespace);
2471 self.used_imports.insert((id, namespace));
2472 self.record_import_use(id, name);
2473 if let Some(DefId{krate: kid, ..}) = target.target_module.def_id.get() {
2474 self.used_crates.insert(kid);
2476 return Success((target, true));
2480 Some(..) | None => {} // Continue.
2483 // Finally, search through external children.
2484 if namespace == TypeNS {
2485 // FIXME (21114): In principle unclear `child` *has* to be lifted.
2486 let child = module_.external_module_children.borrow().get(&name).cloned();
2487 if let Some(module) = child {
2489 Rc::new(Resolver::create_name_bindings_from_module(module));
2490 return Success((Target::new(module_,
2497 // We're out of luck.
2498 debug!("(resolving name in module) failed to resolve `{}`",
2499 &token::get_name(name));
2500 return Failed(None);
2503 fn report_unresolved_imports(&mut self, module_: Rc<Module>) {
2504 let index = module_.resolved_import_count.get();
2505 let imports = module_.imports.borrow();
2506 let import_count = imports.len();
2507 if index != import_count {
2508 let sn = self.session
2510 .span_to_snippet((*imports)[index].span)
2512 if sn.contains("::") {
2513 self.resolve_error((*imports)[index].span,
2514 "unresolved import");
2516 let err = format!("unresolved import (maybe you meant `{}::*`?)",
2518 self.resolve_error((*imports)[index].span, &err[]);
2522 // Descend into children and anonymous children.
2523 build_reduced_graph::populate_module_if_necessary(self, &module_);
2525 for (_, child_node) in &*module_.children.borrow() {
2526 match child_node.get_module_if_available() {
2530 Some(child_module) => {
2531 self.report_unresolved_imports(child_module);
2536 for (_, module_) in &*module_.anonymous_children.borrow() {
2537 self.report_unresolved_imports(module_.clone());
2543 // We maintain a list of value ribs and type ribs.
2545 // Simultaneously, we keep track of the current position in the module
2546 // graph in the `current_module` pointer. When we go to resolve a name in
2547 // the value or type namespaces, we first look through all the ribs and
2548 // then query the module graph. When we resolve a name in the module
2549 // namespace, we can skip all the ribs (since nested modules are not
2550 // allowed within blocks in Rust) and jump straight to the current module
2553 // Named implementations are handled separately. When we find a method
2554 // call, we consult the module node to find all of the implementations in
2555 // scope. This information is lazily cached in the module node. We then
2556 // generate a fake "implementation scope" containing all the
2557 // implementations thus found, for compatibility with old resolve pass.
2559 fn with_scope<F>(&mut self, name: Option<Name>, f: F) where
2560 F: FnOnce(&mut Resolver),
2562 let orig_module = self.current_module.clone();
2564 // Move down in the graph.
2570 build_reduced_graph::populate_module_if_necessary(self, &orig_module);
2572 match orig_module.children.borrow().get(&name) {
2574 debug!("!!! (with scope) didn't find `{}` in `{}`",
2575 token::get_name(name),
2576 self.module_to_string(&*orig_module));
2578 Some(name_bindings) => {
2579 match (*name_bindings).get_module_if_available() {
2581 debug!("!!! (with scope) didn't find module \
2583 token::get_name(name),
2584 self.module_to_string(&*orig_module));
2587 self.current_module = module_;
2597 self.current_module = orig_module;
2600 /// Wraps the given definition in the appropriate number of `DefUpvar`
2606 -> Option<DefLike> {
2608 DlDef(d @ DefUpvar(..)) => {
2609 self.session.span_bug(span,
2610 &format!("unexpected {:?} in bindings", d)[])
2612 DlDef(d @ DefLocal(_)) => {
2613 let node_id = d.def_id().node;
2618 // Nothing to do. Continue.
2620 ClosureRibKind(function_id) => {
2622 def = DefUpvar(node_id, function_id);
2624 let mut seen = self.freevars_seen.borrow_mut();
2625 let seen = match seen.entry(function_id) {
2626 Occupied(v) => v.into_mut(),
2627 Vacant(v) => v.insert(NodeSet()),
2629 if seen.contains(&node_id) {
2632 match self.freevars.borrow_mut().entry(function_id) {
2633 Occupied(v) => v.into_mut(),
2634 Vacant(v) => v.insert(vec![]),
2635 }.push(Freevar { def: prev_def, span: span });
2636 seen.insert(node_id);
2638 MethodRibKind(item_id, _) => {
2639 // If the def is a ty param, and came from the parent
2642 DefTyParam(_, _, did, _) if {
2643 self.def_map.borrow().get(&did.node).cloned()
2644 == Some(DefTyParamBinder(item_id))
2646 DefSelfTy(did) if did == item_id => {} // ok
2648 // This was an attempt to access an upvar inside a
2649 // named function item. This is not allowed, so we
2654 "can't capture dynamic environment in a fn item; \
2655 use the || { ... } closure form instead");
2662 // This was an attempt to access an upvar inside a
2663 // named function item. This is not allowed, so we
2668 "can't capture dynamic environment in a fn item; \
2669 use the || { ... } closure form instead");
2673 ConstantItemRibKind => {
2674 // Still doesn't deal with upvars
2675 self.resolve_error(span,
2676 "attempt to use a non-constant \
2677 value in a constant");
2684 DlDef(def @ DefTyParam(..)) |
2685 DlDef(def @ DefSelfTy(..)) => {
2688 NormalRibKind | ClosureRibKind(..) => {
2689 // Nothing to do. Continue.
2691 MethodRibKind(item_id, _) => {
2692 // If the def is a ty param, and came from the parent
2695 DefTyParam(_, _, did, _) if {
2696 self.def_map.borrow().get(&did.node).cloned()
2697 == Some(DefTyParamBinder(item_id))
2699 DefSelfTy(did) if did == item_id => {} // ok
2702 // This was an attempt to use a type parameter outside
2705 self.resolve_error(span,
2706 "can't use type parameters from \
2707 outer function; try using a local \
2708 type parameter instead");
2715 // This was an attempt to use a type parameter outside
2718 self.resolve_error(span,
2719 "can't use type parameters from \
2720 outer function; try using a local \
2721 type parameter instead");
2725 ConstantItemRibKind => {
2727 self.resolve_error(span,
2728 "cannot use an outer type \
2729 parameter in this context");
2740 /// Searches the current set of local scopes and
2741 /// applies translations for closures.
2742 fn search_ribs(&self,
2746 -> Option<DefLike> {
2747 // FIXME #4950: Try caching?
2749 for (i, rib) in ribs.iter().enumerate().rev() {
2750 match rib.bindings.get(&name).cloned() {
2752 return self.upvarify(&ribs[i + 1..], def_like, span);
2763 /// Searches the current set of local scopes for labels.
2764 /// Stops after meeting a closure.
2765 fn search_label(&self, name: Name) -> Option<DefLike> {
2766 for rib in self.label_ribs.iter().rev() {
2772 // Do not resolve labels across function boundary
2776 let result = rib.bindings.get(&name).cloned();
2777 if result.is_some() {
2784 fn resolve_crate(&mut self, krate: &ast::Crate) {
2785 debug!("(resolving crate) starting");
2787 visit::walk_crate(self, krate);
2790 fn check_if_primitive_type_name(&self, name: Name, span: Span) {
2791 if let Some(_) = self.primitive_type_table.primitive_types.get(&name) {
2792 span_err!(self.session, span, E0317,
2793 "user-defined types or type parameters cannot shadow the primitive types");
2797 fn resolve_item(&mut self, item: &Item) {
2798 let name = item.ident.name;
2800 debug!("(resolving item) resolving {}",
2801 token::get_name(name));
2805 // enum item: resolve all the variants' discrs,
2806 // then resolve the ty params
2807 ItemEnum(ref enum_def, ref generics) => {
2808 self.check_if_primitive_type_name(name, item.span);
2810 for variant in &(*enum_def).variants {
2811 if let Some(ref dis_expr) = variant.node.disr_expr {
2812 // resolve the discriminator expr
2814 self.with_constant_rib(|this| {
2815 this.resolve_expr(&**dis_expr);
2820 // n.b. the discr expr gets visited twice.
2821 // but maybe it's okay since the first time will signal an
2822 // error if there is one? -- tjc
2823 self.with_type_parameter_rib(HasTypeParameters(generics,
2828 this.resolve_type_parameters(&generics.ty_params);
2829 this.resolve_where_clause(&generics.where_clause);
2830 visit::walk_item(this, item);
2834 ItemTy(_, ref generics) => {
2835 self.check_if_primitive_type_name(name, item.span);
2837 self.with_type_parameter_rib(HasTypeParameters(generics,
2842 this.resolve_type_parameters(&generics.ty_params);
2843 visit::walk_item(this, item);
2849 ref implemented_traits,
2851 ref impl_items) => {
2852 self.resolve_implementation(item.id,
2859 ItemTrait(_, ref generics, ref bounds, ref trait_items) => {
2860 self.check_if_primitive_type_name(name, item.span);
2862 // Create a new rib for the self type.
2863 let mut self_type_rib = Rib::new(ItemRibKind);
2865 // plain insert (no renaming, types are not currently hygienic....)
2866 let name = self.type_self_name;
2867 self_type_rib.bindings.insert(name, DlDef(DefSelfTy(item.id)));
2868 self.type_ribs.push(self_type_rib);
2870 // Create a new rib for the trait-wide type parameters.
2871 self.with_type_parameter_rib(HasTypeParameters(generics,
2876 this.resolve_type_parameters(&generics.ty_params);
2877 this.resolve_where_clause(&generics.where_clause);
2879 this.resolve_type_parameter_bounds(item.id, bounds,
2882 for trait_item in &(*trait_items) {
2883 // Create a new rib for the trait_item-specific type
2886 // FIXME #4951: Do we need a node ID here?
2889 ast::RequiredMethod(ref ty_m) => {
2890 this.with_type_parameter_rib
2891 (HasTypeParameters(&ty_m.generics,
2894 MethodRibKind(item.id, RequiredMethod)),
2897 // Resolve the method-specific type
2899 this.resolve_type_parameters(
2900 &ty_m.generics.ty_params);
2901 this.resolve_where_clause(&ty_m.generics
2904 for argument in &ty_m.decl.inputs {
2905 this.resolve_type(&*argument.ty);
2908 if let SelfExplicit(ref typ, _) = ty_m.explicit_self.node {
2909 this.resolve_type(&**typ)
2912 if let ast::Return(ref ret_ty) = ty_m.decl.output {
2913 this.resolve_type(&**ret_ty);
2917 ast::ProvidedMethod(ref m) => {
2918 this.resolve_method(MethodRibKind(item.id,
2919 ProvidedMethod(m.id)),
2922 ast::TypeTraitItem(ref data) => {
2923 this.resolve_type_parameter(&data.ty_param);
2924 visit::walk_trait_item(this, trait_item);
2930 self.type_ribs.pop();
2933 ItemStruct(ref struct_def, ref generics) => {
2934 self.check_if_primitive_type_name(name, item.span);
2936 self.resolve_struct(item.id,
2938 &struct_def.fields[]);
2941 ItemMod(ref module_) => {
2942 self.with_scope(Some(name), |this| {
2943 this.resolve_module(module_, item.span, name,
2948 ItemForeignMod(ref foreign_module) => {
2949 self.with_scope(Some(name), |this| {
2950 for foreign_item in &foreign_module.items {
2951 match foreign_item.node {
2952 ForeignItemFn(_, ref generics) => {
2953 this.with_type_parameter_rib(
2955 generics, FnSpace, foreign_item.id,
2958 this.resolve_type_parameters(&generics.ty_params);
2959 this.resolve_where_clause(&generics.where_clause);
2960 visit::walk_foreign_item(this, &**foreign_item)
2963 ForeignItemStatic(..) => {
2964 visit::walk_foreign_item(this,
2972 ItemFn(ref fn_decl, _, _, ref generics, ref block) => {
2973 self.resolve_function(ItemRibKind,
2983 ItemConst(..) | ItemStatic(..) => {
2984 self.with_constant_rib(|this| {
2985 visit::walk_item(this, item);
2989 ItemUse(ref view_path) => {
2990 // check for imports shadowing primitive types
2991 if let ast::ViewPathSimple(ident, _) = view_path.node {
2992 match self.def_map.borrow().get(&item.id) {
2993 Some(&DefTy(..)) | Some(&DefStruct(..)) | Some(&DefTrait(..)) | None => {
2994 self.check_if_primitive_type_name(ident.name, item.span);
3001 ItemExternCrate(_) | ItemMac(..) => {
3002 // do nothing, these are just around to be encoded
3007 fn with_type_parameter_rib<F>(&mut self, type_parameters: TypeParameters, f: F) where
3008 F: FnOnce(&mut Resolver),
3010 match type_parameters {
3011 HasTypeParameters(generics, space, node_id, rib_kind) => {
3012 let mut function_type_rib = Rib::new(rib_kind);
3013 let mut seen_bindings = HashSet::new();
3014 for (index, type_parameter) in generics.ty_params.iter().enumerate() {
3015 let name = type_parameter.ident.name;
3016 debug!("with_type_parameter_rib: {} {}", node_id,
3019 if seen_bindings.contains(&name) {
3020 self.resolve_error(type_parameter.span,
3021 &format!("the name `{}` is already \
3023 parameter in this type \
3028 seen_bindings.insert(name);
3030 let def_like = DlDef(DefTyParam(space,
3032 local_def(type_parameter.id),
3034 // Associate this type parameter with
3035 // the item that bound it
3036 self.record_def(type_parameter.id,
3037 (DefTyParamBinder(node_id), LastMod(AllPublic)));
3038 // plain insert (no renaming)
3039 function_type_rib.bindings.insert(name, def_like);
3041 self.type_ribs.push(function_type_rib);
3044 NoTypeParameters => {
3051 match type_parameters {
3052 HasTypeParameters(..) => { self.type_ribs.pop(); }
3053 NoTypeParameters => { }
3057 fn with_label_rib<F>(&mut self, f: F) where
3058 F: FnOnce(&mut Resolver),
3060 self.label_ribs.push(Rib::new(NormalRibKind));
3062 self.label_ribs.pop();
3065 fn with_constant_rib<F>(&mut self, f: F) where
3066 F: FnOnce(&mut Resolver),
3068 self.value_ribs.push(Rib::new(ConstantItemRibKind));
3069 self.type_ribs.push(Rib::new(ConstantItemRibKind));
3071 self.type_ribs.pop();
3072 self.value_ribs.pop();
3075 fn resolve_function(&mut self,
3077 optional_declaration: Option<&FnDecl>,
3078 type_parameters: TypeParameters,
3080 // Create a value rib for the function.
3081 let function_value_rib = Rib::new(rib_kind);
3082 self.value_ribs.push(function_value_rib);
3084 // Create a label rib for the function.
3085 let function_label_rib = Rib::new(rib_kind);
3086 self.label_ribs.push(function_label_rib);
3088 // If this function has type parameters, add them now.
3089 self.with_type_parameter_rib(type_parameters, |this| {
3090 // Resolve the type parameters.
3091 match type_parameters {
3092 NoTypeParameters => {
3095 HasTypeParameters(ref generics, _, _, _) => {
3096 this.resolve_type_parameters(&generics.ty_params);
3097 this.resolve_where_clause(&generics.where_clause);
3101 // Add each argument to the rib.
3102 match optional_declaration {
3106 Some(declaration) => {
3107 let mut bindings_list = HashMap::new();
3108 for argument in &declaration.inputs {
3109 this.resolve_pattern(&*argument.pat,
3110 ArgumentIrrefutableMode,
3111 &mut bindings_list);
3113 this.resolve_type(&*argument.ty);
3115 debug!("(resolving function) recorded argument");
3118 if let ast::Return(ref ret_ty) = declaration.output {
3119 this.resolve_type(&**ret_ty);
3124 // Resolve the function body.
3125 this.resolve_block(&*block);
3127 debug!("(resolving function) leaving function");
3130 self.label_ribs.pop();
3131 self.value_ribs.pop();
3134 fn resolve_type_parameters(&mut self,
3135 type_parameters: &OwnedSlice<TyParam>) {
3136 for type_parameter in &**type_parameters {
3137 self.resolve_type_parameter(type_parameter);
3141 fn resolve_type_parameter(&mut self,
3142 type_parameter: &TyParam) {
3143 self.check_if_primitive_type_name(type_parameter.ident.name, type_parameter.span);
3144 for bound in &*type_parameter.bounds {
3145 self.resolve_type_parameter_bound(type_parameter.id, bound,
3146 TraitBoundingTypeParameter);
3148 match type_parameter.default {
3149 Some(ref ty) => self.resolve_type(&**ty),
3154 fn resolve_type_parameter_bounds(&mut self,
3156 type_parameter_bounds: &OwnedSlice<TyParamBound>,
3157 reference_type: TraitReferenceType) {
3158 for type_parameter_bound in &**type_parameter_bounds {
3159 self.resolve_type_parameter_bound(id, type_parameter_bound,
3164 fn resolve_type_parameter_bound(&mut self,
3166 type_parameter_bound: &TyParamBound,
3167 reference_type: TraitReferenceType) {
3168 match *type_parameter_bound {
3169 TraitTyParamBound(ref tref, _) => {
3170 self.resolve_poly_trait_reference(id, tref, reference_type)
3172 RegionTyParamBound(..) => {}
3176 fn resolve_poly_trait_reference(&mut self,
3178 poly_trait_reference: &PolyTraitRef,
3179 reference_type: TraitReferenceType) {
3180 self.resolve_trait_reference(id, &poly_trait_reference.trait_ref, reference_type)
3183 fn resolve_trait_reference(&mut self,
3185 trait_reference: &TraitRef,
3186 reference_type: TraitReferenceType) {
3187 match self.resolve_path(id, &trait_reference.path, TypeNS, true) {
3189 let path_str = self.path_names_to_string(&trait_reference.path);
3190 let usage_str = match reference_type {
3191 TraitBoundingTypeParameter => "bound type parameter with",
3192 TraitImplementation => "implement",
3193 TraitDerivation => "derive",
3194 TraitObject => "reference",
3195 TraitQPath => "extract an associated item from",
3198 let msg = format!("attempt to {} a nonexistent trait `{}`", usage_str, path_str);
3199 self.resolve_error(trait_reference.path.span, &msg[]);
3203 (DefTrait(_), _) => {
3204 debug!("(resolving trait) found trait def: {:?}", def);
3205 self.record_def(trait_reference.ref_id, def);
3208 self.resolve_error(trait_reference.path.span,
3209 &format!("`{}` is not a trait",
3210 self.path_names_to_string(
3211 &trait_reference.path))[]);
3213 // If it's a typedef, give a note
3214 if let DefTy(..) = def {
3215 self.session.span_note(
3216 trait_reference.path.span,
3217 &format!("`type` aliases cannot be used for traits")
3226 fn resolve_where_clause(&mut self, where_clause: &ast::WhereClause) {
3227 for predicate in &where_clause.predicates {
3229 &ast::WherePredicate::BoundPredicate(ref bound_pred) => {
3230 self.resolve_type(&*bound_pred.bounded_ty);
3232 for bound in &*bound_pred.bounds {
3233 self.resolve_type_parameter_bound(bound_pred.bounded_ty.id, bound,
3234 TraitBoundingTypeParameter);
3237 &ast::WherePredicate::RegionPredicate(_) => {}
3238 &ast::WherePredicate::EqPredicate(ref eq_pred) => {
3239 match self.resolve_path(eq_pred.id, &eq_pred.path, TypeNS, true) {
3240 Some((def @ DefTyParam(..), last_private)) => {
3241 self.record_def(eq_pred.id, (def, last_private));
3244 self.resolve_error(eq_pred.path.span,
3245 "undeclared associated type");
3249 self.resolve_type(&*eq_pred.ty);
3255 fn resolve_struct(&mut self,
3257 generics: &Generics,
3258 fields: &[StructField]) {
3259 // If applicable, create a rib for the type parameters.
3260 self.with_type_parameter_rib(HasTypeParameters(generics,
3265 // Resolve the type parameters.
3266 this.resolve_type_parameters(&generics.ty_params);
3267 this.resolve_where_clause(&generics.where_clause);
3270 for field in fields {
3271 this.resolve_type(&*field.node.ty);
3276 // Does this really need to take a RibKind or is it always going
3277 // to be NormalRibKind?
3278 fn resolve_method(&mut self,
3280 method: &ast::Method) {
3281 let method_generics = method.pe_generics();
3282 let type_parameters = HasTypeParameters(method_generics,
3287 if let SelfExplicit(ref typ, _) = method.pe_explicit_self().node {
3288 self.resolve_type(&**typ);
3291 self.resolve_function(rib_kind,
3292 Some(method.pe_fn_decl()),
3297 fn with_current_self_type<T, F>(&mut self, self_type: &Ty, f: F) -> T where
3298 F: FnOnce(&mut Resolver) -> T,
3300 // Handle nested impls (inside fn bodies)
3301 let previous_value = replace(&mut self.current_self_type, Some(self_type.clone()));
3302 let result = f(self);
3303 self.current_self_type = previous_value;
3307 fn with_optional_trait_ref<T, F>(&mut self, id: NodeId,
3308 opt_trait_ref: &Option<TraitRef>,
3310 F: FnOnce(&mut Resolver) -> T,
3312 let new_val = match *opt_trait_ref {
3313 Some(ref trait_ref) => {
3314 self.resolve_trait_reference(id, trait_ref, TraitImplementation);
3316 match self.def_map.borrow().get(&trait_ref.ref_id) {
3318 let did = def.def_id();
3319 Some((did, trait_ref.clone()))
3326 let original_trait_ref = replace(&mut self.current_trait_ref, new_val);
3327 let result = f(self);
3328 self.current_trait_ref = original_trait_ref;
3332 fn resolve_implementation(&mut self,
3334 generics: &Generics,
3335 opt_trait_reference: &Option<TraitRef>,
3337 impl_items: &[ImplItem]) {
3338 // If applicable, create a rib for the type parameters.
3339 self.with_type_parameter_rib(HasTypeParameters(generics,
3344 // Resolve the type parameters.
3345 this.resolve_type_parameters(&generics.ty_params);
3346 this.resolve_where_clause(&generics.where_clause);
3348 // Resolve the trait reference, if necessary.
3349 this.with_optional_trait_ref(id, opt_trait_reference, |this| {
3350 // Resolve the self type.
3351 this.resolve_type(self_type);
3353 this.with_current_self_type(self_type, |this| {
3354 for impl_item in impl_items {
3356 MethodImplItem(ref method) => {
3357 // If this is a trait impl, ensure the method
3359 this.check_trait_item(method.pe_ident().name,
3362 // We also need a new scope for the method-
3363 // specific type parameters.
3364 this.resolve_method(
3365 MethodRibKind(id, ProvidedMethod(method.id)),
3368 TypeImplItem(ref typedef) => {
3369 // If this is a trait impl, ensure the method
3371 this.check_trait_item(typedef.ident.name,
3374 this.resolve_type(&*typedef.typ);
3382 // Check that the current type is indeed a type, if we have an anonymous impl
3383 if opt_trait_reference.is_none() {
3384 match self_type.node {
3385 // TyPath is the only thing that we handled in `build_reduced_graph_for_item`,
3386 // where we created a module with the name of the type in order to implement
3387 // an anonymous trait. In the case that the path does not resolve to an actual
3388 // type, the result will be that the type name resolves to a module but not
3389 // a type (shadowing any imported modules or types with this name), leading
3390 // to weird user-visible bugs. So we ward this off here. See #15060.
3391 TyPath(ref path, path_id) => {
3392 match self.def_map.borrow().get(&path_id) {
3393 // FIXME: should we catch other options and give more precise errors?
3394 Some(&DefMod(_)) => {
3395 self.resolve_error(path.span, "inherent implementations are not \
3396 allowed for types not defined in \
3397 the current module");
3407 fn check_trait_item(&self, name: Name, span: Span) {
3408 // If there is a TraitRef in scope for an impl, then the method must be in the trait.
3409 if let Some((did, ref trait_ref)) = self.current_trait_ref {
3410 if self.trait_item_map.get(&(name, did)).is_none() {
3411 let path_str = self.path_names_to_string(&trait_ref.path);
3412 self.resolve_error(span,
3413 &format!("method `{}` is not a member of trait `{}`",
3414 token::get_name(name),
3420 fn resolve_module(&mut self, module: &Mod, _span: Span,
3421 _name: Name, id: NodeId) {
3422 // Write the implementations in scope into the module metadata.
3423 debug!("(resolving module) resolving module ID {}", id);
3424 visit::walk_mod(self, module);
3427 fn resolve_local(&mut self, local: &Local) {
3428 // Resolve the type.
3429 if let Some(ref ty) = local.ty {
3430 self.resolve_type(&**ty);
3433 // Resolve the initializer, if necessary.
3438 Some(ref initializer) => {
3439 self.resolve_expr(&**initializer);
3443 // Resolve the pattern.
3444 let mut bindings_list = HashMap::new();
3445 self.resolve_pattern(&*local.pat,
3446 LocalIrrefutableMode,
3447 &mut bindings_list);
3450 // build a map from pattern identifiers to binding-info's.
3451 // this is done hygienically. This could arise for a macro
3452 // that expands into an or-pattern where one 'x' was from the
3453 // user and one 'x' came from the macro.
3454 fn binding_mode_map(&mut self, pat: &Pat) -> BindingMap {
3455 let mut result = HashMap::new();
3456 pat_bindings(&self.def_map, pat, |binding_mode, _id, sp, path1| {
3457 let name = mtwt::resolve(path1.node);
3458 result.insert(name, BindingInfo {
3460 binding_mode: binding_mode
3466 // check that all of the arms in an or-pattern have exactly the
3467 // same set of bindings, with the same binding modes for each.
3468 fn check_consistent_bindings(&mut self, arm: &Arm) {
3469 if arm.pats.len() == 0 {
3472 let map_0 = self.binding_mode_map(&*arm.pats[0]);
3473 for (i, p) in arm.pats.iter().enumerate() {
3474 let map_i = self.binding_mode_map(&**p);
3476 for (&key, &binding_0) in &map_0 {
3477 match map_i.get(&key) {
3481 &format!("variable `{}` from pattern #1 is \
3482 not bound in pattern #{}",
3483 token::get_name(key),
3486 Some(binding_i) => {
3487 if binding_0.binding_mode != binding_i.binding_mode {
3490 &format!("variable `{}` is bound with different \
3491 mode in pattern #{} than in pattern #1",
3492 token::get_name(key),
3499 for (&key, &binding) in &map_i {
3500 if !map_0.contains_key(&key) {
3503 &format!("variable `{}` from pattern {}{} is \
3504 not bound in pattern {}1",
3505 token::get_name(key),
3506 "#", i + 1, "#")[]);
3512 fn resolve_arm(&mut self, arm: &Arm) {
3513 self.value_ribs.push(Rib::new(NormalRibKind));
3515 let mut bindings_list = HashMap::new();
3516 for pattern in &arm.pats {
3517 self.resolve_pattern(&**pattern, RefutableMode, &mut bindings_list);
3520 // This has to happen *after* we determine which
3521 // pat_idents are variants
3522 self.check_consistent_bindings(arm);
3524 visit::walk_expr_opt(self, &arm.guard);
3525 self.resolve_expr(&*arm.body);
3527 self.value_ribs.pop();
3530 fn resolve_block(&mut self, block: &Block) {
3531 debug!("(resolving block) entering block");
3532 self.value_ribs.push(Rib::new(NormalRibKind));
3534 // Move down in the graph, if there's an anonymous module rooted here.
3535 let orig_module = self.current_module.clone();
3536 match orig_module.anonymous_children.borrow().get(&block.id) {
3537 None => { /* Nothing to do. */ }
3538 Some(anonymous_module) => {
3539 debug!("(resolving block) found anonymous module, moving \
3541 self.current_module = anonymous_module.clone();
3545 // Check for imports appearing after non-item statements.
3546 let mut found_non_item = false;
3547 for statement in &block.stmts {
3548 if let ast::StmtDecl(ref declaration, _) = statement.node {
3549 if let ast::DeclItem(ref i) = declaration.node {
3551 ItemExternCrate(_) | ItemUse(_) if found_non_item => {
3552 span_err!(self.session, i.span, E0154,
3553 "imports are not allowed after non-item statements");
3558 found_non_item = true
3561 found_non_item = true;
3565 // Descend into the block.
3566 visit::walk_block(self, block);
3569 self.current_module = orig_module;
3571 self.value_ribs.pop();
3572 debug!("(resolving block) leaving block");
3575 fn resolve_type(&mut self, ty: &Ty) {
3577 // Like path expressions, the interpretation of path types depends
3578 // on whether the path has multiple elements in it or not.
3580 TyPath(ref path, path_id) => {
3581 // This is a path in the type namespace. Walk through scopes
3583 let mut result_def = None;
3585 // First, check to see whether the name is a primitive type.
3586 if path.segments.len() == 1 {
3587 let id = path.segments.last().unwrap().identifier;
3589 match self.primitive_type_table
3593 Some(&primitive_type) => {
3595 Some((DefPrimTy(primitive_type), LastMod(AllPublic)));
3597 if path.segments[0].parameters.has_lifetimes() {
3598 span_err!(self.session, path.span, E0157,
3599 "lifetime parameters are not allowed on this type");
3600 } else if !path.segments[0].parameters.is_empty() {
3601 span_err!(self.session, path.span, E0153,
3602 "type parameters are not allowed on this type");
3611 if let None = result_def {
3612 result_def = self.resolve_path(ty.id, path, TypeNS, true);
3617 // Write the result into the def map.
3618 debug!("(resolving type) writing resolution for `{}` \
3620 self.path_names_to_string(path),
3622 self.record_def(path_id, def);
3625 let msg = format!("use of undeclared type name `{}`",
3626 self.path_names_to_string(path));
3627 self.resolve_error(ty.span, &msg[]);
3632 TyObjectSum(ref ty, ref bound_vec) => {
3633 self.resolve_type(&**ty);
3634 self.resolve_type_parameter_bounds(ty.id, bound_vec,
3635 TraitBoundingTypeParameter);
3638 TyQPath(ref qpath) => {
3639 self.resolve_type(&*qpath.self_type);
3640 self.resolve_trait_reference(ty.id, &*qpath.trait_ref, TraitQPath);
3641 for ty in qpath.item_path.parameters.types() {
3642 self.resolve_type(&**ty);
3644 for binding in qpath.item_path.parameters.bindings() {
3645 self.resolve_type(&*binding.ty);
3649 TyPolyTraitRef(ref bounds) => {
3650 self.resolve_type_parameter_bounds(
3654 visit::walk_ty(self, ty);
3657 // Just resolve embedded types.
3658 visit::walk_ty(self, ty);
3663 fn resolve_pattern(&mut self,
3665 mode: PatternBindingMode,
3666 // Maps idents to the node ID for the (outermost)
3667 // pattern that binds them
3668 bindings_list: &mut HashMap<Name, NodeId>) {
3669 let pat_id = pattern.id;
3670 walk_pat(pattern, |pattern| {
3671 match pattern.node {
3672 PatIdent(binding_mode, ref path1, _) => {
3674 // The meaning of pat_ident with no type parameters
3675 // depends on whether an enum variant or unit-like struct
3676 // with that name is in scope. The probing lookup has to
3677 // be careful not to emit spurious errors. Only matching
3678 // patterns (match) can match nullary variants or
3679 // unit-like structs. For binding patterns (let), matching
3680 // such a value is simply disallowed (since it's rarely
3683 let ident = path1.node;
3684 let renamed = mtwt::resolve(ident);
3686 match self.resolve_bare_identifier_pattern(ident.name, pattern.span) {
3687 FoundStructOrEnumVariant(ref def, lp)
3688 if mode == RefutableMode => {
3689 debug!("(resolving pattern) resolving `{}` to \
3690 struct or enum variant",
3691 token::get_name(renamed));
3693 self.enforce_default_binding_mode(
3697 self.record_def(pattern.id, (def.clone(), lp));
3699 FoundStructOrEnumVariant(..) => {
3702 &format!("declaration of `{}` shadows an enum \
3703 variant or unit-like struct in \
3705 token::get_name(renamed))[]);
3707 FoundConst(ref def, lp) if mode == RefutableMode => {
3708 debug!("(resolving pattern) resolving `{}` to \
3710 token::get_name(renamed));
3712 self.enforce_default_binding_mode(
3716 self.record_def(pattern.id, (def.clone(), lp));
3719 self.resolve_error(pattern.span,
3720 "only irrefutable patterns \
3723 BareIdentifierPatternUnresolved => {
3724 debug!("(resolving pattern) binding `{}`",
3725 token::get_name(renamed));
3727 let def = DefLocal(pattern.id);
3729 // Record the definition so that later passes
3730 // will be able to distinguish variants from
3731 // locals in patterns.
3733 self.record_def(pattern.id, (def, LastMod(AllPublic)));
3735 // Add the binding to the local ribs, if it
3736 // doesn't already exist in the bindings list. (We
3737 // must not add it if it's in the bindings list
3738 // because that breaks the assumptions later
3739 // passes make about or-patterns.)
3740 if !bindings_list.contains_key(&renamed) {
3741 let this = &mut *self;
3742 let last_rib = this.value_ribs.last_mut().unwrap();
3743 last_rib.bindings.insert(renamed, DlDef(def));
3744 bindings_list.insert(renamed, pat_id);
3745 } else if mode == ArgumentIrrefutableMode &&
3746 bindings_list.contains_key(&renamed) {
3747 // Forbid duplicate bindings in the same
3749 self.resolve_error(pattern.span,
3750 &format!("identifier `{}` \
3758 } else if bindings_list.get(&renamed) ==
3760 // Then this is a duplicate variable in the
3761 // same disjunction, which is an error.
3762 self.resolve_error(pattern.span,
3763 &format!("identifier `{}` is bound \
3764 more than once in the same \
3766 token::get_ident(ident))[]);
3768 // Else, not bound in the same pattern: do
3774 PatEnum(ref path, _) => {
3775 // This must be an enum variant, struct or const.
3776 match self.resolve_path(pat_id, path, ValueNS, false) {
3777 Some(def @ (DefVariant(..), _)) |
3778 Some(def @ (DefStruct(..), _)) |
3779 Some(def @ (DefConst(..), _)) => {
3780 self.record_def(pattern.id, def);
3782 Some((DefStatic(..), _)) => {
3783 self.resolve_error(path.span,
3784 "static variables cannot be \
3785 referenced in a pattern, \
3786 use a `const` instead");
3789 self.resolve_error(path.span,
3790 &format!("`{}` is not an enum variant, struct or const",
3792 path.segments.last().unwrap().identifier)));
3795 self.resolve_error(path.span,
3796 &format!("unresolved enum variant, struct or const `{}`",
3797 token::get_ident(path.segments.last().unwrap().identifier)));
3801 // Check the types in the path pattern.
3802 for ty in path.segments
3804 .flat_map(|s| s.parameters.types().into_iter()) {
3805 self.resolve_type(&**ty);
3809 PatLit(ref expr) => {
3810 self.resolve_expr(&**expr);
3813 PatRange(ref first_expr, ref last_expr) => {
3814 self.resolve_expr(&**first_expr);
3815 self.resolve_expr(&**last_expr);
3818 PatStruct(ref path, _, _) => {
3819 match self.resolve_path(pat_id, path, TypeNS, false) {
3820 Some(definition) => {
3821 self.record_def(pattern.id, definition);
3824 debug!("(resolving pattern) didn't find struct \
3825 def: {:?}", result);
3826 let msg = format!("`{}` does not name a structure",
3827 self.path_names_to_string(path));
3828 self.resolve_error(path.span, &msg[]);
3841 fn resolve_bare_identifier_pattern(&mut self, name: Name, span: Span)
3842 -> BareIdentifierPatternResolution {
3843 let module = self.current_module.clone();
3844 match self.resolve_item_in_lexical_scope(module,
3847 Success((target, _)) => {
3848 debug!("(resolve bare identifier pattern) succeeded in \
3849 finding {} at {:?}",
3850 token::get_name(name),
3851 target.bindings.value_def.borrow());
3852 match *target.bindings.value_def.borrow() {
3854 panic!("resolved name in the value namespace to a \
3855 set of name bindings with no def?!");
3858 // For the two success cases, this lookup can be
3859 // considered as not having a private component because
3860 // the lookup happened only within the current module.
3862 def @ DefVariant(..) | def @ DefStruct(..) => {
3863 return FoundStructOrEnumVariant(def, LastMod(AllPublic));
3865 def @ DefConst(..) => {
3866 return FoundConst(def, LastMod(AllPublic));
3869 self.resolve_error(span,
3870 "static variables cannot be \
3871 referenced in a pattern, \
3872 use a `const` instead");
3873 return BareIdentifierPatternUnresolved;
3876 return BareIdentifierPatternUnresolved;
3884 panic!("unexpected indeterminate result");
3888 Some((span, msg)) => {
3889 self.resolve_error(span, &format!("failed to resolve: {}",
3895 debug!("(resolve bare identifier pattern) failed to find {}",
3896 token::get_name(name));
3897 return BareIdentifierPatternUnresolved;
3902 /// If `check_ribs` is true, checks the local definitions first; i.e.
3903 /// doesn't skip straight to the containing module.
3904 fn resolve_path(&mut self,
3907 namespace: Namespace,
3908 check_ribs: bool) -> Option<(Def, LastPrivate)> {
3909 // First, resolve the types and associated type bindings.
3910 for ty in path.segments.iter().flat_map(|s| s.parameters.types().into_iter()) {
3911 self.resolve_type(&**ty);
3913 for binding in path.segments.iter().flat_map(|s| s.parameters.bindings().into_iter()) {
3914 self.resolve_type(&*binding.ty);
3917 // A special case for sugared associated type paths `T::A` where `T` is
3918 // a type parameter and `A` is an associated type on some bound of `T`.
3919 if namespace == TypeNS && path.segments.len() == 2 {
3920 match self.resolve_identifier(path.segments[0].identifier,
3924 Some((def, last_private)) => {
3926 DefTyParam(_, _, did, _) => {
3927 let def = DefAssociatedPath(TyParamProvenance::FromParam(did),
3928 path.segments.last()
3929 .unwrap().identifier);
3930 return Some((def, last_private));
3933 let def = DefAssociatedPath(TyParamProvenance::FromSelf(local_def(nid)),
3934 path.segments.last()
3935 .unwrap().identifier);
3936 return Some((def, last_private));
3946 return self.resolve_crate_relative_path(path, namespace);
3949 // Try to find a path to an item in a module.
3950 let unqualified_def =
3951 self.resolve_identifier(path.segments.last().unwrap().identifier,
3956 if path.segments.len() > 1 {
3957 let def = self.resolve_module_relative_path(path, namespace);
3958 match (def, unqualified_def) {
3959 (Some((ref d, _)), Some((ref ud, _))) if *d == *ud => {
3961 .add_lint(lint::builtin::UNUSED_QUALIFICATIONS,
3964 "unnecessary qualification".to_string());
3972 return unqualified_def;
3975 // resolve a single identifier (used as a varref)
3976 fn resolve_identifier(&mut self,
3978 namespace: Namespace,
3981 -> Option<(Def, LastPrivate)> {
3983 match self.resolve_identifier_in_local_ribs(identifier,
3987 return Some((def, LastMod(AllPublic)));
3995 return self.resolve_item_by_name_in_lexical_scope(identifier.name, namespace);
3998 // FIXME #4952: Merge me with resolve_name_in_module?
3999 fn resolve_definition_of_name_in_module(&mut self,
4000 containing_module: Rc<Module>,
4002 namespace: Namespace)
4004 // First, search children.
4005 build_reduced_graph::populate_module_if_necessary(self, &containing_module);
4007 match containing_module.children.borrow().get(&name) {
4008 Some(child_name_bindings) => {
4009 match child_name_bindings.def_for_namespace(namespace) {
4011 // Found it. Stop the search here.
4012 let p = child_name_bindings.defined_in_public_namespace(
4014 let lp = if p {LastMod(AllPublic)} else {
4015 LastMod(DependsOn(def.def_id()))
4017 return ChildNameDefinition(def, lp);
4025 // Next, search import resolutions.
4026 match containing_module.import_resolutions.borrow().get(&name) {
4027 Some(import_resolution) if import_resolution.is_public => {
4028 if let Some(target) = (*import_resolution).target_for_namespace(namespace) {
4029 match target.bindings.def_for_namespace(namespace) {
4032 let id = import_resolution.id(namespace);
4033 // track imports and extern crates as well
4034 self.used_imports.insert((id, namespace));
4035 self.record_import_use(id, name);
4036 match target.target_module.def_id.get() {
4037 Some(DefId{krate: kid, ..}) => {
4038 self.used_crates.insert(kid);
4042 return ImportNameDefinition(def, LastMod(AllPublic));
4045 // This can happen with external impls, due to
4046 // the imperfect way we read the metadata.
4051 Some(..) | None => {} // Continue.
4054 // Finally, search through external children.
4055 if namespace == TypeNS {
4056 if let Some(module) = containing_module.external_module_children.borrow()
4057 .get(&name).cloned() {
4058 if let Some(def_id) = module.def_id.get() {
4059 // track used crates
4060 self.used_crates.insert(def_id.krate);
4061 let lp = if module.is_public {LastMod(AllPublic)} else {
4062 LastMod(DependsOn(def_id))
4064 return ChildNameDefinition(DefMod(def_id), lp);
4069 return NoNameDefinition;
4072 // resolve a "module-relative" path, e.g. a::b::c
4073 fn resolve_module_relative_path(&mut self,
4075 namespace: Namespace)
4076 -> Option<(Def, LastPrivate)> {
4077 let module_path = path.segments.init().iter()
4078 .map(|ps| ps.identifier.name)
4079 .collect::<Vec<_>>();
4081 let containing_module;
4083 let module = self.current_module.clone();
4084 match self.resolve_module_path(module,
4090 let (span, msg) = match err {
4091 Some((span, msg)) => (span, msg),
4093 let msg = format!("Use of undeclared type or module `{}`",
4094 self.names_to_string(&module_path));
4099 self.resolve_error(span, &format!("failed to resolve. {}",
4103 Indeterminate => panic!("indeterminate unexpected"),
4104 Success((resulting_module, resulting_last_private)) => {
4105 containing_module = resulting_module;
4106 last_private = resulting_last_private;
4110 let name = path.segments.last().unwrap().identifier.name;
4111 let def = match self.resolve_definition_of_name_in_module(containing_module.clone(),
4114 NoNameDefinition => {
4115 // We failed to resolve the name. Report an error.
4118 ChildNameDefinition(def, lp) | ImportNameDefinition(def, lp) => {
4119 (def, last_private.or(lp))
4122 if let Some(DefId{krate: kid, ..}) = containing_module.def_id.get() {
4123 self.used_crates.insert(kid);
4128 /// Invariant: This must be called only during main resolution, not during
4129 /// import resolution.
4130 fn resolve_crate_relative_path(&mut self,
4132 namespace: Namespace)
4133 -> Option<(Def, LastPrivate)> {
4134 let module_path = path.segments.init().iter()
4135 .map(|ps| ps.identifier.name)
4136 .collect::<Vec<_>>();
4138 let root_module = self.graph_root.get_module();
4140 let containing_module;
4142 match self.resolve_module_path_from_root(root_module,
4147 LastMod(AllPublic)) {
4149 let (span, msg) = match err {
4150 Some((span, msg)) => (span, msg),
4152 let msg = format!("Use of undeclared module `::{}`",
4153 self.names_to_string(&module_path[]));
4158 self.resolve_error(span, &format!("failed to resolve. {}",
4164 panic!("indeterminate unexpected");
4167 Success((resulting_module, resulting_last_private)) => {
4168 containing_module = resulting_module;
4169 last_private = resulting_last_private;
4173 let name = path.segments.last().unwrap().identifier.name;
4174 match self.resolve_definition_of_name_in_module(containing_module,
4177 NoNameDefinition => {
4178 // We failed to resolve the name. Report an error.
4181 ChildNameDefinition(def, lp) | ImportNameDefinition(def, lp) => {
4182 return Some((def, last_private.or(lp)));
4187 fn resolve_identifier_in_local_ribs(&mut self,
4189 namespace: Namespace,
4192 // Check the local set of ribs.
4193 let search_result = match namespace {
4195 let renamed = mtwt::resolve(ident);
4196 self.search_ribs(&self.value_ribs, renamed, span)
4199 let name = ident.name;
4200 self.search_ribs(&self.type_ribs[], name, span)
4204 match search_result {
4205 Some(DlDef(def)) => {
4206 debug!("(resolving path in local ribs) resolved `{}` to \
4208 token::get_ident(ident),
4212 Some(DlField) | Some(DlImpl(_)) | None => {
4218 fn resolve_item_by_name_in_lexical_scope(&mut self,
4220 namespace: Namespace)
4221 -> Option<(Def, LastPrivate)> {
4223 let module = self.current_module.clone();
4224 match self.resolve_item_in_lexical_scope(module,
4227 Success((target, _)) => {
4228 match (*target.bindings).def_for_namespace(namespace) {
4230 // This can happen if we were looking for a type and
4231 // found a module instead. Modules don't have defs.
4232 debug!("(resolving item path by identifier in lexical \
4233 scope) failed to resolve {} after success...",
4234 token::get_name(name));
4238 debug!("(resolving item path in lexical scope) \
4239 resolved `{}` to item",
4240 token::get_name(name));
4241 // This lookup is "all public" because it only searched
4242 // for one identifier in the current module (couldn't
4243 // have passed through reexports or anything like that.
4244 return Some((def, LastMod(AllPublic)));
4249 panic!("unexpected indeterminate result");
4253 Some((span, msg)) =>
4254 self.resolve_error(span, &format!("failed to resolve. {}",
4259 debug!("(resolving item path by identifier in lexical scope) \
4260 failed to resolve {}", token::get_name(name));
4266 fn with_no_errors<T, F>(&mut self, f: F) -> T where
4267 F: FnOnce(&mut Resolver) -> T,
4269 self.emit_errors = false;
4271 self.emit_errors = true;
4275 fn resolve_error(&self, span: Span, s: &str) {
4276 if self.emit_errors {
4277 self.session.span_err(span, s);
4281 fn find_fallback_in_self_type(&mut self, name: Name) -> FallbackSuggestion {
4282 fn extract_path_and_node_id(t: &Ty, allow: FallbackChecks)
4283 -> Option<(Path, NodeId, FallbackChecks)> {
4285 TyPath(ref path, node_id) => Some((path.clone(), node_id, allow)),
4286 TyPtr(ref mut_ty) => extract_path_and_node_id(&*mut_ty.ty, OnlyTraitAndStatics),
4287 TyRptr(_, ref mut_ty) => extract_path_and_node_id(&*mut_ty.ty, allow),
4288 // This doesn't handle the remaining `Ty` variants as they are not
4289 // that commonly the self_type, it might be interesting to provide
4290 // support for those in future.
4295 fn get_module(this: &mut Resolver, span: Span, name_path: &[ast::Name])
4296 -> Option<Rc<Module>> {
4297 let root = this.current_module.clone();
4298 let last_name = name_path.last().unwrap();
4300 if name_path.len() == 1 {
4301 match this.primitive_type_table.primitive_types.get(last_name) {
4304 match this.current_module.children.borrow().get(last_name) {
4305 Some(child) => child.get_module_if_available(),
4311 match this.resolve_module_path(root,
4316 Success((module, _)) => Some(module),
4322 let (path, node_id, allowed) = match self.current_self_type {
4323 Some(ref ty) => match extract_path_and_node_id(ty, Everything) {
4325 None => return NoSuggestion,
4327 None => return NoSuggestion,
4330 if allowed == Everything {
4331 // Look for a field with the same name in the current self_type.
4332 match self.def_map.borrow().get(&node_id) {
4333 Some(&DefTy(did, _))
4334 | Some(&DefStruct(did))
4335 | Some(&DefVariant(_, did, _)) => match self.structs.get(&did) {
4338 if fields.iter().any(|&field_name| name == field_name) {
4343 _ => {} // Self type didn't resolve properly
4347 let name_path = path.segments.iter().map(|seg| seg.identifier.name).collect::<Vec<_>>();
4349 // Look for a method in the current self type's impl module.
4350 match get_module(self, path.span, &name_path[]) {
4351 Some(module) => match module.children.borrow().get(&name) {
4353 let p_str = self.path_names_to_string(&path);
4354 match binding.def_for_namespace(ValueNS) {
4355 Some(DefStaticMethod(_, provenance)) => {
4357 FromImpl(_) => return StaticMethod(p_str),
4358 FromTrait(_) => unreachable!()
4361 Some(DefMethod(_, None, _)) if allowed == Everything => return Method,
4362 Some(DefMethod(_, Some(_), _)) => return TraitItem,
4371 // Look for a method in the current trait.
4372 match self.current_trait_ref {
4373 Some((did, ref trait_ref)) => {
4374 let path_str = self.path_names_to_string(&trait_ref.path);
4376 match self.trait_item_map.get(&(name, did)) {
4377 Some(&StaticMethodTraitItemKind) => {
4378 return TraitMethod(path_str)
4380 Some(_) => return TraitItem,
4390 fn find_best_match_for_name(&mut self, name: &str, max_distance: uint)
4392 let this = &mut *self;
4394 let mut maybes: Vec<token::InternedString> = Vec::new();
4395 let mut values: Vec<uint> = Vec::new();
4397 for rib in this.value_ribs.iter().rev() {
4398 for (&k, _) in &rib.bindings {
4399 maybes.push(token::get_name(k));
4400 values.push(usize::MAX);
4404 let mut smallest = 0;
4405 for (i, other) in maybes.iter().enumerate() {
4406 values[i] = lev_distance(name, &other);
4408 if values[i] <= values[smallest] {
4413 if values.len() > 0 &&
4414 values[smallest] != usize::MAX &&
4415 values[smallest] < name.len() + 2 &&
4416 values[smallest] <= max_distance &&
4417 name != &maybes[smallest][] {
4419 Some(maybes[smallest].to_string())
4426 fn resolve_expr(&mut self, expr: &Expr) {
4427 // First, record candidate traits for this expression if it could
4428 // result in the invocation of a method call.
4430 self.record_candidate_traits_for_expr_if_necessary(expr);
4432 // Next, resolve the node.
4434 // The interpretation of paths depends on whether the path has
4435 // multiple elements in it or not.
4437 ExprPath(_) | ExprQPath(_) => {
4438 let mut path_from_qpath;
4439 let path = match expr.node {
4440 ExprPath(ref path) => path,
4441 ExprQPath(ref qpath) => {
4442 self.resolve_type(&*qpath.self_type);
4443 self.resolve_trait_reference(expr.id, &*qpath.trait_ref, TraitQPath);
4444 path_from_qpath = qpath.trait_ref.path.clone();
4445 path_from_qpath.segments.push(qpath.item_path.clone());
4450 // This is a local path in the value namespace. Walk through
4451 // scopes looking for it.
4452 match self.resolve_path(expr.id, path, ValueNS, true) {
4453 // Check if struct variant
4454 Some((DefVariant(_, _, true), _)) => {
4455 let path_name = self.path_names_to_string(path);
4456 self.resolve_error(expr.span,
4457 &format!("`{}` is a struct variant name, but \
4459 uses it like a function name",
4462 self.session.span_help(expr.span,
4463 &format!("Did you mean to write: \
4464 `{} {{ /* fields */ }}`?",
4468 // Write the result into the def map.
4469 debug!("(resolving expr) resolved `{}`",
4470 self.path_names_to_string(path));
4472 self.record_def(expr.id, def);
4475 // Be helpful if the name refers to a struct
4476 // (The pattern matching def_tys where the id is in self.structs
4477 // matches on regular structs while excluding tuple- and enum-like
4478 // structs, which wouldn't result in this error.)
4479 let path_name = self.path_names_to_string(path);
4480 match self.with_no_errors(|this|
4481 this.resolve_path(expr.id, path, TypeNS, false)) {
4482 Some((DefTy(struct_id, _), _))
4483 if self.structs.contains_key(&struct_id) => {
4484 self.resolve_error(expr.span,
4485 &format!("`{}` is a structure name, but \
4487 uses it like a function name",
4490 self.session.span_help(expr.span,
4491 &format!("Did you mean to write: \
4492 `{} {{ /* fields */ }}`?",
4497 let mut method_scope = false;
4498 self.value_ribs.iter().rev().all(|rib| {
4499 let res = match *rib {
4500 Rib { bindings: _, kind: MethodRibKind(_, _) } => true,
4501 Rib { bindings: _, kind: ItemRibKind } => false,
4502 _ => return true, // Keep advancing
4506 false // Stop advancing
4509 if method_scope && &token::get_name(self.self_name)[]
4513 "`self` is not available \
4514 in a static method. Maybe a \
4515 `self` argument is missing?");
4517 let last_name = path.segments.last().unwrap().identifier.name;
4518 let mut msg = match self.find_fallback_in_self_type(last_name) {
4520 // limit search to 5 to reduce the number
4521 // of stupid suggestions
4522 self.find_best_match_for_name(&path_name, 5)
4523 .map_or("".to_string(),
4524 |x| format!("`{}`", x))
4527 format!("`self.{}`", path_name),
4530 format!("to call `self.{}`", path_name),
4531 TraitMethod(path_str)
4532 | StaticMethod(path_str) =>
4533 format!("to call `{}::{}`", path_str, path_name)
4537 msg = format!(". Did you mean {}?", msg)
4542 &format!("unresolved name `{}`{}",
4551 visit::walk_expr(self, expr);
4554 ExprClosure(_, ref fn_decl, ref block) => {
4555 self.resolve_function(ClosureRibKind(expr.id),
4556 Some(&**fn_decl), NoTypeParameters,
4560 ExprStruct(ref path, _, _) => {
4561 // Resolve the path to the structure it goes to. We don't
4562 // check to ensure that the path is actually a structure; that
4563 // is checked later during typeck.
4564 match self.resolve_path(expr.id, path, TypeNS, false) {
4565 Some(definition) => self.record_def(expr.id, definition),
4567 debug!("(resolving expression) didn't find struct \
4568 def: {:?}", result);
4569 let msg = format!("`{}` does not name a structure",
4570 self.path_names_to_string(path));
4571 self.resolve_error(path.span, &msg[]);
4575 visit::walk_expr(self, expr);
4578 ExprLoop(_, Some(label)) | ExprWhile(_, _, Some(label)) => {
4579 self.with_label_rib(|this| {
4580 let def_like = DlDef(DefLabel(expr.id));
4583 let rib = this.label_ribs.last_mut().unwrap();
4584 let renamed = mtwt::resolve(label);
4585 rib.bindings.insert(renamed, def_like);
4588 visit::walk_expr(this, expr);
4592 ExprBreak(Some(label)) | ExprAgain(Some(label)) => {
4593 let renamed = mtwt::resolve(label);
4594 match self.search_label(renamed) {
4598 &format!("use of undeclared label `{}`",
4599 token::get_ident(label))[])
4601 Some(DlDef(def @ DefLabel(_))) => {
4602 // Since this def is a label, it is never read.
4603 self.record_def(expr.id, (def, LastMod(AllPublic)))
4606 self.session.span_bug(expr.span,
4607 "label wasn't mapped to a \
4614 visit::walk_expr(self, expr);
4619 fn record_candidate_traits_for_expr_if_necessary(&mut self, expr: &Expr) {
4621 ExprField(_, ident) => {
4622 // FIXME(#6890): Even though you can't treat a method like a
4623 // field, we need to add any trait methods we find that match
4624 // the field name so that we can do some nice error reporting
4625 // later on in typeck.
4626 let traits = self.search_for_traits_containing_method(ident.node.name);
4627 self.trait_map.insert(expr.id, traits);
4629 ExprMethodCall(ident, _, _) => {
4630 debug!("(recording candidate traits for expr) recording \
4633 let traits = self.search_for_traits_containing_method(ident.node.name);
4634 self.trait_map.insert(expr.id, traits);
4642 fn search_for_traits_containing_method(&mut self, name: Name) -> Vec<DefId> {
4643 debug!("(searching for traits containing method) looking for '{}'",
4644 token::get_name(name));
4646 fn add_trait_info(found_traits: &mut Vec<DefId>,
4647 trait_def_id: DefId,
4649 debug!("(adding trait info) found trait {}:{} for method '{}'",
4652 token::get_name(name));
4653 found_traits.push(trait_def_id);
4656 let mut found_traits = Vec::new();
4657 let mut search_module = self.current_module.clone();
4659 // Look for the current trait.
4660 match self.current_trait_ref {
4661 Some((trait_def_id, _)) => {
4662 if self.trait_item_map.contains_key(&(name, trait_def_id)) {
4663 add_trait_info(&mut found_traits, trait_def_id, name);
4666 None => {} // Nothing to do.
4669 // Look for trait children.
4670 build_reduced_graph::populate_module_if_necessary(self, &search_module);
4673 for (_, child_names) in &*search_module.children.borrow() {
4674 let def = match child_names.def_for_namespace(TypeNS) {
4678 let trait_def_id = match def {
4679 DefTrait(trait_def_id) => trait_def_id,
4682 if self.trait_item_map.contains_key(&(name, trait_def_id)) {
4683 add_trait_info(&mut found_traits, trait_def_id, name);
4688 // Look for imports.
4689 for (_, import) in &*search_module.import_resolutions.borrow() {
4690 let target = match import.target_for_namespace(TypeNS) {
4692 Some(target) => target,
4694 let did = match target.bindings.def_for_namespace(TypeNS) {
4695 Some(DefTrait(trait_def_id)) => trait_def_id,
4696 Some(..) | None => continue,
4698 if self.trait_item_map.contains_key(&(name, did)) {
4699 add_trait_info(&mut found_traits, did, name);
4700 let id = import.type_id;
4701 self.used_imports.insert((id, TypeNS));
4702 let trait_name = self.get_trait_name(did);
4703 self.record_import_use(id, trait_name);
4704 if let Some(DefId{krate: kid, ..}) = target.target_module.def_id.get() {
4705 self.used_crates.insert(kid);
4710 match search_module.parent_link.clone() {
4711 NoParentLink | ModuleParentLink(..) => break,
4712 BlockParentLink(parent_module, _) => {
4713 search_module = parent_module.upgrade().unwrap();
4721 fn record_def(&mut self, node_id: NodeId, (def, lp): (Def, LastPrivate)) {
4722 debug!("(recording def) recording {:?} for {}, last private {:?}",
4724 assert!(match lp {LastImport{..} => false, _ => true},
4725 "Import should only be used for `use` directives");
4726 self.last_private.insert(node_id, lp);
4728 match self.def_map.borrow_mut().entry(node_id) {
4729 // Resolve appears to "resolve" the same ID multiple
4730 // times, so here is a sanity check it at least comes to
4731 // the same conclusion! - nmatsakis
4732 Occupied(entry) => if def != *entry.get() {
4734 .bug(&format!("node_id {} resolved first to {:?} and \
4740 Vacant(entry) => { entry.insert(def); },
4744 fn enforce_default_binding_mode(&mut self,
4746 pat_binding_mode: BindingMode,
4748 match pat_binding_mode {
4749 BindByValue(_) => {}
4751 self.resolve_error(pat.span,
4752 &format!("cannot use `ref` binding mode \
4762 // Diagnostics are not particularly efficient, because they're rarely
4766 /// A somewhat inefficient routine to obtain the name of a module.
4767 fn module_to_string(&self, module: &Module) -> String {
4768 let mut names = Vec::new();
4770 fn collect_mod(names: &mut Vec<ast::Name>, module: &Module) {
4771 match module.parent_link {
4773 ModuleParentLink(ref module, name) => {
4775 collect_mod(names, &*module.upgrade().unwrap());
4777 BlockParentLink(ref module, _) => {
4778 // danger, shouldn't be ident?
4779 names.push(special_idents::opaque.name);
4780 collect_mod(names, &*module.upgrade().unwrap());
4784 collect_mod(&mut names, module);
4786 if names.len() == 0 {
4787 return "???".to_string();
4789 self.names_to_string(&names.into_iter().rev()
4790 .collect::<Vec<ast::Name>>()[])
4793 #[allow(dead_code)] // useful for debugging
4794 fn dump_module(&mut self, module_: Rc<Module>) {
4795 debug!("Dump of module `{}`:", self.module_to_string(&*module_));
4797 debug!("Children:");
4798 build_reduced_graph::populate_module_if_necessary(self, &module_);
4799 for (&name, _) in &*module_.children.borrow() {
4800 debug!("* {}", token::get_name(name));
4803 debug!("Import resolutions:");
4804 let import_resolutions = module_.import_resolutions.borrow();
4805 for (&name, import_resolution) in &*import_resolutions {
4807 match import_resolution.target_for_namespace(ValueNS) {
4808 None => { value_repr = "".to_string(); }
4810 value_repr = " value:?".to_string();
4816 match import_resolution.target_for_namespace(TypeNS) {
4817 None => { type_repr = "".to_string(); }
4819 type_repr = " type:?".to_string();
4824 debug!("* {}:{}{}", token::get_name(name), value_repr, type_repr);
4829 pub struct CrateMap {
4830 pub def_map: DefMap,
4831 pub freevars: RefCell<FreevarMap>,
4832 pub export_map: ExportMap,
4833 pub trait_map: TraitMap,
4834 pub external_exports: ExternalExports,
4835 pub last_private_map: LastPrivateMap,
4836 pub glob_map: Option<GlobMap>
4839 #[derive(PartialEq,Copy)]
4840 pub enum MakeGlobMap {
4845 /// Entry point to crate resolution.
4846 pub fn resolve_crate<'a, 'tcx>(session: &'a Session,
4847 ast_map: &'a ast_map::Map<'tcx>,
4850 make_glob_map: MakeGlobMap)
4852 let mut resolver = Resolver::new(session, ast_map, krate.span, make_glob_map);
4854 build_reduced_graph::build_reduced_graph(&mut resolver, krate);
4855 session.abort_if_errors();
4857 resolver.resolve_imports();
4858 session.abort_if_errors();
4860 record_exports::record(&mut resolver);
4861 session.abort_if_errors();
4863 resolver.resolve_crate(krate);
4864 session.abort_if_errors();
4866 check_unused::check_crate(&mut resolver, krate);
4869 def_map: resolver.def_map,
4870 freevars: resolver.freevars,
4871 export_map: resolver.export_map,
4872 trait_map: resolver.trait_map,
4873 external_exports: resolver.external_exports,
4874 last_private_map: resolver.last_private,
4875 glob_map: if resolver.make_glob_map {
4876 Some(resolver.glob_map)