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"]
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/")]
20 #![feature(slicing_syntax)]
21 #![feature(rustc_diagnostic_macros)]
22 #![allow(unknown_features)] #![feature(int_uint)]
25 #[macro_use] extern crate log;
26 #[macro_use] extern crate syntax;
27 #[macro_use] #[no_link] extern crate rustc_bitflags;
31 use self::PatternBindingMode::*;
32 use self::Namespace::*;
33 use self::NamespaceResult::*;
34 use self::NameDefinition::*;
35 use self::ImportDirectiveSubclass::*;
36 use self::ResolveResult::*;
37 use self::FallbackSuggestion::*;
38 use self::TypeParameters::*;
40 use self::MethodSort::*;
41 use self::UseLexicalScopeFlag::*;
42 use self::ModulePrefixResult::*;
43 use self::NameSearchType::*;
44 use self::BareIdentifierPatternResolution::*;
45 use self::ParentLink::*;
46 use self::ModuleKind::*;
47 use self::TraitReferenceType::*;
48 use self::FallbackChecks::*;
50 use rustc::session::Session;
52 use rustc::metadata::csearch;
53 use rustc::metadata::decoder::{DefLike, DlDef, DlField, DlImpl};
54 use rustc::middle::def::*;
55 use rustc::middle::lang_items::LanguageItems;
56 use rustc::middle::pat_util::pat_bindings;
57 use rustc::middle::privacy::*;
58 use rustc::middle::subst::{ParamSpace, FnSpace, TypeSpace};
59 use rustc::middle::ty::{CaptureModeMap, Freevar, FreevarMap, TraitMap, GlobMap};
60 use rustc::util::nodemap::{NodeMap, NodeSet, DefIdSet, FnvHashMap};
61 use rustc::util::lev_distance::lev_distance;
63 use syntax::ast::{Arm, BindByRef, BindByValue, BindingMode, Block, Crate, CrateNum};
64 use syntax::ast::{DefId, Expr, ExprAgain, ExprBreak, ExprField};
65 use syntax::ast::{ExprClosure, ExprForLoop, ExprLoop, ExprWhile, ExprMethodCall};
66 use syntax::ast::{ExprPath, ExprQPath, ExprStruct, FnDecl};
67 use syntax::ast::{ForeignItemFn, ForeignItemStatic, Generics};
68 use syntax::ast::{Ident, ImplItem, Item, ItemConst, ItemEnum, ItemExternCrate};
69 use syntax::ast::{ItemFn, ItemForeignMod, ItemImpl, ItemMac, ItemMod, ItemStatic};
70 use syntax::ast::{ItemStruct, ItemTrait, ItemTy, ItemUse};
71 use syntax::ast::{Local, MethodImplItem, Mod, Name, NodeId};
72 use syntax::ast::{Pat, PatEnum, PatIdent, PatLit};
73 use syntax::ast::{PatRange, PatStruct, Path};
74 use syntax::ast::{PolyTraitRef, PrimTy, SelfExplicit};
75 use syntax::ast::{RegionTyParamBound, StructField};
76 use syntax::ast::{TraitRef, TraitTyParamBound};
77 use syntax::ast::{Ty, TyBool, TyChar, TyF32};
78 use syntax::ast::{TyF64, TyFloat, TyIs, TyI8, TyI16, TyI32, TyI64, TyInt, TyObjectSum};
79 use syntax::ast::{TyParam, TyParamBound, TyPath, TyPtr, TyPolyTraitRef, TyQPath};
80 use syntax::ast::{TyRptr, TyStr, TyUs, TyU8, TyU16, TyU32, TyU64, TyUint};
81 use syntax::ast::{TypeImplItem};
84 use syntax::ast_util::{PostExpansionMethod, local_def, walk_pat};
85 use syntax::attr::AttrMetaMethods;
86 use syntax::ext::mtwt;
87 use syntax::parse::token::{self, special_names, special_idents};
88 use syntax::codemap::{Span, Pos};
89 use syntax::owned_slice::OwnedSlice;
90 use syntax::visit::{self, Visitor};
92 use std::collections::{HashMap, HashSet};
93 use std::collections::hash_map::Entry::{Occupied, Vacant};
94 use std::cell::{Cell, RefCell};
96 use std::mem::replace;
97 use std::rc::{Rc, Weak};
102 mod build_reduced_graph;
107 binding_mode: BindingMode,
110 // Map from the name in a pattern to its binding mode.
111 type BindingMap = HashMap<Name, BindingInfo>;
113 #[derive(Copy, PartialEq)]
114 enum PatternBindingMode {
116 LocalIrrefutableMode,
117 ArgumentIrrefutableMode,
120 #[derive(Copy, PartialEq, Eq, Hash, Show)]
126 /// A NamespaceResult represents the result of resolving an import in
127 /// a particular namespace. The result is either definitely-resolved,
128 /// definitely- unresolved, or unknown.
130 enum NamespaceResult {
131 /// Means that resolve hasn't gathered enough information yet to determine
132 /// whether the name is bound in this namespace. (That is, it hasn't
133 /// resolved all `use` directives yet.)
135 /// Means that resolve has determined that the name is definitely
136 /// not bound in the namespace.
138 /// Means that resolve has determined that the name is bound in the Module
139 /// argument, and specified by the NameBindings argument.
140 BoundResult(Rc<Module>, Rc<NameBindings>)
143 impl NamespaceResult {
144 fn is_unknown(&self) -> bool {
146 UnknownResult => true,
150 fn is_unbound(&self) -> bool {
152 UnboundResult => true,
158 enum NameDefinition {
159 NoNameDefinition, //< The name was unbound.
160 ChildNameDefinition(Def, LastPrivate), //< The name identifies an immediate child.
161 ImportNameDefinition(Def, LastPrivate) //< The name identifies an import.
164 impl<'a, 'v, 'tcx> Visitor<'v> for Resolver<'a, 'tcx> {
165 fn visit_item(&mut self, item: &Item) {
166 self.resolve_item(item);
168 fn visit_arm(&mut self, arm: &Arm) {
169 self.resolve_arm(arm);
171 fn visit_block(&mut self, block: &Block) {
172 self.resolve_block(block);
174 fn visit_expr(&mut self, expr: &Expr) {
175 self.resolve_expr(expr);
177 fn visit_local(&mut self, local: &Local) {
178 self.resolve_local(local);
180 fn visit_ty(&mut self, ty: &Ty) {
181 self.resolve_type(ty);
185 /// Contains data for specific types of import directives.
187 enum ImportDirectiveSubclass {
188 SingleImport(Name /* target */, Name /* source */),
192 type ErrorMessage = Option<(Span, String)>;
194 enum ResolveResult<T> {
195 Failed(ErrorMessage), // Failed to resolve the name, optional helpful error message.
196 Indeterminate, // Couldn't determine due to unresolved globs.
197 Success(T) // Successfully resolved the import.
200 impl<T> ResolveResult<T> {
201 fn indeterminate(&self) -> bool {
202 match *self { Indeterminate => true, _ => false }
206 enum FallbackSuggestion {
211 StaticMethod(String),
216 enum TypeParameters<'a> {
222 // Identifies the things that these parameters
223 // were declared on (type, fn, etc)
226 // ID of the enclosing item.
229 // The kind of the rib used for type parameters.
233 // The rib kind controls the translation of local
234 // definitions (`DefLocal`) to upvars (`DefUpvar`).
235 #[derive(Copy, Show)]
237 // No translation needs to be applied.
240 // We passed through a closure scope at the given node ID.
241 // Translate upvars as appropriate.
242 ClosureRibKind(NodeId /* func id */, NodeId /* body id if proc or unboxed */),
244 // We passed through an impl or trait and are now in one of its
245 // methods. Allow references to ty params that impl or trait
246 // binds. Disallow any other upvars (including other ty params that are
248 // parent; method itself
249 MethodRibKind(NodeId, MethodSort),
251 // We passed through an item scope. Disallow upvars.
254 // We're in a constant item. Can't refer to dynamic stuff.
258 // Methods can be required or provided. RequiredMethod methods only occur in traits.
259 #[derive(Copy, Show)]
262 ProvidedMethod(NodeId)
266 enum UseLexicalScopeFlag {
271 enum ModulePrefixResult {
273 PrefixFound(Rc<Module>, uint)
276 #[derive(Copy, PartialEq)]
277 enum NameSearchType {
278 /// We're doing a name search in order to resolve a `use` directive.
281 /// We're doing a name search in order to resolve a path type, a path
282 /// expression, or a path pattern.
287 enum BareIdentifierPatternResolution {
288 FoundStructOrEnumVariant(Def, LastPrivate),
289 FoundConst(Def, LastPrivate),
290 BareIdentifierPatternUnresolved
296 bindings: HashMap<Name, DefLike>,
301 fn new(kind: RibKind) -> Rib {
303 bindings: HashMap::new(),
309 /// Whether an import can be shadowed by another import.
310 #[derive(Show,PartialEq,Clone,Copy)]
316 /// One import directive.
318 struct ImportDirective {
319 module_path: Vec<Name>,
320 subclass: ImportDirectiveSubclass,
323 is_public: bool, // see note in ImportResolution about how to use this
324 shadowable: Shadowable,
327 impl ImportDirective {
328 fn new(module_path: Vec<Name> ,
329 subclass: ImportDirectiveSubclass,
333 shadowable: Shadowable)
336 module_path: module_path,
340 is_public: is_public,
341 shadowable: shadowable,
346 /// The item that an import resolves to.
347 #[derive(Clone,Show)]
349 target_module: Rc<Module>,
350 bindings: Rc<NameBindings>,
351 shadowable: Shadowable,
355 fn new(target_module: Rc<Module>,
356 bindings: Rc<NameBindings>,
357 shadowable: Shadowable)
360 target_module: target_module,
362 shadowable: shadowable,
367 /// An ImportResolution represents a particular `use` directive.
369 struct ImportResolution {
370 /// Whether this resolution came from a `use` or a `pub use`. Note that this
371 /// should *not* be used whenever resolution is being performed, this is
372 /// only looked at for glob imports statements currently. Privacy testing
373 /// occurs during a later phase of compilation.
376 // The number of outstanding references to this name. When this reaches
377 // zero, outside modules can count on the targets being correct. Before
378 // then, all bets are off; future imports could override this name.
379 outstanding_references: uint,
381 /// The value that this `use` directive names, if there is one.
382 value_target: Option<Target>,
383 /// The source node of the `use` directive leading to the value target
387 /// The type that this `use` directive names, if there is one.
388 type_target: Option<Target>,
389 /// The source node of the `use` directive leading to the type target
394 impl ImportResolution {
395 fn new(id: NodeId, is_public: bool) -> ImportResolution {
399 outstanding_references: 0,
402 is_public: is_public,
406 fn target_for_namespace(&self, namespace: Namespace)
409 TypeNS => self.type_target.clone(),
410 ValueNS => self.value_target.clone(),
414 fn id(&self, namespace: Namespace) -> NodeId {
416 TypeNS => self.type_id,
417 ValueNS => self.value_id,
421 fn shadowable(&self, namespace: Namespace) -> Shadowable {
422 let target = self.target_for_namespace(namespace);
423 if target.is_none() {
424 return Shadowable::Always;
427 target.unwrap().shadowable
430 fn set_target_and_id(&mut self,
431 namespace: Namespace,
432 target: Option<Target>,
436 self.type_target = target;
440 self.value_target = target;
447 /// The link from a module up to its nearest parent node.
448 #[derive(Clone,Show)]
451 ModuleParentLink(Weak<Module>, Name),
452 BlockParentLink(Weak<Module>, NodeId)
455 /// The type of module this is.
456 #[derive(Copy, PartialEq, Show)]
466 /// One node in the tree of modules.
468 parent_link: ParentLink,
469 def_id: Cell<Option<DefId>>,
470 kind: Cell<ModuleKind>,
473 children: RefCell<HashMap<Name, Rc<NameBindings>>>,
474 imports: RefCell<Vec<ImportDirective>>,
476 // The external module children of this node that were declared with
478 external_module_children: RefCell<HashMap<Name, Rc<Module>>>,
480 // The anonymous children of this node. Anonymous children are pseudo-
481 // modules that are implicitly created around items contained within
484 // For example, if we have this:
492 // There will be an anonymous module created around `g` with the ID of the
493 // entry block for `f`.
494 anonymous_children: RefCell<NodeMap<Rc<Module>>>,
496 // The status of resolving each import in this module.
497 import_resolutions: RefCell<HashMap<Name, ImportResolution>>,
499 // The number of unresolved globs that this module exports.
500 glob_count: Cell<uint>,
502 // The index of the import we're resolving.
503 resolved_import_count: Cell<uint>,
505 // Whether this module is populated. If not populated, any attempt to
506 // access the children must be preceded with a
507 // `populate_module_if_necessary` call.
508 populated: Cell<bool>,
512 fn new(parent_link: ParentLink,
513 def_id: Option<DefId>,
519 parent_link: parent_link,
520 def_id: Cell::new(def_id),
521 kind: Cell::new(kind),
522 is_public: is_public,
523 children: RefCell::new(HashMap::new()),
524 imports: RefCell::new(Vec::new()),
525 external_module_children: RefCell::new(HashMap::new()),
526 anonymous_children: RefCell::new(NodeMap()),
527 import_resolutions: RefCell::new(HashMap::new()),
528 glob_count: Cell::new(0),
529 resolved_import_count: Cell::new(0),
530 populated: Cell::new(!external),
534 fn all_imports_resolved(&self) -> bool {
535 self.imports.borrow().len() == self.resolved_import_count.get()
539 impl fmt::Show for Module {
540 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
541 write!(f, "{:?}, kind: {:?}, {}",
544 if self.is_public { "public" } else { "private" } )
550 flags DefModifiers: u8 {
551 const PUBLIC = 0b0000_0001,
552 const IMPORTABLE = 0b0000_0010,
556 // Records a possibly-private type definition.
557 #[derive(Clone,Show)]
559 modifiers: DefModifiers, // see note in ImportResolution about how to use this
560 module_def: Option<Rc<Module>>,
561 type_def: Option<Def>,
562 type_span: Option<Span>
565 // Records a possibly-private value definition.
566 #[derive(Clone, Copy, Show)]
568 modifiers: DefModifiers, // see note in ImportResolution about how to use this
570 value_span: Option<Span>,
573 // Records the definitions (at most one for each namespace) that a name is
576 struct NameBindings {
577 type_def: RefCell<Option<TypeNsDef>>, //< Meaning in type namespace.
578 value_def: RefCell<Option<ValueNsDef>>, //< Meaning in value namespace.
581 /// Ways in which a trait can be referenced
583 enum TraitReferenceType {
584 TraitImplementation, // impl SomeTrait for T { ... }
585 TraitDerivation, // trait T : SomeTrait { ... }
586 TraitBoundingTypeParameter, // fn f<T:SomeTrait>() { ... }
587 TraitObject, // Box<for<'a> SomeTrait>
588 TraitQPath, // <T as SomeTrait>::
592 fn new() -> NameBindings {
594 type_def: RefCell::new(None),
595 value_def: RefCell::new(None),
599 /// Creates a new module in this set of name bindings.
600 fn define_module(&self,
601 parent_link: ParentLink,
602 def_id: Option<DefId>,
607 // Merges the module with the existing type def or creates a new one.
608 let modifiers = if is_public { PUBLIC } else { DefModifiers::empty() } | IMPORTABLE;
609 let module_ = Rc::new(Module::new(parent_link,
614 let type_def = self.type_def.borrow().clone();
617 *self.type_def.borrow_mut() = Some(TypeNsDef {
618 modifiers: modifiers,
619 module_def: Some(module_),
625 *self.type_def.borrow_mut() = Some(TypeNsDef {
626 modifiers: modifiers,
627 module_def: Some(module_),
629 type_def: type_def.type_def
635 /// Sets the kind of the module, creating a new one if necessary.
636 fn set_module_kind(&self,
637 parent_link: ParentLink,
638 def_id: Option<DefId>,
643 let modifiers = if is_public { PUBLIC } else { DefModifiers::empty() } | IMPORTABLE;
644 let type_def = self.type_def.borrow().clone();
647 let module = Module::new(parent_link,
652 *self.type_def.borrow_mut() = Some(TypeNsDef {
653 modifiers: modifiers,
654 module_def: Some(Rc::new(module)),
660 match type_def.module_def {
662 let module = Module::new(parent_link,
667 *self.type_def.borrow_mut() = Some(TypeNsDef {
668 modifiers: modifiers,
669 module_def: Some(Rc::new(module)),
670 type_def: type_def.type_def,
674 Some(module_def) => module_def.kind.set(kind),
680 /// Records a type definition.
681 fn define_type(&self, def: Def, sp: Span, modifiers: DefModifiers) {
682 debug!("defining type for def {:?} with modifiers {:?}", def, modifiers);
683 // Merges the type with the existing type def or creates a new one.
684 let type_def = self.type_def.borrow().clone();
687 *self.type_def.borrow_mut() = Some(TypeNsDef {
691 modifiers: modifiers,
695 *self.type_def.borrow_mut() = Some(TypeNsDef {
696 module_def: type_def.module_def,
699 modifiers: modifiers,
705 /// Records a value definition.
706 fn define_value(&self, def: Def, sp: Span, modifiers: DefModifiers) {
707 debug!("defining value for def {:?} with modifiers {:?}", def, modifiers);
708 *self.value_def.borrow_mut() = Some(ValueNsDef {
710 value_span: Some(sp),
711 modifiers: modifiers,
715 /// Returns the module node if applicable.
716 fn get_module_if_available(&self) -> Option<Rc<Module>> {
717 match *self.type_def.borrow() {
718 Some(ref type_def) => type_def.module_def.clone(),
723 /// Returns the module node. Panics if this node does not have a module
725 fn get_module(&self) -> Rc<Module> {
726 match self.get_module_if_available() {
728 panic!("get_module called on a node with no module \
731 Some(module_def) => module_def
735 fn defined_in_namespace(&self, namespace: Namespace) -> bool {
737 TypeNS => return self.type_def.borrow().is_some(),
738 ValueNS => return self.value_def.borrow().is_some()
742 fn defined_in_public_namespace(&self, namespace: Namespace) -> bool {
743 self.defined_in_namespace_with(namespace, PUBLIC)
746 fn defined_in_namespace_with(&self, namespace: Namespace, modifiers: DefModifiers) -> bool {
748 TypeNS => match *self.type_def.borrow() {
749 Some(ref def) => def.modifiers.contains(modifiers), None => false
751 ValueNS => match *self.value_def.borrow() {
752 Some(ref def) => def.modifiers.contains(modifiers), None => false
757 fn def_for_namespace(&self, namespace: Namespace) -> Option<Def> {
760 match *self.type_def.borrow() {
762 Some(ref type_def) => {
763 match type_def.type_def {
764 Some(type_def) => Some(type_def),
766 match type_def.module_def {
767 Some(ref module) => {
768 match module.def_id.get() {
769 Some(did) => Some(DefMod(did)),
781 match *self.value_def.borrow() {
783 Some(value_def) => Some(value_def.def)
789 fn span_for_namespace(&self, namespace: Namespace) -> Option<Span> {
790 if self.defined_in_namespace(namespace) {
793 match *self.type_def.borrow() {
795 Some(ref type_def) => type_def.type_span
799 match *self.value_def.borrow() {
801 Some(ref value_def) => value_def.value_span
811 /// Interns the names of the primitive types.
812 struct PrimitiveTypeTable {
813 primitive_types: HashMap<Name, PrimTy>,
816 impl PrimitiveTypeTable {
817 fn new() -> PrimitiveTypeTable {
818 let mut table = PrimitiveTypeTable {
819 primitive_types: HashMap::new()
822 table.intern("bool", TyBool);
823 table.intern("char", TyChar);
824 table.intern("f32", TyFloat(TyF32));
825 table.intern("f64", TyFloat(TyF64));
826 table.intern("int", TyInt(TyIs(true)));
827 table.intern("isize", TyInt(TyIs(false)));
828 table.intern("i8", TyInt(TyI8));
829 table.intern("i16", TyInt(TyI16));
830 table.intern("i32", TyInt(TyI32));
831 table.intern("i64", TyInt(TyI64));
832 table.intern("str", TyStr);
833 table.intern("uint", TyUint(TyUs(true)));
834 table.intern("usize", TyUint(TyUs(false)));
835 table.intern("u8", TyUint(TyU8));
836 table.intern("u16", TyUint(TyU16));
837 table.intern("u32", TyUint(TyU32));
838 table.intern("u64", TyUint(TyU64));
843 fn intern(&mut self, string: &str, primitive_type: PrimTy) {
844 self.primitive_types.insert(token::intern(string), primitive_type);
848 /// The main resolver class.
849 struct Resolver<'a, 'tcx:'a> {
850 session: &'a Session,
852 ast_map: &'a ast_map::Map<'tcx>,
854 graph_root: NameBindings,
856 trait_item_map: FnvHashMap<(Name, DefId), TraitItemKind>,
858 structs: FnvHashMap<DefId, Vec<Name>>,
860 // The number of imports that are currently unresolved.
861 unresolved_imports: uint,
863 // The module that represents the current item scope.
864 current_module: Rc<Module>,
866 // The current set of local scopes, for values.
867 // FIXME #4948: Reuse ribs to avoid allocation.
868 value_ribs: Vec<Rib>,
870 // The current set of local scopes, for types.
873 // The current set of local scopes, for labels.
874 label_ribs: Vec<Rib>,
876 // The trait that the current context can refer to.
877 current_trait_ref: Option<(DefId, TraitRef)>,
879 // The current self type if inside an impl (used for better errors).
880 current_self_type: Option<Ty>,
882 // The ident for the keyword "self".
884 // The ident for the non-keyword "Self".
885 type_self_name: Name,
887 // The idents for the primitive types.
888 primitive_type_table: PrimitiveTypeTable,
891 freevars: RefCell<FreevarMap>,
892 freevars_seen: RefCell<NodeMap<NodeSet>>,
893 capture_mode_map: CaptureModeMap,
894 export_map: ExportMap,
896 external_exports: ExternalExports,
897 last_private: LastPrivateMap,
899 // Whether or not to print error messages. Can be set to true
900 // when getting additional info for error message suggestions,
901 // so as to avoid printing duplicate errors
905 // Maps imports to the names of items actually imported (this actually maps
906 // all imports, but only glob imports are actually interesting).
909 used_imports: HashSet<(NodeId, Namespace)>,
910 used_crates: HashSet<CrateNum>,
914 enum FallbackChecks {
920 impl<'a, 'tcx> Resolver<'a, 'tcx> {
921 fn new(session: &'a Session,
922 ast_map: &'a ast_map::Map<'tcx>,
924 make_glob_map: MakeGlobMap) -> Resolver<'a, 'tcx> {
925 let graph_root = NameBindings::new();
927 graph_root.define_module(NoParentLink,
928 Some(DefId { krate: 0, node: 0 }),
934 let current_module = graph_root.get_module();
941 // The outermost module has def ID 0; this is not reflected in the
944 graph_root: graph_root,
946 trait_item_map: FnvHashMap(),
947 structs: FnvHashMap(),
949 unresolved_imports: 0,
951 current_module: current_module,
952 value_ribs: Vec::new(),
953 type_ribs: Vec::new(),
954 label_ribs: Vec::new(),
956 current_trait_ref: None,
957 current_self_type: None,
959 self_name: special_names::self_,
960 type_self_name: special_names::type_self,
962 primitive_type_table: PrimitiveTypeTable::new(),
964 def_map: RefCell::new(NodeMap()),
965 freevars: RefCell::new(NodeMap()),
966 freevars_seen: RefCell::new(NodeMap()),
967 capture_mode_map: NodeMap(),
968 export_map: NodeMap(),
969 trait_map: NodeMap(),
970 used_imports: HashSet::new(),
971 used_crates: HashSet::new(),
972 external_exports: DefIdSet(),
973 last_private: NodeMap(),
976 make_glob_map: make_glob_map == MakeGlobMap::Yes,
977 glob_map: HashMap::new(),
983 // This is a fixed-point algorithm. We resolve imports until our efforts
984 // are stymied by an unresolved import; then we bail out of the current
985 // module and continue. We terminate successfully once no more imports
986 // remain or unsuccessfully when no forward progress in resolving imports
989 /// Resolves all imports for the crate. This method performs the fixed-
991 fn resolve_imports(&mut self) {
993 let mut prev_unresolved_imports = 0;
995 debug!("(resolving imports) iteration {}, {} imports left",
996 i, self.unresolved_imports);
998 let module_root = self.graph_root.get_module();
999 self.resolve_imports_for_module_subtree(module_root.clone());
1001 if self.unresolved_imports == 0 {
1002 debug!("(resolving imports) success");
1006 if self.unresolved_imports == prev_unresolved_imports {
1007 self.report_unresolved_imports(module_root);
1012 prev_unresolved_imports = self.unresolved_imports;
1016 /// Attempts to resolve imports for the given module and all of its
1018 fn resolve_imports_for_module_subtree(&mut self, module_: Rc<Module>) {
1019 debug!("(resolving imports for module subtree) resolving {}",
1020 self.module_to_string(&*module_));
1021 let orig_module = replace(&mut self.current_module, module_.clone());
1022 self.resolve_imports_for_module(module_.clone());
1023 self.current_module = orig_module;
1025 build_reduced_graph::populate_module_if_necessary(self, &module_);
1026 for (_, child_node) in module_.children.borrow().iter() {
1027 match child_node.get_module_if_available() {
1031 Some(child_module) => {
1032 self.resolve_imports_for_module_subtree(child_module);
1037 for (_, child_module) in module_.anonymous_children.borrow().iter() {
1038 self.resolve_imports_for_module_subtree(child_module.clone());
1042 /// Attempts to resolve imports for the given module only.
1043 fn resolve_imports_for_module(&mut self, module: Rc<Module>) {
1044 if module.all_imports_resolved() {
1045 debug!("(resolving imports for module) all imports resolved for \
1047 self.module_to_string(&*module));
1051 let imports = module.imports.borrow();
1052 let import_count = imports.len();
1053 while module.resolved_import_count.get() < import_count {
1054 let import_index = module.resolved_import_count.get();
1055 let import_directive = &(*imports)[import_index];
1056 match self.resolve_import_for_module(module.clone(),
1059 let (span, help) = match err {
1060 Some((span, msg)) => (span, format!(". {}", msg)),
1061 None => (import_directive.span, String::new())
1063 let msg = format!("unresolved import `{}`{}",
1064 self.import_path_to_string(
1065 &import_directive.module_path[],
1066 import_directive.subclass),
1068 self.resolve_error(span, &msg[]);
1070 Indeterminate => break, // Bail out. We'll come around next time.
1071 Success(()) => () // Good. Continue.
1074 module.resolved_import_count
1075 .set(module.resolved_import_count.get() + 1);
1079 fn names_to_string(&self, names: &[Name]) -> String {
1080 let mut first = true;
1081 let mut result = String::new();
1082 for name in names.iter() {
1086 result.push_str("::")
1088 result.push_str(token::get_name(*name).get());
1093 fn path_names_to_string(&self, path: &Path) -> String {
1094 let names: Vec<ast::Name> = path.segments
1096 .map(|seg| seg.identifier.name)
1098 self.names_to_string(&names[])
1101 fn import_directive_subclass_to_string(&mut self,
1102 subclass: ImportDirectiveSubclass)
1105 SingleImport(_, source) => {
1106 token::get_name(source).get().to_string()
1108 GlobImport => "*".to_string()
1112 fn import_path_to_string(&mut self,
1114 subclass: ImportDirectiveSubclass)
1116 if names.is_empty() {
1117 self.import_directive_subclass_to_string(subclass)
1120 self.names_to_string(names),
1121 self.import_directive_subclass_to_string(
1122 subclass))).to_string()
1127 fn record_import_use(&mut self, import_id: NodeId, name: Name) {
1128 if !self.make_glob_map {
1131 if self.glob_map.contains_key(&import_id) {
1132 self.glob_map[import_id].insert(name);
1136 let mut new_set = HashSet::new();
1137 new_set.insert(name);
1138 self.glob_map.insert(import_id, new_set);
1141 fn get_trait_name(&self, did: DefId) -> Name {
1142 if did.krate == ast::LOCAL_CRATE {
1143 self.ast_map.expect_item(did.node).ident.name
1145 csearch::get_trait_name(&self.session.cstore, did)
1149 /// Attempts to resolve the given import. The return value indicates
1150 /// failure if we're certain the name does not exist, indeterminate if we
1151 /// don't know whether the name exists at the moment due to other
1152 /// currently-unresolved imports, or success if we know the name exists.
1153 /// If successful, the resolved bindings are written into the module.
1154 fn resolve_import_for_module(&mut self,
1155 module_: Rc<Module>,
1156 import_directive: &ImportDirective)
1157 -> ResolveResult<()> {
1158 let mut resolution_result = Failed(None);
1159 let module_path = &import_directive.module_path;
1161 debug!("(resolving import for module) resolving import `{}::...` in `{}`",
1162 self.names_to_string(&module_path[]),
1163 self.module_to_string(&*module_));
1165 // First, resolve the module path for the directive, if necessary.
1166 let container = if module_path.len() == 0 {
1167 // Use the crate root.
1168 Some((self.graph_root.get_module(), LastMod(AllPublic)))
1170 match self.resolve_module_path(module_.clone(),
1172 DontUseLexicalScope,
1173 import_directive.span,
1176 resolution_result = Failed(err);
1180 resolution_result = Indeterminate;
1183 Success(container) => Some(container),
1189 Some((containing_module, lp)) => {
1190 // We found the module that the target is contained
1191 // within. Attempt to resolve the import within it.
1193 match import_directive.subclass {
1194 SingleImport(target, source) => {
1196 self.resolve_single_import(&*module_,
1205 self.resolve_glob_import(&*module_,
1214 // Decrement the count of unresolved imports.
1215 match resolution_result {
1217 assert!(self.unresolved_imports >= 1);
1218 self.unresolved_imports -= 1;
1221 // Nothing to do here; just return the error.
1225 // Decrement the count of unresolved globs if necessary. But only if
1226 // the resolution result is indeterminate -- otherwise we'll stop
1227 // processing imports here. (See the loop in
1228 // resolve_imports_for_module.)
1230 if !resolution_result.indeterminate() {
1231 match import_directive.subclass {
1233 assert!(module_.glob_count.get() >= 1);
1234 module_.glob_count.set(module_.glob_count.get() - 1);
1236 SingleImport(..) => {
1242 return resolution_result;
1245 fn create_name_bindings_from_module(module: Rc<Module>) -> NameBindings {
1247 type_def: RefCell::new(Some(TypeNsDef {
1248 modifiers: IMPORTABLE,
1249 module_def: Some(module),
1253 value_def: RefCell::new(None),
1257 fn resolve_single_import(&mut self,
1259 containing_module: Rc<Module>,
1262 directive: &ImportDirective,
1264 -> ResolveResult<()> {
1265 debug!("(resolving single import) resolving `{}` = `{}::{}` from \
1266 `{}` id {}, last private {:?}",
1267 token::get_name(target),
1268 self.module_to_string(&*containing_module),
1269 token::get_name(source),
1270 self.module_to_string(module_),
1276 LastImport {..} => {
1278 .span_bug(directive.span,
1279 "not expecting Import here, must be LastMod")
1283 // We need to resolve both namespaces for this to succeed.
1286 let mut value_result = UnknownResult;
1287 let mut type_result = UnknownResult;
1289 // Search for direct children of the containing module.
1290 build_reduced_graph::populate_module_if_necessary(self, &containing_module);
1292 match containing_module.children.borrow().get(&source) {
1296 Some(ref child_name_bindings) => {
1297 if child_name_bindings.defined_in_namespace(ValueNS) {
1298 debug!("(resolving single import) found value binding");
1299 value_result = BoundResult(containing_module.clone(),
1300 (*child_name_bindings).clone());
1302 if child_name_bindings.defined_in_namespace(TypeNS) {
1303 debug!("(resolving single import) found type binding");
1304 type_result = BoundResult(containing_module.clone(),
1305 (*child_name_bindings).clone());
1310 // Unless we managed to find a result in both namespaces (unlikely),
1311 // search imports as well.
1312 let mut value_used_reexport = false;
1313 let mut type_used_reexport = false;
1314 match (value_result.clone(), type_result.clone()) {
1315 (BoundResult(..), BoundResult(..)) => {} // Continue.
1317 // If there is an unresolved glob at this point in the
1318 // containing module, bail out. We don't know enough to be
1319 // able to resolve this import.
1321 if containing_module.glob_count.get() > 0 {
1322 debug!("(resolving single import) unresolved glob; \
1324 return Indeterminate;
1327 // Now search the exported imports within the containing module.
1328 match containing_module.import_resolutions.borrow().get(&source) {
1330 debug!("(resolving single import) no import");
1331 // The containing module definitely doesn't have an
1332 // exported import with the name in question. We can
1333 // therefore accurately report that the names are
1336 if value_result.is_unknown() {
1337 value_result = UnboundResult;
1339 if type_result.is_unknown() {
1340 type_result = UnboundResult;
1343 Some(import_resolution)
1344 if import_resolution.outstanding_references == 0 => {
1346 fn get_binding(this: &mut Resolver,
1347 import_resolution: &ImportResolution,
1348 namespace: Namespace,
1350 -> NamespaceResult {
1352 // Import resolutions must be declared with "pub"
1353 // in order to be exported.
1354 if !import_resolution.is_public {
1355 return UnboundResult;
1358 match import_resolution.
1359 target_for_namespace(namespace) {
1361 return UnboundResult;
1368 debug!("(resolving single import) found \
1369 import in ns {:?}", namespace);
1370 let id = import_resolution.id(namespace);
1371 // track used imports and extern crates as well
1372 this.used_imports.insert((id, namespace));
1373 this.record_import_use(id, *source);
1374 match target_module.def_id.get() {
1375 Some(DefId{krate: kid, ..}) => {
1376 this.used_crates.insert(kid);
1380 return BoundResult(target_module, bindings);
1385 // The name is an import which has been fully
1386 // resolved. We can, therefore, just follow it.
1387 if value_result.is_unknown() {
1388 value_result = get_binding(self,
1392 value_used_reexport = import_resolution.is_public;
1394 if type_result.is_unknown() {
1395 type_result = get_binding(self,
1399 type_used_reexport = import_resolution.is_public;
1404 // If containing_module is the same module whose import we are resolving
1405 // and there it has an unresolved import with the same name as `source`,
1406 // then the user is actually trying to import an item that is declared
1407 // in the same scope
1410 // use self::submodule;
1411 // pub mod submodule;
1413 // In this case we continue as if we resolved the import and let the
1414 // check_for_conflicts_between_imports_and_items call below handle
1416 match (module_.def_id.get(), containing_module.def_id.get()) {
1417 (Some(id1), Some(id2)) if id1 == id2 => {
1418 if value_result.is_unknown() {
1419 value_result = UnboundResult;
1421 if type_result.is_unknown() {
1422 type_result = UnboundResult;
1426 // The import is unresolved. Bail out.
1427 debug!("(resolving single import) unresolved import; \
1429 return Indeterminate;
1437 // If we didn't find a result in the type namespace, search the
1438 // external modules.
1439 let mut value_used_public = false;
1440 let mut type_used_public = false;
1442 BoundResult(..) => {}
1444 match containing_module.external_module_children.borrow_mut()
1445 .get(&source).cloned() {
1446 None => {} // Continue.
1448 debug!("(resolving single import) found external \
1450 // track the module as used.
1451 match module.def_id.get() {
1452 Some(DefId{krate: kid, ..}) => { self.used_crates.insert(kid); },
1456 Rc::new(Resolver::create_name_bindings_from_module(
1458 type_result = BoundResult(containing_module.clone(),
1460 type_used_public = true;
1466 // We've successfully resolved the import. Write the results in.
1467 let mut import_resolutions = module_.import_resolutions.borrow_mut();
1468 let import_resolution = &mut (*import_resolutions)[target];
1470 let mut check_and_write_import = |&mut: namespace, result: &_, used_public: &mut bool| {
1471 let namespace_name = match namespace {
1477 BoundResult(ref target_module, ref name_bindings) => {
1478 debug!("(resolving single import) found {:?} target: {:?}",
1480 name_bindings.def_for_namespace(namespace));
1481 self.check_for_conflicting_import(
1482 &import_resolution.target_for_namespace(namespace),
1487 self.check_that_import_is_importable(
1493 let target = Some(Target::new(target_module.clone(),
1494 name_bindings.clone(),
1495 directive.shadowable));
1496 import_resolution.set_target_and_id(namespace, target, directive.id);
1497 import_resolution.is_public = directive.is_public;
1498 *used_public = name_bindings.defined_in_public_namespace(namespace);
1500 UnboundResult => { /* Continue. */ }
1502 panic!("{:?} result should be known at this point", namespace_name);
1506 check_and_write_import(ValueNS, &value_result, &mut value_used_public);
1507 check_and_write_import(TypeNS, &type_result, &mut type_used_public);
1510 self.check_for_conflicts_between_imports_and_items(
1516 if value_result.is_unbound() && type_result.is_unbound() {
1517 let msg = format!("There is no `{}` in `{}`",
1518 token::get_name(source),
1519 self.module_to_string(&*containing_module));
1520 return Failed(Some((directive.span, msg)));
1522 let value_used_public = value_used_reexport || value_used_public;
1523 let type_used_public = type_used_reexport || type_used_public;
1525 assert!(import_resolution.outstanding_references >= 1);
1526 import_resolution.outstanding_references -= 1;
1528 // record what this import resolves to for later uses in documentation,
1529 // this may resolve to either a value or a type, but for documentation
1530 // purposes it's good enough to just favor one over the other.
1531 let value_private = match import_resolution.value_target {
1532 Some(ref target) => {
1533 let def = target.bindings.def_for_namespace(ValueNS).unwrap();
1534 self.def_map.borrow_mut().insert(directive.id, def);
1535 let did = def.def_id();
1536 if value_used_public {Some(lp)} else {Some(DependsOn(did))}
1538 // AllPublic here and below is a dummy value, it should never be used because
1539 // _exists is false.
1542 let type_private = match import_resolution.type_target {
1543 Some(ref target) => {
1544 let def = target.bindings.def_for_namespace(TypeNS).unwrap();
1545 self.def_map.borrow_mut().insert(directive.id, def);
1546 let did = def.def_id();
1547 if type_used_public {Some(lp)} else {Some(DependsOn(did))}
1552 self.last_private.insert(directive.id, LastImport{value_priv: value_private,
1554 type_priv: type_private,
1557 debug!("(resolving single import) successfully resolved import");
1561 // Resolves a glob import. Note that this function cannot fail; it either
1562 // succeeds or bails out (as importing * from an empty module or a module
1563 // that exports nothing is valid). containing_module is the module we are
1564 // actually importing, i.e., `foo` in `use foo::*`.
1565 fn resolve_glob_import(&mut self,
1567 containing_module: Rc<Module>,
1568 import_directive: &ImportDirective,
1570 -> ResolveResult<()> {
1571 let id = import_directive.id;
1572 let is_public = import_directive.is_public;
1574 // This function works in a highly imperative manner; it eagerly adds
1575 // everything it can to the list of import resolutions of the module
1577 debug!("(resolving glob import) resolving glob import {}", id);
1579 // We must bail out if the node has unresolved imports of any kind
1580 // (including globs).
1581 if !(*containing_module).all_imports_resolved() {
1582 debug!("(resolving glob import) target module has unresolved \
1583 imports; bailing out");
1584 return Indeterminate;
1587 assert_eq!(containing_module.glob_count.get(), 0);
1589 // Add all resolved imports from the containing module.
1590 let import_resolutions = containing_module.import_resolutions.borrow();
1591 for (ident, target_import_resolution) in import_resolutions.iter() {
1592 debug!("(resolving glob import) writing module resolution \
1594 token::get_name(*ident),
1595 self.module_to_string(module_));
1597 if !target_import_resolution.is_public {
1598 debug!("(resolving glob import) nevermind, just kidding");
1602 // Here we merge two import resolutions.
1603 let mut import_resolutions = module_.import_resolutions.borrow_mut();
1604 match import_resolutions.get_mut(ident) {
1605 Some(dest_import_resolution) => {
1606 // Merge the two import resolutions at a finer-grained
1609 match target_import_resolution.value_target {
1613 Some(ref value_target) => {
1614 self.check_for_conflicting_import(&dest_import_resolution.value_target,
1615 import_directive.span,
1618 dest_import_resolution.value_target = Some(value_target.clone());
1621 match target_import_resolution.type_target {
1625 Some(ref type_target) => {
1626 self.check_for_conflicting_import(&dest_import_resolution.type_target,
1627 import_directive.span,
1630 dest_import_resolution.type_target = Some(type_target.clone());
1633 dest_import_resolution.is_public = is_public;
1639 // Simple: just copy the old import resolution.
1640 let mut new_import_resolution = ImportResolution::new(id, is_public);
1641 new_import_resolution.value_target =
1642 target_import_resolution.value_target.clone();
1643 new_import_resolution.type_target =
1644 target_import_resolution.type_target.clone();
1646 import_resolutions.insert(*ident, new_import_resolution);
1649 // Add all children from the containing module.
1650 build_reduced_graph::populate_module_if_necessary(self, &containing_module);
1652 for (&name, name_bindings) in containing_module.children.borrow().iter() {
1653 self.merge_import_resolution(module_,
1654 containing_module.clone(),
1657 name_bindings.clone());
1661 // Add external module children from the containing module.
1662 for (&name, module) in containing_module.external_module_children.borrow().iter() {
1664 Rc::new(Resolver::create_name_bindings_from_module(module.clone()));
1665 self.merge_import_resolution(module_,
1666 containing_module.clone(),
1672 // Record the destination of this import
1673 match containing_module.def_id.get() {
1675 self.def_map.borrow_mut().insert(id, DefMod(did));
1676 self.last_private.insert(id, lp);
1681 debug!("(resolving glob import) successfully resolved import");
1685 fn merge_import_resolution(&mut self,
1687 containing_module: Rc<Module>,
1688 import_directive: &ImportDirective,
1690 name_bindings: Rc<NameBindings>) {
1691 let id = import_directive.id;
1692 let is_public = import_directive.is_public;
1694 let mut import_resolutions = module_.import_resolutions.borrow_mut();
1695 let dest_import_resolution = import_resolutions.entry(name).get().unwrap_or_else(
1697 // Create a new import resolution from this child.
1698 vacant_entry.insert(ImportResolution::new(id, is_public))
1701 debug!("(resolving glob import) writing resolution `{}` in `{}` \
1703 token::get_name(name).get(),
1704 self.module_to_string(&*containing_module),
1705 self.module_to_string(module_));
1707 // Merge the child item into the import resolution.
1709 let mut merge_child_item = |&mut : namespace| {
1710 if name_bindings.defined_in_namespace_with(namespace, IMPORTABLE | PUBLIC) {
1711 let namespace_name = match namespace {
1715 debug!("(resolving glob import) ... for {} target", namespace_name);
1716 if dest_import_resolution.shadowable(namespace) == Shadowable::Never {
1717 let msg = format!("a {} named `{}` has already been imported \
1720 token::get_name(name).get());
1721 self.session.span_err(import_directive.span, msg.as_slice());
1723 let target = Target::new(containing_module.clone(),
1724 name_bindings.clone(),
1725 import_directive.shadowable);
1726 dest_import_resolution.set_target_and_id(namespace,
1732 merge_child_item(ValueNS);
1733 merge_child_item(TypeNS);
1736 dest_import_resolution.is_public = is_public;
1738 self.check_for_conflicts_between_imports_and_items(
1740 dest_import_resolution,
1741 import_directive.span,
1745 /// Checks that imported names and items don't have the same name.
1746 fn check_for_conflicting_import(&mut self,
1747 target: &Option<Target>,
1750 namespace: Namespace) {
1751 debug!("check_for_conflicting_import: {}; target exists: {}",
1752 token::get_name(name).get(),
1756 Some(ref target) if target.shadowable != Shadowable::Always => {
1757 let msg = format!("a {} named `{}` has already been imported \
1763 token::get_name(name).get());
1764 self.session.span_err(import_span, &msg[]);
1766 Some(_) | None => {}
1770 /// Checks that an import is actually importable
1771 fn check_that_import_is_importable(&mut self,
1772 name_bindings: &NameBindings,
1775 namespace: Namespace) {
1776 if !name_bindings.defined_in_namespace_with(namespace, IMPORTABLE) {
1777 let msg = format!("`{}` is not directly importable",
1778 token::get_name(name));
1779 self.session.span_err(import_span, &msg[]);
1783 /// Checks that imported names and items don't have the same name.
1784 fn check_for_conflicts_between_imports_and_items(&mut self,
1790 // First, check for conflicts between imports and `extern crate`s.
1791 if module.external_module_children
1793 .contains_key(&name) {
1794 match import_resolution.type_target {
1795 Some(ref target) if target.shadowable != Shadowable::Always => {
1796 let msg = format!("import `{0}` conflicts with imported \
1797 crate in this module \
1798 (maybe you meant `use {0}::*`?)",
1799 token::get_name(name).get());
1800 self.session.span_err(import_span, &msg[]);
1802 Some(_) | None => {}
1806 // Check for item conflicts.
1807 let children = module.children.borrow();
1808 let name_bindings = match children.get(&name) {
1810 // There can't be any conflicts.
1813 Some(ref name_bindings) => (*name_bindings).clone(),
1816 match import_resolution.value_target {
1817 Some(ref target) if target.shadowable != Shadowable::Always => {
1818 if let Some(ref value) = *name_bindings.value_def.borrow() {
1819 let msg = format!("import `{}` conflicts with value \
1821 token::get_name(name).get());
1822 self.session.span_err(import_span, &msg[]);
1823 if let Some(span) = value.value_span {
1824 self.session.span_note(span,
1825 "conflicting value here");
1829 Some(_) | None => {}
1832 match import_resolution.type_target {
1833 Some(ref target) if target.shadowable != Shadowable::Always => {
1834 if let Some(ref ty) = *name_bindings.type_def.borrow() {
1835 match ty.module_def {
1837 let msg = format!("import `{}` conflicts with type in \
1839 token::get_name(name).get());
1840 self.session.span_err(import_span, &msg[]);
1841 if let Some(span) = ty.type_span {
1842 self.session.span_note(span,
1843 "note conflicting type here")
1846 Some(ref module_def) => {
1847 match module_def.kind.get() {
1849 if let Some(span) = ty.type_span {
1850 let msg = format!("inherent implementations \
1851 are only allowed on types \
1852 defined in the current module");
1853 self.session.span_err(span, &msg[]);
1854 self.session.span_note(import_span,
1855 "import from other module here")
1859 let msg = format!("import `{}` conflicts with existing \
1861 token::get_name(name).get());
1862 self.session.span_err(import_span, &msg[]);
1863 if let Some(span) = ty.type_span {
1864 self.session.span_note(span,
1865 "note conflicting module here")
1873 Some(_) | None => {}
1877 /// Checks that the names of external crates don't collide with other
1878 /// external crates.
1879 fn check_for_conflicts_between_external_crates(&self,
1883 if module.external_module_children.borrow().contains_key(&name) {
1886 &format!("an external crate named `{}` has already \
1887 been imported into this module",
1888 token::get_name(name).get())[]);
1892 /// Checks that the names of items don't collide with external crates.
1893 fn check_for_conflicts_between_external_crates_and_items(&self,
1897 if module.external_module_children.borrow().contains_key(&name) {
1900 &format!("the name `{}` conflicts with an external \
1901 crate that has been imported into this \
1903 token::get_name(name).get())[]);
1907 /// Resolves the given module path from the given root `module_`.
1908 fn resolve_module_path_from_root(&mut self,
1909 module_: Rc<Module>,
1910 module_path: &[Name],
1913 name_search_type: NameSearchType,
1915 -> ResolveResult<(Rc<Module>, LastPrivate)> {
1916 fn search_parent_externals(needle: Name, module: &Rc<Module>)
1917 -> Option<Rc<Module>> {
1918 module.external_module_children.borrow()
1919 .get(&needle).cloned()
1920 .map(|_| module.clone())
1922 match module.parent_link.clone() {
1923 ModuleParentLink(parent, _) => {
1924 search_parent_externals(needle,
1925 &parent.upgrade().unwrap())
1932 let mut search_module = module_;
1933 let mut index = index;
1934 let module_path_len = module_path.len();
1935 let mut closest_private = lp;
1937 // Resolve the module part of the path. This does not involve looking
1938 // upward though scope chains; we simply resolve names directly in
1939 // modules as we go.
1940 while index < module_path_len {
1941 let name = module_path[index];
1942 match self.resolve_name_in_module(search_module.clone(),
1948 let segment_name = token::get_name(name);
1949 let module_name = self.module_to_string(&*search_module);
1950 let mut span = span;
1951 let msg = if "???" == &module_name[] {
1952 span.hi = span.lo + Pos::from_uint(segment_name.get().len());
1954 match search_parent_externals(name,
1955 &self.current_module) {
1957 let path_str = self.names_to_string(module_path);
1958 let target_mod_str = self.module_to_string(&*module);
1959 let current_mod_str =
1960 self.module_to_string(&*self.current_module);
1962 let prefix = if target_mod_str == current_mod_str {
1963 "self::".to_string()
1965 format!("{}::", target_mod_str)
1968 format!("Did you mean `{}{}`?", prefix, path_str)
1970 None => format!("Maybe a missing `extern crate {}`?",
1974 format!("Could not find `{}` in `{}`",
1979 return Failed(Some((span, msg)));
1981 Failed(err) => return Failed(err),
1983 debug!("(resolving module path for import) module \
1984 resolution is indeterminate: {}",
1985 token::get_name(name));
1986 return Indeterminate;
1988 Success((target, used_proxy)) => {
1989 // Check to see whether there are type bindings, and, if
1990 // so, whether there is a module within.
1991 match *target.bindings.type_def.borrow() {
1992 Some(ref type_def) => {
1993 match type_def.module_def {
1995 let msg = format!("Not a module `{}`",
1996 token::get_name(name));
1998 return Failed(Some((span, msg)));
2000 Some(ref module_def) => {
2001 search_module = module_def.clone();
2003 // track extern crates for unused_extern_crate lint
2004 if let Some(did) = module_def.def_id.get() {
2005 self.used_crates.insert(did.krate);
2008 // Keep track of the closest
2009 // private module used when
2010 // resolving this import chain.
2011 if !used_proxy && !search_module.is_public {
2012 if let Some(did) = search_module.def_id.get() {
2013 closest_private = LastMod(DependsOn(did));
2020 // There are no type bindings at all.
2021 let msg = format!("Not a module `{}`",
2022 token::get_name(name));
2023 return Failed(Some((span, msg)));
2032 return Success((search_module, closest_private));
2035 /// Attempts to resolve the module part of an import directive or path
2036 /// rooted at the given module.
2038 /// On success, returns the resolved module, and the closest *private*
2039 /// module found to the destination when resolving this path.
2040 fn resolve_module_path(&mut self,
2041 module_: Rc<Module>,
2042 module_path: &[Name],
2043 use_lexical_scope: UseLexicalScopeFlag,
2045 name_search_type: NameSearchType)
2046 -> ResolveResult<(Rc<Module>, LastPrivate)> {
2047 let module_path_len = module_path.len();
2048 assert!(module_path_len > 0);
2050 debug!("(resolving module path for import) processing `{}` rooted at `{}`",
2051 self.names_to_string(module_path),
2052 self.module_to_string(&*module_));
2054 // Resolve the module prefix, if any.
2055 let module_prefix_result = self.resolve_module_prefix(module_.clone(),
2061 match module_prefix_result {
2063 let mpath = self.names_to_string(module_path);
2064 let mpath = &mpath[];
2065 match mpath.rfind(':') {
2067 let msg = format!("Could not find `{}` in `{}`",
2068 // idx +- 1 to account for the
2069 // colons on either side
2070 &mpath[(idx + 1)..],
2071 &mpath[..(idx - 1)]);
2072 return Failed(Some((span, msg)));
2079 Failed(err) => return Failed(err),
2081 debug!("(resolving module path for import) indeterminate; \
2083 return Indeterminate;
2085 Success(NoPrefixFound) => {
2086 // There was no prefix, so we're considering the first element
2087 // of the path. How we handle this depends on whether we were
2088 // instructed to use lexical scope or not.
2089 match use_lexical_scope {
2090 DontUseLexicalScope => {
2091 // This is a crate-relative path. We will start the
2092 // resolution process at index zero.
2093 search_module = self.graph_root.get_module();
2095 last_private = LastMod(AllPublic);
2097 UseLexicalScope => {
2098 // This is not a crate-relative path. We resolve the
2099 // first component of the path in the current lexical
2100 // scope and then proceed to resolve below that.
2101 match self.resolve_module_in_lexical_scope(module_,
2103 Failed(err) => return Failed(err),
2105 debug!("(resolving module path for import) \
2106 indeterminate; bailing");
2107 return Indeterminate;
2109 Success(containing_module) => {
2110 search_module = containing_module;
2112 last_private = LastMod(AllPublic);
2118 Success(PrefixFound(ref containing_module, index)) => {
2119 search_module = containing_module.clone();
2120 start_index = index;
2121 last_private = LastMod(DependsOn(containing_module.def_id
2127 self.resolve_module_path_from_root(search_module,
2135 /// Invariant: This must only be called during main resolution, not during
2136 /// import resolution.
2137 fn resolve_item_in_lexical_scope(&mut self,
2138 module_: Rc<Module>,
2140 namespace: Namespace)
2141 -> ResolveResult<(Target, bool)> {
2142 debug!("(resolving item in lexical scope) resolving `{}` in \
2143 namespace {:?} in `{}`",
2144 token::get_name(name),
2146 self.module_to_string(&*module_));
2148 // The current module node is handled specially. First, check for
2149 // its immediate children.
2150 build_reduced_graph::populate_module_if_necessary(self, &module_);
2152 match module_.children.borrow().get(&name) {
2154 if name_bindings.defined_in_namespace(namespace) => {
2155 debug!("top name bindings succeeded");
2156 return Success((Target::new(module_.clone(),
2157 name_bindings.clone(),
2161 Some(_) | None => { /* Not found; continue. */ }
2164 // Now check for its import directives. We don't have to have resolved
2165 // all its imports in the usual way; this is because chains of
2166 // adjacent import statements are processed as though they mutated the
2168 if let Some(import_resolution) = module_.import_resolutions.borrow().get(&name) {
2169 match (*import_resolution).target_for_namespace(namespace) {
2171 // Not found; continue.
2172 debug!("(resolving item in lexical scope) found \
2173 import resolution, but not in namespace {:?}",
2177 debug!("(resolving item in lexical scope) using \
2178 import resolution");
2179 // track used imports and extern crates as well
2180 let id = import_resolution.id(namespace);
2181 self.used_imports.insert((id, namespace));
2182 self.record_import_use(id, name);
2183 if let Some(DefId{krate: kid, ..}) = target.target_module.def_id.get() {
2184 self.used_crates.insert(kid);
2186 return Success((target, false));
2191 // Search for external modules.
2192 if namespace == TypeNS {
2193 if let Some(module) = module_.external_module_children.borrow().get(&name).cloned() {
2195 Rc::new(Resolver::create_name_bindings_from_module(module));
2196 debug!("lower name bindings succeeded");
2197 return Success((Target::new(module_,
2204 // Finally, proceed up the scope chain looking for parent modules.
2205 let mut search_module = module_;
2207 // Go to the next parent.
2208 match search_module.parent_link.clone() {
2210 // No more parents. This module was unresolved.
2211 debug!("(resolving item in lexical scope) unresolved \
2213 return Failed(None);
2215 ModuleParentLink(parent_module_node, _) => {
2216 match search_module.kind.get() {
2217 NormalModuleKind => {
2218 // We stop the search here.
2219 debug!("(resolving item in lexical \
2220 scope) unresolved module: not \
2221 searching through module \
2223 return Failed(None);
2229 AnonymousModuleKind => {
2230 search_module = parent_module_node.upgrade().unwrap();
2234 BlockParentLink(ref parent_module_node, _) => {
2235 search_module = parent_module_node.upgrade().unwrap();
2239 // Resolve the name in the parent module.
2240 match self.resolve_name_in_module(search_module.clone(),
2245 Failed(Some((span, msg))) =>
2246 self.resolve_error(span, &format!("failed to resolve. {}",
2248 Failed(None) => (), // Continue up the search chain.
2250 // We couldn't see through the higher scope because of an
2251 // unresolved import higher up. Bail.
2253 debug!("(resolving item in lexical scope) indeterminate \
2254 higher scope; bailing");
2255 return Indeterminate;
2257 Success((target, used_reexport)) => {
2258 // We found the module.
2259 debug!("(resolving item in lexical scope) found name \
2261 return Success((target, used_reexport));
2267 /// Resolves a module name in the current lexical scope.
2268 fn resolve_module_in_lexical_scope(&mut self,
2269 module_: Rc<Module>,
2271 -> ResolveResult<Rc<Module>> {
2272 // If this module is an anonymous module, resolve the item in the
2273 // lexical scope. Otherwise, resolve the item from the crate root.
2274 let resolve_result = self.resolve_item_in_lexical_scope(module_, name, TypeNS);
2275 match resolve_result {
2276 Success((target, _)) => {
2277 let bindings = &*target.bindings;
2278 match *bindings.type_def.borrow() {
2279 Some(ref type_def) => {
2280 match type_def.module_def {
2282 debug!("!!! (resolving module in lexical \
2283 scope) module wasn't actually a \
2285 return Failed(None);
2287 Some(ref module_def) => {
2288 return Success(module_def.clone());
2293 debug!("!!! (resolving module in lexical scope) module
2294 wasn't actually a module!");
2295 return Failed(None);
2300 debug!("(resolving module in lexical scope) indeterminate; \
2302 return Indeterminate;
2305 debug!("(resolving module in lexical scope) failed to resolve");
2311 /// Returns the nearest normal module parent of the given module.
2312 fn get_nearest_normal_module_parent(&mut self, module_: Rc<Module>)
2313 -> Option<Rc<Module>> {
2314 let mut module_ = module_;
2316 match module_.parent_link.clone() {
2317 NoParentLink => return None,
2318 ModuleParentLink(new_module, _) |
2319 BlockParentLink(new_module, _) => {
2320 let new_module = new_module.upgrade().unwrap();
2321 match new_module.kind.get() {
2322 NormalModuleKind => return Some(new_module),
2327 AnonymousModuleKind => module_ = new_module,
2334 /// Returns the nearest normal module parent of the given module, or the
2335 /// module itself if it is a normal module.
2336 fn get_nearest_normal_module_parent_or_self(&mut self, module_: Rc<Module>)
2338 match module_.kind.get() {
2339 NormalModuleKind => return module_,
2344 AnonymousModuleKind => {
2345 match self.get_nearest_normal_module_parent(module_.clone()) {
2347 Some(new_module) => new_module
2353 /// Resolves a "module prefix". A module prefix is one or both of (a) `self::`;
2354 /// (b) some chain of `super::`.
2355 /// grammar: (SELF MOD_SEP ) ? (SUPER MOD_SEP) *
2356 fn resolve_module_prefix(&mut self,
2357 module_: Rc<Module>,
2358 module_path: &[Name])
2359 -> ResolveResult<ModulePrefixResult> {
2360 // Start at the current module if we see `self` or `super`, or at the
2361 // top of the crate otherwise.
2362 let mut containing_module;
2364 let first_module_path_string = token::get_name(module_path[0]);
2365 if "self" == first_module_path_string.get() {
2367 self.get_nearest_normal_module_parent_or_self(module_);
2369 } else if "super" == first_module_path_string.get() {
2371 self.get_nearest_normal_module_parent_or_self(module_);
2372 i = 0; // We'll handle `super` below.
2374 return Success(NoPrefixFound);
2377 // Now loop through all the `super`s we find.
2378 while i < module_path.len() {
2379 let string = token::get_name(module_path[i]);
2380 if "super" != string.get() {
2383 debug!("(resolving module prefix) resolving `super` at {}",
2384 self.module_to_string(&*containing_module));
2385 match self.get_nearest_normal_module_parent(containing_module) {
2386 None => return Failed(None),
2387 Some(new_module) => {
2388 containing_module = new_module;
2394 debug!("(resolving module prefix) finished resolving prefix at {}",
2395 self.module_to_string(&*containing_module));
2397 return Success(PrefixFound(containing_module, i));
2400 /// Attempts to resolve the supplied name in the given module for the
2401 /// given namespace. If successful, returns the target corresponding to
2404 /// The boolean returned on success is an indicator of whether this lookup
2405 /// passed through a public re-export proxy.
2406 fn resolve_name_in_module(&mut self,
2407 module_: Rc<Module>,
2409 namespace: Namespace,
2410 name_search_type: NameSearchType,
2411 allow_private_imports: bool)
2412 -> ResolveResult<(Target, bool)> {
2413 debug!("(resolving name in module) resolving `{}` in `{}`",
2414 token::get_name(name).get(),
2415 self.module_to_string(&*module_));
2417 // First, check the direct children of the module.
2418 build_reduced_graph::populate_module_if_necessary(self, &module_);
2420 match module_.children.borrow().get(&name) {
2422 if name_bindings.defined_in_namespace(namespace) => {
2423 debug!("(resolving name in module) found node as child");
2424 return Success((Target::new(module_.clone(),
2425 name_bindings.clone(),
2434 // Next, check the module's imports if necessary.
2436 // If this is a search of all imports, we should be done with glob
2437 // resolution at this point.
2438 if name_search_type == PathSearch {
2439 assert_eq!(module_.glob_count.get(), 0);
2442 // Check the list of resolved imports.
2443 match module_.import_resolutions.borrow().get(&name) {
2444 Some(import_resolution) if allow_private_imports ||
2445 import_resolution.is_public => {
2447 if import_resolution.is_public &&
2448 import_resolution.outstanding_references != 0 {
2449 debug!("(resolving name in module) import \
2450 unresolved; bailing out");
2451 return Indeterminate;
2453 match import_resolution.target_for_namespace(namespace) {
2455 debug!("(resolving name in module) name found, \
2456 but not in namespace {:?}",
2460 debug!("(resolving name in module) resolved to \
2462 // track used imports and extern crates as well
2463 let id = import_resolution.id(namespace);
2464 self.used_imports.insert((id, namespace));
2465 self.record_import_use(id, name);
2466 if let Some(DefId{krate: kid, ..}) = target.target_module.def_id.get() {
2467 self.used_crates.insert(kid);
2469 return Success((target, true));
2473 Some(..) | None => {} // Continue.
2476 // Finally, search through external children.
2477 if namespace == TypeNS {
2478 if let Some(module) = module_.external_module_children.borrow().get(&name).cloned() {
2480 Rc::new(Resolver::create_name_bindings_from_module(module));
2481 return Success((Target::new(module_,
2488 // We're out of luck.
2489 debug!("(resolving name in module) failed to resolve `{}`",
2490 token::get_name(name).get());
2491 return Failed(None);
2494 fn report_unresolved_imports(&mut self, module_: Rc<Module>) {
2495 let index = module_.resolved_import_count.get();
2496 let imports = module_.imports.borrow();
2497 let import_count = imports.len();
2498 if index != import_count {
2499 let sn = self.session
2501 .span_to_snippet((*imports)[index].span)
2503 if sn.contains("::") {
2504 self.resolve_error((*imports)[index].span,
2505 "unresolved import");
2507 let err = format!("unresolved import (maybe you meant `{}::*`?)",
2509 self.resolve_error((*imports)[index].span, &err[]);
2513 // Descend into children and anonymous children.
2514 build_reduced_graph::populate_module_if_necessary(self, &module_);
2516 for (_, child_node) in module_.children.borrow().iter() {
2517 match child_node.get_module_if_available() {
2521 Some(child_module) => {
2522 self.report_unresolved_imports(child_module);
2527 for (_, module_) in module_.anonymous_children.borrow().iter() {
2528 self.report_unresolved_imports(module_.clone());
2534 // We maintain a list of value ribs and type ribs.
2536 // Simultaneously, we keep track of the current position in the module
2537 // graph in the `current_module` pointer. When we go to resolve a name in
2538 // the value or type namespaces, we first look through all the ribs and
2539 // then query the module graph. When we resolve a name in the module
2540 // namespace, we can skip all the ribs (since nested modules are not
2541 // allowed within blocks in Rust) and jump straight to the current module
2544 // Named implementations are handled separately. When we find a method
2545 // call, we consult the module node to find all of the implementations in
2546 // scope. This information is lazily cached in the module node. We then
2547 // generate a fake "implementation scope" containing all the
2548 // implementations thus found, for compatibility with old resolve pass.
2550 fn with_scope<F>(&mut self, name: Option<Name>, f: F) where
2551 F: FnOnce(&mut Resolver),
2553 let orig_module = self.current_module.clone();
2555 // Move down in the graph.
2561 build_reduced_graph::populate_module_if_necessary(self, &orig_module);
2563 match orig_module.children.borrow().get(&name) {
2565 debug!("!!! (with scope) didn't find `{}` in `{}`",
2566 token::get_name(name),
2567 self.module_to_string(&*orig_module));
2569 Some(name_bindings) => {
2570 match (*name_bindings).get_module_if_available() {
2572 debug!("!!! (with scope) didn't find module \
2574 token::get_name(name),
2575 self.module_to_string(&*orig_module));
2578 self.current_module = module_;
2588 self.current_module = orig_module;
2591 /// Wraps the given definition in the appropriate number of `DefUpvar`
2597 -> Option<DefLike> {
2599 DlDef(d @ DefUpvar(..)) => {
2600 self.session.span_bug(span,
2601 &format!("unexpected {:?} in bindings", d)[])
2603 DlDef(d @ DefLocal(_)) => {
2604 let node_id = d.def_id().node;
2606 let mut last_proc_body_id = ast::DUMMY_NODE_ID;
2607 for rib in ribs.iter() {
2610 // Nothing to do. Continue.
2612 ClosureRibKind(function_id, maybe_proc_body) => {
2614 if maybe_proc_body != ast::DUMMY_NODE_ID {
2615 last_proc_body_id = maybe_proc_body;
2617 def = DefUpvar(node_id, function_id, last_proc_body_id);
2619 let mut seen = self.freevars_seen.borrow_mut();
2620 let seen = match seen.entry(function_id) {
2621 Occupied(v) => v.into_mut(),
2622 Vacant(v) => v.insert(NodeSet()),
2624 if seen.contains(&node_id) {
2627 match self.freevars.borrow_mut().entry(function_id) {
2628 Occupied(v) => v.into_mut(),
2629 Vacant(v) => v.insert(vec![]),
2630 }.push(Freevar { def: prev_def, span: span });
2631 seen.insert(node_id);
2633 MethodRibKind(item_id, _) => {
2634 // If the def is a ty param, and came from the parent
2637 DefTyParam(_, _, did, _) if {
2638 self.def_map.borrow().get(&did.node).cloned()
2639 == Some(DefTyParamBinder(item_id))
2641 DefSelfTy(did) if did == item_id => {} // ok
2643 // This was an attempt to access an upvar inside a
2644 // named function item. This is not allowed, so we
2649 "can't capture dynamic environment in a fn item; \
2650 use the || { ... } closure form instead");
2657 // This was an attempt to access an upvar inside a
2658 // named function item. This is not allowed, so we
2663 "can't capture dynamic environment in a fn item; \
2664 use the || { ... } closure form instead");
2668 ConstantItemRibKind => {
2669 // Still doesn't deal with upvars
2670 self.resolve_error(span,
2671 "attempt to use a non-constant \
2672 value in a constant");
2679 DlDef(def @ DefTyParam(..)) |
2680 DlDef(def @ DefSelfTy(..)) => {
2681 for rib in ribs.iter() {
2683 NormalRibKind | ClosureRibKind(..) => {
2684 // Nothing to do. Continue.
2686 MethodRibKind(item_id, _) => {
2687 // If the def is a ty param, and came from the parent
2690 DefTyParam(_, _, did, _) if {
2691 self.def_map.borrow().get(&did.node).cloned()
2692 == Some(DefTyParamBinder(item_id))
2694 DefSelfTy(did) if did == item_id => {} // ok
2697 // This was an attempt to use a type parameter outside
2700 self.resolve_error(span,
2701 "can't use type parameters from \
2702 outer function; try using a local \
2703 type parameter instead");
2710 // This was an attempt to use a type parameter outside
2713 self.resolve_error(span,
2714 "can't use type parameters from \
2715 outer function; try using a local \
2716 type parameter instead");
2720 ConstantItemRibKind => {
2722 self.resolve_error(span,
2723 "cannot use an outer type \
2724 parameter in this context");
2735 /// Searches the current set of local scopes and
2736 /// applies translations for closures.
2737 fn search_ribs(&self,
2741 -> Option<DefLike> {
2742 // FIXME #4950: Try caching?
2744 for (i, rib) in ribs.iter().enumerate().rev() {
2745 match rib.bindings.get(&name).cloned() {
2747 return self.upvarify(&ribs[(i + 1)..], def_like, span);
2758 /// Searches the current set of local scopes for labels.
2759 /// Stops after meeting a closure.
2760 fn search_label(&self, name: Name) -> Option<DefLike> {
2761 for rib in self.label_ribs.iter().rev() {
2767 // Do not resolve labels across function boundary
2771 let result = rib.bindings.get(&name).cloned();
2772 if result.is_some() {
2779 fn resolve_crate(&mut self, krate: &ast::Crate) {
2780 debug!("(resolving crate) starting");
2782 visit::walk_crate(self, krate);
2785 fn resolve_item(&mut self, item: &Item) {
2786 let name = item.ident.name;
2788 debug!("(resolving item) resolving {}",
2789 token::get_name(name));
2793 // enum item: resolve all the variants' discrs,
2794 // then resolve the ty params
2795 ItemEnum(ref enum_def, ref generics) => {
2796 for variant in (*enum_def).variants.iter() {
2797 for dis_expr in variant.node.disr_expr.iter() {
2798 // resolve the discriminator expr
2800 self.with_constant_rib(|this| {
2801 this.resolve_expr(&**dis_expr);
2806 // n.b. the discr expr gets visited twice.
2807 // but maybe it's okay since the first time will signal an
2808 // error if there is one? -- tjc
2809 self.with_type_parameter_rib(HasTypeParameters(generics,
2814 this.resolve_type_parameters(&generics.ty_params);
2815 this.resolve_where_clause(&generics.where_clause);
2816 visit::walk_item(this, item);
2820 ItemTy(_, ref generics) => {
2821 self.with_type_parameter_rib(HasTypeParameters(generics,
2826 this.resolve_type_parameters(&generics.ty_params);
2827 visit::walk_item(this, item);
2833 ref implemented_traits,
2835 ref impl_items) => {
2836 self.resolve_implementation(item.id,
2843 ItemTrait(_, ref generics, ref bounds, ref trait_items) => {
2844 // Create a new rib for the self type.
2845 let mut self_type_rib = Rib::new(ItemRibKind);
2847 // plain insert (no renaming, types are not currently hygienic....)
2848 let name = self.type_self_name;
2849 self_type_rib.bindings.insert(name, DlDef(DefSelfTy(item.id)));
2850 self.type_ribs.push(self_type_rib);
2852 // Create a new rib for the trait-wide type parameters.
2853 self.with_type_parameter_rib(HasTypeParameters(generics,
2858 this.resolve_type_parameters(&generics.ty_params);
2859 this.resolve_where_clause(&generics.where_clause);
2861 this.resolve_type_parameter_bounds(item.id, bounds,
2864 for trait_item in (*trait_items).iter() {
2865 // Create a new rib for the trait_item-specific type
2868 // FIXME #4951: Do we need a node ID here?
2871 ast::RequiredMethod(ref ty_m) => {
2872 this.with_type_parameter_rib
2873 (HasTypeParameters(&ty_m.generics,
2876 MethodRibKind(item.id, RequiredMethod)),
2879 // Resolve the method-specific type
2881 this.resolve_type_parameters(
2882 &ty_m.generics.ty_params);
2883 this.resolve_where_clause(&ty_m.generics
2886 for argument in ty_m.decl.inputs.iter() {
2887 this.resolve_type(&*argument.ty);
2890 if let SelfExplicit(ref typ, _) = ty_m.explicit_self.node {
2891 this.resolve_type(&**typ)
2894 if let ast::Return(ref ret_ty) = ty_m.decl.output {
2895 this.resolve_type(&**ret_ty);
2899 ast::ProvidedMethod(ref m) => {
2900 this.resolve_method(MethodRibKind(item.id,
2901 ProvidedMethod(m.id)),
2904 ast::TypeTraitItem(ref data) => {
2905 this.resolve_type_parameter(&data.ty_param);
2906 visit::walk_trait_item(this, trait_item);
2912 self.type_ribs.pop();
2915 ItemStruct(ref struct_def, ref generics) => {
2916 self.resolve_struct(item.id,
2918 &struct_def.fields[]);
2921 ItemMod(ref module_) => {
2922 self.with_scope(Some(name), |this| {
2923 this.resolve_module(module_, item.span, name,
2928 ItemForeignMod(ref foreign_module) => {
2929 self.with_scope(Some(name), |this| {
2930 for foreign_item in foreign_module.items.iter() {
2931 match foreign_item.node {
2932 ForeignItemFn(_, ref generics) => {
2933 this.with_type_parameter_rib(
2935 generics, FnSpace, foreign_item.id,
2938 this.resolve_type_parameters(&generics.ty_params);
2939 this.resolve_where_clause(&generics.where_clause);
2940 visit::walk_foreign_item(this, &**foreign_item)
2943 ForeignItemStatic(..) => {
2944 visit::walk_foreign_item(this,
2952 ItemFn(ref fn_decl, _, _, ref generics, ref block) => {
2953 self.resolve_function(ItemRibKind,
2963 ItemConst(..) | ItemStatic(..) => {
2964 self.with_constant_rib(|this| {
2965 visit::walk_item(this, item);
2969 ItemExternCrate(_) | ItemUse(_) | ItemMac(..) => {
2970 // do nothing, these are just around to be encoded
2975 fn with_type_parameter_rib<F>(&mut self, type_parameters: TypeParameters, f: F) where
2976 F: FnOnce(&mut Resolver),
2978 match type_parameters {
2979 HasTypeParameters(generics, space, node_id, rib_kind) => {
2980 let mut function_type_rib = Rib::new(rib_kind);
2981 let mut seen_bindings = HashSet::new();
2982 for (index, type_parameter) in generics.ty_params.iter().enumerate() {
2983 let name = type_parameter.ident.name;
2984 debug!("with_type_parameter_rib: {} {}", node_id,
2987 if seen_bindings.contains(&name) {
2988 self.resolve_error(type_parameter.span,
2989 &format!("the name `{}` is already \
2991 parameter in this type \
2996 seen_bindings.insert(name);
2998 let def_like = DlDef(DefTyParam(space,
3000 local_def(type_parameter.id),
3002 // Associate this type parameter with
3003 // the item that bound it
3004 self.record_def(type_parameter.id,
3005 (DefTyParamBinder(node_id), LastMod(AllPublic)));
3006 // plain insert (no renaming)
3007 function_type_rib.bindings.insert(name, def_like);
3009 self.type_ribs.push(function_type_rib);
3012 NoTypeParameters => {
3019 match type_parameters {
3020 HasTypeParameters(..) => { self.type_ribs.pop(); }
3021 NoTypeParameters => { }
3025 fn with_label_rib<F>(&mut self, f: F) where
3026 F: FnOnce(&mut Resolver),
3028 self.label_ribs.push(Rib::new(NormalRibKind));
3030 self.label_ribs.pop();
3033 fn with_constant_rib<F>(&mut self, f: F) where
3034 F: FnOnce(&mut Resolver),
3036 self.value_ribs.push(Rib::new(ConstantItemRibKind));
3037 self.type_ribs.push(Rib::new(ConstantItemRibKind));
3039 self.type_ribs.pop();
3040 self.value_ribs.pop();
3043 fn resolve_function(&mut self,
3045 optional_declaration: Option<&FnDecl>,
3046 type_parameters: TypeParameters,
3048 // Create a value rib for the function.
3049 let function_value_rib = Rib::new(rib_kind);
3050 self.value_ribs.push(function_value_rib);
3052 // Create a label rib for the function.
3053 let function_label_rib = Rib::new(rib_kind);
3054 self.label_ribs.push(function_label_rib);
3056 // If this function has type parameters, add them now.
3057 self.with_type_parameter_rib(type_parameters, |this| {
3058 // Resolve the type parameters.
3059 match type_parameters {
3060 NoTypeParameters => {
3063 HasTypeParameters(ref generics, _, _, _) => {
3064 this.resolve_type_parameters(&generics.ty_params);
3065 this.resolve_where_clause(&generics.where_clause);
3069 // Add each argument to the rib.
3070 match optional_declaration {
3074 Some(declaration) => {
3075 let mut bindings_list = HashMap::new();
3076 for argument in declaration.inputs.iter() {
3077 this.resolve_pattern(&*argument.pat,
3078 ArgumentIrrefutableMode,
3079 &mut bindings_list);
3081 this.resolve_type(&*argument.ty);
3083 debug!("(resolving function) recorded argument");
3086 if let ast::Return(ref ret_ty) = declaration.output {
3087 this.resolve_type(&**ret_ty);
3092 // Resolve the function body.
3093 this.resolve_block(&*block);
3095 debug!("(resolving function) leaving function");
3098 self.label_ribs.pop();
3099 self.value_ribs.pop();
3102 fn resolve_type_parameters(&mut self,
3103 type_parameters: &OwnedSlice<TyParam>) {
3104 for type_parameter in type_parameters.iter() {
3105 self.resolve_type_parameter(type_parameter);
3109 fn resolve_type_parameter(&mut self,
3110 type_parameter: &TyParam) {
3111 for bound in type_parameter.bounds.iter() {
3112 self.resolve_type_parameter_bound(type_parameter.id, bound,
3113 TraitBoundingTypeParameter);
3115 match type_parameter.default {
3116 Some(ref ty) => self.resolve_type(&**ty),
3121 fn resolve_type_parameter_bounds(&mut self,
3123 type_parameter_bounds: &OwnedSlice<TyParamBound>,
3124 reference_type: TraitReferenceType) {
3125 for type_parameter_bound in type_parameter_bounds.iter() {
3126 self.resolve_type_parameter_bound(id, type_parameter_bound,
3131 fn resolve_type_parameter_bound(&mut self,
3133 type_parameter_bound: &TyParamBound,
3134 reference_type: TraitReferenceType) {
3135 match *type_parameter_bound {
3136 TraitTyParamBound(ref tref, _) => {
3137 self.resolve_poly_trait_reference(id, tref, reference_type)
3139 RegionTyParamBound(..) => {}
3143 fn resolve_poly_trait_reference(&mut self,
3145 poly_trait_reference: &PolyTraitRef,
3146 reference_type: TraitReferenceType) {
3147 self.resolve_trait_reference(id, &poly_trait_reference.trait_ref, reference_type)
3150 fn resolve_trait_reference(&mut self,
3152 trait_reference: &TraitRef,
3153 reference_type: TraitReferenceType) {
3154 match self.resolve_path(id, &trait_reference.path, TypeNS, true) {
3156 let path_str = self.path_names_to_string(&trait_reference.path);
3157 let usage_str = match reference_type {
3158 TraitBoundingTypeParameter => "bound type parameter with",
3159 TraitImplementation => "implement",
3160 TraitDerivation => "derive",
3161 TraitObject => "reference",
3162 TraitQPath => "extract an associated item from",
3165 let msg = format!("attempt to {} a nonexistent trait `{}`", usage_str, path_str);
3166 self.resolve_error(trait_reference.path.span, &msg[]);
3170 (DefTrait(_), _) => {
3171 debug!("(resolving trait) found trait def: {:?}", def);
3172 self.record_def(trait_reference.ref_id, def);
3175 self.resolve_error(trait_reference.path.span,
3176 &format!("`{}` is not a trait",
3177 self.path_names_to_string(
3178 &trait_reference.path))[]);
3180 // If it's a typedef, give a note
3181 if let DefTy(..) = def {
3182 self.session.span_note(
3183 trait_reference.path.span,
3184 &format!("`type` aliases cannot be used for traits")
3193 fn resolve_where_clause(&mut self, where_clause: &ast::WhereClause) {
3194 for predicate in where_clause.predicates.iter() {
3196 &ast::WherePredicate::BoundPredicate(ref bound_pred) => {
3197 self.resolve_type(&*bound_pred.bounded_ty);
3199 for bound in bound_pred.bounds.iter() {
3200 self.resolve_type_parameter_bound(bound_pred.bounded_ty.id, bound,
3201 TraitBoundingTypeParameter);
3204 &ast::WherePredicate::RegionPredicate(_) => {}
3205 &ast::WherePredicate::EqPredicate(ref eq_pred) => {
3206 match self.resolve_path(eq_pred.id, &eq_pred.path, TypeNS, true) {
3207 Some((def @ DefTyParam(..), last_private)) => {
3208 self.record_def(eq_pred.id, (def, last_private));
3211 self.resolve_error(eq_pred.path.span,
3212 "undeclared associated type");
3216 self.resolve_type(&*eq_pred.ty);
3222 fn resolve_struct(&mut self,
3224 generics: &Generics,
3225 fields: &[StructField]) {
3226 // If applicable, create a rib for the type parameters.
3227 self.with_type_parameter_rib(HasTypeParameters(generics,
3232 // Resolve the type parameters.
3233 this.resolve_type_parameters(&generics.ty_params);
3234 this.resolve_where_clause(&generics.where_clause);
3237 for field in fields.iter() {
3238 this.resolve_type(&*field.node.ty);
3243 // Does this really need to take a RibKind or is it always going
3244 // to be NormalRibKind?
3245 fn resolve_method(&mut self,
3247 method: &ast::Method) {
3248 let method_generics = method.pe_generics();
3249 let type_parameters = HasTypeParameters(method_generics,
3254 if let SelfExplicit(ref typ, _) = method.pe_explicit_self().node {
3255 self.resolve_type(&**typ);
3258 self.resolve_function(rib_kind,
3259 Some(method.pe_fn_decl()),
3264 fn with_current_self_type<T, F>(&mut self, self_type: &Ty, f: F) -> T where
3265 F: FnOnce(&mut Resolver) -> T,
3267 // Handle nested impls (inside fn bodies)
3268 let previous_value = replace(&mut self.current_self_type, Some(self_type.clone()));
3269 let result = f(self);
3270 self.current_self_type = previous_value;
3274 fn with_optional_trait_ref<T, F>(&mut self, id: NodeId,
3275 opt_trait_ref: &Option<TraitRef>,
3277 F: FnOnce(&mut Resolver) -> T,
3279 let new_val = match *opt_trait_ref {
3280 Some(ref trait_ref) => {
3281 self.resolve_trait_reference(id, trait_ref, TraitImplementation);
3283 match self.def_map.borrow().get(&trait_ref.ref_id) {
3285 let did = def.def_id();
3286 Some((did, trait_ref.clone()))
3293 let original_trait_ref = replace(&mut self.current_trait_ref, new_val);
3294 let result = f(self);
3295 self.current_trait_ref = original_trait_ref;
3299 fn resolve_implementation(&mut self,
3301 generics: &Generics,
3302 opt_trait_reference: &Option<TraitRef>,
3304 impl_items: &[ImplItem]) {
3305 // If applicable, create a rib for the type parameters.
3306 self.with_type_parameter_rib(HasTypeParameters(generics,
3311 // Resolve the type parameters.
3312 this.resolve_type_parameters(&generics.ty_params);
3313 this.resolve_where_clause(&generics.where_clause);
3315 // Resolve the trait reference, if necessary.
3316 this.with_optional_trait_ref(id, opt_trait_reference, |this| {
3317 // Resolve the self type.
3318 this.resolve_type(self_type);
3320 this.with_current_self_type(self_type, |this| {
3321 for impl_item in impl_items.iter() {
3323 MethodImplItem(ref method) => {
3324 // If this is a trait impl, ensure the method
3326 this.check_trait_item(method.pe_ident().name,
3329 // We also need a new scope for the method-
3330 // specific type parameters.
3331 this.resolve_method(
3332 MethodRibKind(id, ProvidedMethod(method.id)),
3335 TypeImplItem(ref typedef) => {
3336 // If this is a trait impl, ensure the method
3338 this.check_trait_item(typedef.ident.name,
3341 this.resolve_type(&*typedef.typ);
3349 // Check that the current type is indeed a type, if we have an anonymous impl
3350 if opt_trait_reference.is_none() {
3351 match self_type.node {
3352 // TyPath is the only thing that we handled in `build_reduced_graph_for_item`,
3353 // where we created a module with the name of the type in order to implement
3354 // an anonymous trait. In the case that the path does not resolve to an actual
3355 // type, the result will be that the type name resolves to a module but not
3356 // a type (shadowing any imported modules or types with this name), leading
3357 // to weird user-visible bugs. So we ward this off here. See #15060.
3358 TyPath(ref path, path_id) => {
3359 match self.def_map.borrow().get(&path_id) {
3360 // FIXME: should we catch other options and give more precise errors?
3361 Some(&DefMod(_)) => {
3362 self.resolve_error(path.span, "inherent implementations are not \
3363 allowed for types not defined in \
3364 the current module");
3374 fn check_trait_item(&self, name: Name, span: Span) {
3375 // If there is a TraitRef in scope for an impl, then the method must be in the trait.
3376 for &(did, ref trait_ref) in self.current_trait_ref.iter() {
3377 if self.trait_item_map.get(&(name, did)).is_none() {
3378 let path_str = self.path_names_to_string(&trait_ref.path);
3379 self.resolve_error(span,
3380 &format!("method `{}` is not a member of trait `{}`",
3381 token::get_name(name),
3387 fn resolve_module(&mut self, module: &Mod, _span: Span,
3388 _name: Name, id: NodeId) {
3389 // Write the implementations in scope into the module metadata.
3390 debug!("(resolving module) resolving module ID {}", id);
3391 visit::walk_mod(self, module);
3394 fn resolve_local(&mut self, local: &Local) {
3395 // Resolve the type.
3396 if let Some(ref ty) = local.ty {
3397 self.resolve_type(&**ty);
3400 // Resolve the initializer, if necessary.
3405 Some(ref initializer) => {
3406 self.resolve_expr(&**initializer);
3410 // Resolve the pattern.
3411 let mut bindings_list = HashMap::new();
3412 self.resolve_pattern(&*local.pat,
3413 LocalIrrefutableMode,
3414 &mut bindings_list);
3417 // build a map from pattern identifiers to binding-info's.
3418 // this is done hygienically. This could arise for a macro
3419 // that expands into an or-pattern where one 'x' was from the
3420 // user and one 'x' came from the macro.
3421 fn binding_mode_map(&mut self, pat: &Pat) -> BindingMap {
3422 let mut result = HashMap::new();
3423 pat_bindings(&self.def_map, pat, |binding_mode, _id, sp, path1| {
3424 let name = mtwt::resolve(path1.node);
3425 result.insert(name, BindingInfo {
3427 binding_mode: binding_mode
3433 // check that all of the arms in an or-pattern have exactly the
3434 // same set of bindings, with the same binding modes for each.
3435 fn check_consistent_bindings(&mut self, arm: &Arm) {
3436 if arm.pats.len() == 0 {
3439 let map_0 = self.binding_mode_map(&*arm.pats[0]);
3440 for (i, p) in arm.pats.iter().enumerate() {
3441 let map_i = self.binding_mode_map(&**p);
3443 for (&key, &binding_0) in map_0.iter() {
3444 match map_i.get(&key) {
3448 &format!("variable `{}` from pattern #1 is \
3449 not bound in pattern #{}",
3450 token::get_name(key),
3453 Some(binding_i) => {
3454 if binding_0.binding_mode != binding_i.binding_mode {
3457 &format!("variable `{}` is bound with different \
3458 mode in pattern #{} than in pattern #1",
3459 token::get_name(key),
3466 for (&key, &binding) in map_i.iter() {
3467 if !map_0.contains_key(&key) {
3470 &format!("variable `{}` from pattern {}{} is \
3471 not bound in pattern {}1",
3472 token::get_name(key),
3473 "#", i + 1, "#")[]);
3479 fn resolve_arm(&mut self, arm: &Arm) {
3480 self.value_ribs.push(Rib::new(NormalRibKind));
3482 let mut bindings_list = HashMap::new();
3483 for pattern in arm.pats.iter() {
3484 self.resolve_pattern(&**pattern, RefutableMode, &mut bindings_list);
3487 // This has to happen *after* we determine which
3488 // pat_idents are variants
3489 self.check_consistent_bindings(arm);
3491 visit::walk_expr_opt(self, &arm.guard);
3492 self.resolve_expr(&*arm.body);
3494 self.value_ribs.pop();
3497 fn resolve_block(&mut self, block: &Block) {
3498 debug!("(resolving block) entering block");
3499 self.value_ribs.push(Rib::new(NormalRibKind));
3501 // Move down in the graph, if there's an anonymous module rooted here.
3502 let orig_module = self.current_module.clone();
3503 match orig_module.anonymous_children.borrow().get(&block.id) {
3504 None => { /* Nothing to do. */ }
3505 Some(anonymous_module) => {
3506 debug!("(resolving block) found anonymous module, moving \
3508 self.current_module = anonymous_module.clone();
3512 // Descend into the block.
3513 visit::walk_block(self, block);
3516 self.current_module = orig_module;
3518 self.value_ribs.pop();
3519 debug!("(resolving block) leaving block");
3522 fn resolve_type(&mut self, ty: &Ty) {
3524 // Like path expressions, the interpretation of path types depends
3525 // on whether the path has multiple elements in it or not.
3527 TyPath(ref path, path_id) => {
3528 // This is a path in the type namespace. Walk through scopes
3530 let mut result_def = None;
3532 // First, check to see whether the name is a primitive type.
3533 if path.segments.len() == 1 {
3534 let id = path.segments.last().unwrap().identifier;
3536 match self.primitive_type_table
3540 Some(&primitive_type) => {
3542 Some((DefPrimTy(primitive_type), LastMod(AllPublic)));
3544 if path.segments[0].parameters.has_lifetimes() {
3545 span_err!(self.session, path.span, E0157,
3546 "lifetime parameters are not allowed on this type");
3547 } else if !path.segments[0].parameters.is_empty() {
3548 span_err!(self.session, path.span, E0153,
3549 "type parameters are not allowed on this type");
3558 if let None = result_def {
3559 result_def = self.resolve_path(ty.id, path, TypeNS, true);
3564 // Write the result into the def map.
3565 debug!("(resolving type) writing resolution for `{}` \
3567 self.path_names_to_string(path),
3569 self.record_def(path_id, def);
3572 let msg = format!("use of undeclared type name `{}`",
3573 self.path_names_to_string(path));
3574 self.resolve_error(ty.span, &msg[]);
3579 TyObjectSum(ref ty, ref bound_vec) => {
3580 self.resolve_type(&**ty);
3581 self.resolve_type_parameter_bounds(ty.id, bound_vec,
3582 TraitBoundingTypeParameter);
3585 TyQPath(ref qpath) => {
3586 self.resolve_type(&*qpath.self_type);
3587 self.resolve_trait_reference(ty.id, &*qpath.trait_ref, TraitQPath);
3588 for ty in qpath.item_path.parameters.types().into_iter() {
3589 self.resolve_type(&**ty);
3591 for binding in qpath.item_path.parameters.bindings().into_iter() {
3592 self.resolve_type(&*binding.ty);
3596 TyPolyTraitRef(ref bounds) => {
3597 self.resolve_type_parameter_bounds(
3601 visit::walk_ty(self, ty);
3604 // Just resolve embedded types.
3605 visit::walk_ty(self, ty);
3610 fn resolve_pattern(&mut self,
3612 mode: PatternBindingMode,
3613 // Maps idents to the node ID for the (outermost)
3614 // pattern that binds them
3615 bindings_list: &mut HashMap<Name, NodeId>) {
3616 let pat_id = pattern.id;
3617 walk_pat(pattern, |pattern| {
3618 match pattern.node {
3619 PatIdent(binding_mode, ref path1, _) => {
3621 // The meaning of pat_ident with no type parameters
3622 // depends on whether an enum variant or unit-like struct
3623 // with that name is in scope. The probing lookup has to
3624 // be careful not to emit spurious errors. Only matching
3625 // patterns (match) can match nullary variants or
3626 // unit-like structs. For binding patterns (let), matching
3627 // such a value is simply disallowed (since it's rarely
3630 let ident = path1.node;
3631 let renamed = mtwt::resolve(ident);
3633 match self.resolve_bare_identifier_pattern(ident.name, pattern.span) {
3634 FoundStructOrEnumVariant(ref def, lp)
3635 if mode == RefutableMode => {
3636 debug!("(resolving pattern) resolving `{}` to \
3637 struct or enum variant",
3638 token::get_name(renamed));
3640 self.enforce_default_binding_mode(
3644 self.record_def(pattern.id, (def.clone(), lp));
3646 FoundStructOrEnumVariant(..) => {
3649 &format!("declaration of `{}` shadows an enum \
3650 variant or unit-like struct in \
3652 token::get_name(renamed))[]);
3654 FoundConst(ref def, lp) if mode == RefutableMode => {
3655 debug!("(resolving pattern) resolving `{}` to \
3657 token::get_name(renamed));
3659 self.enforce_default_binding_mode(
3663 self.record_def(pattern.id, (def.clone(), lp));
3666 self.resolve_error(pattern.span,
3667 "only irrefutable patterns \
3670 BareIdentifierPatternUnresolved => {
3671 debug!("(resolving pattern) binding `{}`",
3672 token::get_name(renamed));
3674 let def = DefLocal(pattern.id);
3676 // Record the definition so that later passes
3677 // will be able to distinguish variants from
3678 // locals in patterns.
3680 self.record_def(pattern.id, (def, LastMod(AllPublic)));
3682 // Add the binding to the local ribs, if it
3683 // doesn't already exist in the bindings list. (We
3684 // must not add it if it's in the bindings list
3685 // because that breaks the assumptions later
3686 // passes make about or-patterns.)
3687 if !bindings_list.contains_key(&renamed) {
3688 let this = &mut *self;
3689 let last_rib = this.value_ribs.last_mut().unwrap();
3690 last_rib.bindings.insert(renamed, DlDef(def));
3691 bindings_list.insert(renamed, pat_id);
3692 } else if mode == ArgumentIrrefutableMode &&
3693 bindings_list.contains_key(&renamed) {
3694 // Forbid duplicate bindings in the same
3696 self.resolve_error(pattern.span,
3697 &format!("identifier `{}` \
3705 } else if bindings_list.get(&renamed) ==
3707 // Then this is a duplicate variable in the
3708 // same disjunction, which is an error.
3709 self.resolve_error(pattern.span,
3710 &format!("identifier `{}` is bound \
3711 more than once in the same \
3713 token::get_ident(ident))[]);
3715 // Else, not bound in the same pattern: do
3721 PatEnum(ref path, _) => {
3722 // This must be an enum variant, struct or const.
3723 match self.resolve_path(pat_id, path, ValueNS, false) {
3724 Some(def @ (DefVariant(..), _)) |
3725 Some(def @ (DefStruct(..), _)) |
3726 Some(def @ (DefConst(..), _)) => {
3727 self.record_def(pattern.id, def);
3729 Some((DefStatic(..), _)) => {
3730 self.resolve_error(path.span,
3731 "static variables cannot be \
3732 referenced in a pattern, \
3733 use a `const` instead");
3736 self.resolve_error(path.span,
3737 format!("`{}` is not an enum variant, struct or const",
3739 path.segments.last().unwrap().identifier)).as_slice());
3742 self.resolve_error(path.span,
3743 format!("unresolved enum variant, struct or const `{}`",
3745 path.segments.last().unwrap().identifier)).as_slice());
3749 // Check the types in the path pattern.
3750 for ty in path.segments
3752 .flat_map(|s| s.parameters.types().into_iter()) {
3753 self.resolve_type(&**ty);
3757 PatLit(ref expr) => {
3758 self.resolve_expr(&**expr);
3761 PatRange(ref first_expr, ref last_expr) => {
3762 self.resolve_expr(&**first_expr);
3763 self.resolve_expr(&**last_expr);
3766 PatStruct(ref path, _, _) => {
3767 match self.resolve_path(pat_id, path, TypeNS, false) {
3768 Some(definition) => {
3769 self.record_def(pattern.id, definition);
3772 debug!("(resolving pattern) didn't find struct \
3773 def: {:?}", result);
3774 let msg = format!("`{}` does not name a structure",
3775 self.path_names_to_string(path));
3776 self.resolve_error(path.span, &msg[]);
3789 fn resolve_bare_identifier_pattern(&mut self, name: Name, span: Span)
3790 -> BareIdentifierPatternResolution {
3791 let module = self.current_module.clone();
3792 match self.resolve_item_in_lexical_scope(module,
3795 Success((target, _)) => {
3796 debug!("(resolve bare identifier pattern) succeeded in \
3797 finding {} at {:?}",
3798 token::get_name(name),
3799 target.bindings.value_def.borrow());
3800 match *target.bindings.value_def.borrow() {
3802 panic!("resolved name in the value namespace to a \
3803 set of name bindings with no def?!");
3806 // For the two success cases, this lookup can be
3807 // considered as not having a private component because
3808 // the lookup happened only within the current module.
3810 def @ DefVariant(..) | def @ DefStruct(..) => {
3811 return FoundStructOrEnumVariant(def, LastMod(AllPublic));
3813 def @ DefConst(..) => {
3814 return FoundConst(def, LastMod(AllPublic));
3817 self.resolve_error(span,
3818 "static variables cannot be \
3819 referenced in a pattern, \
3820 use a `const` instead");
3821 return BareIdentifierPatternUnresolved;
3824 return BareIdentifierPatternUnresolved;
3832 panic!("unexpected indeterminate result");
3836 Some((span, msg)) => {
3837 self.resolve_error(span, &format!("failed to resolve: {}",
3843 debug!("(resolve bare identifier pattern) failed to find {}",
3844 token::get_name(name));
3845 return BareIdentifierPatternUnresolved;
3850 /// If `check_ribs` is true, checks the local definitions first; i.e.
3851 /// doesn't skip straight to the containing module.
3852 fn resolve_path(&mut self,
3855 namespace: Namespace,
3856 check_ribs: bool) -> Option<(Def, LastPrivate)> {
3857 // First, resolve the types and associated type bindings.
3858 for ty in path.segments.iter().flat_map(|s| s.parameters.types().into_iter()) {
3859 self.resolve_type(&**ty);
3861 for binding in path.segments.iter().flat_map(|s| s.parameters.bindings().into_iter()) {
3862 self.resolve_type(&*binding.ty);
3865 // A special case for sugared associated type paths `T::A` where `T` is
3866 // a type parameter and `A` is an associated type on some bound of `T`.
3867 if namespace == TypeNS && path.segments.len() == 2 {
3868 match self.resolve_identifier(path.segments[0].identifier,
3872 Some((def, last_private)) => {
3874 DefTyParam(_, _, did, _) => {
3875 let def = DefAssociatedPath(TyParamProvenance::FromParam(did),
3876 path.segments.last()
3877 .unwrap().identifier);
3878 return Some((def, last_private));
3881 let def = DefAssociatedPath(TyParamProvenance::FromSelf(local_def(nid)),
3882 path.segments.last()
3883 .unwrap().identifier);
3884 return Some((def, last_private));
3894 return self.resolve_crate_relative_path(path, namespace);
3897 // Try to find a path to an item in a module.
3898 let unqualified_def =
3899 self.resolve_identifier(path.segments.last().unwrap().identifier,
3904 if path.segments.len() > 1 {
3905 let def = self.resolve_module_relative_path(path, namespace);
3906 match (def, unqualified_def) {
3907 (Some((ref d, _)), Some((ref ud, _))) if *d == *ud => {
3909 .add_lint(lint::builtin::UNUSED_QUALIFICATIONS,
3912 "unnecessary qualification".to_string());
3920 return unqualified_def;
3923 // resolve a single identifier (used as a varref)
3924 fn resolve_identifier(&mut self,
3926 namespace: Namespace,
3929 -> Option<(Def, LastPrivate)> {
3931 match self.resolve_identifier_in_local_ribs(identifier,
3935 return Some((def, LastMod(AllPublic)));
3943 return self.resolve_item_by_name_in_lexical_scope(identifier.name, namespace);
3946 // FIXME #4952: Merge me with resolve_name_in_module?
3947 fn resolve_definition_of_name_in_module(&mut self,
3948 containing_module: Rc<Module>,
3950 namespace: Namespace)
3952 // First, search children.
3953 build_reduced_graph::populate_module_if_necessary(self, &containing_module);
3955 match containing_module.children.borrow().get(&name) {
3956 Some(child_name_bindings) => {
3957 match child_name_bindings.def_for_namespace(namespace) {
3959 // Found it. Stop the search here.
3960 let p = child_name_bindings.defined_in_public_namespace(
3962 let lp = if p {LastMod(AllPublic)} else {
3963 LastMod(DependsOn(def.def_id()))
3965 return ChildNameDefinition(def, lp);
3973 // Next, search import resolutions.
3974 match containing_module.import_resolutions.borrow().get(&name) {
3975 Some(import_resolution) if import_resolution.is_public => {
3976 if let Some(target) = (*import_resolution).target_for_namespace(namespace) {
3977 match target.bindings.def_for_namespace(namespace) {
3980 let id = import_resolution.id(namespace);
3981 // track imports and extern crates as well
3982 self.used_imports.insert((id, namespace));
3983 self.record_import_use(id, name);
3984 match target.target_module.def_id.get() {
3985 Some(DefId{krate: kid, ..}) => {
3986 self.used_crates.insert(kid);
3990 return ImportNameDefinition(def, LastMod(AllPublic));
3993 // This can happen with external impls, due to
3994 // the imperfect way we read the metadata.
3999 Some(..) | None => {} // Continue.
4002 // Finally, search through external children.
4003 if namespace == TypeNS {
4004 if let Some(module) = containing_module.external_module_children.borrow()
4005 .get(&name).cloned() {
4006 if let Some(def_id) = module.def_id.get() {
4007 // track used crates
4008 self.used_crates.insert(def_id.krate);
4009 let lp = if module.is_public {LastMod(AllPublic)} else {
4010 LastMod(DependsOn(def_id))
4012 return ChildNameDefinition(DefMod(def_id), lp);
4017 return NoNameDefinition;
4020 // resolve a "module-relative" path, e.g. a::b::c
4021 fn resolve_module_relative_path(&mut self,
4023 namespace: Namespace)
4024 -> Option<(Def, LastPrivate)> {
4025 let module_path = path.segments.init().iter()
4026 .map(|ps| ps.identifier.name)
4027 .collect::<Vec<_>>();
4029 let containing_module;
4031 let module = self.current_module.clone();
4032 match self.resolve_module_path(module,
4038 let (span, msg) = match err {
4039 Some((span, msg)) => (span, msg),
4041 let msg = format!("Use of undeclared type or module `{}`",
4042 self.names_to_string(module_path.as_slice()));
4047 self.resolve_error(span, &format!("failed to resolve. {}",
4051 Indeterminate => panic!("indeterminate unexpected"),
4052 Success((resulting_module, resulting_last_private)) => {
4053 containing_module = resulting_module;
4054 last_private = resulting_last_private;
4058 let name = path.segments.last().unwrap().identifier.name;
4059 let def = match self.resolve_definition_of_name_in_module(containing_module.clone(),
4062 NoNameDefinition => {
4063 // We failed to resolve the name. Report an error.
4066 ChildNameDefinition(def, lp) | ImportNameDefinition(def, lp) => {
4067 (def, last_private.or(lp))
4070 if let Some(DefId{krate: kid, ..}) = containing_module.def_id.get() {
4071 self.used_crates.insert(kid);
4076 /// Invariant: This must be called only during main resolution, not during
4077 /// import resolution.
4078 fn resolve_crate_relative_path(&mut self,
4080 namespace: Namespace)
4081 -> Option<(Def, LastPrivate)> {
4082 let module_path = path.segments.init().iter()
4083 .map(|ps| ps.identifier.name)
4084 .collect::<Vec<_>>();
4086 let root_module = self.graph_root.get_module();
4088 let containing_module;
4090 match self.resolve_module_path_from_root(root_module,
4095 LastMod(AllPublic)) {
4097 let (span, msg) = match err {
4098 Some((span, msg)) => (span, msg),
4100 let msg = format!("Use of undeclared module `::{}`",
4101 self.names_to_string(&module_path[]));
4106 self.resolve_error(span, &format!("failed to resolve. {}",
4112 panic!("indeterminate unexpected");
4115 Success((resulting_module, resulting_last_private)) => {
4116 containing_module = resulting_module;
4117 last_private = resulting_last_private;
4121 let name = path.segments.last().unwrap().identifier.name;
4122 match self.resolve_definition_of_name_in_module(containing_module,
4125 NoNameDefinition => {
4126 // We failed to resolve the name. Report an error.
4129 ChildNameDefinition(def, lp) | ImportNameDefinition(def, lp) => {
4130 return Some((def, last_private.or(lp)));
4135 fn resolve_identifier_in_local_ribs(&mut self,
4137 namespace: Namespace,
4140 // Check the local set of ribs.
4141 let search_result = match namespace {
4143 let renamed = mtwt::resolve(ident);
4144 self.search_ribs(self.value_ribs.as_slice(), renamed, span)
4147 let name = ident.name;
4148 self.search_ribs(&self.type_ribs[], name, span)
4152 match search_result {
4153 Some(DlDef(def)) => {
4154 debug!("(resolving path in local ribs) resolved `{}` to \
4156 token::get_ident(ident),
4160 Some(DlField) | Some(DlImpl(_)) | None => {
4166 fn resolve_item_by_name_in_lexical_scope(&mut self,
4168 namespace: Namespace)
4169 -> Option<(Def, LastPrivate)> {
4171 let module = self.current_module.clone();
4172 match self.resolve_item_in_lexical_scope(module,
4175 Success((target, _)) => {
4176 match (*target.bindings).def_for_namespace(namespace) {
4178 // This can happen if we were looking for a type and
4179 // found a module instead. Modules don't have defs.
4180 debug!("(resolving item path by identifier in lexical \
4181 scope) failed to resolve {} after success...",
4182 token::get_name(name));
4186 debug!("(resolving item path in lexical scope) \
4187 resolved `{}` to item",
4188 token::get_name(name));
4189 // This lookup is "all public" because it only searched
4190 // for one identifier in the current module (couldn't
4191 // have passed through reexports or anything like that.
4192 return Some((def, LastMod(AllPublic)));
4197 panic!("unexpected indeterminate result");
4201 Some((span, msg)) =>
4202 self.resolve_error(span, &format!("failed to resolve. {}",
4207 debug!("(resolving item path by identifier in lexical scope) \
4208 failed to resolve {}", token::get_name(name));
4214 fn with_no_errors<T, F>(&mut self, f: F) -> T where
4215 F: FnOnce(&mut Resolver) -> T,
4217 self.emit_errors = false;
4219 self.emit_errors = true;
4223 fn resolve_error(&self, span: Span, s: &str) {
4224 if self.emit_errors {
4225 self.session.span_err(span, s);
4229 fn find_fallback_in_self_type(&mut self, name: Name) -> FallbackSuggestion {
4230 fn extract_path_and_node_id(t: &Ty, allow: FallbackChecks)
4231 -> Option<(Path, NodeId, FallbackChecks)> {
4233 TyPath(ref path, node_id) => Some((path.clone(), node_id, allow)),
4234 TyPtr(ref mut_ty) => extract_path_and_node_id(&*mut_ty.ty, OnlyTraitAndStatics),
4235 TyRptr(_, ref mut_ty) => extract_path_and_node_id(&*mut_ty.ty, allow),
4236 // This doesn't handle the remaining `Ty` variants as they are not
4237 // that commonly the self_type, it might be interesting to provide
4238 // support for those in future.
4243 fn get_module(this: &mut Resolver, span: Span, name_path: &[ast::Name])
4244 -> Option<Rc<Module>> {
4245 let root = this.current_module.clone();
4246 let last_name = name_path.last().unwrap();
4248 if name_path.len() == 1 {
4249 match this.primitive_type_table.primitive_types.get(last_name) {
4252 match this.current_module.children.borrow().get(last_name) {
4253 Some(child) => child.get_module_if_available(),
4259 match this.resolve_module_path(root,
4264 Success((module, _)) => Some(module),
4270 let (path, node_id, allowed) = match self.current_self_type {
4271 Some(ref ty) => match extract_path_and_node_id(ty, Everything) {
4273 None => return NoSuggestion,
4275 None => return NoSuggestion,
4278 if allowed == Everything {
4279 // Look for a field with the same name in the current self_type.
4280 match self.def_map.borrow().get(&node_id) {
4281 Some(&DefTy(did, _))
4282 | Some(&DefStruct(did))
4283 | Some(&DefVariant(_, did, _)) => match self.structs.get(&did) {
4286 if fields.iter().any(|&field_name| name == field_name) {
4291 _ => {} // Self type didn't resolve properly
4295 let name_path = path.segments.iter().map(|seg| seg.identifier.name).collect::<Vec<_>>();
4297 // Look for a method in the current self type's impl module.
4298 match get_module(self, path.span, &name_path[]) {
4299 Some(module) => match module.children.borrow().get(&name) {
4301 let p_str = self.path_names_to_string(&path);
4302 match binding.def_for_namespace(ValueNS) {
4303 Some(DefStaticMethod(_, provenance)) => {
4305 FromImpl(_) => return StaticMethod(p_str),
4306 FromTrait(_) => unreachable!()
4309 Some(DefMethod(_, None, _)) if allowed == Everything => return Method,
4310 Some(DefMethod(_, Some(_), _)) => return TraitItem,
4319 // Look for a method in the current trait.
4320 match self.current_trait_ref {
4321 Some((did, ref trait_ref)) => {
4322 let path_str = self.path_names_to_string(&trait_ref.path);
4324 match self.trait_item_map.get(&(name, did)) {
4325 Some(&StaticMethodTraitItemKind) => {
4326 return TraitMethod(path_str)
4328 Some(_) => return TraitItem,
4338 fn find_best_match_for_name(&mut self, name: &str, max_distance: uint)
4340 let this = &mut *self;
4342 let mut maybes: Vec<token::InternedString> = Vec::new();
4343 let mut values: Vec<uint> = Vec::new();
4345 for rib in this.value_ribs.iter().rev() {
4346 for (&k, _) in rib.bindings.iter() {
4347 maybes.push(token::get_name(k));
4348 values.push(uint::MAX);
4352 let mut smallest = 0;
4353 for (i, other) in maybes.iter().enumerate() {
4354 values[i] = lev_distance(name, other.get());
4356 if values[i] <= values[smallest] {
4361 if values.len() > 0 &&
4362 values[smallest] != uint::MAX &&
4363 values[smallest] < name.len() + 2 &&
4364 values[smallest] <= max_distance &&
4365 name != maybes[smallest].get() {
4367 Some(maybes[smallest].get().to_string())
4374 fn resolve_expr(&mut self, expr: &Expr) {
4375 // First, record candidate traits for this expression if it could
4376 // result in the invocation of a method call.
4378 self.record_candidate_traits_for_expr_if_necessary(expr);
4380 // Next, resolve the node.
4382 // The interpretation of paths depends on whether the path has
4383 // multiple elements in it or not.
4385 ExprPath(_) | ExprQPath(_) => {
4386 let mut path_from_qpath;
4387 let path = match expr.node {
4388 ExprPath(ref path) => path,
4389 ExprQPath(ref qpath) => {
4390 self.resolve_type(&*qpath.self_type);
4391 self.resolve_trait_reference(expr.id, &*qpath.trait_ref, TraitQPath);
4392 path_from_qpath = qpath.trait_ref.path.clone();
4393 path_from_qpath.segments.push(qpath.item_path.clone());
4398 // This is a local path in the value namespace. Walk through
4399 // scopes looking for it.
4400 match self.resolve_path(expr.id, path, ValueNS, true) {
4401 // Check if struct variant
4402 Some((DefVariant(_, _, true), _)) => {
4403 let path_name = self.path_names_to_string(path);
4404 self.resolve_error(expr.span,
4405 format!("`{}` is a struct variant name, but \
4407 uses it like a function name",
4408 path_name).as_slice());
4410 self.session.span_help(expr.span,
4411 format!("Did you mean to write: \
4412 `{} {{ /* fields */ }}`?",
4413 path_name).as_slice());
4416 // Write the result into the def map.
4417 debug!("(resolving expr) resolved `{}`",
4418 self.path_names_to_string(path));
4420 self.record_def(expr.id, def);
4423 // Be helpful if the name refers to a struct
4424 // (The pattern matching def_tys where the id is in self.structs
4425 // matches on regular structs while excluding tuple- and enum-like
4426 // structs, which wouldn't result in this error.)
4427 let path_name = self.path_names_to_string(path);
4428 match self.with_no_errors(|this|
4429 this.resolve_path(expr.id, path, TypeNS, false)) {
4430 Some((DefTy(struct_id, _), _))
4431 if self.structs.contains_key(&struct_id) => {
4432 self.resolve_error(expr.span,
4433 format!("`{}` is a structure name, but \
4435 uses it like a function name",
4436 path_name).as_slice());
4438 self.session.span_help(expr.span,
4439 format!("Did you mean to write: \
4440 `{} {{ /* fields */ }}`?",
4441 path_name).as_slice());
4445 let mut method_scope = false;
4446 self.value_ribs.iter().rev().all(|rib| {
4447 let res = match *rib {
4448 Rib { bindings: _, kind: MethodRibKind(_, _) } => true,
4449 Rib { bindings: _, kind: ItemRibKind } => false,
4450 _ => return true, // Keep advancing
4454 false // Stop advancing
4457 if method_scope && token::get_name(self.self_name).get()
4461 "`self` is not available \
4462 in a static method. Maybe a \
4463 `self` argument is missing?");
4465 let last_name = path.segments.last().unwrap().identifier.name;
4466 let mut msg = match self.find_fallback_in_self_type(last_name) {
4468 // limit search to 5 to reduce the number
4469 // of stupid suggestions
4470 self.find_best_match_for_name(path_name.as_slice(), 5)
4471 .map_or("".to_string(),
4472 |x| format!("`{}`", x))
4475 format!("`self.{}`", path_name),
4478 format!("to call `self.{}`", path_name),
4479 TraitMethod(path_str)
4480 | StaticMethod(path_str) =>
4481 format!("to call `{}::{}`", path_str, path_name)
4485 msg = format!(". Did you mean {}?", msg)
4490 format!("unresolved name `{}`{}",
4499 visit::walk_expr(self, expr);
4502 ExprClosure(capture_clause, _, ref fn_decl, ref block) => {
4503 self.capture_mode_map.insert(expr.id, capture_clause);
4504 self.resolve_function(ClosureRibKind(expr.id, ast::DUMMY_NODE_ID),
4505 Some(&**fn_decl), NoTypeParameters,
4509 ExprStruct(ref path, _, _) => {
4510 // Resolve the path to the structure it goes to. We don't
4511 // check to ensure that the path is actually a structure; that
4512 // is checked later during typeck.
4513 match self.resolve_path(expr.id, path, TypeNS, false) {
4514 Some(definition) => self.record_def(expr.id, definition),
4516 debug!("(resolving expression) didn't find struct \
4517 def: {:?}", result);
4518 let msg = format!("`{}` does not name a structure",
4519 self.path_names_to_string(path));
4520 self.resolve_error(path.span, &msg[]);
4524 visit::walk_expr(self, expr);
4527 ExprLoop(_, Some(label)) | ExprWhile(_, _, Some(label)) => {
4528 self.with_label_rib(|this| {
4529 let def_like = DlDef(DefLabel(expr.id));
4532 let rib = this.label_ribs.last_mut().unwrap();
4533 let renamed = mtwt::resolve(label);
4534 rib.bindings.insert(renamed, def_like);
4537 visit::walk_expr(this, expr);
4541 ExprForLoop(ref pattern, ref head, ref body, optional_label) => {
4542 self.resolve_expr(&**head);
4544 self.value_ribs.push(Rib::new(NormalRibKind));
4546 self.resolve_pattern(&**pattern,
4547 LocalIrrefutableMode,
4548 &mut HashMap::new());
4550 match optional_label {
4554 .push(Rib::new(NormalRibKind));
4555 let def_like = DlDef(DefLabel(expr.id));
4558 let rib = self.label_ribs.last_mut().unwrap();
4559 let renamed = mtwt::resolve(label);
4560 rib.bindings.insert(renamed, def_like);
4565 self.resolve_block(&**body);
4567 if optional_label.is_some() {
4568 drop(self.label_ribs.pop())
4571 self.value_ribs.pop();
4574 ExprBreak(Some(label)) | ExprAgain(Some(label)) => {
4575 let renamed = mtwt::resolve(label);
4576 match self.search_label(renamed) {
4580 &format!("use of undeclared label `{}`",
4581 token::get_ident(label))[])
4583 Some(DlDef(def @ DefLabel(_))) => {
4584 // Since this def is a label, it is never read.
4585 self.record_def(expr.id, (def, LastMod(AllPublic)))
4588 self.session.span_bug(expr.span,
4589 "label wasn't mapped to a \
4596 visit::walk_expr(self, expr);
4601 fn record_candidate_traits_for_expr_if_necessary(&mut self, expr: &Expr) {
4603 ExprField(_, ident) => {
4604 // FIXME(#6890): Even though you can't treat a method like a
4605 // field, we need to add any trait methods we find that match
4606 // the field name so that we can do some nice error reporting
4607 // later on in typeck.
4608 let traits = self.search_for_traits_containing_method(ident.node.name);
4609 self.trait_map.insert(expr.id, traits);
4611 ExprMethodCall(ident, _, _) => {
4612 debug!("(recording candidate traits for expr) recording \
4615 let traits = self.search_for_traits_containing_method(ident.node.name);
4616 self.trait_map.insert(expr.id, traits);
4624 fn search_for_traits_containing_method(&mut self, name: Name) -> Vec<DefId> {
4625 debug!("(searching for traits containing method) looking for '{}'",
4626 token::get_name(name));
4628 fn add_trait_info(found_traits: &mut Vec<DefId>,
4629 trait_def_id: DefId,
4631 debug!("(adding trait info) found trait {}:{} for method '{}'",
4634 token::get_name(name));
4635 found_traits.push(trait_def_id);
4638 let mut found_traits = Vec::new();
4639 let mut search_module = self.current_module.clone();
4641 // Look for the current trait.
4642 match self.current_trait_ref {
4643 Some((trait_def_id, _)) => {
4644 if self.trait_item_map.contains_key(&(name, trait_def_id)) {
4645 add_trait_info(&mut found_traits, trait_def_id, name);
4648 None => {} // Nothing to do.
4651 // Look for trait children.
4652 build_reduced_graph::populate_module_if_necessary(self, &search_module);
4655 for (_, child_names) in search_module.children.borrow().iter() {
4656 let def = match child_names.def_for_namespace(TypeNS) {
4660 let trait_def_id = match def {
4661 DefTrait(trait_def_id) => trait_def_id,
4664 if self.trait_item_map.contains_key(&(name, trait_def_id)) {
4665 add_trait_info(&mut found_traits, trait_def_id, name);
4670 // Look for imports.
4671 for (_, import) in search_module.import_resolutions.borrow().iter() {
4672 let target = match import.target_for_namespace(TypeNS) {
4674 Some(target) => target,
4676 let did = match target.bindings.def_for_namespace(TypeNS) {
4677 Some(DefTrait(trait_def_id)) => trait_def_id,
4678 Some(..) | None => continue,
4680 if self.trait_item_map.contains_key(&(name, did)) {
4681 add_trait_info(&mut found_traits, did, name);
4682 let id = import.type_id;
4683 self.used_imports.insert((id, TypeNS));
4684 let trait_name = self.get_trait_name(did);
4685 self.record_import_use(id, trait_name);
4686 if let Some(DefId{krate: kid, ..}) = target.target_module.def_id.get() {
4687 self.used_crates.insert(kid);
4692 match search_module.parent_link.clone() {
4693 NoParentLink | ModuleParentLink(..) => break,
4694 BlockParentLink(parent_module, _) => {
4695 search_module = parent_module.upgrade().unwrap();
4703 fn record_def(&mut self, node_id: NodeId, (def, lp): (Def, LastPrivate)) {
4704 debug!("(recording def) recording {:?} for {}, last private {:?}",
4706 assert!(match lp {LastImport{..} => false, _ => true},
4707 "Import should only be used for `use` directives");
4708 self.last_private.insert(node_id, lp);
4710 match self.def_map.borrow_mut().entry(node_id) {
4711 // Resolve appears to "resolve" the same ID multiple
4712 // times, so here is a sanity check it at least comes to
4713 // the same conclusion! - nmatsakis
4714 Occupied(entry) => if def != *entry.get() {
4716 .bug(&format!("node_id {} resolved first to {:?} and \
4722 Vacant(entry) => { entry.insert(def); },
4726 fn enforce_default_binding_mode(&mut self,
4728 pat_binding_mode: BindingMode,
4730 match pat_binding_mode {
4731 BindByValue(_) => {}
4733 self.resolve_error(pat.span,
4734 &format!("cannot use `ref` binding mode \
4744 // Diagnostics are not particularly efficient, because they're rarely
4748 /// A somewhat inefficient routine to obtain the name of a module.
4749 fn module_to_string(&self, module: &Module) -> String {
4750 let mut names = Vec::new();
4752 fn collect_mod(names: &mut Vec<ast::Name>, module: &Module) {
4753 match module.parent_link {
4755 ModuleParentLink(ref module, name) => {
4757 collect_mod(names, &*module.upgrade().unwrap());
4759 BlockParentLink(ref module, _) => {
4760 // danger, shouldn't be ident?
4761 names.push(special_idents::opaque.name);
4762 collect_mod(names, &*module.upgrade().unwrap());
4766 collect_mod(&mut names, module);
4768 if names.len() == 0 {
4769 return "???".to_string();
4771 self.names_to_string(&names.into_iter().rev()
4772 .collect::<Vec<ast::Name>>()[])
4775 #[allow(dead_code)] // useful for debugging
4776 fn dump_module(&mut self, module_: Rc<Module>) {
4777 debug!("Dump of module `{}`:", self.module_to_string(&*module_));
4779 debug!("Children:");
4780 build_reduced_graph::populate_module_if_necessary(self, &module_);
4781 for (&name, _) in module_.children.borrow().iter() {
4782 debug!("* {}", token::get_name(name));
4785 debug!("Import resolutions:");
4786 let import_resolutions = module_.import_resolutions.borrow();
4787 for (&name, import_resolution) in import_resolutions.iter() {
4789 match import_resolution.target_for_namespace(ValueNS) {
4790 None => { value_repr = "".to_string(); }
4792 value_repr = " value:?".to_string();
4798 match import_resolution.target_for_namespace(TypeNS) {
4799 None => { type_repr = "".to_string(); }
4801 type_repr = " type:?".to_string();
4806 debug!("* {}:{}{}", token::get_name(name), value_repr, type_repr);
4811 pub struct CrateMap {
4812 pub def_map: DefMap,
4813 pub freevars: RefCell<FreevarMap>,
4814 pub capture_mode_map: RefCell<CaptureModeMap>,
4815 pub export_map: ExportMap,
4816 pub trait_map: TraitMap,
4817 pub external_exports: ExternalExports,
4818 pub last_private_map: LastPrivateMap,
4819 pub glob_map: Option<GlobMap>
4822 #[derive(PartialEq,Copy)]
4823 pub enum MakeGlobMap {
4828 /// Entry point to crate resolution.
4829 pub fn resolve_crate<'a, 'tcx>(session: &'a Session,
4830 ast_map: &'a ast_map::Map<'tcx>,
4833 make_glob_map: MakeGlobMap)
4835 let mut resolver = Resolver::new(session, ast_map, krate.span, make_glob_map);
4837 build_reduced_graph::build_reduced_graph(&mut resolver, krate);
4838 session.abort_if_errors();
4840 resolver.resolve_imports();
4841 session.abort_if_errors();
4843 record_exports::record(&mut resolver);
4844 session.abort_if_errors();
4846 resolver.resolve_crate(krate);
4847 session.abort_if_errors();
4849 check_unused::check_crate(&mut resolver, krate);
4852 def_map: resolver.def_map,
4853 freevars: resolver.freevars,
4854 capture_mode_map: RefCell::new(resolver.capture_mode_map),
4855 export_map: resolver.export_map,
4856 trait_map: resolver.trait_map,
4857 external_exports: resolver.external_exports,
4858 last_private_map: resolver.last_private,
4859 glob_map: if resolver.make_glob_map {
4860 Some(resolver.glob_map)