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};
100 // NB: This module needs to be declared first so diagnostics are
101 // registered before they are used.
106 mod build_reduced_graph;
111 binding_mode: BindingMode,
114 // Map from the name in a pattern to its binding mode.
115 type BindingMap = HashMap<Name, BindingInfo>;
117 #[derive(Copy, PartialEq)]
118 enum PatternBindingMode {
120 LocalIrrefutableMode,
121 ArgumentIrrefutableMode,
124 #[derive(Copy, PartialEq, Eq, Hash, Show)]
130 /// A NamespaceResult represents the result of resolving an import in
131 /// a particular namespace. The result is either definitely-resolved,
132 /// definitely- unresolved, or unknown.
134 enum NamespaceResult {
135 /// Means that resolve hasn't gathered enough information yet to determine
136 /// whether the name is bound in this namespace. (That is, it hasn't
137 /// resolved all `use` directives yet.)
139 /// Means that resolve has determined that the name is definitely
140 /// not bound in the namespace.
142 /// Means that resolve has determined that the name is bound in the Module
143 /// argument, and specified by the NameBindings argument.
144 BoundResult(Rc<Module>, Rc<NameBindings>)
147 impl NamespaceResult {
148 fn is_unknown(&self) -> bool {
150 UnknownResult => true,
154 fn is_unbound(&self) -> bool {
156 UnboundResult => true,
162 enum NameDefinition {
163 NoNameDefinition, //< The name was unbound.
164 ChildNameDefinition(Def, LastPrivate), //< The name identifies an immediate child.
165 ImportNameDefinition(Def, LastPrivate) //< The name identifies an import.
168 impl<'a, 'v, 'tcx> Visitor<'v> for Resolver<'a, 'tcx> {
169 fn visit_item(&mut self, item: &Item) {
170 self.resolve_item(item);
172 fn visit_arm(&mut self, arm: &Arm) {
173 self.resolve_arm(arm);
175 fn visit_block(&mut self, block: &Block) {
176 self.resolve_block(block);
178 fn visit_expr(&mut self, expr: &Expr) {
179 self.resolve_expr(expr);
181 fn visit_local(&mut self, local: &Local) {
182 self.resolve_local(local);
184 fn visit_ty(&mut self, ty: &Ty) {
185 self.resolve_type(ty);
189 /// Contains data for specific types of import directives.
191 enum ImportDirectiveSubclass {
192 SingleImport(Name /* target */, Name /* source */),
196 type ErrorMessage = Option<(Span, String)>;
198 enum ResolveResult<T> {
199 Failed(ErrorMessage), // Failed to resolve the name, optional helpful error message.
200 Indeterminate, // Couldn't determine due to unresolved globs.
201 Success(T) // Successfully resolved the import.
204 impl<T> ResolveResult<T> {
205 fn indeterminate(&self) -> bool {
206 match *self { Indeterminate => true, _ => false }
210 enum FallbackSuggestion {
215 StaticMethod(String),
220 enum TypeParameters<'a> {
226 // Identifies the things that these parameters
227 // were declared on (type, fn, etc)
230 // ID of the enclosing item.
233 // The kind of the rib used for type parameters.
237 // The rib kind controls the translation of local
238 // definitions (`DefLocal`) to upvars (`DefUpvar`).
239 #[derive(Copy, Show)]
241 // No translation needs to be applied.
244 // We passed through a closure scope at the given node ID.
245 // Translate upvars as appropriate.
246 ClosureRibKind(NodeId /* func id */, NodeId /* body id if proc or unboxed */),
248 // We passed through an impl or trait and are now in one of its
249 // methods. Allow references to ty params that impl or trait
250 // binds. Disallow any other upvars (including other ty params that are
252 // parent; method itself
253 MethodRibKind(NodeId, MethodSort),
255 // We passed through an item scope. Disallow upvars.
258 // We're in a constant item. Can't refer to dynamic stuff.
262 // Methods can be required or provided. RequiredMethod methods only occur in traits.
263 #[derive(Copy, Show)]
266 ProvidedMethod(NodeId)
270 enum UseLexicalScopeFlag {
275 enum ModulePrefixResult {
277 PrefixFound(Rc<Module>, uint)
280 #[derive(Copy, PartialEq)]
281 enum NameSearchType {
282 /// We're doing a name search in order to resolve a `use` directive.
285 /// We're doing a name search in order to resolve a path type, a path
286 /// expression, or a path pattern.
291 enum BareIdentifierPatternResolution {
292 FoundStructOrEnumVariant(Def, LastPrivate),
293 FoundConst(Def, LastPrivate),
294 BareIdentifierPatternUnresolved
300 bindings: HashMap<Name, DefLike>,
305 fn new(kind: RibKind) -> Rib {
307 bindings: HashMap::new(),
313 /// Whether an import can be shadowed by another import.
314 #[derive(Show,PartialEq,Clone,Copy)]
320 /// One import directive.
322 struct ImportDirective {
323 module_path: Vec<Name>,
324 subclass: ImportDirectiveSubclass,
327 is_public: bool, // see note in ImportResolution about how to use this
328 shadowable: Shadowable,
331 impl ImportDirective {
332 fn new(module_path: Vec<Name> ,
333 subclass: ImportDirectiveSubclass,
337 shadowable: Shadowable)
340 module_path: module_path,
344 is_public: is_public,
345 shadowable: shadowable,
350 /// The item that an import resolves to.
351 #[derive(Clone,Show)]
353 target_module: Rc<Module>,
354 bindings: Rc<NameBindings>,
355 shadowable: Shadowable,
359 fn new(target_module: Rc<Module>,
360 bindings: Rc<NameBindings>,
361 shadowable: Shadowable)
364 target_module: target_module,
366 shadowable: shadowable,
371 /// An ImportResolution represents a particular `use` directive.
373 struct ImportResolution {
374 /// Whether this resolution came from a `use` or a `pub use`. Note that this
375 /// should *not* be used whenever resolution is being performed, this is
376 /// only looked at for glob imports statements currently. Privacy testing
377 /// occurs during a later phase of compilation.
380 // The number of outstanding references to this name. When this reaches
381 // zero, outside modules can count on the targets being correct. Before
382 // then, all bets are off; future imports could override this name.
383 outstanding_references: uint,
385 /// The value that this `use` directive names, if there is one.
386 value_target: Option<Target>,
387 /// The source node of the `use` directive leading to the value target
391 /// The type that this `use` directive names, if there is one.
392 type_target: Option<Target>,
393 /// The source node of the `use` directive leading to the type target
398 impl ImportResolution {
399 fn new(id: NodeId, is_public: bool) -> ImportResolution {
403 outstanding_references: 0,
406 is_public: is_public,
410 fn target_for_namespace(&self, namespace: Namespace)
413 TypeNS => self.type_target.clone(),
414 ValueNS => self.value_target.clone(),
418 fn id(&self, namespace: Namespace) -> NodeId {
420 TypeNS => self.type_id,
421 ValueNS => self.value_id,
425 fn shadowable(&self, namespace: Namespace) -> Shadowable {
426 let target = self.target_for_namespace(namespace);
427 if target.is_none() {
428 return Shadowable::Always;
431 target.unwrap().shadowable
434 fn set_target_and_id(&mut self,
435 namespace: Namespace,
436 target: Option<Target>,
440 self.type_target = target;
444 self.value_target = target;
451 /// The link from a module up to its nearest parent node.
452 #[derive(Clone,Show)]
455 ModuleParentLink(Weak<Module>, Name),
456 BlockParentLink(Weak<Module>, NodeId)
459 /// The type of module this is.
460 #[derive(Copy, PartialEq, Show)]
470 /// One node in the tree of modules.
472 parent_link: ParentLink,
473 def_id: Cell<Option<DefId>>,
474 kind: Cell<ModuleKind>,
477 children: RefCell<HashMap<Name, Rc<NameBindings>>>,
478 imports: RefCell<Vec<ImportDirective>>,
480 // The external module children of this node that were declared with
482 external_module_children: RefCell<HashMap<Name, Rc<Module>>>,
484 // The anonymous children of this node. Anonymous children are pseudo-
485 // modules that are implicitly created around items contained within
488 // For example, if we have this:
496 // There will be an anonymous module created around `g` with the ID of the
497 // entry block for `f`.
498 anonymous_children: RefCell<NodeMap<Rc<Module>>>,
500 // The status of resolving each import in this module.
501 import_resolutions: RefCell<HashMap<Name, ImportResolution>>,
503 // The number of unresolved globs that this module exports.
504 glob_count: Cell<uint>,
506 // The index of the import we're resolving.
507 resolved_import_count: Cell<uint>,
509 // Whether this module is populated. If not populated, any attempt to
510 // access the children must be preceded with a
511 // `populate_module_if_necessary` call.
512 populated: Cell<bool>,
516 fn new(parent_link: ParentLink,
517 def_id: Option<DefId>,
523 parent_link: parent_link,
524 def_id: Cell::new(def_id),
525 kind: Cell::new(kind),
526 is_public: is_public,
527 children: RefCell::new(HashMap::new()),
528 imports: RefCell::new(Vec::new()),
529 external_module_children: RefCell::new(HashMap::new()),
530 anonymous_children: RefCell::new(NodeMap()),
531 import_resolutions: RefCell::new(HashMap::new()),
532 glob_count: Cell::new(0),
533 resolved_import_count: Cell::new(0),
534 populated: Cell::new(!external),
538 fn all_imports_resolved(&self) -> bool {
539 self.imports.borrow().len() == self.resolved_import_count.get()
543 impl fmt::Show for Module {
544 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
545 write!(f, "{:?}, kind: {:?}, {}",
548 if self.is_public { "public" } else { "private" } )
554 flags DefModifiers: u8 {
555 const PUBLIC = 0b0000_0001,
556 const IMPORTABLE = 0b0000_0010,
560 // Records a possibly-private type definition.
561 #[derive(Clone,Show)]
563 modifiers: DefModifiers, // see note in ImportResolution about how to use this
564 module_def: Option<Rc<Module>>,
565 type_def: Option<Def>,
566 type_span: Option<Span>
569 // Records a possibly-private value definition.
570 #[derive(Clone, Copy, Show)]
572 modifiers: DefModifiers, // see note in ImportResolution about how to use this
574 value_span: Option<Span>,
577 // Records the definitions (at most one for each namespace) that a name is
580 struct NameBindings {
581 type_def: RefCell<Option<TypeNsDef>>, //< Meaning in type namespace.
582 value_def: RefCell<Option<ValueNsDef>>, //< Meaning in value namespace.
585 /// Ways in which a trait can be referenced
587 enum TraitReferenceType {
588 TraitImplementation, // impl SomeTrait for T { ... }
589 TraitDerivation, // trait T : SomeTrait { ... }
590 TraitBoundingTypeParameter, // fn f<T:SomeTrait>() { ... }
591 TraitObject, // Box<for<'a> SomeTrait>
592 TraitQPath, // <T as SomeTrait>::
596 fn new() -> NameBindings {
598 type_def: RefCell::new(None),
599 value_def: RefCell::new(None),
603 /// Creates a new module in this set of name bindings.
604 fn define_module(&self,
605 parent_link: ParentLink,
606 def_id: Option<DefId>,
611 // Merges the module with the existing type def or creates a new one.
612 let modifiers = if is_public { PUBLIC } else { DefModifiers::empty() } | IMPORTABLE;
613 let module_ = Rc::new(Module::new(parent_link,
618 let type_def = self.type_def.borrow().clone();
621 *self.type_def.borrow_mut() = Some(TypeNsDef {
622 modifiers: modifiers,
623 module_def: Some(module_),
629 *self.type_def.borrow_mut() = Some(TypeNsDef {
630 modifiers: modifiers,
631 module_def: Some(module_),
633 type_def: type_def.type_def
639 /// Sets the kind of the module, creating a new one if necessary.
640 fn set_module_kind(&self,
641 parent_link: ParentLink,
642 def_id: Option<DefId>,
647 let modifiers = if is_public { PUBLIC } else { DefModifiers::empty() } | IMPORTABLE;
648 let type_def = self.type_def.borrow().clone();
651 let module = Module::new(parent_link,
656 *self.type_def.borrow_mut() = Some(TypeNsDef {
657 modifiers: modifiers,
658 module_def: Some(Rc::new(module)),
664 match type_def.module_def {
666 let module = Module::new(parent_link,
671 *self.type_def.borrow_mut() = Some(TypeNsDef {
672 modifiers: modifiers,
673 module_def: Some(Rc::new(module)),
674 type_def: type_def.type_def,
678 Some(module_def) => module_def.kind.set(kind),
684 /// Records a type definition.
685 fn define_type(&self, def: Def, sp: Span, modifiers: DefModifiers) {
686 debug!("defining type for def {:?} with modifiers {:?}", def, modifiers);
687 // Merges the type with the existing type def or creates a new one.
688 let type_def = self.type_def.borrow().clone();
691 *self.type_def.borrow_mut() = Some(TypeNsDef {
695 modifiers: modifiers,
699 *self.type_def.borrow_mut() = Some(TypeNsDef {
700 module_def: type_def.module_def,
703 modifiers: modifiers,
709 /// Records a value definition.
710 fn define_value(&self, def: Def, sp: Span, modifiers: DefModifiers) {
711 debug!("defining value for def {:?} with modifiers {:?}", def, modifiers);
712 *self.value_def.borrow_mut() = Some(ValueNsDef {
714 value_span: Some(sp),
715 modifiers: modifiers,
719 /// Returns the module node if applicable.
720 fn get_module_if_available(&self) -> Option<Rc<Module>> {
721 match *self.type_def.borrow() {
722 Some(ref type_def) => type_def.module_def.clone(),
727 /// Returns the module node. Panics if this node does not have a module
729 fn get_module(&self) -> Rc<Module> {
730 match self.get_module_if_available() {
732 panic!("get_module called on a node with no module \
735 Some(module_def) => module_def
739 fn defined_in_namespace(&self, namespace: Namespace) -> bool {
741 TypeNS => return self.type_def.borrow().is_some(),
742 ValueNS => return self.value_def.borrow().is_some()
746 fn defined_in_public_namespace(&self, namespace: Namespace) -> bool {
747 self.defined_in_namespace_with(namespace, PUBLIC)
750 fn defined_in_namespace_with(&self, namespace: Namespace, modifiers: DefModifiers) -> bool {
752 TypeNS => match *self.type_def.borrow() {
753 Some(ref def) => def.modifiers.contains(modifiers), None => false
755 ValueNS => match *self.value_def.borrow() {
756 Some(ref def) => def.modifiers.contains(modifiers), None => false
761 fn def_for_namespace(&self, namespace: Namespace) -> Option<Def> {
764 match *self.type_def.borrow() {
766 Some(ref type_def) => {
767 match type_def.type_def {
768 Some(type_def) => Some(type_def),
770 match type_def.module_def {
771 Some(ref module) => {
772 match module.def_id.get() {
773 Some(did) => Some(DefMod(did)),
785 match *self.value_def.borrow() {
787 Some(value_def) => Some(value_def.def)
793 fn span_for_namespace(&self, namespace: Namespace) -> Option<Span> {
794 if self.defined_in_namespace(namespace) {
797 match *self.type_def.borrow() {
799 Some(ref type_def) => type_def.type_span
803 match *self.value_def.borrow() {
805 Some(ref value_def) => value_def.value_span
815 /// Interns the names of the primitive types.
816 struct PrimitiveTypeTable {
817 primitive_types: HashMap<Name, PrimTy>,
820 impl PrimitiveTypeTable {
821 fn new() -> PrimitiveTypeTable {
822 let mut table = PrimitiveTypeTable {
823 primitive_types: HashMap::new()
826 table.intern("bool", TyBool);
827 table.intern("char", TyChar);
828 table.intern("f32", TyFloat(TyF32));
829 table.intern("f64", TyFloat(TyF64));
830 table.intern("int", TyInt(TyIs(true)));
831 table.intern("isize", TyInt(TyIs(false)));
832 table.intern("i8", TyInt(TyI8));
833 table.intern("i16", TyInt(TyI16));
834 table.intern("i32", TyInt(TyI32));
835 table.intern("i64", TyInt(TyI64));
836 table.intern("str", TyStr);
837 table.intern("uint", TyUint(TyUs(true)));
838 table.intern("usize", TyUint(TyUs(false)));
839 table.intern("u8", TyUint(TyU8));
840 table.intern("u16", TyUint(TyU16));
841 table.intern("u32", TyUint(TyU32));
842 table.intern("u64", TyUint(TyU64));
847 fn intern(&mut self, string: &str, primitive_type: PrimTy) {
848 self.primitive_types.insert(token::intern(string), primitive_type);
852 /// The main resolver class.
853 struct Resolver<'a, 'tcx:'a> {
854 session: &'a Session,
856 ast_map: &'a ast_map::Map<'tcx>,
858 graph_root: NameBindings,
860 trait_item_map: FnvHashMap<(Name, DefId), TraitItemKind>,
862 structs: FnvHashMap<DefId, Vec<Name>>,
864 // The number of imports that are currently unresolved.
865 unresolved_imports: uint,
867 // The module that represents the current item scope.
868 current_module: Rc<Module>,
870 // The current set of local scopes, for values.
871 // FIXME #4948: Reuse ribs to avoid allocation.
872 value_ribs: Vec<Rib>,
874 // The current set of local scopes, for types.
877 // The current set of local scopes, for labels.
878 label_ribs: Vec<Rib>,
880 // The trait that the current context can refer to.
881 current_trait_ref: Option<(DefId, TraitRef)>,
883 // The current self type if inside an impl (used for better errors).
884 current_self_type: Option<Ty>,
886 // The ident for the keyword "self".
888 // The ident for the non-keyword "Self".
889 type_self_name: Name,
891 // The idents for the primitive types.
892 primitive_type_table: PrimitiveTypeTable,
895 freevars: RefCell<FreevarMap>,
896 freevars_seen: RefCell<NodeMap<NodeSet>>,
897 capture_mode_map: CaptureModeMap,
898 export_map: ExportMap,
900 external_exports: ExternalExports,
901 last_private: LastPrivateMap,
903 // Whether or not to print error messages. Can be set to true
904 // when getting additional info for error message suggestions,
905 // so as to avoid printing duplicate errors
909 // Maps imports to the names of items actually imported (this actually maps
910 // all imports, but only glob imports are actually interesting).
913 used_imports: HashSet<(NodeId, Namespace)>,
914 used_crates: HashSet<CrateNum>,
918 enum FallbackChecks {
924 impl<'a, 'tcx> Resolver<'a, 'tcx> {
925 fn new(session: &'a Session,
926 ast_map: &'a ast_map::Map<'tcx>,
928 make_glob_map: MakeGlobMap) -> Resolver<'a, 'tcx> {
929 let graph_root = NameBindings::new();
931 graph_root.define_module(NoParentLink,
932 Some(DefId { krate: 0, node: 0 }),
938 let current_module = graph_root.get_module();
945 // The outermost module has def ID 0; this is not reflected in the
948 graph_root: graph_root,
950 trait_item_map: FnvHashMap(),
951 structs: FnvHashMap(),
953 unresolved_imports: 0,
955 current_module: current_module,
956 value_ribs: Vec::new(),
957 type_ribs: Vec::new(),
958 label_ribs: Vec::new(),
960 current_trait_ref: None,
961 current_self_type: None,
963 self_name: special_names::self_,
964 type_self_name: special_names::type_self,
966 primitive_type_table: PrimitiveTypeTable::new(),
968 def_map: RefCell::new(NodeMap()),
969 freevars: RefCell::new(NodeMap()),
970 freevars_seen: RefCell::new(NodeMap()),
971 capture_mode_map: NodeMap(),
972 export_map: NodeMap(),
973 trait_map: NodeMap(),
974 used_imports: HashSet::new(),
975 used_crates: HashSet::new(),
976 external_exports: DefIdSet(),
977 last_private: NodeMap(),
980 make_glob_map: make_glob_map == MakeGlobMap::Yes,
981 glob_map: HashMap::new(),
987 // This is a fixed-point algorithm. We resolve imports until our efforts
988 // are stymied by an unresolved import; then we bail out of the current
989 // module and continue. We terminate successfully once no more imports
990 // remain or unsuccessfully when no forward progress in resolving imports
993 /// Resolves all imports for the crate. This method performs the fixed-
995 fn resolve_imports(&mut self) {
997 let mut prev_unresolved_imports = 0;
999 debug!("(resolving imports) iteration {}, {} imports left",
1000 i, self.unresolved_imports);
1002 let module_root = self.graph_root.get_module();
1003 self.resolve_imports_for_module_subtree(module_root.clone());
1005 if self.unresolved_imports == 0 {
1006 debug!("(resolving imports) success");
1010 if self.unresolved_imports == prev_unresolved_imports {
1011 self.report_unresolved_imports(module_root);
1016 prev_unresolved_imports = self.unresolved_imports;
1020 /// Attempts to resolve imports for the given module and all of its
1022 fn resolve_imports_for_module_subtree(&mut self, module_: Rc<Module>) {
1023 debug!("(resolving imports for module subtree) resolving {}",
1024 self.module_to_string(&*module_));
1025 let orig_module = replace(&mut self.current_module, module_.clone());
1026 self.resolve_imports_for_module(module_.clone());
1027 self.current_module = orig_module;
1029 build_reduced_graph::populate_module_if_necessary(self, &module_);
1030 for (_, child_node) in module_.children.borrow().iter() {
1031 match child_node.get_module_if_available() {
1035 Some(child_module) => {
1036 self.resolve_imports_for_module_subtree(child_module);
1041 for (_, child_module) in module_.anonymous_children.borrow().iter() {
1042 self.resolve_imports_for_module_subtree(child_module.clone());
1046 /// Attempts to resolve imports for the given module only.
1047 fn resolve_imports_for_module(&mut self, module: Rc<Module>) {
1048 if module.all_imports_resolved() {
1049 debug!("(resolving imports for module) all imports resolved for \
1051 self.module_to_string(&*module));
1055 let imports = module.imports.borrow();
1056 let import_count = imports.len();
1057 while module.resolved_import_count.get() < import_count {
1058 let import_index = module.resolved_import_count.get();
1059 let import_directive = &(*imports)[import_index];
1060 match self.resolve_import_for_module(module.clone(),
1063 let (span, help) = match err {
1064 Some((span, msg)) => (span, format!(". {}", msg)),
1065 None => (import_directive.span, String::new())
1067 let msg = format!("unresolved import `{}`{}",
1068 self.import_path_to_string(
1069 &import_directive.module_path[],
1070 import_directive.subclass),
1072 self.resolve_error(span, &msg[]);
1074 Indeterminate => break, // Bail out. We'll come around next time.
1075 Success(()) => () // Good. Continue.
1078 module.resolved_import_count
1079 .set(module.resolved_import_count.get() + 1);
1083 fn names_to_string(&self, names: &[Name]) -> String {
1084 let mut first = true;
1085 let mut result = String::new();
1086 for name in names.iter() {
1090 result.push_str("::")
1092 result.push_str(token::get_name(*name).get());
1097 fn path_names_to_string(&self, path: &Path) -> String {
1098 let names: Vec<ast::Name> = path.segments
1100 .map(|seg| seg.identifier.name)
1102 self.names_to_string(&names[])
1105 fn import_directive_subclass_to_string(&mut self,
1106 subclass: ImportDirectiveSubclass)
1109 SingleImport(_, source) => {
1110 token::get_name(source).get().to_string()
1112 GlobImport => "*".to_string()
1116 fn import_path_to_string(&mut self,
1118 subclass: ImportDirectiveSubclass)
1120 if names.is_empty() {
1121 self.import_directive_subclass_to_string(subclass)
1124 self.names_to_string(names),
1125 self.import_directive_subclass_to_string(
1126 subclass))).to_string()
1131 fn record_import_use(&mut self, import_id: NodeId, name: Name) {
1132 if !self.make_glob_map {
1135 if self.glob_map.contains_key(&import_id) {
1136 self.glob_map[import_id].insert(name);
1140 let mut new_set = HashSet::new();
1141 new_set.insert(name);
1142 self.glob_map.insert(import_id, new_set);
1145 fn get_trait_name(&self, did: DefId) -> Name {
1146 if did.krate == LOCAL_CRATE {
1147 self.ast_map.expect_item(did.node).ident.name
1149 csearch::get_trait_name(&self.session.cstore, did)
1153 /// Attempts to resolve the given import. The return value indicates
1154 /// failure if we're certain the name does not exist, indeterminate if we
1155 /// don't know whether the name exists at the moment due to other
1156 /// currently-unresolved imports, or success if we know the name exists.
1157 /// If successful, the resolved bindings are written into the module.
1158 fn resolve_import_for_module(&mut self,
1159 module_: Rc<Module>,
1160 import_directive: &ImportDirective)
1161 -> ResolveResult<()> {
1162 let mut resolution_result = Failed(None);
1163 let module_path = &import_directive.module_path;
1165 debug!("(resolving import for module) resolving import `{}::...` in `{}`",
1166 self.names_to_string(&module_path[]),
1167 self.module_to_string(&*module_));
1169 // First, resolve the module path for the directive, if necessary.
1170 let container = if module_path.len() == 0 {
1171 // Use the crate root.
1172 Some((self.graph_root.get_module(), LastMod(AllPublic)))
1174 match self.resolve_module_path(module_.clone(),
1176 DontUseLexicalScope,
1177 import_directive.span,
1180 resolution_result = Failed(err);
1184 resolution_result = Indeterminate;
1187 Success(container) => Some(container),
1193 Some((containing_module, lp)) => {
1194 // We found the module that the target is contained
1195 // within. Attempt to resolve the import within it.
1197 match import_directive.subclass {
1198 SingleImport(target, source) => {
1200 self.resolve_single_import(&*module_,
1209 self.resolve_glob_import(&*module_,
1218 // Decrement the count of unresolved imports.
1219 match resolution_result {
1221 assert!(self.unresolved_imports >= 1);
1222 self.unresolved_imports -= 1;
1225 // Nothing to do here; just return the error.
1229 // Decrement the count of unresolved globs if necessary. But only if
1230 // the resolution result is indeterminate -- otherwise we'll stop
1231 // processing imports here. (See the loop in
1232 // resolve_imports_for_module.)
1234 if !resolution_result.indeterminate() {
1235 match import_directive.subclass {
1237 assert!(module_.glob_count.get() >= 1);
1238 module_.glob_count.set(module_.glob_count.get() - 1);
1240 SingleImport(..) => {
1246 return resolution_result;
1249 fn create_name_bindings_from_module(module: Rc<Module>) -> NameBindings {
1251 type_def: RefCell::new(Some(TypeNsDef {
1252 modifiers: IMPORTABLE,
1253 module_def: Some(module),
1257 value_def: RefCell::new(None),
1261 fn resolve_single_import(&mut self,
1263 containing_module: Rc<Module>,
1266 directive: &ImportDirective,
1268 -> ResolveResult<()> {
1269 debug!("(resolving single import) resolving `{}` = `{}::{}` from \
1270 `{}` id {}, last private {:?}",
1271 token::get_name(target),
1272 self.module_to_string(&*containing_module),
1273 token::get_name(source),
1274 self.module_to_string(module_),
1280 LastImport {..} => {
1282 .span_bug(directive.span,
1283 "not expecting Import here, must be LastMod")
1287 // We need to resolve both namespaces for this to succeed.
1290 let mut value_result = UnknownResult;
1291 let mut type_result = UnknownResult;
1293 // Search for direct children of the containing module.
1294 build_reduced_graph::populate_module_if_necessary(self, &containing_module);
1296 match containing_module.children.borrow().get(&source) {
1300 Some(ref child_name_bindings) => {
1301 if child_name_bindings.defined_in_namespace(ValueNS) {
1302 debug!("(resolving single import) found value binding");
1303 value_result = BoundResult(containing_module.clone(),
1304 (*child_name_bindings).clone());
1306 if child_name_bindings.defined_in_namespace(TypeNS) {
1307 debug!("(resolving single import) found type binding");
1308 type_result = BoundResult(containing_module.clone(),
1309 (*child_name_bindings).clone());
1314 // Unless we managed to find a result in both namespaces (unlikely),
1315 // search imports as well.
1316 let mut value_used_reexport = false;
1317 let mut type_used_reexport = false;
1318 match (value_result.clone(), type_result.clone()) {
1319 (BoundResult(..), BoundResult(..)) => {} // Continue.
1321 // If there is an unresolved glob at this point in the
1322 // containing module, bail out. We don't know enough to be
1323 // able to resolve this import.
1325 if containing_module.glob_count.get() > 0 {
1326 debug!("(resolving single import) unresolved glob; \
1328 return Indeterminate;
1331 // Now search the exported imports within the containing module.
1332 match containing_module.import_resolutions.borrow().get(&source) {
1334 debug!("(resolving single import) no import");
1335 // The containing module definitely doesn't have an
1336 // exported import with the name in question. We can
1337 // therefore accurately report that the names are
1340 if value_result.is_unknown() {
1341 value_result = UnboundResult;
1343 if type_result.is_unknown() {
1344 type_result = UnboundResult;
1347 Some(import_resolution)
1348 if import_resolution.outstanding_references == 0 => {
1350 fn get_binding(this: &mut Resolver,
1351 import_resolution: &ImportResolution,
1352 namespace: Namespace,
1354 -> NamespaceResult {
1356 // Import resolutions must be declared with "pub"
1357 // in order to be exported.
1358 if !import_resolution.is_public {
1359 return UnboundResult;
1362 match import_resolution.
1363 target_for_namespace(namespace) {
1365 return UnboundResult;
1372 debug!("(resolving single import) found \
1373 import in ns {:?}", namespace);
1374 let id = import_resolution.id(namespace);
1375 // track used imports and extern crates as well
1376 this.used_imports.insert((id, namespace));
1377 this.record_import_use(id, *source);
1378 match target_module.def_id.get() {
1379 Some(DefId{krate: kid, ..}) => {
1380 this.used_crates.insert(kid);
1384 return BoundResult(target_module, bindings);
1389 // The name is an import which has been fully
1390 // resolved. We can, therefore, just follow it.
1391 if value_result.is_unknown() {
1392 value_result = get_binding(self,
1396 value_used_reexport = import_resolution.is_public;
1398 if type_result.is_unknown() {
1399 type_result = get_binding(self,
1403 type_used_reexport = import_resolution.is_public;
1408 // If containing_module is the same module whose import we are resolving
1409 // and there it has an unresolved import with the same name as `source`,
1410 // then the user is actually trying to import an item that is declared
1411 // in the same scope
1414 // use self::submodule;
1415 // pub mod submodule;
1417 // In this case we continue as if we resolved the import and let the
1418 // check_for_conflicts_between_imports_and_items call below handle
1420 match (module_.def_id.get(), containing_module.def_id.get()) {
1421 (Some(id1), Some(id2)) if id1 == id2 => {
1422 if value_result.is_unknown() {
1423 value_result = UnboundResult;
1425 if type_result.is_unknown() {
1426 type_result = UnboundResult;
1430 // The import is unresolved. Bail out.
1431 debug!("(resolving single import) unresolved import; \
1433 return Indeterminate;
1441 // If we didn't find a result in the type namespace, search the
1442 // external modules.
1443 let mut value_used_public = false;
1444 let mut type_used_public = false;
1446 BoundResult(..) => {}
1448 match containing_module.external_module_children.borrow_mut()
1449 .get(&source).cloned() {
1450 None => {} // Continue.
1452 debug!("(resolving single import) found external \
1454 // track the module as used.
1455 match module.def_id.get() {
1456 Some(DefId{krate: kid, ..}) => { self.used_crates.insert(kid); },
1460 Rc::new(Resolver::create_name_bindings_from_module(
1462 type_result = BoundResult(containing_module.clone(),
1464 type_used_public = true;
1470 // We've successfully resolved the import. Write the results in.
1471 let mut import_resolutions = module_.import_resolutions.borrow_mut();
1472 let import_resolution = &mut (*import_resolutions)[target];
1474 let mut check_and_write_import = |&mut: namespace, result: &_, used_public: &mut bool| {
1475 let namespace_name = match namespace {
1481 BoundResult(ref target_module, ref name_bindings) => {
1482 debug!("(resolving single import) found {:?} target: {:?}",
1484 name_bindings.def_for_namespace(namespace));
1485 self.check_for_conflicting_import(
1486 &import_resolution.target_for_namespace(namespace),
1491 self.check_that_import_is_importable(
1497 let target = Some(Target::new(target_module.clone(),
1498 name_bindings.clone(),
1499 directive.shadowable));
1500 import_resolution.set_target_and_id(namespace, target, directive.id);
1501 import_resolution.is_public = directive.is_public;
1502 *used_public = name_bindings.defined_in_public_namespace(namespace);
1504 UnboundResult => { /* Continue. */ }
1506 panic!("{:?} result should be known at this point", namespace_name);
1510 check_and_write_import(ValueNS, &value_result, &mut value_used_public);
1511 check_and_write_import(TypeNS, &type_result, &mut type_used_public);
1514 self.check_for_conflicts_between_imports_and_items(
1520 if value_result.is_unbound() && type_result.is_unbound() {
1521 let msg = format!("There is no `{}` in `{}`",
1522 token::get_name(source),
1523 self.module_to_string(&*containing_module));
1524 return Failed(Some((directive.span, msg)));
1526 let value_used_public = value_used_reexport || value_used_public;
1527 let type_used_public = type_used_reexport || type_used_public;
1529 assert!(import_resolution.outstanding_references >= 1);
1530 import_resolution.outstanding_references -= 1;
1532 // record what this import resolves to for later uses in documentation,
1533 // this may resolve to either a value or a type, but for documentation
1534 // purposes it's good enough to just favor one over the other.
1535 let value_private = match import_resolution.value_target {
1536 Some(ref target) => {
1537 let def = target.bindings.def_for_namespace(ValueNS).unwrap();
1538 self.def_map.borrow_mut().insert(directive.id, def);
1539 let did = def.def_id();
1540 if value_used_public {Some(lp)} else {Some(DependsOn(did))}
1542 // AllPublic here and below is a dummy value, it should never be used because
1543 // _exists is false.
1546 let type_private = match import_resolution.type_target {
1547 Some(ref target) => {
1548 let def = target.bindings.def_for_namespace(TypeNS).unwrap();
1549 self.def_map.borrow_mut().insert(directive.id, def);
1550 let did = def.def_id();
1551 if type_used_public {Some(lp)} else {Some(DependsOn(did))}
1556 self.last_private.insert(directive.id, LastImport{value_priv: value_private,
1558 type_priv: type_private,
1561 debug!("(resolving single import) successfully resolved import");
1565 // Resolves a glob import. Note that this function cannot fail; it either
1566 // succeeds or bails out (as importing * from an empty module or a module
1567 // that exports nothing is valid). containing_module is the module we are
1568 // actually importing, i.e., `foo` in `use foo::*`.
1569 fn resolve_glob_import(&mut self,
1571 containing_module: Rc<Module>,
1572 import_directive: &ImportDirective,
1574 -> ResolveResult<()> {
1575 let id = import_directive.id;
1576 let is_public = import_directive.is_public;
1578 // This function works in a highly imperative manner; it eagerly adds
1579 // everything it can to the list of import resolutions of the module
1581 debug!("(resolving glob import) resolving glob import {}", id);
1583 // We must bail out if the node has unresolved imports of any kind
1584 // (including globs).
1585 if !(*containing_module).all_imports_resolved() {
1586 debug!("(resolving glob import) target module has unresolved \
1587 imports; bailing out");
1588 return Indeterminate;
1591 assert_eq!(containing_module.glob_count.get(), 0);
1593 // Add all resolved imports from the containing module.
1594 let import_resolutions = containing_module.import_resolutions.borrow();
1595 for (ident, target_import_resolution) in import_resolutions.iter() {
1596 debug!("(resolving glob import) writing module resolution \
1598 token::get_name(*ident),
1599 self.module_to_string(module_));
1601 if !target_import_resolution.is_public {
1602 debug!("(resolving glob import) nevermind, just kidding");
1606 // Here we merge two import resolutions.
1607 let mut import_resolutions = module_.import_resolutions.borrow_mut();
1608 match import_resolutions.get_mut(ident) {
1609 Some(dest_import_resolution) => {
1610 // Merge the two import resolutions at a finer-grained
1613 match target_import_resolution.value_target {
1617 Some(ref value_target) => {
1618 self.check_for_conflicting_import(&dest_import_resolution.value_target,
1619 import_directive.span,
1622 dest_import_resolution.value_target = Some(value_target.clone());
1625 match target_import_resolution.type_target {
1629 Some(ref type_target) => {
1630 self.check_for_conflicting_import(&dest_import_resolution.type_target,
1631 import_directive.span,
1634 dest_import_resolution.type_target = Some(type_target.clone());
1637 dest_import_resolution.is_public = is_public;
1643 // Simple: just copy the old import resolution.
1644 let mut new_import_resolution = ImportResolution::new(id, is_public);
1645 new_import_resolution.value_target =
1646 target_import_resolution.value_target.clone();
1647 new_import_resolution.type_target =
1648 target_import_resolution.type_target.clone();
1650 import_resolutions.insert(*ident, new_import_resolution);
1653 // Add all children from the containing module.
1654 build_reduced_graph::populate_module_if_necessary(self, &containing_module);
1656 for (&name, name_bindings) in containing_module.children.borrow().iter() {
1657 self.merge_import_resolution(module_,
1658 containing_module.clone(),
1661 name_bindings.clone());
1665 // Add external module children from the containing module.
1666 for (&name, module) in containing_module.external_module_children.borrow().iter() {
1668 Rc::new(Resolver::create_name_bindings_from_module(module.clone()));
1669 self.merge_import_resolution(module_,
1670 containing_module.clone(),
1676 // Record the destination of this import
1677 match containing_module.def_id.get() {
1679 self.def_map.borrow_mut().insert(id, DefMod(did));
1680 self.last_private.insert(id, lp);
1685 debug!("(resolving glob import) successfully resolved import");
1689 fn merge_import_resolution(&mut self,
1691 containing_module: Rc<Module>,
1692 import_directive: &ImportDirective,
1694 name_bindings: Rc<NameBindings>) {
1695 let id = import_directive.id;
1696 let is_public = import_directive.is_public;
1698 let mut import_resolutions = module_.import_resolutions.borrow_mut();
1699 let dest_import_resolution = import_resolutions.entry(name).get().unwrap_or_else(
1701 // Create a new import resolution from this child.
1702 vacant_entry.insert(ImportResolution::new(id, is_public))
1705 debug!("(resolving glob import) writing resolution `{}` in `{}` \
1707 token::get_name(name).get(),
1708 self.module_to_string(&*containing_module),
1709 self.module_to_string(module_));
1711 // Merge the child item into the import resolution.
1713 let mut merge_child_item = |&mut : namespace| {
1714 if name_bindings.defined_in_namespace_with(namespace, IMPORTABLE | PUBLIC) {
1715 let namespace_name = match namespace {
1719 debug!("(resolving glob import) ... for {} target", namespace_name);
1720 if dest_import_resolution.shadowable(namespace) == Shadowable::Never {
1721 let msg = format!("a {} named `{}` has already been imported \
1724 token::get_name(name).get());
1725 self.session.span_err(import_directive.span, msg.as_slice());
1727 let target = Target::new(containing_module.clone(),
1728 name_bindings.clone(),
1729 import_directive.shadowable);
1730 dest_import_resolution.set_target_and_id(namespace,
1736 merge_child_item(ValueNS);
1737 merge_child_item(TypeNS);
1740 dest_import_resolution.is_public = is_public;
1742 self.check_for_conflicts_between_imports_and_items(
1744 dest_import_resolution,
1745 import_directive.span,
1749 /// Checks that imported names and items don't have the same name.
1750 fn check_for_conflicting_import(&mut self,
1751 target: &Option<Target>,
1754 namespace: Namespace) {
1755 if self.session.features.borrow().import_shadowing {
1759 debug!("check_for_conflicting_import: {}; target exists: {}",
1760 token::get_name(name).get(),
1764 Some(ref target) if target.shadowable != Shadowable::Always => {
1765 let msg = format!("a {} named `{}` has already been imported \
1771 token::get_name(name).get());
1772 self.session.span_err(import_span, &msg[]);
1774 Some(_) | None => {}
1778 /// Checks that an import is actually importable
1779 fn check_that_import_is_importable(&mut self,
1780 name_bindings: &NameBindings,
1783 namespace: Namespace) {
1784 if !name_bindings.defined_in_namespace_with(namespace, IMPORTABLE) {
1785 let msg = format!("`{}` is not directly importable",
1786 token::get_name(name));
1787 self.session.span_err(import_span, &msg[]);
1791 /// Checks that imported names and items don't have the same name.
1792 fn check_for_conflicts_between_imports_and_items(&mut self,
1798 if self.session.features.borrow().import_shadowing {
1802 // First, check for conflicts between imports and `extern crate`s.
1803 if module.external_module_children
1805 .contains_key(&name) {
1806 match import_resolution.type_target {
1807 Some(ref target) if target.shadowable != Shadowable::Always => {
1808 let msg = format!("import `{0}` conflicts with imported \
1809 crate in this module \
1810 (maybe you meant `use {0}::*`?)",
1811 token::get_name(name).get());
1812 self.session.span_err(import_span, &msg[]);
1814 Some(_) | None => {}
1818 // Check for item conflicts.
1819 let children = module.children.borrow();
1820 let name_bindings = match children.get(&name) {
1822 // There can't be any conflicts.
1825 Some(ref name_bindings) => (*name_bindings).clone(),
1828 match import_resolution.value_target {
1829 Some(ref target) if target.shadowable != Shadowable::Always => {
1830 if let Some(ref value) = *name_bindings.value_def.borrow() {
1831 let msg = format!("import `{}` conflicts with value \
1833 token::get_name(name).get());
1834 self.session.span_err(import_span, &msg[]);
1835 if let Some(span) = value.value_span {
1836 self.session.span_note(span,
1837 "conflicting value here");
1841 Some(_) | None => {}
1844 match import_resolution.type_target {
1845 Some(ref target) if target.shadowable != Shadowable::Always => {
1846 if let Some(ref ty) = *name_bindings.type_def.borrow() {
1847 match ty.module_def {
1849 let msg = format!("import `{}` conflicts with type in \
1851 token::get_name(name).get());
1852 self.session.span_err(import_span, &msg[]);
1853 if let Some(span) = ty.type_span {
1854 self.session.span_note(span,
1855 "note conflicting type here")
1858 Some(ref module_def) => {
1859 match module_def.kind.get() {
1861 if let Some(span) = ty.type_span {
1862 let msg = format!("inherent implementations \
1863 are only allowed on types \
1864 defined in the current module");
1865 self.session.span_err(span, &msg[]);
1866 self.session.span_note(import_span,
1867 "import from other module here")
1871 let msg = format!("import `{}` conflicts with existing \
1873 token::get_name(name).get());
1874 self.session.span_err(import_span, &msg[]);
1875 if let Some(span) = ty.type_span {
1876 self.session.span_note(span,
1877 "note conflicting module here")
1885 Some(_) | None => {}
1889 /// Checks that the names of external crates don't collide with other
1890 /// external crates.
1891 fn check_for_conflicts_between_external_crates(&self,
1895 if self.session.features.borrow().import_shadowing {
1899 if module.external_module_children.borrow().contains_key(&name) {
1902 &format!("an external crate named `{}` has already \
1903 been imported into this module",
1904 token::get_name(name).get())[]);
1908 /// Checks that the names of items don't collide with external crates.
1909 fn check_for_conflicts_between_external_crates_and_items(&self,
1913 if self.session.features.borrow().import_shadowing {
1917 if module.external_module_children.borrow().contains_key(&name) {
1920 &format!("the name `{}` conflicts with an external \
1921 crate that has been imported into this \
1923 token::get_name(name).get())[]);
1927 /// Resolves the given module path from the given root `module_`.
1928 fn resolve_module_path_from_root(&mut self,
1929 module_: Rc<Module>,
1930 module_path: &[Name],
1933 name_search_type: NameSearchType,
1935 -> ResolveResult<(Rc<Module>, LastPrivate)> {
1936 fn search_parent_externals(needle: Name, module: &Rc<Module>)
1937 -> Option<Rc<Module>> {
1938 module.external_module_children.borrow()
1939 .get(&needle).cloned()
1940 .map(|_| module.clone())
1942 match module.parent_link.clone() {
1943 ModuleParentLink(parent, _) => {
1944 search_parent_externals(needle,
1945 &parent.upgrade().unwrap())
1952 let mut search_module = module_;
1953 let mut index = index;
1954 let module_path_len = module_path.len();
1955 let mut closest_private = lp;
1957 // Resolve the module part of the path. This does not involve looking
1958 // upward though scope chains; we simply resolve names directly in
1959 // modules as we go.
1960 while index < module_path_len {
1961 let name = module_path[index];
1962 match self.resolve_name_in_module(search_module.clone(),
1968 let segment_name = token::get_name(name);
1969 let module_name = self.module_to_string(&*search_module);
1970 let mut span = span;
1971 let msg = if "???" == &module_name[] {
1972 span.hi = span.lo + Pos::from_uint(segment_name.get().len());
1974 match search_parent_externals(name,
1975 &self.current_module) {
1977 let path_str = self.names_to_string(module_path);
1978 let target_mod_str = self.module_to_string(&*module);
1979 let current_mod_str =
1980 self.module_to_string(&*self.current_module);
1982 let prefix = if target_mod_str == current_mod_str {
1983 "self::".to_string()
1985 format!("{}::", target_mod_str)
1988 format!("Did you mean `{}{}`?", prefix, path_str)
1990 None => format!("Maybe a missing `extern crate {}`?",
1994 format!("Could not find `{}` in `{}`",
1999 return Failed(Some((span, msg)));
2001 Failed(err) => return Failed(err),
2003 debug!("(resolving module path for import) module \
2004 resolution is indeterminate: {}",
2005 token::get_name(name));
2006 return Indeterminate;
2008 Success((target, used_proxy)) => {
2009 // Check to see whether there are type bindings, and, if
2010 // so, whether there is a module within.
2011 match *target.bindings.type_def.borrow() {
2012 Some(ref type_def) => {
2013 match type_def.module_def {
2015 let msg = format!("Not a module `{}`",
2016 token::get_name(name));
2018 return Failed(Some((span, msg)));
2020 Some(ref module_def) => {
2021 search_module = module_def.clone();
2023 // track extern crates for unused_extern_crate lint
2024 if let Some(did) = module_def.def_id.get() {
2025 self.used_crates.insert(did.krate);
2028 // Keep track of the closest
2029 // private module used when
2030 // resolving this import chain.
2031 if !used_proxy && !search_module.is_public {
2032 if let Some(did) = search_module.def_id.get() {
2033 closest_private = LastMod(DependsOn(did));
2040 // There are no type bindings at all.
2041 let msg = format!("Not a module `{}`",
2042 token::get_name(name));
2043 return Failed(Some((span, msg)));
2052 return Success((search_module, closest_private));
2055 /// Attempts to resolve the module part of an import directive or path
2056 /// rooted at the given module.
2058 /// On success, returns the resolved module, and the closest *private*
2059 /// module found to the destination when resolving this path.
2060 fn resolve_module_path(&mut self,
2061 module_: Rc<Module>,
2062 module_path: &[Name],
2063 use_lexical_scope: UseLexicalScopeFlag,
2065 name_search_type: NameSearchType)
2066 -> ResolveResult<(Rc<Module>, LastPrivate)> {
2067 let module_path_len = module_path.len();
2068 assert!(module_path_len > 0);
2070 debug!("(resolving module path for import) processing `{}` rooted at `{}`",
2071 self.names_to_string(module_path),
2072 self.module_to_string(&*module_));
2074 // Resolve the module prefix, if any.
2075 let module_prefix_result = self.resolve_module_prefix(module_.clone(),
2081 match module_prefix_result {
2083 let mpath = self.names_to_string(module_path);
2084 let mpath = &mpath[];
2085 match mpath.rfind(':') {
2087 let msg = format!("Could not find `{}` in `{}`",
2088 // idx +- 1 to account for the
2089 // colons on either side
2090 &mpath[(idx + 1)..],
2091 &mpath[..(idx - 1)]);
2092 return Failed(Some((span, msg)));
2099 Failed(err) => return Failed(err),
2101 debug!("(resolving module path for import) indeterminate; \
2103 return Indeterminate;
2105 Success(NoPrefixFound) => {
2106 // There was no prefix, so we're considering the first element
2107 // of the path. How we handle this depends on whether we were
2108 // instructed to use lexical scope or not.
2109 match use_lexical_scope {
2110 DontUseLexicalScope => {
2111 // This is a crate-relative path. We will start the
2112 // resolution process at index zero.
2113 search_module = self.graph_root.get_module();
2115 last_private = LastMod(AllPublic);
2117 UseLexicalScope => {
2118 // This is not a crate-relative path. We resolve the
2119 // first component of the path in the current lexical
2120 // scope and then proceed to resolve below that.
2121 match self.resolve_module_in_lexical_scope(module_,
2123 Failed(err) => return Failed(err),
2125 debug!("(resolving module path for import) \
2126 indeterminate; bailing");
2127 return Indeterminate;
2129 Success(containing_module) => {
2130 search_module = containing_module;
2132 last_private = LastMod(AllPublic);
2138 Success(PrefixFound(ref containing_module, index)) => {
2139 search_module = containing_module.clone();
2140 start_index = index;
2141 last_private = LastMod(DependsOn(containing_module.def_id
2147 self.resolve_module_path_from_root(search_module,
2155 /// Invariant: This must only be called during main resolution, not during
2156 /// import resolution.
2157 fn resolve_item_in_lexical_scope(&mut self,
2158 module_: Rc<Module>,
2160 namespace: Namespace)
2161 -> ResolveResult<(Target, bool)> {
2162 debug!("(resolving item in lexical scope) resolving `{}` in \
2163 namespace {:?} in `{}`",
2164 token::get_name(name),
2166 self.module_to_string(&*module_));
2168 // The current module node is handled specially. First, check for
2169 // its immediate children.
2170 build_reduced_graph::populate_module_if_necessary(self, &module_);
2172 match module_.children.borrow().get(&name) {
2174 if name_bindings.defined_in_namespace(namespace) => {
2175 debug!("top name bindings succeeded");
2176 return Success((Target::new(module_.clone(),
2177 name_bindings.clone(),
2181 Some(_) | None => { /* Not found; continue. */ }
2184 // Now check for its import directives. We don't have to have resolved
2185 // all its imports in the usual way; this is because chains of
2186 // adjacent import statements are processed as though they mutated the
2188 if let Some(import_resolution) = module_.import_resolutions.borrow().get(&name) {
2189 match (*import_resolution).target_for_namespace(namespace) {
2191 // Not found; continue.
2192 debug!("(resolving item in lexical scope) found \
2193 import resolution, but not in namespace {:?}",
2197 debug!("(resolving item in lexical scope) using \
2198 import resolution");
2199 // track used imports and extern crates as well
2200 let id = import_resolution.id(namespace);
2201 self.used_imports.insert((id, namespace));
2202 self.record_import_use(id, name);
2203 if let Some(DefId{krate: kid, ..}) = target.target_module.def_id.get() {
2204 self.used_crates.insert(kid);
2206 return Success((target, false));
2211 // Search for external modules.
2212 if namespace == TypeNS {
2213 if let Some(module) = module_.external_module_children.borrow().get(&name).cloned() {
2215 Rc::new(Resolver::create_name_bindings_from_module(module));
2216 debug!("lower name bindings succeeded");
2217 return Success((Target::new(module_,
2224 // Finally, proceed up the scope chain looking for parent modules.
2225 let mut search_module = module_;
2227 // Go to the next parent.
2228 match search_module.parent_link.clone() {
2230 // No more parents. This module was unresolved.
2231 debug!("(resolving item in lexical scope) unresolved \
2233 return Failed(None);
2235 ModuleParentLink(parent_module_node, _) => {
2236 match search_module.kind.get() {
2237 NormalModuleKind => {
2238 // We stop the search here.
2239 debug!("(resolving item in lexical \
2240 scope) unresolved module: not \
2241 searching through module \
2243 return Failed(None);
2249 AnonymousModuleKind => {
2250 search_module = parent_module_node.upgrade().unwrap();
2254 BlockParentLink(ref parent_module_node, _) => {
2255 search_module = parent_module_node.upgrade().unwrap();
2259 // Resolve the name in the parent module.
2260 match self.resolve_name_in_module(search_module.clone(),
2265 Failed(Some((span, msg))) =>
2266 self.resolve_error(span, &format!("failed to resolve. {}",
2268 Failed(None) => (), // Continue up the search chain.
2270 // We couldn't see through the higher scope because of an
2271 // unresolved import higher up. Bail.
2273 debug!("(resolving item in lexical scope) indeterminate \
2274 higher scope; bailing");
2275 return Indeterminate;
2277 Success((target, used_reexport)) => {
2278 // We found the module.
2279 debug!("(resolving item in lexical scope) found name \
2281 return Success((target, used_reexport));
2287 /// Resolves a module name in the current lexical scope.
2288 fn resolve_module_in_lexical_scope(&mut self,
2289 module_: Rc<Module>,
2291 -> ResolveResult<Rc<Module>> {
2292 // If this module is an anonymous module, resolve the item in the
2293 // lexical scope. Otherwise, resolve the item from the crate root.
2294 let resolve_result = self.resolve_item_in_lexical_scope(module_, name, TypeNS);
2295 match resolve_result {
2296 Success((target, _)) => {
2297 let bindings = &*target.bindings;
2298 match *bindings.type_def.borrow() {
2299 Some(ref type_def) => {
2300 match type_def.module_def {
2302 debug!("!!! (resolving module in lexical \
2303 scope) module wasn't actually a \
2305 return Failed(None);
2307 Some(ref module_def) => {
2308 return Success(module_def.clone());
2313 debug!("!!! (resolving module in lexical scope) module
2314 wasn't actually a module!");
2315 return Failed(None);
2320 debug!("(resolving module in lexical scope) indeterminate; \
2322 return Indeterminate;
2325 debug!("(resolving module in lexical scope) failed to resolve");
2331 /// Returns the nearest normal module parent of the given module.
2332 fn get_nearest_normal_module_parent(&mut self, module_: Rc<Module>)
2333 -> Option<Rc<Module>> {
2334 let mut module_ = module_;
2336 match module_.parent_link.clone() {
2337 NoParentLink => return None,
2338 ModuleParentLink(new_module, _) |
2339 BlockParentLink(new_module, _) => {
2340 let new_module = new_module.upgrade().unwrap();
2341 match new_module.kind.get() {
2342 NormalModuleKind => return Some(new_module),
2347 AnonymousModuleKind => module_ = new_module,
2354 /// Returns the nearest normal module parent of the given module, or the
2355 /// module itself if it is a normal module.
2356 fn get_nearest_normal_module_parent_or_self(&mut self, module_: Rc<Module>)
2358 match module_.kind.get() {
2359 NormalModuleKind => return module_,
2364 AnonymousModuleKind => {
2365 match self.get_nearest_normal_module_parent(module_.clone()) {
2367 Some(new_module) => new_module
2373 /// Resolves a "module prefix". A module prefix is one or both of (a) `self::`;
2374 /// (b) some chain of `super::`.
2375 /// grammar: (SELF MOD_SEP ) ? (SUPER MOD_SEP) *
2376 fn resolve_module_prefix(&mut self,
2377 module_: Rc<Module>,
2378 module_path: &[Name])
2379 -> ResolveResult<ModulePrefixResult> {
2380 // Start at the current module if we see `self` or `super`, or at the
2381 // top of the crate otherwise.
2382 let mut containing_module;
2384 let first_module_path_string = token::get_name(module_path[0]);
2385 if "self" == first_module_path_string.get() {
2387 self.get_nearest_normal_module_parent_or_self(module_);
2389 } else if "super" == first_module_path_string.get() {
2391 self.get_nearest_normal_module_parent_or_self(module_);
2392 i = 0; // We'll handle `super` below.
2394 return Success(NoPrefixFound);
2397 // Now loop through all the `super`s we find.
2398 while i < module_path.len() {
2399 let string = token::get_name(module_path[i]);
2400 if "super" != string.get() {
2403 debug!("(resolving module prefix) resolving `super` at {}",
2404 self.module_to_string(&*containing_module));
2405 match self.get_nearest_normal_module_parent(containing_module) {
2406 None => return Failed(None),
2407 Some(new_module) => {
2408 containing_module = new_module;
2414 debug!("(resolving module prefix) finished resolving prefix at {}",
2415 self.module_to_string(&*containing_module));
2417 return Success(PrefixFound(containing_module, i));
2420 /// Attempts to resolve the supplied name in the given module for the
2421 /// given namespace. If successful, returns the target corresponding to
2424 /// The boolean returned on success is an indicator of whether this lookup
2425 /// passed through a public re-export proxy.
2426 fn resolve_name_in_module(&mut self,
2427 module_: Rc<Module>,
2429 namespace: Namespace,
2430 name_search_type: NameSearchType,
2431 allow_private_imports: bool)
2432 -> ResolveResult<(Target, bool)> {
2433 debug!("(resolving name in module) resolving `{}` in `{}`",
2434 token::get_name(name).get(),
2435 self.module_to_string(&*module_));
2437 // First, check the direct children of the module.
2438 build_reduced_graph::populate_module_if_necessary(self, &module_);
2440 match module_.children.borrow().get(&name) {
2442 if name_bindings.defined_in_namespace(namespace) => {
2443 debug!("(resolving name in module) found node as child");
2444 return Success((Target::new(module_.clone(),
2445 name_bindings.clone(),
2454 // Next, check the module's imports if necessary.
2456 // If this is a search of all imports, we should be done with glob
2457 // resolution at this point.
2458 if name_search_type == PathSearch {
2459 assert_eq!(module_.glob_count.get(), 0);
2462 // Check the list of resolved imports.
2463 match module_.import_resolutions.borrow().get(&name) {
2464 Some(import_resolution) if allow_private_imports ||
2465 import_resolution.is_public => {
2467 if import_resolution.is_public &&
2468 import_resolution.outstanding_references != 0 {
2469 debug!("(resolving name in module) import \
2470 unresolved; bailing out");
2471 return Indeterminate;
2473 match import_resolution.target_for_namespace(namespace) {
2475 debug!("(resolving name in module) name found, \
2476 but not in namespace {:?}",
2480 debug!("(resolving name in module) resolved to \
2482 // track used imports and extern crates as well
2483 let id = import_resolution.id(namespace);
2484 self.used_imports.insert((id, namespace));
2485 self.record_import_use(id, name);
2486 if let Some(DefId{krate: kid, ..}) = target.target_module.def_id.get() {
2487 self.used_crates.insert(kid);
2489 return Success((target, true));
2493 Some(..) | None => {} // Continue.
2496 // Finally, search through external children.
2497 if namespace == TypeNS {
2498 if let Some(module) = module_.external_module_children.borrow().get(&name).cloned() {
2500 Rc::new(Resolver::create_name_bindings_from_module(module));
2501 return Success((Target::new(module_,
2508 // We're out of luck.
2509 debug!("(resolving name in module) failed to resolve `{}`",
2510 token::get_name(name).get());
2511 return Failed(None);
2514 fn report_unresolved_imports(&mut self, module_: Rc<Module>) {
2515 let index = module_.resolved_import_count.get();
2516 let imports = module_.imports.borrow();
2517 let import_count = imports.len();
2518 if index != import_count {
2519 let sn = self.session
2521 .span_to_snippet((*imports)[index].span)
2523 if sn.contains("::") {
2524 self.resolve_error((*imports)[index].span,
2525 "unresolved import");
2527 let err = format!("unresolved import (maybe you meant `{}::*`?)",
2529 self.resolve_error((*imports)[index].span, &err[]);
2533 // Descend into children and anonymous children.
2534 build_reduced_graph::populate_module_if_necessary(self, &module_);
2536 for (_, child_node) in module_.children.borrow().iter() {
2537 match child_node.get_module_if_available() {
2541 Some(child_module) => {
2542 self.report_unresolved_imports(child_module);
2547 for (_, module_) in module_.anonymous_children.borrow().iter() {
2548 self.report_unresolved_imports(module_.clone());
2554 // We maintain a list of value ribs and type ribs.
2556 // Simultaneously, we keep track of the current position in the module
2557 // graph in the `current_module` pointer. When we go to resolve a name in
2558 // the value or type namespaces, we first look through all the ribs and
2559 // then query the module graph. When we resolve a name in the module
2560 // namespace, we can skip all the ribs (since nested modules are not
2561 // allowed within blocks in Rust) and jump straight to the current module
2564 // Named implementations are handled separately. When we find a method
2565 // call, we consult the module node to find all of the implementations in
2566 // scope. This information is lazily cached in the module node. We then
2567 // generate a fake "implementation scope" containing all the
2568 // implementations thus found, for compatibility with old resolve pass.
2570 fn with_scope<F>(&mut self, name: Option<Name>, f: F) where
2571 F: FnOnce(&mut Resolver),
2573 let orig_module = self.current_module.clone();
2575 // Move down in the graph.
2581 build_reduced_graph::populate_module_if_necessary(self, &orig_module);
2583 match orig_module.children.borrow().get(&name) {
2585 debug!("!!! (with scope) didn't find `{}` in `{}`",
2586 token::get_name(name),
2587 self.module_to_string(&*orig_module));
2589 Some(name_bindings) => {
2590 match (*name_bindings).get_module_if_available() {
2592 debug!("!!! (with scope) didn't find module \
2594 token::get_name(name),
2595 self.module_to_string(&*orig_module));
2598 self.current_module = module_;
2608 self.current_module = orig_module;
2611 /// Wraps the given definition in the appropriate number of `DefUpvar`
2617 -> Option<DefLike> {
2619 DlDef(d @ DefUpvar(..)) => {
2620 self.session.span_bug(span,
2621 &format!("unexpected {:?} in bindings", d)[])
2623 DlDef(d @ DefLocal(_)) => {
2624 let node_id = d.def_id().node;
2626 let mut last_proc_body_id = ast::DUMMY_NODE_ID;
2627 for rib in ribs.iter() {
2630 // Nothing to do. Continue.
2632 ClosureRibKind(function_id, maybe_proc_body) => {
2634 if maybe_proc_body != ast::DUMMY_NODE_ID {
2635 last_proc_body_id = maybe_proc_body;
2637 def = DefUpvar(node_id, function_id, last_proc_body_id);
2639 let mut seen = self.freevars_seen.borrow_mut();
2640 let seen = match seen.entry(function_id) {
2641 Occupied(v) => v.into_mut(),
2642 Vacant(v) => v.insert(NodeSet()),
2644 if seen.contains(&node_id) {
2647 match self.freevars.borrow_mut().entry(function_id) {
2648 Occupied(v) => v.into_mut(),
2649 Vacant(v) => v.insert(vec![]),
2650 }.push(Freevar { def: prev_def, span: span });
2651 seen.insert(node_id);
2653 MethodRibKind(item_id, _) => {
2654 // If the def is a ty param, and came from the parent
2657 DefTyParam(_, _, did, _) if {
2658 self.def_map.borrow().get(&did.node).cloned()
2659 == Some(DefTyParamBinder(item_id))
2661 DefSelfTy(did) if did == item_id => {} // ok
2663 // This was an attempt to access an upvar inside a
2664 // named function item. This is not allowed, so we
2669 "can't capture dynamic environment in a fn item; \
2670 use the || { ... } closure form instead");
2677 // This was an attempt to access an upvar inside a
2678 // named function item. This is not allowed, so we
2683 "can't capture dynamic environment in a fn item; \
2684 use the || { ... } closure form instead");
2688 ConstantItemRibKind => {
2689 // Still doesn't deal with upvars
2690 self.resolve_error(span,
2691 "attempt to use a non-constant \
2692 value in a constant");
2699 DlDef(def @ DefTyParam(..)) |
2700 DlDef(def @ DefSelfTy(..)) => {
2701 for rib in ribs.iter() {
2703 NormalRibKind | ClosureRibKind(..) => {
2704 // Nothing to do. Continue.
2706 MethodRibKind(item_id, _) => {
2707 // If the def is a ty param, and came from the parent
2710 DefTyParam(_, _, did, _) if {
2711 self.def_map.borrow().get(&did.node).cloned()
2712 == Some(DefTyParamBinder(item_id))
2714 DefSelfTy(did) if did == item_id => {} // ok
2717 // This was an attempt to use a type parameter outside
2720 self.resolve_error(span,
2721 "can't use type parameters from \
2722 outer function; try using a local \
2723 type parameter instead");
2730 // This was an attempt to use a type parameter outside
2733 self.resolve_error(span,
2734 "can't use type parameters from \
2735 outer function; try using a local \
2736 type parameter instead");
2740 ConstantItemRibKind => {
2742 self.resolve_error(span,
2743 "cannot use an outer type \
2744 parameter in this context");
2755 /// Searches the current set of local scopes and
2756 /// applies translations for closures.
2757 fn search_ribs(&self,
2761 -> Option<DefLike> {
2762 // FIXME #4950: Try caching?
2764 for (i, rib) in ribs.iter().enumerate().rev() {
2765 match rib.bindings.get(&name).cloned() {
2767 return self.upvarify(&ribs[(i + 1)..], def_like, span);
2778 /// Searches the current set of local scopes for labels.
2779 /// Stops after meeting a closure.
2780 fn search_label(&self, name: Name) -> Option<DefLike> {
2781 for rib in self.label_ribs.iter().rev() {
2787 // Do not resolve labels across function boundary
2791 let result = rib.bindings.get(&name).cloned();
2792 if result.is_some() {
2799 fn resolve_crate(&mut self, krate: &ast::Crate) {
2800 debug!("(resolving crate) starting");
2802 visit::walk_crate(self, krate);
2805 fn resolve_item(&mut self, item: &Item) {
2806 let name = item.ident.name;
2808 debug!("(resolving item) resolving {}",
2809 token::get_name(name));
2813 // enum item: resolve all the variants' discrs,
2814 // then resolve the ty params
2815 ItemEnum(ref enum_def, ref generics) => {
2816 for variant in (*enum_def).variants.iter() {
2817 for dis_expr in variant.node.disr_expr.iter() {
2818 // resolve the discriminator expr
2820 self.with_constant_rib(|this| {
2821 this.resolve_expr(&**dis_expr);
2826 // n.b. the discr expr gets visited twice.
2827 // but maybe it's okay since the first time will signal an
2828 // error if there is one? -- tjc
2829 self.with_type_parameter_rib(HasTypeParameters(generics,
2834 this.resolve_type_parameters(&generics.ty_params);
2835 this.resolve_where_clause(&generics.where_clause);
2836 visit::walk_item(this, item);
2840 ItemTy(_, ref generics) => {
2841 self.with_type_parameter_rib(HasTypeParameters(generics,
2846 this.resolve_type_parameters(&generics.ty_params);
2847 visit::walk_item(this, item);
2853 ref implemented_traits,
2855 ref impl_items) => {
2856 self.resolve_implementation(item.id,
2863 ItemTrait(_, ref generics, ref bounds, ref trait_items) => {
2864 // Create a new rib for the self type.
2865 let mut self_type_rib = Rib::new(ItemRibKind);
2867 // plain insert (no renaming, types are not currently hygienic....)
2868 let name = self.type_self_name;
2869 self_type_rib.bindings.insert(name, DlDef(DefSelfTy(item.id)));
2870 self.type_ribs.push(self_type_rib);
2872 // Create a new rib for the trait-wide type parameters.
2873 self.with_type_parameter_rib(HasTypeParameters(generics,
2878 this.resolve_type_parameters(&generics.ty_params);
2879 this.resolve_where_clause(&generics.where_clause);
2881 this.resolve_type_parameter_bounds(item.id, bounds,
2884 for trait_item in (*trait_items).iter() {
2885 // Create a new rib for the trait_item-specific type
2888 // FIXME #4951: Do we need a node ID here?
2891 ast::RequiredMethod(ref ty_m) => {
2892 this.with_type_parameter_rib
2893 (HasTypeParameters(&ty_m.generics,
2896 MethodRibKind(item.id, RequiredMethod)),
2899 // Resolve the method-specific type
2901 this.resolve_type_parameters(
2902 &ty_m.generics.ty_params);
2903 this.resolve_where_clause(&ty_m.generics
2906 for argument in ty_m.decl.inputs.iter() {
2907 this.resolve_type(&*argument.ty);
2910 if let SelfExplicit(ref typ, _) = ty_m.explicit_self.node {
2911 this.resolve_type(&**typ)
2914 if let ast::Return(ref ret_ty) = ty_m.decl.output {
2915 this.resolve_type(&**ret_ty);
2919 ast::ProvidedMethod(ref m) => {
2920 this.resolve_method(MethodRibKind(item.id,
2921 ProvidedMethod(m.id)),
2924 ast::TypeTraitItem(ref data) => {
2925 this.resolve_type_parameter(&data.ty_param);
2926 visit::walk_trait_item(this, trait_item);
2932 self.type_ribs.pop();
2935 ItemStruct(ref struct_def, ref generics) => {
2936 self.resolve_struct(item.id,
2938 &struct_def.fields[]);
2941 ItemMod(ref module_) => {
2942 self.with_scope(Some(name), |this| {
2943 this.resolve_module(module_, item.span, name,
2948 ItemForeignMod(ref foreign_module) => {
2949 self.with_scope(Some(name), |this| {
2950 for foreign_item in foreign_module.items.iter() {
2951 match foreign_item.node {
2952 ForeignItemFn(_, ref generics) => {
2953 this.with_type_parameter_rib(
2955 generics, FnSpace, foreign_item.id,
2958 this.resolve_type_parameters(&generics.ty_params);
2959 this.resolve_where_clause(&generics.where_clause);
2960 visit::walk_foreign_item(this, &**foreign_item)
2963 ForeignItemStatic(..) => {
2964 visit::walk_foreign_item(this,
2972 ItemFn(ref fn_decl, _, _, ref generics, ref block) => {
2973 self.resolve_function(ItemRibKind,
2983 ItemConst(..) | ItemStatic(..) => {
2984 self.with_constant_rib(|this| {
2985 visit::walk_item(this, item);
2990 // do nothing, these are just around to be encoded
2995 fn with_type_parameter_rib<F>(&mut self, type_parameters: TypeParameters, f: F) where
2996 F: FnOnce(&mut Resolver),
2998 match type_parameters {
2999 HasTypeParameters(generics, space, node_id, rib_kind) => {
3000 let mut function_type_rib = Rib::new(rib_kind);
3001 let mut seen_bindings = HashSet::new();
3002 for (index, type_parameter) in generics.ty_params.iter().enumerate() {
3003 let name = type_parameter.ident.name;
3004 debug!("with_type_parameter_rib: {} {}", node_id,
3007 if seen_bindings.contains(&name) {
3008 self.resolve_error(type_parameter.span,
3009 &format!("the name `{}` is already \
3011 parameter in this type \
3016 seen_bindings.insert(name);
3018 let def_like = DlDef(DefTyParam(space,
3020 local_def(type_parameter.id),
3022 // Associate this type parameter with
3023 // the item that bound it
3024 self.record_def(type_parameter.id,
3025 (DefTyParamBinder(node_id), LastMod(AllPublic)));
3026 // plain insert (no renaming)
3027 function_type_rib.bindings.insert(name, def_like);
3029 self.type_ribs.push(function_type_rib);
3032 NoTypeParameters => {
3039 match type_parameters {
3040 HasTypeParameters(..) => { self.type_ribs.pop(); }
3041 NoTypeParameters => { }
3045 fn with_label_rib<F>(&mut self, f: F) where
3046 F: FnOnce(&mut Resolver),
3048 self.label_ribs.push(Rib::new(NormalRibKind));
3050 self.label_ribs.pop();
3053 fn with_constant_rib<F>(&mut self, f: F) where
3054 F: FnOnce(&mut Resolver),
3056 self.value_ribs.push(Rib::new(ConstantItemRibKind));
3057 self.type_ribs.push(Rib::new(ConstantItemRibKind));
3059 self.type_ribs.pop();
3060 self.value_ribs.pop();
3063 fn resolve_function(&mut self,
3065 optional_declaration: Option<&FnDecl>,
3066 type_parameters: TypeParameters,
3068 // Create a value rib for the function.
3069 let function_value_rib = Rib::new(rib_kind);
3070 self.value_ribs.push(function_value_rib);
3072 // Create a label rib for the function.
3073 let function_label_rib = Rib::new(rib_kind);
3074 self.label_ribs.push(function_label_rib);
3076 // If this function has type parameters, add them now.
3077 self.with_type_parameter_rib(type_parameters, |this| {
3078 // Resolve the type parameters.
3079 match type_parameters {
3080 NoTypeParameters => {
3083 HasTypeParameters(ref generics, _, _, _) => {
3084 this.resolve_type_parameters(&generics.ty_params);
3085 this.resolve_where_clause(&generics.where_clause);
3089 // Add each argument to the rib.
3090 match optional_declaration {
3094 Some(declaration) => {
3095 let mut bindings_list = HashMap::new();
3096 for argument in declaration.inputs.iter() {
3097 this.resolve_pattern(&*argument.pat,
3098 ArgumentIrrefutableMode,
3099 &mut bindings_list);
3101 this.resolve_type(&*argument.ty);
3103 debug!("(resolving function) recorded argument");
3106 if let ast::Return(ref ret_ty) = declaration.output {
3107 this.resolve_type(&**ret_ty);
3112 // Resolve the function body.
3113 this.resolve_block(&*block);
3115 debug!("(resolving function) leaving function");
3118 self.label_ribs.pop();
3119 self.value_ribs.pop();
3122 fn resolve_type_parameters(&mut self,
3123 type_parameters: &OwnedSlice<TyParam>) {
3124 for type_parameter in type_parameters.iter() {
3125 self.resolve_type_parameter(type_parameter);
3129 fn resolve_type_parameter(&mut self,
3130 type_parameter: &TyParam) {
3131 for bound in type_parameter.bounds.iter() {
3132 self.resolve_type_parameter_bound(type_parameter.id, bound,
3133 TraitBoundingTypeParameter);
3135 match type_parameter.default {
3136 Some(ref ty) => self.resolve_type(&**ty),
3141 fn resolve_type_parameter_bounds(&mut self,
3143 type_parameter_bounds: &OwnedSlice<TyParamBound>,
3144 reference_type: TraitReferenceType) {
3145 for type_parameter_bound in type_parameter_bounds.iter() {
3146 self.resolve_type_parameter_bound(id, type_parameter_bound,
3151 fn resolve_type_parameter_bound(&mut self,
3153 type_parameter_bound: &TyParamBound,
3154 reference_type: TraitReferenceType) {
3155 match *type_parameter_bound {
3156 TraitTyParamBound(ref tref, _) => {
3157 self.resolve_poly_trait_reference(id, tref, reference_type)
3159 RegionTyParamBound(..) => {}
3163 fn resolve_poly_trait_reference(&mut self,
3165 poly_trait_reference: &PolyTraitRef,
3166 reference_type: TraitReferenceType) {
3167 self.resolve_trait_reference(id, &poly_trait_reference.trait_ref, reference_type)
3170 fn resolve_trait_reference(&mut self,
3172 trait_reference: &TraitRef,
3173 reference_type: TraitReferenceType) {
3174 match self.resolve_path(id, &trait_reference.path, TypeNS, true) {
3176 let path_str = self.path_names_to_string(&trait_reference.path);
3177 let usage_str = match reference_type {
3178 TraitBoundingTypeParameter => "bound type parameter with",
3179 TraitImplementation => "implement",
3180 TraitDerivation => "derive",
3181 TraitObject => "reference",
3182 TraitQPath => "extract an associated item from",
3185 let msg = format!("attempt to {} a nonexistent trait `{}`", usage_str, path_str);
3186 self.resolve_error(trait_reference.path.span, &msg[]);
3190 (DefTrait(_), _) => {
3191 debug!("(resolving trait) found trait def: {:?}", def);
3192 self.record_def(trait_reference.ref_id, def);
3195 self.resolve_error(trait_reference.path.span,
3196 &format!("`{}` is not a trait",
3197 self.path_names_to_string(
3198 &trait_reference.path))[]);
3200 // If it's a typedef, give a note
3201 if let DefTy(..) = def {
3202 self.session.span_note(
3203 trait_reference.path.span,
3204 &format!("`type` aliases cannot be used for traits")
3213 fn resolve_where_clause(&mut self, where_clause: &ast::WhereClause) {
3214 for predicate in where_clause.predicates.iter() {
3216 &ast::WherePredicate::BoundPredicate(ref bound_pred) => {
3217 self.resolve_type(&*bound_pred.bounded_ty);
3219 for bound in bound_pred.bounds.iter() {
3220 self.resolve_type_parameter_bound(bound_pred.bounded_ty.id, bound,
3221 TraitBoundingTypeParameter);
3224 &ast::WherePredicate::RegionPredicate(_) => {}
3225 &ast::WherePredicate::EqPredicate(ref eq_pred) => {
3226 match self.resolve_path(eq_pred.id, &eq_pred.path, TypeNS, true) {
3227 Some((def @ DefTyParam(..), last_private)) => {
3228 self.record_def(eq_pred.id, (def, last_private));
3231 self.resolve_error(eq_pred.path.span,
3232 "undeclared associated type");
3236 self.resolve_type(&*eq_pred.ty);
3242 fn resolve_struct(&mut self,
3244 generics: &Generics,
3245 fields: &[StructField]) {
3246 // If applicable, create a rib for the type parameters.
3247 self.with_type_parameter_rib(HasTypeParameters(generics,
3252 // Resolve the type parameters.
3253 this.resolve_type_parameters(&generics.ty_params);
3254 this.resolve_where_clause(&generics.where_clause);
3257 for field in fields.iter() {
3258 this.resolve_type(&*field.node.ty);
3263 // Does this really need to take a RibKind or is it always going
3264 // to be NormalRibKind?
3265 fn resolve_method(&mut self,
3267 method: &ast::Method) {
3268 let method_generics = method.pe_generics();
3269 let type_parameters = HasTypeParameters(method_generics,
3274 if let SelfExplicit(ref typ, _) = method.pe_explicit_self().node {
3275 self.resolve_type(&**typ);
3278 self.resolve_function(rib_kind,
3279 Some(method.pe_fn_decl()),
3284 fn with_current_self_type<T, F>(&mut self, self_type: &Ty, f: F) -> T where
3285 F: FnOnce(&mut Resolver) -> T,
3287 // Handle nested impls (inside fn bodies)
3288 let previous_value = replace(&mut self.current_self_type, Some(self_type.clone()));
3289 let result = f(self);
3290 self.current_self_type = previous_value;
3294 fn with_optional_trait_ref<T, F>(&mut self, id: NodeId,
3295 opt_trait_ref: &Option<TraitRef>,
3297 F: FnOnce(&mut Resolver) -> T,
3299 let new_val = match *opt_trait_ref {
3300 Some(ref trait_ref) => {
3301 self.resolve_trait_reference(id, trait_ref, TraitImplementation);
3303 match self.def_map.borrow().get(&trait_ref.ref_id) {
3305 let did = def.def_id();
3306 Some((did, trait_ref.clone()))
3313 let original_trait_ref = replace(&mut self.current_trait_ref, new_val);
3314 let result = f(self);
3315 self.current_trait_ref = original_trait_ref;
3319 fn resolve_implementation(&mut self,
3321 generics: &Generics,
3322 opt_trait_reference: &Option<TraitRef>,
3324 impl_items: &[ImplItem]) {
3325 // If applicable, create a rib for the type parameters.
3326 self.with_type_parameter_rib(HasTypeParameters(generics,
3331 // Resolve the type parameters.
3332 this.resolve_type_parameters(&generics.ty_params);
3333 this.resolve_where_clause(&generics.where_clause);
3335 // Resolve the trait reference, if necessary.
3336 this.with_optional_trait_ref(id, opt_trait_reference, |this| {
3337 // Resolve the self type.
3338 this.resolve_type(self_type);
3340 this.with_current_self_type(self_type, |this| {
3341 for impl_item in impl_items.iter() {
3343 MethodImplItem(ref method) => {
3344 // If this is a trait impl, ensure the method
3346 this.check_trait_item(method.pe_ident().name,
3349 // We also need a new scope for the method-
3350 // specific type parameters.
3351 this.resolve_method(
3352 MethodRibKind(id, ProvidedMethod(method.id)),
3355 TypeImplItem(ref typedef) => {
3356 // If this is a trait impl, ensure the method
3358 this.check_trait_item(typedef.ident.name,
3361 this.resolve_type(&*typedef.typ);
3369 // Check that the current type is indeed a type, if we have an anonymous impl
3370 if opt_trait_reference.is_none() {
3371 match self_type.node {
3372 // TyPath is the only thing that we handled in `build_reduced_graph_for_item`,
3373 // where we created a module with the name of the type in order to implement
3374 // an anonymous trait. In the case that the path does not resolve to an actual
3375 // type, the result will be that the type name resolves to a module but not
3376 // a type (shadowing any imported modules or types with this name), leading
3377 // to weird user-visible bugs. So we ward this off here. See #15060.
3378 TyPath(ref path, path_id) => {
3379 match self.def_map.borrow().get(&path_id) {
3380 // FIXME: should we catch other options and give more precise errors?
3381 Some(&DefMod(_)) => {
3382 self.resolve_error(path.span, "inherent implementations are not \
3383 allowed for types not defined in \
3384 the current module");
3394 fn check_trait_item(&self, name: Name, span: Span) {
3395 // If there is a TraitRef in scope for an impl, then the method must be in the trait.
3396 for &(did, ref trait_ref) in self.current_trait_ref.iter() {
3397 if self.trait_item_map.get(&(name, did)).is_none() {
3398 let path_str = self.path_names_to_string(&trait_ref.path);
3399 self.resolve_error(span,
3400 &format!("method `{}` is not a member of trait `{}`",
3401 token::get_name(name),
3407 fn resolve_module(&mut self, module: &Mod, _span: Span,
3408 _name: Name, id: NodeId) {
3409 // Write the implementations in scope into the module metadata.
3410 debug!("(resolving module) resolving module ID {}", id);
3411 visit::walk_mod(self, module);
3414 fn resolve_local(&mut self, local: &Local) {
3415 // Resolve the type.
3416 if let Some(ref ty) = local.ty {
3417 self.resolve_type(&**ty);
3420 // Resolve the initializer, if necessary.
3425 Some(ref initializer) => {
3426 self.resolve_expr(&**initializer);
3430 // Resolve the pattern.
3431 let mut bindings_list = HashMap::new();
3432 self.resolve_pattern(&*local.pat,
3433 LocalIrrefutableMode,
3434 &mut bindings_list);
3437 // build a map from pattern identifiers to binding-info's.
3438 // this is done hygienically. This could arise for a macro
3439 // that expands into an or-pattern where one 'x' was from the
3440 // user and one 'x' came from the macro.
3441 fn binding_mode_map(&mut self, pat: &Pat) -> BindingMap {
3442 let mut result = HashMap::new();
3443 pat_bindings(&self.def_map, pat, |binding_mode, _id, sp, path1| {
3444 let name = mtwt::resolve(path1.node);
3445 result.insert(name, BindingInfo {
3447 binding_mode: binding_mode
3453 // check that all of the arms in an or-pattern have exactly the
3454 // same set of bindings, with the same binding modes for each.
3455 fn check_consistent_bindings(&mut self, arm: &Arm) {
3456 if arm.pats.len() == 0 {
3459 let map_0 = self.binding_mode_map(&*arm.pats[0]);
3460 for (i, p) in arm.pats.iter().enumerate() {
3461 let map_i = self.binding_mode_map(&**p);
3463 for (&key, &binding_0) in map_0.iter() {
3464 match map_i.get(&key) {
3468 &format!("variable `{}` from pattern #1 is \
3469 not bound in pattern #{}",
3470 token::get_name(key),
3473 Some(binding_i) => {
3474 if binding_0.binding_mode != binding_i.binding_mode {
3477 &format!("variable `{}` is bound with different \
3478 mode in pattern #{} than in pattern #1",
3479 token::get_name(key),
3486 for (&key, &binding) in map_i.iter() {
3487 if !map_0.contains_key(&key) {
3490 &format!("variable `{}` from pattern {}{} is \
3491 not bound in pattern {}1",
3492 token::get_name(key),
3493 "#", i + 1, "#")[]);
3499 fn resolve_arm(&mut self, arm: &Arm) {
3500 self.value_ribs.push(Rib::new(NormalRibKind));
3502 let mut bindings_list = HashMap::new();
3503 for pattern in arm.pats.iter() {
3504 self.resolve_pattern(&**pattern, RefutableMode, &mut bindings_list);
3507 // This has to happen *after* we determine which
3508 // pat_idents are variants
3509 self.check_consistent_bindings(arm);
3511 visit::walk_expr_opt(self, &arm.guard);
3512 self.resolve_expr(&*arm.body);
3514 self.value_ribs.pop();
3517 fn resolve_block(&mut self, block: &Block) {
3518 debug!("(resolving block) entering block");
3519 self.value_ribs.push(Rib::new(NormalRibKind));
3521 // Move down in the graph, if there's an anonymous module rooted here.
3522 let orig_module = self.current_module.clone();
3523 match orig_module.anonymous_children.borrow().get(&block.id) {
3524 None => { /* Nothing to do. */ }
3525 Some(anonymous_module) => {
3526 debug!("(resolving block) found anonymous module, moving \
3528 self.current_module = anonymous_module.clone();
3532 // Descend into the block.
3533 visit::walk_block(self, block);
3536 self.current_module = orig_module;
3538 self.value_ribs.pop();
3539 debug!("(resolving block) leaving block");
3542 fn resolve_type(&mut self, ty: &Ty) {
3544 // Like path expressions, the interpretation of path types depends
3545 // on whether the path has multiple elements in it or not.
3547 TyPath(ref path, path_id) => {
3548 // This is a path in the type namespace. Walk through scopes
3550 let mut result_def = None;
3552 // First, check to see whether the name is a primitive type.
3553 if path.segments.len() == 1 {
3554 let id = path.segments.last().unwrap().identifier;
3556 match self.primitive_type_table
3560 Some(&primitive_type) => {
3562 Some((DefPrimTy(primitive_type), LastMod(AllPublic)));
3564 if path.segments[0].parameters.has_lifetimes() {
3565 span_err!(self.session, path.span, E0157,
3566 "lifetime parameters are not allowed on this type");
3567 } else if !path.segments[0].parameters.is_empty() {
3568 span_err!(self.session, path.span, E0153,
3569 "type parameters are not allowed on this type");
3578 if let None = result_def {
3579 result_def = self.resolve_path(ty.id, path, TypeNS, true);
3584 // Write the result into the def map.
3585 debug!("(resolving type) writing resolution for `{}` \
3587 self.path_names_to_string(path),
3589 self.record_def(path_id, def);
3592 let msg = format!("use of undeclared type name `{}`",
3593 self.path_names_to_string(path));
3594 self.resolve_error(ty.span, &msg[]);
3599 TyObjectSum(ref ty, ref bound_vec) => {
3600 self.resolve_type(&**ty);
3601 self.resolve_type_parameter_bounds(ty.id, bound_vec,
3602 TraitBoundingTypeParameter);
3605 TyQPath(ref qpath) => {
3606 self.resolve_type(&*qpath.self_type);
3607 self.resolve_trait_reference(ty.id, &*qpath.trait_ref, TraitQPath);
3608 for ty in qpath.item_path.parameters.types().into_iter() {
3609 self.resolve_type(&**ty);
3611 for binding in qpath.item_path.parameters.bindings().into_iter() {
3612 self.resolve_type(&*binding.ty);
3616 TyPolyTraitRef(ref bounds) => {
3617 self.resolve_type_parameter_bounds(
3621 visit::walk_ty(self, ty);
3624 // Just resolve embedded types.
3625 visit::walk_ty(self, ty);
3630 fn resolve_pattern(&mut self,
3632 mode: PatternBindingMode,
3633 // Maps idents to the node ID for the (outermost)
3634 // pattern that binds them
3635 bindings_list: &mut HashMap<Name, NodeId>) {
3636 let pat_id = pattern.id;
3637 walk_pat(pattern, |pattern| {
3638 match pattern.node {
3639 PatIdent(binding_mode, ref path1, _) => {
3641 // The meaning of pat_ident with no type parameters
3642 // depends on whether an enum variant or unit-like struct
3643 // with that name is in scope. The probing lookup has to
3644 // be careful not to emit spurious errors. Only matching
3645 // patterns (match) can match nullary variants or
3646 // unit-like structs. For binding patterns (let), matching
3647 // such a value is simply disallowed (since it's rarely
3650 let ident = path1.node;
3651 let renamed = mtwt::resolve(ident);
3653 match self.resolve_bare_identifier_pattern(ident.name, pattern.span) {
3654 FoundStructOrEnumVariant(ref def, lp)
3655 if mode == RefutableMode => {
3656 debug!("(resolving pattern) resolving `{}` to \
3657 struct or enum variant",
3658 token::get_name(renamed));
3660 self.enforce_default_binding_mode(
3664 self.record_def(pattern.id, (def.clone(), lp));
3666 FoundStructOrEnumVariant(..) => {
3669 &format!("declaration of `{}` shadows an enum \
3670 variant or unit-like struct in \
3672 token::get_name(renamed))[]);
3674 FoundConst(ref def, lp) if mode == RefutableMode => {
3675 debug!("(resolving pattern) resolving `{}` to \
3677 token::get_name(renamed));
3679 self.enforce_default_binding_mode(
3683 self.record_def(pattern.id, (def.clone(), lp));
3686 self.resolve_error(pattern.span,
3687 "only irrefutable patterns \
3690 BareIdentifierPatternUnresolved => {
3691 debug!("(resolving pattern) binding `{}`",
3692 token::get_name(renamed));
3694 let def = DefLocal(pattern.id);
3696 // Record the definition so that later passes
3697 // will be able to distinguish variants from
3698 // locals in patterns.
3700 self.record_def(pattern.id, (def, LastMod(AllPublic)));
3702 // Add the binding to the local ribs, if it
3703 // doesn't already exist in the bindings list. (We
3704 // must not add it if it's in the bindings list
3705 // because that breaks the assumptions later
3706 // passes make about or-patterns.)
3707 if !bindings_list.contains_key(&renamed) {
3708 let this = &mut *self;
3709 let last_rib = this.value_ribs.last_mut().unwrap();
3710 last_rib.bindings.insert(renamed, DlDef(def));
3711 bindings_list.insert(renamed, pat_id);
3712 } else if mode == ArgumentIrrefutableMode &&
3713 bindings_list.contains_key(&renamed) {
3714 // Forbid duplicate bindings in the same
3716 self.resolve_error(pattern.span,
3717 &format!("identifier `{}` \
3725 } else if bindings_list.get(&renamed) ==
3727 // Then this is a duplicate variable in the
3728 // same disjunction, which is an error.
3729 self.resolve_error(pattern.span,
3730 &format!("identifier `{}` is bound \
3731 more than once in the same \
3733 token::get_ident(ident))[]);
3735 // Else, not bound in the same pattern: do
3741 PatEnum(ref path, _) => {
3742 // This must be an enum variant, struct or const.
3743 match self.resolve_path(pat_id, path, ValueNS, false) {
3744 Some(def @ (DefVariant(..), _)) |
3745 Some(def @ (DefStruct(..), _)) |
3746 Some(def @ (DefConst(..), _)) => {
3747 self.record_def(pattern.id, def);
3749 Some((DefStatic(..), _)) => {
3750 self.resolve_error(path.span,
3751 "static variables cannot be \
3752 referenced in a pattern, \
3753 use a `const` instead");
3756 self.resolve_error(path.span,
3757 format!("`{}` is not an enum variant, struct or const",
3759 path.segments.last().unwrap().identifier)).as_slice());
3762 self.resolve_error(path.span,
3763 format!("unresolved enum variant, struct or const `{}`",
3765 path.segments.last().unwrap().identifier)).as_slice());
3769 // Check the types in the path pattern.
3770 for ty in path.segments
3772 .flat_map(|s| s.parameters.types().into_iter()) {
3773 self.resolve_type(&**ty);
3777 PatLit(ref expr) => {
3778 self.resolve_expr(&**expr);
3781 PatRange(ref first_expr, ref last_expr) => {
3782 self.resolve_expr(&**first_expr);
3783 self.resolve_expr(&**last_expr);
3786 PatStruct(ref path, _, _) => {
3787 match self.resolve_path(pat_id, path, TypeNS, false) {
3788 Some(definition) => {
3789 self.record_def(pattern.id, definition);
3792 debug!("(resolving pattern) didn't find struct \
3793 def: {:?}", result);
3794 let msg = format!("`{}` does not name a structure",
3795 self.path_names_to_string(path));
3796 self.resolve_error(path.span, &msg[]);
3809 fn resolve_bare_identifier_pattern(&mut self, name: Name, span: Span)
3810 -> BareIdentifierPatternResolution {
3811 let module = self.current_module.clone();
3812 match self.resolve_item_in_lexical_scope(module,
3815 Success((target, _)) => {
3816 debug!("(resolve bare identifier pattern) succeeded in \
3817 finding {} at {:?}",
3818 token::get_name(name),
3819 target.bindings.value_def.borrow());
3820 match *target.bindings.value_def.borrow() {
3822 panic!("resolved name in the value namespace to a \
3823 set of name bindings with no def?!");
3826 // For the two success cases, this lookup can be
3827 // considered as not having a private component because
3828 // the lookup happened only within the current module.
3830 def @ DefVariant(..) | def @ DefStruct(..) => {
3831 return FoundStructOrEnumVariant(def, LastMod(AllPublic));
3833 def @ DefConst(..) => {
3834 return FoundConst(def, LastMod(AllPublic));
3837 self.resolve_error(span,
3838 "static variables cannot be \
3839 referenced in a pattern, \
3840 use a `const` instead");
3841 return BareIdentifierPatternUnresolved;
3844 return BareIdentifierPatternUnresolved;
3852 panic!("unexpected indeterminate result");
3856 Some((span, msg)) => {
3857 self.resolve_error(span, &format!("failed to resolve: {}",
3863 debug!("(resolve bare identifier pattern) failed to find {}",
3864 token::get_name(name));
3865 return BareIdentifierPatternUnresolved;
3870 /// If `check_ribs` is true, checks the local definitions first; i.e.
3871 /// doesn't skip straight to the containing module.
3872 fn resolve_path(&mut self,
3875 namespace: Namespace,
3876 check_ribs: bool) -> Option<(Def, LastPrivate)> {
3877 // First, resolve the types and associated type bindings.
3878 for ty in path.segments.iter().flat_map(|s| s.parameters.types().into_iter()) {
3879 self.resolve_type(&**ty);
3881 for binding in path.segments.iter().flat_map(|s| s.parameters.bindings().into_iter()) {
3882 self.resolve_type(&*binding.ty);
3885 // A special case for sugared associated type paths `T::A` where `T` is
3886 // a type parameter and `A` is an associated type on some bound of `T`.
3887 if namespace == TypeNS && path.segments.len() == 2 {
3888 match self.resolve_identifier(path.segments[0].identifier,
3892 Some((def, last_private)) => {
3894 DefTyParam(_, _, did, _) => {
3895 let def = DefAssociatedPath(TyParamProvenance::FromParam(did),
3896 path.segments.last()
3897 .unwrap().identifier);
3898 return Some((def, last_private));
3901 let def = DefAssociatedPath(TyParamProvenance::FromSelf(local_def(nid)),
3902 path.segments.last()
3903 .unwrap().identifier);
3904 return Some((def, last_private));
3914 return self.resolve_crate_relative_path(path, namespace);
3917 // Try to find a path to an item in a module.
3918 let unqualified_def =
3919 self.resolve_identifier(path.segments.last().unwrap().identifier,
3924 if path.segments.len() > 1 {
3925 let def = self.resolve_module_relative_path(path, namespace);
3926 match (def, unqualified_def) {
3927 (Some((ref d, _)), Some((ref ud, _))) if *d == *ud => {
3929 .add_lint(lint::builtin::UNUSED_QUALIFICATIONS,
3932 "unnecessary qualification".to_string());
3940 return unqualified_def;
3943 // resolve a single identifier (used as a varref)
3944 fn resolve_identifier(&mut self,
3946 namespace: Namespace,
3949 -> Option<(Def, LastPrivate)> {
3951 match self.resolve_identifier_in_local_ribs(identifier,
3955 return Some((def, LastMod(AllPublic)));
3963 return self.resolve_item_by_name_in_lexical_scope(identifier.name, namespace);
3966 // FIXME #4952: Merge me with resolve_name_in_module?
3967 fn resolve_definition_of_name_in_module(&mut self,
3968 containing_module: Rc<Module>,
3970 namespace: Namespace)
3972 // First, search children.
3973 build_reduced_graph::populate_module_if_necessary(self, &containing_module);
3975 match containing_module.children.borrow().get(&name) {
3976 Some(child_name_bindings) => {
3977 match child_name_bindings.def_for_namespace(namespace) {
3979 // Found it. Stop the search here.
3980 let p = child_name_bindings.defined_in_public_namespace(
3982 let lp = if p {LastMod(AllPublic)} else {
3983 LastMod(DependsOn(def.def_id()))
3985 return ChildNameDefinition(def, lp);
3993 // Next, search import resolutions.
3994 match containing_module.import_resolutions.borrow().get(&name) {
3995 Some(import_resolution) if import_resolution.is_public => {
3996 if let Some(target) = (*import_resolution).target_for_namespace(namespace) {
3997 match target.bindings.def_for_namespace(namespace) {
4000 let id = import_resolution.id(namespace);
4001 // track imports and extern crates as well
4002 self.used_imports.insert((id, namespace));
4003 self.record_import_use(id, name);
4004 match target.target_module.def_id.get() {
4005 Some(DefId{krate: kid, ..}) => {
4006 self.used_crates.insert(kid);
4010 return ImportNameDefinition(def, LastMod(AllPublic));
4013 // This can happen with external impls, due to
4014 // the imperfect way we read the metadata.
4019 Some(..) | None => {} // Continue.
4022 // Finally, search through external children.
4023 if namespace == TypeNS {
4024 if let Some(module) = containing_module.external_module_children.borrow()
4025 .get(&name).cloned() {
4026 if let Some(def_id) = module.def_id.get() {
4027 // track used crates
4028 self.used_crates.insert(def_id.krate);
4029 let lp = if module.is_public {LastMod(AllPublic)} else {
4030 LastMod(DependsOn(def_id))
4032 return ChildNameDefinition(DefMod(def_id), lp);
4037 return NoNameDefinition;
4040 // resolve a "module-relative" path, e.g. a::b::c
4041 fn resolve_module_relative_path(&mut self,
4043 namespace: Namespace)
4044 -> Option<(Def, LastPrivate)> {
4045 let module_path = path.segments.init().iter()
4046 .map(|ps| ps.identifier.name)
4047 .collect::<Vec<_>>();
4049 let containing_module;
4051 let module = self.current_module.clone();
4052 match self.resolve_module_path(module,
4058 let (span, msg) = match err {
4059 Some((span, msg)) => (span, msg),
4061 let msg = format!("Use of undeclared type or module `{}`",
4062 self.names_to_string(module_path.as_slice()));
4067 self.resolve_error(span, &format!("failed to resolve. {}",
4071 Indeterminate => panic!("indeterminate unexpected"),
4072 Success((resulting_module, resulting_last_private)) => {
4073 containing_module = resulting_module;
4074 last_private = resulting_last_private;
4078 let name = path.segments.last().unwrap().identifier.name;
4079 let def = match self.resolve_definition_of_name_in_module(containing_module.clone(),
4082 NoNameDefinition => {
4083 // We failed to resolve the name. Report an error.
4086 ChildNameDefinition(def, lp) | ImportNameDefinition(def, lp) => {
4087 (def, last_private.or(lp))
4090 if let Some(DefId{krate: kid, ..}) = containing_module.def_id.get() {
4091 self.used_crates.insert(kid);
4096 /// Invariant: This must be called only during main resolution, not during
4097 /// import resolution.
4098 fn resolve_crate_relative_path(&mut self,
4100 namespace: Namespace)
4101 -> Option<(Def, LastPrivate)> {
4102 let module_path = path.segments.init().iter()
4103 .map(|ps| ps.identifier.name)
4104 .collect::<Vec<_>>();
4106 let root_module = self.graph_root.get_module();
4108 let containing_module;
4110 match self.resolve_module_path_from_root(root_module,
4115 LastMod(AllPublic)) {
4117 let (span, msg) = match err {
4118 Some((span, msg)) => (span, msg),
4120 let msg = format!("Use of undeclared module `::{}`",
4121 self.names_to_string(&module_path[]));
4126 self.resolve_error(span, &format!("failed to resolve. {}",
4132 panic!("indeterminate unexpected");
4135 Success((resulting_module, resulting_last_private)) => {
4136 containing_module = resulting_module;
4137 last_private = resulting_last_private;
4141 let name = path.segments.last().unwrap().identifier.name;
4142 match self.resolve_definition_of_name_in_module(containing_module,
4145 NoNameDefinition => {
4146 // We failed to resolve the name. Report an error.
4149 ChildNameDefinition(def, lp) | ImportNameDefinition(def, lp) => {
4150 return Some((def, last_private.or(lp)));
4155 fn resolve_identifier_in_local_ribs(&mut self,
4157 namespace: Namespace,
4160 // Check the local set of ribs.
4161 let search_result = match namespace {
4163 let renamed = mtwt::resolve(ident);
4164 self.search_ribs(self.value_ribs.as_slice(), renamed, span)
4167 let name = ident.name;
4168 self.search_ribs(&self.type_ribs[], name, span)
4172 match search_result {
4173 Some(DlDef(def)) => {
4174 debug!("(resolving path in local ribs) resolved `{}` to \
4176 token::get_ident(ident),
4180 Some(DlField) | Some(DlImpl(_)) | None => {
4186 fn resolve_item_by_name_in_lexical_scope(&mut self,
4188 namespace: Namespace)
4189 -> Option<(Def, LastPrivate)> {
4191 let module = self.current_module.clone();
4192 match self.resolve_item_in_lexical_scope(module,
4195 Success((target, _)) => {
4196 match (*target.bindings).def_for_namespace(namespace) {
4198 // This can happen if we were looking for a type and
4199 // found a module instead. Modules don't have defs.
4200 debug!("(resolving item path by identifier in lexical \
4201 scope) failed to resolve {} after success...",
4202 token::get_name(name));
4206 debug!("(resolving item path in lexical scope) \
4207 resolved `{}` to item",
4208 token::get_name(name));
4209 // This lookup is "all public" because it only searched
4210 // for one identifier in the current module (couldn't
4211 // have passed through reexports or anything like that.
4212 return Some((def, LastMod(AllPublic)));
4217 panic!("unexpected indeterminate result");
4221 Some((span, msg)) =>
4222 self.resolve_error(span, &format!("failed to resolve. {}",
4227 debug!("(resolving item path by identifier in lexical scope) \
4228 failed to resolve {}", token::get_name(name));
4234 fn with_no_errors<T, F>(&mut self, f: F) -> T where
4235 F: FnOnce(&mut Resolver) -> T,
4237 self.emit_errors = false;
4239 self.emit_errors = true;
4243 fn resolve_error(&self, span: Span, s: &str) {
4244 if self.emit_errors {
4245 self.session.span_err(span, s);
4249 fn find_fallback_in_self_type(&mut self, name: Name) -> FallbackSuggestion {
4250 fn extract_path_and_node_id(t: &Ty, allow: FallbackChecks)
4251 -> Option<(Path, NodeId, FallbackChecks)> {
4253 TyPath(ref path, node_id) => Some((path.clone(), node_id, allow)),
4254 TyPtr(ref mut_ty) => extract_path_and_node_id(&*mut_ty.ty, OnlyTraitAndStatics),
4255 TyRptr(_, ref mut_ty) => extract_path_and_node_id(&*mut_ty.ty, allow),
4256 // This doesn't handle the remaining `Ty` variants as they are not
4257 // that commonly the self_type, it might be interesting to provide
4258 // support for those in future.
4263 fn get_module(this: &mut Resolver, span: Span, name_path: &[ast::Name])
4264 -> Option<Rc<Module>> {
4265 let root = this.current_module.clone();
4266 let last_name = name_path.last().unwrap();
4268 if name_path.len() == 1 {
4269 match this.primitive_type_table.primitive_types.get(last_name) {
4272 match this.current_module.children.borrow().get(last_name) {
4273 Some(child) => child.get_module_if_available(),
4279 match this.resolve_module_path(root,
4284 Success((module, _)) => Some(module),
4290 let (path, node_id, allowed) = match self.current_self_type {
4291 Some(ref ty) => match extract_path_and_node_id(ty, Everything) {
4293 None => return NoSuggestion,
4295 None => return NoSuggestion,
4298 if allowed == Everything {
4299 // Look for a field with the same name in the current self_type.
4300 match self.def_map.borrow().get(&node_id) {
4301 Some(&DefTy(did, _))
4302 | Some(&DefStruct(did))
4303 | Some(&DefVariant(_, did, _)) => match self.structs.get(&did) {
4306 if fields.iter().any(|&field_name| name == field_name) {
4311 _ => {} // Self type didn't resolve properly
4315 let name_path = path.segments.iter().map(|seg| seg.identifier.name).collect::<Vec<_>>();
4317 // Look for a method in the current self type's impl module.
4318 match get_module(self, path.span, &name_path[]) {
4319 Some(module) => match module.children.borrow().get(&name) {
4321 let p_str = self.path_names_to_string(&path);
4322 match binding.def_for_namespace(ValueNS) {
4323 Some(DefStaticMethod(_, provenance)) => {
4325 FromImpl(_) => return StaticMethod(p_str),
4326 FromTrait(_) => unreachable!()
4329 Some(DefMethod(_, None, _)) if allowed == Everything => return Method,
4330 Some(DefMethod(_, Some(_), _)) => return TraitItem,
4339 // Look for a method in the current trait.
4340 match self.current_trait_ref {
4341 Some((did, ref trait_ref)) => {
4342 let path_str = self.path_names_to_string(&trait_ref.path);
4344 match self.trait_item_map.get(&(name, did)) {
4345 Some(&StaticMethodTraitItemKind) => {
4346 return TraitMethod(path_str)
4348 Some(_) => return TraitItem,
4358 fn find_best_match_for_name(&mut self, name: &str, max_distance: uint)
4360 let this = &mut *self;
4362 let mut maybes: Vec<token::InternedString> = Vec::new();
4363 let mut values: Vec<uint> = Vec::new();
4365 for rib in this.value_ribs.iter().rev() {
4366 for (&k, _) in rib.bindings.iter() {
4367 maybes.push(token::get_name(k));
4368 values.push(uint::MAX);
4372 let mut smallest = 0;
4373 for (i, other) in maybes.iter().enumerate() {
4374 values[i] = lev_distance(name, other.get());
4376 if values[i] <= values[smallest] {
4381 if values.len() > 0 &&
4382 values[smallest] != uint::MAX &&
4383 values[smallest] < name.len() + 2 &&
4384 values[smallest] <= max_distance &&
4385 name != maybes[smallest].get() {
4387 Some(maybes[smallest].get().to_string())
4394 fn resolve_expr(&mut self, expr: &Expr) {
4395 // First, record candidate traits for this expression if it could
4396 // result in the invocation of a method call.
4398 self.record_candidate_traits_for_expr_if_necessary(expr);
4400 // Next, resolve the node.
4402 // The interpretation of paths depends on whether the path has
4403 // multiple elements in it or not.
4405 ExprPath(_) | ExprQPath(_) => {
4406 let mut path_from_qpath;
4407 let path = match expr.node {
4408 ExprPath(ref path) => path,
4409 ExprQPath(ref qpath) => {
4410 self.resolve_type(&*qpath.self_type);
4411 self.resolve_trait_reference(expr.id, &*qpath.trait_ref, TraitQPath);
4412 path_from_qpath = qpath.trait_ref.path.clone();
4413 path_from_qpath.segments.push(qpath.item_path.clone());
4418 // This is a local path in the value namespace. Walk through
4419 // scopes looking for it.
4420 match self.resolve_path(expr.id, path, ValueNS, true) {
4421 // Check if struct variant
4422 Some((DefVariant(_, _, true), _)) => {
4423 let path_name = self.path_names_to_string(path);
4424 self.resolve_error(expr.span,
4425 format!("`{}` is a struct variant name, but \
4427 uses it like a function name",
4428 path_name).as_slice());
4430 self.session.span_help(expr.span,
4431 format!("Did you mean to write: \
4432 `{} {{ /* fields */ }}`?",
4433 path_name).as_slice());
4436 // Write the result into the def map.
4437 debug!("(resolving expr) resolved `{}`",
4438 self.path_names_to_string(path));
4440 self.record_def(expr.id, def);
4443 // Be helpful if the name refers to a struct
4444 // (The pattern matching def_tys where the id is in self.structs
4445 // matches on regular structs while excluding tuple- and enum-like
4446 // structs, which wouldn't result in this error.)
4447 let path_name = self.path_names_to_string(path);
4448 match self.with_no_errors(|this|
4449 this.resolve_path(expr.id, path, TypeNS, false)) {
4450 Some((DefTy(struct_id, _), _))
4451 if self.structs.contains_key(&struct_id) => {
4452 self.resolve_error(expr.span,
4453 format!("`{}` is a structure name, but \
4455 uses it like a function name",
4456 path_name).as_slice());
4458 self.session.span_help(expr.span,
4459 format!("Did you mean to write: \
4460 `{} {{ /* fields */ }}`?",
4461 path_name).as_slice());
4465 let mut method_scope = false;
4466 self.value_ribs.iter().rev().all(|rib| {
4467 let res = match *rib {
4468 Rib { bindings: _, kind: MethodRibKind(_, _) } => true,
4469 Rib { bindings: _, kind: ItemRibKind } => false,
4470 _ => return true, // Keep advancing
4474 false // Stop advancing
4477 if method_scope && token::get_name(self.self_name).get()
4481 "`self` is not available \
4482 in a static method. Maybe a \
4483 `self` argument is missing?");
4485 let last_name = path.segments.last().unwrap().identifier.name;
4486 let mut msg = match self.find_fallback_in_self_type(last_name) {
4488 // limit search to 5 to reduce the number
4489 // of stupid suggestions
4490 self.find_best_match_for_name(path_name.as_slice(), 5)
4491 .map_or("".to_string(),
4492 |x| format!("`{}`", x))
4495 format!("`self.{}`", path_name),
4498 format!("to call `self.{}`", path_name),
4499 TraitMethod(path_str)
4500 | StaticMethod(path_str) =>
4501 format!("to call `{}::{}`", path_str, path_name)
4505 msg = format!(". Did you mean {}?", msg)
4510 format!("unresolved name `{}`{}",
4519 visit::walk_expr(self, expr);
4522 ExprClosure(capture_clause, _, ref fn_decl, ref block) => {
4523 self.capture_mode_map.insert(expr.id, capture_clause);
4524 self.resolve_function(ClosureRibKind(expr.id, ast::DUMMY_NODE_ID),
4525 Some(&**fn_decl), NoTypeParameters,
4529 ExprStruct(ref path, _, _) => {
4530 // Resolve the path to the structure it goes to. We don't
4531 // check to ensure that the path is actually a structure; that
4532 // is checked later during typeck.
4533 match self.resolve_path(expr.id, path, TypeNS, false) {
4534 Some(definition) => self.record_def(expr.id, definition),
4536 debug!("(resolving expression) didn't find struct \
4537 def: {:?}", result);
4538 let msg = format!("`{}` does not name a structure",
4539 self.path_names_to_string(path));
4540 self.resolve_error(path.span, &msg[]);
4544 visit::walk_expr(self, expr);
4547 ExprLoop(_, Some(label)) | ExprWhile(_, _, Some(label)) => {
4548 self.with_label_rib(|this| {
4549 let def_like = DlDef(DefLabel(expr.id));
4552 let rib = this.label_ribs.last_mut().unwrap();
4553 let renamed = mtwt::resolve(label);
4554 rib.bindings.insert(renamed, def_like);
4557 visit::walk_expr(this, expr);
4561 ExprForLoop(ref pattern, ref head, ref body, optional_label) => {
4562 self.resolve_expr(&**head);
4564 self.value_ribs.push(Rib::new(NormalRibKind));
4566 self.resolve_pattern(&**pattern,
4567 LocalIrrefutableMode,
4568 &mut HashMap::new());
4570 match optional_label {
4574 .push(Rib::new(NormalRibKind));
4575 let def_like = DlDef(DefLabel(expr.id));
4578 let rib = self.label_ribs.last_mut().unwrap();
4579 let renamed = mtwt::resolve(label);
4580 rib.bindings.insert(renamed, def_like);
4585 self.resolve_block(&**body);
4587 if optional_label.is_some() {
4588 drop(self.label_ribs.pop())
4591 self.value_ribs.pop();
4594 ExprBreak(Some(label)) | ExprAgain(Some(label)) => {
4595 let renamed = mtwt::resolve(label);
4596 match self.search_label(renamed) {
4600 &format!("use of undeclared label `{}`",
4601 token::get_ident(label))[])
4603 Some(DlDef(def @ DefLabel(_))) => {
4604 // Since this def is a label, it is never read.
4605 self.record_def(expr.id, (def, LastMod(AllPublic)))
4608 self.session.span_bug(expr.span,
4609 "label wasn't mapped to a \
4616 visit::walk_expr(self, expr);
4621 fn record_candidate_traits_for_expr_if_necessary(&mut self, expr: &Expr) {
4623 ExprField(_, ident) => {
4624 // FIXME(#6890): Even though you can't treat a method like a
4625 // field, we need to add any trait methods we find that match
4626 // the field name so that we can do some nice error reporting
4627 // later on in typeck.
4628 let traits = self.search_for_traits_containing_method(ident.node.name);
4629 self.trait_map.insert(expr.id, traits);
4631 ExprMethodCall(ident, _, _) => {
4632 debug!("(recording candidate traits for expr) recording \
4635 let traits = self.search_for_traits_containing_method(ident.node.name);
4636 self.trait_map.insert(expr.id, traits);
4644 fn search_for_traits_containing_method(&mut self, name: Name) -> Vec<DefId> {
4645 debug!("(searching for traits containing method) looking for '{}'",
4646 token::get_name(name));
4648 fn add_trait_info(found_traits: &mut Vec<DefId>,
4649 trait_def_id: DefId,
4651 debug!("(adding trait info) found trait {}:{} for method '{}'",
4654 token::get_name(name));
4655 found_traits.push(trait_def_id);
4658 let mut found_traits = Vec::new();
4659 let mut search_module = self.current_module.clone();
4661 // Look for the current trait.
4662 match self.current_trait_ref {
4663 Some((trait_def_id, _)) => {
4664 if self.trait_item_map.contains_key(&(name, trait_def_id)) {
4665 add_trait_info(&mut found_traits, trait_def_id, name);
4668 None => {} // Nothing to do.
4671 // Look for trait children.
4672 build_reduced_graph::populate_module_if_necessary(self, &search_module);
4675 for (_, child_names) in search_module.children.borrow().iter() {
4676 let def = match child_names.def_for_namespace(TypeNS) {
4680 let trait_def_id = match def {
4681 DefTrait(trait_def_id) => trait_def_id,
4684 if self.trait_item_map.contains_key(&(name, trait_def_id)) {
4685 add_trait_info(&mut found_traits, trait_def_id, name);
4690 // Look for imports.
4691 for (_, import) in search_module.import_resolutions.borrow().iter() {
4692 let target = match import.target_for_namespace(TypeNS) {
4694 Some(target) => target,
4696 let did = match target.bindings.def_for_namespace(TypeNS) {
4697 Some(DefTrait(trait_def_id)) => trait_def_id,
4698 Some(..) | None => continue,
4700 if self.trait_item_map.contains_key(&(name, did)) {
4701 add_trait_info(&mut found_traits, did, name);
4702 let id = import.type_id;
4703 self.used_imports.insert((id, TypeNS));
4704 let trait_name = self.get_trait_name(did);
4705 self.record_import_use(id, trait_name);
4706 if let Some(DefId{krate: kid, ..}) = target.target_module.def_id.get() {
4707 self.used_crates.insert(kid);
4712 match search_module.parent_link.clone() {
4713 NoParentLink | ModuleParentLink(..) => break,
4714 BlockParentLink(parent_module, _) => {
4715 search_module = parent_module.upgrade().unwrap();
4723 fn record_def(&mut self, node_id: NodeId, (def, lp): (Def, LastPrivate)) {
4724 debug!("(recording def) recording {:?} for {}, last private {:?}",
4726 assert!(match lp {LastImport{..} => false, _ => true},
4727 "Import should only be used for `use` directives");
4728 self.last_private.insert(node_id, lp);
4730 match self.def_map.borrow_mut().entry(node_id) {
4731 // Resolve appears to "resolve" the same ID multiple
4732 // times, so here is a sanity check it at least comes to
4733 // the same conclusion! - nmatsakis
4734 Occupied(entry) => if def != *entry.get() {
4736 .bug(&format!("node_id {} resolved first to {:?} and \
4742 Vacant(entry) => { entry.insert(def); },
4746 fn enforce_default_binding_mode(&mut self,
4748 pat_binding_mode: BindingMode,
4750 match pat_binding_mode {
4751 BindByValue(_) => {}
4753 self.resolve_error(pat.span,
4754 &format!("cannot use `ref` binding mode \
4764 // Diagnostics are not particularly efficient, because they're rarely
4768 /// A somewhat inefficient routine to obtain the name of a module.
4769 fn module_to_string(&self, module: &Module) -> String {
4770 let mut names = Vec::new();
4772 fn collect_mod(names: &mut Vec<ast::Name>, module: &Module) {
4773 match module.parent_link {
4775 ModuleParentLink(ref module, name) => {
4777 collect_mod(names, &*module.upgrade().unwrap());
4779 BlockParentLink(ref module, _) => {
4780 // danger, shouldn't be ident?
4781 names.push(special_idents::opaque.name);
4782 collect_mod(names, &*module.upgrade().unwrap());
4786 collect_mod(&mut names, module);
4788 if names.len() == 0 {
4789 return "???".to_string();
4791 self.names_to_string(&names.into_iter().rev()
4792 .collect::<Vec<ast::Name>>()[])
4795 #[allow(dead_code)] // useful for debugging
4796 fn dump_module(&mut self, module_: Rc<Module>) {
4797 debug!("Dump of module `{}`:", self.module_to_string(&*module_));
4799 debug!("Children:");
4800 build_reduced_graph::populate_module_if_necessary(self, &module_);
4801 for (&name, _) in module_.children.borrow().iter() {
4802 debug!("* {}", token::get_name(name));
4805 debug!("Import resolutions:");
4806 let import_resolutions = module_.import_resolutions.borrow();
4807 for (&name, import_resolution) in import_resolutions.iter() {
4809 match import_resolution.target_for_namespace(ValueNS) {
4810 None => { value_repr = "".to_string(); }
4812 value_repr = " value:?".to_string();
4818 match import_resolution.target_for_namespace(TypeNS) {
4819 None => { type_repr = "".to_string(); }
4821 type_repr = " type:?".to_string();
4826 debug!("* {}:{}{}", token::get_name(name), value_repr, type_repr);
4831 pub struct CrateMap {
4832 pub def_map: DefMap,
4833 pub freevars: RefCell<FreevarMap>,
4834 pub capture_mode_map: RefCell<CaptureModeMap>,
4835 pub export_map: ExportMap,
4836 pub trait_map: TraitMap,
4837 pub external_exports: ExternalExports,
4838 pub last_private_map: LastPrivateMap,
4839 pub glob_map: Option<GlobMap>
4842 #[derive(PartialEq,Copy)]
4843 pub enum MakeGlobMap {
4848 /// Entry point to crate resolution.
4849 pub fn resolve_crate<'a, 'tcx>(session: &'a Session,
4850 ast_map: &'a ast_map::Map<'tcx>,
4853 make_glob_map: MakeGlobMap)
4855 let mut resolver = Resolver::new(session, ast_map, krate.span, make_glob_map);
4857 build_reduced_graph::build_reduced_graph(&mut resolver, krate);
4858 session.abort_if_errors();
4860 resolver.resolve_imports();
4861 session.abort_if_errors();
4863 record_exports::record(&mut resolver);
4864 session.abort_if_errors();
4866 resolver.resolve_crate(krate);
4867 session.abort_if_errors();
4869 check_unused::check_crate(&mut resolver, krate);
4872 def_map: resolver.def_map,
4873 freevars: resolver.freevars,
4874 capture_mode_map: RefCell::new(resolver.capture_mode_map),
4875 export_map: resolver.export_map,
4876 trait_map: resolver.trait_map,
4877 external_exports: resolver.external_exports,
4878 last_private_map: resolver.last_private,
4879 glob_map: if resolver.make_glob_map {
4880 Some(resolver.glob_map)