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 span_err!(self.session, import_directive.span, E0251, "{}", 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 span_err!(self.session, import_span, E0252, "{}", &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 span_err!(self.session, import_span, E0253, "{}", &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 span_err!(self.session, import_span, E0254, "{}", &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 span_err!(self.session, import_span, E0255, "{}", &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 span_err!(self.session, import_span, E0256, "{}", &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 span_err!(self.session, span, E0257, "{}", &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 span_err!(self.session, import_span, E0258, "{}", &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) {
1900 span_err!(self.session, span, E0259,
1901 "an external crate named `{}` has already \
1902 been imported into this module",
1903 token::get_name(name).get());
1907 /// Checks that the names of items don't collide with external crates.
1908 fn check_for_conflicts_between_external_crates_and_items(&self,
1912 if self.session.features.borrow().import_shadowing {
1916 if module.external_module_children.borrow().contains_key(&name) {
1917 span_err!(self.session, span, E0260,
1918 "the name `{}` conflicts with an external \
1919 crate that has been imported into this \
1921 token::get_name(name).get());
1925 /// Resolves the given module path from the given root `module_`.
1926 fn resolve_module_path_from_root(&mut self,
1927 module_: Rc<Module>,
1928 module_path: &[Name],
1931 name_search_type: NameSearchType,
1933 -> ResolveResult<(Rc<Module>, LastPrivate)> {
1934 fn search_parent_externals(needle: Name, module: &Rc<Module>)
1935 -> Option<Rc<Module>> {
1936 module.external_module_children.borrow()
1937 .get(&needle).cloned()
1938 .map(|_| module.clone())
1940 match module.parent_link.clone() {
1941 ModuleParentLink(parent, _) => {
1942 search_parent_externals(needle,
1943 &parent.upgrade().unwrap())
1950 let mut search_module = module_;
1951 let mut index = index;
1952 let module_path_len = module_path.len();
1953 let mut closest_private = lp;
1955 // Resolve the module part of the path. This does not involve looking
1956 // upward though scope chains; we simply resolve names directly in
1957 // modules as we go.
1958 while index < module_path_len {
1959 let name = module_path[index];
1960 match self.resolve_name_in_module(search_module.clone(),
1966 let segment_name = token::get_name(name);
1967 let module_name = self.module_to_string(&*search_module);
1968 let mut span = span;
1969 let msg = if "???" == &module_name[] {
1970 span.hi = span.lo + Pos::from_uint(segment_name.get().len());
1972 match search_parent_externals(name,
1973 &self.current_module) {
1975 let path_str = self.names_to_string(module_path);
1976 let target_mod_str = self.module_to_string(&*module);
1977 let current_mod_str =
1978 self.module_to_string(&*self.current_module);
1980 let prefix = if target_mod_str == current_mod_str {
1981 "self::".to_string()
1983 format!("{}::", target_mod_str)
1986 format!("Did you mean `{}{}`?", prefix, path_str)
1988 None => format!("Maybe a missing `extern crate {}`?",
1992 format!("Could not find `{}` in `{}`",
1997 return Failed(Some((span, msg)));
1999 Failed(err) => return Failed(err),
2001 debug!("(resolving module path for import) module \
2002 resolution is indeterminate: {}",
2003 token::get_name(name));
2004 return Indeterminate;
2006 Success((target, used_proxy)) => {
2007 // Check to see whether there are type bindings, and, if
2008 // so, whether there is a module within.
2009 match *target.bindings.type_def.borrow() {
2010 Some(ref type_def) => {
2011 match type_def.module_def {
2013 let msg = format!("Not a module `{}`",
2014 token::get_name(name));
2016 return Failed(Some((span, msg)));
2018 Some(ref module_def) => {
2019 search_module = module_def.clone();
2021 // track extern crates for unused_extern_crate lint
2022 if let Some(did) = module_def.def_id.get() {
2023 self.used_crates.insert(did.krate);
2026 // Keep track of the closest
2027 // private module used when
2028 // resolving this import chain.
2029 if !used_proxy && !search_module.is_public {
2030 if let Some(did) = search_module.def_id.get() {
2031 closest_private = LastMod(DependsOn(did));
2038 // There are no type bindings at all.
2039 let msg = format!("Not a module `{}`",
2040 token::get_name(name));
2041 return Failed(Some((span, msg)));
2050 return Success((search_module, closest_private));
2053 /// Attempts to resolve the module part of an import directive or path
2054 /// rooted at the given module.
2056 /// On success, returns the resolved module, and the closest *private*
2057 /// module found to the destination when resolving this path.
2058 fn resolve_module_path(&mut self,
2059 module_: Rc<Module>,
2060 module_path: &[Name],
2061 use_lexical_scope: UseLexicalScopeFlag,
2063 name_search_type: NameSearchType)
2064 -> ResolveResult<(Rc<Module>, LastPrivate)> {
2065 let module_path_len = module_path.len();
2066 assert!(module_path_len > 0);
2068 debug!("(resolving module path for import) processing `{}` rooted at `{}`",
2069 self.names_to_string(module_path),
2070 self.module_to_string(&*module_));
2072 // Resolve the module prefix, if any.
2073 let module_prefix_result = self.resolve_module_prefix(module_.clone(),
2079 match module_prefix_result {
2081 let mpath = self.names_to_string(module_path);
2082 let mpath = &mpath[];
2083 match mpath.rfind(':') {
2085 let msg = format!("Could not find `{}` in `{}`",
2086 // idx +- 1 to account for the
2087 // colons on either side
2088 &mpath[(idx + 1)..],
2089 &mpath[..(idx - 1)]);
2090 return Failed(Some((span, msg)));
2097 Failed(err) => return Failed(err),
2099 debug!("(resolving module path for import) indeterminate; \
2101 return Indeterminate;
2103 Success(NoPrefixFound) => {
2104 // There was no prefix, so we're considering the first element
2105 // of the path. How we handle this depends on whether we were
2106 // instructed to use lexical scope or not.
2107 match use_lexical_scope {
2108 DontUseLexicalScope => {
2109 // This is a crate-relative path. We will start the
2110 // resolution process at index zero.
2111 search_module = self.graph_root.get_module();
2113 last_private = LastMod(AllPublic);
2115 UseLexicalScope => {
2116 // This is not a crate-relative path. We resolve the
2117 // first component of the path in the current lexical
2118 // scope and then proceed to resolve below that.
2119 match self.resolve_module_in_lexical_scope(module_,
2121 Failed(err) => return Failed(err),
2123 debug!("(resolving module path for import) \
2124 indeterminate; bailing");
2125 return Indeterminate;
2127 Success(containing_module) => {
2128 search_module = containing_module;
2130 last_private = LastMod(AllPublic);
2136 Success(PrefixFound(ref containing_module, index)) => {
2137 search_module = containing_module.clone();
2138 start_index = index;
2139 last_private = LastMod(DependsOn(containing_module.def_id
2145 self.resolve_module_path_from_root(search_module,
2153 /// Invariant: This must only be called during main resolution, not during
2154 /// import resolution.
2155 fn resolve_item_in_lexical_scope(&mut self,
2156 module_: Rc<Module>,
2158 namespace: Namespace)
2159 -> ResolveResult<(Target, bool)> {
2160 debug!("(resolving item in lexical scope) resolving `{}` in \
2161 namespace {:?} in `{}`",
2162 token::get_name(name),
2164 self.module_to_string(&*module_));
2166 // The current module node is handled specially. First, check for
2167 // its immediate children.
2168 build_reduced_graph::populate_module_if_necessary(self, &module_);
2170 match module_.children.borrow().get(&name) {
2172 if name_bindings.defined_in_namespace(namespace) => {
2173 debug!("top name bindings succeeded");
2174 return Success((Target::new(module_.clone(),
2175 name_bindings.clone(),
2179 Some(_) | None => { /* Not found; continue. */ }
2182 // Now check for its import directives. We don't have to have resolved
2183 // all its imports in the usual way; this is because chains of
2184 // adjacent import statements are processed as though they mutated the
2186 if let Some(import_resolution) = module_.import_resolutions.borrow().get(&name) {
2187 match (*import_resolution).target_for_namespace(namespace) {
2189 // Not found; continue.
2190 debug!("(resolving item in lexical scope) found \
2191 import resolution, but not in namespace {:?}",
2195 debug!("(resolving item in lexical scope) using \
2196 import resolution");
2197 // track used imports and extern crates as well
2198 let id = import_resolution.id(namespace);
2199 self.used_imports.insert((id, namespace));
2200 self.record_import_use(id, name);
2201 if let Some(DefId{krate: kid, ..}) = target.target_module.def_id.get() {
2202 self.used_crates.insert(kid);
2204 return Success((target, false));
2209 // Search for external modules.
2210 if namespace == TypeNS {
2211 if let Some(module) = module_.external_module_children.borrow().get(&name).cloned() {
2213 Rc::new(Resolver::create_name_bindings_from_module(module));
2214 debug!("lower name bindings succeeded");
2215 return Success((Target::new(module_,
2222 // Finally, proceed up the scope chain looking for parent modules.
2223 let mut search_module = module_;
2225 // Go to the next parent.
2226 match search_module.parent_link.clone() {
2228 // No more parents. This module was unresolved.
2229 debug!("(resolving item in lexical scope) unresolved \
2231 return Failed(None);
2233 ModuleParentLink(parent_module_node, _) => {
2234 match search_module.kind.get() {
2235 NormalModuleKind => {
2236 // We stop the search here.
2237 debug!("(resolving item in lexical \
2238 scope) unresolved module: not \
2239 searching through module \
2241 return Failed(None);
2247 AnonymousModuleKind => {
2248 search_module = parent_module_node.upgrade().unwrap();
2252 BlockParentLink(ref parent_module_node, _) => {
2253 search_module = parent_module_node.upgrade().unwrap();
2257 // Resolve the name in the parent module.
2258 match self.resolve_name_in_module(search_module.clone(),
2263 Failed(Some((span, msg))) =>
2264 self.resolve_error(span, &format!("failed to resolve. {}",
2266 Failed(None) => (), // Continue up the search chain.
2268 // We couldn't see through the higher scope because of an
2269 // unresolved import higher up. Bail.
2271 debug!("(resolving item in lexical scope) indeterminate \
2272 higher scope; bailing");
2273 return Indeterminate;
2275 Success((target, used_reexport)) => {
2276 // We found the module.
2277 debug!("(resolving item in lexical scope) found name \
2279 return Success((target, used_reexport));
2285 /// Resolves a module name in the current lexical scope.
2286 fn resolve_module_in_lexical_scope(&mut self,
2287 module_: Rc<Module>,
2289 -> ResolveResult<Rc<Module>> {
2290 // If this module is an anonymous module, resolve the item in the
2291 // lexical scope. Otherwise, resolve the item from the crate root.
2292 let resolve_result = self.resolve_item_in_lexical_scope(module_, name, TypeNS);
2293 match resolve_result {
2294 Success((target, _)) => {
2295 let bindings = &*target.bindings;
2296 match *bindings.type_def.borrow() {
2297 Some(ref type_def) => {
2298 match type_def.module_def {
2300 debug!("!!! (resolving module in lexical \
2301 scope) module wasn't actually a \
2303 return Failed(None);
2305 Some(ref module_def) => {
2306 return Success(module_def.clone());
2311 debug!("!!! (resolving module in lexical scope) module
2312 wasn't actually a module!");
2313 return Failed(None);
2318 debug!("(resolving module in lexical scope) indeterminate; \
2320 return Indeterminate;
2323 debug!("(resolving module in lexical scope) failed to resolve");
2329 /// Returns the nearest normal module parent of the given module.
2330 fn get_nearest_normal_module_parent(&mut self, module_: Rc<Module>)
2331 -> Option<Rc<Module>> {
2332 let mut module_ = module_;
2334 match module_.parent_link.clone() {
2335 NoParentLink => return None,
2336 ModuleParentLink(new_module, _) |
2337 BlockParentLink(new_module, _) => {
2338 let new_module = new_module.upgrade().unwrap();
2339 match new_module.kind.get() {
2340 NormalModuleKind => return Some(new_module),
2345 AnonymousModuleKind => module_ = new_module,
2352 /// Returns the nearest normal module parent of the given module, or the
2353 /// module itself if it is a normal module.
2354 fn get_nearest_normal_module_parent_or_self(&mut self, module_: Rc<Module>)
2356 match module_.kind.get() {
2357 NormalModuleKind => return module_,
2362 AnonymousModuleKind => {
2363 match self.get_nearest_normal_module_parent(module_.clone()) {
2365 Some(new_module) => new_module
2371 /// Resolves a "module prefix". A module prefix is one or both of (a) `self::`;
2372 /// (b) some chain of `super::`.
2373 /// grammar: (SELF MOD_SEP ) ? (SUPER MOD_SEP) *
2374 fn resolve_module_prefix(&mut self,
2375 module_: Rc<Module>,
2376 module_path: &[Name])
2377 -> ResolveResult<ModulePrefixResult> {
2378 // Start at the current module if we see `self` or `super`, or at the
2379 // top of the crate otherwise.
2380 let mut containing_module;
2382 let first_module_path_string = token::get_name(module_path[0]);
2383 if "self" == first_module_path_string.get() {
2385 self.get_nearest_normal_module_parent_or_self(module_);
2387 } else if "super" == first_module_path_string.get() {
2389 self.get_nearest_normal_module_parent_or_self(module_);
2390 i = 0; // We'll handle `super` below.
2392 return Success(NoPrefixFound);
2395 // Now loop through all the `super`s we find.
2396 while i < module_path.len() {
2397 let string = token::get_name(module_path[i]);
2398 if "super" != string.get() {
2401 debug!("(resolving module prefix) resolving `super` at {}",
2402 self.module_to_string(&*containing_module));
2403 match self.get_nearest_normal_module_parent(containing_module) {
2404 None => return Failed(None),
2405 Some(new_module) => {
2406 containing_module = new_module;
2412 debug!("(resolving module prefix) finished resolving prefix at {}",
2413 self.module_to_string(&*containing_module));
2415 return Success(PrefixFound(containing_module, i));
2418 /// Attempts to resolve the supplied name in the given module for the
2419 /// given namespace. If successful, returns the target corresponding to
2422 /// The boolean returned on success is an indicator of whether this lookup
2423 /// passed through a public re-export proxy.
2424 fn resolve_name_in_module(&mut self,
2425 module_: Rc<Module>,
2427 namespace: Namespace,
2428 name_search_type: NameSearchType,
2429 allow_private_imports: bool)
2430 -> ResolveResult<(Target, bool)> {
2431 debug!("(resolving name in module) resolving `{}` in `{}`",
2432 token::get_name(name).get(),
2433 self.module_to_string(&*module_));
2435 // First, check the direct children of the module.
2436 build_reduced_graph::populate_module_if_necessary(self, &module_);
2438 match module_.children.borrow().get(&name) {
2440 if name_bindings.defined_in_namespace(namespace) => {
2441 debug!("(resolving name in module) found node as child");
2442 return Success((Target::new(module_.clone(),
2443 name_bindings.clone(),
2452 // Next, check the module's imports if necessary.
2454 // If this is a search of all imports, we should be done with glob
2455 // resolution at this point.
2456 if name_search_type == PathSearch {
2457 assert_eq!(module_.glob_count.get(), 0);
2460 // Check the list of resolved imports.
2461 match module_.import_resolutions.borrow().get(&name) {
2462 Some(import_resolution) if allow_private_imports ||
2463 import_resolution.is_public => {
2465 if import_resolution.is_public &&
2466 import_resolution.outstanding_references != 0 {
2467 debug!("(resolving name in module) import \
2468 unresolved; bailing out");
2469 return Indeterminate;
2471 match import_resolution.target_for_namespace(namespace) {
2473 debug!("(resolving name in module) name found, \
2474 but not in namespace {:?}",
2478 debug!("(resolving name in module) resolved to \
2480 // track used imports and extern crates as well
2481 let id = import_resolution.id(namespace);
2482 self.used_imports.insert((id, namespace));
2483 self.record_import_use(id, name);
2484 if let Some(DefId{krate: kid, ..}) = target.target_module.def_id.get() {
2485 self.used_crates.insert(kid);
2487 return Success((target, true));
2491 Some(..) | None => {} // Continue.
2494 // Finally, search through external children.
2495 if namespace == TypeNS {
2496 if let Some(module) = module_.external_module_children.borrow().get(&name).cloned() {
2498 Rc::new(Resolver::create_name_bindings_from_module(module));
2499 return Success((Target::new(module_,
2506 // We're out of luck.
2507 debug!("(resolving name in module) failed to resolve `{}`",
2508 token::get_name(name).get());
2509 return Failed(None);
2512 fn report_unresolved_imports(&mut self, module_: Rc<Module>) {
2513 let index = module_.resolved_import_count.get();
2514 let imports = module_.imports.borrow();
2515 let import_count = imports.len();
2516 if index != import_count {
2517 let sn = self.session
2519 .span_to_snippet((*imports)[index].span)
2521 if sn.contains("::") {
2522 self.resolve_error((*imports)[index].span,
2523 "unresolved import");
2525 let err = format!("unresolved import (maybe you meant `{}::*`?)",
2527 self.resolve_error((*imports)[index].span, &err[]);
2531 // Descend into children and anonymous children.
2532 build_reduced_graph::populate_module_if_necessary(self, &module_);
2534 for (_, child_node) in module_.children.borrow().iter() {
2535 match child_node.get_module_if_available() {
2539 Some(child_module) => {
2540 self.report_unresolved_imports(child_module);
2545 for (_, module_) in module_.anonymous_children.borrow().iter() {
2546 self.report_unresolved_imports(module_.clone());
2552 // We maintain a list of value ribs and type ribs.
2554 // Simultaneously, we keep track of the current position in the module
2555 // graph in the `current_module` pointer. When we go to resolve a name in
2556 // the value or type namespaces, we first look through all the ribs and
2557 // then query the module graph. When we resolve a name in the module
2558 // namespace, we can skip all the ribs (since nested modules are not
2559 // allowed within blocks in Rust) and jump straight to the current module
2562 // Named implementations are handled separately. When we find a method
2563 // call, we consult the module node to find all of the implementations in
2564 // scope. This information is lazily cached in the module node. We then
2565 // generate a fake "implementation scope" containing all the
2566 // implementations thus found, for compatibility with old resolve pass.
2568 fn with_scope<F>(&mut self, name: Option<Name>, f: F) where
2569 F: FnOnce(&mut Resolver),
2571 let orig_module = self.current_module.clone();
2573 // Move down in the graph.
2579 build_reduced_graph::populate_module_if_necessary(self, &orig_module);
2581 match orig_module.children.borrow().get(&name) {
2583 debug!("!!! (with scope) didn't find `{}` in `{}`",
2584 token::get_name(name),
2585 self.module_to_string(&*orig_module));
2587 Some(name_bindings) => {
2588 match (*name_bindings).get_module_if_available() {
2590 debug!("!!! (with scope) didn't find module \
2592 token::get_name(name),
2593 self.module_to_string(&*orig_module));
2596 self.current_module = module_;
2606 self.current_module = orig_module;
2609 /// Wraps the given definition in the appropriate number of `DefUpvar`
2615 -> Option<DefLike> {
2617 DlDef(d @ DefUpvar(..)) => {
2618 self.session.span_bug(span,
2619 &format!("unexpected {:?} in bindings", d)[])
2621 DlDef(d @ DefLocal(_)) => {
2622 let node_id = d.def_id().node;
2624 let mut last_proc_body_id = ast::DUMMY_NODE_ID;
2625 for rib in ribs.iter() {
2628 // Nothing to do. Continue.
2630 ClosureRibKind(function_id, maybe_proc_body) => {
2632 if maybe_proc_body != ast::DUMMY_NODE_ID {
2633 last_proc_body_id = maybe_proc_body;
2635 def = DefUpvar(node_id, function_id, last_proc_body_id);
2637 let mut seen = self.freevars_seen.borrow_mut();
2638 let seen = match seen.entry(function_id) {
2639 Occupied(v) => v.into_mut(),
2640 Vacant(v) => v.insert(NodeSet()),
2642 if seen.contains(&node_id) {
2645 match self.freevars.borrow_mut().entry(function_id) {
2646 Occupied(v) => v.into_mut(),
2647 Vacant(v) => v.insert(vec![]),
2648 }.push(Freevar { def: prev_def, span: span });
2649 seen.insert(node_id);
2651 MethodRibKind(item_id, _) => {
2652 // If the def is a ty param, and came from the parent
2655 DefTyParam(_, _, did, _) if {
2656 self.def_map.borrow().get(&did.node).cloned()
2657 == Some(DefTyParamBinder(item_id))
2659 DefSelfTy(did) if did == item_id => {} // ok
2661 // This was an attempt to access an upvar inside a
2662 // named function item. This is not allowed, so we
2667 "can't capture dynamic environment in a fn item; \
2668 use the || { ... } closure form instead");
2675 // This was an attempt to access an upvar inside a
2676 // named function item. This is not allowed, so we
2681 "can't capture dynamic environment in a fn item; \
2682 use the || { ... } closure form instead");
2686 ConstantItemRibKind => {
2687 // Still doesn't deal with upvars
2688 self.resolve_error(span,
2689 "attempt to use a non-constant \
2690 value in a constant");
2697 DlDef(def @ DefTyParam(..)) |
2698 DlDef(def @ DefSelfTy(..)) => {
2699 for rib in ribs.iter() {
2701 NormalRibKind | ClosureRibKind(..) => {
2702 // Nothing to do. Continue.
2704 MethodRibKind(item_id, _) => {
2705 // If the def is a ty param, and came from the parent
2708 DefTyParam(_, _, did, _) if {
2709 self.def_map.borrow().get(&did.node).cloned()
2710 == Some(DefTyParamBinder(item_id))
2712 DefSelfTy(did) if did == item_id => {} // ok
2715 // This was an attempt to use a type parameter outside
2718 self.resolve_error(span,
2719 "can't use type parameters from \
2720 outer function; try using a local \
2721 type parameter instead");
2728 // This was an attempt to use a type parameter outside
2731 self.resolve_error(span,
2732 "can't use type parameters from \
2733 outer function; try using a local \
2734 type parameter instead");
2738 ConstantItemRibKind => {
2740 self.resolve_error(span,
2741 "cannot use an outer type \
2742 parameter in this context");
2753 /// Searches the current set of local scopes and
2754 /// applies translations for closures.
2755 fn search_ribs(&self,
2759 -> Option<DefLike> {
2760 // FIXME #4950: Try caching?
2762 for (i, rib) in ribs.iter().enumerate().rev() {
2763 match rib.bindings.get(&name).cloned() {
2765 return self.upvarify(&ribs[(i + 1)..], def_like, span);
2776 /// Searches the current set of local scopes for labels.
2777 /// Stops after meeting a closure.
2778 fn search_label(&self, name: Name) -> Option<DefLike> {
2779 for rib in self.label_ribs.iter().rev() {
2785 // Do not resolve labels across function boundary
2789 let result = rib.bindings.get(&name).cloned();
2790 if result.is_some() {
2797 fn resolve_crate(&mut self, krate: &ast::Crate) {
2798 debug!("(resolving crate) starting");
2800 visit::walk_crate(self, krate);
2803 fn resolve_item(&mut self, item: &Item) {
2804 let name = item.ident.name;
2806 debug!("(resolving item) resolving {}",
2807 token::get_name(name));
2811 // enum item: resolve all the variants' discrs,
2812 // then resolve the ty params
2813 ItemEnum(ref enum_def, ref generics) => {
2814 for variant in (*enum_def).variants.iter() {
2815 for dis_expr in variant.node.disr_expr.iter() {
2816 // resolve the discriminator expr
2818 self.with_constant_rib(|this| {
2819 this.resolve_expr(&**dis_expr);
2824 // n.b. the discr expr gets visited twice.
2825 // but maybe it's okay since the first time will signal an
2826 // error if there is one? -- tjc
2827 self.with_type_parameter_rib(HasTypeParameters(generics,
2832 this.resolve_type_parameters(&generics.ty_params);
2833 this.resolve_where_clause(&generics.where_clause);
2834 visit::walk_item(this, item);
2838 ItemTy(_, ref generics) => {
2839 self.with_type_parameter_rib(HasTypeParameters(generics,
2844 this.resolve_type_parameters(&generics.ty_params);
2845 visit::walk_item(this, item);
2851 ref implemented_traits,
2853 ref impl_items) => {
2854 self.resolve_implementation(item.id,
2861 ItemTrait(_, ref generics, ref bounds, ref trait_items) => {
2862 // Create a new rib for the self type.
2863 let mut self_type_rib = Rib::new(ItemRibKind);
2865 // plain insert (no renaming, types are not currently hygienic....)
2866 let name = self.type_self_name;
2867 self_type_rib.bindings.insert(name, DlDef(DefSelfTy(item.id)));
2868 self.type_ribs.push(self_type_rib);
2870 // Create a new rib for the trait-wide type parameters.
2871 self.with_type_parameter_rib(HasTypeParameters(generics,
2876 this.resolve_type_parameters(&generics.ty_params);
2877 this.resolve_where_clause(&generics.where_clause);
2879 this.resolve_type_parameter_bounds(item.id, bounds,
2882 for trait_item in (*trait_items).iter() {
2883 // Create a new rib for the trait_item-specific type
2886 // FIXME #4951: Do we need a node ID here?
2889 ast::RequiredMethod(ref ty_m) => {
2890 this.with_type_parameter_rib
2891 (HasTypeParameters(&ty_m.generics,
2894 MethodRibKind(item.id, RequiredMethod)),
2897 // Resolve the method-specific type
2899 this.resolve_type_parameters(
2900 &ty_m.generics.ty_params);
2901 this.resolve_where_clause(&ty_m.generics
2904 for argument in ty_m.decl.inputs.iter() {
2905 this.resolve_type(&*argument.ty);
2908 if let SelfExplicit(ref typ, _) = ty_m.explicit_self.node {
2909 this.resolve_type(&**typ)
2912 if let ast::Return(ref ret_ty) = ty_m.decl.output {
2913 this.resolve_type(&**ret_ty);
2917 ast::ProvidedMethod(ref m) => {
2918 this.resolve_method(MethodRibKind(item.id,
2919 ProvidedMethod(m.id)),
2922 ast::TypeTraitItem(ref data) => {
2923 this.resolve_type_parameter(&data.ty_param);
2924 visit::walk_trait_item(this, trait_item);
2930 self.type_ribs.pop();
2933 ItemStruct(ref struct_def, ref generics) => {
2934 self.resolve_struct(item.id,
2936 &struct_def.fields[]);
2939 ItemMod(ref module_) => {
2940 self.with_scope(Some(name), |this| {
2941 this.resolve_module(module_, item.span, name,
2946 ItemForeignMod(ref foreign_module) => {
2947 self.with_scope(Some(name), |this| {
2948 for foreign_item in foreign_module.items.iter() {
2949 match foreign_item.node {
2950 ForeignItemFn(_, ref generics) => {
2951 this.with_type_parameter_rib(
2953 generics, FnSpace, foreign_item.id,
2956 this.resolve_type_parameters(&generics.ty_params);
2957 this.resolve_where_clause(&generics.where_clause);
2958 visit::walk_foreign_item(this, &**foreign_item)
2961 ForeignItemStatic(..) => {
2962 visit::walk_foreign_item(this,
2970 ItemFn(ref fn_decl, _, _, ref generics, ref block) => {
2971 self.resolve_function(ItemRibKind,
2981 ItemConst(..) | ItemStatic(..) => {
2982 self.with_constant_rib(|this| {
2983 visit::walk_item(this, item);
2988 // do nothing, these are just around to be encoded
2993 fn with_type_parameter_rib<F>(&mut self, type_parameters: TypeParameters, f: F) where
2994 F: FnOnce(&mut Resolver),
2996 match type_parameters {
2997 HasTypeParameters(generics, space, node_id, rib_kind) => {
2998 let mut function_type_rib = Rib::new(rib_kind);
2999 let mut seen_bindings = HashSet::new();
3000 for (index, type_parameter) in generics.ty_params.iter().enumerate() {
3001 let name = type_parameter.ident.name;
3002 debug!("with_type_parameter_rib: {} {}", node_id,
3005 if seen_bindings.contains(&name) {
3006 self.resolve_error(type_parameter.span,
3007 &format!("the name `{}` is already \
3009 parameter in this type \
3014 seen_bindings.insert(name);
3016 let def_like = DlDef(DefTyParam(space,
3018 local_def(type_parameter.id),
3020 // Associate this type parameter with
3021 // the item that bound it
3022 self.record_def(type_parameter.id,
3023 (DefTyParamBinder(node_id), LastMod(AllPublic)));
3024 // plain insert (no renaming)
3025 function_type_rib.bindings.insert(name, def_like);
3027 self.type_ribs.push(function_type_rib);
3030 NoTypeParameters => {
3037 match type_parameters {
3038 HasTypeParameters(..) => { self.type_ribs.pop(); }
3039 NoTypeParameters => { }
3043 fn with_label_rib<F>(&mut self, f: F) where
3044 F: FnOnce(&mut Resolver),
3046 self.label_ribs.push(Rib::new(NormalRibKind));
3048 self.label_ribs.pop();
3051 fn with_constant_rib<F>(&mut self, f: F) where
3052 F: FnOnce(&mut Resolver),
3054 self.value_ribs.push(Rib::new(ConstantItemRibKind));
3055 self.type_ribs.push(Rib::new(ConstantItemRibKind));
3057 self.type_ribs.pop();
3058 self.value_ribs.pop();
3061 fn resolve_function(&mut self,
3063 optional_declaration: Option<&FnDecl>,
3064 type_parameters: TypeParameters,
3066 // Create a value rib for the function.
3067 let function_value_rib = Rib::new(rib_kind);
3068 self.value_ribs.push(function_value_rib);
3070 // Create a label rib for the function.
3071 let function_label_rib = Rib::new(rib_kind);
3072 self.label_ribs.push(function_label_rib);
3074 // If this function has type parameters, add them now.
3075 self.with_type_parameter_rib(type_parameters, |this| {
3076 // Resolve the type parameters.
3077 match type_parameters {
3078 NoTypeParameters => {
3081 HasTypeParameters(ref generics, _, _, _) => {
3082 this.resolve_type_parameters(&generics.ty_params);
3083 this.resolve_where_clause(&generics.where_clause);
3087 // Add each argument to the rib.
3088 match optional_declaration {
3092 Some(declaration) => {
3093 let mut bindings_list = HashMap::new();
3094 for argument in declaration.inputs.iter() {
3095 this.resolve_pattern(&*argument.pat,
3096 ArgumentIrrefutableMode,
3097 &mut bindings_list);
3099 this.resolve_type(&*argument.ty);
3101 debug!("(resolving function) recorded argument");
3104 if let ast::Return(ref ret_ty) = declaration.output {
3105 this.resolve_type(&**ret_ty);
3110 // Resolve the function body.
3111 this.resolve_block(&*block);
3113 debug!("(resolving function) leaving function");
3116 self.label_ribs.pop();
3117 self.value_ribs.pop();
3120 fn resolve_type_parameters(&mut self,
3121 type_parameters: &OwnedSlice<TyParam>) {
3122 for type_parameter in type_parameters.iter() {
3123 self.resolve_type_parameter(type_parameter);
3127 fn resolve_type_parameter(&mut self,
3128 type_parameter: &TyParam) {
3129 for bound in type_parameter.bounds.iter() {
3130 self.resolve_type_parameter_bound(type_parameter.id, bound,
3131 TraitBoundingTypeParameter);
3133 match type_parameter.default {
3134 Some(ref ty) => self.resolve_type(&**ty),
3139 fn resolve_type_parameter_bounds(&mut self,
3141 type_parameter_bounds: &OwnedSlice<TyParamBound>,
3142 reference_type: TraitReferenceType) {
3143 for type_parameter_bound in type_parameter_bounds.iter() {
3144 self.resolve_type_parameter_bound(id, type_parameter_bound,
3149 fn resolve_type_parameter_bound(&mut self,
3151 type_parameter_bound: &TyParamBound,
3152 reference_type: TraitReferenceType) {
3153 match *type_parameter_bound {
3154 TraitTyParamBound(ref tref, _) => {
3155 self.resolve_poly_trait_reference(id, tref, reference_type)
3157 RegionTyParamBound(..) => {}
3161 fn resolve_poly_trait_reference(&mut self,
3163 poly_trait_reference: &PolyTraitRef,
3164 reference_type: TraitReferenceType) {
3165 self.resolve_trait_reference(id, &poly_trait_reference.trait_ref, reference_type)
3168 fn resolve_trait_reference(&mut self,
3170 trait_reference: &TraitRef,
3171 reference_type: TraitReferenceType) {
3172 match self.resolve_path(id, &trait_reference.path, TypeNS, true) {
3174 let path_str = self.path_names_to_string(&trait_reference.path);
3175 let usage_str = match reference_type {
3176 TraitBoundingTypeParameter => "bound type parameter with",
3177 TraitImplementation => "implement",
3178 TraitDerivation => "derive",
3179 TraitObject => "reference",
3180 TraitQPath => "extract an associated item from",
3183 let msg = format!("attempt to {} a nonexistent trait `{}`", usage_str, path_str);
3184 self.resolve_error(trait_reference.path.span, &msg[]);
3188 (DefTrait(_), _) => {
3189 debug!("(resolving trait) found trait def: {:?}", def);
3190 self.record_def(trait_reference.ref_id, def);
3193 self.resolve_error(trait_reference.path.span,
3194 &format!("`{}` is not a trait",
3195 self.path_names_to_string(
3196 &trait_reference.path))[]);
3198 // If it's a typedef, give a note
3199 if let DefTy(..) = def {
3200 self.session.span_note(
3201 trait_reference.path.span,
3202 &format!("`type` aliases cannot be used for traits")
3211 fn resolve_where_clause(&mut self, where_clause: &ast::WhereClause) {
3212 for predicate in where_clause.predicates.iter() {
3214 &ast::WherePredicate::BoundPredicate(ref bound_pred) => {
3215 self.resolve_type(&*bound_pred.bounded_ty);
3217 for bound in bound_pred.bounds.iter() {
3218 self.resolve_type_parameter_bound(bound_pred.bounded_ty.id, bound,
3219 TraitBoundingTypeParameter);
3222 &ast::WherePredicate::RegionPredicate(_) => {}
3223 &ast::WherePredicate::EqPredicate(ref eq_pred) => {
3224 match self.resolve_path(eq_pred.id, &eq_pred.path, TypeNS, true) {
3225 Some((def @ DefTyParam(..), last_private)) => {
3226 self.record_def(eq_pred.id, (def, last_private));
3229 self.resolve_error(eq_pred.path.span,
3230 "undeclared associated type");
3234 self.resolve_type(&*eq_pred.ty);
3240 fn resolve_struct(&mut self,
3242 generics: &Generics,
3243 fields: &[StructField]) {
3244 // If applicable, create a rib for the type parameters.
3245 self.with_type_parameter_rib(HasTypeParameters(generics,
3250 // Resolve the type parameters.
3251 this.resolve_type_parameters(&generics.ty_params);
3252 this.resolve_where_clause(&generics.where_clause);
3255 for field in fields.iter() {
3256 this.resolve_type(&*field.node.ty);
3261 // Does this really need to take a RibKind or is it always going
3262 // to be NormalRibKind?
3263 fn resolve_method(&mut self,
3265 method: &ast::Method) {
3266 let method_generics = method.pe_generics();
3267 let type_parameters = HasTypeParameters(method_generics,
3272 if let SelfExplicit(ref typ, _) = method.pe_explicit_self().node {
3273 self.resolve_type(&**typ);
3276 self.resolve_function(rib_kind,
3277 Some(method.pe_fn_decl()),
3282 fn with_current_self_type<T, F>(&mut self, self_type: &Ty, f: F) -> T where
3283 F: FnOnce(&mut Resolver) -> T,
3285 // Handle nested impls (inside fn bodies)
3286 let previous_value = replace(&mut self.current_self_type, Some(self_type.clone()));
3287 let result = f(self);
3288 self.current_self_type = previous_value;
3292 fn with_optional_trait_ref<T, F>(&mut self, id: NodeId,
3293 opt_trait_ref: &Option<TraitRef>,
3295 F: FnOnce(&mut Resolver) -> T,
3297 let new_val = match *opt_trait_ref {
3298 Some(ref trait_ref) => {
3299 self.resolve_trait_reference(id, trait_ref, TraitImplementation);
3301 match self.def_map.borrow().get(&trait_ref.ref_id) {
3303 let did = def.def_id();
3304 Some((did, trait_ref.clone()))
3311 let original_trait_ref = replace(&mut self.current_trait_ref, new_val);
3312 let result = f(self);
3313 self.current_trait_ref = original_trait_ref;
3317 fn resolve_implementation(&mut self,
3319 generics: &Generics,
3320 opt_trait_reference: &Option<TraitRef>,
3322 impl_items: &[ImplItem]) {
3323 // If applicable, create a rib for the type parameters.
3324 self.with_type_parameter_rib(HasTypeParameters(generics,
3329 // Resolve the type parameters.
3330 this.resolve_type_parameters(&generics.ty_params);
3331 this.resolve_where_clause(&generics.where_clause);
3333 // Resolve the trait reference, if necessary.
3334 this.with_optional_trait_ref(id, opt_trait_reference, |this| {
3335 // Resolve the self type.
3336 this.resolve_type(self_type);
3338 this.with_current_self_type(self_type, |this| {
3339 for impl_item in impl_items.iter() {
3341 MethodImplItem(ref method) => {
3342 // If this is a trait impl, ensure the method
3344 this.check_trait_item(method.pe_ident().name,
3347 // We also need a new scope for the method-
3348 // specific type parameters.
3349 this.resolve_method(
3350 MethodRibKind(id, ProvidedMethod(method.id)),
3353 TypeImplItem(ref typedef) => {
3354 // If this is a trait impl, ensure the method
3356 this.check_trait_item(typedef.ident.name,
3359 this.resolve_type(&*typedef.typ);
3367 // Check that the current type is indeed a type, if we have an anonymous impl
3368 if opt_trait_reference.is_none() {
3369 match self_type.node {
3370 // TyPath is the only thing that we handled in `build_reduced_graph_for_item`,
3371 // where we created a module with the name of the type in order to implement
3372 // an anonymous trait. In the case that the path does not resolve to an actual
3373 // type, the result will be that the type name resolves to a module but not
3374 // a type (shadowing any imported modules or types with this name), leading
3375 // to weird user-visible bugs. So we ward this off here. See #15060.
3376 TyPath(ref path, path_id) => {
3377 match self.def_map.borrow().get(&path_id) {
3378 // FIXME: should we catch other options and give more precise errors?
3379 Some(&DefMod(_)) => {
3380 self.resolve_error(path.span, "inherent implementations are not \
3381 allowed for types not defined in \
3382 the current module");
3392 fn check_trait_item(&self, name: Name, span: Span) {
3393 // If there is a TraitRef in scope for an impl, then the method must be in the trait.
3394 for &(did, ref trait_ref) in self.current_trait_ref.iter() {
3395 if self.trait_item_map.get(&(name, did)).is_none() {
3396 let path_str = self.path_names_to_string(&trait_ref.path);
3397 self.resolve_error(span,
3398 &format!("method `{}` is not a member of trait `{}`",
3399 token::get_name(name),
3405 fn resolve_module(&mut self, module: &Mod, _span: Span,
3406 _name: Name, id: NodeId) {
3407 // Write the implementations in scope into the module metadata.
3408 debug!("(resolving module) resolving module ID {}", id);
3409 visit::walk_mod(self, module);
3412 fn resolve_local(&mut self, local: &Local) {
3413 // Resolve the type.
3414 if let Some(ref ty) = local.ty {
3415 self.resolve_type(&**ty);
3418 // Resolve the initializer, if necessary.
3423 Some(ref initializer) => {
3424 self.resolve_expr(&**initializer);
3428 // Resolve the pattern.
3429 let mut bindings_list = HashMap::new();
3430 self.resolve_pattern(&*local.pat,
3431 LocalIrrefutableMode,
3432 &mut bindings_list);
3435 // build a map from pattern identifiers to binding-info's.
3436 // this is done hygienically. This could arise for a macro
3437 // that expands into an or-pattern where one 'x' was from the
3438 // user and one 'x' came from the macro.
3439 fn binding_mode_map(&mut self, pat: &Pat) -> BindingMap {
3440 let mut result = HashMap::new();
3441 pat_bindings(&self.def_map, pat, |binding_mode, _id, sp, path1| {
3442 let name = mtwt::resolve(path1.node);
3443 result.insert(name, BindingInfo {
3445 binding_mode: binding_mode
3451 // check that all of the arms in an or-pattern have exactly the
3452 // same set of bindings, with the same binding modes for each.
3453 fn check_consistent_bindings(&mut self, arm: &Arm) {
3454 if arm.pats.len() == 0 {
3457 let map_0 = self.binding_mode_map(&*arm.pats[0]);
3458 for (i, p) in arm.pats.iter().enumerate() {
3459 let map_i = self.binding_mode_map(&**p);
3461 for (&key, &binding_0) in map_0.iter() {
3462 match map_i.get(&key) {
3466 &format!("variable `{}` from pattern #1 is \
3467 not bound in pattern #{}",
3468 token::get_name(key),
3471 Some(binding_i) => {
3472 if binding_0.binding_mode != binding_i.binding_mode {
3475 &format!("variable `{}` is bound with different \
3476 mode in pattern #{} than in pattern #1",
3477 token::get_name(key),
3484 for (&key, &binding) in map_i.iter() {
3485 if !map_0.contains_key(&key) {
3488 &format!("variable `{}` from pattern {}{} is \
3489 not bound in pattern {}1",
3490 token::get_name(key),
3491 "#", i + 1, "#")[]);
3497 fn resolve_arm(&mut self, arm: &Arm) {
3498 self.value_ribs.push(Rib::new(NormalRibKind));
3500 let mut bindings_list = HashMap::new();
3501 for pattern in arm.pats.iter() {
3502 self.resolve_pattern(&**pattern, RefutableMode, &mut bindings_list);
3505 // This has to happen *after* we determine which
3506 // pat_idents are variants
3507 self.check_consistent_bindings(arm);
3509 visit::walk_expr_opt(self, &arm.guard);
3510 self.resolve_expr(&*arm.body);
3512 self.value_ribs.pop();
3515 fn resolve_block(&mut self, block: &Block) {
3516 debug!("(resolving block) entering block");
3517 self.value_ribs.push(Rib::new(NormalRibKind));
3519 // Move down in the graph, if there's an anonymous module rooted here.
3520 let orig_module = self.current_module.clone();
3521 match orig_module.anonymous_children.borrow().get(&block.id) {
3522 None => { /* Nothing to do. */ }
3523 Some(anonymous_module) => {
3524 debug!("(resolving block) found anonymous module, moving \
3526 self.current_module = anonymous_module.clone();
3530 // Descend into the block.
3531 visit::walk_block(self, block);
3534 self.current_module = orig_module;
3536 self.value_ribs.pop();
3537 debug!("(resolving block) leaving block");
3540 fn resolve_type(&mut self, ty: &Ty) {
3542 // Like path expressions, the interpretation of path types depends
3543 // on whether the path has multiple elements in it or not.
3545 TyPath(ref path, path_id) => {
3546 // This is a path in the type namespace. Walk through scopes
3548 let mut result_def = None;
3550 // First, check to see whether the name is a primitive type.
3551 if path.segments.len() == 1 {
3552 let id = path.segments.last().unwrap().identifier;
3554 match self.primitive_type_table
3558 Some(&primitive_type) => {
3560 Some((DefPrimTy(primitive_type), LastMod(AllPublic)));
3562 if path.segments[0].parameters.has_lifetimes() {
3563 span_err!(self.session, path.span, E0157,
3564 "lifetime parameters are not allowed on this type");
3565 } else if !path.segments[0].parameters.is_empty() {
3566 span_err!(self.session, path.span, E0153,
3567 "type parameters are not allowed on this type");
3576 if let None = result_def {
3577 result_def = self.resolve_path(ty.id, path, TypeNS, true);
3582 // Write the result into the def map.
3583 debug!("(resolving type) writing resolution for `{}` \
3585 self.path_names_to_string(path),
3587 self.record_def(path_id, def);
3590 let msg = format!("use of undeclared type name `{}`",
3591 self.path_names_to_string(path));
3592 self.resolve_error(ty.span, &msg[]);
3597 TyObjectSum(ref ty, ref bound_vec) => {
3598 self.resolve_type(&**ty);
3599 self.resolve_type_parameter_bounds(ty.id, bound_vec,
3600 TraitBoundingTypeParameter);
3603 TyQPath(ref qpath) => {
3604 self.resolve_type(&*qpath.self_type);
3605 self.resolve_trait_reference(ty.id, &*qpath.trait_ref, TraitQPath);
3606 for ty in qpath.item_path.parameters.types().into_iter() {
3607 self.resolve_type(&**ty);
3609 for binding in qpath.item_path.parameters.bindings().into_iter() {
3610 self.resolve_type(&*binding.ty);
3614 TyPolyTraitRef(ref bounds) => {
3615 self.resolve_type_parameter_bounds(
3619 visit::walk_ty(self, ty);
3622 // Just resolve embedded types.
3623 visit::walk_ty(self, ty);
3628 fn resolve_pattern(&mut self,
3630 mode: PatternBindingMode,
3631 // Maps idents to the node ID for the (outermost)
3632 // pattern that binds them
3633 bindings_list: &mut HashMap<Name, NodeId>) {
3634 let pat_id = pattern.id;
3635 walk_pat(pattern, |pattern| {
3636 match pattern.node {
3637 PatIdent(binding_mode, ref path1, _) => {
3639 // The meaning of pat_ident with no type parameters
3640 // depends on whether an enum variant or unit-like struct
3641 // with that name is in scope. The probing lookup has to
3642 // be careful not to emit spurious errors. Only matching
3643 // patterns (match) can match nullary variants or
3644 // unit-like structs. For binding patterns (let), matching
3645 // such a value is simply disallowed (since it's rarely
3648 let ident = path1.node;
3649 let renamed = mtwt::resolve(ident);
3651 match self.resolve_bare_identifier_pattern(ident.name, pattern.span) {
3652 FoundStructOrEnumVariant(ref def, lp)
3653 if mode == RefutableMode => {
3654 debug!("(resolving pattern) resolving `{}` to \
3655 struct or enum variant",
3656 token::get_name(renamed));
3658 self.enforce_default_binding_mode(
3662 self.record_def(pattern.id, (def.clone(), lp));
3664 FoundStructOrEnumVariant(..) => {
3667 &format!("declaration of `{}` shadows an enum \
3668 variant or unit-like struct in \
3670 token::get_name(renamed))[]);
3672 FoundConst(ref def, lp) if mode == RefutableMode => {
3673 debug!("(resolving pattern) resolving `{}` to \
3675 token::get_name(renamed));
3677 self.enforce_default_binding_mode(
3681 self.record_def(pattern.id, (def.clone(), lp));
3684 self.resolve_error(pattern.span,
3685 "only irrefutable patterns \
3688 BareIdentifierPatternUnresolved => {
3689 debug!("(resolving pattern) binding `{}`",
3690 token::get_name(renamed));
3692 let def = DefLocal(pattern.id);
3694 // Record the definition so that later passes
3695 // will be able to distinguish variants from
3696 // locals in patterns.
3698 self.record_def(pattern.id, (def, LastMod(AllPublic)));
3700 // Add the binding to the local ribs, if it
3701 // doesn't already exist in the bindings list. (We
3702 // must not add it if it's in the bindings list
3703 // because that breaks the assumptions later
3704 // passes make about or-patterns.)
3705 if !bindings_list.contains_key(&renamed) {
3706 let this = &mut *self;
3707 let last_rib = this.value_ribs.last_mut().unwrap();
3708 last_rib.bindings.insert(renamed, DlDef(def));
3709 bindings_list.insert(renamed, pat_id);
3710 } else if mode == ArgumentIrrefutableMode &&
3711 bindings_list.contains_key(&renamed) {
3712 // Forbid duplicate bindings in the same
3714 self.resolve_error(pattern.span,
3715 &format!("identifier `{}` \
3723 } else if bindings_list.get(&renamed) ==
3725 // Then this is a duplicate variable in the
3726 // same disjunction, which is an error.
3727 self.resolve_error(pattern.span,
3728 &format!("identifier `{}` is bound \
3729 more than once in the same \
3731 token::get_ident(ident))[]);
3733 // Else, not bound in the same pattern: do
3739 PatEnum(ref path, _) => {
3740 // This must be an enum variant, struct or const.
3741 match self.resolve_path(pat_id, path, ValueNS, false) {
3742 Some(def @ (DefVariant(..), _)) |
3743 Some(def @ (DefStruct(..), _)) |
3744 Some(def @ (DefConst(..), _)) => {
3745 self.record_def(pattern.id, def);
3747 Some((DefStatic(..), _)) => {
3748 self.resolve_error(path.span,
3749 "static variables cannot be \
3750 referenced in a pattern, \
3751 use a `const` instead");
3754 self.resolve_error(path.span,
3755 format!("`{}` is not an enum variant, struct or const",
3757 path.segments.last().unwrap().identifier)).as_slice());
3760 self.resolve_error(path.span,
3761 format!("unresolved enum variant, struct or const `{}`",
3763 path.segments.last().unwrap().identifier)).as_slice());
3767 // Check the types in the path pattern.
3768 for ty in path.segments
3770 .flat_map(|s| s.parameters.types().into_iter()) {
3771 self.resolve_type(&**ty);
3775 PatLit(ref expr) => {
3776 self.resolve_expr(&**expr);
3779 PatRange(ref first_expr, ref last_expr) => {
3780 self.resolve_expr(&**first_expr);
3781 self.resolve_expr(&**last_expr);
3784 PatStruct(ref path, _, _) => {
3785 match self.resolve_path(pat_id, path, TypeNS, false) {
3786 Some(definition) => {
3787 self.record_def(pattern.id, definition);
3790 debug!("(resolving pattern) didn't find struct \
3791 def: {:?}", result);
3792 let msg = format!("`{}` does not name a structure",
3793 self.path_names_to_string(path));
3794 self.resolve_error(path.span, &msg[]);
3807 fn resolve_bare_identifier_pattern(&mut self, name: Name, span: Span)
3808 -> BareIdentifierPatternResolution {
3809 let module = self.current_module.clone();
3810 match self.resolve_item_in_lexical_scope(module,
3813 Success((target, _)) => {
3814 debug!("(resolve bare identifier pattern) succeeded in \
3815 finding {} at {:?}",
3816 token::get_name(name),
3817 target.bindings.value_def.borrow());
3818 match *target.bindings.value_def.borrow() {
3820 panic!("resolved name in the value namespace to a \
3821 set of name bindings with no def?!");
3824 // For the two success cases, this lookup can be
3825 // considered as not having a private component because
3826 // the lookup happened only within the current module.
3828 def @ DefVariant(..) | def @ DefStruct(..) => {
3829 return FoundStructOrEnumVariant(def, LastMod(AllPublic));
3831 def @ DefConst(..) => {
3832 return FoundConst(def, LastMod(AllPublic));
3835 self.resolve_error(span,
3836 "static variables cannot be \
3837 referenced in a pattern, \
3838 use a `const` instead");
3839 return BareIdentifierPatternUnresolved;
3842 return BareIdentifierPatternUnresolved;
3850 panic!("unexpected indeterminate result");
3854 Some((span, msg)) => {
3855 self.resolve_error(span, &format!("failed to resolve: {}",
3861 debug!("(resolve bare identifier pattern) failed to find {}",
3862 token::get_name(name));
3863 return BareIdentifierPatternUnresolved;
3868 /// If `check_ribs` is true, checks the local definitions first; i.e.
3869 /// doesn't skip straight to the containing module.
3870 fn resolve_path(&mut self,
3873 namespace: Namespace,
3874 check_ribs: bool) -> Option<(Def, LastPrivate)> {
3875 // First, resolve the types and associated type bindings.
3876 for ty in path.segments.iter().flat_map(|s| s.parameters.types().into_iter()) {
3877 self.resolve_type(&**ty);
3879 for binding in path.segments.iter().flat_map(|s| s.parameters.bindings().into_iter()) {
3880 self.resolve_type(&*binding.ty);
3883 // A special case for sugared associated type paths `T::A` where `T` is
3884 // a type parameter and `A` is an associated type on some bound of `T`.
3885 if namespace == TypeNS && path.segments.len() == 2 {
3886 match self.resolve_identifier(path.segments[0].identifier,
3890 Some((def, last_private)) => {
3892 DefTyParam(_, _, did, _) => {
3893 let def = DefAssociatedPath(TyParamProvenance::FromParam(did),
3894 path.segments.last()
3895 .unwrap().identifier);
3896 return Some((def, last_private));
3899 let def = DefAssociatedPath(TyParamProvenance::FromSelf(local_def(nid)),
3900 path.segments.last()
3901 .unwrap().identifier);
3902 return Some((def, last_private));
3912 return self.resolve_crate_relative_path(path, namespace);
3915 // Try to find a path to an item in a module.
3916 let unqualified_def =
3917 self.resolve_identifier(path.segments.last().unwrap().identifier,
3922 if path.segments.len() > 1 {
3923 let def = self.resolve_module_relative_path(path, namespace);
3924 match (def, unqualified_def) {
3925 (Some((ref d, _)), Some((ref ud, _))) if *d == *ud => {
3927 .add_lint(lint::builtin::UNUSED_QUALIFICATIONS,
3930 "unnecessary qualification".to_string());
3938 return unqualified_def;
3941 // resolve a single identifier (used as a varref)
3942 fn resolve_identifier(&mut self,
3944 namespace: Namespace,
3947 -> Option<(Def, LastPrivate)> {
3949 match self.resolve_identifier_in_local_ribs(identifier,
3953 return Some((def, LastMod(AllPublic)));
3961 return self.resolve_item_by_name_in_lexical_scope(identifier.name, namespace);
3964 // FIXME #4952: Merge me with resolve_name_in_module?
3965 fn resolve_definition_of_name_in_module(&mut self,
3966 containing_module: Rc<Module>,
3968 namespace: Namespace)
3970 // First, search children.
3971 build_reduced_graph::populate_module_if_necessary(self, &containing_module);
3973 match containing_module.children.borrow().get(&name) {
3974 Some(child_name_bindings) => {
3975 match child_name_bindings.def_for_namespace(namespace) {
3977 // Found it. Stop the search here.
3978 let p = child_name_bindings.defined_in_public_namespace(
3980 let lp = if p {LastMod(AllPublic)} else {
3981 LastMod(DependsOn(def.def_id()))
3983 return ChildNameDefinition(def, lp);
3991 // Next, search import resolutions.
3992 match containing_module.import_resolutions.borrow().get(&name) {
3993 Some(import_resolution) if import_resolution.is_public => {
3994 if let Some(target) = (*import_resolution).target_for_namespace(namespace) {
3995 match target.bindings.def_for_namespace(namespace) {
3998 let id = import_resolution.id(namespace);
3999 // track imports and extern crates as well
4000 self.used_imports.insert((id, namespace));
4001 self.record_import_use(id, name);
4002 match target.target_module.def_id.get() {
4003 Some(DefId{krate: kid, ..}) => {
4004 self.used_crates.insert(kid);
4008 return ImportNameDefinition(def, LastMod(AllPublic));
4011 // This can happen with external impls, due to
4012 // the imperfect way we read the metadata.
4017 Some(..) | None => {} // Continue.
4020 // Finally, search through external children.
4021 if namespace == TypeNS {
4022 if let Some(module) = containing_module.external_module_children.borrow()
4023 .get(&name).cloned() {
4024 if let Some(def_id) = module.def_id.get() {
4025 // track used crates
4026 self.used_crates.insert(def_id.krate);
4027 let lp = if module.is_public {LastMod(AllPublic)} else {
4028 LastMod(DependsOn(def_id))
4030 return ChildNameDefinition(DefMod(def_id), lp);
4035 return NoNameDefinition;
4038 // resolve a "module-relative" path, e.g. a::b::c
4039 fn resolve_module_relative_path(&mut self,
4041 namespace: Namespace)
4042 -> Option<(Def, LastPrivate)> {
4043 let module_path = path.segments.init().iter()
4044 .map(|ps| ps.identifier.name)
4045 .collect::<Vec<_>>();
4047 let containing_module;
4049 let module = self.current_module.clone();
4050 match self.resolve_module_path(module,
4056 let (span, msg) = match err {
4057 Some((span, msg)) => (span, msg),
4059 let msg = format!("Use of undeclared type or module `{}`",
4060 self.names_to_string(module_path.as_slice()));
4065 self.resolve_error(span, &format!("failed to resolve. {}",
4069 Indeterminate => panic!("indeterminate unexpected"),
4070 Success((resulting_module, resulting_last_private)) => {
4071 containing_module = resulting_module;
4072 last_private = resulting_last_private;
4076 let name = path.segments.last().unwrap().identifier.name;
4077 let def = match self.resolve_definition_of_name_in_module(containing_module.clone(),
4080 NoNameDefinition => {
4081 // We failed to resolve the name. Report an error.
4084 ChildNameDefinition(def, lp) | ImportNameDefinition(def, lp) => {
4085 (def, last_private.or(lp))
4088 if let Some(DefId{krate: kid, ..}) = containing_module.def_id.get() {
4089 self.used_crates.insert(kid);
4094 /// Invariant: This must be called only during main resolution, not during
4095 /// import resolution.
4096 fn resolve_crate_relative_path(&mut self,
4098 namespace: Namespace)
4099 -> Option<(Def, LastPrivate)> {
4100 let module_path = path.segments.init().iter()
4101 .map(|ps| ps.identifier.name)
4102 .collect::<Vec<_>>();
4104 let root_module = self.graph_root.get_module();
4106 let containing_module;
4108 match self.resolve_module_path_from_root(root_module,
4113 LastMod(AllPublic)) {
4115 let (span, msg) = match err {
4116 Some((span, msg)) => (span, msg),
4118 let msg = format!("Use of undeclared module `::{}`",
4119 self.names_to_string(&module_path[]));
4124 self.resolve_error(span, &format!("failed to resolve. {}",
4130 panic!("indeterminate unexpected");
4133 Success((resulting_module, resulting_last_private)) => {
4134 containing_module = resulting_module;
4135 last_private = resulting_last_private;
4139 let name = path.segments.last().unwrap().identifier.name;
4140 match self.resolve_definition_of_name_in_module(containing_module,
4143 NoNameDefinition => {
4144 // We failed to resolve the name. Report an error.
4147 ChildNameDefinition(def, lp) | ImportNameDefinition(def, lp) => {
4148 return Some((def, last_private.or(lp)));
4153 fn resolve_identifier_in_local_ribs(&mut self,
4155 namespace: Namespace,
4158 // Check the local set of ribs.
4159 let search_result = match namespace {
4161 let renamed = mtwt::resolve(ident);
4162 self.search_ribs(self.value_ribs.as_slice(), renamed, span)
4165 let name = ident.name;
4166 self.search_ribs(&self.type_ribs[], name, span)
4170 match search_result {
4171 Some(DlDef(def)) => {
4172 debug!("(resolving path in local ribs) resolved `{}` to \
4174 token::get_ident(ident),
4178 Some(DlField) | Some(DlImpl(_)) | None => {
4184 fn resolve_item_by_name_in_lexical_scope(&mut self,
4186 namespace: Namespace)
4187 -> Option<(Def, LastPrivate)> {
4189 let module = self.current_module.clone();
4190 match self.resolve_item_in_lexical_scope(module,
4193 Success((target, _)) => {
4194 match (*target.bindings).def_for_namespace(namespace) {
4196 // This can happen if we were looking for a type and
4197 // found a module instead. Modules don't have defs.
4198 debug!("(resolving item path by identifier in lexical \
4199 scope) failed to resolve {} after success...",
4200 token::get_name(name));
4204 debug!("(resolving item path in lexical scope) \
4205 resolved `{}` to item",
4206 token::get_name(name));
4207 // This lookup is "all public" because it only searched
4208 // for one identifier in the current module (couldn't
4209 // have passed through reexports or anything like that.
4210 return Some((def, LastMod(AllPublic)));
4215 panic!("unexpected indeterminate result");
4219 Some((span, msg)) =>
4220 self.resolve_error(span, &format!("failed to resolve. {}",
4225 debug!("(resolving item path by identifier in lexical scope) \
4226 failed to resolve {}", token::get_name(name));
4232 fn with_no_errors<T, F>(&mut self, f: F) -> T where
4233 F: FnOnce(&mut Resolver) -> T,
4235 self.emit_errors = false;
4237 self.emit_errors = true;
4241 fn resolve_error(&self, span: Span, s: &str) {
4242 if self.emit_errors {
4243 self.session.span_err(span, s);
4247 fn find_fallback_in_self_type(&mut self, name: Name) -> FallbackSuggestion {
4248 fn extract_path_and_node_id(t: &Ty, allow: FallbackChecks)
4249 -> Option<(Path, NodeId, FallbackChecks)> {
4251 TyPath(ref path, node_id) => Some((path.clone(), node_id, allow)),
4252 TyPtr(ref mut_ty) => extract_path_and_node_id(&*mut_ty.ty, OnlyTraitAndStatics),
4253 TyRptr(_, ref mut_ty) => extract_path_and_node_id(&*mut_ty.ty, allow),
4254 // This doesn't handle the remaining `Ty` variants as they are not
4255 // that commonly the self_type, it might be interesting to provide
4256 // support for those in future.
4261 fn get_module(this: &mut Resolver, span: Span, name_path: &[ast::Name])
4262 -> Option<Rc<Module>> {
4263 let root = this.current_module.clone();
4264 let last_name = name_path.last().unwrap();
4266 if name_path.len() == 1 {
4267 match this.primitive_type_table.primitive_types.get(last_name) {
4270 match this.current_module.children.borrow().get(last_name) {
4271 Some(child) => child.get_module_if_available(),
4277 match this.resolve_module_path(root,
4282 Success((module, _)) => Some(module),
4288 let (path, node_id, allowed) = match self.current_self_type {
4289 Some(ref ty) => match extract_path_and_node_id(ty, Everything) {
4291 None => return NoSuggestion,
4293 None => return NoSuggestion,
4296 if allowed == Everything {
4297 // Look for a field with the same name in the current self_type.
4298 match self.def_map.borrow().get(&node_id) {
4299 Some(&DefTy(did, _))
4300 | Some(&DefStruct(did))
4301 | Some(&DefVariant(_, did, _)) => match self.structs.get(&did) {
4304 if fields.iter().any(|&field_name| name == field_name) {
4309 _ => {} // Self type didn't resolve properly
4313 let name_path = path.segments.iter().map(|seg| seg.identifier.name).collect::<Vec<_>>();
4315 // Look for a method in the current self type's impl module.
4316 match get_module(self, path.span, &name_path[]) {
4317 Some(module) => match module.children.borrow().get(&name) {
4319 let p_str = self.path_names_to_string(&path);
4320 match binding.def_for_namespace(ValueNS) {
4321 Some(DefStaticMethod(_, provenance)) => {
4323 FromImpl(_) => return StaticMethod(p_str),
4324 FromTrait(_) => unreachable!()
4327 Some(DefMethod(_, None, _)) if allowed == Everything => return Method,
4328 Some(DefMethod(_, Some(_), _)) => return TraitItem,
4337 // Look for a method in the current trait.
4338 match self.current_trait_ref {
4339 Some((did, ref trait_ref)) => {
4340 let path_str = self.path_names_to_string(&trait_ref.path);
4342 match self.trait_item_map.get(&(name, did)) {
4343 Some(&StaticMethodTraitItemKind) => {
4344 return TraitMethod(path_str)
4346 Some(_) => return TraitItem,
4356 fn find_best_match_for_name(&mut self, name: &str, max_distance: uint)
4358 let this = &mut *self;
4360 let mut maybes: Vec<token::InternedString> = Vec::new();
4361 let mut values: Vec<uint> = Vec::new();
4363 for rib in this.value_ribs.iter().rev() {
4364 for (&k, _) in rib.bindings.iter() {
4365 maybes.push(token::get_name(k));
4366 values.push(uint::MAX);
4370 let mut smallest = 0;
4371 for (i, other) in maybes.iter().enumerate() {
4372 values[i] = lev_distance(name, other.get());
4374 if values[i] <= values[smallest] {
4379 if values.len() > 0 &&
4380 values[smallest] != uint::MAX &&
4381 values[smallest] < name.len() + 2 &&
4382 values[smallest] <= max_distance &&
4383 name != maybes[smallest].get() {
4385 Some(maybes[smallest].get().to_string())
4392 fn resolve_expr(&mut self, expr: &Expr) {
4393 // First, record candidate traits for this expression if it could
4394 // result in the invocation of a method call.
4396 self.record_candidate_traits_for_expr_if_necessary(expr);
4398 // Next, resolve the node.
4400 // The interpretation of paths depends on whether the path has
4401 // multiple elements in it or not.
4403 ExprPath(_) | ExprQPath(_) => {
4404 let mut path_from_qpath;
4405 let path = match expr.node {
4406 ExprPath(ref path) => path,
4407 ExprQPath(ref qpath) => {
4408 self.resolve_type(&*qpath.self_type);
4409 self.resolve_trait_reference(expr.id, &*qpath.trait_ref, TraitQPath);
4410 path_from_qpath = qpath.trait_ref.path.clone();
4411 path_from_qpath.segments.push(qpath.item_path.clone());
4416 // This is a local path in the value namespace. Walk through
4417 // scopes looking for it.
4418 match self.resolve_path(expr.id, path, ValueNS, true) {
4419 // Check if struct variant
4420 Some((DefVariant(_, _, true), _)) => {
4421 let path_name = self.path_names_to_string(path);
4422 self.resolve_error(expr.span,
4423 format!("`{}` is a struct variant name, but \
4425 uses it like a function name",
4426 path_name).as_slice());
4428 self.session.span_help(expr.span,
4429 format!("Did you mean to write: \
4430 `{} {{ /* fields */ }}`?",
4431 path_name).as_slice());
4434 // Write the result into the def map.
4435 debug!("(resolving expr) resolved `{}`",
4436 self.path_names_to_string(path));
4438 self.record_def(expr.id, def);
4441 // Be helpful if the name refers to a struct
4442 // (The pattern matching def_tys where the id is in self.structs
4443 // matches on regular structs while excluding tuple- and enum-like
4444 // structs, which wouldn't result in this error.)
4445 let path_name = self.path_names_to_string(path);
4446 match self.with_no_errors(|this|
4447 this.resolve_path(expr.id, path, TypeNS, false)) {
4448 Some((DefTy(struct_id, _), _))
4449 if self.structs.contains_key(&struct_id) => {
4450 self.resolve_error(expr.span,
4451 format!("`{}` is a structure name, but \
4453 uses it like a function name",
4454 path_name).as_slice());
4456 self.session.span_help(expr.span,
4457 format!("Did you mean to write: \
4458 `{} {{ /* fields */ }}`?",
4459 path_name).as_slice());
4463 let mut method_scope = false;
4464 self.value_ribs.iter().rev().all(|rib| {
4465 let res = match *rib {
4466 Rib { bindings: _, kind: MethodRibKind(_, _) } => true,
4467 Rib { bindings: _, kind: ItemRibKind } => false,
4468 _ => return true, // Keep advancing
4472 false // Stop advancing
4475 if method_scope && token::get_name(self.self_name).get()
4479 "`self` is not available \
4480 in a static method. Maybe a \
4481 `self` argument is missing?");
4483 let last_name = path.segments.last().unwrap().identifier.name;
4484 let mut msg = match self.find_fallback_in_self_type(last_name) {
4486 // limit search to 5 to reduce the number
4487 // of stupid suggestions
4488 self.find_best_match_for_name(path_name.as_slice(), 5)
4489 .map_or("".to_string(),
4490 |x| format!("`{}`", x))
4493 format!("`self.{}`", path_name),
4496 format!("to call `self.{}`", path_name),
4497 TraitMethod(path_str)
4498 | StaticMethod(path_str) =>
4499 format!("to call `{}::{}`", path_str, path_name)
4503 msg = format!(". Did you mean {}?", msg)
4508 format!("unresolved name `{}`{}",
4517 visit::walk_expr(self, expr);
4520 ExprClosure(capture_clause, _, ref fn_decl, ref block) => {
4521 self.capture_mode_map.insert(expr.id, capture_clause);
4522 self.resolve_function(ClosureRibKind(expr.id, ast::DUMMY_NODE_ID),
4523 Some(&**fn_decl), NoTypeParameters,
4527 ExprStruct(ref path, _, _) => {
4528 // Resolve the path to the structure it goes to. We don't
4529 // check to ensure that the path is actually a structure; that
4530 // is checked later during typeck.
4531 match self.resolve_path(expr.id, path, TypeNS, false) {
4532 Some(definition) => self.record_def(expr.id, definition),
4534 debug!("(resolving expression) didn't find struct \
4535 def: {:?}", result);
4536 let msg = format!("`{}` does not name a structure",
4537 self.path_names_to_string(path));
4538 self.resolve_error(path.span, &msg[]);
4542 visit::walk_expr(self, expr);
4545 ExprLoop(_, Some(label)) | ExprWhile(_, _, Some(label)) => {
4546 self.with_label_rib(|this| {
4547 let def_like = DlDef(DefLabel(expr.id));
4550 let rib = this.label_ribs.last_mut().unwrap();
4551 let renamed = mtwt::resolve(label);
4552 rib.bindings.insert(renamed, def_like);
4555 visit::walk_expr(this, expr);
4559 ExprForLoop(ref pattern, ref head, ref body, optional_label) => {
4560 self.resolve_expr(&**head);
4562 self.value_ribs.push(Rib::new(NormalRibKind));
4564 self.resolve_pattern(&**pattern,
4565 LocalIrrefutableMode,
4566 &mut HashMap::new());
4568 match optional_label {
4572 .push(Rib::new(NormalRibKind));
4573 let def_like = DlDef(DefLabel(expr.id));
4576 let rib = self.label_ribs.last_mut().unwrap();
4577 let renamed = mtwt::resolve(label);
4578 rib.bindings.insert(renamed, def_like);
4583 self.resolve_block(&**body);
4585 if optional_label.is_some() {
4586 drop(self.label_ribs.pop())
4589 self.value_ribs.pop();
4592 ExprBreak(Some(label)) | ExprAgain(Some(label)) => {
4593 let renamed = mtwt::resolve(label);
4594 match self.search_label(renamed) {
4598 &format!("use of undeclared label `{}`",
4599 token::get_ident(label))[])
4601 Some(DlDef(def @ DefLabel(_))) => {
4602 // Since this def is a label, it is never read.
4603 self.record_def(expr.id, (def, LastMod(AllPublic)))
4606 self.session.span_bug(expr.span,
4607 "label wasn't mapped to a \
4614 visit::walk_expr(self, expr);
4619 fn record_candidate_traits_for_expr_if_necessary(&mut self, expr: &Expr) {
4621 ExprField(_, ident) => {
4622 // FIXME(#6890): Even though you can't treat a method like a
4623 // field, we need to add any trait methods we find that match
4624 // the field name so that we can do some nice error reporting
4625 // later on in typeck.
4626 let traits = self.search_for_traits_containing_method(ident.node.name);
4627 self.trait_map.insert(expr.id, traits);
4629 ExprMethodCall(ident, _, _) => {
4630 debug!("(recording candidate traits for expr) recording \
4633 let traits = self.search_for_traits_containing_method(ident.node.name);
4634 self.trait_map.insert(expr.id, traits);
4642 fn search_for_traits_containing_method(&mut self, name: Name) -> Vec<DefId> {
4643 debug!("(searching for traits containing method) looking for '{}'",
4644 token::get_name(name));
4646 fn add_trait_info(found_traits: &mut Vec<DefId>,
4647 trait_def_id: DefId,
4649 debug!("(adding trait info) found trait {}:{} for method '{}'",
4652 token::get_name(name));
4653 found_traits.push(trait_def_id);
4656 let mut found_traits = Vec::new();
4657 let mut search_module = self.current_module.clone();
4659 // Look for the current trait.
4660 match self.current_trait_ref {
4661 Some((trait_def_id, _)) => {
4662 if self.trait_item_map.contains_key(&(name, trait_def_id)) {
4663 add_trait_info(&mut found_traits, trait_def_id, name);
4666 None => {} // Nothing to do.
4669 // Look for trait children.
4670 build_reduced_graph::populate_module_if_necessary(self, &search_module);
4673 for (_, child_names) in search_module.children.borrow().iter() {
4674 let def = match child_names.def_for_namespace(TypeNS) {
4678 let trait_def_id = match def {
4679 DefTrait(trait_def_id) => trait_def_id,
4682 if self.trait_item_map.contains_key(&(name, trait_def_id)) {
4683 add_trait_info(&mut found_traits, trait_def_id, name);
4688 // Look for imports.
4689 for (_, import) in search_module.import_resolutions.borrow().iter() {
4690 let target = match import.target_for_namespace(TypeNS) {
4692 Some(target) => target,
4694 let did = match target.bindings.def_for_namespace(TypeNS) {
4695 Some(DefTrait(trait_def_id)) => trait_def_id,
4696 Some(..) | None => continue,
4698 if self.trait_item_map.contains_key(&(name, did)) {
4699 add_trait_info(&mut found_traits, did, name);
4700 let id = import.type_id;
4701 self.used_imports.insert((id, TypeNS));
4702 let trait_name = self.get_trait_name(did);
4703 self.record_import_use(id, trait_name);
4704 if let Some(DefId{krate: kid, ..}) = target.target_module.def_id.get() {
4705 self.used_crates.insert(kid);
4710 match search_module.parent_link.clone() {
4711 NoParentLink | ModuleParentLink(..) => break,
4712 BlockParentLink(parent_module, _) => {
4713 search_module = parent_module.upgrade().unwrap();
4721 fn record_def(&mut self, node_id: NodeId, (def, lp): (Def, LastPrivate)) {
4722 debug!("(recording def) recording {:?} for {}, last private {:?}",
4724 assert!(match lp {LastImport{..} => false, _ => true},
4725 "Import should only be used for `use` directives");
4726 self.last_private.insert(node_id, lp);
4728 match self.def_map.borrow_mut().entry(node_id) {
4729 // Resolve appears to "resolve" the same ID multiple
4730 // times, so here is a sanity check it at least comes to
4731 // the same conclusion! - nmatsakis
4732 Occupied(entry) => if def != *entry.get() {
4734 .bug(&format!("node_id {} resolved first to {:?} and \
4740 Vacant(entry) => { entry.insert(def); },
4744 fn enforce_default_binding_mode(&mut self,
4746 pat_binding_mode: BindingMode,
4748 match pat_binding_mode {
4749 BindByValue(_) => {}
4751 self.resolve_error(pat.span,
4752 &format!("cannot use `ref` binding mode \
4762 // Diagnostics are not particularly efficient, because they're rarely
4766 /// A somewhat inefficient routine to obtain the name of a module.
4767 fn module_to_string(&self, module: &Module) -> String {
4768 let mut names = Vec::new();
4770 fn collect_mod(names: &mut Vec<ast::Name>, module: &Module) {
4771 match module.parent_link {
4773 ModuleParentLink(ref module, name) => {
4775 collect_mod(names, &*module.upgrade().unwrap());
4777 BlockParentLink(ref module, _) => {
4778 // danger, shouldn't be ident?
4779 names.push(special_idents::opaque.name);
4780 collect_mod(names, &*module.upgrade().unwrap());
4784 collect_mod(&mut names, module);
4786 if names.len() == 0 {
4787 return "???".to_string();
4789 self.names_to_string(&names.into_iter().rev()
4790 .collect::<Vec<ast::Name>>()[])
4793 #[allow(dead_code)] // useful for debugging
4794 fn dump_module(&mut self, module_: Rc<Module>) {
4795 debug!("Dump of module `{}`:", self.module_to_string(&*module_));
4797 debug!("Children:");
4798 build_reduced_graph::populate_module_if_necessary(self, &module_);
4799 for (&name, _) in module_.children.borrow().iter() {
4800 debug!("* {}", token::get_name(name));
4803 debug!("Import resolutions:");
4804 let import_resolutions = module_.import_resolutions.borrow();
4805 for (&name, import_resolution) in import_resolutions.iter() {
4807 match import_resolution.target_for_namespace(ValueNS) {
4808 None => { value_repr = "".to_string(); }
4810 value_repr = " value:?".to_string();
4816 match import_resolution.target_for_namespace(TypeNS) {
4817 None => { type_repr = "".to_string(); }
4819 type_repr = " type:?".to_string();
4824 debug!("* {}:{}{}", token::get_name(name), value_repr, type_repr);
4829 pub struct CrateMap {
4830 pub def_map: DefMap,
4831 pub freevars: RefCell<FreevarMap>,
4832 pub capture_mode_map: RefCell<CaptureModeMap>,
4833 pub export_map: ExportMap,
4834 pub trait_map: TraitMap,
4835 pub external_exports: ExternalExports,
4836 pub last_private_map: LastPrivateMap,
4837 pub glob_map: Option<GlobMap>
4840 #[derive(PartialEq,Copy)]
4841 pub enum MakeGlobMap {
4846 /// Entry point to crate resolution.
4847 pub fn resolve_crate<'a, 'tcx>(session: &'a Session,
4848 ast_map: &'a ast_map::Map<'tcx>,
4851 make_glob_map: MakeGlobMap)
4853 let mut resolver = Resolver::new(session, ast_map, krate.span, make_glob_map);
4855 build_reduced_graph::build_reduced_graph(&mut resolver, krate);
4856 session.abort_if_errors();
4858 resolver.resolve_imports();
4859 session.abort_if_errors();
4861 record_exports::record(&mut resolver);
4862 session.abort_if_errors();
4864 resolver.resolve_crate(krate);
4865 session.abort_if_errors();
4867 check_unused::check_crate(&mut resolver, krate);
4870 def_map: resolver.def_map,
4871 freevars: resolver.freevars,
4872 capture_mode_map: RefCell::new(resolver.capture_mode_map),
4873 export_map: resolver.export_map,
4874 trait_map: resolver.trait_map,
4875 external_exports: resolver.external_exports,
4876 last_private_map: resolver.last_private,
4877 glob_map: if resolver.make_glob_map {
4878 Some(resolver.glob_map)