1 // Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
11 #![crate_name = "rustc_resolve"]
14 #![crate_type = "dylib"]
15 #![crate_type = "rlib"]
16 #![doc(html_logo_url = "http://www.rust-lang.org/logos/rust-logo-128x128-blk-v2.png",
17 html_favicon_url = "http://www.rust-lang.org/favicon.ico",
18 html_root_url = "http://doc.rust-lang.org/nightly/")]
20 #![feature(slicing_syntax)]
21 #![feature(rustc_diagnostic_macros)]
22 #![allow(unknown_features)] #![feature(int_uint)]
25 #[macro_use] extern crate log;
26 #[macro_use] extern crate syntax;
27 #[macro_use] #[no_link] extern crate rustc_bitflags;
31 use self::PatternBindingMode::*;
32 use self::Namespace::*;
33 use self::NamespaceResult::*;
34 use self::NameDefinition::*;
35 use self::ImportDirectiveSubclass::*;
36 use self::ResolveResult::*;
37 use self::FallbackSuggestion::*;
38 use self::TypeParameters::*;
40 use self::MethodSort::*;
41 use self::UseLexicalScopeFlag::*;
42 use self::ModulePrefixResult::*;
43 use self::NameSearchType::*;
44 use self::BareIdentifierPatternResolution::*;
45 use self::ParentLink::*;
46 use self::ModuleKind::*;
47 use self::TraitReferenceType::*;
48 use self::FallbackChecks::*;
50 use rustc::session::Session;
52 use rustc::metadata::csearch;
53 use rustc::metadata::decoder::{DefLike, DlDef, DlField, DlImpl};
54 use rustc::middle::def::*;
55 use rustc::middle::lang_items::LanguageItems;
56 use rustc::middle::pat_util::pat_bindings;
57 use rustc::middle::privacy::*;
58 use rustc::middle::subst::{ParamSpace, FnSpace, TypeSpace};
59 use rustc::middle::ty::{CaptureModeMap, Freevar, FreevarMap, TraitMap, GlobMap};
60 use rustc::util::nodemap::{NodeMap, NodeSet, DefIdSet, FnvHashMap};
61 use rustc::util::lev_distance::lev_distance;
63 use syntax::ast::{Arm, BindByRef, BindByValue, BindingMode, Block, Crate, CrateNum};
64 use syntax::ast::{DefId, Expr, ExprAgain, ExprBreak, ExprField};
65 use syntax::ast::{ExprClosure, ExprForLoop, ExprLoop, ExprWhile, ExprMethodCall};
66 use syntax::ast::{ExprPath, ExprQPath, ExprStruct, FnDecl};
67 use syntax::ast::{ForeignItemFn, ForeignItemStatic, Generics};
68 use syntax::ast::{Ident, ImplItem, Item, ItemConst, ItemEnum, ItemFn};
69 use syntax::ast::{ItemForeignMod, ItemImpl, ItemMac, ItemMod, ItemStatic};
70 use syntax::ast::{ItemStruct, ItemTrait, ItemTy, Local, LOCAL_CRATE};
71 use syntax::ast::{MethodImplItem, Mod, Name, NodeId};
72 use syntax::ast::{Pat, PatEnum, PatIdent, PatLit};
73 use syntax::ast::{PatRange, PatStruct, Path};
74 use syntax::ast::{PolyTraitRef, PrimTy, SelfExplicit};
75 use syntax::ast::{RegionTyParamBound, StructField};
76 use syntax::ast::{TraitRef, TraitTyParamBound};
77 use syntax::ast::{Ty, TyBool, TyChar, TyF32};
78 use syntax::ast::{TyF64, TyFloat, TyIs, TyI8, TyI16, TyI32, TyI64, TyInt, TyObjectSum};
79 use syntax::ast::{TyParam, TyParamBound, TyPath, TyPtr, TyPolyTraitRef, TyQPath};
80 use syntax::ast::{TyRptr, TyStr, TyUs, TyU8, TyU16, TyU32, TyU64, TyUint};
81 use syntax::ast::{TypeImplItem};
84 use syntax::ast_util::{PostExpansionMethod, local_def, walk_pat};
85 use syntax::attr::AttrMetaMethods;
86 use syntax::ext::mtwt;
87 use syntax::parse::token::{self, special_names, special_idents};
88 use syntax::codemap::{Span, Pos};
89 use syntax::owned_slice::OwnedSlice;
90 use syntax::visit::{self, Visitor};
92 use std::collections::{HashMap, HashSet};
93 use std::collections::hash_map::Entry::{Occupied, Vacant};
94 use std::cell::{Cell, RefCell};
96 use std::mem::replace;
97 use std::rc::{Rc, Weak};
102 mod build_reduced_graph;
107 binding_mode: BindingMode,
110 // Map from the name in a pattern to its binding mode.
111 type BindingMap = HashMap<Name, BindingInfo>;
113 #[derive(Copy, PartialEq)]
114 enum PatternBindingMode {
116 LocalIrrefutableMode,
117 ArgumentIrrefutableMode,
120 #[derive(Copy, PartialEq, Eq, Hash, Show)]
126 /// A NamespaceResult represents the result of resolving an import in
127 /// a particular namespace. The result is either definitely-resolved,
128 /// definitely- unresolved, or unknown.
130 enum NamespaceResult {
131 /// Means that resolve hasn't gathered enough information yet to determine
132 /// whether the name is bound in this namespace. (That is, it hasn't
133 /// resolved all `use` directives yet.)
135 /// Means that resolve has determined that the name is definitely
136 /// not bound in the namespace.
138 /// Means that resolve has determined that the name is bound in the Module
139 /// argument, and specified by the NameBindings argument.
140 BoundResult(Rc<Module>, Rc<NameBindings>)
143 impl NamespaceResult {
144 fn is_unknown(&self) -> bool {
146 UnknownResult => true,
150 fn is_unbound(&self) -> bool {
152 UnboundResult => true,
158 enum NameDefinition {
159 NoNameDefinition, //< The name was unbound.
160 ChildNameDefinition(Def, LastPrivate), //< The name identifies an immediate child.
161 ImportNameDefinition(Def, LastPrivate) //< The name identifies an import.
164 impl<'a, 'v, 'tcx> Visitor<'v> for Resolver<'a, 'tcx> {
165 fn visit_item(&mut self, item: &Item) {
166 self.resolve_item(item);
168 fn visit_arm(&mut self, arm: &Arm) {
169 self.resolve_arm(arm);
171 fn visit_block(&mut self, block: &Block) {
172 self.resolve_block(block);
174 fn visit_expr(&mut self, expr: &Expr) {
175 self.resolve_expr(expr);
177 fn visit_local(&mut self, local: &Local) {
178 self.resolve_local(local);
180 fn visit_ty(&mut self, ty: &Ty) {
181 self.resolve_type(ty);
185 /// Contains data for specific types of import directives.
187 enum ImportDirectiveSubclass {
188 SingleImport(Name /* target */, Name /* source */),
192 type ErrorMessage = Option<(Span, String)>;
194 enum ResolveResult<T> {
195 Failed(ErrorMessage), // Failed to resolve the name, optional helpful error message.
196 Indeterminate, // Couldn't determine due to unresolved globs.
197 Success(T) // Successfully resolved the import.
200 impl<T> ResolveResult<T> {
201 fn indeterminate(&self) -> bool {
202 match *self { Indeterminate => true, _ => false }
206 enum FallbackSuggestion {
211 StaticMethod(String),
216 enum TypeParameters<'a> {
222 // Identifies the things that these parameters
223 // were declared on (type, fn, etc)
226 // ID of the enclosing item.
229 // The kind of the rib used for type parameters.
233 // The rib kind controls the translation of local
234 // definitions (`DefLocal`) to upvars (`DefUpvar`).
235 #[derive(Copy, Show)]
237 // No translation needs to be applied.
240 // We passed through a closure scope at the given node ID.
241 // Translate upvars as appropriate.
242 ClosureRibKind(NodeId /* func id */, NodeId /* body id if proc or unboxed */),
244 // We passed through an impl or trait and are now in one of its
245 // methods. Allow references to ty params that impl or trait
246 // binds. Disallow any other upvars (including other ty params that are
248 // parent; method itself
249 MethodRibKind(NodeId, MethodSort),
251 // We passed through an item scope. Disallow upvars.
254 // We're in a constant item. Can't refer to dynamic stuff.
258 // Methods can be required or provided. RequiredMethod methods only occur in traits.
259 #[derive(Copy, Show)]
262 ProvidedMethod(NodeId)
266 enum UseLexicalScopeFlag {
271 enum ModulePrefixResult {
273 PrefixFound(Rc<Module>, uint)
276 #[derive(Copy, PartialEq)]
277 enum NameSearchType {
278 /// We're doing a name search in order to resolve a `use` directive.
281 /// We're doing a name search in order to resolve a path type, a path
282 /// expression, or a path pattern.
287 enum BareIdentifierPatternResolution {
288 FoundStructOrEnumVariant(Def, LastPrivate),
289 FoundConst(Def, LastPrivate),
290 BareIdentifierPatternUnresolved
296 bindings: HashMap<Name, DefLike>,
301 fn new(kind: RibKind) -> Rib {
303 bindings: HashMap::new(),
309 /// Whether an import can be shadowed by another import.
310 #[derive(Show,PartialEq,Clone,Copy)]
316 /// One import directive.
318 struct ImportDirective {
319 module_path: Vec<Name>,
320 subclass: ImportDirectiveSubclass,
323 is_public: bool, // see note in ImportResolution about how to use this
324 shadowable: Shadowable,
327 impl ImportDirective {
328 fn new(module_path: Vec<Name> ,
329 subclass: ImportDirectiveSubclass,
333 shadowable: Shadowable)
336 module_path: module_path,
340 is_public: is_public,
341 shadowable: shadowable,
346 /// The item that an import resolves to.
347 #[derive(Clone,Show)]
349 target_module: Rc<Module>,
350 bindings: Rc<NameBindings>,
351 shadowable: Shadowable,
355 fn new(target_module: Rc<Module>,
356 bindings: Rc<NameBindings>,
357 shadowable: Shadowable)
360 target_module: target_module,
362 shadowable: shadowable,
367 /// An ImportResolution represents a particular `use` directive.
369 struct ImportResolution {
370 /// Whether this resolution came from a `use` or a `pub use`. Note that this
371 /// should *not* be used whenever resolution is being performed, this is
372 /// only looked at for glob imports statements currently. Privacy testing
373 /// occurs during a later phase of compilation.
376 // The number of outstanding references to this name. When this reaches
377 // zero, outside modules can count on the targets being correct. Before
378 // then, all bets are off; future imports could override this name.
379 outstanding_references: uint,
381 /// The value that this `use` directive names, if there is one.
382 value_target: Option<Target>,
383 /// The source node of the `use` directive leading to the value target
387 /// The type that this `use` directive names, if there is one.
388 type_target: Option<Target>,
389 /// The source node of the `use` directive leading to the type target
394 impl ImportResolution {
395 fn new(id: NodeId, is_public: bool) -> ImportResolution {
399 outstanding_references: 0,
402 is_public: is_public,
406 fn target_for_namespace(&self, namespace: Namespace)
409 TypeNS => self.type_target.clone(),
410 ValueNS => self.value_target.clone(),
414 fn id(&self, namespace: Namespace) -> NodeId {
416 TypeNS => self.type_id,
417 ValueNS => self.value_id,
421 fn shadowable(&self, namespace: Namespace) -> Shadowable {
422 let target = self.target_for_namespace(namespace);
423 if target.is_none() {
424 return Shadowable::Always;
427 target.unwrap().shadowable
430 fn set_target_and_id(&mut self,
431 namespace: Namespace,
432 target: Option<Target>,
436 self.type_target = target;
440 self.value_target = target;
447 /// The link from a module up to its nearest parent node.
448 #[derive(Clone,Show)]
451 ModuleParentLink(Weak<Module>, Name),
452 BlockParentLink(Weak<Module>, NodeId)
455 /// The type of module this is.
456 #[derive(Copy, PartialEq, Show)]
466 /// One node in the tree of modules.
468 parent_link: ParentLink,
469 def_id: Cell<Option<DefId>>,
470 kind: Cell<ModuleKind>,
473 children: RefCell<HashMap<Name, Rc<NameBindings>>>,
474 imports: RefCell<Vec<ImportDirective>>,
476 // The external module children of this node that were declared with
478 external_module_children: RefCell<HashMap<Name, Rc<Module>>>,
480 // The anonymous children of this node. Anonymous children are pseudo-
481 // modules that are implicitly created around items contained within
484 // For example, if we have this:
492 // There will be an anonymous module created around `g` with the ID of the
493 // entry block for `f`.
494 anonymous_children: RefCell<NodeMap<Rc<Module>>>,
496 // The status of resolving each import in this module.
497 import_resolutions: RefCell<HashMap<Name, ImportResolution>>,
499 // The number of unresolved globs that this module exports.
500 glob_count: Cell<uint>,
502 // The index of the import we're resolving.
503 resolved_import_count: Cell<uint>,
505 // Whether this module is populated. If not populated, any attempt to
506 // access the children must be preceded with a
507 // `populate_module_if_necessary` call.
508 populated: Cell<bool>,
512 fn new(parent_link: ParentLink,
513 def_id: Option<DefId>,
519 parent_link: parent_link,
520 def_id: Cell::new(def_id),
521 kind: Cell::new(kind),
522 is_public: is_public,
523 children: RefCell::new(HashMap::new()),
524 imports: RefCell::new(Vec::new()),
525 external_module_children: RefCell::new(HashMap::new()),
526 anonymous_children: RefCell::new(NodeMap()),
527 import_resolutions: RefCell::new(HashMap::new()),
528 glob_count: Cell::new(0),
529 resolved_import_count: Cell::new(0),
530 populated: Cell::new(!external),
534 fn all_imports_resolved(&self) -> bool {
535 self.imports.borrow().len() == self.resolved_import_count.get()
539 impl fmt::Show for Module {
540 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
541 write!(f, "{:?}, kind: {:?}, {}",
544 if self.is_public { "public" } else { "private" } )
550 flags DefModifiers: u8 {
551 const PUBLIC = 0b0000_0001,
552 const IMPORTABLE = 0b0000_0010,
556 // Records a possibly-private type definition.
557 #[derive(Clone,Show)]
559 modifiers: DefModifiers, // see note in ImportResolution about how to use this
560 module_def: Option<Rc<Module>>,
561 type_def: Option<Def>,
562 type_span: Option<Span>
565 // Records a possibly-private value definition.
566 #[derive(Clone, Copy, Show)]
568 modifiers: DefModifiers, // see note in ImportResolution about how to use this
570 value_span: Option<Span>,
573 // Records the definitions (at most one for each namespace) that a name is
576 struct NameBindings {
577 type_def: RefCell<Option<TypeNsDef>>, //< Meaning in type namespace.
578 value_def: RefCell<Option<ValueNsDef>>, //< Meaning in value namespace.
581 /// Ways in which a trait can be referenced
583 enum TraitReferenceType {
584 TraitImplementation, // impl SomeTrait for T { ... }
585 TraitDerivation, // trait T : SomeTrait { ... }
586 TraitBoundingTypeParameter, // fn f<T:SomeTrait>() { ... }
587 TraitObject, // Box<for<'a> SomeTrait>
588 TraitQPath, // <T as SomeTrait>::
592 fn new() -> NameBindings {
594 type_def: RefCell::new(None),
595 value_def: RefCell::new(None),
599 /// Creates a new module in this set of name bindings.
600 fn define_module(&self,
601 parent_link: ParentLink,
602 def_id: Option<DefId>,
607 // Merges the module with the existing type def or creates a new one.
608 let modifiers = if is_public { PUBLIC } else { DefModifiers::empty() } | IMPORTABLE;
609 let module_ = Rc::new(Module::new(parent_link,
614 let type_def = self.type_def.borrow().clone();
617 *self.type_def.borrow_mut() = Some(TypeNsDef {
618 modifiers: modifiers,
619 module_def: Some(module_),
625 *self.type_def.borrow_mut() = Some(TypeNsDef {
626 modifiers: modifiers,
627 module_def: Some(module_),
629 type_def: type_def.type_def
635 /// Sets the kind of the module, creating a new one if necessary.
636 fn set_module_kind(&self,
637 parent_link: ParentLink,
638 def_id: Option<DefId>,
643 let modifiers = if is_public { PUBLIC } else { DefModifiers::empty() } | IMPORTABLE;
644 let type_def = self.type_def.borrow().clone();
647 let module = Module::new(parent_link,
652 *self.type_def.borrow_mut() = Some(TypeNsDef {
653 modifiers: modifiers,
654 module_def: Some(Rc::new(module)),
660 match type_def.module_def {
662 let module = Module::new(parent_link,
667 *self.type_def.borrow_mut() = Some(TypeNsDef {
668 modifiers: modifiers,
669 module_def: Some(Rc::new(module)),
670 type_def: type_def.type_def,
674 Some(module_def) => module_def.kind.set(kind),
680 /// Records a type definition.
681 fn define_type(&self, def: Def, sp: Span, modifiers: DefModifiers) {
682 debug!("defining type for def {:?} with modifiers {:?}", def, modifiers);
683 // Merges the type with the existing type def or creates a new one.
684 let type_def = self.type_def.borrow().clone();
687 *self.type_def.borrow_mut() = Some(TypeNsDef {
691 modifiers: modifiers,
695 *self.type_def.borrow_mut() = Some(TypeNsDef {
696 module_def: type_def.module_def,
699 modifiers: modifiers,
705 /// Records a value definition.
706 fn define_value(&self, def: Def, sp: Span, modifiers: DefModifiers) {
707 debug!("defining value for def {:?} with modifiers {:?}", def, modifiers);
708 *self.value_def.borrow_mut() = Some(ValueNsDef {
710 value_span: Some(sp),
711 modifiers: modifiers,
715 /// Returns the module node if applicable.
716 fn get_module_if_available(&self) -> Option<Rc<Module>> {
717 match *self.type_def.borrow() {
718 Some(ref type_def) => type_def.module_def.clone(),
723 /// Returns the module node. Panics if this node does not have a module
725 fn get_module(&self) -> Rc<Module> {
726 match self.get_module_if_available() {
728 panic!("get_module called on a node with no module \
731 Some(module_def) => module_def
735 fn defined_in_namespace(&self, namespace: Namespace) -> bool {
737 TypeNS => return self.type_def.borrow().is_some(),
738 ValueNS => return self.value_def.borrow().is_some()
742 fn defined_in_public_namespace(&self, namespace: Namespace) -> bool {
743 self.defined_in_namespace_with(namespace, PUBLIC)
746 fn defined_in_namespace_with(&self, namespace: Namespace, modifiers: DefModifiers) -> bool {
748 TypeNS => match *self.type_def.borrow() {
749 Some(ref def) => def.modifiers.contains(modifiers), None => false
751 ValueNS => match *self.value_def.borrow() {
752 Some(ref def) => def.modifiers.contains(modifiers), None => false
757 fn def_for_namespace(&self, namespace: Namespace) -> Option<Def> {
760 match *self.type_def.borrow() {
762 Some(ref type_def) => {
763 match type_def.type_def {
764 Some(type_def) => Some(type_def),
766 match type_def.module_def {
767 Some(ref module) => {
768 match module.def_id.get() {
769 Some(did) => Some(DefMod(did)),
781 match *self.value_def.borrow() {
783 Some(value_def) => Some(value_def.def)
789 fn span_for_namespace(&self, namespace: Namespace) -> Option<Span> {
790 if self.defined_in_namespace(namespace) {
793 match *self.type_def.borrow() {
795 Some(ref type_def) => type_def.type_span
799 match *self.value_def.borrow() {
801 Some(ref value_def) => value_def.value_span
811 /// Interns the names of the primitive types.
812 struct PrimitiveTypeTable {
813 primitive_types: HashMap<Name, PrimTy>,
816 impl PrimitiveTypeTable {
817 fn new() -> PrimitiveTypeTable {
818 let mut table = PrimitiveTypeTable {
819 primitive_types: HashMap::new()
822 table.intern("bool", TyBool);
823 table.intern("char", TyChar);
824 table.intern("f32", TyFloat(TyF32));
825 table.intern("f64", TyFloat(TyF64));
826 table.intern("int", TyInt(TyIs(true)));
827 table.intern("isize", TyInt(TyIs(false)));
828 table.intern("i8", TyInt(TyI8));
829 table.intern("i16", TyInt(TyI16));
830 table.intern("i32", TyInt(TyI32));
831 table.intern("i64", TyInt(TyI64));
832 table.intern("str", TyStr);
833 table.intern("uint", TyUint(TyUs(true)));
834 table.intern("usize", TyUint(TyUs(false)));
835 table.intern("u8", TyUint(TyU8));
836 table.intern("u16", TyUint(TyU16));
837 table.intern("u32", TyUint(TyU32));
838 table.intern("u64", TyUint(TyU64));
843 fn intern(&mut self, string: &str, primitive_type: PrimTy) {
844 self.primitive_types.insert(token::intern(string), primitive_type);
848 /// The main resolver class.
849 struct Resolver<'a, 'tcx:'a> {
850 session: &'a Session,
852 ast_map: &'a ast_map::Map<'tcx>,
854 graph_root: NameBindings,
856 trait_item_map: FnvHashMap<(Name, DefId), TraitItemKind>,
858 structs: FnvHashMap<DefId, Vec<Name>>,
860 // The number of imports that are currently unresolved.
861 unresolved_imports: uint,
863 // The module that represents the current item scope.
864 current_module: Rc<Module>,
866 // The current set of local scopes, for values.
867 // FIXME #4948: Reuse ribs to avoid allocation.
868 value_ribs: Vec<Rib>,
870 // The current set of local scopes, for types.
873 // The current set of local scopes, for labels.
874 label_ribs: Vec<Rib>,
876 // The trait that the current context can refer to.
877 current_trait_ref: Option<(DefId, TraitRef)>,
879 // The current self type if inside an impl (used for better errors).
880 current_self_type: Option<Ty>,
882 // The ident for the keyword "self".
884 // The ident for the non-keyword "Self".
885 type_self_name: Name,
887 // The idents for the primitive types.
888 primitive_type_table: PrimitiveTypeTable,
891 freevars: RefCell<FreevarMap>,
892 freevars_seen: RefCell<NodeMap<NodeSet>>,
893 capture_mode_map: CaptureModeMap,
894 export_map: ExportMap,
896 external_exports: ExternalExports,
897 last_private: LastPrivateMap,
899 // Whether or not to print error messages. Can be set to true
900 // when getting additional info for error message suggestions,
901 // so as to avoid printing duplicate errors
905 // Maps imports to the names of items actually imported (this actually maps
906 // all imports, but only glob imports are actually interesting).
909 used_imports: HashSet<(NodeId, Namespace)>,
910 used_crates: HashSet<CrateNum>,
914 enum FallbackChecks {
920 impl<'a, 'tcx> Resolver<'a, 'tcx> {
921 fn new(session: &'a Session,
922 ast_map: &'a ast_map::Map<'tcx>,
924 make_glob_map: MakeGlobMap) -> Resolver<'a, 'tcx> {
925 let graph_root = NameBindings::new();
927 graph_root.define_module(NoParentLink,
928 Some(DefId { krate: 0, node: 0 }),
934 let current_module = graph_root.get_module();
941 // The outermost module has def ID 0; this is not reflected in the
944 graph_root: graph_root,
946 trait_item_map: FnvHashMap(),
947 structs: FnvHashMap(),
949 unresolved_imports: 0,
951 current_module: current_module,
952 value_ribs: Vec::new(),
953 type_ribs: Vec::new(),
954 label_ribs: Vec::new(),
956 current_trait_ref: None,
957 current_self_type: None,
959 self_name: special_names::self_,
960 type_self_name: special_names::type_self,
962 primitive_type_table: PrimitiveTypeTable::new(),
964 def_map: RefCell::new(NodeMap()),
965 freevars: RefCell::new(NodeMap()),
966 freevars_seen: RefCell::new(NodeMap()),
967 capture_mode_map: NodeMap(),
968 export_map: NodeMap(),
969 trait_map: NodeMap(),
970 used_imports: HashSet::new(),
971 used_crates: HashSet::new(),
972 external_exports: DefIdSet(),
973 last_private: NodeMap(),
976 make_glob_map: make_glob_map == MakeGlobMap::Yes,
977 glob_map: HashMap::new(),
983 // This is a fixed-point algorithm. We resolve imports until our efforts
984 // are stymied by an unresolved import; then we bail out of the current
985 // module and continue. We terminate successfully once no more imports
986 // remain or unsuccessfully when no forward progress in resolving imports
989 /// Resolves all imports for the crate. This method performs the fixed-
991 fn resolve_imports(&mut self) {
993 let mut prev_unresolved_imports = 0;
995 debug!("(resolving imports) iteration {}, {} imports left",
996 i, self.unresolved_imports);
998 let module_root = self.graph_root.get_module();
999 self.resolve_imports_for_module_subtree(module_root.clone());
1001 if self.unresolved_imports == 0 {
1002 debug!("(resolving imports) success");
1006 if self.unresolved_imports == prev_unresolved_imports {
1007 self.report_unresolved_imports(module_root);
1012 prev_unresolved_imports = self.unresolved_imports;
1016 /// Attempts to resolve imports for the given module and all of its
1018 fn resolve_imports_for_module_subtree(&mut self, module_: Rc<Module>) {
1019 debug!("(resolving imports for module subtree) resolving {}",
1020 self.module_to_string(&*module_));
1021 let orig_module = replace(&mut self.current_module, module_.clone());
1022 self.resolve_imports_for_module(module_.clone());
1023 self.current_module = orig_module;
1025 build_reduced_graph::populate_module_if_necessary(self, &module_);
1026 for (_, child_node) in module_.children.borrow().iter() {
1027 match child_node.get_module_if_available() {
1031 Some(child_module) => {
1032 self.resolve_imports_for_module_subtree(child_module);
1037 for (_, child_module) in module_.anonymous_children.borrow().iter() {
1038 self.resolve_imports_for_module_subtree(child_module.clone());
1042 /// Attempts to resolve imports for the given module only.
1043 fn resolve_imports_for_module(&mut self, module: Rc<Module>) {
1044 if module.all_imports_resolved() {
1045 debug!("(resolving imports for module) all imports resolved for \
1047 self.module_to_string(&*module));
1051 let imports = module.imports.borrow();
1052 let import_count = imports.len();
1053 while module.resolved_import_count.get() < import_count {
1054 let import_index = module.resolved_import_count.get();
1055 let import_directive = &(*imports)[import_index];
1056 match self.resolve_import_for_module(module.clone(),
1059 let (span, help) = match err {
1060 Some((span, msg)) => (span, format!(". {}", msg)),
1061 None => (import_directive.span, String::new())
1063 let msg = format!("unresolved import `{}`{}",
1064 self.import_path_to_string(
1065 &import_directive.module_path[],
1066 import_directive.subclass),
1068 self.resolve_error(span, &msg[]);
1070 Indeterminate => break, // Bail out. We'll come around next time.
1071 Success(()) => () // Good. Continue.
1074 module.resolved_import_count
1075 .set(module.resolved_import_count.get() + 1);
1079 fn names_to_string(&self, names: &[Name]) -> String {
1080 let mut first = true;
1081 let mut result = String::new();
1082 for name in names.iter() {
1086 result.push_str("::")
1088 result.push_str(token::get_name(*name).get());
1093 fn path_names_to_string(&self, path: &Path) -> String {
1094 let names: Vec<ast::Name> = path.segments
1096 .map(|seg| seg.identifier.name)
1098 self.names_to_string(&names[])
1101 fn import_directive_subclass_to_string(&mut self,
1102 subclass: ImportDirectiveSubclass)
1105 SingleImport(_, source) => {
1106 token::get_name(source).get().to_string()
1108 GlobImport => "*".to_string()
1112 fn import_path_to_string(&mut self,
1114 subclass: ImportDirectiveSubclass)
1116 if names.is_empty() {
1117 self.import_directive_subclass_to_string(subclass)
1120 self.names_to_string(names),
1121 self.import_directive_subclass_to_string(
1122 subclass))).to_string()
1127 fn record_import_use(&mut self, import_id: NodeId, name: Name) {
1128 if !self.make_glob_map {
1131 if self.glob_map.contains_key(&import_id) {
1132 self.glob_map[import_id].insert(name);
1136 let mut new_set = HashSet::new();
1137 new_set.insert(name);
1138 self.glob_map.insert(import_id, new_set);
1141 fn get_trait_name(&self, did: DefId) -> Name {
1142 if did.krate == LOCAL_CRATE {
1143 self.ast_map.expect_item(did.node).ident.name
1145 csearch::get_trait_name(&self.session.cstore, did)
1149 /// Attempts to resolve the given import. The return value indicates
1150 /// failure if we're certain the name does not exist, indeterminate if we
1151 /// don't know whether the name exists at the moment due to other
1152 /// currently-unresolved imports, or success if we know the name exists.
1153 /// If successful, the resolved bindings are written into the module.
1154 fn resolve_import_for_module(&mut self,
1155 module_: Rc<Module>,
1156 import_directive: &ImportDirective)
1157 -> ResolveResult<()> {
1158 let mut resolution_result = Failed(None);
1159 let module_path = &import_directive.module_path;
1161 debug!("(resolving import for module) resolving import `{}::...` in `{}`",
1162 self.names_to_string(&module_path[]),
1163 self.module_to_string(&*module_));
1165 // First, resolve the module path for the directive, if necessary.
1166 let container = if module_path.len() == 0 {
1167 // Use the crate root.
1168 Some((self.graph_root.get_module(), LastMod(AllPublic)))
1170 match self.resolve_module_path(module_.clone(),
1172 DontUseLexicalScope,
1173 import_directive.span,
1176 resolution_result = Failed(err);
1180 resolution_result = Indeterminate;
1183 Success(container) => Some(container),
1189 Some((containing_module, lp)) => {
1190 // We found the module that the target is contained
1191 // within. Attempt to resolve the import within it.
1193 match import_directive.subclass {
1194 SingleImport(target, source) => {
1196 self.resolve_single_import(&*module_,
1205 self.resolve_glob_import(&*module_,
1214 // Decrement the count of unresolved imports.
1215 match resolution_result {
1217 assert!(self.unresolved_imports >= 1);
1218 self.unresolved_imports -= 1;
1221 // Nothing to do here; just return the error.
1225 // Decrement the count of unresolved globs if necessary. But only if
1226 // the resolution result is indeterminate -- otherwise we'll stop
1227 // processing imports here. (See the loop in
1228 // resolve_imports_for_module.)
1230 if !resolution_result.indeterminate() {
1231 match import_directive.subclass {
1233 assert!(module_.glob_count.get() >= 1);
1234 module_.glob_count.set(module_.glob_count.get() - 1);
1236 SingleImport(..) => {
1242 return resolution_result;
1245 fn create_name_bindings_from_module(module: Rc<Module>) -> NameBindings {
1247 type_def: RefCell::new(Some(TypeNsDef {
1248 modifiers: IMPORTABLE,
1249 module_def: Some(module),
1253 value_def: RefCell::new(None),
1257 fn resolve_single_import(&mut self,
1259 containing_module: Rc<Module>,
1262 directive: &ImportDirective,
1264 -> ResolveResult<()> {
1265 debug!("(resolving single import) resolving `{}` = `{}::{}` from \
1266 `{}` id {}, last private {:?}",
1267 token::get_name(target),
1268 self.module_to_string(&*containing_module),
1269 token::get_name(source),
1270 self.module_to_string(module_),
1276 LastImport {..} => {
1278 .span_bug(directive.span,
1279 "not expecting Import here, must be LastMod")
1283 // We need to resolve both namespaces for this to succeed.
1286 let mut value_result = UnknownResult;
1287 let mut type_result = UnknownResult;
1289 // Search for direct children of the containing module.
1290 build_reduced_graph::populate_module_if_necessary(self, &containing_module);
1292 match containing_module.children.borrow().get(&source) {
1296 Some(ref child_name_bindings) => {
1297 if child_name_bindings.defined_in_namespace(ValueNS) {
1298 debug!("(resolving single import) found value binding");
1299 value_result = BoundResult(containing_module.clone(),
1300 (*child_name_bindings).clone());
1302 if child_name_bindings.defined_in_namespace(TypeNS) {
1303 debug!("(resolving single import) found type binding");
1304 type_result = BoundResult(containing_module.clone(),
1305 (*child_name_bindings).clone());
1310 // Unless we managed to find a result in both namespaces (unlikely),
1311 // search imports as well.
1312 let mut value_used_reexport = false;
1313 let mut type_used_reexport = false;
1314 match (value_result.clone(), type_result.clone()) {
1315 (BoundResult(..), BoundResult(..)) => {} // Continue.
1317 // If there is an unresolved glob at this point in the
1318 // containing module, bail out. We don't know enough to be
1319 // able to resolve this import.
1321 if containing_module.glob_count.get() > 0 {
1322 debug!("(resolving single import) unresolved glob; \
1324 return Indeterminate;
1327 // Now search the exported imports within the containing module.
1328 match containing_module.import_resolutions.borrow().get(&source) {
1330 debug!("(resolving single import) no import");
1331 // The containing module definitely doesn't have an
1332 // exported import with the name in question. We can
1333 // therefore accurately report that the names are
1336 if value_result.is_unknown() {
1337 value_result = UnboundResult;
1339 if type_result.is_unknown() {
1340 type_result = UnboundResult;
1343 Some(import_resolution)
1344 if import_resolution.outstanding_references == 0 => {
1346 fn get_binding(this: &mut Resolver,
1347 import_resolution: &ImportResolution,
1348 namespace: Namespace,
1350 -> NamespaceResult {
1352 // Import resolutions must be declared with "pub"
1353 // in order to be exported.
1354 if !import_resolution.is_public {
1355 return UnboundResult;
1358 match import_resolution.
1359 target_for_namespace(namespace) {
1361 return UnboundResult;
1368 debug!("(resolving single import) found \
1369 import in ns {:?}", namespace);
1370 let id = import_resolution.id(namespace);
1371 // track used imports and extern crates as well
1372 this.used_imports.insert((id, namespace));
1373 this.record_import_use(id, *source);
1374 match target_module.def_id.get() {
1375 Some(DefId{krate: kid, ..}) => {
1376 this.used_crates.insert(kid);
1380 return BoundResult(target_module, bindings);
1385 // The name is an import which has been fully
1386 // resolved. We can, therefore, just follow it.
1387 if value_result.is_unknown() {
1388 value_result = get_binding(self,
1392 value_used_reexport = import_resolution.is_public;
1394 if type_result.is_unknown() {
1395 type_result = get_binding(self,
1399 type_used_reexport = import_resolution.is_public;
1404 // If containing_module is the same module whose import we are resolving
1405 // and there it has an unresolved import with the same name as `source`,
1406 // then the user is actually trying to import an item that is declared
1407 // in the same scope
1410 // use self::submodule;
1411 // pub mod submodule;
1413 // In this case we continue as if we resolved the import and let the
1414 // check_for_conflicts_between_imports_and_items call below handle
1416 match (module_.def_id.get(), containing_module.def_id.get()) {
1417 (Some(id1), Some(id2)) if id1 == id2 => {
1418 if value_result.is_unknown() {
1419 value_result = UnboundResult;
1421 if type_result.is_unknown() {
1422 type_result = UnboundResult;
1426 // The import is unresolved. Bail out.
1427 debug!("(resolving single import) unresolved import; \
1429 return Indeterminate;
1437 // If we didn't find a result in the type namespace, search the
1438 // external modules.
1439 let mut value_used_public = false;
1440 let mut type_used_public = false;
1442 BoundResult(..) => {}
1444 match containing_module.external_module_children.borrow_mut()
1445 .get(&source).cloned() {
1446 None => {} // Continue.
1448 debug!("(resolving single import) found external \
1450 // track the module as used.
1451 match module.def_id.get() {
1452 Some(DefId{krate: kid, ..}) => { self.used_crates.insert(kid); },
1456 Rc::new(Resolver::create_name_bindings_from_module(
1458 type_result = BoundResult(containing_module.clone(),
1460 type_used_public = true;
1466 // We've successfully resolved the import. Write the results in.
1467 let mut import_resolutions = module_.import_resolutions.borrow_mut();
1468 let import_resolution = &mut (*import_resolutions)[target];
1470 let mut check_and_write_import = |&mut: namespace, result: &_, used_public: &mut bool| {
1471 let namespace_name = match namespace {
1477 BoundResult(ref target_module, ref name_bindings) => {
1478 debug!("(resolving single import) found {:?} target: {:?}",
1480 name_bindings.def_for_namespace(namespace));
1481 self.check_for_conflicting_import(
1482 &import_resolution.target_for_namespace(namespace),
1487 self.check_that_import_is_importable(
1493 let target = Some(Target::new(target_module.clone(),
1494 name_bindings.clone(),
1495 directive.shadowable));
1496 import_resolution.set_target_and_id(namespace, target, directive.id);
1497 import_resolution.is_public = directive.is_public;
1498 *used_public = name_bindings.defined_in_public_namespace(namespace);
1500 UnboundResult => { /* Continue. */ }
1502 panic!("{:?} result should be known at this point", namespace_name);
1506 check_and_write_import(ValueNS, &value_result, &mut value_used_public);
1507 check_and_write_import(TypeNS, &type_result, &mut type_used_public);
1510 self.check_for_conflicts_between_imports_and_items(
1516 if value_result.is_unbound() && type_result.is_unbound() {
1517 let msg = format!("There is no `{}` in `{}`",
1518 token::get_name(source),
1519 self.module_to_string(&*containing_module));
1520 return Failed(Some((directive.span, msg)));
1522 let value_used_public = value_used_reexport || value_used_public;
1523 let type_used_public = type_used_reexport || type_used_public;
1525 assert!(import_resolution.outstanding_references >= 1);
1526 import_resolution.outstanding_references -= 1;
1528 // record what this import resolves to for later uses in documentation,
1529 // this may resolve to either a value or a type, but for documentation
1530 // purposes it's good enough to just favor one over the other.
1531 let value_private = match import_resolution.value_target {
1532 Some(ref target) => {
1533 let def = target.bindings.def_for_namespace(ValueNS).unwrap();
1534 self.def_map.borrow_mut().insert(directive.id, def);
1535 let did = def.def_id();
1536 if value_used_public {Some(lp)} else {Some(DependsOn(did))}
1538 // AllPublic here and below is a dummy value, it should never be used because
1539 // _exists is false.
1542 let type_private = match import_resolution.type_target {
1543 Some(ref target) => {
1544 let def = target.bindings.def_for_namespace(TypeNS).unwrap();
1545 self.def_map.borrow_mut().insert(directive.id, def);
1546 let did = def.def_id();
1547 if type_used_public {Some(lp)} else {Some(DependsOn(did))}
1552 self.last_private.insert(directive.id, LastImport{value_priv: value_private,
1554 type_priv: type_private,
1557 debug!("(resolving single import) successfully resolved import");
1561 // Resolves a glob import. Note that this function cannot fail; it either
1562 // succeeds or bails out (as importing * from an empty module or a module
1563 // that exports nothing is valid). containing_module is the module we are
1564 // actually importing, i.e., `foo` in `use foo::*`.
1565 fn resolve_glob_import(&mut self,
1567 containing_module: Rc<Module>,
1568 import_directive: &ImportDirective,
1570 -> ResolveResult<()> {
1571 let id = import_directive.id;
1572 let is_public = import_directive.is_public;
1574 // This function works in a highly imperative manner; it eagerly adds
1575 // everything it can to the list of import resolutions of the module
1577 debug!("(resolving glob import) resolving glob import {}", id);
1579 // We must bail out if the node has unresolved imports of any kind
1580 // (including globs).
1581 if !(*containing_module).all_imports_resolved() {
1582 debug!("(resolving glob import) target module has unresolved \
1583 imports; bailing out");
1584 return Indeterminate;
1587 assert_eq!(containing_module.glob_count.get(), 0);
1589 // Add all resolved imports from the containing module.
1590 let import_resolutions = containing_module.import_resolutions.borrow();
1591 for (ident, target_import_resolution) in import_resolutions.iter() {
1592 debug!("(resolving glob import) writing module resolution \
1594 token::get_name(*ident),
1595 self.module_to_string(module_));
1597 if !target_import_resolution.is_public {
1598 debug!("(resolving glob import) nevermind, just kidding");
1602 // Here we merge two import resolutions.
1603 let mut import_resolutions = module_.import_resolutions.borrow_mut();
1604 match import_resolutions.get_mut(ident) {
1605 Some(dest_import_resolution) => {
1606 // Merge the two import resolutions at a finer-grained
1609 match target_import_resolution.value_target {
1613 Some(ref value_target) => {
1614 self.check_for_conflicting_import(&dest_import_resolution.value_target,
1615 import_directive.span,
1618 dest_import_resolution.value_target = Some(value_target.clone());
1621 match target_import_resolution.type_target {
1625 Some(ref type_target) => {
1626 self.check_for_conflicting_import(&dest_import_resolution.type_target,
1627 import_directive.span,
1630 dest_import_resolution.type_target = Some(type_target.clone());
1633 dest_import_resolution.is_public = is_public;
1639 // Simple: just copy the old import resolution.
1640 let mut new_import_resolution = ImportResolution::new(id, is_public);
1641 new_import_resolution.value_target =
1642 target_import_resolution.value_target.clone();
1643 new_import_resolution.type_target =
1644 target_import_resolution.type_target.clone();
1646 import_resolutions.insert(*ident, new_import_resolution);
1649 // Add all children from the containing module.
1650 build_reduced_graph::populate_module_if_necessary(self, &containing_module);
1652 for (&name, name_bindings) in containing_module.children.borrow().iter() {
1653 self.merge_import_resolution(module_,
1654 containing_module.clone(),
1657 name_bindings.clone());
1661 // Add external module children from the containing module.
1662 for (&name, module) in containing_module.external_module_children.borrow().iter() {
1664 Rc::new(Resolver::create_name_bindings_from_module(module.clone()));
1665 self.merge_import_resolution(module_,
1666 containing_module.clone(),
1672 // Record the destination of this import
1673 match containing_module.def_id.get() {
1675 self.def_map.borrow_mut().insert(id, DefMod(did));
1676 self.last_private.insert(id, lp);
1681 debug!("(resolving glob import) successfully resolved import");
1685 fn merge_import_resolution(&mut self,
1687 containing_module: Rc<Module>,
1688 import_directive: &ImportDirective,
1690 name_bindings: Rc<NameBindings>) {
1691 let id = import_directive.id;
1692 let is_public = import_directive.is_public;
1694 let mut import_resolutions = module_.import_resolutions.borrow_mut();
1695 let dest_import_resolution = import_resolutions.entry(name).get().unwrap_or_else(
1697 // Create a new import resolution from this child.
1698 vacant_entry.insert(ImportResolution::new(id, is_public))
1701 debug!("(resolving glob import) writing resolution `{}` in `{}` \
1703 token::get_name(name).get(),
1704 self.module_to_string(&*containing_module),
1705 self.module_to_string(module_));
1707 // Merge the child item into the import resolution.
1709 let mut merge_child_item = |&mut : namespace| {
1710 if name_bindings.defined_in_namespace_with(namespace, IMPORTABLE | PUBLIC) {
1711 let namespace_name = match namespace {
1715 debug!("(resolving glob import) ... for {} target", namespace_name);
1716 if dest_import_resolution.shadowable(namespace) == Shadowable::Never {
1717 let msg = format!("a {} named `{}` has already been imported \
1720 token::get_name(name).get());
1721 self.session.span_err(import_directive.span, msg.as_slice());
1723 let target = Target::new(containing_module.clone(),
1724 name_bindings.clone(),
1725 import_directive.shadowable);
1726 dest_import_resolution.set_target_and_id(namespace,
1732 merge_child_item(ValueNS);
1733 merge_child_item(TypeNS);
1736 dest_import_resolution.is_public = is_public;
1738 self.check_for_conflicts_between_imports_and_items(
1740 dest_import_resolution,
1741 import_directive.span,
1745 /// Checks that imported names and items don't have the same name.
1746 fn check_for_conflicting_import(&mut self,
1747 target: &Option<Target>,
1750 namespace: Namespace) {
1751 if self.session.features.borrow().import_shadowing {
1755 debug!("check_for_conflicting_import: {}; target exists: {}",
1756 token::get_name(name).get(),
1760 Some(ref target) if target.shadowable != Shadowable::Always => {
1761 let msg = format!("a {} named `{}` has already been imported \
1767 token::get_name(name).get());
1768 self.session.span_err(import_span, &msg[]);
1770 Some(_) | None => {}
1774 /// Checks that an import is actually importable
1775 fn check_that_import_is_importable(&mut self,
1776 name_bindings: &NameBindings,
1779 namespace: Namespace) {
1780 if !name_bindings.defined_in_namespace_with(namespace, IMPORTABLE) {
1781 let msg = format!("`{}` is not directly importable",
1782 token::get_name(name));
1783 self.session.span_err(import_span, &msg[]);
1787 /// Checks that imported names and items don't have the same name.
1788 fn check_for_conflicts_between_imports_and_items(&mut self,
1794 if self.session.features.borrow().import_shadowing {
1798 // First, check for conflicts between imports and `extern crate`s.
1799 if module.external_module_children
1801 .contains_key(&name) {
1802 match import_resolution.type_target {
1803 Some(ref target) if target.shadowable != Shadowable::Always => {
1804 let msg = format!("import `{0}` conflicts with imported \
1805 crate in this module \
1806 (maybe you meant `use {0}::*`?)",
1807 token::get_name(name).get());
1808 self.session.span_err(import_span, &msg[]);
1810 Some(_) | None => {}
1814 // Check for item conflicts.
1815 let children = module.children.borrow();
1816 let name_bindings = match children.get(&name) {
1818 // There can't be any conflicts.
1821 Some(ref name_bindings) => (*name_bindings).clone(),
1824 match import_resolution.value_target {
1825 Some(ref target) if target.shadowable != Shadowable::Always => {
1826 if let Some(ref value) = *name_bindings.value_def.borrow() {
1827 let msg = format!("import `{}` conflicts with value \
1829 token::get_name(name).get());
1830 self.session.span_err(import_span, &msg[]);
1831 if let Some(span) = value.value_span {
1832 self.session.span_note(span,
1833 "conflicting value here");
1837 Some(_) | None => {}
1840 match import_resolution.type_target {
1841 Some(ref target) if target.shadowable != Shadowable::Always => {
1842 if let Some(ref ty) = *name_bindings.type_def.borrow() {
1843 match ty.module_def {
1845 let msg = format!("import `{}` conflicts with type in \
1847 token::get_name(name).get());
1848 self.session.span_err(import_span, &msg[]);
1849 if let Some(span) = ty.type_span {
1850 self.session.span_note(span,
1851 "note conflicting type here")
1854 Some(ref module_def) => {
1855 match module_def.kind.get() {
1857 if let Some(span) = ty.type_span {
1858 let msg = format!("inherent implementations \
1859 are only allowed on types \
1860 defined in the current module");
1861 self.session.span_err(span, &msg[]);
1862 self.session.span_note(import_span,
1863 "import from other module here")
1867 let msg = format!("import `{}` conflicts with existing \
1869 token::get_name(name).get());
1870 self.session.span_err(import_span, &msg[]);
1871 if let Some(span) = ty.type_span {
1872 self.session.span_note(span,
1873 "note conflicting module here")
1881 Some(_) | None => {}
1885 /// Checks that the names of external crates don't collide with other
1886 /// external crates.
1887 fn check_for_conflicts_between_external_crates(&self,
1891 if self.session.features.borrow().import_shadowing {
1895 if module.external_module_children.borrow().contains_key(&name) {
1898 &format!("an external crate named `{}` has already \
1899 been imported into this module",
1900 token::get_name(name).get())[]);
1904 /// Checks that the names of items don't collide with external crates.
1905 fn check_for_conflicts_between_external_crates_and_items(&self,
1909 if self.session.features.borrow().import_shadowing {
1913 if module.external_module_children.borrow().contains_key(&name) {
1916 &format!("the name `{}` conflicts with an external \
1917 crate that has been imported into this \
1919 token::get_name(name).get())[]);
1923 /// Resolves the given module path from the given root `module_`.
1924 fn resolve_module_path_from_root(&mut self,
1925 module_: Rc<Module>,
1926 module_path: &[Name],
1929 name_search_type: NameSearchType,
1931 -> ResolveResult<(Rc<Module>, LastPrivate)> {
1932 fn search_parent_externals(needle: Name, module: &Rc<Module>)
1933 -> Option<Rc<Module>> {
1934 module.external_module_children.borrow()
1935 .get(&needle).cloned()
1936 .map(|_| module.clone())
1938 match module.parent_link.clone() {
1939 ModuleParentLink(parent, _) => {
1940 search_parent_externals(needle,
1941 &parent.upgrade().unwrap())
1948 let mut search_module = module_;
1949 let mut index = index;
1950 let module_path_len = module_path.len();
1951 let mut closest_private = lp;
1953 // Resolve the module part of the path. This does not involve looking
1954 // upward though scope chains; we simply resolve names directly in
1955 // modules as we go.
1956 while index < module_path_len {
1957 let name = module_path[index];
1958 match self.resolve_name_in_module(search_module.clone(),
1964 let segment_name = token::get_name(name);
1965 let module_name = self.module_to_string(&*search_module);
1966 let mut span = span;
1967 let msg = if "???" == &module_name[] {
1968 span.hi = span.lo + Pos::from_uint(segment_name.get().len());
1970 match search_parent_externals(name,
1971 &self.current_module) {
1973 let path_str = self.names_to_string(module_path);
1974 let target_mod_str = self.module_to_string(&*module);
1975 let current_mod_str =
1976 self.module_to_string(&*self.current_module);
1978 let prefix = if target_mod_str == current_mod_str {
1979 "self::".to_string()
1981 format!("{}::", target_mod_str)
1984 format!("Did you mean `{}{}`?", prefix, path_str)
1986 None => format!("Maybe a missing `extern crate {}`?",
1990 format!("Could not find `{}` in `{}`",
1995 return Failed(Some((span, msg)));
1997 Failed(err) => return Failed(err),
1999 debug!("(resolving module path for import) module \
2000 resolution is indeterminate: {}",
2001 token::get_name(name));
2002 return Indeterminate;
2004 Success((target, used_proxy)) => {
2005 // Check to see whether there are type bindings, and, if
2006 // so, whether there is a module within.
2007 match *target.bindings.type_def.borrow() {
2008 Some(ref type_def) => {
2009 match type_def.module_def {
2011 let msg = format!("Not a module `{}`",
2012 token::get_name(name));
2014 return Failed(Some((span, msg)));
2016 Some(ref module_def) => {
2017 search_module = module_def.clone();
2019 // track extern crates for unused_extern_crate lint
2020 if let Some(did) = module_def.def_id.get() {
2021 self.used_crates.insert(did.krate);
2024 // Keep track of the closest
2025 // private module used when
2026 // resolving this import chain.
2027 if !used_proxy && !search_module.is_public {
2028 if let Some(did) = search_module.def_id.get() {
2029 closest_private = LastMod(DependsOn(did));
2036 // There are no type bindings at all.
2037 let msg = format!("Not a module `{}`",
2038 token::get_name(name));
2039 return Failed(Some((span, msg)));
2048 return Success((search_module, closest_private));
2051 /// Attempts to resolve the module part of an import directive or path
2052 /// rooted at the given module.
2054 /// On success, returns the resolved module, and the closest *private*
2055 /// module found to the destination when resolving this path.
2056 fn resolve_module_path(&mut self,
2057 module_: Rc<Module>,
2058 module_path: &[Name],
2059 use_lexical_scope: UseLexicalScopeFlag,
2061 name_search_type: NameSearchType)
2062 -> ResolveResult<(Rc<Module>, LastPrivate)> {
2063 let module_path_len = module_path.len();
2064 assert!(module_path_len > 0);
2066 debug!("(resolving module path for import) processing `{}` rooted at `{}`",
2067 self.names_to_string(module_path),
2068 self.module_to_string(&*module_));
2070 // Resolve the module prefix, if any.
2071 let module_prefix_result = self.resolve_module_prefix(module_.clone(),
2077 match module_prefix_result {
2079 let mpath = self.names_to_string(module_path);
2080 let mpath = &mpath[];
2081 match mpath.rfind(':') {
2083 let msg = format!("Could not find `{}` in `{}`",
2084 // idx +- 1 to account for the
2085 // colons on either side
2086 &mpath[(idx + 1)..],
2087 &mpath[..(idx - 1)]);
2088 return Failed(Some((span, msg)));
2095 Failed(err) => return Failed(err),
2097 debug!("(resolving module path for import) indeterminate; \
2099 return Indeterminate;
2101 Success(NoPrefixFound) => {
2102 // There was no prefix, so we're considering the first element
2103 // of the path. How we handle this depends on whether we were
2104 // instructed to use lexical scope or not.
2105 match use_lexical_scope {
2106 DontUseLexicalScope => {
2107 // This is a crate-relative path. We will start the
2108 // resolution process at index zero.
2109 search_module = self.graph_root.get_module();
2111 last_private = LastMod(AllPublic);
2113 UseLexicalScope => {
2114 // This is not a crate-relative path. We resolve the
2115 // first component of the path in the current lexical
2116 // scope and then proceed to resolve below that.
2117 match self.resolve_module_in_lexical_scope(module_,
2119 Failed(err) => return Failed(err),
2121 debug!("(resolving module path for import) \
2122 indeterminate; bailing");
2123 return Indeterminate;
2125 Success(containing_module) => {
2126 search_module = containing_module;
2128 last_private = LastMod(AllPublic);
2134 Success(PrefixFound(ref containing_module, index)) => {
2135 search_module = containing_module.clone();
2136 start_index = index;
2137 last_private = LastMod(DependsOn(containing_module.def_id
2143 self.resolve_module_path_from_root(search_module,
2151 /// Invariant: This must only be called during main resolution, not during
2152 /// import resolution.
2153 fn resolve_item_in_lexical_scope(&mut self,
2154 module_: Rc<Module>,
2156 namespace: Namespace)
2157 -> ResolveResult<(Target, bool)> {
2158 debug!("(resolving item in lexical scope) resolving `{}` in \
2159 namespace {:?} in `{}`",
2160 token::get_name(name),
2162 self.module_to_string(&*module_));
2164 // The current module node is handled specially. First, check for
2165 // its immediate children.
2166 build_reduced_graph::populate_module_if_necessary(self, &module_);
2168 match module_.children.borrow().get(&name) {
2170 if name_bindings.defined_in_namespace(namespace) => {
2171 debug!("top name bindings succeeded");
2172 return Success((Target::new(module_.clone(),
2173 name_bindings.clone(),
2177 Some(_) | None => { /* Not found; continue. */ }
2180 // Now check for its import directives. We don't have to have resolved
2181 // all its imports in the usual way; this is because chains of
2182 // adjacent import statements are processed as though they mutated the
2184 if let Some(import_resolution) = module_.import_resolutions.borrow().get(&name) {
2185 match (*import_resolution).target_for_namespace(namespace) {
2187 // Not found; continue.
2188 debug!("(resolving item in lexical scope) found \
2189 import resolution, but not in namespace {:?}",
2193 debug!("(resolving item in lexical scope) using \
2194 import resolution");
2195 // track used imports and extern crates as well
2196 let id = import_resolution.id(namespace);
2197 self.used_imports.insert((id, namespace));
2198 self.record_import_use(id, name);
2199 if let Some(DefId{krate: kid, ..}) = target.target_module.def_id.get() {
2200 self.used_crates.insert(kid);
2202 return Success((target, false));
2207 // Search for external modules.
2208 if namespace == TypeNS {
2209 if let Some(module) = module_.external_module_children.borrow().get(&name).cloned() {
2211 Rc::new(Resolver::create_name_bindings_from_module(module));
2212 debug!("lower name bindings succeeded");
2213 return Success((Target::new(module_,
2220 // Finally, proceed up the scope chain looking for parent modules.
2221 let mut search_module = module_;
2223 // Go to the next parent.
2224 match search_module.parent_link.clone() {
2226 // No more parents. This module was unresolved.
2227 debug!("(resolving item in lexical scope) unresolved \
2229 return Failed(None);
2231 ModuleParentLink(parent_module_node, _) => {
2232 match search_module.kind.get() {
2233 NormalModuleKind => {
2234 // We stop the search here.
2235 debug!("(resolving item in lexical \
2236 scope) unresolved module: not \
2237 searching through module \
2239 return Failed(None);
2245 AnonymousModuleKind => {
2246 search_module = parent_module_node.upgrade().unwrap();
2250 BlockParentLink(ref parent_module_node, _) => {
2251 search_module = parent_module_node.upgrade().unwrap();
2255 // Resolve the name in the parent module.
2256 match self.resolve_name_in_module(search_module.clone(),
2261 Failed(Some((span, msg))) =>
2262 self.resolve_error(span, &format!("failed to resolve. {}",
2264 Failed(None) => (), // Continue up the search chain.
2266 // We couldn't see through the higher scope because of an
2267 // unresolved import higher up. Bail.
2269 debug!("(resolving item in lexical scope) indeterminate \
2270 higher scope; bailing");
2271 return Indeterminate;
2273 Success((target, used_reexport)) => {
2274 // We found the module.
2275 debug!("(resolving item in lexical scope) found name \
2277 return Success((target, used_reexport));
2283 /// Resolves a module name in the current lexical scope.
2284 fn resolve_module_in_lexical_scope(&mut self,
2285 module_: Rc<Module>,
2287 -> ResolveResult<Rc<Module>> {
2288 // If this module is an anonymous module, resolve the item in the
2289 // lexical scope. Otherwise, resolve the item from the crate root.
2290 let resolve_result = self.resolve_item_in_lexical_scope(module_, name, TypeNS);
2291 match resolve_result {
2292 Success((target, _)) => {
2293 let bindings = &*target.bindings;
2294 match *bindings.type_def.borrow() {
2295 Some(ref type_def) => {
2296 match type_def.module_def {
2298 debug!("!!! (resolving module in lexical \
2299 scope) module wasn't actually a \
2301 return Failed(None);
2303 Some(ref module_def) => {
2304 return Success(module_def.clone());
2309 debug!("!!! (resolving module in lexical scope) module
2310 wasn't actually a module!");
2311 return Failed(None);
2316 debug!("(resolving module in lexical scope) indeterminate; \
2318 return Indeterminate;
2321 debug!("(resolving module in lexical scope) failed to resolve");
2327 /// Returns the nearest normal module parent of the given module.
2328 fn get_nearest_normal_module_parent(&mut self, module_: Rc<Module>)
2329 -> Option<Rc<Module>> {
2330 let mut module_ = module_;
2332 match module_.parent_link.clone() {
2333 NoParentLink => return None,
2334 ModuleParentLink(new_module, _) |
2335 BlockParentLink(new_module, _) => {
2336 let new_module = new_module.upgrade().unwrap();
2337 match new_module.kind.get() {
2338 NormalModuleKind => return Some(new_module),
2343 AnonymousModuleKind => module_ = new_module,
2350 /// Returns the nearest normal module parent of the given module, or the
2351 /// module itself if it is a normal module.
2352 fn get_nearest_normal_module_parent_or_self(&mut self, module_: Rc<Module>)
2354 match module_.kind.get() {
2355 NormalModuleKind => return module_,
2360 AnonymousModuleKind => {
2361 match self.get_nearest_normal_module_parent(module_.clone()) {
2363 Some(new_module) => new_module
2369 /// Resolves a "module prefix". A module prefix is one or both of (a) `self::`;
2370 /// (b) some chain of `super::`.
2371 /// grammar: (SELF MOD_SEP ) ? (SUPER MOD_SEP) *
2372 fn resolve_module_prefix(&mut self,
2373 module_: Rc<Module>,
2374 module_path: &[Name])
2375 -> ResolveResult<ModulePrefixResult> {
2376 // Start at the current module if we see `self` or `super`, or at the
2377 // top of the crate otherwise.
2378 let mut containing_module;
2380 let first_module_path_string = token::get_name(module_path[0]);
2381 if "self" == first_module_path_string.get() {
2383 self.get_nearest_normal_module_parent_or_self(module_);
2385 } else if "super" == first_module_path_string.get() {
2387 self.get_nearest_normal_module_parent_or_self(module_);
2388 i = 0; // We'll handle `super` below.
2390 return Success(NoPrefixFound);
2393 // Now loop through all the `super`s we find.
2394 while i < module_path.len() {
2395 let string = token::get_name(module_path[i]);
2396 if "super" != string.get() {
2399 debug!("(resolving module prefix) resolving `super` at {}",
2400 self.module_to_string(&*containing_module));
2401 match self.get_nearest_normal_module_parent(containing_module) {
2402 None => return Failed(None),
2403 Some(new_module) => {
2404 containing_module = new_module;
2410 debug!("(resolving module prefix) finished resolving prefix at {}",
2411 self.module_to_string(&*containing_module));
2413 return Success(PrefixFound(containing_module, i));
2416 /// Attempts to resolve the supplied name in the given module for the
2417 /// given namespace. If successful, returns the target corresponding to
2420 /// The boolean returned on success is an indicator of whether this lookup
2421 /// passed through a public re-export proxy.
2422 fn resolve_name_in_module(&mut self,
2423 module_: Rc<Module>,
2425 namespace: Namespace,
2426 name_search_type: NameSearchType,
2427 allow_private_imports: bool)
2428 -> ResolveResult<(Target, bool)> {
2429 debug!("(resolving name in module) resolving `{}` in `{}`",
2430 token::get_name(name).get(),
2431 self.module_to_string(&*module_));
2433 // First, check the direct children of the module.
2434 build_reduced_graph::populate_module_if_necessary(self, &module_);
2436 match module_.children.borrow().get(&name) {
2438 if name_bindings.defined_in_namespace(namespace) => {
2439 debug!("(resolving name in module) found node as child");
2440 return Success((Target::new(module_.clone(),
2441 name_bindings.clone(),
2450 // Next, check the module's imports if necessary.
2452 // If this is a search of all imports, we should be done with glob
2453 // resolution at this point.
2454 if name_search_type == PathSearch {
2455 assert_eq!(module_.glob_count.get(), 0);
2458 // Check the list of resolved imports.
2459 match module_.import_resolutions.borrow().get(&name) {
2460 Some(import_resolution) if allow_private_imports ||
2461 import_resolution.is_public => {
2463 if import_resolution.is_public &&
2464 import_resolution.outstanding_references != 0 {
2465 debug!("(resolving name in module) import \
2466 unresolved; bailing out");
2467 return Indeterminate;
2469 match import_resolution.target_for_namespace(namespace) {
2471 debug!("(resolving name in module) name found, \
2472 but not in namespace {:?}",
2476 debug!("(resolving name in module) resolved to \
2478 // track used imports and extern crates as well
2479 let id = import_resolution.id(namespace);
2480 self.used_imports.insert((id, namespace));
2481 self.record_import_use(id, name);
2482 if let Some(DefId{krate: kid, ..}) = target.target_module.def_id.get() {
2483 self.used_crates.insert(kid);
2485 return Success((target, true));
2489 Some(..) | None => {} // Continue.
2492 // Finally, search through external children.
2493 if namespace == TypeNS {
2494 if let Some(module) = module_.external_module_children.borrow().get(&name).cloned() {
2496 Rc::new(Resolver::create_name_bindings_from_module(module));
2497 return Success((Target::new(module_,
2504 // We're out of luck.
2505 debug!("(resolving name in module) failed to resolve `{}`",
2506 token::get_name(name).get());
2507 return Failed(None);
2510 fn report_unresolved_imports(&mut self, module_: Rc<Module>) {
2511 let index = module_.resolved_import_count.get();
2512 let imports = module_.imports.borrow();
2513 let import_count = imports.len();
2514 if index != import_count {
2515 let sn = self.session
2517 .span_to_snippet((*imports)[index].span)
2519 if sn.contains("::") {
2520 self.resolve_error((*imports)[index].span,
2521 "unresolved import");
2523 let err = format!("unresolved import (maybe you meant `{}::*`?)",
2525 self.resolve_error((*imports)[index].span, &err[]);
2529 // Descend into children and anonymous children.
2530 build_reduced_graph::populate_module_if_necessary(self, &module_);
2532 for (_, child_node) in module_.children.borrow().iter() {
2533 match child_node.get_module_if_available() {
2537 Some(child_module) => {
2538 self.report_unresolved_imports(child_module);
2543 for (_, module_) in module_.anonymous_children.borrow().iter() {
2544 self.report_unresolved_imports(module_.clone());
2550 // We maintain a list of value ribs and type ribs.
2552 // Simultaneously, we keep track of the current position in the module
2553 // graph in the `current_module` pointer. When we go to resolve a name in
2554 // the value or type namespaces, we first look through all the ribs and
2555 // then query the module graph. When we resolve a name in the module
2556 // namespace, we can skip all the ribs (since nested modules are not
2557 // allowed within blocks in Rust) and jump straight to the current module
2560 // Named implementations are handled separately. When we find a method
2561 // call, we consult the module node to find all of the implementations in
2562 // scope. This information is lazily cached in the module node. We then
2563 // generate a fake "implementation scope" containing all the
2564 // implementations thus found, for compatibility with old resolve pass.
2566 fn with_scope<F>(&mut self, name: Option<Name>, f: F) where
2567 F: FnOnce(&mut Resolver),
2569 let orig_module = self.current_module.clone();
2571 // Move down in the graph.
2577 build_reduced_graph::populate_module_if_necessary(self, &orig_module);
2579 match orig_module.children.borrow().get(&name) {
2581 debug!("!!! (with scope) didn't find `{}` in `{}`",
2582 token::get_name(name),
2583 self.module_to_string(&*orig_module));
2585 Some(name_bindings) => {
2586 match (*name_bindings).get_module_if_available() {
2588 debug!("!!! (with scope) didn't find module \
2590 token::get_name(name),
2591 self.module_to_string(&*orig_module));
2594 self.current_module = module_;
2604 self.current_module = orig_module;
2607 /// Wraps the given definition in the appropriate number of `DefUpvar`
2613 -> Option<DefLike> {
2615 DlDef(d @ DefUpvar(..)) => {
2616 self.session.span_bug(span,
2617 &format!("unexpected {:?} in bindings", d)[])
2619 DlDef(d @ DefLocal(_)) => {
2620 let node_id = d.def_id().node;
2622 let mut last_proc_body_id = ast::DUMMY_NODE_ID;
2623 for rib in ribs.iter() {
2626 // Nothing to do. Continue.
2628 ClosureRibKind(function_id, maybe_proc_body) => {
2630 if maybe_proc_body != ast::DUMMY_NODE_ID {
2631 last_proc_body_id = maybe_proc_body;
2633 def = DefUpvar(node_id, function_id, last_proc_body_id);
2635 let mut seen = self.freevars_seen.borrow_mut();
2636 let seen = match seen.entry(function_id) {
2637 Occupied(v) => v.into_mut(),
2638 Vacant(v) => v.insert(NodeSet()),
2640 if seen.contains(&node_id) {
2643 match self.freevars.borrow_mut().entry(function_id) {
2644 Occupied(v) => v.into_mut(),
2645 Vacant(v) => v.insert(vec![]),
2646 }.push(Freevar { def: prev_def, span: span });
2647 seen.insert(node_id);
2649 MethodRibKind(item_id, _) => {
2650 // If the def is a ty param, and came from the parent
2653 DefTyParam(_, _, did, _) if {
2654 self.def_map.borrow().get(&did.node).cloned()
2655 == Some(DefTyParamBinder(item_id))
2657 DefSelfTy(did) if did == item_id => {} // ok
2659 // This was an attempt to access an upvar inside a
2660 // named function item. This is not allowed, so we
2665 "can't capture dynamic environment in a fn item; \
2666 use the || { ... } closure form instead");
2673 // This was an attempt to access an upvar inside a
2674 // named function item. This is not allowed, so we
2679 "can't capture dynamic environment in a fn item; \
2680 use the || { ... } closure form instead");
2684 ConstantItemRibKind => {
2685 // Still doesn't deal with upvars
2686 self.resolve_error(span,
2687 "attempt to use a non-constant \
2688 value in a constant");
2695 DlDef(def @ DefTyParam(..)) |
2696 DlDef(def @ DefSelfTy(..)) => {
2697 for rib in ribs.iter() {
2699 NormalRibKind | ClosureRibKind(..) => {
2700 // Nothing to do. Continue.
2702 MethodRibKind(item_id, _) => {
2703 // If the def is a ty param, and came from the parent
2706 DefTyParam(_, _, did, _) if {
2707 self.def_map.borrow().get(&did.node).cloned()
2708 == Some(DefTyParamBinder(item_id))
2710 DefSelfTy(did) if did == item_id => {} // ok
2713 // This was an attempt to use a type parameter outside
2716 self.resolve_error(span,
2717 "can't use type parameters from \
2718 outer function; try using a local \
2719 type parameter instead");
2726 // This was an attempt to use a type parameter outside
2729 self.resolve_error(span,
2730 "can't use type parameters from \
2731 outer function; try using a local \
2732 type parameter instead");
2736 ConstantItemRibKind => {
2738 self.resolve_error(span,
2739 "cannot use an outer type \
2740 parameter in this context");
2751 /// Searches the current set of local scopes and
2752 /// applies translations for closures.
2753 fn search_ribs(&self,
2757 -> Option<DefLike> {
2758 // FIXME #4950: Try caching?
2760 for (i, rib) in ribs.iter().enumerate().rev() {
2761 match rib.bindings.get(&name).cloned() {
2763 return self.upvarify(&ribs[(i + 1)..], def_like, span);
2774 /// Searches the current set of local scopes for labels.
2775 /// Stops after meeting a closure.
2776 fn search_label(&self, name: Name) -> Option<DefLike> {
2777 for rib in self.label_ribs.iter().rev() {
2783 // Do not resolve labels across function boundary
2787 let result = rib.bindings.get(&name).cloned();
2788 if result.is_some() {
2795 fn resolve_crate(&mut self, krate: &ast::Crate) {
2796 debug!("(resolving crate) starting");
2798 visit::walk_crate(self, krate);
2801 fn resolve_item(&mut self, item: &Item) {
2802 let name = item.ident.name;
2804 debug!("(resolving item) resolving {}",
2805 token::get_name(name));
2809 // enum item: resolve all the variants' discrs,
2810 // then resolve the ty params
2811 ItemEnum(ref enum_def, ref generics) => {
2812 for variant in (*enum_def).variants.iter() {
2813 for dis_expr in variant.node.disr_expr.iter() {
2814 // resolve the discriminator expr
2816 self.with_constant_rib(|this| {
2817 this.resolve_expr(&**dis_expr);
2822 // n.b. the discr expr gets visited twice.
2823 // but maybe it's okay since the first time will signal an
2824 // error if there is one? -- tjc
2825 self.with_type_parameter_rib(HasTypeParameters(generics,
2830 this.resolve_type_parameters(&generics.ty_params);
2831 this.resolve_where_clause(&generics.where_clause);
2832 visit::walk_item(this, item);
2836 ItemTy(_, ref generics) => {
2837 self.with_type_parameter_rib(HasTypeParameters(generics,
2842 this.resolve_type_parameters(&generics.ty_params);
2843 visit::walk_item(this, item);
2849 ref implemented_traits,
2851 ref impl_items) => {
2852 self.resolve_implementation(item.id,
2859 ItemTrait(_, ref generics, ref bounds, ref trait_items) => {
2860 // Create a new rib for the self type.
2861 let mut self_type_rib = Rib::new(ItemRibKind);
2863 // plain insert (no renaming, types are not currently hygienic....)
2864 let name = self.type_self_name;
2865 self_type_rib.bindings.insert(name, DlDef(DefSelfTy(item.id)));
2866 self.type_ribs.push(self_type_rib);
2868 // Create a new rib for the trait-wide type parameters.
2869 self.with_type_parameter_rib(HasTypeParameters(generics,
2874 this.resolve_type_parameters(&generics.ty_params);
2875 this.resolve_where_clause(&generics.where_clause);
2877 this.resolve_type_parameter_bounds(item.id, bounds,
2880 for trait_item in (*trait_items).iter() {
2881 // Create a new rib for the trait_item-specific type
2884 // FIXME #4951: Do we need a node ID here?
2887 ast::RequiredMethod(ref ty_m) => {
2888 this.with_type_parameter_rib
2889 (HasTypeParameters(&ty_m.generics,
2892 MethodRibKind(item.id, RequiredMethod)),
2895 // Resolve the method-specific type
2897 this.resolve_type_parameters(
2898 &ty_m.generics.ty_params);
2899 this.resolve_where_clause(&ty_m.generics
2902 for argument in ty_m.decl.inputs.iter() {
2903 this.resolve_type(&*argument.ty);
2906 if let SelfExplicit(ref typ, _) = ty_m.explicit_self.node {
2907 this.resolve_type(&**typ)
2910 if let ast::Return(ref ret_ty) = ty_m.decl.output {
2911 this.resolve_type(&**ret_ty);
2915 ast::ProvidedMethod(ref m) => {
2916 this.resolve_method(MethodRibKind(item.id,
2917 ProvidedMethod(m.id)),
2920 ast::TypeTraitItem(ref data) => {
2921 this.resolve_type_parameter(&data.ty_param);
2922 visit::walk_trait_item(this, trait_item);
2928 self.type_ribs.pop();
2931 ItemStruct(ref struct_def, ref generics) => {
2932 self.resolve_struct(item.id,
2934 &struct_def.fields[]);
2937 ItemMod(ref module_) => {
2938 self.with_scope(Some(name), |this| {
2939 this.resolve_module(module_, item.span, name,
2944 ItemForeignMod(ref foreign_module) => {
2945 self.with_scope(Some(name), |this| {
2946 for foreign_item in foreign_module.items.iter() {
2947 match foreign_item.node {
2948 ForeignItemFn(_, ref generics) => {
2949 this.with_type_parameter_rib(
2951 generics, FnSpace, foreign_item.id,
2954 this.resolve_type_parameters(&generics.ty_params);
2955 this.resolve_where_clause(&generics.where_clause);
2956 visit::walk_foreign_item(this, &**foreign_item)
2959 ForeignItemStatic(..) => {
2960 visit::walk_foreign_item(this,
2968 ItemFn(ref fn_decl, _, _, ref generics, ref block) => {
2969 self.resolve_function(ItemRibKind,
2979 ItemConst(..) | ItemStatic(..) => {
2980 self.with_constant_rib(|this| {
2981 visit::walk_item(this, item);
2986 // do nothing, these are just around to be encoded
2991 fn with_type_parameter_rib<F>(&mut self, type_parameters: TypeParameters, f: F) where
2992 F: FnOnce(&mut Resolver),
2994 match type_parameters {
2995 HasTypeParameters(generics, space, node_id, rib_kind) => {
2996 let mut function_type_rib = Rib::new(rib_kind);
2997 let mut seen_bindings = HashSet::new();
2998 for (index, type_parameter) in generics.ty_params.iter().enumerate() {
2999 let name = type_parameter.ident.name;
3000 debug!("with_type_parameter_rib: {} {}", node_id,
3003 if seen_bindings.contains(&name) {
3004 self.resolve_error(type_parameter.span,
3005 &format!("the name `{}` is already \
3007 parameter in this type \
3012 seen_bindings.insert(name);
3014 let def_like = DlDef(DefTyParam(space,
3016 local_def(type_parameter.id),
3018 // Associate this type parameter with
3019 // the item that bound it
3020 self.record_def(type_parameter.id,
3021 (DefTyParamBinder(node_id), LastMod(AllPublic)));
3022 // plain insert (no renaming)
3023 function_type_rib.bindings.insert(name, def_like);
3025 self.type_ribs.push(function_type_rib);
3028 NoTypeParameters => {
3035 match type_parameters {
3036 HasTypeParameters(..) => { self.type_ribs.pop(); }
3037 NoTypeParameters => { }
3041 fn with_label_rib<F>(&mut self, f: F) where
3042 F: FnOnce(&mut Resolver),
3044 self.label_ribs.push(Rib::new(NormalRibKind));
3046 self.label_ribs.pop();
3049 fn with_constant_rib<F>(&mut self, f: F) where
3050 F: FnOnce(&mut Resolver),
3052 self.value_ribs.push(Rib::new(ConstantItemRibKind));
3053 self.type_ribs.push(Rib::new(ConstantItemRibKind));
3055 self.type_ribs.pop();
3056 self.value_ribs.pop();
3059 fn resolve_function(&mut self,
3061 optional_declaration: Option<&FnDecl>,
3062 type_parameters: TypeParameters,
3064 // Create a value rib for the function.
3065 let function_value_rib = Rib::new(rib_kind);
3066 self.value_ribs.push(function_value_rib);
3068 // Create a label rib for the function.
3069 let function_label_rib = Rib::new(rib_kind);
3070 self.label_ribs.push(function_label_rib);
3072 // If this function has type parameters, add them now.
3073 self.with_type_parameter_rib(type_parameters, |this| {
3074 // Resolve the type parameters.
3075 match type_parameters {
3076 NoTypeParameters => {
3079 HasTypeParameters(ref generics, _, _, _) => {
3080 this.resolve_type_parameters(&generics.ty_params);
3081 this.resolve_where_clause(&generics.where_clause);
3085 // Add each argument to the rib.
3086 match optional_declaration {
3090 Some(declaration) => {
3091 let mut bindings_list = HashMap::new();
3092 for argument in declaration.inputs.iter() {
3093 this.resolve_pattern(&*argument.pat,
3094 ArgumentIrrefutableMode,
3095 &mut bindings_list);
3097 this.resolve_type(&*argument.ty);
3099 debug!("(resolving function) recorded argument");
3102 if let ast::Return(ref ret_ty) = declaration.output {
3103 this.resolve_type(&**ret_ty);
3108 // Resolve the function body.
3109 this.resolve_block(&*block);
3111 debug!("(resolving function) leaving function");
3114 self.label_ribs.pop();
3115 self.value_ribs.pop();
3118 fn resolve_type_parameters(&mut self,
3119 type_parameters: &OwnedSlice<TyParam>) {
3120 for type_parameter in type_parameters.iter() {
3121 self.resolve_type_parameter(type_parameter);
3125 fn resolve_type_parameter(&mut self,
3126 type_parameter: &TyParam) {
3127 for bound in type_parameter.bounds.iter() {
3128 self.resolve_type_parameter_bound(type_parameter.id, bound,
3129 TraitBoundingTypeParameter);
3131 match type_parameter.default {
3132 Some(ref ty) => self.resolve_type(&**ty),
3137 fn resolve_type_parameter_bounds(&mut self,
3139 type_parameter_bounds: &OwnedSlice<TyParamBound>,
3140 reference_type: TraitReferenceType) {
3141 for type_parameter_bound in type_parameter_bounds.iter() {
3142 self.resolve_type_parameter_bound(id, type_parameter_bound,
3147 fn resolve_type_parameter_bound(&mut self,
3149 type_parameter_bound: &TyParamBound,
3150 reference_type: TraitReferenceType) {
3151 match *type_parameter_bound {
3152 TraitTyParamBound(ref tref, _) => {
3153 self.resolve_poly_trait_reference(id, tref, reference_type)
3155 RegionTyParamBound(..) => {}
3159 fn resolve_poly_trait_reference(&mut self,
3161 poly_trait_reference: &PolyTraitRef,
3162 reference_type: TraitReferenceType) {
3163 self.resolve_trait_reference(id, &poly_trait_reference.trait_ref, reference_type)
3166 fn resolve_trait_reference(&mut self,
3168 trait_reference: &TraitRef,
3169 reference_type: TraitReferenceType) {
3170 match self.resolve_path(id, &trait_reference.path, TypeNS, true) {
3172 let path_str = self.path_names_to_string(&trait_reference.path);
3173 let usage_str = match reference_type {
3174 TraitBoundingTypeParameter => "bound type parameter with",
3175 TraitImplementation => "implement",
3176 TraitDerivation => "derive",
3177 TraitObject => "reference",
3178 TraitQPath => "extract an associated item from",
3181 let msg = format!("attempt to {} a nonexistent trait `{}`", usage_str, path_str);
3182 self.resolve_error(trait_reference.path.span, &msg[]);
3186 (DefTrait(_), _) => {
3187 debug!("(resolving trait) found trait def: {:?}", def);
3188 self.record_def(trait_reference.ref_id, def);
3191 self.resolve_error(trait_reference.path.span,
3192 &format!("`{}` is not a trait",
3193 self.path_names_to_string(
3194 &trait_reference.path))[]);
3196 // If it's a typedef, give a note
3197 if let DefTy(..) = def {
3198 self.session.span_note(
3199 trait_reference.path.span,
3200 &format!("`type` aliases cannot be used for traits")
3209 fn resolve_where_clause(&mut self, where_clause: &ast::WhereClause) {
3210 for predicate in where_clause.predicates.iter() {
3212 &ast::WherePredicate::BoundPredicate(ref bound_pred) => {
3213 self.resolve_type(&*bound_pred.bounded_ty);
3215 for bound in bound_pred.bounds.iter() {
3216 self.resolve_type_parameter_bound(bound_pred.bounded_ty.id, bound,
3217 TraitBoundingTypeParameter);
3220 &ast::WherePredicate::RegionPredicate(_) => {}
3221 &ast::WherePredicate::EqPredicate(ref eq_pred) => {
3222 match self.resolve_path(eq_pred.id, &eq_pred.path, TypeNS, true) {
3223 Some((def @ DefTyParam(..), last_private)) => {
3224 self.record_def(eq_pred.id, (def, last_private));
3227 self.resolve_error(eq_pred.path.span,
3228 "undeclared associated type");
3232 self.resolve_type(&*eq_pred.ty);
3238 fn resolve_struct(&mut self,
3240 generics: &Generics,
3241 fields: &[StructField]) {
3242 // If applicable, create a rib for the type parameters.
3243 self.with_type_parameter_rib(HasTypeParameters(generics,
3248 // Resolve the type parameters.
3249 this.resolve_type_parameters(&generics.ty_params);
3250 this.resolve_where_clause(&generics.where_clause);
3253 for field in fields.iter() {
3254 this.resolve_type(&*field.node.ty);
3259 // Does this really need to take a RibKind or is it always going
3260 // to be NormalRibKind?
3261 fn resolve_method(&mut self,
3263 method: &ast::Method) {
3264 let method_generics = method.pe_generics();
3265 let type_parameters = HasTypeParameters(method_generics,
3270 if let SelfExplicit(ref typ, _) = method.pe_explicit_self().node {
3271 self.resolve_type(&**typ);
3274 self.resolve_function(rib_kind,
3275 Some(method.pe_fn_decl()),
3280 fn with_current_self_type<T, F>(&mut self, self_type: &Ty, f: F) -> T where
3281 F: FnOnce(&mut Resolver) -> T,
3283 // Handle nested impls (inside fn bodies)
3284 let previous_value = replace(&mut self.current_self_type, Some(self_type.clone()));
3285 let result = f(self);
3286 self.current_self_type = previous_value;
3290 fn with_optional_trait_ref<T, F>(&mut self, id: NodeId,
3291 opt_trait_ref: &Option<TraitRef>,
3293 F: FnOnce(&mut Resolver) -> T,
3295 let new_val = match *opt_trait_ref {
3296 Some(ref trait_ref) => {
3297 self.resolve_trait_reference(id, trait_ref, TraitImplementation);
3299 match self.def_map.borrow().get(&trait_ref.ref_id) {
3301 let did = def.def_id();
3302 Some((did, trait_ref.clone()))
3309 let original_trait_ref = replace(&mut self.current_trait_ref, new_val);
3310 let result = f(self);
3311 self.current_trait_ref = original_trait_ref;
3315 fn resolve_implementation(&mut self,
3317 generics: &Generics,
3318 opt_trait_reference: &Option<TraitRef>,
3320 impl_items: &[ImplItem]) {
3321 // If applicable, create a rib for the type parameters.
3322 self.with_type_parameter_rib(HasTypeParameters(generics,
3327 // Resolve the type parameters.
3328 this.resolve_type_parameters(&generics.ty_params);
3329 this.resolve_where_clause(&generics.where_clause);
3331 // Resolve the trait reference, if necessary.
3332 this.with_optional_trait_ref(id, opt_trait_reference, |this| {
3333 // Resolve the self type.
3334 this.resolve_type(self_type);
3336 this.with_current_self_type(self_type, |this| {
3337 for impl_item in impl_items.iter() {
3339 MethodImplItem(ref method) => {
3340 // If this is a trait impl, ensure the method
3342 this.check_trait_item(method.pe_ident().name,
3345 // We also need a new scope for the method-
3346 // specific type parameters.
3347 this.resolve_method(
3348 MethodRibKind(id, ProvidedMethod(method.id)),
3351 TypeImplItem(ref typedef) => {
3352 // If this is a trait impl, ensure the method
3354 this.check_trait_item(typedef.ident.name,
3357 this.resolve_type(&*typedef.typ);
3365 // Check that the current type is indeed a type, if we have an anonymous impl
3366 if opt_trait_reference.is_none() {
3367 match self_type.node {
3368 // TyPath is the only thing that we handled in `build_reduced_graph_for_item`,
3369 // where we created a module with the name of the type in order to implement
3370 // an anonymous trait. In the case that the path does not resolve to an actual
3371 // type, the result will be that the type name resolves to a module but not
3372 // a type (shadowing any imported modules or types with this name), leading
3373 // to weird user-visible bugs. So we ward this off here. See #15060.
3374 TyPath(ref path, path_id) => {
3375 match self.def_map.borrow().get(&path_id) {
3376 // FIXME: should we catch other options and give more precise errors?
3377 Some(&DefMod(_)) => {
3378 self.resolve_error(path.span, "inherent implementations are not \
3379 allowed for types not defined in \
3380 the current module");
3390 fn check_trait_item(&self, name: Name, span: Span) {
3391 // If there is a TraitRef in scope for an impl, then the method must be in the trait.
3392 for &(did, ref trait_ref) in self.current_trait_ref.iter() {
3393 if self.trait_item_map.get(&(name, did)).is_none() {
3394 let path_str = self.path_names_to_string(&trait_ref.path);
3395 self.resolve_error(span,
3396 &format!("method `{}` is not a member of trait `{}`",
3397 token::get_name(name),
3403 fn resolve_module(&mut self, module: &Mod, _span: Span,
3404 _name: Name, id: NodeId) {
3405 // Write the implementations in scope into the module metadata.
3406 debug!("(resolving module) resolving module ID {}", id);
3407 visit::walk_mod(self, module);
3410 fn resolve_local(&mut self, local: &Local) {
3411 // Resolve the type.
3412 if let Some(ref ty) = local.ty {
3413 self.resolve_type(&**ty);
3416 // Resolve the initializer, if necessary.
3421 Some(ref initializer) => {
3422 self.resolve_expr(&**initializer);
3426 // Resolve the pattern.
3427 let mut bindings_list = HashMap::new();
3428 self.resolve_pattern(&*local.pat,
3429 LocalIrrefutableMode,
3430 &mut bindings_list);
3433 // build a map from pattern identifiers to binding-info's.
3434 // this is done hygienically. This could arise for a macro
3435 // that expands into an or-pattern where one 'x' was from the
3436 // user and one 'x' came from the macro.
3437 fn binding_mode_map(&mut self, pat: &Pat) -> BindingMap {
3438 let mut result = HashMap::new();
3439 pat_bindings(&self.def_map, pat, |binding_mode, _id, sp, path1| {
3440 let name = mtwt::resolve(path1.node);
3441 result.insert(name, BindingInfo {
3443 binding_mode: binding_mode
3449 // check that all of the arms in an or-pattern have exactly the
3450 // same set of bindings, with the same binding modes for each.
3451 fn check_consistent_bindings(&mut self, arm: &Arm) {
3452 if arm.pats.len() == 0 {
3455 let map_0 = self.binding_mode_map(&*arm.pats[0]);
3456 for (i, p) in arm.pats.iter().enumerate() {
3457 let map_i = self.binding_mode_map(&**p);
3459 for (&key, &binding_0) in map_0.iter() {
3460 match map_i.get(&key) {
3464 &format!("variable `{}` from pattern #1 is \
3465 not bound in pattern #{}",
3466 token::get_name(key),
3469 Some(binding_i) => {
3470 if binding_0.binding_mode != binding_i.binding_mode {
3473 &format!("variable `{}` is bound with different \
3474 mode in pattern #{} than in pattern #1",
3475 token::get_name(key),
3482 for (&key, &binding) in map_i.iter() {
3483 if !map_0.contains_key(&key) {
3486 &format!("variable `{}` from pattern {}{} is \
3487 not bound in pattern {}1",
3488 token::get_name(key),
3489 "#", i + 1, "#")[]);
3495 fn resolve_arm(&mut self, arm: &Arm) {
3496 self.value_ribs.push(Rib::new(NormalRibKind));
3498 let mut bindings_list = HashMap::new();
3499 for pattern in arm.pats.iter() {
3500 self.resolve_pattern(&**pattern, RefutableMode, &mut bindings_list);
3503 // This has to happen *after* we determine which
3504 // pat_idents are variants
3505 self.check_consistent_bindings(arm);
3507 visit::walk_expr_opt(self, &arm.guard);
3508 self.resolve_expr(&*arm.body);
3510 self.value_ribs.pop();
3513 fn resolve_block(&mut self, block: &Block) {
3514 debug!("(resolving block) entering block");
3515 self.value_ribs.push(Rib::new(NormalRibKind));
3517 // Move down in the graph, if there's an anonymous module rooted here.
3518 let orig_module = self.current_module.clone();
3519 match orig_module.anonymous_children.borrow().get(&block.id) {
3520 None => { /* Nothing to do. */ }
3521 Some(anonymous_module) => {
3522 debug!("(resolving block) found anonymous module, moving \
3524 self.current_module = anonymous_module.clone();
3528 // Descend into the block.
3529 visit::walk_block(self, block);
3532 self.current_module = orig_module;
3534 self.value_ribs.pop();
3535 debug!("(resolving block) leaving block");
3538 fn resolve_type(&mut self, ty: &Ty) {
3540 // Like path expressions, the interpretation of path types depends
3541 // on whether the path has multiple elements in it or not.
3543 TyPath(ref path, path_id) => {
3544 // This is a path in the type namespace. Walk through scopes
3546 let mut result_def = None;
3548 // First, check to see whether the name is a primitive type.
3549 if path.segments.len() == 1 {
3550 let id = path.segments.last().unwrap().identifier;
3552 match self.primitive_type_table
3556 Some(&primitive_type) => {
3558 Some((DefPrimTy(primitive_type), LastMod(AllPublic)));
3560 if path.segments[0].parameters.has_lifetimes() {
3561 span_err!(self.session, path.span, E0157,
3562 "lifetime parameters are not allowed on this type");
3563 } else if !path.segments[0].parameters.is_empty() {
3564 span_err!(self.session, path.span, E0153,
3565 "type parameters are not allowed on this type");
3574 if let None = result_def {
3575 result_def = self.resolve_path(ty.id, path, TypeNS, true);
3580 // Write the result into the def map.
3581 debug!("(resolving type) writing resolution for `{}` \
3583 self.path_names_to_string(path),
3585 self.record_def(path_id, def);
3588 let msg = format!("use of undeclared type name `{}`",
3589 self.path_names_to_string(path));
3590 self.resolve_error(ty.span, &msg[]);
3595 TyObjectSum(ref ty, ref bound_vec) => {
3596 self.resolve_type(&**ty);
3597 self.resolve_type_parameter_bounds(ty.id, bound_vec,
3598 TraitBoundingTypeParameter);
3601 TyQPath(ref qpath) => {
3602 self.resolve_type(&*qpath.self_type);
3603 self.resolve_trait_reference(ty.id, &*qpath.trait_ref, TraitQPath);
3604 for ty in qpath.item_path.parameters.types().into_iter() {
3605 self.resolve_type(&**ty);
3607 for binding in qpath.item_path.parameters.bindings().into_iter() {
3608 self.resolve_type(&*binding.ty);
3612 TyPolyTraitRef(ref bounds) => {
3613 self.resolve_type_parameter_bounds(
3617 visit::walk_ty(self, ty);
3620 // Just resolve embedded types.
3621 visit::walk_ty(self, ty);
3626 fn resolve_pattern(&mut self,
3628 mode: PatternBindingMode,
3629 // Maps idents to the node ID for the (outermost)
3630 // pattern that binds them
3631 bindings_list: &mut HashMap<Name, NodeId>) {
3632 let pat_id = pattern.id;
3633 walk_pat(pattern, |pattern| {
3634 match pattern.node {
3635 PatIdent(binding_mode, ref path1, _) => {
3637 // The meaning of pat_ident with no type parameters
3638 // depends on whether an enum variant or unit-like struct
3639 // with that name is in scope. The probing lookup has to
3640 // be careful not to emit spurious errors. Only matching
3641 // patterns (match) can match nullary variants or
3642 // unit-like structs. For binding patterns (let), matching
3643 // such a value is simply disallowed (since it's rarely
3646 let ident = path1.node;
3647 let renamed = mtwt::resolve(ident);
3649 match self.resolve_bare_identifier_pattern(ident.name, pattern.span) {
3650 FoundStructOrEnumVariant(ref def, lp)
3651 if mode == RefutableMode => {
3652 debug!("(resolving pattern) resolving `{}` to \
3653 struct or enum variant",
3654 token::get_name(renamed));
3656 self.enforce_default_binding_mode(
3660 self.record_def(pattern.id, (def.clone(), lp));
3662 FoundStructOrEnumVariant(..) => {
3665 &format!("declaration of `{}` shadows an enum \
3666 variant or unit-like struct in \
3668 token::get_name(renamed))[]);
3670 FoundConst(ref def, lp) if mode == RefutableMode => {
3671 debug!("(resolving pattern) resolving `{}` to \
3673 token::get_name(renamed));
3675 self.enforce_default_binding_mode(
3679 self.record_def(pattern.id, (def.clone(), lp));
3682 self.resolve_error(pattern.span,
3683 "only irrefutable patterns \
3686 BareIdentifierPatternUnresolved => {
3687 debug!("(resolving pattern) binding `{}`",
3688 token::get_name(renamed));
3690 let def = DefLocal(pattern.id);
3692 // Record the definition so that later passes
3693 // will be able to distinguish variants from
3694 // locals in patterns.
3696 self.record_def(pattern.id, (def, LastMod(AllPublic)));
3698 // Add the binding to the local ribs, if it
3699 // doesn't already exist in the bindings list. (We
3700 // must not add it if it's in the bindings list
3701 // because that breaks the assumptions later
3702 // passes make about or-patterns.)
3703 if !bindings_list.contains_key(&renamed) {
3704 let this = &mut *self;
3705 let last_rib = this.value_ribs.last_mut().unwrap();
3706 last_rib.bindings.insert(renamed, DlDef(def));
3707 bindings_list.insert(renamed, pat_id);
3708 } else if mode == ArgumentIrrefutableMode &&
3709 bindings_list.contains_key(&renamed) {
3710 // Forbid duplicate bindings in the same
3712 self.resolve_error(pattern.span,
3713 &format!("identifier `{}` \
3721 } else if bindings_list.get(&renamed) ==
3723 // Then this is a duplicate variable in the
3724 // same disjunction, which is an error.
3725 self.resolve_error(pattern.span,
3726 &format!("identifier `{}` is bound \
3727 more than once in the same \
3729 token::get_ident(ident))[]);
3731 // Else, not bound in the same pattern: do
3737 PatEnum(ref path, _) => {
3738 // This must be an enum variant, struct or const.
3739 match self.resolve_path(pat_id, path, ValueNS, false) {
3740 Some(def @ (DefVariant(..), _)) |
3741 Some(def @ (DefStruct(..), _)) |
3742 Some(def @ (DefConst(..), _)) => {
3743 self.record_def(pattern.id, def);
3745 Some((DefStatic(..), _)) => {
3746 self.resolve_error(path.span,
3747 "static variables cannot be \
3748 referenced in a pattern, \
3749 use a `const` instead");
3752 self.resolve_error(path.span,
3753 format!("`{}` is not an enum variant, struct or const",
3755 path.segments.last().unwrap().identifier)).as_slice());
3758 self.resolve_error(path.span,
3759 format!("unresolved enum variant, struct or const `{}`",
3761 path.segments.last().unwrap().identifier)).as_slice());
3765 // Check the types in the path pattern.
3766 for ty in path.segments
3768 .flat_map(|s| s.parameters.types().into_iter()) {
3769 self.resolve_type(&**ty);
3773 PatLit(ref expr) => {
3774 self.resolve_expr(&**expr);
3777 PatRange(ref first_expr, ref last_expr) => {
3778 self.resolve_expr(&**first_expr);
3779 self.resolve_expr(&**last_expr);
3782 PatStruct(ref path, _, _) => {
3783 match self.resolve_path(pat_id, path, TypeNS, false) {
3784 Some(definition) => {
3785 self.record_def(pattern.id, definition);
3788 debug!("(resolving pattern) didn't find struct \
3789 def: {:?}", result);
3790 let msg = format!("`{}` does not name a structure",
3791 self.path_names_to_string(path));
3792 self.resolve_error(path.span, &msg[]);
3805 fn resolve_bare_identifier_pattern(&mut self, name: Name, span: Span)
3806 -> BareIdentifierPatternResolution {
3807 let module = self.current_module.clone();
3808 match self.resolve_item_in_lexical_scope(module,
3811 Success((target, _)) => {
3812 debug!("(resolve bare identifier pattern) succeeded in \
3813 finding {} at {:?}",
3814 token::get_name(name),
3815 target.bindings.value_def.borrow());
3816 match *target.bindings.value_def.borrow() {
3818 panic!("resolved name in the value namespace to a \
3819 set of name bindings with no def?!");
3822 // For the two success cases, this lookup can be
3823 // considered as not having a private component because
3824 // the lookup happened only within the current module.
3826 def @ DefVariant(..) | def @ DefStruct(..) => {
3827 return FoundStructOrEnumVariant(def, LastMod(AllPublic));
3829 def @ DefConst(..) => {
3830 return FoundConst(def, LastMod(AllPublic));
3833 self.resolve_error(span,
3834 "static variables cannot be \
3835 referenced in a pattern, \
3836 use a `const` instead");
3837 return BareIdentifierPatternUnresolved;
3840 return BareIdentifierPatternUnresolved;
3848 panic!("unexpected indeterminate result");
3852 Some((span, msg)) => {
3853 self.resolve_error(span, &format!("failed to resolve: {}",
3859 debug!("(resolve bare identifier pattern) failed to find {}",
3860 token::get_name(name));
3861 return BareIdentifierPatternUnresolved;
3866 /// If `check_ribs` is true, checks the local definitions first; i.e.
3867 /// doesn't skip straight to the containing module.
3868 fn resolve_path(&mut self,
3871 namespace: Namespace,
3872 check_ribs: bool) -> Option<(Def, LastPrivate)> {
3873 // First, resolve the types and associated type bindings.
3874 for ty in path.segments.iter().flat_map(|s| s.parameters.types().into_iter()) {
3875 self.resolve_type(&**ty);
3877 for binding in path.segments.iter().flat_map(|s| s.parameters.bindings().into_iter()) {
3878 self.resolve_type(&*binding.ty);
3881 // A special case for sugared associated type paths `T::A` where `T` is
3882 // a type parameter and `A` is an associated type on some bound of `T`.
3883 if namespace == TypeNS && path.segments.len() == 2 {
3884 match self.resolve_identifier(path.segments[0].identifier,
3888 Some((def, last_private)) => {
3890 DefTyParam(_, _, did, _) => {
3891 let def = DefAssociatedPath(TyParamProvenance::FromParam(did),
3892 path.segments.last()
3893 .unwrap().identifier);
3894 return Some((def, last_private));
3897 let def = DefAssociatedPath(TyParamProvenance::FromSelf(local_def(nid)),
3898 path.segments.last()
3899 .unwrap().identifier);
3900 return Some((def, last_private));
3910 return self.resolve_crate_relative_path(path, namespace);
3913 // Try to find a path to an item in a module.
3914 let unqualified_def =
3915 self.resolve_identifier(path.segments.last().unwrap().identifier,
3920 if path.segments.len() > 1 {
3921 let def = self.resolve_module_relative_path(path, namespace);
3922 match (def, unqualified_def) {
3923 (Some((ref d, _)), Some((ref ud, _))) if *d == *ud => {
3925 .add_lint(lint::builtin::UNUSED_QUALIFICATIONS,
3928 "unnecessary qualification".to_string());
3936 return unqualified_def;
3939 // resolve a single identifier (used as a varref)
3940 fn resolve_identifier(&mut self,
3942 namespace: Namespace,
3945 -> Option<(Def, LastPrivate)> {
3947 match self.resolve_identifier_in_local_ribs(identifier,
3951 return Some((def, LastMod(AllPublic)));
3959 return self.resolve_item_by_name_in_lexical_scope(identifier.name, namespace);
3962 // FIXME #4952: Merge me with resolve_name_in_module?
3963 fn resolve_definition_of_name_in_module(&mut self,
3964 containing_module: Rc<Module>,
3966 namespace: Namespace)
3968 // First, search children.
3969 build_reduced_graph::populate_module_if_necessary(self, &containing_module);
3971 match containing_module.children.borrow().get(&name) {
3972 Some(child_name_bindings) => {
3973 match child_name_bindings.def_for_namespace(namespace) {
3975 // Found it. Stop the search here.
3976 let p = child_name_bindings.defined_in_public_namespace(
3978 let lp = if p {LastMod(AllPublic)} else {
3979 LastMod(DependsOn(def.def_id()))
3981 return ChildNameDefinition(def, lp);
3989 // Next, search import resolutions.
3990 match containing_module.import_resolutions.borrow().get(&name) {
3991 Some(import_resolution) if import_resolution.is_public => {
3992 if let Some(target) = (*import_resolution).target_for_namespace(namespace) {
3993 match target.bindings.def_for_namespace(namespace) {
3996 let id = import_resolution.id(namespace);
3997 // track imports and extern crates as well
3998 self.used_imports.insert((id, namespace));
3999 self.record_import_use(id, name);
4000 match target.target_module.def_id.get() {
4001 Some(DefId{krate: kid, ..}) => {
4002 self.used_crates.insert(kid);
4006 return ImportNameDefinition(def, LastMod(AllPublic));
4009 // This can happen with external impls, due to
4010 // the imperfect way we read the metadata.
4015 Some(..) | None => {} // Continue.
4018 // Finally, search through external children.
4019 if namespace == TypeNS {
4020 if let Some(module) = containing_module.external_module_children.borrow()
4021 .get(&name).cloned() {
4022 if let Some(def_id) = module.def_id.get() {
4023 // track used crates
4024 self.used_crates.insert(def_id.krate);
4025 let lp = if module.is_public {LastMod(AllPublic)} else {
4026 LastMod(DependsOn(def_id))
4028 return ChildNameDefinition(DefMod(def_id), lp);
4033 return NoNameDefinition;
4036 // resolve a "module-relative" path, e.g. a::b::c
4037 fn resolve_module_relative_path(&mut self,
4039 namespace: Namespace)
4040 -> Option<(Def, LastPrivate)> {
4041 let module_path = path.segments.init().iter()
4042 .map(|ps| ps.identifier.name)
4043 .collect::<Vec<_>>();
4045 let containing_module;
4047 let module = self.current_module.clone();
4048 match self.resolve_module_path(module,
4054 let (span, msg) = match err {
4055 Some((span, msg)) => (span, msg),
4057 let msg = format!("Use of undeclared type or module `{}`",
4058 self.names_to_string(module_path.as_slice()));
4063 self.resolve_error(span, &format!("failed to resolve. {}",
4067 Indeterminate => panic!("indeterminate unexpected"),
4068 Success((resulting_module, resulting_last_private)) => {
4069 containing_module = resulting_module;
4070 last_private = resulting_last_private;
4074 let name = path.segments.last().unwrap().identifier.name;
4075 let def = match self.resolve_definition_of_name_in_module(containing_module.clone(),
4078 NoNameDefinition => {
4079 // We failed to resolve the name. Report an error.
4082 ChildNameDefinition(def, lp) | ImportNameDefinition(def, lp) => {
4083 (def, last_private.or(lp))
4086 if let Some(DefId{krate: kid, ..}) = containing_module.def_id.get() {
4087 self.used_crates.insert(kid);
4092 /// Invariant: This must be called only during main resolution, not during
4093 /// import resolution.
4094 fn resolve_crate_relative_path(&mut self,
4096 namespace: Namespace)
4097 -> Option<(Def, LastPrivate)> {
4098 let module_path = path.segments.init().iter()
4099 .map(|ps| ps.identifier.name)
4100 .collect::<Vec<_>>();
4102 let root_module = self.graph_root.get_module();
4104 let containing_module;
4106 match self.resolve_module_path_from_root(root_module,
4111 LastMod(AllPublic)) {
4113 let (span, msg) = match err {
4114 Some((span, msg)) => (span, msg),
4116 let msg = format!("Use of undeclared module `::{}`",
4117 self.names_to_string(&module_path[]));
4122 self.resolve_error(span, &format!("failed to resolve. {}",
4128 panic!("indeterminate unexpected");
4131 Success((resulting_module, resulting_last_private)) => {
4132 containing_module = resulting_module;
4133 last_private = resulting_last_private;
4137 let name = path.segments.last().unwrap().identifier.name;
4138 match self.resolve_definition_of_name_in_module(containing_module,
4141 NoNameDefinition => {
4142 // We failed to resolve the name. Report an error.
4145 ChildNameDefinition(def, lp) | ImportNameDefinition(def, lp) => {
4146 return Some((def, last_private.or(lp)));
4151 fn resolve_identifier_in_local_ribs(&mut self,
4153 namespace: Namespace,
4156 // Check the local set of ribs.
4157 let search_result = match namespace {
4159 let renamed = mtwt::resolve(ident);
4160 self.search_ribs(self.value_ribs.as_slice(), renamed, span)
4163 let name = ident.name;
4164 self.search_ribs(&self.type_ribs[], name, span)
4168 match search_result {
4169 Some(DlDef(def)) => {
4170 debug!("(resolving path in local ribs) resolved `{}` to \
4172 token::get_ident(ident),
4176 Some(DlField) | Some(DlImpl(_)) | None => {
4182 fn resolve_item_by_name_in_lexical_scope(&mut self,
4184 namespace: Namespace)
4185 -> Option<(Def, LastPrivate)> {
4187 let module = self.current_module.clone();
4188 match self.resolve_item_in_lexical_scope(module,
4191 Success((target, _)) => {
4192 match (*target.bindings).def_for_namespace(namespace) {
4194 // This can happen if we were looking for a type and
4195 // found a module instead. Modules don't have defs.
4196 debug!("(resolving item path by identifier in lexical \
4197 scope) failed to resolve {} after success...",
4198 token::get_name(name));
4202 debug!("(resolving item path in lexical scope) \
4203 resolved `{}` to item",
4204 token::get_name(name));
4205 // This lookup is "all public" because it only searched
4206 // for one identifier in the current module (couldn't
4207 // have passed through reexports or anything like that.
4208 return Some((def, LastMod(AllPublic)));
4213 panic!("unexpected indeterminate result");
4217 Some((span, msg)) =>
4218 self.resolve_error(span, &format!("failed to resolve. {}",
4223 debug!("(resolving item path by identifier in lexical scope) \
4224 failed to resolve {}", token::get_name(name));
4230 fn with_no_errors<T, F>(&mut self, f: F) -> T where
4231 F: FnOnce(&mut Resolver) -> T,
4233 self.emit_errors = false;
4235 self.emit_errors = true;
4239 fn resolve_error(&self, span: Span, s: &str) {
4240 if self.emit_errors {
4241 self.session.span_err(span, s);
4245 fn find_fallback_in_self_type(&mut self, name: Name) -> FallbackSuggestion {
4246 fn extract_path_and_node_id(t: &Ty, allow: FallbackChecks)
4247 -> Option<(Path, NodeId, FallbackChecks)> {
4249 TyPath(ref path, node_id) => Some((path.clone(), node_id, allow)),
4250 TyPtr(ref mut_ty) => extract_path_and_node_id(&*mut_ty.ty, OnlyTraitAndStatics),
4251 TyRptr(_, ref mut_ty) => extract_path_and_node_id(&*mut_ty.ty, allow),
4252 // This doesn't handle the remaining `Ty` variants as they are not
4253 // that commonly the self_type, it might be interesting to provide
4254 // support for those in future.
4259 fn get_module(this: &mut Resolver, span: Span, name_path: &[ast::Name])
4260 -> Option<Rc<Module>> {
4261 let root = this.current_module.clone();
4262 let last_name = name_path.last().unwrap();
4264 if name_path.len() == 1 {
4265 match this.primitive_type_table.primitive_types.get(last_name) {
4268 match this.current_module.children.borrow().get(last_name) {
4269 Some(child) => child.get_module_if_available(),
4275 match this.resolve_module_path(root,
4280 Success((module, _)) => Some(module),
4286 let (path, node_id, allowed) = match self.current_self_type {
4287 Some(ref ty) => match extract_path_and_node_id(ty, Everything) {
4289 None => return NoSuggestion,
4291 None => return NoSuggestion,
4294 if allowed == Everything {
4295 // Look for a field with the same name in the current self_type.
4296 match self.def_map.borrow().get(&node_id) {
4297 Some(&DefTy(did, _))
4298 | Some(&DefStruct(did))
4299 | Some(&DefVariant(_, did, _)) => match self.structs.get(&did) {
4302 if fields.iter().any(|&field_name| name == field_name) {
4307 _ => {} // Self type didn't resolve properly
4311 let name_path = path.segments.iter().map(|seg| seg.identifier.name).collect::<Vec<_>>();
4313 // Look for a method in the current self type's impl module.
4314 match get_module(self, path.span, &name_path[]) {
4315 Some(module) => match module.children.borrow().get(&name) {
4317 let p_str = self.path_names_to_string(&path);
4318 match binding.def_for_namespace(ValueNS) {
4319 Some(DefStaticMethod(_, provenance)) => {
4321 FromImpl(_) => return StaticMethod(p_str),
4322 FromTrait(_) => unreachable!()
4325 Some(DefMethod(_, None, _)) if allowed == Everything => return Method,
4326 Some(DefMethod(_, Some(_), _)) => return TraitItem,
4335 // Look for a method in the current trait.
4336 match self.current_trait_ref {
4337 Some((did, ref trait_ref)) => {
4338 let path_str = self.path_names_to_string(&trait_ref.path);
4340 match self.trait_item_map.get(&(name, did)) {
4341 Some(&StaticMethodTraitItemKind) => {
4342 return TraitMethod(path_str)
4344 Some(_) => return TraitItem,
4354 fn find_best_match_for_name(&mut self, name: &str, max_distance: uint)
4356 let this = &mut *self;
4358 let mut maybes: Vec<token::InternedString> = Vec::new();
4359 let mut values: Vec<uint> = Vec::new();
4361 for rib in this.value_ribs.iter().rev() {
4362 for (&k, _) in rib.bindings.iter() {
4363 maybes.push(token::get_name(k));
4364 values.push(uint::MAX);
4368 let mut smallest = 0;
4369 for (i, other) in maybes.iter().enumerate() {
4370 values[i] = lev_distance(name, other.get());
4372 if values[i] <= values[smallest] {
4377 if values.len() > 0 &&
4378 values[smallest] != uint::MAX &&
4379 values[smallest] < name.len() + 2 &&
4380 values[smallest] <= max_distance &&
4381 name != maybes[smallest].get() {
4383 Some(maybes[smallest].get().to_string())
4390 fn resolve_expr(&mut self, expr: &Expr) {
4391 // First, record candidate traits for this expression if it could
4392 // result in the invocation of a method call.
4394 self.record_candidate_traits_for_expr_if_necessary(expr);
4396 // Next, resolve the node.
4398 // The interpretation of paths depends on whether the path has
4399 // multiple elements in it or not.
4401 ExprPath(_) | ExprQPath(_) => {
4402 let mut path_from_qpath;
4403 let path = match expr.node {
4404 ExprPath(ref path) => path,
4405 ExprQPath(ref qpath) => {
4406 self.resolve_type(&*qpath.self_type);
4407 self.resolve_trait_reference(expr.id, &*qpath.trait_ref, TraitQPath);
4408 path_from_qpath = qpath.trait_ref.path.clone();
4409 path_from_qpath.segments.push(qpath.item_path.clone());
4414 // This is a local path in the value namespace. Walk through
4415 // scopes looking for it.
4416 match self.resolve_path(expr.id, path, ValueNS, true) {
4417 // Check if struct variant
4418 Some((DefVariant(_, _, true), _)) => {
4419 let path_name = self.path_names_to_string(path);
4420 self.resolve_error(expr.span,
4421 format!("`{}` is a struct variant name, but \
4423 uses it like a function name",
4424 path_name).as_slice());
4426 self.session.span_help(expr.span,
4427 format!("Did you mean to write: \
4428 `{} {{ /* fields */ }}`?",
4429 path_name).as_slice());
4432 // Write the result into the def map.
4433 debug!("(resolving expr) resolved `{}`",
4434 self.path_names_to_string(path));
4436 self.record_def(expr.id, def);
4439 // Be helpful if the name refers to a struct
4440 // (The pattern matching def_tys where the id is in self.structs
4441 // matches on regular structs while excluding tuple- and enum-like
4442 // structs, which wouldn't result in this error.)
4443 let path_name = self.path_names_to_string(path);
4444 match self.with_no_errors(|this|
4445 this.resolve_path(expr.id, path, TypeNS, false)) {
4446 Some((DefTy(struct_id, _), _))
4447 if self.structs.contains_key(&struct_id) => {
4448 self.resolve_error(expr.span,
4449 format!("`{}` is a structure name, but \
4451 uses it like a function name",
4452 path_name).as_slice());
4454 self.session.span_help(expr.span,
4455 format!("Did you mean to write: \
4456 `{} {{ /* fields */ }}`?",
4457 path_name).as_slice());
4461 let mut method_scope = false;
4462 self.value_ribs.iter().rev().all(|rib| {
4463 let res = match *rib {
4464 Rib { bindings: _, kind: MethodRibKind(_, _) } => true,
4465 Rib { bindings: _, kind: ItemRibKind } => false,
4466 _ => return true, // Keep advancing
4470 false // Stop advancing
4473 if method_scope && token::get_name(self.self_name).get()
4477 "`self` is not available \
4478 in a static method. Maybe a \
4479 `self` argument is missing?");
4481 let last_name = path.segments.last().unwrap().identifier.name;
4482 let mut msg = match self.find_fallback_in_self_type(last_name) {
4484 // limit search to 5 to reduce the number
4485 // of stupid suggestions
4486 self.find_best_match_for_name(path_name.as_slice(), 5)
4487 .map_or("".to_string(),
4488 |x| format!("`{}`", x))
4491 format!("`self.{}`", path_name),
4494 format!("to call `self.{}`", path_name),
4495 TraitMethod(path_str)
4496 | StaticMethod(path_str) =>
4497 format!("to call `{}::{}`", path_str, path_name)
4501 msg = format!(". Did you mean {}?", msg)
4506 format!("unresolved name `{}`{}",
4515 visit::walk_expr(self, expr);
4518 ExprClosure(capture_clause, _, ref fn_decl, ref block) => {
4519 self.capture_mode_map.insert(expr.id, capture_clause);
4520 self.resolve_function(ClosureRibKind(expr.id, ast::DUMMY_NODE_ID),
4521 Some(&**fn_decl), NoTypeParameters,
4525 ExprStruct(ref path, _, _) => {
4526 // Resolve the path to the structure it goes to. We don't
4527 // check to ensure that the path is actually a structure; that
4528 // is checked later during typeck.
4529 match self.resolve_path(expr.id, path, TypeNS, false) {
4530 Some(definition) => self.record_def(expr.id, definition),
4532 debug!("(resolving expression) didn't find struct \
4533 def: {:?}", result);
4534 let msg = format!("`{}` does not name a structure",
4535 self.path_names_to_string(path));
4536 self.resolve_error(path.span, &msg[]);
4540 visit::walk_expr(self, expr);
4543 ExprLoop(_, Some(label)) | ExprWhile(_, _, Some(label)) => {
4544 self.with_label_rib(|this| {
4545 let def_like = DlDef(DefLabel(expr.id));
4548 let rib = this.label_ribs.last_mut().unwrap();
4549 let renamed = mtwt::resolve(label);
4550 rib.bindings.insert(renamed, def_like);
4553 visit::walk_expr(this, expr);
4557 ExprForLoop(ref pattern, ref head, ref body, optional_label) => {
4558 self.resolve_expr(&**head);
4560 self.value_ribs.push(Rib::new(NormalRibKind));
4562 self.resolve_pattern(&**pattern,
4563 LocalIrrefutableMode,
4564 &mut HashMap::new());
4566 match optional_label {
4570 .push(Rib::new(NormalRibKind));
4571 let def_like = DlDef(DefLabel(expr.id));
4574 let rib = self.label_ribs.last_mut().unwrap();
4575 let renamed = mtwt::resolve(label);
4576 rib.bindings.insert(renamed, def_like);
4581 self.resolve_block(&**body);
4583 if optional_label.is_some() {
4584 drop(self.label_ribs.pop())
4587 self.value_ribs.pop();
4590 ExprBreak(Some(label)) | ExprAgain(Some(label)) => {
4591 let renamed = mtwt::resolve(label);
4592 match self.search_label(renamed) {
4596 &format!("use of undeclared label `{}`",
4597 token::get_ident(label))[])
4599 Some(DlDef(def @ DefLabel(_))) => {
4600 // Since this def is a label, it is never read.
4601 self.record_def(expr.id, (def, LastMod(AllPublic)))
4604 self.session.span_bug(expr.span,
4605 "label wasn't mapped to a \
4612 visit::walk_expr(self, expr);
4617 fn record_candidate_traits_for_expr_if_necessary(&mut self, expr: &Expr) {
4619 ExprField(_, ident) => {
4620 // FIXME(#6890): Even though you can't treat a method like a
4621 // field, we need to add any trait methods we find that match
4622 // the field name so that we can do some nice error reporting
4623 // later on in typeck.
4624 let traits = self.search_for_traits_containing_method(ident.node.name);
4625 self.trait_map.insert(expr.id, traits);
4627 ExprMethodCall(ident, _, _) => {
4628 debug!("(recording candidate traits for expr) recording \
4631 let traits = self.search_for_traits_containing_method(ident.node.name);
4632 self.trait_map.insert(expr.id, traits);
4640 fn search_for_traits_containing_method(&mut self, name: Name) -> Vec<DefId> {
4641 debug!("(searching for traits containing method) looking for '{}'",
4642 token::get_name(name));
4644 fn add_trait_info(found_traits: &mut Vec<DefId>,
4645 trait_def_id: DefId,
4647 debug!("(adding trait info) found trait {}:{} for method '{}'",
4650 token::get_name(name));
4651 found_traits.push(trait_def_id);
4654 let mut found_traits = Vec::new();
4655 let mut search_module = self.current_module.clone();
4657 // Look for the current trait.
4658 match self.current_trait_ref {
4659 Some((trait_def_id, _)) => {
4660 if self.trait_item_map.contains_key(&(name, trait_def_id)) {
4661 add_trait_info(&mut found_traits, trait_def_id, name);
4664 None => {} // Nothing to do.
4667 // Look for trait children.
4668 build_reduced_graph::populate_module_if_necessary(self, &search_module);
4671 for (_, child_names) in search_module.children.borrow().iter() {
4672 let def = match child_names.def_for_namespace(TypeNS) {
4676 let trait_def_id = match def {
4677 DefTrait(trait_def_id) => trait_def_id,
4680 if self.trait_item_map.contains_key(&(name, trait_def_id)) {
4681 add_trait_info(&mut found_traits, trait_def_id, name);
4686 // Look for imports.
4687 for (_, import) in search_module.import_resolutions.borrow().iter() {
4688 let target = match import.target_for_namespace(TypeNS) {
4690 Some(target) => target,
4692 let did = match target.bindings.def_for_namespace(TypeNS) {
4693 Some(DefTrait(trait_def_id)) => trait_def_id,
4694 Some(..) | None => continue,
4696 if self.trait_item_map.contains_key(&(name, did)) {
4697 add_trait_info(&mut found_traits, did, name);
4698 let id = import.type_id;
4699 self.used_imports.insert((id, TypeNS));
4700 let trait_name = self.get_trait_name(did);
4701 self.record_import_use(id, trait_name);
4702 if let Some(DefId{krate: kid, ..}) = target.target_module.def_id.get() {
4703 self.used_crates.insert(kid);
4708 match search_module.parent_link.clone() {
4709 NoParentLink | ModuleParentLink(..) => break,
4710 BlockParentLink(parent_module, _) => {
4711 search_module = parent_module.upgrade().unwrap();
4719 fn record_def(&mut self, node_id: NodeId, (def, lp): (Def, LastPrivate)) {
4720 debug!("(recording def) recording {:?} for {}, last private {:?}",
4722 assert!(match lp {LastImport{..} => false, _ => true},
4723 "Import should only be used for `use` directives");
4724 self.last_private.insert(node_id, lp);
4726 match self.def_map.borrow_mut().entry(node_id) {
4727 // Resolve appears to "resolve" the same ID multiple
4728 // times, so here is a sanity check it at least comes to
4729 // the same conclusion! - nmatsakis
4730 Occupied(entry) => if def != *entry.get() {
4732 .bug(&format!("node_id {} resolved first to {:?} and \
4738 Vacant(entry) => { entry.insert(def); },
4742 fn enforce_default_binding_mode(&mut self,
4744 pat_binding_mode: BindingMode,
4746 match pat_binding_mode {
4747 BindByValue(_) => {}
4749 self.resolve_error(pat.span,
4750 &format!("cannot use `ref` binding mode \
4760 // Diagnostics are not particularly efficient, because they're rarely
4764 /// A somewhat inefficient routine to obtain the name of a module.
4765 fn module_to_string(&self, module: &Module) -> String {
4766 let mut names = Vec::new();
4768 fn collect_mod(names: &mut Vec<ast::Name>, module: &Module) {
4769 match module.parent_link {
4771 ModuleParentLink(ref module, name) => {
4773 collect_mod(names, &*module.upgrade().unwrap());
4775 BlockParentLink(ref module, _) => {
4776 // danger, shouldn't be ident?
4777 names.push(special_idents::opaque.name);
4778 collect_mod(names, &*module.upgrade().unwrap());
4782 collect_mod(&mut names, module);
4784 if names.len() == 0 {
4785 return "???".to_string();
4787 self.names_to_string(&names.into_iter().rev()
4788 .collect::<Vec<ast::Name>>()[])
4791 #[allow(dead_code)] // useful for debugging
4792 fn dump_module(&mut self, module_: Rc<Module>) {
4793 debug!("Dump of module `{}`:", self.module_to_string(&*module_));
4795 debug!("Children:");
4796 build_reduced_graph::populate_module_if_necessary(self, &module_);
4797 for (&name, _) in module_.children.borrow().iter() {
4798 debug!("* {}", token::get_name(name));
4801 debug!("Import resolutions:");
4802 let import_resolutions = module_.import_resolutions.borrow();
4803 for (&name, import_resolution) in import_resolutions.iter() {
4805 match import_resolution.target_for_namespace(ValueNS) {
4806 None => { value_repr = "".to_string(); }
4808 value_repr = " value:?".to_string();
4814 match import_resolution.target_for_namespace(TypeNS) {
4815 None => { type_repr = "".to_string(); }
4817 type_repr = " type:?".to_string();
4822 debug!("* {}:{}{}", token::get_name(name), value_repr, type_repr);
4827 pub struct CrateMap {
4828 pub def_map: DefMap,
4829 pub freevars: RefCell<FreevarMap>,
4830 pub capture_mode_map: RefCell<CaptureModeMap>,
4831 pub export_map: ExportMap,
4832 pub trait_map: TraitMap,
4833 pub external_exports: ExternalExports,
4834 pub last_private_map: LastPrivateMap,
4835 pub glob_map: Option<GlobMap>
4838 #[derive(PartialEq,Copy)]
4839 pub enum MakeGlobMap {
4844 /// Entry point to crate resolution.
4845 pub fn resolve_crate<'a, 'tcx>(session: &'a Session,
4846 ast_map: &'a ast_map::Map<'tcx>,
4849 make_glob_map: MakeGlobMap)
4851 let mut resolver = Resolver::new(session, ast_map, krate.span, make_glob_map);
4853 build_reduced_graph::build_reduced_graph(&mut resolver, krate);
4854 session.abort_if_errors();
4856 resolver.resolve_imports();
4857 session.abort_if_errors();
4859 record_exports::record(&mut resolver);
4860 session.abort_if_errors();
4862 resolver.resolve_crate(krate);
4863 session.abort_if_errors();
4865 check_unused::check_crate(&mut resolver, krate);
4868 def_map: resolver.def_map,
4869 freevars: resolver.freevars,
4870 capture_mode_map: RefCell::new(resolver.capture_mode_map),
4871 export_map: resolver.export_map,
4872 trait_map: resolver.trait_map,
4873 external_exports: resolver.external_exports,
4874 last_private_map: resolver.last_private,
4875 glob_map: if resolver.make_glob_map {
4876 Some(resolver.glob_map)