1 // Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
11 #![crate_name = "rustc_resolve"]
14 #![crate_type = "dylib"]
15 #![crate_type = "rlib"]
16 #![doc(html_logo_url = "http://www.rust-lang.org/logos/rust-logo-128x128-blk-v2.png",
17 html_favicon_url = "http://www.rust-lang.org/favicon.ico",
18 html_root_url = "http://doc.rust-lang.org/nightly/")]
20 #![feature(slicing_syntax)]
21 #![feature(rustc_diagnostic_macros)]
22 #![allow(unknown_features)] #![feature(int_uint)]
24 #[macro_use] extern crate log;
25 #[macro_use] extern crate syntax;
29 use self::PatternBindingMode::*;
30 use self::Namespace::*;
31 use self::NamespaceResult::*;
32 use self::NameDefinition::*;
33 use self::ImportDirectiveSubclass::*;
34 use self::ResolveResult::*;
35 use self::FallbackSuggestion::*;
36 use self::TypeParameters::*;
38 use self::MethodSort::*;
39 use self::UseLexicalScopeFlag::*;
40 use self::ModulePrefixResult::*;
41 use self::NameSearchType::*;
42 use self::BareIdentifierPatternResolution::*;
43 use self::ParentLink::*;
44 use self::ModuleKind::*;
45 use self::TraitReferenceType::*;
46 use self::FallbackChecks::*;
48 use rustc::session::Session;
50 use rustc::metadata::csearch;
51 use rustc::metadata::decoder::{DefLike, DlDef, DlField, DlImpl};
52 use rustc::middle::def::*;
53 use rustc::middle::lang_items::LanguageItems;
54 use rustc::middle::pat_util::pat_bindings;
55 use rustc::middle::privacy::*;
56 use rustc::middle::subst::{ParamSpace, FnSpace, TypeSpace};
57 use rustc::middle::ty::{CaptureModeMap, Freevar, FreevarMap, TraitMap, GlobMap};
58 use rustc::util::nodemap::{NodeMap, NodeSet, DefIdSet, FnvHashMap};
59 use rustc::util::lev_distance::lev_distance;
61 use syntax::ast::{Arm, BindByRef, BindByValue, BindingMode, Block, Crate, CrateNum};
62 use syntax::ast::{DefId, Expr, ExprAgain, ExprBreak, ExprField};
63 use syntax::ast::{ExprClosure, ExprForLoop, ExprLoop, ExprWhile, ExprMethodCall};
64 use syntax::ast::{ExprPath, ExprStruct, FnDecl};
65 use syntax::ast::{ForeignItemFn, ForeignItemStatic, Generics};
66 use syntax::ast::{Ident, ImplItem, Item, ItemConst, ItemEnum, ItemFn};
67 use syntax::ast::{ItemForeignMod, ItemImpl, ItemMac, ItemMod, ItemStatic};
68 use syntax::ast::{ItemStruct, ItemTrait, ItemTy, Local, LOCAL_CRATE};
69 use syntax::ast::{MethodImplItem, Mod, Name, NodeId};
70 use syntax::ast::{Pat, PatEnum, PatIdent, PatLit};
71 use syntax::ast::{PatRange, PatStruct, Path};
72 use syntax::ast::{PolyTraitRef, PrimTy, SelfExplicit};
73 use syntax::ast::{RegionTyParamBound, StructField};
74 use syntax::ast::{TraitRef, TraitTyParamBound};
75 use syntax::ast::{Ty, TyBool, TyChar, TyF32};
76 use syntax::ast::{TyF64, TyFloat, TyIs, TyI8, TyI16, TyI32, TyI64, TyInt, TyObjectSum};
77 use syntax::ast::{TyParam, TyParamBound, TyPath, TyPtr, TyPolyTraitRef, TyQPath};
78 use syntax::ast::{TyRptr, TyStr, TyUs, TyU8, TyU16, TyU32, TyU64, TyUint};
79 use syntax::ast::{TypeImplItem};
82 use syntax::ast_util::{PostExpansionMethod, local_def, walk_pat};
83 use syntax::attr::AttrMetaMethods;
84 use syntax::ext::mtwt;
85 use syntax::parse::token::{self, special_names, special_idents};
86 use syntax::codemap::{Span, Pos};
87 use syntax::owned_slice::OwnedSlice;
88 use syntax::visit::{self, Visitor};
90 use std::collections::{HashMap, HashSet};
91 use std::collections::hash_map::Entry::{Occupied, Vacant};
92 use std::cell::{Cell, RefCell};
94 use std::mem::replace;
95 use std::rc::{Rc, Weak};
100 mod build_reduced_graph;
105 binding_mode: BindingMode,
108 // Map from the name in a pattern to its binding mode.
109 type BindingMap = HashMap<Name, BindingInfo>;
111 #[derive(Copy, PartialEq)]
112 enum PatternBindingMode {
114 LocalIrrefutableMode,
115 ArgumentIrrefutableMode,
118 #[derive(Copy, PartialEq, Eq, Hash, Show)]
124 /// A NamespaceResult represents the result of resolving an import in
125 /// a particular namespace. The result is either definitely-resolved,
126 /// definitely- unresolved, or unknown.
128 enum NamespaceResult {
129 /// Means that resolve hasn't gathered enough information yet to determine
130 /// whether the name is bound in this namespace. (That is, it hasn't
131 /// resolved all `use` directives yet.)
133 /// Means that resolve has determined that the name is definitely
134 /// not bound in the namespace.
136 /// Means that resolve has determined that the name is bound in the Module
137 /// argument, and specified by the NameBindings argument.
138 BoundResult(Rc<Module>, Rc<NameBindings>)
141 impl NamespaceResult {
142 fn is_unknown(&self) -> bool {
144 UnknownResult => true,
148 fn is_unbound(&self) -> bool {
150 UnboundResult => true,
156 enum NameDefinition {
157 NoNameDefinition, //< The name was unbound.
158 ChildNameDefinition(Def, LastPrivate), //< The name identifies an immediate child.
159 ImportNameDefinition(Def, LastPrivate) //< The name identifies an import.
162 impl<'a, 'v, 'tcx> Visitor<'v> for Resolver<'a, 'tcx> {
163 fn visit_item(&mut self, item: &Item) {
164 self.resolve_item(item);
166 fn visit_arm(&mut self, arm: &Arm) {
167 self.resolve_arm(arm);
169 fn visit_block(&mut self, block: &Block) {
170 self.resolve_block(block);
172 fn visit_expr(&mut self, expr: &Expr) {
173 self.resolve_expr(expr);
175 fn visit_local(&mut self, local: &Local) {
176 self.resolve_local(local);
178 fn visit_ty(&mut self, ty: &Ty) {
179 self.resolve_type(ty);
183 /// Contains data for specific types of import directives.
185 enum ImportDirectiveSubclass {
186 SingleImport(Name /* target */, Name /* source */),
190 type ErrorMessage = Option<(Span, String)>;
192 enum ResolveResult<T> {
193 Failed(ErrorMessage), // Failed to resolve the name, optional helpful error message.
194 Indeterminate, // Couldn't determine due to unresolved globs.
195 Success(T) // Successfully resolved the import.
198 impl<T> ResolveResult<T> {
199 fn indeterminate(&self) -> bool {
200 match *self { Indeterminate => true, _ => false }
204 enum FallbackSuggestion {
209 StaticMethod(String),
214 enum TypeParameters<'a> {
220 // Identifies the things that these parameters
221 // were declared on (type, fn, etc)
224 // ID of the enclosing item.
227 // The kind of the rib used for type parameters.
231 // The rib kind controls the translation of local
232 // definitions (`DefLocal`) to upvars (`DefUpvar`).
233 #[derive(Copy, Show)]
235 // No translation needs to be applied.
238 // We passed through a closure scope at the given node ID.
239 // Translate upvars as appropriate.
240 ClosureRibKind(NodeId /* func id */, NodeId /* body id if proc or unboxed */),
242 // We passed through an impl or trait and are now in one of its
243 // methods. Allow references to ty params that impl or trait
244 // binds. Disallow any other upvars (including other ty params that are
246 // parent; method itself
247 MethodRibKind(NodeId, MethodSort),
249 // We passed through an item scope. Disallow upvars.
252 // We're in a constant item. Can't refer to dynamic stuff.
256 // Methods can be required or provided. RequiredMethod methods only occur in traits.
257 #[derive(Copy, Show)]
260 ProvidedMethod(NodeId)
264 enum UseLexicalScopeFlag {
269 enum ModulePrefixResult {
271 PrefixFound(Rc<Module>, uint)
274 #[derive(Copy, PartialEq)]
275 enum NameSearchType {
276 /// We're doing a name search in order to resolve a `use` directive.
279 /// We're doing a name search in order to resolve a path type, a path
280 /// expression, or a path pattern.
285 enum BareIdentifierPatternResolution {
286 FoundStructOrEnumVariant(Def, LastPrivate),
287 FoundConst(Def, LastPrivate),
288 BareIdentifierPatternUnresolved
294 bindings: HashMap<Name, DefLike>,
299 fn new(kind: RibKind) -> Rib {
301 bindings: HashMap::new(),
307 /// Whether an import can be shadowed by another import.
308 #[derive(Show,PartialEq,Clone,Copy)]
314 /// One import directive.
316 struct ImportDirective {
317 module_path: Vec<Name>,
318 subclass: ImportDirectiveSubclass,
321 is_public: bool, // see note in ImportResolution about how to use this
322 shadowable: Shadowable,
325 impl ImportDirective {
326 fn new(module_path: Vec<Name> ,
327 subclass: ImportDirectiveSubclass,
331 shadowable: Shadowable)
334 module_path: module_path,
338 is_public: is_public,
339 shadowable: shadowable,
344 /// The item that an import resolves to.
345 #[derive(Clone,Show)]
347 target_module: Rc<Module>,
348 bindings: Rc<NameBindings>,
349 shadowable: Shadowable,
353 fn new(target_module: Rc<Module>,
354 bindings: Rc<NameBindings>,
355 shadowable: Shadowable)
358 target_module: target_module,
360 shadowable: shadowable,
365 /// An ImportResolution represents a particular `use` directive.
367 struct ImportResolution {
368 /// Whether this resolution came from a `use` or a `pub use`. Note that this
369 /// should *not* be used whenever resolution is being performed, this is
370 /// only looked at for glob imports statements currently. Privacy testing
371 /// occurs during a later phase of compilation.
374 // The number of outstanding references to this name. When this reaches
375 // zero, outside modules can count on the targets being correct. Before
376 // then, all bets are off; future imports could override this name.
377 outstanding_references: uint,
379 /// The value that this `use` directive names, if there is one.
380 value_target: Option<Target>,
381 /// The source node of the `use` directive leading to the value target
385 /// The type that this `use` directive names, if there is one.
386 type_target: Option<Target>,
387 /// The source node of the `use` directive leading to the type target
392 impl ImportResolution {
393 fn new(id: NodeId, is_public: bool) -> ImportResolution {
397 outstanding_references: 0,
400 is_public: is_public,
404 fn target_for_namespace(&self, namespace: Namespace)
407 TypeNS => self.type_target.clone(),
408 ValueNS => self.value_target.clone(),
412 fn id(&self, namespace: Namespace) -> NodeId {
414 TypeNS => self.type_id,
415 ValueNS => self.value_id,
419 fn shadowable(&self, namespace: Namespace) -> Shadowable {
420 let target = self.target_for_namespace(namespace);
421 if target.is_none() {
422 return Shadowable::Always;
425 target.unwrap().shadowable
428 fn set_target_and_id(&mut self,
429 namespace: Namespace,
430 target: Option<Target>,
434 self.type_target = target;
438 self.value_target = target;
445 /// The link from a module up to its nearest parent node.
446 #[derive(Clone,Show)]
449 ModuleParentLink(Weak<Module>, Name),
450 BlockParentLink(Weak<Module>, NodeId)
453 /// The type of module this is.
454 #[derive(Copy, PartialEq, Show)]
463 /// One node in the tree of modules.
465 parent_link: ParentLink,
466 def_id: Cell<Option<DefId>>,
467 kind: Cell<ModuleKind>,
470 children: RefCell<HashMap<Name, Rc<NameBindings>>>,
471 imports: RefCell<Vec<ImportDirective>>,
473 // The external module children of this node that were declared with
475 external_module_children: RefCell<HashMap<Name, Rc<Module>>>,
477 // The anonymous children of this node. Anonymous children are pseudo-
478 // modules that are implicitly created around items contained within
481 // For example, if we have this:
489 // There will be an anonymous module created around `g` with the ID of the
490 // entry block for `f`.
491 anonymous_children: RefCell<NodeMap<Rc<Module>>>,
493 // The status of resolving each import in this module.
494 import_resolutions: RefCell<HashMap<Name, ImportResolution>>,
496 // The number of unresolved globs that this module exports.
497 glob_count: Cell<uint>,
499 // The index of the import we're resolving.
500 resolved_import_count: Cell<uint>,
502 // Whether this module is populated. If not populated, any attempt to
503 // access the children must be preceded with a
504 // `populate_module_if_necessary` call.
505 populated: Cell<bool>,
509 fn new(parent_link: ParentLink,
510 def_id: Option<DefId>,
516 parent_link: parent_link,
517 def_id: Cell::new(def_id),
518 kind: Cell::new(kind),
519 is_public: is_public,
520 children: RefCell::new(HashMap::new()),
521 imports: RefCell::new(Vec::new()),
522 external_module_children: RefCell::new(HashMap::new()),
523 anonymous_children: RefCell::new(NodeMap::new()),
524 import_resolutions: RefCell::new(HashMap::new()),
525 glob_count: Cell::new(0),
526 resolved_import_count: Cell::new(0),
527 populated: Cell::new(!external),
531 fn all_imports_resolved(&self) -> bool {
532 self.imports.borrow().len() == self.resolved_import_count.get()
536 impl fmt::Show for Module {
537 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
538 write!(f, "{:?}, kind: {:?}, {}",
541 if self.is_public { "public" } else { "private" } )
547 flags DefModifiers: u8 {
548 const PUBLIC = 0b0000_0001,
549 const IMPORTABLE = 0b0000_0010,
553 // Records a possibly-private type definition.
554 #[derive(Clone,Show)]
556 modifiers: DefModifiers, // see note in ImportResolution about how to use this
557 module_def: Option<Rc<Module>>,
558 type_def: Option<Def>,
559 type_span: Option<Span>
562 // Records a possibly-private value definition.
563 #[derive(Clone, Copy, Show)]
565 modifiers: DefModifiers, // see note in ImportResolution about how to use this
567 value_span: Option<Span>,
570 // Records the definitions (at most one for each namespace) that a name is
573 struct NameBindings {
574 type_def: RefCell<Option<TypeNsDef>>, //< Meaning in type namespace.
575 value_def: RefCell<Option<ValueNsDef>>, //< Meaning in value namespace.
578 /// Ways in which a trait can be referenced
580 enum TraitReferenceType {
581 TraitImplementation, // impl SomeTrait for T { ... }
582 TraitDerivation, // trait T : SomeTrait { ... }
583 TraitBoundingTypeParameter, // fn f<T:SomeTrait>() { ... }
584 TraitObject, // Box<for<'a> SomeTrait>
585 TraitQPath, // <T as SomeTrait>::
589 fn new() -> NameBindings {
591 type_def: RefCell::new(None),
592 value_def: RefCell::new(None),
596 /// Creates a new module in this set of name bindings.
597 fn define_module(&self,
598 parent_link: ParentLink,
599 def_id: Option<DefId>,
604 // Merges the module with the existing type def or creates a new one.
605 let modifiers = if is_public { PUBLIC } else { DefModifiers::empty() } | IMPORTABLE;
606 let module_ = Rc::new(Module::new(parent_link,
611 let type_def = self.type_def.borrow().clone();
614 *self.type_def.borrow_mut() = Some(TypeNsDef {
615 modifiers: modifiers,
616 module_def: Some(module_),
622 *self.type_def.borrow_mut() = Some(TypeNsDef {
623 modifiers: modifiers,
624 module_def: Some(module_),
626 type_def: type_def.type_def
632 /// Sets the kind of the module, creating a new one if necessary.
633 fn set_module_kind(&self,
634 parent_link: ParentLink,
635 def_id: Option<DefId>,
640 let modifiers = if is_public { PUBLIC } else { DefModifiers::empty() } | IMPORTABLE;
641 let type_def = self.type_def.borrow().clone();
644 let module = Module::new(parent_link,
649 *self.type_def.borrow_mut() = Some(TypeNsDef {
650 modifiers: modifiers,
651 module_def: Some(Rc::new(module)),
657 match type_def.module_def {
659 let module = Module::new(parent_link,
664 *self.type_def.borrow_mut() = Some(TypeNsDef {
665 modifiers: modifiers,
666 module_def: Some(Rc::new(module)),
667 type_def: type_def.type_def,
671 Some(module_def) => module_def.kind.set(kind),
677 /// Records a type definition.
678 fn define_type(&self, def: Def, sp: Span, modifiers: DefModifiers) {
679 debug!("defining type for def {:?} with modifiers {:?}", def, modifiers);
680 // Merges the type with the existing type def or creates a new one.
681 let type_def = self.type_def.borrow().clone();
684 *self.type_def.borrow_mut() = Some(TypeNsDef {
688 modifiers: modifiers,
692 *self.type_def.borrow_mut() = Some(TypeNsDef {
693 module_def: type_def.module_def,
696 modifiers: modifiers,
702 /// Records a value definition.
703 fn define_value(&self, def: Def, sp: Span, modifiers: DefModifiers) {
704 debug!("defining value for def {:?} with modifiers {:?}", def, modifiers);
705 *self.value_def.borrow_mut() = Some(ValueNsDef {
707 value_span: Some(sp),
708 modifiers: modifiers,
712 /// Returns the module node if applicable.
713 fn get_module_if_available(&self) -> Option<Rc<Module>> {
714 match *self.type_def.borrow() {
715 Some(ref type_def) => type_def.module_def.clone(),
720 /// Returns the module node. Panics if this node does not have a module
722 fn get_module(&self) -> Rc<Module> {
723 match self.get_module_if_available() {
725 panic!("get_module called on a node with no module \
728 Some(module_def) => module_def
732 fn defined_in_namespace(&self, namespace: Namespace) -> bool {
734 TypeNS => return self.type_def.borrow().is_some(),
735 ValueNS => return self.value_def.borrow().is_some()
739 fn defined_in_public_namespace(&self, namespace: Namespace) -> bool {
740 self.defined_in_namespace_with(namespace, PUBLIC)
743 fn defined_in_namespace_with(&self, namespace: Namespace, modifiers: DefModifiers) -> bool {
745 TypeNS => match *self.type_def.borrow() {
746 Some(ref def) => def.modifiers.contains(modifiers), None => false
748 ValueNS => match *self.value_def.borrow() {
749 Some(ref def) => def.modifiers.contains(modifiers), None => false
754 fn def_for_namespace(&self, namespace: Namespace) -> Option<Def> {
757 match *self.type_def.borrow() {
759 Some(ref type_def) => {
760 match type_def.type_def {
761 Some(type_def) => Some(type_def),
763 match type_def.module_def {
764 Some(ref module) => {
765 match module.def_id.get() {
766 Some(did) => Some(DefMod(did)),
778 match *self.value_def.borrow() {
780 Some(value_def) => Some(value_def.def)
786 fn span_for_namespace(&self, namespace: Namespace) -> Option<Span> {
787 if self.defined_in_namespace(namespace) {
790 match *self.type_def.borrow() {
792 Some(ref type_def) => type_def.type_span
796 match *self.value_def.borrow() {
798 Some(ref value_def) => value_def.value_span
808 /// Interns the names of the primitive types.
809 struct PrimitiveTypeTable {
810 primitive_types: HashMap<Name, PrimTy>,
813 impl PrimitiveTypeTable {
814 fn new() -> PrimitiveTypeTable {
815 let mut table = PrimitiveTypeTable {
816 primitive_types: HashMap::new()
819 table.intern("bool", TyBool);
820 table.intern("char", TyChar);
821 table.intern("f32", TyFloat(TyF32));
822 table.intern("f64", TyFloat(TyF64));
823 table.intern("int", TyInt(TyIs(true)));
824 table.intern("isize", TyInt(TyIs(false)));
825 table.intern("i8", TyInt(TyI8));
826 table.intern("i16", TyInt(TyI16));
827 table.intern("i32", TyInt(TyI32));
828 table.intern("i64", TyInt(TyI64));
829 table.intern("str", TyStr);
830 table.intern("uint", TyUint(TyUs(true)));
831 table.intern("usize", TyUint(TyUs(false)));
832 table.intern("u8", TyUint(TyU8));
833 table.intern("u16", TyUint(TyU16));
834 table.intern("u32", TyUint(TyU32));
835 table.intern("u64", TyUint(TyU64));
840 fn intern(&mut self, string: &str, primitive_type: PrimTy) {
841 self.primitive_types.insert(token::intern(string), primitive_type);
845 /// The main resolver class.
846 struct Resolver<'a, 'tcx:'a> {
847 session: &'a Session,
849 ast_map: &'a ast_map::Map<'tcx>,
851 graph_root: NameBindings,
853 trait_item_map: FnvHashMap<(Name, DefId), TraitItemKind>,
855 structs: FnvHashMap<DefId, Vec<Name>>,
857 // The number of imports that are currently unresolved.
858 unresolved_imports: uint,
860 // The module that represents the current item scope.
861 current_module: Rc<Module>,
863 // The current set of local scopes, for values.
864 // FIXME #4948: Reuse ribs to avoid allocation.
865 value_ribs: Vec<Rib>,
867 // The current set of local scopes, for types.
870 // The current set of local scopes, for labels.
871 label_ribs: Vec<Rib>,
873 // The trait that the current context can refer to.
874 current_trait_ref: Option<(DefId, TraitRef)>,
876 // The current self type if inside an impl (used for better errors).
877 current_self_type: Option<Ty>,
879 // The ident for the keyword "self".
881 // The ident for the non-keyword "Self".
882 type_self_name: Name,
884 // The idents for the primitive types.
885 primitive_type_table: PrimitiveTypeTable,
888 freevars: RefCell<FreevarMap>,
889 freevars_seen: RefCell<NodeMap<NodeSet>>,
890 capture_mode_map: CaptureModeMap,
891 export_map: ExportMap,
893 external_exports: ExternalExports,
894 last_private: LastPrivateMap,
896 // Whether or not to print error messages. Can be set to true
897 // when getting additional info for error message suggestions,
898 // so as to avoid printing duplicate errors
902 // Maps imports to the names of items actually imported (this actually maps
903 // all imports, but only glob imports are actually interesting).
906 used_imports: HashSet<(NodeId, Namespace)>,
907 used_crates: HashSet<CrateNum>,
911 enum FallbackChecks {
917 impl<'a, 'tcx> Resolver<'a, 'tcx> {
918 fn new(session: &'a Session,
919 ast_map: &'a ast_map::Map<'tcx>,
921 make_glob_map: MakeGlobMap) -> Resolver<'a, 'tcx> {
922 let graph_root = NameBindings::new();
924 graph_root.define_module(NoParentLink,
925 Some(DefId { krate: 0, node: 0 }),
931 let current_module = graph_root.get_module();
938 // The outermost module has def ID 0; this is not reflected in the
941 graph_root: graph_root,
943 trait_item_map: FnvHashMap::new(),
944 structs: FnvHashMap::new(),
946 unresolved_imports: 0,
948 current_module: current_module,
949 value_ribs: Vec::new(),
950 type_ribs: Vec::new(),
951 label_ribs: Vec::new(),
953 current_trait_ref: None,
954 current_self_type: None,
956 self_name: special_names::self_,
957 type_self_name: special_names::type_self,
959 primitive_type_table: PrimitiveTypeTable::new(),
961 def_map: RefCell::new(NodeMap::new()),
962 freevars: RefCell::new(NodeMap::new()),
963 freevars_seen: RefCell::new(NodeMap::new()),
964 capture_mode_map: NodeMap::new(),
965 export_map: NodeMap::new(),
966 trait_map: NodeMap::new(),
967 used_imports: HashSet::new(),
968 used_crates: HashSet::new(),
969 external_exports: DefIdSet::new(),
970 last_private: NodeMap::new(),
973 make_glob_map: make_glob_map == MakeGlobMap::Yes,
974 glob_map: HashMap::new(),
980 // This is a fixed-point algorithm. We resolve imports until our efforts
981 // are stymied by an unresolved import; then we bail out of the current
982 // module and continue. We terminate successfully once no more imports
983 // remain or unsuccessfully when no forward progress in resolving imports
986 /// Resolves all imports for the crate. This method performs the fixed-
988 fn resolve_imports(&mut self) {
990 let mut prev_unresolved_imports = 0;
992 debug!("(resolving imports) iteration {}, {} imports left",
993 i, self.unresolved_imports);
995 let module_root = self.graph_root.get_module();
996 self.resolve_imports_for_module_subtree(module_root.clone());
998 if self.unresolved_imports == 0 {
999 debug!("(resolving imports) success");
1003 if self.unresolved_imports == prev_unresolved_imports {
1004 self.report_unresolved_imports(module_root);
1009 prev_unresolved_imports = self.unresolved_imports;
1013 /// Attempts to resolve imports for the given module and all of its
1015 fn resolve_imports_for_module_subtree(&mut self, module_: Rc<Module>) {
1016 debug!("(resolving imports for module subtree) resolving {}",
1017 self.module_to_string(&*module_));
1018 let orig_module = replace(&mut self.current_module, module_.clone());
1019 self.resolve_imports_for_module(module_.clone());
1020 self.current_module = orig_module;
1022 build_reduced_graph::populate_module_if_necessary(self, &module_);
1023 for (_, child_node) in module_.children.borrow().iter() {
1024 match child_node.get_module_if_available() {
1028 Some(child_module) => {
1029 self.resolve_imports_for_module_subtree(child_module);
1034 for (_, child_module) in module_.anonymous_children.borrow().iter() {
1035 self.resolve_imports_for_module_subtree(child_module.clone());
1039 /// Attempts to resolve imports for the given module only.
1040 fn resolve_imports_for_module(&mut self, module: Rc<Module>) {
1041 if module.all_imports_resolved() {
1042 debug!("(resolving imports for module) all imports resolved for \
1044 self.module_to_string(&*module));
1048 let imports = module.imports.borrow();
1049 let import_count = imports.len();
1050 while module.resolved_import_count.get() < import_count {
1051 let import_index = module.resolved_import_count.get();
1052 let import_directive = &(*imports)[import_index];
1053 match self.resolve_import_for_module(module.clone(),
1056 let (span, help) = match err {
1057 Some((span, msg)) => (span, format!(". {}", msg)),
1058 None => (import_directive.span, String::new())
1060 let msg = format!("unresolved import `{}`{}",
1061 self.import_path_to_string(
1062 &import_directive.module_path[],
1063 import_directive.subclass),
1065 self.resolve_error(span, &msg[]);
1067 Indeterminate => break, // Bail out. We'll come around next time.
1068 Success(()) => () // Good. Continue.
1071 module.resolved_import_count
1072 .set(module.resolved_import_count.get() + 1);
1076 fn names_to_string(&self, names: &[Name]) -> String {
1077 let mut first = true;
1078 let mut result = String::new();
1079 for name in names.iter() {
1083 result.push_str("::")
1085 result.push_str(token::get_name(*name).get());
1090 fn path_names_to_string(&self, path: &Path) -> String {
1091 let names: Vec<ast::Name> = path.segments
1093 .map(|seg| seg.identifier.name)
1095 self.names_to_string(&names[])
1098 fn import_directive_subclass_to_string(&mut self,
1099 subclass: ImportDirectiveSubclass)
1102 SingleImport(_, source) => {
1103 token::get_name(source).get().to_string()
1105 GlobImport => "*".to_string()
1109 fn import_path_to_string(&mut self,
1111 subclass: ImportDirectiveSubclass)
1113 if names.is_empty() {
1114 self.import_directive_subclass_to_string(subclass)
1117 self.names_to_string(names),
1118 self.import_directive_subclass_to_string(
1119 subclass))).to_string()
1124 fn record_import_use(&mut self, import_id: NodeId, name: Name) {
1125 if !self.make_glob_map {
1128 if self.glob_map.contains_key(&import_id) {
1129 self.glob_map[import_id].insert(name);
1133 let mut new_set = HashSet::new();
1134 new_set.insert(name);
1135 self.glob_map.insert(import_id, new_set);
1138 fn get_trait_name(&self, did: DefId) -> Name {
1139 if did.krate == LOCAL_CRATE {
1140 self.ast_map.expect_item(did.node).ident.name
1142 csearch::get_trait_name(&self.session.cstore, did)
1146 /// Attempts to resolve the given import. The return value indicates
1147 /// failure if we're certain the name does not exist, indeterminate if we
1148 /// don't know whether the name exists at the moment due to other
1149 /// currently-unresolved imports, or success if we know the name exists.
1150 /// If successful, the resolved bindings are written into the module.
1151 fn resolve_import_for_module(&mut self,
1152 module_: Rc<Module>,
1153 import_directive: &ImportDirective)
1154 -> ResolveResult<()> {
1155 let mut resolution_result = Failed(None);
1156 let module_path = &import_directive.module_path;
1158 debug!("(resolving import for module) resolving import `{}::...` in `{}`",
1159 self.names_to_string(&module_path[]),
1160 self.module_to_string(&*module_));
1162 // First, resolve the module path for the directive, if necessary.
1163 let container = if module_path.len() == 0 {
1164 // Use the crate root.
1165 Some((self.graph_root.get_module(), LastMod(AllPublic)))
1167 match self.resolve_module_path(module_.clone(),
1169 DontUseLexicalScope,
1170 import_directive.span,
1173 resolution_result = Failed(err);
1177 resolution_result = Indeterminate;
1180 Success(container) => Some(container),
1186 Some((containing_module, lp)) => {
1187 // We found the module that the target is contained
1188 // within. Attempt to resolve the import within it.
1190 match import_directive.subclass {
1191 SingleImport(target, source) => {
1193 self.resolve_single_import(&*module_,
1202 self.resolve_glob_import(&*module_,
1211 // Decrement the count of unresolved imports.
1212 match resolution_result {
1214 assert!(self.unresolved_imports >= 1);
1215 self.unresolved_imports -= 1;
1218 // Nothing to do here; just return the error.
1222 // Decrement the count of unresolved globs if necessary. But only if
1223 // the resolution result is indeterminate -- otherwise we'll stop
1224 // processing imports here. (See the loop in
1225 // resolve_imports_for_module.)
1227 if !resolution_result.indeterminate() {
1228 match import_directive.subclass {
1230 assert!(module_.glob_count.get() >= 1);
1231 module_.glob_count.set(module_.glob_count.get() - 1);
1233 SingleImport(..) => {
1239 return resolution_result;
1242 fn create_name_bindings_from_module(module: Rc<Module>) -> NameBindings {
1244 type_def: RefCell::new(Some(TypeNsDef {
1245 modifiers: IMPORTABLE,
1246 module_def: Some(module),
1250 value_def: RefCell::new(None),
1254 fn resolve_single_import(&mut self,
1256 containing_module: Rc<Module>,
1259 directive: &ImportDirective,
1261 -> ResolveResult<()> {
1262 debug!("(resolving single import) resolving `{}` = `{}::{}` from \
1263 `{}` id {}, last private {:?}",
1264 token::get_name(target),
1265 self.module_to_string(&*containing_module),
1266 token::get_name(source),
1267 self.module_to_string(module_),
1273 LastImport {..} => {
1275 .span_bug(directive.span,
1276 "not expecting Import here, must be LastMod")
1280 // We need to resolve both namespaces for this to succeed.
1283 let mut value_result = UnknownResult;
1284 let mut type_result = UnknownResult;
1286 // Search for direct children of the containing module.
1287 build_reduced_graph::populate_module_if_necessary(self, &containing_module);
1289 match containing_module.children.borrow().get(&source) {
1293 Some(ref child_name_bindings) => {
1294 if child_name_bindings.defined_in_namespace(ValueNS) {
1295 debug!("(resolving single import) found value binding");
1296 value_result = BoundResult(containing_module.clone(),
1297 (*child_name_bindings).clone());
1299 if child_name_bindings.defined_in_namespace(TypeNS) {
1300 debug!("(resolving single import) found type binding");
1301 type_result = BoundResult(containing_module.clone(),
1302 (*child_name_bindings).clone());
1307 // Unless we managed to find a result in both namespaces (unlikely),
1308 // search imports as well.
1309 let mut value_used_reexport = false;
1310 let mut type_used_reexport = false;
1311 match (value_result.clone(), type_result.clone()) {
1312 (BoundResult(..), BoundResult(..)) => {} // Continue.
1314 // If there is an unresolved glob at this point in the
1315 // containing module, bail out. We don't know enough to be
1316 // able to resolve this import.
1318 if containing_module.glob_count.get() > 0 {
1319 debug!("(resolving single import) unresolved glob; \
1321 return Indeterminate;
1324 // Now search the exported imports within the containing module.
1325 match containing_module.import_resolutions.borrow().get(&source) {
1327 debug!("(resolving single import) no import");
1328 // The containing module definitely doesn't have an
1329 // exported import with the name in question. We can
1330 // therefore accurately report that the names are
1333 if value_result.is_unknown() {
1334 value_result = UnboundResult;
1336 if type_result.is_unknown() {
1337 type_result = UnboundResult;
1340 Some(import_resolution)
1341 if import_resolution.outstanding_references == 0 => {
1343 fn get_binding(this: &mut Resolver,
1344 import_resolution: &ImportResolution,
1345 namespace: Namespace,
1347 -> NamespaceResult {
1349 // Import resolutions must be declared with "pub"
1350 // in order to be exported.
1351 if !import_resolution.is_public {
1352 return UnboundResult;
1355 match import_resolution.
1356 target_for_namespace(namespace) {
1358 return UnboundResult;
1365 debug!("(resolving single import) found \
1366 import in ns {:?}", namespace);
1367 let id = import_resolution.id(namespace);
1368 // track used imports and extern crates as well
1369 this.used_imports.insert((id, namespace));
1370 this.record_import_use(id, *source);
1371 match target_module.def_id.get() {
1372 Some(DefId{krate: kid, ..}) => {
1373 this.used_crates.insert(kid);
1377 return BoundResult(target_module, bindings);
1382 // The name is an import which has been fully
1383 // resolved. We can, therefore, just follow it.
1384 if value_result.is_unknown() {
1385 value_result = get_binding(self,
1389 value_used_reexport = import_resolution.is_public;
1391 if type_result.is_unknown() {
1392 type_result = get_binding(self,
1396 type_used_reexport = import_resolution.is_public;
1401 // If containing_module is the same module whose import we are resolving
1402 // and there it has an unresolved import with the same name as `source`,
1403 // then the user is actually trying to import an item that is declared
1404 // in the same scope
1407 // use self::submodule;
1408 // pub mod submodule;
1410 // In this case we continue as if we resolved the import and let the
1411 // check_for_conflicts_between_imports_and_items call below handle
1413 match (module_.def_id.get(), containing_module.def_id.get()) {
1414 (Some(id1), Some(id2)) if id1 == id2 => {
1415 if value_result.is_unknown() {
1416 value_result = UnboundResult;
1418 if type_result.is_unknown() {
1419 type_result = UnboundResult;
1423 // The import is unresolved. Bail out.
1424 debug!("(resolving single import) unresolved import; \
1426 return Indeterminate;
1434 // If we didn't find a result in the type namespace, search the
1435 // external modules.
1436 let mut value_used_public = false;
1437 let mut type_used_public = false;
1439 BoundResult(..) => {}
1441 match containing_module.external_module_children.borrow_mut()
1442 .get(&source).cloned() {
1443 None => {} // Continue.
1445 debug!("(resolving single import) found external \
1447 // track the module as used.
1448 match module.def_id.get() {
1449 Some(DefId{krate: kid, ..}) => { self.used_crates.insert(kid); },
1453 Rc::new(Resolver::create_name_bindings_from_module(
1455 type_result = BoundResult(containing_module.clone(),
1457 type_used_public = true;
1463 // We've successfully resolved the import. Write the results in.
1464 let mut import_resolutions = module_.import_resolutions.borrow_mut();
1465 let import_resolution = &mut (*import_resolutions)[target];
1467 let mut check_and_write_import = |&mut: namespace, result: &_, used_public: &mut bool| {
1468 let namespace_name = match namespace {
1474 BoundResult(ref target_module, ref name_bindings) => {
1475 debug!("(resolving single import) found {:?} target: {:?}",
1477 name_bindings.def_for_namespace(namespace));
1478 self.check_for_conflicting_import(
1479 &import_resolution.target_for_namespace(namespace),
1484 self.check_that_import_is_importable(
1490 let target = Some(Target::new(target_module.clone(),
1491 name_bindings.clone(),
1492 directive.shadowable));
1493 import_resolution.set_target_and_id(namespace, target, directive.id);
1494 import_resolution.is_public = directive.is_public;
1495 *used_public = name_bindings.defined_in_public_namespace(namespace);
1497 UnboundResult => { /* Continue. */ }
1499 panic!("{:?} result should be known at this point", namespace_name);
1503 check_and_write_import(ValueNS, &value_result, &mut value_used_public);
1504 check_and_write_import(TypeNS, &type_result, &mut type_used_public);
1507 self.check_for_conflicts_between_imports_and_items(
1513 if value_result.is_unbound() && type_result.is_unbound() {
1514 let msg = format!("There is no `{}` in `{}`",
1515 token::get_name(source),
1516 self.module_to_string(&*containing_module));
1517 return Failed(Some((directive.span, msg)));
1519 let value_used_public = value_used_reexport || value_used_public;
1520 let type_used_public = type_used_reexport || type_used_public;
1522 assert!(import_resolution.outstanding_references >= 1);
1523 import_resolution.outstanding_references -= 1;
1525 // record what this import resolves to for later uses in documentation,
1526 // this may resolve to either a value or a type, but for documentation
1527 // purposes it's good enough to just favor one over the other.
1528 let value_private = match import_resolution.value_target {
1529 Some(ref target) => {
1530 let def = target.bindings.def_for_namespace(ValueNS).unwrap();
1531 self.def_map.borrow_mut().insert(directive.id, def);
1532 let did = def.def_id();
1533 if value_used_public {Some(lp)} else {Some(DependsOn(did))}
1535 // AllPublic here and below is a dummy value, it should never be used because
1536 // _exists is false.
1539 let type_private = match import_resolution.type_target {
1540 Some(ref target) => {
1541 let def = target.bindings.def_for_namespace(TypeNS).unwrap();
1542 self.def_map.borrow_mut().insert(directive.id, def);
1543 let did = def.def_id();
1544 if type_used_public {Some(lp)} else {Some(DependsOn(did))}
1549 self.last_private.insert(directive.id, LastImport{value_priv: value_private,
1551 type_priv: type_private,
1554 debug!("(resolving single import) successfully resolved import");
1558 // Resolves a glob import. Note that this function cannot fail; it either
1559 // succeeds or bails out (as importing * from an empty module or a module
1560 // that exports nothing is valid). containing_module is the module we are
1561 // actually importing, i.e., `foo` in `use foo::*`.
1562 fn resolve_glob_import(&mut self,
1564 containing_module: Rc<Module>,
1565 import_directive: &ImportDirective,
1567 -> ResolveResult<()> {
1568 let id = import_directive.id;
1569 let is_public = import_directive.is_public;
1571 // This function works in a highly imperative manner; it eagerly adds
1572 // everything it can to the list of import resolutions of the module
1574 debug!("(resolving glob import) resolving glob import {}", id);
1576 // We must bail out if the node has unresolved imports of any kind
1577 // (including globs).
1578 if !(*containing_module).all_imports_resolved() {
1579 debug!("(resolving glob import) target module has unresolved \
1580 imports; bailing out");
1581 return Indeterminate;
1584 assert_eq!(containing_module.glob_count.get(), 0);
1586 // Add all resolved imports from the containing module.
1587 let import_resolutions = containing_module.import_resolutions.borrow();
1588 for (ident, target_import_resolution) in import_resolutions.iter() {
1589 debug!("(resolving glob import) writing module resolution \
1591 token::get_name(*ident),
1592 self.module_to_string(module_));
1594 if !target_import_resolution.is_public {
1595 debug!("(resolving glob import) nevermind, just kidding");
1599 // Here we merge two import resolutions.
1600 let mut import_resolutions = module_.import_resolutions.borrow_mut();
1601 match import_resolutions.get_mut(ident) {
1602 Some(dest_import_resolution) => {
1603 // Merge the two import resolutions at a finer-grained
1606 match target_import_resolution.value_target {
1610 Some(ref value_target) => {
1611 self.check_for_conflicting_import(&dest_import_resolution.value_target,
1612 import_directive.span,
1615 dest_import_resolution.value_target = Some(value_target.clone());
1618 match target_import_resolution.type_target {
1622 Some(ref type_target) => {
1623 self.check_for_conflicting_import(&dest_import_resolution.type_target,
1624 import_directive.span,
1627 dest_import_resolution.type_target = Some(type_target.clone());
1630 dest_import_resolution.is_public = is_public;
1636 // Simple: just copy the old import resolution.
1637 let mut new_import_resolution = ImportResolution::new(id, is_public);
1638 new_import_resolution.value_target =
1639 target_import_resolution.value_target.clone();
1640 new_import_resolution.type_target =
1641 target_import_resolution.type_target.clone();
1643 import_resolutions.insert(*ident, new_import_resolution);
1646 // Add all children from the containing module.
1647 build_reduced_graph::populate_module_if_necessary(self, &containing_module);
1649 for (&name, name_bindings) in containing_module.children.borrow().iter() {
1650 self.merge_import_resolution(module_,
1651 containing_module.clone(),
1654 name_bindings.clone());
1658 // Add external module children from the containing module.
1659 for (&name, module) in containing_module.external_module_children.borrow().iter() {
1661 Rc::new(Resolver::create_name_bindings_from_module(module.clone()));
1662 self.merge_import_resolution(module_,
1663 containing_module.clone(),
1669 // Record the destination of this import
1670 match containing_module.def_id.get() {
1672 self.def_map.borrow_mut().insert(id, DefMod(did));
1673 self.last_private.insert(id, lp);
1678 debug!("(resolving glob import) successfully resolved import");
1682 fn merge_import_resolution(&mut self,
1684 containing_module: Rc<Module>,
1685 import_directive: &ImportDirective,
1687 name_bindings: Rc<NameBindings>) {
1688 let id = import_directive.id;
1689 let is_public = import_directive.is_public;
1691 let mut import_resolutions = module_.import_resolutions.borrow_mut();
1692 let dest_import_resolution = import_resolutions.entry(name).get().unwrap_or_else(
1694 // Create a new import resolution from this child.
1695 vacant_entry.insert(ImportResolution::new(id, is_public))
1698 debug!("(resolving glob import) writing resolution `{}` in `{}` \
1700 token::get_name(name).get(),
1701 self.module_to_string(&*containing_module),
1702 self.module_to_string(module_));
1704 // Merge the child item into the import resolution.
1706 let mut merge_child_item = |&mut : namespace| {
1707 if name_bindings.defined_in_namespace_with(namespace, IMPORTABLE | PUBLIC) {
1708 let namespace_name = match namespace {
1712 debug!("(resolving glob import) ... for {} target", namespace_name);
1713 if dest_import_resolution.shadowable(namespace) == Shadowable::Never {
1714 let msg = format!("a {} named `{}` has already been imported \
1717 token::get_name(name).get());
1718 self.session.span_err(import_directive.span, msg.as_slice());
1720 let target = Target::new(containing_module.clone(),
1721 name_bindings.clone(),
1722 import_directive.shadowable);
1723 dest_import_resolution.set_target_and_id(namespace,
1729 merge_child_item(ValueNS);
1730 merge_child_item(TypeNS);
1733 dest_import_resolution.is_public = is_public;
1735 self.check_for_conflicts_between_imports_and_items(
1737 dest_import_resolution,
1738 import_directive.span,
1742 /// Checks that imported names and items don't have the same name.
1743 fn check_for_conflicting_import(&mut self,
1744 target: &Option<Target>,
1747 namespace: Namespace) {
1748 if self.session.features.borrow().import_shadowing {
1752 debug!("check_for_conflicting_import: {}; target exists: {}",
1753 token::get_name(name).get(),
1757 Some(ref target) if target.shadowable != Shadowable::Always => {
1758 let msg = format!("a {} named `{}` has already been imported \
1764 token::get_name(name).get());
1765 self.session.span_err(import_span, &msg[]);
1767 Some(_) | None => {}
1771 /// Checks that an import is actually importable
1772 fn check_that_import_is_importable(&mut self,
1773 name_bindings: &NameBindings,
1776 namespace: Namespace) {
1777 if !name_bindings.defined_in_namespace_with(namespace, IMPORTABLE) {
1778 let msg = format!("`{}` is not directly importable",
1779 token::get_name(name));
1780 self.session.span_err(import_span, &msg[]);
1784 /// Checks that imported names and items don't have the same name.
1785 fn check_for_conflicts_between_imports_and_items(&mut self,
1791 if self.session.features.borrow().import_shadowing {
1795 // First, check for conflicts between imports and `extern crate`s.
1796 if module.external_module_children
1798 .contains_key(&name) {
1799 match import_resolution.type_target {
1800 Some(ref target) if target.shadowable != Shadowable::Always => {
1801 let msg = format!("import `{0}` conflicts with imported \
1802 crate in this module \
1803 (maybe you meant `use {0}::*`?)",
1804 token::get_name(name).get());
1805 self.session.span_err(import_span, &msg[]);
1807 Some(_) | None => {}
1811 // Check for item conflicts.
1812 let children = module.children.borrow();
1813 let name_bindings = match children.get(&name) {
1815 // There can't be any conflicts.
1818 Some(ref name_bindings) => (*name_bindings).clone(),
1821 match import_resolution.value_target {
1822 Some(ref target) if target.shadowable != Shadowable::Always => {
1823 if let Some(ref value) = *name_bindings.value_def.borrow() {
1824 let msg = format!("import `{}` conflicts with value \
1826 token::get_name(name).get());
1827 self.session.span_err(import_span, &msg[]);
1828 if let Some(span) = value.value_span {
1829 self.session.span_note(span,
1830 "conflicting value here");
1834 Some(_) | None => {}
1837 match import_resolution.type_target {
1838 Some(ref target) if target.shadowable != Shadowable::Always => {
1839 if let Some(ref ty) = *name_bindings.type_def.borrow() {
1840 match ty.module_def {
1842 let msg = format!("import `{}` conflicts with type in \
1844 token::get_name(name).get());
1845 self.session.span_err(import_span, &msg[]);
1846 if let Some(span) = ty.type_span {
1847 self.session.span_note(span,
1848 "note conflicting type here")
1851 Some(ref module_def) => {
1852 match module_def.kind.get() {
1854 if let Some(span) = ty.type_span {
1855 let msg = format!("inherent implementations \
1856 are only allowed on types \
1857 defined in the current module");
1858 self.session.span_err(span, &msg[]);
1859 self.session.span_note(import_span,
1860 "import from other module here")
1864 let msg = format!("import `{}` conflicts with existing \
1866 token::get_name(name).get());
1867 self.session.span_err(import_span, &msg[]);
1868 if let Some(span) = ty.type_span {
1869 self.session.span_note(span,
1870 "note conflicting module here")
1878 Some(_) | None => {}
1882 /// Checks that the names of external crates don't collide with other
1883 /// external crates.
1884 fn check_for_conflicts_between_external_crates(&self,
1888 if self.session.features.borrow().import_shadowing {
1892 if module.external_module_children.borrow().contains_key(&name) {
1895 &format!("an external crate named `{}` has already \
1896 been imported into this module",
1897 token::get_name(name).get())[]);
1901 /// Checks that the names of items don't collide with external crates.
1902 fn check_for_conflicts_between_external_crates_and_items(&self,
1906 if self.session.features.borrow().import_shadowing {
1910 if module.external_module_children.borrow().contains_key(&name) {
1913 &format!("the name `{}` conflicts with an external \
1914 crate that has been imported into this \
1916 token::get_name(name).get())[]);
1920 /// Resolves the given module path from the given root `module_`.
1921 fn resolve_module_path_from_root(&mut self,
1922 module_: Rc<Module>,
1923 module_path: &[Name],
1926 name_search_type: NameSearchType,
1928 -> ResolveResult<(Rc<Module>, LastPrivate)> {
1929 fn search_parent_externals(needle: Name, module: &Rc<Module>)
1930 -> Option<Rc<Module>> {
1931 module.external_module_children.borrow()
1932 .get(&needle).cloned()
1933 .map(|_| module.clone())
1935 match module.parent_link.clone() {
1936 ModuleParentLink(parent, _) => {
1937 search_parent_externals(needle,
1938 &parent.upgrade().unwrap())
1945 let mut search_module = module_;
1946 let mut index = index;
1947 let module_path_len = module_path.len();
1948 let mut closest_private = lp;
1950 // Resolve the module part of the path. This does not involve looking
1951 // upward though scope chains; we simply resolve names directly in
1952 // modules as we go.
1953 while index < module_path_len {
1954 let name = module_path[index];
1955 match self.resolve_name_in_module(search_module.clone(),
1961 let segment_name = token::get_name(name);
1962 let module_name = self.module_to_string(&*search_module);
1963 let mut span = span;
1964 let msg = if "???" == &module_name[] {
1965 span.hi = span.lo + Pos::from_uint(segment_name.get().len());
1967 match search_parent_externals(name,
1968 &self.current_module) {
1970 let path_str = self.names_to_string(module_path);
1971 let target_mod_str = self.module_to_string(&*module);
1972 let current_mod_str =
1973 self.module_to_string(&*self.current_module);
1975 let prefix = if target_mod_str == current_mod_str {
1976 "self::".to_string()
1978 format!("{}::", target_mod_str)
1981 format!("Did you mean `{}{}`?", prefix, path_str)
1983 None => format!("Maybe a missing `extern crate {}`?",
1987 format!("Could not find `{}` in `{}`",
1992 return Failed(Some((span, msg)));
1994 Failed(err) => return Failed(err),
1996 debug!("(resolving module path for import) module \
1997 resolution is indeterminate: {}",
1998 token::get_name(name));
1999 return Indeterminate;
2001 Success((target, used_proxy)) => {
2002 // Check to see whether there are type bindings, and, if
2003 // so, whether there is a module within.
2004 match *target.bindings.type_def.borrow() {
2005 Some(ref type_def) => {
2006 match type_def.module_def {
2008 let msg = format!("Not a module `{}`",
2009 token::get_name(name));
2011 return Failed(Some((span, msg)));
2013 Some(ref module_def) => {
2014 search_module = module_def.clone();
2016 // track extern crates for unused_extern_crate lint
2017 if let Some(did) = module_def.def_id.get() {
2018 self.used_crates.insert(did.krate);
2021 // Keep track of the closest
2022 // private module used when
2023 // resolving this import chain.
2024 if !used_proxy && !search_module.is_public {
2025 if let Some(did) = search_module.def_id.get() {
2026 closest_private = LastMod(DependsOn(did));
2033 // There are no type bindings at all.
2034 let msg = format!("Not a module `{}`",
2035 token::get_name(name));
2036 return Failed(Some((span, msg)));
2045 return Success((search_module, closest_private));
2048 /// Attempts to resolve the module part of an import directive or path
2049 /// rooted at the given module.
2051 /// On success, returns the resolved module, and the closest *private*
2052 /// module found to the destination when resolving this path.
2053 fn resolve_module_path(&mut self,
2054 module_: Rc<Module>,
2055 module_path: &[Name],
2056 use_lexical_scope: UseLexicalScopeFlag,
2058 name_search_type: NameSearchType)
2059 -> ResolveResult<(Rc<Module>, LastPrivate)> {
2060 let module_path_len = module_path.len();
2061 assert!(module_path_len > 0);
2063 debug!("(resolving module path for import) processing `{}` rooted at `{}`",
2064 self.names_to_string(module_path),
2065 self.module_to_string(&*module_));
2067 // Resolve the module prefix, if any.
2068 let module_prefix_result = self.resolve_module_prefix(module_.clone(),
2074 match module_prefix_result {
2076 let mpath = self.names_to_string(module_path);
2077 let mpath = &mpath[];
2078 match mpath.rfind(':') {
2080 let msg = format!("Could not find `{}` in `{}`",
2081 // idx +- 1 to account for the
2082 // colons on either side
2083 &mpath[(idx + 1)..],
2084 &mpath[..(idx - 1)]);
2085 return Failed(Some((span, msg)));
2092 Failed(err) => return Failed(err),
2094 debug!("(resolving module path for import) indeterminate; \
2096 return Indeterminate;
2098 Success(NoPrefixFound) => {
2099 // There was no prefix, so we're considering the first element
2100 // of the path. How we handle this depends on whether we were
2101 // instructed to use lexical scope or not.
2102 match use_lexical_scope {
2103 DontUseLexicalScope => {
2104 // This is a crate-relative path. We will start the
2105 // resolution process at index zero.
2106 search_module = self.graph_root.get_module();
2108 last_private = LastMod(AllPublic);
2110 UseLexicalScope => {
2111 // This is not a crate-relative path. We resolve the
2112 // first component of the path in the current lexical
2113 // scope and then proceed to resolve below that.
2114 match self.resolve_module_in_lexical_scope(module_,
2116 Failed(err) => return Failed(err),
2118 debug!("(resolving module path for import) \
2119 indeterminate; bailing");
2120 return Indeterminate;
2122 Success(containing_module) => {
2123 search_module = containing_module;
2125 last_private = LastMod(AllPublic);
2131 Success(PrefixFound(ref containing_module, index)) => {
2132 search_module = containing_module.clone();
2133 start_index = index;
2134 last_private = LastMod(DependsOn(containing_module.def_id
2140 self.resolve_module_path_from_root(search_module,
2148 /// Invariant: This must only be called during main resolution, not during
2149 /// import resolution.
2150 fn resolve_item_in_lexical_scope(&mut self,
2151 module_: Rc<Module>,
2153 namespace: Namespace)
2154 -> ResolveResult<(Target, bool)> {
2155 debug!("(resolving item in lexical scope) resolving `{}` in \
2156 namespace {:?} in `{}`",
2157 token::get_name(name),
2159 self.module_to_string(&*module_));
2161 // The current module node is handled specially. First, check for
2162 // its immediate children.
2163 build_reduced_graph::populate_module_if_necessary(self, &module_);
2165 match module_.children.borrow().get(&name) {
2167 if name_bindings.defined_in_namespace(namespace) => {
2168 debug!("top name bindings succeeded");
2169 return Success((Target::new(module_.clone(),
2170 name_bindings.clone(),
2174 Some(_) | None => { /* Not found; continue. */ }
2177 // Now check for its import directives. We don't have to have resolved
2178 // all its imports in the usual way; this is because chains of
2179 // adjacent import statements are processed as though they mutated the
2181 if let Some(import_resolution) = module_.import_resolutions.borrow().get(&name) {
2182 match (*import_resolution).target_for_namespace(namespace) {
2184 // Not found; continue.
2185 debug!("(resolving item in lexical scope) found \
2186 import resolution, but not in namespace {:?}",
2190 debug!("(resolving item in lexical scope) using \
2191 import resolution");
2192 // track used imports and extern crates as well
2193 let id = import_resolution.id(namespace);
2194 self.used_imports.insert((id, namespace));
2195 self.record_import_use(id, name);
2196 if let Some(DefId{krate: kid, ..}) = target.target_module.def_id.get() {
2197 self.used_crates.insert(kid);
2199 return Success((target, false));
2204 // Search for external modules.
2205 if namespace == TypeNS {
2206 if let Some(module) = module_.external_module_children.borrow().get(&name).cloned() {
2208 Rc::new(Resolver::create_name_bindings_from_module(module));
2209 debug!("lower name bindings succeeded");
2210 return Success((Target::new(module_,
2217 // Finally, proceed up the scope chain looking for parent modules.
2218 let mut search_module = module_;
2220 // Go to the next parent.
2221 match search_module.parent_link.clone() {
2223 // No more parents. This module was unresolved.
2224 debug!("(resolving item in lexical scope) unresolved \
2226 return Failed(None);
2228 ModuleParentLink(parent_module_node, _) => {
2229 match search_module.kind.get() {
2230 NormalModuleKind => {
2231 // We stop the search here.
2232 debug!("(resolving item in lexical \
2233 scope) unresolved module: not \
2234 searching through module \
2236 return Failed(None);
2241 AnonymousModuleKind => {
2242 search_module = parent_module_node.upgrade().unwrap();
2246 BlockParentLink(ref parent_module_node, _) => {
2247 search_module = parent_module_node.upgrade().unwrap();
2251 // Resolve the name in the parent module.
2252 match self.resolve_name_in_module(search_module.clone(),
2257 Failed(Some((span, msg))) =>
2258 self.resolve_error(span, &format!("failed to resolve. {}",
2260 Failed(None) => (), // Continue up the search chain.
2262 // We couldn't see through the higher scope because of an
2263 // unresolved import higher up. Bail.
2265 debug!("(resolving item in lexical scope) indeterminate \
2266 higher scope; bailing");
2267 return Indeterminate;
2269 Success((target, used_reexport)) => {
2270 // We found the module.
2271 debug!("(resolving item in lexical scope) found name \
2273 return Success((target, used_reexport));
2279 /// Resolves a module name in the current lexical scope.
2280 fn resolve_module_in_lexical_scope(&mut self,
2281 module_: Rc<Module>,
2283 -> ResolveResult<Rc<Module>> {
2284 // If this module is an anonymous module, resolve the item in the
2285 // lexical scope. Otherwise, resolve the item from the crate root.
2286 let resolve_result = self.resolve_item_in_lexical_scope(module_, name, TypeNS);
2287 match resolve_result {
2288 Success((target, _)) => {
2289 let bindings = &*target.bindings;
2290 match *bindings.type_def.borrow() {
2291 Some(ref type_def) => {
2292 match type_def.module_def {
2294 debug!("!!! (resolving module in lexical \
2295 scope) module wasn't actually a \
2297 return Failed(None);
2299 Some(ref module_def) => {
2300 return Success(module_def.clone());
2305 debug!("!!! (resolving module in lexical scope) module
2306 wasn't actually a module!");
2307 return Failed(None);
2312 debug!("(resolving module in lexical scope) indeterminate; \
2314 return Indeterminate;
2317 debug!("(resolving module in lexical scope) failed to resolve");
2323 /// Returns the nearest normal module parent of the given module.
2324 fn get_nearest_normal_module_parent(&mut self, module_: Rc<Module>)
2325 -> Option<Rc<Module>> {
2326 let mut module_ = module_;
2328 match module_.parent_link.clone() {
2329 NoParentLink => return None,
2330 ModuleParentLink(new_module, _) |
2331 BlockParentLink(new_module, _) => {
2332 let new_module = new_module.upgrade().unwrap();
2333 match new_module.kind.get() {
2334 NormalModuleKind => return Some(new_module),
2338 AnonymousModuleKind => module_ = new_module,
2345 /// Returns the nearest normal module parent of the given module, or the
2346 /// module itself if it is a normal module.
2347 fn get_nearest_normal_module_parent_or_self(&mut self, module_: Rc<Module>)
2349 match module_.kind.get() {
2350 NormalModuleKind => return module_,
2354 AnonymousModuleKind => {
2355 match self.get_nearest_normal_module_parent(module_.clone()) {
2357 Some(new_module) => new_module
2363 /// Resolves a "module prefix". A module prefix is one or both of (a) `self::`;
2364 /// (b) some chain of `super::`.
2365 /// grammar: (SELF MOD_SEP ) ? (SUPER MOD_SEP) *
2366 fn resolve_module_prefix(&mut self,
2367 module_: Rc<Module>,
2368 module_path: &[Name])
2369 -> ResolveResult<ModulePrefixResult> {
2370 // Start at the current module if we see `self` or `super`, or at the
2371 // top of the crate otherwise.
2372 let mut containing_module;
2374 let first_module_path_string = token::get_name(module_path[0]);
2375 if "self" == first_module_path_string.get() {
2377 self.get_nearest_normal_module_parent_or_self(module_);
2379 } else if "super" == first_module_path_string.get() {
2381 self.get_nearest_normal_module_parent_or_self(module_);
2382 i = 0; // We'll handle `super` below.
2384 return Success(NoPrefixFound);
2387 // Now loop through all the `super`s we find.
2388 while i < module_path.len() {
2389 let string = token::get_name(module_path[i]);
2390 if "super" != string.get() {
2393 debug!("(resolving module prefix) resolving `super` at {}",
2394 self.module_to_string(&*containing_module));
2395 match self.get_nearest_normal_module_parent(containing_module) {
2396 None => return Failed(None),
2397 Some(new_module) => {
2398 containing_module = new_module;
2404 debug!("(resolving module prefix) finished resolving prefix at {}",
2405 self.module_to_string(&*containing_module));
2407 return Success(PrefixFound(containing_module, i));
2410 /// Attempts to resolve the supplied name in the given module for the
2411 /// given namespace. If successful, returns the target corresponding to
2414 /// The boolean returned on success is an indicator of whether this lookup
2415 /// passed through a public re-export proxy.
2416 fn resolve_name_in_module(&mut self,
2417 module_: Rc<Module>,
2419 namespace: Namespace,
2420 name_search_type: NameSearchType,
2421 allow_private_imports: bool)
2422 -> ResolveResult<(Target, bool)> {
2423 debug!("(resolving name in module) resolving `{}` in `{}`",
2424 token::get_name(name).get(),
2425 self.module_to_string(&*module_));
2427 // First, check the direct children of the module.
2428 build_reduced_graph::populate_module_if_necessary(self, &module_);
2430 match module_.children.borrow().get(&name) {
2432 if name_bindings.defined_in_namespace(namespace) => {
2433 debug!("(resolving name in module) found node as child");
2434 return Success((Target::new(module_.clone(),
2435 name_bindings.clone(),
2444 // Next, check the module's imports if necessary.
2446 // If this is a search of all imports, we should be done with glob
2447 // resolution at this point.
2448 if name_search_type == PathSearch {
2449 assert_eq!(module_.glob_count.get(), 0);
2452 // Check the list of resolved imports.
2453 match module_.import_resolutions.borrow().get(&name) {
2454 Some(import_resolution) if allow_private_imports ||
2455 import_resolution.is_public => {
2457 if import_resolution.is_public &&
2458 import_resolution.outstanding_references != 0 {
2459 debug!("(resolving name in module) import \
2460 unresolved; bailing out");
2461 return Indeterminate;
2463 match import_resolution.target_for_namespace(namespace) {
2465 debug!("(resolving name in module) name found, \
2466 but not in namespace {:?}",
2470 debug!("(resolving name in module) resolved to \
2472 // track used imports and extern crates as well
2473 let id = import_resolution.id(namespace);
2474 self.used_imports.insert((id, namespace));
2475 self.record_import_use(id, name);
2476 if let Some(DefId{krate: kid, ..}) = target.target_module.def_id.get() {
2477 self.used_crates.insert(kid);
2479 return Success((target, true));
2483 Some(..) | None => {} // Continue.
2486 // Finally, search through external children.
2487 if namespace == TypeNS {
2488 if let Some(module) = module_.external_module_children.borrow().get(&name).cloned() {
2490 Rc::new(Resolver::create_name_bindings_from_module(module));
2491 return Success((Target::new(module_,
2498 // We're out of luck.
2499 debug!("(resolving name in module) failed to resolve `{}`",
2500 token::get_name(name).get());
2501 return Failed(None);
2504 fn report_unresolved_imports(&mut self, module_: Rc<Module>) {
2505 let index = module_.resolved_import_count.get();
2506 let imports = module_.imports.borrow();
2507 let import_count = imports.len();
2508 if index != import_count {
2509 let sn = self.session
2511 .span_to_snippet((*imports)[index].span)
2513 if sn.contains("::") {
2514 self.resolve_error((*imports)[index].span,
2515 "unresolved import");
2517 let err = format!("unresolved import (maybe you meant `{}::*`?)",
2519 self.resolve_error((*imports)[index].span, &err[]);
2523 // Descend into children and anonymous children.
2524 build_reduced_graph::populate_module_if_necessary(self, &module_);
2526 for (_, child_node) in module_.children.borrow().iter() {
2527 match child_node.get_module_if_available() {
2531 Some(child_module) => {
2532 self.report_unresolved_imports(child_module);
2537 for (_, module_) in module_.anonymous_children.borrow().iter() {
2538 self.report_unresolved_imports(module_.clone());
2544 // We maintain a list of value ribs and type ribs.
2546 // Simultaneously, we keep track of the current position in the module
2547 // graph in the `current_module` pointer. When we go to resolve a name in
2548 // the value or type namespaces, we first look through all the ribs and
2549 // then query the module graph. When we resolve a name in the module
2550 // namespace, we can skip all the ribs (since nested modules are not
2551 // allowed within blocks in Rust) and jump straight to the current module
2554 // Named implementations are handled separately. When we find a method
2555 // call, we consult the module node to find all of the implementations in
2556 // scope. This information is lazily cached in the module node. We then
2557 // generate a fake "implementation scope" containing all the
2558 // implementations thus found, for compatibility with old resolve pass.
2560 fn with_scope<F>(&mut self, name: Option<Name>, f: F) where
2561 F: FnOnce(&mut Resolver),
2563 let orig_module = self.current_module.clone();
2565 // Move down in the graph.
2571 build_reduced_graph::populate_module_if_necessary(self, &orig_module);
2573 match orig_module.children.borrow().get(&name) {
2575 debug!("!!! (with scope) didn't find `{}` in `{}`",
2576 token::get_name(name),
2577 self.module_to_string(&*orig_module));
2579 Some(name_bindings) => {
2580 match (*name_bindings).get_module_if_available() {
2582 debug!("!!! (with scope) didn't find module \
2584 token::get_name(name),
2585 self.module_to_string(&*orig_module));
2588 self.current_module = module_;
2598 self.current_module = orig_module;
2601 /// Wraps the given definition in the appropriate number of `DefUpvar`
2607 -> Option<DefLike> {
2609 DlDef(d @ DefUpvar(..)) => {
2610 self.session.span_bug(span,
2611 &format!("unexpected {:?} in bindings", d)[])
2613 DlDef(d @ DefLocal(_)) => {
2614 let node_id = d.def_id().node;
2616 let mut last_proc_body_id = ast::DUMMY_NODE_ID;
2617 for rib in ribs.iter() {
2620 // Nothing to do. Continue.
2622 ClosureRibKind(function_id, maybe_proc_body) => {
2624 if maybe_proc_body != ast::DUMMY_NODE_ID {
2625 last_proc_body_id = maybe_proc_body;
2627 def = DefUpvar(node_id, function_id, last_proc_body_id);
2629 let mut seen = self.freevars_seen.borrow_mut();
2630 let seen = match seen.entry(function_id) {
2631 Occupied(v) => v.into_mut(),
2632 Vacant(v) => v.insert(NodeSet::new()),
2634 if seen.contains(&node_id) {
2637 match self.freevars.borrow_mut().entry(function_id) {
2638 Occupied(v) => v.into_mut(),
2639 Vacant(v) => v.insert(vec![]),
2640 }.push(Freevar { def: prev_def, span: span });
2641 seen.insert(node_id);
2643 MethodRibKind(item_id, _) => {
2644 // If the def is a ty param, and came from the parent
2647 DefTyParam(_, _, did, _) if {
2648 self.def_map.borrow().get(&did.node).cloned()
2649 == Some(DefTyParamBinder(item_id))
2651 DefSelfTy(did) if did == item_id => {} // ok
2653 // This was an attempt to access an upvar inside a
2654 // named function item. This is not allowed, so we
2659 "can't capture dynamic environment in a fn item; \
2660 use the || { ... } closure form instead");
2667 // This was an attempt to access an upvar inside a
2668 // named function item. This is not allowed, so we
2673 "can't capture dynamic environment in a fn item; \
2674 use the || { ... } closure form instead");
2678 ConstantItemRibKind => {
2679 // Still doesn't deal with upvars
2680 self.resolve_error(span,
2681 "attempt to use a non-constant \
2682 value in a constant");
2689 DlDef(def @ DefTyParam(..)) |
2690 DlDef(def @ DefSelfTy(..)) => {
2691 for rib in ribs.iter() {
2693 NormalRibKind | ClosureRibKind(..) => {
2694 // Nothing to do. Continue.
2696 MethodRibKind(item_id, _) => {
2697 // If the def is a ty param, and came from the parent
2700 DefTyParam(_, _, did, _) if {
2701 self.def_map.borrow().get(&did.node).cloned()
2702 == Some(DefTyParamBinder(item_id))
2704 DefSelfTy(did) if did == item_id => {} // ok
2707 // This was an attempt to use a type parameter outside
2710 self.resolve_error(span,
2711 "can't use type parameters from \
2712 outer function; try using a local \
2713 type parameter instead");
2720 // This was an attempt to use a type parameter outside
2723 self.resolve_error(span,
2724 "can't use type parameters from \
2725 outer function; try using a local \
2726 type parameter instead");
2730 ConstantItemRibKind => {
2732 self.resolve_error(span,
2733 "cannot use an outer type \
2734 parameter in this context");
2745 /// Searches the current set of local scopes and
2746 /// applies translations for closures.
2747 fn search_ribs(&self,
2751 -> Option<DefLike> {
2752 // FIXME #4950: Try caching?
2754 for (i, rib) in ribs.iter().enumerate().rev() {
2755 match rib.bindings.get(&name).cloned() {
2757 return self.upvarify(&ribs[(i + 1)..], def_like, span);
2768 /// Searches the current set of local scopes for labels.
2769 /// Stops after meeting a closure.
2770 fn search_label(&self, name: Name) -> Option<DefLike> {
2771 for rib in self.label_ribs.iter().rev() {
2777 // Do not resolve labels across function boundary
2781 let result = rib.bindings.get(&name).cloned();
2782 if result.is_some() {
2789 fn resolve_crate(&mut self, krate: &ast::Crate) {
2790 debug!("(resolving crate) starting");
2792 visit::walk_crate(self, krate);
2795 fn resolve_item(&mut self, item: &Item) {
2796 let name = item.ident.name;
2798 debug!("(resolving item) resolving {}",
2799 token::get_name(name));
2803 // enum item: resolve all the variants' discrs,
2804 // then resolve the ty params
2805 ItemEnum(ref enum_def, ref generics) => {
2806 for variant in (*enum_def).variants.iter() {
2807 for dis_expr in variant.node.disr_expr.iter() {
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.with_type_parameter_rib(HasTypeParameters(generics,
2836 this.resolve_type_parameters(&generics.ty_params);
2837 visit::walk_item(this, item);
2843 ref implemented_traits,
2845 ref impl_items) => {
2846 self.resolve_implementation(item.id,
2853 ItemTrait(_, ref generics, ref bounds, ref trait_items) => {
2854 // Create a new rib for the self type.
2855 let mut self_type_rib = Rib::new(ItemRibKind);
2857 // plain insert (no renaming, types are not currently hygienic....)
2858 let name = self.type_self_name;
2859 self_type_rib.bindings.insert(name, DlDef(DefSelfTy(item.id)));
2860 self.type_ribs.push(self_type_rib);
2862 // Create a new rib for the trait-wide type parameters.
2863 self.with_type_parameter_rib(HasTypeParameters(generics,
2868 this.resolve_type_parameters(&generics.ty_params);
2869 this.resolve_where_clause(&generics.where_clause);
2871 this.resolve_type_parameter_bounds(item.id, bounds,
2874 for trait_item in (*trait_items).iter() {
2875 // Create a new rib for the trait_item-specific type
2878 // FIXME #4951: Do we need a node ID here?
2881 ast::RequiredMethod(ref ty_m) => {
2882 this.with_type_parameter_rib
2883 (HasTypeParameters(&ty_m.generics,
2886 MethodRibKind(item.id, RequiredMethod)),
2889 // Resolve the method-specific type
2891 this.resolve_type_parameters(
2892 &ty_m.generics.ty_params);
2893 this.resolve_where_clause(&ty_m.generics
2896 for argument in ty_m.decl.inputs.iter() {
2897 this.resolve_type(&*argument.ty);
2900 if let SelfExplicit(ref typ, _) = ty_m.explicit_self.node {
2901 this.resolve_type(&**typ)
2904 if let ast::Return(ref ret_ty) = ty_m.decl.output {
2905 this.resolve_type(&**ret_ty);
2909 ast::ProvidedMethod(ref m) => {
2910 this.resolve_method(MethodRibKind(item.id,
2911 ProvidedMethod(m.id)),
2914 ast::TypeTraitItem(ref data) => {
2915 this.resolve_type_parameter(&data.ty_param);
2916 visit::walk_trait_item(this, trait_item);
2922 self.type_ribs.pop();
2925 ItemStruct(ref struct_def, ref generics) => {
2926 self.resolve_struct(item.id,
2928 &struct_def.fields[]);
2931 ItemMod(ref module_) => {
2932 self.with_scope(Some(name), |this| {
2933 this.resolve_module(module_, item.span, name,
2938 ItemForeignMod(ref foreign_module) => {
2939 self.with_scope(Some(name), |this| {
2940 for foreign_item in foreign_module.items.iter() {
2941 match foreign_item.node {
2942 ForeignItemFn(_, ref generics) => {
2943 this.with_type_parameter_rib(
2945 generics, FnSpace, foreign_item.id,
2948 this.resolve_type_parameters(&generics.ty_params);
2949 this.resolve_where_clause(&generics.where_clause);
2950 visit::walk_foreign_item(this, &**foreign_item)
2953 ForeignItemStatic(..) => {
2954 visit::walk_foreign_item(this,
2962 ItemFn(ref fn_decl, _, _, ref generics, ref block) => {
2963 self.resolve_function(ItemRibKind,
2973 ItemConst(..) | ItemStatic(..) => {
2974 self.with_constant_rib(|this| {
2975 visit::walk_item(this, item);
2980 // do nothing, these are just around to be encoded
2985 fn with_type_parameter_rib<F>(&mut self, type_parameters: TypeParameters, f: F) where
2986 F: FnOnce(&mut Resolver),
2988 match type_parameters {
2989 HasTypeParameters(generics, space, node_id, rib_kind) => {
2990 let mut function_type_rib = Rib::new(rib_kind);
2991 let mut seen_bindings = HashSet::new();
2992 for (index, type_parameter) in generics.ty_params.iter().enumerate() {
2993 let name = type_parameter.ident.name;
2994 debug!("with_type_parameter_rib: {} {}", node_id,
2997 if seen_bindings.contains(&name) {
2998 self.resolve_error(type_parameter.span,
2999 &format!("the name `{}` is already \
3001 parameter in this type \
3006 seen_bindings.insert(name);
3008 let def_like = DlDef(DefTyParam(space,
3010 local_def(type_parameter.id),
3012 // Associate this type parameter with
3013 // the item that bound it
3014 self.record_def(type_parameter.id,
3015 (DefTyParamBinder(node_id), LastMod(AllPublic)));
3016 // plain insert (no renaming)
3017 function_type_rib.bindings.insert(name, def_like);
3019 self.type_ribs.push(function_type_rib);
3022 NoTypeParameters => {
3029 match type_parameters {
3030 HasTypeParameters(..) => { self.type_ribs.pop(); }
3031 NoTypeParameters => { }
3035 fn with_label_rib<F>(&mut self, f: F) where
3036 F: FnOnce(&mut Resolver),
3038 self.label_ribs.push(Rib::new(NormalRibKind));
3040 self.label_ribs.pop();
3043 fn with_constant_rib<F>(&mut self, f: F) where
3044 F: FnOnce(&mut Resolver),
3046 self.value_ribs.push(Rib::new(ConstantItemRibKind));
3047 self.type_ribs.push(Rib::new(ConstantItemRibKind));
3049 self.type_ribs.pop();
3050 self.value_ribs.pop();
3053 fn resolve_function(&mut self,
3055 optional_declaration: Option<&FnDecl>,
3056 type_parameters: TypeParameters,
3058 // Create a value rib for the function.
3059 let function_value_rib = Rib::new(rib_kind);
3060 self.value_ribs.push(function_value_rib);
3062 // Create a label rib for the function.
3063 let function_label_rib = Rib::new(rib_kind);
3064 self.label_ribs.push(function_label_rib);
3066 // If this function has type parameters, add them now.
3067 self.with_type_parameter_rib(type_parameters, |this| {
3068 // Resolve the type parameters.
3069 match type_parameters {
3070 NoTypeParameters => {
3073 HasTypeParameters(ref generics, _, _, _) => {
3074 this.resolve_type_parameters(&generics.ty_params);
3075 this.resolve_where_clause(&generics.where_clause);
3079 // Add each argument to the rib.
3080 match optional_declaration {
3084 Some(declaration) => {
3085 let mut bindings_list = HashMap::new();
3086 for argument in declaration.inputs.iter() {
3087 this.resolve_pattern(&*argument.pat,
3088 ArgumentIrrefutableMode,
3089 &mut bindings_list);
3091 this.resolve_type(&*argument.ty);
3093 debug!("(resolving function) recorded argument");
3096 if let ast::Return(ref ret_ty) = declaration.output {
3097 this.resolve_type(&**ret_ty);
3102 // Resolve the function body.
3103 this.resolve_block(&*block);
3105 debug!("(resolving function) leaving function");
3108 self.label_ribs.pop();
3109 self.value_ribs.pop();
3112 fn resolve_type_parameters(&mut self,
3113 type_parameters: &OwnedSlice<TyParam>) {
3114 for type_parameter in type_parameters.iter() {
3115 self.resolve_type_parameter(type_parameter);
3119 fn resolve_type_parameter(&mut self,
3120 type_parameter: &TyParam) {
3121 for bound in type_parameter.bounds.iter() {
3122 self.resolve_type_parameter_bound(type_parameter.id, bound,
3123 TraitBoundingTypeParameter);
3125 match type_parameter.default {
3126 Some(ref ty) => self.resolve_type(&**ty),
3131 fn resolve_type_parameter_bounds(&mut self,
3133 type_parameter_bounds: &OwnedSlice<TyParamBound>,
3134 reference_type: TraitReferenceType) {
3135 for type_parameter_bound in type_parameter_bounds.iter() {
3136 self.resolve_type_parameter_bound(id, type_parameter_bound,
3141 fn resolve_type_parameter_bound(&mut self,
3143 type_parameter_bound: &TyParamBound,
3144 reference_type: TraitReferenceType) {
3145 match *type_parameter_bound {
3146 TraitTyParamBound(ref tref, _) => {
3147 self.resolve_poly_trait_reference(id, tref, reference_type)
3149 RegionTyParamBound(..) => {}
3153 fn resolve_poly_trait_reference(&mut self,
3155 poly_trait_reference: &PolyTraitRef,
3156 reference_type: TraitReferenceType) {
3157 self.resolve_trait_reference(id, &poly_trait_reference.trait_ref, reference_type)
3160 fn resolve_trait_reference(&mut self,
3162 trait_reference: &TraitRef,
3163 reference_type: TraitReferenceType) {
3164 match self.resolve_path(id, &trait_reference.path, TypeNS, true) {
3166 let path_str = self.path_names_to_string(&trait_reference.path);
3167 let usage_str = match reference_type {
3168 TraitBoundingTypeParameter => "bound type parameter with",
3169 TraitImplementation => "implement",
3170 TraitDerivation => "derive",
3171 TraitObject => "reference",
3172 TraitQPath => "extract an associated type from",
3175 let msg = format!("attempt to {} a nonexistent trait `{}`", usage_str, path_str);
3176 self.resolve_error(trait_reference.path.span, &msg[]);
3180 (DefTrait(_), _) => {
3181 debug!("(resolving trait) found trait def: {:?}", def);
3182 self.record_def(trait_reference.ref_id, def);
3185 self.resolve_error(trait_reference.path.span,
3186 &format!("`{}` is not a trait",
3187 self.path_names_to_string(
3188 &trait_reference.path))[]);
3190 // If it's a typedef, give a note
3191 if let DefTy(..) = def {
3192 self.session.span_note(
3193 trait_reference.path.span,
3194 &format!("`type` aliases cannot be used for traits")
3203 fn resolve_where_clause(&mut self, where_clause: &ast::WhereClause) {
3204 for predicate in where_clause.predicates.iter() {
3206 &ast::WherePredicate::BoundPredicate(ref bound_pred) => {
3207 self.resolve_type(&*bound_pred.bounded_ty);
3209 for bound in bound_pred.bounds.iter() {
3210 self.resolve_type_parameter_bound(bound_pred.bounded_ty.id, bound,
3211 TraitBoundingTypeParameter);
3214 &ast::WherePredicate::RegionPredicate(_) => {}
3215 &ast::WherePredicate::EqPredicate(ref eq_pred) => {
3216 match self.resolve_path(eq_pred.id, &eq_pred.path, TypeNS, true) {
3217 Some((def @ DefTyParam(..), last_private)) => {
3218 self.record_def(eq_pred.id, (def, last_private));
3221 self.resolve_error(eq_pred.path.span,
3222 "undeclared associated type");
3226 self.resolve_type(&*eq_pred.ty);
3232 fn resolve_struct(&mut self,
3234 generics: &Generics,
3235 fields: &[StructField]) {
3236 // If applicable, create a rib for the type parameters.
3237 self.with_type_parameter_rib(HasTypeParameters(generics,
3242 // Resolve the type parameters.
3243 this.resolve_type_parameters(&generics.ty_params);
3244 this.resolve_where_clause(&generics.where_clause);
3247 for field in fields.iter() {
3248 this.resolve_type(&*field.node.ty);
3253 // Does this really need to take a RibKind or is it always going
3254 // to be NormalRibKind?
3255 fn resolve_method(&mut self,
3257 method: &ast::Method) {
3258 let method_generics = method.pe_generics();
3259 let type_parameters = HasTypeParameters(method_generics,
3264 if let SelfExplicit(ref typ, _) = method.pe_explicit_self().node {
3265 self.resolve_type(&**typ);
3268 self.resolve_function(rib_kind,
3269 Some(method.pe_fn_decl()),
3274 fn with_current_self_type<T, F>(&mut self, self_type: &Ty, f: F) -> T where
3275 F: FnOnce(&mut Resolver) -> T,
3277 // Handle nested impls (inside fn bodies)
3278 let previous_value = replace(&mut self.current_self_type, Some(self_type.clone()));
3279 let result = f(self);
3280 self.current_self_type = previous_value;
3284 fn with_optional_trait_ref<T, F>(&mut self, id: NodeId,
3285 opt_trait_ref: &Option<TraitRef>,
3287 F: FnOnce(&mut Resolver) -> T,
3289 let new_val = match *opt_trait_ref {
3290 Some(ref trait_ref) => {
3291 self.resolve_trait_reference(id, trait_ref, TraitImplementation);
3293 match self.def_map.borrow().get(&trait_ref.ref_id) {
3295 let did = def.def_id();
3296 Some((did, trait_ref.clone()))
3303 let original_trait_ref = replace(&mut self.current_trait_ref, new_val);
3304 let result = f(self);
3305 self.current_trait_ref = original_trait_ref;
3309 fn resolve_implementation(&mut self,
3311 generics: &Generics,
3312 opt_trait_reference: &Option<TraitRef>,
3314 impl_items: &[ImplItem]) {
3315 // If applicable, create a rib for the type parameters.
3316 self.with_type_parameter_rib(HasTypeParameters(generics,
3321 // Resolve the type parameters.
3322 this.resolve_type_parameters(&generics.ty_params);
3323 this.resolve_where_clause(&generics.where_clause);
3325 // Resolve the trait reference, if necessary.
3326 this.with_optional_trait_ref(id, opt_trait_reference, |this| {
3327 // Resolve the self type.
3328 this.resolve_type(self_type);
3330 this.with_current_self_type(self_type, |this| {
3331 for impl_item in impl_items.iter() {
3333 MethodImplItem(ref method) => {
3334 // If this is a trait impl, ensure the method
3336 this.check_trait_item(method.pe_ident().name,
3339 // We also need a new scope for the method-
3340 // specific type parameters.
3341 this.resolve_method(
3342 MethodRibKind(id, ProvidedMethod(method.id)),
3345 TypeImplItem(ref typedef) => {
3346 // If this is a trait impl, ensure the method
3348 this.check_trait_item(typedef.ident.name,
3351 this.resolve_type(&*typedef.typ);
3359 // Check that the current type is indeed a type, if we have an anonymous impl
3360 if opt_trait_reference.is_none() {
3361 match self_type.node {
3362 // TyPath is the only thing that we handled in `build_reduced_graph_for_item`,
3363 // where we created a module with the name of the type in order to implement
3364 // an anonymous trait. In the case that the path does not resolve to an actual
3365 // type, the result will be that the type name resolves to a module but not
3366 // a type (shadowing any imported modules or types with this name), leading
3367 // to weird user-visible bugs. So we ward this off here. See #15060.
3368 TyPath(ref path, path_id) => {
3369 match self.def_map.borrow().get(&path_id) {
3370 // FIXME: should we catch other options and give more precise errors?
3371 Some(&DefMod(_)) => {
3372 self.resolve_error(path.span, "inherent implementations are not \
3373 allowed for types not defined in \
3374 the current module");
3384 fn check_trait_item(&self, name: Name, span: Span) {
3385 // If there is a TraitRef in scope for an impl, then the method must be in the trait.
3386 for &(did, ref trait_ref) in self.current_trait_ref.iter() {
3387 if self.trait_item_map.get(&(name, did)).is_none() {
3388 let path_str = self.path_names_to_string(&trait_ref.path);
3389 self.resolve_error(span,
3390 &format!("method `{}` is not a member of trait `{}`",
3391 token::get_name(name),
3397 fn resolve_module(&mut self, module: &Mod, _span: Span,
3398 _name: Name, id: NodeId) {
3399 // Write the implementations in scope into the module metadata.
3400 debug!("(resolving module) resolving module ID {}", id);
3401 visit::walk_mod(self, module);
3404 fn resolve_local(&mut self, local: &Local) {
3405 // Resolve the type.
3406 if let Some(ref ty) = local.ty {
3407 self.resolve_type(&**ty);
3410 // Resolve the initializer, if necessary.
3415 Some(ref initializer) => {
3416 self.resolve_expr(&**initializer);
3420 // Resolve the pattern.
3421 let mut bindings_list = HashMap::new();
3422 self.resolve_pattern(&*local.pat,
3423 LocalIrrefutableMode,
3424 &mut bindings_list);
3427 // build a map from pattern identifiers to binding-info's.
3428 // this is done hygienically. This could arise for a macro
3429 // that expands into an or-pattern where one 'x' was from the
3430 // user and one 'x' came from the macro.
3431 fn binding_mode_map(&mut self, pat: &Pat) -> BindingMap {
3432 let mut result = HashMap::new();
3433 pat_bindings(&self.def_map, pat, |binding_mode, _id, sp, path1| {
3434 let name = mtwt::resolve(path1.node);
3435 result.insert(name, BindingInfo {
3437 binding_mode: binding_mode
3443 // check that all of the arms in an or-pattern have exactly the
3444 // same set of bindings, with the same binding modes for each.
3445 fn check_consistent_bindings(&mut self, arm: &Arm) {
3446 if arm.pats.len() == 0 {
3449 let map_0 = self.binding_mode_map(&*arm.pats[0]);
3450 for (i, p) in arm.pats.iter().enumerate() {
3451 let map_i = self.binding_mode_map(&**p);
3453 for (&key, &binding_0) in map_0.iter() {
3454 match map_i.get(&key) {
3458 &format!("variable `{}` from pattern #1 is \
3459 not bound in pattern #{}",
3460 token::get_name(key),
3463 Some(binding_i) => {
3464 if binding_0.binding_mode != binding_i.binding_mode {
3467 &format!("variable `{}` is bound with different \
3468 mode in pattern #{} than in pattern #1",
3469 token::get_name(key),
3476 for (&key, &binding) in map_i.iter() {
3477 if !map_0.contains_key(&key) {
3480 &format!("variable `{}` from pattern {}{} is \
3481 not bound in pattern {}1",
3482 token::get_name(key),
3483 "#", i + 1, "#")[]);
3489 fn resolve_arm(&mut self, arm: &Arm) {
3490 self.value_ribs.push(Rib::new(NormalRibKind));
3492 let mut bindings_list = HashMap::new();
3493 for pattern in arm.pats.iter() {
3494 self.resolve_pattern(&**pattern, RefutableMode, &mut bindings_list);
3497 // This has to happen *after* we determine which
3498 // pat_idents are variants
3499 self.check_consistent_bindings(arm);
3501 visit::walk_expr_opt(self, &arm.guard);
3502 self.resolve_expr(&*arm.body);
3504 self.value_ribs.pop();
3507 fn resolve_block(&mut self, block: &Block) {
3508 debug!("(resolving block) entering block");
3509 self.value_ribs.push(Rib::new(NormalRibKind));
3511 // Move down in the graph, if there's an anonymous module rooted here.
3512 let orig_module = self.current_module.clone();
3513 match orig_module.anonymous_children.borrow().get(&block.id) {
3514 None => { /* Nothing to do. */ }
3515 Some(anonymous_module) => {
3516 debug!("(resolving block) found anonymous module, moving \
3518 self.current_module = anonymous_module.clone();
3522 // Descend into the block.
3523 visit::walk_block(self, block);
3526 self.current_module = orig_module;
3528 self.value_ribs.pop();
3529 debug!("(resolving block) leaving block");
3532 fn resolve_type(&mut self, ty: &Ty) {
3534 // Like path expressions, the interpretation of path types depends
3535 // on whether the path has multiple elements in it or not.
3537 TyPath(ref path, path_id) => {
3538 // This is a path in the type namespace. Walk through scopes
3540 let mut result_def = None;
3542 // First, check to see whether the name is a primitive type.
3543 if path.segments.len() == 1 {
3544 let id = path.segments.last().unwrap().identifier;
3546 match self.primitive_type_table
3550 Some(&primitive_type) => {
3552 Some((DefPrimTy(primitive_type), LastMod(AllPublic)));
3554 if path.segments[0].parameters.has_lifetimes() {
3555 span_err!(self.session, path.span, E0157,
3556 "lifetime parameters are not allowed on this type");
3557 } else if !path.segments[0].parameters.is_empty() {
3558 span_err!(self.session, path.span, E0153,
3559 "type parameters are not allowed on this type");
3570 match self.resolve_path(ty.id, path, TypeNS, true) {
3572 debug!("(resolving type) resolved `{:?}` to \
3574 token::get_ident(path.segments.last().unwrap() .identifier),
3576 result_def = Some(def);
3583 Some(_) => {} // Continue.
3588 // Write the result into the def map.
3589 debug!("(resolving type) writing resolution for `{}` \
3591 self.path_names_to_string(path),
3593 self.record_def(path_id, def);
3596 let msg = format!("use of undeclared type name `{}`",
3597 self.path_names_to_string(path));
3598 self.resolve_error(ty.span, &msg[]);
3603 TyObjectSum(ref ty, ref bound_vec) => {
3604 self.resolve_type(&**ty);
3605 self.resolve_type_parameter_bounds(ty.id, bound_vec,
3606 TraitBoundingTypeParameter);
3609 TyQPath(ref qpath) => {
3610 self.resolve_type(&*qpath.self_type);
3611 self.resolve_trait_reference(ty.id, &*qpath.trait_ref, TraitQPath);
3614 TyPolyTraitRef(ref bounds) => {
3615 self.resolve_type_parameter_bounds(
3619 visit::walk_ty(self, ty);
3622 // Just resolve embedded types.
3623 visit::walk_ty(self, ty);
3628 fn resolve_pattern(&mut self,
3630 mode: PatternBindingMode,
3631 // Maps idents to the node ID for the (outermost)
3632 // pattern that binds them
3633 bindings_list: &mut HashMap<Name, NodeId>) {
3634 let pat_id = pattern.id;
3635 walk_pat(pattern, |pattern| {
3636 match pattern.node {
3637 PatIdent(binding_mode, ref path1, _) => {
3639 // The meaning of pat_ident with no type parameters
3640 // depends on whether an enum variant or unit-like struct
3641 // with that name is in scope. The probing lookup has to
3642 // be careful not to emit spurious errors. Only matching
3643 // patterns (match) can match nullary variants or
3644 // unit-like structs. For binding patterns (let), matching
3645 // such a value is simply disallowed (since it's rarely
3648 let ident = path1.node;
3649 let renamed = mtwt::resolve(ident);
3651 match self.resolve_bare_identifier_pattern(ident.name, pattern.span) {
3652 FoundStructOrEnumVariant(ref def, lp)
3653 if mode == RefutableMode => {
3654 debug!("(resolving pattern) resolving `{}` to \
3655 struct or enum variant",
3656 token::get_name(renamed));
3658 self.enforce_default_binding_mode(
3662 self.record_def(pattern.id, (def.clone(), lp));
3664 FoundStructOrEnumVariant(..) => {
3667 &format!("declaration of `{}` shadows an enum \
3668 variant or unit-like struct in \
3670 token::get_name(renamed))[]);
3672 FoundConst(ref def, lp) if mode == RefutableMode => {
3673 debug!("(resolving pattern) resolving `{}` to \
3675 token::get_name(renamed));
3677 self.enforce_default_binding_mode(
3681 self.record_def(pattern.id, (def.clone(), lp));
3684 self.resolve_error(pattern.span,
3685 "only irrefutable patterns \
3688 BareIdentifierPatternUnresolved => {
3689 debug!("(resolving pattern) binding `{}`",
3690 token::get_name(renamed));
3692 let def = DefLocal(pattern.id);
3694 // Record the definition so that later passes
3695 // will be able to distinguish variants from
3696 // locals in patterns.
3698 self.record_def(pattern.id, (def, LastMod(AllPublic)));
3700 // Add the binding to the local ribs, if it
3701 // doesn't already exist in the bindings list. (We
3702 // must not add it if it's in the bindings list
3703 // because that breaks the assumptions later
3704 // passes make about or-patterns.)
3705 if !bindings_list.contains_key(&renamed) {
3706 let this = &mut *self;
3707 let last_rib = this.value_ribs.last_mut().unwrap();
3708 last_rib.bindings.insert(renamed, DlDef(def));
3709 bindings_list.insert(renamed, pat_id);
3710 } else if mode == ArgumentIrrefutableMode &&
3711 bindings_list.contains_key(&renamed) {
3712 // Forbid duplicate bindings in the same
3714 self.resolve_error(pattern.span,
3715 &format!("identifier `{}` \
3723 } else if bindings_list.get(&renamed) ==
3725 // Then this is a duplicate variable in the
3726 // same disjunction, which is an error.
3727 self.resolve_error(pattern.span,
3728 &format!("identifier `{}` is bound \
3729 more than once in the same \
3731 token::get_ident(ident))[]);
3733 // Else, not bound in the same pattern: do
3739 PatEnum(ref path, _) => {
3740 // This must be an enum variant, struct or const.
3741 match self.resolve_path(pat_id, path, ValueNS, false) {
3742 Some(def @ (DefVariant(..), _)) |
3743 Some(def @ (DefStruct(..), _)) |
3744 Some(def @ (DefConst(..), _)) => {
3745 self.record_def(pattern.id, def);
3747 Some((DefStatic(..), _)) => {
3748 self.resolve_error(path.span,
3749 "static variables cannot be \
3750 referenced in a pattern, \
3751 use a `const` instead");
3754 self.resolve_error(path.span,
3755 format!("`{}` is not an enum variant, struct or const",
3757 path.segments.last().unwrap().identifier)).as_slice());
3760 self.resolve_error(path.span,
3761 format!("unresolved enum variant, struct or const `{}`",
3763 path.segments.last().unwrap().identifier)).as_slice());
3767 // Check the types in the path pattern.
3768 for ty in path.segments
3770 .flat_map(|s| s.parameters.types().into_iter()) {
3771 self.resolve_type(&**ty);
3775 PatLit(ref expr) => {
3776 self.resolve_expr(&**expr);
3779 PatRange(ref first_expr, ref last_expr) => {
3780 self.resolve_expr(&**first_expr);
3781 self.resolve_expr(&**last_expr);
3784 PatStruct(ref path, _, _) => {
3785 match self.resolve_path(pat_id, path, TypeNS, false) {
3786 Some(definition) => {
3787 self.record_def(pattern.id, definition);
3790 debug!("(resolving pattern) didn't find struct \
3791 def: {:?}", result);
3792 let msg = format!("`{}` does not name a structure",
3793 self.path_names_to_string(path));
3794 self.resolve_error(path.span, &msg[]);
3807 fn resolve_bare_identifier_pattern(&mut self, name: Name, span: Span)
3808 -> BareIdentifierPatternResolution {
3809 let module = self.current_module.clone();
3810 match self.resolve_item_in_lexical_scope(module,
3813 Success((target, _)) => {
3814 debug!("(resolve bare identifier pattern) succeeded in \
3815 finding {} at {:?}",
3816 token::get_name(name),
3817 target.bindings.value_def.borrow());
3818 match *target.bindings.value_def.borrow() {
3820 panic!("resolved name in the value namespace to a \
3821 set of name bindings with no def?!");
3824 // For the two success cases, this lookup can be
3825 // considered as not having a private component because
3826 // the lookup happened only within the current module.
3828 def @ DefVariant(..) | def @ DefStruct(..) => {
3829 return FoundStructOrEnumVariant(def, LastMod(AllPublic));
3831 def @ DefConst(..) => {
3832 return FoundConst(def, LastMod(AllPublic));
3835 self.resolve_error(span,
3836 "static variables cannot be \
3837 referenced in a pattern, \
3838 use a `const` instead");
3839 return BareIdentifierPatternUnresolved;
3842 return BareIdentifierPatternUnresolved;
3850 panic!("unexpected indeterminate result");
3854 Some((span, msg)) => {
3855 self.resolve_error(span, &format!("failed to resolve: {}",
3861 debug!("(resolve bare identifier pattern) failed to find {}",
3862 token::get_name(name));
3863 return BareIdentifierPatternUnresolved;
3868 /// If `check_ribs` is true, checks the local definitions first; i.e.
3869 /// doesn't skip straight to the containing module.
3870 fn resolve_path(&mut self,
3873 namespace: Namespace,
3874 check_ribs: bool) -> Option<(Def, LastPrivate)> {
3875 // First, resolve the types and associated type bindings.
3876 for ty in path.segments.iter().flat_map(|s| s.parameters.types().into_iter()) {
3877 self.resolve_type(&**ty);
3879 for binding in path.segments.iter().flat_map(|s| s.parameters.bindings().into_iter()) {
3880 self.resolve_type(&*binding.ty);
3883 // A special case for sugared associated type paths `T::A` where `T` is
3884 // a type parameter and `A` is an associated type on some bound of `T`.
3885 if namespace == TypeNS && path.segments.len() == 2 {
3886 match self.resolve_identifier(path.segments[0].identifier,
3890 Some((def, last_private)) => {
3892 DefTyParam(_, _, did, _) => {
3893 let def = DefAssociatedPath(TyParamProvenance::FromParam(did),
3894 path.segments.last()
3895 .unwrap().identifier);
3896 return Some((def, last_private));
3899 let def = DefAssociatedPath(TyParamProvenance::FromSelf(local_def(nid)),
3900 path.segments.last()
3901 .unwrap().identifier);
3902 return Some((def, last_private));
3912 return self.resolve_crate_relative_path(path, namespace);
3915 // Try to find a path to an item in a module.
3916 let unqualified_def =
3917 self.resolve_identifier(path.segments.last().unwrap().identifier,
3922 if path.segments.len() > 1 {
3923 let def = self.resolve_module_relative_path(path, namespace);
3924 match (def, unqualified_def) {
3925 (Some((ref d, _)), Some((ref ud, _))) if *d == *ud => {
3927 .add_lint(lint::builtin::UNUSED_QUALIFICATIONS,
3930 "unnecessary qualification".to_string());
3938 return unqualified_def;
3941 // resolve a single identifier (used as a varref)
3942 fn resolve_identifier(&mut self,
3944 namespace: Namespace,
3947 -> Option<(Def, LastPrivate)> {
3949 match self.resolve_identifier_in_local_ribs(identifier,
3953 return Some((def, LastMod(AllPublic)));
3961 return self.resolve_item_by_name_in_lexical_scope(identifier.name, namespace);
3964 // FIXME #4952: Merge me with resolve_name_in_module?
3965 fn resolve_definition_of_name_in_module(&mut self,
3966 containing_module: Rc<Module>,
3968 namespace: Namespace)
3970 // First, search children.
3971 build_reduced_graph::populate_module_if_necessary(self, &containing_module);
3973 match containing_module.children.borrow().get(&name) {
3974 Some(child_name_bindings) => {
3975 match child_name_bindings.def_for_namespace(namespace) {
3977 // Found it. Stop the search here.
3978 let p = child_name_bindings.defined_in_public_namespace(
3980 let lp = if p {LastMod(AllPublic)} else {
3981 LastMod(DependsOn(def.def_id()))
3983 return ChildNameDefinition(def, lp);
3991 // Next, search import resolutions.
3992 match containing_module.import_resolutions.borrow().get(&name) {
3993 Some(import_resolution) if import_resolution.is_public => {
3994 if let Some(target) = (*import_resolution).target_for_namespace(namespace) {
3995 match target.bindings.def_for_namespace(namespace) {
3998 let id = import_resolution.id(namespace);
3999 // track imports and extern crates as well
4000 self.used_imports.insert((id, namespace));
4001 self.record_import_use(id, name);
4002 match target.target_module.def_id.get() {
4003 Some(DefId{krate: kid, ..}) => {
4004 self.used_crates.insert(kid);
4008 return ImportNameDefinition(def, LastMod(AllPublic));
4011 // This can happen with external impls, due to
4012 // the imperfect way we read the metadata.
4017 Some(..) | None => {} // Continue.
4020 // Finally, search through external children.
4021 if namespace == TypeNS {
4022 if let Some(module) = containing_module.external_module_children.borrow()
4023 .get(&name).cloned() {
4024 if let Some(def_id) = module.def_id.get() {
4025 // track used crates
4026 self.used_crates.insert(def_id.krate);
4027 let lp = if module.is_public {LastMod(AllPublic)} else {
4028 LastMod(DependsOn(def_id))
4030 return ChildNameDefinition(DefMod(def_id), lp);
4035 return NoNameDefinition;
4038 // resolve a "module-relative" path, e.g. a::b::c
4039 fn resolve_module_relative_path(&mut self,
4041 namespace: Namespace)
4042 -> Option<(Def, LastPrivate)> {
4043 let module_path = path.segments.init().iter()
4044 .map(|ps| ps.identifier.name)
4045 .collect::<Vec<_>>();
4047 let containing_module;
4049 let module = self.current_module.clone();
4050 match self.resolve_module_path(module,
4056 let (span, msg) = match err {
4057 Some((span, msg)) => (span, msg),
4059 let msg = format!("Use of undeclared type or module `{}`",
4060 self.names_to_string(module_path.as_slice()));
4065 self.resolve_error(span, &format!("failed to resolve. {}",
4069 Indeterminate => panic!("indeterminate unexpected"),
4070 Success((resulting_module, resulting_last_private)) => {
4071 containing_module = resulting_module;
4072 last_private = resulting_last_private;
4076 let name = path.segments.last().unwrap().identifier.name;
4077 let def = match self.resolve_definition_of_name_in_module(containing_module.clone(),
4080 NoNameDefinition => {
4081 // We failed to resolve the name. Report an error.
4084 ChildNameDefinition(def, lp) | ImportNameDefinition(def, lp) => {
4085 (def, last_private.or(lp))
4088 if let Some(DefId{krate: kid, ..}) = containing_module.def_id.get() {
4089 self.used_crates.insert(kid);
4094 /// Invariant: This must be called only during main resolution, not during
4095 /// import resolution.
4096 fn resolve_crate_relative_path(&mut self,
4098 namespace: Namespace)
4099 -> Option<(Def, LastPrivate)> {
4100 let module_path = path.segments.init().iter()
4101 .map(|ps| ps.identifier.name)
4102 .collect::<Vec<_>>();
4104 let root_module = self.graph_root.get_module();
4106 let containing_module;
4108 match self.resolve_module_path_from_root(root_module,
4113 LastMod(AllPublic)) {
4115 let (span, msg) = match err {
4116 Some((span, msg)) => (span, msg),
4118 let msg = format!("Use of undeclared module `::{}`",
4119 self.names_to_string(&module_path[]));
4124 self.resolve_error(span, &format!("failed to resolve. {}",
4130 panic!("indeterminate unexpected");
4133 Success((resulting_module, resulting_last_private)) => {
4134 containing_module = resulting_module;
4135 last_private = resulting_last_private;
4139 let name = path.segments.last().unwrap().identifier.name;
4140 match self.resolve_definition_of_name_in_module(containing_module,
4143 NoNameDefinition => {
4144 // We failed to resolve the name. Report an error.
4147 ChildNameDefinition(def, lp) | ImportNameDefinition(def, lp) => {
4148 return Some((def, last_private.or(lp)));
4153 fn resolve_identifier_in_local_ribs(&mut self,
4155 namespace: Namespace,
4158 // Check the local set of ribs.
4159 let search_result = match namespace {
4161 let renamed = mtwt::resolve(ident);
4162 self.search_ribs(self.value_ribs.as_slice(), renamed, span)
4165 let name = ident.name;
4166 self.search_ribs(&self.type_ribs[], name, span)
4170 match search_result {
4171 Some(DlDef(def)) => {
4172 debug!("(resolving path in local ribs) resolved `{}` to \
4174 token::get_ident(ident),
4178 Some(DlField) | Some(DlImpl(_)) | None => {
4184 fn resolve_item_by_name_in_lexical_scope(&mut self,
4186 namespace: Namespace)
4187 -> Option<(Def, LastPrivate)> {
4189 let module = self.current_module.clone();
4190 match self.resolve_item_in_lexical_scope(module,
4193 Success((target, _)) => {
4194 match (*target.bindings).def_for_namespace(namespace) {
4196 // This can happen if we were looking for a type and
4197 // found a module instead. Modules don't have defs.
4198 debug!("(resolving item path by identifier in lexical \
4199 scope) failed to resolve {} after success...",
4200 token::get_name(name));
4204 debug!("(resolving item path in lexical scope) \
4205 resolved `{}` to item",
4206 token::get_name(name));
4207 // This lookup is "all public" because it only searched
4208 // for one identifier in the current module (couldn't
4209 // have passed through reexports or anything like that.
4210 return Some((def, LastMod(AllPublic)));
4215 panic!("unexpected indeterminate result");
4219 Some((span, msg)) =>
4220 self.resolve_error(span, &format!("failed to resolve. {}",
4225 debug!("(resolving item path by identifier in lexical scope) \
4226 failed to resolve {}", token::get_name(name));
4232 fn with_no_errors<T, F>(&mut self, f: F) -> T where
4233 F: FnOnce(&mut Resolver) -> T,
4235 self.emit_errors = false;
4237 self.emit_errors = true;
4241 fn resolve_error(&self, span: Span, s: &str) {
4242 if self.emit_errors {
4243 self.session.span_err(span, s);
4247 fn find_fallback_in_self_type(&mut self, name: Name) -> FallbackSuggestion {
4248 fn extract_path_and_node_id(t: &Ty, allow: FallbackChecks)
4249 -> Option<(Path, NodeId, FallbackChecks)> {
4251 TyPath(ref path, node_id) => Some((path.clone(), node_id, allow)),
4252 TyPtr(ref mut_ty) => extract_path_and_node_id(&*mut_ty.ty, OnlyTraitAndStatics),
4253 TyRptr(_, ref mut_ty) => extract_path_and_node_id(&*mut_ty.ty, allow),
4254 // This doesn't handle the remaining `Ty` variants as they are not
4255 // that commonly the self_type, it might be interesting to provide
4256 // support for those in future.
4261 fn get_module(this: &mut Resolver, span: Span, name_path: &[ast::Name])
4262 -> Option<Rc<Module>> {
4263 let root = this.current_module.clone();
4264 let last_name = name_path.last().unwrap();
4266 if name_path.len() == 1 {
4267 match this.primitive_type_table.primitive_types.get(last_name) {
4270 match this.current_module.children.borrow().get(last_name) {
4271 Some(child) => child.get_module_if_available(),
4277 match this.resolve_module_path(root,
4282 Success((module, _)) => Some(module),
4288 let (path, node_id, allowed) = match self.current_self_type {
4289 Some(ref ty) => match extract_path_and_node_id(ty, Everything) {
4291 None => return NoSuggestion,
4293 None => return NoSuggestion,
4296 if allowed == Everything {
4297 // Look for a field with the same name in the current self_type.
4298 match self.def_map.borrow().get(&node_id) {
4299 Some(&DefTy(did, _))
4300 | Some(&DefStruct(did))
4301 | Some(&DefVariant(_, did, _)) => match self.structs.get(&did) {
4304 if fields.iter().any(|&field_name| name == field_name) {
4309 _ => {} // Self type didn't resolve properly
4313 let name_path = path.segments.iter().map(|seg| seg.identifier.name).collect::<Vec<_>>();
4315 // Look for a method in the current self type's impl module.
4316 match get_module(self, path.span, &name_path[]) {
4317 Some(module) => match module.children.borrow().get(&name) {
4319 let p_str = self.path_names_to_string(&path);
4320 match binding.def_for_namespace(ValueNS) {
4321 Some(DefStaticMethod(_, provenance)) => {
4323 FromImpl(_) => return StaticMethod(p_str),
4324 FromTrait(_) => unreachable!()
4327 Some(DefMethod(_, None, _)) if allowed == Everything => return Method,
4328 Some(DefMethod(_, Some(_), _)) => return TraitItem,
4337 // Look for a method in the current trait.
4338 match self.current_trait_ref {
4339 Some((did, ref trait_ref)) => {
4340 let path_str = self.path_names_to_string(&trait_ref.path);
4342 match self.trait_item_map.get(&(name, did)) {
4343 Some(&StaticMethodTraitItemKind) => {
4344 return TraitMethod(path_str)
4346 Some(_) => return TraitItem,
4356 fn find_best_match_for_name(&mut self, name: &str, max_distance: uint)
4358 let this = &mut *self;
4360 let mut maybes: Vec<token::InternedString> = Vec::new();
4361 let mut values: Vec<uint> = Vec::new();
4363 for rib in this.value_ribs.iter().rev() {
4364 for (&k, _) in rib.bindings.iter() {
4365 maybes.push(token::get_name(k));
4366 values.push(uint::MAX);
4370 let mut smallest = 0;
4371 for (i, other) in maybes.iter().enumerate() {
4372 values[i] = lev_distance(name, other.get());
4374 if values[i] <= values[smallest] {
4379 if values.len() > 0 &&
4380 values[smallest] != uint::MAX &&
4381 values[smallest] < name.len() + 2 &&
4382 values[smallest] <= max_distance &&
4383 name != maybes[smallest].get() {
4385 Some(maybes[smallest].get().to_string())
4392 fn resolve_expr(&mut self, expr: &Expr) {
4393 // First, record candidate traits for this expression if it could
4394 // result in the invocation of a method call.
4396 self.record_candidate_traits_for_expr_if_necessary(expr);
4398 // Next, resolve the node.
4400 // The interpretation of paths depends on whether the path has
4401 // multiple elements in it or not.
4403 ExprPath(ref path) => {
4404 // This is a local path in the value namespace. Walk through
4405 // scopes looking for it.
4407 let path_name = self.path_names_to_string(path);
4409 match self.resolve_path(expr.id, path, ValueNS, true) {
4410 // Check if struct variant
4411 Some((DefVariant(_, _, true), _)) => {
4412 self.resolve_error(expr.span,
4413 format!("`{}` is a struct variant name, but \
4415 uses it like a function name",
4416 path_name).as_slice());
4418 self.session.span_help(expr.span,
4419 format!("Did you mean to write: \
4420 `{} {{ /* fields */ }}`?",
4421 path_name).as_slice());
4424 // Write the result into the def map.
4425 debug!("(resolving expr) resolved `{}`",
4428 self.record_def(expr.id, def);
4431 // Be helpful if the name refers to a struct
4432 // (The pattern matching def_tys where the id is in self.structs
4433 // matches on regular structs while excluding tuple- and enum-like
4434 // structs, which wouldn't result in this error.)
4435 match self.with_no_errors(|this|
4436 this.resolve_path(expr.id, path, TypeNS, false)) {
4437 Some((DefTy(struct_id, _), _))
4438 if self.structs.contains_key(&struct_id) => {
4439 self.resolve_error(expr.span,
4440 format!("`{}` is a structure name, but \
4442 uses it like a function name",
4443 path_name).as_slice());
4445 self.session.span_help(expr.span,
4446 format!("Did you mean to write: \
4447 `{} {{ /* fields */ }}`?",
4448 path_name).as_slice());
4452 let mut method_scope = false;
4453 self.value_ribs.iter().rev().all(|rib| {
4454 let res = match *rib {
4455 Rib { bindings: _, kind: MethodRibKind(_, _) } => true,
4456 Rib { bindings: _, kind: ItemRibKind } => false,
4457 _ => return true, // Keep advancing
4461 false // Stop advancing
4464 if method_scope && token::get_name(self.self_name).get()
4468 "`self` is not available \
4469 in a static method. Maybe a \
4470 `self` argument is missing?");
4472 let last_name = path.segments.last().unwrap().identifier.name;
4473 let mut msg = match self.find_fallback_in_self_type(last_name) {
4475 // limit search to 5 to reduce the number
4476 // of stupid suggestions
4477 self.find_best_match_for_name(path_name.as_slice(), 5)
4478 .map_or("".to_string(),
4479 |x| format!("`{}`", x))
4482 format!("`self.{}`", path_name),
4485 format!("to call `self.{}`", path_name),
4486 TraitMethod(path_str)
4487 | StaticMethod(path_str) =>
4488 format!("to call `{}::{}`", path_str, path_name)
4492 msg = format!(". Did you mean {}?", msg)
4497 format!("unresolved name `{}`{}",
4506 visit::walk_expr(self, expr);
4509 ExprClosure(capture_clause, _, ref fn_decl, ref block) => {
4510 self.capture_mode_map.insert(expr.id, capture_clause);
4511 self.resolve_function(ClosureRibKind(expr.id, ast::DUMMY_NODE_ID),
4512 Some(&**fn_decl), NoTypeParameters,
4516 ExprStruct(ref path, _, _) => {
4517 // Resolve the path to the structure it goes to. We don't
4518 // check to ensure that the path is actually a structure; that
4519 // is checked later during typeck.
4520 match self.resolve_path(expr.id, path, TypeNS, false) {
4521 Some(definition) => self.record_def(expr.id, definition),
4523 debug!("(resolving expression) didn't find struct \
4524 def: {:?}", result);
4525 let msg = format!("`{}` does not name a structure",
4526 self.path_names_to_string(path));
4527 self.resolve_error(path.span, &msg[]);
4531 visit::walk_expr(self, expr);
4534 ExprLoop(_, Some(label)) | ExprWhile(_, _, Some(label)) => {
4535 self.with_label_rib(|this| {
4536 let def_like = DlDef(DefLabel(expr.id));
4539 let rib = this.label_ribs.last_mut().unwrap();
4540 let renamed = mtwt::resolve(label);
4541 rib.bindings.insert(renamed, def_like);
4544 visit::walk_expr(this, expr);
4548 ExprForLoop(ref pattern, ref head, ref body, optional_label) => {
4549 self.resolve_expr(&**head);
4551 self.value_ribs.push(Rib::new(NormalRibKind));
4553 self.resolve_pattern(&**pattern,
4554 LocalIrrefutableMode,
4555 &mut HashMap::new());
4557 match optional_label {
4561 .push(Rib::new(NormalRibKind));
4562 let def_like = DlDef(DefLabel(expr.id));
4565 let rib = self.label_ribs.last_mut().unwrap();
4566 let renamed = mtwt::resolve(label);
4567 rib.bindings.insert(renamed, def_like);
4572 self.resolve_block(&**body);
4574 if optional_label.is_some() {
4575 drop(self.label_ribs.pop())
4578 self.value_ribs.pop();
4581 ExprBreak(Some(label)) | ExprAgain(Some(label)) => {
4582 let renamed = mtwt::resolve(label);
4583 match self.search_label(renamed) {
4587 &format!("use of undeclared label `{}`",
4588 token::get_ident(label))[])
4590 Some(DlDef(def @ DefLabel(_))) => {
4591 // Since this def is a label, it is never read.
4592 self.record_def(expr.id, (def, LastMod(AllPublic)))
4595 self.session.span_bug(expr.span,
4596 "label wasn't mapped to a \
4603 visit::walk_expr(self, expr);
4608 fn record_candidate_traits_for_expr_if_necessary(&mut self, expr: &Expr) {
4610 ExprField(_, ident) => {
4611 // FIXME(#6890): Even though you can't treat a method like a
4612 // field, we need to add any trait methods we find that match
4613 // the field name so that we can do some nice error reporting
4614 // later on in typeck.
4615 let traits = self.search_for_traits_containing_method(ident.node.name);
4616 self.trait_map.insert(expr.id, traits);
4618 ExprMethodCall(ident, _, _) => {
4619 debug!("(recording candidate traits for expr) recording \
4622 let traits = self.search_for_traits_containing_method(ident.node.name);
4623 self.trait_map.insert(expr.id, traits);
4631 fn search_for_traits_containing_method(&mut self, name: Name) -> Vec<DefId> {
4632 debug!("(searching for traits containing method) looking for '{}'",
4633 token::get_name(name));
4635 fn add_trait_info(found_traits: &mut Vec<DefId>,
4636 trait_def_id: DefId,
4638 debug!("(adding trait info) found trait {}:{} for method '{}'",
4641 token::get_name(name));
4642 found_traits.push(trait_def_id);
4645 let mut found_traits = Vec::new();
4646 let mut search_module = self.current_module.clone();
4648 // Look for the current trait.
4649 match self.current_trait_ref {
4650 Some((trait_def_id, _)) => {
4651 if self.trait_item_map.contains_key(&(name, trait_def_id)) {
4652 add_trait_info(&mut found_traits, trait_def_id, name);
4655 None => {} // Nothing to do.
4658 // Look for trait children.
4659 build_reduced_graph::populate_module_if_necessary(self, &search_module);
4662 for (_, child_names) in search_module.children.borrow().iter() {
4663 let def = match child_names.def_for_namespace(TypeNS) {
4667 let trait_def_id = match def {
4668 DefTrait(trait_def_id) => trait_def_id,
4671 if self.trait_item_map.contains_key(&(name, trait_def_id)) {
4672 add_trait_info(&mut found_traits, trait_def_id, name);
4677 // Look for imports.
4678 for (_, import) in search_module.import_resolutions.borrow().iter() {
4679 let target = match import.target_for_namespace(TypeNS) {
4681 Some(target) => target,
4683 let did = match target.bindings.def_for_namespace(TypeNS) {
4684 Some(DefTrait(trait_def_id)) => trait_def_id,
4685 Some(..) | None => continue,
4687 if self.trait_item_map.contains_key(&(name, did)) {
4688 add_trait_info(&mut found_traits, did, name);
4689 let id = import.type_id;
4690 self.used_imports.insert((id, TypeNS));
4691 let trait_name = self.get_trait_name(did);
4692 self.record_import_use(id, trait_name);
4693 if let Some(DefId{krate: kid, ..}) = target.target_module.def_id.get() {
4694 self.used_crates.insert(kid);
4699 match search_module.parent_link.clone() {
4700 NoParentLink | ModuleParentLink(..) => break,
4701 BlockParentLink(parent_module, _) => {
4702 search_module = parent_module.upgrade().unwrap();
4710 fn record_def(&mut self, node_id: NodeId, (def, lp): (Def, LastPrivate)) {
4711 debug!("(recording def) recording {:?} for {}, last private {:?}",
4713 assert!(match lp {LastImport{..} => false, _ => true},
4714 "Import should only be used for `use` directives");
4715 self.last_private.insert(node_id, lp);
4717 match self.def_map.borrow_mut().entry(node_id) {
4718 // Resolve appears to "resolve" the same ID multiple
4719 // times, so here is a sanity check it at least comes to
4720 // the same conclusion! - nmatsakis
4721 Occupied(entry) => if def != *entry.get() {
4723 .bug(&format!("node_id {} resolved first to {:?} and \
4729 Vacant(entry) => { entry.insert(def); },
4733 fn enforce_default_binding_mode(&mut self,
4735 pat_binding_mode: BindingMode,
4737 match pat_binding_mode {
4738 BindByValue(_) => {}
4740 self.resolve_error(pat.span,
4741 &format!("cannot use `ref` binding mode \
4751 // Diagnostics are not particularly efficient, because they're rarely
4755 /// A somewhat inefficient routine to obtain the name of a module.
4756 fn module_to_string(&self, module: &Module) -> String {
4757 let mut names = Vec::new();
4759 fn collect_mod(names: &mut Vec<ast::Name>, module: &Module) {
4760 match module.parent_link {
4762 ModuleParentLink(ref module, name) => {
4764 collect_mod(names, &*module.upgrade().unwrap());
4766 BlockParentLink(ref module, _) => {
4767 // danger, shouldn't be ident?
4768 names.push(special_idents::opaque.name);
4769 collect_mod(names, &*module.upgrade().unwrap());
4773 collect_mod(&mut names, module);
4775 if names.len() == 0 {
4776 return "???".to_string();
4778 self.names_to_string(&names.into_iter().rev()
4779 .collect::<Vec<ast::Name>>()[])
4782 #[allow(dead_code)] // useful for debugging
4783 fn dump_module(&mut self, module_: Rc<Module>) {
4784 debug!("Dump of module `{}`:", self.module_to_string(&*module_));
4786 debug!("Children:");
4787 build_reduced_graph::populate_module_if_necessary(self, &module_);
4788 for (&name, _) in module_.children.borrow().iter() {
4789 debug!("* {}", token::get_name(name));
4792 debug!("Import resolutions:");
4793 let import_resolutions = module_.import_resolutions.borrow();
4794 for (&name, import_resolution) in import_resolutions.iter() {
4796 match import_resolution.target_for_namespace(ValueNS) {
4797 None => { value_repr = "".to_string(); }
4799 value_repr = " value:?".to_string();
4805 match import_resolution.target_for_namespace(TypeNS) {
4806 None => { type_repr = "".to_string(); }
4808 type_repr = " type:?".to_string();
4813 debug!("* {}:{}{}", token::get_name(name), value_repr, type_repr);
4818 pub struct CrateMap {
4819 pub def_map: DefMap,
4820 pub freevars: RefCell<FreevarMap>,
4821 pub capture_mode_map: RefCell<CaptureModeMap>,
4822 pub export_map: ExportMap,
4823 pub trait_map: TraitMap,
4824 pub external_exports: ExternalExports,
4825 pub last_private_map: LastPrivateMap,
4826 pub glob_map: Option<GlobMap>
4829 #[derive(PartialEq,Copy)]
4830 pub enum MakeGlobMap {
4835 /// Entry point to crate resolution.
4836 pub fn resolve_crate<'a, 'tcx>(session: &'a Session,
4837 ast_map: &'a ast_map::Map<'tcx>,
4840 make_glob_map: MakeGlobMap)
4842 let mut resolver = Resolver::new(session, ast_map, krate.span, make_glob_map);
4844 build_reduced_graph::build_reduced_graph(&mut resolver, krate);
4845 session.abort_if_errors();
4847 resolver.resolve_imports();
4848 session.abort_if_errors();
4850 record_exports::record(&mut resolver);
4851 session.abort_if_errors();
4853 resolver.resolve_crate(krate);
4854 session.abort_if_errors();
4856 check_unused::check_crate(&mut resolver, krate);
4859 def_map: resolver.def_map,
4860 freevars: resolver.freevars,
4861 capture_mode_map: RefCell::new(resolver.capture_mode_map),
4862 export_map: resolver.export_map,
4863 trait_map: resolver.trait_map,
4864 external_exports: resolver.external_exports,
4865 last_private_map: resolver.last_private,
4866 glob_map: if resolver.make_glob_map {
4867 Some(resolver.glob_map)