1 // Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
11 #![crate_name = "rustc_resolve"]
13 #![crate_type = "dylib"]
14 #![crate_type = "rlib"]
15 #![doc(html_logo_url = "http://www.rust-lang.org/logos/rust-logo-128x128-blk-v2.png",
16 html_favicon_url = "http://www.rust-lang.org/favicon.ico",
17 html_root_url = "http://doc.rust-lang.org/nightly/")]
19 #![feature(globs, phase, slicing_syntax)]
20 #![feature(rustc_diagnostic_macros)]
21 #![feature(associated_types)]
22 #![feature(old_orphan_check)]
25 #[phase(plugin, link)]
33 #[phase(plugin, link)]
42 use self::PatternBindingMode::*;
43 use self::Namespace::*;
44 use self::NamespaceResult::*;
45 use self::NameDefinition::*;
46 use self::ImportDirectiveSubclass::*;
47 use self::ResolveResult::*;
48 use self::FallbackSuggestion::*;
49 use self::TypeParameters::*;
51 use self::MethodSort::*;
52 use self::UseLexicalScopeFlag::*;
53 use self::ModulePrefixResult::*;
54 use self::NameSearchType::*;
55 use self::BareIdentifierPatternResolution::*;
56 use self::ParentLink::*;
57 use self::ModuleKind::*;
58 use self::TraitReferenceType::*;
59 use self::FallbackChecks::*;
61 use rustc::session::Session;
63 use rustc::metadata::csearch;
64 use rustc::metadata::decoder::{DefLike, DlDef, DlField, DlImpl};
65 use rustc::middle::def::*;
66 use rustc::middle::lang_items::LanguageItems;
67 use rustc::middle::pat_util::pat_bindings;
68 use rustc::middle::privacy::*;
69 use rustc::middle::subst::{ParamSpace, FnSpace, TypeSpace};
70 use rustc::middle::ty::{CaptureModeMap, Freevar, FreevarMap, TraitMap, GlobMap};
71 use rustc::util::nodemap::{NodeMap, NodeSet, DefIdSet, FnvHashMap};
72 use rustc::util::lev_distance::lev_distance;
74 use syntax::ast::{Arm, BindByRef, BindByValue, BindingMode, Block, Crate, CrateNum};
75 use syntax::ast::{DefId, Expr, ExprAgain, ExprBreak, ExprField};
76 use syntax::ast::{ExprClosure, ExprForLoop, ExprLoop, ExprWhile, ExprMethodCall};
77 use syntax::ast::{ExprPath, ExprStruct, FnDecl};
78 use syntax::ast::{ForeignItemFn, ForeignItemStatic, Generics};
79 use syntax::ast::{Ident, ImplItem, Item, ItemConst, ItemEnum, ItemFn};
80 use syntax::ast::{ItemForeignMod, ItemImpl, ItemMac, ItemMod, ItemStatic};
81 use syntax::ast::{ItemStruct, ItemTrait, ItemTy, Local, LOCAL_CRATE};
82 use syntax::ast::{MethodImplItem, Mod, Name, NodeId};
83 use syntax::ast::{Pat, PatEnum, PatIdent, PatLit};
84 use syntax::ast::{PatRange, PatStruct, Path};
85 use syntax::ast::{PolyTraitRef, PrimTy, SelfExplicit};
86 use syntax::ast::{RegionTyParamBound, StructField};
87 use syntax::ast::{TraitRef, TraitTyParamBound};
88 use syntax::ast::{Ty, TyBool, TyChar, TyF32};
89 use syntax::ast::{TyF64, TyFloat, TyI, TyI8, TyI16, TyI32, TyI64, TyInt, TyObjectSum};
90 use syntax::ast::{TyParam, TyParamBound, TyPath, TyPtr, TyPolyTraitRef, TyQPath};
91 use syntax::ast::{TyRptr, TyStr, TyU, TyU8, TyU16, TyU32, TyU64, TyUint};
92 use syntax::ast::{TypeImplItem};
95 use syntax::ast_util::{PostExpansionMethod, local_def, walk_pat};
96 use syntax::attr::AttrMetaMethods;
97 use syntax::ext::mtwt;
98 use syntax::parse::token::{self, special_names, special_idents};
99 use syntax::codemap::{Span, Pos};
100 use syntax::owned_slice::OwnedSlice;
101 use syntax::visit::{self, Visitor};
103 use std::collections::{HashMap, HashSet};
104 use std::collections::hash_map::Entry::{Occupied, Vacant};
105 use std::cell::{Cell, RefCell};
107 use std::mem::replace;
108 use std::rc::{Rc, Weak};
113 mod build_reduced_graph;
118 binding_mode: BindingMode,
121 // Map from the name in a pattern to its binding mode.
122 type BindingMap = HashMap<Name, BindingInfo>;
124 #[derive(Copy, PartialEq)]
125 enum PatternBindingMode {
127 LocalIrrefutableMode,
128 ArgumentIrrefutableMode,
131 #[derive(Copy, PartialEq, Eq, Hash, Show)]
137 /// A NamespaceResult represents the result of resolving an import in
138 /// a particular namespace. The result is either definitely-resolved,
139 /// definitely- unresolved, or unknown.
141 enum NamespaceResult {
142 /// Means that resolve hasn't gathered enough information yet to determine
143 /// whether the name is bound in this namespace. (That is, it hasn't
144 /// resolved all `use` directives yet.)
146 /// Means that resolve has determined that the name is definitely
147 /// not bound in the namespace.
149 /// Means that resolve has determined that the name is bound in the Module
150 /// argument, and specified by the NameBindings argument.
151 BoundResult(Rc<Module>, Rc<NameBindings>)
154 impl NamespaceResult {
155 fn is_unknown(&self) -> bool {
157 UnknownResult => true,
161 fn is_unbound(&self) -> bool {
163 UnboundResult => true,
169 enum NameDefinition {
170 NoNameDefinition, //< The name was unbound.
171 ChildNameDefinition(Def, LastPrivate), //< The name identifies an immediate child.
172 ImportNameDefinition(Def, LastPrivate) //< The name identifies an import.
175 impl<'a, 'v, 'tcx> Visitor<'v> for Resolver<'a, 'tcx> {
176 fn visit_item(&mut self, item: &Item) {
177 self.resolve_item(item);
179 fn visit_arm(&mut self, arm: &Arm) {
180 self.resolve_arm(arm);
182 fn visit_block(&mut self, block: &Block) {
183 self.resolve_block(block);
185 fn visit_expr(&mut self, expr: &Expr) {
186 self.resolve_expr(expr);
188 fn visit_local(&mut self, local: &Local) {
189 self.resolve_local(local);
191 fn visit_ty(&mut self, ty: &Ty) {
192 self.resolve_type(ty);
196 /// Contains data for specific types of import directives.
198 enum ImportDirectiveSubclass {
199 SingleImport(Name /* target */, Name /* source */),
203 type ErrorMessage = Option<(Span, String)>;
205 enum ResolveResult<T> {
206 Failed(ErrorMessage), // Failed to resolve the name, optional helpful error message.
207 Indeterminate, // Couldn't determine due to unresolved globs.
208 Success(T) // Successfully resolved the import.
211 impl<T> ResolveResult<T> {
212 fn indeterminate(&self) -> bool {
213 match *self { Indeterminate => true, _ => false }
217 enum FallbackSuggestion {
222 StaticMethod(String),
227 enum TypeParameters<'a> {
233 // Identifies the things that these parameters
234 // were declared on (type, fn, etc)
237 // ID of the enclosing item.
240 // The kind of the rib used for type parameters.
244 // The rib kind controls the translation of local
245 // definitions (`DefLocal`) to upvars (`DefUpvar`).
246 #[derive(Copy, Show)]
248 // No translation needs to be applied.
251 // We passed through a closure scope at the given node ID.
252 // Translate upvars as appropriate.
253 ClosureRibKind(NodeId /* func id */, NodeId /* body id if proc or unboxed */),
255 // We passed through an impl or trait and are now in one of its
256 // methods. Allow references to ty params that impl or trait
257 // binds. Disallow any other upvars (including other ty params that are
259 // parent; method itself
260 MethodRibKind(NodeId, MethodSort),
262 // We passed through an item scope. Disallow upvars.
265 // We're in a constant item. Can't refer to dynamic stuff.
269 // Methods can be required or provided. RequiredMethod methods only occur in traits.
270 #[derive(Copy, Show)]
273 ProvidedMethod(NodeId)
277 enum UseLexicalScopeFlag {
282 enum ModulePrefixResult {
284 PrefixFound(Rc<Module>, uint)
287 #[derive(Copy, PartialEq)]
288 enum NameSearchType {
289 /// We're doing a name search in order to resolve a `use` directive.
292 /// We're doing a name search in order to resolve a path type, a path
293 /// expression, or a path pattern.
298 enum BareIdentifierPatternResolution {
299 FoundStructOrEnumVariant(Def, LastPrivate),
300 FoundConst(Def, LastPrivate),
301 BareIdentifierPatternUnresolved
307 bindings: HashMap<Name, DefLike>,
312 fn new(kind: RibKind) -> Rib {
314 bindings: HashMap::new(),
320 /// Whether an import can be shadowed by another import.
321 #[derive(Show,PartialEq,Clone,Copy)]
327 /// One import directive.
329 struct ImportDirective {
330 module_path: Vec<Name>,
331 subclass: ImportDirectiveSubclass,
334 is_public: bool, // see note in ImportResolution about how to use this
335 shadowable: Shadowable,
338 impl ImportDirective {
339 fn new(module_path: Vec<Name> ,
340 subclass: ImportDirectiveSubclass,
344 shadowable: Shadowable)
347 module_path: module_path,
351 is_public: is_public,
352 shadowable: shadowable,
357 /// The item that an import resolves to.
358 #[derive(Clone,Show)]
360 target_module: Rc<Module>,
361 bindings: Rc<NameBindings>,
362 shadowable: Shadowable,
366 fn new(target_module: Rc<Module>,
367 bindings: Rc<NameBindings>,
368 shadowable: Shadowable)
371 target_module: target_module,
373 shadowable: shadowable,
378 /// An ImportResolution represents a particular `use` directive.
380 struct ImportResolution {
381 /// Whether this resolution came from a `use` or a `pub use`. Note that this
382 /// should *not* be used whenever resolution is being performed, this is
383 /// only looked at for glob imports statements currently. Privacy testing
384 /// occurs during a later phase of compilation.
387 // The number of outstanding references to this name. When this reaches
388 // zero, outside modules can count on the targets being correct. Before
389 // then, all bets are off; future imports could override this name.
390 outstanding_references: uint,
392 /// The value that this `use` directive names, if there is one.
393 value_target: Option<Target>,
394 /// The source node of the `use` directive leading to the value target
398 /// The type that this `use` directive names, if there is one.
399 type_target: Option<Target>,
400 /// The source node of the `use` directive leading to the type target
405 impl ImportResolution {
406 fn new(id: NodeId, is_public: bool) -> ImportResolution {
410 outstanding_references: 0,
413 is_public: is_public,
417 fn target_for_namespace(&self, namespace: Namespace)
420 TypeNS => self.type_target.clone(),
421 ValueNS => self.value_target.clone(),
425 fn id(&self, namespace: Namespace) -> NodeId {
427 TypeNS => self.type_id,
428 ValueNS => self.value_id,
432 fn shadowable(&self, namespace: Namespace) -> Shadowable {
433 let target = self.target_for_namespace(namespace);
434 if target.is_none() {
435 return Shadowable::Always;
438 target.unwrap().shadowable
441 fn set_target_and_id(&mut self,
442 namespace: Namespace,
443 target: Option<Target>,
447 self.type_target = target;
451 self.value_target = target;
458 /// The link from a module up to its nearest parent node.
459 #[derive(Clone,Show)]
462 ModuleParentLink(Weak<Module>, Name),
463 BlockParentLink(Weak<Module>, NodeId)
466 /// The type of module this is.
467 #[derive(Copy, PartialEq, Show)]
476 /// One node in the tree of modules.
478 parent_link: ParentLink,
479 def_id: Cell<Option<DefId>>,
480 kind: Cell<ModuleKind>,
483 children: RefCell<HashMap<Name, Rc<NameBindings>>>,
484 imports: RefCell<Vec<ImportDirective>>,
486 // The external module children of this node that were declared with
488 external_module_children: RefCell<HashMap<Name, Rc<Module>>>,
490 // The anonymous children of this node. Anonymous children are pseudo-
491 // modules that are implicitly created around items contained within
494 // For example, if we have this:
502 // There will be an anonymous module created around `g` with the ID of the
503 // entry block for `f`.
504 anonymous_children: RefCell<NodeMap<Rc<Module>>>,
506 // The status of resolving each import in this module.
507 import_resolutions: RefCell<HashMap<Name, ImportResolution>>,
509 // The number of unresolved globs that this module exports.
510 glob_count: Cell<uint>,
512 // The index of the import we're resolving.
513 resolved_import_count: Cell<uint>,
515 // Whether this module is populated. If not populated, any attempt to
516 // access the children must be preceded with a
517 // `populate_module_if_necessary` call.
518 populated: Cell<bool>,
522 fn new(parent_link: ParentLink,
523 def_id: Option<DefId>,
529 parent_link: parent_link,
530 def_id: Cell::new(def_id),
531 kind: Cell::new(kind),
532 is_public: is_public,
533 children: RefCell::new(HashMap::new()),
534 imports: RefCell::new(Vec::new()),
535 external_module_children: RefCell::new(HashMap::new()),
536 anonymous_children: RefCell::new(NodeMap::new()),
537 import_resolutions: RefCell::new(HashMap::new()),
538 glob_count: Cell::new(0),
539 resolved_import_count: Cell::new(0),
540 populated: Cell::new(!external),
544 fn all_imports_resolved(&self) -> bool {
545 self.imports.borrow().len() == self.resolved_import_count.get()
549 impl fmt::Show for Module {
550 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
551 write!(f, "{}, kind: {}, {}",
554 if self.is_public { "public" } else { "private" } )
560 flags DefModifiers: u8 {
561 const PUBLIC = 0b0000_0001,
562 const IMPORTABLE = 0b0000_0010,
566 // Records a possibly-private type definition.
567 #[derive(Clone,Show)]
569 modifiers: DefModifiers, // see note in ImportResolution about how to use this
570 module_def: Option<Rc<Module>>,
571 type_def: Option<Def>,
572 type_span: Option<Span>
575 // Records a possibly-private value definition.
576 #[derive(Clone, Copy, Show)]
578 modifiers: DefModifiers, // see note in ImportResolution about how to use this
580 value_span: Option<Span>,
583 // Records the definitions (at most one for each namespace) that a name is
586 struct NameBindings {
587 type_def: RefCell<Option<TypeNsDef>>, //< Meaning in type namespace.
588 value_def: RefCell<Option<ValueNsDef>>, //< Meaning in value namespace.
591 /// Ways in which a trait can be referenced
593 enum TraitReferenceType {
594 TraitImplementation, // impl SomeTrait for T { ... }
595 TraitDerivation, // trait T : SomeTrait { ... }
596 TraitBoundingTypeParameter, // fn f<T:SomeTrait>() { ... }
597 TraitObject, // Box<for<'a> SomeTrait>
598 TraitQPath, // <T as SomeTrait>::
602 fn new() -> NameBindings {
604 type_def: RefCell::new(None),
605 value_def: RefCell::new(None),
609 /// Creates a new module in this set of name bindings.
610 fn define_module(&self,
611 parent_link: ParentLink,
612 def_id: Option<DefId>,
617 // Merges the module with the existing type def or creates a new one.
618 let modifiers = if is_public { PUBLIC } else { DefModifiers::empty() } | IMPORTABLE;
619 let module_ = Rc::new(Module::new(parent_link,
624 let type_def = self.type_def.borrow().clone();
627 *self.type_def.borrow_mut() = Some(TypeNsDef {
628 modifiers: modifiers,
629 module_def: Some(module_),
635 *self.type_def.borrow_mut() = Some(TypeNsDef {
636 modifiers: modifiers,
637 module_def: Some(module_),
639 type_def: type_def.type_def
645 /// Sets the kind of the module, creating a new one if necessary.
646 fn set_module_kind(&self,
647 parent_link: ParentLink,
648 def_id: Option<DefId>,
653 let modifiers = if is_public { PUBLIC } else { DefModifiers::empty() } | IMPORTABLE;
654 let type_def = self.type_def.borrow().clone();
657 let module = Module::new(parent_link,
662 *self.type_def.borrow_mut() = Some(TypeNsDef {
663 modifiers: modifiers,
664 module_def: Some(Rc::new(module)),
670 match type_def.module_def {
672 let module = Module::new(parent_link,
677 *self.type_def.borrow_mut() = Some(TypeNsDef {
678 modifiers: modifiers,
679 module_def: Some(Rc::new(module)),
680 type_def: type_def.type_def,
684 Some(module_def) => module_def.kind.set(kind),
690 /// Records a type definition.
691 fn define_type(&self, def: Def, sp: Span, modifiers: DefModifiers) {
692 debug!("defining type for def {} with modifiers {}", def, modifiers);
693 // Merges the type with the existing type def or creates a new one.
694 let type_def = self.type_def.borrow().clone();
697 *self.type_def.borrow_mut() = Some(TypeNsDef {
701 modifiers: modifiers,
705 *self.type_def.borrow_mut() = Some(TypeNsDef {
706 module_def: type_def.module_def,
709 modifiers: modifiers,
715 /// Records a value definition.
716 fn define_value(&self, def: Def, sp: Span, modifiers: DefModifiers) {
717 debug!("defining value for def {} with modifiers {}", def, modifiers);
718 *self.value_def.borrow_mut() = Some(ValueNsDef {
720 value_span: Some(sp),
721 modifiers: modifiers,
725 /// Returns the module node if applicable.
726 fn get_module_if_available(&self) -> Option<Rc<Module>> {
727 match *self.type_def.borrow() {
728 Some(ref type_def) => type_def.module_def.clone(),
733 /// Returns the module node. Panics if this node does not have a module
735 fn get_module(&self) -> Rc<Module> {
736 match self.get_module_if_available() {
738 panic!("get_module called on a node with no module \
741 Some(module_def) => module_def
745 fn defined_in_namespace(&self, namespace: Namespace) -> bool {
747 TypeNS => return self.type_def.borrow().is_some(),
748 ValueNS => return self.value_def.borrow().is_some()
752 fn defined_in_public_namespace(&self, namespace: Namespace) -> bool {
753 self.defined_in_namespace_with(namespace, PUBLIC)
756 fn defined_in_namespace_with(&self, namespace: Namespace, modifiers: DefModifiers) -> bool {
758 TypeNS => match *self.type_def.borrow() {
759 Some(ref def) => def.modifiers.contains(modifiers), None => false
761 ValueNS => match *self.value_def.borrow() {
762 Some(ref def) => def.modifiers.contains(modifiers), None => false
767 fn def_for_namespace(&self, namespace: Namespace) -> Option<Def> {
770 match *self.type_def.borrow() {
772 Some(ref type_def) => {
773 match type_def.type_def {
774 Some(type_def) => Some(type_def),
776 match type_def.module_def {
777 Some(ref module) => {
778 match module.def_id.get() {
779 Some(did) => Some(DefMod(did)),
791 match *self.value_def.borrow() {
793 Some(value_def) => Some(value_def.def)
799 fn span_for_namespace(&self, namespace: Namespace) -> Option<Span> {
800 if self.defined_in_namespace(namespace) {
803 match *self.type_def.borrow() {
805 Some(ref type_def) => type_def.type_span
809 match *self.value_def.borrow() {
811 Some(ref value_def) => value_def.value_span
821 /// Interns the names of the primitive types.
822 struct PrimitiveTypeTable {
823 primitive_types: HashMap<Name, PrimTy>,
826 impl PrimitiveTypeTable {
827 fn new() -> PrimitiveTypeTable {
828 let mut table = PrimitiveTypeTable {
829 primitive_types: HashMap::new()
832 table.intern("bool", TyBool);
833 table.intern("char", TyChar);
834 table.intern("f32", TyFloat(TyF32));
835 table.intern("f64", TyFloat(TyF64));
836 table.intern("int", TyInt(TyI));
837 table.intern("i8", TyInt(TyI8));
838 table.intern("i16", TyInt(TyI16));
839 table.intern("i32", TyInt(TyI32));
840 table.intern("i64", TyInt(TyI64));
841 table.intern("str", TyStr);
842 table.intern("uint", TyUint(TyU));
843 table.intern("u8", TyUint(TyU8));
844 table.intern("u16", TyUint(TyU16));
845 table.intern("u32", TyUint(TyU32));
846 table.intern("u64", TyUint(TyU64));
851 fn intern(&mut self, string: &str, primitive_type: PrimTy) {
852 self.primitive_types.insert(token::intern(string), primitive_type);
856 /// The main resolver class.
857 struct Resolver<'a, 'tcx:'a> {
858 session: &'a Session,
860 ast_map: &'a ast_map::Map<'tcx>,
862 graph_root: NameBindings,
864 trait_item_map: FnvHashMap<(Name, DefId), TraitItemKind>,
866 structs: FnvHashMap<DefId, Vec<Name>>,
868 // The number of imports that are currently unresolved.
869 unresolved_imports: uint,
871 // The module that represents the current item scope.
872 current_module: Rc<Module>,
874 // The current set of local scopes, for values.
875 // FIXME #4948: Reuse ribs to avoid allocation.
876 value_ribs: Vec<Rib>,
878 // The current set of local scopes, for types.
881 // The current set of local scopes, for labels.
882 label_ribs: Vec<Rib>,
884 // The trait that the current context can refer to.
885 current_trait_ref: Option<(DefId, TraitRef)>,
887 // The current self type if inside an impl (used for better errors).
888 current_self_type: Option<Ty>,
890 // The ident for the keyword "self".
892 // The ident for the non-keyword "Self".
893 type_self_name: Name,
895 // The idents for the primitive types.
896 primitive_type_table: PrimitiveTypeTable,
899 freevars: RefCell<FreevarMap>,
900 freevars_seen: RefCell<NodeMap<NodeSet>>,
901 capture_mode_map: CaptureModeMap,
902 export_map: ExportMap,
904 external_exports: ExternalExports,
905 last_private: LastPrivateMap,
907 // Whether or not to print error messages. Can be set to true
908 // when getting additional info for error message suggestions,
909 // so as to avoid printing duplicate errors
913 // Maps imports to the names of items actually imported (this actually maps
914 // all imports, but only glob imports are actually interesting).
917 used_imports: HashSet<(NodeId, Namespace)>,
918 used_crates: HashSet<CrateNum>,
922 enum FallbackChecks {
928 impl<'a, 'tcx> Resolver<'a, 'tcx> {
929 fn new(session: &'a Session,
930 ast_map: &'a ast_map::Map<'tcx>,
932 make_glob_map: MakeGlobMap) -> Resolver<'a, 'tcx> {
933 let graph_root = NameBindings::new();
935 graph_root.define_module(NoParentLink,
936 Some(DefId { krate: 0, node: 0 }),
942 let current_module = graph_root.get_module();
949 // The outermost module has def ID 0; this is not reflected in the
952 graph_root: graph_root,
954 trait_item_map: FnvHashMap::new(),
955 structs: FnvHashMap::new(),
957 unresolved_imports: 0,
959 current_module: current_module,
960 value_ribs: Vec::new(),
961 type_ribs: Vec::new(),
962 label_ribs: Vec::new(),
964 current_trait_ref: None,
965 current_self_type: None,
967 self_name: special_names::self_,
968 type_self_name: special_names::type_self,
970 primitive_type_table: PrimitiveTypeTable::new(),
972 def_map: RefCell::new(NodeMap::new()),
973 freevars: RefCell::new(NodeMap::new()),
974 freevars_seen: RefCell::new(NodeMap::new()),
975 capture_mode_map: NodeMap::new(),
976 export_map: NodeMap::new(),
977 trait_map: NodeMap::new(),
978 used_imports: HashSet::new(),
979 used_crates: HashSet::new(),
980 external_exports: DefIdSet::new(),
981 last_private: NodeMap::new(),
984 make_glob_map: make_glob_map == MakeGlobMap::Yes,
985 glob_map: HashMap::new(),
991 // This is a fixed-point algorithm. We resolve imports until our efforts
992 // are stymied by an unresolved import; then we bail out of the current
993 // module and continue. We terminate successfully once no more imports
994 // remain or unsuccessfully when no forward progress in resolving imports
997 /// Resolves all imports for the crate. This method performs the fixed-
999 fn resolve_imports(&mut self) {
1001 let mut prev_unresolved_imports = 0;
1003 debug!("(resolving imports) iteration {}, {} imports left",
1004 i, self.unresolved_imports);
1006 let module_root = self.graph_root.get_module();
1007 self.resolve_imports_for_module_subtree(module_root.clone());
1009 if self.unresolved_imports == 0 {
1010 debug!("(resolving imports) success");
1014 if self.unresolved_imports == prev_unresolved_imports {
1015 self.report_unresolved_imports(module_root);
1020 prev_unresolved_imports = self.unresolved_imports;
1024 /// Attempts to resolve imports for the given module and all of its
1026 fn resolve_imports_for_module_subtree(&mut self, module_: Rc<Module>) {
1027 debug!("(resolving imports for module subtree) resolving {}",
1028 self.module_to_string(&*module_));
1029 let orig_module = replace(&mut self.current_module, module_.clone());
1030 self.resolve_imports_for_module(module_.clone());
1031 self.current_module = orig_module;
1033 build_reduced_graph::populate_module_if_necessary(self, &module_);
1034 for (_, child_node) in module_.children.borrow().iter() {
1035 match child_node.get_module_if_available() {
1039 Some(child_module) => {
1040 self.resolve_imports_for_module_subtree(child_module);
1045 for (_, child_module) in module_.anonymous_children.borrow().iter() {
1046 self.resolve_imports_for_module_subtree(child_module.clone());
1050 /// Attempts to resolve imports for the given module only.
1051 fn resolve_imports_for_module(&mut self, module: Rc<Module>) {
1052 if module.all_imports_resolved() {
1053 debug!("(resolving imports for module) all imports resolved for \
1055 self.module_to_string(&*module));
1059 let imports = module.imports.borrow();
1060 let import_count = imports.len();
1061 while module.resolved_import_count.get() < import_count {
1062 let import_index = module.resolved_import_count.get();
1063 let import_directive = &(*imports)[import_index];
1064 match self.resolve_import_for_module(module.clone(),
1067 let (span, help) = match err {
1068 Some((span, msg)) => (span, format!(". {}", msg)),
1069 None => (import_directive.span, String::new())
1071 let msg = format!("unresolved import `{}`{}",
1072 self.import_path_to_string(
1073 import_directive.module_path
1075 import_directive.subclass),
1077 self.resolve_error(span, msg[]);
1079 Indeterminate => break, // Bail out. We'll come around next time.
1080 Success(()) => () // Good. Continue.
1083 module.resolved_import_count
1084 .set(module.resolved_import_count.get() + 1);
1088 fn names_to_string(&self, names: &[Name]) -> String {
1089 let mut first = true;
1090 let mut result = String::new();
1091 for name in names.iter() {
1095 result.push_str("::")
1097 result.push_str(token::get_name(*name).get());
1102 fn path_names_to_string(&self, path: &Path) -> String {
1103 let names: Vec<ast::Name> = path.segments
1105 .map(|seg| seg.identifier.name)
1107 self.names_to_string(names[])
1110 fn import_directive_subclass_to_string(&mut self,
1111 subclass: ImportDirectiveSubclass)
1114 SingleImport(_, source) => {
1115 token::get_name(source).get().to_string()
1117 GlobImport => "*".to_string()
1121 fn import_path_to_string(&mut self,
1123 subclass: ImportDirectiveSubclass)
1125 if names.is_empty() {
1126 self.import_directive_subclass_to_string(subclass)
1129 self.names_to_string(names),
1130 self.import_directive_subclass_to_string(
1131 subclass))).to_string()
1136 fn record_import_use(&mut self, import_id: NodeId, name: Name) {
1137 if !self.make_glob_map {
1140 if self.glob_map.contains_key(&import_id) {
1141 self.glob_map[import_id].insert(name);
1145 let mut new_set = HashSet::new();
1146 new_set.insert(name);
1147 self.glob_map.insert(import_id, new_set);
1150 fn get_trait_name(&self, did: DefId) -> Name {
1151 if did.krate == LOCAL_CRATE {
1152 self.ast_map.expect_item(did.node).ident.name
1154 csearch::get_trait_name(&self.session.cstore, did)
1158 /// Attempts to resolve the given import. The return value indicates
1159 /// failure if we're certain the name does not exist, indeterminate if we
1160 /// don't know whether the name exists at the moment due to other
1161 /// currently-unresolved imports, or success if we know the name exists.
1162 /// If successful, the resolved bindings are written into the module.
1163 fn resolve_import_for_module(&mut self,
1164 module_: Rc<Module>,
1165 import_directive: &ImportDirective)
1166 -> ResolveResult<()> {
1167 let mut resolution_result = Failed(None);
1168 let module_path = &import_directive.module_path;
1170 debug!("(resolving import for module) resolving import `{}::...` in `{}`",
1171 self.names_to_string(module_path[]),
1172 self.module_to_string(&*module_));
1174 // First, resolve the module path for the directive, if necessary.
1175 let container = if module_path.len() == 0 {
1176 // Use the crate root.
1177 Some((self.graph_root.get_module(), LastMod(AllPublic)))
1179 match self.resolve_module_path(module_.clone(),
1181 DontUseLexicalScope,
1182 import_directive.span,
1185 resolution_result = Failed(err);
1189 resolution_result = Indeterminate;
1192 Success(container) => Some(container),
1198 Some((containing_module, lp)) => {
1199 // We found the module that the target is contained
1200 // within. Attempt to resolve the import within it.
1202 match import_directive.subclass {
1203 SingleImport(target, source) => {
1205 self.resolve_single_import(&*module_,
1214 self.resolve_glob_import(&*module_,
1223 // Decrement the count of unresolved imports.
1224 match resolution_result {
1226 assert!(self.unresolved_imports >= 1);
1227 self.unresolved_imports -= 1;
1230 // Nothing to do here; just return the error.
1234 // Decrement the count of unresolved globs if necessary. But only if
1235 // the resolution result is indeterminate -- otherwise we'll stop
1236 // processing imports here. (See the loop in
1237 // resolve_imports_for_module.)
1239 if !resolution_result.indeterminate() {
1240 match import_directive.subclass {
1242 assert!(module_.glob_count.get() >= 1);
1243 module_.glob_count.set(module_.glob_count.get() - 1);
1245 SingleImport(..) => {
1251 return resolution_result;
1254 fn create_name_bindings_from_module(module: Rc<Module>) -> NameBindings {
1256 type_def: RefCell::new(Some(TypeNsDef {
1257 modifiers: IMPORTABLE,
1258 module_def: Some(module),
1262 value_def: RefCell::new(None),
1266 fn resolve_single_import(&mut self,
1268 containing_module: Rc<Module>,
1271 directive: &ImportDirective,
1273 -> ResolveResult<()> {
1274 debug!("(resolving single import) resolving `{}` = `{}::{}` from \
1275 `{}` id {}, last private {}",
1276 token::get_name(target),
1277 self.module_to_string(&*containing_module),
1278 token::get_name(source),
1279 self.module_to_string(module_),
1285 LastImport {..} => {
1287 .span_bug(directive.span,
1288 "not expecting Import here, must be LastMod")
1292 // We need to resolve both namespaces for this to succeed.
1295 let mut value_result = UnknownResult;
1296 let mut type_result = UnknownResult;
1298 // Search for direct children of the containing module.
1299 build_reduced_graph::populate_module_if_necessary(self, &containing_module);
1301 match containing_module.children.borrow().get(&source) {
1305 Some(ref child_name_bindings) => {
1306 if child_name_bindings.defined_in_namespace(ValueNS) {
1307 debug!("(resolving single import) found value binding");
1308 value_result = BoundResult(containing_module.clone(),
1309 (*child_name_bindings).clone());
1311 if child_name_bindings.defined_in_namespace(TypeNS) {
1312 debug!("(resolving single import) found type binding");
1313 type_result = BoundResult(containing_module.clone(),
1314 (*child_name_bindings).clone());
1319 // Unless we managed to find a result in both namespaces (unlikely),
1320 // search imports as well.
1321 let mut value_used_reexport = false;
1322 let mut type_used_reexport = false;
1323 match (value_result.clone(), type_result.clone()) {
1324 (BoundResult(..), BoundResult(..)) => {} // Continue.
1326 // If there is an unresolved glob at this point in the
1327 // containing module, bail out. We don't know enough to be
1328 // able to resolve this import.
1330 if containing_module.glob_count.get() > 0 {
1331 debug!("(resolving single import) unresolved glob; \
1333 return Indeterminate;
1336 // Now search the exported imports within the containing module.
1337 match containing_module.import_resolutions.borrow().get(&source) {
1339 debug!("(resolving single import) no import");
1340 // The containing module definitely doesn't have an
1341 // exported import with the name in question. We can
1342 // therefore accurately report that the names are
1345 if value_result.is_unknown() {
1346 value_result = UnboundResult;
1348 if type_result.is_unknown() {
1349 type_result = UnboundResult;
1352 Some(import_resolution)
1353 if import_resolution.outstanding_references == 0 => {
1355 fn get_binding(this: &mut Resolver,
1356 import_resolution: &ImportResolution,
1357 namespace: Namespace,
1359 -> NamespaceResult {
1361 // Import resolutions must be declared with "pub"
1362 // in order to be exported.
1363 if !import_resolution.is_public {
1364 return UnboundResult;
1367 match import_resolution.
1368 target_for_namespace(namespace) {
1370 return UnboundResult;
1377 debug!("(resolving single import) found \
1378 import in ns {}", namespace);
1379 let id = import_resolution.id(namespace);
1380 // track used imports and extern crates as well
1381 this.used_imports.insert((id, namespace));
1382 this.record_import_use(id, *source);
1383 match target_module.def_id.get() {
1384 Some(DefId{krate: kid, ..}) => {
1385 this.used_crates.insert(kid);
1389 return BoundResult(target_module, bindings);
1394 // The name is an import which has been fully
1395 // resolved. We can, therefore, just follow it.
1396 if value_result.is_unknown() {
1397 value_result = get_binding(self,
1401 value_used_reexport = import_resolution.is_public;
1403 if type_result.is_unknown() {
1404 type_result = get_binding(self,
1408 type_used_reexport = import_resolution.is_public;
1413 // If containing_module is the same module whose import we are resolving
1414 // and there it has an unresolved import with the same name as `source`,
1415 // then the user is actually trying to import an item that is declared
1416 // in the same scope
1419 // use self::submodule;
1420 // pub mod submodule;
1422 // In this case we continue as if we resolved the import and let the
1423 // check_for_conflicts_between_imports_and_items call below handle
1425 match (module_.def_id.get(), containing_module.def_id.get()) {
1426 (Some(id1), Some(id2)) if id1 == id2 => {
1427 if value_result.is_unknown() {
1428 value_result = UnboundResult;
1430 if type_result.is_unknown() {
1431 type_result = UnboundResult;
1435 // The import is unresolved. Bail out.
1436 debug!("(resolving single import) unresolved import; \
1438 return Indeterminate;
1446 // If we didn't find a result in the type namespace, search the
1447 // external modules.
1448 let mut value_used_public = false;
1449 let mut type_used_public = false;
1451 BoundResult(..) => {}
1453 match containing_module.external_module_children.borrow_mut()
1454 .get(&source).cloned() {
1455 None => {} // Continue.
1457 debug!("(resolving single import) found external \
1459 // track the module as used.
1460 match module.def_id.get() {
1461 Some(DefId{krate: kid, ..}) => { self.used_crates.insert(kid); },
1465 Rc::new(Resolver::create_name_bindings_from_module(
1467 type_result = BoundResult(containing_module.clone(),
1469 type_used_public = true;
1475 // We've successfully resolved the import. Write the results in.
1476 let mut import_resolutions = module_.import_resolutions.borrow_mut();
1477 let import_resolution = &mut (*import_resolutions)[target];
1479 let mut check_and_write_import = |&mut: namespace, result: &_, used_public: &mut bool| {
1480 let namespace_name = match namespace {
1486 BoundResult(ref target_module, ref name_bindings) => {
1487 debug!("(resolving single import) found {} target: {}",
1489 name_bindings.def_for_namespace(namespace));
1490 self.check_for_conflicting_import(
1491 &import_resolution.target_for_namespace(namespace),
1496 self.check_that_import_is_importable(
1502 let target = Some(Target::new(target_module.clone(),
1503 name_bindings.clone(),
1504 directive.shadowable));
1505 import_resolution.set_target_and_id(namespace, target, directive.id);
1506 import_resolution.is_public = directive.is_public;
1507 *used_public = name_bindings.defined_in_public_namespace(namespace);
1509 UnboundResult => { /* Continue. */ }
1511 panic!("{} result should be known at this point", namespace_name);
1515 check_and_write_import(ValueNS, &value_result, &mut value_used_public);
1516 check_and_write_import(TypeNS, &type_result, &mut type_used_public);
1519 self.check_for_conflicts_between_imports_and_items(
1525 if value_result.is_unbound() && type_result.is_unbound() {
1526 let msg = format!("There is no `{}` in `{}`",
1527 token::get_name(source),
1528 self.module_to_string(&*containing_module));
1529 return Failed(Some((directive.span, msg)));
1531 let value_used_public = value_used_reexport || value_used_public;
1532 let type_used_public = type_used_reexport || type_used_public;
1534 assert!(import_resolution.outstanding_references >= 1);
1535 import_resolution.outstanding_references -= 1;
1537 // record what this import resolves to for later uses in documentation,
1538 // this may resolve to either a value or a type, but for documentation
1539 // purposes it's good enough to just favor one over the other.
1540 let value_private = match import_resolution.value_target {
1541 Some(ref target) => {
1542 let def = target.bindings.def_for_namespace(ValueNS).unwrap();
1543 self.def_map.borrow_mut().insert(directive.id, def);
1544 let did = def.def_id();
1545 if value_used_public {Some(lp)} else {Some(DependsOn(did))}
1547 // AllPublic here and below is a dummy value, it should never be used because
1548 // _exists is false.
1551 let type_private = match import_resolution.type_target {
1552 Some(ref target) => {
1553 let def = target.bindings.def_for_namespace(TypeNS).unwrap();
1554 self.def_map.borrow_mut().insert(directive.id, def);
1555 let did = def.def_id();
1556 if type_used_public {Some(lp)} else {Some(DependsOn(did))}
1561 self.last_private.insert(directive.id, LastImport{value_priv: value_private,
1563 type_priv: type_private,
1566 debug!("(resolving single import) successfully resolved import");
1570 // Resolves a glob import. Note that this function cannot fail; it either
1571 // succeeds or bails out (as importing * from an empty module or a module
1572 // that exports nothing is valid). containing_module is the module we are
1573 // actually importing, i.e., `foo` in `use foo::*`.
1574 fn resolve_glob_import(&mut self,
1576 containing_module: Rc<Module>,
1577 import_directive: &ImportDirective,
1579 -> ResolveResult<()> {
1580 let id = import_directive.id;
1581 let is_public = import_directive.is_public;
1583 // This function works in a highly imperative manner; it eagerly adds
1584 // everything it can to the list of import resolutions of the module
1586 debug!("(resolving glob import) resolving glob import {}", id);
1588 // We must bail out if the node has unresolved imports of any kind
1589 // (including globs).
1590 if !(*containing_module).all_imports_resolved() {
1591 debug!("(resolving glob import) target module has unresolved \
1592 imports; bailing out");
1593 return Indeterminate;
1596 assert_eq!(containing_module.glob_count.get(), 0);
1598 // Add all resolved imports from the containing module.
1599 let import_resolutions = containing_module.import_resolutions.borrow();
1600 for (ident, target_import_resolution) in import_resolutions.iter() {
1601 debug!("(resolving glob import) writing module resolution \
1603 token::get_name(*ident),
1604 self.module_to_string(module_));
1606 if !target_import_resolution.is_public {
1607 debug!("(resolving glob import) nevermind, just kidding");
1611 // Here we merge two import resolutions.
1612 let mut import_resolutions = module_.import_resolutions.borrow_mut();
1613 match import_resolutions.get_mut(ident) {
1614 Some(dest_import_resolution) => {
1615 // Merge the two import resolutions at a finer-grained
1618 match target_import_resolution.value_target {
1622 Some(ref value_target) => {
1623 self.check_for_conflicting_import(&dest_import_resolution.value_target,
1624 import_directive.span,
1627 dest_import_resolution.value_target = Some(value_target.clone());
1630 match target_import_resolution.type_target {
1634 Some(ref type_target) => {
1635 self.check_for_conflicting_import(&dest_import_resolution.type_target,
1636 import_directive.span,
1639 dest_import_resolution.type_target = Some(type_target.clone());
1642 dest_import_resolution.is_public = is_public;
1648 // Simple: just copy the old import resolution.
1649 let mut new_import_resolution = ImportResolution::new(id, is_public);
1650 new_import_resolution.value_target =
1651 target_import_resolution.value_target.clone();
1652 new_import_resolution.type_target =
1653 target_import_resolution.type_target.clone();
1655 import_resolutions.insert(*ident, new_import_resolution);
1658 // Add all children from the containing module.
1659 build_reduced_graph::populate_module_if_necessary(self, &containing_module);
1661 for (&name, name_bindings) in containing_module.children.borrow().iter() {
1662 self.merge_import_resolution(module_,
1663 containing_module.clone(),
1666 name_bindings.clone());
1670 // Add external module children from the containing module.
1671 for (&name, module) in containing_module.external_module_children.borrow().iter() {
1673 Rc::new(Resolver::create_name_bindings_from_module(module.clone()));
1674 self.merge_import_resolution(module_,
1675 containing_module.clone(),
1681 // Record the destination of this import
1682 match containing_module.def_id.get() {
1684 self.def_map.borrow_mut().insert(id, DefMod(did));
1685 self.last_private.insert(id, lp);
1690 debug!("(resolving glob import) successfully resolved import");
1694 fn merge_import_resolution(&mut self,
1696 containing_module: Rc<Module>,
1697 import_directive: &ImportDirective,
1699 name_bindings: Rc<NameBindings>) {
1700 let id = import_directive.id;
1701 let is_public = import_directive.is_public;
1703 let mut import_resolutions = module_.import_resolutions.borrow_mut();
1704 let dest_import_resolution = import_resolutions.entry(&name).get().unwrap_or_else(
1706 // Create a new import resolution from this child.
1707 vacant_entry.insert(ImportResolution::new(id, is_public))
1710 debug!("(resolving glob import) writing resolution `{}` in `{}` \
1712 token::get_name(name).get(),
1713 self.module_to_string(&*containing_module),
1714 self.module_to_string(module_));
1716 // Merge the child item into the import resolution.
1718 let mut merge_child_item = |&mut : namespace| {
1719 if name_bindings.defined_in_namespace_with(namespace, IMPORTABLE | PUBLIC) {
1720 let namespace_name = match namespace {
1724 debug!("(resolving glob import) ... for {} target", namespace_name);
1725 if dest_import_resolution.shadowable(namespace) == Shadowable::Never {
1726 let msg = format!("a {} named `{}` has already been imported \
1729 token::get_name(name).get());
1730 self.session.span_err(import_directive.span, msg.as_slice());
1732 let target = Target::new(containing_module.clone(),
1733 name_bindings.clone(),
1734 import_directive.shadowable);
1735 dest_import_resolution.set_target_and_id(namespace,
1741 merge_child_item(ValueNS);
1742 merge_child_item(TypeNS);
1745 dest_import_resolution.is_public = is_public;
1747 self.check_for_conflicts_between_imports_and_items(
1749 dest_import_resolution,
1750 import_directive.span,
1754 /// Checks that imported names and items don't have the same name.
1755 fn check_for_conflicting_import(&mut self,
1756 target: &Option<Target>,
1759 namespace: Namespace) {
1760 if self.session.features.borrow().import_shadowing {
1764 debug!("check_for_conflicting_import: {}; target exists: {}",
1765 token::get_name(name).get(),
1769 Some(ref target) if target.shadowable != Shadowable::Always => {
1770 let msg = format!("a {} named `{}` has already been imported \
1776 token::get_name(name).get());
1777 self.session.span_err(import_span, msg[]);
1779 Some(_) | None => {}
1783 /// Checks that an import is actually importable
1784 fn check_that_import_is_importable(&mut self,
1785 name_bindings: &NameBindings,
1788 namespace: Namespace) {
1789 if !name_bindings.defined_in_namespace_with(namespace, IMPORTABLE) {
1790 let msg = format!("`{}` is not directly importable",
1791 token::get_name(name));
1792 self.session.span_err(import_span, msg[]);
1796 /// Checks that imported names and items don't have the same name.
1797 fn check_for_conflicts_between_imports_and_items(&mut self,
1803 if self.session.features.borrow().import_shadowing {
1807 // First, check for conflicts between imports and `extern crate`s.
1808 if module.external_module_children
1810 .contains_key(&name) {
1811 match import_resolution.type_target {
1812 Some(ref target) if target.shadowable != Shadowable::Always => {
1813 let msg = format!("import `{0}` conflicts with imported \
1814 crate in this module \
1815 (maybe you meant `use {0}::*`?)",
1816 token::get_name(name).get());
1817 self.session.span_err(import_span, msg[]);
1819 Some(_) | None => {}
1823 // Check for item conflicts.
1824 let children = module.children.borrow();
1825 let name_bindings = match children.get(&name) {
1827 // There can't be any conflicts.
1830 Some(ref name_bindings) => (*name_bindings).clone(),
1833 match import_resolution.value_target {
1834 Some(ref target) if target.shadowable != Shadowable::Always => {
1835 if let Some(ref value) = *name_bindings.value_def.borrow() {
1836 let msg = format!("import `{}` conflicts with value \
1838 token::get_name(name).get());
1839 self.session.span_err(import_span, msg[]);
1840 if let Some(span) = value.value_span {
1841 self.session.span_note(span,
1842 "conflicting value here");
1846 Some(_) | None => {}
1849 match import_resolution.type_target {
1850 Some(ref target) if target.shadowable != Shadowable::Always => {
1851 if let Some(ref ty) = *name_bindings.type_def.borrow() {
1852 match ty.module_def {
1854 let msg = format!("import `{}` conflicts with type in \
1856 token::get_name(name).get());
1857 self.session.span_err(import_span, msg[]);
1858 if let Some(span) = ty.type_span {
1859 self.session.span_note(span,
1860 "note conflicting type here")
1863 Some(ref module_def) => {
1864 match module_def.kind.get() {
1866 if let Some(span) = ty.type_span {
1867 let msg = format!("inherent implementations \
1868 are only allowed on types \
1869 defined in the current module");
1870 self.session.span_err(span, msg[]);
1871 self.session.span_note(import_span,
1872 "import from other module here")
1876 let msg = format!("import `{}` conflicts with existing \
1878 token::get_name(name).get());
1879 self.session.span_err(import_span, msg[]);
1880 if let Some(span) = ty.type_span {
1881 self.session.span_note(span,
1882 "note conflicting module here")
1890 Some(_) | None => {}
1894 /// Checks that the names of external crates don't collide with other
1895 /// external crates.
1896 fn check_for_conflicts_between_external_crates(&self,
1900 if self.session.features.borrow().import_shadowing {
1904 if module.external_module_children.borrow().contains_key(&name) {
1907 format!("an external crate named `{}` has already \
1908 been imported into this module",
1909 token::get_name(name).get())[]);
1913 /// Checks that the names of items don't collide with external crates.
1914 fn check_for_conflicts_between_external_crates_and_items(&self,
1918 if self.session.features.borrow().import_shadowing {
1922 if module.external_module_children.borrow().contains_key(&name) {
1925 format!("the name `{}` conflicts with an external \
1926 crate that has been imported into this \
1928 token::get_name(name).get())[]);
1932 /// Resolves the given module path from the given root `module_`.
1933 fn resolve_module_path_from_root(&mut self,
1934 module_: Rc<Module>,
1935 module_path: &[Name],
1938 name_search_type: NameSearchType,
1940 -> ResolveResult<(Rc<Module>, LastPrivate)> {
1941 fn search_parent_externals(needle: Name, module: &Rc<Module>)
1942 -> Option<Rc<Module>> {
1943 module.external_module_children.borrow()
1944 .get(&needle).cloned()
1945 .map(|_| module.clone())
1947 match module.parent_link.clone() {
1948 ModuleParentLink(parent, _) => {
1949 search_parent_externals(needle,
1950 &parent.upgrade().unwrap())
1957 let mut search_module = module_;
1958 let mut index = index;
1959 let module_path_len = module_path.len();
1960 let mut closest_private = lp;
1962 // Resolve the module part of the path. This does not involve looking
1963 // upward though scope chains; we simply resolve names directly in
1964 // modules as we go.
1965 while index < module_path_len {
1966 let name = module_path[index];
1967 match self.resolve_name_in_module(search_module.clone(),
1973 let segment_name = token::get_name(name);
1974 let module_name = self.module_to_string(&*search_module);
1975 let mut span = span;
1976 let msg = if "???" == module_name[] {
1977 span.hi = span.lo + Pos::from_uint(segment_name.get().len());
1979 match search_parent_externals(name,
1980 &self.current_module) {
1982 let path_str = self.names_to_string(module_path);
1983 let target_mod_str = self.module_to_string(&*module);
1984 let current_mod_str =
1985 self.module_to_string(&*self.current_module);
1987 let prefix = if target_mod_str == current_mod_str {
1988 "self::".to_string()
1990 format!("{}::", target_mod_str)
1993 format!("Did you mean `{}{}`?", prefix, path_str)
1995 None => format!("Maybe a missing `extern crate {}`?",
1999 format!("Could not find `{}` in `{}`",
2004 return Failed(Some((span, msg)));
2006 Failed(err) => return Failed(err),
2008 debug!("(resolving module path for import) module \
2009 resolution is indeterminate: {}",
2010 token::get_name(name));
2011 return Indeterminate;
2013 Success((target, used_proxy)) => {
2014 // Check to see whether there are type bindings, and, if
2015 // so, whether there is a module within.
2016 match *target.bindings.type_def.borrow() {
2017 Some(ref type_def) => {
2018 match type_def.module_def {
2020 let msg = format!("Not a module `{}`",
2021 token::get_name(name));
2023 return Failed(Some((span, msg)));
2025 Some(ref module_def) => {
2026 search_module = module_def.clone();
2028 // track extern crates for unused_extern_crate lint
2029 if let Some(did) = module_def.def_id.get() {
2030 self.used_crates.insert(did.krate);
2033 // Keep track of the closest
2034 // private module used when
2035 // resolving this import chain.
2036 if !used_proxy && !search_module.is_public {
2037 if let Some(did) = search_module.def_id.get() {
2038 closest_private = LastMod(DependsOn(did));
2045 // There are no type bindings at all.
2046 let msg = format!("Not a module `{}`",
2047 token::get_name(name));
2048 return Failed(Some((span, msg)));
2057 return Success((search_module, closest_private));
2060 /// Attempts to resolve the module part of an import directive or path
2061 /// rooted at the given module.
2063 /// On success, returns the resolved module, and the closest *private*
2064 /// module found to the destination when resolving this path.
2065 fn resolve_module_path(&mut self,
2066 module_: Rc<Module>,
2067 module_path: &[Name],
2068 use_lexical_scope: UseLexicalScopeFlag,
2070 name_search_type: NameSearchType)
2071 -> ResolveResult<(Rc<Module>, LastPrivate)> {
2072 let module_path_len = module_path.len();
2073 assert!(module_path_len > 0);
2075 debug!("(resolving module path for import) processing `{}` rooted at `{}`",
2076 self.names_to_string(module_path),
2077 self.module_to_string(&*module_));
2079 // Resolve the module prefix, if any.
2080 let module_prefix_result = self.resolve_module_prefix(module_.clone(),
2086 match module_prefix_result {
2088 let mpath = self.names_to_string(module_path);
2089 let mpath = mpath[];
2090 match mpath.rfind(':') {
2092 let msg = format!("Could not find `{}` in `{}`",
2093 // idx +- 1 to account for the
2094 // colons on either side
2097 return Failed(Some((span, msg)));
2104 Failed(err) => return Failed(err),
2106 debug!("(resolving module path for import) indeterminate; \
2108 return Indeterminate;
2110 Success(NoPrefixFound) => {
2111 // There was no prefix, so we're considering the first element
2112 // of the path. How we handle this depends on whether we were
2113 // instructed to use lexical scope or not.
2114 match use_lexical_scope {
2115 DontUseLexicalScope => {
2116 // This is a crate-relative path. We will start the
2117 // resolution process at index zero.
2118 search_module = self.graph_root.get_module();
2120 last_private = LastMod(AllPublic);
2122 UseLexicalScope => {
2123 // This is not a crate-relative path. We resolve the
2124 // first component of the path in the current lexical
2125 // scope and then proceed to resolve below that.
2126 match self.resolve_module_in_lexical_scope(module_,
2128 Failed(err) => return Failed(err),
2130 debug!("(resolving module path for import) \
2131 indeterminate; bailing");
2132 return Indeterminate;
2134 Success(containing_module) => {
2135 search_module = containing_module;
2137 last_private = LastMod(AllPublic);
2143 Success(PrefixFound(ref containing_module, index)) => {
2144 search_module = containing_module.clone();
2145 start_index = index;
2146 last_private = LastMod(DependsOn(containing_module.def_id
2152 self.resolve_module_path_from_root(search_module,
2160 /// Invariant: This must only be called during main resolution, not during
2161 /// import resolution.
2162 fn resolve_item_in_lexical_scope(&mut self,
2163 module_: Rc<Module>,
2165 namespace: Namespace)
2166 -> ResolveResult<(Target, bool)> {
2167 debug!("(resolving item in lexical scope) resolving `{}` in \
2168 namespace {} in `{}`",
2169 token::get_name(name),
2171 self.module_to_string(&*module_));
2173 // The current module node is handled specially. First, check for
2174 // its immediate children.
2175 build_reduced_graph::populate_module_if_necessary(self, &module_);
2177 match module_.children.borrow().get(&name) {
2179 if name_bindings.defined_in_namespace(namespace) => {
2180 debug!("top name bindings succeeded");
2181 return Success((Target::new(module_.clone(),
2182 name_bindings.clone(),
2186 Some(_) | None => { /* Not found; continue. */ }
2189 // Now check for its import directives. We don't have to have resolved
2190 // all its imports in the usual way; this is because chains of
2191 // adjacent import statements are processed as though they mutated the
2193 if let Some(import_resolution) = module_.import_resolutions.borrow().get(&name) {
2194 match (*import_resolution).target_for_namespace(namespace) {
2196 // Not found; continue.
2197 debug!("(resolving item in lexical scope) found \
2198 import resolution, but not in namespace {}",
2202 debug!("(resolving item in lexical scope) using \
2203 import resolution");
2204 // track used imports and extern crates as well
2205 let id = import_resolution.id(namespace);
2206 self.used_imports.insert((id, namespace));
2207 self.record_import_use(id, name);
2208 if let Some(DefId{krate: kid, ..}) = target.target_module.def_id.get() {
2209 self.used_crates.insert(kid);
2211 return Success((target, false));
2216 // Search for external modules.
2217 if namespace == TypeNS {
2218 if let Some(module) = module_.external_module_children.borrow().get(&name).cloned() {
2220 Rc::new(Resolver::create_name_bindings_from_module(module));
2221 debug!("lower name bindings succeeded");
2222 return Success((Target::new(module_,
2229 // Finally, proceed up the scope chain looking for parent modules.
2230 let mut search_module = module_;
2232 // Go to the next parent.
2233 match search_module.parent_link.clone() {
2235 // No more parents. This module was unresolved.
2236 debug!("(resolving item in lexical scope) unresolved \
2238 return Failed(None);
2240 ModuleParentLink(parent_module_node, _) => {
2241 match search_module.kind.get() {
2242 NormalModuleKind => {
2243 // We stop the search here.
2244 debug!("(resolving item in lexical \
2245 scope) unresolved module: not \
2246 searching through module \
2248 return Failed(None);
2253 AnonymousModuleKind => {
2254 search_module = parent_module_node.upgrade().unwrap();
2258 BlockParentLink(ref parent_module_node, _) => {
2259 search_module = parent_module_node.upgrade().unwrap();
2263 // Resolve the name in the parent module.
2264 match self.resolve_name_in_module(search_module.clone(),
2269 Failed(Some((span, msg))) =>
2270 self.resolve_error(span, format!("failed to resolve. {}",
2272 Failed(None) => (), // Continue up the search chain.
2274 // We couldn't see through the higher scope because of an
2275 // unresolved import higher up. Bail.
2277 debug!("(resolving item in lexical scope) indeterminate \
2278 higher scope; bailing");
2279 return Indeterminate;
2281 Success((target, used_reexport)) => {
2282 // We found the module.
2283 debug!("(resolving item in lexical scope) found name \
2285 return Success((target, used_reexport));
2291 /// Resolves a module name in the current lexical scope.
2292 fn resolve_module_in_lexical_scope(&mut self,
2293 module_: Rc<Module>,
2295 -> ResolveResult<Rc<Module>> {
2296 // If this module is an anonymous module, resolve the item in the
2297 // lexical scope. Otherwise, resolve the item from the crate root.
2298 let resolve_result = self.resolve_item_in_lexical_scope(module_, name, TypeNS);
2299 match resolve_result {
2300 Success((target, _)) => {
2301 let bindings = &*target.bindings;
2302 match *bindings.type_def.borrow() {
2303 Some(ref type_def) => {
2304 match type_def.module_def {
2306 debug!("!!! (resolving module in lexical \
2307 scope) module wasn't actually a \
2309 return Failed(None);
2311 Some(ref module_def) => {
2312 return Success(module_def.clone());
2317 debug!("!!! (resolving module in lexical scope) module
2318 wasn't actually a module!");
2319 return Failed(None);
2324 debug!("(resolving module in lexical scope) indeterminate; \
2326 return Indeterminate;
2329 debug!("(resolving module in lexical scope) failed to resolve");
2335 /// Returns the nearest normal module parent of the given module.
2336 fn get_nearest_normal_module_parent(&mut self, module_: Rc<Module>)
2337 -> Option<Rc<Module>> {
2338 let mut module_ = module_;
2340 match module_.parent_link.clone() {
2341 NoParentLink => return None,
2342 ModuleParentLink(new_module, _) |
2343 BlockParentLink(new_module, _) => {
2344 let new_module = new_module.upgrade().unwrap();
2345 match new_module.kind.get() {
2346 NormalModuleKind => return Some(new_module),
2350 AnonymousModuleKind => module_ = new_module,
2357 /// Returns the nearest normal module parent of the given module, or the
2358 /// module itself if it is a normal module.
2359 fn get_nearest_normal_module_parent_or_self(&mut self, module_: Rc<Module>)
2361 match module_.kind.get() {
2362 NormalModuleKind => return module_,
2366 AnonymousModuleKind => {
2367 match self.get_nearest_normal_module_parent(module_.clone()) {
2369 Some(new_module) => new_module
2375 /// Resolves a "module prefix". A module prefix is one or both of (a) `self::`;
2376 /// (b) some chain of `super::`.
2377 /// grammar: (SELF MOD_SEP ) ? (SUPER MOD_SEP) *
2378 fn resolve_module_prefix(&mut self,
2379 module_: Rc<Module>,
2380 module_path: &[Name])
2381 -> ResolveResult<ModulePrefixResult> {
2382 // Start at the current module if we see `self` or `super`, or at the
2383 // top of the crate otherwise.
2384 let mut containing_module;
2386 let first_module_path_string = token::get_name(module_path[0]);
2387 if "self" == first_module_path_string.get() {
2389 self.get_nearest_normal_module_parent_or_self(module_);
2391 } else if "super" == first_module_path_string.get() {
2393 self.get_nearest_normal_module_parent_or_self(module_);
2394 i = 0; // We'll handle `super` below.
2396 return Success(NoPrefixFound);
2399 // Now loop through all the `super`s we find.
2400 while i < module_path.len() {
2401 let string = token::get_name(module_path[i]);
2402 if "super" != string.get() {
2405 debug!("(resolving module prefix) resolving `super` at {}",
2406 self.module_to_string(&*containing_module));
2407 match self.get_nearest_normal_module_parent(containing_module) {
2408 None => return Failed(None),
2409 Some(new_module) => {
2410 containing_module = new_module;
2416 debug!("(resolving module prefix) finished resolving prefix at {}",
2417 self.module_to_string(&*containing_module));
2419 return Success(PrefixFound(containing_module, i));
2422 /// Attempts to resolve the supplied name in the given module for the
2423 /// given namespace. If successful, returns the target corresponding to
2426 /// The boolean returned on success is an indicator of whether this lookup
2427 /// passed through a public re-export proxy.
2428 fn resolve_name_in_module(&mut self,
2429 module_: Rc<Module>,
2431 namespace: Namespace,
2432 name_search_type: NameSearchType,
2433 allow_private_imports: bool)
2434 -> ResolveResult<(Target, bool)> {
2435 debug!("(resolving name in module) resolving `{}` in `{}`",
2436 token::get_name(name).get(),
2437 self.module_to_string(&*module_));
2439 // First, check the direct children of the module.
2440 build_reduced_graph::populate_module_if_necessary(self, &module_);
2442 match module_.children.borrow().get(&name) {
2444 if name_bindings.defined_in_namespace(namespace) => {
2445 debug!("(resolving name in module) found node as child");
2446 return Success((Target::new(module_.clone(),
2447 name_bindings.clone(),
2456 // Next, check the module's imports if necessary.
2458 // If this is a search of all imports, we should be done with glob
2459 // resolution at this point.
2460 if name_search_type == PathSearch {
2461 assert_eq!(module_.glob_count.get(), 0);
2464 // Check the list of resolved imports.
2465 match module_.import_resolutions.borrow().get(&name) {
2466 Some(import_resolution) if allow_private_imports ||
2467 import_resolution.is_public => {
2469 if import_resolution.is_public &&
2470 import_resolution.outstanding_references != 0 {
2471 debug!("(resolving name in module) import \
2472 unresolved; bailing out");
2473 return Indeterminate;
2475 match import_resolution.target_for_namespace(namespace) {
2477 debug!("(resolving name in module) name found, \
2478 but not in namespace {}",
2482 debug!("(resolving name in module) resolved to \
2484 // track used imports and extern crates as well
2485 let id = import_resolution.id(namespace);
2486 self.used_imports.insert((id, namespace));
2487 self.record_import_use(id, name);
2488 if let Some(DefId{krate: kid, ..}) = target.target_module.def_id.get() {
2489 self.used_crates.insert(kid);
2491 return Success((target, true));
2495 Some(..) | None => {} // Continue.
2498 // Finally, search through external children.
2499 if namespace == TypeNS {
2500 if let Some(module) = module_.external_module_children.borrow().get(&name).cloned() {
2502 Rc::new(Resolver::create_name_bindings_from_module(module));
2503 return Success((Target::new(module_,
2510 // We're out of luck.
2511 debug!("(resolving name in module) failed to resolve `{}`",
2512 token::get_name(name).get());
2513 return Failed(None);
2516 fn report_unresolved_imports(&mut self, module_: Rc<Module>) {
2517 let index = module_.resolved_import_count.get();
2518 let imports = module_.imports.borrow();
2519 let import_count = imports.len();
2520 if index != import_count {
2521 let sn = self.session
2523 .span_to_snippet((*imports)[index].span)
2525 if sn.contains("::") {
2526 self.resolve_error((*imports)[index].span,
2527 "unresolved import");
2529 let err = format!("unresolved import (maybe you meant `{}::*`?)",
2531 self.resolve_error((*imports)[index].span, err[]);
2535 // Descend into children and anonymous children.
2536 build_reduced_graph::populate_module_if_necessary(self, &module_);
2538 for (_, child_node) in module_.children.borrow().iter() {
2539 match child_node.get_module_if_available() {
2543 Some(child_module) => {
2544 self.report_unresolved_imports(child_module);
2549 for (_, module_) in module_.anonymous_children.borrow().iter() {
2550 self.report_unresolved_imports(module_.clone());
2556 // We maintain a list of value ribs and type ribs.
2558 // Simultaneously, we keep track of the current position in the module
2559 // graph in the `current_module` pointer. When we go to resolve a name in
2560 // the value or type namespaces, we first look through all the ribs and
2561 // then query the module graph. When we resolve a name in the module
2562 // namespace, we can skip all the ribs (since nested modules are not
2563 // allowed within blocks in Rust) and jump straight to the current module
2566 // Named implementations are handled separately. When we find a method
2567 // call, we consult the module node to find all of the implementations in
2568 // scope. This information is lazily cached in the module node. We then
2569 // generate a fake "implementation scope" containing all the
2570 // implementations thus found, for compatibility with old resolve pass.
2572 fn with_scope<F>(&mut self, name: Option<Name>, f: F) where
2573 F: FnOnce(&mut Resolver),
2575 let orig_module = self.current_module.clone();
2577 // Move down in the graph.
2583 build_reduced_graph::populate_module_if_necessary(self, &orig_module);
2585 match orig_module.children.borrow().get(&name) {
2587 debug!("!!! (with scope) didn't find `{}` in `{}`",
2588 token::get_name(name),
2589 self.module_to_string(&*orig_module));
2591 Some(name_bindings) => {
2592 match (*name_bindings).get_module_if_available() {
2594 debug!("!!! (with scope) didn't find module \
2596 token::get_name(name),
2597 self.module_to_string(&*orig_module));
2600 self.current_module = module_;
2610 self.current_module = orig_module;
2613 /// Wraps the given definition in the appropriate number of `DefUpvar`
2619 -> Option<DefLike> {
2621 DlDef(d @ DefUpvar(..)) => {
2622 self.session.span_bug(span,
2623 format!("unexpected {} in bindings", d)[])
2625 DlDef(d @ DefLocal(_)) => {
2626 let node_id = d.def_id().node;
2628 let mut last_proc_body_id = ast::DUMMY_NODE_ID;
2629 for rib in ribs.iter() {
2632 // Nothing to do. Continue.
2634 ClosureRibKind(function_id, maybe_proc_body) => {
2636 if maybe_proc_body != ast::DUMMY_NODE_ID {
2637 last_proc_body_id = maybe_proc_body;
2639 def = DefUpvar(node_id, function_id, last_proc_body_id);
2641 let mut seen = self.freevars_seen.borrow_mut();
2642 let seen = match seen.entry(&function_id) {
2643 Occupied(v) => v.into_mut(),
2644 Vacant(v) => v.insert(NodeSet::new()),
2646 if seen.contains(&node_id) {
2649 match self.freevars.borrow_mut().entry(&function_id) {
2650 Occupied(v) => v.into_mut(),
2651 Vacant(v) => v.insert(vec![]),
2652 }.push(Freevar { def: prev_def, span: span });
2653 seen.insert(node_id);
2655 MethodRibKind(item_id, _) => {
2656 // If the def is a ty param, and came from the parent
2659 DefTyParam(_, _, did, _) if {
2660 self.def_map.borrow().get(&did.node).cloned()
2661 == Some(DefTyParamBinder(item_id))
2663 DefSelfTy(did) if did == item_id => {} // ok
2665 // This was an attempt to access an upvar inside a
2666 // named function item. This is not allowed, so we
2671 "can't capture dynamic environment in a fn item; \
2672 use the || { ... } closure form instead");
2679 // This was an attempt to access an upvar inside a
2680 // named function item. This is not allowed, so we
2685 "can't capture dynamic environment in a fn item; \
2686 use the || { ... } closure form instead");
2690 ConstantItemRibKind => {
2691 // Still doesn't deal with upvars
2692 self.resolve_error(span,
2693 "attempt to use a non-constant \
2694 value in a constant");
2701 DlDef(def @ DefTyParam(..)) |
2702 DlDef(def @ DefSelfTy(..)) => {
2703 for rib in ribs.iter() {
2705 NormalRibKind | ClosureRibKind(..) => {
2706 // Nothing to do. Continue.
2708 MethodRibKind(item_id, _) => {
2709 // If the def is a ty param, and came from the parent
2712 DefTyParam(_, _, did, _) if {
2713 self.def_map.borrow().get(&did.node).cloned()
2714 == Some(DefTyParamBinder(item_id))
2716 DefSelfTy(did) if did == item_id => {} // ok
2719 // This was an attempt to use a type parameter outside
2722 self.resolve_error(span,
2723 "can't use type parameters from \
2724 outer function; try using a local \
2725 type parameter instead");
2732 // This was an attempt to use a type parameter outside
2735 self.resolve_error(span,
2736 "can't use type parameters from \
2737 outer function; try using a local \
2738 type parameter instead");
2742 ConstantItemRibKind => {
2744 self.resolve_error(span,
2745 "cannot use an outer type \
2746 parameter in this context");
2757 /// Searches the current set of local scopes and
2758 /// applies translations for closures.
2759 fn search_ribs(&self,
2763 -> Option<DefLike> {
2764 // FIXME #4950: Try caching?
2766 for (i, rib) in ribs.iter().enumerate().rev() {
2767 match rib.bindings.get(&name).cloned() {
2769 return self.upvarify(ribs[i + 1..], def_like, span);
2780 /// Searches the current set of local scopes for labels.
2781 /// Stops after meeting a closure.
2782 fn search_label(&self, name: Name) -> Option<DefLike> {
2783 for rib in self.label_ribs.iter().rev() {
2789 // Do not resolve labels across function boundary
2793 let result = rib.bindings.get(&name).cloned();
2794 if result.is_some() {
2801 fn resolve_crate(&mut self, krate: &ast::Crate) {
2802 debug!("(resolving crate) starting");
2804 visit::walk_crate(self, krate);
2807 fn resolve_item(&mut self, item: &Item) {
2808 let name = item.ident.name;
2810 debug!("(resolving item) resolving {}",
2811 token::get_name(name));
2815 // enum item: resolve all the variants' discrs,
2816 // then resolve the ty params
2817 ItemEnum(ref enum_def, ref generics) => {
2818 for variant in (*enum_def).variants.iter() {
2819 for dis_expr in variant.node.disr_expr.iter() {
2820 // resolve the discriminator expr
2822 self.with_constant_rib(|this| {
2823 this.resolve_expr(&**dis_expr);
2828 // n.b. the discr expr gets visited twice.
2829 // but maybe it's okay since the first time will signal an
2830 // error if there is one? -- tjc
2831 self.with_type_parameter_rib(HasTypeParameters(generics,
2836 this.resolve_type_parameters(&generics.ty_params);
2837 this.resolve_where_clause(&generics.where_clause);
2838 visit::walk_item(this, item);
2842 ItemTy(_, ref generics) => {
2843 self.with_type_parameter_rib(HasTypeParameters(generics,
2848 this.resolve_type_parameters(&generics.ty_params);
2849 visit::walk_item(this, item);
2855 ref implemented_traits,
2857 ref impl_items) => {
2858 self.resolve_implementation(item.id,
2865 ItemTrait(_, ref generics, ref bounds, ref trait_items) => {
2866 // Create a new rib for the self type.
2867 let mut self_type_rib = Rib::new(ItemRibKind);
2869 // plain insert (no renaming, types are not currently hygienic....)
2870 let name = self.type_self_name;
2871 self_type_rib.bindings.insert(name, DlDef(DefSelfTy(item.id)));
2872 self.type_ribs.push(self_type_rib);
2874 // Create a new rib for the trait-wide type parameters.
2875 self.with_type_parameter_rib(HasTypeParameters(generics,
2880 this.resolve_type_parameters(&generics.ty_params);
2881 this.resolve_where_clause(&generics.where_clause);
2883 this.resolve_type_parameter_bounds(item.id, bounds,
2886 for trait_item in (*trait_items).iter() {
2887 // Create a new rib for the trait_item-specific type
2890 // FIXME #4951: Do we need a node ID here?
2893 ast::RequiredMethod(ref ty_m) => {
2894 this.with_type_parameter_rib
2895 (HasTypeParameters(&ty_m.generics,
2898 MethodRibKind(item.id, RequiredMethod)),
2901 // Resolve the method-specific type
2903 this.resolve_type_parameters(
2904 &ty_m.generics.ty_params);
2905 this.resolve_where_clause(&ty_m.generics
2908 for argument in ty_m.decl.inputs.iter() {
2909 this.resolve_type(&*argument.ty);
2912 if let SelfExplicit(ref typ, _) = ty_m.explicit_self.node {
2913 this.resolve_type(&**typ)
2916 if let ast::Return(ref ret_ty) = ty_m.decl.output {
2917 this.resolve_type(&**ret_ty);
2921 ast::ProvidedMethod(ref m) => {
2922 this.resolve_method(MethodRibKind(item.id,
2923 ProvidedMethod(m.id)),
2926 ast::TypeTraitItem(ref data) => {
2927 this.resolve_type_parameter(&data.ty_param);
2928 visit::walk_trait_item(this, trait_item);
2934 self.type_ribs.pop();
2937 ItemStruct(ref struct_def, ref generics) => {
2938 self.resolve_struct(item.id,
2940 struct_def.fields[]);
2943 ItemMod(ref module_) => {
2944 self.with_scope(Some(name), |this| {
2945 this.resolve_module(module_, item.span, name,
2950 ItemForeignMod(ref foreign_module) => {
2951 self.with_scope(Some(name), |this| {
2952 for foreign_item in foreign_module.items.iter() {
2953 match foreign_item.node {
2954 ForeignItemFn(_, ref generics) => {
2955 this.with_type_parameter_rib(
2957 generics, FnSpace, foreign_item.id,
2959 |this| visit::walk_foreign_item(this,
2962 ForeignItemStatic(..) => {
2963 visit::walk_foreign_item(this,
2971 ItemFn(ref fn_decl, _, _, ref generics, ref block) => {
2972 self.resolve_function(ItemRibKind,
2982 ItemConst(..) | ItemStatic(..) => {
2983 self.with_constant_rib(|this| {
2984 visit::walk_item(this, item);
2989 // do nothing, these are just around to be encoded
2994 fn with_type_parameter_rib<F>(&mut self, type_parameters: TypeParameters, f: F) where
2995 F: FnOnce(&mut Resolver),
2997 match type_parameters {
2998 HasTypeParameters(generics, space, node_id, rib_kind) => {
2999 let mut function_type_rib = Rib::new(rib_kind);
3000 let mut seen_bindings = HashSet::new();
3001 for (index, type_parameter) in generics.ty_params.iter().enumerate() {
3002 let name = type_parameter.ident.name;
3003 debug!("with_type_parameter_rib: {} {}", node_id,
3006 if seen_bindings.contains(&name) {
3007 self.resolve_error(type_parameter.span,
3008 format!("the name `{}` is already \
3010 parameter in this type \
3015 seen_bindings.insert(name);
3017 let def_like = DlDef(DefTyParam(space,
3019 local_def(type_parameter.id),
3021 // Associate this type parameter with
3022 // the item that bound it
3023 self.record_def(type_parameter.id,
3024 (DefTyParamBinder(node_id), LastMod(AllPublic)));
3025 // plain insert (no renaming)
3026 function_type_rib.bindings.insert(name, def_like);
3028 self.type_ribs.push(function_type_rib);
3031 NoTypeParameters => {
3038 match type_parameters {
3039 HasTypeParameters(..) => { self.type_ribs.pop(); }
3040 NoTypeParameters => { }
3044 fn with_label_rib<F>(&mut self, f: F) where
3045 F: FnOnce(&mut Resolver),
3047 self.label_ribs.push(Rib::new(NormalRibKind));
3049 self.label_ribs.pop();
3052 fn with_constant_rib<F>(&mut self, f: F) where
3053 F: FnOnce(&mut Resolver),
3055 self.value_ribs.push(Rib::new(ConstantItemRibKind));
3056 self.type_ribs.push(Rib::new(ConstantItemRibKind));
3058 self.type_ribs.pop();
3059 self.value_ribs.pop();
3062 fn resolve_function(&mut self,
3064 optional_declaration: Option<&FnDecl>,
3065 type_parameters: TypeParameters,
3067 // Create a value rib for the function.
3068 let function_value_rib = Rib::new(rib_kind);
3069 self.value_ribs.push(function_value_rib);
3071 // Create a label rib for the function.
3072 let function_label_rib = Rib::new(rib_kind);
3073 self.label_ribs.push(function_label_rib);
3075 // If this function has type parameters, add them now.
3076 self.with_type_parameter_rib(type_parameters, |this| {
3077 // Resolve the type parameters.
3078 match type_parameters {
3079 NoTypeParameters => {
3082 HasTypeParameters(ref generics, _, _, _) => {
3083 this.resolve_type_parameters(&generics.ty_params);
3084 this.resolve_where_clause(&generics.where_clause);
3088 // Add each argument to the rib.
3089 match optional_declaration {
3093 Some(declaration) => {
3094 let mut bindings_list = HashMap::new();
3095 for argument in declaration.inputs.iter() {
3096 this.resolve_pattern(&*argument.pat,
3097 ArgumentIrrefutableMode,
3098 &mut bindings_list);
3100 this.resolve_type(&*argument.ty);
3102 debug!("(resolving function) recorded argument");
3105 if let ast::Return(ref ret_ty) = declaration.output {
3106 this.resolve_type(&**ret_ty);
3111 // Resolve the function body.
3112 this.resolve_block(&*block);
3114 debug!("(resolving function) leaving function");
3117 self.label_ribs.pop();
3118 self.value_ribs.pop();
3121 fn resolve_type_parameters(&mut self,
3122 type_parameters: &OwnedSlice<TyParam>) {
3123 for type_parameter in type_parameters.iter() {
3124 self.resolve_type_parameter(type_parameter);
3128 fn resolve_type_parameter(&mut self,
3129 type_parameter: &TyParam) {
3130 for bound in type_parameter.bounds.iter() {
3131 self.resolve_type_parameter_bound(type_parameter.id, bound,
3132 TraitBoundingTypeParameter);
3134 match type_parameter.default {
3135 Some(ref ty) => self.resolve_type(&**ty),
3140 fn resolve_type_parameter_bounds(&mut self,
3142 type_parameter_bounds: &OwnedSlice<TyParamBound>,
3143 reference_type: TraitReferenceType) {
3144 for type_parameter_bound in type_parameter_bounds.iter() {
3145 self.resolve_type_parameter_bound(id, type_parameter_bound,
3150 fn resolve_type_parameter_bound(&mut self,
3152 type_parameter_bound: &TyParamBound,
3153 reference_type: TraitReferenceType) {
3154 match *type_parameter_bound {
3155 TraitTyParamBound(ref tref, _) => {
3156 self.resolve_poly_trait_reference(id, tref, reference_type)
3158 RegionTyParamBound(..) => {}
3162 fn resolve_poly_trait_reference(&mut self,
3164 poly_trait_reference: &PolyTraitRef,
3165 reference_type: TraitReferenceType) {
3166 self.resolve_trait_reference(id, &poly_trait_reference.trait_ref, reference_type)
3169 fn resolve_trait_reference(&mut self,
3171 trait_reference: &TraitRef,
3172 reference_type: TraitReferenceType) {
3173 match self.resolve_path(id, &trait_reference.path, TypeNS, true) {
3175 let path_str = self.path_names_to_string(&trait_reference.path);
3176 let usage_str = match reference_type {
3177 TraitBoundingTypeParameter => "bound type parameter with",
3178 TraitImplementation => "implement",
3179 TraitDerivation => "derive",
3180 TraitObject => "reference",
3181 TraitQPath => "extract an associated type from",
3184 let msg = format!("attempt to {} a nonexistent trait `{}`", usage_str, path_str);
3185 self.resolve_error(trait_reference.path.span, msg[]);
3189 (DefTrait(_), _) => {
3190 debug!("(resolving trait) found trait def: {}", def);
3191 self.record_def(trait_reference.ref_id, def);
3194 self.resolve_error(trait_reference.path.span,
3195 format!("`{}` is not a trait",
3196 self.path_names_to_string(
3197 &trait_reference.path))[]);
3199 // If it's a typedef, give a note
3200 if let DefTy(..) = def {
3201 self.session.span_note(
3202 trait_reference.path.span,
3203 format!("`type` aliases cannot be used for traits")
3212 fn resolve_where_clause(&mut self, where_clause: &ast::WhereClause) {
3213 for predicate in where_clause.predicates.iter() {
3215 &ast::WherePredicate::BoundPredicate(ref bound_pred) => {
3216 self.resolve_type(&*bound_pred.bounded_ty);
3218 for bound in bound_pred.bounds.iter() {
3219 self.resolve_type_parameter_bound(bound_pred.bounded_ty.id, bound,
3220 TraitBoundingTypeParameter);
3223 &ast::WherePredicate::RegionPredicate(_) => {}
3224 &ast::WherePredicate::EqPredicate(ref eq_pred) => {
3225 match self.resolve_path(eq_pred.id, &eq_pred.path, TypeNS, true) {
3226 Some((def @ DefTyParam(..), last_private)) => {
3227 self.record_def(eq_pred.id, (def, last_private));
3230 self.resolve_error(eq_pred.path.span,
3231 "undeclared associated type");
3235 self.resolve_type(&*eq_pred.ty);
3241 fn resolve_struct(&mut self,
3243 generics: &Generics,
3244 fields: &[StructField]) {
3245 // If applicable, create a rib for the type parameters.
3246 self.with_type_parameter_rib(HasTypeParameters(generics,
3251 // Resolve the type parameters.
3252 this.resolve_type_parameters(&generics.ty_params);
3253 this.resolve_where_clause(&generics.where_clause);
3256 for field in fields.iter() {
3257 this.resolve_type(&*field.node.ty);
3262 // Does this really need to take a RibKind or is it always going
3263 // to be NormalRibKind?
3264 fn resolve_method(&mut self,
3266 method: &ast::Method) {
3267 let method_generics = method.pe_generics();
3268 let type_parameters = HasTypeParameters(method_generics,
3273 if let SelfExplicit(ref typ, _) = method.pe_explicit_self().node {
3274 self.resolve_type(&**typ);
3277 self.resolve_function(rib_kind,
3278 Some(method.pe_fn_decl()),
3283 fn with_current_self_type<T, F>(&mut self, self_type: &Ty, f: F) -> T where
3284 F: FnOnce(&mut Resolver) -> T,
3286 // Handle nested impls (inside fn bodies)
3287 let previous_value = replace(&mut self.current_self_type, Some(self_type.clone()));
3288 let result = f(self);
3289 self.current_self_type = previous_value;
3293 fn with_optional_trait_ref<T, F>(&mut self, id: NodeId,
3294 opt_trait_ref: &Option<TraitRef>,
3296 F: FnOnce(&mut Resolver) -> T,
3298 let new_val = match *opt_trait_ref {
3299 Some(ref trait_ref) => {
3300 self.resolve_trait_reference(id, trait_ref, TraitImplementation);
3302 match self.def_map.borrow().get(&trait_ref.ref_id) {
3304 let did = def.def_id();
3305 Some((did, trait_ref.clone()))
3312 let original_trait_ref = replace(&mut self.current_trait_ref, new_val);
3313 let result = f(self);
3314 self.current_trait_ref = original_trait_ref;
3318 fn resolve_implementation(&mut self,
3320 generics: &Generics,
3321 opt_trait_reference: &Option<TraitRef>,
3323 impl_items: &[ImplItem]) {
3324 // If applicable, create a rib for the type parameters.
3325 self.with_type_parameter_rib(HasTypeParameters(generics,
3330 // Resolve the type parameters.
3331 this.resolve_type_parameters(&generics.ty_params);
3332 this.resolve_where_clause(&generics.where_clause);
3334 // Resolve the trait reference, if necessary.
3335 this.with_optional_trait_ref(id, opt_trait_reference, |this| {
3336 // Resolve the self type.
3337 this.resolve_type(self_type);
3339 this.with_current_self_type(self_type, |this| {
3340 for impl_item in impl_items.iter() {
3342 MethodImplItem(ref method) => {
3343 // If this is a trait impl, ensure the method
3345 this.check_trait_item(method.pe_ident().name,
3348 // We also need a new scope for the method-
3349 // specific type parameters.
3350 this.resolve_method(
3351 MethodRibKind(id, ProvidedMethod(method.id)),
3354 TypeImplItem(ref typedef) => {
3355 // If this is a trait impl, ensure the method
3357 this.check_trait_item(typedef.ident.name,
3360 this.resolve_type(&*typedef.typ);
3368 // Check that the current type is indeed a type, if we have an anonymous impl
3369 if opt_trait_reference.is_none() {
3370 match self_type.node {
3371 // TyPath is the only thing that we handled in `build_reduced_graph_for_item`,
3372 // where we created a module with the name of the type in order to implement
3373 // an anonymous trait. In the case that the path does not resolve to an actual
3374 // type, the result will be that the type name resolves to a module but not
3375 // a type (shadowing any imported modules or types with this name), leading
3376 // to weird user-visible bugs. So we ward this off here. See #15060.
3377 TyPath(ref path, path_id) => {
3378 match self.def_map.borrow().get(&path_id) {
3379 // FIXME: should we catch other options and give more precise errors?
3380 Some(&DefMod(_)) => {
3381 self.resolve_error(path.span, "inherent implementations are not \
3382 allowed for types not defined in \
3383 the current module");
3393 fn check_trait_item(&self, name: Name, span: Span) {
3394 // If there is a TraitRef in scope for an impl, then the method must be in the trait.
3395 for &(did, ref trait_ref) in self.current_trait_ref.iter() {
3396 if self.trait_item_map.get(&(name, did)).is_none() {
3397 let path_str = self.path_names_to_string(&trait_ref.path);
3398 self.resolve_error(span,
3399 format!("method `{}` is not a member of trait `{}`",
3400 token::get_name(name),
3406 fn resolve_module(&mut self, module: &Mod, _span: Span,
3407 _name: Name, id: NodeId) {
3408 // Write the implementations in scope into the module metadata.
3409 debug!("(resolving module) resolving module ID {}", id);
3410 visit::walk_mod(self, module);
3413 fn resolve_local(&mut self, local: &Local) {
3414 // Resolve the type.
3415 if let Some(ref ty) = local.ty {
3416 self.resolve_type(&**ty);
3419 // Resolve the initializer, if necessary.
3424 Some(ref initializer) => {
3425 self.resolve_expr(&**initializer);
3429 // Resolve the pattern.
3430 let mut bindings_list = HashMap::new();
3431 self.resolve_pattern(&*local.pat,
3432 LocalIrrefutableMode,
3433 &mut bindings_list);
3436 // build a map from pattern identifiers to binding-info's.
3437 // this is done hygienically. This could arise for a macro
3438 // that expands into an or-pattern where one 'x' was from the
3439 // user and one 'x' came from the macro.
3440 fn binding_mode_map(&mut self, pat: &Pat) -> BindingMap {
3441 let mut result = HashMap::new();
3442 pat_bindings(&self.def_map, pat, |binding_mode, _id, sp, path1| {
3443 let name = mtwt::resolve(path1.node);
3444 result.insert(name, BindingInfo {
3446 binding_mode: binding_mode
3452 // check that all of the arms in an or-pattern have exactly the
3453 // same set of bindings, with the same binding modes for each.
3454 fn check_consistent_bindings(&mut self, arm: &Arm) {
3455 if arm.pats.len() == 0 {
3458 let map_0 = self.binding_mode_map(&*arm.pats[0]);
3459 for (i, p) in arm.pats.iter().enumerate() {
3460 let map_i = self.binding_mode_map(&**p);
3462 for (&key, &binding_0) in map_0.iter() {
3463 match map_i.get(&key) {
3467 format!("variable `{}` from pattern #1 is \
3468 not bound in pattern #{}",
3469 token::get_name(key),
3472 Some(binding_i) => {
3473 if binding_0.binding_mode != binding_i.binding_mode {
3476 format!("variable `{}` is bound with different \
3477 mode in pattern #{} than in pattern #1",
3478 token::get_name(key),
3485 for (&key, &binding) in map_i.iter() {
3486 if !map_0.contains_key(&key) {
3489 format!("variable `{}` from pattern {}{} is \
3490 not bound in pattern {}1",
3491 token::get_name(key),
3492 "#", i + 1, "#")[]);
3498 fn resolve_arm(&mut self, arm: &Arm) {
3499 self.value_ribs.push(Rib::new(NormalRibKind));
3501 let mut bindings_list = HashMap::new();
3502 for pattern in arm.pats.iter() {
3503 self.resolve_pattern(&**pattern, RefutableMode, &mut bindings_list);
3506 // This has to happen *after* we determine which
3507 // pat_idents are variants
3508 self.check_consistent_bindings(arm);
3510 visit::walk_expr_opt(self, &arm.guard);
3511 self.resolve_expr(&*arm.body);
3513 self.value_ribs.pop();
3516 fn resolve_block(&mut self, block: &Block) {
3517 debug!("(resolving block) entering block");
3518 self.value_ribs.push(Rib::new(NormalRibKind));
3520 // Move down in the graph, if there's an anonymous module rooted here.
3521 let orig_module = self.current_module.clone();
3522 match orig_module.anonymous_children.borrow().get(&block.id) {
3523 None => { /* Nothing to do. */ }
3524 Some(anonymous_module) => {
3525 debug!("(resolving block) found anonymous module, moving \
3527 self.current_module = anonymous_module.clone();
3531 // Descend into the block.
3532 visit::walk_block(self, block);
3535 self.current_module = orig_module;
3537 self.value_ribs.pop();
3538 debug!("(resolving block) leaving block");
3541 fn resolve_type(&mut self, ty: &Ty) {
3543 // Like path expressions, the interpretation of path types depends
3544 // on whether the path has multiple elements in it or not.
3546 TyPath(ref path, path_id) => {
3547 // This is a path in the type namespace. Walk through scopes
3549 let mut result_def = None;
3551 // First, check to see whether the name is a primitive type.
3552 if path.segments.len() == 1 {
3553 let id = path.segments.last().unwrap().identifier;
3555 match self.primitive_type_table
3559 Some(&primitive_type) => {
3561 Some((DefPrimTy(primitive_type), LastMod(AllPublic)));
3563 if path.segments[0].parameters.has_lifetimes() {
3564 span_err!(self.session, path.span, E0157,
3565 "lifetime parameters are not allowed on this type");
3566 } else if !path.segments[0].parameters.is_empty() {
3567 span_err!(self.session, path.span, E0153,
3568 "type parameters are not allowed on this type");
3579 match self.resolve_path(ty.id, path, TypeNS, true) {
3581 debug!("(resolving type) resolved `{}` to \
3583 token::get_ident(path.segments.last().unwrap() .identifier),
3585 result_def = Some(def);
3592 Some(_) => {} // Continue.
3597 // Write the result into the def map.
3598 debug!("(resolving type) writing resolution for `{}` \
3600 self.path_names_to_string(path),
3602 self.record_def(path_id, def);
3605 let msg = format!("use of undeclared type name `{}`",
3606 self.path_names_to_string(path));
3607 self.resolve_error(ty.span, msg[]);
3612 TyObjectSum(ref ty, ref bound_vec) => {
3613 self.resolve_type(&**ty);
3614 self.resolve_type_parameter_bounds(ty.id, bound_vec,
3615 TraitBoundingTypeParameter);
3618 TyQPath(ref qpath) => {
3619 self.resolve_type(&*qpath.self_type);
3620 self.resolve_trait_reference(ty.id, &*qpath.trait_ref, TraitQPath);
3623 TyPolyTraitRef(ref bounds) => {
3624 self.resolve_type_parameter_bounds(
3628 visit::walk_ty(self, ty);
3631 // Just resolve embedded types.
3632 visit::walk_ty(self, ty);
3637 fn resolve_pattern(&mut self,
3639 mode: PatternBindingMode,
3640 // Maps idents to the node ID for the (outermost)
3641 // pattern that binds them
3642 bindings_list: &mut HashMap<Name, NodeId>) {
3643 let pat_id = pattern.id;
3644 walk_pat(pattern, |pattern| {
3645 match pattern.node {
3646 PatIdent(binding_mode, ref path1, _) => {
3648 // The meaning of pat_ident with no type parameters
3649 // depends on whether an enum variant or unit-like struct
3650 // with that name is in scope. The probing lookup has to
3651 // be careful not to emit spurious errors. Only matching
3652 // patterns (match) can match nullary variants or
3653 // unit-like structs. For binding patterns (let), matching
3654 // such a value is simply disallowed (since it's rarely
3657 let ident = path1.node;
3658 let renamed = mtwt::resolve(ident);
3660 match self.resolve_bare_identifier_pattern(ident.name, pattern.span) {
3661 FoundStructOrEnumVariant(ref def, lp)
3662 if mode == RefutableMode => {
3663 debug!("(resolving pattern) resolving `{}` to \
3664 struct or enum variant",
3665 token::get_name(renamed));
3667 self.enforce_default_binding_mode(
3671 self.record_def(pattern.id, (def.clone(), lp));
3673 FoundStructOrEnumVariant(..) => {
3676 format!("declaration of `{}` shadows an enum \
3677 variant or unit-like struct in \
3679 token::get_name(renamed))[]);
3681 FoundConst(ref def, lp) if mode == RefutableMode => {
3682 debug!("(resolving pattern) resolving `{}` to \
3684 token::get_name(renamed));
3686 self.enforce_default_binding_mode(
3690 self.record_def(pattern.id, (def.clone(), lp));
3693 self.resolve_error(pattern.span,
3694 "only irrefutable patterns \
3697 BareIdentifierPatternUnresolved => {
3698 debug!("(resolving pattern) binding `{}`",
3699 token::get_name(renamed));
3701 let def = DefLocal(pattern.id);
3703 // Record the definition so that later passes
3704 // will be able to distinguish variants from
3705 // locals in patterns.
3707 self.record_def(pattern.id, (def, LastMod(AllPublic)));
3709 // Add the binding to the local ribs, if it
3710 // doesn't already exist in the bindings list. (We
3711 // must not add it if it's in the bindings list
3712 // because that breaks the assumptions later
3713 // passes make about or-patterns.)
3714 if !bindings_list.contains_key(&renamed) {
3715 let this = &mut *self;
3716 let last_rib = this.value_ribs.last_mut().unwrap();
3717 last_rib.bindings.insert(renamed, DlDef(def));
3718 bindings_list.insert(renamed, pat_id);
3719 } else if mode == ArgumentIrrefutableMode &&
3720 bindings_list.contains_key(&renamed) {
3721 // Forbid duplicate bindings in the same
3723 self.resolve_error(pattern.span,
3724 format!("identifier `{}` \
3732 } else if bindings_list.get(&renamed) ==
3734 // Then this is a duplicate variable in the
3735 // same disjunction, which is an error.
3736 self.resolve_error(pattern.span,
3737 format!("identifier `{}` is bound \
3738 more than once in the same \
3740 token::get_ident(ident))[]);
3742 // Else, not bound in the same pattern: do
3748 PatEnum(ref path, _) => {
3749 // This must be an enum variant, struct or const.
3750 match self.resolve_path(pat_id, path, ValueNS, false) {
3751 Some(def @ (DefVariant(..), _)) |
3752 Some(def @ (DefStruct(..), _)) |
3753 Some(def @ (DefConst(..), _)) => {
3754 self.record_def(pattern.id, def);
3756 Some((DefStatic(..), _)) => {
3757 self.resolve_error(path.span,
3758 "static variables cannot be \
3759 referenced in a pattern, \
3760 use a `const` instead");
3763 self.resolve_error(path.span,
3764 format!("`{}` is not an enum variant, struct or const",
3766 path.segments.last().unwrap().identifier))[]);
3769 self.resolve_error(path.span,
3770 format!("unresolved enum variant, struct or const `{}`",
3772 path.segments.last().unwrap().identifier))[]);
3776 // Check the types in the path pattern.
3777 for ty in path.segments
3779 .flat_map(|s| s.parameters.types().into_iter()) {
3780 self.resolve_type(&**ty);
3784 PatLit(ref expr) => {
3785 self.resolve_expr(&**expr);
3788 PatRange(ref first_expr, ref last_expr) => {
3789 self.resolve_expr(&**first_expr);
3790 self.resolve_expr(&**last_expr);
3793 PatStruct(ref path, _, _) => {
3794 match self.resolve_path(pat_id, path, TypeNS, false) {
3795 Some(definition) => {
3796 self.record_def(pattern.id, definition);
3799 debug!("(resolving pattern) didn't find struct \
3801 let msg = format!("`{}` does not name a structure",
3802 self.path_names_to_string(path));
3803 self.resolve_error(path.span, msg[]);
3816 fn resolve_bare_identifier_pattern(&mut self, name: Name, span: Span)
3817 -> BareIdentifierPatternResolution {
3818 let module = self.current_module.clone();
3819 match self.resolve_item_in_lexical_scope(module,
3822 Success((target, _)) => {
3823 debug!("(resolve bare identifier pattern) succeeded in \
3825 token::get_name(name),
3826 target.bindings.value_def.borrow());
3827 match *target.bindings.value_def.borrow() {
3829 panic!("resolved name in the value namespace to a \
3830 set of name bindings with no def?!");
3833 // For the two success cases, this lookup can be
3834 // considered as not having a private component because
3835 // the lookup happened only within the current module.
3837 def @ DefVariant(..) | def @ DefStruct(..) => {
3838 return FoundStructOrEnumVariant(def, LastMod(AllPublic));
3840 def @ DefConst(..) => {
3841 return FoundConst(def, LastMod(AllPublic));
3844 self.resolve_error(span,
3845 "static variables cannot be \
3846 referenced in a pattern, \
3847 use a `const` instead");
3848 return BareIdentifierPatternUnresolved;
3851 return BareIdentifierPatternUnresolved;
3859 panic!("unexpected indeterminate result");
3863 Some((span, msg)) => {
3864 self.resolve_error(span, format!("failed to resolve: {}",
3870 debug!("(resolve bare identifier pattern) failed to find {}",
3871 token::get_name(name));
3872 return BareIdentifierPatternUnresolved;
3877 /// If `check_ribs` is true, checks the local definitions first; i.e.
3878 /// doesn't skip straight to the containing module.
3879 fn resolve_path(&mut self,
3882 namespace: Namespace,
3883 check_ribs: bool) -> Option<(Def, LastPrivate)> {
3884 // First, resolve the types and associated type bindings.
3885 for ty in path.segments.iter().flat_map(|s| s.parameters.types().into_iter()) {
3886 self.resolve_type(&**ty);
3888 for binding in path.segments.iter().flat_map(|s| s.parameters.bindings().into_iter()) {
3889 self.resolve_type(&*binding.ty);
3892 // A special case for sugared associated type paths `T::A` where `T` is
3893 // a type parameter and `A` is an associated type on some bound of `T`.
3894 if namespace == TypeNS && path.segments.len() == 2 {
3895 match self.resolve_identifier(path.segments[0].identifier,
3899 Some((def, last_private)) => {
3901 DefTyParam(_, _, did, _) => {
3902 let def = DefAssociatedPath(TyParamProvenance::FromParam(did),
3903 path.segments.last()
3904 .unwrap().identifier);
3905 return Some((def, last_private));
3908 let def = DefAssociatedPath(TyParamProvenance::FromSelf(local_def(nid)),
3909 path.segments.last()
3910 .unwrap().identifier);
3911 return Some((def, last_private));
3921 return self.resolve_crate_relative_path(path, namespace);
3924 // Try to find a path to an item in a module.
3925 let unqualified_def =
3926 self.resolve_identifier(path.segments.last().unwrap().identifier,
3931 if path.segments.len() > 1 {
3932 let def = self.resolve_module_relative_path(path, namespace);
3933 match (def, unqualified_def) {
3934 (Some((ref d, _)), Some((ref ud, _))) if *d == *ud => {
3936 .add_lint(lint::builtin::UNUSED_QUALIFICATIONS,
3939 "unnecessary qualification".to_string());
3947 return unqualified_def;
3950 // resolve a single identifier (used as a varref)
3951 fn resolve_identifier(&mut self,
3953 namespace: Namespace,
3956 -> Option<(Def, LastPrivate)> {
3958 match self.resolve_identifier_in_local_ribs(identifier,
3962 return Some((def, LastMod(AllPublic)));
3970 return self.resolve_item_by_name_in_lexical_scope(identifier.name, namespace);
3973 // FIXME #4952: Merge me with resolve_name_in_module?
3974 fn resolve_definition_of_name_in_module(&mut self,
3975 containing_module: Rc<Module>,
3977 namespace: Namespace)
3979 // First, search children.
3980 build_reduced_graph::populate_module_if_necessary(self, &containing_module);
3982 match containing_module.children.borrow().get(&name) {
3983 Some(child_name_bindings) => {
3984 match child_name_bindings.def_for_namespace(namespace) {
3986 // Found it. Stop the search here.
3987 let p = child_name_bindings.defined_in_public_namespace(
3989 let lp = if p {LastMod(AllPublic)} else {
3990 LastMod(DependsOn(def.def_id()))
3992 return ChildNameDefinition(def, lp);
4000 // Next, search import resolutions.
4001 match containing_module.import_resolutions.borrow().get(&name) {
4002 Some(import_resolution) if import_resolution.is_public => {
4003 if let Some(target) = (*import_resolution).target_for_namespace(namespace) {
4004 match target.bindings.def_for_namespace(namespace) {
4007 let id = import_resolution.id(namespace);
4008 // track imports and extern crates as well
4009 self.used_imports.insert((id, namespace));
4010 self.record_import_use(id, name);
4011 match target.target_module.def_id.get() {
4012 Some(DefId{krate: kid, ..}) => {
4013 self.used_crates.insert(kid);
4017 return ImportNameDefinition(def, LastMod(AllPublic));
4020 // This can happen with external impls, due to
4021 // the imperfect way we read the metadata.
4026 Some(..) | None => {} // Continue.
4029 // Finally, search through external children.
4030 if namespace == TypeNS {
4031 if let Some(module) = containing_module.external_module_children.borrow()
4032 .get(&name).cloned() {
4033 if let Some(def_id) = module.def_id.get() {
4034 // track used crates
4035 self.used_crates.insert(def_id.krate);
4036 let lp = if module.is_public {LastMod(AllPublic)} else {
4037 LastMod(DependsOn(def_id))
4039 return ChildNameDefinition(DefMod(def_id), lp);
4044 return NoNameDefinition;
4047 // resolve a "module-relative" path, e.g. a::b::c
4048 fn resolve_module_relative_path(&mut self,
4050 namespace: Namespace)
4051 -> Option<(Def, LastPrivate)> {
4052 let module_path = path.segments.init().iter()
4053 .map(|ps| ps.identifier.name)
4054 .collect::<Vec<_>>();
4056 let containing_module;
4058 let module = self.current_module.clone();
4059 match self.resolve_module_path(module,
4065 let (span, msg) = match err {
4066 Some((span, msg)) => (span, msg),
4068 let msg = format!("Use of undeclared type or module `{}`",
4069 self.names_to_string(module_path.as_slice()));
4074 self.resolve_error(span, format!("failed to resolve. {}",
4078 Indeterminate => panic!("indeterminate unexpected"),
4079 Success((resulting_module, resulting_last_private)) => {
4080 containing_module = resulting_module;
4081 last_private = resulting_last_private;
4085 let name = path.segments.last().unwrap().identifier.name;
4086 let def = match self.resolve_definition_of_name_in_module(containing_module.clone(),
4089 NoNameDefinition => {
4090 // We failed to resolve the name. Report an error.
4093 ChildNameDefinition(def, lp) | ImportNameDefinition(def, lp) => {
4094 (def, last_private.or(lp))
4097 if let Some(DefId{krate: kid, ..}) = containing_module.def_id.get() {
4098 self.used_crates.insert(kid);
4103 /// Invariant: This must be called only during main resolution, not during
4104 /// import resolution.
4105 fn resolve_crate_relative_path(&mut self,
4107 namespace: Namespace)
4108 -> Option<(Def, LastPrivate)> {
4109 let module_path = path.segments.init().iter()
4110 .map(|ps| ps.identifier.name)
4111 .collect::<Vec<_>>();
4113 let root_module = self.graph_root.get_module();
4115 let containing_module;
4117 match self.resolve_module_path_from_root(root_module,
4122 LastMod(AllPublic)) {
4124 let (span, msg) = match err {
4125 Some((span, msg)) => (span, msg),
4127 let msg = format!("Use of undeclared module `::{}`",
4128 self.names_to_string(module_path[]));
4133 self.resolve_error(span, format!("failed to resolve. {}",
4139 panic!("indeterminate unexpected");
4142 Success((resulting_module, resulting_last_private)) => {
4143 containing_module = resulting_module;
4144 last_private = resulting_last_private;
4148 let name = path.segments.last().unwrap().identifier.name;
4149 match self.resolve_definition_of_name_in_module(containing_module,
4152 NoNameDefinition => {
4153 // We failed to resolve the name. Report an error.
4156 ChildNameDefinition(def, lp) | ImportNameDefinition(def, lp) => {
4157 return Some((def, last_private.or(lp)));
4162 fn resolve_identifier_in_local_ribs(&mut self,
4164 namespace: Namespace,
4167 // Check the local set of ribs.
4168 let search_result = match namespace {
4170 let renamed = mtwt::resolve(ident);
4171 self.search_ribs(self.value_ribs.as_slice(), renamed, span)
4174 let name = ident.name;
4175 self.search_ribs(self.type_ribs[], name, span)
4179 match search_result {
4180 Some(DlDef(def)) => {
4181 debug!("(resolving path in local ribs) resolved `{}` to \
4183 token::get_ident(ident),
4187 Some(DlField) | Some(DlImpl(_)) | None => {
4193 fn resolve_item_by_name_in_lexical_scope(&mut self,
4195 namespace: Namespace)
4196 -> Option<(Def, LastPrivate)> {
4198 let module = self.current_module.clone();
4199 match self.resolve_item_in_lexical_scope(module,
4202 Success((target, _)) => {
4203 match (*target.bindings).def_for_namespace(namespace) {
4205 // This can happen if we were looking for a type and
4206 // found a module instead. Modules don't have defs.
4207 debug!("(resolving item path by identifier in lexical \
4208 scope) failed to resolve {} after success...",
4209 token::get_name(name));
4213 debug!("(resolving item path in lexical scope) \
4214 resolved `{}` to item",
4215 token::get_name(name));
4216 // This lookup is "all public" because it only searched
4217 // for one identifier in the current module (couldn't
4218 // have passed through reexports or anything like that.
4219 return Some((def, LastMod(AllPublic)));
4224 panic!("unexpected indeterminate result");
4228 Some((span, msg)) =>
4229 self.resolve_error(span, format!("failed to resolve. {}",
4234 debug!("(resolving item path by identifier in lexical scope) \
4235 failed to resolve {}", token::get_name(name));
4241 fn with_no_errors<T, F>(&mut self, f: F) -> T where
4242 F: FnOnce(&mut Resolver) -> T,
4244 self.emit_errors = false;
4246 self.emit_errors = true;
4250 fn resolve_error(&self, span: Span, s: &str) {
4251 if self.emit_errors {
4252 self.session.span_err(span, s);
4256 fn find_fallback_in_self_type(&mut self, name: Name) -> FallbackSuggestion {
4257 fn extract_path_and_node_id(t: &Ty, allow: FallbackChecks)
4258 -> Option<(Path, NodeId, FallbackChecks)> {
4260 TyPath(ref path, node_id) => Some((path.clone(), node_id, allow)),
4261 TyPtr(ref mut_ty) => extract_path_and_node_id(&*mut_ty.ty, OnlyTraitAndStatics),
4262 TyRptr(_, ref mut_ty) => extract_path_and_node_id(&*mut_ty.ty, allow),
4263 // This doesn't handle the remaining `Ty` variants as they are not
4264 // that commonly the self_type, it might be interesting to provide
4265 // support for those in future.
4270 fn get_module(this: &mut Resolver, span: Span, name_path: &[ast::Name])
4271 -> Option<Rc<Module>> {
4272 let root = this.current_module.clone();
4273 let last_name = name_path.last().unwrap();
4275 if name_path.len() == 1 {
4276 match this.primitive_type_table.primitive_types.get(last_name) {
4279 match this.current_module.children.borrow().get(last_name) {
4280 Some(child) => child.get_module_if_available(),
4286 match this.resolve_module_path(root,
4291 Success((module, _)) => Some(module),
4297 let (path, node_id, allowed) = match self.current_self_type {
4298 Some(ref ty) => match extract_path_and_node_id(ty, Everything) {
4300 None => return NoSuggestion,
4302 None => return NoSuggestion,
4305 if allowed == Everything {
4306 // Look for a field with the same name in the current self_type.
4307 match self.def_map.borrow().get(&node_id) {
4308 Some(&DefTy(did, _))
4309 | Some(&DefStruct(did))
4310 | Some(&DefVariant(_, did, _)) => match self.structs.get(&did) {
4313 if fields.iter().any(|&field_name| name == field_name) {
4318 _ => {} // Self type didn't resolve properly
4322 let name_path = path.segments.iter().map(|seg| seg.identifier.name).collect::<Vec<_>>();
4324 // Look for a method in the current self type's impl module.
4325 match get_module(self, path.span, name_path[]) {
4326 Some(module) => match module.children.borrow().get(&name) {
4328 let p_str = self.path_names_to_string(&path);
4329 match binding.def_for_namespace(ValueNS) {
4330 Some(DefStaticMethod(_, provenance)) => {
4332 FromImpl(_) => return StaticMethod(p_str),
4333 FromTrait(_) => unreachable!()
4336 Some(DefMethod(_, None, _)) if allowed == Everything => return Method,
4337 Some(DefMethod(_, Some(_), _)) => return TraitItem,
4346 // Look for a method in the current trait.
4347 match self.current_trait_ref {
4348 Some((did, ref trait_ref)) => {
4349 let path_str = self.path_names_to_string(&trait_ref.path);
4351 match self.trait_item_map.get(&(name, did)) {
4352 Some(&StaticMethodTraitItemKind) => {
4353 return TraitMethod(path_str)
4355 Some(_) => return TraitItem,
4365 fn find_best_match_for_name(&mut self, name: &str, max_distance: uint)
4367 let this = &mut *self;
4369 let mut maybes: Vec<token::InternedString> = Vec::new();
4370 let mut values: Vec<uint> = Vec::new();
4372 for rib in this.value_ribs.iter().rev() {
4373 for (&k, _) in rib.bindings.iter() {
4374 maybes.push(token::get_name(k));
4375 values.push(uint::MAX);
4379 let mut smallest = 0;
4380 for (i, other) in maybes.iter().enumerate() {
4381 values[i] = lev_distance(name, other.get());
4383 if values[i] <= values[smallest] {
4388 if values.len() > 0 &&
4389 values[smallest] != uint::MAX &&
4390 values[smallest] < name.len() + 2 &&
4391 values[smallest] <= max_distance &&
4392 name != maybes[smallest].get() {
4394 Some(maybes[smallest].get().to_string())
4401 fn resolve_expr(&mut self, expr: &Expr) {
4402 // First, record candidate traits for this expression if it could
4403 // result in the invocation of a method call.
4405 self.record_candidate_traits_for_expr_if_necessary(expr);
4407 // Next, resolve the node.
4409 // The interpretation of paths depends on whether the path has
4410 // multiple elements in it or not.
4412 ExprPath(ref path) => {
4413 // This is a local path in the value namespace. Walk through
4414 // scopes looking for it.
4416 let path_name = self.path_names_to_string(path);
4418 match self.resolve_path(expr.id, path, ValueNS, true) {
4419 // Check if struct variant
4420 Some((DefVariant(_, _, true), _)) => {
4421 self.resolve_error(expr.span,
4422 format!("`{}` is a struct variant name, but \
4424 uses it like a function name",
4425 path_name).as_slice());
4427 self.session.span_help(expr.span,
4428 format!("Did you mean to write: \
4429 `{} {{ /* fields */ }}`?",
4430 path_name).as_slice());
4433 // Write the result into the def map.
4434 debug!("(resolving expr) resolved `{}`",
4437 self.record_def(expr.id, def);
4440 // Be helpful if the name refers to a struct
4441 // (The pattern matching def_tys where the id is in self.structs
4442 // matches on regular structs while excluding tuple- and enum-like
4443 // structs, which wouldn't result in this error.)
4444 match self.with_no_errors(|this|
4445 this.resolve_path(expr.id, path, TypeNS, false)) {
4446 Some((DefTy(struct_id, _), _))
4447 if self.structs.contains_key(&struct_id) => {
4448 self.resolve_error(expr.span,
4449 format!("`{}` is a structure name, but \
4451 uses it like a function name",
4452 path_name).as_slice());
4454 self.session.span_help(expr.span,
4455 format!("Did you mean to write: \
4456 `{} {{ /* fields */ }}`?",
4457 path_name).as_slice());
4461 let mut method_scope = false;
4462 self.value_ribs.iter().rev().all(|rib| {
4463 let res = match *rib {
4464 Rib { bindings: _, kind: MethodRibKind(_, _) } => true,
4465 Rib { bindings: _, kind: ItemRibKind } => false,
4466 _ => return true, // Keep advancing
4470 false // Stop advancing
4473 if method_scope && token::get_name(self.self_name).get()
4477 "`self` is not available \
4478 in a static method. Maybe a \
4479 `self` argument is missing?");
4481 let last_name = path.segments.last().unwrap().identifier.name;
4482 let mut msg = match self.find_fallback_in_self_type(last_name) {
4484 // limit search to 5 to reduce the number
4485 // of stupid suggestions
4486 self.find_best_match_for_name(path_name.as_slice(), 5)
4487 .map_or("".to_string(),
4488 |x| format!("`{}`", x))
4491 format!("`self.{}`", path_name),
4494 format!("to call `self.{}`", path_name),
4495 TraitMethod(path_str)
4496 | StaticMethod(path_str) =>
4497 format!("to call `{}::{}`", path_str, path_name)
4501 msg = format!(". Did you mean {}?", msg)
4506 format!("unresolved name `{}`{}",
4515 visit::walk_expr(self, expr);
4518 ExprClosure(capture_clause, _, ref fn_decl, ref block) => {
4519 self.capture_mode_map.insert(expr.id, capture_clause);
4520 self.resolve_function(ClosureRibKind(expr.id, ast::DUMMY_NODE_ID),
4521 Some(&**fn_decl), NoTypeParameters,
4525 ExprStruct(ref path, _, _) => {
4526 // Resolve the path to the structure it goes to. We don't
4527 // check to ensure that the path is actually a structure; that
4528 // is checked later during typeck.
4529 match self.resolve_path(expr.id, path, TypeNS, false) {
4530 Some(definition) => self.record_def(expr.id, definition),
4532 debug!("(resolving expression) didn't find struct \
4534 let msg = format!("`{}` does not name a structure",
4535 self.path_names_to_string(path));
4536 self.resolve_error(path.span, msg[]);
4540 visit::walk_expr(self, expr);
4543 ExprLoop(_, Some(label)) | ExprWhile(_, _, Some(label)) => {
4544 self.with_label_rib(|this| {
4545 let def_like = DlDef(DefLabel(expr.id));
4548 let rib = this.label_ribs.last_mut().unwrap();
4549 let renamed = mtwt::resolve(label);
4550 rib.bindings.insert(renamed, def_like);
4553 visit::walk_expr(this, expr);
4557 ExprForLoop(ref pattern, ref head, ref body, optional_label) => {
4558 self.resolve_expr(&**head);
4560 self.value_ribs.push(Rib::new(NormalRibKind));
4562 self.resolve_pattern(&**pattern,
4563 LocalIrrefutableMode,
4564 &mut HashMap::new());
4566 match optional_label {
4570 .push(Rib::new(NormalRibKind));
4571 let def_like = DlDef(DefLabel(expr.id));
4574 let rib = self.label_ribs.last_mut().unwrap();
4575 let renamed = mtwt::resolve(label);
4576 rib.bindings.insert(renamed, def_like);
4581 self.resolve_block(&**body);
4583 if optional_label.is_some() {
4584 drop(self.label_ribs.pop())
4587 self.value_ribs.pop();
4590 ExprBreak(Some(label)) | ExprAgain(Some(label)) => {
4591 let renamed = mtwt::resolve(label);
4592 match self.search_label(renamed) {
4596 format!("use of undeclared label `{}`",
4597 token::get_ident(label))[])
4599 Some(DlDef(def @ DefLabel(_))) => {
4600 // Since this def is a label, it is never read.
4601 self.record_def(expr.id, (def, LastMod(AllPublic)))
4604 self.session.span_bug(expr.span,
4605 "label wasn't mapped to a \
4612 visit::walk_expr(self, expr);
4617 fn record_candidate_traits_for_expr_if_necessary(&mut self, expr: &Expr) {
4619 ExprField(_, ident) => {
4620 // FIXME(#6890): Even though you can't treat a method like a
4621 // field, we need to add any trait methods we find that match
4622 // the field name so that we can do some nice error reporting
4623 // later on in typeck.
4624 let traits = self.search_for_traits_containing_method(ident.node.name);
4625 self.trait_map.insert(expr.id, traits);
4627 ExprMethodCall(ident, _, _) => {
4628 debug!("(recording candidate traits for expr) recording \
4631 let traits = self.search_for_traits_containing_method(ident.node.name);
4632 self.trait_map.insert(expr.id, traits);
4640 fn search_for_traits_containing_method(&mut self, name: Name) -> Vec<DefId> {
4641 debug!("(searching for traits containing method) looking for '{}'",
4642 token::get_name(name));
4644 fn add_trait_info(found_traits: &mut Vec<DefId>,
4645 trait_def_id: DefId,
4647 debug!("(adding trait info) found trait {}:{} for method '{}'",
4650 token::get_name(name));
4651 found_traits.push(trait_def_id);
4654 let mut found_traits = Vec::new();
4655 let mut search_module = self.current_module.clone();
4657 // Look for the current trait.
4658 match self.current_trait_ref {
4659 Some((trait_def_id, _)) => {
4660 if self.trait_item_map.contains_key(&(name, trait_def_id)) {
4661 add_trait_info(&mut found_traits, trait_def_id, name);
4664 None => {} // Nothing to do.
4667 // Look for trait children.
4668 build_reduced_graph::populate_module_if_necessary(self, &search_module);
4671 for (_, child_names) in search_module.children.borrow().iter() {
4672 let def = match child_names.def_for_namespace(TypeNS) {
4676 let trait_def_id = match def {
4677 DefTrait(trait_def_id) => trait_def_id,
4680 if self.trait_item_map.contains_key(&(name, trait_def_id)) {
4681 add_trait_info(&mut found_traits, trait_def_id, name);
4686 // Look for imports.
4687 for (_, import) in search_module.import_resolutions.borrow().iter() {
4688 let target = match import.target_for_namespace(TypeNS) {
4690 Some(target) => target,
4692 let did = match target.bindings.def_for_namespace(TypeNS) {
4693 Some(DefTrait(trait_def_id)) => trait_def_id,
4694 Some(..) | None => continue,
4696 if self.trait_item_map.contains_key(&(name, did)) {
4697 add_trait_info(&mut found_traits, did, name);
4698 let id = import.type_id;
4699 self.used_imports.insert((id, TypeNS));
4700 let trait_name = self.get_trait_name(did);
4701 self.record_import_use(id, trait_name);
4702 if let Some(DefId{krate: kid, ..}) = target.target_module.def_id.get() {
4703 self.used_crates.insert(kid);
4708 match search_module.parent_link.clone() {
4709 NoParentLink | ModuleParentLink(..) => break,
4710 BlockParentLink(parent_module, _) => {
4711 search_module = parent_module.upgrade().unwrap();
4719 fn record_def(&mut self, node_id: NodeId, (def, lp): (Def, LastPrivate)) {
4720 debug!("(recording def) recording {} for {}, last private {}",
4722 assert!(match lp {LastImport{..} => false, _ => true},
4723 "Import should only be used for `use` directives");
4724 self.last_private.insert(node_id, lp);
4726 match self.def_map.borrow_mut().entry(&node_id) {
4727 // Resolve appears to "resolve" the same ID multiple
4728 // times, so here is a sanity check it at least comes to
4729 // the same conclusion! - nmatsakis
4730 Occupied(entry) => if def != *entry.get() {
4732 .bug(format!("node_id {} resolved first to {} and \
4738 Vacant(entry) => { entry.insert(def); },
4742 fn enforce_default_binding_mode(&mut self,
4744 pat_binding_mode: BindingMode,
4746 match pat_binding_mode {
4747 BindByValue(_) => {}
4749 self.resolve_error(pat.span,
4750 format!("cannot use `ref` binding mode \
4760 // Diagnostics are not particularly efficient, because they're rarely
4764 /// A somewhat inefficient routine to obtain the name of a module.
4765 fn module_to_string(&self, module: &Module) -> String {
4766 let mut names = Vec::new();
4768 fn collect_mod(names: &mut Vec<ast::Name>, module: &Module) {
4769 match module.parent_link {
4771 ModuleParentLink(ref module, name) => {
4773 collect_mod(names, &*module.upgrade().unwrap());
4775 BlockParentLink(ref module, _) => {
4776 // danger, shouldn't be ident?
4777 names.push(special_idents::opaque.name);
4778 collect_mod(names, &*module.upgrade().unwrap());
4782 collect_mod(&mut names, module);
4784 if names.len() == 0 {
4785 return "???".to_string();
4787 self.names_to_string(names.into_iter().rev()
4788 .collect::<Vec<ast::Name>>()[])
4791 #[allow(dead_code)] // useful for debugging
4792 fn dump_module(&mut self, module_: Rc<Module>) {
4793 debug!("Dump of module `{}`:", self.module_to_string(&*module_));
4795 debug!("Children:");
4796 build_reduced_graph::populate_module_if_necessary(self, &module_);
4797 for (&name, _) in module_.children.borrow().iter() {
4798 debug!("* {}", token::get_name(name));
4801 debug!("Import resolutions:");
4802 let import_resolutions = module_.import_resolutions.borrow();
4803 for (&name, import_resolution) in import_resolutions.iter() {
4805 match import_resolution.target_for_namespace(ValueNS) {
4806 None => { value_repr = "".to_string(); }
4808 value_repr = " value:?".to_string();
4814 match import_resolution.target_for_namespace(TypeNS) {
4815 None => { type_repr = "".to_string(); }
4817 type_repr = " type:?".to_string();
4822 debug!("* {}:{}{}", token::get_name(name), value_repr, type_repr);
4827 pub struct CrateMap {
4828 pub def_map: DefMap,
4829 pub freevars: RefCell<FreevarMap>,
4830 pub capture_mode_map: RefCell<CaptureModeMap>,
4831 pub export_map: ExportMap,
4832 pub trait_map: TraitMap,
4833 pub external_exports: ExternalExports,
4834 pub last_private_map: LastPrivateMap,
4835 pub glob_map: Option<GlobMap>
4838 #[derive(PartialEq,Copy)]
4839 pub enum MakeGlobMap {
4844 /// Entry point to crate resolution.
4845 pub fn resolve_crate<'a, 'tcx>(session: &'a Session,
4846 ast_map: &'a ast_map::Map<'tcx>,
4849 make_glob_map: MakeGlobMap)
4851 let mut resolver = Resolver::new(session, ast_map, krate.span, make_glob_map);
4853 build_reduced_graph::build_reduced_graph(&mut resolver, krate);
4854 session.abort_if_errors();
4856 resolver.resolve_imports();
4857 session.abort_if_errors();
4859 record_exports::record(&mut resolver);
4860 session.abort_if_errors();
4862 resolver.resolve_crate(krate);
4863 session.abort_if_errors();
4865 check_unused::check_crate(&mut resolver, krate);
4868 def_map: resolver.def_map,
4869 freevars: resolver.freevars,
4870 capture_mode_map: RefCell::new(resolver.capture_mode_map),
4871 export_map: resolver.export_map,
4872 trait_map: resolver.trait_map,
4873 external_exports: resolver.external_exports,
4874 last_private_map: resolver.last_private,
4875 glob_map: if resolver.make_glob_map {
4876 Some(resolver.glob_map)