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"]
13 #![crate_type = "dylib"]
14 #![crate_type = "rlib"]
15 #![doc(html_logo_url = "http://www.rust-lang.org/logos/rust-logo-128x128-blk-v2.png",
16 html_favicon_url = "http://www.rust-lang.org/favicon.ico",
17 html_root_url = "http://doc.rust-lang.org/nightly/")]
19 #![feature(globs, phase, slicing_syntax)]
20 #![feature(rustc_diagnostic_macros)]
21 #![feature(associated_types)]
22 #![feature(old_orphan_check)]
24 #[phase(plugin, link)] extern crate log;
25 #[phase(plugin, link)] 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, TyI, TyI8, TyI16, TyI32, TyI64, TyInt, TyObjectSum};
77 use syntax::ast::{TyParam, TyParamBound, TyPath, TyPtr, TyPolyTraitRef, TyQPath};
78 use syntax::ast::{TyRptr, TyStr, TyU, 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(TyI));
824 table.intern("i8", TyInt(TyI8));
825 table.intern("i16", TyInt(TyI16));
826 table.intern("i32", TyInt(TyI32));
827 table.intern("i64", TyInt(TyI64));
828 table.intern("str", TyStr);
829 table.intern("uint", TyUint(TyU));
830 table.intern("u8", TyUint(TyU8));
831 table.intern("u16", TyUint(TyU16));
832 table.intern("u32", TyUint(TyU32));
833 table.intern("u64", TyUint(TyU64));
838 fn intern(&mut self, string: &str, primitive_type: PrimTy) {
839 self.primitive_types.insert(token::intern(string), primitive_type);
843 /// The main resolver class.
844 struct Resolver<'a, 'tcx:'a> {
845 session: &'a Session,
847 ast_map: &'a ast_map::Map<'tcx>,
849 graph_root: NameBindings,
851 trait_item_map: FnvHashMap<(Name, DefId), TraitItemKind>,
853 structs: FnvHashMap<DefId, Vec<Name>>,
855 // The number of imports that are currently unresolved.
856 unresolved_imports: uint,
858 // The module that represents the current item scope.
859 current_module: Rc<Module>,
861 // The current set of local scopes, for values.
862 // FIXME #4948: Reuse ribs to avoid allocation.
863 value_ribs: Vec<Rib>,
865 // The current set of local scopes, for types.
868 // The current set of local scopes, for labels.
869 label_ribs: Vec<Rib>,
871 // The trait that the current context can refer to.
872 current_trait_ref: Option<(DefId, TraitRef)>,
874 // The current self type if inside an impl (used for better errors).
875 current_self_type: Option<Ty>,
877 // The ident for the keyword "self".
879 // The ident for the non-keyword "Self".
880 type_self_name: Name,
882 // The idents for the primitive types.
883 primitive_type_table: PrimitiveTypeTable,
886 freevars: RefCell<FreevarMap>,
887 freevars_seen: RefCell<NodeMap<NodeSet>>,
888 capture_mode_map: CaptureModeMap,
889 export_map: ExportMap,
891 external_exports: ExternalExports,
892 last_private: LastPrivateMap,
894 // Whether or not to print error messages. Can be set to true
895 // when getting additional info for error message suggestions,
896 // so as to avoid printing duplicate errors
900 // Maps imports to the names of items actually imported (this actually maps
901 // all imports, but only glob imports are actually interesting).
904 used_imports: HashSet<(NodeId, Namespace)>,
905 used_crates: HashSet<CrateNum>,
909 enum FallbackChecks {
915 impl<'a, 'tcx> Resolver<'a, 'tcx> {
916 fn new(session: &'a Session,
917 ast_map: &'a ast_map::Map<'tcx>,
919 make_glob_map: MakeGlobMap) -> Resolver<'a, 'tcx> {
920 let graph_root = NameBindings::new();
922 graph_root.define_module(NoParentLink,
923 Some(DefId { krate: 0, node: 0 }),
929 let current_module = graph_root.get_module();
936 // The outermost module has def ID 0; this is not reflected in the
939 graph_root: graph_root,
941 trait_item_map: FnvHashMap::new(),
942 structs: FnvHashMap::new(),
944 unresolved_imports: 0,
946 current_module: current_module,
947 value_ribs: Vec::new(),
948 type_ribs: Vec::new(),
949 label_ribs: Vec::new(),
951 current_trait_ref: None,
952 current_self_type: None,
954 self_name: special_names::self_,
955 type_self_name: special_names::type_self,
957 primitive_type_table: PrimitiveTypeTable::new(),
959 def_map: RefCell::new(NodeMap::new()),
960 freevars: RefCell::new(NodeMap::new()),
961 freevars_seen: RefCell::new(NodeMap::new()),
962 capture_mode_map: NodeMap::new(),
963 export_map: NodeMap::new(),
964 trait_map: NodeMap::new(),
965 used_imports: HashSet::new(),
966 used_crates: HashSet::new(),
967 external_exports: DefIdSet::new(),
968 last_private: NodeMap::new(),
971 make_glob_map: make_glob_map == MakeGlobMap::Yes,
972 glob_map: HashMap::new(),
978 // This is a fixed-point algorithm. We resolve imports until our efforts
979 // are stymied by an unresolved import; then we bail out of the current
980 // module and continue. We terminate successfully once no more imports
981 // remain or unsuccessfully when no forward progress in resolving imports
984 /// Resolves all imports for the crate. This method performs the fixed-
986 fn resolve_imports(&mut self) {
988 let mut prev_unresolved_imports = 0;
990 debug!("(resolving imports) iteration {}, {} imports left",
991 i, self.unresolved_imports);
993 let module_root = self.graph_root.get_module();
994 self.resolve_imports_for_module_subtree(module_root.clone());
996 if self.unresolved_imports == 0 {
997 debug!("(resolving imports) success");
1001 if self.unresolved_imports == prev_unresolved_imports {
1002 self.report_unresolved_imports(module_root);
1007 prev_unresolved_imports = self.unresolved_imports;
1011 /// Attempts to resolve imports for the given module and all of its
1013 fn resolve_imports_for_module_subtree(&mut self, module_: Rc<Module>) {
1014 debug!("(resolving imports for module subtree) resolving {}",
1015 self.module_to_string(&*module_));
1016 let orig_module = replace(&mut self.current_module, module_.clone());
1017 self.resolve_imports_for_module(module_.clone());
1018 self.current_module = orig_module;
1020 build_reduced_graph::populate_module_if_necessary(self, &module_);
1021 for (_, child_node) in module_.children.borrow().iter() {
1022 match child_node.get_module_if_available() {
1026 Some(child_module) => {
1027 self.resolve_imports_for_module_subtree(child_module);
1032 for (_, child_module) in module_.anonymous_children.borrow().iter() {
1033 self.resolve_imports_for_module_subtree(child_module.clone());
1037 /// Attempts to resolve imports for the given module only.
1038 fn resolve_imports_for_module(&mut self, module: Rc<Module>) {
1039 if module.all_imports_resolved() {
1040 debug!("(resolving imports for module) all imports resolved for \
1042 self.module_to_string(&*module));
1046 let imports = module.imports.borrow();
1047 let import_count = imports.len();
1048 while module.resolved_import_count.get() < import_count {
1049 let import_index = module.resolved_import_count.get();
1050 let import_directive = &(*imports)[import_index];
1051 match self.resolve_import_for_module(module.clone(),
1054 let (span, help) = match err {
1055 Some((span, msg)) => (span, format!(". {}", msg)),
1056 None => (import_directive.span, String::new())
1058 let msg = format!("unresolved import `{}`{}",
1059 self.import_path_to_string(
1060 import_directive.module_path
1062 import_directive.subclass),
1064 self.resolve_error(span, msg[]);
1066 Indeterminate => break, // Bail out. We'll come around next time.
1067 Success(()) => () // Good. Continue.
1070 module.resolved_import_count
1071 .set(module.resolved_import_count.get() + 1);
1075 fn names_to_string(&self, names: &[Name]) -> String {
1076 let mut first = true;
1077 let mut result = String::new();
1078 for name in names.iter() {
1082 result.push_str("::")
1084 result.push_str(token::get_name(*name).get());
1089 fn path_names_to_string(&self, path: &Path) -> String {
1090 let names: Vec<ast::Name> = path.segments
1092 .map(|seg| seg.identifier.name)
1094 self.names_to_string(names[])
1097 fn import_directive_subclass_to_string(&mut self,
1098 subclass: ImportDirectiveSubclass)
1101 SingleImport(_, source) => {
1102 token::get_name(source).get().to_string()
1104 GlobImport => "*".to_string()
1108 fn import_path_to_string(&mut self,
1110 subclass: ImportDirectiveSubclass)
1112 if names.is_empty() {
1113 self.import_directive_subclass_to_string(subclass)
1116 self.names_to_string(names),
1117 self.import_directive_subclass_to_string(
1118 subclass))).to_string()
1123 fn record_import_use(&mut self, import_id: NodeId, name: Name) {
1124 if !self.make_glob_map {
1127 if self.glob_map.contains_key(&import_id) {
1128 self.glob_map[import_id].insert(name);
1132 let mut new_set = HashSet::new();
1133 new_set.insert(name);
1134 self.glob_map.insert(import_id, new_set);
1137 fn get_trait_name(&self, did: DefId) -> Name {
1138 if did.krate == LOCAL_CRATE {
1139 self.ast_map.expect_item(did.node).ident.name
1141 csearch::get_trait_name(&self.session.cstore, did)
1145 /// Attempts to resolve the given import. The return value indicates
1146 /// failure if we're certain the name does not exist, indeterminate if we
1147 /// don't know whether the name exists at the moment due to other
1148 /// currently-unresolved imports, or success if we know the name exists.
1149 /// If successful, the resolved bindings are written into the module.
1150 fn resolve_import_for_module(&mut self,
1151 module_: Rc<Module>,
1152 import_directive: &ImportDirective)
1153 -> ResolveResult<()> {
1154 let mut resolution_result = Failed(None);
1155 let module_path = &import_directive.module_path;
1157 debug!("(resolving import for module) resolving import `{}::...` in `{}`",
1158 self.names_to_string(module_path[]),
1159 self.module_to_string(&*module_));
1161 // First, resolve the module path for the directive, if necessary.
1162 let container = if module_path.len() == 0 {
1163 // Use the crate root.
1164 Some((self.graph_root.get_module(), LastMod(AllPublic)))
1166 match self.resolve_module_path(module_.clone(),
1168 DontUseLexicalScope,
1169 import_directive.span,
1172 resolution_result = Failed(err);
1176 resolution_result = Indeterminate;
1179 Success(container) => Some(container),
1185 Some((containing_module, lp)) => {
1186 // We found the module that the target is contained
1187 // within. Attempt to resolve the import within it.
1189 match import_directive.subclass {
1190 SingleImport(target, source) => {
1192 self.resolve_single_import(&*module_,
1201 self.resolve_glob_import(&*module_,
1210 // Decrement the count of unresolved imports.
1211 match resolution_result {
1213 assert!(self.unresolved_imports >= 1);
1214 self.unresolved_imports -= 1;
1217 // Nothing to do here; just return the error.
1221 // Decrement the count of unresolved globs if necessary. But only if
1222 // the resolution result is indeterminate -- otherwise we'll stop
1223 // processing imports here. (See the loop in
1224 // resolve_imports_for_module.)
1226 if !resolution_result.indeterminate() {
1227 match import_directive.subclass {
1229 assert!(module_.glob_count.get() >= 1);
1230 module_.glob_count.set(module_.glob_count.get() - 1);
1232 SingleImport(..) => {
1238 return resolution_result;
1241 fn create_name_bindings_from_module(module: Rc<Module>) -> NameBindings {
1243 type_def: RefCell::new(Some(TypeNsDef {
1244 modifiers: IMPORTABLE,
1245 module_def: Some(module),
1249 value_def: RefCell::new(None),
1253 fn resolve_single_import(&mut self,
1255 containing_module: Rc<Module>,
1258 directive: &ImportDirective,
1260 -> ResolveResult<()> {
1261 debug!("(resolving single import) resolving `{}` = `{}::{}` from \
1262 `{}` id {}, last private {}",
1263 token::get_name(target),
1264 self.module_to_string(&*containing_module),
1265 token::get_name(source),
1266 self.module_to_string(module_),
1272 LastImport {..} => {
1274 .span_bug(directive.span,
1275 "not expecting Import here, must be LastMod")
1279 // We need to resolve both namespaces for this to succeed.
1282 let mut value_result = UnknownResult;
1283 let mut type_result = UnknownResult;
1285 // Search for direct children of the containing module.
1286 build_reduced_graph::populate_module_if_necessary(self, &containing_module);
1288 match containing_module.children.borrow().get(&source) {
1292 Some(ref child_name_bindings) => {
1293 if child_name_bindings.defined_in_namespace(ValueNS) {
1294 debug!("(resolving single import) found value binding");
1295 value_result = BoundResult(containing_module.clone(),
1296 (*child_name_bindings).clone());
1298 if child_name_bindings.defined_in_namespace(TypeNS) {
1299 debug!("(resolving single import) found type binding");
1300 type_result = BoundResult(containing_module.clone(),
1301 (*child_name_bindings).clone());
1306 // Unless we managed to find a result in both namespaces (unlikely),
1307 // search imports as well.
1308 let mut value_used_reexport = false;
1309 let mut type_used_reexport = false;
1310 match (value_result.clone(), type_result.clone()) {
1311 (BoundResult(..), BoundResult(..)) => {} // Continue.
1313 // If there is an unresolved glob at this point in the
1314 // containing module, bail out. We don't know enough to be
1315 // able to resolve this import.
1317 if containing_module.glob_count.get() > 0 {
1318 debug!("(resolving single import) unresolved glob; \
1320 return Indeterminate;
1323 // Now search the exported imports within the containing module.
1324 match containing_module.import_resolutions.borrow().get(&source) {
1326 debug!("(resolving single import) no import");
1327 // The containing module definitely doesn't have an
1328 // exported import with the name in question. We can
1329 // therefore accurately report that the names are
1332 if value_result.is_unknown() {
1333 value_result = UnboundResult;
1335 if type_result.is_unknown() {
1336 type_result = UnboundResult;
1339 Some(import_resolution)
1340 if import_resolution.outstanding_references == 0 => {
1342 fn get_binding(this: &mut Resolver,
1343 import_resolution: &ImportResolution,
1344 namespace: Namespace,
1346 -> NamespaceResult {
1348 // Import resolutions must be declared with "pub"
1349 // in order to be exported.
1350 if !import_resolution.is_public {
1351 return UnboundResult;
1354 match import_resolution.
1355 target_for_namespace(namespace) {
1357 return UnboundResult;
1364 debug!("(resolving single import) found \
1365 import in ns {}", namespace);
1366 let id = import_resolution.id(namespace);
1367 // track used imports and extern crates as well
1368 this.used_imports.insert((id, namespace));
1369 this.record_import_use(id, *source);
1370 match target_module.def_id.get() {
1371 Some(DefId{krate: kid, ..}) => {
1372 this.used_crates.insert(kid);
1376 return BoundResult(target_module, bindings);
1381 // The name is an import which has been fully
1382 // resolved. We can, therefore, just follow it.
1383 if value_result.is_unknown() {
1384 value_result = get_binding(self,
1388 value_used_reexport = import_resolution.is_public;
1390 if type_result.is_unknown() {
1391 type_result = get_binding(self,
1395 type_used_reexport = import_resolution.is_public;
1400 // If containing_module is the same module whose import we are resolving
1401 // and there it has an unresolved import with the same name as `source`,
1402 // then the user is actually trying to import an item that is declared
1403 // in the same scope
1406 // use self::submodule;
1407 // pub mod submodule;
1409 // In this case we continue as if we resolved the import and let the
1410 // check_for_conflicts_between_imports_and_items call below handle
1412 match (module_.def_id.get(), containing_module.def_id.get()) {
1413 (Some(id1), Some(id2)) if id1 == id2 => {
1414 if value_result.is_unknown() {
1415 value_result = UnboundResult;
1417 if type_result.is_unknown() {
1418 type_result = UnboundResult;
1422 // The import is unresolved. Bail out.
1423 debug!("(resolving single import) unresolved import; \
1425 return Indeterminate;
1433 // If we didn't find a result in the type namespace, search the
1434 // external modules.
1435 let mut value_used_public = false;
1436 let mut type_used_public = false;
1438 BoundResult(..) => {}
1440 match containing_module.external_module_children.borrow_mut()
1441 .get(&source).cloned() {
1442 None => {} // Continue.
1444 debug!("(resolving single import) found external \
1446 // track the module as used.
1447 match module.def_id.get() {
1448 Some(DefId{krate: kid, ..}) => { self.used_crates.insert(kid); },
1452 Rc::new(Resolver::create_name_bindings_from_module(
1454 type_result = BoundResult(containing_module.clone(),
1456 type_used_public = true;
1462 // We've successfully resolved the import. Write the results in.
1463 let mut import_resolutions = module_.import_resolutions.borrow_mut();
1464 let import_resolution = &mut (*import_resolutions)[target];
1466 let mut check_and_write_import = |&mut: namespace, result: &_, used_public: &mut bool| {
1467 let namespace_name = match namespace {
1473 BoundResult(ref target_module, ref name_bindings) => {
1474 debug!("(resolving single import) found {} target: {}",
1476 name_bindings.def_for_namespace(namespace));
1477 self.check_for_conflicting_import(
1478 &import_resolution.target_for_namespace(namespace),
1483 self.check_that_import_is_importable(
1489 let target = Some(Target::new(target_module.clone(),
1490 name_bindings.clone(),
1491 directive.shadowable));
1492 import_resolution.set_target_and_id(namespace, target, directive.id);
1493 import_resolution.is_public = directive.is_public;
1494 *used_public = name_bindings.defined_in_public_namespace(namespace);
1496 UnboundResult => { /* Continue. */ }
1498 panic!("{} result should be known at this point", namespace_name);
1502 check_and_write_import(ValueNS, &value_result, &mut value_used_public);
1503 check_and_write_import(TypeNS, &type_result, &mut type_used_public);
1506 self.check_for_conflicts_between_imports_and_items(
1512 if value_result.is_unbound() && type_result.is_unbound() {
1513 let msg = format!("There is no `{}` in `{}`",
1514 token::get_name(source),
1515 self.module_to_string(&*containing_module));
1516 return Failed(Some((directive.span, msg)));
1518 let value_used_public = value_used_reexport || value_used_public;
1519 let type_used_public = type_used_reexport || type_used_public;
1521 assert!(import_resolution.outstanding_references >= 1);
1522 import_resolution.outstanding_references -= 1;
1524 // record what this import resolves to for later uses in documentation,
1525 // this may resolve to either a value or a type, but for documentation
1526 // purposes it's good enough to just favor one over the other.
1527 let value_private = match import_resolution.value_target {
1528 Some(ref target) => {
1529 let def = target.bindings.def_for_namespace(ValueNS).unwrap();
1530 self.def_map.borrow_mut().insert(directive.id, def);
1531 let did = def.def_id();
1532 if value_used_public {Some(lp)} else {Some(DependsOn(did))}
1534 // AllPublic here and below is a dummy value, it should never be used because
1535 // _exists is false.
1538 let type_private = match import_resolution.type_target {
1539 Some(ref target) => {
1540 let def = target.bindings.def_for_namespace(TypeNS).unwrap();
1541 self.def_map.borrow_mut().insert(directive.id, def);
1542 let did = def.def_id();
1543 if type_used_public {Some(lp)} else {Some(DependsOn(did))}
1548 self.last_private.insert(directive.id, LastImport{value_priv: value_private,
1550 type_priv: type_private,
1553 debug!("(resolving single import) successfully resolved import");
1557 // Resolves a glob import. Note that this function cannot fail; it either
1558 // succeeds or bails out (as importing * from an empty module or a module
1559 // that exports nothing is valid). containing_module is the module we are
1560 // actually importing, i.e., `foo` in `use foo::*`.
1561 fn resolve_glob_import(&mut self,
1563 containing_module: Rc<Module>,
1564 import_directive: &ImportDirective,
1566 -> ResolveResult<()> {
1567 let id = import_directive.id;
1568 let is_public = import_directive.is_public;
1570 // This function works in a highly imperative manner; it eagerly adds
1571 // everything it can to the list of import resolutions of the module
1573 debug!("(resolving glob import) resolving glob import {}", id);
1575 // We must bail out if the node has unresolved imports of any kind
1576 // (including globs).
1577 if !(*containing_module).all_imports_resolved() {
1578 debug!("(resolving glob import) target module has unresolved \
1579 imports; bailing out");
1580 return Indeterminate;
1583 assert_eq!(containing_module.glob_count.get(), 0);
1585 // Add all resolved imports from the containing module.
1586 let import_resolutions = containing_module.import_resolutions.borrow();
1587 for (ident, target_import_resolution) in import_resolutions.iter() {
1588 debug!("(resolving glob import) writing module resolution \
1590 token::get_name(*ident),
1591 self.module_to_string(module_));
1593 if !target_import_resolution.is_public {
1594 debug!("(resolving glob import) nevermind, just kidding");
1598 // Here we merge two import resolutions.
1599 let mut import_resolutions = module_.import_resolutions.borrow_mut();
1600 match import_resolutions.get_mut(ident) {
1601 Some(dest_import_resolution) => {
1602 // Merge the two import resolutions at a finer-grained
1605 match target_import_resolution.value_target {
1609 Some(ref value_target) => {
1610 self.check_for_conflicting_import(&dest_import_resolution.value_target,
1611 import_directive.span,
1614 dest_import_resolution.value_target = Some(value_target.clone());
1617 match target_import_resolution.type_target {
1621 Some(ref type_target) => {
1622 self.check_for_conflicting_import(&dest_import_resolution.type_target,
1623 import_directive.span,
1626 dest_import_resolution.type_target = Some(type_target.clone());
1629 dest_import_resolution.is_public = is_public;
1635 // Simple: just copy the old import resolution.
1636 let mut new_import_resolution = ImportResolution::new(id, is_public);
1637 new_import_resolution.value_target =
1638 target_import_resolution.value_target.clone();
1639 new_import_resolution.type_target =
1640 target_import_resolution.type_target.clone();
1642 import_resolutions.insert(*ident, new_import_resolution);
1645 // Add all children from the containing module.
1646 build_reduced_graph::populate_module_if_necessary(self, &containing_module);
1648 for (&name, name_bindings) in containing_module.children.borrow().iter() {
1649 self.merge_import_resolution(module_,
1650 containing_module.clone(),
1653 name_bindings.clone());
1657 // Add external module children from the containing module.
1658 for (&name, module) in containing_module.external_module_children.borrow().iter() {
1660 Rc::new(Resolver::create_name_bindings_from_module(module.clone()));
1661 self.merge_import_resolution(module_,
1662 containing_module.clone(),
1668 // Record the destination of this import
1669 match containing_module.def_id.get() {
1671 self.def_map.borrow_mut().insert(id, DefMod(did));
1672 self.last_private.insert(id, lp);
1677 debug!("(resolving glob import) successfully resolved import");
1681 fn merge_import_resolution(&mut self,
1683 containing_module: Rc<Module>,
1684 import_directive: &ImportDirective,
1686 name_bindings: Rc<NameBindings>) {
1687 let id = import_directive.id;
1688 let is_public = import_directive.is_public;
1690 let mut import_resolutions = module_.import_resolutions.borrow_mut();
1691 let dest_import_resolution = import_resolutions.entry(&name).get().unwrap_or_else(
1693 // Create a new import resolution from this child.
1694 vacant_entry.insert(ImportResolution::new(id, is_public))
1697 debug!("(resolving glob import) writing resolution `{}` in `{}` \
1699 token::get_name(name).get(),
1700 self.module_to_string(&*containing_module),
1701 self.module_to_string(module_));
1703 // Merge the child item into the import resolution.
1705 let mut merge_child_item = |&mut : namespace| {
1706 if name_bindings.defined_in_namespace_with(namespace, IMPORTABLE | PUBLIC) {
1707 let namespace_name = match namespace {
1711 debug!("(resolving glob import) ... for {} target", namespace_name);
1712 if dest_import_resolution.shadowable(namespace) == Shadowable::Never {
1713 let msg = format!("a {} named `{}` has already been imported \
1716 token::get_name(name).get());
1717 self.session.span_err(import_directive.span, msg.as_slice());
1719 let target = Target::new(containing_module.clone(),
1720 name_bindings.clone(),
1721 import_directive.shadowable);
1722 dest_import_resolution.set_target_and_id(namespace,
1728 merge_child_item(ValueNS);
1729 merge_child_item(TypeNS);
1732 dest_import_resolution.is_public = is_public;
1734 self.check_for_conflicts_between_imports_and_items(
1736 dest_import_resolution,
1737 import_directive.span,
1741 /// Checks that imported names and items don't have the same name.
1742 fn check_for_conflicting_import(&mut self,
1743 target: &Option<Target>,
1746 namespace: Namespace) {
1747 if self.session.features.borrow().import_shadowing {
1751 debug!("check_for_conflicting_import: {}; target exists: {}",
1752 token::get_name(name).get(),
1756 Some(ref target) if target.shadowable != Shadowable::Always => {
1757 let msg = format!("a {} named `{}` has already been imported \
1763 token::get_name(name).get());
1764 self.session.span_err(import_span, msg[]);
1766 Some(_) | None => {}
1770 /// Checks that an import is actually importable
1771 fn check_that_import_is_importable(&mut self,
1772 name_bindings: &NameBindings,
1775 namespace: Namespace) {
1776 if !name_bindings.defined_in_namespace_with(namespace, IMPORTABLE) {
1777 let msg = format!("`{}` is not directly importable",
1778 token::get_name(name));
1779 self.session.span_err(import_span, msg[]);
1783 /// Checks that imported names and items don't have the same name.
1784 fn check_for_conflicts_between_imports_and_items(&mut self,
1790 if self.session.features.borrow().import_shadowing {
1794 // First, check for conflicts between imports and `extern crate`s.
1795 if module.external_module_children
1797 .contains_key(&name) {
1798 match import_resolution.type_target {
1799 Some(ref target) if target.shadowable != Shadowable::Always => {
1800 let msg = format!("import `{0}` conflicts with imported \
1801 crate in this module \
1802 (maybe you meant `use {0}::*`?)",
1803 token::get_name(name).get());
1804 self.session.span_err(import_span, msg[]);
1806 Some(_) | None => {}
1810 // Check for item conflicts.
1811 let children = module.children.borrow();
1812 let name_bindings = match children.get(&name) {
1814 // There can't be any conflicts.
1817 Some(ref name_bindings) => (*name_bindings).clone(),
1820 match import_resolution.value_target {
1821 Some(ref target) if target.shadowable != Shadowable::Always => {
1822 if let Some(ref value) = *name_bindings.value_def.borrow() {
1823 let msg = format!("import `{}` conflicts with value \
1825 token::get_name(name).get());
1826 self.session.span_err(import_span, msg[]);
1827 if let Some(span) = value.value_span {
1828 self.session.span_note(span,
1829 "conflicting value here");
1833 Some(_) | None => {}
1836 match import_resolution.type_target {
1837 Some(ref target) if target.shadowable != Shadowable::Always => {
1838 if let Some(ref ty) = *name_bindings.type_def.borrow() {
1839 match ty.module_def {
1841 let msg = format!("import `{}` conflicts with type in \
1843 token::get_name(name).get());
1844 self.session.span_err(import_span, msg[]);
1845 if let Some(span) = ty.type_span {
1846 self.session.span_note(span,
1847 "note conflicting type here")
1850 Some(ref module_def) => {
1851 match module_def.kind.get() {
1853 if let Some(span) = ty.type_span {
1854 let msg = format!("inherent implementations \
1855 are only allowed on types \
1856 defined in the current module");
1857 self.session.span_err(span, msg[]);
1858 self.session.span_note(import_span,
1859 "import from other module here")
1863 let msg = format!("import `{}` conflicts with existing \
1865 token::get_name(name).get());
1866 self.session.span_err(import_span, msg[]);
1867 if let Some(span) = ty.type_span {
1868 self.session.span_note(span,
1869 "note conflicting module here")
1877 Some(_) | None => {}
1881 /// Checks that the names of external crates don't collide with other
1882 /// external crates.
1883 fn check_for_conflicts_between_external_crates(&self,
1887 if self.session.features.borrow().import_shadowing {
1891 if module.external_module_children.borrow().contains_key(&name) {
1894 format!("an external crate named `{}` has already \
1895 been imported into this module",
1896 token::get_name(name).get())[]);
1900 /// Checks that the names of items don't collide with external crates.
1901 fn check_for_conflicts_between_external_crates_and_items(&self,
1905 if self.session.features.borrow().import_shadowing {
1909 if module.external_module_children.borrow().contains_key(&name) {
1912 format!("the name `{}` conflicts with an external \
1913 crate that has been imported into this \
1915 token::get_name(name).get())[]);
1919 /// Resolves the given module path from the given root `module_`.
1920 fn resolve_module_path_from_root(&mut self,
1921 module_: Rc<Module>,
1922 module_path: &[Name],
1925 name_search_type: NameSearchType,
1927 -> ResolveResult<(Rc<Module>, LastPrivate)> {
1928 fn search_parent_externals(needle: Name, module: &Rc<Module>)
1929 -> Option<Rc<Module>> {
1930 module.external_module_children.borrow()
1931 .get(&needle).cloned()
1932 .map(|_| module.clone())
1934 match module.parent_link.clone() {
1935 ModuleParentLink(parent, _) => {
1936 search_parent_externals(needle,
1937 &parent.upgrade().unwrap())
1944 let mut search_module = module_;
1945 let mut index = index;
1946 let module_path_len = module_path.len();
1947 let mut closest_private = lp;
1949 // Resolve the module part of the path. This does not involve looking
1950 // upward though scope chains; we simply resolve names directly in
1951 // modules as we go.
1952 while index < module_path_len {
1953 let name = module_path[index];
1954 match self.resolve_name_in_module(search_module.clone(),
1960 let segment_name = token::get_name(name);
1961 let module_name = self.module_to_string(&*search_module);
1962 let mut span = span;
1963 let msg = if "???" == module_name[] {
1964 span.hi = span.lo + Pos::from_uint(segment_name.get().len());
1966 match search_parent_externals(name,
1967 &self.current_module) {
1969 let path_str = self.names_to_string(module_path);
1970 let target_mod_str = self.module_to_string(&*module);
1971 let current_mod_str =
1972 self.module_to_string(&*self.current_module);
1974 let prefix = if target_mod_str == current_mod_str {
1975 "self::".to_string()
1977 format!("{}::", target_mod_str)
1980 format!("Did you mean `{}{}`?", prefix, path_str)
1982 None => format!("Maybe a missing `extern crate {}`?",
1986 format!("Could not find `{}` in `{}`",
1991 return Failed(Some((span, msg)));
1993 Failed(err) => return Failed(err),
1995 debug!("(resolving module path for import) module \
1996 resolution is indeterminate: {}",
1997 token::get_name(name));
1998 return Indeterminate;
2000 Success((target, used_proxy)) => {
2001 // Check to see whether there are type bindings, and, if
2002 // so, whether there is a module within.
2003 match *target.bindings.type_def.borrow() {
2004 Some(ref type_def) => {
2005 match type_def.module_def {
2007 let msg = format!("Not a module `{}`",
2008 token::get_name(name));
2010 return Failed(Some((span, msg)));
2012 Some(ref module_def) => {
2013 search_module = module_def.clone();
2015 // track extern crates for unused_extern_crate lint
2016 if let Some(did) = module_def.def_id.get() {
2017 self.used_crates.insert(did.krate);
2020 // Keep track of the closest
2021 // private module used when
2022 // resolving this import chain.
2023 if !used_proxy && !search_module.is_public {
2024 if let Some(did) = search_module.def_id.get() {
2025 closest_private = LastMod(DependsOn(did));
2032 // There are no type bindings at all.
2033 let msg = format!("Not a module `{}`",
2034 token::get_name(name));
2035 return Failed(Some((span, msg)));
2044 return Success((search_module, closest_private));
2047 /// Attempts to resolve the module part of an import directive or path
2048 /// rooted at the given module.
2050 /// On success, returns the resolved module, and the closest *private*
2051 /// module found to the destination when resolving this path.
2052 fn resolve_module_path(&mut self,
2053 module_: Rc<Module>,
2054 module_path: &[Name],
2055 use_lexical_scope: UseLexicalScopeFlag,
2057 name_search_type: NameSearchType)
2058 -> ResolveResult<(Rc<Module>, LastPrivate)> {
2059 let module_path_len = module_path.len();
2060 assert!(module_path_len > 0);
2062 debug!("(resolving module path for import) processing `{}` rooted at `{}`",
2063 self.names_to_string(module_path),
2064 self.module_to_string(&*module_));
2066 // Resolve the module prefix, if any.
2067 let module_prefix_result = self.resolve_module_prefix(module_.clone(),
2073 match module_prefix_result {
2075 let mpath = self.names_to_string(module_path);
2076 let mpath = mpath[];
2077 match mpath.rfind(':') {
2079 let msg = format!("Could not find `{}` in `{}`",
2080 // idx +- 1 to account for the
2081 // colons on either side
2084 return Failed(Some((span, msg)));
2091 Failed(err) => return Failed(err),
2093 debug!("(resolving module path for import) indeterminate; \
2095 return Indeterminate;
2097 Success(NoPrefixFound) => {
2098 // There was no prefix, so we're considering the first element
2099 // of the path. How we handle this depends on whether we were
2100 // instructed to use lexical scope or not.
2101 match use_lexical_scope {
2102 DontUseLexicalScope => {
2103 // This is a crate-relative path. We will start the
2104 // resolution process at index zero.
2105 search_module = self.graph_root.get_module();
2107 last_private = LastMod(AllPublic);
2109 UseLexicalScope => {
2110 // This is not a crate-relative path. We resolve the
2111 // first component of the path in the current lexical
2112 // scope and then proceed to resolve below that.
2113 match self.resolve_module_in_lexical_scope(module_,
2115 Failed(err) => return Failed(err),
2117 debug!("(resolving module path for import) \
2118 indeterminate; bailing");
2119 return Indeterminate;
2121 Success(containing_module) => {
2122 search_module = containing_module;
2124 last_private = LastMod(AllPublic);
2130 Success(PrefixFound(ref containing_module, index)) => {
2131 search_module = containing_module.clone();
2132 start_index = index;
2133 last_private = LastMod(DependsOn(containing_module.def_id
2139 self.resolve_module_path_from_root(search_module,
2147 /// Invariant: This must only be called during main resolution, not during
2148 /// import resolution.
2149 fn resolve_item_in_lexical_scope(&mut self,
2150 module_: Rc<Module>,
2152 namespace: Namespace)
2153 -> ResolveResult<(Target, bool)> {
2154 debug!("(resolving item in lexical scope) resolving `{}` in \
2155 namespace {} in `{}`",
2156 token::get_name(name),
2158 self.module_to_string(&*module_));
2160 // The current module node is handled specially. First, check for
2161 // its immediate children.
2162 build_reduced_graph::populate_module_if_necessary(self, &module_);
2164 match module_.children.borrow().get(&name) {
2166 if name_bindings.defined_in_namespace(namespace) => {
2167 debug!("top name bindings succeeded");
2168 return Success((Target::new(module_.clone(),
2169 name_bindings.clone(),
2173 Some(_) | None => { /* Not found; continue. */ }
2176 // Now check for its import directives. We don't have to have resolved
2177 // all its imports in the usual way; this is because chains of
2178 // adjacent import statements are processed as though they mutated the
2180 if let Some(import_resolution) = module_.import_resolutions.borrow().get(&name) {
2181 match (*import_resolution).target_for_namespace(namespace) {
2183 // Not found; continue.
2184 debug!("(resolving item in lexical scope) found \
2185 import resolution, but not in namespace {}",
2189 debug!("(resolving item in lexical scope) using \
2190 import resolution");
2191 // track used imports and extern crates as well
2192 let id = import_resolution.id(namespace);
2193 self.used_imports.insert((id, namespace));
2194 self.record_import_use(id, name);
2195 if let Some(DefId{krate: kid, ..}) = target.target_module.def_id.get() {
2196 self.used_crates.insert(kid);
2198 return Success((target, false));
2203 // Search for external modules.
2204 if namespace == TypeNS {
2205 if let Some(module) = module_.external_module_children.borrow().get(&name).cloned() {
2207 Rc::new(Resolver::create_name_bindings_from_module(module));
2208 debug!("lower name bindings succeeded");
2209 return Success((Target::new(module_,
2216 // Finally, proceed up the scope chain looking for parent modules.
2217 let mut search_module = module_;
2219 // Go to the next parent.
2220 match search_module.parent_link.clone() {
2222 // No more parents. This module was unresolved.
2223 debug!("(resolving item in lexical scope) unresolved \
2225 return Failed(None);
2227 ModuleParentLink(parent_module_node, _) => {
2228 match search_module.kind.get() {
2229 NormalModuleKind => {
2230 // We stop the search here.
2231 debug!("(resolving item in lexical \
2232 scope) unresolved module: not \
2233 searching through module \
2235 return Failed(None);
2240 AnonymousModuleKind => {
2241 search_module = parent_module_node.upgrade().unwrap();
2245 BlockParentLink(ref parent_module_node, _) => {
2246 search_module = parent_module_node.upgrade().unwrap();
2250 // Resolve the name in the parent module.
2251 match self.resolve_name_in_module(search_module.clone(),
2256 Failed(Some((span, msg))) =>
2257 self.resolve_error(span, format!("failed to resolve. {}",
2259 Failed(None) => (), // Continue up the search chain.
2261 // We couldn't see through the higher scope because of an
2262 // unresolved import higher up. Bail.
2264 debug!("(resolving item in lexical scope) indeterminate \
2265 higher scope; bailing");
2266 return Indeterminate;
2268 Success((target, used_reexport)) => {
2269 // We found the module.
2270 debug!("(resolving item in lexical scope) found name \
2272 return Success((target, used_reexport));
2278 /// Resolves a module name in the current lexical scope.
2279 fn resolve_module_in_lexical_scope(&mut self,
2280 module_: Rc<Module>,
2282 -> ResolveResult<Rc<Module>> {
2283 // If this module is an anonymous module, resolve the item in the
2284 // lexical scope. Otherwise, resolve the item from the crate root.
2285 let resolve_result = self.resolve_item_in_lexical_scope(module_, name, TypeNS);
2286 match resolve_result {
2287 Success((target, _)) => {
2288 let bindings = &*target.bindings;
2289 match *bindings.type_def.borrow() {
2290 Some(ref type_def) => {
2291 match type_def.module_def {
2293 debug!("!!! (resolving module in lexical \
2294 scope) module wasn't actually a \
2296 return Failed(None);
2298 Some(ref module_def) => {
2299 return Success(module_def.clone());
2304 debug!("!!! (resolving module in lexical scope) module
2305 wasn't actually a module!");
2306 return Failed(None);
2311 debug!("(resolving module in lexical scope) indeterminate; \
2313 return Indeterminate;
2316 debug!("(resolving module in lexical scope) failed to resolve");
2322 /// Returns the nearest normal module parent of the given module.
2323 fn get_nearest_normal_module_parent(&mut self, module_: Rc<Module>)
2324 -> Option<Rc<Module>> {
2325 let mut module_ = module_;
2327 match module_.parent_link.clone() {
2328 NoParentLink => return None,
2329 ModuleParentLink(new_module, _) |
2330 BlockParentLink(new_module, _) => {
2331 let new_module = new_module.upgrade().unwrap();
2332 match new_module.kind.get() {
2333 NormalModuleKind => return Some(new_module),
2337 AnonymousModuleKind => module_ = new_module,
2344 /// Returns the nearest normal module parent of the given module, or the
2345 /// module itself if it is a normal module.
2346 fn get_nearest_normal_module_parent_or_self(&mut self, module_: Rc<Module>)
2348 match module_.kind.get() {
2349 NormalModuleKind => return module_,
2353 AnonymousModuleKind => {
2354 match self.get_nearest_normal_module_parent(module_.clone()) {
2356 Some(new_module) => new_module
2362 /// Resolves a "module prefix". A module prefix is one or both of (a) `self::`;
2363 /// (b) some chain of `super::`.
2364 /// grammar: (SELF MOD_SEP ) ? (SUPER MOD_SEP) *
2365 fn resolve_module_prefix(&mut self,
2366 module_: Rc<Module>,
2367 module_path: &[Name])
2368 -> ResolveResult<ModulePrefixResult> {
2369 // Start at the current module if we see `self` or `super`, or at the
2370 // top of the crate otherwise.
2371 let mut containing_module;
2373 let first_module_path_string = token::get_name(module_path[0]);
2374 if "self" == first_module_path_string.get() {
2376 self.get_nearest_normal_module_parent_or_self(module_);
2378 } else if "super" == first_module_path_string.get() {
2380 self.get_nearest_normal_module_parent_or_self(module_);
2381 i = 0; // We'll handle `super` below.
2383 return Success(NoPrefixFound);
2386 // Now loop through all the `super`s we find.
2387 while i < module_path.len() {
2388 let string = token::get_name(module_path[i]);
2389 if "super" != string.get() {
2392 debug!("(resolving module prefix) resolving `super` at {}",
2393 self.module_to_string(&*containing_module));
2394 match self.get_nearest_normal_module_parent(containing_module) {
2395 None => return Failed(None),
2396 Some(new_module) => {
2397 containing_module = new_module;
2403 debug!("(resolving module prefix) finished resolving prefix at {}",
2404 self.module_to_string(&*containing_module));
2406 return Success(PrefixFound(containing_module, i));
2409 /// Attempts to resolve the supplied name in the given module for the
2410 /// given namespace. If successful, returns the target corresponding to
2413 /// The boolean returned on success is an indicator of whether this lookup
2414 /// passed through a public re-export proxy.
2415 fn resolve_name_in_module(&mut self,
2416 module_: Rc<Module>,
2418 namespace: Namespace,
2419 name_search_type: NameSearchType,
2420 allow_private_imports: bool)
2421 -> ResolveResult<(Target, bool)> {
2422 debug!("(resolving name in module) resolving `{}` in `{}`",
2423 token::get_name(name).get(),
2424 self.module_to_string(&*module_));
2426 // First, check the direct children of the module.
2427 build_reduced_graph::populate_module_if_necessary(self, &module_);
2429 match module_.children.borrow().get(&name) {
2431 if name_bindings.defined_in_namespace(namespace) => {
2432 debug!("(resolving name in module) found node as child");
2433 return Success((Target::new(module_.clone(),
2434 name_bindings.clone(),
2443 // Next, check the module's imports if necessary.
2445 // If this is a search of all imports, we should be done with glob
2446 // resolution at this point.
2447 if name_search_type == PathSearch {
2448 assert_eq!(module_.glob_count.get(), 0);
2451 // Check the list of resolved imports.
2452 match module_.import_resolutions.borrow().get(&name) {
2453 Some(import_resolution) if allow_private_imports ||
2454 import_resolution.is_public => {
2456 if import_resolution.is_public &&
2457 import_resolution.outstanding_references != 0 {
2458 debug!("(resolving name in module) import \
2459 unresolved; bailing out");
2460 return Indeterminate;
2462 match import_resolution.target_for_namespace(namespace) {
2464 debug!("(resolving name in module) name found, \
2465 but not in namespace {}",
2469 debug!("(resolving name in module) resolved to \
2471 // track used imports and extern crates as well
2472 let id = import_resolution.id(namespace);
2473 self.used_imports.insert((id, namespace));
2474 self.record_import_use(id, name);
2475 if let Some(DefId{krate: kid, ..}) = target.target_module.def_id.get() {
2476 self.used_crates.insert(kid);
2478 return Success((target, true));
2482 Some(..) | None => {} // Continue.
2485 // Finally, search through external children.
2486 if namespace == TypeNS {
2487 if let Some(module) = module_.external_module_children.borrow().get(&name).cloned() {
2489 Rc::new(Resolver::create_name_bindings_from_module(module));
2490 return Success((Target::new(module_,
2497 // We're out of luck.
2498 debug!("(resolving name in module) failed to resolve `{}`",
2499 token::get_name(name).get());
2500 return Failed(None);
2503 fn report_unresolved_imports(&mut self, module_: Rc<Module>) {
2504 let index = module_.resolved_import_count.get();
2505 let imports = module_.imports.borrow();
2506 let import_count = imports.len();
2507 if index != import_count {
2508 let sn = self.session
2510 .span_to_snippet((*imports)[index].span)
2512 if sn.contains("::") {
2513 self.resolve_error((*imports)[index].span,
2514 "unresolved import");
2516 let err = format!("unresolved import (maybe you meant `{}::*`?)",
2518 self.resolve_error((*imports)[index].span, err[]);
2522 // Descend into children and anonymous children.
2523 build_reduced_graph::populate_module_if_necessary(self, &module_);
2525 for (_, child_node) in module_.children.borrow().iter() {
2526 match child_node.get_module_if_available() {
2530 Some(child_module) => {
2531 self.report_unresolved_imports(child_module);
2536 for (_, module_) in module_.anonymous_children.borrow().iter() {
2537 self.report_unresolved_imports(module_.clone());
2543 // We maintain a list of value ribs and type ribs.
2545 // Simultaneously, we keep track of the current position in the module
2546 // graph in the `current_module` pointer. When we go to resolve a name in
2547 // the value or type namespaces, we first look through all the ribs and
2548 // then query the module graph. When we resolve a name in the module
2549 // namespace, we can skip all the ribs (since nested modules are not
2550 // allowed within blocks in Rust) and jump straight to the current module
2553 // Named implementations are handled separately. When we find a method
2554 // call, we consult the module node to find all of the implementations in
2555 // scope. This information is lazily cached in the module node. We then
2556 // generate a fake "implementation scope" containing all the
2557 // implementations thus found, for compatibility with old resolve pass.
2559 fn with_scope<F>(&mut self, name: Option<Name>, f: F) where
2560 F: FnOnce(&mut Resolver),
2562 let orig_module = self.current_module.clone();
2564 // Move down in the graph.
2570 build_reduced_graph::populate_module_if_necessary(self, &orig_module);
2572 match orig_module.children.borrow().get(&name) {
2574 debug!("!!! (with scope) didn't find `{}` in `{}`",
2575 token::get_name(name),
2576 self.module_to_string(&*orig_module));
2578 Some(name_bindings) => {
2579 match (*name_bindings).get_module_if_available() {
2581 debug!("!!! (with scope) didn't find module \
2583 token::get_name(name),
2584 self.module_to_string(&*orig_module));
2587 self.current_module = module_;
2597 self.current_module = orig_module;
2600 /// Wraps the given definition in the appropriate number of `DefUpvar`
2606 -> Option<DefLike> {
2608 DlDef(d @ DefUpvar(..)) => {
2609 self.session.span_bug(span,
2610 format!("unexpected {} in bindings", d)[])
2612 DlDef(d @ DefLocal(_)) => {
2613 let node_id = d.def_id().node;
2615 let mut last_proc_body_id = ast::DUMMY_NODE_ID;
2616 for rib in ribs.iter() {
2619 // Nothing to do. Continue.
2621 ClosureRibKind(function_id, maybe_proc_body) => {
2623 if maybe_proc_body != ast::DUMMY_NODE_ID {
2624 last_proc_body_id = maybe_proc_body;
2626 def = DefUpvar(node_id, function_id, last_proc_body_id);
2628 let mut seen = self.freevars_seen.borrow_mut();
2629 let seen = match seen.entry(&function_id) {
2630 Occupied(v) => v.into_mut(),
2631 Vacant(v) => v.insert(NodeSet::new()),
2633 if seen.contains(&node_id) {
2636 match self.freevars.borrow_mut().entry(&function_id) {
2637 Occupied(v) => v.into_mut(),
2638 Vacant(v) => v.insert(vec![]),
2639 }.push(Freevar { def: prev_def, span: span });
2640 seen.insert(node_id);
2642 MethodRibKind(item_id, _) => {
2643 // If the def is a ty param, and came from the parent
2646 DefTyParam(_, _, did, _) if {
2647 self.def_map.borrow().get(&did.node).cloned()
2648 == Some(DefTyParamBinder(item_id))
2650 DefSelfTy(did) if did == item_id => {} // ok
2652 // This was an attempt to access an upvar inside a
2653 // named function item. This is not allowed, so we
2658 "can't capture dynamic environment in a fn item; \
2659 use the || { ... } closure form instead");
2666 // This was an attempt to access an upvar inside a
2667 // named function item. This is not allowed, so we
2672 "can't capture dynamic environment in a fn item; \
2673 use the || { ... } closure form instead");
2677 ConstantItemRibKind => {
2678 // Still doesn't deal with upvars
2679 self.resolve_error(span,
2680 "attempt to use a non-constant \
2681 value in a constant");
2688 DlDef(def @ DefTyParam(..)) |
2689 DlDef(def @ DefSelfTy(..)) => {
2690 for rib in ribs.iter() {
2692 NormalRibKind | ClosureRibKind(..) => {
2693 // Nothing to do. Continue.
2695 MethodRibKind(item_id, _) => {
2696 // If the def is a ty param, and came from the parent
2699 DefTyParam(_, _, did, _) if {
2700 self.def_map.borrow().get(&did.node).cloned()
2701 == Some(DefTyParamBinder(item_id))
2703 DefSelfTy(did) if did == item_id => {} // ok
2706 // This was an attempt to use a type parameter outside
2709 self.resolve_error(span,
2710 "can't use type parameters from \
2711 outer function; try using a local \
2712 type parameter instead");
2719 // This was an attempt to use a type parameter outside
2722 self.resolve_error(span,
2723 "can't use type parameters from \
2724 outer function; try using a local \
2725 type parameter instead");
2729 ConstantItemRibKind => {
2731 self.resolve_error(span,
2732 "cannot use an outer type \
2733 parameter in this context");
2744 /// Searches the current set of local scopes and
2745 /// applies translations for closures.
2746 fn search_ribs(&self,
2750 -> Option<DefLike> {
2751 // FIXME #4950: Try caching?
2753 for (i, rib) in ribs.iter().enumerate().rev() {
2754 match rib.bindings.get(&name).cloned() {
2756 return self.upvarify(ribs[i + 1..], def_like, span);
2767 /// Searches the current set of local scopes for labels.
2768 /// Stops after meeting a closure.
2769 fn search_label(&self, name: Name) -> Option<DefLike> {
2770 for rib in self.label_ribs.iter().rev() {
2776 // Do not resolve labels across function boundary
2780 let result = rib.bindings.get(&name).cloned();
2781 if result.is_some() {
2788 fn resolve_crate(&mut self, krate: &ast::Crate) {
2789 debug!("(resolving crate) starting");
2791 visit::walk_crate(self, krate);
2794 fn resolve_item(&mut self, item: &Item) {
2795 let name = item.ident.name;
2797 debug!("(resolving item) resolving {}",
2798 token::get_name(name));
2802 // enum item: resolve all the variants' discrs,
2803 // then resolve the ty params
2804 ItemEnum(ref enum_def, ref generics) => {
2805 for variant in (*enum_def).variants.iter() {
2806 for dis_expr in variant.node.disr_expr.iter() {
2807 // resolve the discriminator expr
2809 self.with_constant_rib(|this| {
2810 this.resolve_expr(&**dis_expr);
2815 // n.b. the discr expr gets visited twice.
2816 // but maybe it's okay since the first time will signal an
2817 // error if there is one? -- tjc
2818 self.with_type_parameter_rib(HasTypeParameters(generics,
2823 this.resolve_type_parameters(&generics.ty_params);
2824 this.resolve_where_clause(&generics.where_clause);
2825 visit::walk_item(this, item);
2829 ItemTy(_, ref generics) => {
2830 self.with_type_parameter_rib(HasTypeParameters(generics,
2835 this.resolve_type_parameters(&generics.ty_params);
2836 visit::walk_item(this, item);
2842 ref implemented_traits,
2844 ref impl_items) => {
2845 self.resolve_implementation(item.id,
2852 ItemTrait(_, ref generics, ref bounds, ref trait_items) => {
2853 // Create a new rib for the self type.
2854 let mut self_type_rib = Rib::new(ItemRibKind);
2856 // plain insert (no renaming, types are not currently hygienic....)
2857 let name = self.type_self_name;
2858 self_type_rib.bindings.insert(name, DlDef(DefSelfTy(item.id)));
2859 self.type_ribs.push(self_type_rib);
2861 // Create a new rib for the trait-wide type parameters.
2862 self.with_type_parameter_rib(HasTypeParameters(generics,
2867 this.resolve_type_parameters(&generics.ty_params);
2868 this.resolve_where_clause(&generics.where_clause);
2870 this.resolve_type_parameter_bounds(item.id, bounds,
2873 for trait_item in (*trait_items).iter() {
2874 // Create a new rib for the trait_item-specific type
2877 // FIXME #4951: Do we need a node ID here?
2880 ast::RequiredMethod(ref ty_m) => {
2881 this.with_type_parameter_rib
2882 (HasTypeParameters(&ty_m.generics,
2885 MethodRibKind(item.id, RequiredMethod)),
2888 // Resolve the method-specific type
2890 this.resolve_type_parameters(
2891 &ty_m.generics.ty_params);
2892 this.resolve_where_clause(&ty_m.generics
2895 for argument in ty_m.decl.inputs.iter() {
2896 this.resolve_type(&*argument.ty);
2899 if let SelfExplicit(ref typ, _) = ty_m.explicit_self.node {
2900 this.resolve_type(&**typ)
2903 if let ast::Return(ref ret_ty) = ty_m.decl.output {
2904 this.resolve_type(&**ret_ty);
2908 ast::ProvidedMethod(ref m) => {
2909 this.resolve_method(MethodRibKind(item.id,
2910 ProvidedMethod(m.id)),
2913 ast::TypeTraitItem(ref data) => {
2914 this.resolve_type_parameter(&data.ty_param);
2915 visit::walk_trait_item(this, trait_item);
2921 self.type_ribs.pop();
2924 ItemStruct(ref struct_def, ref generics) => {
2925 self.resolve_struct(item.id,
2927 struct_def.fields[]);
2930 ItemMod(ref module_) => {
2931 self.with_scope(Some(name), |this| {
2932 this.resolve_module(module_, item.span, name,
2937 ItemForeignMod(ref foreign_module) => {
2938 self.with_scope(Some(name), |this| {
2939 for foreign_item in foreign_module.items.iter() {
2940 match foreign_item.node {
2941 ForeignItemFn(_, ref generics) => {
2942 this.with_type_parameter_rib(
2944 generics, FnSpace, foreign_item.id,
2946 |this| visit::walk_foreign_item(this,
2949 ForeignItemStatic(..) => {
2950 visit::walk_foreign_item(this,
2958 ItemFn(ref fn_decl, _, _, ref generics, ref block) => {
2959 self.resolve_function(ItemRibKind,
2969 ItemConst(..) | ItemStatic(..) => {
2970 self.with_constant_rib(|this| {
2971 visit::walk_item(this, item);
2976 // do nothing, these are just around to be encoded
2981 fn with_type_parameter_rib<F>(&mut self, type_parameters: TypeParameters, f: F) where
2982 F: FnOnce(&mut Resolver),
2984 match type_parameters {
2985 HasTypeParameters(generics, space, node_id, rib_kind) => {
2986 let mut function_type_rib = Rib::new(rib_kind);
2987 let mut seen_bindings = HashSet::new();
2988 for (index, type_parameter) in generics.ty_params.iter().enumerate() {
2989 let name = type_parameter.ident.name;
2990 debug!("with_type_parameter_rib: {} {}", node_id,
2993 if seen_bindings.contains(&name) {
2994 self.resolve_error(type_parameter.span,
2995 format!("the name `{}` is already \
2997 parameter in this type \
3002 seen_bindings.insert(name);
3004 let def_like = DlDef(DefTyParam(space,
3006 local_def(type_parameter.id),
3008 // Associate this type parameter with
3009 // the item that bound it
3010 self.record_def(type_parameter.id,
3011 (DefTyParamBinder(node_id), LastMod(AllPublic)));
3012 // plain insert (no renaming)
3013 function_type_rib.bindings.insert(name, def_like);
3015 self.type_ribs.push(function_type_rib);
3018 NoTypeParameters => {
3025 match type_parameters {
3026 HasTypeParameters(..) => { self.type_ribs.pop(); }
3027 NoTypeParameters => { }
3031 fn with_label_rib<F>(&mut self, f: F) where
3032 F: FnOnce(&mut Resolver),
3034 self.label_ribs.push(Rib::new(NormalRibKind));
3036 self.label_ribs.pop();
3039 fn with_constant_rib<F>(&mut self, f: F) where
3040 F: FnOnce(&mut Resolver),
3042 self.value_ribs.push(Rib::new(ConstantItemRibKind));
3043 self.type_ribs.push(Rib::new(ConstantItemRibKind));
3045 self.type_ribs.pop();
3046 self.value_ribs.pop();
3049 fn resolve_function(&mut self,
3051 optional_declaration: Option<&FnDecl>,
3052 type_parameters: TypeParameters,
3054 // Create a value rib for the function.
3055 let function_value_rib = Rib::new(rib_kind);
3056 self.value_ribs.push(function_value_rib);
3058 // Create a label rib for the function.
3059 let function_label_rib = Rib::new(rib_kind);
3060 self.label_ribs.push(function_label_rib);
3062 // If this function has type parameters, add them now.
3063 self.with_type_parameter_rib(type_parameters, |this| {
3064 // Resolve the type parameters.
3065 match type_parameters {
3066 NoTypeParameters => {
3069 HasTypeParameters(ref generics, _, _, _) => {
3070 this.resolve_type_parameters(&generics.ty_params);
3071 this.resolve_where_clause(&generics.where_clause);
3075 // Add each argument to the rib.
3076 match optional_declaration {
3080 Some(declaration) => {
3081 let mut bindings_list = HashMap::new();
3082 for argument in declaration.inputs.iter() {
3083 this.resolve_pattern(&*argument.pat,
3084 ArgumentIrrefutableMode,
3085 &mut bindings_list);
3087 this.resolve_type(&*argument.ty);
3089 debug!("(resolving function) recorded argument");
3092 if let ast::Return(ref ret_ty) = declaration.output {
3093 this.resolve_type(&**ret_ty);
3098 // Resolve the function body.
3099 this.resolve_block(&*block);
3101 debug!("(resolving function) leaving function");
3104 self.label_ribs.pop();
3105 self.value_ribs.pop();
3108 fn resolve_type_parameters(&mut self,
3109 type_parameters: &OwnedSlice<TyParam>) {
3110 for type_parameter in type_parameters.iter() {
3111 self.resolve_type_parameter(type_parameter);
3115 fn resolve_type_parameter(&mut self,
3116 type_parameter: &TyParam) {
3117 for bound in type_parameter.bounds.iter() {
3118 self.resolve_type_parameter_bound(type_parameter.id, bound,
3119 TraitBoundingTypeParameter);
3121 match type_parameter.default {
3122 Some(ref ty) => self.resolve_type(&**ty),
3127 fn resolve_type_parameter_bounds(&mut self,
3129 type_parameter_bounds: &OwnedSlice<TyParamBound>,
3130 reference_type: TraitReferenceType) {
3131 for type_parameter_bound in type_parameter_bounds.iter() {
3132 self.resolve_type_parameter_bound(id, type_parameter_bound,
3137 fn resolve_type_parameter_bound(&mut self,
3139 type_parameter_bound: &TyParamBound,
3140 reference_type: TraitReferenceType) {
3141 match *type_parameter_bound {
3142 TraitTyParamBound(ref tref, _) => {
3143 self.resolve_poly_trait_reference(id, tref, reference_type)
3145 RegionTyParamBound(..) => {}
3149 fn resolve_poly_trait_reference(&mut self,
3151 poly_trait_reference: &PolyTraitRef,
3152 reference_type: TraitReferenceType) {
3153 self.resolve_trait_reference(id, &poly_trait_reference.trait_ref, reference_type)
3156 fn resolve_trait_reference(&mut self,
3158 trait_reference: &TraitRef,
3159 reference_type: TraitReferenceType) {
3160 match self.resolve_path(id, &trait_reference.path, TypeNS, true) {
3162 let path_str = self.path_names_to_string(&trait_reference.path);
3163 let usage_str = match reference_type {
3164 TraitBoundingTypeParameter => "bound type parameter with",
3165 TraitImplementation => "implement",
3166 TraitDerivation => "derive",
3167 TraitObject => "reference",
3168 TraitQPath => "extract an associated type from",
3171 let msg = format!("attempt to {} a nonexistent trait `{}`", usage_str, path_str);
3172 self.resolve_error(trait_reference.path.span, msg[]);
3176 (DefTrait(_), _) => {
3177 debug!("(resolving trait) found trait def: {}", def);
3178 self.record_def(trait_reference.ref_id, def);
3181 self.resolve_error(trait_reference.path.span,
3182 format!("`{}` is not a trait",
3183 self.path_names_to_string(
3184 &trait_reference.path))[]);
3186 // If it's a typedef, give a note
3187 if let DefTy(..) = def {
3188 self.session.span_note(
3189 trait_reference.path.span,
3190 format!("`type` aliases cannot be used for traits")
3199 fn resolve_where_clause(&mut self, where_clause: &ast::WhereClause) {
3200 for predicate in where_clause.predicates.iter() {
3202 &ast::WherePredicate::BoundPredicate(ref bound_pred) => {
3203 self.resolve_type(&*bound_pred.bounded_ty);
3205 for bound in bound_pred.bounds.iter() {
3206 self.resolve_type_parameter_bound(bound_pred.bounded_ty.id, bound,
3207 TraitBoundingTypeParameter);
3210 &ast::WherePredicate::RegionPredicate(_) => {}
3211 &ast::WherePredicate::EqPredicate(ref eq_pred) => {
3212 match self.resolve_path(eq_pred.id, &eq_pred.path, TypeNS, true) {
3213 Some((def @ DefTyParam(..), last_private)) => {
3214 self.record_def(eq_pred.id, (def, last_private));
3217 self.resolve_error(eq_pred.path.span,
3218 "undeclared associated type");
3222 self.resolve_type(&*eq_pred.ty);
3228 fn resolve_struct(&mut self,
3230 generics: &Generics,
3231 fields: &[StructField]) {
3232 // If applicable, create a rib for the type parameters.
3233 self.with_type_parameter_rib(HasTypeParameters(generics,
3238 // Resolve the type parameters.
3239 this.resolve_type_parameters(&generics.ty_params);
3240 this.resolve_where_clause(&generics.where_clause);
3243 for field in fields.iter() {
3244 this.resolve_type(&*field.node.ty);
3249 // Does this really need to take a RibKind or is it always going
3250 // to be NormalRibKind?
3251 fn resolve_method(&mut self,
3253 method: &ast::Method) {
3254 let method_generics = method.pe_generics();
3255 let type_parameters = HasTypeParameters(method_generics,
3260 if let SelfExplicit(ref typ, _) = method.pe_explicit_self().node {
3261 self.resolve_type(&**typ);
3264 self.resolve_function(rib_kind,
3265 Some(method.pe_fn_decl()),
3270 fn with_current_self_type<T, F>(&mut self, self_type: &Ty, f: F) -> T where
3271 F: FnOnce(&mut Resolver) -> T,
3273 // Handle nested impls (inside fn bodies)
3274 let previous_value = replace(&mut self.current_self_type, Some(self_type.clone()));
3275 let result = f(self);
3276 self.current_self_type = previous_value;
3280 fn with_optional_trait_ref<T, F>(&mut self, id: NodeId,
3281 opt_trait_ref: &Option<TraitRef>,
3283 F: FnOnce(&mut Resolver) -> T,
3285 let new_val = match *opt_trait_ref {
3286 Some(ref trait_ref) => {
3287 self.resolve_trait_reference(id, trait_ref, TraitImplementation);
3289 match self.def_map.borrow().get(&trait_ref.ref_id) {
3291 let did = def.def_id();
3292 Some((did, trait_ref.clone()))
3299 let original_trait_ref = replace(&mut self.current_trait_ref, new_val);
3300 let result = f(self);
3301 self.current_trait_ref = original_trait_ref;
3305 fn resolve_implementation(&mut self,
3307 generics: &Generics,
3308 opt_trait_reference: &Option<TraitRef>,
3310 impl_items: &[ImplItem]) {
3311 // If applicable, create a rib for the type parameters.
3312 self.with_type_parameter_rib(HasTypeParameters(generics,
3317 // Resolve the type parameters.
3318 this.resolve_type_parameters(&generics.ty_params);
3319 this.resolve_where_clause(&generics.where_clause);
3321 // Resolve the trait reference, if necessary.
3322 this.with_optional_trait_ref(id, opt_trait_reference, |this| {
3323 // Resolve the self type.
3324 this.resolve_type(self_type);
3326 this.with_current_self_type(self_type, |this| {
3327 for impl_item in impl_items.iter() {
3329 MethodImplItem(ref method) => {
3330 // If this is a trait impl, ensure the method
3332 this.check_trait_item(method.pe_ident().name,
3335 // We also need a new scope for the method-
3336 // specific type parameters.
3337 this.resolve_method(
3338 MethodRibKind(id, ProvidedMethod(method.id)),
3341 TypeImplItem(ref typedef) => {
3342 // If this is a trait impl, ensure the method
3344 this.check_trait_item(typedef.ident.name,
3347 this.resolve_type(&*typedef.typ);
3355 // Check that the current type is indeed a type, if we have an anonymous impl
3356 if opt_trait_reference.is_none() {
3357 match self_type.node {
3358 // TyPath is the only thing that we handled in `build_reduced_graph_for_item`,
3359 // where we created a module with the name of the type in order to implement
3360 // an anonymous trait. In the case that the path does not resolve to an actual
3361 // type, the result will be that the type name resolves to a module but not
3362 // a type (shadowing any imported modules or types with this name), leading
3363 // to weird user-visible bugs. So we ward this off here. See #15060.
3364 TyPath(ref path, path_id) => {
3365 match self.def_map.borrow().get(&path_id) {
3366 // FIXME: should we catch other options and give more precise errors?
3367 Some(&DefMod(_)) => {
3368 self.resolve_error(path.span, "inherent implementations are not \
3369 allowed for types not defined in \
3370 the current module");
3380 fn check_trait_item(&self, name: Name, span: Span) {
3381 // If there is a TraitRef in scope for an impl, then the method must be in the trait.
3382 for &(did, ref trait_ref) in self.current_trait_ref.iter() {
3383 if self.trait_item_map.get(&(name, did)).is_none() {
3384 let path_str = self.path_names_to_string(&trait_ref.path);
3385 self.resolve_error(span,
3386 format!("method `{}` is not a member of trait `{}`",
3387 token::get_name(name),
3393 fn resolve_module(&mut self, module: &Mod, _span: Span,
3394 _name: Name, id: NodeId) {
3395 // Write the implementations in scope into the module metadata.
3396 debug!("(resolving module) resolving module ID {}", id);
3397 visit::walk_mod(self, module);
3400 fn resolve_local(&mut self, local: &Local) {
3401 // Resolve the type.
3402 if let Some(ref ty) = local.ty {
3403 self.resolve_type(&**ty);
3406 // Resolve the initializer, if necessary.
3411 Some(ref initializer) => {
3412 self.resolve_expr(&**initializer);
3416 // Resolve the pattern.
3417 let mut bindings_list = HashMap::new();
3418 self.resolve_pattern(&*local.pat,
3419 LocalIrrefutableMode,
3420 &mut bindings_list);
3423 // build a map from pattern identifiers to binding-info's.
3424 // this is done hygienically. This could arise for a macro
3425 // that expands into an or-pattern where one 'x' was from the
3426 // user and one 'x' came from the macro.
3427 fn binding_mode_map(&mut self, pat: &Pat) -> BindingMap {
3428 let mut result = HashMap::new();
3429 pat_bindings(&self.def_map, pat, |binding_mode, _id, sp, path1| {
3430 let name = mtwt::resolve(path1.node);
3431 result.insert(name, BindingInfo {
3433 binding_mode: binding_mode
3439 // check that all of the arms in an or-pattern have exactly the
3440 // same set of bindings, with the same binding modes for each.
3441 fn check_consistent_bindings(&mut self, arm: &Arm) {
3442 if arm.pats.len() == 0 {
3445 let map_0 = self.binding_mode_map(&*arm.pats[0]);
3446 for (i, p) in arm.pats.iter().enumerate() {
3447 let map_i = self.binding_mode_map(&**p);
3449 for (&key, &binding_0) in map_0.iter() {
3450 match map_i.get(&key) {
3454 format!("variable `{}` from pattern #1 is \
3455 not bound in pattern #{}",
3456 token::get_name(key),
3459 Some(binding_i) => {
3460 if binding_0.binding_mode != binding_i.binding_mode {
3463 format!("variable `{}` is bound with different \
3464 mode in pattern #{} than in pattern #1",
3465 token::get_name(key),
3472 for (&key, &binding) in map_i.iter() {
3473 if !map_0.contains_key(&key) {
3476 format!("variable `{}` from pattern {}{} is \
3477 not bound in pattern {}1",
3478 token::get_name(key),
3479 "#", i + 1, "#")[]);
3485 fn resolve_arm(&mut self, arm: &Arm) {
3486 self.value_ribs.push(Rib::new(NormalRibKind));
3488 let mut bindings_list = HashMap::new();
3489 for pattern in arm.pats.iter() {
3490 self.resolve_pattern(&**pattern, RefutableMode, &mut bindings_list);
3493 // This has to happen *after* we determine which
3494 // pat_idents are variants
3495 self.check_consistent_bindings(arm);
3497 visit::walk_expr_opt(self, &arm.guard);
3498 self.resolve_expr(&*arm.body);
3500 self.value_ribs.pop();
3503 fn resolve_block(&mut self, block: &Block) {
3504 debug!("(resolving block) entering block");
3505 self.value_ribs.push(Rib::new(NormalRibKind));
3507 // Move down in the graph, if there's an anonymous module rooted here.
3508 let orig_module = self.current_module.clone();
3509 match orig_module.anonymous_children.borrow().get(&block.id) {
3510 None => { /* Nothing to do. */ }
3511 Some(anonymous_module) => {
3512 debug!("(resolving block) found anonymous module, moving \
3514 self.current_module = anonymous_module.clone();
3518 // Descend into the block.
3519 visit::walk_block(self, block);
3522 self.current_module = orig_module;
3524 self.value_ribs.pop();
3525 debug!("(resolving block) leaving block");
3528 fn resolve_type(&mut self, ty: &Ty) {
3530 // Like path expressions, the interpretation of path types depends
3531 // on whether the path has multiple elements in it or not.
3533 TyPath(ref path, path_id) => {
3534 // This is a path in the type namespace. Walk through scopes
3536 let mut result_def = None;
3538 // First, check to see whether the name is a primitive type.
3539 if path.segments.len() == 1 {
3540 let id = path.segments.last().unwrap().identifier;
3542 match self.primitive_type_table
3546 Some(&primitive_type) => {
3548 Some((DefPrimTy(primitive_type), LastMod(AllPublic)));
3550 if path.segments[0].parameters.has_lifetimes() {
3551 span_err!(self.session, path.span, E0157,
3552 "lifetime parameters are not allowed on this type");
3553 } else if !path.segments[0].parameters.is_empty() {
3554 span_err!(self.session, path.span, E0153,
3555 "type parameters are not allowed on this type");
3566 match self.resolve_path(ty.id, path, TypeNS, true) {
3568 debug!("(resolving type) resolved `{}` to \
3570 token::get_ident(path.segments.last().unwrap() .identifier),
3572 result_def = Some(def);
3579 Some(_) => {} // Continue.
3584 // Write the result into the def map.
3585 debug!("(resolving type) writing resolution for `{}` \
3587 self.path_names_to_string(path),
3589 self.record_def(path_id, def);
3592 let msg = format!("use of undeclared type name `{}`",
3593 self.path_names_to_string(path));
3594 self.resolve_error(ty.span, msg[]);
3599 TyObjectSum(ref ty, ref bound_vec) => {
3600 self.resolve_type(&**ty);
3601 self.resolve_type_parameter_bounds(ty.id, bound_vec,
3602 TraitBoundingTypeParameter);
3605 TyQPath(ref qpath) => {
3606 self.resolve_type(&*qpath.self_type);
3607 self.resolve_trait_reference(ty.id, &*qpath.trait_ref, TraitQPath);
3610 TyPolyTraitRef(ref bounds) => {
3611 self.resolve_type_parameter_bounds(
3615 visit::walk_ty(self, ty);
3618 // Just resolve embedded types.
3619 visit::walk_ty(self, ty);
3624 fn resolve_pattern(&mut self,
3626 mode: PatternBindingMode,
3627 // Maps idents to the node ID for the (outermost)
3628 // pattern that binds them
3629 bindings_list: &mut HashMap<Name, NodeId>) {
3630 let pat_id = pattern.id;
3631 walk_pat(pattern, |pattern| {
3632 match pattern.node {
3633 PatIdent(binding_mode, ref path1, _) => {
3635 // The meaning of pat_ident with no type parameters
3636 // depends on whether an enum variant or unit-like struct
3637 // with that name is in scope. The probing lookup has to
3638 // be careful not to emit spurious errors. Only matching
3639 // patterns (match) can match nullary variants or
3640 // unit-like structs. For binding patterns (let), matching
3641 // such a value is simply disallowed (since it's rarely
3644 let ident = path1.node;
3645 let renamed = mtwt::resolve(ident);
3647 match self.resolve_bare_identifier_pattern(ident.name, pattern.span) {
3648 FoundStructOrEnumVariant(ref def, lp)
3649 if mode == RefutableMode => {
3650 debug!("(resolving pattern) resolving `{}` to \
3651 struct or enum variant",
3652 token::get_name(renamed));
3654 self.enforce_default_binding_mode(
3658 self.record_def(pattern.id, (def.clone(), lp));
3660 FoundStructOrEnumVariant(..) => {
3663 format!("declaration of `{}` shadows an enum \
3664 variant or unit-like struct in \
3666 token::get_name(renamed))[]);
3668 FoundConst(ref def, lp) if mode == RefutableMode => {
3669 debug!("(resolving pattern) resolving `{}` to \
3671 token::get_name(renamed));
3673 self.enforce_default_binding_mode(
3677 self.record_def(pattern.id, (def.clone(), lp));
3680 self.resolve_error(pattern.span,
3681 "only irrefutable patterns \
3684 BareIdentifierPatternUnresolved => {
3685 debug!("(resolving pattern) binding `{}`",
3686 token::get_name(renamed));
3688 let def = DefLocal(pattern.id);
3690 // Record the definition so that later passes
3691 // will be able to distinguish variants from
3692 // locals in patterns.
3694 self.record_def(pattern.id, (def, LastMod(AllPublic)));
3696 // Add the binding to the local ribs, if it
3697 // doesn't already exist in the bindings list. (We
3698 // must not add it if it's in the bindings list
3699 // because that breaks the assumptions later
3700 // passes make about or-patterns.)
3701 if !bindings_list.contains_key(&renamed) {
3702 let this = &mut *self;
3703 let last_rib = this.value_ribs.last_mut().unwrap();
3704 last_rib.bindings.insert(renamed, DlDef(def));
3705 bindings_list.insert(renamed, pat_id);
3706 } else if mode == ArgumentIrrefutableMode &&
3707 bindings_list.contains_key(&renamed) {
3708 // Forbid duplicate bindings in the same
3710 self.resolve_error(pattern.span,
3711 format!("identifier `{}` \
3719 } else if bindings_list.get(&renamed) ==
3721 // Then this is a duplicate variable in the
3722 // same disjunction, which is an error.
3723 self.resolve_error(pattern.span,
3724 format!("identifier `{}` is bound \
3725 more than once in the same \
3727 token::get_ident(ident))[]);
3729 // Else, not bound in the same pattern: do
3735 PatEnum(ref path, _) => {
3736 // This must be an enum variant, struct or const.
3737 match self.resolve_path(pat_id, path, ValueNS, false) {
3738 Some(def @ (DefVariant(..), _)) |
3739 Some(def @ (DefStruct(..), _)) |
3740 Some(def @ (DefConst(..), _)) => {
3741 self.record_def(pattern.id, def);
3743 Some((DefStatic(..), _)) => {
3744 self.resolve_error(path.span,
3745 "static variables cannot be \
3746 referenced in a pattern, \
3747 use a `const` instead");
3750 self.resolve_error(path.span,
3751 format!("`{}` is not an enum variant, struct or const",
3753 path.segments.last().unwrap().identifier))[]);
3756 self.resolve_error(path.span,
3757 format!("unresolved enum variant, struct or const `{}`",
3759 path.segments.last().unwrap().identifier))[]);
3763 // Check the types in the path pattern.
3764 for ty in path.segments
3766 .flat_map(|s| s.parameters.types().into_iter()) {
3767 self.resolve_type(&**ty);
3771 PatLit(ref expr) => {
3772 self.resolve_expr(&**expr);
3775 PatRange(ref first_expr, ref last_expr) => {
3776 self.resolve_expr(&**first_expr);
3777 self.resolve_expr(&**last_expr);
3780 PatStruct(ref path, _, _) => {
3781 match self.resolve_path(pat_id, path, TypeNS, false) {
3782 Some(definition) => {
3783 self.record_def(pattern.id, definition);
3786 debug!("(resolving pattern) didn't find struct \
3788 let msg = format!("`{}` does not name a structure",
3789 self.path_names_to_string(path));
3790 self.resolve_error(path.span, msg[]);
3803 fn resolve_bare_identifier_pattern(&mut self, name: Name, span: Span)
3804 -> BareIdentifierPatternResolution {
3805 let module = self.current_module.clone();
3806 match self.resolve_item_in_lexical_scope(module,
3809 Success((target, _)) => {
3810 debug!("(resolve bare identifier pattern) succeeded in \
3812 token::get_name(name),
3813 target.bindings.value_def.borrow());
3814 match *target.bindings.value_def.borrow() {
3816 panic!("resolved name in the value namespace to a \
3817 set of name bindings with no def?!");
3820 // For the two success cases, this lookup can be
3821 // considered as not having a private component because
3822 // the lookup happened only within the current module.
3824 def @ DefVariant(..) | def @ DefStruct(..) => {
3825 return FoundStructOrEnumVariant(def, LastMod(AllPublic));
3827 def @ DefConst(..) => {
3828 return FoundConst(def, LastMod(AllPublic));
3831 self.resolve_error(span,
3832 "static variables cannot be \
3833 referenced in a pattern, \
3834 use a `const` instead");
3835 return BareIdentifierPatternUnresolved;
3838 return BareIdentifierPatternUnresolved;
3846 panic!("unexpected indeterminate result");
3850 Some((span, msg)) => {
3851 self.resolve_error(span, format!("failed to resolve: {}",
3857 debug!("(resolve bare identifier pattern) failed to find {}",
3858 token::get_name(name));
3859 return BareIdentifierPatternUnresolved;
3864 /// If `check_ribs` is true, checks the local definitions first; i.e.
3865 /// doesn't skip straight to the containing module.
3866 fn resolve_path(&mut self,
3869 namespace: Namespace,
3870 check_ribs: bool) -> Option<(Def, LastPrivate)> {
3871 // First, resolve the types and associated type bindings.
3872 for ty in path.segments.iter().flat_map(|s| s.parameters.types().into_iter()) {
3873 self.resolve_type(&**ty);
3875 for binding in path.segments.iter().flat_map(|s| s.parameters.bindings().into_iter()) {
3876 self.resolve_type(&*binding.ty);
3879 // A special case for sugared associated type paths `T::A` where `T` is
3880 // a type parameter and `A` is an associated type on some bound of `T`.
3881 if namespace == TypeNS && path.segments.len() == 2 {
3882 match self.resolve_identifier(path.segments[0].identifier,
3886 Some((def, last_private)) => {
3888 DefTyParam(_, _, did, _) => {
3889 let def = DefAssociatedPath(TyParamProvenance::FromParam(did),
3890 path.segments.last()
3891 .unwrap().identifier);
3892 return Some((def, last_private));
3895 let def = DefAssociatedPath(TyParamProvenance::FromSelf(local_def(nid)),
3896 path.segments.last()
3897 .unwrap().identifier);
3898 return Some((def, last_private));
3908 return self.resolve_crate_relative_path(path, namespace);
3911 // Try to find a path to an item in a module.
3912 let unqualified_def =
3913 self.resolve_identifier(path.segments.last().unwrap().identifier,
3918 if path.segments.len() > 1 {
3919 let def = self.resolve_module_relative_path(path, namespace);
3920 match (def, unqualified_def) {
3921 (Some((ref d, _)), Some((ref ud, _))) if *d == *ud => {
3923 .add_lint(lint::builtin::UNUSED_QUALIFICATIONS,
3926 "unnecessary qualification".to_string());
3934 return unqualified_def;
3937 // resolve a single identifier (used as a varref)
3938 fn resolve_identifier(&mut self,
3940 namespace: Namespace,
3943 -> Option<(Def, LastPrivate)> {
3945 match self.resolve_identifier_in_local_ribs(identifier,
3949 return Some((def, LastMod(AllPublic)));
3957 return self.resolve_item_by_name_in_lexical_scope(identifier.name, namespace);
3960 // FIXME #4952: Merge me with resolve_name_in_module?
3961 fn resolve_definition_of_name_in_module(&mut self,
3962 containing_module: Rc<Module>,
3964 namespace: Namespace)
3966 // First, search children.
3967 build_reduced_graph::populate_module_if_necessary(self, &containing_module);
3969 match containing_module.children.borrow().get(&name) {
3970 Some(child_name_bindings) => {
3971 match child_name_bindings.def_for_namespace(namespace) {
3973 // Found it. Stop the search here.
3974 let p = child_name_bindings.defined_in_public_namespace(
3976 let lp = if p {LastMod(AllPublic)} else {
3977 LastMod(DependsOn(def.def_id()))
3979 return ChildNameDefinition(def, lp);
3987 // Next, search import resolutions.
3988 match containing_module.import_resolutions.borrow().get(&name) {
3989 Some(import_resolution) if import_resolution.is_public => {
3990 if let Some(target) = (*import_resolution).target_for_namespace(namespace) {
3991 match target.bindings.def_for_namespace(namespace) {
3994 let id = import_resolution.id(namespace);
3995 // track imports and extern crates as well
3996 self.used_imports.insert((id, namespace));
3997 self.record_import_use(id, name);
3998 match target.target_module.def_id.get() {
3999 Some(DefId{krate: kid, ..}) => {
4000 self.used_crates.insert(kid);
4004 return ImportNameDefinition(def, LastMod(AllPublic));
4007 // This can happen with external impls, due to
4008 // the imperfect way we read the metadata.
4013 Some(..) | None => {} // Continue.
4016 // Finally, search through external children.
4017 if namespace == TypeNS {
4018 if let Some(module) = containing_module.external_module_children.borrow()
4019 .get(&name).cloned() {
4020 if let Some(def_id) = module.def_id.get() {
4021 // track used crates
4022 self.used_crates.insert(def_id.krate);
4023 let lp = if module.is_public {LastMod(AllPublic)} else {
4024 LastMod(DependsOn(def_id))
4026 return ChildNameDefinition(DefMod(def_id), lp);
4031 return NoNameDefinition;
4034 // resolve a "module-relative" path, e.g. a::b::c
4035 fn resolve_module_relative_path(&mut self,
4037 namespace: Namespace)
4038 -> Option<(Def, LastPrivate)> {
4039 let module_path = path.segments.init().iter()
4040 .map(|ps| ps.identifier.name)
4041 .collect::<Vec<_>>();
4043 let containing_module;
4045 let module = self.current_module.clone();
4046 match self.resolve_module_path(module,
4052 let (span, msg) = match err {
4053 Some((span, msg)) => (span, msg),
4055 let msg = format!("Use of undeclared type or module `{}`",
4056 self.names_to_string(module_path.as_slice()));
4061 self.resolve_error(span, format!("failed to resolve. {}",
4065 Indeterminate => panic!("indeterminate unexpected"),
4066 Success((resulting_module, resulting_last_private)) => {
4067 containing_module = resulting_module;
4068 last_private = resulting_last_private;
4072 let name = path.segments.last().unwrap().identifier.name;
4073 let def = match self.resolve_definition_of_name_in_module(containing_module.clone(),
4076 NoNameDefinition => {
4077 // We failed to resolve the name. Report an error.
4080 ChildNameDefinition(def, lp) | ImportNameDefinition(def, lp) => {
4081 (def, last_private.or(lp))
4084 if let Some(DefId{krate: kid, ..}) = containing_module.def_id.get() {
4085 self.used_crates.insert(kid);
4090 /// Invariant: This must be called only during main resolution, not during
4091 /// import resolution.
4092 fn resolve_crate_relative_path(&mut self,
4094 namespace: Namespace)
4095 -> Option<(Def, LastPrivate)> {
4096 let module_path = path.segments.init().iter()
4097 .map(|ps| ps.identifier.name)
4098 .collect::<Vec<_>>();
4100 let root_module = self.graph_root.get_module();
4102 let containing_module;
4104 match self.resolve_module_path_from_root(root_module,
4109 LastMod(AllPublic)) {
4111 let (span, msg) = match err {
4112 Some((span, msg)) => (span, msg),
4114 let msg = format!("Use of undeclared module `::{}`",
4115 self.names_to_string(module_path[]));
4120 self.resolve_error(span, format!("failed to resolve. {}",
4126 panic!("indeterminate unexpected");
4129 Success((resulting_module, resulting_last_private)) => {
4130 containing_module = resulting_module;
4131 last_private = resulting_last_private;
4135 let name = path.segments.last().unwrap().identifier.name;
4136 match self.resolve_definition_of_name_in_module(containing_module,
4139 NoNameDefinition => {
4140 // We failed to resolve the name. Report an error.
4143 ChildNameDefinition(def, lp) | ImportNameDefinition(def, lp) => {
4144 return Some((def, last_private.or(lp)));
4149 fn resolve_identifier_in_local_ribs(&mut self,
4151 namespace: Namespace,
4154 // Check the local set of ribs.
4155 let search_result = match namespace {
4157 let renamed = mtwt::resolve(ident);
4158 self.search_ribs(self.value_ribs.as_slice(), renamed, span)
4161 let name = ident.name;
4162 self.search_ribs(self.type_ribs[], name, span)
4166 match search_result {
4167 Some(DlDef(def)) => {
4168 debug!("(resolving path in local ribs) resolved `{}` to \
4170 token::get_ident(ident),
4174 Some(DlField) | Some(DlImpl(_)) | None => {
4180 fn resolve_item_by_name_in_lexical_scope(&mut self,
4182 namespace: Namespace)
4183 -> Option<(Def, LastPrivate)> {
4185 let module = self.current_module.clone();
4186 match self.resolve_item_in_lexical_scope(module,
4189 Success((target, _)) => {
4190 match (*target.bindings).def_for_namespace(namespace) {
4192 // This can happen if we were looking for a type and
4193 // found a module instead. Modules don't have defs.
4194 debug!("(resolving item path by identifier in lexical \
4195 scope) failed to resolve {} after success...",
4196 token::get_name(name));
4200 debug!("(resolving item path in lexical scope) \
4201 resolved `{}` to item",
4202 token::get_name(name));
4203 // This lookup is "all public" because it only searched
4204 // for one identifier in the current module (couldn't
4205 // have passed through reexports or anything like that.
4206 return Some((def, LastMod(AllPublic)));
4211 panic!("unexpected indeterminate result");
4215 Some((span, msg)) =>
4216 self.resolve_error(span, format!("failed to resolve. {}",
4221 debug!("(resolving item path by identifier in lexical scope) \
4222 failed to resolve {}", token::get_name(name));
4228 fn with_no_errors<T, F>(&mut self, f: F) -> T where
4229 F: FnOnce(&mut Resolver) -> T,
4231 self.emit_errors = false;
4233 self.emit_errors = true;
4237 fn resolve_error(&self, span: Span, s: &str) {
4238 if self.emit_errors {
4239 self.session.span_err(span, s);
4243 fn find_fallback_in_self_type(&mut self, name: Name) -> FallbackSuggestion {
4244 fn extract_path_and_node_id(t: &Ty, allow: FallbackChecks)
4245 -> Option<(Path, NodeId, FallbackChecks)> {
4247 TyPath(ref path, node_id) => Some((path.clone(), node_id, allow)),
4248 TyPtr(ref mut_ty) => extract_path_and_node_id(&*mut_ty.ty, OnlyTraitAndStatics),
4249 TyRptr(_, ref mut_ty) => extract_path_and_node_id(&*mut_ty.ty, allow),
4250 // This doesn't handle the remaining `Ty` variants as they are not
4251 // that commonly the self_type, it might be interesting to provide
4252 // support for those in future.
4257 fn get_module(this: &mut Resolver, span: Span, name_path: &[ast::Name])
4258 -> Option<Rc<Module>> {
4259 let root = this.current_module.clone();
4260 let last_name = name_path.last().unwrap();
4262 if name_path.len() == 1 {
4263 match this.primitive_type_table.primitive_types.get(last_name) {
4266 match this.current_module.children.borrow().get(last_name) {
4267 Some(child) => child.get_module_if_available(),
4273 match this.resolve_module_path(root,
4278 Success((module, _)) => Some(module),
4284 let (path, node_id, allowed) = match self.current_self_type {
4285 Some(ref ty) => match extract_path_and_node_id(ty, Everything) {
4287 None => return NoSuggestion,
4289 None => return NoSuggestion,
4292 if allowed == Everything {
4293 // Look for a field with the same name in the current self_type.
4294 match self.def_map.borrow().get(&node_id) {
4295 Some(&DefTy(did, _))
4296 | Some(&DefStruct(did))
4297 | Some(&DefVariant(_, did, _)) => match self.structs.get(&did) {
4300 if fields.iter().any(|&field_name| name == field_name) {
4305 _ => {} // Self type didn't resolve properly
4309 let name_path = path.segments.iter().map(|seg| seg.identifier.name).collect::<Vec<_>>();
4311 // Look for a method in the current self type's impl module.
4312 match get_module(self, path.span, name_path[]) {
4313 Some(module) => match module.children.borrow().get(&name) {
4315 let p_str = self.path_names_to_string(&path);
4316 match binding.def_for_namespace(ValueNS) {
4317 Some(DefStaticMethod(_, provenance)) => {
4319 FromImpl(_) => return StaticMethod(p_str),
4320 FromTrait(_) => unreachable!()
4323 Some(DefMethod(_, None, _)) if allowed == Everything => return Method,
4324 Some(DefMethod(_, Some(_), _)) => return TraitItem,
4333 // Look for a method in the current trait.
4334 match self.current_trait_ref {
4335 Some((did, ref trait_ref)) => {
4336 let path_str = self.path_names_to_string(&trait_ref.path);
4338 match self.trait_item_map.get(&(name, did)) {
4339 Some(&StaticMethodTraitItemKind) => {
4340 return TraitMethod(path_str)
4342 Some(_) => return TraitItem,
4352 fn find_best_match_for_name(&mut self, name: &str, max_distance: uint)
4354 let this = &mut *self;
4356 let mut maybes: Vec<token::InternedString> = Vec::new();
4357 let mut values: Vec<uint> = Vec::new();
4359 for rib in this.value_ribs.iter().rev() {
4360 for (&k, _) in rib.bindings.iter() {
4361 maybes.push(token::get_name(k));
4362 values.push(uint::MAX);
4366 let mut smallest = 0;
4367 for (i, other) in maybes.iter().enumerate() {
4368 values[i] = lev_distance(name, other.get());
4370 if values[i] <= values[smallest] {
4375 if values.len() > 0 &&
4376 values[smallest] != uint::MAX &&
4377 values[smallest] < name.len() + 2 &&
4378 values[smallest] <= max_distance &&
4379 name != maybes[smallest].get() {
4381 Some(maybes[smallest].get().to_string())
4388 fn resolve_expr(&mut self, expr: &Expr) {
4389 // First, record candidate traits for this expression if it could
4390 // result in the invocation of a method call.
4392 self.record_candidate_traits_for_expr_if_necessary(expr);
4394 // Next, resolve the node.
4396 // The interpretation of paths depends on whether the path has
4397 // multiple elements in it or not.
4399 ExprPath(ref path) => {
4400 // This is a local path in the value namespace. Walk through
4401 // scopes looking for it.
4403 let path_name = self.path_names_to_string(path);
4405 match self.resolve_path(expr.id, path, ValueNS, true) {
4406 // Check if struct variant
4407 Some((DefVariant(_, _, true), _)) => {
4408 self.resolve_error(expr.span,
4409 format!("`{}` is a struct variant name, but \
4411 uses it like a function name",
4412 path_name).as_slice());
4414 self.session.span_help(expr.span,
4415 format!("Did you mean to write: \
4416 `{} {{ /* fields */ }}`?",
4417 path_name).as_slice());
4420 // Write the result into the def map.
4421 debug!("(resolving expr) resolved `{}`",
4424 self.record_def(expr.id, def);
4427 // Be helpful if the name refers to a struct
4428 // (The pattern matching def_tys where the id is in self.structs
4429 // matches on regular structs while excluding tuple- and enum-like
4430 // structs, which wouldn't result in this error.)
4431 match self.with_no_errors(|this|
4432 this.resolve_path(expr.id, path, TypeNS, false)) {
4433 Some((DefTy(struct_id, _), _))
4434 if self.structs.contains_key(&struct_id) => {
4435 self.resolve_error(expr.span,
4436 format!("`{}` is a structure name, but \
4438 uses it like a function name",
4439 path_name).as_slice());
4441 self.session.span_help(expr.span,
4442 format!("Did you mean to write: \
4443 `{} {{ /* fields */ }}`?",
4444 path_name).as_slice());
4448 let mut method_scope = false;
4449 self.value_ribs.iter().rev().all(|rib| {
4450 let res = match *rib {
4451 Rib { bindings: _, kind: MethodRibKind(_, _) } => true,
4452 Rib { bindings: _, kind: ItemRibKind } => false,
4453 _ => return true, // Keep advancing
4457 false // Stop advancing
4460 if method_scope && token::get_name(self.self_name).get()
4464 "`self` is not available \
4465 in a static method. Maybe a \
4466 `self` argument is missing?");
4468 let last_name = path.segments.last().unwrap().identifier.name;
4469 let mut msg = match self.find_fallback_in_self_type(last_name) {
4471 // limit search to 5 to reduce the number
4472 // of stupid suggestions
4473 self.find_best_match_for_name(path_name.as_slice(), 5)
4474 .map_or("".to_string(),
4475 |x| format!("`{}`", x))
4478 format!("`self.{}`", path_name),
4481 format!("to call `self.{}`", path_name),
4482 TraitMethod(path_str)
4483 | StaticMethod(path_str) =>
4484 format!("to call `{}::{}`", path_str, path_name)
4488 msg = format!(". Did you mean {}?", msg)
4493 format!("unresolved name `{}`{}",
4502 visit::walk_expr(self, expr);
4505 ExprClosure(capture_clause, _, ref fn_decl, ref block) => {
4506 self.capture_mode_map.insert(expr.id, capture_clause);
4507 self.resolve_function(ClosureRibKind(expr.id, ast::DUMMY_NODE_ID),
4508 Some(&**fn_decl), NoTypeParameters,
4512 ExprStruct(ref path, _, _) => {
4513 // Resolve the path to the structure it goes to. We don't
4514 // check to ensure that the path is actually a structure; that
4515 // is checked later during typeck.
4516 match self.resolve_path(expr.id, path, TypeNS, false) {
4517 Some(definition) => self.record_def(expr.id, definition),
4519 debug!("(resolving expression) didn't find struct \
4521 let msg = format!("`{}` does not name a structure",
4522 self.path_names_to_string(path));
4523 self.resolve_error(path.span, msg[]);
4527 visit::walk_expr(self, expr);
4530 ExprLoop(_, Some(label)) | ExprWhile(_, _, Some(label)) => {
4531 self.with_label_rib(|this| {
4532 let def_like = DlDef(DefLabel(expr.id));
4535 let rib = this.label_ribs.last_mut().unwrap();
4536 let renamed = mtwt::resolve(label);
4537 rib.bindings.insert(renamed, def_like);
4540 visit::walk_expr(this, expr);
4544 ExprForLoop(ref pattern, ref head, ref body, optional_label) => {
4545 self.resolve_expr(&**head);
4547 self.value_ribs.push(Rib::new(NormalRibKind));
4549 self.resolve_pattern(&**pattern,
4550 LocalIrrefutableMode,
4551 &mut HashMap::new());
4553 match optional_label {
4557 .push(Rib::new(NormalRibKind));
4558 let def_like = DlDef(DefLabel(expr.id));
4561 let rib = self.label_ribs.last_mut().unwrap();
4562 let renamed = mtwt::resolve(label);
4563 rib.bindings.insert(renamed, def_like);
4568 self.resolve_block(&**body);
4570 if optional_label.is_some() {
4571 drop(self.label_ribs.pop())
4574 self.value_ribs.pop();
4577 ExprBreak(Some(label)) | ExprAgain(Some(label)) => {
4578 let renamed = mtwt::resolve(label);
4579 match self.search_label(renamed) {
4583 format!("use of undeclared label `{}`",
4584 token::get_ident(label))[])
4586 Some(DlDef(def @ DefLabel(_))) => {
4587 // Since this def is a label, it is never read.
4588 self.record_def(expr.id, (def, LastMod(AllPublic)))
4591 self.session.span_bug(expr.span,
4592 "label wasn't mapped to a \
4599 visit::walk_expr(self, expr);
4604 fn record_candidate_traits_for_expr_if_necessary(&mut self, expr: &Expr) {
4606 ExprField(_, ident) => {
4607 // FIXME(#6890): Even though you can't treat a method like a
4608 // field, we need to add any trait methods we find that match
4609 // the field name so that we can do some nice error reporting
4610 // later on in typeck.
4611 let traits = self.search_for_traits_containing_method(ident.node.name);
4612 self.trait_map.insert(expr.id, traits);
4614 ExprMethodCall(ident, _, _) => {
4615 debug!("(recording candidate traits for expr) recording \
4618 let traits = self.search_for_traits_containing_method(ident.node.name);
4619 self.trait_map.insert(expr.id, traits);
4627 fn search_for_traits_containing_method(&mut self, name: Name) -> Vec<DefId> {
4628 debug!("(searching for traits containing method) looking for '{}'",
4629 token::get_name(name));
4631 fn add_trait_info(found_traits: &mut Vec<DefId>,
4632 trait_def_id: DefId,
4634 debug!("(adding trait info) found trait {}:{} for method '{}'",
4637 token::get_name(name));
4638 found_traits.push(trait_def_id);
4641 let mut found_traits = Vec::new();
4642 let mut search_module = self.current_module.clone();
4644 // Look for the current trait.
4645 match self.current_trait_ref {
4646 Some((trait_def_id, _)) => {
4647 if self.trait_item_map.contains_key(&(name, trait_def_id)) {
4648 add_trait_info(&mut found_traits, trait_def_id, name);
4651 None => {} // Nothing to do.
4654 // Look for trait children.
4655 build_reduced_graph::populate_module_if_necessary(self, &search_module);
4658 for (_, child_names) in search_module.children.borrow().iter() {
4659 let def = match child_names.def_for_namespace(TypeNS) {
4663 let trait_def_id = match def {
4664 DefTrait(trait_def_id) => trait_def_id,
4667 if self.trait_item_map.contains_key(&(name, trait_def_id)) {
4668 add_trait_info(&mut found_traits, trait_def_id, name);
4673 // Look for imports.
4674 for (_, import) in search_module.import_resolutions.borrow().iter() {
4675 let target = match import.target_for_namespace(TypeNS) {
4677 Some(target) => target,
4679 let did = match target.bindings.def_for_namespace(TypeNS) {
4680 Some(DefTrait(trait_def_id)) => trait_def_id,
4681 Some(..) | None => continue,
4683 if self.trait_item_map.contains_key(&(name, did)) {
4684 add_trait_info(&mut found_traits, did, name);
4685 let id = import.type_id;
4686 self.used_imports.insert((id, TypeNS));
4687 let trait_name = self.get_trait_name(did);
4688 self.record_import_use(id, trait_name);
4689 if let Some(DefId{krate: kid, ..}) = target.target_module.def_id.get() {
4690 self.used_crates.insert(kid);
4695 match search_module.parent_link.clone() {
4696 NoParentLink | ModuleParentLink(..) => break,
4697 BlockParentLink(parent_module, _) => {
4698 search_module = parent_module.upgrade().unwrap();
4706 fn record_def(&mut self, node_id: NodeId, (def, lp): (Def, LastPrivate)) {
4707 debug!("(recording def) recording {} for {}, last private {}",
4709 assert!(match lp {LastImport{..} => false, _ => true},
4710 "Import should only be used for `use` directives");
4711 self.last_private.insert(node_id, lp);
4713 match self.def_map.borrow_mut().entry(&node_id) {
4714 // Resolve appears to "resolve" the same ID multiple
4715 // times, so here is a sanity check it at least comes to
4716 // the same conclusion! - nmatsakis
4717 Occupied(entry) => if def != *entry.get() {
4719 .bug(format!("node_id {} resolved first to {} and \
4725 Vacant(entry) => { entry.insert(def); },
4729 fn enforce_default_binding_mode(&mut self,
4731 pat_binding_mode: BindingMode,
4733 match pat_binding_mode {
4734 BindByValue(_) => {}
4736 self.resolve_error(pat.span,
4737 format!("cannot use `ref` binding mode \
4747 // Diagnostics are not particularly efficient, because they're rarely
4751 /// A somewhat inefficient routine to obtain the name of a module.
4752 fn module_to_string(&self, module: &Module) -> String {
4753 let mut names = Vec::new();
4755 fn collect_mod(names: &mut Vec<ast::Name>, module: &Module) {
4756 match module.parent_link {
4758 ModuleParentLink(ref module, name) => {
4760 collect_mod(names, &*module.upgrade().unwrap());
4762 BlockParentLink(ref module, _) => {
4763 // danger, shouldn't be ident?
4764 names.push(special_idents::opaque.name);
4765 collect_mod(names, &*module.upgrade().unwrap());
4769 collect_mod(&mut names, module);
4771 if names.len() == 0 {
4772 return "???".to_string();
4774 self.names_to_string(names.into_iter().rev()
4775 .collect::<Vec<ast::Name>>()[])
4778 #[allow(dead_code)] // useful for debugging
4779 fn dump_module(&mut self, module_: Rc<Module>) {
4780 debug!("Dump of module `{}`:", self.module_to_string(&*module_));
4782 debug!("Children:");
4783 build_reduced_graph::populate_module_if_necessary(self, &module_);
4784 for (&name, _) in module_.children.borrow().iter() {
4785 debug!("* {}", token::get_name(name));
4788 debug!("Import resolutions:");
4789 let import_resolutions = module_.import_resolutions.borrow();
4790 for (&name, import_resolution) in import_resolutions.iter() {
4792 match import_resolution.target_for_namespace(ValueNS) {
4793 None => { value_repr = "".to_string(); }
4795 value_repr = " value:?".to_string();
4801 match import_resolution.target_for_namespace(TypeNS) {
4802 None => { type_repr = "".to_string(); }
4804 type_repr = " type:?".to_string();
4809 debug!("* {}:{}{}", token::get_name(name), value_repr, type_repr);
4814 pub struct CrateMap {
4815 pub def_map: DefMap,
4816 pub freevars: RefCell<FreevarMap>,
4817 pub capture_mode_map: RefCell<CaptureModeMap>,
4818 pub export_map: ExportMap,
4819 pub trait_map: TraitMap,
4820 pub external_exports: ExternalExports,
4821 pub last_private_map: LastPrivateMap,
4822 pub glob_map: Option<GlobMap>
4825 #[derive(PartialEq,Copy)]
4826 pub enum MakeGlobMap {
4831 /// Entry point to crate resolution.
4832 pub fn resolve_crate<'a, 'tcx>(session: &'a Session,
4833 ast_map: &'a ast_map::Map<'tcx>,
4836 make_glob_map: MakeGlobMap)
4838 let mut resolver = Resolver::new(session, ast_map, krate.span, make_glob_map);
4840 build_reduced_graph::build_reduced_graph(&mut resolver, krate);
4841 session.abort_if_errors();
4843 resolver.resolve_imports();
4844 session.abort_if_errors();
4846 record_exports::record(&mut resolver);
4847 session.abort_if_errors();
4849 resolver.resolve_crate(krate);
4850 session.abort_if_errors();
4852 check_unused::check_crate(&mut resolver, krate);
4855 def_map: resolver.def_map,
4856 freevars: resolver.freevars,
4857 capture_mode_map: RefCell::new(resolver.capture_mode_map),
4858 export_map: resolver.export_map,
4859 trait_map: resolver.trait_map,
4860 external_exports: resolver.external_exports,
4861 last_private_map: resolver.last_private,
4862 glob_map: if resolver.make_glob_map {
4863 Some(resolver.glob_map)