1 // Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
11 #![crate_name = "rustc_resolve"]
14 #![crate_type = "dylib"]
15 #![crate_type = "rlib"]
16 #![doc(html_logo_url = "http://www.rust-lang.org/logos/rust-logo-128x128-blk-v2.png",
17 html_favicon_url = "http://www.rust-lang.org/favicon.ico",
18 html_root_url = "http://doc.rust-lang.org/nightly/")]
20 #![feature(slicing_syntax)]
21 #![feature(rustc_diagnostic_macros)]
22 #![allow(unknown_features)] #![feature(int_uint)]
25 #[macro_use] extern crate log;
26 #[macro_use] extern crate syntax;
27 #[macro_use] #[no_link] extern crate rustc_bitflags;
31 use self::PatternBindingMode::*;
32 use self::Namespace::*;
33 use self::NamespaceResult::*;
34 use self::NameDefinition::*;
35 use self::ImportDirectiveSubclass::*;
36 use self::ResolveResult::*;
37 use self::FallbackSuggestion::*;
38 use self::TypeParameters::*;
40 use self::MethodSort::*;
41 use self::UseLexicalScopeFlag::*;
42 use self::ModulePrefixResult::*;
43 use self::NameSearchType::*;
44 use self::BareIdentifierPatternResolution::*;
45 use self::ParentLink::*;
46 use self::ModuleKind::*;
47 use self::TraitReferenceType::*;
48 use self::FallbackChecks::*;
50 use rustc::session::Session;
52 use rustc::metadata::csearch;
53 use rustc::metadata::decoder::{DefLike, DlDef, DlField, DlImpl};
54 use rustc::middle::def::*;
55 use rustc::middle::lang_items::LanguageItems;
56 use rustc::middle::pat_util::pat_bindings;
57 use rustc::middle::privacy::*;
58 use rustc::middle::subst::{ParamSpace, FnSpace, TypeSpace};
59 use rustc::middle::ty::{CaptureModeMap, Freevar, FreevarMap, TraitMap, GlobMap};
60 use rustc::util::nodemap::{NodeMap, NodeSet, DefIdSet, FnvHashMap};
61 use rustc::util::lev_distance::lev_distance;
63 use syntax::ast::{Arm, BindByRef, BindByValue, BindingMode, Block, Crate, CrateNum};
64 use syntax::ast::{DefId, Expr, ExprAgain, ExprBreak, ExprField};
65 use syntax::ast::{ExprClosure, ExprForLoop, ExprLoop, ExprWhile, ExprMethodCall};
66 use syntax::ast::{ExprPath, ExprQPath, ExprStruct, FnDecl};
67 use syntax::ast::{ForeignItemFn, ForeignItemStatic, Generics};
68 use syntax::ast::{Ident, ImplItem, Item, ItemConst, ItemEnum, ItemFn};
69 use syntax::ast::{ItemForeignMod, ItemImpl, ItemMac, ItemMod, ItemStatic};
70 use syntax::ast::{ItemStruct, ItemTrait, ItemTy, Local, LOCAL_CRATE};
71 use syntax::ast::{MethodImplItem, Mod, Name, NodeId};
72 use syntax::ast::{Pat, PatEnum, PatIdent, PatLit};
73 use syntax::ast::{PatRange, PatStruct, Path};
74 use syntax::ast::{PolyTraitRef, PrimTy, SelfExplicit};
75 use syntax::ast::{RegionTyParamBound, StructField};
76 use syntax::ast::{TraitRef, TraitTyParamBound};
77 use syntax::ast::{Ty, TyBool, TyChar, TyF32};
78 use syntax::ast::{TyF64, TyFloat, TyIs, TyI8, TyI16, TyI32, TyI64, TyInt, TyObjectSum};
79 use syntax::ast::{TyParam, TyParamBound, TyPath, TyPtr, TyPolyTraitRef, TyQPath};
80 use syntax::ast::{TyRptr, TyStr, TyUs, TyU8, TyU16, TyU32, TyU64, TyUint};
81 use syntax::ast::{TypeImplItem};
84 use syntax::ast_util::{PostExpansionMethod, local_def, walk_pat};
85 use syntax::attr::AttrMetaMethods;
86 use syntax::ext::mtwt;
87 use syntax::parse::token::{self, special_names, special_idents};
88 use syntax::codemap::{Span, Pos};
89 use syntax::owned_slice::OwnedSlice;
90 use syntax::visit::{self, Visitor};
92 use std::collections::{HashMap, HashSet};
93 use std::collections::hash_map::Entry::{Occupied, Vacant};
94 use std::cell::{Cell, RefCell};
96 use std::mem::replace;
97 use std::rc::{Rc, Weak};
102 mod build_reduced_graph;
107 binding_mode: BindingMode,
110 // Map from the name in a pattern to its binding mode.
111 type BindingMap = HashMap<Name, BindingInfo>;
113 #[derive(Copy, PartialEq)]
114 enum PatternBindingMode {
116 LocalIrrefutableMode,
117 ArgumentIrrefutableMode,
120 #[derive(Copy, PartialEq, Eq, Hash, Show)]
126 /// A NamespaceResult represents the result of resolving an import in
127 /// a particular namespace. The result is either definitely-resolved,
128 /// definitely- unresolved, or unknown.
130 enum NamespaceResult {
131 /// Means that resolve hasn't gathered enough information yet to determine
132 /// whether the name is bound in this namespace. (That is, it hasn't
133 /// resolved all `use` directives yet.)
135 /// Means that resolve has determined that the name is definitely
136 /// not bound in the namespace.
138 /// Means that resolve has determined that the name is bound in the Module
139 /// argument, and specified by the NameBindings argument.
140 BoundResult(Rc<Module>, Rc<NameBindings>)
143 impl NamespaceResult {
144 fn is_unknown(&self) -> bool {
146 UnknownResult => true,
150 fn is_unbound(&self) -> bool {
152 UnboundResult => true,
158 enum NameDefinition {
159 NoNameDefinition, //< The name was unbound.
160 ChildNameDefinition(Def, LastPrivate), //< The name identifies an immediate child.
161 ImportNameDefinition(Def, LastPrivate) //< The name identifies an import.
164 impl<'a, 'v, 'tcx> Visitor<'v> for Resolver<'a, 'tcx> {
165 fn visit_item(&mut self, item: &Item) {
166 self.resolve_item(item);
168 fn visit_arm(&mut self, arm: &Arm) {
169 self.resolve_arm(arm);
171 fn visit_block(&mut self, block: &Block) {
172 self.resolve_block(block);
174 fn visit_expr(&mut self, expr: &Expr) {
175 self.resolve_expr(expr);
177 fn visit_local(&mut self, local: &Local) {
178 self.resolve_local(local);
180 fn visit_ty(&mut self, ty: &Ty) {
181 self.resolve_type(ty);
185 /// Contains data for specific types of import directives.
187 enum ImportDirectiveSubclass {
188 SingleImport(Name /* target */, Name /* source */),
192 type ErrorMessage = Option<(Span, String)>;
194 enum ResolveResult<T> {
195 Failed(ErrorMessage), // Failed to resolve the name, optional helpful error message.
196 Indeterminate, // Couldn't determine due to unresolved globs.
197 Success(T) // Successfully resolved the import.
200 impl<T> ResolveResult<T> {
201 fn indeterminate(&self) -> bool {
202 match *self { Indeterminate => true, _ => false }
206 enum FallbackSuggestion {
211 StaticMethod(String),
216 enum TypeParameters<'a> {
222 // Identifies the things that these parameters
223 // were declared on (type, fn, etc)
226 // ID of the enclosing item.
229 // The kind of the rib used for type parameters.
233 // The rib kind controls the translation of local
234 // definitions (`DefLocal`) to upvars (`DefUpvar`).
235 #[derive(Copy, Show)]
237 // No translation needs to be applied.
240 // We passed through a closure scope at the given node ID.
241 // Translate upvars as appropriate.
242 ClosureRibKind(NodeId /* func id */, NodeId /* body id if proc or unboxed */),
244 // We passed through an impl or trait and are now in one of its
245 // methods. Allow references to ty params that impl or trait
246 // binds. Disallow any other upvars (including other ty params that are
248 // parent; method itself
249 MethodRibKind(NodeId, MethodSort),
251 // We passed through an item scope. Disallow upvars.
254 // We're in a constant item. Can't refer to dynamic stuff.
258 // Methods can be required or provided. RequiredMethod methods only occur in traits.
259 #[derive(Copy, Show)]
262 ProvidedMethod(NodeId)
266 enum UseLexicalScopeFlag {
271 enum ModulePrefixResult {
273 PrefixFound(Rc<Module>, uint)
276 #[derive(Copy, PartialEq)]
277 enum NameSearchType {
278 /// We're doing a name search in order to resolve a `use` directive.
281 /// We're doing a name search in order to resolve a path type, a path
282 /// expression, or a path pattern.
287 enum BareIdentifierPatternResolution {
288 FoundStructOrEnumVariant(Def, LastPrivate),
289 FoundConst(Def, LastPrivate),
290 BareIdentifierPatternUnresolved
296 bindings: HashMap<Name, DefLike>,
301 fn new(kind: RibKind) -> Rib {
303 bindings: HashMap::new(),
309 /// Whether an import can be shadowed by another import.
310 #[derive(Show,PartialEq,Clone,Copy)]
316 /// One import directive.
318 struct ImportDirective {
319 module_path: Vec<Name>,
320 subclass: ImportDirectiveSubclass,
323 is_public: bool, // see note in ImportResolution about how to use this
324 shadowable: Shadowable,
327 impl ImportDirective {
328 fn new(module_path: Vec<Name> ,
329 subclass: ImportDirectiveSubclass,
333 shadowable: Shadowable)
336 module_path: module_path,
340 is_public: is_public,
341 shadowable: shadowable,
346 /// The item that an import resolves to.
347 #[derive(Clone,Show)]
349 target_module: Rc<Module>,
350 bindings: Rc<NameBindings>,
351 shadowable: Shadowable,
355 fn new(target_module: Rc<Module>,
356 bindings: Rc<NameBindings>,
357 shadowable: Shadowable)
360 target_module: target_module,
362 shadowable: shadowable,
367 /// An ImportResolution represents a particular `use` directive.
369 struct ImportResolution {
370 /// Whether this resolution came from a `use` or a `pub use`. Note that this
371 /// should *not* be used whenever resolution is being performed, this is
372 /// only looked at for glob imports statements currently. Privacy testing
373 /// occurs during a later phase of compilation.
376 // The number of outstanding references to this name. When this reaches
377 // zero, outside modules can count on the targets being correct. Before
378 // then, all bets are off; future imports could override this name.
379 outstanding_references: uint,
381 /// The value that this `use` directive names, if there is one.
382 value_target: Option<Target>,
383 /// The source node of the `use` directive leading to the value target
387 /// The type that this `use` directive names, if there is one.
388 type_target: Option<Target>,
389 /// The source node of the `use` directive leading to the type target
394 impl ImportResolution {
395 fn new(id: NodeId, is_public: bool) -> ImportResolution {
399 outstanding_references: 0,
402 is_public: is_public,
406 fn target_for_namespace(&self, namespace: Namespace)
409 TypeNS => self.type_target.clone(),
410 ValueNS => self.value_target.clone(),
414 fn id(&self, namespace: Namespace) -> NodeId {
416 TypeNS => self.type_id,
417 ValueNS => self.value_id,
421 fn shadowable(&self, namespace: Namespace) -> Shadowable {
422 let target = self.target_for_namespace(namespace);
423 if target.is_none() {
424 return Shadowable::Always;
427 target.unwrap().shadowable
430 fn set_target_and_id(&mut self,
431 namespace: Namespace,
432 target: Option<Target>,
436 self.type_target = target;
440 self.value_target = target;
447 /// The link from a module up to its nearest parent node.
448 #[derive(Clone,Show)]
451 ModuleParentLink(Weak<Module>, Name),
452 BlockParentLink(Weak<Module>, NodeId)
455 /// The type of module this is.
456 #[derive(Copy, PartialEq, Show)]
465 /// One node in the tree of modules.
467 parent_link: ParentLink,
468 def_id: Cell<Option<DefId>>,
469 kind: Cell<ModuleKind>,
472 children: RefCell<HashMap<Name, Rc<NameBindings>>>,
473 imports: RefCell<Vec<ImportDirective>>,
475 // The external module children of this node that were declared with
477 external_module_children: RefCell<HashMap<Name, Rc<Module>>>,
479 // The anonymous children of this node. Anonymous children are pseudo-
480 // modules that are implicitly created around items contained within
483 // For example, if we have this:
491 // There will be an anonymous module created around `g` with the ID of the
492 // entry block for `f`.
493 anonymous_children: RefCell<NodeMap<Rc<Module>>>,
495 // The status of resolving each import in this module.
496 import_resolutions: RefCell<HashMap<Name, ImportResolution>>,
498 // The number of unresolved globs that this module exports.
499 glob_count: Cell<uint>,
501 // The index of the import we're resolving.
502 resolved_import_count: Cell<uint>,
504 // Whether this module is populated. If not populated, any attempt to
505 // access the children must be preceded with a
506 // `populate_module_if_necessary` call.
507 populated: Cell<bool>,
511 fn new(parent_link: ParentLink,
512 def_id: Option<DefId>,
518 parent_link: parent_link,
519 def_id: Cell::new(def_id),
520 kind: Cell::new(kind),
521 is_public: is_public,
522 children: RefCell::new(HashMap::new()),
523 imports: RefCell::new(Vec::new()),
524 external_module_children: RefCell::new(HashMap::new()),
525 anonymous_children: RefCell::new(NodeMap::new()),
526 import_resolutions: RefCell::new(HashMap::new()),
527 glob_count: Cell::new(0),
528 resolved_import_count: Cell::new(0),
529 populated: Cell::new(!external),
533 fn all_imports_resolved(&self) -> bool {
534 self.imports.borrow().len() == self.resolved_import_count.get()
538 impl fmt::Show for Module {
539 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
540 write!(f, "{:?}, kind: {:?}, {}",
543 if self.is_public { "public" } else { "private" } )
549 flags DefModifiers: u8 {
550 const PUBLIC = 0b0000_0001,
551 const IMPORTABLE = 0b0000_0010,
555 // Records a possibly-private type definition.
556 #[derive(Clone,Show)]
558 modifiers: DefModifiers, // see note in ImportResolution about how to use this
559 module_def: Option<Rc<Module>>,
560 type_def: Option<Def>,
561 type_span: Option<Span>
564 // Records a possibly-private value definition.
565 #[derive(Clone, Copy, Show)]
567 modifiers: DefModifiers, // see note in ImportResolution about how to use this
569 value_span: Option<Span>,
572 // Records the definitions (at most one for each namespace) that a name is
575 struct NameBindings {
576 type_def: RefCell<Option<TypeNsDef>>, //< Meaning in type namespace.
577 value_def: RefCell<Option<ValueNsDef>>, //< Meaning in value namespace.
580 /// Ways in which a trait can be referenced
582 enum TraitReferenceType {
583 TraitImplementation, // impl SomeTrait for T { ... }
584 TraitDerivation, // trait T : SomeTrait { ... }
585 TraitBoundingTypeParameter, // fn f<T:SomeTrait>() { ... }
586 TraitObject, // Box<for<'a> SomeTrait>
587 TraitQPath, // <T as SomeTrait>::
591 fn new() -> NameBindings {
593 type_def: RefCell::new(None),
594 value_def: RefCell::new(None),
598 /// Creates a new module in this set of name bindings.
599 fn define_module(&self,
600 parent_link: ParentLink,
601 def_id: Option<DefId>,
606 // Merges the module with the existing type def or creates a new one.
607 let modifiers = if is_public { PUBLIC } else { DefModifiers::empty() } | IMPORTABLE;
608 let module_ = Rc::new(Module::new(parent_link,
613 let type_def = self.type_def.borrow().clone();
616 *self.type_def.borrow_mut() = Some(TypeNsDef {
617 modifiers: modifiers,
618 module_def: Some(module_),
624 *self.type_def.borrow_mut() = Some(TypeNsDef {
625 modifiers: modifiers,
626 module_def: Some(module_),
628 type_def: type_def.type_def
634 /// Sets the kind of the module, creating a new one if necessary.
635 fn set_module_kind(&self,
636 parent_link: ParentLink,
637 def_id: Option<DefId>,
642 let modifiers = if is_public { PUBLIC } else { DefModifiers::empty() } | IMPORTABLE;
643 let type_def = self.type_def.borrow().clone();
646 let module = Module::new(parent_link,
651 *self.type_def.borrow_mut() = Some(TypeNsDef {
652 modifiers: modifiers,
653 module_def: Some(Rc::new(module)),
659 match type_def.module_def {
661 let module = Module::new(parent_link,
666 *self.type_def.borrow_mut() = Some(TypeNsDef {
667 modifiers: modifiers,
668 module_def: Some(Rc::new(module)),
669 type_def: type_def.type_def,
673 Some(module_def) => module_def.kind.set(kind),
679 /// Records a type definition.
680 fn define_type(&self, def: Def, sp: Span, modifiers: DefModifiers) {
681 debug!("defining type for def {:?} with modifiers {:?}", def, modifiers);
682 // Merges the type with the existing type def or creates a new one.
683 let type_def = self.type_def.borrow().clone();
686 *self.type_def.borrow_mut() = Some(TypeNsDef {
690 modifiers: modifiers,
694 *self.type_def.borrow_mut() = Some(TypeNsDef {
695 module_def: type_def.module_def,
698 modifiers: modifiers,
704 /// Records a value definition.
705 fn define_value(&self, def: Def, sp: Span, modifiers: DefModifiers) {
706 debug!("defining value for def {:?} with modifiers {:?}", def, modifiers);
707 *self.value_def.borrow_mut() = Some(ValueNsDef {
709 value_span: Some(sp),
710 modifiers: modifiers,
714 /// Returns the module node if applicable.
715 fn get_module_if_available(&self) -> Option<Rc<Module>> {
716 match *self.type_def.borrow() {
717 Some(ref type_def) => type_def.module_def.clone(),
722 /// Returns the module node. Panics if this node does not have a module
724 fn get_module(&self) -> Rc<Module> {
725 match self.get_module_if_available() {
727 panic!("get_module called on a node with no module \
730 Some(module_def) => module_def
734 fn defined_in_namespace(&self, namespace: Namespace) -> bool {
736 TypeNS => return self.type_def.borrow().is_some(),
737 ValueNS => return self.value_def.borrow().is_some()
741 fn defined_in_public_namespace(&self, namespace: Namespace) -> bool {
742 self.defined_in_namespace_with(namespace, PUBLIC)
745 fn defined_in_namespace_with(&self, namespace: Namespace, modifiers: DefModifiers) -> bool {
747 TypeNS => match *self.type_def.borrow() {
748 Some(ref def) => def.modifiers.contains(modifiers), None => false
750 ValueNS => match *self.value_def.borrow() {
751 Some(ref def) => def.modifiers.contains(modifiers), None => false
756 fn def_for_namespace(&self, namespace: Namespace) -> Option<Def> {
759 match *self.type_def.borrow() {
761 Some(ref type_def) => {
762 match type_def.type_def {
763 Some(type_def) => Some(type_def),
765 match type_def.module_def {
766 Some(ref module) => {
767 match module.def_id.get() {
768 Some(did) => Some(DefMod(did)),
780 match *self.value_def.borrow() {
782 Some(value_def) => Some(value_def.def)
788 fn span_for_namespace(&self, namespace: Namespace) -> Option<Span> {
789 if self.defined_in_namespace(namespace) {
792 match *self.type_def.borrow() {
794 Some(ref type_def) => type_def.type_span
798 match *self.value_def.borrow() {
800 Some(ref value_def) => value_def.value_span
810 /// Interns the names of the primitive types.
811 struct PrimitiveTypeTable {
812 primitive_types: HashMap<Name, PrimTy>,
815 impl PrimitiveTypeTable {
816 fn new() -> PrimitiveTypeTable {
817 let mut table = PrimitiveTypeTable {
818 primitive_types: HashMap::new()
821 table.intern("bool", TyBool);
822 table.intern("char", TyChar);
823 table.intern("f32", TyFloat(TyF32));
824 table.intern("f64", TyFloat(TyF64));
825 table.intern("int", TyInt(TyIs(true)));
826 table.intern("isize", TyInt(TyIs(false)));
827 table.intern("i8", TyInt(TyI8));
828 table.intern("i16", TyInt(TyI16));
829 table.intern("i32", TyInt(TyI32));
830 table.intern("i64", TyInt(TyI64));
831 table.intern("str", TyStr);
832 table.intern("uint", TyUint(TyUs(true)));
833 table.intern("usize", TyUint(TyUs(false)));
834 table.intern("u8", TyUint(TyU8));
835 table.intern("u16", TyUint(TyU16));
836 table.intern("u32", TyUint(TyU32));
837 table.intern("u64", TyUint(TyU64));
842 fn intern(&mut self, string: &str, primitive_type: PrimTy) {
843 self.primitive_types.insert(token::intern(string), primitive_type);
847 /// The main resolver class.
848 struct Resolver<'a, 'tcx:'a> {
849 session: &'a Session,
851 ast_map: &'a ast_map::Map<'tcx>,
853 graph_root: NameBindings,
855 trait_item_map: FnvHashMap<(Name, DefId), TraitItemKind>,
857 structs: FnvHashMap<DefId, Vec<Name>>,
859 // The number of imports that are currently unresolved.
860 unresolved_imports: uint,
862 // The module that represents the current item scope.
863 current_module: Rc<Module>,
865 // The current set of local scopes, for values.
866 // FIXME #4948: Reuse ribs to avoid allocation.
867 value_ribs: Vec<Rib>,
869 // The current set of local scopes, for types.
872 // The current set of local scopes, for labels.
873 label_ribs: Vec<Rib>,
875 // The trait that the current context can refer to.
876 current_trait_ref: Option<(DefId, TraitRef)>,
878 // The current self type if inside an impl (used for better errors).
879 current_self_type: Option<Ty>,
881 // The ident for the keyword "self".
883 // The ident for the non-keyword "Self".
884 type_self_name: Name,
886 // The idents for the primitive types.
887 primitive_type_table: PrimitiveTypeTable,
890 freevars: RefCell<FreevarMap>,
891 freevars_seen: RefCell<NodeMap<NodeSet>>,
892 capture_mode_map: CaptureModeMap,
893 export_map: ExportMap,
895 external_exports: ExternalExports,
896 last_private: LastPrivateMap,
898 // Whether or not to print error messages. Can be set to true
899 // when getting additional info for error message suggestions,
900 // so as to avoid printing duplicate errors
904 // Maps imports to the names of items actually imported (this actually maps
905 // all imports, but only glob imports are actually interesting).
908 used_imports: HashSet<(NodeId, Namespace)>,
909 used_crates: HashSet<CrateNum>,
913 enum FallbackChecks {
919 impl<'a, 'tcx> Resolver<'a, 'tcx> {
920 fn new(session: &'a Session,
921 ast_map: &'a ast_map::Map<'tcx>,
923 make_glob_map: MakeGlobMap) -> Resolver<'a, 'tcx> {
924 let graph_root = NameBindings::new();
926 graph_root.define_module(NoParentLink,
927 Some(DefId { krate: 0, node: 0 }),
933 let current_module = graph_root.get_module();
940 // The outermost module has def ID 0; this is not reflected in the
943 graph_root: graph_root,
945 trait_item_map: FnvHashMap::new(),
946 structs: FnvHashMap::new(),
948 unresolved_imports: 0,
950 current_module: current_module,
951 value_ribs: Vec::new(),
952 type_ribs: Vec::new(),
953 label_ribs: Vec::new(),
955 current_trait_ref: None,
956 current_self_type: None,
958 self_name: special_names::self_,
959 type_self_name: special_names::type_self,
961 primitive_type_table: PrimitiveTypeTable::new(),
963 def_map: RefCell::new(NodeMap::new()),
964 freevars: RefCell::new(NodeMap::new()),
965 freevars_seen: RefCell::new(NodeMap::new()),
966 capture_mode_map: NodeMap::new(),
967 export_map: NodeMap::new(),
968 trait_map: NodeMap::new(),
969 used_imports: HashSet::new(),
970 used_crates: HashSet::new(),
971 external_exports: DefIdSet::new(),
972 last_private: NodeMap::new(),
975 make_glob_map: make_glob_map == MakeGlobMap::Yes,
976 glob_map: HashMap::new(),
982 // This is a fixed-point algorithm. We resolve imports until our efforts
983 // are stymied by an unresolved import; then we bail out of the current
984 // module and continue. We terminate successfully once no more imports
985 // remain or unsuccessfully when no forward progress in resolving imports
988 /// Resolves all imports for the crate. This method performs the fixed-
990 fn resolve_imports(&mut self) {
992 let mut prev_unresolved_imports = 0;
994 debug!("(resolving imports) iteration {}, {} imports left",
995 i, self.unresolved_imports);
997 let module_root = self.graph_root.get_module();
998 self.resolve_imports_for_module_subtree(module_root.clone());
1000 if self.unresolved_imports == 0 {
1001 debug!("(resolving imports) success");
1005 if self.unresolved_imports == prev_unresolved_imports {
1006 self.report_unresolved_imports(module_root);
1011 prev_unresolved_imports = self.unresolved_imports;
1015 /// Attempts to resolve imports for the given module and all of its
1017 fn resolve_imports_for_module_subtree(&mut self, module_: Rc<Module>) {
1018 debug!("(resolving imports for module subtree) resolving {}",
1019 self.module_to_string(&*module_));
1020 let orig_module = replace(&mut self.current_module, module_.clone());
1021 self.resolve_imports_for_module(module_.clone());
1022 self.current_module = orig_module;
1024 build_reduced_graph::populate_module_if_necessary(self, &module_);
1025 for (_, child_node) in module_.children.borrow().iter() {
1026 match child_node.get_module_if_available() {
1030 Some(child_module) => {
1031 self.resolve_imports_for_module_subtree(child_module);
1036 for (_, child_module) in module_.anonymous_children.borrow().iter() {
1037 self.resolve_imports_for_module_subtree(child_module.clone());
1041 /// Attempts to resolve imports for the given module only.
1042 fn resolve_imports_for_module(&mut self, module: Rc<Module>) {
1043 if module.all_imports_resolved() {
1044 debug!("(resolving imports for module) all imports resolved for \
1046 self.module_to_string(&*module));
1050 let imports = module.imports.borrow();
1051 let import_count = imports.len();
1052 while module.resolved_import_count.get() < import_count {
1053 let import_index = module.resolved_import_count.get();
1054 let import_directive = &(*imports)[import_index];
1055 match self.resolve_import_for_module(module.clone(),
1058 let (span, help) = match err {
1059 Some((span, msg)) => (span, format!(". {}", msg)),
1060 None => (import_directive.span, String::new())
1062 let msg = format!("unresolved import `{}`{}",
1063 self.import_path_to_string(
1064 &import_directive.module_path[],
1065 import_directive.subclass),
1067 self.resolve_error(span, &msg[]);
1069 Indeterminate => break, // Bail out. We'll come around next time.
1070 Success(()) => () // Good. Continue.
1073 module.resolved_import_count
1074 .set(module.resolved_import_count.get() + 1);
1078 fn names_to_string(&self, names: &[Name]) -> String {
1079 let mut first = true;
1080 let mut result = String::new();
1081 for name in names.iter() {
1085 result.push_str("::")
1087 result.push_str(token::get_name(*name).get());
1092 fn path_names_to_string(&self, path: &Path) -> String {
1093 let names: Vec<ast::Name> = path.segments
1095 .map(|seg| seg.identifier.name)
1097 self.names_to_string(&names[])
1100 fn import_directive_subclass_to_string(&mut self,
1101 subclass: ImportDirectiveSubclass)
1104 SingleImport(_, source) => {
1105 token::get_name(source).get().to_string()
1107 GlobImport => "*".to_string()
1111 fn import_path_to_string(&mut self,
1113 subclass: ImportDirectiveSubclass)
1115 if names.is_empty() {
1116 self.import_directive_subclass_to_string(subclass)
1119 self.names_to_string(names),
1120 self.import_directive_subclass_to_string(
1121 subclass))).to_string()
1126 fn record_import_use(&mut self, import_id: NodeId, name: Name) {
1127 if !self.make_glob_map {
1130 if self.glob_map.contains_key(&import_id) {
1131 self.glob_map[import_id].insert(name);
1135 let mut new_set = HashSet::new();
1136 new_set.insert(name);
1137 self.glob_map.insert(import_id, new_set);
1140 fn get_trait_name(&self, did: DefId) -> Name {
1141 if did.krate == LOCAL_CRATE {
1142 self.ast_map.expect_item(did.node).ident.name
1144 csearch::get_trait_name(&self.session.cstore, did)
1148 /// Attempts to resolve the given import. The return value indicates
1149 /// failure if we're certain the name does not exist, indeterminate if we
1150 /// don't know whether the name exists at the moment due to other
1151 /// currently-unresolved imports, or success if we know the name exists.
1152 /// If successful, the resolved bindings are written into the module.
1153 fn resolve_import_for_module(&mut self,
1154 module_: Rc<Module>,
1155 import_directive: &ImportDirective)
1156 -> ResolveResult<()> {
1157 let mut resolution_result = Failed(None);
1158 let module_path = &import_directive.module_path;
1160 debug!("(resolving import for module) resolving import `{}::...` in `{}`",
1161 self.names_to_string(&module_path[]),
1162 self.module_to_string(&*module_));
1164 // First, resolve the module path for the directive, if necessary.
1165 let container = if module_path.len() == 0 {
1166 // Use the crate root.
1167 Some((self.graph_root.get_module(), LastMod(AllPublic)))
1169 match self.resolve_module_path(module_.clone(),
1171 DontUseLexicalScope,
1172 import_directive.span,
1175 resolution_result = Failed(err);
1179 resolution_result = Indeterminate;
1182 Success(container) => Some(container),
1188 Some((containing_module, lp)) => {
1189 // We found the module that the target is contained
1190 // within. Attempt to resolve the import within it.
1192 match import_directive.subclass {
1193 SingleImport(target, source) => {
1195 self.resolve_single_import(&*module_,
1204 self.resolve_glob_import(&*module_,
1213 // Decrement the count of unresolved imports.
1214 match resolution_result {
1216 assert!(self.unresolved_imports >= 1);
1217 self.unresolved_imports -= 1;
1220 // Nothing to do here; just return the error.
1224 // Decrement the count of unresolved globs if necessary. But only if
1225 // the resolution result is indeterminate -- otherwise we'll stop
1226 // processing imports here. (See the loop in
1227 // resolve_imports_for_module.)
1229 if !resolution_result.indeterminate() {
1230 match import_directive.subclass {
1232 assert!(module_.glob_count.get() >= 1);
1233 module_.glob_count.set(module_.glob_count.get() - 1);
1235 SingleImport(..) => {
1241 return resolution_result;
1244 fn create_name_bindings_from_module(module: Rc<Module>) -> NameBindings {
1246 type_def: RefCell::new(Some(TypeNsDef {
1247 modifiers: IMPORTABLE,
1248 module_def: Some(module),
1252 value_def: RefCell::new(None),
1256 fn resolve_single_import(&mut self,
1258 containing_module: Rc<Module>,
1261 directive: &ImportDirective,
1263 -> ResolveResult<()> {
1264 debug!("(resolving single import) resolving `{}` = `{}::{}` from \
1265 `{}` id {}, last private {:?}",
1266 token::get_name(target),
1267 self.module_to_string(&*containing_module),
1268 token::get_name(source),
1269 self.module_to_string(module_),
1275 LastImport {..} => {
1277 .span_bug(directive.span,
1278 "not expecting Import here, must be LastMod")
1282 // We need to resolve both namespaces for this to succeed.
1285 let mut value_result = UnknownResult;
1286 let mut type_result = UnknownResult;
1288 // Search for direct children of the containing module.
1289 build_reduced_graph::populate_module_if_necessary(self, &containing_module);
1291 match containing_module.children.borrow().get(&source) {
1295 Some(ref child_name_bindings) => {
1296 if child_name_bindings.defined_in_namespace(ValueNS) {
1297 debug!("(resolving single import) found value binding");
1298 value_result = BoundResult(containing_module.clone(),
1299 (*child_name_bindings).clone());
1301 if child_name_bindings.defined_in_namespace(TypeNS) {
1302 debug!("(resolving single import) found type binding");
1303 type_result = BoundResult(containing_module.clone(),
1304 (*child_name_bindings).clone());
1309 // Unless we managed to find a result in both namespaces (unlikely),
1310 // search imports as well.
1311 let mut value_used_reexport = false;
1312 let mut type_used_reexport = false;
1313 match (value_result.clone(), type_result.clone()) {
1314 (BoundResult(..), BoundResult(..)) => {} // Continue.
1316 // If there is an unresolved glob at this point in the
1317 // containing module, bail out. We don't know enough to be
1318 // able to resolve this import.
1320 if containing_module.glob_count.get() > 0 {
1321 debug!("(resolving single import) unresolved glob; \
1323 return Indeterminate;
1326 // Now search the exported imports within the containing module.
1327 match containing_module.import_resolutions.borrow().get(&source) {
1329 debug!("(resolving single import) no import");
1330 // The containing module definitely doesn't have an
1331 // exported import with the name in question. We can
1332 // therefore accurately report that the names are
1335 if value_result.is_unknown() {
1336 value_result = UnboundResult;
1338 if type_result.is_unknown() {
1339 type_result = UnboundResult;
1342 Some(import_resolution)
1343 if import_resolution.outstanding_references == 0 => {
1345 fn get_binding(this: &mut Resolver,
1346 import_resolution: &ImportResolution,
1347 namespace: Namespace,
1349 -> NamespaceResult {
1351 // Import resolutions must be declared with "pub"
1352 // in order to be exported.
1353 if !import_resolution.is_public {
1354 return UnboundResult;
1357 match import_resolution.
1358 target_for_namespace(namespace) {
1360 return UnboundResult;
1367 debug!("(resolving single import) found \
1368 import in ns {:?}", namespace);
1369 let id = import_resolution.id(namespace);
1370 // track used imports and extern crates as well
1371 this.used_imports.insert((id, namespace));
1372 this.record_import_use(id, *source);
1373 match target_module.def_id.get() {
1374 Some(DefId{krate: kid, ..}) => {
1375 this.used_crates.insert(kid);
1379 return BoundResult(target_module, bindings);
1384 // The name is an import which has been fully
1385 // resolved. We can, therefore, just follow it.
1386 if value_result.is_unknown() {
1387 value_result = get_binding(self,
1391 value_used_reexport = import_resolution.is_public;
1393 if type_result.is_unknown() {
1394 type_result = get_binding(self,
1398 type_used_reexport = import_resolution.is_public;
1403 // If containing_module is the same module whose import we are resolving
1404 // and there it has an unresolved import with the same name as `source`,
1405 // then the user is actually trying to import an item that is declared
1406 // in the same scope
1409 // use self::submodule;
1410 // pub mod submodule;
1412 // In this case we continue as if we resolved the import and let the
1413 // check_for_conflicts_between_imports_and_items call below handle
1415 match (module_.def_id.get(), containing_module.def_id.get()) {
1416 (Some(id1), Some(id2)) if id1 == id2 => {
1417 if value_result.is_unknown() {
1418 value_result = UnboundResult;
1420 if type_result.is_unknown() {
1421 type_result = UnboundResult;
1425 // The import is unresolved. Bail out.
1426 debug!("(resolving single import) unresolved import; \
1428 return Indeterminate;
1436 // If we didn't find a result in the type namespace, search the
1437 // external modules.
1438 let mut value_used_public = false;
1439 let mut type_used_public = false;
1441 BoundResult(..) => {}
1443 match containing_module.external_module_children.borrow_mut()
1444 .get(&source).cloned() {
1445 None => {} // Continue.
1447 debug!("(resolving single import) found external \
1449 // track the module as used.
1450 match module.def_id.get() {
1451 Some(DefId{krate: kid, ..}) => { self.used_crates.insert(kid); },
1455 Rc::new(Resolver::create_name_bindings_from_module(
1457 type_result = BoundResult(containing_module.clone(),
1459 type_used_public = true;
1465 // We've successfully resolved the import. Write the results in.
1466 let mut import_resolutions = module_.import_resolutions.borrow_mut();
1467 let import_resolution = &mut (*import_resolutions)[target];
1469 let mut check_and_write_import = |&mut: namespace, result: &_, used_public: &mut bool| {
1470 let namespace_name = match namespace {
1476 BoundResult(ref target_module, ref name_bindings) => {
1477 debug!("(resolving single import) found {:?} target: {:?}",
1479 name_bindings.def_for_namespace(namespace));
1480 self.check_for_conflicting_import(
1481 &import_resolution.target_for_namespace(namespace),
1486 self.check_that_import_is_importable(
1492 let target = Some(Target::new(target_module.clone(),
1493 name_bindings.clone(),
1494 directive.shadowable));
1495 import_resolution.set_target_and_id(namespace, target, directive.id);
1496 import_resolution.is_public = directive.is_public;
1497 *used_public = name_bindings.defined_in_public_namespace(namespace);
1499 UnboundResult => { /* Continue. */ }
1501 panic!("{:?} result should be known at this point", namespace_name);
1505 check_and_write_import(ValueNS, &value_result, &mut value_used_public);
1506 check_and_write_import(TypeNS, &type_result, &mut type_used_public);
1509 self.check_for_conflicts_between_imports_and_items(
1515 if value_result.is_unbound() && type_result.is_unbound() {
1516 let msg = format!("There is no `{}` in `{}`",
1517 token::get_name(source),
1518 self.module_to_string(&*containing_module));
1519 return Failed(Some((directive.span, msg)));
1521 let value_used_public = value_used_reexport || value_used_public;
1522 let type_used_public = type_used_reexport || type_used_public;
1524 assert!(import_resolution.outstanding_references >= 1);
1525 import_resolution.outstanding_references -= 1;
1527 // record what this import resolves to for later uses in documentation,
1528 // this may resolve to either a value or a type, but for documentation
1529 // purposes it's good enough to just favor one over the other.
1530 let value_private = match import_resolution.value_target {
1531 Some(ref target) => {
1532 let def = target.bindings.def_for_namespace(ValueNS).unwrap();
1533 self.def_map.borrow_mut().insert(directive.id, def);
1534 let did = def.def_id();
1535 if value_used_public {Some(lp)} else {Some(DependsOn(did))}
1537 // AllPublic here and below is a dummy value, it should never be used because
1538 // _exists is false.
1541 let type_private = match import_resolution.type_target {
1542 Some(ref target) => {
1543 let def = target.bindings.def_for_namespace(TypeNS).unwrap();
1544 self.def_map.borrow_mut().insert(directive.id, def);
1545 let did = def.def_id();
1546 if type_used_public {Some(lp)} else {Some(DependsOn(did))}
1551 self.last_private.insert(directive.id, LastImport{value_priv: value_private,
1553 type_priv: type_private,
1556 debug!("(resolving single import) successfully resolved import");
1560 // Resolves a glob import. Note that this function cannot fail; it either
1561 // succeeds or bails out (as importing * from an empty module or a module
1562 // that exports nothing is valid). containing_module is the module we are
1563 // actually importing, i.e., `foo` in `use foo::*`.
1564 fn resolve_glob_import(&mut self,
1566 containing_module: Rc<Module>,
1567 import_directive: &ImportDirective,
1569 -> ResolveResult<()> {
1570 let id = import_directive.id;
1571 let is_public = import_directive.is_public;
1573 // This function works in a highly imperative manner; it eagerly adds
1574 // everything it can to the list of import resolutions of the module
1576 debug!("(resolving glob import) resolving glob import {}", id);
1578 // We must bail out if the node has unresolved imports of any kind
1579 // (including globs).
1580 if !(*containing_module).all_imports_resolved() {
1581 debug!("(resolving glob import) target module has unresolved \
1582 imports; bailing out");
1583 return Indeterminate;
1586 assert_eq!(containing_module.glob_count.get(), 0);
1588 // Add all resolved imports from the containing module.
1589 let import_resolutions = containing_module.import_resolutions.borrow();
1590 for (ident, target_import_resolution) in import_resolutions.iter() {
1591 debug!("(resolving glob import) writing module resolution \
1593 token::get_name(*ident),
1594 self.module_to_string(module_));
1596 if !target_import_resolution.is_public {
1597 debug!("(resolving glob import) nevermind, just kidding");
1601 // Here we merge two import resolutions.
1602 let mut import_resolutions = module_.import_resolutions.borrow_mut();
1603 match import_resolutions.get_mut(ident) {
1604 Some(dest_import_resolution) => {
1605 // Merge the two import resolutions at a finer-grained
1608 match target_import_resolution.value_target {
1612 Some(ref value_target) => {
1613 self.check_for_conflicting_import(&dest_import_resolution.value_target,
1614 import_directive.span,
1617 dest_import_resolution.value_target = Some(value_target.clone());
1620 match target_import_resolution.type_target {
1624 Some(ref type_target) => {
1625 self.check_for_conflicting_import(&dest_import_resolution.type_target,
1626 import_directive.span,
1629 dest_import_resolution.type_target = Some(type_target.clone());
1632 dest_import_resolution.is_public = is_public;
1638 // Simple: just copy the old import resolution.
1639 let mut new_import_resolution = ImportResolution::new(id, is_public);
1640 new_import_resolution.value_target =
1641 target_import_resolution.value_target.clone();
1642 new_import_resolution.type_target =
1643 target_import_resolution.type_target.clone();
1645 import_resolutions.insert(*ident, new_import_resolution);
1648 // Add all children from the containing module.
1649 build_reduced_graph::populate_module_if_necessary(self, &containing_module);
1651 for (&name, name_bindings) in containing_module.children.borrow().iter() {
1652 self.merge_import_resolution(module_,
1653 containing_module.clone(),
1656 name_bindings.clone());
1660 // Add external module children from the containing module.
1661 for (&name, module) in containing_module.external_module_children.borrow().iter() {
1663 Rc::new(Resolver::create_name_bindings_from_module(module.clone()));
1664 self.merge_import_resolution(module_,
1665 containing_module.clone(),
1671 // Record the destination of this import
1672 match containing_module.def_id.get() {
1674 self.def_map.borrow_mut().insert(id, DefMod(did));
1675 self.last_private.insert(id, lp);
1680 debug!("(resolving glob import) successfully resolved import");
1684 fn merge_import_resolution(&mut self,
1686 containing_module: Rc<Module>,
1687 import_directive: &ImportDirective,
1689 name_bindings: Rc<NameBindings>) {
1690 let id = import_directive.id;
1691 let is_public = import_directive.is_public;
1693 let mut import_resolutions = module_.import_resolutions.borrow_mut();
1694 let dest_import_resolution = import_resolutions.entry(name).get().unwrap_or_else(
1696 // Create a new import resolution from this child.
1697 vacant_entry.insert(ImportResolution::new(id, is_public))
1700 debug!("(resolving glob import) writing resolution `{}` in `{}` \
1702 token::get_name(name).get(),
1703 self.module_to_string(&*containing_module),
1704 self.module_to_string(module_));
1706 // Merge the child item into the import resolution.
1708 let mut merge_child_item = |&mut : namespace| {
1709 if name_bindings.defined_in_namespace_with(namespace, IMPORTABLE | PUBLIC) {
1710 let namespace_name = match namespace {
1714 debug!("(resolving glob import) ... for {} target", namespace_name);
1715 if dest_import_resolution.shadowable(namespace) == Shadowable::Never {
1716 let msg = format!("a {} named `{}` has already been imported \
1719 token::get_name(name).get());
1720 self.session.span_err(import_directive.span, msg.as_slice());
1722 let target = Target::new(containing_module.clone(),
1723 name_bindings.clone(),
1724 import_directive.shadowable);
1725 dest_import_resolution.set_target_and_id(namespace,
1731 merge_child_item(ValueNS);
1732 merge_child_item(TypeNS);
1735 dest_import_resolution.is_public = is_public;
1737 self.check_for_conflicts_between_imports_and_items(
1739 dest_import_resolution,
1740 import_directive.span,
1744 /// Checks that imported names and items don't have the same name.
1745 fn check_for_conflicting_import(&mut self,
1746 target: &Option<Target>,
1749 namespace: Namespace) {
1750 if self.session.features.borrow().import_shadowing {
1754 debug!("check_for_conflicting_import: {}; target exists: {}",
1755 token::get_name(name).get(),
1759 Some(ref target) if target.shadowable != Shadowable::Always => {
1760 let msg = format!("a {} named `{}` has already been imported \
1766 token::get_name(name).get());
1767 self.session.span_err(import_span, &msg[]);
1769 Some(_) | None => {}
1773 /// Checks that an import is actually importable
1774 fn check_that_import_is_importable(&mut self,
1775 name_bindings: &NameBindings,
1778 namespace: Namespace) {
1779 if !name_bindings.defined_in_namespace_with(namespace, IMPORTABLE) {
1780 let msg = format!("`{}` is not directly importable",
1781 token::get_name(name));
1782 self.session.span_err(import_span, &msg[]);
1786 /// Checks that imported names and items don't have the same name.
1787 fn check_for_conflicts_between_imports_and_items(&mut self,
1793 if self.session.features.borrow().import_shadowing {
1797 // First, check for conflicts between imports and `extern crate`s.
1798 if module.external_module_children
1800 .contains_key(&name) {
1801 match import_resolution.type_target {
1802 Some(ref target) if target.shadowable != Shadowable::Always => {
1803 let msg = format!("import `{0}` conflicts with imported \
1804 crate in this module \
1805 (maybe you meant `use {0}::*`?)",
1806 token::get_name(name).get());
1807 self.session.span_err(import_span, &msg[]);
1809 Some(_) | None => {}
1813 // Check for item conflicts.
1814 let children = module.children.borrow();
1815 let name_bindings = match children.get(&name) {
1817 // There can't be any conflicts.
1820 Some(ref name_bindings) => (*name_bindings).clone(),
1823 match import_resolution.value_target {
1824 Some(ref target) if target.shadowable != Shadowable::Always => {
1825 if let Some(ref value) = *name_bindings.value_def.borrow() {
1826 let msg = format!("import `{}` conflicts with value \
1828 token::get_name(name).get());
1829 self.session.span_err(import_span, &msg[]);
1830 if let Some(span) = value.value_span {
1831 self.session.span_note(span,
1832 "conflicting value here");
1836 Some(_) | None => {}
1839 match import_resolution.type_target {
1840 Some(ref target) if target.shadowable != Shadowable::Always => {
1841 if let Some(ref ty) = *name_bindings.type_def.borrow() {
1842 match ty.module_def {
1844 let msg = format!("import `{}` conflicts with type in \
1846 token::get_name(name).get());
1847 self.session.span_err(import_span, &msg[]);
1848 if let Some(span) = ty.type_span {
1849 self.session.span_note(span,
1850 "note conflicting type here")
1853 Some(ref module_def) => {
1854 match module_def.kind.get() {
1856 if let Some(span) = ty.type_span {
1857 let msg = format!("inherent implementations \
1858 are only allowed on types \
1859 defined in the current module");
1860 self.session.span_err(span, &msg[]);
1861 self.session.span_note(import_span,
1862 "import from other module here")
1866 let msg = format!("import `{}` conflicts with existing \
1868 token::get_name(name).get());
1869 self.session.span_err(import_span, &msg[]);
1870 if let Some(span) = ty.type_span {
1871 self.session.span_note(span,
1872 "note conflicting module here")
1880 Some(_) | None => {}
1884 /// Checks that the names of external crates don't collide with other
1885 /// external crates.
1886 fn check_for_conflicts_between_external_crates(&self,
1890 if self.session.features.borrow().import_shadowing {
1894 if module.external_module_children.borrow().contains_key(&name) {
1897 &format!("an external crate named `{}` has already \
1898 been imported into this module",
1899 token::get_name(name).get())[]);
1903 /// Checks that the names of items don't collide with external crates.
1904 fn check_for_conflicts_between_external_crates_and_items(&self,
1908 if self.session.features.borrow().import_shadowing {
1912 if module.external_module_children.borrow().contains_key(&name) {
1915 &format!("the name `{}` conflicts with an external \
1916 crate that has been imported into this \
1918 token::get_name(name).get())[]);
1922 /// Resolves the given module path from the given root `module_`.
1923 fn resolve_module_path_from_root(&mut self,
1924 module_: Rc<Module>,
1925 module_path: &[Name],
1928 name_search_type: NameSearchType,
1930 -> ResolveResult<(Rc<Module>, LastPrivate)> {
1931 fn search_parent_externals(needle: Name, module: &Rc<Module>)
1932 -> Option<Rc<Module>> {
1933 module.external_module_children.borrow()
1934 .get(&needle).cloned()
1935 .map(|_| module.clone())
1937 match module.parent_link.clone() {
1938 ModuleParentLink(parent, _) => {
1939 search_parent_externals(needle,
1940 &parent.upgrade().unwrap())
1947 let mut search_module = module_;
1948 let mut index = index;
1949 let module_path_len = module_path.len();
1950 let mut closest_private = lp;
1952 // Resolve the module part of the path. This does not involve looking
1953 // upward though scope chains; we simply resolve names directly in
1954 // modules as we go.
1955 while index < module_path_len {
1956 let name = module_path[index];
1957 match self.resolve_name_in_module(search_module.clone(),
1963 let segment_name = token::get_name(name);
1964 let module_name = self.module_to_string(&*search_module);
1965 let mut span = span;
1966 let msg = if "???" == &module_name[] {
1967 span.hi = span.lo + Pos::from_uint(segment_name.get().len());
1969 match search_parent_externals(name,
1970 &self.current_module) {
1972 let path_str = self.names_to_string(module_path);
1973 let target_mod_str = self.module_to_string(&*module);
1974 let current_mod_str =
1975 self.module_to_string(&*self.current_module);
1977 let prefix = if target_mod_str == current_mod_str {
1978 "self::".to_string()
1980 format!("{}::", target_mod_str)
1983 format!("Did you mean `{}{}`?", prefix, path_str)
1985 None => format!("Maybe a missing `extern crate {}`?",
1989 format!("Could not find `{}` in `{}`",
1994 return Failed(Some((span, msg)));
1996 Failed(err) => return Failed(err),
1998 debug!("(resolving module path for import) module \
1999 resolution is indeterminate: {}",
2000 token::get_name(name));
2001 return Indeterminate;
2003 Success((target, used_proxy)) => {
2004 // Check to see whether there are type bindings, and, if
2005 // so, whether there is a module within.
2006 match *target.bindings.type_def.borrow() {
2007 Some(ref type_def) => {
2008 match type_def.module_def {
2010 let msg = format!("Not a module `{}`",
2011 token::get_name(name));
2013 return Failed(Some((span, msg)));
2015 Some(ref module_def) => {
2016 search_module = module_def.clone();
2018 // track extern crates for unused_extern_crate lint
2019 if let Some(did) = module_def.def_id.get() {
2020 self.used_crates.insert(did.krate);
2023 // Keep track of the closest
2024 // private module used when
2025 // resolving this import chain.
2026 if !used_proxy && !search_module.is_public {
2027 if let Some(did) = search_module.def_id.get() {
2028 closest_private = LastMod(DependsOn(did));
2035 // There are no type bindings at all.
2036 let msg = format!("Not a module `{}`",
2037 token::get_name(name));
2038 return Failed(Some((span, msg)));
2047 return Success((search_module, closest_private));
2050 /// Attempts to resolve the module part of an import directive or path
2051 /// rooted at the given module.
2053 /// On success, returns the resolved module, and the closest *private*
2054 /// module found to the destination when resolving this path.
2055 fn resolve_module_path(&mut self,
2056 module_: Rc<Module>,
2057 module_path: &[Name],
2058 use_lexical_scope: UseLexicalScopeFlag,
2060 name_search_type: NameSearchType)
2061 -> ResolveResult<(Rc<Module>, LastPrivate)> {
2062 let module_path_len = module_path.len();
2063 assert!(module_path_len > 0);
2065 debug!("(resolving module path for import) processing `{}` rooted at `{}`",
2066 self.names_to_string(module_path),
2067 self.module_to_string(&*module_));
2069 // Resolve the module prefix, if any.
2070 let module_prefix_result = self.resolve_module_prefix(module_.clone(),
2076 match module_prefix_result {
2078 let mpath = self.names_to_string(module_path);
2079 let mpath = &mpath[];
2080 match mpath.rfind(':') {
2082 let msg = format!("Could not find `{}` in `{}`",
2083 // idx +- 1 to account for the
2084 // colons on either side
2085 &mpath[(idx + 1)..],
2086 &mpath[..(idx - 1)]);
2087 return Failed(Some((span, msg)));
2094 Failed(err) => return Failed(err),
2096 debug!("(resolving module path for import) indeterminate; \
2098 return Indeterminate;
2100 Success(NoPrefixFound) => {
2101 // There was no prefix, so we're considering the first element
2102 // of the path. How we handle this depends on whether we were
2103 // instructed to use lexical scope or not.
2104 match use_lexical_scope {
2105 DontUseLexicalScope => {
2106 // This is a crate-relative path. We will start the
2107 // resolution process at index zero.
2108 search_module = self.graph_root.get_module();
2110 last_private = LastMod(AllPublic);
2112 UseLexicalScope => {
2113 // This is not a crate-relative path. We resolve the
2114 // first component of the path in the current lexical
2115 // scope and then proceed to resolve below that.
2116 match self.resolve_module_in_lexical_scope(module_,
2118 Failed(err) => return Failed(err),
2120 debug!("(resolving module path for import) \
2121 indeterminate; bailing");
2122 return Indeterminate;
2124 Success(containing_module) => {
2125 search_module = containing_module;
2127 last_private = LastMod(AllPublic);
2133 Success(PrefixFound(ref containing_module, index)) => {
2134 search_module = containing_module.clone();
2135 start_index = index;
2136 last_private = LastMod(DependsOn(containing_module.def_id
2142 self.resolve_module_path_from_root(search_module,
2150 /// Invariant: This must only be called during main resolution, not during
2151 /// import resolution.
2152 fn resolve_item_in_lexical_scope(&mut self,
2153 module_: Rc<Module>,
2155 namespace: Namespace)
2156 -> ResolveResult<(Target, bool)> {
2157 debug!("(resolving item in lexical scope) resolving `{}` in \
2158 namespace {:?} in `{}`",
2159 token::get_name(name),
2161 self.module_to_string(&*module_));
2163 // The current module node is handled specially. First, check for
2164 // its immediate children.
2165 build_reduced_graph::populate_module_if_necessary(self, &module_);
2167 match module_.children.borrow().get(&name) {
2169 if name_bindings.defined_in_namespace(namespace) => {
2170 debug!("top name bindings succeeded");
2171 return Success((Target::new(module_.clone(),
2172 name_bindings.clone(),
2176 Some(_) | None => { /* Not found; continue. */ }
2179 // Now check for its import directives. We don't have to have resolved
2180 // all its imports in the usual way; this is because chains of
2181 // adjacent import statements are processed as though they mutated the
2183 if let Some(import_resolution) = module_.import_resolutions.borrow().get(&name) {
2184 match (*import_resolution).target_for_namespace(namespace) {
2186 // Not found; continue.
2187 debug!("(resolving item in lexical scope) found \
2188 import resolution, but not in namespace {:?}",
2192 debug!("(resolving item in lexical scope) using \
2193 import resolution");
2194 // track used imports and extern crates as well
2195 let id = import_resolution.id(namespace);
2196 self.used_imports.insert((id, namespace));
2197 self.record_import_use(id, name);
2198 if let Some(DefId{krate: kid, ..}) = target.target_module.def_id.get() {
2199 self.used_crates.insert(kid);
2201 return Success((target, false));
2206 // Search for external modules.
2207 if namespace == TypeNS {
2208 if let Some(module) = module_.external_module_children.borrow().get(&name).cloned() {
2210 Rc::new(Resolver::create_name_bindings_from_module(module));
2211 debug!("lower name bindings succeeded");
2212 return Success((Target::new(module_,
2219 // Finally, proceed up the scope chain looking for parent modules.
2220 let mut search_module = module_;
2222 // Go to the next parent.
2223 match search_module.parent_link.clone() {
2225 // No more parents. This module was unresolved.
2226 debug!("(resolving item in lexical scope) unresolved \
2228 return Failed(None);
2230 ModuleParentLink(parent_module_node, _) => {
2231 match search_module.kind.get() {
2232 NormalModuleKind => {
2233 // We stop the search here.
2234 debug!("(resolving item in lexical \
2235 scope) unresolved module: not \
2236 searching through module \
2238 return Failed(None);
2243 AnonymousModuleKind => {
2244 search_module = parent_module_node.upgrade().unwrap();
2248 BlockParentLink(ref parent_module_node, _) => {
2249 search_module = parent_module_node.upgrade().unwrap();
2253 // Resolve the name in the parent module.
2254 match self.resolve_name_in_module(search_module.clone(),
2259 Failed(Some((span, msg))) =>
2260 self.resolve_error(span, &format!("failed to resolve. {}",
2262 Failed(None) => (), // Continue up the search chain.
2264 // We couldn't see through the higher scope because of an
2265 // unresolved import higher up. Bail.
2267 debug!("(resolving item in lexical scope) indeterminate \
2268 higher scope; bailing");
2269 return Indeterminate;
2271 Success((target, used_reexport)) => {
2272 // We found the module.
2273 debug!("(resolving item in lexical scope) found name \
2275 return Success((target, used_reexport));
2281 /// Resolves a module name in the current lexical scope.
2282 fn resolve_module_in_lexical_scope(&mut self,
2283 module_: Rc<Module>,
2285 -> ResolveResult<Rc<Module>> {
2286 // If this module is an anonymous module, resolve the item in the
2287 // lexical scope. Otherwise, resolve the item from the crate root.
2288 let resolve_result = self.resolve_item_in_lexical_scope(module_, name, TypeNS);
2289 match resolve_result {
2290 Success((target, _)) => {
2291 let bindings = &*target.bindings;
2292 match *bindings.type_def.borrow() {
2293 Some(ref type_def) => {
2294 match type_def.module_def {
2296 debug!("!!! (resolving module in lexical \
2297 scope) module wasn't actually a \
2299 return Failed(None);
2301 Some(ref module_def) => {
2302 return Success(module_def.clone());
2307 debug!("!!! (resolving module in lexical scope) module
2308 wasn't actually a module!");
2309 return Failed(None);
2314 debug!("(resolving module in lexical scope) indeterminate; \
2316 return Indeterminate;
2319 debug!("(resolving module in lexical scope) failed to resolve");
2325 /// Returns the nearest normal module parent of the given module.
2326 fn get_nearest_normal_module_parent(&mut self, module_: Rc<Module>)
2327 -> Option<Rc<Module>> {
2328 let mut module_ = module_;
2330 match module_.parent_link.clone() {
2331 NoParentLink => return None,
2332 ModuleParentLink(new_module, _) |
2333 BlockParentLink(new_module, _) => {
2334 let new_module = new_module.upgrade().unwrap();
2335 match new_module.kind.get() {
2336 NormalModuleKind => return Some(new_module),
2340 AnonymousModuleKind => module_ = new_module,
2347 /// Returns the nearest normal module parent of the given module, or the
2348 /// module itself if it is a normal module.
2349 fn get_nearest_normal_module_parent_or_self(&mut self, module_: Rc<Module>)
2351 match module_.kind.get() {
2352 NormalModuleKind => return module_,
2356 AnonymousModuleKind => {
2357 match self.get_nearest_normal_module_parent(module_.clone()) {
2359 Some(new_module) => new_module
2365 /// Resolves a "module prefix". A module prefix is one or both of (a) `self::`;
2366 /// (b) some chain of `super::`.
2367 /// grammar: (SELF MOD_SEP ) ? (SUPER MOD_SEP) *
2368 fn resolve_module_prefix(&mut self,
2369 module_: Rc<Module>,
2370 module_path: &[Name])
2371 -> ResolveResult<ModulePrefixResult> {
2372 // Start at the current module if we see `self` or `super`, or at the
2373 // top of the crate otherwise.
2374 let mut containing_module;
2376 let first_module_path_string = token::get_name(module_path[0]);
2377 if "self" == first_module_path_string.get() {
2379 self.get_nearest_normal_module_parent_or_self(module_);
2381 } else if "super" == first_module_path_string.get() {
2383 self.get_nearest_normal_module_parent_or_self(module_);
2384 i = 0; // We'll handle `super` below.
2386 return Success(NoPrefixFound);
2389 // Now loop through all the `super`s we find.
2390 while i < module_path.len() {
2391 let string = token::get_name(module_path[i]);
2392 if "super" != string.get() {
2395 debug!("(resolving module prefix) resolving `super` at {}",
2396 self.module_to_string(&*containing_module));
2397 match self.get_nearest_normal_module_parent(containing_module) {
2398 None => return Failed(None),
2399 Some(new_module) => {
2400 containing_module = new_module;
2406 debug!("(resolving module prefix) finished resolving prefix at {}",
2407 self.module_to_string(&*containing_module));
2409 return Success(PrefixFound(containing_module, i));
2412 /// Attempts to resolve the supplied name in the given module for the
2413 /// given namespace. If successful, returns the target corresponding to
2416 /// The boolean returned on success is an indicator of whether this lookup
2417 /// passed through a public re-export proxy.
2418 fn resolve_name_in_module(&mut self,
2419 module_: Rc<Module>,
2421 namespace: Namespace,
2422 name_search_type: NameSearchType,
2423 allow_private_imports: bool)
2424 -> ResolveResult<(Target, bool)> {
2425 debug!("(resolving name in module) resolving `{}` in `{}`",
2426 token::get_name(name).get(),
2427 self.module_to_string(&*module_));
2429 // First, check the direct children of the module.
2430 build_reduced_graph::populate_module_if_necessary(self, &module_);
2432 match module_.children.borrow().get(&name) {
2434 if name_bindings.defined_in_namespace(namespace) => {
2435 debug!("(resolving name in module) found node as child");
2436 return Success((Target::new(module_.clone(),
2437 name_bindings.clone(),
2446 // Next, check the module's imports if necessary.
2448 // If this is a search of all imports, we should be done with glob
2449 // resolution at this point.
2450 if name_search_type == PathSearch {
2451 assert_eq!(module_.glob_count.get(), 0);
2454 // Check the list of resolved imports.
2455 match module_.import_resolutions.borrow().get(&name) {
2456 Some(import_resolution) if allow_private_imports ||
2457 import_resolution.is_public => {
2459 if import_resolution.is_public &&
2460 import_resolution.outstanding_references != 0 {
2461 debug!("(resolving name in module) import \
2462 unresolved; bailing out");
2463 return Indeterminate;
2465 match import_resolution.target_for_namespace(namespace) {
2467 debug!("(resolving name in module) name found, \
2468 but not in namespace {:?}",
2472 debug!("(resolving name in module) resolved to \
2474 // track used imports and extern crates as well
2475 let id = import_resolution.id(namespace);
2476 self.used_imports.insert((id, namespace));
2477 self.record_import_use(id, name);
2478 if let Some(DefId{krate: kid, ..}) = target.target_module.def_id.get() {
2479 self.used_crates.insert(kid);
2481 return Success((target, true));
2485 Some(..) | None => {} // Continue.
2488 // Finally, search through external children.
2489 if namespace == TypeNS {
2490 if let Some(module) = module_.external_module_children.borrow().get(&name).cloned() {
2492 Rc::new(Resolver::create_name_bindings_from_module(module));
2493 return Success((Target::new(module_,
2500 // We're out of luck.
2501 debug!("(resolving name in module) failed to resolve `{}`",
2502 token::get_name(name).get());
2503 return Failed(None);
2506 fn report_unresolved_imports(&mut self, module_: Rc<Module>) {
2507 let index = module_.resolved_import_count.get();
2508 let imports = module_.imports.borrow();
2509 let import_count = imports.len();
2510 if index != import_count {
2511 let sn = self.session
2513 .span_to_snippet((*imports)[index].span)
2515 if sn.contains("::") {
2516 self.resolve_error((*imports)[index].span,
2517 "unresolved import");
2519 let err = format!("unresolved import (maybe you meant `{}::*`?)",
2521 self.resolve_error((*imports)[index].span, &err[]);
2525 // Descend into children and anonymous children.
2526 build_reduced_graph::populate_module_if_necessary(self, &module_);
2528 for (_, child_node) in module_.children.borrow().iter() {
2529 match child_node.get_module_if_available() {
2533 Some(child_module) => {
2534 self.report_unresolved_imports(child_module);
2539 for (_, module_) in module_.anonymous_children.borrow().iter() {
2540 self.report_unresolved_imports(module_.clone());
2546 // We maintain a list of value ribs and type ribs.
2548 // Simultaneously, we keep track of the current position in the module
2549 // graph in the `current_module` pointer. When we go to resolve a name in
2550 // the value or type namespaces, we first look through all the ribs and
2551 // then query the module graph. When we resolve a name in the module
2552 // namespace, we can skip all the ribs (since nested modules are not
2553 // allowed within blocks in Rust) and jump straight to the current module
2556 // Named implementations are handled separately. When we find a method
2557 // call, we consult the module node to find all of the implementations in
2558 // scope. This information is lazily cached in the module node. We then
2559 // generate a fake "implementation scope" containing all the
2560 // implementations thus found, for compatibility with old resolve pass.
2562 fn with_scope<F>(&mut self, name: Option<Name>, f: F) where
2563 F: FnOnce(&mut Resolver),
2565 let orig_module = self.current_module.clone();
2567 // Move down in the graph.
2573 build_reduced_graph::populate_module_if_necessary(self, &orig_module);
2575 match orig_module.children.borrow().get(&name) {
2577 debug!("!!! (with scope) didn't find `{}` in `{}`",
2578 token::get_name(name),
2579 self.module_to_string(&*orig_module));
2581 Some(name_bindings) => {
2582 match (*name_bindings).get_module_if_available() {
2584 debug!("!!! (with scope) didn't find module \
2586 token::get_name(name),
2587 self.module_to_string(&*orig_module));
2590 self.current_module = module_;
2600 self.current_module = orig_module;
2603 /// Wraps the given definition in the appropriate number of `DefUpvar`
2609 -> Option<DefLike> {
2611 DlDef(d @ DefUpvar(..)) => {
2612 self.session.span_bug(span,
2613 &format!("unexpected {:?} in bindings", d)[])
2615 DlDef(d @ DefLocal(_)) => {
2616 let node_id = d.def_id().node;
2618 let mut last_proc_body_id = ast::DUMMY_NODE_ID;
2619 for rib in ribs.iter() {
2622 // Nothing to do. Continue.
2624 ClosureRibKind(function_id, maybe_proc_body) => {
2626 if maybe_proc_body != ast::DUMMY_NODE_ID {
2627 last_proc_body_id = maybe_proc_body;
2629 def = DefUpvar(node_id, function_id, last_proc_body_id);
2631 let mut seen = self.freevars_seen.borrow_mut();
2632 let seen = match seen.entry(function_id) {
2633 Occupied(v) => v.into_mut(),
2634 Vacant(v) => v.insert(NodeSet::new()),
2636 if seen.contains(&node_id) {
2639 match self.freevars.borrow_mut().entry(function_id) {
2640 Occupied(v) => v.into_mut(),
2641 Vacant(v) => v.insert(vec![]),
2642 }.push(Freevar { def: prev_def, span: span });
2643 seen.insert(node_id);
2645 MethodRibKind(item_id, _) => {
2646 // If the def is a ty param, and came from the parent
2649 DefTyParam(_, _, did, _) if {
2650 self.def_map.borrow().get(&did.node).cloned()
2651 == Some(DefTyParamBinder(item_id))
2653 DefSelfTy(did) if did == item_id => {} // ok
2655 // This was an attempt to access an upvar inside a
2656 // named function item. This is not allowed, so we
2661 "can't capture dynamic environment in a fn item; \
2662 use the || { ... } closure form instead");
2669 // This was an attempt to access an upvar inside a
2670 // named function item. This is not allowed, so we
2675 "can't capture dynamic environment in a fn item; \
2676 use the || { ... } closure form instead");
2680 ConstantItemRibKind => {
2681 // Still doesn't deal with upvars
2682 self.resolve_error(span,
2683 "attempt to use a non-constant \
2684 value in a constant");
2691 DlDef(def @ DefTyParam(..)) |
2692 DlDef(def @ DefSelfTy(..)) => {
2693 for rib in ribs.iter() {
2695 NormalRibKind | ClosureRibKind(..) => {
2696 // Nothing to do. Continue.
2698 MethodRibKind(item_id, _) => {
2699 // If the def is a ty param, and came from the parent
2702 DefTyParam(_, _, did, _) if {
2703 self.def_map.borrow().get(&did.node).cloned()
2704 == Some(DefTyParamBinder(item_id))
2706 DefSelfTy(did) if did == item_id => {} // ok
2709 // This was an attempt to use a type parameter outside
2712 self.resolve_error(span,
2713 "can't use type parameters from \
2714 outer function; try using a local \
2715 type parameter instead");
2722 // This was an attempt to use a type parameter outside
2725 self.resolve_error(span,
2726 "can't use type parameters from \
2727 outer function; try using a local \
2728 type parameter instead");
2732 ConstantItemRibKind => {
2734 self.resolve_error(span,
2735 "cannot use an outer type \
2736 parameter in this context");
2747 /// Searches the current set of local scopes and
2748 /// applies translations for closures.
2749 fn search_ribs(&self,
2753 -> Option<DefLike> {
2754 // FIXME #4950: Try caching?
2756 for (i, rib) in ribs.iter().enumerate().rev() {
2757 match rib.bindings.get(&name).cloned() {
2759 return self.upvarify(&ribs[(i + 1)..], def_like, span);
2770 /// Searches the current set of local scopes for labels.
2771 /// Stops after meeting a closure.
2772 fn search_label(&self, name: Name) -> Option<DefLike> {
2773 for rib in self.label_ribs.iter().rev() {
2779 // Do not resolve labels across function boundary
2783 let result = rib.bindings.get(&name).cloned();
2784 if result.is_some() {
2791 fn resolve_crate(&mut self, krate: &ast::Crate) {
2792 debug!("(resolving crate) starting");
2794 visit::walk_crate(self, krate);
2797 fn resolve_item(&mut self, item: &Item) {
2798 let name = item.ident.name;
2800 debug!("(resolving item) resolving {}",
2801 token::get_name(name));
2805 // enum item: resolve all the variants' discrs,
2806 // then resolve the ty params
2807 ItemEnum(ref enum_def, ref generics) => {
2808 for variant in (*enum_def).variants.iter() {
2809 for dis_expr in variant.node.disr_expr.iter() {
2810 // resolve the discriminator expr
2812 self.with_constant_rib(|this| {
2813 this.resolve_expr(&**dis_expr);
2818 // n.b. the discr expr gets visited twice.
2819 // but maybe it's okay since the first time will signal an
2820 // error if there is one? -- tjc
2821 self.with_type_parameter_rib(HasTypeParameters(generics,
2826 this.resolve_type_parameters(&generics.ty_params);
2827 this.resolve_where_clause(&generics.where_clause);
2828 visit::walk_item(this, item);
2832 ItemTy(_, ref generics) => {
2833 self.with_type_parameter_rib(HasTypeParameters(generics,
2838 this.resolve_type_parameters(&generics.ty_params);
2839 visit::walk_item(this, item);
2845 ref implemented_traits,
2847 ref impl_items) => {
2848 self.resolve_implementation(item.id,
2855 ItemTrait(_, ref generics, ref bounds, ref trait_items) => {
2856 // Create a new rib for the self type.
2857 let mut self_type_rib = Rib::new(ItemRibKind);
2859 // plain insert (no renaming, types are not currently hygienic....)
2860 let name = self.type_self_name;
2861 self_type_rib.bindings.insert(name, DlDef(DefSelfTy(item.id)));
2862 self.type_ribs.push(self_type_rib);
2864 // Create a new rib for the trait-wide type parameters.
2865 self.with_type_parameter_rib(HasTypeParameters(generics,
2870 this.resolve_type_parameters(&generics.ty_params);
2871 this.resolve_where_clause(&generics.where_clause);
2873 this.resolve_type_parameter_bounds(item.id, bounds,
2876 for trait_item in (*trait_items).iter() {
2877 // Create a new rib for the trait_item-specific type
2880 // FIXME #4951: Do we need a node ID here?
2883 ast::RequiredMethod(ref ty_m) => {
2884 this.with_type_parameter_rib
2885 (HasTypeParameters(&ty_m.generics,
2888 MethodRibKind(item.id, RequiredMethod)),
2891 // Resolve the method-specific type
2893 this.resolve_type_parameters(
2894 &ty_m.generics.ty_params);
2895 this.resolve_where_clause(&ty_m.generics
2898 for argument in ty_m.decl.inputs.iter() {
2899 this.resolve_type(&*argument.ty);
2902 if let SelfExplicit(ref typ, _) = ty_m.explicit_self.node {
2903 this.resolve_type(&**typ)
2906 if let ast::Return(ref ret_ty) = ty_m.decl.output {
2907 this.resolve_type(&**ret_ty);
2911 ast::ProvidedMethod(ref m) => {
2912 this.resolve_method(MethodRibKind(item.id,
2913 ProvidedMethod(m.id)),
2916 ast::TypeTraitItem(ref data) => {
2917 this.resolve_type_parameter(&data.ty_param);
2918 visit::walk_trait_item(this, trait_item);
2924 self.type_ribs.pop();
2927 ItemStruct(ref struct_def, ref generics) => {
2928 self.resolve_struct(item.id,
2930 &struct_def.fields[]);
2933 ItemMod(ref module_) => {
2934 self.with_scope(Some(name), |this| {
2935 this.resolve_module(module_, item.span, name,
2940 ItemForeignMod(ref foreign_module) => {
2941 self.with_scope(Some(name), |this| {
2942 for foreign_item in foreign_module.items.iter() {
2943 match foreign_item.node {
2944 ForeignItemFn(_, ref generics) => {
2945 this.with_type_parameter_rib(
2947 generics, FnSpace, foreign_item.id,
2950 this.resolve_type_parameters(&generics.ty_params);
2951 this.resolve_where_clause(&generics.where_clause);
2952 visit::walk_foreign_item(this, &**foreign_item)
2955 ForeignItemStatic(..) => {
2956 visit::walk_foreign_item(this,
2964 ItemFn(ref fn_decl, _, _, ref generics, ref block) => {
2965 self.resolve_function(ItemRibKind,
2975 ItemConst(..) | ItemStatic(..) => {
2976 self.with_constant_rib(|this| {
2977 visit::walk_item(this, item);
2982 // do nothing, these are just around to be encoded
2987 fn with_type_parameter_rib<F>(&mut self, type_parameters: TypeParameters, f: F) where
2988 F: FnOnce(&mut Resolver),
2990 match type_parameters {
2991 HasTypeParameters(generics, space, node_id, rib_kind) => {
2992 let mut function_type_rib = Rib::new(rib_kind);
2993 let mut seen_bindings = HashSet::new();
2994 for (index, type_parameter) in generics.ty_params.iter().enumerate() {
2995 let name = type_parameter.ident.name;
2996 debug!("with_type_parameter_rib: {} {}", node_id,
2999 if seen_bindings.contains(&name) {
3000 self.resolve_error(type_parameter.span,
3001 &format!("the name `{}` is already \
3003 parameter in this type \
3008 seen_bindings.insert(name);
3010 let def_like = DlDef(DefTyParam(space,
3012 local_def(type_parameter.id),
3014 // Associate this type parameter with
3015 // the item that bound it
3016 self.record_def(type_parameter.id,
3017 (DefTyParamBinder(node_id), LastMod(AllPublic)));
3018 // plain insert (no renaming)
3019 function_type_rib.bindings.insert(name, def_like);
3021 self.type_ribs.push(function_type_rib);
3024 NoTypeParameters => {
3031 match type_parameters {
3032 HasTypeParameters(..) => { self.type_ribs.pop(); }
3033 NoTypeParameters => { }
3037 fn with_label_rib<F>(&mut self, f: F) where
3038 F: FnOnce(&mut Resolver),
3040 self.label_ribs.push(Rib::new(NormalRibKind));
3042 self.label_ribs.pop();
3045 fn with_constant_rib<F>(&mut self, f: F) where
3046 F: FnOnce(&mut Resolver),
3048 self.value_ribs.push(Rib::new(ConstantItemRibKind));
3049 self.type_ribs.push(Rib::new(ConstantItemRibKind));
3051 self.type_ribs.pop();
3052 self.value_ribs.pop();
3055 fn resolve_function(&mut self,
3057 optional_declaration: Option<&FnDecl>,
3058 type_parameters: TypeParameters,
3060 // Create a value rib for the function.
3061 let function_value_rib = Rib::new(rib_kind);
3062 self.value_ribs.push(function_value_rib);
3064 // Create a label rib for the function.
3065 let function_label_rib = Rib::new(rib_kind);
3066 self.label_ribs.push(function_label_rib);
3068 // If this function has type parameters, add them now.
3069 self.with_type_parameter_rib(type_parameters, |this| {
3070 // Resolve the type parameters.
3071 match type_parameters {
3072 NoTypeParameters => {
3075 HasTypeParameters(ref generics, _, _, _) => {
3076 this.resolve_type_parameters(&generics.ty_params);
3077 this.resolve_where_clause(&generics.where_clause);
3081 // Add each argument to the rib.
3082 match optional_declaration {
3086 Some(declaration) => {
3087 let mut bindings_list = HashMap::new();
3088 for argument in declaration.inputs.iter() {
3089 this.resolve_pattern(&*argument.pat,
3090 ArgumentIrrefutableMode,
3091 &mut bindings_list);
3093 this.resolve_type(&*argument.ty);
3095 debug!("(resolving function) recorded argument");
3098 if let ast::Return(ref ret_ty) = declaration.output {
3099 this.resolve_type(&**ret_ty);
3104 // Resolve the function body.
3105 this.resolve_block(&*block);
3107 debug!("(resolving function) leaving function");
3110 self.label_ribs.pop();
3111 self.value_ribs.pop();
3114 fn resolve_type_parameters(&mut self,
3115 type_parameters: &OwnedSlice<TyParam>) {
3116 for type_parameter in type_parameters.iter() {
3117 self.resolve_type_parameter(type_parameter);
3121 fn resolve_type_parameter(&mut self,
3122 type_parameter: &TyParam) {
3123 for bound in type_parameter.bounds.iter() {
3124 self.resolve_type_parameter_bound(type_parameter.id, bound,
3125 TraitBoundingTypeParameter);
3127 match type_parameter.default {
3128 Some(ref ty) => self.resolve_type(&**ty),
3133 fn resolve_type_parameter_bounds(&mut self,
3135 type_parameter_bounds: &OwnedSlice<TyParamBound>,
3136 reference_type: TraitReferenceType) {
3137 for type_parameter_bound in type_parameter_bounds.iter() {
3138 self.resolve_type_parameter_bound(id, type_parameter_bound,
3143 fn resolve_type_parameter_bound(&mut self,
3145 type_parameter_bound: &TyParamBound,
3146 reference_type: TraitReferenceType) {
3147 match *type_parameter_bound {
3148 TraitTyParamBound(ref tref, _) => {
3149 self.resolve_poly_trait_reference(id, tref, reference_type)
3151 RegionTyParamBound(..) => {}
3155 fn resolve_poly_trait_reference(&mut self,
3157 poly_trait_reference: &PolyTraitRef,
3158 reference_type: TraitReferenceType) {
3159 self.resolve_trait_reference(id, &poly_trait_reference.trait_ref, reference_type)
3162 fn resolve_trait_reference(&mut self,
3164 trait_reference: &TraitRef,
3165 reference_type: TraitReferenceType) {
3166 match self.resolve_path(id, &trait_reference.path, TypeNS, true) {
3168 let path_str = self.path_names_to_string(&trait_reference.path);
3169 let usage_str = match reference_type {
3170 TraitBoundingTypeParameter => "bound type parameter with",
3171 TraitImplementation => "implement",
3172 TraitDerivation => "derive",
3173 TraitObject => "reference",
3174 TraitQPath => "extract an associated item from",
3177 let msg = format!("attempt to {} a nonexistent trait `{}`", usage_str, path_str);
3178 self.resolve_error(trait_reference.path.span, &msg[]);
3182 (DefTrait(_), _) => {
3183 debug!("(resolving trait) found trait def: {:?}", def);
3184 self.record_def(trait_reference.ref_id, def);
3187 self.resolve_error(trait_reference.path.span,
3188 &format!("`{}` is not a trait",
3189 self.path_names_to_string(
3190 &trait_reference.path))[]);
3192 // If it's a typedef, give a note
3193 if let DefTy(..) = def {
3194 self.session.span_note(
3195 trait_reference.path.span,
3196 &format!("`type` aliases cannot be used for traits")
3205 fn resolve_where_clause(&mut self, where_clause: &ast::WhereClause) {
3206 for predicate in where_clause.predicates.iter() {
3208 &ast::WherePredicate::BoundPredicate(ref bound_pred) => {
3209 self.resolve_type(&*bound_pred.bounded_ty);
3211 for bound in bound_pred.bounds.iter() {
3212 self.resolve_type_parameter_bound(bound_pred.bounded_ty.id, bound,
3213 TraitBoundingTypeParameter);
3216 &ast::WherePredicate::RegionPredicate(_) => {}
3217 &ast::WherePredicate::EqPredicate(ref eq_pred) => {
3218 match self.resolve_path(eq_pred.id, &eq_pred.path, TypeNS, true) {
3219 Some((def @ DefTyParam(..), last_private)) => {
3220 self.record_def(eq_pred.id, (def, last_private));
3223 self.resolve_error(eq_pred.path.span,
3224 "undeclared associated type");
3228 self.resolve_type(&*eq_pred.ty);
3234 fn resolve_struct(&mut self,
3236 generics: &Generics,
3237 fields: &[StructField]) {
3238 // If applicable, create a rib for the type parameters.
3239 self.with_type_parameter_rib(HasTypeParameters(generics,
3244 // Resolve the type parameters.
3245 this.resolve_type_parameters(&generics.ty_params);
3246 this.resolve_where_clause(&generics.where_clause);
3249 for field in fields.iter() {
3250 this.resolve_type(&*field.node.ty);
3255 // Does this really need to take a RibKind or is it always going
3256 // to be NormalRibKind?
3257 fn resolve_method(&mut self,
3259 method: &ast::Method) {
3260 let method_generics = method.pe_generics();
3261 let type_parameters = HasTypeParameters(method_generics,
3266 if let SelfExplicit(ref typ, _) = method.pe_explicit_self().node {
3267 self.resolve_type(&**typ);
3270 self.resolve_function(rib_kind,
3271 Some(method.pe_fn_decl()),
3276 fn with_current_self_type<T, F>(&mut self, self_type: &Ty, f: F) -> T where
3277 F: FnOnce(&mut Resolver) -> T,
3279 // Handle nested impls (inside fn bodies)
3280 let previous_value = replace(&mut self.current_self_type, Some(self_type.clone()));
3281 let result = f(self);
3282 self.current_self_type = previous_value;
3286 fn with_optional_trait_ref<T, F>(&mut self, id: NodeId,
3287 opt_trait_ref: &Option<TraitRef>,
3289 F: FnOnce(&mut Resolver) -> T,
3291 let new_val = match *opt_trait_ref {
3292 Some(ref trait_ref) => {
3293 self.resolve_trait_reference(id, trait_ref, TraitImplementation);
3295 match self.def_map.borrow().get(&trait_ref.ref_id) {
3297 let did = def.def_id();
3298 Some((did, trait_ref.clone()))
3305 let original_trait_ref = replace(&mut self.current_trait_ref, new_val);
3306 let result = f(self);
3307 self.current_trait_ref = original_trait_ref;
3311 fn resolve_implementation(&mut self,
3313 generics: &Generics,
3314 opt_trait_reference: &Option<TraitRef>,
3316 impl_items: &[ImplItem]) {
3317 // If applicable, create a rib for the type parameters.
3318 self.with_type_parameter_rib(HasTypeParameters(generics,
3323 // Resolve the type parameters.
3324 this.resolve_type_parameters(&generics.ty_params);
3325 this.resolve_where_clause(&generics.where_clause);
3327 // Resolve the trait reference, if necessary.
3328 this.with_optional_trait_ref(id, opt_trait_reference, |this| {
3329 // Resolve the self type.
3330 this.resolve_type(self_type);
3332 this.with_current_self_type(self_type, |this| {
3333 for impl_item in impl_items.iter() {
3335 MethodImplItem(ref method) => {
3336 // If this is a trait impl, ensure the method
3338 this.check_trait_item(method.pe_ident().name,
3341 // We also need a new scope for the method-
3342 // specific type parameters.
3343 this.resolve_method(
3344 MethodRibKind(id, ProvidedMethod(method.id)),
3347 TypeImplItem(ref typedef) => {
3348 // If this is a trait impl, ensure the method
3350 this.check_trait_item(typedef.ident.name,
3353 this.resolve_type(&*typedef.typ);
3361 // Check that the current type is indeed a type, if we have an anonymous impl
3362 if opt_trait_reference.is_none() {
3363 match self_type.node {
3364 // TyPath is the only thing that we handled in `build_reduced_graph_for_item`,
3365 // where we created a module with the name of the type in order to implement
3366 // an anonymous trait. In the case that the path does not resolve to an actual
3367 // type, the result will be that the type name resolves to a module but not
3368 // a type (shadowing any imported modules or types with this name), leading
3369 // to weird user-visible bugs. So we ward this off here. See #15060.
3370 TyPath(ref path, path_id) => {
3371 match self.def_map.borrow().get(&path_id) {
3372 // FIXME: should we catch other options and give more precise errors?
3373 Some(&DefMod(_)) => {
3374 self.resolve_error(path.span, "inherent implementations are not \
3375 allowed for types not defined in \
3376 the current module");
3386 fn check_trait_item(&self, name: Name, span: Span) {
3387 // If there is a TraitRef in scope for an impl, then the method must be in the trait.
3388 for &(did, ref trait_ref) in self.current_trait_ref.iter() {
3389 if self.trait_item_map.get(&(name, did)).is_none() {
3390 let path_str = self.path_names_to_string(&trait_ref.path);
3391 self.resolve_error(span,
3392 &format!("method `{}` is not a member of trait `{}`",
3393 token::get_name(name),
3399 fn resolve_module(&mut self, module: &Mod, _span: Span,
3400 _name: Name, id: NodeId) {
3401 // Write the implementations in scope into the module metadata.
3402 debug!("(resolving module) resolving module ID {}", id);
3403 visit::walk_mod(self, module);
3406 fn resolve_local(&mut self, local: &Local) {
3407 // Resolve the type.
3408 if let Some(ref ty) = local.ty {
3409 self.resolve_type(&**ty);
3412 // Resolve the initializer, if necessary.
3417 Some(ref initializer) => {
3418 self.resolve_expr(&**initializer);
3422 // Resolve the pattern.
3423 let mut bindings_list = HashMap::new();
3424 self.resolve_pattern(&*local.pat,
3425 LocalIrrefutableMode,
3426 &mut bindings_list);
3429 // build a map from pattern identifiers to binding-info's.
3430 // this is done hygienically. This could arise for a macro
3431 // that expands into an or-pattern where one 'x' was from the
3432 // user and one 'x' came from the macro.
3433 fn binding_mode_map(&mut self, pat: &Pat) -> BindingMap {
3434 let mut result = HashMap::new();
3435 pat_bindings(&self.def_map, pat, |binding_mode, _id, sp, path1| {
3436 let name = mtwt::resolve(path1.node);
3437 result.insert(name, BindingInfo {
3439 binding_mode: binding_mode
3445 // check that all of the arms in an or-pattern have exactly the
3446 // same set of bindings, with the same binding modes for each.
3447 fn check_consistent_bindings(&mut self, arm: &Arm) {
3448 if arm.pats.len() == 0 {
3451 let map_0 = self.binding_mode_map(&*arm.pats[0]);
3452 for (i, p) in arm.pats.iter().enumerate() {
3453 let map_i = self.binding_mode_map(&**p);
3455 for (&key, &binding_0) in map_0.iter() {
3456 match map_i.get(&key) {
3460 &format!("variable `{}` from pattern #1 is \
3461 not bound in pattern #{}",
3462 token::get_name(key),
3465 Some(binding_i) => {
3466 if binding_0.binding_mode != binding_i.binding_mode {
3469 &format!("variable `{}` is bound with different \
3470 mode in pattern #{} than in pattern #1",
3471 token::get_name(key),
3478 for (&key, &binding) in map_i.iter() {
3479 if !map_0.contains_key(&key) {
3482 &format!("variable `{}` from pattern {}{} is \
3483 not bound in pattern {}1",
3484 token::get_name(key),
3485 "#", i + 1, "#")[]);
3491 fn resolve_arm(&mut self, arm: &Arm) {
3492 self.value_ribs.push(Rib::new(NormalRibKind));
3494 let mut bindings_list = HashMap::new();
3495 for pattern in arm.pats.iter() {
3496 self.resolve_pattern(&**pattern, RefutableMode, &mut bindings_list);
3499 // This has to happen *after* we determine which
3500 // pat_idents are variants
3501 self.check_consistent_bindings(arm);
3503 visit::walk_expr_opt(self, &arm.guard);
3504 self.resolve_expr(&*arm.body);
3506 self.value_ribs.pop();
3509 fn resolve_block(&mut self, block: &Block) {
3510 debug!("(resolving block) entering block");
3511 self.value_ribs.push(Rib::new(NormalRibKind));
3513 // Move down in the graph, if there's an anonymous module rooted here.
3514 let orig_module = self.current_module.clone();
3515 match orig_module.anonymous_children.borrow().get(&block.id) {
3516 None => { /* Nothing to do. */ }
3517 Some(anonymous_module) => {
3518 debug!("(resolving block) found anonymous module, moving \
3520 self.current_module = anonymous_module.clone();
3524 // Descend into the block.
3525 visit::walk_block(self, block);
3528 self.current_module = orig_module;
3530 self.value_ribs.pop();
3531 debug!("(resolving block) leaving block");
3534 fn resolve_type(&mut self, ty: &Ty) {
3536 // Like path expressions, the interpretation of path types depends
3537 // on whether the path has multiple elements in it or not.
3539 TyPath(ref path, path_id) => {
3540 // This is a path in the type namespace. Walk through scopes
3542 let mut result_def = None;
3544 // First, check to see whether the name is a primitive type.
3545 if path.segments.len() == 1 {
3546 let id = path.segments.last().unwrap().identifier;
3548 match self.primitive_type_table
3552 Some(&primitive_type) => {
3554 Some((DefPrimTy(primitive_type), LastMod(AllPublic)));
3556 if path.segments[0].parameters.has_lifetimes() {
3557 span_err!(self.session, path.span, E0157,
3558 "lifetime parameters are not allowed on this type");
3559 } else if !path.segments[0].parameters.is_empty() {
3560 span_err!(self.session, path.span, E0153,
3561 "type parameters are not allowed on this type");
3570 if let None = result_def {
3571 result_def = self.resolve_path(ty.id, path, TypeNS, true);
3576 // Write the result into the def map.
3577 debug!("(resolving type) writing resolution for `{}` \
3579 self.path_names_to_string(path),
3581 self.record_def(path_id, def);
3584 let msg = format!("use of undeclared type name `{}`",
3585 self.path_names_to_string(path));
3586 self.resolve_error(ty.span, &msg[]);
3591 TyObjectSum(ref ty, ref bound_vec) => {
3592 self.resolve_type(&**ty);
3593 self.resolve_type_parameter_bounds(ty.id, bound_vec,
3594 TraitBoundingTypeParameter);
3597 TyQPath(ref qpath) => {
3598 self.resolve_type(&*qpath.self_type);
3599 self.resolve_trait_reference(ty.id, &*qpath.trait_ref, TraitQPath);
3600 for ty in qpath.item_path.parameters.types().into_iter() {
3601 self.resolve_type(&**ty);
3603 for binding in qpath.item_path.parameters.bindings().into_iter() {
3604 self.resolve_type(&*binding.ty);
3608 TyPolyTraitRef(ref bounds) => {
3609 self.resolve_type_parameter_bounds(
3613 visit::walk_ty(self, ty);
3616 // Just resolve embedded types.
3617 visit::walk_ty(self, ty);
3622 fn resolve_pattern(&mut self,
3624 mode: PatternBindingMode,
3625 // Maps idents to the node ID for the (outermost)
3626 // pattern that binds them
3627 bindings_list: &mut HashMap<Name, NodeId>) {
3628 let pat_id = pattern.id;
3629 walk_pat(pattern, |pattern| {
3630 match pattern.node {
3631 PatIdent(binding_mode, ref path1, _) => {
3633 // The meaning of pat_ident with no type parameters
3634 // depends on whether an enum variant or unit-like struct
3635 // with that name is in scope. The probing lookup has to
3636 // be careful not to emit spurious errors. Only matching
3637 // patterns (match) can match nullary variants or
3638 // unit-like structs. For binding patterns (let), matching
3639 // such a value is simply disallowed (since it's rarely
3642 let ident = path1.node;
3643 let renamed = mtwt::resolve(ident);
3645 match self.resolve_bare_identifier_pattern(ident.name, pattern.span) {
3646 FoundStructOrEnumVariant(ref def, lp)
3647 if mode == RefutableMode => {
3648 debug!("(resolving pattern) resolving `{}` to \
3649 struct or enum variant",
3650 token::get_name(renamed));
3652 self.enforce_default_binding_mode(
3656 self.record_def(pattern.id, (def.clone(), lp));
3658 FoundStructOrEnumVariant(..) => {
3661 &format!("declaration of `{}` shadows an enum \
3662 variant or unit-like struct in \
3664 token::get_name(renamed))[]);
3666 FoundConst(ref def, lp) if mode == RefutableMode => {
3667 debug!("(resolving pattern) resolving `{}` to \
3669 token::get_name(renamed));
3671 self.enforce_default_binding_mode(
3675 self.record_def(pattern.id, (def.clone(), lp));
3678 self.resolve_error(pattern.span,
3679 "only irrefutable patterns \
3682 BareIdentifierPatternUnresolved => {
3683 debug!("(resolving pattern) binding `{}`",
3684 token::get_name(renamed));
3686 let def = DefLocal(pattern.id);
3688 // Record the definition so that later passes
3689 // will be able to distinguish variants from
3690 // locals in patterns.
3692 self.record_def(pattern.id, (def, LastMod(AllPublic)));
3694 // Add the binding to the local ribs, if it
3695 // doesn't already exist in the bindings list. (We
3696 // must not add it if it's in the bindings list
3697 // because that breaks the assumptions later
3698 // passes make about or-patterns.)
3699 if !bindings_list.contains_key(&renamed) {
3700 let this = &mut *self;
3701 let last_rib = this.value_ribs.last_mut().unwrap();
3702 last_rib.bindings.insert(renamed, DlDef(def));
3703 bindings_list.insert(renamed, pat_id);
3704 } else if mode == ArgumentIrrefutableMode &&
3705 bindings_list.contains_key(&renamed) {
3706 // Forbid duplicate bindings in the same
3708 self.resolve_error(pattern.span,
3709 &format!("identifier `{}` \
3717 } else if bindings_list.get(&renamed) ==
3719 // Then this is a duplicate variable in the
3720 // same disjunction, which is an error.
3721 self.resolve_error(pattern.span,
3722 &format!("identifier `{}` is bound \
3723 more than once in the same \
3725 token::get_ident(ident))[]);
3727 // Else, not bound in the same pattern: do
3733 PatEnum(ref path, _) => {
3734 // This must be an enum variant, struct or const.
3735 match self.resolve_path(pat_id, path, ValueNS, false) {
3736 Some(def @ (DefVariant(..), _)) |
3737 Some(def @ (DefStruct(..), _)) |
3738 Some(def @ (DefConst(..), _)) => {
3739 self.record_def(pattern.id, def);
3741 Some((DefStatic(..), _)) => {
3742 self.resolve_error(path.span,
3743 "static variables cannot be \
3744 referenced in a pattern, \
3745 use a `const` instead");
3748 self.resolve_error(path.span,
3749 format!("`{}` is not an enum variant, struct or const",
3751 path.segments.last().unwrap().identifier)).as_slice());
3754 self.resolve_error(path.span,
3755 format!("unresolved enum variant, struct or const `{}`",
3757 path.segments.last().unwrap().identifier)).as_slice());
3761 // Check the types in the path pattern.
3762 for ty in path.segments
3764 .flat_map(|s| s.parameters.types().into_iter()) {
3765 self.resolve_type(&**ty);
3769 PatLit(ref expr) => {
3770 self.resolve_expr(&**expr);
3773 PatRange(ref first_expr, ref last_expr) => {
3774 self.resolve_expr(&**first_expr);
3775 self.resolve_expr(&**last_expr);
3778 PatStruct(ref path, _, _) => {
3779 match self.resolve_path(pat_id, path, TypeNS, false) {
3780 Some(definition) => {
3781 self.record_def(pattern.id, definition);
3784 debug!("(resolving pattern) didn't find struct \
3785 def: {:?}", result);
3786 let msg = format!("`{}` does not name a structure",
3787 self.path_names_to_string(path));
3788 self.resolve_error(path.span, &msg[]);
3801 fn resolve_bare_identifier_pattern(&mut self, name: Name, span: Span)
3802 -> BareIdentifierPatternResolution {
3803 let module = self.current_module.clone();
3804 match self.resolve_item_in_lexical_scope(module,
3807 Success((target, _)) => {
3808 debug!("(resolve bare identifier pattern) succeeded in \
3809 finding {} at {:?}",
3810 token::get_name(name),
3811 target.bindings.value_def.borrow());
3812 match *target.bindings.value_def.borrow() {
3814 panic!("resolved name in the value namespace to a \
3815 set of name bindings with no def?!");
3818 // For the two success cases, this lookup can be
3819 // considered as not having a private component because
3820 // the lookup happened only within the current module.
3822 def @ DefVariant(..) | def @ DefStruct(..) => {
3823 return FoundStructOrEnumVariant(def, LastMod(AllPublic));
3825 def @ DefConst(..) => {
3826 return FoundConst(def, LastMod(AllPublic));
3829 self.resolve_error(span,
3830 "static variables cannot be \
3831 referenced in a pattern, \
3832 use a `const` instead");
3833 return BareIdentifierPatternUnresolved;
3836 return BareIdentifierPatternUnresolved;
3844 panic!("unexpected indeterminate result");
3848 Some((span, msg)) => {
3849 self.resolve_error(span, &format!("failed to resolve: {}",
3855 debug!("(resolve bare identifier pattern) failed to find {}",
3856 token::get_name(name));
3857 return BareIdentifierPatternUnresolved;
3862 /// If `check_ribs` is true, checks the local definitions first; i.e.
3863 /// doesn't skip straight to the containing module.
3864 fn resolve_path(&mut self,
3867 namespace: Namespace,
3868 check_ribs: bool) -> Option<(Def, LastPrivate)> {
3869 // First, resolve the types and associated type bindings.
3870 for ty in path.segments.iter().flat_map(|s| s.parameters.types().into_iter()) {
3871 self.resolve_type(&**ty);
3873 for binding in path.segments.iter().flat_map(|s| s.parameters.bindings().into_iter()) {
3874 self.resolve_type(&*binding.ty);
3877 // A special case for sugared associated type paths `T::A` where `T` is
3878 // a type parameter and `A` is an associated type on some bound of `T`.
3879 if namespace == TypeNS && path.segments.len() == 2 {
3880 match self.resolve_identifier(path.segments[0].identifier,
3884 Some((def, last_private)) => {
3886 DefTyParam(_, _, did, _) => {
3887 let def = DefAssociatedPath(TyParamProvenance::FromParam(did),
3888 path.segments.last()
3889 .unwrap().identifier);
3890 return Some((def, last_private));
3893 let def = DefAssociatedPath(TyParamProvenance::FromSelf(local_def(nid)),
3894 path.segments.last()
3895 .unwrap().identifier);
3896 return Some((def, last_private));
3906 return self.resolve_crate_relative_path(path, namespace);
3909 // Try to find a path to an item in a module.
3910 let unqualified_def =
3911 self.resolve_identifier(path.segments.last().unwrap().identifier,
3916 if path.segments.len() > 1 {
3917 let def = self.resolve_module_relative_path(path, namespace);
3918 match (def, unqualified_def) {
3919 (Some((ref d, _)), Some((ref ud, _))) if *d == *ud => {
3921 .add_lint(lint::builtin::UNUSED_QUALIFICATIONS,
3924 "unnecessary qualification".to_string());
3932 return unqualified_def;
3935 // resolve a single identifier (used as a varref)
3936 fn resolve_identifier(&mut self,
3938 namespace: Namespace,
3941 -> Option<(Def, LastPrivate)> {
3943 match self.resolve_identifier_in_local_ribs(identifier,
3947 return Some((def, LastMod(AllPublic)));
3955 return self.resolve_item_by_name_in_lexical_scope(identifier.name, namespace);
3958 // FIXME #4952: Merge me with resolve_name_in_module?
3959 fn resolve_definition_of_name_in_module(&mut self,
3960 containing_module: Rc<Module>,
3962 namespace: Namespace)
3964 // First, search children.
3965 build_reduced_graph::populate_module_if_necessary(self, &containing_module);
3967 match containing_module.children.borrow().get(&name) {
3968 Some(child_name_bindings) => {
3969 match child_name_bindings.def_for_namespace(namespace) {
3971 // Found it. Stop the search here.
3972 let p = child_name_bindings.defined_in_public_namespace(
3974 let lp = if p {LastMod(AllPublic)} else {
3975 LastMod(DependsOn(def.def_id()))
3977 return ChildNameDefinition(def, lp);
3985 // Next, search import resolutions.
3986 match containing_module.import_resolutions.borrow().get(&name) {
3987 Some(import_resolution) if import_resolution.is_public => {
3988 if let Some(target) = (*import_resolution).target_for_namespace(namespace) {
3989 match target.bindings.def_for_namespace(namespace) {
3992 let id = import_resolution.id(namespace);
3993 // track imports and extern crates as well
3994 self.used_imports.insert((id, namespace));
3995 self.record_import_use(id, name);
3996 match target.target_module.def_id.get() {
3997 Some(DefId{krate: kid, ..}) => {
3998 self.used_crates.insert(kid);
4002 return ImportNameDefinition(def, LastMod(AllPublic));
4005 // This can happen with external impls, due to
4006 // the imperfect way we read the metadata.
4011 Some(..) | None => {} // Continue.
4014 // Finally, search through external children.
4015 if namespace == TypeNS {
4016 if let Some(module) = containing_module.external_module_children.borrow()
4017 .get(&name).cloned() {
4018 if let Some(def_id) = module.def_id.get() {
4019 // track used crates
4020 self.used_crates.insert(def_id.krate);
4021 let lp = if module.is_public {LastMod(AllPublic)} else {
4022 LastMod(DependsOn(def_id))
4024 return ChildNameDefinition(DefMod(def_id), lp);
4029 return NoNameDefinition;
4032 // resolve a "module-relative" path, e.g. a::b::c
4033 fn resolve_module_relative_path(&mut self,
4035 namespace: Namespace)
4036 -> Option<(Def, LastPrivate)> {
4037 let module_path = path.segments.init().iter()
4038 .map(|ps| ps.identifier.name)
4039 .collect::<Vec<_>>();
4041 let containing_module;
4043 let module = self.current_module.clone();
4044 match self.resolve_module_path(module,
4050 let (span, msg) = match err {
4051 Some((span, msg)) => (span, msg),
4053 let msg = format!("Use of undeclared type or module `{}`",
4054 self.names_to_string(module_path.as_slice()));
4059 self.resolve_error(span, &format!("failed to resolve. {}",
4063 Indeterminate => panic!("indeterminate unexpected"),
4064 Success((resulting_module, resulting_last_private)) => {
4065 containing_module = resulting_module;
4066 last_private = resulting_last_private;
4070 let name = path.segments.last().unwrap().identifier.name;
4071 let def = match self.resolve_definition_of_name_in_module(containing_module.clone(),
4074 NoNameDefinition => {
4075 // We failed to resolve the name. Report an error.
4078 ChildNameDefinition(def, lp) | ImportNameDefinition(def, lp) => {
4079 (def, last_private.or(lp))
4082 if let Some(DefId{krate: kid, ..}) = containing_module.def_id.get() {
4083 self.used_crates.insert(kid);
4088 /// Invariant: This must be called only during main resolution, not during
4089 /// import resolution.
4090 fn resolve_crate_relative_path(&mut self,
4092 namespace: Namespace)
4093 -> Option<(Def, LastPrivate)> {
4094 let module_path = path.segments.init().iter()
4095 .map(|ps| ps.identifier.name)
4096 .collect::<Vec<_>>();
4098 let root_module = self.graph_root.get_module();
4100 let containing_module;
4102 match self.resolve_module_path_from_root(root_module,
4107 LastMod(AllPublic)) {
4109 let (span, msg) = match err {
4110 Some((span, msg)) => (span, msg),
4112 let msg = format!("Use of undeclared module `::{}`",
4113 self.names_to_string(&module_path[]));
4118 self.resolve_error(span, &format!("failed to resolve. {}",
4124 panic!("indeterminate unexpected");
4127 Success((resulting_module, resulting_last_private)) => {
4128 containing_module = resulting_module;
4129 last_private = resulting_last_private;
4133 let name = path.segments.last().unwrap().identifier.name;
4134 match self.resolve_definition_of_name_in_module(containing_module,
4137 NoNameDefinition => {
4138 // We failed to resolve the name. Report an error.
4141 ChildNameDefinition(def, lp) | ImportNameDefinition(def, lp) => {
4142 return Some((def, last_private.or(lp)));
4147 fn resolve_identifier_in_local_ribs(&mut self,
4149 namespace: Namespace,
4152 // Check the local set of ribs.
4153 let search_result = match namespace {
4155 let renamed = mtwt::resolve(ident);
4156 self.search_ribs(self.value_ribs.as_slice(), renamed, span)
4159 let name = ident.name;
4160 self.search_ribs(&self.type_ribs[], name, span)
4164 match search_result {
4165 Some(DlDef(def)) => {
4166 debug!("(resolving path in local ribs) resolved `{}` to \
4168 token::get_ident(ident),
4172 Some(DlField) | Some(DlImpl(_)) | None => {
4178 fn resolve_item_by_name_in_lexical_scope(&mut self,
4180 namespace: Namespace)
4181 -> Option<(Def, LastPrivate)> {
4183 let module = self.current_module.clone();
4184 match self.resolve_item_in_lexical_scope(module,
4187 Success((target, _)) => {
4188 match (*target.bindings).def_for_namespace(namespace) {
4190 // This can happen if we were looking for a type and
4191 // found a module instead. Modules don't have defs.
4192 debug!("(resolving item path by identifier in lexical \
4193 scope) failed to resolve {} after success...",
4194 token::get_name(name));
4198 debug!("(resolving item path in lexical scope) \
4199 resolved `{}` to item",
4200 token::get_name(name));
4201 // This lookup is "all public" because it only searched
4202 // for one identifier in the current module (couldn't
4203 // have passed through reexports or anything like that.
4204 return Some((def, LastMod(AllPublic)));
4209 panic!("unexpected indeterminate result");
4213 Some((span, msg)) =>
4214 self.resolve_error(span, &format!("failed to resolve. {}",
4219 debug!("(resolving item path by identifier in lexical scope) \
4220 failed to resolve {}", token::get_name(name));
4226 fn with_no_errors<T, F>(&mut self, f: F) -> T where
4227 F: FnOnce(&mut Resolver) -> T,
4229 self.emit_errors = false;
4231 self.emit_errors = true;
4235 fn resolve_error(&self, span: Span, s: &str) {
4236 if self.emit_errors {
4237 self.session.span_err(span, s);
4241 fn find_fallback_in_self_type(&mut self, name: Name) -> FallbackSuggestion {
4242 fn extract_path_and_node_id(t: &Ty, allow: FallbackChecks)
4243 -> Option<(Path, NodeId, FallbackChecks)> {
4245 TyPath(ref path, node_id) => Some((path.clone(), node_id, allow)),
4246 TyPtr(ref mut_ty) => extract_path_and_node_id(&*mut_ty.ty, OnlyTraitAndStatics),
4247 TyRptr(_, ref mut_ty) => extract_path_and_node_id(&*mut_ty.ty, allow),
4248 // This doesn't handle the remaining `Ty` variants as they are not
4249 // that commonly the self_type, it might be interesting to provide
4250 // support for those in future.
4255 fn get_module(this: &mut Resolver, span: Span, name_path: &[ast::Name])
4256 -> Option<Rc<Module>> {
4257 let root = this.current_module.clone();
4258 let last_name = name_path.last().unwrap();
4260 if name_path.len() == 1 {
4261 match this.primitive_type_table.primitive_types.get(last_name) {
4264 match this.current_module.children.borrow().get(last_name) {
4265 Some(child) => child.get_module_if_available(),
4271 match this.resolve_module_path(root,
4276 Success((module, _)) => Some(module),
4282 let (path, node_id, allowed) = match self.current_self_type {
4283 Some(ref ty) => match extract_path_and_node_id(ty, Everything) {
4285 None => return NoSuggestion,
4287 None => return NoSuggestion,
4290 if allowed == Everything {
4291 // Look for a field with the same name in the current self_type.
4292 match self.def_map.borrow().get(&node_id) {
4293 Some(&DefTy(did, _))
4294 | Some(&DefStruct(did))
4295 | Some(&DefVariant(_, did, _)) => match self.structs.get(&did) {
4298 if fields.iter().any(|&field_name| name == field_name) {
4303 _ => {} // Self type didn't resolve properly
4307 let name_path = path.segments.iter().map(|seg| seg.identifier.name).collect::<Vec<_>>();
4309 // Look for a method in the current self type's impl module.
4310 match get_module(self, path.span, &name_path[]) {
4311 Some(module) => match module.children.borrow().get(&name) {
4313 let p_str = self.path_names_to_string(&path);
4314 match binding.def_for_namespace(ValueNS) {
4315 Some(DefStaticMethod(_, provenance)) => {
4317 FromImpl(_) => return StaticMethod(p_str),
4318 FromTrait(_) => unreachable!()
4321 Some(DefMethod(_, None, _)) if allowed == Everything => return Method,
4322 Some(DefMethod(_, Some(_), _)) => return TraitItem,
4331 // Look for a method in the current trait.
4332 match self.current_trait_ref {
4333 Some((did, ref trait_ref)) => {
4334 let path_str = self.path_names_to_string(&trait_ref.path);
4336 match self.trait_item_map.get(&(name, did)) {
4337 Some(&StaticMethodTraitItemKind) => {
4338 return TraitMethod(path_str)
4340 Some(_) => return TraitItem,
4350 fn find_best_match_for_name(&mut self, name: &str, max_distance: uint)
4352 let this = &mut *self;
4354 let mut maybes: Vec<token::InternedString> = Vec::new();
4355 let mut values: Vec<uint> = Vec::new();
4357 for rib in this.value_ribs.iter().rev() {
4358 for (&k, _) in rib.bindings.iter() {
4359 maybes.push(token::get_name(k));
4360 values.push(uint::MAX);
4364 let mut smallest = 0;
4365 for (i, other) in maybes.iter().enumerate() {
4366 values[i] = lev_distance(name, other.get());
4368 if values[i] <= values[smallest] {
4373 if values.len() > 0 &&
4374 values[smallest] != uint::MAX &&
4375 values[smallest] < name.len() + 2 &&
4376 values[smallest] <= max_distance &&
4377 name != maybes[smallest].get() {
4379 Some(maybes[smallest].get().to_string())
4386 fn resolve_expr(&mut self, expr: &Expr) {
4387 // First, record candidate traits for this expression if it could
4388 // result in the invocation of a method call.
4390 self.record_candidate_traits_for_expr_if_necessary(expr);
4392 // Next, resolve the node.
4394 // The interpretation of paths depends on whether the path has
4395 // multiple elements in it or not.
4397 ExprPath(_) | ExprQPath(_) => {
4398 let mut path_from_qpath;
4399 let path = match expr.node {
4400 ExprPath(ref path) => path,
4401 ExprQPath(ref qpath) => {
4402 self.resolve_type(&*qpath.self_type);
4403 self.resolve_trait_reference(expr.id, &*qpath.trait_ref, TraitQPath);
4404 path_from_qpath = qpath.trait_ref.path.clone();
4405 path_from_qpath.segments.push(qpath.item_path.clone());
4410 // This is a local path in the value namespace. Walk through
4411 // scopes looking for it.
4412 match self.resolve_path(expr.id, path, ValueNS, true) {
4413 // Check if struct variant
4414 Some((DefVariant(_, _, true), _)) => {
4415 let path_name = self.path_names_to_string(path);
4416 self.resolve_error(expr.span,
4417 format!("`{}` is a struct variant name, but \
4419 uses it like a function name",
4420 path_name).as_slice());
4422 self.session.span_help(expr.span,
4423 format!("Did you mean to write: \
4424 `{} {{ /* fields */ }}`?",
4425 path_name).as_slice());
4428 // Write the result into the def map.
4429 debug!("(resolving expr) resolved `{}`",
4430 self.path_names_to_string(path));
4432 self.record_def(expr.id, def);
4435 // Be helpful if the name refers to a struct
4436 // (The pattern matching def_tys where the id is in self.structs
4437 // matches on regular structs while excluding tuple- and enum-like
4438 // structs, which wouldn't result in this error.)
4439 let path_name = self.path_names_to_string(path);
4440 match self.with_no_errors(|this|
4441 this.resolve_path(expr.id, path, TypeNS, false)) {
4442 Some((DefTy(struct_id, _), _))
4443 if self.structs.contains_key(&struct_id) => {
4444 self.resolve_error(expr.span,
4445 format!("`{}` is a structure name, but \
4447 uses it like a function name",
4448 path_name).as_slice());
4450 self.session.span_help(expr.span,
4451 format!("Did you mean to write: \
4452 `{} {{ /* fields */ }}`?",
4453 path_name).as_slice());
4457 let mut method_scope = false;
4458 self.value_ribs.iter().rev().all(|rib| {
4459 let res = match *rib {
4460 Rib { bindings: _, kind: MethodRibKind(_, _) } => true,
4461 Rib { bindings: _, kind: ItemRibKind } => false,
4462 _ => return true, // Keep advancing
4466 false // Stop advancing
4469 if method_scope && token::get_name(self.self_name).get()
4473 "`self` is not available \
4474 in a static method. Maybe a \
4475 `self` argument is missing?");
4477 let last_name = path.segments.last().unwrap().identifier.name;
4478 let mut msg = match self.find_fallback_in_self_type(last_name) {
4480 // limit search to 5 to reduce the number
4481 // of stupid suggestions
4482 self.find_best_match_for_name(path_name.as_slice(), 5)
4483 .map_or("".to_string(),
4484 |x| format!("`{}`", x))
4487 format!("`self.{}`", path_name),
4490 format!("to call `self.{}`", path_name),
4491 TraitMethod(path_str)
4492 | StaticMethod(path_str) =>
4493 format!("to call `{}::{}`", path_str, path_name)
4497 msg = format!(". Did you mean {}?", msg)
4502 format!("unresolved name `{}`{}",
4511 visit::walk_expr(self, expr);
4514 ExprClosure(capture_clause, _, ref fn_decl, ref block) => {
4515 self.capture_mode_map.insert(expr.id, capture_clause);
4516 self.resolve_function(ClosureRibKind(expr.id, ast::DUMMY_NODE_ID),
4517 Some(&**fn_decl), NoTypeParameters,
4521 ExprStruct(ref path, _, _) => {
4522 // Resolve the path to the structure it goes to. We don't
4523 // check to ensure that the path is actually a structure; that
4524 // is checked later during typeck.
4525 match self.resolve_path(expr.id, path, TypeNS, false) {
4526 Some(definition) => self.record_def(expr.id, definition),
4528 debug!("(resolving expression) didn't find struct \
4529 def: {:?}", result);
4530 let msg = format!("`{}` does not name a structure",
4531 self.path_names_to_string(path));
4532 self.resolve_error(path.span, &msg[]);
4536 visit::walk_expr(self, expr);
4539 ExprLoop(_, Some(label)) | ExprWhile(_, _, Some(label)) => {
4540 self.with_label_rib(|this| {
4541 let def_like = DlDef(DefLabel(expr.id));
4544 let rib = this.label_ribs.last_mut().unwrap();
4545 let renamed = mtwt::resolve(label);
4546 rib.bindings.insert(renamed, def_like);
4549 visit::walk_expr(this, expr);
4553 ExprForLoop(ref pattern, ref head, ref body, optional_label) => {
4554 self.resolve_expr(&**head);
4556 self.value_ribs.push(Rib::new(NormalRibKind));
4558 self.resolve_pattern(&**pattern,
4559 LocalIrrefutableMode,
4560 &mut HashMap::new());
4562 match optional_label {
4566 .push(Rib::new(NormalRibKind));
4567 let def_like = DlDef(DefLabel(expr.id));
4570 let rib = self.label_ribs.last_mut().unwrap();
4571 let renamed = mtwt::resolve(label);
4572 rib.bindings.insert(renamed, def_like);
4577 self.resolve_block(&**body);
4579 if optional_label.is_some() {
4580 drop(self.label_ribs.pop())
4583 self.value_ribs.pop();
4586 ExprBreak(Some(label)) | ExprAgain(Some(label)) => {
4587 let renamed = mtwt::resolve(label);
4588 match self.search_label(renamed) {
4592 &format!("use of undeclared label `{}`",
4593 token::get_ident(label))[])
4595 Some(DlDef(def @ DefLabel(_))) => {
4596 // Since this def is a label, it is never read.
4597 self.record_def(expr.id, (def, LastMod(AllPublic)))
4600 self.session.span_bug(expr.span,
4601 "label wasn't mapped to a \
4608 visit::walk_expr(self, expr);
4613 fn record_candidate_traits_for_expr_if_necessary(&mut self, expr: &Expr) {
4615 ExprField(_, ident) => {
4616 // FIXME(#6890): Even though you can't treat a method like a
4617 // field, we need to add any trait methods we find that match
4618 // the field name so that we can do some nice error reporting
4619 // later on in typeck.
4620 let traits = self.search_for_traits_containing_method(ident.node.name);
4621 self.trait_map.insert(expr.id, traits);
4623 ExprMethodCall(ident, _, _) => {
4624 debug!("(recording candidate traits for expr) recording \
4627 let traits = self.search_for_traits_containing_method(ident.node.name);
4628 self.trait_map.insert(expr.id, traits);
4636 fn search_for_traits_containing_method(&mut self, name: Name) -> Vec<DefId> {
4637 debug!("(searching for traits containing method) looking for '{}'",
4638 token::get_name(name));
4640 fn add_trait_info(found_traits: &mut Vec<DefId>,
4641 trait_def_id: DefId,
4643 debug!("(adding trait info) found trait {}:{} for method '{}'",
4646 token::get_name(name));
4647 found_traits.push(trait_def_id);
4650 let mut found_traits = Vec::new();
4651 let mut search_module = self.current_module.clone();
4653 // Look for the current trait.
4654 match self.current_trait_ref {
4655 Some((trait_def_id, _)) => {
4656 if self.trait_item_map.contains_key(&(name, trait_def_id)) {
4657 add_trait_info(&mut found_traits, trait_def_id, name);
4660 None => {} // Nothing to do.
4663 // Look for trait children.
4664 build_reduced_graph::populate_module_if_necessary(self, &search_module);
4667 for (_, child_names) in search_module.children.borrow().iter() {
4668 let def = match child_names.def_for_namespace(TypeNS) {
4672 let trait_def_id = match def {
4673 DefTrait(trait_def_id) => trait_def_id,
4676 if self.trait_item_map.contains_key(&(name, trait_def_id)) {
4677 add_trait_info(&mut found_traits, trait_def_id, name);
4682 // Look for imports.
4683 for (_, import) in search_module.import_resolutions.borrow().iter() {
4684 let target = match import.target_for_namespace(TypeNS) {
4686 Some(target) => target,
4688 let did = match target.bindings.def_for_namespace(TypeNS) {
4689 Some(DefTrait(trait_def_id)) => trait_def_id,
4690 Some(..) | None => continue,
4692 if self.trait_item_map.contains_key(&(name, did)) {
4693 add_trait_info(&mut found_traits, did, name);
4694 let id = import.type_id;
4695 self.used_imports.insert((id, TypeNS));
4696 let trait_name = self.get_trait_name(did);
4697 self.record_import_use(id, trait_name);
4698 if let Some(DefId{krate: kid, ..}) = target.target_module.def_id.get() {
4699 self.used_crates.insert(kid);
4704 match search_module.parent_link.clone() {
4705 NoParentLink | ModuleParentLink(..) => break,
4706 BlockParentLink(parent_module, _) => {
4707 search_module = parent_module.upgrade().unwrap();
4715 fn record_def(&mut self, node_id: NodeId, (def, lp): (Def, LastPrivate)) {
4716 debug!("(recording def) recording {:?} for {}, last private {:?}",
4718 assert!(match lp {LastImport{..} => false, _ => true},
4719 "Import should only be used for `use` directives");
4720 self.last_private.insert(node_id, lp);
4722 match self.def_map.borrow_mut().entry(node_id) {
4723 // Resolve appears to "resolve" the same ID multiple
4724 // times, so here is a sanity check it at least comes to
4725 // the same conclusion! - nmatsakis
4726 Occupied(entry) => if def != *entry.get() {
4728 .bug(&format!("node_id {} resolved first to {:?} and \
4734 Vacant(entry) => { entry.insert(def); },
4738 fn enforce_default_binding_mode(&mut self,
4740 pat_binding_mode: BindingMode,
4742 match pat_binding_mode {
4743 BindByValue(_) => {}
4745 self.resolve_error(pat.span,
4746 &format!("cannot use `ref` binding mode \
4756 // Diagnostics are not particularly efficient, because they're rarely
4760 /// A somewhat inefficient routine to obtain the name of a module.
4761 fn module_to_string(&self, module: &Module) -> String {
4762 let mut names = Vec::new();
4764 fn collect_mod(names: &mut Vec<ast::Name>, module: &Module) {
4765 match module.parent_link {
4767 ModuleParentLink(ref module, name) => {
4769 collect_mod(names, &*module.upgrade().unwrap());
4771 BlockParentLink(ref module, _) => {
4772 // danger, shouldn't be ident?
4773 names.push(special_idents::opaque.name);
4774 collect_mod(names, &*module.upgrade().unwrap());
4778 collect_mod(&mut names, module);
4780 if names.len() == 0 {
4781 return "???".to_string();
4783 self.names_to_string(&names.into_iter().rev()
4784 .collect::<Vec<ast::Name>>()[])
4787 #[allow(dead_code)] // useful for debugging
4788 fn dump_module(&mut self, module_: Rc<Module>) {
4789 debug!("Dump of module `{}`:", self.module_to_string(&*module_));
4791 debug!("Children:");
4792 build_reduced_graph::populate_module_if_necessary(self, &module_);
4793 for (&name, _) in module_.children.borrow().iter() {
4794 debug!("* {}", token::get_name(name));
4797 debug!("Import resolutions:");
4798 let import_resolutions = module_.import_resolutions.borrow();
4799 for (&name, import_resolution) in import_resolutions.iter() {
4801 match import_resolution.target_for_namespace(ValueNS) {
4802 None => { value_repr = "".to_string(); }
4804 value_repr = " value:?".to_string();
4810 match import_resolution.target_for_namespace(TypeNS) {
4811 None => { type_repr = "".to_string(); }
4813 type_repr = " type:?".to_string();
4818 debug!("* {}:{}{}", token::get_name(name), value_repr, type_repr);
4823 pub struct CrateMap {
4824 pub def_map: DefMap,
4825 pub freevars: RefCell<FreevarMap>,
4826 pub capture_mode_map: RefCell<CaptureModeMap>,
4827 pub export_map: ExportMap,
4828 pub trait_map: TraitMap,
4829 pub external_exports: ExternalExports,
4830 pub last_private_map: LastPrivateMap,
4831 pub glob_map: Option<GlobMap>
4834 #[derive(PartialEq,Copy)]
4835 pub enum MakeGlobMap {
4840 /// Entry point to crate resolution.
4841 pub fn resolve_crate<'a, 'tcx>(session: &'a Session,
4842 ast_map: &'a ast_map::Map<'tcx>,
4845 make_glob_map: MakeGlobMap)
4847 let mut resolver = Resolver::new(session, ast_map, krate.span, make_glob_map);
4849 build_reduced_graph::build_reduced_graph(&mut resolver, krate);
4850 session.abort_if_errors();
4852 resolver.resolve_imports();
4853 session.abort_if_errors();
4855 record_exports::record(&mut resolver);
4856 session.abort_if_errors();
4858 resolver.resolve_crate(krate);
4859 session.abort_if_errors();
4861 check_unused::check_crate(&mut resolver, krate);
4864 def_map: resolver.def_map,
4865 freevars: resolver.freevars,
4866 capture_mode_map: RefCell::new(resolver.capture_mode_map),
4867 export_map: resolver.export_map,
4868 trait_map: resolver.trait_map,
4869 external_exports: resolver.external_exports,
4870 last_private_map: resolver.last_private,
4871 glob_map: if resolver.make_glob_map {
4872 Some(resolver.glob_map)