1 // Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
11 #![crate_name = "rustc_resolve"]
13 #![crate_type = "dylib"]
14 #![crate_type = "rlib"]
15 #![doc(html_logo_url = "http://www.rust-lang.org/logos/rust-logo-128x128-blk-v2.png",
16 html_favicon_url = "http://www.rust-lang.org/favicon.ico",
17 html_root_url = "http://doc.rust-lang.org/nightly/")]
19 #![feature(globs, phase, slicing_syntax)]
20 #![feature(rustc_diagnostic_macros)]
21 #![feature(associated_types)]
23 #[phase(plugin, link)] extern crate log;
24 #[phase(plugin, link)] extern crate syntax;
28 use self::PatternBindingMode::*;
29 use self::Namespace::*;
30 use self::NamespaceResult::*;
31 use self::NameDefinition::*;
32 use self::ImportDirectiveSubclass::*;
33 use self::ResolveResult::*;
34 use self::FallbackSuggestion::*;
35 use self::TypeParameters::*;
37 use self::MethodSort::*;
38 use self::UseLexicalScopeFlag::*;
39 use self::ModulePrefixResult::*;
40 use self::NameSearchType::*;
41 use self::BareIdentifierPatternResolution::*;
42 use self::ParentLink::*;
43 use self::ModuleKind::*;
44 use self::TraitReferenceType::*;
45 use self::FallbackChecks::*;
47 use rustc::session::Session;
49 use rustc::metadata::csearch;
50 use rustc::metadata::decoder::{DefLike, DlDef, DlField, DlImpl};
51 use rustc::middle::def::*;
52 use rustc::middle::lang_items::LanguageItems;
53 use rustc::middle::pat_util::pat_bindings;
54 use rustc::middle::privacy::*;
55 use rustc::middle::subst::{ParamSpace, FnSpace, TypeSpace};
56 use rustc::middle::ty::{CaptureModeMap, Freevar, FreevarMap, TraitMap, GlobMap};
57 use rustc::util::nodemap::{NodeMap, NodeSet, DefIdSet, FnvHashMap};
58 use rustc::util::lev_distance::lev_distance;
60 use syntax::ast::{Arm, BindByRef, BindByValue, BindingMode, Block, Crate, CrateNum};
61 use syntax::ast::{DefId, Expr, ExprAgain, ExprBreak, ExprField};
62 use syntax::ast::{ExprClosure, ExprForLoop, ExprLoop, ExprWhile, ExprMethodCall};
63 use syntax::ast::{ExprPath, ExprStruct, FnDecl};
64 use syntax::ast::{ForeignItemFn, ForeignItemStatic, Generics};
65 use syntax::ast::{Ident, ImplItem, Item, ItemConst, ItemEnum, ItemFn};
66 use syntax::ast::{ItemForeignMod, ItemImpl, ItemMac, ItemMod, ItemStatic};
67 use syntax::ast::{ItemStruct, ItemTrait, ItemTy, Local, LOCAL_CRATE};
68 use syntax::ast::{MethodImplItem, Mod, Name, NodeId};
69 use syntax::ast::{Pat, PatEnum, PatIdent, PatLit};
70 use syntax::ast::{PatRange, PatStruct, Path};
71 use syntax::ast::{PolyTraitRef, PrimTy, SelfExplicit};
72 use syntax::ast::{RegionTyParamBound, StructField};
73 use syntax::ast::{TraitRef, TraitTyParamBound};
74 use syntax::ast::{Ty, TyBool, TyChar, TyClosure, TyF32};
75 use syntax::ast::{TyF64, TyFloat, TyI, TyI8, TyI16, TyI32, TyI64, TyInt, TyObjectSum};
76 use syntax::ast::{TyParam, TyParamBound, TyPath, TyPtr, TyPolyTraitRef, TyQPath};
77 use syntax::ast::{TyRptr, TyStr, TyU, TyU8, TyU16, TyU32, TyU64, TyUint};
78 use syntax::ast::{TypeImplItem};
81 use syntax::ast_util::{PostExpansionMethod, local_def, walk_pat};
82 use syntax::attr::AttrMetaMethods;
83 use syntax::ext::mtwt;
84 use syntax::parse::token::{self, special_names, special_idents};
85 use syntax::codemap::{Span, Pos};
86 use syntax::owned_slice::OwnedSlice;
87 use syntax::visit::{self, Visitor};
89 use std::collections::{HashMap, HashSet};
90 use std::collections::hash_map::Entry::{Occupied, Vacant};
91 use std::cell::{Cell, RefCell};
93 use std::mem::replace;
94 use std::rc::{Rc, Weak};
99 mod build_reduced_graph;
104 binding_mode: BindingMode,
107 // Map from the name in a pattern to its binding mode.
108 type BindingMap = HashMap<Name, BindingInfo>;
110 #[derive(Copy, PartialEq)]
111 enum PatternBindingMode {
113 LocalIrrefutableMode,
114 ArgumentIrrefutableMode,
117 #[derive(Copy, PartialEq, Eq, Hash, Show)]
123 /// A NamespaceResult represents the result of resolving an import in
124 /// a particular namespace. The result is either definitely-resolved,
125 /// definitely- unresolved, or unknown.
127 enum NamespaceResult {
128 /// Means that resolve hasn't gathered enough information yet to determine
129 /// whether the name is bound in this namespace. (That is, it hasn't
130 /// resolved all `use` directives yet.)
132 /// Means that resolve has determined that the name is definitely
133 /// not bound in the namespace.
135 /// Means that resolve has determined that the name is bound in the Module
136 /// argument, and specified by the NameBindings argument.
137 BoundResult(Rc<Module>, Rc<NameBindings>)
140 impl NamespaceResult {
141 fn is_unknown(&self) -> bool {
143 UnknownResult => true,
147 fn is_unbound(&self) -> bool {
149 UnboundResult => true,
155 enum NameDefinition {
156 NoNameDefinition, //< The name was unbound.
157 ChildNameDefinition(Def, LastPrivate), //< The name identifies an immediate child.
158 ImportNameDefinition(Def, LastPrivate) //< The name identifies an import.
161 impl<'a, 'v, 'tcx> Visitor<'v> for Resolver<'a, 'tcx> {
162 fn visit_item(&mut self, item: &Item) {
163 self.resolve_item(item);
165 fn visit_arm(&mut self, arm: &Arm) {
166 self.resolve_arm(arm);
168 fn visit_block(&mut self, block: &Block) {
169 self.resolve_block(block);
171 fn visit_expr(&mut self, expr: &Expr) {
172 self.resolve_expr(expr);
174 fn visit_local(&mut self, local: &Local) {
175 self.resolve_local(local);
177 fn visit_ty(&mut self, ty: &Ty) {
178 self.resolve_type(ty);
182 /// Contains data for specific types of import directives.
184 enum ImportDirectiveSubclass {
185 SingleImport(Name /* target */, Name /* source */),
189 type ErrorMessage = Option<(Span, String)>;
191 enum ResolveResult<T> {
192 Failed(ErrorMessage), // Failed to resolve the name, optional helpful error message.
193 Indeterminate, // Couldn't determine due to unresolved globs.
194 Success(T) // Successfully resolved the import.
197 impl<T> ResolveResult<T> {
198 fn indeterminate(&self) -> bool {
199 match *self { Indeterminate => true, _ => false }
203 enum FallbackSuggestion {
208 StaticMethod(String),
213 enum TypeParameters<'a> {
219 // Identifies the things that these parameters
220 // were declared on (type, fn, etc)
223 // ID of the enclosing item.
226 // The kind of the rib used for type parameters.
230 // The rib kind controls the translation of local
231 // definitions (`DefLocal`) to upvars (`DefUpvar`).
232 #[derive(Copy, Show)]
234 // No translation needs to be applied.
237 // We passed through a closure scope at the given node ID.
238 // Translate upvars as appropriate.
239 ClosureRibKind(NodeId /* func id */, NodeId /* body id if proc or unboxed */),
241 // We passed through an impl or trait and are now in one of its
242 // methods. Allow references to ty params that impl or trait
243 // binds. Disallow any other upvars (including other ty params that are
245 // parent; method itself
246 MethodRibKind(NodeId, MethodSort),
248 // We passed through an item scope. Disallow upvars.
251 // We're in a constant item. Can't refer to dynamic stuff.
255 // Methods can be required or provided. RequiredMethod methods only occur in traits.
256 #[derive(Copy, Show)]
259 ProvidedMethod(NodeId)
263 enum UseLexicalScopeFlag {
268 enum ModulePrefixResult {
270 PrefixFound(Rc<Module>, uint)
273 #[derive(Copy, PartialEq)]
274 enum NameSearchType {
275 /// We're doing a name search in order to resolve a `use` directive.
278 /// We're doing a name search in order to resolve a path type, a path
279 /// expression, or a path pattern.
284 enum BareIdentifierPatternResolution {
285 FoundStructOrEnumVariant(Def, LastPrivate),
286 FoundConst(Def, LastPrivate),
287 BareIdentifierPatternUnresolved
293 bindings: HashMap<Name, DefLike>,
298 fn new(kind: RibKind) -> Rib {
300 bindings: HashMap::new(),
306 /// Whether an import can be shadowed by another import.
307 #[derive(Show,PartialEq,Clone,Copy)]
313 /// One import directive.
315 struct ImportDirective {
316 module_path: Vec<Name>,
317 subclass: ImportDirectiveSubclass,
320 is_public: bool, // see note in ImportResolution about how to use this
321 shadowable: Shadowable,
324 impl ImportDirective {
325 fn new(module_path: Vec<Name> ,
326 subclass: ImportDirectiveSubclass,
330 shadowable: Shadowable)
333 module_path: module_path,
337 is_public: is_public,
338 shadowable: shadowable,
343 /// The item that an import resolves to.
344 #[derive(Clone,Show)]
346 target_module: Rc<Module>,
347 bindings: Rc<NameBindings>,
348 shadowable: Shadowable,
352 fn new(target_module: Rc<Module>,
353 bindings: Rc<NameBindings>,
354 shadowable: Shadowable)
357 target_module: target_module,
359 shadowable: shadowable,
364 /// An ImportResolution represents a particular `use` directive.
366 struct ImportResolution {
367 /// Whether this resolution came from a `use` or a `pub use`. Note that this
368 /// should *not* be used whenever resolution is being performed, this is
369 /// only looked at for glob imports statements currently. Privacy testing
370 /// occurs during a later phase of compilation.
373 // The number of outstanding references to this name. When this reaches
374 // zero, outside modules can count on the targets being correct. Before
375 // then, all bets are off; future imports could override this name.
376 outstanding_references: uint,
378 /// The value that this `use` directive names, if there is one.
379 value_target: Option<Target>,
380 /// The source node of the `use` directive leading to the value target
384 /// The type that this `use` directive names, if there is one.
385 type_target: Option<Target>,
386 /// The source node of the `use` directive leading to the type target
391 impl ImportResolution {
392 fn new(id: NodeId, is_public: bool) -> ImportResolution {
396 outstanding_references: 0,
399 is_public: is_public,
403 fn target_for_namespace(&self, namespace: Namespace)
406 TypeNS => self.type_target.clone(),
407 ValueNS => self.value_target.clone(),
411 fn id(&self, namespace: Namespace) -> NodeId {
413 TypeNS => self.type_id,
414 ValueNS => self.value_id,
418 fn shadowable(&self, namespace: Namespace) -> Shadowable {
419 let target = self.target_for_namespace(namespace);
420 if target.is_none() {
421 return Shadowable::Always;
424 target.unwrap().shadowable
427 fn set_target_and_id(&mut self,
428 namespace: Namespace,
429 target: Option<Target>,
433 self.type_target = target;
437 self.value_target = target;
444 /// The link from a module up to its nearest parent node.
445 #[derive(Clone,Show)]
448 ModuleParentLink(Weak<Module>, Name),
449 BlockParentLink(Weak<Module>, NodeId)
452 /// The type of module this is.
453 #[derive(Copy, PartialEq, Show)]
462 /// One node in the tree of modules.
464 parent_link: ParentLink,
465 def_id: Cell<Option<DefId>>,
466 kind: Cell<ModuleKind>,
469 children: RefCell<HashMap<Name, Rc<NameBindings>>>,
470 imports: RefCell<Vec<ImportDirective>>,
472 // The external module children of this node that were declared with
474 external_module_children: RefCell<HashMap<Name, Rc<Module>>>,
476 // The anonymous children of this node. Anonymous children are pseudo-
477 // modules that are implicitly created around items contained within
480 // For example, if we have this:
488 // There will be an anonymous module created around `g` with the ID of the
489 // entry block for `f`.
490 anonymous_children: RefCell<NodeMap<Rc<Module>>>,
492 // The status of resolving each import in this module.
493 import_resolutions: RefCell<HashMap<Name, ImportResolution>>,
495 // The number of unresolved globs that this module exports.
496 glob_count: Cell<uint>,
498 // The index of the import we're resolving.
499 resolved_import_count: Cell<uint>,
501 // Whether this module is populated. If not populated, any attempt to
502 // access the children must be preceded with a
503 // `populate_module_if_necessary` call.
504 populated: Cell<bool>,
508 fn new(parent_link: ParentLink,
509 def_id: Option<DefId>,
515 parent_link: parent_link,
516 def_id: Cell::new(def_id),
517 kind: Cell::new(kind),
518 is_public: is_public,
519 children: RefCell::new(HashMap::new()),
520 imports: RefCell::new(Vec::new()),
521 external_module_children: RefCell::new(HashMap::new()),
522 anonymous_children: RefCell::new(NodeMap::new()),
523 import_resolutions: RefCell::new(HashMap::new()),
524 glob_count: Cell::new(0),
525 resolved_import_count: Cell::new(0),
526 populated: Cell::new(!external),
530 fn all_imports_resolved(&self) -> bool {
531 self.imports.borrow().len() == self.resolved_import_count.get()
535 impl fmt::Show for Module {
536 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
537 write!(f, "{}, kind: {}, {}",
540 if self.is_public { "public" } else { "private" } )
546 flags DefModifiers: u8 {
547 const PUBLIC = 0b0000_0001,
548 const IMPORTABLE = 0b0000_0010,
552 // Records a possibly-private type definition.
553 #[derive(Clone,Show)]
555 modifiers: DefModifiers, // see note in ImportResolution about how to use this
556 module_def: Option<Rc<Module>>,
557 type_def: Option<Def>,
558 type_span: Option<Span>
561 // Records a possibly-private value definition.
562 #[derive(Clone, Copy, Show)]
564 modifiers: DefModifiers, // see note in ImportResolution about how to use this
566 value_span: Option<Span>,
569 // Records the definitions (at most one for each namespace) that a name is
572 struct NameBindings {
573 type_def: RefCell<Option<TypeNsDef>>, //< Meaning in type namespace.
574 value_def: RefCell<Option<ValueNsDef>>, //< Meaning in value namespace.
577 /// Ways in which a trait can be referenced
579 enum TraitReferenceType {
580 TraitImplementation, // impl SomeTrait for T { ... }
581 TraitDerivation, // trait T : SomeTrait { ... }
582 TraitBoundingTypeParameter, // fn f<T:SomeTrait>() { ... }
583 TraitObject, // Box<for<'a> SomeTrait>
584 TraitQPath, // <T as SomeTrait>::
588 fn new() -> NameBindings {
590 type_def: RefCell::new(None),
591 value_def: RefCell::new(None),
595 /// Creates a new module in this set of name bindings.
596 fn define_module(&self,
597 parent_link: ParentLink,
598 def_id: Option<DefId>,
603 // Merges the module with the existing type def or creates a new one.
604 let modifiers = if is_public { PUBLIC } else { DefModifiers::empty() } | IMPORTABLE;
605 let module_ = Rc::new(Module::new(parent_link,
610 let type_def = self.type_def.borrow().clone();
613 *self.type_def.borrow_mut() = Some(TypeNsDef {
614 modifiers: modifiers,
615 module_def: Some(module_),
621 *self.type_def.borrow_mut() = Some(TypeNsDef {
622 modifiers: modifiers,
623 module_def: Some(module_),
625 type_def: type_def.type_def
631 /// Sets the kind of the module, creating a new one if necessary.
632 fn set_module_kind(&self,
633 parent_link: ParentLink,
634 def_id: Option<DefId>,
639 let modifiers = if is_public { PUBLIC } else { DefModifiers::empty() } | IMPORTABLE;
640 let type_def = self.type_def.borrow().clone();
643 let module = Module::new(parent_link,
648 *self.type_def.borrow_mut() = Some(TypeNsDef {
649 modifiers: modifiers,
650 module_def: Some(Rc::new(module)),
656 match type_def.module_def {
658 let module = Module::new(parent_link,
663 *self.type_def.borrow_mut() = Some(TypeNsDef {
664 modifiers: modifiers,
665 module_def: Some(Rc::new(module)),
666 type_def: type_def.type_def,
670 Some(module_def) => module_def.kind.set(kind),
676 /// Records a type definition.
677 fn define_type(&self, def: Def, sp: Span, modifiers: DefModifiers) {
678 debug!("defining type for def {} with modifiers {}", def, modifiers);
679 // Merges the type with the existing type def or creates a new one.
680 let type_def = self.type_def.borrow().clone();
683 *self.type_def.borrow_mut() = Some(TypeNsDef {
687 modifiers: modifiers,
691 *self.type_def.borrow_mut() = Some(TypeNsDef {
692 module_def: type_def.module_def,
695 modifiers: modifiers,
701 /// Records a value definition.
702 fn define_value(&self, def: Def, sp: Span, modifiers: DefModifiers) {
703 debug!("defining value for def {} with modifiers {}", def, modifiers);
704 *self.value_def.borrow_mut() = Some(ValueNsDef {
706 value_span: Some(sp),
707 modifiers: modifiers,
711 /// Returns the module node if applicable.
712 fn get_module_if_available(&self) -> Option<Rc<Module>> {
713 match *self.type_def.borrow() {
714 Some(ref type_def) => type_def.module_def.clone(),
719 /// Returns the module node. Panics if this node does not have a module
721 fn get_module(&self) -> Rc<Module> {
722 match self.get_module_if_available() {
724 panic!("get_module called on a node with no module \
727 Some(module_def) => module_def
731 fn defined_in_namespace(&self, namespace: Namespace) -> bool {
733 TypeNS => return self.type_def.borrow().is_some(),
734 ValueNS => return self.value_def.borrow().is_some()
738 fn defined_in_public_namespace(&self, namespace: Namespace) -> bool {
739 self.defined_in_namespace_with(namespace, PUBLIC)
742 fn defined_in_namespace_with(&self, namespace: Namespace, modifiers: DefModifiers) -> bool {
744 TypeNS => match *self.type_def.borrow() {
745 Some(ref def) => def.modifiers.contains(modifiers), None => false
747 ValueNS => match *self.value_def.borrow() {
748 Some(ref def) => def.modifiers.contains(modifiers), None => false
753 fn def_for_namespace(&self, namespace: Namespace) -> Option<Def> {
756 match *self.type_def.borrow() {
758 Some(ref type_def) => {
759 match type_def.type_def {
760 Some(type_def) => Some(type_def),
762 match type_def.module_def {
763 Some(ref module) => {
764 match module.def_id.get() {
765 Some(did) => Some(DefMod(did)),
777 match *self.value_def.borrow() {
779 Some(value_def) => Some(value_def.def)
785 fn span_for_namespace(&self, namespace: Namespace) -> Option<Span> {
786 if self.defined_in_namespace(namespace) {
789 match *self.type_def.borrow() {
791 Some(ref type_def) => type_def.type_span
795 match *self.value_def.borrow() {
797 Some(ref value_def) => value_def.value_span
807 /// Interns the names of the primitive types.
808 struct PrimitiveTypeTable {
809 primitive_types: HashMap<Name, PrimTy>,
812 impl PrimitiveTypeTable {
813 fn new() -> PrimitiveTypeTable {
814 let mut table = PrimitiveTypeTable {
815 primitive_types: HashMap::new()
818 table.intern("bool", TyBool);
819 table.intern("char", TyChar);
820 table.intern("f32", TyFloat(TyF32));
821 table.intern("f64", TyFloat(TyF64));
822 table.intern("int", TyInt(TyI));
823 table.intern("i8", TyInt(TyI8));
824 table.intern("i16", TyInt(TyI16));
825 table.intern("i32", TyInt(TyI32));
826 table.intern("i64", TyInt(TyI64));
827 table.intern("str", TyStr);
828 table.intern("uint", TyUint(TyU));
829 table.intern("u8", TyUint(TyU8));
830 table.intern("u16", TyUint(TyU16));
831 table.intern("u32", TyUint(TyU32));
832 table.intern("u64", TyUint(TyU64));
837 fn intern(&mut self, string: &str, primitive_type: PrimTy) {
838 self.primitive_types.insert(token::intern(string), primitive_type);
842 /// The main resolver class.
843 struct Resolver<'a, 'tcx:'a> {
844 session: &'a Session,
846 ast_map: &'a ast_map::Map<'tcx>,
848 graph_root: NameBindings,
850 trait_item_map: FnvHashMap<(Name, DefId), TraitItemKind>,
852 structs: FnvHashMap<DefId, Vec<Name>>,
854 // The number of imports that are currently unresolved.
855 unresolved_imports: uint,
857 // The module that represents the current item scope.
858 current_module: Rc<Module>,
860 // The current set of local scopes, for values.
861 // FIXME #4948: Reuse ribs to avoid allocation.
862 value_ribs: Vec<Rib>,
864 // The current set of local scopes, for types.
867 // The current set of local scopes, for labels.
868 label_ribs: Vec<Rib>,
870 // The trait that the current context can refer to.
871 current_trait_ref: Option<(DefId, TraitRef)>,
873 // The current self type if inside an impl (used for better errors).
874 current_self_type: Option<Ty>,
876 // The ident for the keyword "self".
878 // The ident for the non-keyword "Self".
879 type_self_name: Name,
881 // The idents for the primitive types.
882 primitive_type_table: PrimitiveTypeTable,
885 freevars: RefCell<FreevarMap>,
886 freevars_seen: RefCell<NodeMap<NodeSet>>,
887 capture_mode_map: CaptureModeMap,
888 export_map: ExportMap,
890 external_exports: ExternalExports,
891 last_private: LastPrivateMap,
893 // Whether or not to print error messages. Can be set to true
894 // when getting additional info for error message suggestions,
895 // so as to avoid printing duplicate errors
899 // Maps imports to the names of items actually imported (this actually maps
900 // all imports, but only glob imports are actually interesting).
903 used_imports: HashSet<(NodeId, Namespace)>,
904 used_crates: HashSet<CrateNum>,
908 enum FallbackChecks {
914 impl<'a, 'tcx> Resolver<'a, 'tcx> {
915 fn new(session: &'a Session,
916 ast_map: &'a ast_map::Map<'tcx>,
918 make_glob_map: MakeGlobMap) -> Resolver<'a, 'tcx> {
919 let graph_root = NameBindings::new();
921 graph_root.define_module(NoParentLink,
922 Some(DefId { krate: 0, node: 0 }),
928 let current_module = graph_root.get_module();
935 // The outermost module has def ID 0; this is not reflected in the
938 graph_root: graph_root,
940 trait_item_map: FnvHashMap::new(),
941 structs: FnvHashMap::new(),
943 unresolved_imports: 0,
945 current_module: current_module,
946 value_ribs: Vec::new(),
947 type_ribs: Vec::new(),
948 label_ribs: Vec::new(),
950 current_trait_ref: None,
951 current_self_type: None,
953 self_name: special_names::self_,
954 type_self_name: special_names::type_self,
956 primitive_type_table: PrimitiveTypeTable::new(),
958 def_map: RefCell::new(NodeMap::new()),
959 freevars: RefCell::new(NodeMap::new()),
960 freevars_seen: RefCell::new(NodeMap::new()),
961 capture_mode_map: NodeMap::new(),
962 export_map: NodeMap::new(),
963 trait_map: NodeMap::new(),
964 used_imports: HashSet::new(),
965 used_crates: HashSet::new(),
966 external_exports: DefIdSet::new(),
967 last_private: NodeMap::new(),
970 make_glob_map: make_glob_map == MakeGlobMap::Yes,
971 glob_map: HashMap::new(),
978 // This is a fixed-point algorithm. We resolve imports until our efforts
979 // are stymied by an unresolved import; then we bail out of the current
980 // module and continue. We terminate successfully once no more imports
981 // remain or unsuccessfully when no forward progress in resolving imports
984 /// Resolves all imports for the crate. This method performs the fixed-
986 fn resolve_imports(&mut self) {
988 let mut prev_unresolved_imports = 0;
990 debug!("(resolving imports) iteration {}, {} imports left",
991 i, self.unresolved_imports);
993 let module_root = self.graph_root.get_module();
994 self.resolve_imports_for_module_subtree(module_root.clone());
996 if self.unresolved_imports == 0 {
997 debug!("(resolving imports) success");
1001 if self.unresolved_imports == prev_unresolved_imports {
1002 self.report_unresolved_imports(module_root);
1007 prev_unresolved_imports = self.unresolved_imports;
1011 /// Attempts to resolve imports for the given module and all of its
1013 fn resolve_imports_for_module_subtree(&mut self, module_: Rc<Module>) {
1014 debug!("(resolving imports for module subtree) resolving {}",
1015 self.module_to_string(&*module_));
1016 let orig_module = replace(&mut self.current_module, module_.clone());
1017 self.resolve_imports_for_module(module_.clone());
1018 self.current_module = orig_module;
1020 build_reduced_graph::populate_module_if_necessary(self, &module_);
1021 for (_, child_node) in module_.children.borrow().iter() {
1022 match child_node.get_module_if_available() {
1026 Some(child_module) => {
1027 self.resolve_imports_for_module_subtree(child_module);
1032 for (_, child_module) in module_.anonymous_children.borrow().iter() {
1033 self.resolve_imports_for_module_subtree(child_module.clone());
1037 /// Attempts to resolve imports for the given module only.
1038 fn resolve_imports_for_module(&mut self, module: Rc<Module>) {
1039 if module.all_imports_resolved() {
1040 debug!("(resolving imports for module) all imports resolved for \
1042 self.module_to_string(&*module));
1046 let imports = module.imports.borrow();
1047 let import_count = imports.len();
1048 while module.resolved_import_count.get() < import_count {
1049 let import_index = module.resolved_import_count.get();
1050 let import_directive = &(*imports)[import_index];
1051 match self.resolve_import_for_module(module.clone(),
1054 let (span, help) = match err {
1055 Some((span, msg)) => (span, format!(". {}", msg)),
1056 None => (import_directive.span, String::new())
1058 let msg = format!("unresolved import `{}`{}",
1059 self.import_path_to_string(
1060 import_directive.module_path
1062 import_directive.subclass),
1064 self.resolve_error(span, msg[]);
1066 Indeterminate => break, // Bail out. We'll come around next time.
1067 Success(()) => () // Good. Continue.
1070 module.resolved_import_count
1071 .set(module.resolved_import_count.get() + 1);
1075 fn names_to_string(&self, names: &[Name]) -> String {
1076 let mut first = true;
1077 let mut result = String::new();
1078 for name in names.iter() {
1082 result.push_str("::")
1084 result.push_str(token::get_name(*name).get());
1089 fn path_names_to_string(&self, path: &Path) -> String {
1090 let names: Vec<ast::Name> = path.segments
1092 .map(|seg| seg.identifier.name)
1094 self.names_to_string(names[])
1097 fn import_directive_subclass_to_string(&mut self,
1098 subclass: ImportDirectiveSubclass)
1101 SingleImport(_, source) => {
1102 token::get_name(source).get().to_string()
1104 GlobImport => "*".to_string()
1108 fn import_path_to_string(&mut self,
1110 subclass: ImportDirectiveSubclass)
1112 if names.is_empty() {
1113 self.import_directive_subclass_to_string(subclass)
1116 self.names_to_string(names),
1117 self.import_directive_subclass_to_string(
1118 subclass))).to_string()
1123 fn record_import_use(&mut self, import_id: NodeId, name: Name) {
1124 if !self.make_glob_map {
1127 if self.glob_map.contains_key(&import_id) {
1128 self.glob_map[import_id].insert(name);
1132 let mut new_set = HashSet::new();
1133 new_set.insert(name);
1134 self.glob_map.insert(import_id, new_set);
1137 fn get_trait_name(&self, did: DefId) -> Name {
1138 if did.krate == LOCAL_CRATE {
1139 self.ast_map.expect_item(did.node).ident.name
1141 csearch::get_trait_name(&self.session.cstore, did)
1145 /// Attempts to resolve the given import. The return value indicates
1146 /// failure if we're certain the name does not exist, indeterminate if we
1147 /// don't know whether the name exists at the moment due to other
1148 /// currently-unresolved imports, or success if we know the name exists.
1149 /// If successful, the resolved bindings are written into the module.
1150 fn resolve_import_for_module(&mut self,
1151 module_: Rc<Module>,
1152 import_directive: &ImportDirective)
1153 -> ResolveResult<()> {
1154 let mut resolution_result = Failed(None);
1155 let module_path = &import_directive.module_path;
1157 debug!("(resolving import for module) resolving import `{}::...` in `{}`",
1158 self.names_to_string(module_path[]),
1159 self.module_to_string(&*module_));
1161 // First, resolve the module path for the directive, if necessary.
1162 let container = if module_path.len() == 0 {
1163 // Use the crate root.
1164 Some((self.graph_root.get_module(), LastMod(AllPublic)))
1166 match self.resolve_module_path(module_.clone(),
1168 DontUseLexicalScope,
1169 import_directive.span,
1172 resolution_result = Failed(err);
1176 resolution_result = Indeterminate;
1179 Success(container) => Some(container),
1185 Some((containing_module, lp)) => {
1186 // We found the module that the target is contained
1187 // within. Attempt to resolve the import within it.
1189 match import_directive.subclass {
1190 SingleImport(target, source) => {
1192 self.resolve_single_import(&*module_,
1201 self.resolve_glob_import(&*module_,
1210 // Decrement the count of unresolved imports.
1211 match resolution_result {
1213 assert!(self.unresolved_imports >= 1);
1214 self.unresolved_imports -= 1;
1217 // Nothing to do here; just return the error.
1221 // Decrement the count of unresolved globs if necessary. But only if
1222 // the resolution result is indeterminate -- otherwise we'll stop
1223 // processing imports here. (See the loop in
1224 // resolve_imports_for_module.)
1226 if !resolution_result.indeterminate() {
1227 match import_directive.subclass {
1229 assert!(module_.glob_count.get() >= 1);
1230 module_.glob_count.set(module_.glob_count.get() - 1);
1232 SingleImport(..) => {
1238 return resolution_result;
1241 fn create_name_bindings_from_module(module: Rc<Module>) -> NameBindings {
1243 type_def: RefCell::new(Some(TypeNsDef {
1244 modifiers: IMPORTABLE,
1245 module_def: Some(module),
1249 value_def: RefCell::new(None),
1253 fn resolve_single_import(&mut self,
1255 containing_module: Rc<Module>,
1258 directive: &ImportDirective,
1260 -> ResolveResult<()> {
1261 debug!("(resolving single import) resolving `{}` = `{}::{}` from \
1262 `{}` id {}, last private {}",
1263 token::get_name(target),
1264 self.module_to_string(&*containing_module),
1265 token::get_name(source),
1266 self.module_to_string(module_),
1272 LastImport {..} => {
1274 .span_bug(directive.span,
1275 "not expecting Import here, must be LastMod")
1279 // We need to resolve both namespaces for this to succeed.
1282 let mut value_result = UnknownResult;
1283 let mut type_result = UnknownResult;
1285 // Search for direct children of the containing module.
1286 build_reduced_graph::populate_module_if_necessary(self, &containing_module);
1288 match containing_module.children.borrow().get(&source) {
1292 Some(ref child_name_bindings) => {
1293 if child_name_bindings.defined_in_namespace(ValueNS) {
1294 debug!("(resolving single import) found value binding");
1295 value_result = BoundResult(containing_module.clone(),
1296 (*child_name_bindings).clone());
1298 if child_name_bindings.defined_in_namespace(TypeNS) {
1299 debug!("(resolving single import) found type binding");
1300 type_result = BoundResult(containing_module.clone(),
1301 (*child_name_bindings).clone());
1306 // Unless we managed to find a result in both namespaces (unlikely),
1307 // search imports as well.
1308 let mut value_used_reexport = false;
1309 let mut type_used_reexport = false;
1310 match (value_result.clone(), type_result.clone()) {
1311 (BoundResult(..), BoundResult(..)) => {} // Continue.
1313 // If there is an unresolved glob at this point in the
1314 // containing module, bail out. We don't know enough to be
1315 // able to resolve this import.
1317 if containing_module.glob_count.get() > 0 {
1318 debug!("(resolving single import) unresolved glob; \
1320 return Indeterminate;
1323 // Now search the exported imports within the containing module.
1324 match containing_module.import_resolutions.borrow().get(&source) {
1326 debug!("(resolving single import) no import");
1327 // The containing module definitely doesn't have an
1328 // exported import with the name in question. We can
1329 // therefore accurately report that the names are
1332 if value_result.is_unknown() {
1333 value_result = UnboundResult;
1335 if type_result.is_unknown() {
1336 type_result = UnboundResult;
1339 Some(import_resolution)
1340 if import_resolution.outstanding_references == 0 => {
1342 fn get_binding(this: &mut Resolver,
1343 import_resolution: &ImportResolution,
1344 namespace: Namespace,
1346 -> NamespaceResult {
1348 // Import resolutions must be declared with "pub"
1349 // in order to be exported.
1350 if !import_resolution.is_public {
1351 return UnboundResult;
1354 match import_resolution.
1355 target_for_namespace(namespace) {
1357 return UnboundResult;
1364 debug!("(resolving single import) found \
1365 import in ns {}", namespace);
1366 let id = import_resolution.id(namespace);
1367 // track used imports and extern crates as well
1368 this.used_imports.insert((id, namespace));
1369 this.record_import_use(id, *source);
1370 match target_module.def_id.get() {
1371 Some(DefId{krate: kid, ..}) => {
1372 this.used_crates.insert(kid);
1376 return BoundResult(target_module, bindings);
1381 // The name is an import which has been fully
1382 // resolved. We can, therefore, just follow it.
1383 if value_result.is_unknown() {
1384 value_result = get_binding(self,
1388 value_used_reexport = import_resolution.is_public;
1390 if type_result.is_unknown() {
1391 type_result = get_binding(self,
1395 type_used_reexport = import_resolution.is_public;
1400 // If containing_module is the same module whose import we are resolving
1401 // and there it has an unresolved import with the same name as `source`,
1402 // then the user is actually trying to import an item that is declared
1403 // in the same scope
1406 // use self::submodule;
1407 // pub mod submodule;
1409 // In this case we continue as if we resolved the import and let the
1410 // check_for_conflicts_between_imports_and_items call below handle
1412 match (module_.def_id.get(), containing_module.def_id.get()) {
1413 (Some(id1), Some(id2)) if id1 == id2 => {
1414 if value_result.is_unknown() {
1415 value_result = UnboundResult;
1417 if type_result.is_unknown() {
1418 type_result = UnboundResult;
1422 // The import is unresolved. Bail out.
1423 debug!("(resolving single import) unresolved import; \
1425 return Indeterminate;
1433 // If we didn't find a result in the type namespace, search the
1434 // external modules.
1435 let mut value_used_public = false;
1436 let mut type_used_public = false;
1438 BoundResult(..) => {}
1440 match containing_module.external_module_children.borrow_mut()
1441 .get(&source).cloned() {
1442 None => {} // Continue.
1444 debug!("(resolving single import) found external \
1446 // track the module as used.
1447 match module.def_id.get() {
1448 Some(DefId{krate: kid, ..}) => { self.used_crates.insert(kid); },
1452 Rc::new(Resolver::create_name_bindings_from_module(
1454 type_result = BoundResult(containing_module.clone(),
1456 type_used_public = true;
1462 // We've successfully resolved the import. Write the results in.
1463 let mut import_resolutions = module_.import_resolutions.borrow_mut();
1464 let import_resolution = &mut (*import_resolutions)[target];
1466 let mut check_and_write_import = |&mut: namespace, result: &_, used_public: &mut bool| {
1467 let namespace_name = match namespace {
1473 BoundResult(ref target_module, ref name_bindings) => {
1474 debug!("(resolving single import) found {} target: {}",
1476 name_bindings.def_for_namespace(namespace));
1477 self.check_for_conflicting_import(
1478 &import_resolution.target_for_namespace(namespace),
1483 self.check_that_import_is_importable(
1489 let target = Some(Target::new(target_module.clone(),
1490 name_bindings.clone(),
1491 directive.shadowable));
1492 import_resolution.set_target_and_id(namespace, target, directive.id);
1493 import_resolution.is_public = directive.is_public;
1494 *used_public = name_bindings.defined_in_public_namespace(namespace);
1496 UnboundResult => { /* Continue. */ }
1498 panic!("{} result should be known at this point", namespace_name);
1502 check_and_write_import(ValueNS, &value_result, &mut value_used_public);
1503 check_and_write_import(TypeNS, &type_result, &mut type_used_public);
1506 self.check_for_conflicts_between_imports_and_items(
1512 if value_result.is_unbound() && type_result.is_unbound() {
1513 let msg = format!("There is no `{}` in `{}`",
1514 token::get_name(source),
1515 self.module_to_string(&*containing_module));
1516 return Failed(Some((directive.span, msg)));
1518 let value_used_public = value_used_reexport || value_used_public;
1519 let type_used_public = type_used_reexport || type_used_public;
1521 assert!(import_resolution.outstanding_references >= 1);
1522 import_resolution.outstanding_references -= 1;
1524 // record what this import resolves to for later uses in documentation,
1525 // this may resolve to either a value or a type, but for documentation
1526 // purposes it's good enough to just favor one over the other.
1527 let value_private = match import_resolution.value_target {
1528 Some(ref target) => {
1529 let def = target.bindings.def_for_namespace(ValueNS).unwrap();
1530 self.def_map.borrow_mut().insert(directive.id, def);
1531 let did = def.def_id();
1532 if value_used_public {Some(lp)} else {Some(DependsOn(did))}
1534 // AllPublic here and below is a dummy value, it should never be used because
1535 // _exists is false.
1538 let type_private = match import_resolution.type_target {
1539 Some(ref target) => {
1540 let def = target.bindings.def_for_namespace(TypeNS).unwrap();
1541 self.def_map.borrow_mut().insert(directive.id, def);
1542 let did = def.def_id();
1543 if type_used_public {Some(lp)} else {Some(DependsOn(did))}
1548 self.last_private.insert(directive.id, LastImport{value_priv: value_private,
1550 type_priv: type_private,
1553 debug!("(resolving single import) successfully resolved import");
1557 // Resolves a glob import. Note that this function cannot fail; it either
1558 // succeeds or bails out (as importing * from an empty module or a module
1559 // that exports nothing is valid). containing_module is the module we are
1560 // actually importing, i.e., `foo` in `use foo::*`.
1561 fn resolve_glob_import(&mut self,
1563 containing_module: Rc<Module>,
1564 import_directive: &ImportDirective,
1566 -> ResolveResult<()> {
1567 let id = import_directive.id;
1568 let is_public = import_directive.is_public;
1570 // This function works in a highly imperative manner; it eagerly adds
1571 // everything it can to the list of import resolutions of the module
1573 debug!("(resolving glob import) resolving glob import {}", id);
1575 // We must bail out if the node has unresolved imports of any kind
1576 // (including globs).
1577 if !(*containing_module).all_imports_resolved() {
1578 debug!("(resolving glob import) target module has unresolved \
1579 imports; bailing out");
1580 return Indeterminate;
1583 assert_eq!(containing_module.glob_count.get(), 0);
1585 // Add all resolved imports from the containing module.
1586 let import_resolutions = containing_module.import_resolutions.borrow();
1587 for (ident, target_import_resolution) in import_resolutions.iter() {
1588 debug!("(resolving glob import) writing module resolution \
1590 token::get_name(*ident),
1591 self.module_to_string(module_));
1593 if !target_import_resolution.is_public {
1594 debug!("(resolving glob import) nevermind, just kidding");
1598 // Here we merge two import resolutions.
1599 let mut import_resolutions = module_.import_resolutions.borrow_mut();
1600 match import_resolutions.get_mut(ident) {
1601 Some(dest_import_resolution) => {
1602 // Merge the two import resolutions at a finer-grained
1605 match target_import_resolution.value_target {
1609 Some(ref value_target) => {
1610 self.check_for_conflicting_import(&dest_import_resolution.value_target,
1611 import_directive.span,
1614 dest_import_resolution.value_target = Some(value_target.clone());
1617 match target_import_resolution.type_target {
1621 Some(ref type_target) => {
1622 self.check_for_conflicting_import(&dest_import_resolution.type_target,
1623 import_directive.span,
1626 dest_import_resolution.type_target = Some(type_target.clone());
1629 dest_import_resolution.is_public = is_public;
1635 // Simple: just copy the old import resolution.
1636 let mut new_import_resolution = ImportResolution::new(id, is_public);
1637 new_import_resolution.value_target =
1638 target_import_resolution.value_target.clone();
1639 new_import_resolution.type_target =
1640 target_import_resolution.type_target.clone();
1642 import_resolutions.insert(*ident, new_import_resolution);
1645 // Add all children from the containing module.
1646 build_reduced_graph::populate_module_if_necessary(self, &containing_module);
1648 for (&name, name_bindings) in containing_module.children.borrow().iter() {
1649 self.merge_import_resolution(module_,
1650 containing_module.clone(),
1653 name_bindings.clone());
1657 // Add external module children from the containing module.
1658 for (&name, module) in containing_module.external_module_children.borrow().iter() {
1660 Rc::new(Resolver::create_name_bindings_from_module(module.clone()));
1661 self.merge_import_resolution(module_,
1662 containing_module.clone(),
1668 // Record the destination of this import
1669 match containing_module.def_id.get() {
1671 self.def_map.borrow_mut().insert(id, DefMod(did));
1672 self.last_private.insert(id, lp);
1677 debug!("(resolving glob import) successfully resolved import");
1681 fn merge_import_resolution(&mut self,
1683 containing_module: Rc<Module>,
1684 import_directive: &ImportDirective,
1686 name_bindings: Rc<NameBindings>) {
1687 let id = import_directive.id;
1688 let is_public = import_directive.is_public;
1690 let mut import_resolutions = module_.import_resolutions.borrow_mut();
1691 let dest_import_resolution = match import_resolutions.entry(name) {
1692 Occupied(entry) => {
1696 // Create a new import resolution from this child.
1697 entry.set(ImportResolution::new(id, is_public))
1701 debug!("(resolving glob import) writing resolution `{}` in `{}` \
1703 token::get_name(name).get(),
1704 self.module_to_string(&*containing_module),
1705 self.module_to_string(module_));
1707 // Merge the child item into the import resolution.
1709 let mut merge_child_item = |&mut : namespace| {
1710 if name_bindings.defined_in_namespace_with(namespace, IMPORTABLE | PUBLIC) {
1711 let namespace_name = match namespace {
1715 debug!("(resolving glob import) ... for {} target", namespace_name);
1716 if dest_import_resolution.shadowable(namespace) == Shadowable::Never {
1717 let msg = format!("a {} named `{}` has already been imported \
1720 token::get_name(name).get());
1721 self.session.span_err(import_directive.span, msg.as_slice());
1723 let target = Target::new(containing_module.clone(),
1724 name_bindings.clone(),
1725 import_directive.shadowable);
1726 dest_import_resolution.set_target_and_id(namespace,
1732 merge_child_item(ValueNS);
1733 merge_child_item(TypeNS);
1736 dest_import_resolution.is_public = is_public;
1738 self.check_for_conflicts_between_imports_and_items(
1740 dest_import_resolution,
1741 import_directive.span,
1745 /// Checks that imported names and items don't have the same name.
1746 fn check_for_conflicting_import(&mut self,
1747 target: &Option<Target>,
1750 namespace: Namespace) {
1751 if self.session.features.borrow().import_shadowing {
1755 debug!("check_for_conflicting_import: {}; target exists: {}",
1756 token::get_name(name).get(),
1760 Some(ref target) if target.shadowable != Shadowable::Always => {
1761 let msg = format!("a {} named `{}` has already been imported \
1767 token::get_name(name).get());
1768 self.session.span_err(import_span, msg[]);
1770 Some(_) | None => {}
1774 /// Checks that an import is actually importable
1775 fn check_that_import_is_importable(&mut self,
1776 name_bindings: &NameBindings,
1779 namespace: Namespace) {
1780 if !name_bindings.defined_in_namespace_with(namespace, IMPORTABLE) {
1781 let msg = format!("`{}` is not directly importable",
1782 token::get_name(name));
1783 self.session.span_err(import_span, msg[]);
1787 /// Checks that imported names and items don't have the same name.
1788 fn check_for_conflicts_between_imports_and_items(&mut self,
1794 if self.session.features.borrow().import_shadowing {
1798 // First, check for conflicts between imports and `extern crate`s.
1799 if module.external_module_children
1801 .contains_key(&name) {
1802 match import_resolution.type_target {
1803 Some(ref target) if target.shadowable != Shadowable::Always => {
1804 let msg = format!("import `{0}` conflicts with imported \
1805 crate in this module \
1806 (maybe you meant `use {0}::*`?)",
1807 token::get_name(name).get());
1808 self.session.span_err(import_span, msg[]);
1810 Some(_) | None => {}
1814 // Check for item conflicts.
1815 let children = module.children.borrow();
1816 let name_bindings = match children.get(&name) {
1818 // There can't be any conflicts.
1821 Some(ref name_bindings) => (*name_bindings).clone(),
1824 match import_resolution.value_target {
1825 Some(ref target) if target.shadowable != Shadowable::Always => {
1826 if let Some(ref value) = *name_bindings.value_def.borrow() {
1827 let msg = format!("import `{}` conflicts with value \
1829 token::get_name(name).get());
1830 self.session.span_err(import_span, msg[]);
1831 if let Some(span) = value.value_span {
1832 self.session.span_note(span,
1833 "conflicting value here");
1837 Some(_) | None => {}
1840 match import_resolution.type_target {
1841 Some(ref target) if target.shadowable != Shadowable::Always => {
1842 if let Some(ref ty) = *name_bindings.type_def.borrow() {
1843 match ty.module_def {
1845 let msg = format!("import `{}` conflicts with type in \
1847 token::get_name(name).get());
1848 self.session.span_err(import_span, msg[]);
1849 if let Some(span) = ty.type_span {
1850 self.session.span_note(span,
1851 "note conflicting type here")
1854 Some(ref module_def) => {
1855 match module_def.kind.get() {
1857 if let Some(span) = ty.type_span {
1858 let msg = format!("inherent implementations \
1859 are only allowed on types \
1860 defined in the current module");
1861 self.session.span_err(span, msg[]);
1862 self.session.span_note(import_span,
1863 "import from other module here")
1867 let msg = format!("import `{}` conflicts with existing \
1869 token::get_name(name).get());
1870 self.session.span_err(import_span, msg[]);
1871 if let Some(span) = ty.type_span {
1872 self.session.span_note(span,
1873 "note conflicting module here")
1881 Some(_) | None => {}
1885 /// Checks that the names of external crates don't collide with other
1886 /// external crates.
1887 fn check_for_conflicts_between_external_crates(&self,
1891 if self.session.features.borrow().import_shadowing {
1895 if module.external_module_children.borrow().contains_key(&name) {
1898 format!("an external crate named `{}` has already \
1899 been imported into this module",
1900 token::get_name(name).get())[]);
1904 /// Checks that the names of items don't collide with external crates.
1905 fn check_for_conflicts_between_external_crates_and_items(&self,
1909 if self.session.features.borrow().import_shadowing {
1913 if module.external_module_children.borrow().contains_key(&name) {
1916 format!("the name `{}` conflicts with an external \
1917 crate that has been imported into this \
1919 token::get_name(name).get())[]);
1923 /// Resolves the given module path from the given root `module_`.
1924 fn resolve_module_path_from_root(&mut self,
1925 module_: Rc<Module>,
1926 module_path: &[Name],
1929 name_search_type: NameSearchType,
1931 -> ResolveResult<(Rc<Module>, LastPrivate)> {
1932 fn search_parent_externals(needle: Name, module: &Rc<Module>)
1933 -> Option<Rc<Module>> {
1934 module.external_module_children.borrow()
1935 .get(&needle).cloned()
1936 .map(|_| module.clone())
1938 match module.parent_link.clone() {
1939 ModuleParentLink(parent, _) => {
1940 search_parent_externals(needle,
1941 &parent.upgrade().unwrap())
1948 let mut search_module = module_;
1949 let mut index = index;
1950 let module_path_len = module_path.len();
1951 let mut closest_private = lp;
1953 // Resolve the module part of the path. This does not involve looking
1954 // upward though scope chains; we simply resolve names directly in
1955 // modules as we go.
1956 while index < module_path_len {
1957 let name = module_path[index];
1958 match self.resolve_name_in_module(search_module.clone(),
1964 let segment_name = token::get_name(name);
1965 let module_name = self.module_to_string(&*search_module);
1966 let mut span = span;
1967 let msg = if "???" == module_name[] {
1968 span.hi = span.lo + Pos::from_uint(segment_name.get().len());
1970 match search_parent_externals(name,
1971 &self.current_module) {
1973 let path_str = self.names_to_string(module_path);
1974 let target_mod_str = self.module_to_string(&*module);
1975 let current_mod_str =
1976 self.module_to_string(&*self.current_module);
1978 let prefix = if target_mod_str == current_mod_str {
1979 "self::".to_string()
1981 format!("{}::", target_mod_str)
1984 format!("Did you mean `{}{}`?", prefix, path_str)
1986 None => format!("Maybe a missing `extern crate {}`?",
1990 format!("Could not find `{}` in `{}`",
1995 return Failed(Some((span, msg)));
1997 Failed(err) => return Failed(err),
1999 debug!("(resolving module path for import) module \
2000 resolution is indeterminate: {}",
2001 token::get_name(name));
2002 return Indeterminate;
2004 Success((target, used_proxy)) => {
2005 // Check to see whether there are type bindings, and, if
2006 // so, whether there is a module within.
2007 match *target.bindings.type_def.borrow() {
2008 Some(ref type_def) => {
2009 match type_def.module_def {
2011 let msg = format!("Not a module `{}`",
2012 token::get_name(name));
2014 return Failed(Some((span, msg)));
2016 Some(ref module_def) => {
2017 search_module = module_def.clone();
2019 // track extern crates for unused_extern_crate lint
2020 if let Some(did) = module_def.def_id.get() {
2021 self.used_crates.insert(did.krate);
2024 // Keep track of the closest
2025 // private module used when
2026 // resolving this import chain.
2027 if !used_proxy && !search_module.is_public {
2028 if let Some(did) = search_module.def_id.get() {
2029 closest_private = LastMod(DependsOn(did));
2036 // There are no type bindings at all.
2037 let msg = format!("Not a module `{}`",
2038 token::get_name(name));
2039 return Failed(Some((span, msg)));
2048 return Success((search_module, closest_private));
2051 /// Attempts to resolve the module part of an import directive or path
2052 /// rooted at the given module.
2054 /// On success, returns the resolved module, and the closest *private*
2055 /// module found to the destination when resolving this path.
2056 fn resolve_module_path(&mut self,
2057 module_: Rc<Module>,
2058 module_path: &[Name],
2059 use_lexical_scope: UseLexicalScopeFlag,
2061 name_search_type: NameSearchType)
2062 -> ResolveResult<(Rc<Module>, LastPrivate)> {
2063 let module_path_len = module_path.len();
2064 assert!(module_path_len > 0);
2066 debug!("(resolving module path for import) processing `{}` rooted at `{}`",
2067 self.names_to_string(module_path),
2068 self.module_to_string(&*module_));
2070 // Resolve the module prefix, if any.
2071 let module_prefix_result = self.resolve_module_prefix(module_.clone(),
2077 match module_prefix_result {
2079 let mpath = self.names_to_string(module_path);
2080 let mpath = mpath[];
2081 match mpath.rfind(':') {
2083 let msg = format!("Could not find `{}` in `{}`",
2084 // idx +- 1 to account for the
2085 // colons on either side
2088 return Failed(Some((span, msg)));
2095 Failed(err) => return Failed(err),
2097 debug!("(resolving module path for import) indeterminate; \
2099 return Indeterminate;
2101 Success(NoPrefixFound) => {
2102 // There was no prefix, so we're considering the first element
2103 // of the path. How we handle this depends on whether we were
2104 // instructed to use lexical scope or not.
2105 match use_lexical_scope {
2106 DontUseLexicalScope => {
2107 // This is a crate-relative path. We will start the
2108 // resolution process at index zero.
2109 search_module = self.graph_root.get_module();
2111 last_private = LastMod(AllPublic);
2113 UseLexicalScope => {
2114 // This is not a crate-relative path. We resolve the
2115 // first component of the path in the current lexical
2116 // scope and then proceed to resolve below that.
2117 match self.resolve_module_in_lexical_scope(module_,
2119 Failed(err) => return Failed(err),
2121 debug!("(resolving module path for import) \
2122 indeterminate; bailing");
2123 return Indeterminate;
2125 Success(containing_module) => {
2126 search_module = containing_module;
2128 last_private = LastMod(AllPublic);
2134 Success(PrefixFound(ref containing_module, index)) => {
2135 search_module = containing_module.clone();
2136 start_index = index;
2137 last_private = LastMod(DependsOn(containing_module.def_id
2143 self.resolve_module_path_from_root(search_module,
2151 /// Invariant: This must only be called during main resolution, not during
2152 /// import resolution.
2153 fn resolve_item_in_lexical_scope(&mut self,
2154 module_: Rc<Module>,
2156 namespace: Namespace)
2157 -> ResolveResult<(Target, bool)> {
2158 debug!("(resolving item in lexical scope) resolving `{}` in \
2159 namespace {} in `{}`",
2160 token::get_name(name),
2162 self.module_to_string(&*module_));
2164 // The current module node is handled specially. First, check for
2165 // its immediate children.
2166 build_reduced_graph::populate_module_if_necessary(self, &module_);
2168 match module_.children.borrow().get(&name) {
2170 if name_bindings.defined_in_namespace(namespace) => {
2171 debug!("top name bindings succeeded");
2172 return Success((Target::new(module_.clone(),
2173 name_bindings.clone(),
2177 Some(_) | None => { /* Not found; continue. */ }
2180 // Now check for its import directives. We don't have to have resolved
2181 // all its imports in the usual way; this is because chains of
2182 // adjacent import statements are processed as though they mutated the
2184 if let Some(import_resolution) = module_.import_resolutions.borrow().get(&name) {
2185 match (*import_resolution).target_for_namespace(namespace) {
2187 // Not found; continue.
2188 debug!("(resolving item in lexical scope) found \
2189 import resolution, but not in namespace {}",
2193 debug!("(resolving item in lexical scope) using \
2194 import resolution");
2195 // track used imports and extern crates as well
2196 let id = import_resolution.id(namespace);
2197 self.used_imports.insert((id, namespace));
2198 self.record_import_use(id, name);
2199 if let Some(DefId{krate: kid, ..}) = target.target_module.def_id.get() {
2200 self.used_crates.insert(kid);
2202 return Success((target, false));
2207 // Search for external modules.
2208 if namespace == TypeNS {
2209 if let Some(module) = module_.external_module_children.borrow().get(&name).cloned() {
2211 Rc::new(Resolver::create_name_bindings_from_module(module));
2212 debug!("lower name bindings succeeded");
2213 return Success((Target::new(module_,
2220 // Finally, proceed up the scope chain looking for parent modules.
2221 let mut search_module = module_;
2223 // Go to the next parent.
2224 match search_module.parent_link.clone() {
2226 // No more parents. This module was unresolved.
2227 debug!("(resolving item in lexical scope) unresolved \
2229 return Failed(None);
2231 ModuleParentLink(parent_module_node, _) => {
2232 match search_module.kind.get() {
2233 NormalModuleKind => {
2234 // We stop the search here.
2235 debug!("(resolving item in lexical \
2236 scope) unresolved module: not \
2237 searching through module \
2239 return Failed(None);
2244 AnonymousModuleKind => {
2245 search_module = parent_module_node.upgrade().unwrap();
2249 BlockParentLink(ref parent_module_node, _) => {
2250 search_module = parent_module_node.upgrade().unwrap();
2254 // Resolve the name in the parent module.
2255 match self.resolve_name_in_module(search_module.clone(),
2260 Failed(Some((span, msg))) =>
2261 self.resolve_error(span, format!("failed to resolve. {}",
2263 Failed(None) => (), // Continue up the search chain.
2265 // We couldn't see through the higher scope because of an
2266 // unresolved import higher up. Bail.
2268 debug!("(resolving item in lexical scope) indeterminate \
2269 higher scope; bailing");
2270 return Indeterminate;
2272 Success((target, used_reexport)) => {
2273 // We found the module.
2274 debug!("(resolving item in lexical scope) found name \
2276 return Success((target, used_reexport));
2282 /// Resolves a module name in the current lexical scope.
2283 fn resolve_module_in_lexical_scope(&mut self,
2284 module_: Rc<Module>,
2286 -> ResolveResult<Rc<Module>> {
2287 // If this module is an anonymous module, resolve the item in the
2288 // lexical scope. Otherwise, resolve the item from the crate root.
2289 let resolve_result = self.resolve_item_in_lexical_scope(module_, name, TypeNS);
2290 match resolve_result {
2291 Success((target, _)) => {
2292 let bindings = &*target.bindings;
2293 match *bindings.type_def.borrow() {
2294 Some(ref type_def) => {
2295 match type_def.module_def {
2297 debug!("!!! (resolving module in lexical \
2298 scope) module wasn't actually a \
2300 return Failed(None);
2302 Some(ref module_def) => {
2303 return Success(module_def.clone());
2308 debug!("!!! (resolving module in lexical scope) module
2309 wasn't actually a module!");
2310 return Failed(None);
2315 debug!("(resolving module in lexical scope) indeterminate; \
2317 return Indeterminate;
2320 debug!("(resolving module in lexical scope) failed to resolve");
2326 /// Returns the nearest normal module parent of the given module.
2327 fn get_nearest_normal_module_parent(&mut self, module_: Rc<Module>)
2328 -> Option<Rc<Module>> {
2329 let mut module_ = module_;
2331 match module_.parent_link.clone() {
2332 NoParentLink => return None,
2333 ModuleParentLink(new_module, _) |
2334 BlockParentLink(new_module, _) => {
2335 let new_module = new_module.upgrade().unwrap();
2336 match new_module.kind.get() {
2337 NormalModuleKind => return Some(new_module),
2341 AnonymousModuleKind => module_ = new_module,
2348 /// Returns the nearest normal module parent of the given module, or the
2349 /// module itself if it is a normal module.
2350 fn get_nearest_normal_module_parent_or_self(&mut self, module_: Rc<Module>)
2352 match module_.kind.get() {
2353 NormalModuleKind => return module_,
2357 AnonymousModuleKind => {
2358 match self.get_nearest_normal_module_parent(module_.clone()) {
2360 Some(new_module) => new_module
2366 /// Resolves a "module prefix". A module prefix is one or both of (a) `self::`;
2367 /// (b) some chain of `super::`.
2368 /// grammar: (SELF MOD_SEP ) ? (SUPER MOD_SEP) *
2369 fn resolve_module_prefix(&mut self,
2370 module_: Rc<Module>,
2371 module_path: &[Name])
2372 -> ResolveResult<ModulePrefixResult> {
2373 // Start at the current module if we see `self` or `super`, or at the
2374 // top of the crate otherwise.
2375 let mut containing_module;
2377 let first_module_path_string = token::get_name(module_path[0]);
2378 if "self" == first_module_path_string.get() {
2380 self.get_nearest_normal_module_parent_or_self(module_);
2382 } else if "super" == first_module_path_string.get() {
2384 self.get_nearest_normal_module_parent_or_self(module_);
2385 i = 0; // We'll handle `super` below.
2387 return Success(NoPrefixFound);
2390 // Now loop through all the `super`s we find.
2391 while i < module_path.len() {
2392 let string = token::get_name(module_path[i]);
2393 if "super" != string.get() {
2396 debug!("(resolving module prefix) resolving `super` at {}",
2397 self.module_to_string(&*containing_module));
2398 match self.get_nearest_normal_module_parent(containing_module) {
2399 None => return Failed(None),
2400 Some(new_module) => {
2401 containing_module = new_module;
2407 debug!("(resolving module prefix) finished resolving prefix at {}",
2408 self.module_to_string(&*containing_module));
2410 return Success(PrefixFound(containing_module, i));
2413 /// Attempts to resolve the supplied name in the given module for the
2414 /// given namespace. If successful, returns the target corresponding to
2417 /// The boolean returned on success is an indicator of whether this lookup
2418 /// passed through a public re-export proxy.
2419 fn resolve_name_in_module(&mut self,
2420 module_: Rc<Module>,
2422 namespace: Namespace,
2423 name_search_type: NameSearchType,
2424 allow_private_imports: bool)
2425 -> ResolveResult<(Target, bool)> {
2426 debug!("(resolving name in module) resolving `{}` in `{}`",
2427 token::get_name(name).get(),
2428 self.module_to_string(&*module_));
2430 // First, check the direct children of the module.
2431 build_reduced_graph::populate_module_if_necessary(self, &module_);
2433 match module_.children.borrow().get(&name) {
2435 if name_bindings.defined_in_namespace(namespace) => {
2436 debug!("(resolving name in module) found node as child");
2437 return Success((Target::new(module_.clone(),
2438 name_bindings.clone(),
2447 // Next, check the module's imports if necessary.
2449 // If this is a search of all imports, we should be done with glob
2450 // resolution at this point.
2451 if name_search_type == PathSearch {
2452 assert_eq!(module_.glob_count.get(), 0);
2455 // Check the list of resolved imports.
2456 match module_.import_resolutions.borrow().get(&name) {
2457 Some(import_resolution) if allow_private_imports ||
2458 import_resolution.is_public => {
2460 if import_resolution.is_public &&
2461 import_resolution.outstanding_references != 0 {
2462 debug!("(resolving name in module) import \
2463 unresolved; bailing out");
2464 return Indeterminate;
2466 match import_resolution.target_for_namespace(namespace) {
2468 debug!("(resolving name in module) name found, \
2469 but not in namespace {}",
2473 debug!("(resolving name in module) resolved to \
2475 // track used imports and extern crates as well
2476 let id = import_resolution.id(namespace);
2477 self.used_imports.insert((id, namespace));
2478 self.record_import_use(id, name);
2479 if let Some(DefId{krate: kid, ..}) = target.target_module.def_id.get() {
2480 self.used_crates.insert(kid);
2482 return Success((target, true));
2486 Some(..) | None => {} // Continue.
2489 // Finally, search through external children.
2490 if namespace == TypeNS {
2491 if let Some(module) = module_.external_module_children.borrow().get(&name).cloned() {
2493 Rc::new(Resolver::create_name_bindings_from_module(module));
2494 return Success((Target::new(module_,
2501 // We're out of luck.
2502 debug!("(resolving name in module) failed to resolve `{}`",
2503 token::get_name(name).get());
2504 return Failed(None);
2507 fn report_unresolved_imports(&mut self, module_: Rc<Module>) {
2508 let index = module_.resolved_import_count.get();
2509 let imports = module_.imports.borrow();
2510 let import_count = imports.len();
2511 if index != import_count {
2512 let sn = self.session
2514 .span_to_snippet((*imports)[index].span)
2516 if sn.contains("::") {
2517 self.resolve_error((*imports)[index].span,
2518 "unresolved import");
2520 let err = format!("unresolved import (maybe you meant `{}::*`?)",
2522 self.resolve_error((*imports)[index].span, err[]);
2526 // Descend into children and anonymous children.
2527 build_reduced_graph::populate_module_if_necessary(self, &module_);
2529 for (_, child_node) in module_.children.borrow().iter() {
2530 match child_node.get_module_if_available() {
2534 Some(child_module) => {
2535 self.report_unresolved_imports(child_module);
2540 for (_, module_) in module_.anonymous_children.borrow().iter() {
2541 self.report_unresolved_imports(module_.clone());
2547 // We maintain a list of value ribs and type ribs.
2549 // Simultaneously, we keep track of the current position in the module
2550 // graph in the `current_module` pointer. When we go to resolve a name in
2551 // the value or type namespaces, we first look through all the ribs and
2552 // then query the module graph. When we resolve a name in the module
2553 // namespace, we can skip all the ribs (since nested modules are not
2554 // allowed within blocks in Rust) and jump straight to the current module
2557 // Named implementations are handled separately. When we find a method
2558 // call, we consult the module node to find all of the implementations in
2559 // scope. This information is lazily cached in the module node. We then
2560 // generate a fake "implementation scope" containing all the
2561 // implementations thus found, for compatibility with old resolve pass.
2563 fn with_scope<F>(&mut self, name: Option<Name>, f: F) where
2564 F: FnOnce(&mut Resolver),
2566 let orig_module = self.current_module.clone();
2568 // Move down in the graph.
2574 build_reduced_graph::populate_module_if_necessary(self, &orig_module);
2576 match orig_module.children.borrow().get(&name) {
2578 debug!("!!! (with scope) didn't find `{}` in `{}`",
2579 token::get_name(name),
2580 self.module_to_string(&*orig_module));
2582 Some(name_bindings) => {
2583 match (*name_bindings).get_module_if_available() {
2585 debug!("!!! (with scope) didn't find module \
2587 token::get_name(name),
2588 self.module_to_string(&*orig_module));
2591 self.current_module = module_;
2601 self.current_module = orig_module;
2604 /// Wraps the given definition in the appropriate number of `DefUpvar`
2610 -> Option<DefLike> {
2612 DlDef(d @ DefUpvar(..)) => {
2613 self.session.span_bug(span,
2614 format!("unexpected {} in bindings", d)[])
2616 DlDef(d @ DefLocal(_)) => {
2617 let node_id = d.def_id().node;
2619 let mut last_proc_body_id = ast::DUMMY_NODE_ID;
2620 for rib in ribs.iter() {
2623 // Nothing to do. Continue.
2625 ClosureRibKind(function_id, maybe_proc_body) => {
2627 if maybe_proc_body != ast::DUMMY_NODE_ID {
2628 last_proc_body_id = maybe_proc_body;
2630 def = DefUpvar(node_id, function_id, last_proc_body_id);
2632 let mut seen = self.freevars_seen.borrow_mut();
2633 let seen = match seen.entry(function_id) {
2634 Occupied(v) => v.into_mut(),
2635 Vacant(v) => v.set(NodeSet::new()),
2637 if seen.contains(&node_id) {
2640 match self.freevars.borrow_mut().entry(function_id) {
2641 Occupied(v) => v.into_mut(),
2642 Vacant(v) => v.set(vec![]),
2643 }.push(Freevar { def: prev_def, span: span });
2644 seen.insert(node_id);
2646 MethodRibKind(item_id, _) => {
2647 // If the def is a ty param, and came from the parent
2650 DefTyParam(_, _, did, _) if {
2651 self.def_map.borrow().get(&did.node).cloned()
2652 == Some(DefTyParamBinder(item_id))
2654 DefSelfTy(did) if did == item_id => {} // ok
2656 // This was an attempt to access an upvar inside a
2657 // named function item. This is not allowed, so we
2662 "can't capture dynamic environment in a fn item; \
2663 use the || { ... } closure form instead");
2670 // This was an attempt to access an upvar inside a
2671 // named function item. This is not allowed, so we
2676 "can't capture dynamic environment in a fn item; \
2677 use the || { ... } closure form instead");
2681 ConstantItemRibKind => {
2682 // Still doesn't deal with upvars
2683 self.resolve_error(span,
2684 "attempt to use a non-constant \
2685 value in a constant");
2692 DlDef(def @ DefTyParam(..)) |
2693 DlDef(def @ DefSelfTy(..)) => {
2694 for rib in ribs.iter() {
2696 NormalRibKind | ClosureRibKind(..) => {
2697 // Nothing to do. Continue.
2699 MethodRibKind(item_id, _) => {
2700 // If the def is a ty param, and came from the parent
2703 DefTyParam(_, _, did, _) if {
2704 self.def_map.borrow().get(&did.node).cloned()
2705 == Some(DefTyParamBinder(item_id))
2707 DefSelfTy(did) if did == item_id => {} // ok
2710 // This was an attempt to use a type parameter outside
2713 self.resolve_error(span,
2714 "can't use type parameters from \
2715 outer function; try using a local \
2716 type parameter instead");
2723 // This was an attempt to use a type parameter outside
2726 self.resolve_error(span,
2727 "can't use type parameters from \
2728 outer function; try using a local \
2729 type parameter instead");
2733 ConstantItemRibKind => {
2735 self.resolve_error(span,
2736 "cannot use an outer type \
2737 parameter in this context");
2748 /// Searches the current set of local scopes and
2749 /// applies translations for closures.
2750 fn search_ribs(&self,
2754 -> Option<DefLike> {
2755 // FIXME #4950: Try caching?
2757 for (i, rib) in ribs.iter().enumerate().rev() {
2758 match rib.bindings.get(&name).cloned() {
2760 return self.upvarify(ribs[i + 1..], def_like, span);
2771 /// Searches the current set of local scopes for labels.
2772 /// Stops after meeting a closure.
2773 fn search_label(&self, name: Name) -> Option<DefLike> {
2774 for rib in self.label_ribs.iter().rev() {
2780 // Do not resolve labels across function boundary
2784 let result = rib.bindings.get(&name).cloned();
2785 if result.is_some() {
2792 fn resolve_crate(&mut self, krate: &ast::Crate) {
2793 debug!("(resolving crate) starting");
2795 visit::walk_crate(self, krate);
2798 fn resolve_item(&mut self, item: &Item) {
2799 let name = item.ident.name;
2801 debug!("(resolving item) resolving {}",
2802 token::get_name(name));
2806 // enum item: resolve all the variants' discrs,
2807 // then resolve the ty params
2808 ItemEnum(ref enum_def, ref generics) => {
2809 for variant in (*enum_def).variants.iter() {
2810 for dis_expr in variant.node.disr_expr.iter() {
2811 // resolve the discriminator expr
2813 self.with_constant_rib(|this| {
2814 this.resolve_expr(&**dis_expr);
2819 // n.b. the discr expr gets visited twice.
2820 // but maybe it's okay since the first time will signal an
2821 // error if there is one? -- tjc
2822 self.with_type_parameter_rib(HasTypeParameters(generics,
2827 this.resolve_type_parameters(&generics.ty_params);
2828 this.resolve_where_clause(&generics.where_clause);
2829 visit::walk_item(this, item);
2833 ItemTy(_, ref generics) => {
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 // Create a new rib for the self type.
2858 let mut self_type_rib = Rib::new(ItemRibKind);
2860 // plain insert (no renaming, types are not currently hygienic....)
2861 let name = self.type_self_name;
2862 self_type_rib.bindings.insert(name, DlDef(DefSelfTy(item.id)));
2863 self.type_ribs.push(self_type_rib);
2865 // Create a new rib for the trait-wide type parameters.
2866 self.with_type_parameter_rib(HasTypeParameters(generics,
2871 this.resolve_type_parameters(&generics.ty_params);
2872 this.resolve_where_clause(&generics.where_clause);
2874 this.resolve_type_parameter_bounds(item.id, bounds,
2877 for trait_item in (*trait_items).iter() {
2878 // Create a new rib for the trait_item-specific type
2881 // FIXME #4951: Do we need a node ID here?
2884 ast::RequiredMethod(ref ty_m) => {
2885 this.with_type_parameter_rib
2886 (HasTypeParameters(&ty_m.generics,
2889 MethodRibKind(item.id, RequiredMethod)),
2892 // Resolve the method-specific type
2894 this.resolve_type_parameters(
2895 &ty_m.generics.ty_params);
2896 this.resolve_where_clause(&ty_m.generics
2899 for argument in ty_m.decl.inputs.iter() {
2900 this.resolve_type(&*argument.ty);
2903 if let SelfExplicit(ref typ, _) = ty_m.explicit_self.node {
2904 this.resolve_type(&**typ)
2907 if let ast::Return(ref ret_ty) = ty_m.decl.output {
2908 this.resolve_type(&**ret_ty);
2912 ast::ProvidedMethod(ref m) => {
2913 this.resolve_method(MethodRibKind(item.id,
2914 ProvidedMethod(m.id)),
2917 ast::TypeTraitItem(ref data) => {
2918 this.resolve_type_parameter(&data.ty_param);
2919 visit::walk_trait_item(this, trait_item);
2925 self.type_ribs.pop();
2928 ItemStruct(ref struct_def, ref generics) => {
2929 self.resolve_struct(item.id,
2931 struct_def.fields[]);
2934 ItemMod(ref module_) => {
2935 self.with_scope(Some(name), |this| {
2936 this.resolve_module(module_, item.span, name,
2941 ItemForeignMod(ref foreign_module) => {
2942 self.with_scope(Some(name), |this| {
2943 for foreign_item in foreign_module.items.iter() {
2944 match foreign_item.node {
2945 ForeignItemFn(_, ref generics) => {
2946 this.with_type_parameter_rib(
2948 generics, FnSpace, foreign_item.id,
2950 |this| visit::walk_foreign_item(this,
2953 ForeignItemStatic(..) => {
2954 visit::walk_foreign_item(this,
2962 ItemFn(ref fn_decl, _, _, ref generics, ref block) => {
2963 self.resolve_function(ItemRibKind,
2973 ItemConst(..) | ItemStatic(..) => {
2974 self.with_constant_rib(|this| {
2975 visit::walk_item(this, item);
2980 // do nothing, these are just around to be encoded
2985 fn with_type_parameter_rib<F>(&mut self, type_parameters: TypeParameters, f: F) where
2986 F: FnOnce(&mut Resolver),
2988 match type_parameters {
2989 HasTypeParameters(generics, space, node_id, rib_kind) => {
2990 let mut function_type_rib = Rib::new(rib_kind);
2991 let mut seen_bindings = HashSet::new();
2992 for (index, type_parameter) in generics.ty_params.iter().enumerate() {
2993 let name = type_parameter.ident.name;
2994 debug!("with_type_parameter_rib: {} {}", node_id,
2997 if seen_bindings.contains(&name) {
2998 self.resolve_error(type_parameter.span,
2999 format!("the name `{}` is already \
3001 parameter in this type \
3006 seen_bindings.insert(name);
3008 let def_like = DlDef(DefTyParam(space,
3010 local_def(type_parameter.id),
3012 // Associate this type parameter with
3013 // the item that bound it
3014 self.record_def(type_parameter.id,
3015 (DefTyParamBinder(node_id), LastMod(AllPublic)));
3016 // plain insert (no renaming)
3017 function_type_rib.bindings.insert(name, def_like);
3019 self.type_ribs.push(function_type_rib);
3022 NoTypeParameters => {
3029 match type_parameters {
3030 HasTypeParameters(..) => { self.type_ribs.pop(); }
3031 NoTypeParameters => { }
3035 fn with_label_rib<F>(&mut self, f: F) where
3036 F: FnOnce(&mut Resolver),
3038 self.label_ribs.push(Rib::new(NormalRibKind));
3040 self.label_ribs.pop();
3043 fn with_constant_rib<F>(&mut self, f: F) where
3044 F: FnOnce(&mut Resolver),
3046 self.value_ribs.push(Rib::new(ConstantItemRibKind));
3047 self.type_ribs.push(Rib::new(ConstantItemRibKind));
3049 self.type_ribs.pop();
3050 self.value_ribs.pop();
3053 fn resolve_function(&mut self,
3055 optional_declaration: Option<&FnDecl>,
3056 type_parameters: TypeParameters,
3058 // Create a value rib for the function.
3059 let function_value_rib = Rib::new(rib_kind);
3060 self.value_ribs.push(function_value_rib);
3062 // Create a label rib for the function.
3063 let function_label_rib = Rib::new(rib_kind);
3064 self.label_ribs.push(function_label_rib);
3066 // If this function has type parameters, add them now.
3067 self.with_type_parameter_rib(type_parameters, |this| {
3068 // Resolve the type parameters.
3069 match type_parameters {
3070 NoTypeParameters => {
3073 HasTypeParameters(ref generics, _, _, _) => {
3074 this.resolve_type_parameters(&generics.ty_params);
3075 this.resolve_where_clause(&generics.where_clause);
3079 // Add each argument to the rib.
3080 match optional_declaration {
3084 Some(declaration) => {
3085 let mut bindings_list = HashMap::new();
3086 for argument in declaration.inputs.iter() {
3087 this.resolve_pattern(&*argument.pat,
3088 ArgumentIrrefutableMode,
3089 &mut bindings_list);
3091 this.resolve_type(&*argument.ty);
3093 debug!("(resolving function) recorded argument");
3096 if let ast::Return(ref ret_ty) = declaration.output {
3097 this.resolve_type(&**ret_ty);
3102 // Resolve the function body.
3103 this.resolve_block(&*block);
3105 debug!("(resolving function) leaving function");
3108 self.label_ribs.pop();
3109 self.value_ribs.pop();
3112 fn resolve_type_parameters(&mut self,
3113 type_parameters: &OwnedSlice<TyParam>) {
3114 for type_parameter in type_parameters.iter() {
3115 self.resolve_type_parameter(type_parameter);
3119 fn resolve_type_parameter(&mut self,
3120 type_parameter: &TyParam) {
3121 for bound in type_parameter.bounds.iter() {
3122 self.resolve_type_parameter_bound(type_parameter.id, bound,
3123 TraitBoundingTypeParameter);
3125 match type_parameter.default {
3126 Some(ref ty) => self.resolve_type(&**ty),
3131 fn resolve_type_parameter_bounds(&mut self,
3133 type_parameter_bounds: &OwnedSlice<TyParamBound>,
3134 reference_type: TraitReferenceType) {
3135 for type_parameter_bound in type_parameter_bounds.iter() {
3136 self.resolve_type_parameter_bound(id, type_parameter_bound,
3141 fn resolve_type_parameter_bound(&mut self,
3143 type_parameter_bound: &TyParamBound,
3144 reference_type: TraitReferenceType) {
3145 match *type_parameter_bound {
3146 TraitTyParamBound(ref tref, _) => {
3147 self.resolve_poly_trait_reference(id, tref, reference_type)
3149 RegionTyParamBound(..) => {}
3153 fn resolve_poly_trait_reference(&mut self,
3155 poly_trait_reference: &PolyTraitRef,
3156 reference_type: TraitReferenceType) {
3157 self.resolve_trait_reference(id, &poly_trait_reference.trait_ref, reference_type)
3160 fn resolve_trait_reference(&mut self,
3162 trait_reference: &TraitRef,
3163 reference_type: TraitReferenceType) {
3164 match self.resolve_path(id, &trait_reference.path, TypeNS, true) {
3166 let path_str = self.path_names_to_string(&trait_reference.path);
3167 let usage_str = match reference_type {
3168 TraitBoundingTypeParameter => "bound type parameter with",
3169 TraitImplementation => "implement",
3170 TraitDerivation => "derive",
3171 TraitObject => "reference",
3172 TraitQPath => "extract an associated type from",
3175 let msg = format!("attempt to {} a nonexistent trait `{}`", usage_str, path_str);
3176 self.resolve_error(trait_reference.path.span, msg[]);
3180 (DefTrait(_), _) => {
3181 debug!("(resolving trait) found trait def: {}", def);
3182 self.record_def(trait_reference.ref_id, def);
3185 self.resolve_error(trait_reference.path.span,
3186 format!("`{}` is not a trait",
3187 self.path_names_to_string(
3188 &trait_reference.path))[]);
3190 // If it's a typedef, give a note
3191 if let DefTy(..) = def {
3192 self.session.span_note(
3193 trait_reference.path.span,
3194 format!("`type` aliases cannot be used for traits")
3203 fn resolve_where_clause(&mut self, where_clause: &ast::WhereClause) {
3204 for predicate in where_clause.predicates.iter() {
3206 &ast::WherePredicate::BoundPredicate(ref bound_pred) => {
3207 self.resolve_type(&*bound_pred.bounded_ty);
3209 for bound in bound_pred.bounds.iter() {
3210 self.resolve_type_parameter_bound(bound_pred.bounded_ty.id, bound,
3211 TraitBoundingTypeParameter);
3214 &ast::WherePredicate::RegionPredicate(_) => {}
3215 &ast::WherePredicate::EqPredicate(ref eq_pred) => {
3216 match self.resolve_path(eq_pred.id, &eq_pred.path, TypeNS, true) {
3217 Some((def @ DefTyParam(..), last_private)) => {
3218 self.record_def(eq_pred.id, (def, last_private));
3221 self.resolve_error(eq_pred.path.span,
3222 "undeclared associated type");
3226 self.resolve_type(&*eq_pred.ty);
3232 fn resolve_struct(&mut self,
3234 generics: &Generics,
3235 fields: &[StructField]) {
3236 // If applicable, create a rib for the type parameters.
3237 self.with_type_parameter_rib(HasTypeParameters(generics,
3242 // Resolve the type parameters.
3243 this.resolve_type_parameters(&generics.ty_params);
3244 this.resolve_where_clause(&generics.where_clause);
3247 for field in fields.iter() {
3248 this.resolve_type(&*field.node.ty);
3253 // Does this really need to take a RibKind or is it always going
3254 // to be NormalRibKind?
3255 fn resolve_method(&mut self,
3257 method: &ast::Method) {
3258 let method_generics = method.pe_generics();
3259 let type_parameters = HasTypeParameters(method_generics,
3264 if let SelfExplicit(ref typ, _) = method.pe_explicit_self().node {
3265 self.resolve_type(&**typ);
3268 self.resolve_function(rib_kind,
3269 Some(method.pe_fn_decl()),
3274 fn with_current_self_type<T, F>(&mut self, self_type: &Ty, f: F) -> T where
3275 F: FnOnce(&mut Resolver) -> T,
3277 // Handle nested impls (inside fn bodies)
3278 let previous_value = replace(&mut self.current_self_type, Some(self_type.clone()));
3279 let result = f(self);
3280 self.current_self_type = previous_value;
3284 fn with_optional_trait_ref<T, F>(&mut self, id: NodeId,
3285 opt_trait_ref: &Option<TraitRef>,
3287 F: FnOnce(&mut Resolver) -> T,
3289 let new_val = match *opt_trait_ref {
3290 Some(ref trait_ref) => {
3291 self.resolve_trait_reference(id, trait_ref, TraitImplementation);
3293 match self.def_map.borrow().get(&trait_ref.ref_id) {
3295 let did = def.def_id();
3296 Some((did, trait_ref.clone()))
3303 let original_trait_ref = replace(&mut self.current_trait_ref, new_val);
3304 let result = f(self);
3305 self.current_trait_ref = original_trait_ref;
3309 fn resolve_implementation(&mut self,
3311 generics: &Generics,
3312 opt_trait_reference: &Option<TraitRef>,
3314 impl_items: &[ImplItem]) {
3315 // If applicable, create a rib for the type parameters.
3316 self.with_type_parameter_rib(HasTypeParameters(generics,
3321 // Resolve the type parameters.
3322 this.resolve_type_parameters(&generics.ty_params);
3323 this.resolve_where_clause(&generics.where_clause);
3325 // Resolve the trait reference, if necessary.
3326 this.with_optional_trait_ref(id, opt_trait_reference, |this| {
3327 // Resolve the self type.
3328 this.resolve_type(self_type);
3330 this.with_current_self_type(self_type, |this| {
3331 for impl_item in impl_items.iter() {
3333 MethodImplItem(ref method) => {
3334 // If this is a trait impl, ensure the method
3336 this.check_trait_item(method.pe_ident().name,
3339 // We also need a new scope for the method-
3340 // specific type parameters.
3341 this.resolve_method(
3342 MethodRibKind(id, ProvidedMethod(method.id)),
3345 TypeImplItem(ref typedef) => {
3346 // If this is a trait impl, ensure the method
3348 this.check_trait_item(typedef.ident.name,
3351 this.resolve_type(&*typedef.typ);
3359 // Check that the current type is indeed a type, if we have an anonymous impl
3360 if opt_trait_reference.is_none() {
3361 match self_type.node {
3362 // TyPath is the only thing that we handled in `build_reduced_graph_for_item`,
3363 // where we created a module with the name of the type in order to implement
3364 // an anonymous trait. In the case that the path does not resolve to an actual
3365 // type, the result will be that the type name resolves to a module but not
3366 // a type (shadowing any imported modules or types with this name), leading
3367 // to weird user-visible bugs. So we ward this off here. See #15060.
3368 TyPath(ref path, path_id) => {
3369 match self.def_map.borrow().get(&path_id) {
3370 // FIXME: should we catch other options and give more precise errors?
3371 Some(&DefMod(_)) => {
3372 self.resolve_error(path.span, "inherent implementations are not \
3373 allowed for types not defined in \
3374 the current module");
3384 fn check_trait_item(&self, name: Name, span: Span) {
3385 // If there is a TraitRef in scope for an impl, then the method must be in the trait.
3386 for &(did, ref trait_ref) in self.current_trait_ref.iter() {
3387 if self.trait_item_map.get(&(name, did)).is_none() {
3388 let path_str = self.path_names_to_string(&trait_ref.path);
3389 self.resolve_error(span,
3390 format!("method `{}` is not a member of trait `{}`",
3391 token::get_name(name),
3397 fn resolve_module(&mut self, module: &Mod, _span: Span,
3398 _name: Name, id: NodeId) {
3399 // Write the implementations in scope into the module metadata.
3400 debug!("(resolving module) resolving module ID {}", id);
3401 visit::walk_mod(self, module);
3404 fn resolve_local(&mut self, local: &Local) {
3405 // Resolve the type.
3406 if let Some(ref ty) = local.ty {
3407 self.resolve_type(&**ty);
3410 // Resolve the initializer, if necessary.
3415 Some(ref initializer) => {
3416 self.resolve_expr(&**initializer);
3420 // Resolve the pattern.
3421 let mut bindings_list = HashMap::new();
3422 self.resolve_pattern(&*local.pat,
3423 LocalIrrefutableMode,
3424 &mut bindings_list);
3427 // build a map from pattern identifiers to binding-info's.
3428 // this is done hygienically. This could arise for a macro
3429 // that expands into an or-pattern where one 'x' was from the
3430 // user and one 'x' came from the macro.
3431 fn binding_mode_map(&mut self, pat: &Pat) -> BindingMap {
3432 let mut result = HashMap::new();
3433 pat_bindings(&self.def_map, pat, |binding_mode, _id, sp, path1| {
3434 let name = mtwt::resolve(path1.node);
3435 result.insert(name, BindingInfo {
3437 binding_mode: binding_mode
3443 // check that all of the arms in an or-pattern have exactly the
3444 // same set of bindings, with the same binding modes for each.
3445 fn check_consistent_bindings(&mut self, arm: &Arm) {
3446 if arm.pats.len() == 0 {
3449 let map_0 = self.binding_mode_map(&*arm.pats[0]);
3450 for (i, p) in arm.pats.iter().enumerate() {
3451 let map_i = self.binding_mode_map(&**p);
3453 for (&key, &binding_0) in map_0.iter() {
3454 match map_i.get(&key) {
3458 format!("variable `{}` from pattern #1 is \
3459 not bound in pattern #{}",
3460 token::get_name(key),
3463 Some(binding_i) => {
3464 if binding_0.binding_mode != binding_i.binding_mode {
3467 format!("variable `{}` is bound with different \
3468 mode in pattern #{} than in pattern #1",
3469 token::get_name(key),
3476 for (&key, &binding) in map_i.iter() {
3477 if !map_0.contains_key(&key) {
3480 format!("variable `{}` from pattern {}{} is \
3481 not bound in pattern {}1",
3482 token::get_name(key),
3483 "#", i + 1, "#")[]);
3489 fn resolve_arm(&mut self, arm: &Arm) {
3490 self.value_ribs.push(Rib::new(NormalRibKind));
3492 let mut bindings_list = HashMap::new();
3493 for pattern in arm.pats.iter() {
3494 self.resolve_pattern(&**pattern, RefutableMode, &mut bindings_list);
3497 // This has to happen *after* we determine which
3498 // pat_idents are variants
3499 self.check_consistent_bindings(arm);
3501 visit::walk_expr_opt(self, &arm.guard);
3502 self.resolve_expr(&*arm.body);
3504 self.value_ribs.pop();
3507 fn resolve_block(&mut self, block: &Block) {
3508 debug!("(resolving block) entering block");
3509 self.value_ribs.push(Rib::new(NormalRibKind));
3511 // Move down in the graph, if there's an anonymous module rooted here.
3512 let orig_module = self.current_module.clone();
3513 match orig_module.anonymous_children.borrow().get(&block.id) {
3514 None => { /* Nothing to do. */ }
3515 Some(anonymous_module) => {
3516 debug!("(resolving block) found anonymous module, moving \
3518 self.current_module = anonymous_module.clone();
3522 // Descend into the block.
3523 visit::walk_block(self, block);
3526 self.current_module = orig_module;
3528 self.value_ribs.pop();
3529 debug!("(resolving block) leaving block");
3532 fn resolve_type(&mut self, ty: &Ty) {
3534 // Like path expressions, the interpretation of path types depends
3535 // on whether the path has multiple elements in it or not.
3537 TyPath(ref path, path_id) => {
3538 // This is a path in the type namespace. Walk through scopes
3540 let mut result_def = None;
3542 // First, check to see whether the name is a primitive type.
3543 if path.segments.len() == 1 {
3544 let id = path.segments.last().unwrap().identifier;
3546 match self.primitive_type_table
3550 Some(&primitive_type) => {
3552 Some((DefPrimTy(primitive_type), LastMod(AllPublic)));
3554 if path.segments[0].parameters.has_lifetimes() {
3555 span_err!(self.session, path.span, E0157,
3556 "lifetime parameters are not allowed on this type");
3557 } else if !path.segments[0].parameters.is_empty() {
3558 span_err!(self.session, path.span, E0153,
3559 "type parameters are not allowed on this type");
3570 match self.resolve_path(ty.id, path, TypeNS, true) {
3572 debug!("(resolving type) resolved `{}` to \
3574 token::get_ident(path.segments.last().unwrap() .identifier),
3576 result_def = Some(def);
3583 Some(_) => {} // Continue.
3588 // Write the result into the def map.
3589 debug!("(resolving type) writing resolution for `{}` \
3591 self.path_names_to_string(path),
3593 self.record_def(path_id, def);
3596 let msg = format!("use of undeclared type name `{}`",
3597 self.path_names_to_string(path));
3598 self.resolve_error(ty.span, msg[]);
3603 TyObjectSum(ref ty, ref bound_vec) => {
3604 self.resolve_type(&**ty);
3605 self.resolve_type_parameter_bounds(ty.id, bound_vec,
3606 TraitBoundingTypeParameter);
3609 TyQPath(ref qpath) => {
3610 self.resolve_type(&*qpath.self_type);
3611 self.resolve_trait_reference(ty.id, &*qpath.trait_ref, TraitQPath);
3614 TyClosure(ref c) => {
3615 self.resolve_type_parameter_bounds(
3618 TraitBoundingTypeParameter);
3619 visit::walk_ty(self, ty);
3622 TyPolyTraitRef(ref bounds) => {
3623 self.resolve_type_parameter_bounds(
3627 visit::walk_ty(self, ty);
3630 // Just resolve embedded types.
3631 visit::walk_ty(self, ty);
3636 fn resolve_pattern(&mut self,
3638 mode: PatternBindingMode,
3639 // Maps idents to the node ID for the (outermost)
3640 // pattern that binds them
3641 bindings_list: &mut HashMap<Name, NodeId>) {
3642 let pat_id = pattern.id;
3643 walk_pat(pattern, |pattern| {
3644 match pattern.node {
3645 PatIdent(binding_mode, ref path1, _) => {
3647 // The meaning of pat_ident with no type parameters
3648 // depends on whether an enum variant or unit-like struct
3649 // with that name is in scope. The probing lookup has to
3650 // be careful not to emit spurious errors. Only matching
3651 // patterns (match) can match nullary variants or
3652 // unit-like structs. For binding patterns (let), matching
3653 // such a value is simply disallowed (since it's rarely
3656 let ident = path1.node;
3657 let renamed = mtwt::resolve(ident);
3659 match self.resolve_bare_identifier_pattern(ident.name, pattern.span) {
3660 FoundStructOrEnumVariant(ref def, lp)
3661 if mode == RefutableMode => {
3662 debug!("(resolving pattern) resolving `{}` to \
3663 struct or enum variant",
3664 token::get_name(renamed));
3666 self.enforce_default_binding_mode(
3670 self.record_def(pattern.id, (def.clone(), lp));
3672 FoundStructOrEnumVariant(..) => {
3675 format!("declaration of `{}` shadows an enum \
3676 variant or unit-like struct in \
3678 token::get_name(renamed))[]);
3680 FoundConst(ref def, lp) if mode == RefutableMode => {
3681 debug!("(resolving pattern) resolving `{}` to \
3683 token::get_name(renamed));
3685 self.enforce_default_binding_mode(
3689 self.record_def(pattern.id, (def.clone(), lp));
3692 self.resolve_error(pattern.span,
3693 "only irrefutable patterns \
3696 BareIdentifierPatternUnresolved => {
3697 debug!("(resolving pattern) binding `{}`",
3698 token::get_name(renamed));
3700 let def = DefLocal(pattern.id);
3702 // Record the definition so that later passes
3703 // will be able to distinguish variants from
3704 // locals in patterns.
3706 self.record_def(pattern.id, (def, LastMod(AllPublic)));
3708 // Add the binding to the local ribs, if it
3709 // doesn't already exist in the bindings list. (We
3710 // must not add it if it's in the bindings list
3711 // because that breaks the assumptions later
3712 // passes make about or-patterns.)
3713 if !bindings_list.contains_key(&renamed) {
3714 let this = &mut *self;
3715 let last_rib = this.value_ribs.last_mut().unwrap();
3716 last_rib.bindings.insert(renamed, DlDef(def));
3717 bindings_list.insert(renamed, pat_id);
3718 } else if mode == ArgumentIrrefutableMode &&
3719 bindings_list.contains_key(&renamed) {
3720 // Forbid duplicate bindings in the same
3722 self.resolve_error(pattern.span,
3723 format!("identifier `{}` \
3731 } else if bindings_list.get(&renamed) ==
3733 // Then this is a duplicate variable in the
3734 // same disjunction, which is an error.
3735 self.resolve_error(pattern.span,
3736 format!("identifier `{}` is bound \
3737 more than once in the same \
3739 token::get_ident(ident))[]);
3741 // Else, not bound in the same pattern: do
3747 PatEnum(ref path, _) => {
3748 // This must be an enum variant, struct or const.
3749 match self.resolve_path(pat_id, path, ValueNS, false) {
3750 Some(def @ (DefVariant(..), _)) |
3751 Some(def @ (DefStruct(..), _)) |
3752 Some(def @ (DefConst(..), _)) => {
3753 self.record_def(pattern.id, def);
3755 Some((DefStatic(..), _)) => {
3756 self.resolve_error(path.span,
3757 "static variables cannot be \
3758 referenced in a pattern, \
3759 use a `const` instead");
3762 self.resolve_error(path.span,
3763 format!("`{}` is not an enum variant, struct or const",
3765 path.segments.last().unwrap().identifier))[]);
3768 self.resolve_error(path.span,
3769 format!("unresolved enum variant, struct or const `{}`",
3771 path.segments.last().unwrap().identifier))[]);
3775 // Check the types in the path pattern.
3776 for ty in path.segments
3778 .flat_map(|s| s.parameters.types().into_iter()) {
3779 self.resolve_type(&**ty);
3783 PatLit(ref expr) => {
3784 self.resolve_expr(&**expr);
3787 PatRange(ref first_expr, ref last_expr) => {
3788 self.resolve_expr(&**first_expr);
3789 self.resolve_expr(&**last_expr);
3792 PatStruct(ref path, _, _) => {
3793 match self.resolve_path(pat_id, path, TypeNS, false) {
3794 Some(definition) => {
3795 self.record_def(pattern.id, definition);
3798 debug!("(resolving pattern) didn't find struct \
3800 let msg = format!("`{}` does not name a structure",
3801 self.path_names_to_string(path));
3802 self.resolve_error(path.span, msg[]);
3815 fn resolve_bare_identifier_pattern(&mut self, name: Name, span: Span)
3816 -> BareIdentifierPatternResolution {
3817 let module = self.current_module.clone();
3818 match self.resolve_item_in_lexical_scope(module,
3821 Success((target, _)) => {
3822 debug!("(resolve bare identifier pattern) succeeded in \
3824 token::get_name(name),
3825 target.bindings.value_def.borrow());
3826 match *target.bindings.value_def.borrow() {
3828 panic!("resolved name in the value namespace to a \
3829 set of name bindings with no def?!");
3832 // For the two success cases, this lookup can be
3833 // considered as not having a private component because
3834 // the lookup happened only within the current module.
3836 def @ DefVariant(..) | def @ DefStruct(..) => {
3837 return FoundStructOrEnumVariant(def, LastMod(AllPublic));
3839 def @ DefConst(..) => {
3840 return FoundConst(def, LastMod(AllPublic));
3843 self.resolve_error(span,
3844 "static variables cannot be \
3845 referenced in a pattern, \
3846 use a `const` instead");
3847 return BareIdentifierPatternUnresolved;
3850 return BareIdentifierPatternUnresolved;
3858 panic!("unexpected indeterminate result");
3862 Some((span, msg)) => {
3863 self.resolve_error(span, format!("failed to resolve: {}",
3869 debug!("(resolve bare identifier pattern) failed to find {}",
3870 token::get_name(name));
3871 return BareIdentifierPatternUnresolved;
3876 /// If `check_ribs` is true, checks the local definitions first; i.e.
3877 /// doesn't skip straight to the containing module.
3878 fn resolve_path(&mut self,
3881 namespace: Namespace,
3882 check_ribs: bool) -> Option<(Def, LastPrivate)> {
3883 // First, resolve the types and associated type bindings.
3884 for ty in path.segments.iter().flat_map(|s| s.parameters.types().into_iter()) {
3885 self.resolve_type(&**ty);
3887 for binding in path.segments.iter().flat_map(|s| s.parameters.bindings().into_iter()) {
3888 self.resolve_type(&*binding.ty);
3891 // A special case for sugared associated type paths `T::A` where `T` is
3892 // a type parameter and `A` is an associated type on some bound of `T`.
3893 if namespace == TypeNS && path.segments.len() == 2 {
3894 match self.resolve_identifier(path.segments[0].identifier,
3898 Some((def, last_private)) => {
3900 DefTyParam(_, _, did, _) => {
3901 let def = DefAssociatedPath(TyParamProvenance::FromParam(did),
3902 path.segments.last()
3903 .unwrap().identifier);
3904 return Some((def, last_private));
3907 let def = DefAssociatedPath(TyParamProvenance::FromSelf(local_def(nid)),
3908 path.segments.last()
3909 .unwrap().identifier);
3910 return Some((def, last_private));
3920 return self.resolve_crate_relative_path(path, namespace);
3923 // Try to find a path to an item in a module.
3924 let unqualified_def =
3925 self.resolve_identifier(path.segments.last().unwrap().identifier,
3930 if path.segments.len() > 1 {
3931 let def = self.resolve_module_relative_path(path, namespace);
3932 match (def, unqualified_def) {
3933 (Some((ref d, _)), Some((ref ud, _))) if *d == *ud => {
3935 .add_lint(lint::builtin::UNUSED_QUALIFICATIONS,
3938 "unnecessary qualification".to_string());
3946 return unqualified_def;
3949 // resolve a single identifier (used as a varref)
3950 fn resolve_identifier(&mut self,
3952 namespace: Namespace,
3955 -> Option<(Def, LastPrivate)> {
3957 match self.resolve_identifier_in_local_ribs(identifier,
3961 return Some((def, LastMod(AllPublic)));
3969 return self.resolve_item_by_name_in_lexical_scope(identifier.name, namespace);
3972 // FIXME #4952: Merge me with resolve_name_in_module?
3973 fn resolve_definition_of_name_in_module(&mut self,
3974 containing_module: Rc<Module>,
3976 namespace: Namespace)
3978 // First, search children.
3979 build_reduced_graph::populate_module_if_necessary(self, &containing_module);
3981 match containing_module.children.borrow().get(&name) {
3982 Some(child_name_bindings) => {
3983 match child_name_bindings.def_for_namespace(namespace) {
3985 // Found it. Stop the search here.
3986 let p = child_name_bindings.defined_in_public_namespace(
3988 let lp = if p {LastMod(AllPublic)} else {
3989 LastMod(DependsOn(def.def_id()))
3991 return ChildNameDefinition(def, lp);
3999 // Next, search import resolutions.
4000 match containing_module.import_resolutions.borrow().get(&name) {
4001 Some(import_resolution) if import_resolution.is_public => {
4002 if let Some(target) = (*import_resolution).target_for_namespace(namespace) {
4003 match target.bindings.def_for_namespace(namespace) {
4006 let id = import_resolution.id(namespace);
4007 // track imports and extern crates as well
4008 self.used_imports.insert((id, namespace));
4009 self.record_import_use(id, name);
4010 match target.target_module.def_id.get() {
4011 Some(DefId{krate: kid, ..}) => {
4012 self.used_crates.insert(kid);
4016 return ImportNameDefinition(def, LastMod(AllPublic));
4019 // This can happen with external impls, due to
4020 // the imperfect way we read the metadata.
4025 Some(..) | None => {} // Continue.
4028 // Finally, search through external children.
4029 if namespace == TypeNS {
4030 if let Some(module) = containing_module.external_module_children.borrow()
4031 .get(&name).cloned() {
4032 if let Some(def_id) = module.def_id.get() {
4033 // track used crates
4034 self.used_crates.insert(def_id.krate);
4035 let lp = if module.is_public {LastMod(AllPublic)} else {
4036 LastMod(DependsOn(def_id))
4038 return ChildNameDefinition(DefMod(def_id), lp);
4043 return NoNameDefinition;
4046 // resolve a "module-relative" path, e.g. a::b::c
4047 fn resolve_module_relative_path(&mut self,
4049 namespace: Namespace)
4050 -> Option<(Def, LastPrivate)> {
4051 let module_path = path.segments.init().iter()
4052 .map(|ps| ps.identifier.name)
4053 .collect::<Vec<_>>();
4055 let containing_module;
4057 let module = self.current_module.clone();
4058 match self.resolve_module_path(module,
4064 let (span, msg) = match err {
4065 Some((span, msg)) => (span, msg),
4067 let msg = format!("Use of undeclared type or module `{}`",
4068 self.names_to_string(module_path.as_slice()));
4073 self.resolve_error(span, format!("failed to resolve. {}",
4077 Indeterminate => panic!("indeterminate unexpected"),
4078 Success((resulting_module, resulting_last_private)) => {
4079 containing_module = resulting_module;
4080 last_private = resulting_last_private;
4084 let name = path.segments.last().unwrap().identifier.name;
4085 let def = match self.resolve_definition_of_name_in_module(containing_module.clone(),
4088 NoNameDefinition => {
4089 // We failed to resolve the name. Report an error.
4092 ChildNameDefinition(def, lp) | ImportNameDefinition(def, lp) => {
4093 (def, last_private.or(lp))
4096 if let Some(DefId{krate: kid, ..}) = containing_module.def_id.get() {
4097 self.used_crates.insert(kid);
4102 /// Invariant: This must be called only during main resolution, not during
4103 /// import resolution.
4104 fn resolve_crate_relative_path(&mut self,
4106 namespace: Namespace)
4107 -> Option<(Def, LastPrivate)> {
4108 let module_path = path.segments.init().iter()
4109 .map(|ps| ps.identifier.name)
4110 .collect::<Vec<_>>();
4112 let root_module = self.graph_root.get_module();
4114 let containing_module;
4116 match self.resolve_module_path_from_root(root_module,
4121 LastMod(AllPublic)) {
4123 let (span, msg) = match err {
4124 Some((span, msg)) => (span, msg),
4126 let msg = format!("Use of undeclared module `::{}`",
4127 self.names_to_string(module_path[]));
4132 self.resolve_error(span, format!("failed to resolve. {}",
4138 panic!("indeterminate unexpected");
4141 Success((resulting_module, resulting_last_private)) => {
4142 containing_module = resulting_module;
4143 last_private = resulting_last_private;
4147 let name = path.segments.last().unwrap().identifier.name;
4148 match self.resolve_definition_of_name_in_module(containing_module,
4151 NoNameDefinition => {
4152 // We failed to resolve the name. Report an error.
4155 ChildNameDefinition(def, lp) | ImportNameDefinition(def, lp) => {
4156 return Some((def, last_private.or(lp)));
4161 fn resolve_identifier_in_local_ribs(&mut self,
4163 namespace: Namespace,
4166 // Check the local set of ribs.
4167 let search_result = match namespace {
4169 let renamed = mtwt::resolve(ident);
4170 self.search_ribs(self.value_ribs.as_slice(), renamed, span)
4173 let name = ident.name;
4174 self.search_ribs(self.type_ribs[], name, span)
4178 match search_result {
4179 Some(DlDef(def)) => {
4180 debug!("(resolving path in local ribs) resolved `{}` to \
4182 token::get_ident(ident),
4186 Some(DlField) | Some(DlImpl(_)) | None => {
4192 fn resolve_item_by_name_in_lexical_scope(&mut self,
4194 namespace: Namespace)
4195 -> Option<(Def, LastPrivate)> {
4197 let module = self.current_module.clone();
4198 match self.resolve_item_in_lexical_scope(module,
4201 Success((target, _)) => {
4202 match (*target.bindings).def_for_namespace(namespace) {
4204 // This can happen if we were looking for a type and
4205 // found a module instead. Modules don't have defs.
4206 debug!("(resolving item path by identifier in lexical \
4207 scope) failed to resolve {} after success...",
4208 token::get_name(name));
4212 debug!("(resolving item path in lexical scope) \
4213 resolved `{}` to item",
4214 token::get_name(name));
4215 // This lookup is "all public" because it only searched
4216 // for one identifier in the current module (couldn't
4217 // have passed through reexports or anything like that.
4218 return Some((def, LastMod(AllPublic)));
4223 panic!("unexpected indeterminate result");
4227 Some((span, msg)) =>
4228 self.resolve_error(span, format!("failed to resolve. {}",
4233 debug!("(resolving item path by identifier in lexical scope) \
4234 failed to resolve {}", token::get_name(name));
4240 fn with_no_errors<T, F>(&mut self, f: F) -> T where
4241 F: FnOnce(&mut Resolver) -> T,
4243 self.emit_errors = false;
4245 self.emit_errors = true;
4249 fn resolve_error(&self, span: Span, s: &str) {
4250 if self.emit_errors {
4251 self.session.span_err(span, s);
4255 fn find_fallback_in_self_type(&mut self, name: Name) -> FallbackSuggestion {
4256 fn extract_path_and_node_id(t: &Ty, allow: FallbackChecks)
4257 -> Option<(Path, NodeId, FallbackChecks)> {
4259 TyPath(ref path, node_id) => Some((path.clone(), node_id, allow)),
4260 TyPtr(ref mut_ty) => extract_path_and_node_id(&*mut_ty.ty, OnlyTraitAndStatics),
4261 TyRptr(_, ref mut_ty) => extract_path_and_node_id(&*mut_ty.ty, allow),
4262 // This doesn't handle the remaining `Ty` variants as they are not
4263 // that commonly the self_type, it might be interesting to provide
4264 // support for those in future.
4269 fn get_module(this: &mut Resolver, span: Span, name_path: &[ast::Name])
4270 -> Option<Rc<Module>> {
4271 let root = this.current_module.clone();
4272 let last_name = name_path.last().unwrap();
4274 if name_path.len() == 1 {
4275 match this.primitive_type_table.primitive_types.get(last_name) {
4278 match this.current_module.children.borrow().get(last_name) {
4279 Some(child) => child.get_module_if_available(),
4285 match this.resolve_module_path(root,
4290 Success((module, _)) => Some(module),
4296 let (path, node_id, allowed) = match self.current_self_type {
4297 Some(ref ty) => match extract_path_and_node_id(ty, Everything) {
4299 None => return NoSuggestion,
4301 None => return NoSuggestion,
4304 if allowed == Everything {
4305 // Look for a field with the same name in the current self_type.
4306 match self.def_map.borrow().get(&node_id) {
4307 Some(&DefTy(did, _))
4308 | Some(&DefStruct(did))
4309 | Some(&DefVariant(_, did, _)) => match self.structs.get(&did) {
4312 if fields.iter().any(|&field_name| name == field_name) {
4317 _ => {} // Self type didn't resolve properly
4321 let name_path = path.segments.iter().map(|seg| seg.identifier.name).collect::<Vec<_>>();
4323 // Look for a method in the current self type's impl module.
4324 match get_module(self, path.span, name_path[]) {
4325 Some(module) => match module.children.borrow().get(&name) {
4327 let p_str = self.path_names_to_string(&path);
4328 match binding.def_for_namespace(ValueNS) {
4329 Some(DefStaticMethod(_, provenance)) => {
4331 FromImpl(_) => return StaticMethod(p_str),
4332 FromTrait(_) => unreachable!()
4335 Some(DefMethod(_, None, _)) if allowed == Everything => return Method,
4336 Some(DefMethod(_, Some(_), _)) => return TraitItem,
4345 // Look for a method in the current trait.
4346 match self.current_trait_ref {
4347 Some((did, ref trait_ref)) => {
4348 let path_str = self.path_names_to_string(&trait_ref.path);
4350 match self.trait_item_map.get(&(name, did)) {
4351 Some(&StaticMethodTraitItemKind) => {
4352 return TraitMethod(path_str)
4354 Some(_) => return TraitItem,
4364 fn find_best_match_for_name(&mut self, name: &str, max_distance: uint)
4366 let this = &mut *self;
4368 let mut maybes: Vec<token::InternedString> = Vec::new();
4369 let mut values: Vec<uint> = Vec::new();
4371 for rib in this.value_ribs.iter().rev() {
4372 for (&k, _) in rib.bindings.iter() {
4373 maybes.push(token::get_name(k));
4374 values.push(uint::MAX);
4378 let mut smallest = 0;
4379 for (i, other) in maybes.iter().enumerate() {
4380 values[i] = lev_distance(name, other.get());
4382 if values[i] <= values[smallest] {
4387 if values.len() > 0 &&
4388 values[smallest] != uint::MAX &&
4389 values[smallest] < name.len() + 2 &&
4390 values[smallest] <= max_distance &&
4391 name != maybes[smallest].get() {
4393 Some(maybes[smallest].get().to_string())
4400 fn resolve_expr(&mut self, expr: &Expr) {
4401 // First, record candidate traits for this expression if it could
4402 // result in the invocation of a method call.
4404 self.record_candidate_traits_for_expr_if_necessary(expr);
4406 // Next, resolve the node.
4408 // The interpretation of paths depends on whether the path has
4409 // multiple elements in it or not.
4411 ExprPath(ref path) => {
4412 // This is a local path in the value namespace. Walk through
4413 // scopes looking for it.
4415 let path_name = self.path_names_to_string(path);
4417 match self.resolve_path(expr.id, path, ValueNS, true) {
4418 // Check if struct variant
4419 Some((DefVariant(_, _, true), _)) => {
4420 self.resolve_error(expr.span,
4421 format!("`{}` is a struct variant name, but \
4423 uses it like a function name",
4424 path_name).as_slice());
4426 self.session.span_help(expr.span,
4427 format!("Did you mean to write: \
4428 `{} {{ /* fields */ }}`?",
4429 path_name).as_slice());
4432 // Write the result into the def map.
4433 debug!("(resolving expr) resolved `{}`",
4436 self.record_def(expr.id, def);
4439 // Be helpful if the name refers to a struct
4440 // (The pattern matching def_tys where the id is in self.structs
4441 // matches on regular structs while excluding tuple- and enum-like
4442 // structs, which wouldn't result in this error.)
4443 match self.with_no_errors(|this|
4444 this.resolve_path(expr.id, path, TypeNS, false)) {
4445 Some((DefTy(struct_id, _), _))
4446 if self.structs.contains_key(&struct_id) => {
4447 self.resolve_error(expr.span,
4448 format!("`{}` is a structure name, but \
4450 uses it like a function name",
4451 path_name).as_slice());
4453 self.session.span_help(expr.span,
4454 format!("Did you mean to write: \
4455 `{} {{ /* fields */ }}`?",
4456 path_name).as_slice());
4460 let mut method_scope = false;
4461 self.value_ribs.iter().rev().all(|rib| {
4462 let res = match *rib {
4463 Rib { bindings: _, kind: MethodRibKind(_, _) } => true,
4464 Rib { bindings: _, kind: ItemRibKind } => false,
4465 _ => return true, // Keep advancing
4469 false // Stop advancing
4472 if method_scope && token::get_name(self.self_name).get()
4476 "`self` is not available \
4477 in a static method. Maybe a \
4478 `self` argument is missing?");
4480 let last_name = path.segments.last().unwrap().identifier.name;
4481 let mut msg = match self.find_fallback_in_self_type(last_name) {
4483 // limit search to 5 to reduce the number
4484 // of stupid suggestions
4485 self.find_best_match_for_name(path_name.as_slice(), 5)
4486 .map_or("".to_string(),
4487 |x| format!("`{}`", x))
4490 format!("`self.{}`", path_name),
4493 format!("to call `self.{}`", path_name),
4494 TraitMethod(path_str)
4495 | StaticMethod(path_str) =>
4496 format!("to call `{}::{}`", path_str, path_name)
4500 msg = format!(". Did you mean {}?", msg)
4505 format!("unresolved name `{}`{}",
4514 visit::walk_expr(self, expr);
4517 ExprClosure(capture_clause, _, ref fn_decl, ref block) => {
4518 self.capture_mode_map.insert(expr.id, capture_clause);
4519 self.resolve_function(ClosureRibKind(expr.id, ast::DUMMY_NODE_ID),
4520 Some(&**fn_decl), NoTypeParameters,
4524 ExprStruct(ref path, _, _) => {
4525 // Resolve the path to the structure it goes to. We don't
4526 // check to ensure that the path is actually a structure; that
4527 // is checked later during typeck.
4528 match self.resolve_path(expr.id, path, TypeNS, false) {
4529 Some(definition) => self.record_def(expr.id, definition),
4531 debug!("(resolving expression) didn't find struct \
4533 let msg = format!("`{}` does not name a structure",
4534 self.path_names_to_string(path));
4535 self.resolve_error(path.span, msg[]);
4539 visit::walk_expr(self, expr);
4542 ExprLoop(_, Some(label)) | ExprWhile(_, _, Some(label)) => {
4543 self.with_label_rib(|this| {
4544 let def_like = DlDef(DefLabel(expr.id));
4547 let rib = this.label_ribs.last_mut().unwrap();
4548 let renamed = mtwt::resolve(label);
4549 rib.bindings.insert(renamed, def_like);
4552 visit::walk_expr(this, expr);
4556 ExprForLoop(ref pattern, ref head, ref body, optional_label) => {
4557 self.resolve_expr(&**head);
4559 self.value_ribs.push(Rib::new(NormalRibKind));
4561 self.resolve_pattern(&**pattern,
4562 LocalIrrefutableMode,
4563 &mut HashMap::new());
4565 match optional_label {
4569 .push(Rib::new(NormalRibKind));
4570 let def_like = DlDef(DefLabel(expr.id));
4573 let rib = self.label_ribs.last_mut().unwrap();
4574 let renamed = mtwt::resolve(label);
4575 rib.bindings.insert(renamed, def_like);
4580 self.resolve_block(&**body);
4582 if optional_label.is_some() {
4583 drop(self.label_ribs.pop())
4586 self.value_ribs.pop();
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().iter() {
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().iter() {
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.set(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().iter() {
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.iter() {
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 capture_mode_map: RefCell<CaptureModeMap>,
4830 pub export_map: ExportMap,
4831 pub trait_map: TraitMap,
4832 pub external_exports: ExternalExports,
4833 pub last_private_map: LastPrivateMap,
4834 pub glob_map: Option<GlobMap>
4837 #[derive(PartialEq,Copy)]
4838 pub enum MakeGlobMap {
4843 /// Entry point to crate resolution.
4844 pub fn resolve_crate<'a, 'tcx>(session: &'a Session,
4845 ast_map: &'a ast_map::Map<'tcx>,
4848 make_glob_map: MakeGlobMap)
4850 let mut resolver = Resolver::new(session, ast_map, krate.span, make_glob_map);
4852 build_reduced_graph::build_reduced_graph(&mut resolver, krate);
4853 session.abort_if_errors();
4855 resolver.resolve_imports();
4856 session.abort_if_errors();
4858 record_exports::record(&mut resolver);
4859 session.abort_if_errors();
4861 resolver.resolve_crate(krate);
4862 session.abort_if_errors();
4864 check_unused::check_crate(&mut resolver, krate);
4867 def_map: resolver.def_map,
4868 freevars: resolver.freevars,
4869 capture_mode_map: RefCell::new(resolver.capture_mode_map),
4870 export_map: resolver.export_map,
4871 trait_map: resolver.trait_map,
4872 external_exports: resolver.external_exports,
4873 last_private_map: resolver.last_private,
4874 glob_map: if resolver.make_glob_map {
4875 Some(resolver.glob_map)