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)]
24 #[macro_use] extern crate log;
25 #[macro_use] extern crate syntax;
26 #[macro_use] #[no_link] extern crate rustc_bitflags;
30 use self::PatternBindingMode::*;
31 use self::Namespace::*;
32 use self::NamespaceResult::*;
33 use self::NameDefinition::*;
34 use self::ImportDirectiveSubclass::*;
35 use self::ResolveResult::*;
36 use self::FallbackSuggestion::*;
37 use self::TypeParameters::*;
39 use self::MethodSort::*;
40 use self::UseLexicalScopeFlag::*;
41 use self::ModulePrefixResult::*;
42 use self::NameSearchType::*;
43 use self::BareIdentifierPatternResolution::*;
44 use self::ParentLink::*;
45 use self::ModuleKind::*;
46 use self::TraitReferenceType::*;
47 use self::FallbackChecks::*;
49 use rustc::session::Session;
51 use rustc::metadata::csearch;
52 use rustc::metadata::decoder::{DefLike, DlDef, DlField, DlImpl};
53 use rustc::middle::def::*;
54 use rustc::middle::lang_items::LanguageItems;
55 use rustc::middle::pat_util::pat_bindings;
56 use rustc::middle::privacy::*;
57 use rustc::middle::subst::{ParamSpace, FnSpace, TypeSpace};
58 use rustc::middle::ty::{CaptureModeMap, Freevar, FreevarMap, TraitMap, GlobMap};
59 use rustc::util::nodemap::{NodeMap, NodeSet, DefIdSet, FnvHashMap};
60 use rustc::util::lev_distance::lev_distance;
62 use syntax::ast::{Arm, BindByRef, BindByValue, BindingMode, Block, Crate, CrateNum};
63 use syntax::ast::{DefId, Expr, ExprAgain, ExprBreak, ExprField};
64 use syntax::ast::{ExprClosure, ExprForLoop, ExprLoop, ExprWhile, ExprMethodCall};
65 use syntax::ast::{ExprPath, ExprQPath, ExprStruct, FnDecl};
66 use syntax::ast::{ForeignItemFn, ForeignItemStatic, Generics};
67 use syntax::ast::{Ident, ImplItem, Item, ItemConst, ItemEnum, ItemFn};
68 use syntax::ast::{ItemForeignMod, ItemImpl, ItemMac, ItemMod, ItemStatic};
69 use syntax::ast::{ItemStruct, ItemTrait, ItemTy, Local, LOCAL_CRATE};
70 use syntax::ast::{MethodImplItem, Mod, Name, NodeId};
71 use syntax::ast::{Pat, PatEnum, PatIdent, PatLit};
72 use syntax::ast::{PatRange, PatStruct, Path};
73 use syntax::ast::{PolyTraitRef, PrimTy, SelfExplicit};
74 use syntax::ast::{RegionTyParamBound, StructField};
75 use syntax::ast::{TraitRef, TraitTyParamBound};
76 use syntax::ast::{Ty, TyBool, TyChar, TyF32};
77 use syntax::ast::{TyF64, TyFloat, TyIs, TyI8, TyI16, TyI32, TyI64, TyInt, TyObjectSum};
78 use syntax::ast::{TyParam, TyParamBound, TyPath, TyPtr, TyPolyTraitRef, TyQPath};
79 use syntax::ast::{TyRptr, TyStr, TyUs, TyU8, TyU16, TyU32, TyU64, TyUint};
80 use syntax::ast::{TypeImplItem};
83 use syntax::ast_util::{PostExpansionMethod, local_def, walk_pat};
84 use syntax::attr::AttrMetaMethods;
85 use syntax::ext::mtwt;
86 use syntax::parse::token::{self, special_names, special_idents};
87 use syntax::codemap::{Span, Pos};
88 use syntax::owned_slice::OwnedSlice;
89 use syntax::visit::{self, Visitor};
91 use std::collections::{HashMap, HashSet};
92 use std::collections::hash_map::Entry::{Occupied, Vacant};
93 use std::cell::{Cell, RefCell};
95 use std::mem::replace;
96 use std::rc::{Rc, Weak};
101 mod build_reduced_graph;
106 binding_mode: BindingMode,
109 // Map from the name in a pattern to its binding mode.
110 type BindingMap = HashMap<Name, BindingInfo>;
112 #[derive(Copy, PartialEq)]
113 enum PatternBindingMode {
115 LocalIrrefutableMode,
116 ArgumentIrrefutableMode,
119 #[derive(Copy, PartialEq, Eq, Hash, Show)]
125 /// A NamespaceResult represents the result of resolving an import in
126 /// a particular namespace. The result is either definitely-resolved,
127 /// definitely- unresolved, or unknown.
129 enum NamespaceResult {
130 /// Means that resolve hasn't gathered enough information yet to determine
131 /// whether the name is bound in this namespace. (That is, it hasn't
132 /// resolved all `use` directives yet.)
134 /// Means that resolve has determined that the name is definitely
135 /// not bound in the namespace.
137 /// Means that resolve has determined that the name is bound in the Module
138 /// argument, and specified by the NameBindings argument.
139 BoundResult(Rc<Module>, Rc<NameBindings>)
142 impl NamespaceResult {
143 fn is_unknown(&self) -> bool {
145 UnknownResult => true,
149 fn is_unbound(&self) -> bool {
151 UnboundResult => true,
157 enum NameDefinition {
158 NoNameDefinition, //< The name was unbound.
159 ChildNameDefinition(Def, LastPrivate), //< The name identifies an immediate child.
160 ImportNameDefinition(Def, LastPrivate) //< The name identifies an import.
163 impl<'a, 'v, 'tcx> Visitor<'v> for Resolver<'a, 'tcx> {
164 fn visit_item(&mut self, item: &Item) {
165 self.resolve_item(item);
167 fn visit_arm(&mut self, arm: &Arm) {
168 self.resolve_arm(arm);
170 fn visit_block(&mut self, block: &Block) {
171 self.resolve_block(block);
173 fn visit_expr(&mut self, expr: &Expr) {
174 self.resolve_expr(expr);
176 fn visit_local(&mut self, local: &Local) {
177 self.resolve_local(local);
179 fn visit_ty(&mut self, ty: &Ty) {
180 self.resolve_type(ty);
184 /// Contains data for specific types of import directives.
186 enum ImportDirectiveSubclass {
187 SingleImport(Name /* target */, Name /* source */),
191 type ErrorMessage = Option<(Span, String)>;
193 enum ResolveResult<T> {
194 Failed(ErrorMessage), // Failed to resolve the name, optional helpful error message.
195 Indeterminate, // Couldn't determine due to unresolved globs.
196 Success(T) // Successfully resolved the import.
199 impl<T> ResolveResult<T> {
200 fn indeterminate(&self) -> bool {
201 match *self { Indeterminate => true, _ => false }
205 enum FallbackSuggestion {
210 StaticMethod(String),
215 enum TypeParameters<'a> {
221 // Identifies the things that these parameters
222 // were declared on (type, fn, etc)
225 // ID of the enclosing item.
228 // The kind of the rib used for type parameters.
232 // The rib kind controls the translation of local
233 // definitions (`DefLocal`) to upvars (`DefUpvar`).
234 #[derive(Copy, Show)]
236 // No translation needs to be applied.
239 // We passed through a closure scope at the given node ID.
240 // Translate upvars as appropriate.
241 ClosureRibKind(NodeId /* func id */, NodeId /* body id if proc or unboxed */),
243 // We passed through an impl or trait and are now in one of its
244 // methods. Allow references to ty params that impl or trait
245 // binds. Disallow any other upvars (including other ty params that are
247 // parent; method itself
248 MethodRibKind(NodeId, MethodSort),
250 // We passed through an item scope. Disallow upvars.
253 // We're in a constant item. Can't refer to dynamic stuff.
257 // Methods can be required or provided. RequiredMethod methods only occur in traits.
258 #[derive(Copy, Show)]
261 ProvidedMethod(NodeId)
265 enum UseLexicalScopeFlag {
270 enum ModulePrefixResult {
272 PrefixFound(Rc<Module>, uint)
275 #[derive(Copy, PartialEq)]
276 enum NameSearchType {
277 /// We're doing a name search in order to resolve a `use` directive.
280 /// We're doing a name search in order to resolve a path type, a path
281 /// expression, or a path pattern.
286 enum BareIdentifierPatternResolution {
287 FoundStructOrEnumVariant(Def, LastPrivate),
288 FoundConst(Def, LastPrivate),
289 BareIdentifierPatternUnresolved
295 bindings: HashMap<Name, DefLike>,
300 fn new(kind: RibKind) -> Rib {
302 bindings: HashMap::new(),
308 /// Whether an import can be shadowed by another import.
309 #[derive(Show,PartialEq,Clone,Copy)]
315 /// One import directive.
317 struct ImportDirective {
318 module_path: Vec<Name>,
319 subclass: ImportDirectiveSubclass,
322 is_public: bool, // see note in ImportResolution about how to use this
323 shadowable: Shadowable,
326 impl ImportDirective {
327 fn new(module_path: Vec<Name> ,
328 subclass: ImportDirectiveSubclass,
332 shadowable: Shadowable)
335 module_path: module_path,
339 is_public: is_public,
340 shadowable: shadowable,
345 /// The item that an import resolves to.
346 #[derive(Clone,Show)]
348 target_module: Rc<Module>,
349 bindings: Rc<NameBindings>,
350 shadowable: Shadowable,
354 fn new(target_module: Rc<Module>,
355 bindings: Rc<NameBindings>,
356 shadowable: Shadowable)
359 target_module: target_module,
361 shadowable: shadowable,
366 /// An ImportResolution represents a particular `use` directive.
368 struct ImportResolution {
369 /// Whether this resolution came from a `use` or a `pub use`. Note that this
370 /// should *not* be used whenever resolution is being performed, this is
371 /// only looked at for glob imports statements currently. Privacy testing
372 /// occurs during a later phase of compilation.
375 // The number of outstanding references to this name. When this reaches
376 // zero, outside modules can count on the targets being correct. Before
377 // then, all bets are off; future imports could override this name.
378 outstanding_references: uint,
380 /// The value that this `use` directive names, if there is one.
381 value_target: Option<Target>,
382 /// The source node of the `use` directive leading to the value target
386 /// The type that this `use` directive names, if there is one.
387 type_target: Option<Target>,
388 /// The source node of the `use` directive leading to the type target
393 impl ImportResolution {
394 fn new(id: NodeId, is_public: bool) -> ImportResolution {
398 outstanding_references: 0,
401 is_public: is_public,
405 fn target_for_namespace(&self, namespace: Namespace)
408 TypeNS => self.type_target.clone(),
409 ValueNS => self.value_target.clone(),
413 fn id(&self, namespace: Namespace) -> NodeId {
415 TypeNS => self.type_id,
416 ValueNS => self.value_id,
420 fn shadowable(&self, namespace: Namespace) -> Shadowable {
421 let target = self.target_for_namespace(namespace);
422 if target.is_none() {
423 return Shadowable::Always;
426 target.unwrap().shadowable
429 fn set_target_and_id(&mut self,
430 namespace: Namespace,
431 target: Option<Target>,
435 self.type_target = target;
439 self.value_target = target;
446 /// The link from a module up to its nearest parent node.
447 #[derive(Clone,Show)]
450 ModuleParentLink(Weak<Module>, Name),
451 BlockParentLink(Weak<Module>, NodeId)
454 /// The type of module this is.
455 #[derive(Copy, PartialEq, Show)]
464 /// One node in the tree of modules.
466 parent_link: ParentLink,
467 def_id: Cell<Option<DefId>>,
468 kind: Cell<ModuleKind>,
471 children: RefCell<HashMap<Name, Rc<NameBindings>>>,
472 imports: RefCell<Vec<ImportDirective>>,
474 // The external module children of this node that were declared with
476 external_module_children: RefCell<HashMap<Name, Rc<Module>>>,
478 // The anonymous children of this node. Anonymous children are pseudo-
479 // modules that are implicitly created around items contained within
482 // For example, if we have this:
490 // There will be an anonymous module created around `g` with the ID of the
491 // entry block for `f`.
492 anonymous_children: RefCell<NodeMap<Rc<Module>>>,
494 // The status of resolving each import in this module.
495 import_resolutions: RefCell<HashMap<Name, ImportResolution>>,
497 // The number of unresolved globs that this module exports.
498 glob_count: Cell<uint>,
500 // The index of the import we're resolving.
501 resolved_import_count: Cell<uint>,
503 // Whether this module is populated. If not populated, any attempt to
504 // access the children must be preceded with a
505 // `populate_module_if_necessary` call.
506 populated: Cell<bool>,
510 fn new(parent_link: ParentLink,
511 def_id: Option<DefId>,
517 parent_link: parent_link,
518 def_id: Cell::new(def_id),
519 kind: Cell::new(kind),
520 is_public: is_public,
521 children: RefCell::new(HashMap::new()),
522 imports: RefCell::new(Vec::new()),
523 external_module_children: RefCell::new(HashMap::new()),
524 anonymous_children: RefCell::new(NodeMap::new()),
525 import_resolutions: RefCell::new(HashMap::new()),
526 glob_count: Cell::new(0),
527 resolved_import_count: Cell::new(0),
528 populated: Cell::new(!external),
532 fn all_imports_resolved(&self) -> bool {
533 self.imports.borrow().len() == self.resolved_import_count.get()
537 impl fmt::Show for Module {
538 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
539 write!(f, "{:?}, kind: {:?}, {}",
542 if self.is_public { "public" } else { "private" } )
548 flags DefModifiers: u8 {
549 const PUBLIC = 0b0000_0001,
550 const IMPORTABLE = 0b0000_0010,
554 // Records a possibly-private type definition.
555 #[derive(Clone,Show)]
557 modifiers: DefModifiers, // see note in ImportResolution about how to use this
558 module_def: Option<Rc<Module>>,
559 type_def: Option<Def>,
560 type_span: Option<Span>
563 // Records a possibly-private value definition.
564 #[derive(Clone, Copy, Show)]
566 modifiers: DefModifiers, // see note in ImportResolution about how to use this
568 value_span: Option<Span>,
571 // Records the definitions (at most one for each namespace) that a name is
574 struct NameBindings {
575 type_def: RefCell<Option<TypeNsDef>>, //< Meaning in type namespace.
576 value_def: RefCell<Option<ValueNsDef>>, //< Meaning in value namespace.
579 /// Ways in which a trait can be referenced
581 enum TraitReferenceType {
582 TraitImplementation, // impl SomeTrait for T { ... }
583 TraitDerivation, // trait T : SomeTrait { ... }
584 TraitBoundingTypeParameter, // fn f<T:SomeTrait>() { ... }
585 TraitObject, // Box<for<'a> SomeTrait>
586 TraitQPath, // <T as SomeTrait>::
590 fn new() -> NameBindings {
592 type_def: RefCell::new(None),
593 value_def: RefCell::new(None),
597 /// Creates a new module in this set of name bindings.
598 fn define_module(&self,
599 parent_link: ParentLink,
600 def_id: Option<DefId>,
605 // Merges the module with the existing type def or creates a new one.
606 let modifiers = if is_public { PUBLIC } else { DefModifiers::empty() } | IMPORTABLE;
607 let module_ = Rc::new(Module::new(parent_link,
612 let type_def = self.type_def.borrow().clone();
615 *self.type_def.borrow_mut() = Some(TypeNsDef {
616 modifiers: modifiers,
617 module_def: Some(module_),
623 *self.type_def.borrow_mut() = Some(TypeNsDef {
624 modifiers: modifiers,
625 module_def: Some(module_),
627 type_def: type_def.type_def
633 /// Sets the kind of the module, creating a new one if necessary.
634 fn set_module_kind(&self,
635 parent_link: ParentLink,
636 def_id: Option<DefId>,
641 let modifiers = if is_public { PUBLIC } else { DefModifiers::empty() } | IMPORTABLE;
642 let type_def = self.type_def.borrow().clone();
645 let module = Module::new(parent_link,
650 *self.type_def.borrow_mut() = Some(TypeNsDef {
651 modifiers: modifiers,
652 module_def: Some(Rc::new(module)),
658 match type_def.module_def {
660 let module = Module::new(parent_link,
665 *self.type_def.borrow_mut() = Some(TypeNsDef {
666 modifiers: modifiers,
667 module_def: Some(Rc::new(module)),
668 type_def: type_def.type_def,
672 Some(module_def) => module_def.kind.set(kind),
678 /// Records a type definition.
679 fn define_type(&self, def: Def, sp: Span, modifiers: DefModifiers) {
680 debug!("defining type for def {:?} with modifiers {:?}", def, modifiers);
681 // Merges the type with the existing type def or creates a new one.
682 let type_def = self.type_def.borrow().clone();
685 *self.type_def.borrow_mut() = Some(TypeNsDef {
689 modifiers: modifiers,
693 *self.type_def.borrow_mut() = Some(TypeNsDef {
694 module_def: type_def.module_def,
697 modifiers: modifiers,
703 /// Records a value definition.
704 fn define_value(&self, def: Def, sp: Span, modifiers: DefModifiers) {
705 debug!("defining value for def {:?} with modifiers {:?}", def, modifiers);
706 *self.value_def.borrow_mut() = Some(ValueNsDef {
708 value_span: Some(sp),
709 modifiers: modifiers,
713 /// Returns the module node if applicable.
714 fn get_module_if_available(&self) -> Option<Rc<Module>> {
715 match *self.type_def.borrow() {
716 Some(ref type_def) => type_def.module_def.clone(),
721 /// Returns the module node. Panics if this node does not have a module
723 fn get_module(&self) -> Rc<Module> {
724 match self.get_module_if_available() {
726 panic!("get_module called on a node with no module \
729 Some(module_def) => module_def
733 fn defined_in_namespace(&self, namespace: Namespace) -> bool {
735 TypeNS => return self.type_def.borrow().is_some(),
736 ValueNS => return self.value_def.borrow().is_some()
740 fn defined_in_public_namespace(&self, namespace: Namespace) -> bool {
741 self.defined_in_namespace_with(namespace, PUBLIC)
744 fn defined_in_namespace_with(&self, namespace: Namespace, modifiers: DefModifiers) -> bool {
746 TypeNS => match *self.type_def.borrow() {
747 Some(ref def) => def.modifiers.contains(modifiers), None => false
749 ValueNS => match *self.value_def.borrow() {
750 Some(ref def) => def.modifiers.contains(modifiers), None => false
755 fn def_for_namespace(&self, namespace: Namespace) -> Option<Def> {
758 match *self.type_def.borrow() {
760 Some(ref type_def) => {
761 match type_def.type_def {
762 Some(type_def) => Some(type_def),
764 match type_def.module_def {
765 Some(ref module) => {
766 match module.def_id.get() {
767 Some(did) => Some(DefMod(did)),
779 match *self.value_def.borrow() {
781 Some(value_def) => Some(value_def.def)
787 fn span_for_namespace(&self, namespace: Namespace) -> Option<Span> {
788 if self.defined_in_namespace(namespace) {
791 match *self.type_def.borrow() {
793 Some(ref type_def) => type_def.type_span
797 match *self.value_def.borrow() {
799 Some(ref value_def) => value_def.value_span
809 /// Interns the names of the primitive types.
810 struct PrimitiveTypeTable {
811 primitive_types: HashMap<Name, PrimTy>,
814 impl PrimitiveTypeTable {
815 fn new() -> PrimitiveTypeTable {
816 let mut table = PrimitiveTypeTable {
817 primitive_types: HashMap::new()
820 table.intern("bool", TyBool);
821 table.intern("char", TyChar);
822 table.intern("f32", TyFloat(TyF32));
823 table.intern("f64", TyFloat(TyF64));
824 table.intern("int", TyInt(TyIs(true)));
825 table.intern("isize", TyInt(TyIs(false)));
826 table.intern("i8", TyInt(TyI8));
827 table.intern("i16", TyInt(TyI16));
828 table.intern("i32", TyInt(TyI32));
829 table.intern("i64", TyInt(TyI64));
830 table.intern("str", TyStr);
831 table.intern("uint", TyUint(TyUs(true)));
832 table.intern("usize", TyUint(TyUs(false)));
833 table.intern("u8", TyUint(TyU8));
834 table.intern("u16", TyUint(TyU16));
835 table.intern("u32", TyUint(TyU32));
836 table.intern("u64", TyUint(TyU64));
841 fn intern(&mut self, string: &str, primitive_type: PrimTy) {
842 self.primitive_types.insert(token::intern(string), primitive_type);
846 /// The main resolver class.
847 struct Resolver<'a, 'tcx:'a> {
848 session: &'a Session,
850 ast_map: &'a ast_map::Map<'tcx>,
852 graph_root: NameBindings,
854 trait_item_map: FnvHashMap<(Name, DefId), TraitItemKind>,
856 structs: FnvHashMap<DefId, Vec<Name>>,
858 // The number of imports that are currently unresolved.
859 unresolved_imports: uint,
861 // The module that represents the current item scope.
862 current_module: Rc<Module>,
864 // The current set of local scopes, for values.
865 // FIXME #4948: Reuse ribs to avoid allocation.
866 value_ribs: Vec<Rib>,
868 // The current set of local scopes, for types.
871 // The current set of local scopes, for labels.
872 label_ribs: Vec<Rib>,
874 // The trait that the current context can refer to.
875 current_trait_ref: Option<(DefId, TraitRef)>,
877 // The current self type if inside an impl (used for better errors).
878 current_self_type: Option<Ty>,
880 // The ident for the keyword "self".
882 // The ident for the non-keyword "Self".
883 type_self_name: Name,
885 // The idents for the primitive types.
886 primitive_type_table: PrimitiveTypeTable,
889 freevars: RefCell<FreevarMap>,
890 freevars_seen: RefCell<NodeMap<NodeSet>>,
891 capture_mode_map: CaptureModeMap,
892 export_map: ExportMap,
894 external_exports: ExternalExports,
895 last_private: LastPrivateMap,
897 // Whether or not to print error messages. Can be set to true
898 // when getting additional info for error message suggestions,
899 // so as to avoid printing duplicate errors
903 // Maps imports to the names of items actually imported (this actually maps
904 // all imports, but only glob imports are actually interesting).
907 used_imports: HashSet<(NodeId, Namespace)>,
908 used_crates: HashSet<CrateNum>,
912 enum FallbackChecks {
918 impl<'a, 'tcx> Resolver<'a, 'tcx> {
919 fn new(session: &'a Session,
920 ast_map: &'a ast_map::Map<'tcx>,
922 make_glob_map: MakeGlobMap) -> Resolver<'a, 'tcx> {
923 let graph_root = NameBindings::new();
925 graph_root.define_module(NoParentLink,
926 Some(DefId { krate: 0, node: 0 }),
932 let current_module = graph_root.get_module();
939 // The outermost module has def ID 0; this is not reflected in the
942 graph_root: graph_root,
944 trait_item_map: FnvHashMap::new(),
945 structs: FnvHashMap::new(),
947 unresolved_imports: 0,
949 current_module: current_module,
950 value_ribs: Vec::new(),
951 type_ribs: Vec::new(),
952 label_ribs: Vec::new(),
954 current_trait_ref: None,
955 current_self_type: None,
957 self_name: special_names::self_,
958 type_self_name: special_names::type_self,
960 primitive_type_table: PrimitiveTypeTable::new(),
962 def_map: RefCell::new(NodeMap::new()),
963 freevars: RefCell::new(NodeMap::new()),
964 freevars_seen: RefCell::new(NodeMap::new()),
965 capture_mode_map: NodeMap::new(),
966 export_map: NodeMap::new(),
967 trait_map: NodeMap::new(),
968 used_imports: HashSet::new(),
969 used_crates: HashSet::new(),
970 external_exports: DefIdSet::new(),
971 last_private: NodeMap::new(),
974 make_glob_map: make_glob_map == MakeGlobMap::Yes,
975 glob_map: HashMap::new(),
981 // This is a fixed-point algorithm. We resolve imports until our efforts
982 // are stymied by an unresolved import; then we bail out of the current
983 // module and continue. We terminate successfully once no more imports
984 // remain or unsuccessfully when no forward progress in resolving imports
987 /// Resolves all imports for the crate. This method performs the fixed-
989 fn resolve_imports(&mut self) {
991 let mut prev_unresolved_imports = 0;
993 debug!("(resolving imports) iteration {}, {} imports left",
994 i, self.unresolved_imports);
996 let module_root = self.graph_root.get_module();
997 self.resolve_imports_for_module_subtree(module_root.clone());
999 if self.unresolved_imports == 0 {
1000 debug!("(resolving imports) success");
1004 if self.unresolved_imports == prev_unresolved_imports {
1005 self.report_unresolved_imports(module_root);
1010 prev_unresolved_imports = self.unresolved_imports;
1014 /// Attempts to resolve imports for the given module and all of its
1016 fn resolve_imports_for_module_subtree(&mut self, module_: Rc<Module>) {
1017 debug!("(resolving imports for module subtree) resolving {}",
1018 self.module_to_string(&*module_));
1019 let orig_module = replace(&mut self.current_module, module_.clone());
1020 self.resolve_imports_for_module(module_.clone());
1021 self.current_module = orig_module;
1023 build_reduced_graph::populate_module_if_necessary(self, &module_);
1024 for (_, child_node) in module_.children.borrow().iter() {
1025 match child_node.get_module_if_available() {
1029 Some(child_module) => {
1030 self.resolve_imports_for_module_subtree(child_module);
1035 for (_, child_module) in module_.anonymous_children.borrow().iter() {
1036 self.resolve_imports_for_module_subtree(child_module.clone());
1040 /// Attempts to resolve imports for the given module only.
1041 fn resolve_imports_for_module(&mut self, module: Rc<Module>) {
1042 if module.all_imports_resolved() {
1043 debug!("(resolving imports for module) all imports resolved for \
1045 self.module_to_string(&*module));
1049 let imports = module.imports.borrow();
1050 let import_count = imports.len();
1051 while module.resolved_import_count.get() < import_count {
1052 let import_index = module.resolved_import_count.get();
1053 let import_directive = &(*imports)[import_index];
1054 match self.resolve_import_for_module(module.clone(),
1057 let (span, help) = match err {
1058 Some((span, msg)) => (span, format!(". {}", msg)),
1059 None => (import_directive.span, String::new())
1061 let msg = format!("unresolved import `{}`{}",
1062 self.import_path_to_string(
1063 &import_directive.module_path[],
1064 import_directive.subclass),
1066 self.resolve_error(span, &msg[]);
1068 Indeterminate => break, // Bail out. We'll come around next time.
1069 Success(()) => () // Good. Continue.
1072 module.resolved_import_count
1073 .set(module.resolved_import_count.get() + 1);
1077 fn names_to_string(&self, names: &[Name]) -> String {
1078 let mut first = true;
1079 let mut result = String::new();
1080 for name in names.iter() {
1084 result.push_str("::")
1086 result.push_str(token::get_name(*name).get());
1091 fn path_names_to_string(&self, path: &Path) -> String {
1092 let names: Vec<ast::Name> = path.segments
1094 .map(|seg| seg.identifier.name)
1096 self.names_to_string(&names[])
1099 fn import_directive_subclass_to_string(&mut self,
1100 subclass: ImportDirectiveSubclass)
1103 SingleImport(_, source) => {
1104 token::get_name(source).get().to_string()
1106 GlobImport => "*".to_string()
1110 fn import_path_to_string(&mut self,
1112 subclass: ImportDirectiveSubclass)
1114 if names.is_empty() {
1115 self.import_directive_subclass_to_string(subclass)
1118 self.names_to_string(names),
1119 self.import_directive_subclass_to_string(
1120 subclass))).to_string()
1125 fn record_import_use(&mut self, import_id: NodeId, name: Name) {
1126 if !self.make_glob_map {
1129 if self.glob_map.contains_key(&import_id) {
1130 self.glob_map[import_id].insert(name);
1134 let mut new_set = HashSet::new();
1135 new_set.insert(name);
1136 self.glob_map.insert(import_id, new_set);
1139 fn get_trait_name(&self, did: DefId) -> Name {
1140 if did.krate == LOCAL_CRATE {
1141 self.ast_map.expect_item(did.node).ident.name
1143 csearch::get_trait_name(&self.session.cstore, did)
1147 /// Attempts to resolve the given import. The return value indicates
1148 /// failure if we're certain the name does not exist, indeterminate if we
1149 /// don't know whether the name exists at the moment due to other
1150 /// currently-unresolved imports, or success if we know the name exists.
1151 /// If successful, the resolved bindings are written into the module.
1152 fn resolve_import_for_module(&mut self,
1153 module_: Rc<Module>,
1154 import_directive: &ImportDirective)
1155 -> ResolveResult<()> {
1156 let mut resolution_result = Failed(None);
1157 let module_path = &import_directive.module_path;
1159 debug!("(resolving import for module) resolving import `{}::...` in `{}`",
1160 self.names_to_string(&module_path[]),
1161 self.module_to_string(&*module_));
1163 // First, resolve the module path for the directive, if necessary.
1164 let container = if module_path.len() == 0 {
1165 // Use the crate root.
1166 Some((self.graph_root.get_module(), LastMod(AllPublic)))
1168 match self.resolve_module_path(module_.clone(),
1170 DontUseLexicalScope,
1171 import_directive.span,
1174 resolution_result = Failed(err);
1178 resolution_result = Indeterminate;
1181 Success(container) => Some(container),
1187 Some((containing_module, lp)) => {
1188 // We found the module that the target is contained
1189 // within. Attempt to resolve the import within it.
1191 match import_directive.subclass {
1192 SingleImport(target, source) => {
1194 self.resolve_single_import(&*module_,
1203 self.resolve_glob_import(&*module_,
1212 // Decrement the count of unresolved imports.
1213 match resolution_result {
1215 assert!(self.unresolved_imports >= 1);
1216 self.unresolved_imports -= 1;
1219 // Nothing to do here; just return the error.
1223 // Decrement the count of unresolved globs if necessary. But only if
1224 // the resolution result is indeterminate -- otherwise we'll stop
1225 // processing imports here. (See the loop in
1226 // resolve_imports_for_module.)
1228 if !resolution_result.indeterminate() {
1229 match import_directive.subclass {
1231 assert!(module_.glob_count.get() >= 1);
1232 module_.glob_count.set(module_.glob_count.get() - 1);
1234 SingleImport(..) => {
1240 return resolution_result;
1243 fn create_name_bindings_from_module(module: Rc<Module>) -> NameBindings {
1245 type_def: RefCell::new(Some(TypeNsDef {
1246 modifiers: IMPORTABLE,
1247 module_def: Some(module),
1251 value_def: RefCell::new(None),
1255 fn resolve_single_import(&mut self,
1257 containing_module: Rc<Module>,
1260 directive: &ImportDirective,
1262 -> ResolveResult<()> {
1263 debug!("(resolving single import) resolving `{}` = `{}::{}` from \
1264 `{}` id {}, last private {:?}",
1265 token::get_name(target),
1266 self.module_to_string(&*containing_module),
1267 token::get_name(source),
1268 self.module_to_string(module_),
1274 LastImport {..} => {
1276 .span_bug(directive.span,
1277 "not expecting Import here, must be LastMod")
1281 // We need to resolve both namespaces for this to succeed.
1284 let mut value_result = UnknownResult;
1285 let mut type_result = UnknownResult;
1287 // Search for direct children of the containing module.
1288 build_reduced_graph::populate_module_if_necessary(self, &containing_module);
1290 match containing_module.children.borrow().get(&source) {
1294 Some(ref child_name_bindings) => {
1295 if child_name_bindings.defined_in_namespace(ValueNS) {
1296 debug!("(resolving single import) found value binding");
1297 value_result = BoundResult(containing_module.clone(),
1298 (*child_name_bindings).clone());
1300 if child_name_bindings.defined_in_namespace(TypeNS) {
1301 debug!("(resolving single import) found type binding");
1302 type_result = BoundResult(containing_module.clone(),
1303 (*child_name_bindings).clone());
1308 // Unless we managed to find a result in both namespaces (unlikely),
1309 // search imports as well.
1310 let mut value_used_reexport = false;
1311 let mut type_used_reexport = false;
1312 match (value_result.clone(), type_result.clone()) {
1313 (BoundResult(..), BoundResult(..)) => {} // Continue.
1315 // If there is an unresolved glob at this point in the
1316 // containing module, bail out. We don't know enough to be
1317 // able to resolve this import.
1319 if containing_module.glob_count.get() > 0 {
1320 debug!("(resolving single import) unresolved glob; \
1322 return Indeterminate;
1325 // Now search the exported imports within the containing module.
1326 match containing_module.import_resolutions.borrow().get(&source) {
1328 debug!("(resolving single import) no import");
1329 // The containing module definitely doesn't have an
1330 // exported import with the name in question. We can
1331 // therefore accurately report that the names are
1334 if value_result.is_unknown() {
1335 value_result = UnboundResult;
1337 if type_result.is_unknown() {
1338 type_result = UnboundResult;
1341 Some(import_resolution)
1342 if import_resolution.outstanding_references == 0 => {
1344 fn get_binding(this: &mut Resolver,
1345 import_resolution: &ImportResolution,
1346 namespace: Namespace,
1348 -> NamespaceResult {
1350 // Import resolutions must be declared with "pub"
1351 // in order to be exported.
1352 if !import_resolution.is_public {
1353 return UnboundResult;
1356 match import_resolution.
1357 target_for_namespace(namespace) {
1359 return UnboundResult;
1366 debug!("(resolving single import) found \
1367 import in ns {:?}", namespace);
1368 let id = import_resolution.id(namespace);
1369 // track used imports and extern crates as well
1370 this.used_imports.insert((id, namespace));
1371 this.record_import_use(id, *source);
1372 match target_module.def_id.get() {
1373 Some(DefId{krate: kid, ..}) => {
1374 this.used_crates.insert(kid);
1378 return BoundResult(target_module, bindings);
1383 // The name is an import which has been fully
1384 // resolved. We can, therefore, just follow it.
1385 if value_result.is_unknown() {
1386 value_result = get_binding(self,
1390 value_used_reexport = import_resolution.is_public;
1392 if type_result.is_unknown() {
1393 type_result = get_binding(self,
1397 type_used_reexport = import_resolution.is_public;
1402 // If containing_module is the same module whose import we are resolving
1403 // and there it has an unresolved import with the same name as `source`,
1404 // then the user is actually trying to import an item that is declared
1405 // in the same scope
1408 // use self::submodule;
1409 // pub mod submodule;
1411 // In this case we continue as if we resolved the import and let the
1412 // check_for_conflicts_between_imports_and_items call below handle
1414 match (module_.def_id.get(), containing_module.def_id.get()) {
1415 (Some(id1), Some(id2)) if id1 == id2 => {
1416 if value_result.is_unknown() {
1417 value_result = UnboundResult;
1419 if type_result.is_unknown() {
1420 type_result = UnboundResult;
1424 // The import is unresolved. Bail out.
1425 debug!("(resolving single import) unresolved import; \
1427 return Indeterminate;
1435 // If we didn't find a result in the type namespace, search the
1436 // external modules.
1437 let mut value_used_public = false;
1438 let mut type_used_public = false;
1440 BoundResult(..) => {}
1442 match containing_module.external_module_children.borrow_mut()
1443 .get(&source).cloned() {
1444 None => {} // Continue.
1446 debug!("(resolving single import) found external \
1448 // track the module as used.
1449 match module.def_id.get() {
1450 Some(DefId{krate: kid, ..}) => { self.used_crates.insert(kid); },
1454 Rc::new(Resolver::create_name_bindings_from_module(
1456 type_result = BoundResult(containing_module.clone(),
1458 type_used_public = true;
1464 // We've successfully resolved the import. Write the results in.
1465 let mut import_resolutions = module_.import_resolutions.borrow_mut();
1466 let import_resolution = &mut (*import_resolutions)[target];
1468 let mut check_and_write_import = |&mut: namespace, result: &_, used_public: &mut bool| {
1469 let namespace_name = match namespace {
1475 BoundResult(ref target_module, ref name_bindings) => {
1476 debug!("(resolving single import) found {:?} target: {:?}",
1478 name_bindings.def_for_namespace(namespace));
1479 self.check_for_conflicting_import(
1480 &import_resolution.target_for_namespace(namespace),
1485 self.check_that_import_is_importable(
1491 let target = Some(Target::new(target_module.clone(),
1492 name_bindings.clone(),
1493 directive.shadowable));
1494 import_resolution.set_target_and_id(namespace, target, directive.id);
1495 import_resolution.is_public = directive.is_public;
1496 *used_public = name_bindings.defined_in_public_namespace(namespace);
1498 UnboundResult => { /* Continue. */ }
1500 panic!("{:?} result should be known at this point", namespace_name);
1504 check_and_write_import(ValueNS, &value_result, &mut value_used_public);
1505 check_and_write_import(TypeNS, &type_result, &mut type_used_public);
1508 self.check_for_conflicts_between_imports_and_items(
1514 if value_result.is_unbound() && type_result.is_unbound() {
1515 let msg = format!("There is no `{}` in `{}`",
1516 token::get_name(source),
1517 self.module_to_string(&*containing_module));
1518 return Failed(Some((directive.span, msg)));
1520 let value_used_public = value_used_reexport || value_used_public;
1521 let type_used_public = type_used_reexport || type_used_public;
1523 assert!(import_resolution.outstanding_references >= 1);
1524 import_resolution.outstanding_references -= 1;
1526 // record what this import resolves to for later uses in documentation,
1527 // this may resolve to either a value or a type, but for documentation
1528 // purposes it's good enough to just favor one over the other.
1529 let value_private = match import_resolution.value_target {
1530 Some(ref target) => {
1531 let def = target.bindings.def_for_namespace(ValueNS).unwrap();
1532 self.def_map.borrow_mut().insert(directive.id, def);
1533 let did = def.def_id();
1534 if value_used_public {Some(lp)} else {Some(DependsOn(did))}
1536 // AllPublic here and below is a dummy value, it should never be used because
1537 // _exists is false.
1540 let type_private = match import_resolution.type_target {
1541 Some(ref target) => {
1542 let def = target.bindings.def_for_namespace(TypeNS).unwrap();
1543 self.def_map.borrow_mut().insert(directive.id, def);
1544 let did = def.def_id();
1545 if type_used_public {Some(lp)} else {Some(DependsOn(did))}
1550 self.last_private.insert(directive.id, LastImport{value_priv: value_private,
1552 type_priv: type_private,
1555 debug!("(resolving single import) successfully resolved import");
1559 // Resolves a glob import. Note that this function cannot fail; it either
1560 // succeeds or bails out (as importing * from an empty module or a module
1561 // that exports nothing is valid). containing_module is the module we are
1562 // actually importing, i.e., `foo` in `use foo::*`.
1563 fn resolve_glob_import(&mut self,
1565 containing_module: Rc<Module>,
1566 import_directive: &ImportDirective,
1568 -> ResolveResult<()> {
1569 let id = import_directive.id;
1570 let is_public = import_directive.is_public;
1572 // This function works in a highly imperative manner; it eagerly adds
1573 // everything it can to the list of import resolutions of the module
1575 debug!("(resolving glob import) resolving glob import {}", id);
1577 // We must bail out if the node has unresolved imports of any kind
1578 // (including globs).
1579 if !(*containing_module).all_imports_resolved() {
1580 debug!("(resolving glob import) target module has unresolved \
1581 imports; bailing out");
1582 return Indeterminate;
1585 assert_eq!(containing_module.glob_count.get(), 0);
1587 // Add all resolved imports from the containing module.
1588 let import_resolutions = containing_module.import_resolutions.borrow();
1589 for (ident, target_import_resolution) in import_resolutions.iter() {
1590 debug!("(resolving glob import) writing module resolution \
1592 token::get_name(*ident),
1593 self.module_to_string(module_));
1595 if !target_import_resolution.is_public {
1596 debug!("(resolving glob import) nevermind, just kidding");
1600 // Here we merge two import resolutions.
1601 let mut import_resolutions = module_.import_resolutions.borrow_mut();
1602 match import_resolutions.get_mut(ident) {
1603 Some(dest_import_resolution) => {
1604 // Merge the two import resolutions at a finer-grained
1607 match target_import_resolution.value_target {
1611 Some(ref value_target) => {
1612 self.check_for_conflicting_import(&dest_import_resolution.value_target,
1613 import_directive.span,
1616 dest_import_resolution.value_target = Some(value_target.clone());
1619 match target_import_resolution.type_target {
1623 Some(ref type_target) => {
1624 self.check_for_conflicting_import(&dest_import_resolution.type_target,
1625 import_directive.span,
1628 dest_import_resolution.type_target = Some(type_target.clone());
1631 dest_import_resolution.is_public = is_public;
1637 // Simple: just copy the old import resolution.
1638 let mut new_import_resolution = ImportResolution::new(id, is_public);
1639 new_import_resolution.value_target =
1640 target_import_resolution.value_target.clone();
1641 new_import_resolution.type_target =
1642 target_import_resolution.type_target.clone();
1644 import_resolutions.insert(*ident, new_import_resolution);
1647 // Add all children from the containing module.
1648 build_reduced_graph::populate_module_if_necessary(self, &containing_module);
1650 for (&name, name_bindings) in containing_module.children.borrow().iter() {
1651 self.merge_import_resolution(module_,
1652 containing_module.clone(),
1655 name_bindings.clone());
1659 // Add external module children from the containing module.
1660 for (&name, module) in containing_module.external_module_children.borrow().iter() {
1662 Rc::new(Resolver::create_name_bindings_from_module(module.clone()));
1663 self.merge_import_resolution(module_,
1664 containing_module.clone(),
1670 // Record the destination of this import
1671 match containing_module.def_id.get() {
1673 self.def_map.borrow_mut().insert(id, DefMod(did));
1674 self.last_private.insert(id, lp);
1679 debug!("(resolving glob import) successfully resolved import");
1683 fn merge_import_resolution(&mut self,
1685 containing_module: Rc<Module>,
1686 import_directive: &ImportDirective,
1688 name_bindings: Rc<NameBindings>) {
1689 let id = import_directive.id;
1690 let is_public = import_directive.is_public;
1692 let mut import_resolutions = module_.import_resolutions.borrow_mut();
1693 let dest_import_resolution = import_resolutions.entry(name).get().unwrap_or_else(
1695 // Create a new import resolution from this child.
1696 vacant_entry.insert(ImportResolution::new(id, is_public))
1699 debug!("(resolving glob import) writing resolution `{}` in `{}` \
1701 token::get_name(name).get(),
1702 self.module_to_string(&*containing_module),
1703 self.module_to_string(module_));
1705 // Merge the child item into the import resolution.
1707 let mut merge_child_item = |&mut : namespace| {
1708 if name_bindings.defined_in_namespace_with(namespace, IMPORTABLE | PUBLIC) {
1709 let namespace_name = match namespace {
1713 debug!("(resolving glob import) ... for {} target", namespace_name);
1714 if dest_import_resolution.shadowable(namespace) == Shadowable::Never {
1715 let msg = format!("a {} named `{}` has already been imported \
1718 token::get_name(name).get());
1719 self.session.span_err(import_directive.span, msg.as_slice());
1721 let target = Target::new(containing_module.clone(),
1722 name_bindings.clone(),
1723 import_directive.shadowable);
1724 dest_import_resolution.set_target_and_id(namespace,
1730 merge_child_item(ValueNS);
1731 merge_child_item(TypeNS);
1734 dest_import_resolution.is_public = is_public;
1736 self.check_for_conflicts_between_imports_and_items(
1738 dest_import_resolution,
1739 import_directive.span,
1743 /// Checks that imported names and items don't have the same name.
1744 fn check_for_conflicting_import(&mut self,
1745 target: &Option<Target>,
1748 namespace: Namespace) {
1749 if self.session.features.borrow().import_shadowing {
1753 debug!("check_for_conflicting_import: {}; target exists: {}",
1754 token::get_name(name).get(),
1758 Some(ref target) if target.shadowable != Shadowable::Always => {
1759 let msg = format!("a {} named `{}` has already been imported \
1765 token::get_name(name).get());
1766 self.session.span_err(import_span, &msg[]);
1768 Some(_) | None => {}
1772 /// Checks that an import is actually importable
1773 fn check_that_import_is_importable(&mut self,
1774 name_bindings: &NameBindings,
1777 namespace: Namespace) {
1778 if !name_bindings.defined_in_namespace_with(namespace, IMPORTABLE) {
1779 let msg = format!("`{}` is not directly importable",
1780 token::get_name(name));
1781 self.session.span_err(import_span, &msg[]);
1785 /// Checks that imported names and items don't have the same name.
1786 fn check_for_conflicts_between_imports_and_items(&mut self,
1792 if self.session.features.borrow().import_shadowing {
1796 // First, check for conflicts between imports and `extern crate`s.
1797 if module.external_module_children
1799 .contains_key(&name) {
1800 match import_resolution.type_target {
1801 Some(ref target) if target.shadowable != Shadowable::Always => {
1802 let msg = format!("import `{0}` conflicts with imported \
1803 crate in this module \
1804 (maybe you meant `use {0}::*`?)",
1805 token::get_name(name).get());
1806 self.session.span_err(import_span, &msg[]);
1808 Some(_) | None => {}
1812 // Check for item conflicts.
1813 let children = module.children.borrow();
1814 let name_bindings = match children.get(&name) {
1816 // There can't be any conflicts.
1819 Some(ref name_bindings) => (*name_bindings).clone(),
1822 match import_resolution.value_target {
1823 Some(ref target) if target.shadowable != Shadowable::Always => {
1824 if let Some(ref value) = *name_bindings.value_def.borrow() {
1825 let msg = format!("import `{}` conflicts with value \
1827 token::get_name(name).get());
1828 self.session.span_err(import_span, &msg[]);
1829 if let Some(span) = value.value_span {
1830 self.session.span_note(span,
1831 "conflicting value here");
1835 Some(_) | None => {}
1838 match import_resolution.type_target {
1839 Some(ref target) if target.shadowable != Shadowable::Always => {
1840 if let Some(ref ty) = *name_bindings.type_def.borrow() {
1841 match ty.module_def {
1843 let msg = format!("import `{}` conflicts with type in \
1845 token::get_name(name).get());
1846 self.session.span_err(import_span, &msg[]);
1847 if let Some(span) = ty.type_span {
1848 self.session.span_note(span,
1849 "note conflicting type here")
1852 Some(ref module_def) => {
1853 match module_def.kind.get() {
1855 if let Some(span) = ty.type_span {
1856 let msg = format!("inherent implementations \
1857 are only allowed on types \
1858 defined in the current module");
1859 self.session.span_err(span, &msg[]);
1860 self.session.span_note(import_span,
1861 "import from other module here")
1865 let msg = format!("import `{}` conflicts with existing \
1867 token::get_name(name).get());
1868 self.session.span_err(import_span, &msg[]);
1869 if let Some(span) = ty.type_span {
1870 self.session.span_note(span,
1871 "note conflicting module here")
1879 Some(_) | None => {}
1883 /// Checks that the names of external crates don't collide with other
1884 /// external crates.
1885 fn check_for_conflicts_between_external_crates(&self,
1889 if self.session.features.borrow().import_shadowing {
1893 if module.external_module_children.borrow().contains_key(&name) {
1896 &format!("an external crate named `{}` has already \
1897 been imported into this module",
1898 token::get_name(name).get())[]);
1902 /// Checks that the names of items don't collide with external crates.
1903 fn check_for_conflicts_between_external_crates_and_items(&self,
1907 if self.session.features.borrow().import_shadowing {
1911 if module.external_module_children.borrow().contains_key(&name) {
1914 &format!("the name `{}` conflicts with an external \
1915 crate that has been imported into this \
1917 token::get_name(name).get())[]);
1921 /// Resolves the given module path from the given root `module_`.
1922 fn resolve_module_path_from_root(&mut self,
1923 module_: Rc<Module>,
1924 module_path: &[Name],
1927 name_search_type: NameSearchType,
1929 -> ResolveResult<(Rc<Module>, LastPrivate)> {
1930 fn search_parent_externals(needle: Name, module: &Rc<Module>)
1931 -> Option<Rc<Module>> {
1932 module.external_module_children.borrow()
1933 .get(&needle).cloned()
1934 .map(|_| module.clone())
1936 match module.parent_link.clone() {
1937 ModuleParentLink(parent, _) => {
1938 search_parent_externals(needle,
1939 &parent.upgrade().unwrap())
1946 let mut search_module = module_;
1947 let mut index = index;
1948 let module_path_len = module_path.len();
1949 let mut closest_private = lp;
1951 // Resolve the module part of the path. This does not involve looking
1952 // upward though scope chains; we simply resolve names directly in
1953 // modules as we go.
1954 while index < module_path_len {
1955 let name = module_path[index];
1956 match self.resolve_name_in_module(search_module.clone(),
1962 let segment_name = token::get_name(name);
1963 let module_name = self.module_to_string(&*search_module);
1964 let mut span = span;
1965 let msg = if "???" == &module_name[] {
1966 span.hi = span.lo + Pos::from_uint(segment_name.get().len());
1968 match search_parent_externals(name,
1969 &self.current_module) {
1971 let path_str = self.names_to_string(module_path);
1972 let target_mod_str = self.module_to_string(&*module);
1973 let current_mod_str =
1974 self.module_to_string(&*self.current_module);
1976 let prefix = if target_mod_str == current_mod_str {
1977 "self::".to_string()
1979 format!("{}::", target_mod_str)
1982 format!("Did you mean `{}{}`?", prefix, path_str)
1984 None => format!("Maybe a missing `extern crate {}`?",
1988 format!("Could not find `{}` in `{}`",
1993 return Failed(Some((span, msg)));
1995 Failed(err) => return Failed(err),
1997 debug!("(resolving module path for import) module \
1998 resolution is indeterminate: {}",
1999 token::get_name(name));
2000 return Indeterminate;
2002 Success((target, used_proxy)) => {
2003 // Check to see whether there are type bindings, and, if
2004 // so, whether there is a module within.
2005 match *target.bindings.type_def.borrow() {
2006 Some(ref type_def) => {
2007 match type_def.module_def {
2009 let msg = format!("Not a module `{}`",
2010 token::get_name(name));
2012 return Failed(Some((span, msg)));
2014 Some(ref module_def) => {
2015 search_module = module_def.clone();
2017 // track extern crates for unused_extern_crate lint
2018 if let Some(did) = module_def.def_id.get() {
2019 self.used_crates.insert(did.krate);
2022 // Keep track of the closest
2023 // private module used when
2024 // resolving this import chain.
2025 if !used_proxy && !search_module.is_public {
2026 if let Some(did) = search_module.def_id.get() {
2027 closest_private = LastMod(DependsOn(did));
2034 // There are no type bindings at all.
2035 let msg = format!("Not a module `{}`",
2036 token::get_name(name));
2037 return Failed(Some((span, msg)));
2046 return Success((search_module, closest_private));
2049 /// Attempts to resolve the module part of an import directive or path
2050 /// rooted at the given module.
2052 /// On success, returns the resolved module, and the closest *private*
2053 /// module found to the destination when resolving this path.
2054 fn resolve_module_path(&mut self,
2055 module_: Rc<Module>,
2056 module_path: &[Name],
2057 use_lexical_scope: UseLexicalScopeFlag,
2059 name_search_type: NameSearchType)
2060 -> ResolveResult<(Rc<Module>, LastPrivate)> {
2061 let module_path_len = module_path.len();
2062 assert!(module_path_len > 0);
2064 debug!("(resolving module path for import) processing `{}` rooted at `{}`",
2065 self.names_to_string(module_path),
2066 self.module_to_string(&*module_));
2068 // Resolve the module prefix, if any.
2069 let module_prefix_result = self.resolve_module_prefix(module_.clone(),
2075 match module_prefix_result {
2077 let mpath = self.names_to_string(module_path);
2078 let mpath = &mpath[];
2079 match mpath.rfind(':') {
2081 let msg = format!("Could not find `{}` in `{}`",
2082 // idx +- 1 to account for the
2083 // colons on either side
2084 &mpath[(idx + 1)..],
2085 &mpath[..(idx - 1)]);
2086 return Failed(Some((span, msg)));
2093 Failed(err) => return Failed(err),
2095 debug!("(resolving module path for import) indeterminate; \
2097 return Indeterminate;
2099 Success(NoPrefixFound) => {
2100 // There was no prefix, so we're considering the first element
2101 // of the path. How we handle this depends on whether we were
2102 // instructed to use lexical scope or not.
2103 match use_lexical_scope {
2104 DontUseLexicalScope => {
2105 // This is a crate-relative path. We will start the
2106 // resolution process at index zero.
2107 search_module = self.graph_root.get_module();
2109 last_private = LastMod(AllPublic);
2111 UseLexicalScope => {
2112 // This is not a crate-relative path. We resolve the
2113 // first component of the path in the current lexical
2114 // scope and then proceed to resolve below that.
2115 match self.resolve_module_in_lexical_scope(module_,
2117 Failed(err) => return Failed(err),
2119 debug!("(resolving module path for import) \
2120 indeterminate; bailing");
2121 return Indeterminate;
2123 Success(containing_module) => {
2124 search_module = containing_module;
2126 last_private = LastMod(AllPublic);
2132 Success(PrefixFound(ref containing_module, index)) => {
2133 search_module = containing_module.clone();
2134 start_index = index;
2135 last_private = LastMod(DependsOn(containing_module.def_id
2141 self.resolve_module_path_from_root(search_module,
2149 /// Invariant: This must only be called during main resolution, not during
2150 /// import resolution.
2151 fn resolve_item_in_lexical_scope(&mut self,
2152 module_: Rc<Module>,
2154 namespace: Namespace)
2155 -> ResolveResult<(Target, bool)> {
2156 debug!("(resolving item in lexical scope) resolving `{}` in \
2157 namespace {:?} in `{}`",
2158 token::get_name(name),
2160 self.module_to_string(&*module_));
2162 // The current module node is handled specially. First, check for
2163 // its immediate children.
2164 build_reduced_graph::populate_module_if_necessary(self, &module_);
2166 match module_.children.borrow().get(&name) {
2168 if name_bindings.defined_in_namespace(namespace) => {
2169 debug!("top name bindings succeeded");
2170 return Success((Target::new(module_.clone(),
2171 name_bindings.clone(),
2175 Some(_) | None => { /* Not found; continue. */ }
2178 // Now check for its import directives. We don't have to have resolved
2179 // all its imports in the usual way; this is because chains of
2180 // adjacent import statements are processed as though they mutated the
2182 if let Some(import_resolution) = module_.import_resolutions.borrow().get(&name) {
2183 match (*import_resolution).target_for_namespace(namespace) {
2185 // Not found; continue.
2186 debug!("(resolving item in lexical scope) found \
2187 import resolution, but not in namespace {:?}",
2191 debug!("(resolving item in lexical scope) using \
2192 import resolution");
2193 // track used imports and extern crates as well
2194 let id = import_resolution.id(namespace);
2195 self.used_imports.insert((id, namespace));
2196 self.record_import_use(id, name);
2197 if let Some(DefId{krate: kid, ..}) = target.target_module.def_id.get() {
2198 self.used_crates.insert(kid);
2200 return Success((target, false));
2205 // Search for external modules.
2206 if namespace == TypeNS {
2207 if let Some(module) = module_.external_module_children.borrow().get(&name).cloned() {
2209 Rc::new(Resolver::create_name_bindings_from_module(module));
2210 debug!("lower name bindings succeeded");
2211 return Success((Target::new(module_,
2218 // Finally, proceed up the scope chain looking for parent modules.
2219 let mut search_module = module_;
2221 // Go to the next parent.
2222 match search_module.parent_link.clone() {
2224 // No more parents. This module was unresolved.
2225 debug!("(resolving item in lexical scope) unresolved \
2227 return Failed(None);
2229 ModuleParentLink(parent_module_node, _) => {
2230 match search_module.kind.get() {
2231 NormalModuleKind => {
2232 // We stop the search here.
2233 debug!("(resolving item in lexical \
2234 scope) unresolved module: not \
2235 searching through module \
2237 return Failed(None);
2242 AnonymousModuleKind => {
2243 search_module = parent_module_node.upgrade().unwrap();
2247 BlockParentLink(ref parent_module_node, _) => {
2248 search_module = parent_module_node.upgrade().unwrap();
2252 // Resolve the name in the parent module.
2253 match self.resolve_name_in_module(search_module.clone(),
2258 Failed(Some((span, msg))) =>
2259 self.resolve_error(span, &format!("failed to resolve. {}",
2261 Failed(None) => (), // Continue up the search chain.
2263 // We couldn't see through the higher scope because of an
2264 // unresolved import higher up. Bail.
2266 debug!("(resolving item in lexical scope) indeterminate \
2267 higher scope; bailing");
2268 return Indeterminate;
2270 Success((target, used_reexport)) => {
2271 // We found the module.
2272 debug!("(resolving item in lexical scope) found name \
2274 return Success((target, used_reexport));
2280 /// Resolves a module name in the current lexical scope.
2281 fn resolve_module_in_lexical_scope(&mut self,
2282 module_: Rc<Module>,
2284 -> ResolveResult<Rc<Module>> {
2285 // If this module is an anonymous module, resolve the item in the
2286 // lexical scope. Otherwise, resolve the item from the crate root.
2287 let resolve_result = self.resolve_item_in_lexical_scope(module_, name, TypeNS);
2288 match resolve_result {
2289 Success((target, _)) => {
2290 let bindings = &*target.bindings;
2291 match *bindings.type_def.borrow() {
2292 Some(ref type_def) => {
2293 match type_def.module_def {
2295 debug!("!!! (resolving module in lexical \
2296 scope) module wasn't actually a \
2298 return Failed(None);
2300 Some(ref module_def) => {
2301 return Success(module_def.clone());
2306 debug!("!!! (resolving module in lexical scope) module
2307 wasn't actually a module!");
2308 return Failed(None);
2313 debug!("(resolving module in lexical scope) indeterminate; \
2315 return Indeterminate;
2318 debug!("(resolving module in lexical scope) failed to resolve");
2324 /// Returns the nearest normal module parent of the given module.
2325 fn get_nearest_normal_module_parent(&mut self, module_: Rc<Module>)
2326 -> Option<Rc<Module>> {
2327 let mut module_ = module_;
2329 match module_.parent_link.clone() {
2330 NoParentLink => return None,
2331 ModuleParentLink(new_module, _) |
2332 BlockParentLink(new_module, _) => {
2333 let new_module = new_module.upgrade().unwrap();
2334 match new_module.kind.get() {
2335 NormalModuleKind => return Some(new_module),
2339 AnonymousModuleKind => module_ = new_module,
2346 /// Returns the nearest normal module parent of the given module, or the
2347 /// module itself if it is a normal module.
2348 fn get_nearest_normal_module_parent_or_self(&mut self, module_: Rc<Module>)
2350 match module_.kind.get() {
2351 NormalModuleKind => return module_,
2355 AnonymousModuleKind => {
2356 match self.get_nearest_normal_module_parent(module_.clone()) {
2358 Some(new_module) => new_module
2364 /// Resolves a "module prefix". A module prefix is one or both of (a) `self::`;
2365 /// (b) some chain of `super::`.
2366 /// grammar: (SELF MOD_SEP ) ? (SUPER MOD_SEP) *
2367 fn resolve_module_prefix(&mut self,
2368 module_: Rc<Module>,
2369 module_path: &[Name])
2370 -> ResolveResult<ModulePrefixResult> {
2371 // Start at the current module if we see `self` or `super`, or at the
2372 // top of the crate otherwise.
2373 let mut containing_module;
2375 let first_module_path_string = token::get_name(module_path[0]);
2376 if "self" == first_module_path_string.get() {
2378 self.get_nearest_normal_module_parent_or_self(module_);
2380 } else if "super" == first_module_path_string.get() {
2382 self.get_nearest_normal_module_parent_or_self(module_);
2383 i = 0; // We'll handle `super` below.
2385 return Success(NoPrefixFound);
2388 // Now loop through all the `super`s we find.
2389 while i < module_path.len() {
2390 let string = token::get_name(module_path[i]);
2391 if "super" != string.get() {
2394 debug!("(resolving module prefix) resolving `super` at {}",
2395 self.module_to_string(&*containing_module));
2396 match self.get_nearest_normal_module_parent(containing_module) {
2397 None => return Failed(None),
2398 Some(new_module) => {
2399 containing_module = new_module;
2405 debug!("(resolving module prefix) finished resolving prefix at {}",
2406 self.module_to_string(&*containing_module));
2408 return Success(PrefixFound(containing_module, i));
2411 /// Attempts to resolve the supplied name in the given module for the
2412 /// given namespace. If successful, returns the target corresponding to
2415 /// The boolean returned on success is an indicator of whether this lookup
2416 /// passed through a public re-export proxy.
2417 fn resolve_name_in_module(&mut self,
2418 module_: Rc<Module>,
2420 namespace: Namespace,
2421 name_search_type: NameSearchType,
2422 allow_private_imports: bool)
2423 -> ResolveResult<(Target, bool)> {
2424 debug!("(resolving name in module) resolving `{}` in `{}`",
2425 token::get_name(name).get(),
2426 self.module_to_string(&*module_));
2428 // First, check the direct children of the module.
2429 build_reduced_graph::populate_module_if_necessary(self, &module_);
2431 match module_.children.borrow().get(&name) {
2433 if name_bindings.defined_in_namespace(namespace) => {
2434 debug!("(resolving name in module) found node as child");
2435 return Success((Target::new(module_.clone(),
2436 name_bindings.clone(),
2445 // Next, check the module's imports if necessary.
2447 // If this is a search of all imports, we should be done with glob
2448 // resolution at this point.
2449 if name_search_type == PathSearch {
2450 assert_eq!(module_.glob_count.get(), 0);
2453 // Check the list of resolved imports.
2454 match module_.import_resolutions.borrow().get(&name) {
2455 Some(import_resolution) if allow_private_imports ||
2456 import_resolution.is_public => {
2458 if import_resolution.is_public &&
2459 import_resolution.outstanding_references != 0 {
2460 debug!("(resolving name in module) import \
2461 unresolved; bailing out");
2462 return Indeterminate;
2464 match import_resolution.target_for_namespace(namespace) {
2466 debug!("(resolving name in module) name found, \
2467 but not in namespace {:?}",
2471 debug!("(resolving name in module) resolved to \
2473 // track used imports and extern crates as well
2474 let id = import_resolution.id(namespace);
2475 self.used_imports.insert((id, namespace));
2476 self.record_import_use(id, name);
2477 if let Some(DefId{krate: kid, ..}) = target.target_module.def_id.get() {
2478 self.used_crates.insert(kid);
2480 return Success((target, true));
2484 Some(..) | None => {} // Continue.
2487 // Finally, search through external children.
2488 if namespace == TypeNS {
2489 if let Some(module) = module_.external_module_children.borrow().get(&name).cloned() {
2491 Rc::new(Resolver::create_name_bindings_from_module(module));
2492 return Success((Target::new(module_,
2499 // We're out of luck.
2500 debug!("(resolving name in module) failed to resolve `{}`",
2501 token::get_name(name).get());
2502 return Failed(None);
2505 fn report_unresolved_imports(&mut self, module_: Rc<Module>) {
2506 let index = module_.resolved_import_count.get();
2507 let imports = module_.imports.borrow();
2508 let import_count = imports.len();
2509 if index != import_count {
2510 let sn = self.session
2512 .span_to_snippet((*imports)[index].span)
2514 if sn.contains("::") {
2515 self.resolve_error((*imports)[index].span,
2516 "unresolved import");
2518 let err = format!("unresolved import (maybe you meant `{}::*`?)",
2520 self.resolve_error((*imports)[index].span, &err[]);
2524 // Descend into children and anonymous children.
2525 build_reduced_graph::populate_module_if_necessary(self, &module_);
2527 for (_, child_node) in module_.children.borrow().iter() {
2528 match child_node.get_module_if_available() {
2532 Some(child_module) => {
2533 self.report_unresolved_imports(child_module);
2538 for (_, module_) in module_.anonymous_children.borrow().iter() {
2539 self.report_unresolved_imports(module_.clone());
2545 // We maintain a list of value ribs and type ribs.
2547 // Simultaneously, we keep track of the current position in the module
2548 // graph in the `current_module` pointer. When we go to resolve a name in
2549 // the value or type namespaces, we first look through all the ribs and
2550 // then query the module graph. When we resolve a name in the module
2551 // namespace, we can skip all the ribs (since nested modules are not
2552 // allowed within blocks in Rust) and jump straight to the current module
2555 // Named implementations are handled separately. When we find a method
2556 // call, we consult the module node to find all of the implementations in
2557 // scope. This information is lazily cached in the module node. We then
2558 // generate a fake "implementation scope" containing all the
2559 // implementations thus found, for compatibility with old resolve pass.
2561 fn with_scope<F>(&mut self, name: Option<Name>, f: F) where
2562 F: FnOnce(&mut Resolver),
2564 let orig_module = self.current_module.clone();
2566 // Move down in the graph.
2572 build_reduced_graph::populate_module_if_necessary(self, &orig_module);
2574 match orig_module.children.borrow().get(&name) {
2576 debug!("!!! (with scope) didn't find `{}` in `{}`",
2577 token::get_name(name),
2578 self.module_to_string(&*orig_module));
2580 Some(name_bindings) => {
2581 match (*name_bindings).get_module_if_available() {
2583 debug!("!!! (with scope) didn't find module \
2585 token::get_name(name),
2586 self.module_to_string(&*orig_module));
2589 self.current_module = module_;
2599 self.current_module = orig_module;
2602 /// Wraps the given definition in the appropriate number of `DefUpvar`
2608 -> Option<DefLike> {
2610 DlDef(d @ DefUpvar(..)) => {
2611 self.session.span_bug(span,
2612 &format!("unexpected {:?} in bindings", d)[])
2614 DlDef(d @ DefLocal(_)) => {
2615 let node_id = d.def_id().node;
2617 let mut last_proc_body_id = ast::DUMMY_NODE_ID;
2618 for rib in ribs.iter() {
2621 // Nothing to do. Continue.
2623 ClosureRibKind(function_id, maybe_proc_body) => {
2625 if maybe_proc_body != ast::DUMMY_NODE_ID {
2626 last_proc_body_id = maybe_proc_body;
2628 def = DefUpvar(node_id, function_id, last_proc_body_id);
2630 let mut seen = self.freevars_seen.borrow_mut();
2631 let seen = match seen.entry(function_id) {
2632 Occupied(v) => v.into_mut(),
2633 Vacant(v) => v.insert(NodeSet::new()),
2635 if seen.contains(&node_id) {
2638 match self.freevars.borrow_mut().entry(function_id) {
2639 Occupied(v) => v.into_mut(),
2640 Vacant(v) => v.insert(vec![]),
2641 }.push(Freevar { def: prev_def, span: span });
2642 seen.insert(node_id);
2644 MethodRibKind(item_id, _) => {
2645 // If the def is a ty param, and came from the parent
2648 DefTyParam(_, _, did, _) if {
2649 self.def_map.borrow().get(&did.node).cloned()
2650 == Some(DefTyParamBinder(item_id))
2652 DefSelfTy(did) if did == item_id => {} // ok
2654 // This was an attempt to access an upvar inside a
2655 // named function item. This is not allowed, so we
2660 "can't capture dynamic environment in a fn item; \
2661 use the || { ... } closure form instead");
2668 // This was an attempt to access an upvar inside a
2669 // named function item. This is not allowed, so we
2674 "can't capture dynamic environment in a fn item; \
2675 use the || { ... } closure form instead");
2679 ConstantItemRibKind => {
2680 // Still doesn't deal with upvars
2681 self.resolve_error(span,
2682 "attempt to use a non-constant \
2683 value in a constant");
2690 DlDef(def @ DefTyParam(..)) |
2691 DlDef(def @ DefSelfTy(..)) => {
2692 for rib in ribs.iter() {
2694 NormalRibKind | ClosureRibKind(..) => {
2695 // Nothing to do. Continue.
2697 MethodRibKind(item_id, _) => {
2698 // If the def is a ty param, and came from the parent
2701 DefTyParam(_, _, did, _) if {
2702 self.def_map.borrow().get(&did.node).cloned()
2703 == Some(DefTyParamBinder(item_id))
2705 DefSelfTy(did) if did == item_id => {} // ok
2708 // This was an attempt to use a type parameter outside
2711 self.resolve_error(span,
2712 "can't use type parameters from \
2713 outer function; try using a local \
2714 type parameter instead");
2721 // This was an attempt to use a type parameter outside
2724 self.resolve_error(span,
2725 "can't use type parameters from \
2726 outer function; try using a local \
2727 type parameter instead");
2731 ConstantItemRibKind => {
2733 self.resolve_error(span,
2734 "cannot use an outer type \
2735 parameter in this context");
2746 /// Searches the current set of local scopes and
2747 /// applies translations for closures.
2748 fn search_ribs(&self,
2752 -> Option<DefLike> {
2753 // FIXME #4950: Try caching?
2755 for (i, rib) in ribs.iter().enumerate().rev() {
2756 match rib.bindings.get(&name).cloned() {
2758 return self.upvarify(&ribs[(i + 1)..], def_like, span);
2769 /// Searches the current set of local scopes for labels.
2770 /// Stops after meeting a closure.
2771 fn search_label(&self, name: Name) -> Option<DefLike> {
2772 for rib in self.label_ribs.iter().rev() {
2778 // Do not resolve labels across function boundary
2782 let result = rib.bindings.get(&name).cloned();
2783 if result.is_some() {
2790 fn resolve_crate(&mut self, krate: &ast::Crate) {
2791 debug!("(resolving crate) starting");
2793 visit::walk_crate(self, krate);
2796 fn resolve_item(&mut self, item: &Item) {
2797 let name = item.ident.name;
2799 debug!("(resolving item) resolving {}",
2800 token::get_name(name));
2804 // enum item: resolve all the variants' discrs,
2805 // then resolve the ty params
2806 ItemEnum(ref enum_def, ref generics) => {
2807 for variant in (*enum_def).variants.iter() {
2808 for dis_expr in variant.node.disr_expr.iter() {
2809 // resolve the discriminator expr
2811 self.with_constant_rib(|this| {
2812 this.resolve_expr(&**dis_expr);
2817 // n.b. the discr expr gets visited twice.
2818 // but maybe it's okay since the first time will signal an
2819 // error if there is one? -- tjc
2820 self.with_type_parameter_rib(HasTypeParameters(generics,
2825 this.resolve_type_parameters(&generics.ty_params);
2826 this.resolve_where_clause(&generics.where_clause);
2827 visit::walk_item(this, item);
2831 ItemTy(_, ref generics) => {
2832 self.with_type_parameter_rib(HasTypeParameters(generics,
2837 this.resolve_type_parameters(&generics.ty_params);
2838 visit::walk_item(this, item);
2844 ref implemented_traits,
2846 ref impl_items) => {
2847 self.resolve_implementation(item.id,
2854 ItemTrait(_, ref generics, ref bounds, ref trait_items) => {
2855 // Create a new rib for the self type.
2856 let mut self_type_rib = Rib::new(ItemRibKind);
2858 // plain insert (no renaming, types are not currently hygienic....)
2859 let name = self.type_self_name;
2860 self_type_rib.bindings.insert(name, DlDef(DefSelfTy(item.id)));
2861 self.type_ribs.push(self_type_rib);
2863 // Create a new rib for the trait-wide type parameters.
2864 self.with_type_parameter_rib(HasTypeParameters(generics,
2869 this.resolve_type_parameters(&generics.ty_params);
2870 this.resolve_where_clause(&generics.where_clause);
2872 this.resolve_type_parameter_bounds(item.id, bounds,
2875 for trait_item in (*trait_items).iter() {
2876 // Create a new rib for the trait_item-specific type
2879 // FIXME #4951: Do we need a node ID here?
2882 ast::RequiredMethod(ref ty_m) => {
2883 this.with_type_parameter_rib
2884 (HasTypeParameters(&ty_m.generics,
2887 MethodRibKind(item.id, RequiredMethod)),
2890 // Resolve the method-specific type
2892 this.resolve_type_parameters(
2893 &ty_m.generics.ty_params);
2894 this.resolve_where_clause(&ty_m.generics
2897 for argument in ty_m.decl.inputs.iter() {
2898 this.resolve_type(&*argument.ty);
2901 if let SelfExplicit(ref typ, _) = ty_m.explicit_self.node {
2902 this.resolve_type(&**typ)
2905 if let ast::Return(ref ret_ty) = ty_m.decl.output {
2906 this.resolve_type(&**ret_ty);
2910 ast::ProvidedMethod(ref m) => {
2911 this.resolve_method(MethodRibKind(item.id,
2912 ProvidedMethod(m.id)),
2915 ast::TypeTraitItem(ref data) => {
2916 this.resolve_type_parameter(&data.ty_param);
2917 visit::walk_trait_item(this, trait_item);
2923 self.type_ribs.pop();
2926 ItemStruct(ref struct_def, ref generics) => {
2927 self.resolve_struct(item.id,
2929 &struct_def.fields[]);
2932 ItemMod(ref module_) => {
2933 self.with_scope(Some(name), |this| {
2934 this.resolve_module(module_, item.span, name,
2939 ItemForeignMod(ref foreign_module) => {
2940 self.with_scope(Some(name), |this| {
2941 for foreign_item in foreign_module.items.iter() {
2942 match foreign_item.node {
2943 ForeignItemFn(_, ref generics) => {
2944 this.with_type_parameter_rib(
2946 generics, FnSpace, foreign_item.id,
2949 this.resolve_type_parameters(&generics.ty_params);
2950 this.resolve_where_clause(&generics.where_clause);
2951 visit::walk_foreign_item(this, &**foreign_item)
2954 ForeignItemStatic(..) => {
2955 visit::walk_foreign_item(this,
2963 ItemFn(ref fn_decl, _, _, ref generics, ref block) => {
2964 self.resolve_function(ItemRibKind,
2974 ItemConst(..) | ItemStatic(..) => {
2975 self.with_constant_rib(|this| {
2976 visit::walk_item(this, item);
2981 // do nothing, these are just around to be encoded
2986 fn with_type_parameter_rib<F>(&mut self, type_parameters: TypeParameters, f: F) where
2987 F: FnOnce(&mut Resolver),
2989 match type_parameters {
2990 HasTypeParameters(generics, space, node_id, rib_kind) => {
2991 let mut function_type_rib = Rib::new(rib_kind);
2992 let mut seen_bindings = HashSet::new();
2993 for (index, type_parameter) in generics.ty_params.iter().enumerate() {
2994 let name = type_parameter.ident.name;
2995 debug!("with_type_parameter_rib: {} {}", node_id,
2998 if seen_bindings.contains(&name) {
2999 self.resolve_error(type_parameter.span,
3000 &format!("the name `{}` is already \
3002 parameter in this type \
3007 seen_bindings.insert(name);
3009 let def_like = DlDef(DefTyParam(space,
3011 local_def(type_parameter.id),
3013 // Associate this type parameter with
3014 // the item that bound it
3015 self.record_def(type_parameter.id,
3016 (DefTyParamBinder(node_id), LastMod(AllPublic)));
3017 // plain insert (no renaming)
3018 function_type_rib.bindings.insert(name, def_like);
3020 self.type_ribs.push(function_type_rib);
3023 NoTypeParameters => {
3030 match type_parameters {
3031 HasTypeParameters(..) => { self.type_ribs.pop(); }
3032 NoTypeParameters => { }
3036 fn with_label_rib<F>(&mut self, f: F) where
3037 F: FnOnce(&mut Resolver),
3039 self.label_ribs.push(Rib::new(NormalRibKind));
3041 self.label_ribs.pop();
3044 fn with_constant_rib<F>(&mut self, f: F) where
3045 F: FnOnce(&mut Resolver),
3047 self.value_ribs.push(Rib::new(ConstantItemRibKind));
3048 self.type_ribs.push(Rib::new(ConstantItemRibKind));
3050 self.type_ribs.pop();
3051 self.value_ribs.pop();
3054 fn resolve_function(&mut self,
3056 optional_declaration: Option<&FnDecl>,
3057 type_parameters: TypeParameters,
3059 // Create a value rib for the function.
3060 let function_value_rib = Rib::new(rib_kind);
3061 self.value_ribs.push(function_value_rib);
3063 // Create a label rib for the function.
3064 let function_label_rib = Rib::new(rib_kind);
3065 self.label_ribs.push(function_label_rib);
3067 // If this function has type parameters, add them now.
3068 self.with_type_parameter_rib(type_parameters, |this| {
3069 // Resolve the type parameters.
3070 match type_parameters {
3071 NoTypeParameters => {
3074 HasTypeParameters(ref generics, _, _, _) => {
3075 this.resolve_type_parameters(&generics.ty_params);
3076 this.resolve_where_clause(&generics.where_clause);
3080 // Add each argument to the rib.
3081 match optional_declaration {
3085 Some(declaration) => {
3086 let mut bindings_list = HashMap::new();
3087 for argument in declaration.inputs.iter() {
3088 this.resolve_pattern(&*argument.pat,
3089 ArgumentIrrefutableMode,
3090 &mut bindings_list);
3092 this.resolve_type(&*argument.ty);
3094 debug!("(resolving function) recorded argument");
3097 if let ast::Return(ref ret_ty) = declaration.output {
3098 this.resolve_type(&**ret_ty);
3103 // Resolve the function body.
3104 this.resolve_block(&*block);
3106 debug!("(resolving function) leaving function");
3109 self.label_ribs.pop();
3110 self.value_ribs.pop();
3113 fn resolve_type_parameters(&mut self,
3114 type_parameters: &OwnedSlice<TyParam>) {
3115 for type_parameter in type_parameters.iter() {
3116 self.resolve_type_parameter(type_parameter);
3120 fn resolve_type_parameter(&mut self,
3121 type_parameter: &TyParam) {
3122 for bound in type_parameter.bounds.iter() {
3123 self.resolve_type_parameter_bound(type_parameter.id, bound,
3124 TraitBoundingTypeParameter);
3126 match type_parameter.default {
3127 Some(ref ty) => self.resolve_type(&**ty),
3132 fn resolve_type_parameter_bounds(&mut self,
3134 type_parameter_bounds: &OwnedSlice<TyParamBound>,
3135 reference_type: TraitReferenceType) {
3136 for type_parameter_bound in type_parameter_bounds.iter() {
3137 self.resolve_type_parameter_bound(id, type_parameter_bound,
3142 fn resolve_type_parameter_bound(&mut self,
3144 type_parameter_bound: &TyParamBound,
3145 reference_type: TraitReferenceType) {
3146 match *type_parameter_bound {
3147 TraitTyParamBound(ref tref, _) => {
3148 self.resolve_poly_trait_reference(id, tref, reference_type)
3150 RegionTyParamBound(..) => {}
3154 fn resolve_poly_trait_reference(&mut self,
3156 poly_trait_reference: &PolyTraitRef,
3157 reference_type: TraitReferenceType) {
3158 self.resolve_trait_reference(id, &poly_trait_reference.trait_ref, reference_type)
3161 fn resolve_trait_reference(&mut self,
3163 trait_reference: &TraitRef,
3164 reference_type: TraitReferenceType) {
3165 match self.resolve_path(id, &trait_reference.path, TypeNS, true) {
3167 let path_str = self.path_names_to_string(&trait_reference.path);
3168 let usage_str = match reference_type {
3169 TraitBoundingTypeParameter => "bound type parameter with",
3170 TraitImplementation => "implement",
3171 TraitDerivation => "derive",
3172 TraitObject => "reference",
3173 TraitQPath => "extract an associated item from",
3176 let msg = format!("attempt to {} a nonexistent trait `{}`", usage_str, path_str);
3177 self.resolve_error(trait_reference.path.span, &msg[]);
3181 (DefTrait(_), _) => {
3182 debug!("(resolving trait) found trait def: {:?}", def);
3183 self.record_def(trait_reference.ref_id, def);
3186 self.resolve_error(trait_reference.path.span,
3187 &format!("`{}` is not a trait",
3188 self.path_names_to_string(
3189 &trait_reference.path))[]);
3191 // If it's a typedef, give a note
3192 if let DefTy(..) = def {
3193 self.session.span_note(
3194 trait_reference.path.span,
3195 &format!("`type` aliases cannot be used for traits")
3204 fn resolve_where_clause(&mut self, where_clause: &ast::WhereClause) {
3205 for predicate in where_clause.predicates.iter() {
3207 &ast::WherePredicate::BoundPredicate(ref bound_pred) => {
3208 self.resolve_type(&*bound_pred.bounded_ty);
3210 for bound in bound_pred.bounds.iter() {
3211 self.resolve_type_parameter_bound(bound_pred.bounded_ty.id, bound,
3212 TraitBoundingTypeParameter);
3215 &ast::WherePredicate::RegionPredicate(_) => {}
3216 &ast::WherePredicate::EqPredicate(ref eq_pred) => {
3217 match self.resolve_path(eq_pred.id, &eq_pred.path, TypeNS, true) {
3218 Some((def @ DefTyParam(..), last_private)) => {
3219 self.record_def(eq_pred.id, (def, last_private));
3222 self.resolve_error(eq_pred.path.span,
3223 "undeclared associated type");
3227 self.resolve_type(&*eq_pred.ty);
3233 fn resolve_struct(&mut self,
3235 generics: &Generics,
3236 fields: &[StructField]) {
3237 // If applicable, create a rib for the type parameters.
3238 self.with_type_parameter_rib(HasTypeParameters(generics,
3243 // Resolve the type parameters.
3244 this.resolve_type_parameters(&generics.ty_params);
3245 this.resolve_where_clause(&generics.where_clause);
3248 for field in fields.iter() {
3249 this.resolve_type(&*field.node.ty);
3254 // Does this really need to take a RibKind or is it always going
3255 // to be NormalRibKind?
3256 fn resolve_method(&mut self,
3258 method: &ast::Method) {
3259 let method_generics = method.pe_generics();
3260 let type_parameters = HasTypeParameters(method_generics,
3265 if let SelfExplicit(ref typ, _) = method.pe_explicit_self().node {
3266 self.resolve_type(&**typ);
3269 self.resolve_function(rib_kind,
3270 Some(method.pe_fn_decl()),
3275 fn with_current_self_type<T, F>(&mut self, self_type: &Ty, f: F) -> T where
3276 F: FnOnce(&mut Resolver) -> T,
3278 // Handle nested impls (inside fn bodies)
3279 let previous_value = replace(&mut self.current_self_type, Some(self_type.clone()));
3280 let result = f(self);
3281 self.current_self_type = previous_value;
3285 fn with_optional_trait_ref<T, F>(&mut self, id: NodeId,
3286 opt_trait_ref: &Option<TraitRef>,
3288 F: FnOnce(&mut Resolver) -> T,
3290 let new_val = match *opt_trait_ref {
3291 Some(ref trait_ref) => {
3292 self.resolve_trait_reference(id, trait_ref, TraitImplementation);
3294 match self.def_map.borrow().get(&trait_ref.ref_id) {
3296 let did = def.def_id();
3297 Some((did, trait_ref.clone()))
3304 let original_trait_ref = replace(&mut self.current_trait_ref, new_val);
3305 let result = f(self);
3306 self.current_trait_ref = original_trait_ref;
3310 fn resolve_implementation(&mut self,
3312 generics: &Generics,
3313 opt_trait_reference: &Option<TraitRef>,
3315 impl_items: &[ImplItem]) {
3316 // If applicable, create a rib for the type parameters.
3317 self.with_type_parameter_rib(HasTypeParameters(generics,
3322 // Resolve the type parameters.
3323 this.resolve_type_parameters(&generics.ty_params);
3324 this.resolve_where_clause(&generics.where_clause);
3326 // Resolve the trait reference, if necessary.
3327 this.with_optional_trait_ref(id, opt_trait_reference, |this| {
3328 // Resolve the self type.
3329 this.resolve_type(self_type);
3331 this.with_current_self_type(self_type, |this| {
3332 for impl_item in impl_items.iter() {
3334 MethodImplItem(ref method) => {
3335 // If this is a trait impl, ensure the method
3337 this.check_trait_item(method.pe_ident().name,
3340 // We also need a new scope for the method-
3341 // specific type parameters.
3342 this.resolve_method(
3343 MethodRibKind(id, ProvidedMethod(method.id)),
3346 TypeImplItem(ref typedef) => {
3347 // If this is a trait impl, ensure the method
3349 this.check_trait_item(typedef.ident.name,
3352 this.resolve_type(&*typedef.typ);
3360 // Check that the current type is indeed a type, if we have an anonymous impl
3361 if opt_trait_reference.is_none() {
3362 match self_type.node {
3363 // TyPath is the only thing that we handled in `build_reduced_graph_for_item`,
3364 // where we created a module with the name of the type in order to implement
3365 // an anonymous trait. In the case that the path does not resolve to an actual
3366 // type, the result will be that the type name resolves to a module but not
3367 // a type (shadowing any imported modules or types with this name), leading
3368 // to weird user-visible bugs. So we ward this off here. See #15060.
3369 TyPath(ref path, path_id) => {
3370 match self.def_map.borrow().get(&path_id) {
3371 // FIXME: should we catch other options and give more precise errors?
3372 Some(&DefMod(_)) => {
3373 self.resolve_error(path.span, "inherent implementations are not \
3374 allowed for types not defined in \
3375 the current module");
3385 fn check_trait_item(&self, name: Name, span: Span) {
3386 // If there is a TraitRef in scope for an impl, then the method must be in the trait.
3387 for &(did, ref trait_ref) in self.current_trait_ref.iter() {
3388 if self.trait_item_map.get(&(name, did)).is_none() {
3389 let path_str = self.path_names_to_string(&trait_ref.path);
3390 self.resolve_error(span,
3391 &format!("method `{}` is not a member of trait `{}`",
3392 token::get_name(name),
3398 fn resolve_module(&mut self, module: &Mod, _span: Span,
3399 _name: Name, id: NodeId) {
3400 // Write the implementations in scope into the module metadata.
3401 debug!("(resolving module) resolving module ID {}", id);
3402 visit::walk_mod(self, module);
3405 fn resolve_local(&mut self, local: &Local) {
3406 // Resolve the type.
3407 if let Some(ref ty) = local.ty {
3408 self.resolve_type(&**ty);
3411 // Resolve the initializer, if necessary.
3416 Some(ref initializer) => {
3417 self.resolve_expr(&**initializer);
3421 // Resolve the pattern.
3422 let mut bindings_list = HashMap::new();
3423 self.resolve_pattern(&*local.pat,
3424 LocalIrrefutableMode,
3425 &mut bindings_list);
3428 // build a map from pattern identifiers to binding-info's.
3429 // this is done hygienically. This could arise for a macro
3430 // that expands into an or-pattern where one 'x' was from the
3431 // user and one 'x' came from the macro.
3432 fn binding_mode_map(&mut self, pat: &Pat) -> BindingMap {
3433 let mut result = HashMap::new();
3434 pat_bindings(&self.def_map, pat, |binding_mode, _id, sp, path1| {
3435 let name = mtwt::resolve(path1.node);
3436 result.insert(name, BindingInfo {
3438 binding_mode: binding_mode
3444 // check that all of the arms in an or-pattern have exactly the
3445 // same set of bindings, with the same binding modes for each.
3446 fn check_consistent_bindings(&mut self, arm: &Arm) {
3447 if arm.pats.len() == 0 {
3450 let map_0 = self.binding_mode_map(&*arm.pats[0]);
3451 for (i, p) in arm.pats.iter().enumerate() {
3452 let map_i = self.binding_mode_map(&**p);
3454 for (&key, &binding_0) in map_0.iter() {
3455 match map_i.get(&key) {
3459 &format!("variable `{}` from pattern #1 is \
3460 not bound in pattern #{}",
3461 token::get_name(key),
3464 Some(binding_i) => {
3465 if binding_0.binding_mode != binding_i.binding_mode {
3468 &format!("variable `{}` is bound with different \
3469 mode in pattern #{} than in pattern #1",
3470 token::get_name(key),
3477 for (&key, &binding) in map_i.iter() {
3478 if !map_0.contains_key(&key) {
3481 &format!("variable `{}` from pattern {}{} is \
3482 not bound in pattern {}1",
3483 token::get_name(key),
3484 "#", i + 1, "#")[]);
3490 fn resolve_arm(&mut self, arm: &Arm) {
3491 self.value_ribs.push(Rib::new(NormalRibKind));
3493 let mut bindings_list = HashMap::new();
3494 for pattern in arm.pats.iter() {
3495 self.resolve_pattern(&**pattern, RefutableMode, &mut bindings_list);
3498 // This has to happen *after* we determine which
3499 // pat_idents are variants
3500 self.check_consistent_bindings(arm);
3502 visit::walk_expr_opt(self, &arm.guard);
3503 self.resolve_expr(&*arm.body);
3505 self.value_ribs.pop();
3508 fn resolve_block(&mut self, block: &Block) {
3509 debug!("(resolving block) entering block");
3510 self.value_ribs.push(Rib::new(NormalRibKind));
3512 // Move down in the graph, if there's an anonymous module rooted here.
3513 let orig_module = self.current_module.clone();
3514 match orig_module.anonymous_children.borrow().get(&block.id) {
3515 None => { /* Nothing to do. */ }
3516 Some(anonymous_module) => {
3517 debug!("(resolving block) found anonymous module, moving \
3519 self.current_module = anonymous_module.clone();
3523 // Descend into the block.
3524 visit::walk_block(self, block);
3527 self.current_module = orig_module;
3529 self.value_ribs.pop();
3530 debug!("(resolving block) leaving block");
3533 fn resolve_type(&mut self, ty: &Ty) {
3535 // Like path expressions, the interpretation of path types depends
3536 // on whether the path has multiple elements in it or not.
3538 TyPath(ref path, path_id) => {
3539 // This is a path in the type namespace. Walk through scopes
3541 let mut result_def = None;
3543 // First, check to see whether the name is a primitive type.
3544 if path.segments.len() == 1 {
3545 let id = path.segments.last().unwrap().identifier;
3547 match self.primitive_type_table
3551 Some(&primitive_type) => {
3553 Some((DefPrimTy(primitive_type), LastMod(AllPublic)));
3555 if path.segments[0].parameters.has_lifetimes() {
3556 span_err!(self.session, path.span, E0157,
3557 "lifetime parameters are not allowed on this type");
3558 } else if !path.segments[0].parameters.is_empty() {
3559 span_err!(self.session, path.span, E0153,
3560 "type parameters are not allowed on this type");
3569 if let None = result_def {
3570 result_def = self.resolve_path(ty.id, path, TypeNS, true);
3575 // Write the result into the def map.
3576 debug!("(resolving type) writing resolution for `{}` \
3578 self.path_names_to_string(path),
3580 self.record_def(path_id, def);
3583 let msg = format!("use of undeclared type name `{}`",
3584 self.path_names_to_string(path));
3585 self.resolve_error(ty.span, &msg[]);
3590 TyObjectSum(ref ty, ref bound_vec) => {
3591 self.resolve_type(&**ty);
3592 self.resolve_type_parameter_bounds(ty.id, bound_vec,
3593 TraitBoundingTypeParameter);
3596 TyQPath(ref qpath) => {
3597 self.resolve_type(&*qpath.self_type);
3598 self.resolve_trait_reference(ty.id, &*qpath.trait_ref, TraitQPath);
3599 for ty in qpath.item_path.parameters.types().into_iter() {
3600 self.resolve_type(&**ty);
3602 for binding in qpath.item_path.parameters.bindings().into_iter() {
3603 self.resolve_type(&*binding.ty);
3607 TyPolyTraitRef(ref bounds) => {
3608 self.resolve_type_parameter_bounds(
3612 visit::walk_ty(self, ty);
3615 // Just resolve embedded types.
3616 visit::walk_ty(self, ty);
3621 fn resolve_pattern(&mut self,
3623 mode: PatternBindingMode,
3624 // Maps idents to the node ID for the (outermost)
3625 // pattern that binds them
3626 bindings_list: &mut HashMap<Name, NodeId>) {
3627 let pat_id = pattern.id;
3628 walk_pat(pattern, |pattern| {
3629 match pattern.node {
3630 PatIdent(binding_mode, ref path1, _) => {
3632 // The meaning of pat_ident with no type parameters
3633 // depends on whether an enum variant or unit-like struct
3634 // with that name is in scope. The probing lookup has to
3635 // be careful not to emit spurious errors. Only matching
3636 // patterns (match) can match nullary variants or
3637 // unit-like structs. For binding patterns (let), matching
3638 // such a value is simply disallowed (since it's rarely
3641 let ident = path1.node;
3642 let renamed = mtwt::resolve(ident);
3644 match self.resolve_bare_identifier_pattern(ident.name, pattern.span) {
3645 FoundStructOrEnumVariant(ref def, lp)
3646 if mode == RefutableMode => {
3647 debug!("(resolving pattern) resolving `{}` to \
3648 struct or enum variant",
3649 token::get_name(renamed));
3651 self.enforce_default_binding_mode(
3655 self.record_def(pattern.id, (def.clone(), lp));
3657 FoundStructOrEnumVariant(..) => {
3660 &format!("declaration of `{}` shadows an enum \
3661 variant or unit-like struct in \
3663 token::get_name(renamed))[]);
3665 FoundConst(ref def, lp) if mode == RefutableMode => {
3666 debug!("(resolving pattern) resolving `{}` to \
3668 token::get_name(renamed));
3670 self.enforce_default_binding_mode(
3674 self.record_def(pattern.id, (def.clone(), lp));
3677 self.resolve_error(pattern.span,
3678 "only irrefutable patterns \
3681 BareIdentifierPatternUnresolved => {
3682 debug!("(resolving pattern) binding `{}`",
3683 token::get_name(renamed));
3685 let def = DefLocal(pattern.id);
3687 // Record the definition so that later passes
3688 // will be able to distinguish variants from
3689 // locals in patterns.
3691 self.record_def(pattern.id, (def, LastMod(AllPublic)));
3693 // Add the binding to the local ribs, if it
3694 // doesn't already exist in the bindings list. (We
3695 // must not add it if it's in the bindings list
3696 // because that breaks the assumptions later
3697 // passes make about or-patterns.)
3698 if !bindings_list.contains_key(&renamed) {
3699 let this = &mut *self;
3700 let last_rib = this.value_ribs.last_mut().unwrap();
3701 last_rib.bindings.insert(renamed, DlDef(def));
3702 bindings_list.insert(renamed, pat_id);
3703 } else if mode == ArgumentIrrefutableMode &&
3704 bindings_list.contains_key(&renamed) {
3705 // Forbid duplicate bindings in the same
3707 self.resolve_error(pattern.span,
3708 &format!("identifier `{}` \
3716 } else if bindings_list.get(&renamed) ==
3718 // Then this is a duplicate variable in the
3719 // same disjunction, which is an error.
3720 self.resolve_error(pattern.span,
3721 &format!("identifier `{}` is bound \
3722 more than once in the same \
3724 token::get_ident(ident))[]);
3726 // Else, not bound in the same pattern: do
3732 PatEnum(ref path, _) => {
3733 // This must be an enum variant, struct or const.
3734 match self.resolve_path(pat_id, path, ValueNS, false) {
3735 Some(def @ (DefVariant(..), _)) |
3736 Some(def @ (DefStruct(..), _)) |
3737 Some(def @ (DefConst(..), _)) => {
3738 self.record_def(pattern.id, def);
3740 Some((DefStatic(..), _)) => {
3741 self.resolve_error(path.span,
3742 "static variables cannot be \
3743 referenced in a pattern, \
3744 use a `const` instead");
3747 self.resolve_error(path.span,
3748 format!("`{}` is not an enum variant, struct or const",
3750 path.segments.last().unwrap().identifier)).as_slice());
3753 self.resolve_error(path.span,
3754 format!("unresolved enum variant, struct or const `{}`",
3756 path.segments.last().unwrap().identifier)).as_slice());
3760 // Check the types in the path pattern.
3761 for ty in path.segments
3763 .flat_map(|s| s.parameters.types().into_iter()) {
3764 self.resolve_type(&**ty);
3768 PatLit(ref expr) => {
3769 self.resolve_expr(&**expr);
3772 PatRange(ref first_expr, ref last_expr) => {
3773 self.resolve_expr(&**first_expr);
3774 self.resolve_expr(&**last_expr);
3777 PatStruct(ref path, _, _) => {
3778 match self.resolve_path(pat_id, path, TypeNS, false) {
3779 Some(definition) => {
3780 self.record_def(pattern.id, definition);
3783 debug!("(resolving pattern) didn't find struct \
3784 def: {:?}", result);
3785 let msg = format!("`{}` does not name a structure",
3786 self.path_names_to_string(path));
3787 self.resolve_error(path.span, &msg[]);
3800 fn resolve_bare_identifier_pattern(&mut self, name: Name, span: Span)
3801 -> BareIdentifierPatternResolution {
3802 let module = self.current_module.clone();
3803 match self.resolve_item_in_lexical_scope(module,
3806 Success((target, _)) => {
3807 debug!("(resolve bare identifier pattern) succeeded in \
3808 finding {} at {:?}",
3809 token::get_name(name),
3810 target.bindings.value_def.borrow());
3811 match *target.bindings.value_def.borrow() {
3813 panic!("resolved name in the value namespace to a \
3814 set of name bindings with no def?!");
3817 // For the two success cases, this lookup can be
3818 // considered as not having a private component because
3819 // the lookup happened only within the current module.
3821 def @ DefVariant(..) | def @ DefStruct(..) => {
3822 return FoundStructOrEnumVariant(def, LastMod(AllPublic));
3824 def @ DefConst(..) => {
3825 return FoundConst(def, LastMod(AllPublic));
3828 self.resolve_error(span,
3829 "static variables cannot be \
3830 referenced in a pattern, \
3831 use a `const` instead");
3832 return BareIdentifierPatternUnresolved;
3835 return BareIdentifierPatternUnresolved;
3843 panic!("unexpected indeterminate result");
3847 Some((span, msg)) => {
3848 self.resolve_error(span, &format!("failed to resolve: {}",
3854 debug!("(resolve bare identifier pattern) failed to find {}",
3855 token::get_name(name));
3856 return BareIdentifierPatternUnresolved;
3861 /// If `check_ribs` is true, checks the local definitions first; i.e.
3862 /// doesn't skip straight to the containing module.
3863 fn resolve_path(&mut self,
3866 namespace: Namespace,
3867 check_ribs: bool) -> Option<(Def, LastPrivate)> {
3868 // First, resolve the types and associated type bindings.
3869 for ty in path.segments.iter().flat_map(|s| s.parameters.types().into_iter()) {
3870 self.resolve_type(&**ty);
3872 for binding in path.segments.iter().flat_map(|s| s.parameters.bindings().into_iter()) {
3873 self.resolve_type(&*binding.ty);
3876 // A special case for sugared associated type paths `T::A` where `T` is
3877 // a type parameter and `A` is an associated type on some bound of `T`.
3878 if namespace == TypeNS && path.segments.len() == 2 {
3879 match self.resolve_identifier(path.segments[0].identifier,
3883 Some((def, last_private)) => {
3885 DefTyParam(_, _, did, _) => {
3886 let def = DefAssociatedPath(TyParamProvenance::FromParam(did),
3887 path.segments.last()
3888 .unwrap().identifier);
3889 return Some((def, last_private));
3892 let def = DefAssociatedPath(TyParamProvenance::FromSelf(local_def(nid)),
3893 path.segments.last()
3894 .unwrap().identifier);
3895 return Some((def, last_private));
3905 return self.resolve_crate_relative_path(path, namespace);
3908 // Try to find a path to an item in a module.
3909 let unqualified_def =
3910 self.resolve_identifier(path.segments.last().unwrap().identifier,
3915 if path.segments.len() > 1 {
3916 let def = self.resolve_module_relative_path(path, namespace);
3917 match (def, unqualified_def) {
3918 (Some((ref d, _)), Some((ref ud, _))) if *d == *ud => {
3920 .add_lint(lint::builtin::UNUSED_QUALIFICATIONS,
3923 "unnecessary qualification".to_string());
3931 return unqualified_def;
3934 // resolve a single identifier (used as a varref)
3935 fn resolve_identifier(&mut self,
3937 namespace: Namespace,
3940 -> Option<(Def, LastPrivate)> {
3942 match self.resolve_identifier_in_local_ribs(identifier,
3946 return Some((def, LastMod(AllPublic)));
3954 return self.resolve_item_by_name_in_lexical_scope(identifier.name, namespace);
3957 // FIXME #4952: Merge me with resolve_name_in_module?
3958 fn resolve_definition_of_name_in_module(&mut self,
3959 containing_module: Rc<Module>,
3961 namespace: Namespace)
3963 // First, search children.
3964 build_reduced_graph::populate_module_if_necessary(self, &containing_module);
3966 match containing_module.children.borrow().get(&name) {
3967 Some(child_name_bindings) => {
3968 match child_name_bindings.def_for_namespace(namespace) {
3970 // Found it. Stop the search here.
3971 let p = child_name_bindings.defined_in_public_namespace(
3973 let lp = if p {LastMod(AllPublic)} else {
3974 LastMod(DependsOn(def.def_id()))
3976 return ChildNameDefinition(def, lp);
3984 // Next, search import resolutions.
3985 match containing_module.import_resolutions.borrow().get(&name) {
3986 Some(import_resolution) if import_resolution.is_public => {
3987 if let Some(target) = (*import_resolution).target_for_namespace(namespace) {
3988 match target.bindings.def_for_namespace(namespace) {
3991 let id = import_resolution.id(namespace);
3992 // track imports and extern crates as well
3993 self.used_imports.insert((id, namespace));
3994 self.record_import_use(id, name);
3995 match target.target_module.def_id.get() {
3996 Some(DefId{krate: kid, ..}) => {
3997 self.used_crates.insert(kid);
4001 return ImportNameDefinition(def, LastMod(AllPublic));
4004 // This can happen with external impls, due to
4005 // the imperfect way we read the metadata.
4010 Some(..) | None => {} // Continue.
4013 // Finally, search through external children.
4014 if namespace == TypeNS {
4015 if let Some(module) = containing_module.external_module_children.borrow()
4016 .get(&name).cloned() {
4017 if let Some(def_id) = module.def_id.get() {
4018 // track used crates
4019 self.used_crates.insert(def_id.krate);
4020 let lp = if module.is_public {LastMod(AllPublic)} else {
4021 LastMod(DependsOn(def_id))
4023 return ChildNameDefinition(DefMod(def_id), lp);
4028 return NoNameDefinition;
4031 // resolve a "module-relative" path, e.g. a::b::c
4032 fn resolve_module_relative_path(&mut self,
4034 namespace: Namespace)
4035 -> Option<(Def, LastPrivate)> {
4036 let module_path = path.segments.init().iter()
4037 .map(|ps| ps.identifier.name)
4038 .collect::<Vec<_>>();
4040 let containing_module;
4042 let module = self.current_module.clone();
4043 match self.resolve_module_path(module,
4049 let (span, msg) = match err {
4050 Some((span, msg)) => (span, msg),
4052 let msg = format!("Use of undeclared type or module `{}`",
4053 self.names_to_string(module_path.as_slice()));
4058 self.resolve_error(span, &format!("failed to resolve. {}",
4062 Indeterminate => panic!("indeterminate unexpected"),
4063 Success((resulting_module, resulting_last_private)) => {
4064 containing_module = resulting_module;
4065 last_private = resulting_last_private;
4069 let name = path.segments.last().unwrap().identifier.name;
4070 let def = match self.resolve_definition_of_name_in_module(containing_module.clone(),
4073 NoNameDefinition => {
4074 // We failed to resolve the name. Report an error.
4077 ChildNameDefinition(def, lp) | ImportNameDefinition(def, lp) => {
4078 (def, last_private.or(lp))
4081 if let Some(DefId{krate: kid, ..}) = containing_module.def_id.get() {
4082 self.used_crates.insert(kid);
4087 /// Invariant: This must be called only during main resolution, not during
4088 /// import resolution.
4089 fn resolve_crate_relative_path(&mut self,
4091 namespace: Namespace)
4092 -> Option<(Def, LastPrivate)> {
4093 let module_path = path.segments.init().iter()
4094 .map(|ps| ps.identifier.name)
4095 .collect::<Vec<_>>();
4097 let root_module = self.graph_root.get_module();
4099 let containing_module;
4101 match self.resolve_module_path_from_root(root_module,
4106 LastMod(AllPublic)) {
4108 let (span, msg) = match err {
4109 Some((span, msg)) => (span, msg),
4111 let msg = format!("Use of undeclared module `::{}`",
4112 self.names_to_string(&module_path[]));
4117 self.resolve_error(span, &format!("failed to resolve. {}",
4123 panic!("indeterminate unexpected");
4126 Success((resulting_module, resulting_last_private)) => {
4127 containing_module = resulting_module;
4128 last_private = resulting_last_private;
4132 let name = path.segments.last().unwrap().identifier.name;
4133 match self.resolve_definition_of_name_in_module(containing_module,
4136 NoNameDefinition => {
4137 // We failed to resolve the name. Report an error.
4140 ChildNameDefinition(def, lp) | ImportNameDefinition(def, lp) => {
4141 return Some((def, last_private.or(lp)));
4146 fn resolve_identifier_in_local_ribs(&mut self,
4148 namespace: Namespace,
4151 // Check the local set of ribs.
4152 let search_result = match namespace {
4154 let renamed = mtwt::resolve(ident);
4155 self.search_ribs(self.value_ribs.as_slice(), renamed, span)
4158 let name = ident.name;
4159 self.search_ribs(&self.type_ribs[], name, span)
4163 match search_result {
4164 Some(DlDef(def)) => {
4165 debug!("(resolving path in local ribs) resolved `{}` to \
4167 token::get_ident(ident),
4171 Some(DlField) | Some(DlImpl(_)) | None => {
4177 fn resolve_item_by_name_in_lexical_scope(&mut self,
4179 namespace: Namespace)
4180 -> Option<(Def, LastPrivate)> {
4182 let module = self.current_module.clone();
4183 match self.resolve_item_in_lexical_scope(module,
4186 Success((target, _)) => {
4187 match (*target.bindings).def_for_namespace(namespace) {
4189 // This can happen if we were looking for a type and
4190 // found a module instead. Modules don't have defs.
4191 debug!("(resolving item path by identifier in lexical \
4192 scope) failed to resolve {} after success...",
4193 token::get_name(name));
4197 debug!("(resolving item path in lexical scope) \
4198 resolved `{}` to item",
4199 token::get_name(name));
4200 // This lookup is "all public" because it only searched
4201 // for one identifier in the current module (couldn't
4202 // have passed through reexports or anything like that.
4203 return Some((def, LastMod(AllPublic)));
4208 panic!("unexpected indeterminate result");
4212 Some((span, msg)) =>
4213 self.resolve_error(span, &format!("failed to resolve. {}",
4218 debug!("(resolving item path by identifier in lexical scope) \
4219 failed to resolve {}", token::get_name(name));
4225 fn with_no_errors<T, F>(&mut self, f: F) -> T where
4226 F: FnOnce(&mut Resolver) -> T,
4228 self.emit_errors = false;
4230 self.emit_errors = true;
4234 fn resolve_error(&self, span: Span, s: &str) {
4235 if self.emit_errors {
4236 self.session.span_err(span, s);
4240 fn find_fallback_in_self_type(&mut self, name: Name) -> FallbackSuggestion {
4241 fn extract_path_and_node_id(t: &Ty, allow: FallbackChecks)
4242 -> Option<(Path, NodeId, FallbackChecks)> {
4244 TyPath(ref path, node_id) => Some((path.clone(), node_id, allow)),
4245 TyPtr(ref mut_ty) => extract_path_and_node_id(&*mut_ty.ty, OnlyTraitAndStatics),
4246 TyRptr(_, ref mut_ty) => extract_path_and_node_id(&*mut_ty.ty, allow),
4247 // This doesn't handle the remaining `Ty` variants as they are not
4248 // that commonly the self_type, it might be interesting to provide
4249 // support for those in future.
4254 fn get_module(this: &mut Resolver, span: Span, name_path: &[ast::Name])
4255 -> Option<Rc<Module>> {
4256 let root = this.current_module.clone();
4257 let last_name = name_path.last().unwrap();
4259 if name_path.len() == 1 {
4260 match this.primitive_type_table.primitive_types.get(last_name) {
4263 match this.current_module.children.borrow().get(last_name) {
4264 Some(child) => child.get_module_if_available(),
4270 match this.resolve_module_path(root,
4275 Success((module, _)) => Some(module),
4281 let (path, node_id, allowed) = match self.current_self_type {
4282 Some(ref ty) => match extract_path_and_node_id(ty, Everything) {
4284 None => return NoSuggestion,
4286 None => return NoSuggestion,
4289 if allowed == Everything {
4290 // Look for a field with the same name in the current self_type.
4291 match self.def_map.borrow().get(&node_id) {
4292 Some(&DefTy(did, _))
4293 | Some(&DefStruct(did))
4294 | Some(&DefVariant(_, did, _)) => match self.structs.get(&did) {
4297 if fields.iter().any(|&field_name| name == field_name) {
4302 _ => {} // Self type didn't resolve properly
4306 let name_path = path.segments.iter().map(|seg| seg.identifier.name).collect::<Vec<_>>();
4308 // Look for a method in the current self type's impl module.
4309 match get_module(self, path.span, &name_path[]) {
4310 Some(module) => match module.children.borrow().get(&name) {
4312 let p_str = self.path_names_to_string(&path);
4313 match binding.def_for_namespace(ValueNS) {
4314 Some(DefStaticMethod(_, provenance)) => {
4316 FromImpl(_) => return StaticMethod(p_str),
4317 FromTrait(_) => unreachable!()
4320 Some(DefMethod(_, None, _)) if allowed == Everything => return Method,
4321 Some(DefMethod(_, Some(_), _)) => return TraitItem,
4330 // Look for a method in the current trait.
4331 match self.current_trait_ref {
4332 Some((did, ref trait_ref)) => {
4333 let path_str = self.path_names_to_string(&trait_ref.path);
4335 match self.trait_item_map.get(&(name, did)) {
4336 Some(&StaticMethodTraitItemKind) => {
4337 return TraitMethod(path_str)
4339 Some(_) => return TraitItem,
4349 fn find_best_match_for_name(&mut self, name: &str, max_distance: uint)
4351 let this = &mut *self;
4353 let mut maybes: Vec<token::InternedString> = Vec::new();
4354 let mut values: Vec<uint> = Vec::new();
4356 for rib in this.value_ribs.iter().rev() {
4357 for (&k, _) in rib.bindings.iter() {
4358 maybes.push(token::get_name(k));
4359 values.push(uint::MAX);
4363 let mut smallest = 0;
4364 for (i, other) in maybes.iter().enumerate() {
4365 values[i] = lev_distance(name, other.get());
4367 if values[i] <= values[smallest] {
4372 if values.len() > 0 &&
4373 values[smallest] != uint::MAX &&
4374 values[smallest] < name.len() + 2 &&
4375 values[smallest] <= max_distance &&
4376 name != maybes[smallest].get() {
4378 Some(maybes[smallest].get().to_string())
4385 fn resolve_expr(&mut self, expr: &Expr) {
4386 // First, record candidate traits for this expression if it could
4387 // result in the invocation of a method call.
4389 self.record_candidate_traits_for_expr_if_necessary(expr);
4391 // Next, resolve the node.
4393 // The interpretation of paths depends on whether the path has
4394 // multiple elements in it or not.
4396 ExprPath(_) | ExprQPath(_) => {
4397 let mut path_from_qpath;
4398 let path = match expr.node {
4399 ExprPath(ref path) => path,
4400 ExprQPath(ref qpath) => {
4401 self.resolve_type(&*qpath.self_type);
4402 self.resolve_trait_reference(expr.id, &*qpath.trait_ref, TraitQPath);
4403 path_from_qpath = qpath.trait_ref.path.clone();
4404 path_from_qpath.segments.push(qpath.item_path.clone());
4409 // This is a local path in the value namespace. Walk through
4410 // scopes looking for it.
4411 match self.resolve_path(expr.id, path, ValueNS, true) {
4412 // Check if struct variant
4413 Some((DefVariant(_, _, true), _)) => {
4414 let path_name = self.path_names_to_string(path);
4415 self.resolve_error(expr.span,
4416 format!("`{}` is a struct variant name, but \
4418 uses it like a function name",
4419 path_name).as_slice());
4421 self.session.span_help(expr.span,
4422 format!("Did you mean to write: \
4423 `{} {{ /* fields */ }}`?",
4424 path_name).as_slice());
4427 // Write the result into the def map.
4428 debug!("(resolving expr) resolved `{}`",
4429 self.path_names_to_string(path));
4431 self.record_def(expr.id, def);
4434 // Be helpful if the name refers to a struct
4435 // (The pattern matching def_tys where the id is in self.structs
4436 // matches on regular structs while excluding tuple- and enum-like
4437 // structs, which wouldn't result in this error.)
4438 let path_name = self.path_names_to_string(path);
4439 match self.with_no_errors(|this|
4440 this.resolve_path(expr.id, path, TypeNS, false)) {
4441 Some((DefTy(struct_id, _), _))
4442 if self.structs.contains_key(&struct_id) => {
4443 self.resolve_error(expr.span,
4444 format!("`{}` is a structure name, but \
4446 uses it like a function name",
4447 path_name).as_slice());
4449 self.session.span_help(expr.span,
4450 format!("Did you mean to write: \
4451 `{} {{ /* fields */ }}`?",
4452 path_name).as_slice());
4456 let mut method_scope = false;
4457 self.value_ribs.iter().rev().all(|rib| {
4458 let res = match *rib {
4459 Rib { bindings: _, kind: MethodRibKind(_, _) } => true,
4460 Rib { bindings: _, kind: ItemRibKind } => false,
4461 _ => return true, // Keep advancing
4465 false // Stop advancing
4468 if method_scope && token::get_name(self.self_name).get()
4472 "`self` is not available \
4473 in a static method. Maybe a \
4474 `self` argument is missing?");
4476 let last_name = path.segments.last().unwrap().identifier.name;
4477 let mut msg = match self.find_fallback_in_self_type(last_name) {
4479 // limit search to 5 to reduce the number
4480 // of stupid suggestions
4481 self.find_best_match_for_name(path_name.as_slice(), 5)
4482 .map_or("".to_string(),
4483 |x| format!("`{}`", x))
4486 format!("`self.{}`", path_name),
4489 format!("to call `self.{}`", path_name),
4490 TraitMethod(path_str)
4491 | StaticMethod(path_str) =>
4492 format!("to call `{}::{}`", path_str, path_name)
4496 msg = format!(". Did you mean {}?", msg)
4501 format!("unresolved name `{}`{}",
4510 visit::walk_expr(self, expr);
4513 ExprClosure(capture_clause, _, ref fn_decl, ref block) => {
4514 self.capture_mode_map.insert(expr.id, capture_clause);
4515 self.resolve_function(ClosureRibKind(expr.id, ast::DUMMY_NODE_ID),
4516 Some(&**fn_decl), NoTypeParameters,
4520 ExprStruct(ref path, _, _) => {
4521 // Resolve the path to the structure it goes to. We don't
4522 // check to ensure that the path is actually a structure; that
4523 // is checked later during typeck.
4524 match self.resolve_path(expr.id, path, TypeNS, false) {
4525 Some(definition) => self.record_def(expr.id, definition),
4527 debug!("(resolving expression) didn't find struct \
4528 def: {:?}", result);
4529 let msg = format!("`{}` does not name a structure",
4530 self.path_names_to_string(path));
4531 self.resolve_error(path.span, &msg[]);
4535 visit::walk_expr(self, expr);
4538 ExprLoop(_, Some(label)) | ExprWhile(_, _, Some(label)) => {
4539 self.with_label_rib(|this| {
4540 let def_like = DlDef(DefLabel(expr.id));
4543 let rib = this.label_ribs.last_mut().unwrap();
4544 let renamed = mtwt::resolve(label);
4545 rib.bindings.insert(renamed, def_like);
4548 visit::walk_expr(this, expr);
4552 ExprForLoop(ref pattern, ref head, ref body, optional_label) => {
4553 self.resolve_expr(&**head);
4555 self.value_ribs.push(Rib::new(NormalRibKind));
4557 self.resolve_pattern(&**pattern,
4558 LocalIrrefutableMode,
4559 &mut HashMap::new());
4561 match optional_label {
4565 .push(Rib::new(NormalRibKind));
4566 let def_like = DlDef(DefLabel(expr.id));
4569 let rib = self.label_ribs.last_mut().unwrap();
4570 let renamed = mtwt::resolve(label);
4571 rib.bindings.insert(renamed, def_like);
4576 self.resolve_block(&**body);
4578 if optional_label.is_some() {
4579 drop(self.label_ribs.pop())
4582 self.value_ribs.pop();
4585 ExprBreak(Some(label)) | ExprAgain(Some(label)) => {
4586 let renamed = mtwt::resolve(label);
4587 match self.search_label(renamed) {
4591 &format!("use of undeclared label `{}`",
4592 token::get_ident(label))[])
4594 Some(DlDef(def @ DefLabel(_))) => {
4595 // Since this def is a label, it is never read.
4596 self.record_def(expr.id, (def, LastMod(AllPublic)))
4599 self.session.span_bug(expr.span,
4600 "label wasn't mapped to a \
4607 visit::walk_expr(self, expr);
4612 fn record_candidate_traits_for_expr_if_necessary(&mut self, expr: &Expr) {
4614 ExprField(_, ident) => {
4615 // FIXME(#6890): Even though you can't treat a method like a
4616 // field, we need to add any trait methods we find that match
4617 // the field name so that we can do some nice error reporting
4618 // later on in typeck.
4619 let traits = self.search_for_traits_containing_method(ident.node.name);
4620 self.trait_map.insert(expr.id, traits);
4622 ExprMethodCall(ident, _, _) => {
4623 debug!("(recording candidate traits for expr) recording \
4626 let traits = self.search_for_traits_containing_method(ident.node.name);
4627 self.trait_map.insert(expr.id, traits);
4635 fn search_for_traits_containing_method(&mut self, name: Name) -> Vec<DefId> {
4636 debug!("(searching for traits containing method) looking for '{}'",
4637 token::get_name(name));
4639 fn add_trait_info(found_traits: &mut Vec<DefId>,
4640 trait_def_id: DefId,
4642 debug!("(adding trait info) found trait {}:{} for method '{}'",
4645 token::get_name(name));
4646 found_traits.push(trait_def_id);
4649 let mut found_traits = Vec::new();
4650 let mut search_module = self.current_module.clone();
4652 // Look for the current trait.
4653 match self.current_trait_ref {
4654 Some((trait_def_id, _)) => {
4655 if self.trait_item_map.contains_key(&(name, trait_def_id)) {
4656 add_trait_info(&mut found_traits, trait_def_id, name);
4659 None => {} // Nothing to do.
4662 // Look for trait children.
4663 build_reduced_graph::populate_module_if_necessary(self, &search_module);
4666 for (_, child_names) in search_module.children.borrow().iter() {
4667 let def = match child_names.def_for_namespace(TypeNS) {
4671 let trait_def_id = match def {
4672 DefTrait(trait_def_id) => trait_def_id,
4675 if self.trait_item_map.contains_key(&(name, trait_def_id)) {
4676 add_trait_info(&mut found_traits, trait_def_id, name);
4681 // Look for imports.
4682 for (_, import) in search_module.import_resolutions.borrow().iter() {
4683 let target = match import.target_for_namespace(TypeNS) {
4685 Some(target) => target,
4687 let did = match target.bindings.def_for_namespace(TypeNS) {
4688 Some(DefTrait(trait_def_id)) => trait_def_id,
4689 Some(..) | None => continue,
4691 if self.trait_item_map.contains_key(&(name, did)) {
4692 add_trait_info(&mut found_traits, did, name);
4693 let id = import.type_id;
4694 self.used_imports.insert((id, TypeNS));
4695 let trait_name = self.get_trait_name(did);
4696 self.record_import_use(id, trait_name);
4697 if let Some(DefId{krate: kid, ..}) = target.target_module.def_id.get() {
4698 self.used_crates.insert(kid);
4703 match search_module.parent_link.clone() {
4704 NoParentLink | ModuleParentLink(..) => break,
4705 BlockParentLink(parent_module, _) => {
4706 search_module = parent_module.upgrade().unwrap();
4714 fn record_def(&mut self, node_id: NodeId, (def, lp): (Def, LastPrivate)) {
4715 debug!("(recording def) recording {:?} for {}, last private {:?}",
4717 assert!(match lp {LastImport{..} => false, _ => true},
4718 "Import should only be used for `use` directives");
4719 self.last_private.insert(node_id, lp);
4721 match self.def_map.borrow_mut().entry(node_id) {
4722 // Resolve appears to "resolve" the same ID multiple
4723 // times, so here is a sanity check it at least comes to
4724 // the same conclusion! - nmatsakis
4725 Occupied(entry) => if def != *entry.get() {
4727 .bug(&format!("node_id {} resolved first to {:?} and \
4733 Vacant(entry) => { entry.insert(def); },
4737 fn enforce_default_binding_mode(&mut self,
4739 pat_binding_mode: BindingMode,
4741 match pat_binding_mode {
4742 BindByValue(_) => {}
4744 self.resolve_error(pat.span,
4745 &format!("cannot use `ref` binding mode \
4755 // Diagnostics are not particularly efficient, because they're rarely
4759 /// A somewhat inefficient routine to obtain the name of a module.
4760 fn module_to_string(&self, module: &Module) -> String {
4761 let mut names = Vec::new();
4763 fn collect_mod(names: &mut Vec<ast::Name>, module: &Module) {
4764 match module.parent_link {
4766 ModuleParentLink(ref module, name) => {
4768 collect_mod(names, &*module.upgrade().unwrap());
4770 BlockParentLink(ref module, _) => {
4771 // danger, shouldn't be ident?
4772 names.push(special_idents::opaque.name);
4773 collect_mod(names, &*module.upgrade().unwrap());
4777 collect_mod(&mut names, module);
4779 if names.len() == 0 {
4780 return "???".to_string();
4782 self.names_to_string(&names.into_iter().rev()
4783 .collect::<Vec<ast::Name>>()[])
4786 #[allow(dead_code)] // useful for debugging
4787 fn dump_module(&mut self, module_: Rc<Module>) {
4788 debug!("Dump of module `{}`:", self.module_to_string(&*module_));
4790 debug!("Children:");
4791 build_reduced_graph::populate_module_if_necessary(self, &module_);
4792 for (&name, _) in module_.children.borrow().iter() {
4793 debug!("* {}", token::get_name(name));
4796 debug!("Import resolutions:");
4797 let import_resolutions = module_.import_resolutions.borrow();
4798 for (&name, import_resolution) in import_resolutions.iter() {
4800 match import_resolution.target_for_namespace(ValueNS) {
4801 None => { value_repr = "".to_string(); }
4803 value_repr = " value:?".to_string();
4809 match import_resolution.target_for_namespace(TypeNS) {
4810 None => { type_repr = "".to_string(); }
4812 type_repr = " type:?".to_string();
4817 debug!("* {}:{}{}", token::get_name(name), value_repr, type_repr);
4822 pub struct CrateMap {
4823 pub def_map: DefMap,
4824 pub freevars: RefCell<FreevarMap>,
4825 pub capture_mode_map: RefCell<CaptureModeMap>,
4826 pub export_map: ExportMap,
4827 pub trait_map: TraitMap,
4828 pub external_exports: ExternalExports,
4829 pub last_private_map: LastPrivateMap,
4830 pub glob_map: Option<GlobMap>
4833 #[derive(PartialEq,Copy)]
4834 pub enum MakeGlobMap {
4839 /// Entry point to crate resolution.
4840 pub fn resolve_crate<'a, 'tcx>(session: &'a Session,
4841 ast_map: &'a ast_map::Map<'tcx>,
4844 make_glob_map: MakeGlobMap)
4846 let mut resolver = Resolver::new(session, ast_map, krate.span, make_glob_map);
4848 build_reduced_graph::build_reduced_graph(&mut resolver, krate);
4849 session.abort_if_errors();
4851 resolver.resolve_imports();
4852 session.abort_if_errors();
4854 record_exports::record(&mut resolver);
4855 session.abort_if_errors();
4857 resolver.resolve_crate(krate);
4858 session.abort_if_errors();
4860 check_unused::check_crate(&mut resolver, krate);
4863 def_map: resolver.def_map,
4864 freevars: resolver.freevars,
4865 capture_mode_map: RefCell::new(resolver.capture_mode_map),
4866 export_map: resolver.export_map,
4867 trait_map: resolver.trait_map,
4868 external_exports: resolver.external_exports,
4869 last_private_map: resolver.last_private,
4870 glob_map: if resolver.make_glob_map {
4871 Some(resolver.glob_map)