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"]
12 #![unstable(feature = "rustc_private")]
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/")]
21 #![feature(collections)]
24 #![feature(rustc_diagnostic_macros)]
25 #![feature(rustc_private)]
26 #![feature(staged_api)]
29 #[macro_use] extern crate log;
30 #[macro_use] extern crate syntax;
31 #[macro_use] #[no_link] extern crate rustc_bitflags;
35 use self::PatternBindingMode::*;
36 use self::Namespace::*;
37 use self::NamespaceResult::*;
38 use self::NameDefinition::*;
39 use self::ImportDirectiveSubclass::*;
40 use self::ResolveResult::*;
41 use self::FallbackSuggestion::*;
42 use self::TypeParameters::*;
44 use self::MethodSort::*;
45 use self::UseLexicalScopeFlag::*;
46 use self::ModulePrefixResult::*;
47 use self::NameSearchType::*;
48 use self::BareIdentifierPatternResolution::*;
49 use self::ParentLink::*;
50 use self::ModuleKind::*;
51 use self::TraitReferenceType::*;
52 use self::FallbackChecks::*;
54 use rustc::session::Session;
56 use rustc::metadata::csearch;
57 use rustc::metadata::decoder::{DefLike, DlDef, DlField, DlImpl};
58 use rustc::middle::def::*;
59 use rustc::middle::lang_items::LanguageItems;
60 use rustc::middle::pat_util::pat_bindings;
61 use rustc::middle::privacy::*;
62 use rustc::middle::subst::{ParamSpace, FnSpace, TypeSpace};
63 use rustc::middle::ty::{Freevar, FreevarMap, TraitMap, GlobMap};
64 use rustc::util::nodemap::{NodeMap, NodeSet, DefIdSet, FnvHashMap};
65 use rustc::util::lev_distance::lev_distance;
67 use syntax::ast::{Arm, BindByRef, BindByValue, BindingMode, Block, Crate, CrateNum};
68 use syntax::ast::{DefId, Expr, ExprAgain, ExprBreak, ExprField};
69 use syntax::ast::{ExprClosure, ExprLoop, ExprWhile, ExprMethodCall};
70 use syntax::ast::{ExprPath, ExprQPath, ExprStruct, FnDecl};
71 use syntax::ast::{ForeignItemFn, ForeignItemStatic, Generics};
72 use syntax::ast::{Ident, ImplItem, Item, ItemConst, ItemEnum, ItemExternCrate};
73 use syntax::ast::{ItemFn, ItemForeignMod, ItemImpl, ItemMac, ItemMod, ItemStatic};
74 use syntax::ast::{ItemStruct, ItemTrait, ItemTy, ItemUse};
75 use syntax::ast::{Local, MethodImplItem, Mod, Name, NodeId};
76 use syntax::ast::{Pat, PatEnum, PatIdent, PatLit};
77 use syntax::ast::{PatRange, PatStruct, Path};
78 use syntax::ast::{PolyTraitRef, PrimTy, SelfExplicit};
79 use syntax::ast::{RegionTyParamBound, StructField};
80 use syntax::ast::{TraitRef, TraitTyParamBound};
81 use syntax::ast::{Ty, TyBool, TyChar, TyF32};
82 use syntax::ast::{TyF64, TyFloat, TyIs, TyI8, TyI16, TyI32, TyI64, TyInt, TyObjectSum};
83 use syntax::ast::{TyParam, TyParamBound, TyPath, TyPtr, TyPolyTraitRef, TyQPath};
84 use syntax::ast::{TyRptr, TyStr, TyUs, TyU8, TyU16, TyU32, TyU64, TyUint};
85 use syntax::ast::{TypeImplItem};
88 use syntax::ast_util::{PostExpansionMethod, local_def, walk_pat};
89 use syntax::attr::AttrMetaMethods;
90 use syntax::ext::mtwt;
91 use syntax::parse::token::{self, special_names, special_idents};
92 use syntax::codemap::{Span, Pos};
93 use syntax::owned_slice::OwnedSlice;
94 use syntax::visit::{self, Visitor};
96 use std::collections::{HashMap, HashSet};
97 use std::collections::hash_map::Entry::{Occupied, Vacant};
98 use std::cell::{Cell, RefCell};
100 use std::mem::replace;
101 use std::rc::{Rc, Weak};
104 // NB: This module needs to be declared first so diagnostics are
105 // registered before they are used.
110 mod build_reduced_graph;
115 binding_mode: BindingMode,
118 // Map from the name in a pattern to its binding mode.
119 type BindingMap = HashMap<Name, BindingInfo>;
121 #[derive(Copy, PartialEq)]
122 enum PatternBindingMode {
124 LocalIrrefutableMode,
125 ArgumentIrrefutableMode,
128 #[derive(Copy, PartialEq, Eq, Hash, Debug)]
134 /// A NamespaceResult represents the result of resolving an import in
135 /// a particular namespace. The result is either definitely-resolved,
136 /// definitely- unresolved, or unknown.
138 enum NamespaceResult {
139 /// Means that resolve hasn't gathered enough information yet to determine
140 /// whether the name is bound in this namespace. (That is, it hasn't
141 /// resolved all `use` directives yet.)
143 /// Means that resolve has determined that the name is definitely
144 /// not bound in the namespace.
146 /// Means that resolve has determined that the name is bound in the Module
147 /// argument, and specified by the NameBindings argument.
148 BoundResult(Rc<Module>, Rc<NameBindings>)
151 impl NamespaceResult {
152 fn is_unknown(&self) -> bool {
154 UnknownResult => true,
158 fn is_unbound(&self) -> bool {
160 UnboundResult => true,
166 enum NameDefinition {
167 NoNameDefinition, //< The name was unbound.
168 ChildNameDefinition(Def, LastPrivate), //< The name identifies an immediate child.
169 ImportNameDefinition(Def, LastPrivate) //< The name identifies an import.
172 impl<'a, 'v, 'tcx> Visitor<'v> for Resolver<'a, 'tcx> {
173 fn visit_item(&mut self, item: &Item) {
174 self.resolve_item(item);
176 fn visit_arm(&mut self, arm: &Arm) {
177 self.resolve_arm(arm);
179 fn visit_block(&mut self, block: &Block) {
180 self.resolve_block(block);
182 fn visit_expr(&mut self, expr: &Expr) {
183 self.resolve_expr(expr);
185 fn visit_local(&mut self, local: &Local) {
186 self.resolve_local(local);
188 fn visit_ty(&mut self, ty: &Ty) {
189 self.resolve_type(ty);
193 /// Contains data for specific types of import directives.
194 #[derive(Copy,Debug)]
195 enum ImportDirectiveSubclass {
196 SingleImport(Name /* target */, Name /* source */),
200 type ErrorMessage = Option<(Span, String)>;
202 enum ResolveResult<T> {
203 Failed(ErrorMessage), // Failed to resolve the name, optional helpful error message.
204 Indeterminate, // Couldn't determine due to unresolved globs.
205 Success(T) // Successfully resolved the import.
208 impl<T> ResolveResult<T> {
209 fn indeterminate(&self) -> bool {
210 match *self { Indeterminate => true, _ => false }
214 enum FallbackSuggestion {
219 StaticMethod(String),
224 enum TypeParameters<'a> {
230 // Identifies the things that these parameters
231 // were declared on (type, fn, etc)
234 // ID of the enclosing item.
237 // The kind of the rib used for type parameters.
241 // The rib kind controls the translation of local
242 // definitions (`DefLocal`) to upvars (`DefUpvar`).
243 #[derive(Copy, Debug)]
245 // No translation needs to be applied.
248 // We passed through a closure scope at the given node ID.
249 // Translate upvars as appropriate.
250 ClosureRibKind(NodeId /* func id */),
252 // We passed through an impl or trait and are now in one of its
253 // methods. Allow references to ty params that impl or trait
254 // binds. Disallow any other upvars (including other ty params that are
256 // parent; method itself
257 MethodRibKind(NodeId, MethodSort),
259 // We passed through an item scope. Disallow upvars.
262 // We're in a constant item. Can't refer to dynamic stuff.
266 // Methods can be required or provided. RequiredMethod methods only occur in traits.
267 #[derive(Copy, Debug)]
270 ProvidedMethod(NodeId)
274 enum UseLexicalScopeFlag {
279 enum ModulePrefixResult {
281 PrefixFound(Rc<Module>, uint)
284 #[derive(Copy, PartialEq)]
285 enum NameSearchType {
286 /// We're doing a name search in order to resolve a `use` directive.
289 /// We're doing a name search in order to resolve a path type, a path
290 /// expression, or a path pattern.
295 enum BareIdentifierPatternResolution {
296 FoundStructOrEnumVariant(Def, LastPrivate),
297 FoundConst(Def, LastPrivate),
298 BareIdentifierPatternUnresolved
304 bindings: HashMap<Name, DefLike>,
309 fn new(kind: RibKind) -> Rib {
311 bindings: HashMap::new(),
317 /// Whether an import can be shadowed by another import.
318 #[derive(Debug,PartialEq,Clone,Copy)]
324 /// One import directive.
326 struct ImportDirective {
327 module_path: Vec<Name>,
328 subclass: ImportDirectiveSubclass,
331 is_public: bool, // see note in ImportResolution about how to use this
332 shadowable: Shadowable,
335 impl ImportDirective {
336 fn new(module_path: Vec<Name> ,
337 subclass: ImportDirectiveSubclass,
341 shadowable: Shadowable)
344 module_path: module_path,
348 is_public: is_public,
349 shadowable: shadowable,
354 /// The item that an import resolves to.
355 #[derive(Clone,Debug)]
357 target_module: Rc<Module>,
358 bindings: Rc<NameBindings>,
359 shadowable: Shadowable,
363 fn new(target_module: Rc<Module>,
364 bindings: Rc<NameBindings>,
365 shadowable: Shadowable)
368 target_module: target_module,
370 shadowable: shadowable,
375 /// An ImportResolution represents a particular `use` directive.
377 struct ImportResolution {
378 /// Whether this resolution came from a `use` or a `pub use`. Note that this
379 /// should *not* be used whenever resolution is being performed, this is
380 /// only looked at for glob imports statements currently. Privacy testing
381 /// occurs during a later phase of compilation.
384 // The number of outstanding references to this name. When this reaches
385 // zero, outside modules can count on the targets being correct. Before
386 // then, all bets are off; future imports could override this name.
387 outstanding_references: uint,
389 /// The value that this `use` directive names, if there is one.
390 value_target: Option<Target>,
391 /// The source node of the `use` directive leading to the value target
395 /// The type that this `use` directive names, if there is one.
396 type_target: Option<Target>,
397 /// The source node of the `use` directive leading to the type target
402 impl ImportResolution {
403 fn new(id: NodeId, is_public: bool) -> ImportResolution {
407 outstanding_references: 0,
410 is_public: is_public,
414 fn target_for_namespace(&self, namespace: Namespace)
417 TypeNS => self.type_target.clone(),
418 ValueNS => self.value_target.clone(),
422 fn id(&self, namespace: Namespace) -> NodeId {
424 TypeNS => self.type_id,
425 ValueNS => self.value_id,
429 fn shadowable(&self, namespace: Namespace) -> Shadowable {
430 let target = self.target_for_namespace(namespace);
431 if target.is_none() {
432 return Shadowable::Always;
435 target.unwrap().shadowable
438 fn set_target_and_id(&mut self,
439 namespace: Namespace,
440 target: Option<Target>,
444 self.type_target = target;
448 self.value_target = target;
455 /// The link from a module up to its nearest parent node.
456 #[derive(Clone,Debug)]
459 ModuleParentLink(Weak<Module>, Name),
460 BlockParentLink(Weak<Module>, NodeId)
463 /// The type of module this is.
464 #[derive(Copy, PartialEq, Debug)]
474 /// One node in the tree of modules.
476 parent_link: ParentLink,
477 def_id: Cell<Option<DefId>>,
478 kind: Cell<ModuleKind>,
481 children: RefCell<HashMap<Name, Rc<NameBindings>>>,
482 imports: RefCell<Vec<ImportDirective>>,
484 // The external module children of this node that were declared with
486 external_module_children: RefCell<HashMap<Name, Rc<Module>>>,
488 // The anonymous children of this node. Anonymous children are pseudo-
489 // modules that are implicitly created around items contained within
492 // For example, if we have this:
500 // There will be an anonymous module created around `g` with the ID of the
501 // entry block for `f`.
502 anonymous_children: RefCell<NodeMap<Rc<Module>>>,
504 // The status of resolving each import in this module.
505 import_resolutions: RefCell<HashMap<Name, ImportResolution>>,
507 // The number of unresolved globs that this module exports.
508 glob_count: Cell<uint>,
510 // The index of the import we're resolving.
511 resolved_import_count: Cell<uint>,
513 // Whether this module is populated. If not populated, any attempt to
514 // access the children must be preceded with a
515 // `populate_module_if_necessary` call.
516 populated: Cell<bool>,
520 fn new(parent_link: ParentLink,
521 def_id: Option<DefId>,
527 parent_link: parent_link,
528 def_id: Cell::new(def_id),
529 kind: Cell::new(kind),
530 is_public: is_public,
531 children: RefCell::new(HashMap::new()),
532 imports: RefCell::new(Vec::new()),
533 external_module_children: RefCell::new(HashMap::new()),
534 anonymous_children: RefCell::new(NodeMap()),
535 import_resolutions: RefCell::new(HashMap::new()),
536 glob_count: Cell::new(0),
537 resolved_import_count: Cell::new(0),
538 populated: Cell::new(!external),
542 fn all_imports_resolved(&self) -> bool {
543 self.imports.borrow().len() == self.resolved_import_count.get()
547 impl fmt::Debug for Module {
548 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
549 write!(f, "{:?}, kind: {:?}, {}",
552 if self.is_public { "public" } else { "private" } )
558 flags DefModifiers: u8 {
559 const PUBLIC = 0b0000_0001,
560 const IMPORTABLE = 0b0000_0010,
564 // Records a possibly-private type definition.
565 #[derive(Clone,Debug)]
567 modifiers: DefModifiers, // see note in ImportResolution about how to use this
568 module_def: Option<Rc<Module>>,
569 type_def: Option<Def>,
570 type_span: Option<Span>
573 // Records a possibly-private value definition.
574 #[derive(Clone, Copy, Debug)]
576 modifiers: DefModifiers, // see note in ImportResolution about how to use this
578 value_span: Option<Span>,
581 // Records the definitions (at most one for each namespace) that a name is
584 struct NameBindings {
585 type_def: RefCell<Option<TypeNsDef>>, //< Meaning in type namespace.
586 value_def: RefCell<Option<ValueNsDef>>, //< Meaning in value namespace.
589 /// Ways in which a trait can be referenced
591 enum TraitReferenceType {
592 TraitImplementation, // impl SomeTrait for T { ... }
593 TraitDerivation, // trait T : SomeTrait { ... }
594 TraitBoundingTypeParameter, // fn f<T:SomeTrait>() { ... }
595 TraitObject, // Box<for<'a> SomeTrait>
596 TraitQPath, // <T as SomeTrait>::
600 fn new() -> NameBindings {
602 type_def: RefCell::new(None),
603 value_def: RefCell::new(None),
607 /// Creates a new module in this set of name bindings.
608 fn define_module(&self,
609 parent_link: ParentLink,
610 def_id: Option<DefId>,
615 // Merges the module with the existing type def or creates a new one.
616 let modifiers = if is_public { PUBLIC } else { DefModifiers::empty() } | IMPORTABLE;
617 let module_ = Rc::new(Module::new(parent_link,
622 let type_def = self.type_def.borrow().clone();
625 *self.type_def.borrow_mut() = Some(TypeNsDef {
626 modifiers: modifiers,
627 module_def: Some(module_),
633 *self.type_def.borrow_mut() = Some(TypeNsDef {
634 modifiers: modifiers,
635 module_def: Some(module_),
637 type_def: type_def.type_def
643 /// Sets the kind of the module, creating a new one if necessary.
644 fn set_module_kind(&self,
645 parent_link: ParentLink,
646 def_id: Option<DefId>,
651 let modifiers = if is_public { PUBLIC } else { DefModifiers::empty() } | IMPORTABLE;
652 let type_def = self.type_def.borrow().clone();
655 let module = Module::new(parent_link,
660 *self.type_def.borrow_mut() = Some(TypeNsDef {
661 modifiers: modifiers,
662 module_def: Some(Rc::new(module)),
668 match type_def.module_def {
670 let module = Module::new(parent_link,
675 *self.type_def.borrow_mut() = Some(TypeNsDef {
676 modifiers: modifiers,
677 module_def: Some(Rc::new(module)),
678 type_def: type_def.type_def,
682 Some(module_def) => module_def.kind.set(kind),
688 /// Records a type definition.
689 fn define_type(&self, def: Def, sp: Span, modifiers: DefModifiers) {
690 debug!("defining type for def {:?} with modifiers {:?}", def, modifiers);
691 // Merges the type with the existing type def or creates a new one.
692 let type_def = self.type_def.borrow().clone();
695 *self.type_def.borrow_mut() = Some(TypeNsDef {
699 modifiers: modifiers,
703 *self.type_def.borrow_mut() = Some(TypeNsDef {
704 module_def: type_def.module_def,
707 modifiers: modifiers,
713 /// Records a value definition.
714 fn define_value(&self, def: Def, sp: Span, modifiers: DefModifiers) {
715 debug!("defining value for def {:?} with modifiers {:?}", def, modifiers);
716 *self.value_def.borrow_mut() = Some(ValueNsDef {
718 value_span: Some(sp),
719 modifiers: modifiers,
723 /// Returns the module node if applicable.
724 fn get_module_if_available(&self) -> Option<Rc<Module>> {
725 match *self.type_def.borrow() {
726 Some(ref type_def) => type_def.module_def.clone(),
731 /// Returns the module node. Panics if this node does not have a module
733 fn get_module(&self) -> Rc<Module> {
734 match self.get_module_if_available() {
736 panic!("get_module called on a node with no module \
739 Some(module_def) => module_def
743 fn defined_in_namespace(&self, namespace: Namespace) -> bool {
745 TypeNS => return self.type_def.borrow().is_some(),
746 ValueNS => return self.value_def.borrow().is_some()
750 fn defined_in_public_namespace(&self, namespace: Namespace) -> bool {
751 self.defined_in_namespace_with(namespace, PUBLIC)
754 fn defined_in_namespace_with(&self, namespace: Namespace, modifiers: DefModifiers) -> bool {
756 TypeNS => match *self.type_def.borrow() {
757 Some(ref def) => def.modifiers.contains(modifiers), None => false
759 ValueNS => match *self.value_def.borrow() {
760 Some(ref def) => def.modifiers.contains(modifiers), None => false
765 fn def_for_namespace(&self, namespace: Namespace) -> Option<Def> {
768 match *self.type_def.borrow() {
770 Some(ref type_def) => {
771 match type_def.type_def {
772 Some(type_def) => Some(type_def),
774 match type_def.module_def {
775 Some(ref module) => {
776 match module.def_id.get() {
777 Some(did) => Some(DefMod(did)),
789 match *self.value_def.borrow() {
791 Some(value_def) => Some(value_def.def)
797 fn span_for_namespace(&self, namespace: Namespace) -> Option<Span> {
798 if self.defined_in_namespace(namespace) {
801 match *self.type_def.borrow() {
803 Some(ref type_def) => type_def.type_span
807 match *self.value_def.borrow() {
809 Some(ref value_def) => value_def.value_span
819 /// Interns the names of the primitive types.
820 struct PrimitiveTypeTable {
821 primitive_types: HashMap<Name, PrimTy>,
824 impl PrimitiveTypeTable {
825 fn new() -> PrimitiveTypeTable {
826 let mut table = PrimitiveTypeTable {
827 primitive_types: HashMap::new()
830 table.intern("bool", TyBool);
831 table.intern("char", TyChar);
832 table.intern("f32", TyFloat(TyF32));
833 table.intern("f64", TyFloat(TyF64));
834 table.intern("int", TyInt(TyIs(true)));
835 table.intern("isize", TyInt(TyIs(false)));
836 table.intern("i8", TyInt(TyI8));
837 table.intern("i16", TyInt(TyI16));
838 table.intern("i32", TyInt(TyI32));
839 table.intern("i64", TyInt(TyI64));
840 table.intern("str", TyStr);
841 table.intern("uint", TyUint(TyUs(true)));
842 table.intern("usize", TyUint(TyUs(false)));
843 table.intern("u8", TyUint(TyU8));
844 table.intern("u16", TyUint(TyU16));
845 table.intern("u32", TyUint(TyU32));
846 table.intern("u64", TyUint(TyU64));
851 fn intern(&mut self, string: &str, primitive_type: PrimTy) {
852 self.primitive_types.insert(token::intern(string), primitive_type);
856 /// The main resolver class.
857 struct Resolver<'a, 'tcx:'a> {
858 session: &'a Session,
860 ast_map: &'a ast_map::Map<'tcx>,
862 graph_root: NameBindings,
864 trait_item_map: FnvHashMap<(Name, DefId), TraitItemKind>,
866 structs: FnvHashMap<DefId, Vec<Name>>,
868 // The number of imports that are currently unresolved.
869 unresolved_imports: uint,
871 // The module that represents the current item scope.
872 current_module: Rc<Module>,
874 // The current set of local scopes, for values.
875 // FIXME #4948: Reuse ribs to avoid allocation.
876 value_ribs: Vec<Rib>,
878 // The current set of local scopes, for types.
881 // The current set of local scopes, for labels.
882 label_ribs: Vec<Rib>,
884 // The trait that the current context can refer to.
885 current_trait_ref: Option<(DefId, TraitRef)>,
887 // The current self type if inside an impl (used for better errors).
888 current_self_type: Option<Ty>,
890 // The ident for the keyword "self".
892 // The ident for the non-keyword "Self".
893 type_self_name: Name,
895 // The idents for the primitive types.
896 primitive_type_table: PrimitiveTypeTable,
899 freevars: RefCell<FreevarMap>,
900 freevars_seen: RefCell<NodeMap<NodeSet>>,
901 export_map: ExportMap,
903 external_exports: ExternalExports,
904 last_private: LastPrivateMap,
906 // Whether or not to print error messages. Can be set to true
907 // when getting additional info for error message suggestions,
908 // so as to avoid printing duplicate errors
912 // Maps imports to the names of items actually imported (this actually maps
913 // all imports, but only glob imports are actually interesting).
916 used_imports: HashSet<(NodeId, Namespace)>,
917 used_crates: HashSet<CrateNum>,
921 enum FallbackChecks {
927 impl<'a, 'tcx> Resolver<'a, 'tcx> {
928 fn new(session: &'a Session,
929 ast_map: &'a ast_map::Map<'tcx>,
931 make_glob_map: MakeGlobMap) -> Resolver<'a, 'tcx> {
932 let graph_root = NameBindings::new();
934 graph_root.define_module(NoParentLink,
935 Some(DefId { krate: 0, node: 0 }),
941 let current_module = graph_root.get_module();
948 // The outermost module has def ID 0; this is not reflected in the
951 graph_root: graph_root,
953 trait_item_map: FnvHashMap(),
954 structs: FnvHashMap(),
956 unresolved_imports: 0,
958 current_module: current_module,
959 value_ribs: Vec::new(),
960 type_ribs: Vec::new(),
961 label_ribs: Vec::new(),
963 current_trait_ref: None,
964 current_self_type: None,
966 self_name: special_names::self_,
967 type_self_name: special_names::type_self,
969 primitive_type_table: PrimitiveTypeTable::new(),
971 def_map: RefCell::new(NodeMap()),
972 freevars: RefCell::new(NodeMap()),
973 freevars_seen: RefCell::new(NodeMap()),
974 export_map: NodeMap(),
975 trait_map: NodeMap(),
976 used_imports: HashSet::new(),
977 used_crates: HashSet::new(),
978 external_exports: DefIdSet(),
979 last_private: NodeMap(),
982 make_glob_map: make_glob_map == MakeGlobMap::Yes,
983 glob_map: HashMap::new(),
989 // This is a fixed-point algorithm. We resolve imports until our efforts
990 // are stymied by an unresolved import; then we bail out of the current
991 // module and continue. We terminate successfully once no more imports
992 // remain or unsuccessfully when no forward progress in resolving imports
995 /// Resolves all imports for the crate. This method performs the fixed-
997 fn resolve_imports(&mut self) {
999 let mut prev_unresolved_imports = 0;
1001 debug!("(resolving imports) iteration {}, {} imports left",
1002 i, self.unresolved_imports);
1004 let module_root = self.graph_root.get_module();
1005 self.resolve_imports_for_module_subtree(module_root.clone());
1007 if self.unresolved_imports == 0 {
1008 debug!("(resolving imports) success");
1012 if self.unresolved_imports == prev_unresolved_imports {
1013 self.report_unresolved_imports(module_root);
1018 prev_unresolved_imports = self.unresolved_imports;
1022 /// Attempts to resolve imports for the given module and all of its
1024 fn resolve_imports_for_module_subtree(&mut self, module_: Rc<Module>) {
1025 debug!("(resolving imports for module subtree) resolving {}",
1026 self.module_to_string(&*module_));
1027 let orig_module = replace(&mut self.current_module, module_.clone());
1028 self.resolve_imports_for_module(module_.clone());
1029 self.current_module = orig_module;
1031 build_reduced_graph::populate_module_if_necessary(self, &module_);
1032 for (_, child_node) in &*module_.children.borrow() {
1033 match child_node.get_module_if_available() {
1037 Some(child_module) => {
1038 self.resolve_imports_for_module_subtree(child_module);
1043 for (_, child_module) in &*module_.anonymous_children.borrow() {
1044 self.resolve_imports_for_module_subtree(child_module.clone());
1048 /// Attempts to resolve imports for the given module only.
1049 fn resolve_imports_for_module(&mut self, module: Rc<Module>) {
1050 if module.all_imports_resolved() {
1051 debug!("(resolving imports for module) all imports resolved for \
1053 self.module_to_string(&*module));
1057 let imports = module.imports.borrow();
1058 let import_count = imports.len();
1059 while module.resolved_import_count.get() < import_count {
1060 let import_index = module.resolved_import_count.get();
1061 let import_directive = &(*imports)[import_index];
1062 match self.resolve_import_for_module(module.clone(),
1065 let (span, help) = match err {
1066 Some((span, msg)) => (span, format!(". {}", msg)),
1067 None => (import_directive.span, String::new())
1069 let msg = format!("unresolved import `{}`{}",
1070 self.import_path_to_string(
1071 &import_directive.module_path[],
1072 import_directive.subclass),
1074 self.resolve_error(span, &msg[..]);
1076 Indeterminate => break, // Bail out. We'll come around next time.
1077 Success(()) => () // Good. Continue.
1080 module.resolved_import_count
1081 .set(module.resolved_import_count.get() + 1);
1085 fn names_to_string(&self, names: &[Name]) -> String {
1086 let mut first = true;
1087 let mut result = String::new();
1092 result.push_str("::")
1094 result.push_str(&token::get_name(*name));
1099 fn path_names_to_string(&self, path: &Path) -> String {
1100 let names: Vec<ast::Name> = path.segments
1102 .map(|seg| seg.identifier.name)
1104 self.names_to_string(&names[..])
1107 fn import_directive_subclass_to_string(&mut self,
1108 subclass: ImportDirectiveSubclass)
1111 SingleImport(_, source) => {
1112 token::get_name(source).to_string()
1114 GlobImport => "*".to_string()
1118 fn import_path_to_string(&mut self,
1120 subclass: ImportDirectiveSubclass)
1122 if names.is_empty() {
1123 self.import_directive_subclass_to_string(subclass)
1126 self.names_to_string(names),
1127 self.import_directive_subclass_to_string(
1128 subclass))).to_string()
1133 fn record_import_use(&mut self, import_id: NodeId, name: Name) {
1134 if !self.make_glob_map {
1137 if self.glob_map.contains_key(&import_id) {
1138 self.glob_map[import_id].insert(name);
1142 let mut new_set = HashSet::new();
1143 new_set.insert(name);
1144 self.glob_map.insert(import_id, new_set);
1147 fn get_trait_name(&self, did: DefId) -> Name {
1148 if did.krate == ast::LOCAL_CRATE {
1149 self.ast_map.expect_item(did.node).ident.name
1151 csearch::get_trait_name(&self.session.cstore, did)
1155 /// Attempts to resolve the given import. The return value indicates
1156 /// failure if we're certain the name does not exist, indeterminate if we
1157 /// don't know whether the name exists at the moment due to other
1158 /// currently-unresolved imports, or success if we know the name exists.
1159 /// If successful, the resolved bindings are written into the module.
1160 fn resolve_import_for_module(&mut self,
1161 module_: Rc<Module>,
1162 import_directive: &ImportDirective)
1163 -> ResolveResult<()> {
1164 let mut resolution_result = Failed(None);
1165 let module_path = &import_directive.module_path;
1167 debug!("(resolving import for module) resolving import `{}::...` in `{}`",
1168 self.names_to_string(&module_path[..]),
1169 self.module_to_string(&*module_));
1171 // First, resolve the module path for the directive, if necessary.
1172 let container = if module_path.len() == 0 {
1173 // Use the crate root.
1174 Some((self.graph_root.get_module(), LastMod(AllPublic)))
1176 match self.resolve_module_path(module_.clone(),
1178 DontUseLexicalScope,
1179 import_directive.span,
1182 resolution_result = Failed(err);
1186 resolution_result = Indeterminate;
1189 Success(container) => Some(container),
1195 Some((containing_module, lp)) => {
1196 // We found the module that the target is contained
1197 // within. Attempt to resolve the import within it.
1199 match import_directive.subclass {
1200 SingleImport(target, source) => {
1202 self.resolve_single_import(&*module_,
1211 self.resolve_glob_import(&*module_,
1220 // Decrement the count of unresolved imports.
1221 match resolution_result {
1223 assert!(self.unresolved_imports >= 1);
1224 self.unresolved_imports -= 1;
1227 // Nothing to do here; just return the error.
1231 // Decrement the count of unresolved globs if necessary. But only if
1232 // the resolution result is indeterminate -- otherwise we'll stop
1233 // processing imports here. (See the loop in
1234 // resolve_imports_for_module.)
1236 if !resolution_result.indeterminate() {
1237 match import_directive.subclass {
1239 assert!(module_.glob_count.get() >= 1);
1240 module_.glob_count.set(module_.glob_count.get() - 1);
1242 SingleImport(..) => {
1248 return resolution_result;
1251 fn create_name_bindings_from_module(module: Rc<Module>) -> NameBindings {
1253 type_def: RefCell::new(Some(TypeNsDef {
1254 modifiers: IMPORTABLE,
1255 module_def: Some(module),
1259 value_def: RefCell::new(None),
1263 fn resolve_single_import(&mut self,
1265 containing_module: Rc<Module>,
1268 directive: &ImportDirective,
1270 -> ResolveResult<()> {
1271 debug!("(resolving single import) resolving `{}` = `{}::{}` from \
1272 `{}` id {}, last private {:?}",
1273 token::get_name(target),
1274 self.module_to_string(&*containing_module),
1275 token::get_name(source),
1276 self.module_to_string(module_),
1282 LastImport {..} => {
1284 .span_bug(directive.span,
1285 "not expecting Import here, must be LastMod")
1289 // We need to resolve both namespaces for this to succeed.
1292 let mut value_result = UnknownResult;
1293 let mut type_result = UnknownResult;
1295 // Search for direct children of the containing module.
1296 build_reduced_graph::populate_module_if_necessary(self, &containing_module);
1298 match containing_module.children.borrow().get(&source) {
1302 Some(ref child_name_bindings) => {
1303 if child_name_bindings.defined_in_namespace(ValueNS) {
1304 debug!("(resolving single import) found value binding");
1305 value_result = BoundResult(containing_module.clone(),
1306 (*child_name_bindings).clone());
1308 if child_name_bindings.defined_in_namespace(TypeNS) {
1309 debug!("(resolving single import) found type binding");
1310 type_result = BoundResult(containing_module.clone(),
1311 (*child_name_bindings).clone());
1316 // Unless we managed to find a result in both namespaces (unlikely),
1317 // search imports as well.
1318 let mut value_used_reexport = false;
1319 let mut type_used_reexport = false;
1320 match (value_result.clone(), type_result.clone()) {
1321 (BoundResult(..), BoundResult(..)) => {} // Continue.
1323 // If there is an unresolved glob at this point in the
1324 // containing module, bail out. We don't know enough to be
1325 // able to resolve this import.
1327 if containing_module.glob_count.get() > 0 {
1328 debug!("(resolving single import) unresolved glob; \
1330 return Indeterminate;
1333 // Now search the exported imports within the containing module.
1334 match containing_module.import_resolutions.borrow().get(&source) {
1336 debug!("(resolving single import) no import");
1337 // The containing module definitely doesn't have an
1338 // exported import with the name in question. We can
1339 // therefore accurately report that the names are
1342 if value_result.is_unknown() {
1343 value_result = UnboundResult;
1345 if type_result.is_unknown() {
1346 type_result = UnboundResult;
1349 Some(import_resolution)
1350 if import_resolution.outstanding_references == 0 => {
1352 fn get_binding(this: &mut Resolver,
1353 import_resolution: &ImportResolution,
1354 namespace: Namespace,
1356 -> NamespaceResult {
1358 // Import resolutions must be declared with "pub"
1359 // in order to be exported.
1360 if !import_resolution.is_public {
1361 return UnboundResult;
1364 match import_resolution.
1365 target_for_namespace(namespace) {
1367 return UnboundResult;
1374 debug!("(resolving single import) found \
1375 import in ns {:?}", namespace);
1376 let id = import_resolution.id(namespace);
1377 // track used imports and extern crates as well
1378 this.used_imports.insert((id, namespace));
1379 this.record_import_use(id, *source);
1380 match target_module.def_id.get() {
1381 Some(DefId{krate: kid, ..}) => {
1382 this.used_crates.insert(kid);
1386 return BoundResult(target_module, bindings);
1391 // The name is an import which has been fully
1392 // resolved. We can, therefore, just follow it.
1393 if value_result.is_unknown() {
1394 value_result = get_binding(self,
1398 value_used_reexport = import_resolution.is_public;
1400 if type_result.is_unknown() {
1401 type_result = get_binding(self,
1405 type_used_reexport = import_resolution.is_public;
1410 // If containing_module is the same module whose import we are resolving
1411 // and there it has an unresolved import with the same name as `source`,
1412 // then the user is actually trying to import an item that is declared
1413 // in the same scope
1416 // use self::submodule;
1417 // pub mod submodule;
1419 // In this case we continue as if we resolved the import and let the
1420 // check_for_conflicts_between_imports_and_items call below handle
1422 match (module_.def_id.get(), containing_module.def_id.get()) {
1423 (Some(id1), Some(id2)) if id1 == id2 => {
1424 if value_result.is_unknown() {
1425 value_result = UnboundResult;
1427 if type_result.is_unknown() {
1428 type_result = UnboundResult;
1432 // The import is unresolved. Bail out.
1433 debug!("(resolving single import) unresolved import; \
1435 return Indeterminate;
1443 // If we didn't find a result in the type namespace, search the
1444 // external modules.
1445 let mut value_used_public = false;
1446 let mut type_used_public = false;
1448 BoundResult(..) => {}
1450 match containing_module.external_module_children.borrow_mut()
1451 .get(&source).cloned() {
1452 None => {} // Continue.
1454 debug!("(resolving single import) found external \
1456 // track the module as used.
1457 match module.def_id.get() {
1458 Some(DefId{krate: kid, ..}) => { self.used_crates.insert(kid); },
1462 Rc::new(Resolver::create_name_bindings_from_module(
1464 type_result = BoundResult(containing_module.clone(),
1466 type_used_public = true;
1472 // We've successfully resolved the import. Write the results in.
1473 let mut import_resolutions = module_.import_resolutions.borrow_mut();
1474 let import_resolution = &mut (*import_resolutions)[target];
1476 let mut check_and_write_import = |namespace, result: &_, used_public: &mut bool| {
1477 let namespace_name = match namespace {
1483 BoundResult(ref target_module, ref name_bindings) => {
1484 debug!("(resolving single import) found {:?} target: {:?}",
1486 name_bindings.def_for_namespace(namespace));
1487 self.check_for_conflicting_import(
1488 &import_resolution.target_for_namespace(namespace),
1493 self.check_that_import_is_importable(
1499 let target = Some(Target::new(target_module.clone(),
1500 name_bindings.clone(),
1501 directive.shadowable));
1502 import_resolution.set_target_and_id(namespace, target, directive.id);
1503 import_resolution.is_public = directive.is_public;
1504 *used_public = name_bindings.defined_in_public_namespace(namespace);
1506 UnboundResult => { /* Continue. */ }
1508 panic!("{:?} result should be known at this point", namespace_name);
1512 check_and_write_import(ValueNS, &value_result, &mut value_used_public);
1513 check_and_write_import(TypeNS, &type_result, &mut type_used_public);
1516 self.check_for_conflicts_between_imports_and_items(
1522 if value_result.is_unbound() && type_result.is_unbound() {
1523 let msg = format!("There is no `{}` in `{}`",
1524 token::get_name(source),
1525 self.module_to_string(&*containing_module));
1526 return Failed(Some((directive.span, msg)));
1528 let value_used_public = value_used_reexport || value_used_public;
1529 let type_used_public = type_used_reexport || type_used_public;
1531 assert!(import_resolution.outstanding_references >= 1);
1532 import_resolution.outstanding_references -= 1;
1534 // record what this import resolves to for later uses in documentation,
1535 // this may resolve to either a value or a type, but for documentation
1536 // purposes it's good enough to just favor one over the other.
1537 let value_private = match import_resolution.value_target {
1538 Some(ref target) => {
1539 let def = target.bindings.def_for_namespace(ValueNS).unwrap();
1540 self.def_map.borrow_mut().insert(directive.id, def);
1541 let did = def.def_id();
1542 if value_used_public {Some(lp)} else {Some(DependsOn(did))}
1544 // AllPublic here and below is a dummy value, it should never be used because
1545 // _exists is false.
1548 let type_private = match import_resolution.type_target {
1549 Some(ref target) => {
1550 let def = target.bindings.def_for_namespace(TypeNS).unwrap();
1551 self.def_map.borrow_mut().insert(directive.id, def);
1552 let did = def.def_id();
1553 if type_used_public {Some(lp)} else {Some(DependsOn(did))}
1558 self.last_private.insert(directive.id, LastImport{value_priv: value_private,
1560 type_priv: type_private,
1563 debug!("(resolving single import) successfully resolved import");
1567 // Resolves a glob import. Note that this function cannot fail; it either
1568 // succeeds or bails out (as importing * from an empty module or a module
1569 // that exports nothing is valid). containing_module is the module we are
1570 // actually importing, i.e., `foo` in `use foo::*`.
1571 fn resolve_glob_import(&mut self,
1573 containing_module: Rc<Module>,
1574 import_directive: &ImportDirective,
1576 -> ResolveResult<()> {
1577 let id = import_directive.id;
1578 let is_public = import_directive.is_public;
1580 // This function works in a highly imperative manner; it eagerly adds
1581 // everything it can to the list of import resolutions of the module
1583 debug!("(resolving glob import) resolving glob import {}", id);
1585 // We must bail out if the node has unresolved imports of any kind
1586 // (including globs).
1587 if !(*containing_module).all_imports_resolved() {
1588 debug!("(resolving glob import) target module has unresolved \
1589 imports; bailing out");
1590 return Indeterminate;
1593 assert_eq!(containing_module.glob_count.get(), 0);
1595 // Add all resolved imports from the containing module.
1596 let import_resolutions = containing_module.import_resolutions.borrow();
1597 for (ident, target_import_resolution) in &*import_resolutions {
1598 debug!("(resolving glob import) writing module resolution \
1600 token::get_name(*ident),
1601 self.module_to_string(module_));
1603 if !target_import_resolution.is_public {
1604 debug!("(resolving glob import) nevermind, just kidding");
1608 // Here we merge two import resolutions.
1609 let mut import_resolutions = module_.import_resolutions.borrow_mut();
1610 match import_resolutions.get_mut(ident) {
1611 Some(dest_import_resolution) => {
1612 // Merge the two import resolutions at a finer-grained
1615 match target_import_resolution.value_target {
1619 Some(ref value_target) => {
1620 self.check_for_conflicting_import(&dest_import_resolution.value_target,
1621 import_directive.span,
1624 dest_import_resolution.value_target = Some(value_target.clone());
1627 match target_import_resolution.type_target {
1631 Some(ref type_target) => {
1632 self.check_for_conflicting_import(&dest_import_resolution.type_target,
1633 import_directive.span,
1636 dest_import_resolution.type_target = Some(type_target.clone());
1639 dest_import_resolution.is_public = is_public;
1645 // Simple: just copy the old import resolution.
1646 let mut new_import_resolution = ImportResolution::new(id, is_public);
1647 new_import_resolution.value_target =
1648 target_import_resolution.value_target.clone();
1649 new_import_resolution.type_target =
1650 target_import_resolution.type_target.clone();
1652 import_resolutions.insert(*ident, new_import_resolution);
1655 // Add all children from the containing module.
1656 build_reduced_graph::populate_module_if_necessary(self, &containing_module);
1658 for (&name, name_bindings) in &*containing_module.children.borrow() {
1659 self.merge_import_resolution(module_,
1660 containing_module.clone(),
1663 name_bindings.clone());
1667 // Add external module children from the containing module.
1668 for (&name, module) in &*containing_module.external_module_children.borrow() {
1670 Rc::new(Resolver::create_name_bindings_from_module(module.clone()));
1671 self.merge_import_resolution(module_,
1672 containing_module.clone(),
1678 // Record the destination of this import
1679 match containing_module.def_id.get() {
1681 self.def_map.borrow_mut().insert(id, DefMod(did));
1682 self.last_private.insert(id, lp);
1687 debug!("(resolving glob import) successfully resolved import");
1691 fn merge_import_resolution(&mut self,
1693 containing_module: Rc<Module>,
1694 import_directive: &ImportDirective,
1696 name_bindings: Rc<NameBindings>) {
1697 let id = import_directive.id;
1698 let is_public = import_directive.is_public;
1700 let mut import_resolutions = module_.import_resolutions.borrow_mut();
1701 let dest_import_resolution = import_resolutions.entry(name).get().unwrap_or_else(
1703 // Create a new import resolution from this child.
1704 vacant_entry.insert(ImportResolution::new(id, is_public))
1707 debug!("(resolving glob import) writing resolution `{}` in `{}` \
1709 &token::get_name(name),
1710 self.module_to_string(&*containing_module),
1711 self.module_to_string(module_));
1713 // Merge the child item into the import resolution.
1715 let mut merge_child_item = |namespace| {
1716 if name_bindings.defined_in_namespace_with(namespace, IMPORTABLE | PUBLIC) {
1717 let namespace_name = match namespace {
1721 debug!("(resolving glob import) ... for {} target", namespace_name);
1722 if dest_import_resolution.shadowable(namespace) == Shadowable::Never {
1723 let msg = format!("a {} named `{}` has already been imported \
1726 &token::get_name(name));
1727 span_err!(self.session, import_directive.span, E0251, "{}", msg);
1729 let target = Target::new(containing_module.clone(),
1730 name_bindings.clone(),
1731 import_directive.shadowable);
1732 dest_import_resolution.set_target_and_id(namespace,
1738 merge_child_item(ValueNS);
1739 merge_child_item(TypeNS);
1742 dest_import_resolution.is_public = is_public;
1744 self.check_for_conflicts_between_imports_and_items(
1746 dest_import_resolution,
1747 import_directive.span,
1751 /// Checks that imported names and items don't have the same name.
1752 fn check_for_conflicting_import(&mut self,
1753 target: &Option<Target>,
1756 namespace: Namespace) {
1757 debug!("check_for_conflicting_import: {}; target exists: {}",
1758 &token::get_name(name),
1762 Some(ref target) if target.shadowable != Shadowable::Always => {
1763 let msg = format!("a {} named `{}` has already been imported \
1769 &token::get_name(name));
1770 span_err!(self.session, import_span, E0252, "{}", &msg[..]);
1772 Some(_) | None => {}
1776 /// Checks that an import is actually importable
1777 fn check_that_import_is_importable(&mut self,
1778 name_bindings: &NameBindings,
1781 namespace: Namespace) {
1782 if !name_bindings.defined_in_namespace_with(namespace, IMPORTABLE) {
1783 let msg = format!("`{}` is not directly importable",
1784 token::get_name(name));
1785 span_err!(self.session, import_span, E0253, "{}", &msg[..]);
1789 /// Checks that imported names and items don't have the same name.
1790 fn check_for_conflicts_between_imports_and_items(&mut self,
1796 // First, check for conflicts between imports and `extern crate`s.
1797 if module.external_module_children
1799 .contains_key(&name) {
1800 match import_resolution.type_target {
1801 Some(ref target) if target.shadowable != Shadowable::Always => {
1802 let msg = format!("import `{0}` conflicts with imported \
1803 crate in this module \
1804 (maybe you meant `use {0}::*`?)",
1805 &token::get_name(name));
1806 span_err!(self.session, import_span, E0254, "{}", &msg[..]);
1808 Some(_) | None => {}
1812 // Check for item conflicts.
1813 let children = module.children.borrow();
1814 let name_bindings = match children.get(&name) {
1816 // There can't be any conflicts.
1819 Some(ref name_bindings) => (*name_bindings).clone(),
1822 match import_resolution.value_target {
1823 Some(ref target) if target.shadowable != Shadowable::Always => {
1824 if let Some(ref value) = *name_bindings.value_def.borrow() {
1825 let msg = format!("import `{}` conflicts with value \
1827 &token::get_name(name));
1828 span_err!(self.session, import_span, E0255, "{}", &msg[..]);
1829 if let Some(span) = value.value_span {
1830 self.session.span_note(span,
1831 "conflicting value here");
1835 Some(_) | None => {}
1838 match import_resolution.type_target {
1839 Some(ref target) if target.shadowable != Shadowable::Always => {
1840 if let Some(ref ty) = *name_bindings.type_def.borrow() {
1841 match ty.module_def {
1843 let msg = format!("import `{}` conflicts with type in \
1845 &token::get_name(name));
1846 span_err!(self.session, import_span, E0256, "{}", &msg[..]);
1847 if let Some(span) = ty.type_span {
1848 self.session.span_note(span,
1849 "note conflicting type here")
1852 Some(ref module_def) => {
1853 match module_def.kind.get() {
1855 if let Some(span) = ty.type_span {
1856 let msg = format!("inherent implementations \
1857 are only allowed on types \
1858 defined in the current module");
1859 span_err!(self.session, span, E0257, "{}", &msg[..]);
1860 self.session.span_note(import_span,
1861 "import from other module here")
1865 let msg = format!("import `{}` conflicts with existing \
1867 &token::get_name(name));
1868 span_err!(self.session, import_span, E0258, "{}", &msg[..]);
1869 if let Some(span) = ty.type_span {
1870 self.session.span_note(span,
1871 "note conflicting module here")
1879 Some(_) | None => {}
1883 /// Checks that the names of external crates don't collide with other
1884 /// external crates.
1885 fn check_for_conflicts_between_external_crates(&self,
1889 if module.external_module_children.borrow().contains_key(&name) {
1890 span_err!(self.session, span, E0259,
1891 "an external crate named `{}` has already \
1892 been imported into this module",
1893 &token::get_name(name));
1897 /// Checks that the names of items don't collide with external crates.
1898 fn check_for_conflicts_between_external_crates_and_items(&self,
1902 if module.external_module_children.borrow().contains_key(&name) {
1903 span_err!(self.session, span, E0260,
1904 "the name `{}` conflicts with an external \
1905 crate that has been imported into this \
1907 &token::get_name(name));
1911 /// Resolves the given module path from the given root `module_`.
1912 fn resolve_module_path_from_root(&mut self,
1913 module_: Rc<Module>,
1914 module_path: &[Name],
1917 name_search_type: NameSearchType,
1919 -> ResolveResult<(Rc<Module>, LastPrivate)> {
1920 fn search_parent_externals(needle: Name, module: &Rc<Module>)
1921 -> Option<Rc<Module>> {
1922 match module.external_module_children.borrow().get(&needle) {
1923 Some(_) => Some(module.clone()),
1924 None => match module.parent_link {
1925 ModuleParentLink(ref parent, _) => {
1926 search_parent_externals(needle, &parent.upgrade().unwrap())
1933 let mut search_module = module_;
1934 let mut index = index;
1935 let module_path_len = module_path.len();
1936 let mut closest_private = lp;
1938 // Resolve the module part of the path. This does not involve looking
1939 // upward though scope chains; we simply resolve names directly in
1940 // modules as we go.
1941 while index < module_path_len {
1942 let name = module_path[index];
1943 match self.resolve_name_in_module(search_module.clone(),
1949 let segment_name = token::get_name(name);
1950 let module_name = self.module_to_string(&*search_module);
1951 let mut span = span;
1952 let msg = if "???" == &module_name[..] {
1953 span.hi = span.lo + Pos::from_usize(segment_name.len());
1955 match search_parent_externals(name,
1956 &self.current_module) {
1958 let path_str = self.names_to_string(module_path);
1959 let target_mod_str = self.module_to_string(&*module);
1960 let current_mod_str =
1961 self.module_to_string(&*self.current_module);
1963 let prefix = if target_mod_str == current_mod_str {
1964 "self::".to_string()
1966 format!("{}::", target_mod_str)
1969 format!("Did you mean `{}{}`?", prefix, path_str)
1971 None => format!("Maybe a missing `extern crate {}`?",
1975 format!("Could not find `{}` in `{}`",
1980 return Failed(Some((span, msg)));
1982 Failed(err) => return Failed(err),
1984 debug!("(resolving module path for import) module \
1985 resolution is indeterminate: {}",
1986 token::get_name(name));
1987 return Indeterminate;
1989 Success((target, used_proxy)) => {
1990 // Check to see whether there are type bindings, and, if
1991 // so, whether there is a module within.
1992 match *target.bindings.type_def.borrow() {
1993 Some(ref type_def) => {
1994 match type_def.module_def {
1996 let msg = format!("Not a module `{}`",
1997 token::get_name(name));
1999 return Failed(Some((span, msg)));
2001 Some(ref module_def) => {
2002 search_module = module_def.clone();
2004 // track extern crates for unused_extern_crate lint
2005 if let Some(did) = module_def.def_id.get() {
2006 self.used_crates.insert(did.krate);
2009 // Keep track of the closest
2010 // private module used when
2011 // resolving this import chain.
2012 if !used_proxy && !search_module.is_public {
2013 if let Some(did) = search_module.def_id.get() {
2014 closest_private = LastMod(DependsOn(did));
2021 // There are no type bindings at all.
2022 let msg = format!("Not a module `{}`",
2023 token::get_name(name));
2024 return Failed(Some((span, msg)));
2033 return Success((search_module, closest_private));
2036 /// Attempts to resolve the module part of an import directive or path
2037 /// rooted at the given module.
2039 /// On success, returns the resolved module, and the closest *private*
2040 /// module found to the destination when resolving this path.
2041 fn resolve_module_path(&mut self,
2042 module_: Rc<Module>,
2043 module_path: &[Name],
2044 use_lexical_scope: UseLexicalScopeFlag,
2046 name_search_type: NameSearchType)
2047 -> ResolveResult<(Rc<Module>, LastPrivate)> {
2048 let module_path_len = module_path.len();
2049 assert!(module_path_len > 0);
2051 debug!("(resolving module path for import) processing `{}` rooted at `{}`",
2052 self.names_to_string(module_path),
2053 self.module_to_string(&*module_));
2055 // Resolve the module prefix, if any.
2056 let module_prefix_result = self.resolve_module_prefix(module_.clone(),
2062 match module_prefix_result {
2064 let mpath = self.names_to_string(module_path);
2065 let mpath = &mpath[..];
2066 match mpath.rfind(':') {
2068 let msg = format!("Could not find `{}` in `{}`",
2069 // idx +- 1 to account for the
2070 // colons on either side
2073 return Failed(Some((span, msg)));
2080 Failed(err) => return Failed(err),
2082 debug!("(resolving module path for import) indeterminate; \
2084 return Indeterminate;
2086 Success(NoPrefixFound) => {
2087 // There was no prefix, so we're considering the first element
2088 // of the path. How we handle this depends on whether we were
2089 // instructed to use lexical scope or not.
2090 match use_lexical_scope {
2091 DontUseLexicalScope => {
2092 // This is a crate-relative path. We will start the
2093 // resolution process at index zero.
2094 search_module = self.graph_root.get_module();
2096 last_private = LastMod(AllPublic);
2098 UseLexicalScope => {
2099 // This is not a crate-relative path. We resolve the
2100 // first component of the path in the current lexical
2101 // scope and then proceed to resolve below that.
2102 match self.resolve_module_in_lexical_scope(module_,
2104 Failed(err) => return Failed(err),
2106 debug!("(resolving module path for import) \
2107 indeterminate; bailing");
2108 return Indeterminate;
2110 Success(containing_module) => {
2111 search_module = containing_module;
2113 last_private = LastMod(AllPublic);
2119 Success(PrefixFound(ref containing_module, index)) => {
2120 search_module = containing_module.clone();
2121 start_index = index;
2122 last_private = LastMod(DependsOn(containing_module.def_id
2128 self.resolve_module_path_from_root(search_module,
2136 /// Invariant: This must only be called during main resolution, not during
2137 /// import resolution.
2138 fn resolve_item_in_lexical_scope(&mut self,
2139 module_: Rc<Module>,
2141 namespace: Namespace)
2142 -> ResolveResult<(Target, bool)> {
2143 debug!("(resolving item in lexical scope) resolving `{}` in \
2144 namespace {:?} in `{}`",
2145 token::get_name(name),
2147 self.module_to_string(&*module_));
2149 // The current module node is handled specially. First, check for
2150 // its immediate children.
2151 build_reduced_graph::populate_module_if_necessary(self, &module_);
2153 match module_.children.borrow().get(&name) {
2155 if name_bindings.defined_in_namespace(namespace) => {
2156 debug!("top name bindings succeeded");
2157 return Success((Target::new(module_.clone(),
2158 name_bindings.clone(),
2162 Some(_) | None => { /* Not found; continue. */ }
2165 // Now check for its import directives. We don't have to have resolved
2166 // all its imports in the usual way; this is because chains of
2167 // adjacent import statements are processed as though they mutated the
2169 if let Some(import_resolution) = module_.import_resolutions.borrow().get(&name) {
2170 match (*import_resolution).target_for_namespace(namespace) {
2172 // Not found; continue.
2173 debug!("(resolving item in lexical scope) found \
2174 import resolution, but not in namespace {:?}",
2178 debug!("(resolving item in lexical scope) using \
2179 import resolution");
2180 // track used imports and extern crates as well
2181 let id = import_resolution.id(namespace);
2182 self.used_imports.insert((id, namespace));
2183 self.record_import_use(id, name);
2184 if let Some(DefId{krate: kid, ..}) = target.target_module.def_id.get() {
2185 self.used_crates.insert(kid);
2187 return Success((target, false));
2192 // Search for external modules.
2193 if namespace == TypeNS {
2194 // FIXME (21114): In principle unclear `child` *has* to be lifted.
2195 let child = module_.external_module_children.borrow().get(&name).cloned();
2196 if let Some(module) = child {
2198 Rc::new(Resolver::create_name_bindings_from_module(module));
2199 debug!("lower name bindings succeeded");
2200 return Success((Target::new(module_,
2207 // Finally, proceed up the scope chain looking for parent modules.
2208 let mut search_module = module_;
2210 // Go to the next parent.
2211 match search_module.parent_link.clone() {
2213 // No more parents. This module was unresolved.
2214 debug!("(resolving item in lexical scope) unresolved \
2216 return Failed(None);
2218 ModuleParentLink(parent_module_node, _) => {
2219 match search_module.kind.get() {
2220 NormalModuleKind => {
2221 // We stop the search here.
2222 debug!("(resolving item in lexical \
2223 scope) unresolved module: not \
2224 searching through module \
2226 return Failed(None);
2232 AnonymousModuleKind => {
2233 search_module = parent_module_node.upgrade().unwrap();
2237 BlockParentLink(ref parent_module_node, _) => {
2238 search_module = parent_module_node.upgrade().unwrap();
2242 // Resolve the name in the parent module.
2243 match self.resolve_name_in_module(search_module.clone(),
2248 Failed(Some((span, msg))) =>
2249 self.resolve_error(span, &format!("failed to resolve. {}",
2251 Failed(None) => (), // Continue up the search chain.
2253 // We couldn't see through the higher scope because of an
2254 // unresolved import higher up. Bail.
2256 debug!("(resolving item in lexical scope) indeterminate \
2257 higher scope; bailing");
2258 return Indeterminate;
2260 Success((target, used_reexport)) => {
2261 // We found the module.
2262 debug!("(resolving item in lexical scope) found name \
2264 return Success((target, used_reexport));
2270 /// Resolves a module name in the current lexical scope.
2271 fn resolve_module_in_lexical_scope(&mut self,
2272 module_: Rc<Module>,
2274 -> ResolveResult<Rc<Module>> {
2275 // If this module is an anonymous module, resolve the item in the
2276 // lexical scope. Otherwise, resolve the item from the crate root.
2277 let resolve_result = self.resolve_item_in_lexical_scope(module_, name, TypeNS);
2278 match resolve_result {
2279 Success((target, _)) => {
2280 let bindings = &*target.bindings;
2281 match *bindings.type_def.borrow() {
2282 Some(ref type_def) => {
2283 match type_def.module_def {
2285 debug!("!!! (resolving module in lexical \
2286 scope) module wasn't actually a \
2288 return Failed(None);
2290 Some(ref module_def) => {
2291 return Success(module_def.clone());
2296 debug!("!!! (resolving module in lexical scope) module
2297 wasn't actually a module!");
2298 return Failed(None);
2303 debug!("(resolving module in lexical scope) indeterminate; \
2305 return Indeterminate;
2308 debug!("(resolving module in lexical scope) failed to resolve");
2314 /// Returns the nearest normal module parent of the given module.
2315 fn get_nearest_normal_module_parent(&mut self, module_: Rc<Module>)
2316 -> Option<Rc<Module>> {
2317 let mut module_ = module_;
2319 match module_.parent_link.clone() {
2320 NoParentLink => return None,
2321 ModuleParentLink(new_module, _) |
2322 BlockParentLink(new_module, _) => {
2323 let new_module = new_module.upgrade().unwrap();
2324 match new_module.kind.get() {
2325 NormalModuleKind => return Some(new_module),
2330 AnonymousModuleKind => module_ = new_module,
2337 /// Returns the nearest normal module parent of the given module, or the
2338 /// module itself if it is a normal module.
2339 fn get_nearest_normal_module_parent_or_self(&mut self, module_: Rc<Module>)
2341 match module_.kind.get() {
2342 NormalModuleKind => return module_,
2347 AnonymousModuleKind => {
2348 match self.get_nearest_normal_module_parent(module_.clone()) {
2350 Some(new_module) => new_module
2356 /// Resolves a "module prefix". A module prefix is one or both of (a) `self::`;
2357 /// (b) some chain of `super::`.
2358 /// grammar: (SELF MOD_SEP ) ? (SUPER MOD_SEP) *
2359 fn resolve_module_prefix(&mut self,
2360 module_: Rc<Module>,
2361 module_path: &[Name])
2362 -> ResolveResult<ModulePrefixResult> {
2363 // Start at the current module if we see `self` or `super`, or at the
2364 // top of the crate otherwise.
2365 let mut containing_module;
2367 let first_module_path_string = token::get_name(module_path[0]);
2368 if "self" == &first_module_path_string[..] {
2370 self.get_nearest_normal_module_parent_or_self(module_);
2372 } else if "super" == &first_module_path_string[..] {
2374 self.get_nearest_normal_module_parent_or_self(module_);
2375 i = 0; // We'll handle `super` below.
2377 return Success(NoPrefixFound);
2380 // Now loop through all the `super`s we find.
2381 while i < module_path.len() {
2382 let string = token::get_name(module_path[i]);
2383 if "super" != &string[..] {
2386 debug!("(resolving module prefix) resolving `super` at {}",
2387 self.module_to_string(&*containing_module));
2388 match self.get_nearest_normal_module_parent(containing_module) {
2389 None => return Failed(None),
2390 Some(new_module) => {
2391 containing_module = new_module;
2397 debug!("(resolving module prefix) finished resolving prefix at {}",
2398 self.module_to_string(&*containing_module));
2400 return Success(PrefixFound(containing_module, i));
2403 /// Attempts to resolve the supplied name in the given module for the
2404 /// given namespace. If successful, returns the target corresponding to
2407 /// The boolean returned on success is an indicator of whether this lookup
2408 /// passed through a public re-export proxy.
2409 fn resolve_name_in_module(&mut self,
2410 module_: Rc<Module>,
2412 namespace: Namespace,
2413 name_search_type: NameSearchType,
2414 allow_private_imports: bool)
2415 -> ResolveResult<(Target, bool)> {
2416 debug!("(resolving name in module) resolving `{}` in `{}`",
2417 &token::get_name(name),
2418 self.module_to_string(&*module_));
2420 // First, check the direct children of the module.
2421 build_reduced_graph::populate_module_if_necessary(self, &module_);
2423 match module_.children.borrow().get(&name) {
2425 if name_bindings.defined_in_namespace(namespace) => {
2426 debug!("(resolving name in module) found node as child");
2427 return Success((Target::new(module_.clone(),
2428 name_bindings.clone(),
2437 // Next, check the module's imports if necessary.
2439 // If this is a search of all imports, we should be done with glob
2440 // resolution at this point.
2441 if name_search_type == PathSearch {
2442 assert_eq!(module_.glob_count.get(), 0);
2445 // Check the list of resolved imports.
2446 match module_.import_resolutions.borrow().get(&name) {
2447 Some(import_resolution) if allow_private_imports ||
2448 import_resolution.is_public => {
2450 if import_resolution.is_public &&
2451 import_resolution.outstanding_references != 0 {
2452 debug!("(resolving name in module) import \
2453 unresolved; bailing out");
2454 return Indeterminate;
2456 match import_resolution.target_for_namespace(namespace) {
2458 debug!("(resolving name in module) name found, \
2459 but not in namespace {:?}",
2463 debug!("(resolving name in module) resolved to \
2465 // track used imports and extern crates as well
2466 let id = import_resolution.id(namespace);
2467 self.used_imports.insert((id, namespace));
2468 self.record_import_use(id, name);
2469 if let Some(DefId{krate: kid, ..}) = target.target_module.def_id.get() {
2470 self.used_crates.insert(kid);
2472 return Success((target, true));
2476 Some(..) | None => {} // Continue.
2479 // Finally, search through external children.
2480 if namespace == TypeNS {
2481 // FIXME (21114): In principle unclear `child` *has* to be lifted.
2482 let child = module_.external_module_children.borrow().get(&name).cloned();
2483 if let Some(module) = child {
2485 Rc::new(Resolver::create_name_bindings_from_module(module));
2486 return Success((Target::new(module_,
2493 // We're out of luck.
2494 debug!("(resolving name in module) failed to resolve `{}`",
2495 &token::get_name(name));
2496 return Failed(None);
2499 fn report_unresolved_imports(&mut self, module_: Rc<Module>) {
2500 let index = module_.resolved_import_count.get();
2501 let imports = module_.imports.borrow();
2502 let import_count = imports.len();
2503 if index != import_count {
2504 let sn = self.session
2506 .span_to_snippet((*imports)[index].span)
2508 if sn.contains("::") {
2509 self.resolve_error((*imports)[index].span,
2510 "unresolved import");
2512 let err = format!("unresolved import (maybe you meant `{}::*`?)",
2514 self.resolve_error((*imports)[index].span, &err[..]);
2518 // Descend into children and anonymous children.
2519 build_reduced_graph::populate_module_if_necessary(self, &module_);
2521 for (_, child_node) in &*module_.children.borrow() {
2522 match child_node.get_module_if_available() {
2526 Some(child_module) => {
2527 self.report_unresolved_imports(child_module);
2532 for (_, module_) in &*module_.anonymous_children.borrow() {
2533 self.report_unresolved_imports(module_.clone());
2539 // We maintain a list of value ribs and type ribs.
2541 // Simultaneously, we keep track of the current position in the module
2542 // graph in the `current_module` pointer. When we go to resolve a name in
2543 // the value or type namespaces, we first look through all the ribs and
2544 // then query the module graph. When we resolve a name in the module
2545 // namespace, we can skip all the ribs (since nested modules are not
2546 // allowed within blocks in Rust) and jump straight to the current module
2549 // Named implementations are handled separately. When we find a method
2550 // call, we consult the module node to find all of the implementations in
2551 // scope. This information is lazily cached in the module node. We then
2552 // generate a fake "implementation scope" containing all the
2553 // implementations thus found, for compatibility with old resolve pass.
2555 fn with_scope<F>(&mut self, name: Option<Name>, f: F) where
2556 F: FnOnce(&mut Resolver),
2558 let orig_module = self.current_module.clone();
2560 // Move down in the graph.
2566 build_reduced_graph::populate_module_if_necessary(self, &orig_module);
2568 match orig_module.children.borrow().get(&name) {
2570 debug!("!!! (with scope) didn't find `{}` in `{}`",
2571 token::get_name(name),
2572 self.module_to_string(&*orig_module));
2574 Some(name_bindings) => {
2575 match (*name_bindings).get_module_if_available() {
2577 debug!("!!! (with scope) didn't find module \
2579 token::get_name(name),
2580 self.module_to_string(&*orig_module));
2583 self.current_module = module_;
2593 self.current_module = orig_module;
2596 /// Wraps the given definition in the appropriate number of `DefUpvar`
2602 -> Option<DefLike> {
2604 DlDef(d @ DefUpvar(..)) => {
2605 self.session.span_bug(span,
2606 &format!("unexpected {:?} in bindings", d)[])
2608 DlDef(d @ DefLocal(_)) => {
2609 let node_id = d.def_id().node;
2614 // Nothing to do. Continue.
2616 ClosureRibKind(function_id) => {
2618 def = DefUpvar(node_id, function_id);
2620 let mut seen = self.freevars_seen.borrow_mut();
2621 let seen = match seen.entry(function_id) {
2622 Occupied(v) => v.into_mut(),
2623 Vacant(v) => v.insert(NodeSet()),
2625 if seen.contains(&node_id) {
2628 match self.freevars.borrow_mut().entry(function_id) {
2629 Occupied(v) => v.into_mut(),
2630 Vacant(v) => v.insert(vec![]),
2631 }.push(Freevar { def: prev_def, span: span });
2632 seen.insert(node_id);
2634 MethodRibKind(item_id, _) => {
2635 // If the def is a ty param, and came from the parent
2638 DefTyParam(_, _, did, _) if {
2639 self.def_map.borrow().get(&did.node).cloned()
2640 == Some(DefTyParamBinder(item_id))
2642 DefSelfTy(did) if did == item_id => {} // ok
2644 // This was an attempt to access an upvar inside a
2645 // named function item. This is not allowed, so we
2650 "can't capture dynamic environment in a fn item; \
2651 use the || { ... } closure form instead");
2658 // This was an attempt to access an upvar inside a
2659 // named function item. This is not allowed, so we
2664 "can't capture dynamic environment in a fn item; \
2665 use the || { ... } closure form instead");
2669 ConstantItemRibKind => {
2670 // Still doesn't deal with upvars
2671 self.resolve_error(span,
2672 "attempt to use a non-constant \
2673 value in a constant");
2680 DlDef(def @ DefTyParam(..)) |
2681 DlDef(def @ DefSelfTy(..)) => {
2684 NormalRibKind | ClosureRibKind(..) => {
2685 // Nothing to do. Continue.
2687 MethodRibKind(item_id, _) => {
2688 // If the def is a ty param, and came from the parent
2691 DefTyParam(_, _, did, _) if {
2692 self.def_map.borrow().get(&did.node).cloned()
2693 == Some(DefTyParamBinder(item_id))
2695 DefSelfTy(did) if did == item_id => {} // ok
2698 // This was an attempt to use a type parameter outside
2701 self.resolve_error(span,
2702 "can't use type parameters from \
2703 outer function; try using a local \
2704 type parameter instead");
2711 // This was an attempt to use a type parameter outside
2714 self.resolve_error(span,
2715 "can't use type parameters from \
2716 outer function; try using a local \
2717 type parameter instead");
2721 ConstantItemRibKind => {
2723 self.resolve_error(span,
2724 "cannot use an outer type \
2725 parameter in this context");
2736 /// Searches the current set of local scopes and
2737 /// applies translations for closures.
2738 fn search_ribs(&self,
2742 -> Option<DefLike> {
2743 // FIXME #4950: Try caching?
2745 for (i, rib) in ribs.iter().enumerate().rev() {
2746 match rib.bindings.get(&name).cloned() {
2748 return self.upvarify(&ribs[i + 1..], def_like, span);
2759 /// Searches the current set of local scopes for labels.
2760 /// Stops after meeting a closure.
2761 fn search_label(&self, name: Name) -> Option<DefLike> {
2762 for rib in self.label_ribs.iter().rev() {
2768 // Do not resolve labels across function boundary
2772 let result = rib.bindings.get(&name).cloned();
2773 if result.is_some() {
2780 fn resolve_crate(&mut self, krate: &ast::Crate) {
2781 debug!("(resolving crate) starting");
2783 visit::walk_crate(self, krate);
2786 fn check_if_primitive_type_name(&self, name: Name, span: Span) {
2787 if let Some(_) = self.primitive_type_table.primitive_types.get(&name) {
2788 span_err!(self.session, span, E0317,
2789 "user-defined types or type parameters cannot shadow the primitive types");
2793 fn resolve_item(&mut self, item: &Item) {
2794 let name = item.ident.name;
2796 debug!("(resolving item) resolving {}",
2797 token::get_name(name));
2801 // enum item: resolve all the variants' discrs,
2802 // then resolve the ty params
2803 ItemEnum(ref enum_def, ref generics) => {
2804 self.check_if_primitive_type_name(name, item.span);
2806 for variant in &(*enum_def).variants {
2807 if let Some(ref dis_expr) = variant.node.disr_expr {
2808 // resolve the discriminator expr
2810 self.with_constant_rib(|this| {
2811 this.resolve_expr(&**dis_expr);
2816 // n.b. the discr expr gets visited twice.
2817 // but maybe it's okay since the first time will signal an
2818 // error if there is one? -- tjc
2819 self.with_type_parameter_rib(HasTypeParameters(generics,
2824 this.resolve_type_parameters(&generics.ty_params);
2825 this.resolve_where_clause(&generics.where_clause);
2826 visit::walk_item(this, item);
2830 ItemTy(_, ref generics) => {
2831 self.check_if_primitive_type_name(name, item.span);
2833 self.with_type_parameter_rib(HasTypeParameters(generics,
2838 this.resolve_type_parameters(&generics.ty_params);
2839 visit::walk_item(this, item);
2845 ref implemented_traits,
2847 ref impl_items) => {
2848 self.resolve_implementation(item.id,
2855 ItemTrait(_, ref generics, ref bounds, ref trait_items) => {
2856 self.check_if_primitive_type_name(name, item.span);
2858 // Create a new rib for the self type.
2859 let mut self_type_rib = Rib::new(ItemRibKind);
2861 // plain insert (no renaming, types are not currently hygienic....)
2862 let name = self.type_self_name;
2863 self_type_rib.bindings.insert(name, DlDef(DefSelfTy(item.id)));
2864 self.type_ribs.push(self_type_rib);
2866 // Create a new rib for the trait-wide type parameters.
2867 self.with_type_parameter_rib(HasTypeParameters(generics,
2872 this.resolve_type_parameters(&generics.ty_params);
2873 this.resolve_where_clause(&generics.where_clause);
2875 this.resolve_type_parameter_bounds(item.id, bounds,
2878 for trait_item in &(*trait_items) {
2879 // Create a new rib for the trait_item-specific type
2882 // FIXME #4951: Do we need a node ID here?
2885 ast::RequiredMethod(ref ty_m) => {
2886 this.with_type_parameter_rib
2887 (HasTypeParameters(&ty_m.generics,
2890 MethodRibKind(item.id, RequiredMethod)),
2893 // Resolve the method-specific type
2895 this.resolve_type_parameters(
2896 &ty_m.generics.ty_params);
2897 this.resolve_where_clause(&ty_m.generics
2900 for argument in &ty_m.decl.inputs {
2901 this.resolve_type(&*argument.ty);
2904 if let SelfExplicit(ref typ, _) = ty_m.explicit_self.node {
2905 this.resolve_type(&**typ)
2908 if let ast::Return(ref ret_ty) = ty_m.decl.output {
2909 this.resolve_type(&**ret_ty);
2913 ast::ProvidedMethod(ref m) => {
2914 this.resolve_method(MethodRibKind(item.id,
2915 ProvidedMethod(m.id)),
2918 ast::TypeTraitItem(ref data) => {
2919 this.resolve_type_parameter(&data.ty_param);
2920 visit::walk_trait_item(this, trait_item);
2926 self.type_ribs.pop();
2929 ItemStruct(ref struct_def, ref generics) => {
2930 self.check_if_primitive_type_name(name, item.span);
2932 self.resolve_struct(item.id,
2934 &struct_def.fields[]);
2937 ItemMod(ref module_) => {
2938 self.with_scope(Some(name), |this| {
2939 this.resolve_module(module_, item.span, name,
2944 ItemForeignMod(ref foreign_module) => {
2945 self.with_scope(Some(name), |this| {
2946 for foreign_item in &foreign_module.items {
2947 match foreign_item.node {
2948 ForeignItemFn(_, ref generics) => {
2949 this.with_type_parameter_rib(
2951 generics, FnSpace, foreign_item.id,
2954 this.resolve_type_parameters(&generics.ty_params);
2955 this.resolve_where_clause(&generics.where_clause);
2956 visit::walk_foreign_item(this, &**foreign_item)
2959 ForeignItemStatic(..) => {
2960 visit::walk_foreign_item(this,
2968 ItemFn(ref fn_decl, _, _, ref generics, ref block) => {
2969 self.resolve_function(ItemRibKind,
2979 ItemConst(..) | ItemStatic(..) => {
2980 self.with_constant_rib(|this| {
2981 visit::walk_item(this, item);
2985 ItemUse(ref view_path) => {
2986 // check for imports shadowing primitive types
2987 if let ast::ViewPathSimple(ident, _) = view_path.node {
2988 match self.def_map.borrow().get(&item.id) {
2989 Some(&DefTy(..)) | Some(&DefStruct(..)) | Some(&DefTrait(..)) | None => {
2990 self.check_if_primitive_type_name(ident.name, item.span);
2997 ItemExternCrate(_) | ItemMac(..) => {
2998 // do nothing, these are just around to be encoded
3003 fn with_type_parameter_rib<F>(&mut self, type_parameters: TypeParameters, f: F) where
3004 F: FnOnce(&mut Resolver),
3006 match type_parameters {
3007 HasTypeParameters(generics, space, node_id, rib_kind) => {
3008 let mut function_type_rib = Rib::new(rib_kind);
3009 let mut seen_bindings = HashSet::new();
3010 for (index, type_parameter) in generics.ty_params.iter().enumerate() {
3011 let name = type_parameter.ident.name;
3012 debug!("with_type_parameter_rib: {} {}", node_id,
3015 if seen_bindings.contains(&name) {
3016 self.resolve_error(type_parameter.span,
3017 &format!("the name `{}` is already \
3019 parameter in this type \
3024 seen_bindings.insert(name);
3026 let def_like = DlDef(DefTyParam(space,
3028 local_def(type_parameter.id),
3030 // Associate this type parameter with
3031 // the item that bound it
3032 self.record_def(type_parameter.id,
3033 (DefTyParamBinder(node_id), LastMod(AllPublic)));
3034 // plain insert (no renaming)
3035 function_type_rib.bindings.insert(name, def_like);
3037 self.type_ribs.push(function_type_rib);
3040 NoTypeParameters => {
3047 match type_parameters {
3048 HasTypeParameters(..) => { self.type_ribs.pop(); }
3049 NoTypeParameters => { }
3053 fn with_label_rib<F>(&mut self, f: F) where
3054 F: FnOnce(&mut Resolver),
3056 self.label_ribs.push(Rib::new(NormalRibKind));
3058 self.label_ribs.pop();
3061 fn with_constant_rib<F>(&mut self, f: F) where
3062 F: FnOnce(&mut Resolver),
3064 self.value_ribs.push(Rib::new(ConstantItemRibKind));
3065 self.type_ribs.push(Rib::new(ConstantItemRibKind));
3067 self.type_ribs.pop();
3068 self.value_ribs.pop();
3071 fn resolve_function(&mut self,
3073 optional_declaration: Option<&FnDecl>,
3074 type_parameters: TypeParameters,
3076 // Create a value rib for the function.
3077 let function_value_rib = Rib::new(rib_kind);
3078 self.value_ribs.push(function_value_rib);
3080 // Create a label rib for the function.
3081 let function_label_rib = Rib::new(rib_kind);
3082 self.label_ribs.push(function_label_rib);
3084 // If this function has type parameters, add them now.
3085 self.with_type_parameter_rib(type_parameters, |this| {
3086 // Resolve the type parameters.
3087 match type_parameters {
3088 NoTypeParameters => {
3091 HasTypeParameters(ref generics, _, _, _) => {
3092 this.resolve_type_parameters(&generics.ty_params);
3093 this.resolve_where_clause(&generics.where_clause);
3097 // Add each argument to the rib.
3098 match optional_declaration {
3102 Some(declaration) => {
3103 let mut bindings_list = HashMap::new();
3104 for argument in &declaration.inputs {
3105 this.resolve_pattern(&*argument.pat,
3106 ArgumentIrrefutableMode,
3107 &mut bindings_list);
3109 this.resolve_type(&*argument.ty);
3111 debug!("(resolving function) recorded argument");
3114 if let ast::Return(ref ret_ty) = declaration.output {
3115 this.resolve_type(&**ret_ty);
3120 // Resolve the function body.
3121 this.resolve_block(&*block);
3123 debug!("(resolving function) leaving function");
3126 self.label_ribs.pop();
3127 self.value_ribs.pop();
3130 fn resolve_type_parameters(&mut self,
3131 type_parameters: &OwnedSlice<TyParam>) {
3132 for type_parameter in &**type_parameters {
3133 self.resolve_type_parameter(type_parameter);
3137 fn resolve_type_parameter(&mut self,
3138 type_parameter: &TyParam) {
3139 self.check_if_primitive_type_name(type_parameter.ident.name, type_parameter.span);
3140 for bound in &*type_parameter.bounds {
3141 self.resolve_type_parameter_bound(type_parameter.id, bound,
3142 TraitBoundingTypeParameter);
3144 match type_parameter.default {
3145 Some(ref ty) => self.resolve_type(&**ty),
3150 fn resolve_type_parameter_bounds(&mut self,
3152 type_parameter_bounds: &OwnedSlice<TyParamBound>,
3153 reference_type: TraitReferenceType) {
3154 for type_parameter_bound in &**type_parameter_bounds {
3155 self.resolve_type_parameter_bound(id, type_parameter_bound,
3160 fn resolve_type_parameter_bound(&mut self,
3162 type_parameter_bound: &TyParamBound,
3163 reference_type: TraitReferenceType) {
3164 match *type_parameter_bound {
3165 TraitTyParamBound(ref tref, _) => {
3166 self.resolve_poly_trait_reference(id, tref, reference_type)
3168 RegionTyParamBound(..) => {}
3172 fn resolve_poly_trait_reference(&mut self,
3174 poly_trait_reference: &PolyTraitRef,
3175 reference_type: TraitReferenceType) {
3176 self.resolve_trait_reference(id, &poly_trait_reference.trait_ref, reference_type)
3179 fn resolve_trait_reference(&mut self,
3181 trait_reference: &TraitRef,
3182 reference_type: TraitReferenceType) {
3183 match self.resolve_path(id, &trait_reference.path, TypeNS, true) {
3185 let path_str = self.path_names_to_string(&trait_reference.path);
3186 let usage_str = match reference_type {
3187 TraitBoundingTypeParameter => "bound type parameter with",
3188 TraitImplementation => "implement",
3189 TraitDerivation => "derive",
3190 TraitObject => "reference",
3191 TraitQPath => "extract an associated item from",
3194 let msg = format!("attempt to {} a nonexistent trait `{}`", usage_str, path_str);
3195 self.resolve_error(trait_reference.path.span, &msg[..]);
3199 (DefTrait(_), _) => {
3200 debug!("(resolving trait) found trait def: {:?}", def);
3201 self.record_def(trait_reference.ref_id, def);
3204 self.resolve_error(trait_reference.path.span,
3205 &format!("`{}` is not a trait",
3206 self.path_names_to_string(
3207 &trait_reference.path))[]);
3209 // If it's a typedef, give a note
3210 if let DefTy(..) = def {
3211 self.session.span_note(
3212 trait_reference.path.span,
3213 &format!("`type` aliases cannot be used for traits")
3222 fn resolve_where_clause(&mut self, where_clause: &ast::WhereClause) {
3223 for predicate in &where_clause.predicates {
3225 &ast::WherePredicate::BoundPredicate(ref bound_pred) => {
3226 self.resolve_type(&*bound_pred.bounded_ty);
3228 for bound in &*bound_pred.bounds {
3229 self.resolve_type_parameter_bound(bound_pred.bounded_ty.id, bound,
3230 TraitBoundingTypeParameter);
3233 &ast::WherePredicate::RegionPredicate(_) => {}
3234 &ast::WherePredicate::EqPredicate(ref eq_pred) => {
3235 match self.resolve_path(eq_pred.id, &eq_pred.path, TypeNS, true) {
3236 Some((def @ DefTyParam(..), last_private)) => {
3237 self.record_def(eq_pred.id, (def, last_private));
3240 self.resolve_error(eq_pred.path.span,
3241 "undeclared associated type");
3245 self.resolve_type(&*eq_pred.ty);
3251 fn resolve_struct(&mut self,
3253 generics: &Generics,
3254 fields: &[StructField]) {
3255 // If applicable, create a rib for the type parameters.
3256 self.with_type_parameter_rib(HasTypeParameters(generics,
3261 // Resolve the type parameters.
3262 this.resolve_type_parameters(&generics.ty_params);
3263 this.resolve_where_clause(&generics.where_clause);
3266 for field in fields {
3267 this.resolve_type(&*field.node.ty);
3272 // Does this really need to take a RibKind or is it always going
3273 // to be NormalRibKind?
3274 fn resolve_method(&mut self,
3276 method: &ast::Method) {
3277 let method_generics = method.pe_generics();
3278 let type_parameters = HasTypeParameters(method_generics,
3283 if let SelfExplicit(ref typ, _) = method.pe_explicit_self().node {
3284 self.resolve_type(&**typ);
3287 self.resolve_function(rib_kind,
3288 Some(method.pe_fn_decl()),
3293 fn with_current_self_type<T, F>(&mut self, self_type: &Ty, f: F) -> T where
3294 F: FnOnce(&mut Resolver) -> T,
3296 // Handle nested impls (inside fn bodies)
3297 let previous_value = replace(&mut self.current_self_type, Some(self_type.clone()));
3298 let result = f(self);
3299 self.current_self_type = previous_value;
3303 fn with_optional_trait_ref<T, F>(&mut self, id: NodeId,
3304 opt_trait_ref: &Option<TraitRef>,
3306 F: FnOnce(&mut Resolver) -> T,
3308 let new_val = match *opt_trait_ref {
3309 Some(ref trait_ref) => {
3310 self.resolve_trait_reference(id, trait_ref, TraitImplementation);
3312 match self.def_map.borrow().get(&trait_ref.ref_id) {
3314 let did = def.def_id();
3315 Some((did, trait_ref.clone()))
3322 let original_trait_ref = replace(&mut self.current_trait_ref, new_val);
3323 let result = f(self);
3324 self.current_trait_ref = original_trait_ref;
3328 fn resolve_implementation(&mut self,
3330 generics: &Generics,
3331 opt_trait_reference: &Option<TraitRef>,
3333 impl_items: &[ImplItem]) {
3334 // If applicable, create a rib for the type parameters.
3335 self.with_type_parameter_rib(HasTypeParameters(generics,
3340 // Resolve the type parameters.
3341 this.resolve_type_parameters(&generics.ty_params);
3342 this.resolve_where_clause(&generics.where_clause);
3344 // Resolve the trait reference, if necessary.
3345 this.with_optional_trait_ref(id, opt_trait_reference, |this| {
3346 // Resolve the self type.
3347 this.resolve_type(self_type);
3349 this.with_current_self_type(self_type, |this| {
3350 for impl_item in impl_items {
3352 MethodImplItem(ref method) => {
3353 // If this is a trait impl, ensure the method
3355 this.check_trait_item(method.pe_ident().name,
3358 // We also need a new scope for the method-
3359 // specific type parameters.
3360 this.resolve_method(
3361 MethodRibKind(id, ProvidedMethod(method.id)),
3364 TypeImplItem(ref typedef) => {
3365 // If this is a trait impl, ensure the method
3367 this.check_trait_item(typedef.ident.name,
3370 this.resolve_type(&*typedef.typ);
3378 // Check that the current type is indeed a type, if we have an anonymous impl
3379 if opt_trait_reference.is_none() {
3380 match self_type.node {
3381 // TyPath is the only thing that we handled in `build_reduced_graph_for_item`,
3382 // where we created a module with the name of the type in order to implement
3383 // an anonymous trait. In the case that the path does not resolve to an actual
3384 // type, the result will be that the type name resolves to a module but not
3385 // a type (shadowing any imported modules or types with this name), leading
3386 // to weird user-visible bugs. So we ward this off here. See #15060.
3387 TyPath(ref path, path_id) => {
3388 match self.def_map.borrow().get(&path_id) {
3389 // FIXME: should we catch other options and give more precise errors?
3390 Some(&DefMod(_)) => {
3391 self.resolve_error(path.span, "inherent implementations are not \
3392 allowed for types not defined in \
3393 the current module");
3403 fn check_trait_item(&self, name: Name, span: Span) {
3404 // If there is a TraitRef in scope for an impl, then the method must be in the trait.
3405 if let Some((did, ref trait_ref)) = self.current_trait_ref {
3406 if self.trait_item_map.get(&(name, did)).is_none() {
3407 let path_str = self.path_names_to_string(&trait_ref.path);
3408 self.resolve_error(span,
3409 &format!("method `{}` is not a member of trait `{}`",
3410 token::get_name(name),
3416 fn resolve_module(&mut self, module: &Mod, _span: Span,
3417 _name: Name, id: NodeId) {
3418 // Write the implementations in scope into the module metadata.
3419 debug!("(resolving module) resolving module ID {}", id);
3420 visit::walk_mod(self, module);
3423 fn resolve_local(&mut self, local: &Local) {
3424 // Resolve the type.
3425 if let Some(ref ty) = local.ty {
3426 self.resolve_type(&**ty);
3429 // Resolve the initializer, if necessary.
3434 Some(ref initializer) => {
3435 self.resolve_expr(&**initializer);
3439 // Resolve the pattern.
3440 let mut bindings_list = HashMap::new();
3441 self.resolve_pattern(&*local.pat,
3442 LocalIrrefutableMode,
3443 &mut bindings_list);
3446 // build a map from pattern identifiers to binding-info's.
3447 // this is done hygienically. This could arise for a macro
3448 // that expands into an or-pattern where one 'x' was from the
3449 // user and one 'x' came from the macro.
3450 fn binding_mode_map(&mut self, pat: &Pat) -> BindingMap {
3451 let mut result = HashMap::new();
3452 pat_bindings(&self.def_map, pat, |binding_mode, _id, sp, path1| {
3453 let name = mtwt::resolve(path1.node);
3454 result.insert(name, BindingInfo {
3456 binding_mode: binding_mode
3462 // check that all of the arms in an or-pattern have exactly the
3463 // same set of bindings, with the same binding modes for each.
3464 fn check_consistent_bindings(&mut self, arm: &Arm) {
3465 if arm.pats.len() == 0 {
3468 let map_0 = self.binding_mode_map(&*arm.pats[0]);
3469 for (i, p) in arm.pats.iter().enumerate() {
3470 let map_i = self.binding_mode_map(&**p);
3472 for (&key, &binding_0) in &map_0 {
3473 match map_i.get(&key) {
3477 &format!("variable `{}` from pattern #1 is \
3478 not bound in pattern #{}",
3479 token::get_name(key),
3482 Some(binding_i) => {
3483 if binding_0.binding_mode != binding_i.binding_mode {
3486 &format!("variable `{}` is bound with different \
3487 mode in pattern #{} than in pattern #1",
3488 token::get_name(key),
3495 for (&key, &binding) in &map_i {
3496 if !map_0.contains_key(&key) {
3499 &format!("variable `{}` from pattern {}{} is \
3500 not bound in pattern {}1",
3501 token::get_name(key),
3502 "#", i + 1, "#")[]);
3508 fn resolve_arm(&mut self, arm: &Arm) {
3509 self.value_ribs.push(Rib::new(NormalRibKind));
3511 let mut bindings_list = HashMap::new();
3512 for pattern in &arm.pats {
3513 self.resolve_pattern(&**pattern, RefutableMode, &mut bindings_list);
3516 // This has to happen *after* we determine which
3517 // pat_idents are variants
3518 self.check_consistent_bindings(arm);
3520 visit::walk_expr_opt(self, &arm.guard);
3521 self.resolve_expr(&*arm.body);
3523 self.value_ribs.pop();
3526 fn resolve_block(&mut self, block: &Block) {
3527 debug!("(resolving block) entering block");
3528 self.value_ribs.push(Rib::new(NormalRibKind));
3530 // Move down in the graph, if there's an anonymous module rooted here.
3531 let orig_module = self.current_module.clone();
3532 match orig_module.anonymous_children.borrow().get(&block.id) {
3533 None => { /* Nothing to do. */ }
3534 Some(anonymous_module) => {
3535 debug!("(resolving block) found anonymous module, moving \
3537 self.current_module = anonymous_module.clone();
3541 // Check for imports appearing after non-item statements.
3542 let mut found_non_item = false;
3543 for statement in &block.stmts {
3544 if let ast::StmtDecl(ref declaration, _) = statement.node {
3545 if let ast::DeclItem(ref i) = declaration.node {
3547 ItemExternCrate(_) | ItemUse(_) if found_non_item => {
3548 span_err!(self.session, i.span, E0154,
3549 "imports are not allowed after non-item statements");
3554 found_non_item = true
3557 found_non_item = true;
3561 // Descend into the block.
3562 visit::walk_block(self, block);
3565 self.current_module = orig_module;
3567 self.value_ribs.pop();
3568 debug!("(resolving block) leaving block");
3571 fn resolve_type(&mut self, ty: &Ty) {
3573 // Like path expressions, the interpretation of path types depends
3574 // on whether the path has multiple elements in it or not.
3576 TyPath(ref path, path_id) => {
3577 // This is a path in the type namespace. Walk through scopes
3579 let mut result_def = None;
3581 // First, check to see whether the name is a primitive type.
3582 if path.segments.len() == 1 {
3583 let id = path.segments.last().unwrap().identifier;
3585 match self.primitive_type_table
3589 Some(&primitive_type) => {
3591 Some((DefPrimTy(primitive_type), LastMod(AllPublic)));
3593 if path.segments[0].parameters.has_lifetimes() {
3594 span_err!(self.session, path.span, E0157,
3595 "lifetime parameters are not allowed on this type");
3596 } else if !path.segments[0].parameters.is_empty() {
3597 span_err!(self.session, path.span, E0153,
3598 "type parameters are not allowed on this type");
3607 if let None = result_def {
3608 result_def = self.resolve_path(ty.id, path, TypeNS, true);
3613 // Write the result into the def map.
3614 debug!("(resolving type) writing resolution for `{}` \
3616 self.path_names_to_string(path),
3618 self.record_def(path_id, def);
3621 let msg = format!("use of undeclared type name `{}`",
3622 self.path_names_to_string(path));
3623 self.resolve_error(ty.span, &msg[..]);
3628 TyObjectSum(ref ty, ref bound_vec) => {
3629 self.resolve_type(&**ty);
3630 self.resolve_type_parameter_bounds(ty.id, bound_vec,
3631 TraitBoundingTypeParameter);
3634 TyQPath(ref qpath) => {
3635 self.resolve_type(&*qpath.self_type);
3636 self.resolve_trait_reference(ty.id, &*qpath.trait_ref, TraitQPath);
3637 for ty in qpath.item_path.parameters.types() {
3638 self.resolve_type(&**ty);
3640 for binding in qpath.item_path.parameters.bindings() {
3641 self.resolve_type(&*binding.ty);
3645 TyPolyTraitRef(ref bounds) => {
3646 self.resolve_type_parameter_bounds(
3650 visit::walk_ty(self, ty);
3653 // Just resolve embedded types.
3654 visit::walk_ty(self, ty);
3659 fn resolve_pattern(&mut self,
3661 mode: PatternBindingMode,
3662 // Maps idents to the node ID for the (outermost)
3663 // pattern that binds them
3664 bindings_list: &mut HashMap<Name, NodeId>) {
3665 let pat_id = pattern.id;
3666 walk_pat(pattern, |pattern| {
3667 match pattern.node {
3668 PatIdent(binding_mode, ref path1, _) => {
3670 // The meaning of pat_ident with no type parameters
3671 // depends on whether an enum variant or unit-like struct
3672 // with that name is in scope. The probing lookup has to
3673 // be careful not to emit spurious errors. Only matching
3674 // patterns (match) can match nullary variants or
3675 // unit-like structs. For binding patterns (let), matching
3676 // such a value is simply disallowed (since it's rarely
3679 let ident = path1.node;
3680 let renamed = mtwt::resolve(ident);
3682 match self.resolve_bare_identifier_pattern(ident.name, pattern.span) {
3683 FoundStructOrEnumVariant(ref def, lp)
3684 if mode == RefutableMode => {
3685 debug!("(resolving pattern) resolving `{}` to \
3686 struct or enum variant",
3687 token::get_name(renamed));
3689 self.enforce_default_binding_mode(
3693 self.record_def(pattern.id, (def.clone(), lp));
3695 FoundStructOrEnumVariant(..) => {
3698 &format!("declaration of `{}` shadows an enum \
3699 variant or unit-like struct in \
3701 token::get_name(renamed))[]);
3703 FoundConst(ref def, lp) if mode == RefutableMode => {
3704 debug!("(resolving pattern) resolving `{}` to \
3706 token::get_name(renamed));
3708 self.enforce_default_binding_mode(
3712 self.record_def(pattern.id, (def.clone(), lp));
3715 self.resolve_error(pattern.span,
3716 "only irrefutable patterns \
3719 BareIdentifierPatternUnresolved => {
3720 debug!("(resolving pattern) binding `{}`",
3721 token::get_name(renamed));
3723 let def = DefLocal(pattern.id);
3725 // Record the definition so that later passes
3726 // will be able to distinguish variants from
3727 // locals in patterns.
3729 self.record_def(pattern.id, (def, LastMod(AllPublic)));
3731 // Add the binding to the local ribs, if it
3732 // doesn't already exist in the bindings list. (We
3733 // must not add it if it's in the bindings list
3734 // because that breaks the assumptions later
3735 // passes make about or-patterns.)
3736 if !bindings_list.contains_key(&renamed) {
3737 let this = &mut *self;
3738 let last_rib = this.value_ribs.last_mut().unwrap();
3739 last_rib.bindings.insert(renamed, DlDef(def));
3740 bindings_list.insert(renamed, pat_id);
3741 } else if mode == ArgumentIrrefutableMode &&
3742 bindings_list.contains_key(&renamed) {
3743 // Forbid duplicate bindings in the same
3745 self.resolve_error(pattern.span,
3746 &format!("identifier `{}` \
3754 } else if bindings_list.get(&renamed) ==
3756 // Then this is a duplicate variable in the
3757 // same disjunction, which is an error.
3758 self.resolve_error(pattern.span,
3759 &format!("identifier `{}` is bound \
3760 more than once in the same \
3762 token::get_ident(ident))[]);
3764 // Else, not bound in the same pattern: do
3770 PatEnum(ref path, _) => {
3771 // This must be an enum variant, struct or const.
3772 match self.resolve_path(pat_id, path, ValueNS, false) {
3773 Some(def @ (DefVariant(..), _)) |
3774 Some(def @ (DefStruct(..), _)) |
3775 Some(def @ (DefConst(..), _)) => {
3776 self.record_def(pattern.id, def);
3778 Some((DefStatic(..), _)) => {
3779 self.resolve_error(path.span,
3780 "static variables cannot be \
3781 referenced in a pattern, \
3782 use a `const` instead");
3785 self.resolve_error(path.span,
3786 &format!("`{}` is not an enum variant, struct or const",
3788 path.segments.last().unwrap().identifier)));
3791 self.resolve_error(path.span,
3792 &format!("unresolved enum variant, struct or const `{}`",
3793 token::get_ident(path.segments.last().unwrap().identifier)));
3797 // Check the types in the path pattern.
3798 for ty in path.segments
3800 .flat_map(|s| s.parameters.types().into_iter()) {
3801 self.resolve_type(&**ty);
3805 PatLit(ref expr) => {
3806 self.resolve_expr(&**expr);
3809 PatRange(ref first_expr, ref last_expr) => {
3810 self.resolve_expr(&**first_expr);
3811 self.resolve_expr(&**last_expr);
3814 PatStruct(ref path, _, _) => {
3815 match self.resolve_path(pat_id, path, TypeNS, false) {
3816 Some(definition) => {
3817 self.record_def(pattern.id, definition);
3820 debug!("(resolving pattern) didn't find struct \
3821 def: {:?}", result);
3822 let msg = format!("`{}` does not name a structure",
3823 self.path_names_to_string(path));
3824 self.resolve_error(path.span, &msg[..]);
3837 fn resolve_bare_identifier_pattern(&mut self, name: Name, span: Span)
3838 -> BareIdentifierPatternResolution {
3839 let module = self.current_module.clone();
3840 match self.resolve_item_in_lexical_scope(module,
3843 Success((target, _)) => {
3844 debug!("(resolve bare identifier pattern) succeeded in \
3845 finding {} at {:?}",
3846 token::get_name(name),
3847 target.bindings.value_def.borrow());
3848 match *target.bindings.value_def.borrow() {
3850 panic!("resolved name in the value namespace to a \
3851 set of name bindings with no def?!");
3854 // For the two success cases, this lookup can be
3855 // considered as not having a private component because
3856 // the lookup happened only within the current module.
3858 def @ DefVariant(..) | def @ DefStruct(..) => {
3859 return FoundStructOrEnumVariant(def, LastMod(AllPublic));
3861 def @ DefConst(..) => {
3862 return FoundConst(def, LastMod(AllPublic));
3865 self.resolve_error(span,
3866 "static variables cannot be \
3867 referenced in a pattern, \
3868 use a `const` instead");
3869 return BareIdentifierPatternUnresolved;
3872 return BareIdentifierPatternUnresolved;
3880 panic!("unexpected indeterminate result");
3884 Some((span, msg)) => {
3885 self.resolve_error(span, &format!("failed to resolve: {}",
3891 debug!("(resolve bare identifier pattern) failed to find {}",
3892 token::get_name(name));
3893 return BareIdentifierPatternUnresolved;
3898 /// If `check_ribs` is true, checks the local definitions first; i.e.
3899 /// doesn't skip straight to the containing module.
3900 fn resolve_path(&mut self,
3903 namespace: Namespace,
3904 check_ribs: bool) -> Option<(Def, LastPrivate)> {
3905 // First, resolve the types and associated type bindings.
3906 for ty in path.segments.iter().flat_map(|s| s.parameters.types().into_iter()) {
3907 self.resolve_type(&**ty);
3909 for binding in path.segments.iter().flat_map(|s| s.parameters.bindings().into_iter()) {
3910 self.resolve_type(&*binding.ty);
3913 // A special case for sugared associated type paths `T::A` where `T` is
3914 // a type parameter and `A` is an associated type on some bound of `T`.
3915 if namespace == TypeNS && path.segments.len() == 2 {
3916 match self.resolve_identifier(path.segments[0].identifier,
3920 Some((def, last_private)) => {
3922 DefTyParam(_, _, did, _) => {
3923 let def = DefAssociatedPath(TyParamProvenance::FromParam(did),
3924 path.segments.last()
3925 .unwrap().identifier);
3926 return Some((def, last_private));
3929 let def = DefAssociatedPath(TyParamProvenance::FromSelf(local_def(nid)),
3930 path.segments.last()
3931 .unwrap().identifier);
3932 return Some((def, last_private));
3942 return self.resolve_crate_relative_path(path, namespace);
3945 // Try to find a path to an item in a module.
3946 let unqualified_def =
3947 self.resolve_identifier(path.segments.last().unwrap().identifier,
3952 if path.segments.len() > 1 {
3953 let def = self.resolve_module_relative_path(path, namespace);
3954 match (def, unqualified_def) {
3955 (Some((ref d, _)), Some((ref ud, _))) if *d == *ud => {
3957 .add_lint(lint::builtin::UNUSED_QUALIFICATIONS,
3960 "unnecessary qualification".to_string());
3968 return unqualified_def;
3971 // resolve a single identifier (used as a varref)
3972 fn resolve_identifier(&mut self,
3974 namespace: Namespace,
3977 -> Option<(Def, LastPrivate)> {
3979 match self.resolve_identifier_in_local_ribs(identifier,
3983 return Some((def, LastMod(AllPublic)));
3991 return self.resolve_item_by_name_in_lexical_scope(identifier.name, namespace);
3994 // FIXME #4952: Merge me with resolve_name_in_module?
3995 fn resolve_definition_of_name_in_module(&mut self,
3996 containing_module: Rc<Module>,
3998 namespace: Namespace)
4000 // First, search children.
4001 build_reduced_graph::populate_module_if_necessary(self, &containing_module);
4003 match containing_module.children.borrow().get(&name) {
4004 Some(child_name_bindings) => {
4005 match child_name_bindings.def_for_namespace(namespace) {
4007 // Found it. Stop the search here.
4008 let p = child_name_bindings.defined_in_public_namespace(
4010 let lp = if p {LastMod(AllPublic)} else {
4011 LastMod(DependsOn(def.def_id()))
4013 return ChildNameDefinition(def, lp);
4021 // Next, search import resolutions.
4022 match containing_module.import_resolutions.borrow().get(&name) {
4023 Some(import_resolution) if import_resolution.is_public => {
4024 if let Some(target) = (*import_resolution).target_for_namespace(namespace) {
4025 match target.bindings.def_for_namespace(namespace) {
4028 let id = import_resolution.id(namespace);
4029 // track imports and extern crates as well
4030 self.used_imports.insert((id, namespace));
4031 self.record_import_use(id, name);
4032 match target.target_module.def_id.get() {
4033 Some(DefId{krate: kid, ..}) => {
4034 self.used_crates.insert(kid);
4038 return ImportNameDefinition(def, LastMod(AllPublic));
4041 // This can happen with external impls, due to
4042 // the imperfect way we read the metadata.
4047 Some(..) | None => {} // Continue.
4050 // Finally, search through external children.
4051 if namespace == TypeNS {
4052 if let Some(module) = containing_module.external_module_children.borrow()
4053 .get(&name).cloned() {
4054 if let Some(def_id) = module.def_id.get() {
4055 // track used crates
4056 self.used_crates.insert(def_id.krate);
4057 let lp = if module.is_public {LastMod(AllPublic)} else {
4058 LastMod(DependsOn(def_id))
4060 return ChildNameDefinition(DefMod(def_id), lp);
4065 return NoNameDefinition;
4068 // resolve a "module-relative" path, e.g. a::b::c
4069 fn resolve_module_relative_path(&mut self,
4071 namespace: Namespace)
4072 -> Option<(Def, LastPrivate)> {
4073 let module_path = path.segments.init().iter()
4074 .map(|ps| ps.identifier.name)
4075 .collect::<Vec<_>>();
4077 let containing_module;
4079 let module = self.current_module.clone();
4080 match self.resolve_module_path(module,
4086 let (span, msg) = match err {
4087 Some((span, msg)) => (span, msg),
4089 let msg = format!("Use of undeclared type or module `{}`",
4090 self.names_to_string(&module_path));
4095 self.resolve_error(span, &format!("failed to resolve. {}",
4099 Indeterminate => panic!("indeterminate unexpected"),
4100 Success((resulting_module, resulting_last_private)) => {
4101 containing_module = resulting_module;
4102 last_private = resulting_last_private;
4106 let name = path.segments.last().unwrap().identifier.name;
4107 let def = match self.resolve_definition_of_name_in_module(containing_module.clone(),
4110 NoNameDefinition => {
4111 // We failed to resolve the name. Report an error.
4114 ChildNameDefinition(def, lp) | ImportNameDefinition(def, lp) => {
4115 (def, last_private.or(lp))
4118 if let Some(DefId{krate: kid, ..}) = containing_module.def_id.get() {
4119 self.used_crates.insert(kid);
4124 /// Invariant: This must be called only during main resolution, not during
4125 /// import resolution.
4126 fn resolve_crate_relative_path(&mut self,
4128 namespace: Namespace)
4129 -> Option<(Def, LastPrivate)> {
4130 let module_path = path.segments.init().iter()
4131 .map(|ps| ps.identifier.name)
4132 .collect::<Vec<_>>();
4134 let root_module = self.graph_root.get_module();
4136 let containing_module;
4138 match self.resolve_module_path_from_root(root_module,
4143 LastMod(AllPublic)) {
4145 let (span, msg) = match err {
4146 Some((span, msg)) => (span, msg),
4148 let msg = format!("Use of undeclared module `::{}`",
4149 self.names_to_string(&module_path[..]));
4154 self.resolve_error(span, &format!("failed to resolve. {}",
4160 panic!("indeterminate unexpected");
4163 Success((resulting_module, resulting_last_private)) => {
4164 containing_module = resulting_module;
4165 last_private = resulting_last_private;
4169 let name = path.segments.last().unwrap().identifier.name;
4170 match self.resolve_definition_of_name_in_module(containing_module,
4173 NoNameDefinition => {
4174 // We failed to resolve the name. Report an error.
4177 ChildNameDefinition(def, lp) | ImportNameDefinition(def, lp) => {
4178 return Some((def, last_private.or(lp)));
4183 fn resolve_identifier_in_local_ribs(&mut self,
4185 namespace: Namespace,
4188 // Check the local set of ribs.
4189 let search_result = match namespace {
4191 let renamed = mtwt::resolve(ident);
4192 self.search_ribs(&self.value_ribs, renamed, span)
4195 let name = ident.name;
4196 self.search_ribs(&self.type_ribs[], name, span)
4200 match search_result {
4201 Some(DlDef(def)) => {
4202 debug!("(resolving path in local ribs) resolved `{}` to \
4204 token::get_ident(ident),
4208 Some(DlField) | Some(DlImpl(_)) | None => {
4214 fn resolve_item_by_name_in_lexical_scope(&mut self,
4216 namespace: Namespace)
4217 -> Option<(Def, LastPrivate)> {
4219 let module = self.current_module.clone();
4220 match self.resolve_item_in_lexical_scope(module,
4223 Success((target, _)) => {
4224 match (*target.bindings).def_for_namespace(namespace) {
4226 // This can happen if we were looking for a type and
4227 // found a module instead. Modules don't have defs.
4228 debug!("(resolving item path by identifier in lexical \
4229 scope) failed to resolve {} after success...",
4230 token::get_name(name));
4234 debug!("(resolving item path in lexical scope) \
4235 resolved `{}` to item",
4236 token::get_name(name));
4237 // This lookup is "all public" because it only searched
4238 // for one identifier in the current module (couldn't
4239 // have passed through reexports or anything like that.
4240 return Some((def, LastMod(AllPublic)));
4245 panic!("unexpected indeterminate result");
4249 Some((span, msg)) =>
4250 self.resolve_error(span, &format!("failed to resolve. {}",
4255 debug!("(resolving item path by identifier in lexical scope) \
4256 failed to resolve {}", token::get_name(name));
4262 fn with_no_errors<T, F>(&mut self, f: F) -> T where
4263 F: FnOnce(&mut Resolver) -> T,
4265 self.emit_errors = false;
4267 self.emit_errors = true;
4271 fn resolve_error(&self, span: Span, s: &str) {
4272 if self.emit_errors {
4273 self.session.span_err(span, s);
4277 fn find_fallback_in_self_type(&mut self, name: Name) -> FallbackSuggestion {
4278 fn extract_path_and_node_id(t: &Ty, allow: FallbackChecks)
4279 -> Option<(Path, NodeId, FallbackChecks)> {
4281 TyPath(ref path, node_id) => Some((path.clone(), node_id, allow)),
4282 TyPtr(ref mut_ty) => extract_path_and_node_id(&*mut_ty.ty, OnlyTraitAndStatics),
4283 TyRptr(_, ref mut_ty) => extract_path_and_node_id(&*mut_ty.ty, allow),
4284 // This doesn't handle the remaining `Ty` variants as they are not
4285 // that commonly the self_type, it might be interesting to provide
4286 // support for those in future.
4291 fn get_module(this: &mut Resolver, span: Span, name_path: &[ast::Name])
4292 -> Option<Rc<Module>> {
4293 let root = this.current_module.clone();
4294 let last_name = name_path.last().unwrap();
4296 if name_path.len() == 1 {
4297 match this.primitive_type_table.primitive_types.get(last_name) {
4300 match this.current_module.children.borrow().get(last_name) {
4301 Some(child) => child.get_module_if_available(),
4307 match this.resolve_module_path(root,
4312 Success((module, _)) => Some(module),
4318 let (path, node_id, allowed) = match self.current_self_type {
4319 Some(ref ty) => match extract_path_and_node_id(ty, Everything) {
4321 None => return NoSuggestion,
4323 None => return NoSuggestion,
4326 if allowed == Everything {
4327 // Look for a field with the same name in the current self_type.
4328 match self.def_map.borrow().get(&node_id) {
4329 Some(&DefTy(did, _))
4330 | Some(&DefStruct(did))
4331 | Some(&DefVariant(_, did, _)) => match self.structs.get(&did) {
4334 if fields.iter().any(|&field_name| name == field_name) {
4339 _ => {} // Self type didn't resolve properly
4343 let name_path = path.segments.iter().map(|seg| seg.identifier.name).collect::<Vec<_>>();
4345 // Look for a method in the current self type's impl module.
4346 match get_module(self, path.span, &name_path[..]) {
4347 Some(module) => match module.children.borrow().get(&name) {
4349 let p_str = self.path_names_to_string(&path);
4350 match binding.def_for_namespace(ValueNS) {
4351 Some(DefStaticMethod(_, provenance)) => {
4353 FromImpl(_) => return StaticMethod(p_str),
4354 FromTrait(_) => unreachable!()
4357 Some(DefMethod(_, None, _)) if allowed == Everything => return Method,
4358 Some(DefMethod(_, Some(_), _)) => return TraitItem,
4367 // Look for a method in the current trait.
4368 match self.current_trait_ref {
4369 Some((did, ref trait_ref)) => {
4370 let path_str = self.path_names_to_string(&trait_ref.path);
4372 match self.trait_item_map.get(&(name, did)) {
4373 Some(&StaticMethodTraitItemKind) => {
4374 return TraitMethod(path_str)
4376 Some(_) => return TraitItem,
4386 fn find_best_match_for_name(&mut self, name: &str, max_distance: uint)
4388 let this = &mut *self;
4390 let mut maybes: Vec<token::InternedString> = Vec::new();
4391 let mut values: Vec<uint> = Vec::new();
4393 for rib in this.value_ribs.iter().rev() {
4394 for (&k, _) in &rib.bindings {
4395 maybes.push(token::get_name(k));
4396 values.push(usize::MAX);
4400 let mut smallest = 0;
4401 for (i, other) in maybes.iter().enumerate() {
4402 values[i] = lev_distance(name, &other);
4404 if values[i] <= values[smallest] {
4409 if values.len() > 0 &&
4410 values[smallest] != usize::MAX &&
4411 values[smallest] < name.len() + 2 &&
4412 values[smallest] <= max_distance &&
4413 name != &maybes[smallest][] {
4415 Some(maybes[smallest].to_string())
4422 fn resolve_expr(&mut self, expr: &Expr) {
4423 // First, record candidate traits for this expression if it could
4424 // result in the invocation of a method call.
4426 self.record_candidate_traits_for_expr_if_necessary(expr);
4428 // Next, resolve the node.
4430 // The interpretation of paths depends on whether the path has
4431 // multiple elements in it or not.
4433 ExprPath(_) | ExprQPath(_) => {
4434 let mut path_from_qpath;
4435 let path = match expr.node {
4436 ExprPath(ref path) => path,
4437 ExprQPath(ref qpath) => {
4438 self.resolve_type(&*qpath.self_type);
4439 self.resolve_trait_reference(expr.id, &*qpath.trait_ref, TraitQPath);
4440 path_from_qpath = qpath.trait_ref.path.clone();
4441 path_from_qpath.segments.push(qpath.item_path.clone());
4446 // This is a local path in the value namespace. Walk through
4447 // scopes looking for it.
4448 match self.resolve_path(expr.id, path, ValueNS, true) {
4449 // Check if struct variant
4450 Some((DefVariant(_, _, true), _)) => {
4451 let path_name = self.path_names_to_string(path);
4452 self.resolve_error(expr.span,
4453 &format!("`{}` is a struct variant name, but \
4455 uses it like a function name",
4458 self.session.span_help(expr.span,
4459 &format!("Did you mean to write: \
4460 `{} {{ /* fields */ }}`?",
4464 // Write the result into the def map.
4465 debug!("(resolving expr) resolved `{}`",
4466 self.path_names_to_string(path));
4468 self.record_def(expr.id, def);
4471 // Be helpful if the name refers to a struct
4472 // (The pattern matching def_tys where the id is in self.structs
4473 // matches on regular structs while excluding tuple- and enum-like
4474 // structs, which wouldn't result in this error.)
4475 let path_name = self.path_names_to_string(path);
4476 match self.with_no_errors(|this|
4477 this.resolve_path(expr.id, path, TypeNS, false)) {
4478 Some((DefTy(struct_id, _), _))
4479 if self.structs.contains_key(&struct_id) => {
4480 self.resolve_error(expr.span,
4481 &format!("`{}` is a structure name, but \
4483 uses it like a function name",
4486 self.session.span_help(expr.span,
4487 &format!("Did you mean to write: \
4488 `{} {{ /* fields */ }}`?",
4493 let mut method_scope = false;
4494 self.value_ribs.iter().rev().all(|rib| {
4495 let res = match *rib {
4496 Rib { bindings: _, kind: MethodRibKind(_, _) } => true,
4497 Rib { bindings: _, kind: ItemRibKind } => false,
4498 _ => return true, // Keep advancing
4502 false // Stop advancing
4505 if method_scope && &token::get_name(self.self_name)[]
4509 "`self` is not available \
4510 in a static method. Maybe a \
4511 `self` argument is missing?");
4513 let last_name = path.segments.last().unwrap().identifier.name;
4514 let mut msg = match self.find_fallback_in_self_type(last_name) {
4516 // limit search to 5 to reduce the number
4517 // of stupid suggestions
4518 self.find_best_match_for_name(&path_name, 5)
4519 .map_or("".to_string(),
4520 |x| format!("`{}`", x))
4523 format!("`self.{}`", path_name),
4526 format!("to call `self.{}`", path_name),
4527 TraitMethod(path_str)
4528 | StaticMethod(path_str) =>
4529 format!("to call `{}::{}`", path_str, path_name)
4533 msg = format!(". Did you mean {}?", msg)
4538 &format!("unresolved name `{}`{}",
4547 visit::walk_expr(self, expr);
4550 ExprClosure(_, ref fn_decl, ref block) => {
4551 self.resolve_function(ClosureRibKind(expr.id),
4552 Some(&**fn_decl), NoTypeParameters,
4556 ExprStruct(ref path, _, _) => {
4557 // Resolve the path to the structure it goes to. We don't
4558 // check to ensure that the path is actually a structure; that
4559 // is checked later during typeck.
4560 match self.resolve_path(expr.id, path, TypeNS, false) {
4561 Some(definition) => self.record_def(expr.id, definition),
4563 debug!("(resolving expression) didn't find struct \
4564 def: {:?}", result);
4565 let msg = format!("`{}` does not name a structure",
4566 self.path_names_to_string(path));
4567 self.resolve_error(path.span, &msg[..]);
4571 visit::walk_expr(self, expr);
4574 ExprLoop(_, Some(label)) | ExprWhile(_, _, Some(label)) => {
4575 self.with_label_rib(|this| {
4576 let def_like = DlDef(DefLabel(expr.id));
4579 let rib = this.label_ribs.last_mut().unwrap();
4580 let renamed = mtwt::resolve(label);
4581 rib.bindings.insert(renamed, def_like);
4584 visit::walk_expr(this, expr);
4588 ExprBreak(Some(label)) | ExprAgain(Some(label)) => {
4589 let renamed = mtwt::resolve(label);
4590 match self.search_label(renamed) {
4594 &format!("use of undeclared label `{}`",
4595 token::get_ident(label))[])
4597 Some(DlDef(def @ DefLabel(_))) => {
4598 // Since this def is a label, it is never read.
4599 self.record_def(expr.id, (def, LastMod(AllPublic)))
4602 self.session.span_bug(expr.span,
4603 "label wasn't mapped to a \
4610 visit::walk_expr(self, expr);
4615 fn record_candidate_traits_for_expr_if_necessary(&mut self, expr: &Expr) {
4617 ExprField(_, ident) => {
4618 // FIXME(#6890): Even though you can't treat a method like a
4619 // field, we need to add any trait methods we find that match
4620 // the field name so that we can do some nice error reporting
4621 // later on in typeck.
4622 let traits = self.search_for_traits_containing_method(ident.node.name);
4623 self.trait_map.insert(expr.id, traits);
4625 ExprMethodCall(ident, _, _) => {
4626 debug!("(recording candidate traits for expr) recording \
4629 let traits = self.search_for_traits_containing_method(ident.node.name);
4630 self.trait_map.insert(expr.id, traits);
4638 fn search_for_traits_containing_method(&mut self, name: Name) -> Vec<DefId> {
4639 debug!("(searching for traits containing method) looking for '{}'",
4640 token::get_name(name));
4642 fn add_trait_info(found_traits: &mut Vec<DefId>,
4643 trait_def_id: DefId,
4645 debug!("(adding trait info) found trait {}:{} for method '{}'",
4648 token::get_name(name));
4649 found_traits.push(trait_def_id);
4652 let mut found_traits = Vec::new();
4653 let mut search_module = self.current_module.clone();
4655 // Look for the current trait.
4656 match self.current_trait_ref {
4657 Some((trait_def_id, _)) => {
4658 if self.trait_item_map.contains_key(&(name, trait_def_id)) {
4659 add_trait_info(&mut found_traits, trait_def_id, name);
4662 None => {} // Nothing to do.
4665 // Look for trait children.
4666 build_reduced_graph::populate_module_if_necessary(self, &search_module);
4669 for (_, child_names) in &*search_module.children.borrow() {
4670 let def = match child_names.def_for_namespace(TypeNS) {
4674 let trait_def_id = match def {
4675 DefTrait(trait_def_id) => trait_def_id,
4678 if self.trait_item_map.contains_key(&(name, trait_def_id)) {
4679 add_trait_info(&mut found_traits, trait_def_id, name);
4684 // Look for imports.
4685 for (_, import) in &*search_module.import_resolutions.borrow() {
4686 let target = match import.target_for_namespace(TypeNS) {
4688 Some(target) => target,
4690 let did = match target.bindings.def_for_namespace(TypeNS) {
4691 Some(DefTrait(trait_def_id)) => trait_def_id,
4692 Some(..) | None => continue,
4694 if self.trait_item_map.contains_key(&(name, did)) {
4695 add_trait_info(&mut found_traits, did, name);
4696 let id = import.type_id;
4697 self.used_imports.insert((id, TypeNS));
4698 let trait_name = self.get_trait_name(did);
4699 self.record_import_use(id, trait_name);
4700 if let Some(DefId{krate: kid, ..}) = target.target_module.def_id.get() {
4701 self.used_crates.insert(kid);
4706 match search_module.parent_link.clone() {
4707 NoParentLink | ModuleParentLink(..) => break,
4708 BlockParentLink(parent_module, _) => {
4709 search_module = parent_module.upgrade().unwrap();
4717 fn record_def(&mut self, node_id: NodeId, (def, lp): (Def, LastPrivate)) {
4718 debug!("(recording def) recording {:?} for {}, last private {:?}",
4720 assert!(match lp {LastImport{..} => false, _ => true},
4721 "Import should only be used for `use` directives");
4722 self.last_private.insert(node_id, lp);
4724 match self.def_map.borrow_mut().entry(node_id) {
4725 // Resolve appears to "resolve" the same ID multiple
4726 // times, so here is a sanity check it at least comes to
4727 // the same conclusion! - nmatsakis
4728 Occupied(entry) => if def != *entry.get() {
4730 .bug(&format!("node_id {} resolved first to {:?} and \
4736 Vacant(entry) => { entry.insert(def); },
4740 fn enforce_default_binding_mode(&mut self,
4742 pat_binding_mode: BindingMode,
4744 match pat_binding_mode {
4745 BindByValue(_) => {}
4747 self.resolve_error(pat.span,
4748 &format!("cannot use `ref` binding mode \
4758 // Diagnostics are not particularly efficient, because they're rarely
4762 /// A somewhat inefficient routine to obtain the name of a module.
4763 fn module_to_string(&self, module: &Module) -> String {
4764 let mut names = Vec::new();
4766 fn collect_mod(names: &mut Vec<ast::Name>, module: &Module) {
4767 match module.parent_link {
4769 ModuleParentLink(ref module, name) => {
4771 collect_mod(names, &*module.upgrade().unwrap());
4773 BlockParentLink(ref module, _) => {
4774 // danger, shouldn't be ident?
4775 names.push(special_idents::opaque.name);
4776 collect_mod(names, &*module.upgrade().unwrap());
4780 collect_mod(&mut names, module);
4782 if names.len() == 0 {
4783 return "???".to_string();
4785 self.names_to_string(&names.into_iter().rev()
4786 .collect::<Vec<ast::Name>>()[])
4789 #[allow(dead_code)] // useful for debugging
4790 fn dump_module(&mut self, module_: Rc<Module>) {
4791 debug!("Dump of module `{}`:", self.module_to_string(&*module_));
4793 debug!("Children:");
4794 build_reduced_graph::populate_module_if_necessary(self, &module_);
4795 for (&name, _) in &*module_.children.borrow() {
4796 debug!("* {}", token::get_name(name));
4799 debug!("Import resolutions:");
4800 let import_resolutions = module_.import_resolutions.borrow();
4801 for (&name, import_resolution) in &*import_resolutions {
4803 match import_resolution.target_for_namespace(ValueNS) {
4804 None => { value_repr = "".to_string(); }
4806 value_repr = " value:?".to_string();
4812 match import_resolution.target_for_namespace(TypeNS) {
4813 None => { type_repr = "".to_string(); }
4815 type_repr = " type:?".to_string();
4820 debug!("* {}:{}{}", token::get_name(name), value_repr, type_repr);
4825 pub struct CrateMap {
4826 pub def_map: DefMap,
4827 pub freevars: RefCell<FreevarMap>,
4828 pub export_map: ExportMap,
4829 pub trait_map: TraitMap,
4830 pub external_exports: ExternalExports,
4831 pub last_private_map: LastPrivateMap,
4832 pub glob_map: Option<GlobMap>
4835 #[derive(PartialEq,Copy)]
4836 pub enum MakeGlobMap {
4841 /// Entry point to crate resolution.
4842 pub fn resolve_crate<'a, 'tcx>(session: &'a Session,
4843 ast_map: &'a ast_map::Map<'tcx>,
4846 make_glob_map: MakeGlobMap)
4848 let mut resolver = Resolver::new(session, ast_map, krate.span, make_glob_map);
4850 build_reduced_graph::build_reduced_graph(&mut resolver, krate);
4851 session.abort_if_errors();
4853 resolver.resolve_imports();
4854 session.abort_if_errors();
4856 record_exports::record(&mut resolver);
4857 session.abort_if_errors();
4859 resolver.resolve_crate(krate);
4860 session.abort_if_errors();
4862 check_unused::check_crate(&mut resolver, krate);
4865 def_map: resolver.def_map,
4866 freevars: resolver.freevars,
4867 export_map: resolver.export_map,
4868 trait_map: resolver.trait_map,
4869 external_exports: resolver.external_exports,
4870 last_private_map: resolver.last_private,
4871 glob_map: if resolver.make_glob_map {
4872 Some(resolver.glob_map)