1 // Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
11 #![crate_name = "rustc_resolve"]
12 #![unstable(feature = "rustc_private")]
14 #![crate_type = "dylib"]
15 #![crate_type = "rlib"]
16 #![doc(html_logo_url = "http://www.rust-lang.org/logos/rust-logo-128x128-blk-v2.png",
17 html_favicon_url = "http://www.rust-lang.org/favicon.ico",
18 html_root_url = "http://doc.rust-lang.org/nightly/")]
21 #![feature(collections)]
25 #![feature(rustc_diagnostic_macros)]
26 #![feature(rustc_private)]
27 #![feature(slicing_syntax)]
28 #![feature(staged_api)]
31 #[macro_use] extern crate log;
32 #[macro_use] extern crate syntax;
33 #[macro_use] #[no_link] extern crate rustc_bitflags;
37 use self::PatternBindingMode::*;
38 use self::Namespace::*;
39 use self::NamespaceResult::*;
40 use self::NameDefinition::*;
41 use self::ImportDirectiveSubclass::*;
42 use self::ResolveResult::*;
43 use self::FallbackSuggestion::*;
44 use self::TypeParameters::*;
46 use self::MethodSort::*;
47 use self::UseLexicalScopeFlag::*;
48 use self::ModulePrefixResult::*;
49 use self::NameSearchType::*;
50 use self::BareIdentifierPatternResolution::*;
51 use self::ParentLink::*;
52 use self::ModuleKind::*;
53 use self::TraitReferenceType::*;
54 use self::FallbackChecks::*;
56 use rustc::session::Session;
58 use rustc::metadata::csearch;
59 use rustc::metadata::decoder::{DefLike, DlDef, DlField, DlImpl};
60 use rustc::middle::def::*;
61 use rustc::middle::lang_items::LanguageItems;
62 use rustc::middle::pat_util::pat_bindings;
63 use rustc::middle::privacy::*;
64 use rustc::middle::subst::{ParamSpace, FnSpace, TypeSpace};
65 use rustc::middle::ty::{Freevar, FreevarMap, TraitMap, GlobMap};
66 use rustc::util::nodemap::{NodeMap, NodeSet, DefIdSet, FnvHashMap};
67 use rustc::util::lev_distance::lev_distance;
69 use syntax::ast::{Arm, BindByRef, BindByValue, BindingMode, Block, Crate, CrateNum};
70 use syntax::ast::{DefId, Expr, ExprAgain, ExprBreak, ExprField};
71 use syntax::ast::{ExprClosure, ExprLoop, ExprWhile, ExprMethodCall};
72 use syntax::ast::{ExprPath, ExprQPath, ExprStruct, FnDecl};
73 use syntax::ast::{ForeignItemFn, ForeignItemStatic, Generics};
74 use syntax::ast::{Ident, ImplItem, Item, ItemConst, ItemEnum, ItemExternCrate};
75 use syntax::ast::{ItemFn, ItemForeignMod, ItemImpl, ItemMac, ItemMod, ItemStatic};
76 use syntax::ast::{ItemStruct, ItemTrait, ItemTy, ItemUse};
77 use syntax::ast::{Local, MethodImplItem, Mod, Name, NodeId};
78 use syntax::ast::{Pat, PatEnum, PatIdent, PatLit};
79 use syntax::ast::{PatRange, PatStruct, Path};
80 use syntax::ast::{PolyTraitRef, PrimTy, SelfExplicit};
81 use syntax::ast::{RegionTyParamBound, StructField};
82 use syntax::ast::{TraitRef, TraitTyParamBound};
83 use syntax::ast::{Ty, TyBool, TyChar, TyF32};
84 use syntax::ast::{TyF64, TyFloat, TyIs, TyI8, TyI16, TyI32, TyI64, TyInt, TyObjectSum};
85 use syntax::ast::{TyParam, TyParamBound, TyPath, TyPtr, TyPolyTraitRef, TyQPath};
86 use syntax::ast::{TyRptr, TyStr, TyUs, TyU8, TyU16, TyU32, TyU64, TyUint};
87 use syntax::ast::{TypeImplItem};
90 use syntax::ast_util::{PostExpansionMethod, local_def, walk_pat};
91 use syntax::attr::AttrMetaMethods;
92 use syntax::ext::mtwt;
93 use syntax::parse::token::{self, special_names, special_idents};
94 use syntax::codemap::{Span, Pos};
95 use syntax::owned_slice::OwnedSlice;
96 use syntax::visit::{self, Visitor};
98 use std::collections::{HashMap, HashSet};
99 use std::collections::hash_map::Entry::{Occupied, Vacant};
100 use std::cell::{Cell, RefCell};
102 use std::mem::replace;
103 use std::rc::{Rc, Weak};
106 // NB: This module needs to be declared first so diagnostics are
107 // registered before they are used.
112 mod build_reduced_graph;
117 binding_mode: BindingMode,
120 // Map from the name in a pattern to its binding mode.
121 type BindingMap = HashMap<Name, BindingInfo>;
123 #[derive(Copy, PartialEq)]
124 enum PatternBindingMode {
126 LocalIrrefutableMode,
127 ArgumentIrrefutableMode,
130 #[derive(Copy, PartialEq, Eq, Hash, Debug)]
136 /// A NamespaceResult represents the result of resolving an import in
137 /// a particular namespace. The result is either definitely-resolved,
138 /// definitely- unresolved, or unknown.
140 enum NamespaceResult {
141 /// Means that resolve hasn't gathered enough information yet to determine
142 /// whether the name is bound in this namespace. (That is, it hasn't
143 /// resolved all `use` directives yet.)
145 /// Means that resolve has determined that the name is definitely
146 /// not bound in the namespace.
148 /// Means that resolve has determined that the name is bound in the Module
149 /// argument, and specified by the NameBindings argument.
150 BoundResult(Rc<Module>, Rc<NameBindings>)
153 impl NamespaceResult {
154 fn is_unknown(&self) -> bool {
156 UnknownResult => true,
160 fn is_unbound(&self) -> bool {
162 UnboundResult => true,
168 enum NameDefinition {
169 NoNameDefinition, //< The name was unbound.
170 ChildNameDefinition(Def, LastPrivate), //< The name identifies an immediate child.
171 ImportNameDefinition(Def, LastPrivate) //< The name identifies an import.
174 impl<'a, 'v, 'tcx> Visitor<'v> for Resolver<'a, 'tcx> {
175 fn visit_item(&mut self, item: &Item) {
176 self.resolve_item(item);
178 fn visit_arm(&mut self, arm: &Arm) {
179 self.resolve_arm(arm);
181 fn visit_block(&mut self, block: &Block) {
182 self.resolve_block(block);
184 fn visit_expr(&mut self, expr: &Expr) {
185 self.resolve_expr(expr);
187 fn visit_local(&mut self, local: &Local) {
188 self.resolve_local(local);
190 fn visit_ty(&mut self, ty: &Ty) {
191 self.resolve_type(ty);
195 /// Contains data for specific types of import directives.
196 #[derive(Copy,Debug)]
197 enum ImportDirectiveSubclass {
198 SingleImport(Name /* target */, Name /* source */),
202 type ErrorMessage = Option<(Span, String)>;
204 enum ResolveResult<T> {
205 Failed(ErrorMessage), // Failed to resolve the name, optional helpful error message.
206 Indeterminate, // Couldn't determine due to unresolved globs.
207 Success(T) // Successfully resolved the import.
210 impl<T> ResolveResult<T> {
211 fn indeterminate(&self) -> bool {
212 match *self { Indeterminate => true, _ => false }
216 enum FallbackSuggestion {
221 StaticMethod(String),
226 enum TypeParameters<'a> {
232 // Identifies the things that these parameters
233 // were declared on (type, fn, etc)
236 // ID of the enclosing item.
239 // The kind of the rib used for type parameters.
243 // The rib kind controls the translation of local
244 // definitions (`DefLocal`) to upvars (`DefUpvar`).
245 #[derive(Copy, Debug)]
247 // No translation needs to be applied.
250 // We passed through a closure scope at the given node ID.
251 // Translate upvars as appropriate.
252 ClosureRibKind(NodeId /* func id */),
254 // We passed through an impl or trait and are now in one of its
255 // methods. Allow references to ty params that impl or trait
256 // binds. Disallow any other upvars (including other ty params that are
258 // parent; method itself
259 MethodRibKind(NodeId, MethodSort),
261 // We passed through an item scope. Disallow upvars.
264 // We're in a constant item. Can't refer to dynamic stuff.
268 // Methods can be required or provided. RequiredMethod methods only occur in traits.
269 #[derive(Copy, Debug)]
272 ProvidedMethod(NodeId)
276 enum UseLexicalScopeFlag {
281 enum ModulePrefixResult {
283 PrefixFound(Rc<Module>, uint)
286 #[derive(Copy, PartialEq)]
287 enum NameSearchType {
288 /// We're doing a name search in order to resolve a `use` directive.
291 /// We're doing a name search in order to resolve a path type, a path
292 /// expression, or a path pattern.
297 enum BareIdentifierPatternResolution {
298 FoundStructOrEnumVariant(Def, LastPrivate),
299 FoundConst(Def, LastPrivate),
300 BareIdentifierPatternUnresolved
306 bindings: HashMap<Name, DefLike>,
311 fn new(kind: RibKind) -> Rib {
313 bindings: HashMap::new(),
319 /// Whether an import can be shadowed by another import.
320 #[derive(Debug,PartialEq,Clone,Copy)]
326 /// One import directive.
328 struct ImportDirective {
329 module_path: Vec<Name>,
330 subclass: ImportDirectiveSubclass,
333 is_public: bool, // see note in ImportResolution about how to use this
334 shadowable: Shadowable,
337 impl ImportDirective {
338 fn new(module_path: Vec<Name> ,
339 subclass: ImportDirectiveSubclass,
343 shadowable: Shadowable)
346 module_path: module_path,
350 is_public: is_public,
351 shadowable: shadowable,
356 /// The item that an import resolves to.
357 #[derive(Clone,Debug)]
359 target_module: Rc<Module>,
360 bindings: Rc<NameBindings>,
361 shadowable: Shadowable,
365 fn new(target_module: Rc<Module>,
366 bindings: Rc<NameBindings>,
367 shadowable: Shadowable)
370 target_module: target_module,
372 shadowable: shadowable,
377 /// An ImportResolution represents a particular `use` directive.
379 struct ImportResolution {
380 /// Whether this resolution came from a `use` or a `pub use`. Note that this
381 /// should *not* be used whenever resolution is being performed, this is
382 /// only looked at for glob imports statements currently. Privacy testing
383 /// occurs during a later phase of compilation.
386 // The number of outstanding references to this name. When this reaches
387 // zero, outside modules can count on the targets being correct. Before
388 // then, all bets are off; future imports could override this name.
389 outstanding_references: uint,
391 /// The value that this `use` directive names, if there is one.
392 value_target: Option<Target>,
393 /// The source node of the `use` directive leading to the value target
397 /// The type that this `use` directive names, if there is one.
398 type_target: Option<Target>,
399 /// The source node of the `use` directive leading to the type target
404 impl ImportResolution {
405 fn new(id: NodeId, is_public: bool) -> ImportResolution {
409 outstanding_references: 0,
412 is_public: is_public,
416 fn target_for_namespace(&self, namespace: Namespace)
419 TypeNS => self.type_target.clone(),
420 ValueNS => self.value_target.clone(),
424 fn id(&self, namespace: Namespace) -> NodeId {
426 TypeNS => self.type_id,
427 ValueNS => self.value_id,
431 fn shadowable(&self, namespace: Namespace) -> Shadowable {
432 let target = self.target_for_namespace(namespace);
433 if target.is_none() {
434 return Shadowable::Always;
437 target.unwrap().shadowable
440 fn set_target_and_id(&mut self,
441 namespace: Namespace,
442 target: Option<Target>,
446 self.type_target = target;
450 self.value_target = target;
457 /// The link from a module up to its nearest parent node.
458 #[derive(Clone,Debug)]
461 ModuleParentLink(Weak<Module>, Name),
462 BlockParentLink(Weak<Module>, NodeId)
465 /// The type of module this is.
466 #[derive(Copy, PartialEq, Debug)]
476 /// One node in the tree of modules.
478 parent_link: ParentLink,
479 def_id: Cell<Option<DefId>>,
480 kind: Cell<ModuleKind>,
483 children: RefCell<HashMap<Name, Rc<NameBindings>>>,
484 imports: RefCell<Vec<ImportDirective>>,
486 // The external module children of this node that were declared with
488 external_module_children: RefCell<HashMap<Name, Rc<Module>>>,
490 // The anonymous children of this node. Anonymous children are pseudo-
491 // modules that are implicitly created around items contained within
494 // For example, if we have this:
502 // There will be an anonymous module created around `g` with the ID of the
503 // entry block for `f`.
504 anonymous_children: RefCell<NodeMap<Rc<Module>>>,
506 // The status of resolving each import in this module.
507 import_resolutions: RefCell<HashMap<Name, ImportResolution>>,
509 // The number of unresolved globs that this module exports.
510 glob_count: Cell<uint>,
512 // The index of the import we're resolving.
513 resolved_import_count: Cell<uint>,
515 // Whether this module is populated. If not populated, any attempt to
516 // access the children must be preceded with a
517 // `populate_module_if_necessary` call.
518 populated: Cell<bool>,
522 fn new(parent_link: ParentLink,
523 def_id: Option<DefId>,
529 parent_link: parent_link,
530 def_id: Cell::new(def_id),
531 kind: Cell::new(kind),
532 is_public: is_public,
533 children: RefCell::new(HashMap::new()),
534 imports: RefCell::new(Vec::new()),
535 external_module_children: RefCell::new(HashMap::new()),
536 anonymous_children: RefCell::new(NodeMap()),
537 import_resolutions: RefCell::new(HashMap::new()),
538 glob_count: Cell::new(0),
539 resolved_import_count: Cell::new(0),
540 populated: Cell::new(!external),
544 fn all_imports_resolved(&self) -> bool {
545 self.imports.borrow().len() == self.resolved_import_count.get()
549 impl fmt::Debug for Module {
550 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
551 write!(f, "{:?}, kind: {:?}, {}",
554 if self.is_public { "public" } else { "private" } )
560 flags DefModifiers: u8 {
561 const PUBLIC = 0b0000_0001,
562 const IMPORTABLE = 0b0000_0010,
566 // Records a possibly-private type definition.
567 #[derive(Clone,Debug)]
569 modifiers: DefModifiers, // see note in ImportResolution about how to use this
570 module_def: Option<Rc<Module>>,
571 type_def: Option<Def>,
572 type_span: Option<Span>
575 // Records a possibly-private value definition.
576 #[derive(Clone, Copy, Debug)]
578 modifiers: DefModifiers, // see note in ImportResolution about how to use this
580 value_span: Option<Span>,
583 // Records the definitions (at most one for each namespace) that a name is
586 struct NameBindings {
587 type_def: RefCell<Option<TypeNsDef>>, //< Meaning in type namespace.
588 value_def: RefCell<Option<ValueNsDef>>, //< Meaning in value namespace.
591 /// Ways in which a trait can be referenced
593 enum TraitReferenceType {
594 TraitImplementation, // impl SomeTrait for T { ... }
595 TraitDerivation, // trait T : SomeTrait { ... }
596 TraitBoundingTypeParameter, // fn f<T:SomeTrait>() { ... }
597 TraitObject, // Box<for<'a> SomeTrait>
598 TraitQPath, // <T as SomeTrait>::
602 fn new() -> NameBindings {
604 type_def: RefCell::new(None),
605 value_def: RefCell::new(None),
609 /// Creates a new module in this set of name bindings.
610 fn define_module(&self,
611 parent_link: ParentLink,
612 def_id: Option<DefId>,
617 // Merges the module with the existing type def or creates a new one.
618 let modifiers = if is_public { PUBLIC } else { DefModifiers::empty() } | IMPORTABLE;
619 let module_ = Rc::new(Module::new(parent_link,
624 let type_def = self.type_def.borrow().clone();
627 *self.type_def.borrow_mut() = Some(TypeNsDef {
628 modifiers: modifiers,
629 module_def: Some(module_),
635 *self.type_def.borrow_mut() = Some(TypeNsDef {
636 modifiers: modifiers,
637 module_def: Some(module_),
639 type_def: type_def.type_def
645 /// Sets the kind of the module, creating a new one if necessary.
646 fn set_module_kind(&self,
647 parent_link: ParentLink,
648 def_id: Option<DefId>,
653 let modifiers = if is_public { PUBLIC } else { DefModifiers::empty() } | IMPORTABLE;
654 let type_def = self.type_def.borrow().clone();
657 let module = Module::new(parent_link,
662 *self.type_def.borrow_mut() = Some(TypeNsDef {
663 modifiers: modifiers,
664 module_def: Some(Rc::new(module)),
670 match type_def.module_def {
672 let module = Module::new(parent_link,
677 *self.type_def.borrow_mut() = Some(TypeNsDef {
678 modifiers: modifiers,
679 module_def: Some(Rc::new(module)),
680 type_def: type_def.type_def,
684 Some(module_def) => module_def.kind.set(kind),
690 /// Records a type definition.
691 fn define_type(&self, def: Def, sp: Span, modifiers: DefModifiers) {
692 debug!("defining type for def {:?} with modifiers {:?}", def, modifiers);
693 // Merges the type with the existing type def or creates a new one.
694 let type_def = self.type_def.borrow().clone();
697 *self.type_def.borrow_mut() = Some(TypeNsDef {
701 modifiers: modifiers,
705 *self.type_def.borrow_mut() = Some(TypeNsDef {
706 module_def: type_def.module_def,
709 modifiers: modifiers,
715 /// Records a value definition.
716 fn define_value(&self, def: Def, sp: Span, modifiers: DefModifiers) {
717 debug!("defining value for def {:?} with modifiers {:?}", def, modifiers);
718 *self.value_def.borrow_mut() = Some(ValueNsDef {
720 value_span: Some(sp),
721 modifiers: modifiers,
725 /// Returns the module node if applicable.
726 fn get_module_if_available(&self) -> Option<Rc<Module>> {
727 match *self.type_def.borrow() {
728 Some(ref type_def) => type_def.module_def.clone(),
733 /// Returns the module node. Panics if this node does not have a module
735 fn get_module(&self) -> Rc<Module> {
736 match self.get_module_if_available() {
738 panic!("get_module called on a node with no module \
741 Some(module_def) => module_def
745 fn defined_in_namespace(&self, namespace: Namespace) -> bool {
747 TypeNS => return self.type_def.borrow().is_some(),
748 ValueNS => return self.value_def.borrow().is_some()
752 fn defined_in_public_namespace(&self, namespace: Namespace) -> bool {
753 self.defined_in_namespace_with(namespace, PUBLIC)
756 fn defined_in_namespace_with(&self, namespace: Namespace, modifiers: DefModifiers) -> bool {
758 TypeNS => match *self.type_def.borrow() {
759 Some(ref def) => def.modifiers.contains(modifiers), None => false
761 ValueNS => match *self.value_def.borrow() {
762 Some(ref def) => def.modifiers.contains(modifiers), None => false
767 fn def_for_namespace(&self, namespace: Namespace) -> Option<Def> {
770 match *self.type_def.borrow() {
772 Some(ref type_def) => {
773 match type_def.type_def {
774 Some(type_def) => Some(type_def),
776 match type_def.module_def {
777 Some(ref module) => {
778 match module.def_id.get() {
779 Some(did) => Some(DefMod(did)),
791 match *self.value_def.borrow() {
793 Some(value_def) => Some(value_def.def)
799 fn span_for_namespace(&self, namespace: Namespace) -> Option<Span> {
800 if self.defined_in_namespace(namespace) {
803 match *self.type_def.borrow() {
805 Some(ref type_def) => type_def.type_span
809 match *self.value_def.borrow() {
811 Some(ref value_def) => value_def.value_span
821 /// Interns the names of the primitive types.
822 struct PrimitiveTypeTable {
823 primitive_types: HashMap<Name, PrimTy>,
826 impl PrimitiveTypeTable {
827 fn new() -> PrimitiveTypeTable {
828 let mut table = PrimitiveTypeTable {
829 primitive_types: HashMap::new()
832 table.intern("bool", TyBool);
833 table.intern("char", TyChar);
834 table.intern("f32", TyFloat(TyF32));
835 table.intern("f64", TyFloat(TyF64));
836 table.intern("int", TyInt(TyIs(true)));
837 table.intern("isize", TyInt(TyIs(false)));
838 table.intern("i8", TyInt(TyI8));
839 table.intern("i16", TyInt(TyI16));
840 table.intern("i32", TyInt(TyI32));
841 table.intern("i64", TyInt(TyI64));
842 table.intern("str", TyStr);
843 table.intern("uint", TyUint(TyUs(true)));
844 table.intern("usize", TyUint(TyUs(false)));
845 table.intern("u8", TyUint(TyU8));
846 table.intern("u16", TyUint(TyU16));
847 table.intern("u32", TyUint(TyU32));
848 table.intern("u64", TyUint(TyU64));
853 fn intern(&mut self, string: &str, primitive_type: PrimTy) {
854 self.primitive_types.insert(token::intern(string), primitive_type);
858 /// The main resolver class.
859 struct Resolver<'a, 'tcx:'a> {
860 session: &'a Session,
862 ast_map: &'a ast_map::Map<'tcx>,
864 graph_root: NameBindings,
866 trait_item_map: FnvHashMap<(Name, DefId), TraitItemKind>,
868 structs: FnvHashMap<DefId, Vec<Name>>,
870 // The number of imports that are currently unresolved.
871 unresolved_imports: uint,
873 // The module that represents the current item scope.
874 current_module: Rc<Module>,
876 // The current set of local scopes, for values.
877 // FIXME #4948: Reuse ribs to avoid allocation.
878 value_ribs: Vec<Rib>,
880 // The current set of local scopes, for types.
883 // The current set of local scopes, for labels.
884 label_ribs: Vec<Rib>,
886 // The trait that the current context can refer to.
887 current_trait_ref: Option<(DefId, TraitRef)>,
889 // The current self type if inside an impl (used for better errors).
890 current_self_type: Option<Ty>,
892 // The ident for the keyword "self".
894 // The ident for the non-keyword "Self".
895 type_self_name: Name,
897 // The idents for the primitive types.
898 primitive_type_table: PrimitiveTypeTable,
901 freevars: RefCell<FreevarMap>,
902 freevars_seen: RefCell<NodeMap<NodeSet>>,
903 export_map: ExportMap,
905 external_exports: ExternalExports,
906 last_private: LastPrivateMap,
908 // Whether or not to print error messages. Can be set to true
909 // when getting additional info for error message suggestions,
910 // so as to avoid printing duplicate errors
914 // Maps imports to the names of items actually imported (this actually maps
915 // all imports, but only glob imports are actually interesting).
918 used_imports: HashSet<(NodeId, Namespace)>,
919 used_crates: HashSet<CrateNum>,
923 enum FallbackChecks {
929 impl<'a, 'tcx> Resolver<'a, 'tcx> {
930 fn new(session: &'a Session,
931 ast_map: &'a ast_map::Map<'tcx>,
933 make_glob_map: MakeGlobMap) -> Resolver<'a, 'tcx> {
934 let graph_root = NameBindings::new();
936 graph_root.define_module(NoParentLink,
937 Some(DefId { krate: 0, node: 0 }),
943 let current_module = graph_root.get_module();
950 // The outermost module has def ID 0; this is not reflected in the
953 graph_root: graph_root,
955 trait_item_map: FnvHashMap(),
956 structs: FnvHashMap(),
958 unresolved_imports: 0,
960 current_module: current_module,
961 value_ribs: Vec::new(),
962 type_ribs: Vec::new(),
963 label_ribs: Vec::new(),
965 current_trait_ref: None,
966 current_self_type: None,
968 self_name: special_names::self_,
969 type_self_name: special_names::type_self,
971 primitive_type_table: PrimitiveTypeTable::new(),
973 def_map: RefCell::new(NodeMap()),
974 freevars: RefCell::new(NodeMap()),
975 freevars_seen: RefCell::new(NodeMap()),
976 export_map: NodeMap(),
977 trait_map: NodeMap(),
978 used_imports: HashSet::new(),
979 used_crates: HashSet::new(),
980 external_exports: DefIdSet(),
981 last_private: NodeMap(),
984 make_glob_map: make_glob_map == MakeGlobMap::Yes,
985 glob_map: HashMap::new(),
991 // This is a fixed-point algorithm. We resolve imports until our efforts
992 // are stymied by an unresolved import; then we bail out of the current
993 // module and continue. We terminate successfully once no more imports
994 // remain or unsuccessfully when no forward progress in resolving imports
997 /// Resolves all imports for the crate. This method performs the fixed-
999 fn resolve_imports(&mut self) {
1001 let mut prev_unresolved_imports = 0;
1003 debug!("(resolving imports) iteration {}, {} imports left",
1004 i, self.unresolved_imports);
1006 let module_root = self.graph_root.get_module();
1007 self.resolve_imports_for_module_subtree(module_root.clone());
1009 if self.unresolved_imports == 0 {
1010 debug!("(resolving imports) success");
1014 if self.unresolved_imports == prev_unresolved_imports {
1015 self.report_unresolved_imports(module_root);
1020 prev_unresolved_imports = self.unresolved_imports;
1024 /// Attempts to resolve imports for the given module and all of its
1026 fn resolve_imports_for_module_subtree(&mut self, module_: Rc<Module>) {
1027 debug!("(resolving imports for module subtree) resolving {}",
1028 self.module_to_string(&*module_));
1029 let orig_module = replace(&mut self.current_module, module_.clone());
1030 self.resolve_imports_for_module(module_.clone());
1031 self.current_module = orig_module;
1033 build_reduced_graph::populate_module_if_necessary(self, &module_);
1034 for (_, child_node) in &*module_.children.borrow() {
1035 match child_node.get_module_if_available() {
1039 Some(child_module) => {
1040 self.resolve_imports_for_module_subtree(child_module);
1045 for (_, child_module) in &*module_.anonymous_children.borrow() {
1046 self.resolve_imports_for_module_subtree(child_module.clone());
1050 /// Attempts to resolve imports for the given module only.
1051 fn resolve_imports_for_module(&mut self, module: Rc<Module>) {
1052 if module.all_imports_resolved() {
1053 debug!("(resolving imports for module) all imports resolved for \
1055 self.module_to_string(&*module));
1059 let imports = module.imports.borrow();
1060 let import_count = imports.len();
1061 while module.resolved_import_count.get() < import_count {
1062 let import_index = module.resolved_import_count.get();
1063 let import_directive = &(*imports)[import_index];
1064 match self.resolve_import_for_module(module.clone(),
1067 let (span, help) = match err {
1068 Some((span, msg)) => (span, format!(". {}", msg)),
1069 None => (import_directive.span, String::new())
1071 let msg = format!("unresolved import `{}`{}",
1072 self.import_path_to_string(
1073 &import_directive.module_path[],
1074 import_directive.subclass),
1076 self.resolve_error(span, &msg[]);
1078 Indeterminate => break, // Bail out. We'll come around next time.
1079 Success(()) => () // Good. Continue.
1082 module.resolved_import_count
1083 .set(module.resolved_import_count.get() + 1);
1087 fn names_to_string(&self, names: &[Name]) -> String {
1088 let mut first = true;
1089 let mut result = String::new();
1094 result.push_str("::")
1096 result.push_str(token::get_name(*name).get());
1101 fn path_names_to_string(&self, path: &Path) -> String {
1102 let names: Vec<ast::Name> = path.segments
1104 .map(|seg| seg.identifier.name)
1106 self.names_to_string(&names[])
1109 fn import_directive_subclass_to_string(&mut self,
1110 subclass: ImportDirectiveSubclass)
1113 SingleImport(_, source) => {
1114 token::get_name(source).get().to_string()
1116 GlobImport => "*".to_string()
1120 fn import_path_to_string(&mut self,
1122 subclass: ImportDirectiveSubclass)
1124 if names.is_empty() {
1125 self.import_directive_subclass_to_string(subclass)
1128 self.names_to_string(names),
1129 self.import_directive_subclass_to_string(
1130 subclass))).to_string()
1135 fn record_import_use(&mut self, import_id: NodeId, name: Name) {
1136 if !self.make_glob_map {
1139 if self.glob_map.contains_key(&import_id) {
1140 self.glob_map[import_id].insert(name);
1144 let mut new_set = HashSet::new();
1145 new_set.insert(name);
1146 self.glob_map.insert(import_id, new_set);
1149 fn get_trait_name(&self, did: DefId) -> Name {
1150 if did.krate == ast::LOCAL_CRATE {
1151 self.ast_map.expect_item(did.node).ident.name
1153 csearch::get_trait_name(&self.session.cstore, did)
1157 /// Attempts to resolve the given import. The return value indicates
1158 /// failure if we're certain the name does not exist, indeterminate if we
1159 /// don't know whether the name exists at the moment due to other
1160 /// currently-unresolved imports, or success if we know the name exists.
1161 /// If successful, the resolved bindings are written into the module.
1162 fn resolve_import_for_module(&mut self,
1163 module_: Rc<Module>,
1164 import_directive: &ImportDirective)
1165 -> ResolveResult<()> {
1166 let mut resolution_result = Failed(None);
1167 let module_path = &import_directive.module_path;
1169 debug!("(resolving import for module) resolving import `{}::...` in `{}`",
1170 self.names_to_string(&module_path[]),
1171 self.module_to_string(&*module_));
1173 // First, resolve the module path for the directive, if necessary.
1174 let container = if module_path.len() == 0 {
1175 // Use the crate root.
1176 Some((self.graph_root.get_module(), LastMod(AllPublic)))
1178 match self.resolve_module_path(module_.clone(),
1180 DontUseLexicalScope,
1181 import_directive.span,
1184 resolution_result = Failed(err);
1188 resolution_result = Indeterminate;
1191 Success(container) => Some(container),
1197 Some((containing_module, lp)) => {
1198 // We found the module that the target is contained
1199 // within. Attempt to resolve the import within it.
1201 match import_directive.subclass {
1202 SingleImport(target, source) => {
1204 self.resolve_single_import(&*module_,
1213 self.resolve_glob_import(&*module_,
1222 // Decrement the count of unresolved imports.
1223 match resolution_result {
1225 assert!(self.unresolved_imports >= 1);
1226 self.unresolved_imports -= 1;
1229 // Nothing to do here; just return the error.
1233 // Decrement the count of unresolved globs if necessary. But only if
1234 // the resolution result is indeterminate -- otherwise we'll stop
1235 // processing imports here. (See the loop in
1236 // resolve_imports_for_module.)
1238 if !resolution_result.indeterminate() {
1239 match import_directive.subclass {
1241 assert!(module_.glob_count.get() >= 1);
1242 module_.glob_count.set(module_.glob_count.get() - 1);
1244 SingleImport(..) => {
1250 return resolution_result;
1253 fn create_name_bindings_from_module(module: Rc<Module>) -> NameBindings {
1255 type_def: RefCell::new(Some(TypeNsDef {
1256 modifiers: IMPORTABLE,
1257 module_def: Some(module),
1261 value_def: RefCell::new(None),
1265 fn resolve_single_import(&mut self,
1267 containing_module: Rc<Module>,
1270 directive: &ImportDirective,
1272 -> ResolveResult<()> {
1273 debug!("(resolving single import) resolving `{}` = `{}::{}` from \
1274 `{}` id {}, last private {:?}",
1275 token::get_name(target),
1276 self.module_to_string(&*containing_module),
1277 token::get_name(source),
1278 self.module_to_string(module_),
1284 LastImport {..} => {
1286 .span_bug(directive.span,
1287 "not expecting Import here, must be LastMod")
1291 // We need to resolve both namespaces for this to succeed.
1294 let mut value_result = UnknownResult;
1295 let mut type_result = UnknownResult;
1297 // Search for direct children of the containing module.
1298 build_reduced_graph::populate_module_if_necessary(self, &containing_module);
1300 match containing_module.children.borrow().get(&source) {
1304 Some(ref child_name_bindings) => {
1305 if child_name_bindings.defined_in_namespace(ValueNS) {
1306 debug!("(resolving single import) found value binding");
1307 value_result = BoundResult(containing_module.clone(),
1308 (*child_name_bindings).clone());
1310 if child_name_bindings.defined_in_namespace(TypeNS) {
1311 debug!("(resolving single import) found type binding");
1312 type_result = BoundResult(containing_module.clone(),
1313 (*child_name_bindings).clone());
1318 // Unless we managed to find a result in both namespaces (unlikely),
1319 // search imports as well.
1320 let mut value_used_reexport = false;
1321 let mut type_used_reexport = false;
1322 match (value_result.clone(), type_result.clone()) {
1323 (BoundResult(..), BoundResult(..)) => {} // Continue.
1325 // If there is an unresolved glob at this point in the
1326 // containing module, bail out. We don't know enough to be
1327 // able to resolve this import.
1329 if containing_module.glob_count.get() > 0 {
1330 debug!("(resolving single import) unresolved glob; \
1332 return Indeterminate;
1335 // Now search the exported imports within the containing module.
1336 match containing_module.import_resolutions.borrow().get(&source) {
1338 debug!("(resolving single import) no import");
1339 // The containing module definitely doesn't have an
1340 // exported import with the name in question. We can
1341 // therefore accurately report that the names are
1344 if value_result.is_unknown() {
1345 value_result = UnboundResult;
1347 if type_result.is_unknown() {
1348 type_result = UnboundResult;
1351 Some(import_resolution)
1352 if import_resolution.outstanding_references == 0 => {
1354 fn get_binding(this: &mut Resolver,
1355 import_resolution: &ImportResolution,
1356 namespace: Namespace,
1358 -> NamespaceResult {
1360 // Import resolutions must be declared with "pub"
1361 // in order to be exported.
1362 if !import_resolution.is_public {
1363 return UnboundResult;
1366 match import_resolution.
1367 target_for_namespace(namespace) {
1369 return UnboundResult;
1376 debug!("(resolving single import) found \
1377 import in ns {:?}", namespace);
1378 let id = import_resolution.id(namespace);
1379 // track used imports and extern crates as well
1380 this.used_imports.insert((id, namespace));
1381 this.record_import_use(id, *source);
1382 match target_module.def_id.get() {
1383 Some(DefId{krate: kid, ..}) => {
1384 this.used_crates.insert(kid);
1388 return BoundResult(target_module, bindings);
1393 // The name is an import which has been fully
1394 // resolved. We can, therefore, just follow it.
1395 if value_result.is_unknown() {
1396 value_result = get_binding(self,
1400 value_used_reexport = import_resolution.is_public;
1402 if type_result.is_unknown() {
1403 type_result = get_binding(self,
1407 type_used_reexport = import_resolution.is_public;
1412 // If containing_module is the same module whose import we are resolving
1413 // and there it has an unresolved import with the same name as `source`,
1414 // then the user is actually trying to import an item that is declared
1415 // in the same scope
1418 // use self::submodule;
1419 // pub mod submodule;
1421 // In this case we continue as if we resolved the import and let the
1422 // check_for_conflicts_between_imports_and_items call below handle
1424 match (module_.def_id.get(), containing_module.def_id.get()) {
1425 (Some(id1), Some(id2)) if id1 == id2 => {
1426 if value_result.is_unknown() {
1427 value_result = UnboundResult;
1429 if type_result.is_unknown() {
1430 type_result = UnboundResult;
1434 // The import is unresolved. Bail out.
1435 debug!("(resolving single import) unresolved import; \
1437 return Indeterminate;
1445 // If we didn't find a result in the type namespace, search the
1446 // external modules.
1447 let mut value_used_public = false;
1448 let mut type_used_public = false;
1450 BoundResult(..) => {}
1452 match containing_module.external_module_children.borrow_mut()
1453 .get(&source).cloned() {
1454 None => {} // Continue.
1456 debug!("(resolving single import) found external \
1458 // track the module as used.
1459 match module.def_id.get() {
1460 Some(DefId{krate: kid, ..}) => { self.used_crates.insert(kid); },
1464 Rc::new(Resolver::create_name_bindings_from_module(
1466 type_result = BoundResult(containing_module.clone(),
1468 type_used_public = true;
1474 // We've successfully resolved the import. Write the results in.
1475 let mut import_resolutions = module_.import_resolutions.borrow_mut();
1476 let import_resolution = &mut (*import_resolutions)[target];
1478 let mut check_and_write_import = |namespace, result: &_, used_public: &mut bool| {
1479 let namespace_name = match namespace {
1485 BoundResult(ref target_module, ref name_bindings) => {
1486 debug!("(resolving single import) found {:?} target: {:?}",
1488 name_bindings.def_for_namespace(namespace));
1489 self.check_for_conflicting_import(
1490 &import_resolution.target_for_namespace(namespace),
1495 self.check_that_import_is_importable(
1501 let target = Some(Target::new(target_module.clone(),
1502 name_bindings.clone(),
1503 directive.shadowable));
1504 import_resolution.set_target_and_id(namespace, target, directive.id);
1505 import_resolution.is_public = directive.is_public;
1506 *used_public = name_bindings.defined_in_public_namespace(namespace);
1508 UnboundResult => { /* Continue. */ }
1510 panic!("{:?} result should be known at this point", namespace_name);
1514 check_and_write_import(ValueNS, &value_result, &mut value_used_public);
1515 check_and_write_import(TypeNS, &type_result, &mut type_used_public);
1518 self.check_for_conflicts_between_imports_and_items(
1524 if value_result.is_unbound() && type_result.is_unbound() {
1525 let msg = format!("There is no `{}` in `{}`",
1526 token::get_name(source),
1527 self.module_to_string(&*containing_module));
1528 return Failed(Some((directive.span, msg)));
1530 let value_used_public = value_used_reexport || value_used_public;
1531 let type_used_public = type_used_reexport || type_used_public;
1533 assert!(import_resolution.outstanding_references >= 1);
1534 import_resolution.outstanding_references -= 1;
1536 // record what this import resolves to for later uses in documentation,
1537 // this may resolve to either a value or a type, but for documentation
1538 // purposes it's good enough to just favor one over the other.
1539 let value_private = match import_resolution.value_target {
1540 Some(ref target) => {
1541 let def = target.bindings.def_for_namespace(ValueNS).unwrap();
1542 self.def_map.borrow_mut().insert(directive.id, def);
1543 let did = def.def_id();
1544 if value_used_public {Some(lp)} else {Some(DependsOn(did))}
1546 // AllPublic here and below is a dummy value, it should never be used because
1547 // _exists is false.
1550 let type_private = match import_resolution.type_target {
1551 Some(ref target) => {
1552 let def = target.bindings.def_for_namespace(TypeNS).unwrap();
1553 self.def_map.borrow_mut().insert(directive.id, def);
1554 let did = def.def_id();
1555 if type_used_public {Some(lp)} else {Some(DependsOn(did))}
1560 self.last_private.insert(directive.id, LastImport{value_priv: value_private,
1562 type_priv: type_private,
1565 debug!("(resolving single import) successfully resolved import");
1569 // Resolves a glob import. Note that this function cannot fail; it either
1570 // succeeds or bails out (as importing * from an empty module or a module
1571 // that exports nothing is valid). containing_module is the module we are
1572 // actually importing, i.e., `foo` in `use foo::*`.
1573 fn resolve_glob_import(&mut self,
1575 containing_module: Rc<Module>,
1576 import_directive: &ImportDirective,
1578 -> ResolveResult<()> {
1579 let id = import_directive.id;
1580 let is_public = import_directive.is_public;
1582 // This function works in a highly imperative manner; it eagerly adds
1583 // everything it can to the list of import resolutions of the module
1585 debug!("(resolving glob import) resolving glob import {}", id);
1587 // We must bail out if the node has unresolved imports of any kind
1588 // (including globs).
1589 if !(*containing_module).all_imports_resolved() {
1590 debug!("(resolving glob import) target module has unresolved \
1591 imports; bailing out");
1592 return Indeterminate;
1595 assert_eq!(containing_module.glob_count.get(), 0);
1597 // Add all resolved imports from the containing module.
1598 let import_resolutions = containing_module.import_resolutions.borrow();
1599 for (ident, target_import_resolution) in &*import_resolutions {
1600 debug!("(resolving glob import) writing module resolution \
1602 token::get_name(*ident),
1603 self.module_to_string(module_));
1605 if !target_import_resolution.is_public {
1606 debug!("(resolving glob import) nevermind, just kidding");
1610 // Here we merge two import resolutions.
1611 let mut import_resolutions = module_.import_resolutions.borrow_mut();
1612 match import_resolutions.get_mut(ident) {
1613 Some(dest_import_resolution) => {
1614 // Merge the two import resolutions at a finer-grained
1617 match target_import_resolution.value_target {
1621 Some(ref value_target) => {
1622 self.check_for_conflicting_import(&dest_import_resolution.value_target,
1623 import_directive.span,
1626 dest_import_resolution.value_target = Some(value_target.clone());
1629 match target_import_resolution.type_target {
1633 Some(ref type_target) => {
1634 self.check_for_conflicting_import(&dest_import_resolution.type_target,
1635 import_directive.span,
1638 dest_import_resolution.type_target = Some(type_target.clone());
1641 dest_import_resolution.is_public = is_public;
1647 // Simple: just copy the old import resolution.
1648 let mut new_import_resolution = ImportResolution::new(id, is_public);
1649 new_import_resolution.value_target =
1650 target_import_resolution.value_target.clone();
1651 new_import_resolution.type_target =
1652 target_import_resolution.type_target.clone();
1654 import_resolutions.insert(*ident, new_import_resolution);
1657 // Add all children from the containing module.
1658 build_reduced_graph::populate_module_if_necessary(self, &containing_module);
1660 for (&name, name_bindings) in &*containing_module.children.borrow() {
1661 self.merge_import_resolution(module_,
1662 containing_module.clone(),
1665 name_bindings.clone());
1669 // Add external module children from the containing module.
1670 for (&name, module) in &*containing_module.external_module_children.borrow() {
1672 Rc::new(Resolver::create_name_bindings_from_module(module.clone()));
1673 self.merge_import_resolution(module_,
1674 containing_module.clone(),
1680 // Record the destination of this import
1681 match containing_module.def_id.get() {
1683 self.def_map.borrow_mut().insert(id, DefMod(did));
1684 self.last_private.insert(id, lp);
1689 debug!("(resolving glob import) successfully resolved import");
1693 fn merge_import_resolution(&mut self,
1695 containing_module: Rc<Module>,
1696 import_directive: &ImportDirective,
1698 name_bindings: Rc<NameBindings>) {
1699 let id = import_directive.id;
1700 let is_public = import_directive.is_public;
1702 let mut import_resolutions = module_.import_resolutions.borrow_mut();
1703 let dest_import_resolution = import_resolutions.entry(name).get().unwrap_or_else(
1705 // Create a new import resolution from this child.
1706 vacant_entry.insert(ImportResolution::new(id, is_public))
1709 debug!("(resolving glob import) writing resolution `{}` in `{}` \
1711 token::get_name(name).get(),
1712 self.module_to_string(&*containing_module),
1713 self.module_to_string(module_));
1715 // Merge the child item into the import resolution.
1717 let mut merge_child_item = |namespace| {
1718 if name_bindings.defined_in_namespace_with(namespace, IMPORTABLE | PUBLIC) {
1719 let namespace_name = match namespace {
1723 debug!("(resolving glob import) ... for {} target", namespace_name);
1724 if dest_import_resolution.shadowable(namespace) == Shadowable::Never {
1725 let msg = format!("a {} named `{}` has already been imported \
1728 token::get_name(name).get());
1729 span_err!(self.session, import_directive.span, E0251, "{}", msg);
1731 let target = Target::new(containing_module.clone(),
1732 name_bindings.clone(),
1733 import_directive.shadowable);
1734 dest_import_resolution.set_target_and_id(namespace,
1740 merge_child_item(ValueNS);
1741 merge_child_item(TypeNS);
1744 dest_import_resolution.is_public = is_public;
1746 self.check_for_conflicts_between_imports_and_items(
1748 dest_import_resolution,
1749 import_directive.span,
1753 /// Checks that imported names and items don't have the same name.
1754 fn check_for_conflicting_import(&mut self,
1755 target: &Option<Target>,
1758 namespace: Namespace) {
1759 debug!("check_for_conflicting_import: {}; target exists: {}",
1760 token::get_name(name).get(),
1764 Some(ref target) if target.shadowable != Shadowable::Always => {
1765 let msg = format!("a {} named `{}` has already been imported \
1771 token::get_name(name).get());
1772 span_err!(self.session, import_span, E0252, "{}", &msg[]);
1774 Some(_) | None => {}
1778 /// Checks that an import is actually importable
1779 fn check_that_import_is_importable(&mut self,
1780 name_bindings: &NameBindings,
1783 namespace: Namespace) {
1784 if !name_bindings.defined_in_namespace_with(namespace, IMPORTABLE) {
1785 let msg = format!("`{}` is not directly importable",
1786 token::get_name(name));
1787 span_err!(self.session, import_span, E0253, "{}", &msg[]);
1791 /// Checks that imported names and items don't have the same name.
1792 fn check_for_conflicts_between_imports_and_items(&mut self,
1798 // 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 span_err!(self.session, import_span, E0254, "{}", &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 span_err!(self.session, import_span, E0255, "{}", &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 span_err!(self.session, import_span, E0256, "{}", &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 span_err!(self.session, span, E0257, "{}", &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 span_err!(self.session, import_span, E0258, "{}", &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 module.external_module_children.borrow().contains_key(&name) {
1892 span_err!(self.session, span, E0259,
1893 "an external crate named `{}` has already \
1894 been imported into this module",
1895 token::get_name(name).get());
1899 /// Checks that the names of items don't collide with external crates.
1900 fn check_for_conflicts_between_external_crates_and_items(&self,
1904 if module.external_module_children.borrow().contains_key(&name) {
1905 span_err!(self.session, span, E0260,
1906 "the name `{}` conflicts with an external \
1907 crate that has been imported into this \
1909 token::get_name(name).get());
1913 /// Resolves the given module path from the given root `module_`.
1914 fn resolve_module_path_from_root(&mut self,
1915 module_: Rc<Module>,
1916 module_path: &[Name],
1919 name_search_type: NameSearchType,
1921 -> ResolveResult<(Rc<Module>, LastPrivate)> {
1922 fn search_parent_externals(needle: Name, module: &Rc<Module>)
1923 -> Option<Rc<Module>> {
1924 module.external_module_children.borrow()
1925 .get(&needle).cloned()
1926 .map(|_| module.clone())
1928 match module.parent_link.clone() {
1929 ModuleParentLink(parent, _) => {
1930 search_parent_externals(needle,
1931 &parent.upgrade().unwrap())
1938 let mut search_module = module_;
1939 let mut index = index;
1940 let module_path_len = module_path.len();
1941 let mut closest_private = lp;
1943 // Resolve the module part of the path. This does not involve looking
1944 // upward though scope chains; we simply resolve names directly in
1945 // modules as we go.
1946 while index < module_path_len {
1947 let name = module_path[index];
1948 match self.resolve_name_in_module(search_module.clone(),
1954 let segment_name = token::get_name(name);
1955 let module_name = self.module_to_string(&*search_module);
1956 let mut span = span;
1957 let msg = if "???" == &module_name[] {
1958 span.hi = span.lo + Pos::from_usize(segment_name.get().len());
1960 match search_parent_externals(name,
1961 &self.current_module) {
1963 let path_str = self.names_to_string(module_path);
1964 let target_mod_str = self.module_to_string(&*module);
1965 let current_mod_str =
1966 self.module_to_string(&*self.current_module);
1968 let prefix = if target_mod_str == current_mod_str {
1969 "self::".to_string()
1971 format!("{}::", target_mod_str)
1974 format!("Did you mean `{}{}`?", prefix, path_str)
1976 None => format!("Maybe a missing `extern crate {}`?",
1980 format!("Could not find `{}` in `{}`",
1985 return Failed(Some((span, msg)));
1987 Failed(err) => return Failed(err),
1989 debug!("(resolving module path for import) module \
1990 resolution is indeterminate: {}",
1991 token::get_name(name));
1992 return Indeterminate;
1994 Success((target, used_proxy)) => {
1995 // Check to see whether there are type bindings, and, if
1996 // so, whether there is a module within.
1997 match *target.bindings.type_def.borrow() {
1998 Some(ref type_def) => {
1999 match type_def.module_def {
2001 let msg = format!("Not a module `{}`",
2002 token::get_name(name));
2004 return Failed(Some((span, msg)));
2006 Some(ref module_def) => {
2007 search_module = module_def.clone();
2009 // track extern crates for unused_extern_crate lint
2010 if let Some(did) = module_def.def_id.get() {
2011 self.used_crates.insert(did.krate);
2014 // Keep track of the closest
2015 // private module used when
2016 // resolving this import chain.
2017 if !used_proxy && !search_module.is_public {
2018 if let Some(did) = search_module.def_id.get() {
2019 closest_private = LastMod(DependsOn(did));
2026 // There are no type bindings at all.
2027 let msg = format!("Not a module `{}`",
2028 token::get_name(name));
2029 return Failed(Some((span, msg)));
2038 return Success((search_module, closest_private));
2041 /// Attempts to resolve the module part of an import directive or path
2042 /// rooted at the given module.
2044 /// On success, returns the resolved module, and the closest *private*
2045 /// module found to the destination when resolving this path.
2046 fn resolve_module_path(&mut self,
2047 module_: Rc<Module>,
2048 module_path: &[Name],
2049 use_lexical_scope: UseLexicalScopeFlag,
2051 name_search_type: NameSearchType)
2052 -> ResolveResult<(Rc<Module>, LastPrivate)> {
2053 let module_path_len = module_path.len();
2054 assert!(module_path_len > 0);
2056 debug!("(resolving module path for import) processing `{}` rooted at `{}`",
2057 self.names_to_string(module_path),
2058 self.module_to_string(&*module_));
2060 // Resolve the module prefix, if any.
2061 let module_prefix_result = self.resolve_module_prefix(module_.clone(),
2067 match module_prefix_result {
2069 let mpath = self.names_to_string(module_path);
2070 let mpath = &mpath[];
2071 match mpath.rfind(':') {
2073 let msg = format!("Could not find `{}` in `{}`",
2074 // idx +- 1 to account for the
2075 // colons on either side
2078 return Failed(Some((span, msg)));
2085 Failed(err) => return Failed(err),
2087 debug!("(resolving module path for import) indeterminate; \
2089 return Indeterminate;
2091 Success(NoPrefixFound) => {
2092 // There was no prefix, so we're considering the first element
2093 // of the path. How we handle this depends on whether we were
2094 // instructed to use lexical scope or not.
2095 match use_lexical_scope {
2096 DontUseLexicalScope => {
2097 // This is a crate-relative path. We will start the
2098 // resolution process at index zero.
2099 search_module = self.graph_root.get_module();
2101 last_private = LastMod(AllPublic);
2103 UseLexicalScope => {
2104 // This is not a crate-relative path. We resolve the
2105 // first component of the path in the current lexical
2106 // scope and then proceed to resolve below that.
2107 match self.resolve_module_in_lexical_scope(module_,
2109 Failed(err) => return Failed(err),
2111 debug!("(resolving module path for import) \
2112 indeterminate; bailing");
2113 return Indeterminate;
2115 Success(containing_module) => {
2116 search_module = containing_module;
2118 last_private = LastMod(AllPublic);
2124 Success(PrefixFound(ref containing_module, index)) => {
2125 search_module = containing_module.clone();
2126 start_index = index;
2127 last_private = LastMod(DependsOn(containing_module.def_id
2133 self.resolve_module_path_from_root(search_module,
2141 /// Invariant: This must only be called during main resolution, not during
2142 /// import resolution.
2143 fn resolve_item_in_lexical_scope(&mut self,
2144 module_: Rc<Module>,
2146 namespace: Namespace)
2147 -> ResolveResult<(Target, bool)> {
2148 debug!("(resolving item in lexical scope) resolving `{}` in \
2149 namespace {:?} in `{}`",
2150 token::get_name(name),
2152 self.module_to_string(&*module_));
2154 // The current module node is handled specially. First, check for
2155 // its immediate children.
2156 build_reduced_graph::populate_module_if_necessary(self, &module_);
2158 match module_.children.borrow().get(&name) {
2160 if name_bindings.defined_in_namespace(namespace) => {
2161 debug!("top name bindings succeeded");
2162 return Success((Target::new(module_.clone(),
2163 name_bindings.clone(),
2167 Some(_) | None => { /* Not found; continue. */ }
2170 // Now check for its import directives. We don't have to have resolved
2171 // all its imports in the usual way; this is because chains of
2172 // adjacent import statements are processed as though they mutated the
2174 if let Some(import_resolution) = module_.import_resolutions.borrow().get(&name) {
2175 match (*import_resolution).target_for_namespace(namespace) {
2177 // Not found; continue.
2178 debug!("(resolving item in lexical scope) found \
2179 import resolution, but not in namespace {:?}",
2183 debug!("(resolving item in lexical scope) using \
2184 import resolution");
2185 // track used imports and extern crates as well
2186 let id = import_resolution.id(namespace);
2187 self.used_imports.insert((id, namespace));
2188 self.record_import_use(id, name);
2189 if let Some(DefId{krate: kid, ..}) = target.target_module.def_id.get() {
2190 self.used_crates.insert(kid);
2192 return Success((target, false));
2197 // Search for external modules.
2198 if namespace == TypeNS {
2199 if let Some(module) = module_.external_module_children.borrow().get(&name).cloned() {
2201 Rc::new(Resolver::create_name_bindings_from_module(module));
2202 debug!("lower name bindings succeeded");
2203 return Success((Target::new(module_,
2210 // Finally, proceed up the scope chain looking for parent modules.
2211 let mut search_module = module_;
2213 // Go to the next parent.
2214 match search_module.parent_link.clone() {
2216 // No more parents. This module was unresolved.
2217 debug!("(resolving item in lexical scope) unresolved \
2219 return Failed(None);
2221 ModuleParentLink(parent_module_node, _) => {
2222 match search_module.kind.get() {
2223 NormalModuleKind => {
2224 // We stop the search here.
2225 debug!("(resolving item in lexical \
2226 scope) unresolved module: not \
2227 searching through module \
2229 return Failed(None);
2235 AnonymousModuleKind => {
2236 search_module = parent_module_node.upgrade().unwrap();
2240 BlockParentLink(ref parent_module_node, _) => {
2241 search_module = parent_module_node.upgrade().unwrap();
2245 // Resolve the name in the parent module.
2246 match self.resolve_name_in_module(search_module.clone(),
2251 Failed(Some((span, msg))) =>
2252 self.resolve_error(span, &format!("failed to resolve. {}",
2254 Failed(None) => (), // Continue up the search chain.
2256 // We couldn't see through the higher scope because of an
2257 // unresolved import higher up. Bail.
2259 debug!("(resolving item in lexical scope) indeterminate \
2260 higher scope; bailing");
2261 return Indeterminate;
2263 Success((target, used_reexport)) => {
2264 // We found the module.
2265 debug!("(resolving item in lexical scope) found name \
2267 return Success((target, used_reexport));
2273 /// Resolves a module name in the current lexical scope.
2274 fn resolve_module_in_lexical_scope(&mut self,
2275 module_: Rc<Module>,
2277 -> ResolveResult<Rc<Module>> {
2278 // If this module is an anonymous module, resolve the item in the
2279 // lexical scope. Otherwise, resolve the item from the crate root.
2280 let resolve_result = self.resolve_item_in_lexical_scope(module_, name, TypeNS);
2281 match resolve_result {
2282 Success((target, _)) => {
2283 let bindings = &*target.bindings;
2284 match *bindings.type_def.borrow() {
2285 Some(ref type_def) => {
2286 match type_def.module_def {
2288 debug!("!!! (resolving module in lexical \
2289 scope) module wasn't actually a \
2291 return Failed(None);
2293 Some(ref module_def) => {
2294 return Success(module_def.clone());
2299 debug!("!!! (resolving module in lexical scope) module
2300 wasn't actually a module!");
2301 return Failed(None);
2306 debug!("(resolving module in lexical scope) indeterminate; \
2308 return Indeterminate;
2311 debug!("(resolving module in lexical scope) failed to resolve");
2317 /// Returns the nearest normal module parent of the given module.
2318 fn get_nearest_normal_module_parent(&mut self, module_: Rc<Module>)
2319 -> Option<Rc<Module>> {
2320 let mut module_ = module_;
2322 match module_.parent_link.clone() {
2323 NoParentLink => return None,
2324 ModuleParentLink(new_module, _) |
2325 BlockParentLink(new_module, _) => {
2326 let new_module = new_module.upgrade().unwrap();
2327 match new_module.kind.get() {
2328 NormalModuleKind => return Some(new_module),
2333 AnonymousModuleKind => module_ = new_module,
2340 /// Returns the nearest normal module parent of the given module, or the
2341 /// module itself if it is a normal module.
2342 fn get_nearest_normal_module_parent_or_self(&mut self, module_: Rc<Module>)
2344 match module_.kind.get() {
2345 NormalModuleKind => return module_,
2350 AnonymousModuleKind => {
2351 match self.get_nearest_normal_module_parent(module_.clone()) {
2353 Some(new_module) => new_module
2359 /// Resolves a "module prefix". A module prefix is one or both of (a) `self::`;
2360 /// (b) some chain of `super::`.
2361 /// grammar: (SELF MOD_SEP ) ? (SUPER MOD_SEP) *
2362 fn resolve_module_prefix(&mut self,
2363 module_: Rc<Module>,
2364 module_path: &[Name])
2365 -> ResolveResult<ModulePrefixResult> {
2366 // Start at the current module if we see `self` or `super`, or at the
2367 // top of the crate otherwise.
2368 let mut containing_module;
2370 let first_module_path_string = token::get_name(module_path[0]);
2371 if "self" == first_module_path_string.get() {
2373 self.get_nearest_normal_module_parent_or_self(module_);
2375 } else if "super" == first_module_path_string.get() {
2377 self.get_nearest_normal_module_parent_or_self(module_);
2378 i = 0; // We'll handle `super` below.
2380 return Success(NoPrefixFound);
2383 // Now loop through all the `super`s we find.
2384 while i < module_path.len() {
2385 let string = token::get_name(module_path[i]);
2386 if "super" != string.get() {
2389 debug!("(resolving module prefix) resolving `super` at {}",
2390 self.module_to_string(&*containing_module));
2391 match self.get_nearest_normal_module_parent(containing_module) {
2392 None => return Failed(None),
2393 Some(new_module) => {
2394 containing_module = new_module;
2400 debug!("(resolving module prefix) finished resolving prefix at {}",
2401 self.module_to_string(&*containing_module));
2403 return Success(PrefixFound(containing_module, i));
2406 /// Attempts to resolve the supplied name in the given module for the
2407 /// given namespace. If successful, returns the target corresponding to
2410 /// The boolean returned on success is an indicator of whether this lookup
2411 /// passed through a public re-export proxy.
2412 fn resolve_name_in_module(&mut self,
2413 module_: Rc<Module>,
2415 namespace: Namespace,
2416 name_search_type: NameSearchType,
2417 allow_private_imports: bool)
2418 -> ResolveResult<(Target, bool)> {
2419 debug!("(resolving name in module) resolving `{}` in `{}`",
2420 token::get_name(name).get(),
2421 self.module_to_string(&*module_));
2423 // First, check the direct children of the module.
2424 build_reduced_graph::populate_module_if_necessary(self, &module_);
2426 match module_.children.borrow().get(&name) {
2428 if name_bindings.defined_in_namespace(namespace) => {
2429 debug!("(resolving name in module) found node as child");
2430 return Success((Target::new(module_.clone(),
2431 name_bindings.clone(),
2440 // Next, check the module's imports if necessary.
2442 // If this is a search of all imports, we should be done with glob
2443 // resolution at this point.
2444 if name_search_type == PathSearch {
2445 assert_eq!(module_.glob_count.get(), 0);
2448 // Check the list of resolved imports.
2449 match module_.import_resolutions.borrow().get(&name) {
2450 Some(import_resolution) if allow_private_imports ||
2451 import_resolution.is_public => {
2453 if import_resolution.is_public &&
2454 import_resolution.outstanding_references != 0 {
2455 debug!("(resolving name in module) import \
2456 unresolved; bailing out");
2457 return Indeterminate;
2459 match import_resolution.target_for_namespace(namespace) {
2461 debug!("(resolving name in module) name found, \
2462 but not in namespace {:?}",
2466 debug!("(resolving name in module) resolved to \
2468 // track used imports and extern crates as well
2469 let id = import_resolution.id(namespace);
2470 self.used_imports.insert((id, namespace));
2471 self.record_import_use(id, name);
2472 if let Some(DefId{krate: kid, ..}) = target.target_module.def_id.get() {
2473 self.used_crates.insert(kid);
2475 return Success((target, true));
2479 Some(..) | None => {} // Continue.
2482 // Finally, search through external children.
2483 if namespace == TypeNS {
2484 if let Some(module) = module_.external_module_children.borrow().get(&name).cloned() {
2486 Rc::new(Resolver::create_name_bindings_from_module(module));
2487 return Success((Target::new(module_,
2494 // We're out of luck.
2495 debug!("(resolving name in module) failed to resolve `{}`",
2496 token::get_name(name).get());
2497 return Failed(None);
2500 fn report_unresolved_imports(&mut self, module_: Rc<Module>) {
2501 let index = module_.resolved_import_count.get();
2502 let imports = module_.imports.borrow();
2503 let import_count = imports.len();
2504 if index != import_count {
2505 let sn = self.session
2507 .span_to_snippet((*imports)[index].span)
2509 if sn.contains("::") {
2510 self.resolve_error((*imports)[index].span,
2511 "unresolved import");
2513 let err = format!("unresolved import (maybe you meant `{}::*`?)",
2515 self.resolve_error((*imports)[index].span, &err[]);
2519 // Descend into children and anonymous children.
2520 build_reduced_graph::populate_module_if_necessary(self, &module_);
2522 for (_, child_node) in &*module_.children.borrow() {
2523 match child_node.get_module_if_available() {
2527 Some(child_module) => {
2528 self.report_unresolved_imports(child_module);
2533 for (_, module_) in &*module_.anonymous_children.borrow() {
2534 self.report_unresolved_imports(module_.clone());
2540 // We maintain a list of value ribs and type ribs.
2542 // Simultaneously, we keep track of the current position in the module
2543 // graph in the `current_module` pointer. When we go to resolve a name in
2544 // the value or type namespaces, we first look through all the ribs and
2545 // then query the module graph. When we resolve a name in the module
2546 // namespace, we can skip all the ribs (since nested modules are not
2547 // allowed within blocks in Rust) and jump straight to the current module
2550 // Named implementations are handled separately. When we find a method
2551 // call, we consult the module node to find all of the implementations in
2552 // scope. This information is lazily cached in the module node. We then
2553 // generate a fake "implementation scope" containing all the
2554 // implementations thus found, for compatibility with old resolve pass.
2556 fn with_scope<F>(&mut self, name: Option<Name>, f: F) where
2557 F: FnOnce(&mut Resolver),
2559 let orig_module = self.current_module.clone();
2561 // Move down in the graph.
2567 build_reduced_graph::populate_module_if_necessary(self, &orig_module);
2569 match orig_module.children.borrow().get(&name) {
2571 debug!("!!! (with scope) didn't find `{}` in `{}`",
2572 token::get_name(name),
2573 self.module_to_string(&*orig_module));
2575 Some(name_bindings) => {
2576 match (*name_bindings).get_module_if_available() {
2578 debug!("!!! (with scope) didn't find module \
2580 token::get_name(name),
2581 self.module_to_string(&*orig_module));
2584 self.current_module = module_;
2594 self.current_module = orig_module;
2597 /// Wraps the given definition in the appropriate number of `DefUpvar`
2603 -> Option<DefLike> {
2605 DlDef(d @ DefUpvar(..)) => {
2606 self.session.span_bug(span,
2607 &format!("unexpected {:?} in bindings", d)[])
2609 DlDef(d @ DefLocal(_)) => {
2610 let node_id = d.def_id().node;
2615 // Nothing to do. Continue.
2617 ClosureRibKind(function_id) => {
2619 def = DefUpvar(node_id, function_id);
2621 let mut seen = self.freevars_seen.borrow_mut();
2622 let seen = match seen.entry(function_id) {
2623 Occupied(v) => v.into_mut(),
2624 Vacant(v) => v.insert(NodeSet()),
2626 if seen.contains(&node_id) {
2629 match self.freevars.borrow_mut().entry(function_id) {
2630 Occupied(v) => v.into_mut(),
2631 Vacant(v) => v.insert(vec![]),
2632 }.push(Freevar { def: prev_def, span: span });
2633 seen.insert(node_id);
2635 MethodRibKind(item_id, _) => {
2636 // If the def is a ty param, and came from the parent
2639 DefTyParam(_, _, did, _) if {
2640 self.def_map.borrow().get(&did.node).cloned()
2641 == Some(DefTyParamBinder(item_id))
2643 DefSelfTy(did) if did == item_id => {} // ok
2645 // This was an attempt to access an upvar inside a
2646 // named function item. This is not allowed, so we
2651 "can't capture dynamic environment in a fn item; \
2652 use the || { ... } closure form instead");
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");
2670 ConstantItemRibKind => {
2671 // Still doesn't deal with upvars
2672 self.resolve_error(span,
2673 "attempt to use a non-constant \
2674 value in a constant");
2681 DlDef(def @ DefTyParam(..)) |
2682 DlDef(def @ DefSelfTy(..)) => {
2685 NormalRibKind | ClosureRibKind(..) => {
2686 // Nothing to do. Continue.
2688 MethodRibKind(item_id, _) => {
2689 // If the def is a ty param, and came from the parent
2692 DefTyParam(_, _, did, _) if {
2693 self.def_map.borrow().get(&did.node).cloned()
2694 == Some(DefTyParamBinder(item_id))
2696 DefSelfTy(did) if did == item_id => {} // ok
2699 // This was an attempt to use a type parameter outside
2702 self.resolve_error(span,
2703 "can't use type parameters from \
2704 outer function; try using a local \
2705 type parameter instead");
2712 // This was an attempt to use a type parameter outside
2715 self.resolve_error(span,
2716 "can't use type parameters from \
2717 outer function; try using a local \
2718 type parameter instead");
2722 ConstantItemRibKind => {
2724 self.resolve_error(span,
2725 "cannot use an outer type \
2726 parameter in this context");
2737 /// Searches the current set of local scopes and
2738 /// applies translations for closures.
2739 fn search_ribs(&self,
2743 -> Option<DefLike> {
2744 // FIXME #4950: Try caching?
2746 for (i, rib) in ribs.iter().enumerate().rev() {
2747 match rib.bindings.get(&name).cloned() {
2749 return self.upvarify(&ribs[i + 1..], def_like, span);
2760 /// Searches the current set of local scopes for labels.
2761 /// Stops after meeting a closure.
2762 fn search_label(&self, name: Name) -> Option<DefLike> {
2763 for rib in self.label_ribs.iter().rev() {
2769 // Do not resolve labels across function boundary
2773 let result = rib.bindings.get(&name).cloned();
2774 if result.is_some() {
2781 fn resolve_crate(&mut self, krate: &ast::Crate) {
2782 debug!("(resolving crate) starting");
2784 visit::walk_crate(self, krate);
2787 fn check_if_primitive_type_name(&self, name: Name, span: Span) {
2788 if let Some(_) = self.primitive_type_table.primitive_types.get(&name) {
2789 span_err!(self.session, span, E0316,
2790 "user-defined types or type parameters cannot shadow the primitive types");
2794 fn resolve_item(&mut self, item: &Item) {
2795 let name = item.ident.name;
2797 debug!("(resolving item) resolving {}",
2798 token::get_name(name));
2802 // enum item: resolve all the variants' discrs,
2803 // then resolve the ty params
2804 ItemEnum(ref enum_def, ref generics) => {
2805 self.check_if_primitive_type_name(name, item.span);
2807 for variant in &(*enum_def).variants {
2808 if let Some(ref dis_expr) = variant.node.disr_expr {
2809 // resolve the discriminator expr
2811 self.with_constant_rib(|this| {
2812 this.resolve_expr(&**dis_expr);
2817 // n.b. the discr expr gets visited twice.
2818 // but maybe it's okay since the first time will signal an
2819 // error if there is one? -- tjc
2820 self.with_type_parameter_rib(HasTypeParameters(generics,
2825 this.resolve_type_parameters(&generics.ty_params);
2826 this.resolve_where_clause(&generics.where_clause);
2827 visit::walk_item(this, item);
2831 ItemTy(_, ref generics) => {
2832 self.check_if_primitive_type_name(name, item.span);
2834 self.with_type_parameter_rib(HasTypeParameters(generics,
2839 this.resolve_type_parameters(&generics.ty_params);
2840 visit::walk_item(this, item);
2846 ref implemented_traits,
2848 ref impl_items) => {
2849 self.resolve_implementation(item.id,
2856 ItemTrait(_, ref generics, ref bounds, ref trait_items) => {
2857 self.check_if_primitive_type_name(name, item.span);
2859 // Create a new rib for the self type.
2860 let mut self_type_rib = Rib::new(ItemRibKind);
2862 // plain insert (no renaming, types are not currently hygienic....)
2863 let name = self.type_self_name;
2864 self_type_rib.bindings.insert(name, DlDef(DefSelfTy(item.id)));
2865 self.type_ribs.push(self_type_rib);
2867 // Create a new rib for the trait-wide type parameters.
2868 self.with_type_parameter_rib(HasTypeParameters(generics,
2873 this.resolve_type_parameters(&generics.ty_params);
2874 this.resolve_where_clause(&generics.where_clause);
2876 this.resolve_type_parameter_bounds(item.id, bounds,
2879 for trait_item in &(*trait_items) {
2880 // Create a new rib for the trait_item-specific type
2883 // FIXME #4951: Do we need a node ID here?
2886 ast::RequiredMethod(ref ty_m) => {
2887 this.with_type_parameter_rib
2888 (HasTypeParameters(&ty_m.generics,
2891 MethodRibKind(item.id, RequiredMethod)),
2894 // Resolve the method-specific type
2896 this.resolve_type_parameters(
2897 &ty_m.generics.ty_params);
2898 this.resolve_where_clause(&ty_m.generics
2901 for argument in &ty_m.decl.inputs {
2902 this.resolve_type(&*argument.ty);
2905 if let SelfExplicit(ref typ, _) = ty_m.explicit_self.node {
2906 this.resolve_type(&**typ)
2909 if let ast::Return(ref ret_ty) = ty_m.decl.output {
2910 this.resolve_type(&**ret_ty);
2914 ast::ProvidedMethod(ref m) => {
2915 this.resolve_method(MethodRibKind(item.id,
2916 ProvidedMethod(m.id)),
2919 ast::TypeTraitItem(ref data) => {
2920 this.resolve_type_parameter(&data.ty_param);
2921 visit::walk_trait_item(this, trait_item);
2927 self.type_ribs.pop();
2930 ItemStruct(ref struct_def, ref generics) => {
2931 self.check_if_primitive_type_name(name, item.span);
2933 self.resolve_struct(item.id,
2935 &struct_def.fields[]);
2938 ItemMod(ref module_) => {
2939 self.with_scope(Some(name), |this| {
2940 this.resolve_module(module_, item.span, name,
2945 ItemForeignMod(ref foreign_module) => {
2946 self.with_scope(Some(name), |this| {
2947 for foreign_item in &foreign_module.items {
2948 match foreign_item.node {
2949 ForeignItemFn(_, ref generics) => {
2950 this.with_type_parameter_rib(
2952 generics, FnSpace, foreign_item.id,
2955 this.resolve_type_parameters(&generics.ty_params);
2956 this.resolve_where_clause(&generics.where_clause);
2957 visit::walk_foreign_item(this, &**foreign_item)
2960 ForeignItemStatic(..) => {
2961 visit::walk_foreign_item(this,
2969 ItemFn(ref fn_decl, _, _, ref generics, ref block) => {
2970 self.resolve_function(ItemRibKind,
2980 ItemConst(..) | ItemStatic(..) => {
2981 self.with_constant_rib(|this| {
2982 visit::walk_item(this, item);
2986 ItemUse(ref view_path) => {
2987 // check for imports shadowing primitive types
2988 if let ast::ViewPathSimple(ident, _) = view_path.node {
2989 match self.def_map.borrow().get(&item.id) {
2990 Some(&DefTy(..)) | Some(&DefStruct(..)) | Some(&DefTrait(..)) | None => {
2991 self.check_if_primitive_type_name(ident.name, item.span);
2998 ItemExternCrate(_) | ItemMac(..) => {
2999 // do nothing, these are just around to be encoded
3004 fn with_type_parameter_rib<F>(&mut self, type_parameters: TypeParameters, f: F) where
3005 F: FnOnce(&mut Resolver),
3007 match type_parameters {
3008 HasTypeParameters(generics, space, node_id, rib_kind) => {
3009 let mut function_type_rib = Rib::new(rib_kind);
3010 let mut seen_bindings = HashSet::new();
3011 for (index, type_parameter) in generics.ty_params.iter().enumerate() {
3012 let name = type_parameter.ident.name;
3013 debug!("with_type_parameter_rib: {} {}", node_id,
3016 if seen_bindings.contains(&name) {
3017 self.resolve_error(type_parameter.span,
3018 &format!("the name `{}` is already \
3020 parameter in this type \
3025 seen_bindings.insert(name);
3027 let def_like = DlDef(DefTyParam(space,
3029 local_def(type_parameter.id),
3031 // Associate this type parameter with
3032 // the item that bound it
3033 self.record_def(type_parameter.id,
3034 (DefTyParamBinder(node_id), LastMod(AllPublic)));
3035 // plain insert (no renaming)
3036 function_type_rib.bindings.insert(name, def_like);
3038 self.type_ribs.push(function_type_rib);
3041 NoTypeParameters => {
3048 match type_parameters {
3049 HasTypeParameters(..) => { self.type_ribs.pop(); }
3050 NoTypeParameters => { }
3054 fn with_label_rib<F>(&mut self, f: F) where
3055 F: FnOnce(&mut Resolver),
3057 self.label_ribs.push(Rib::new(NormalRibKind));
3059 self.label_ribs.pop();
3062 fn with_constant_rib<F>(&mut self, f: F) where
3063 F: FnOnce(&mut Resolver),
3065 self.value_ribs.push(Rib::new(ConstantItemRibKind));
3066 self.type_ribs.push(Rib::new(ConstantItemRibKind));
3068 self.type_ribs.pop();
3069 self.value_ribs.pop();
3072 fn resolve_function(&mut self,
3074 optional_declaration: Option<&FnDecl>,
3075 type_parameters: TypeParameters,
3077 // Create a value rib for the function.
3078 let function_value_rib = Rib::new(rib_kind);
3079 self.value_ribs.push(function_value_rib);
3081 // Create a label rib for the function.
3082 let function_label_rib = Rib::new(rib_kind);
3083 self.label_ribs.push(function_label_rib);
3085 // If this function has type parameters, add them now.
3086 self.with_type_parameter_rib(type_parameters, |this| {
3087 // Resolve the type parameters.
3088 match type_parameters {
3089 NoTypeParameters => {
3092 HasTypeParameters(ref generics, _, _, _) => {
3093 this.resolve_type_parameters(&generics.ty_params);
3094 this.resolve_where_clause(&generics.where_clause);
3098 // Add each argument to the rib.
3099 match optional_declaration {
3103 Some(declaration) => {
3104 let mut bindings_list = HashMap::new();
3105 for argument in &declaration.inputs {
3106 this.resolve_pattern(&*argument.pat,
3107 ArgumentIrrefutableMode,
3108 &mut bindings_list);
3110 this.resolve_type(&*argument.ty);
3112 debug!("(resolving function) recorded argument");
3115 if let ast::Return(ref ret_ty) = declaration.output {
3116 this.resolve_type(&**ret_ty);
3121 // Resolve the function body.
3122 this.resolve_block(&*block);
3124 debug!("(resolving function) leaving function");
3127 self.label_ribs.pop();
3128 self.value_ribs.pop();
3131 fn resolve_type_parameters(&mut self,
3132 type_parameters: &OwnedSlice<TyParam>) {
3133 for type_parameter in &**type_parameters {
3134 self.resolve_type_parameter(type_parameter);
3138 fn resolve_type_parameter(&mut self,
3139 type_parameter: &TyParam) {
3140 self.check_if_primitive_type_name(type_parameter.ident.name, type_parameter.span);
3141 for bound in &*type_parameter.bounds {
3142 self.resolve_type_parameter_bound(type_parameter.id, bound,
3143 TraitBoundingTypeParameter);
3145 match type_parameter.default {
3146 Some(ref ty) => self.resolve_type(&**ty),
3151 fn resolve_type_parameter_bounds(&mut self,
3153 type_parameter_bounds: &OwnedSlice<TyParamBound>,
3154 reference_type: TraitReferenceType) {
3155 for type_parameter_bound in &**type_parameter_bounds {
3156 self.resolve_type_parameter_bound(id, type_parameter_bound,
3161 fn resolve_type_parameter_bound(&mut self,
3163 type_parameter_bound: &TyParamBound,
3164 reference_type: TraitReferenceType) {
3165 match *type_parameter_bound {
3166 TraitTyParamBound(ref tref, _) => {
3167 self.resolve_poly_trait_reference(id, tref, reference_type)
3169 RegionTyParamBound(..) => {}
3173 fn resolve_poly_trait_reference(&mut self,
3175 poly_trait_reference: &PolyTraitRef,
3176 reference_type: TraitReferenceType) {
3177 self.resolve_trait_reference(id, &poly_trait_reference.trait_ref, reference_type)
3180 fn resolve_trait_reference(&mut self,
3182 trait_reference: &TraitRef,
3183 reference_type: TraitReferenceType) {
3184 match self.resolve_path(id, &trait_reference.path, TypeNS, true) {
3186 let path_str = self.path_names_to_string(&trait_reference.path);
3187 let usage_str = match reference_type {
3188 TraitBoundingTypeParameter => "bound type parameter with",
3189 TraitImplementation => "implement",
3190 TraitDerivation => "derive",
3191 TraitObject => "reference",
3192 TraitQPath => "extract an associated item from",
3195 let msg = format!("attempt to {} a nonexistent trait `{}`", usage_str, path_str);
3196 self.resolve_error(trait_reference.path.span, &msg[]);
3200 (DefTrait(_), _) => {
3201 debug!("(resolving trait) found trait def: {:?}", def);
3202 self.record_def(trait_reference.ref_id, def);
3205 self.resolve_error(trait_reference.path.span,
3206 &format!("`{}` is not a trait",
3207 self.path_names_to_string(
3208 &trait_reference.path))[]);
3210 // If it's a typedef, give a note
3211 if let DefTy(..) = def {
3212 self.session.span_note(
3213 trait_reference.path.span,
3214 &format!("`type` aliases cannot be used for traits")
3223 fn resolve_where_clause(&mut self, where_clause: &ast::WhereClause) {
3224 for predicate in &where_clause.predicates {
3226 &ast::WherePredicate::BoundPredicate(ref bound_pred) => {
3227 self.resolve_type(&*bound_pred.bounded_ty);
3229 for bound in &*bound_pred.bounds {
3230 self.resolve_type_parameter_bound(bound_pred.bounded_ty.id, bound,
3231 TraitBoundingTypeParameter);
3234 &ast::WherePredicate::RegionPredicate(_) => {}
3235 &ast::WherePredicate::EqPredicate(ref eq_pred) => {
3236 match self.resolve_path(eq_pred.id, &eq_pred.path, TypeNS, true) {
3237 Some((def @ DefTyParam(..), last_private)) => {
3238 self.record_def(eq_pred.id, (def, last_private));
3241 self.resolve_error(eq_pred.path.span,
3242 "undeclared associated type");
3246 self.resolve_type(&*eq_pred.ty);
3252 fn resolve_struct(&mut self,
3254 generics: &Generics,
3255 fields: &[StructField]) {
3256 // If applicable, create a rib for the type parameters.
3257 self.with_type_parameter_rib(HasTypeParameters(generics,
3262 // Resolve the type parameters.
3263 this.resolve_type_parameters(&generics.ty_params);
3264 this.resolve_where_clause(&generics.where_clause);
3267 for field in fields {
3268 this.resolve_type(&*field.node.ty);
3273 // Does this really need to take a RibKind or is it always going
3274 // to be NormalRibKind?
3275 fn resolve_method(&mut self,
3277 method: &ast::Method) {
3278 let method_generics = method.pe_generics();
3279 let type_parameters = HasTypeParameters(method_generics,
3284 if let SelfExplicit(ref typ, _) = method.pe_explicit_self().node {
3285 self.resolve_type(&**typ);
3288 self.resolve_function(rib_kind,
3289 Some(method.pe_fn_decl()),
3294 fn with_current_self_type<T, F>(&mut self, self_type: &Ty, f: F) -> T where
3295 F: FnOnce(&mut Resolver) -> T,
3297 // Handle nested impls (inside fn bodies)
3298 let previous_value = replace(&mut self.current_self_type, Some(self_type.clone()));
3299 let result = f(self);
3300 self.current_self_type = previous_value;
3304 fn with_optional_trait_ref<T, F>(&mut self, id: NodeId,
3305 opt_trait_ref: &Option<TraitRef>,
3307 F: FnOnce(&mut Resolver) -> T,
3309 let new_val = match *opt_trait_ref {
3310 Some(ref trait_ref) => {
3311 self.resolve_trait_reference(id, trait_ref, TraitImplementation);
3313 match self.def_map.borrow().get(&trait_ref.ref_id) {
3315 let did = def.def_id();
3316 Some((did, trait_ref.clone()))
3323 let original_trait_ref = replace(&mut self.current_trait_ref, new_val);
3324 let result = f(self);
3325 self.current_trait_ref = original_trait_ref;
3329 fn resolve_implementation(&mut self,
3331 generics: &Generics,
3332 opt_trait_reference: &Option<TraitRef>,
3334 impl_items: &[ImplItem]) {
3335 // If applicable, create a rib for the type parameters.
3336 self.with_type_parameter_rib(HasTypeParameters(generics,
3341 // Resolve the type parameters.
3342 this.resolve_type_parameters(&generics.ty_params);
3343 this.resolve_where_clause(&generics.where_clause);
3345 // Resolve the trait reference, if necessary.
3346 this.with_optional_trait_ref(id, opt_trait_reference, |this| {
3347 // Resolve the self type.
3348 this.resolve_type(self_type);
3350 this.with_current_self_type(self_type, |this| {
3351 for impl_item in impl_items {
3353 MethodImplItem(ref method) => {
3354 // If this is a trait impl, ensure the method
3356 this.check_trait_item(method.pe_ident().name,
3359 // We also need a new scope for the method-
3360 // specific type parameters.
3361 this.resolve_method(
3362 MethodRibKind(id, ProvidedMethod(method.id)),
3365 TypeImplItem(ref typedef) => {
3366 // If this is a trait impl, ensure the method
3368 this.check_trait_item(typedef.ident.name,
3371 this.resolve_type(&*typedef.typ);
3379 // Check that the current type is indeed a type, if we have an anonymous impl
3380 if opt_trait_reference.is_none() {
3381 match self_type.node {
3382 // TyPath is the only thing that we handled in `build_reduced_graph_for_item`,
3383 // where we created a module with the name of the type in order to implement
3384 // an anonymous trait. In the case that the path does not resolve to an actual
3385 // type, the result will be that the type name resolves to a module but not
3386 // a type (shadowing any imported modules or types with this name), leading
3387 // to weird user-visible bugs. So we ward this off here. See #15060.
3388 TyPath(ref path, path_id) => {
3389 match self.def_map.borrow().get(&path_id) {
3390 // FIXME: should we catch other options and give more precise errors?
3391 Some(&DefMod(_)) => {
3392 self.resolve_error(path.span, "inherent implementations are not \
3393 allowed for types not defined in \
3394 the current module");
3404 fn check_trait_item(&self, name: Name, span: Span) {
3405 // If there is a TraitRef in scope for an impl, then the method must be in the trait.
3406 if let Some((did, ref trait_ref)) = self.current_trait_ref {
3407 if self.trait_item_map.get(&(name, did)).is_none() {
3408 let path_str = self.path_names_to_string(&trait_ref.path);
3409 self.resolve_error(span,
3410 &format!("method `{}` is not a member of trait `{}`",
3411 token::get_name(name),
3417 fn resolve_module(&mut self, module: &Mod, _span: Span,
3418 _name: Name, id: NodeId) {
3419 // Write the implementations in scope into the module metadata.
3420 debug!("(resolving module) resolving module ID {}", id);
3421 visit::walk_mod(self, module);
3424 fn resolve_local(&mut self, local: &Local) {
3425 // Resolve the type.
3426 if let Some(ref ty) = local.ty {
3427 self.resolve_type(&**ty);
3430 // Resolve the initializer, if necessary.
3435 Some(ref initializer) => {
3436 self.resolve_expr(&**initializer);
3440 // Resolve the pattern.
3441 let mut bindings_list = HashMap::new();
3442 self.resolve_pattern(&*local.pat,
3443 LocalIrrefutableMode,
3444 &mut bindings_list);
3447 // build a map from pattern identifiers to binding-info's.
3448 // this is done hygienically. This could arise for a macro
3449 // that expands into an or-pattern where one 'x' was from the
3450 // user and one 'x' came from the macro.
3451 fn binding_mode_map(&mut self, pat: &Pat) -> BindingMap {
3452 let mut result = HashMap::new();
3453 pat_bindings(&self.def_map, pat, |binding_mode, _id, sp, path1| {
3454 let name = mtwt::resolve(path1.node);
3455 result.insert(name, BindingInfo {
3457 binding_mode: binding_mode
3463 // check that all of the arms in an or-pattern have exactly the
3464 // same set of bindings, with the same binding modes for each.
3465 fn check_consistent_bindings(&mut self, arm: &Arm) {
3466 if arm.pats.len() == 0 {
3469 let map_0 = self.binding_mode_map(&*arm.pats[0]);
3470 for (i, p) in arm.pats.iter().enumerate() {
3471 let map_i = self.binding_mode_map(&**p);
3473 for (&key, &binding_0) in &map_0 {
3474 match map_i.get(&key) {
3478 &format!("variable `{}` from pattern #1 is \
3479 not bound in pattern #{}",
3480 token::get_name(key),
3483 Some(binding_i) => {
3484 if binding_0.binding_mode != binding_i.binding_mode {
3487 &format!("variable `{}` is bound with different \
3488 mode in pattern #{} than in pattern #1",
3489 token::get_name(key),
3496 for (&key, &binding) in &map_i {
3497 if !map_0.contains_key(&key) {
3500 &format!("variable `{}` from pattern {}{} is \
3501 not bound in pattern {}1",
3502 token::get_name(key),
3503 "#", i + 1, "#")[]);
3509 fn resolve_arm(&mut self, arm: &Arm) {
3510 self.value_ribs.push(Rib::new(NormalRibKind));
3512 let mut bindings_list = HashMap::new();
3513 for pattern in &arm.pats {
3514 self.resolve_pattern(&**pattern, RefutableMode, &mut bindings_list);
3517 // This has to happen *after* we determine which
3518 // pat_idents are variants
3519 self.check_consistent_bindings(arm);
3521 visit::walk_expr_opt(self, &arm.guard);
3522 self.resolve_expr(&*arm.body);
3524 self.value_ribs.pop();
3527 fn resolve_block(&mut self, block: &Block) {
3528 debug!("(resolving block) entering block");
3529 self.value_ribs.push(Rib::new(NormalRibKind));
3531 // Move down in the graph, if there's an anonymous module rooted here.
3532 let orig_module = self.current_module.clone();
3533 match orig_module.anonymous_children.borrow().get(&block.id) {
3534 None => { /* Nothing to do. */ }
3535 Some(anonymous_module) => {
3536 debug!("(resolving block) found anonymous module, moving \
3538 self.current_module = anonymous_module.clone();
3542 // Check for imports appearing after non-item statements.
3543 let mut found_non_item = false;
3544 for statement in &block.stmts {
3545 if let ast::StmtDecl(ref declaration, _) = statement.node {
3546 if let ast::DeclItem(ref i) = declaration.node {
3548 ItemExternCrate(_) | ItemUse(_) if found_non_item => {
3549 span_err!(self.session, i.span, E0154,
3550 "imports are not allowed after non-item statements");
3555 found_non_item = true
3558 found_non_item = true;
3562 // Descend into the block.
3563 visit::walk_block(self, block);
3566 self.current_module = orig_module;
3568 self.value_ribs.pop();
3569 debug!("(resolving block) leaving block");
3572 fn resolve_type(&mut self, ty: &Ty) {
3574 // Like path expressions, the interpretation of path types depends
3575 // on whether the path has multiple elements in it or not.
3577 TyPath(ref path, path_id) => {
3578 // This is a path in the type namespace. Walk through scopes
3580 let mut result_def = None;
3582 // First, check to see whether the name is a primitive type.
3583 if path.segments.len() == 1 {
3584 let id = path.segments.last().unwrap().identifier;
3586 match self.primitive_type_table
3590 Some(&primitive_type) => {
3592 Some((DefPrimTy(primitive_type), LastMod(AllPublic)));
3594 if path.segments[0].parameters.has_lifetimes() {
3595 span_err!(self.session, path.span, E0157,
3596 "lifetime parameters are not allowed on this type");
3597 } else if !path.segments[0].parameters.is_empty() {
3598 span_err!(self.session, path.span, E0153,
3599 "type parameters are not allowed on this type");
3608 if let None = result_def {
3609 result_def = self.resolve_path(ty.id, path, TypeNS, true);
3614 // Write the result into the def map.
3615 debug!("(resolving type) writing resolution for `{}` \
3617 self.path_names_to_string(path),
3619 self.record_def(path_id, def);
3622 let msg = format!("use of undeclared type name `{}`",
3623 self.path_names_to_string(path));
3624 self.resolve_error(ty.span, &msg[]);
3629 TyObjectSum(ref ty, ref bound_vec) => {
3630 self.resolve_type(&**ty);
3631 self.resolve_type_parameter_bounds(ty.id, bound_vec,
3632 TraitBoundingTypeParameter);
3635 TyQPath(ref qpath) => {
3636 self.resolve_type(&*qpath.self_type);
3637 self.resolve_trait_reference(ty.id, &*qpath.trait_ref, TraitQPath);
3638 for ty in qpath.item_path.parameters.types() {
3639 self.resolve_type(&**ty);
3641 for binding in qpath.item_path.parameters.bindings() {
3642 self.resolve_type(&*binding.ty);
3646 TyPolyTraitRef(ref bounds) => {
3647 self.resolve_type_parameter_bounds(
3651 visit::walk_ty(self, ty);
3654 // Just resolve embedded types.
3655 visit::walk_ty(self, ty);
3660 fn resolve_pattern(&mut self,
3662 mode: PatternBindingMode,
3663 // Maps idents to the node ID for the (outermost)
3664 // pattern that binds them
3665 bindings_list: &mut HashMap<Name, NodeId>) {
3666 let pat_id = pattern.id;
3667 walk_pat(pattern, |pattern| {
3668 match pattern.node {
3669 PatIdent(binding_mode, ref path1, _) => {
3671 // The meaning of pat_ident with no type parameters
3672 // depends on whether an enum variant or unit-like struct
3673 // with that name is in scope. The probing lookup has to
3674 // be careful not to emit spurious errors. Only matching
3675 // patterns (match) can match nullary variants or
3676 // unit-like structs. For binding patterns (let), matching
3677 // such a value is simply disallowed (since it's rarely
3680 let ident = path1.node;
3681 let renamed = mtwt::resolve(ident);
3683 match self.resolve_bare_identifier_pattern(ident.name, pattern.span) {
3684 FoundStructOrEnumVariant(ref def, lp)
3685 if mode == RefutableMode => {
3686 debug!("(resolving pattern) resolving `{}` to \
3687 struct or enum variant",
3688 token::get_name(renamed));
3690 self.enforce_default_binding_mode(
3694 self.record_def(pattern.id, (def.clone(), lp));
3696 FoundStructOrEnumVariant(..) => {
3699 &format!("declaration of `{}` shadows an enum \
3700 variant or unit-like struct in \
3702 token::get_name(renamed))[]);
3704 FoundConst(ref def, lp) if mode == RefutableMode => {
3705 debug!("(resolving pattern) resolving `{}` to \
3707 token::get_name(renamed));
3709 self.enforce_default_binding_mode(
3713 self.record_def(pattern.id, (def.clone(), lp));
3716 self.resolve_error(pattern.span,
3717 "only irrefutable patterns \
3720 BareIdentifierPatternUnresolved => {
3721 debug!("(resolving pattern) binding `{}`",
3722 token::get_name(renamed));
3724 let def = DefLocal(pattern.id);
3726 // Record the definition so that later passes
3727 // will be able to distinguish variants from
3728 // locals in patterns.
3730 self.record_def(pattern.id, (def, LastMod(AllPublic)));
3732 // Add the binding to the local ribs, if it
3733 // doesn't already exist in the bindings list. (We
3734 // must not add it if it's in the bindings list
3735 // because that breaks the assumptions later
3736 // passes make about or-patterns.)
3737 if !bindings_list.contains_key(&renamed) {
3738 let this = &mut *self;
3739 let last_rib = this.value_ribs.last_mut().unwrap();
3740 last_rib.bindings.insert(renamed, DlDef(def));
3741 bindings_list.insert(renamed, pat_id);
3742 } else if mode == ArgumentIrrefutableMode &&
3743 bindings_list.contains_key(&renamed) {
3744 // Forbid duplicate bindings in the same
3746 self.resolve_error(pattern.span,
3747 &format!("identifier `{}` \
3755 } else if bindings_list.get(&renamed) ==
3757 // Then this is a duplicate variable in the
3758 // same disjunction, which is an error.
3759 self.resolve_error(pattern.span,
3760 &format!("identifier `{}` is bound \
3761 more than once in the same \
3763 token::get_ident(ident))[]);
3765 // Else, not bound in the same pattern: do
3771 PatEnum(ref path, _) => {
3772 // This must be an enum variant, struct or const.
3773 match self.resolve_path(pat_id, path, ValueNS, false) {
3774 Some(def @ (DefVariant(..), _)) |
3775 Some(def @ (DefStruct(..), _)) |
3776 Some(def @ (DefConst(..), _)) => {
3777 self.record_def(pattern.id, def);
3779 Some((DefStatic(..), _)) => {
3780 self.resolve_error(path.span,
3781 "static variables cannot be \
3782 referenced in a pattern, \
3783 use a `const` instead");
3786 self.resolve_error(path.span,
3787 &format!("`{}` is not an enum variant, struct or const",
3789 path.segments.last().unwrap().identifier)));
3792 self.resolve_error(path.span,
3793 &format!("unresolved enum variant, struct or const `{}`",
3794 token::get_ident(path.segments.last().unwrap().identifier)));
3798 // Check the types in the path pattern.
3799 for ty in path.segments
3801 .flat_map(|s| s.parameters.types().into_iter()) {
3802 self.resolve_type(&**ty);
3806 PatLit(ref expr) => {
3807 self.resolve_expr(&**expr);
3810 PatRange(ref first_expr, ref last_expr) => {
3811 self.resolve_expr(&**first_expr);
3812 self.resolve_expr(&**last_expr);
3815 PatStruct(ref path, _, _) => {
3816 match self.resolve_path(pat_id, path, TypeNS, false) {
3817 Some(definition) => {
3818 self.record_def(pattern.id, definition);
3821 debug!("(resolving pattern) didn't find struct \
3822 def: {:?}", result);
3823 let msg = format!("`{}` does not name a structure",
3824 self.path_names_to_string(path));
3825 self.resolve_error(path.span, &msg[]);
3838 fn resolve_bare_identifier_pattern(&mut self, name: Name, span: Span)
3839 -> BareIdentifierPatternResolution {
3840 let module = self.current_module.clone();
3841 match self.resolve_item_in_lexical_scope(module,
3844 Success((target, _)) => {
3845 debug!("(resolve bare identifier pattern) succeeded in \
3846 finding {} at {:?}",
3847 token::get_name(name),
3848 target.bindings.value_def.borrow());
3849 match *target.bindings.value_def.borrow() {
3851 panic!("resolved name in the value namespace to a \
3852 set of name bindings with no def?!");
3855 // For the two success cases, this lookup can be
3856 // considered as not having a private component because
3857 // the lookup happened only within the current module.
3859 def @ DefVariant(..) | def @ DefStruct(..) => {
3860 return FoundStructOrEnumVariant(def, LastMod(AllPublic));
3862 def @ DefConst(..) => {
3863 return FoundConst(def, LastMod(AllPublic));
3866 self.resolve_error(span,
3867 "static variables cannot be \
3868 referenced in a pattern, \
3869 use a `const` instead");
3870 return BareIdentifierPatternUnresolved;
3873 return BareIdentifierPatternUnresolved;
3881 panic!("unexpected indeterminate result");
3885 Some((span, msg)) => {
3886 self.resolve_error(span, &format!("failed to resolve: {}",
3892 debug!("(resolve bare identifier pattern) failed to find {}",
3893 token::get_name(name));
3894 return BareIdentifierPatternUnresolved;
3899 /// If `check_ribs` is true, checks the local definitions first; i.e.
3900 /// doesn't skip straight to the containing module.
3901 fn resolve_path(&mut self,
3904 namespace: Namespace,
3905 check_ribs: bool) -> Option<(Def, LastPrivate)> {
3906 // First, resolve the types and associated type bindings.
3907 for ty in path.segments.iter().flat_map(|s| s.parameters.types().into_iter()) {
3908 self.resolve_type(&**ty);
3910 for binding in path.segments.iter().flat_map(|s| s.parameters.bindings().into_iter()) {
3911 self.resolve_type(&*binding.ty);
3914 // A special case for sugared associated type paths `T::A` where `T` is
3915 // a type parameter and `A` is an associated type on some bound of `T`.
3916 if namespace == TypeNS && path.segments.len() == 2 {
3917 match self.resolve_identifier(path.segments[0].identifier,
3921 Some((def, last_private)) => {
3923 DefTyParam(_, _, did, _) => {
3924 let def = DefAssociatedPath(TyParamProvenance::FromParam(did),
3925 path.segments.last()
3926 .unwrap().identifier);
3927 return Some((def, last_private));
3930 let def = DefAssociatedPath(TyParamProvenance::FromSelf(local_def(nid)),
3931 path.segments.last()
3932 .unwrap().identifier);
3933 return Some((def, last_private));
3943 return self.resolve_crate_relative_path(path, namespace);
3946 // Try to find a path to an item in a module.
3947 let unqualified_def =
3948 self.resolve_identifier(path.segments.last().unwrap().identifier,
3953 if path.segments.len() > 1 {
3954 let def = self.resolve_module_relative_path(path, namespace);
3955 match (def, unqualified_def) {
3956 (Some((ref d, _)), Some((ref ud, _))) if *d == *ud => {
3958 .add_lint(lint::builtin::UNUSED_QUALIFICATIONS,
3961 "unnecessary qualification".to_string());
3969 return unqualified_def;
3972 // resolve a single identifier (used as a varref)
3973 fn resolve_identifier(&mut self,
3975 namespace: Namespace,
3978 -> Option<(Def, LastPrivate)> {
3980 match self.resolve_identifier_in_local_ribs(identifier,
3984 return Some((def, LastMod(AllPublic)));
3992 return self.resolve_item_by_name_in_lexical_scope(identifier.name, namespace);
3995 // FIXME #4952: Merge me with resolve_name_in_module?
3996 fn resolve_definition_of_name_in_module(&mut self,
3997 containing_module: Rc<Module>,
3999 namespace: Namespace)
4001 // First, search children.
4002 build_reduced_graph::populate_module_if_necessary(self, &containing_module);
4004 match containing_module.children.borrow().get(&name) {
4005 Some(child_name_bindings) => {
4006 match child_name_bindings.def_for_namespace(namespace) {
4008 // Found it. Stop the search here.
4009 let p = child_name_bindings.defined_in_public_namespace(
4011 let lp = if p {LastMod(AllPublic)} else {
4012 LastMod(DependsOn(def.def_id()))
4014 return ChildNameDefinition(def, lp);
4022 // Next, search import resolutions.
4023 match containing_module.import_resolutions.borrow().get(&name) {
4024 Some(import_resolution) if import_resolution.is_public => {
4025 if let Some(target) = (*import_resolution).target_for_namespace(namespace) {
4026 match target.bindings.def_for_namespace(namespace) {
4029 let id = import_resolution.id(namespace);
4030 // track imports and extern crates as well
4031 self.used_imports.insert((id, namespace));
4032 self.record_import_use(id, name);
4033 match target.target_module.def_id.get() {
4034 Some(DefId{krate: kid, ..}) => {
4035 self.used_crates.insert(kid);
4039 return ImportNameDefinition(def, LastMod(AllPublic));
4042 // This can happen with external impls, due to
4043 // the imperfect way we read the metadata.
4048 Some(..) | None => {} // Continue.
4051 // Finally, search through external children.
4052 if namespace == TypeNS {
4053 if let Some(module) = containing_module.external_module_children.borrow()
4054 .get(&name).cloned() {
4055 if let Some(def_id) = module.def_id.get() {
4056 // track used crates
4057 self.used_crates.insert(def_id.krate);
4058 let lp = if module.is_public {LastMod(AllPublic)} else {
4059 LastMod(DependsOn(def_id))
4061 return ChildNameDefinition(DefMod(def_id), lp);
4066 return NoNameDefinition;
4069 // resolve a "module-relative" path, e.g. a::b::c
4070 fn resolve_module_relative_path(&mut self,
4072 namespace: Namespace)
4073 -> Option<(Def, LastPrivate)> {
4074 let module_path = path.segments.init().iter()
4075 .map(|ps| ps.identifier.name)
4076 .collect::<Vec<_>>();
4078 let containing_module;
4080 let module = self.current_module.clone();
4081 match self.resolve_module_path(module,
4087 let (span, msg) = match err {
4088 Some((span, msg)) => (span, msg),
4090 let msg = format!("Use of undeclared type or module `{}`",
4091 self.names_to_string(&module_path));
4096 self.resolve_error(span, &format!("failed to resolve. {}",
4100 Indeterminate => panic!("indeterminate unexpected"),
4101 Success((resulting_module, resulting_last_private)) => {
4102 containing_module = resulting_module;
4103 last_private = resulting_last_private;
4107 let name = path.segments.last().unwrap().identifier.name;
4108 let def = match self.resolve_definition_of_name_in_module(containing_module.clone(),
4111 NoNameDefinition => {
4112 // We failed to resolve the name. Report an error.
4115 ChildNameDefinition(def, lp) | ImportNameDefinition(def, lp) => {
4116 (def, last_private.or(lp))
4119 if let Some(DefId{krate: kid, ..}) = containing_module.def_id.get() {
4120 self.used_crates.insert(kid);
4125 /// Invariant: This must be called only during main resolution, not during
4126 /// import resolution.
4127 fn resolve_crate_relative_path(&mut self,
4129 namespace: Namespace)
4130 -> Option<(Def, LastPrivate)> {
4131 let module_path = path.segments.init().iter()
4132 .map(|ps| ps.identifier.name)
4133 .collect::<Vec<_>>();
4135 let root_module = self.graph_root.get_module();
4137 let containing_module;
4139 match self.resolve_module_path_from_root(root_module,
4144 LastMod(AllPublic)) {
4146 let (span, msg) = match err {
4147 Some((span, msg)) => (span, msg),
4149 let msg = format!("Use of undeclared module `::{}`",
4150 self.names_to_string(&module_path[]));
4155 self.resolve_error(span, &format!("failed to resolve. {}",
4161 panic!("indeterminate unexpected");
4164 Success((resulting_module, resulting_last_private)) => {
4165 containing_module = resulting_module;
4166 last_private = resulting_last_private;
4170 let name = path.segments.last().unwrap().identifier.name;
4171 match self.resolve_definition_of_name_in_module(containing_module,
4174 NoNameDefinition => {
4175 // We failed to resolve the name. Report an error.
4178 ChildNameDefinition(def, lp) | ImportNameDefinition(def, lp) => {
4179 return Some((def, last_private.or(lp)));
4184 fn resolve_identifier_in_local_ribs(&mut self,
4186 namespace: Namespace,
4189 // Check the local set of ribs.
4190 let search_result = match namespace {
4192 let renamed = mtwt::resolve(ident);
4193 self.search_ribs(&self.value_ribs, renamed, span)
4196 let name = ident.name;
4197 self.search_ribs(&self.type_ribs[], name, span)
4201 match search_result {
4202 Some(DlDef(def)) => {
4203 debug!("(resolving path in local ribs) resolved `{}` to \
4205 token::get_ident(ident),
4209 Some(DlField) | Some(DlImpl(_)) | None => {
4215 fn resolve_item_by_name_in_lexical_scope(&mut self,
4217 namespace: Namespace)
4218 -> Option<(Def, LastPrivate)> {
4220 let module = self.current_module.clone();
4221 match self.resolve_item_in_lexical_scope(module,
4224 Success((target, _)) => {
4225 match (*target.bindings).def_for_namespace(namespace) {
4227 // This can happen if we were looking for a type and
4228 // found a module instead. Modules don't have defs.
4229 debug!("(resolving item path by identifier in lexical \
4230 scope) failed to resolve {} after success...",
4231 token::get_name(name));
4235 debug!("(resolving item path in lexical scope) \
4236 resolved `{}` to item",
4237 token::get_name(name));
4238 // This lookup is "all public" because it only searched
4239 // for one identifier in the current module (couldn't
4240 // have passed through reexports or anything like that.
4241 return Some((def, LastMod(AllPublic)));
4246 panic!("unexpected indeterminate result");
4250 Some((span, msg)) =>
4251 self.resolve_error(span, &format!("failed to resolve. {}",
4256 debug!("(resolving item path by identifier in lexical scope) \
4257 failed to resolve {}", token::get_name(name));
4263 fn with_no_errors<T, F>(&mut self, f: F) -> T where
4264 F: FnOnce(&mut Resolver) -> T,
4266 self.emit_errors = false;
4268 self.emit_errors = true;
4272 fn resolve_error(&self, span: Span, s: &str) {
4273 if self.emit_errors {
4274 self.session.span_err(span, s);
4278 fn find_fallback_in_self_type(&mut self, name: Name) -> FallbackSuggestion {
4279 fn extract_path_and_node_id(t: &Ty, allow: FallbackChecks)
4280 -> Option<(Path, NodeId, FallbackChecks)> {
4282 TyPath(ref path, node_id) => Some((path.clone(), node_id, allow)),
4283 TyPtr(ref mut_ty) => extract_path_and_node_id(&*mut_ty.ty, OnlyTraitAndStatics),
4284 TyRptr(_, ref mut_ty) => extract_path_and_node_id(&*mut_ty.ty, allow),
4285 // This doesn't handle the remaining `Ty` variants as they are not
4286 // that commonly the self_type, it might be interesting to provide
4287 // support for those in future.
4292 fn get_module(this: &mut Resolver, span: Span, name_path: &[ast::Name])
4293 -> Option<Rc<Module>> {
4294 let root = this.current_module.clone();
4295 let last_name = name_path.last().unwrap();
4297 if name_path.len() == 1 {
4298 match this.primitive_type_table.primitive_types.get(last_name) {
4301 match this.current_module.children.borrow().get(last_name) {
4302 Some(child) => child.get_module_if_available(),
4308 match this.resolve_module_path(root,
4313 Success((module, _)) => Some(module),
4319 let (path, node_id, allowed) = match self.current_self_type {
4320 Some(ref ty) => match extract_path_and_node_id(ty, Everything) {
4322 None => return NoSuggestion,
4324 None => return NoSuggestion,
4327 if allowed == Everything {
4328 // Look for a field with the same name in the current self_type.
4329 match self.def_map.borrow().get(&node_id) {
4330 Some(&DefTy(did, _))
4331 | Some(&DefStruct(did))
4332 | Some(&DefVariant(_, did, _)) => match self.structs.get(&did) {
4335 if fields.iter().any(|&field_name| name == field_name) {
4340 _ => {} // Self type didn't resolve properly
4344 let name_path = path.segments.iter().map(|seg| seg.identifier.name).collect::<Vec<_>>();
4346 // Look for a method in the current self type's impl module.
4347 match get_module(self, path.span, &name_path[]) {
4348 Some(module) => match module.children.borrow().get(&name) {
4350 let p_str = self.path_names_to_string(&path);
4351 match binding.def_for_namespace(ValueNS) {
4352 Some(DefStaticMethod(_, provenance)) => {
4354 FromImpl(_) => return StaticMethod(p_str),
4355 FromTrait(_) => unreachable!()
4358 Some(DefMethod(_, None, _)) if allowed == Everything => return Method,
4359 Some(DefMethod(_, Some(_), _)) => return TraitItem,
4368 // Look for a method in the current trait.
4369 match self.current_trait_ref {
4370 Some((did, ref trait_ref)) => {
4371 let path_str = self.path_names_to_string(&trait_ref.path);
4373 match self.trait_item_map.get(&(name, did)) {
4374 Some(&StaticMethodTraitItemKind) => {
4375 return TraitMethod(path_str)
4377 Some(_) => return TraitItem,
4387 fn find_best_match_for_name(&mut self, name: &str, max_distance: uint)
4389 let this = &mut *self;
4391 let mut maybes: Vec<token::InternedString> = Vec::new();
4392 let mut values: Vec<uint> = Vec::new();
4394 for rib in this.value_ribs.iter().rev() {
4395 for (&k, _) in &rib.bindings {
4396 maybes.push(token::get_name(k));
4397 values.push(uint::MAX);
4401 let mut smallest = 0;
4402 for (i, other) in maybes.iter().enumerate() {
4403 values[i] = lev_distance(name, other.get());
4405 if values[i] <= values[smallest] {
4410 if values.len() > 0 &&
4411 values[smallest] != uint::MAX &&
4412 values[smallest] < name.len() + 2 &&
4413 values[smallest] <= max_distance &&
4414 name != maybes[smallest].get() {
4416 Some(maybes[smallest].get().to_string())
4423 fn resolve_expr(&mut self, expr: &Expr) {
4424 // First, record candidate traits for this expression if it could
4425 // result in the invocation of a method call.
4427 self.record_candidate_traits_for_expr_if_necessary(expr);
4429 // Next, resolve the node.
4431 // The interpretation of paths depends on whether the path has
4432 // multiple elements in it or not.
4434 ExprPath(_) | ExprQPath(_) => {
4435 let mut path_from_qpath;
4436 let path = match expr.node {
4437 ExprPath(ref path) => path,
4438 ExprQPath(ref qpath) => {
4439 self.resolve_type(&*qpath.self_type);
4440 self.resolve_trait_reference(expr.id, &*qpath.trait_ref, TraitQPath);
4441 path_from_qpath = qpath.trait_ref.path.clone();
4442 path_from_qpath.segments.push(qpath.item_path.clone());
4447 // This is a local path in the value namespace. Walk through
4448 // scopes looking for it.
4449 match self.resolve_path(expr.id, path, ValueNS, true) {
4450 // Check if struct variant
4451 Some((DefVariant(_, _, true), _)) => {
4452 let path_name = self.path_names_to_string(path);
4453 self.resolve_error(expr.span,
4454 &format!("`{}` is a struct variant name, but \
4456 uses it like a function name",
4459 self.session.span_help(expr.span,
4460 &format!("Did you mean to write: \
4461 `{} {{ /* fields */ }}`?",
4465 // Write the result into the def map.
4466 debug!("(resolving expr) resolved `{}`",
4467 self.path_names_to_string(path));
4469 self.record_def(expr.id, def);
4472 // Be helpful if the name refers to a struct
4473 // (The pattern matching def_tys where the id is in self.structs
4474 // matches on regular structs while excluding tuple- and enum-like
4475 // structs, which wouldn't result in this error.)
4476 let path_name = self.path_names_to_string(path);
4477 match self.with_no_errors(|this|
4478 this.resolve_path(expr.id, path, TypeNS, false)) {
4479 Some((DefTy(struct_id, _), _))
4480 if self.structs.contains_key(&struct_id) => {
4481 self.resolve_error(expr.span,
4482 &format!("`{}` is a structure name, but \
4484 uses it like a function name",
4487 self.session.span_help(expr.span,
4488 &format!("Did you mean to write: \
4489 `{} {{ /* fields */ }}`?",
4494 let mut method_scope = false;
4495 self.value_ribs.iter().rev().all(|rib| {
4496 let res = match *rib {
4497 Rib { bindings: _, kind: MethodRibKind(_, _) } => true,
4498 Rib { bindings: _, kind: ItemRibKind } => false,
4499 _ => return true, // Keep advancing
4503 false // Stop advancing
4506 if method_scope && token::get_name(self.self_name).get()
4510 "`self` is not available \
4511 in a static method. Maybe a \
4512 `self` argument is missing?");
4514 let last_name = path.segments.last().unwrap().identifier.name;
4515 let mut msg = match self.find_fallback_in_self_type(last_name) {
4517 // limit search to 5 to reduce the number
4518 // of stupid suggestions
4519 self.find_best_match_for_name(&path_name, 5)
4520 .map_or("".to_string(),
4521 |x| format!("`{}`", x))
4524 format!("`self.{}`", path_name),
4527 format!("to call `self.{}`", path_name),
4528 TraitMethod(path_str)
4529 | StaticMethod(path_str) =>
4530 format!("to call `{}::{}`", path_str, path_name)
4534 msg = format!(". Did you mean {}?", msg)
4539 &format!("unresolved name `{}`{}",
4548 visit::walk_expr(self, expr);
4551 ExprClosure(_, ref fn_decl, ref block) => {
4552 self.resolve_function(ClosureRibKind(expr.id),
4553 Some(&**fn_decl), NoTypeParameters,
4557 ExprStruct(ref path, _, _) => {
4558 // Resolve the path to the structure it goes to. We don't
4559 // check to ensure that the path is actually a structure; that
4560 // is checked later during typeck.
4561 match self.resolve_path(expr.id, path, TypeNS, false) {
4562 Some(definition) => self.record_def(expr.id, definition),
4564 debug!("(resolving expression) didn't find struct \
4565 def: {:?}", result);
4566 let msg = format!("`{}` does not name a structure",
4567 self.path_names_to_string(path));
4568 self.resolve_error(path.span, &msg[]);
4572 visit::walk_expr(self, expr);
4575 ExprLoop(_, Some(label)) | ExprWhile(_, _, Some(label)) => {
4576 self.with_label_rib(|this| {
4577 let def_like = DlDef(DefLabel(expr.id));
4580 let rib = this.label_ribs.last_mut().unwrap();
4581 let renamed = mtwt::resolve(label);
4582 rib.bindings.insert(renamed, def_like);
4585 visit::walk_expr(this, expr);
4589 ExprBreak(Some(label)) | ExprAgain(Some(label)) => {
4590 let renamed = mtwt::resolve(label);
4591 match self.search_label(renamed) {
4595 &format!("use of undeclared label `{}`",
4596 token::get_ident(label))[])
4598 Some(DlDef(def @ DefLabel(_))) => {
4599 // Since this def is a label, it is never read.
4600 self.record_def(expr.id, (def, LastMod(AllPublic)))
4603 self.session.span_bug(expr.span,
4604 "label wasn't mapped to a \
4611 visit::walk_expr(self, expr);
4616 fn record_candidate_traits_for_expr_if_necessary(&mut self, expr: &Expr) {
4618 ExprField(_, ident) => {
4619 // FIXME(#6890): Even though you can't treat a method like a
4620 // field, we need to add any trait methods we find that match
4621 // the field name so that we can do some nice error reporting
4622 // later on in typeck.
4623 let traits = self.search_for_traits_containing_method(ident.node.name);
4624 self.trait_map.insert(expr.id, traits);
4626 ExprMethodCall(ident, _, _) => {
4627 debug!("(recording candidate traits for expr) recording \
4630 let traits = self.search_for_traits_containing_method(ident.node.name);
4631 self.trait_map.insert(expr.id, traits);
4639 fn search_for_traits_containing_method(&mut self, name: Name) -> Vec<DefId> {
4640 debug!("(searching for traits containing method) looking for '{}'",
4641 token::get_name(name));
4643 fn add_trait_info(found_traits: &mut Vec<DefId>,
4644 trait_def_id: DefId,
4646 debug!("(adding trait info) found trait {}:{} for method '{}'",
4649 token::get_name(name));
4650 found_traits.push(trait_def_id);
4653 let mut found_traits = Vec::new();
4654 let mut search_module = self.current_module.clone();
4656 // Look for the current trait.
4657 match self.current_trait_ref {
4658 Some((trait_def_id, _)) => {
4659 if self.trait_item_map.contains_key(&(name, trait_def_id)) {
4660 add_trait_info(&mut found_traits, trait_def_id, name);
4663 None => {} // Nothing to do.
4666 // Look for trait children.
4667 build_reduced_graph::populate_module_if_necessary(self, &search_module);
4670 for (_, child_names) in &*search_module.children.borrow() {
4671 let def = match child_names.def_for_namespace(TypeNS) {
4675 let trait_def_id = match def {
4676 DefTrait(trait_def_id) => trait_def_id,
4679 if self.trait_item_map.contains_key(&(name, trait_def_id)) {
4680 add_trait_info(&mut found_traits, trait_def_id, name);
4685 // Look for imports.
4686 for (_, import) in &*search_module.import_resolutions.borrow() {
4687 let target = match import.target_for_namespace(TypeNS) {
4689 Some(target) => target,
4691 let did = match target.bindings.def_for_namespace(TypeNS) {
4692 Some(DefTrait(trait_def_id)) => trait_def_id,
4693 Some(..) | None => continue,
4695 if self.trait_item_map.contains_key(&(name, did)) {
4696 add_trait_info(&mut found_traits, did, name);
4697 let id = import.type_id;
4698 self.used_imports.insert((id, TypeNS));
4699 let trait_name = self.get_trait_name(did);
4700 self.record_import_use(id, trait_name);
4701 if let Some(DefId{krate: kid, ..}) = target.target_module.def_id.get() {
4702 self.used_crates.insert(kid);
4707 match search_module.parent_link.clone() {
4708 NoParentLink | ModuleParentLink(..) => break,
4709 BlockParentLink(parent_module, _) => {
4710 search_module = parent_module.upgrade().unwrap();
4718 fn record_def(&mut self, node_id: NodeId, (def, lp): (Def, LastPrivate)) {
4719 debug!("(recording def) recording {:?} for {}, last private {:?}",
4721 assert!(match lp {LastImport{..} => false, _ => true},
4722 "Import should only be used for `use` directives");
4723 self.last_private.insert(node_id, lp);
4725 match self.def_map.borrow_mut().entry(node_id) {
4726 // Resolve appears to "resolve" the same ID multiple
4727 // times, so here is a sanity check it at least comes to
4728 // the same conclusion! - nmatsakis
4729 Occupied(entry) => if def != *entry.get() {
4731 .bug(&format!("node_id {} resolved first to {:?} and \
4737 Vacant(entry) => { entry.insert(def); },
4741 fn enforce_default_binding_mode(&mut self,
4743 pat_binding_mode: BindingMode,
4745 match pat_binding_mode {
4746 BindByValue(_) => {}
4748 self.resolve_error(pat.span,
4749 &format!("cannot use `ref` binding mode \
4759 // Diagnostics are not particularly efficient, because they're rarely
4763 /// A somewhat inefficient routine to obtain the name of a module.
4764 fn module_to_string(&self, module: &Module) -> String {
4765 let mut names = Vec::new();
4767 fn collect_mod(names: &mut Vec<ast::Name>, module: &Module) {
4768 match module.parent_link {
4770 ModuleParentLink(ref module, name) => {
4772 collect_mod(names, &*module.upgrade().unwrap());
4774 BlockParentLink(ref module, _) => {
4775 // danger, shouldn't be ident?
4776 names.push(special_idents::opaque.name);
4777 collect_mod(names, &*module.upgrade().unwrap());
4781 collect_mod(&mut names, module);
4783 if names.len() == 0 {
4784 return "???".to_string();
4786 self.names_to_string(&names.into_iter().rev()
4787 .collect::<Vec<ast::Name>>()[])
4790 #[allow(dead_code)] // useful for debugging
4791 fn dump_module(&mut self, module_: Rc<Module>) {
4792 debug!("Dump of module `{}`:", self.module_to_string(&*module_));
4794 debug!("Children:");
4795 build_reduced_graph::populate_module_if_necessary(self, &module_);
4796 for (&name, _) in &*module_.children.borrow() {
4797 debug!("* {}", token::get_name(name));
4800 debug!("Import resolutions:");
4801 let import_resolutions = module_.import_resolutions.borrow();
4802 for (&name, import_resolution) in &*import_resolutions {
4804 match import_resolution.target_for_namespace(ValueNS) {
4805 None => { value_repr = "".to_string(); }
4807 value_repr = " value:?".to_string();
4813 match import_resolution.target_for_namespace(TypeNS) {
4814 None => { type_repr = "".to_string(); }
4816 type_repr = " type:?".to_string();
4821 debug!("* {}:{}{}", token::get_name(name), value_repr, type_repr);
4826 pub struct CrateMap {
4827 pub def_map: DefMap,
4828 pub freevars: RefCell<FreevarMap>,
4829 pub export_map: ExportMap,
4830 pub trait_map: TraitMap,
4831 pub external_exports: ExternalExports,
4832 pub last_private_map: LastPrivateMap,
4833 pub glob_map: Option<GlobMap>
4836 #[derive(PartialEq,Copy)]
4837 pub enum MakeGlobMap {
4842 /// Entry point to crate resolution.
4843 pub fn resolve_crate<'a, 'tcx>(session: &'a Session,
4844 ast_map: &'a ast_map::Map<'tcx>,
4847 make_glob_map: MakeGlobMap)
4849 let mut resolver = Resolver::new(session, ast_map, krate.span, make_glob_map);
4851 build_reduced_graph::build_reduced_graph(&mut resolver, krate);
4852 session.abort_if_errors();
4854 resolver.resolve_imports();
4855 session.abort_if_errors();
4857 record_exports::record(&mut resolver);
4858 session.abort_if_errors();
4860 resolver.resolve_crate(krate);
4861 session.abort_if_errors();
4863 check_unused::check_crate(&mut resolver, krate);
4866 def_map: resolver.def_map,
4867 freevars: resolver.freevars,
4868 export_map: resolver.export_map,
4869 trait_map: resolver.trait_map,
4870 external_exports: resolver.external_exports,
4871 last_private_map: resolver.last_private,
4872 glob_map: if resolver.make_glob_map {
4873 Some(resolver.glob_map)