1 // Copyright 2012-2015 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 // Do not remove on snapshot creation. Needed for bootstrap. (Issue #22364)
12 #![cfg_attr(stage0, feature(custom_attribute))]
13 #![crate_name = "rustc_resolve"]
14 #![unstable(feature = "rustc_private")]
16 #![crate_type = "dylib"]
17 #![crate_type = "rlib"]
18 #![doc(html_logo_url = "http://www.rust-lang.org/logos/rust-logo-128x128-blk-v2.png",
19 html_favicon_url = "https://doc.rust-lang.org/favicon.ico",
20 html_root_url = "http://doc.rust-lang.org/nightly/")]
22 #![feature(associated_consts)]
24 #![feature(rustc_diagnostic_macros)]
25 #![feature(rustc_private)]
26 #![feature(slice_extras)]
27 #![feature(staged_api)]
29 #[macro_use] extern crate log;
30 #[macro_use] extern crate syntax;
31 #[macro_use] #[no_link] extern crate rustc_bitflags;
35 use self::PatternBindingMode::*;
36 use self::Namespace::*;
37 use self::NamespaceResult::*;
38 use self::NameDefinition::*;
39 use self::ResolveResult::*;
40 use self::FallbackSuggestion::*;
41 use self::TypeParameters::*;
43 use self::UseLexicalScopeFlag::*;
44 use self::ModulePrefixResult::*;
45 use self::AssocItemResolveResult::*;
46 use self::NameSearchType::*;
47 use self::BareIdentifierPatternResolution::*;
48 use self::ParentLink::*;
49 use self::ModuleKind::*;
50 use self::FallbackChecks::*;
53 use rustc::session::Session;
55 use rustc::metadata::csearch;
56 use rustc::metadata::decoder::{DefLike, DlDef, DlField, DlImpl};
57 use rustc::middle::def::*;
58 use rustc::middle::pat_util::pat_bindings;
59 use rustc::middle::privacy::*;
60 use rustc::middle::subst::{ParamSpace, FnSpace, TypeSpace};
61 use rustc::middle::ty::{Freevar, FreevarMap, TraitMap, GlobMap};
62 use rustc::util::nodemap::{NodeMap, NodeSet, DefIdSet, FnvHashMap};
63 use rustc::util::lev_distance::lev_distance;
65 use syntax::ast::{Arm, BindByRef, BindByValue, BindingMode, Block};
66 use syntax::ast::{ConstImplItem, Crate, CrateNum};
67 use syntax::ast::{DefId, Expr, ExprAgain, ExprBreak, ExprField};
68 use syntax::ast::{ExprLoop, ExprWhile, ExprMethodCall};
69 use syntax::ast::{ExprPath, ExprStruct, FnDecl};
70 use syntax::ast::{ForeignItemFn, ForeignItemStatic, Generics};
71 use syntax::ast::{Ident, ImplItem, Item, ItemConst, ItemEnum, ItemExternCrate};
72 use syntax::ast::{ItemFn, ItemForeignMod, ItemImpl, ItemMac, ItemMod, ItemStatic, ItemDefaultImpl};
73 use syntax::ast::{ItemStruct, ItemTrait, ItemTy, ItemUse};
74 use syntax::ast::{Local, MethodImplItem, Name, NodeId};
75 use syntax::ast::{Pat, PatEnum, PatIdent, PatLit, PatQPath};
76 use syntax::ast::{PatRange, PatStruct, Path, PrimTy};
77 use syntax::ast::{TraitRef, Ty, TyBool, TyChar, TyF32};
78 use syntax::ast::{TyF64, TyFloat, TyIs, TyI8, TyI16, TyI32, TyI64, TyInt};
79 use syntax::ast::{TyPath, TyPtr};
80 use syntax::ast::{TyRptr, TyStr, TyUs, TyU8, TyU16, TyU32, TyU64, TyUint};
81 use syntax::ast::TypeImplItem;
83 use syntax::ast_util::{local_def, walk_pat};
84 use syntax::attr::AttrMetaMethods;
85 use syntax::ext::mtwt;
86 use syntax::parse::token::{self, special_names, special_idents};
88 use syntax::codemap::{self, Span, Pos};
89 use syntax::visit::{self, Visitor};
91 use std::collections::{HashMap, HashSet};
92 use std::collections::hash_map::Entry::{Occupied, Vacant};
93 use std::cell::{Cell, RefCell};
95 use std::mem::replace;
96 use std::rc::{Rc, Weak};
99 use resolve_imports::{Target, ImportDirective, ImportResolution};
100 use resolve_imports::Shadowable;
102 // NB: This module needs to be declared first so diagnostics are
103 // registered before they are used.
106 macro_rules! resolve_err {
107 ($this:expr, $span:expr, $code:ident, $($rest:tt)*) => {
108 if $this.emit_errors {
109 span_err!($this.session, $span, $code, $($rest)*);
116 mod build_reduced_graph;
119 pub enum ResolutionError<'b, 'a:'b, 'tcx:'a> {
120 /// error: static variables cannot be referenced in a pattern
121 StaticVariableReference(&'b Resolver<'a, 'tcx>, syntax::codemap::Span),
122 /// error: does not name a struct
123 DoesNotNameAStruct(&'b Resolver<'a, 'tcx>, syntax::codemap::Span),
124 /// error: is a struct variant name, but this expression uses it like a function name
125 StructVariantUsedAsFunction(&'a Resolver<'a, 'tcx>, syntax::codemap::Span),
126 /// error: unresolved import
127 UnresolvedImport(&'b Resolver<'a, 'tcx>, syntax::codemap::Span),
128 /// error: failed to resolve
129 FailedToResolve(&'b Resolver<'a, 'tcx>, syntax::codemap::Span),
132 fn resolve_error<'b, 'a:'b, 'tcx:'a>(resolution_error: &ResolutionError<'b, 'a, 'tcx>, formatted: &str) {
133 match resolution_error {
134 &ResolutionError::StaticVariableReference(resolver, span) => {
135 resolve_err!(resolver, span, E0417, "{}", formatted);
137 &ResolutionError::DoesNotNameAStruct(resolver, span) => {
138 resolve_err!(resolver, span, E0422, "{}", formatted);
140 &ResolutionError::StructVariantUsedAsFunction(resolver, span) => {
141 resolve_err!(resolver, span, E0423, "{}", formatted);
143 &ResolutionError::UnresolvedImport(resolver, span) => {
144 resolve_err!(resolver, span, E0432, "{}", formatted);
146 &ResolutionError::FailedToResolve(resolver, span) => {
147 resolve_err!(resolver, span, E0433, "{}", formatted);
152 #[derive(Copy, Clone)]
155 binding_mode: BindingMode,
158 // Map from the name in a pattern to its binding mode.
159 type BindingMap = HashMap<Name, BindingInfo>;
161 #[derive(Copy, Clone, PartialEq)]
162 enum PatternBindingMode {
164 LocalIrrefutableMode,
165 ArgumentIrrefutableMode,
168 #[derive(Copy, Clone, PartialEq, Eq, Hash, Debug)]
174 /// A NamespaceResult represents the result of resolving an import in
175 /// a particular namespace. The result is either definitely-resolved,
176 /// definitely- unresolved, or unknown.
178 enum NamespaceResult {
179 /// Means that resolve hasn't gathered enough information yet to determine
180 /// whether the name is bound in this namespace. (That is, it hasn't
181 /// resolved all `use` directives yet.)
183 /// Means that resolve has determined that the name is definitely
184 /// not bound in the namespace.
186 /// Means that resolve has determined that the name is bound in the Module
187 /// argument, and specified by the NameBindings argument.
188 BoundResult(Rc<Module>, Rc<NameBindings>)
191 impl NamespaceResult {
192 fn is_unknown(&self) -> bool {
194 UnknownResult => true,
198 fn is_unbound(&self) -> bool {
200 UnboundResult => true,
206 enum NameDefinition {
207 // The name was unbound.
209 // The name identifies an immediate child.
210 ChildNameDefinition(Def, LastPrivate),
211 // The name identifies an import.
212 ImportNameDefinition(Def, LastPrivate),
215 impl<'a, 'v, 'tcx> Visitor<'v> for Resolver<'a, 'tcx> {
216 fn visit_item(&mut self, item: &Item) {
217 self.resolve_item(item);
219 fn visit_arm(&mut self, arm: &Arm) {
220 self.resolve_arm(arm);
222 fn visit_block(&mut self, block: &Block) {
223 self.resolve_block(block);
225 fn visit_expr(&mut self, expr: &Expr) {
226 self.resolve_expr(expr);
228 fn visit_local(&mut self, local: &Local) {
229 self.resolve_local(local);
231 fn visit_ty(&mut self, ty: &Ty) {
232 self.resolve_type(ty);
234 fn visit_generics(&mut self, generics: &Generics) {
235 self.resolve_generics(generics);
237 fn visit_poly_trait_ref(&mut self,
238 tref: &ast::PolyTraitRef,
239 m: &ast::TraitBoundModifier) {
240 match self.resolve_trait_reference(tref.trait_ref.ref_id, &tref.trait_ref.path, 0) {
241 Ok(def) => self.record_def(tref.trait_ref.ref_id, def),
242 Err(_) => { /* error already reported */ }
244 visit::walk_poly_trait_ref(self, tref, m);
246 fn visit_variant(&mut self, variant: &ast::Variant, generics: &Generics) {
247 if let Some(ref dis_expr) = variant.node.disr_expr {
248 // resolve the discriminator expr as a constant
249 self.with_constant_rib(|this| {
250 this.visit_expr(&**dis_expr);
254 // `visit::walk_variant` without the discriminant expression.
255 match variant.node.kind {
256 ast::TupleVariantKind(ref variant_arguments) => {
257 for variant_argument in variant_arguments {
258 self.visit_ty(&*variant_argument.ty);
261 ast::StructVariantKind(ref struct_definition) => {
262 self.visit_struct_def(&**struct_definition,
269 fn visit_foreign_item(&mut self, foreign_item: &ast::ForeignItem) {
270 let type_parameters = match foreign_item.node {
271 ForeignItemFn(_, ref generics) => {
272 HasTypeParameters(generics, FnSpace, ItemRibKind)
274 ForeignItemStatic(..) => NoTypeParameters
276 self.with_type_parameter_rib(type_parameters, |this| {
277 visit::walk_foreign_item(this, foreign_item);
280 fn visit_fn(&mut self,
281 function_kind: visit::FnKind<'v>,
282 declaration: &'v FnDecl,
286 let rib_kind = match function_kind {
287 visit::FkItemFn(_, generics, _, _, _, _) => {
288 self.visit_generics(generics);
291 visit::FkMethod(_, sig, _) => {
292 self.visit_generics(&sig.generics);
293 self.visit_explicit_self(&sig.explicit_self);
296 visit::FkFnBlock(..) => ClosureRibKind(node_id)
298 self.resolve_function(rib_kind, declaration, block);
302 type ErrorMessage = Option<(Span, String)>;
304 enum ResolveResult<T> {
305 Failed(ErrorMessage), // Failed to resolve the name, optional helpful error message.
306 Indeterminate, // Couldn't determine due to unresolved globs.
307 Success(T) // Successfully resolved the import.
310 impl<T> ResolveResult<T> {
311 fn indeterminate(&self) -> bool {
312 match *self { Indeterminate => true, _ => false }
316 enum FallbackSuggestion {
321 StaticMethod(String),
325 #[derive(Copy, Clone)]
326 enum TypeParameters<'a> {
332 // Identifies the things that these parameters
333 // were declared on (type, fn, etc)
336 // The kind of the rib used for type parameters.
340 // The rib kind controls the translation of local
341 // definitions (`DefLocal`) to upvars (`DefUpvar`).
342 #[derive(Copy, Clone, Debug)]
344 // No translation needs to be applied.
347 // We passed through a closure scope at the given node ID.
348 // Translate upvars as appropriate.
349 ClosureRibKind(NodeId /* func id */),
351 // We passed through an impl or trait and are now in one of its
352 // methods. Allow references to ty params that impl or trait
353 // binds. Disallow any other upvars (including other ty params that are
357 // We passed through an item scope. Disallow upvars.
360 // We're in a constant item. Can't refer to dynamic stuff.
364 #[derive(Copy, Clone)]
365 enum UseLexicalScopeFlag {
370 enum ModulePrefixResult {
372 PrefixFound(Rc<Module>, usize)
375 #[derive(Copy, Clone)]
376 enum AssocItemResolveResult {
377 /// Syntax such as `<T>::item`, which can't be resolved until type
380 /// We should have been able to resolve the associated item.
381 ResolveAttempt(Option<PathResolution>),
384 #[derive(Copy, Clone, PartialEq)]
385 enum NameSearchType {
386 /// We're doing a name search in order to resolve a `use` directive.
389 /// We're doing a name search in order to resolve a path type, a path
390 /// expression, or a path pattern.
394 #[derive(Copy, Clone)]
395 enum BareIdentifierPatternResolution {
396 FoundStructOrEnumVariant(Def, LastPrivate),
397 FoundConst(Def, LastPrivate),
398 BareIdentifierPatternUnresolved
404 bindings: HashMap<Name, DefLike>,
409 fn new(kind: RibKind) -> Rib {
411 bindings: HashMap::new(),
417 /// The link from a module up to its nearest parent node.
418 #[derive(Clone,Debug)]
421 ModuleParentLink(Weak<Module>, Name),
422 BlockParentLink(Weak<Module>, NodeId)
425 /// The type of module this is.
426 #[derive(Copy, Clone, PartialEq, Debug)]
435 /// One node in the tree of modules.
437 parent_link: ParentLink,
438 def_id: Cell<Option<DefId>>,
439 kind: Cell<ModuleKind>,
442 children: RefCell<HashMap<Name, Rc<NameBindings>>>,
443 imports: RefCell<Vec<ImportDirective>>,
445 // The external module children of this node that were declared with
447 external_module_children: RefCell<HashMap<Name, Rc<Module>>>,
449 // The anonymous children of this node. Anonymous children are pseudo-
450 // modules that are implicitly created around items contained within
453 // For example, if we have this:
461 // There will be an anonymous module created around `g` with the ID of the
462 // entry block for `f`.
463 anonymous_children: RefCell<NodeMap<Rc<Module>>>,
465 // The status of resolving each import in this module.
466 import_resolutions: RefCell<HashMap<Name, ImportResolution>>,
468 // The number of unresolved globs that this module exports.
469 glob_count: Cell<usize>,
471 // The index of the import we're resolving.
472 resolved_import_count: Cell<usize>,
474 // Whether this module is populated. If not populated, any attempt to
475 // access the children must be preceded with a
476 // `populate_module_if_necessary` call.
477 populated: Cell<bool>,
481 fn new(parent_link: ParentLink,
482 def_id: Option<DefId>,
488 parent_link: parent_link,
489 def_id: Cell::new(def_id),
490 kind: Cell::new(kind),
491 is_public: is_public,
492 children: RefCell::new(HashMap::new()),
493 imports: RefCell::new(Vec::new()),
494 external_module_children: RefCell::new(HashMap::new()),
495 anonymous_children: RefCell::new(NodeMap()),
496 import_resolutions: RefCell::new(HashMap::new()),
497 glob_count: Cell::new(0),
498 resolved_import_count: Cell::new(0),
499 populated: Cell::new(!external),
503 fn all_imports_resolved(&self) -> bool {
504 self.imports.borrow().len() == self.resolved_import_count.get()
508 impl fmt::Debug for Module {
509 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
510 write!(f, "{:?}, kind: {:?}, {}",
513 if self.is_public { "public" } else { "private" } )
519 flags DefModifiers: u8 {
520 const PUBLIC = 1 << 0,
521 const IMPORTABLE = 1 << 1,
525 // Records a possibly-private type definition.
526 #[derive(Clone,Debug)]
528 modifiers: DefModifiers, // see note in ImportResolution about how to use this
529 module_def: Option<Rc<Module>>,
530 type_def: Option<Def>,
531 type_span: Option<Span>
534 // Records a possibly-private value definition.
535 #[derive(Clone, Copy, Debug)]
537 modifiers: DefModifiers, // see note in ImportResolution about how to use this
539 value_span: Option<Span>,
542 // Records the definitions (at most one for each namespace) that a name is
545 pub struct NameBindings {
546 type_def: RefCell<Option<TypeNsDef>>, //< Meaning in type namespace.
547 value_def: RefCell<Option<ValueNsDef>>, //< Meaning in value namespace.
551 fn new() -> NameBindings {
553 type_def: RefCell::new(None),
554 value_def: RefCell::new(None),
558 /// Creates a new module in this set of name bindings.
559 fn define_module(&self,
560 parent_link: ParentLink,
561 def_id: Option<DefId>,
566 // Merges the module with the existing type def or creates a new one.
567 let modifiers = if is_public {
570 DefModifiers::empty()
571 } | DefModifiers::IMPORTABLE;
572 let module_ = Rc::new(Module::new(parent_link,
577 let type_def = self.type_def.borrow().clone();
580 *self.type_def.borrow_mut() = Some(TypeNsDef {
581 modifiers: modifiers,
582 module_def: Some(module_),
588 *self.type_def.borrow_mut() = Some(TypeNsDef {
589 modifiers: modifiers,
590 module_def: Some(module_),
592 type_def: type_def.type_def
598 /// Sets the kind of the module, creating a new one if necessary.
599 fn set_module_kind(&self,
600 parent_link: ParentLink,
601 def_id: Option<DefId>,
606 let modifiers = if is_public {
609 DefModifiers::empty()
610 } | DefModifiers::IMPORTABLE;
611 let type_def = self.type_def.borrow().clone();
614 let module = Module::new(parent_link,
619 *self.type_def.borrow_mut() = Some(TypeNsDef {
620 modifiers: modifiers,
621 module_def: Some(Rc::new(module)),
627 match type_def.module_def {
629 let module = Module::new(parent_link,
634 *self.type_def.borrow_mut() = Some(TypeNsDef {
635 modifiers: modifiers,
636 module_def: Some(Rc::new(module)),
637 type_def: type_def.type_def,
641 Some(module_def) => module_def.kind.set(kind),
647 /// Records a type definition.
648 fn define_type(&self, def: Def, sp: Span, modifiers: DefModifiers) {
649 debug!("defining type for def {:?} with modifiers {:?}", def, modifiers);
650 // Merges the type with the existing type def or creates a new one.
651 let type_def = self.type_def.borrow().clone();
654 *self.type_def.borrow_mut() = Some(TypeNsDef {
658 modifiers: modifiers,
662 *self.type_def.borrow_mut() = Some(TypeNsDef {
663 module_def: type_def.module_def,
666 modifiers: modifiers,
672 /// Records a value definition.
673 fn define_value(&self, def: Def, sp: Span, modifiers: DefModifiers) {
674 debug!("defining value for def {:?} with modifiers {:?}", def, modifiers);
675 *self.value_def.borrow_mut() = Some(ValueNsDef {
677 value_span: Some(sp),
678 modifiers: modifiers,
682 /// Returns the module node if applicable.
683 fn get_module_if_available(&self) -> Option<Rc<Module>> {
684 match *self.type_def.borrow() {
685 Some(ref type_def) => type_def.module_def.clone(),
690 /// Returns the module node. Panics if this node does not have a module
692 fn get_module(&self) -> Rc<Module> {
693 match self.get_module_if_available() {
695 panic!("get_module called on a node with no module \
698 Some(module_def) => module_def
702 fn defined_in_namespace(&self, namespace: Namespace) -> bool {
704 TypeNS => return self.type_def.borrow().is_some(),
705 ValueNS => return self.value_def.borrow().is_some()
709 fn defined_in_public_namespace(&self, namespace: Namespace) -> bool {
710 self.defined_in_namespace_with(namespace, DefModifiers::PUBLIC)
713 fn defined_in_namespace_with(&self, namespace: Namespace, modifiers: DefModifiers) -> bool {
715 TypeNS => match *self.type_def.borrow() {
716 Some(ref def) => def.modifiers.contains(modifiers), None => false
718 ValueNS => match *self.value_def.borrow() {
719 Some(ref def) => def.modifiers.contains(modifiers), None => false
724 fn def_for_namespace(&self, namespace: Namespace) -> Option<Def> {
727 match *self.type_def.borrow() {
729 Some(ref type_def) => {
730 match type_def.type_def {
731 Some(type_def) => Some(type_def),
733 match type_def.module_def {
734 Some(ref module) => {
735 match module.def_id.get() {
736 Some(did) => Some(DefMod(did)),
748 match *self.value_def.borrow() {
750 Some(value_def) => Some(value_def.def)
756 fn span_for_namespace(&self, namespace: Namespace) -> Option<Span> {
757 if self.defined_in_namespace(namespace) {
760 match *self.type_def.borrow() {
762 Some(ref type_def) => type_def.type_span
766 match *self.value_def.borrow() {
768 Some(ref value_def) => value_def.value_span
777 fn is_public(&self, namespace: Namespace) -> bool {
780 let type_def = self.type_def.borrow();
781 type_def.as_ref().unwrap().modifiers.contains(DefModifiers::PUBLIC)
784 let value_def = self.value_def.borrow();
785 value_def.as_ref().unwrap().modifiers.contains(DefModifiers::PUBLIC)
791 /// Interns the names of the primitive types.
792 struct PrimitiveTypeTable {
793 primitive_types: HashMap<Name, PrimTy>,
796 impl PrimitiveTypeTable {
797 fn new() -> PrimitiveTypeTable {
798 let mut table = PrimitiveTypeTable {
799 primitive_types: HashMap::new()
802 table.intern("bool", TyBool);
803 table.intern("char", TyChar);
804 table.intern("f32", TyFloat(TyF32));
805 table.intern("f64", TyFloat(TyF64));
806 table.intern("isize", TyInt(TyIs));
807 table.intern("i8", TyInt(TyI8));
808 table.intern("i16", TyInt(TyI16));
809 table.intern("i32", TyInt(TyI32));
810 table.intern("i64", TyInt(TyI64));
811 table.intern("str", TyStr);
812 table.intern("usize", TyUint(TyUs));
813 table.intern("u8", TyUint(TyU8));
814 table.intern("u16", TyUint(TyU16));
815 table.intern("u32", TyUint(TyU32));
816 table.intern("u64", TyUint(TyU64));
821 fn intern(&mut self, string: &str, primitive_type: PrimTy) {
822 self.primitive_types.insert(token::intern(string), primitive_type);
826 /// The main resolver class.
827 pub struct Resolver<'a, 'tcx:'a> {
828 session: &'a Session,
830 ast_map: &'a ast_map::Map<'tcx>,
832 graph_root: NameBindings,
834 trait_item_map: FnvHashMap<(Name, DefId), DefId>,
836 structs: FnvHashMap<DefId, Vec<Name>>,
838 // The number of imports that are currently unresolved.
839 unresolved_imports: usize,
841 // The module that represents the current item scope.
842 current_module: Rc<Module>,
844 // The current set of local scopes, for values.
845 // FIXME #4948: Reuse ribs to avoid allocation.
846 value_ribs: Vec<Rib>,
848 // The current set of local scopes, for types.
851 // The current set of local scopes, for labels.
852 label_ribs: Vec<Rib>,
854 // The trait that the current context can refer to.
855 current_trait_ref: Option<(DefId, TraitRef)>,
857 // The current self type if inside an impl (used for better errors).
858 current_self_type: Option<Ty>,
860 // The idents for the primitive types.
861 primitive_type_table: PrimitiveTypeTable,
864 freevars: RefCell<FreevarMap>,
865 freevars_seen: RefCell<NodeMap<NodeSet>>,
866 export_map: ExportMap,
868 external_exports: ExternalExports,
870 // Whether or not to print error messages. Can be set to true
871 // when getting additional info for error message suggestions,
872 // so as to avoid printing duplicate errors
876 // Maps imports to the names of items actually imported (this actually maps
877 // all imports, but only glob imports are actually interesting).
880 used_imports: HashSet<(NodeId, Namespace)>,
881 used_crates: HashSet<CrateNum>,
885 enum FallbackChecks {
890 impl<'a, 'tcx> Resolver<'a, 'tcx> {
891 fn new(session: &'a Session,
892 ast_map: &'a ast_map::Map<'tcx>,
894 make_glob_map: MakeGlobMap) -> Resolver<'a, 'tcx> {
895 let graph_root = NameBindings::new();
897 graph_root.define_module(NoParentLink,
898 Some(DefId { krate: 0, node: 0 }),
904 let current_module = graph_root.get_module();
911 // The outermost module has def ID 0; this is not reflected in the
914 graph_root: graph_root,
916 trait_item_map: FnvHashMap(),
917 structs: FnvHashMap(),
919 unresolved_imports: 0,
921 current_module: current_module,
922 value_ribs: Vec::new(),
923 type_ribs: Vec::new(),
924 label_ribs: Vec::new(),
926 current_trait_ref: None,
927 current_self_type: None,
929 primitive_type_table: PrimitiveTypeTable::new(),
931 def_map: RefCell::new(NodeMap()),
932 freevars: RefCell::new(NodeMap()),
933 freevars_seen: RefCell::new(NodeMap()),
934 export_map: NodeMap(),
935 trait_map: NodeMap(),
936 used_imports: HashSet::new(),
937 used_crates: HashSet::new(),
938 external_exports: DefIdSet(),
941 make_glob_map: make_glob_map == MakeGlobMap::Yes,
942 glob_map: HashMap::new(),
947 fn record_import_use(&mut self, import_id: NodeId, name: Name) {
948 if !self.make_glob_map {
951 if self.glob_map.contains_key(&import_id) {
952 self.glob_map.get_mut(&import_id).unwrap().insert(name);
956 let mut new_set = HashSet::new();
957 new_set.insert(name);
958 self.glob_map.insert(import_id, new_set);
961 fn get_trait_name(&self, did: DefId) -> Name {
962 if did.krate == ast::LOCAL_CRATE {
963 self.ast_map.expect_item(did.node).ident.name
965 csearch::get_trait_name(&self.session.cstore, did)
969 fn create_name_bindings_from_module(module: Rc<Module>) -> NameBindings {
971 type_def: RefCell::new(Some(TypeNsDef {
972 modifiers: DefModifiers::IMPORTABLE,
973 module_def: Some(module),
977 value_def: RefCell::new(None),
981 /// Checks that the names of external crates don't collide with other
983 fn check_for_conflicts_between_external_crates(&self,
987 if module.external_module_children.borrow().contains_key(&name) {
988 span_err!(self.session, span, E0259,
989 "an external crate named `{}` has already \
990 been imported into this module",
995 /// Checks that the names of items don't collide with external crates.
996 fn check_for_conflicts_between_external_crates_and_items(&self,
1000 if module.external_module_children.borrow().contains_key(&name) {
1001 span_err!(self.session, span, E0260,
1002 "the name `{}` conflicts with an external \
1003 crate that has been imported into this \
1009 /// Resolves the given module path from the given root `module_`.
1010 fn resolve_module_path_from_root(&mut self,
1011 module_: Rc<Module>,
1012 module_path: &[Name],
1015 name_search_type: NameSearchType,
1017 -> ResolveResult<(Rc<Module>, LastPrivate)> {
1018 fn search_parent_externals(needle: Name, module: &Rc<Module>)
1019 -> Option<Rc<Module>> {
1020 match module.external_module_children.borrow().get(&needle) {
1021 Some(_) => Some(module.clone()),
1022 None => match module.parent_link {
1023 ModuleParentLink(ref parent, _) => {
1024 search_parent_externals(needle, &parent.upgrade().unwrap())
1031 let mut search_module = module_;
1032 let mut index = index;
1033 let module_path_len = module_path.len();
1034 let mut closest_private = lp;
1036 // Resolve the module part of the path. This does not involve looking
1037 // upward though scope chains; we simply resolve names directly in
1038 // modules as we go.
1039 while index < module_path_len {
1040 let name = module_path[index];
1041 match self.resolve_name_in_module(search_module.clone(),
1047 let segment_name = token::get_name(name);
1048 let module_name = module_to_string(&*search_module);
1049 let mut span = span;
1050 let msg = if "???" == &module_name[..] {
1051 span.hi = span.lo + Pos::from_usize(segment_name.len());
1053 match search_parent_externals(name,
1054 &self.current_module) {
1056 let path_str = names_to_string(module_path);
1057 let target_mod_str = module_to_string(&*module);
1058 let current_mod_str =
1059 module_to_string(&*self.current_module);
1061 let prefix = if target_mod_str == current_mod_str {
1062 "self::".to_string()
1064 format!("{}::", target_mod_str)
1067 format!("Did you mean `{}{}`?", prefix, path_str)
1069 None => format!("Maybe a missing `extern crate {}`?",
1073 format!("Could not find `{}` in `{}`",
1078 return Failed(Some((span, msg)));
1080 Failed(err) => return Failed(err),
1082 debug!("(resolving module path for import) module \
1083 resolution is indeterminate: {}",
1085 return Indeterminate;
1087 Success((target, used_proxy)) => {
1088 // Check to see whether there are type bindings, and, if
1089 // so, whether there is a module within.
1090 match *target.bindings.type_def.borrow() {
1091 Some(ref type_def) => {
1092 match type_def.module_def {
1094 let msg = format!("Not a module `{}`",
1097 return Failed(Some((span, msg)));
1099 Some(ref module_def) => {
1100 search_module = module_def.clone();
1102 // track extern crates for unused_extern_crate lint
1103 if let Some(did) = module_def.def_id.get() {
1104 self.used_crates.insert(did.krate);
1107 // Keep track of the closest
1108 // private module used when
1109 // resolving this import chain.
1110 if !used_proxy && !search_module.is_public {
1111 if let Some(did) = search_module.def_id.get() {
1112 closest_private = LastMod(DependsOn(did));
1119 // There are no type bindings at all.
1120 let msg = format!("Not a module `{}`",
1122 return Failed(Some((span, msg)));
1131 return Success((search_module, closest_private));
1134 /// Attempts to resolve the module part of an import directive or path
1135 /// rooted at the given module.
1137 /// On success, returns the resolved module, and the closest *private*
1138 /// module found to the destination when resolving this path.
1139 fn resolve_module_path(&mut self,
1140 module_: Rc<Module>,
1141 module_path: &[Name],
1142 use_lexical_scope: UseLexicalScopeFlag,
1144 name_search_type: NameSearchType)
1145 -> ResolveResult<(Rc<Module>, LastPrivate)> {
1146 let module_path_len = module_path.len();
1147 assert!(module_path_len > 0);
1149 debug!("(resolving module path for import) processing `{}` rooted at `{}`",
1150 names_to_string(module_path),
1151 module_to_string(&*module_));
1153 // Resolve the module prefix, if any.
1154 let module_prefix_result = self.resolve_module_prefix(module_.clone(),
1160 match module_prefix_result {
1162 let mpath = names_to_string(module_path);
1163 let mpath = &mpath[..];
1164 match mpath.rfind(':') {
1166 let msg = format!("Could not find `{}` in `{}`",
1167 // idx +- 1 to account for the
1168 // colons on either side
1171 return Failed(Some((span, msg)));
1178 Failed(err) => return Failed(err),
1180 debug!("(resolving module path for import) indeterminate; \
1182 return Indeterminate;
1184 Success(NoPrefixFound) => {
1185 // There was no prefix, so we're considering the first element
1186 // of the path. How we handle this depends on whether we were
1187 // instructed to use lexical scope or not.
1188 match use_lexical_scope {
1189 DontUseLexicalScope => {
1190 // This is a crate-relative path. We will start the
1191 // resolution process at index zero.
1192 search_module = self.graph_root.get_module();
1194 last_private = LastMod(AllPublic);
1196 UseLexicalScope => {
1197 // This is not a crate-relative path. We resolve the
1198 // first component of the path in the current lexical
1199 // scope and then proceed to resolve below that.
1200 match self.resolve_module_in_lexical_scope(module_,
1202 Failed(err) => return Failed(err),
1204 debug!("(resolving module path for import) \
1205 indeterminate; bailing");
1206 return Indeterminate;
1208 Success(containing_module) => {
1209 search_module = containing_module;
1211 last_private = LastMod(AllPublic);
1217 Success(PrefixFound(ref containing_module, index)) => {
1218 search_module = containing_module.clone();
1219 start_index = index;
1220 last_private = LastMod(DependsOn(containing_module.def_id
1226 self.resolve_module_path_from_root(search_module,
1234 /// Invariant: This must only be called during main resolution, not during
1235 /// import resolution.
1236 fn resolve_item_in_lexical_scope(&mut self,
1237 module_: Rc<Module>,
1239 namespace: Namespace)
1240 -> ResolveResult<(Target, bool)> {
1241 debug!("(resolving item in lexical scope) resolving `{}` in \
1242 namespace {:?} in `{}`",
1245 module_to_string(&*module_));
1247 // The current module node is handled specially. First, check for
1248 // its immediate children.
1249 build_reduced_graph::populate_module_if_necessary(self, &module_);
1251 match module_.children.borrow().get(&name) {
1253 if name_bindings.defined_in_namespace(namespace) => {
1254 debug!("top name bindings succeeded");
1255 return Success((Target::new(module_.clone(),
1256 name_bindings.clone(),
1260 Some(_) | None => { /* Not found; continue. */ }
1263 // Now check for its import directives. We don't have to have resolved
1264 // all its imports in the usual way; this is because chains of
1265 // adjacent import statements are processed as though they mutated the
1267 if let Some(import_resolution) = module_.import_resolutions.borrow().get(&name) {
1268 match (*import_resolution).target_for_namespace(namespace) {
1270 // Not found; continue.
1271 debug!("(resolving item in lexical scope) found \
1272 import resolution, but not in namespace {:?}",
1276 debug!("(resolving item in lexical scope) using \
1277 import resolution");
1278 // track used imports and extern crates as well
1279 let id = import_resolution.id(namespace);
1280 self.used_imports.insert((id, namespace));
1281 self.record_import_use(id, name);
1282 if let Some(DefId{krate: kid, ..}) = target.target_module.def_id.get() {
1283 self.used_crates.insert(kid);
1285 return Success((target, false));
1290 // Search for external modules.
1291 if namespace == TypeNS {
1292 // FIXME (21114): In principle unclear `child` *has* to be lifted.
1293 let child = module_.external_module_children.borrow().get(&name).cloned();
1294 if let Some(module) = child {
1296 Rc::new(Resolver::create_name_bindings_from_module(module));
1297 debug!("lower name bindings succeeded");
1298 return Success((Target::new(module_,
1305 // Finally, proceed up the scope chain looking for parent modules.
1306 let mut search_module = module_;
1308 // Go to the next parent.
1309 match search_module.parent_link.clone() {
1311 // No more parents. This module was unresolved.
1312 debug!("(resolving item in lexical scope) unresolved \
1314 return Failed(None);
1316 ModuleParentLink(parent_module_node, _) => {
1317 match search_module.kind.get() {
1318 NormalModuleKind => {
1319 // We stop the search here.
1320 debug!("(resolving item in lexical \
1321 scope) unresolved module: not \
1322 searching through module \
1324 return Failed(None);
1329 AnonymousModuleKind => {
1330 search_module = parent_module_node.upgrade().unwrap();
1334 BlockParentLink(ref parent_module_node, _) => {
1335 search_module = parent_module_node.upgrade().unwrap();
1339 // Resolve the name in the parent module.
1340 match self.resolve_name_in_module(search_module.clone(),
1345 Failed(Some((span, msg))) => {
1346 resolve_error(&ResolutionError::FailedToResolve(self, span),
1347 &*format!("failed to resolve. {}",
1351 Failed(None) => (), // Continue up the search chain.
1353 // We couldn't see through the higher scope because of an
1354 // unresolved import higher up. Bail.
1356 debug!("(resolving item in lexical scope) indeterminate \
1357 higher scope; bailing");
1358 return Indeterminate;
1360 Success((target, used_reexport)) => {
1361 // We found the module.
1362 debug!("(resolving item in lexical scope) found name \
1364 return Success((target, used_reexport));
1370 /// Resolves a module name in the current lexical scope.
1371 fn resolve_module_in_lexical_scope(&mut self,
1372 module_: Rc<Module>,
1374 -> ResolveResult<Rc<Module>> {
1375 // If this module is an anonymous module, resolve the item in the
1376 // lexical scope. Otherwise, resolve the item from the crate root.
1377 let resolve_result = self.resolve_item_in_lexical_scope(module_, name, TypeNS);
1378 match resolve_result {
1379 Success((target, _)) => {
1380 let bindings = &*target.bindings;
1381 match *bindings.type_def.borrow() {
1382 Some(ref type_def) => {
1383 match type_def.module_def {
1385 debug!("!!! (resolving module in lexical \
1386 scope) module wasn't actually a \
1388 return Failed(None);
1390 Some(ref module_def) => {
1391 return Success(module_def.clone());
1396 debug!("!!! (resolving module in lexical scope) module
1397 wasn't actually a module!");
1398 return Failed(None);
1403 debug!("(resolving module in lexical scope) indeterminate; \
1405 return Indeterminate;
1408 debug!("(resolving module in lexical scope) failed to resolve");
1414 /// Returns the nearest normal module parent of the given module.
1415 fn get_nearest_normal_module_parent(&mut self, module_: Rc<Module>)
1416 -> Option<Rc<Module>> {
1417 let mut module_ = module_;
1419 match module_.parent_link.clone() {
1420 NoParentLink => return None,
1421 ModuleParentLink(new_module, _) |
1422 BlockParentLink(new_module, _) => {
1423 let new_module = new_module.upgrade().unwrap();
1424 match new_module.kind.get() {
1425 NormalModuleKind => return Some(new_module),
1429 AnonymousModuleKind => module_ = new_module,
1436 /// Returns the nearest normal module parent of the given module, or the
1437 /// module itself if it is a normal module.
1438 fn get_nearest_normal_module_parent_or_self(&mut self, module_: Rc<Module>)
1440 match module_.kind.get() {
1441 NormalModuleKind => return module_,
1445 AnonymousModuleKind => {
1446 match self.get_nearest_normal_module_parent(module_.clone()) {
1448 Some(new_module) => new_module
1454 /// Resolves a "module prefix". A module prefix is one or both of (a) `self::`;
1455 /// (b) some chain of `super::`.
1456 /// grammar: (SELF MOD_SEP ) ? (SUPER MOD_SEP) *
1457 fn resolve_module_prefix(&mut self,
1458 module_: Rc<Module>,
1459 module_path: &[Name])
1460 -> ResolveResult<ModulePrefixResult> {
1461 // Start at the current module if we see `self` or `super`, or at the
1462 // top of the crate otherwise.
1463 let mut containing_module;
1465 let first_module_path_string = token::get_name(module_path[0]);
1466 if "self" == &first_module_path_string[..] {
1468 self.get_nearest_normal_module_parent_or_self(module_);
1470 } else if "super" == &first_module_path_string[..] {
1472 self.get_nearest_normal_module_parent_or_self(module_);
1473 i = 0; // We'll handle `super` below.
1475 return Success(NoPrefixFound);
1478 // Now loop through all the `super`s we find.
1479 while i < module_path.len() {
1480 let string = token::get_name(module_path[i]);
1481 if "super" != &string[..] {
1484 debug!("(resolving module prefix) resolving `super` at {}",
1485 module_to_string(&*containing_module));
1486 match self.get_nearest_normal_module_parent(containing_module) {
1487 None => return Failed(None),
1488 Some(new_module) => {
1489 containing_module = new_module;
1495 debug!("(resolving module prefix) finished resolving prefix at {}",
1496 module_to_string(&*containing_module));
1498 return Success(PrefixFound(containing_module, i));
1501 /// Attempts to resolve the supplied name in the given module for the
1502 /// given namespace. If successful, returns the target corresponding to
1505 /// The boolean returned on success is an indicator of whether this lookup
1506 /// passed through a public re-export proxy.
1507 fn resolve_name_in_module(&mut self,
1508 module_: Rc<Module>,
1510 namespace: Namespace,
1511 name_search_type: NameSearchType,
1512 allow_private_imports: bool)
1513 -> ResolveResult<(Target, bool)> {
1514 debug!("(resolving name in module) resolving `{}` in `{}`",
1516 module_to_string(&*module_));
1518 // First, check the direct children of the module.
1519 build_reduced_graph::populate_module_if_necessary(self, &module_);
1521 match module_.children.borrow().get(&name) {
1523 if name_bindings.defined_in_namespace(namespace) => {
1524 debug!("(resolving name in module) found node as child");
1525 return Success((Target::new(module_.clone(),
1526 name_bindings.clone(),
1535 // Next, check the module's imports if necessary.
1537 // If this is a search of all imports, we should be done with glob
1538 // resolution at this point.
1539 if name_search_type == PathSearch {
1540 assert_eq!(module_.glob_count.get(), 0);
1543 // Check the list of resolved imports.
1544 match module_.import_resolutions.borrow().get(&name) {
1545 Some(import_resolution) if allow_private_imports ||
1546 import_resolution.is_public => {
1548 if import_resolution.is_public &&
1549 import_resolution.outstanding_references != 0 {
1550 debug!("(resolving name in module) import \
1551 unresolved; bailing out");
1552 return Indeterminate;
1554 match import_resolution.target_for_namespace(namespace) {
1556 debug!("(resolving name in module) name found, \
1557 but not in namespace {:?}",
1561 debug!("(resolving name in module) resolved to \
1563 // track used imports and extern crates as well
1564 let id = import_resolution.id(namespace);
1565 self.used_imports.insert((id, namespace));
1566 self.record_import_use(id, name);
1567 if let Some(DefId{krate: kid, ..}) = target.target_module.def_id.get() {
1568 self.used_crates.insert(kid);
1570 return Success((target, true));
1574 Some(..) | None => {} // Continue.
1577 // Finally, search through external children.
1578 if namespace == TypeNS {
1579 // FIXME (21114): In principle unclear `child` *has* to be lifted.
1580 let child = module_.external_module_children.borrow().get(&name).cloned();
1581 if let Some(module) = child {
1583 Rc::new(Resolver::create_name_bindings_from_module(module));
1584 return Success((Target::new(module_,
1591 // We're out of luck.
1592 debug!("(resolving name in module) failed to resolve `{}`",
1594 return Failed(None);
1597 fn report_unresolved_imports(&mut self, module_: Rc<Module>) {
1598 let index = module_.resolved_import_count.get();
1599 let imports = module_.imports.borrow();
1600 let import_count = imports.len();
1601 if index != import_count {
1602 let sn = self.session
1604 .span_to_snippet((*imports)[index].span)
1606 if sn.contains("::") {
1607 resolve_error(&ResolutionError::UnresolvedImport(self, (*imports)[index].span),
1608 "unresolved import");
1610 resolve_error(&ResolutionError::UnresolvedImport(self, (*imports)[index].span),
1611 &*format!("unresolved import (maybe you meant `{}::*`?)",
1617 // Descend into children and anonymous children.
1618 build_reduced_graph::populate_module_if_necessary(self, &module_);
1620 for (_, child_node) in module_.children.borrow().iter() {
1621 match child_node.get_module_if_available() {
1625 Some(child_module) => {
1626 self.report_unresolved_imports(child_module);
1631 for (_, module_) in module_.anonymous_children.borrow().iter() {
1632 self.report_unresolved_imports(module_.clone());
1638 // We maintain a list of value ribs and type ribs.
1640 // Simultaneously, we keep track of the current position in the module
1641 // graph in the `current_module` pointer. When we go to resolve a name in
1642 // the value or type namespaces, we first look through all the ribs and
1643 // then query the module graph. When we resolve a name in the module
1644 // namespace, we can skip all the ribs (since nested modules are not
1645 // allowed within blocks in Rust) and jump straight to the current module
1648 // Named implementations are handled separately. When we find a method
1649 // call, we consult the module node to find all of the implementations in
1650 // scope. This information is lazily cached in the module node. We then
1651 // generate a fake "implementation scope" containing all the
1652 // implementations thus found, for compatibility with old resolve pass.
1654 fn with_scope<F>(&mut self, name: Option<Name>, f: F) where
1655 F: FnOnce(&mut Resolver),
1657 let orig_module = self.current_module.clone();
1659 // Move down in the graph.
1665 build_reduced_graph::populate_module_if_necessary(self, &orig_module);
1667 match orig_module.children.borrow().get(&name) {
1669 debug!("!!! (with scope) didn't find `{}` in `{}`",
1671 module_to_string(&*orig_module));
1673 Some(name_bindings) => {
1674 match (*name_bindings).get_module_if_available() {
1676 debug!("!!! (with scope) didn't find module \
1679 module_to_string(&*orig_module));
1682 self.current_module = module_;
1692 self.current_module = orig_module;
1695 /// Wraps the given definition in the appropriate number of `DefUpvar`
1701 -> Option<DefLike> {
1702 let mut def = match def_like {
1704 _ => return Some(def_like)
1708 self.session.span_bug(span,
1709 &format!("unexpected {:?} in bindings", def))
1711 DefLocal(node_id) => {
1715 // Nothing to do. Continue.
1717 ClosureRibKind(function_id) => {
1719 def = DefUpvar(node_id, function_id);
1721 let mut seen = self.freevars_seen.borrow_mut();
1722 let seen = match seen.entry(function_id) {
1723 Occupied(v) => v.into_mut(),
1724 Vacant(v) => v.insert(NodeSet()),
1726 if seen.contains(&node_id) {
1729 match self.freevars.borrow_mut().entry(function_id) {
1730 Occupied(v) => v.into_mut(),
1731 Vacant(v) => v.insert(vec![]),
1732 }.push(Freevar { def: prev_def, span: span });
1733 seen.insert(node_id);
1735 ItemRibKind | MethodRibKind => {
1736 // This was an attempt to access an upvar inside a
1737 // named function item. This is not allowed, so we
1739 resolve_err!(self, span, E0434, "{}",
1740 "can't capture dynamic environment in a fn item; \
1741 use the || { ... } closure form instead");
1744 ConstantItemRibKind => {
1745 // Still doesn't deal with upvars
1746 resolve_err!(self, span, E0435, "{}",
1747 "attempt to use a non-constant \
1748 value in a constant");
1754 DefTyParam(..) | DefSelfTy(..) => {
1757 NormalRibKind | MethodRibKind | ClosureRibKind(..) => {
1758 // Nothing to do. Continue.
1761 // This was an attempt to use a type parameter outside
1764 resolve_err!(self, span, E0401, "{}",
1765 "can't use type parameters from \
1766 outer function; try using a local \
1767 type parameter instead");
1770 ConstantItemRibKind => {
1772 resolve_err!(self, span, E0402, "{}",
1773 "cannot use an outer type \
1774 parameter in this context");
1785 /// Searches the current set of local scopes and
1786 /// applies translations for closures.
1787 fn search_ribs(&self,
1791 -> Option<DefLike> {
1792 // FIXME #4950: Try caching?
1794 for (i, rib) in ribs.iter().enumerate().rev() {
1795 if let Some(def_like) = rib.bindings.get(&name).cloned() {
1796 return self.upvarify(&ribs[i + 1..], def_like, span);
1803 /// Searches the current set of local scopes for labels.
1804 /// Stops after meeting a closure.
1805 fn search_label(&self, name: Name) -> Option<DefLike> {
1806 for rib in self.label_ribs.iter().rev() {
1812 // Do not resolve labels across function boundary
1816 let result = rib.bindings.get(&name).cloned();
1817 if result.is_some() {
1824 fn resolve_crate(&mut self, krate: &ast::Crate) {
1825 debug!("(resolving crate) starting");
1827 visit::walk_crate(self, krate);
1830 fn check_if_primitive_type_name(&self, name: Name, span: Span) {
1831 if let Some(_) = self.primitive_type_table.primitive_types.get(&name) {
1832 span_err!(self.session, span, E0317,
1833 "user-defined types or type parameters cannot shadow the primitive types");
1837 fn resolve_item(&mut self, item: &Item) {
1838 let name = item.ident.name;
1840 debug!("(resolving item) resolving {}",
1844 ItemEnum(_, ref generics) |
1845 ItemTy(_, ref generics) |
1846 ItemStruct(_, ref generics) => {
1847 self.check_if_primitive_type_name(name, item.span);
1849 self.with_type_parameter_rib(HasTypeParameters(generics,
1852 |this| visit::walk_item(this, item));
1854 ItemFn(_, _, _, _, ref generics, _) => {
1855 self.with_type_parameter_rib(HasTypeParameters(generics,
1858 |this| visit::walk_item(this, item));
1861 ItemDefaultImpl(_, ref trait_ref) => {
1862 self.with_optional_trait_ref(Some(trait_ref), |_, _| {});
1869 ref impl_items) => {
1870 self.resolve_implementation(generics,
1877 ItemTrait(_, ref generics, ref bounds, ref trait_items) => {
1878 self.check_if_primitive_type_name(name, item.span);
1880 // Create a new rib for the trait-wide type parameters.
1881 self.with_type_parameter_rib(HasTypeParameters(generics,
1885 this.with_self_rib(DefSelfTy(Some(local_def(item.id)), None), |this| {
1886 this.visit_generics(generics);
1887 visit::walk_ty_param_bounds_helper(this, bounds);
1889 for trait_item in trait_items {
1890 // Create a new rib for the trait_item-specific type
1893 // FIXME #4951: Do we need a node ID here?
1895 match trait_item.node {
1896 ast::ConstTraitItem(_, ref default) => {
1897 // Only impose the restrictions of
1898 // ConstRibKind if there's an actual constant
1899 // expression in a provided default.
1900 if default.is_some() {
1901 this.with_constant_rib(|this| {
1902 visit::walk_trait_item(this, trait_item)
1905 visit::walk_trait_item(this, trait_item)
1908 ast::MethodTraitItem(ref sig, _) => {
1909 let type_parameters =
1910 HasTypeParameters(&sig.generics,
1913 this.with_type_parameter_rib(type_parameters, |this| {
1914 visit::walk_trait_item(this, trait_item)
1917 ast::TypeTraitItem(..) => {
1918 this.check_if_primitive_type_name(trait_item.ident.name,
1920 this.with_type_parameter_rib(NoTypeParameters, |this| {
1921 visit::walk_trait_item(this, trait_item)
1930 ItemMod(_) | ItemForeignMod(_) => {
1931 self.with_scope(Some(name), |this| {
1932 visit::walk_item(this, item);
1936 ItemConst(..) | ItemStatic(..) => {
1937 self.with_constant_rib(|this| {
1938 visit::walk_item(this, item);
1942 ItemUse(ref view_path) => {
1943 // check for imports shadowing primitive types
1944 if let ast::ViewPathSimple(ident, _) = view_path.node {
1945 match self.def_map.borrow().get(&item.id).map(|d| d.full_def()) {
1946 Some(DefTy(..)) | Some(DefStruct(..)) | Some(DefTrait(..)) | None => {
1947 self.check_if_primitive_type_name(ident.name, item.span);
1954 ItemExternCrate(_) | ItemMac(..) => {
1955 // do nothing, these are just around to be encoded
1960 fn with_type_parameter_rib<F>(&mut self, type_parameters: TypeParameters, f: F) where
1961 F: FnOnce(&mut Resolver),
1963 match type_parameters {
1964 HasTypeParameters(generics, space, rib_kind) => {
1965 let mut function_type_rib = Rib::new(rib_kind);
1966 let mut seen_bindings = HashSet::new();
1967 for (index, type_parameter) in generics.ty_params.iter().enumerate() {
1968 let name = type_parameter.ident.name;
1969 debug!("with_type_parameter_rib: {}", type_parameter.id);
1971 if seen_bindings.contains(&name) {
1972 resolve_err!(self, type_parameter.span, E0403,
1973 "the name `{}` is already \
1975 parameter in this type \
1979 seen_bindings.insert(name);
1981 // plain insert (no renaming)
1982 function_type_rib.bindings.insert(name,
1983 DlDef(DefTyParam(space,
1985 local_def(type_parameter.id),
1988 self.type_ribs.push(function_type_rib);
1991 NoTypeParameters => {
1998 match type_parameters {
1999 HasTypeParameters(..) => { self.type_ribs.pop(); }
2000 NoTypeParameters => { }
2004 fn with_label_rib<F>(&mut self, f: F) where
2005 F: FnOnce(&mut Resolver),
2007 self.label_ribs.push(Rib::new(NormalRibKind));
2009 self.label_ribs.pop();
2012 fn with_constant_rib<F>(&mut self, f: F) where
2013 F: FnOnce(&mut Resolver),
2015 self.value_ribs.push(Rib::new(ConstantItemRibKind));
2016 self.type_ribs.push(Rib::new(ConstantItemRibKind));
2018 self.type_ribs.pop();
2019 self.value_ribs.pop();
2022 fn resolve_function(&mut self,
2024 declaration: &FnDecl,
2026 // Create a value rib for the function.
2027 self.value_ribs.push(Rib::new(rib_kind));
2029 // Create a label rib for the function.
2030 self.label_ribs.push(Rib::new(rib_kind));
2032 // Add each argument to the rib.
2033 let mut bindings_list = HashMap::new();
2034 for argument in &declaration.inputs {
2035 self.resolve_pattern(&*argument.pat,
2036 ArgumentIrrefutableMode,
2037 &mut bindings_list);
2039 self.visit_ty(&*argument.ty);
2041 debug!("(resolving function) recorded argument");
2043 visit::walk_fn_ret_ty(self, &declaration.output);
2045 // Resolve the function body.
2046 self.visit_block(&*block);
2048 debug!("(resolving function) leaving function");
2050 self.label_ribs.pop();
2051 self.value_ribs.pop();
2054 fn resolve_trait_reference(&mut self,
2058 -> Result<PathResolution, ()> {
2059 if let Some(path_res) = self.resolve_path(id, trait_path, path_depth, TypeNS, true) {
2060 if let DefTrait(_) = path_res.base_def {
2061 debug!("(resolving trait) found trait def: {:?}", path_res);
2064 resolve_err!(self, trait_path.span, E0404,
2065 "`{}` is not a trait",
2066 path_names_to_string(trait_path, path_depth));
2068 // If it's a typedef, give a note
2069 if let DefTy(..) = path_res.base_def {
2070 self.session.span_note(trait_path.span,
2071 "`type` aliases cannot be used for traits");
2076 resolve_err!(self, trait_path.span, E0405,
2077 "use of undeclared trait name `{}`",
2078 path_names_to_string(trait_path, path_depth));
2083 fn resolve_generics(&mut self, generics: &Generics) {
2084 for type_parameter in generics.ty_params.iter() {
2085 self.check_if_primitive_type_name(type_parameter.ident.name, type_parameter.span);
2087 for predicate in &generics.where_clause.predicates {
2089 &ast::WherePredicate::BoundPredicate(_) |
2090 &ast::WherePredicate::RegionPredicate(_) => {}
2091 &ast::WherePredicate::EqPredicate(ref eq_pred) => {
2092 let path_res = self.resolve_path(eq_pred.id, &eq_pred.path, 0, TypeNS, true);
2093 if let Some(PathResolution { base_def: DefTyParam(..), .. }) = path_res {
2094 self.record_def(eq_pred.id, path_res.unwrap());
2096 resolve_err!(self, eq_pred.span, E0406, "{}",
2097 "undeclared associated type");
2102 visit::walk_generics(self, generics);
2105 fn with_current_self_type<T, F>(&mut self, self_type: &Ty, f: F) -> T
2106 where F: FnOnce(&mut Resolver) -> T
2108 // Handle nested impls (inside fn bodies)
2109 let previous_value = replace(&mut self.current_self_type, Some(self_type.clone()));
2110 let result = f(self);
2111 self.current_self_type = previous_value;
2115 fn with_optional_trait_ref<T, F>(&mut self,
2116 opt_trait_ref: Option<&TraitRef>,
2119 where F: FnOnce(&mut Resolver, Option<DefId>) -> T
2121 let mut new_val = None;
2122 let mut new_id = None;
2123 if let Some(trait_ref) = opt_trait_ref {
2124 if let Ok(path_res) = self.resolve_trait_reference(trait_ref.ref_id,
2125 &trait_ref.path, 0) {
2126 assert!(path_res.depth == 0);
2127 self.record_def(trait_ref.ref_id, path_res);
2128 new_val = Some((path_res.base_def.def_id(), trait_ref.clone()));
2129 new_id = Some(path_res.base_def.def_id());
2131 visit::walk_trait_ref(self, trait_ref);
2133 let original_trait_ref = replace(&mut self.current_trait_ref, new_val);
2134 let result = f(self, new_id);
2135 self.current_trait_ref = original_trait_ref;
2139 fn with_self_rib<F>(&mut self, self_def: Def, f: F)
2140 where F: FnOnce(&mut Resolver)
2142 let mut self_type_rib = Rib::new(NormalRibKind);
2144 // plain insert (no renaming, types are not currently hygienic....)
2145 let name = special_names::type_self;
2146 self_type_rib.bindings.insert(name, DlDef(self_def));
2147 self.type_ribs.push(self_type_rib);
2149 self.type_ribs.pop();
2152 fn resolve_implementation(&mut self,
2153 generics: &Generics,
2154 opt_trait_reference: &Option<TraitRef>,
2157 impl_items: &[P<ImplItem>]) {
2158 // If applicable, create a rib for the type parameters.
2159 self.with_type_parameter_rib(HasTypeParameters(generics,
2163 // Resolve the type parameters.
2164 this.visit_generics(generics);
2166 // Resolve the trait reference, if necessary.
2167 this.with_optional_trait_ref(opt_trait_reference.as_ref(), |this, trait_id| {
2168 // Resolve the self type.
2169 this.visit_ty(self_type);
2171 this.with_self_rib(DefSelfTy(trait_id, Some((item_id, self_type.id))), |this| {
2172 this.with_current_self_type(self_type, |this| {
2173 for impl_item in impl_items {
2174 match impl_item.node {
2175 ConstImplItem(..) => {
2176 // If this is a trait impl, ensure the method
2178 this.check_trait_item(impl_item.ident.name,
2180 this.with_constant_rib(|this| {
2181 visit::walk_impl_item(this, impl_item);
2184 MethodImplItem(ref sig, _) => {
2185 // If this is a trait impl, ensure the method
2187 this.check_trait_item(impl_item.ident.name,
2190 // We also need a new scope for the method-
2191 // specific type parameters.
2192 let type_parameters =
2193 HasTypeParameters(&sig.generics,
2196 this.with_type_parameter_rib(type_parameters, |this| {
2197 visit::walk_impl_item(this, impl_item);
2200 TypeImplItem(ref ty) => {
2201 // If this is a trait impl, ensure the method
2203 this.check_trait_item(impl_item.ident.name,
2208 ast::MacImplItem(_) => {}
2217 fn check_trait_item(&self, name: Name, span: Span) {
2218 // If there is a TraitRef in scope for an impl, then the method must be in the trait.
2219 if let Some((did, ref trait_ref)) = self.current_trait_ref {
2220 if !self.trait_item_map.contains_key(&(name, did)) {
2221 let path_str = path_names_to_string(&trait_ref.path, 0);
2222 resolve_err!(self, span, E0407, "method `{}` is not a member of trait `{}`",
2228 fn resolve_local(&mut self, local: &Local) {
2229 // Resolve the type.
2230 visit::walk_ty_opt(self, &local.ty);
2232 // Resolve the initializer.
2233 visit::walk_expr_opt(self, &local.init);
2235 // Resolve the pattern.
2236 self.resolve_pattern(&*local.pat,
2237 LocalIrrefutableMode,
2238 &mut HashMap::new());
2241 // build a map from pattern identifiers to binding-info's.
2242 // this is done hygienically. This could arise for a macro
2243 // that expands into an or-pattern where one 'x' was from the
2244 // user and one 'x' came from the macro.
2245 fn binding_mode_map(&mut self, pat: &Pat) -> BindingMap {
2246 let mut result = HashMap::new();
2247 pat_bindings(&self.def_map, pat, |binding_mode, _id, sp, path1| {
2248 let name = mtwt::resolve(path1.node);
2249 result.insert(name, BindingInfo {
2251 binding_mode: binding_mode
2257 // check that all of the arms in an or-pattern have exactly the
2258 // same set of bindings, with the same binding modes for each.
2259 fn check_consistent_bindings(&mut self, arm: &Arm) {
2260 if arm.pats.is_empty() {
2263 let map_0 = self.binding_mode_map(&*arm.pats[0]);
2264 for (i, p) in arm.pats.iter().enumerate() {
2265 let map_i = self.binding_mode_map(&**p);
2267 for (&key, &binding_0) in &map_0 {
2268 match map_i.get(&key) {
2270 resolve_err!(self, p.span, E0408,
2271 "variable `{}` from pattern #1 is \
2272 not bound in pattern #{}",
2276 Some(binding_i) => {
2277 if binding_0.binding_mode != binding_i.binding_mode {
2278 resolve_err!(self, binding_i.span, E0409,
2279 "variable `{}` is bound with different \
2280 mode in pattern #{} than in pattern #1",
2288 for (&key, &binding) in &map_i {
2289 if !map_0.contains_key(&key) {
2290 resolve_err!(self, binding.span, E0410,
2291 "variable `{}` from pattern #{} is \
2292 not bound in pattern #1",
2300 fn resolve_arm(&mut self, arm: &Arm) {
2301 self.value_ribs.push(Rib::new(NormalRibKind));
2303 let mut bindings_list = HashMap::new();
2304 for pattern in &arm.pats {
2305 self.resolve_pattern(&**pattern, RefutableMode, &mut bindings_list);
2308 // This has to happen *after* we determine which
2309 // pat_idents are variants
2310 self.check_consistent_bindings(arm);
2312 visit::walk_expr_opt(self, &arm.guard);
2313 self.visit_expr(&*arm.body);
2315 self.value_ribs.pop();
2318 fn resolve_block(&mut self, block: &Block) {
2319 debug!("(resolving block) entering block");
2320 self.value_ribs.push(Rib::new(NormalRibKind));
2322 // Move down in the graph, if there's an anonymous module rooted here.
2323 let orig_module = self.current_module.clone();
2324 match orig_module.anonymous_children.borrow().get(&block.id) {
2325 None => { /* Nothing to do. */ }
2326 Some(anonymous_module) => {
2327 debug!("(resolving block) found anonymous module, moving \
2329 self.current_module = anonymous_module.clone();
2333 // Check for imports appearing after non-item statements.
2334 let mut found_non_item = false;
2335 for statement in &block.stmts {
2336 if let ast::StmtDecl(ref declaration, _) = statement.node {
2337 if let ast::DeclItem(ref i) = declaration.node {
2339 ItemExternCrate(_) | ItemUse(_) if found_non_item => {
2340 span_err!(self.session, i.span, E0154,
2341 "imports are not allowed after non-item statements");
2346 found_non_item = true
2349 found_non_item = true;
2353 // Descend into the block.
2354 visit::walk_block(self, block);
2357 self.current_module = orig_module;
2359 self.value_ribs.pop();
2360 debug!("(resolving block) leaving block");
2363 fn resolve_type(&mut self, ty: &Ty) {
2365 TyPath(ref maybe_qself, ref path) => {
2367 match self.resolve_possibly_assoc_item(ty.id,
2368 maybe_qself.as_ref(),
2372 // `<T>::a::b::c` is resolved by typeck alone.
2373 TypecheckRequired => {
2374 // Resolve embedded types.
2375 visit::walk_ty(self, ty);
2378 ResolveAttempt(resolution) => resolution,
2381 // This is a path in the type namespace. Walk through scopes
2385 // Write the result into the def map.
2386 debug!("(resolving type) writing resolution for `{}` \
2388 path_names_to_string(path, 0),
2390 self.record_def(ty.id, def);
2393 // Keep reporting some errors even if they're ignored above.
2394 self.resolve_path(ty.id, path, 0, TypeNS, true);
2396 let kind = if maybe_qself.is_some() {
2402 let self_type_name = special_idents::type_self.name;
2403 let is_invalid_self_type_name =
2404 path.segments.len() > 0 &&
2405 maybe_qself.is_none() &&
2406 path.segments[0].identifier.name == self_type_name;
2407 if is_invalid_self_type_name {
2408 resolve_err!(self, ty.span, E0411,
2409 "use of `Self` outside of an impl or trait");
2411 resolve_err!(self, ty.span, E0412,
2412 "use of undeclared {} `{}`",
2414 path_names_to_string(path, 0));
2421 // Resolve embedded types.
2422 visit::walk_ty(self, ty);
2425 fn resolve_pattern(&mut self,
2427 mode: PatternBindingMode,
2428 // Maps idents to the node ID for the (outermost)
2429 // pattern that binds them
2430 bindings_list: &mut HashMap<Name, NodeId>) {
2431 let pat_id = pattern.id;
2432 walk_pat(pattern, |pattern| {
2433 match pattern.node {
2434 PatIdent(binding_mode, ref path1, _) => {
2436 // The meaning of pat_ident with no type parameters
2437 // depends on whether an enum variant or unit-like struct
2438 // with that name is in scope. The probing lookup has to
2439 // be careful not to emit spurious errors. Only matching
2440 // patterns (match) can match nullary variants or
2441 // unit-like structs. For binding patterns (let), matching
2442 // such a value is simply disallowed (since it's rarely
2445 let ident = path1.node;
2446 let renamed = mtwt::resolve(ident);
2448 match self.resolve_bare_identifier_pattern(ident.name, pattern.span) {
2449 FoundStructOrEnumVariant(def, lp)
2450 if mode == RefutableMode => {
2451 debug!("(resolving pattern) resolving `{}` to \
2452 struct or enum variant",
2455 self.enforce_default_binding_mode(
2459 self.record_def(pattern.id, PathResolution {
2465 FoundStructOrEnumVariant(..) => {
2466 resolve_err!(self, pattern.span, E0413,
2467 "declaration of `{}` shadows an enum \
2468 variant or unit-like struct in \
2472 FoundConst(def, lp) if mode == RefutableMode => {
2473 debug!("(resolving pattern) resolving `{}` to \
2477 self.enforce_default_binding_mode(
2481 self.record_def(pattern.id, PathResolution {
2488 resolve_err!(self, pattern.span, E0414,
2490 "only irrefutable patterns \
2493 BareIdentifierPatternUnresolved => {
2494 debug!("(resolving pattern) binding `{}`",
2497 let def = DefLocal(pattern.id);
2499 // Record the definition so that later passes
2500 // will be able to distinguish variants from
2501 // locals in patterns.
2503 self.record_def(pattern.id, PathResolution {
2505 last_private: LastMod(AllPublic),
2509 // Add the binding to the local ribs, if it
2510 // doesn't already exist in the bindings list. (We
2511 // must not add it if it's in the bindings list
2512 // because that breaks the assumptions later
2513 // passes make about or-patterns.)
2514 if !bindings_list.contains_key(&renamed) {
2515 let this = &mut *self;
2516 let last_rib = this.value_ribs.last_mut().unwrap();
2517 last_rib.bindings.insert(renamed, DlDef(def));
2518 bindings_list.insert(renamed, pat_id);
2519 } else if mode == ArgumentIrrefutableMode &&
2520 bindings_list.contains_key(&renamed) {
2521 // Forbid duplicate bindings in the same
2523 resolve_err!(self, pattern.span, E0415,
2529 token::get_ident(ident));
2530 } else if bindings_list.get(&renamed) ==
2532 // Then this is a duplicate variable in the
2533 // same disjunction, which is an error.
2534 resolve_err!(self, pattern.span, E0416,
2535 "identifier `{}` is bound \
2536 more than once in the same \
2538 token::get_ident(ident));
2540 // Else, not bound in the same pattern: do
2546 PatEnum(ref path, _) => {
2547 // This must be an enum variant, struct or const.
2549 match self.resolve_possibly_assoc_item(pat_id, None,
2552 // The below shouldn't happen because all
2553 // qualified paths should be in PatQPath.
2554 TypecheckRequired =>
2555 self.session.span_bug(
2557 "resolve_possibly_assoc_item claimed
2558 that a path in PatEnum requires typecheck
2559 to resolve, but qualified paths should be
2561 ResolveAttempt(resolution) => resolution,
2563 if let Some(path_res) = resolution {
2564 match path_res.base_def {
2565 DefVariant(..) | DefStruct(..) | DefConst(..) => {
2566 self.record_def(pattern.id, path_res);
2569 resolve_error(&ResolutionError::StaticVariableReference(&self, path.span),
2570 "static variables cannot be \
2571 referenced in a pattern, \
2572 use a `const` instead");
2575 // If anything ends up here entirely resolved,
2576 // it's an error. If anything ends up here
2577 // partially resolved, that's OK, because it may
2578 // be a `T::CONST` that typeck will resolve.
2579 if path_res.depth == 0 {
2580 resolve_err!(self, path.span, E0418,
2581 "`{}` is not an enum variant, struct or const",
2583 path.segments.last().unwrap().identifier));
2585 let const_name = path.segments.last().unwrap()
2587 let traits = self.get_traits_containing_item(const_name);
2588 self.trait_map.insert(pattern.id, traits);
2589 self.record_def(pattern.id, path_res);
2594 resolve_err!(self, path.span, E0419,
2595 "unresolved enum variant, struct or const `{}`",
2596 token::get_ident(path.segments.last().unwrap().identifier));
2598 visit::walk_path(self, path);
2601 PatQPath(ref qself, ref path) => {
2602 // Associated constants only.
2604 match self.resolve_possibly_assoc_item(pat_id, Some(qself),
2607 TypecheckRequired => {
2608 // All `<T>::CONST` should end up here, and will
2609 // require use of the trait map to resolve
2610 // during typechecking.
2611 let const_name = path.segments.last().unwrap()
2613 let traits = self.get_traits_containing_item(const_name);
2614 self.trait_map.insert(pattern.id, traits);
2615 visit::walk_pat(self, pattern);
2618 ResolveAttempt(resolution) => resolution,
2620 if let Some(path_res) = resolution {
2621 match path_res.base_def {
2622 // All `<T as Trait>::CONST` should end up here, and
2623 // have the trait already selected.
2624 DefAssociatedConst(..) => {
2625 self.record_def(pattern.id, path_res);
2628 resolve_err!(self, path.span, E0420,
2629 "`{}` is not an associated const",
2631 path.segments.last().unwrap().identifier));
2635 resolve_err!(self, path.span, E0421,
2636 "unresolved associated const `{}`",
2637 token::get_ident(path.segments.last().unwrap().identifier));
2639 visit::walk_pat(self, pattern);
2642 PatStruct(ref path, _, _) => {
2643 match self.resolve_path(pat_id, path, 0, TypeNS, false) {
2644 Some(definition) => {
2645 self.record_def(pattern.id, definition);
2648 debug!("(resolving pattern) didn't find struct \
2649 def: {:?}", result);
2650 resolve_error(&ResolutionError::DoesNotNameAStruct(self, path.span),
2651 &*format!("`{}` does not name a structure",
2652 path_names_to_string(path, 0)));
2655 visit::walk_path(self, path);
2658 PatLit(_) | PatRange(..) => {
2659 visit::walk_pat(self, pattern);
2670 fn resolve_bare_identifier_pattern(&mut self, name: Name, span: Span)
2671 -> BareIdentifierPatternResolution {
2672 let module = self.current_module.clone();
2673 match self.resolve_item_in_lexical_scope(module,
2676 Success((target, _)) => {
2677 debug!("(resolve bare identifier pattern) succeeded in \
2678 finding {} at {:?}",
2680 target.bindings.value_def.borrow());
2681 match *target.bindings.value_def.borrow() {
2683 panic!("resolved name in the value namespace to a \
2684 set of name bindings with no def?!");
2687 // For the two success cases, this lookup can be
2688 // considered as not having a private component because
2689 // the lookup happened only within the current module.
2691 def @ DefVariant(..) | def @ DefStruct(..) => {
2692 return FoundStructOrEnumVariant(def, LastMod(AllPublic));
2694 def @ DefConst(..) | def @ DefAssociatedConst(..) => {
2695 return FoundConst(def, LastMod(AllPublic));
2698 resolve_error(&ResolutionError::StaticVariableReference(self, span),
2699 "static variables cannot be \
2700 referenced in a pattern, \
2701 use a `const` instead");
2702 return BareIdentifierPatternUnresolved;
2705 return BareIdentifierPatternUnresolved;
2713 panic!("unexpected indeterminate result");
2717 Some((span, msg)) => {
2718 resolve_error(&ResolutionError::FailedToResolve(self, span),
2719 &*format!("failed to resolve. {}",
2726 debug!("(resolve bare identifier pattern) failed to find {}",
2728 return BareIdentifierPatternUnresolved;
2733 /// Handles paths that may refer to associated items
2734 fn resolve_possibly_assoc_item(&mut self,
2736 maybe_qself: Option<&ast::QSelf>,
2738 namespace: Namespace,
2740 -> AssocItemResolveResult
2742 let max_assoc_types;
2746 if qself.position == 0 {
2747 return TypecheckRequired;
2749 max_assoc_types = path.segments.len() - qself.position;
2750 // Make sure the trait is valid.
2751 let _ = self.resolve_trait_reference(id, path, max_assoc_types);
2754 max_assoc_types = path.segments.len();
2758 let mut resolution = self.with_no_errors(|this| {
2759 this.resolve_path(id, path, 0, namespace, check_ribs)
2761 for depth in 1..max_assoc_types {
2762 if resolution.is_some() {
2765 self.with_no_errors(|this| {
2766 resolution = this.resolve_path(id, path, depth,
2770 if let Some(DefMod(_)) = resolution.map(|r| r.base_def) {
2771 // A module is not a valid type or value.
2774 ResolveAttempt(resolution)
2777 /// If `check_ribs` is true, checks the local definitions first; i.e.
2778 /// doesn't skip straight to the containing module.
2779 /// Skips `path_depth` trailing segments, which is also reflected in the
2780 /// returned value. See `middle::def::PathResolution` for more info.
2781 fn resolve_path(&mut self,
2785 namespace: Namespace,
2786 check_ribs: bool) -> Option<PathResolution> {
2787 let span = path.span;
2788 let segments = &path.segments[..path.segments.len()-path_depth];
2790 let mk_res = |(def, lp)| PathResolution::new(def, lp, path_depth);
2793 let def = self.resolve_crate_relative_path(span, segments, namespace);
2794 return def.map(mk_res);
2797 // Try to find a path to an item in a module.
2798 let unqualified_def =
2799 self.resolve_identifier(segments.last().unwrap().identifier,
2804 if segments.len() <= 1 {
2805 return unqualified_def.map(mk_res);
2808 let def = self.resolve_module_relative_path(span, segments, namespace);
2809 match (def, unqualified_def) {
2810 (Some((ref d, _)), Some((ref ud, _))) if *d == *ud => {
2812 .add_lint(lint::builtin::UNUSED_QUALIFICATIONS,
2814 "unnecessary qualification".to_string());
2822 // Resolve a single identifier.
2823 fn resolve_identifier(&mut self,
2825 namespace: Namespace,
2828 -> Option<(Def, LastPrivate)> {
2829 // First, check to see whether the name is a primitive type.
2830 if namespace == TypeNS {
2831 if let Some(&prim_ty) = self.primitive_type_table
2833 .get(&identifier.name) {
2834 return Some((DefPrimTy(prim_ty), LastMod(AllPublic)));
2839 if let Some(def) = self.resolve_identifier_in_local_ribs(identifier,
2842 return Some((def, LastMod(AllPublic)));
2846 self.resolve_item_by_name_in_lexical_scope(identifier.name, namespace)
2849 // FIXME #4952: Merge me with resolve_name_in_module?
2850 fn resolve_definition_of_name_in_module(&mut self,
2851 containing_module: Rc<Module>,
2853 namespace: Namespace)
2855 // First, search children.
2856 build_reduced_graph::populate_module_if_necessary(self, &containing_module);
2858 match containing_module.children.borrow().get(&name) {
2859 Some(child_name_bindings) => {
2860 match child_name_bindings.def_for_namespace(namespace) {
2862 // Found it. Stop the search here.
2863 let p = child_name_bindings.defined_in_public_namespace(namespace);
2864 let lp = if p {LastMod(AllPublic)} else {
2865 LastMod(DependsOn(def.def_id()))
2867 return ChildNameDefinition(def, lp);
2875 // Next, search import resolutions.
2876 match containing_module.import_resolutions.borrow().get(&name) {
2877 Some(import_resolution) if import_resolution.is_public => {
2878 if let Some(target) = (*import_resolution).target_for_namespace(namespace) {
2879 match target.bindings.def_for_namespace(namespace) {
2882 let id = import_resolution.id(namespace);
2883 // track imports and extern crates as well
2884 self.used_imports.insert((id, namespace));
2885 self.record_import_use(id, name);
2886 match target.target_module.def_id.get() {
2887 Some(DefId{krate: kid, ..}) => {
2888 self.used_crates.insert(kid);
2892 return ImportNameDefinition(def, LastMod(AllPublic));
2895 // This can happen with external impls, due to
2896 // the imperfect way we read the metadata.
2901 Some(..) | None => {} // Continue.
2904 // Finally, search through external children.
2905 if namespace == TypeNS {
2906 if let Some(module) = containing_module.external_module_children.borrow()
2907 .get(&name).cloned() {
2908 if let Some(def_id) = module.def_id.get() {
2909 // track used crates
2910 self.used_crates.insert(def_id.krate);
2911 let lp = if module.is_public {LastMod(AllPublic)} else {
2912 LastMod(DependsOn(def_id))
2914 return ChildNameDefinition(DefMod(def_id), lp);
2919 return NoNameDefinition;
2922 // resolve a "module-relative" path, e.g. a::b::c
2923 fn resolve_module_relative_path(&mut self,
2925 segments: &[ast::PathSegment],
2926 namespace: Namespace)
2927 -> Option<(Def, LastPrivate)> {
2928 let module_path = segments.init().iter()
2929 .map(|ps| ps.identifier.name)
2930 .collect::<Vec<_>>();
2932 let containing_module;
2934 let current_module = self.current_module.clone();
2935 match self.resolve_module_path(current_module,
2941 let (span, msg) = match err {
2942 Some((span, msg)) => (span, msg),
2944 let msg = format!("Use of undeclared type or module `{}`",
2945 names_to_string(&module_path));
2950 resolve_error(&ResolutionError::FailedToResolve(self, span),
2951 &*format!("failed to resolve. {}",
2956 Indeterminate => panic!("indeterminate unexpected"),
2957 Success((resulting_module, resulting_last_private)) => {
2958 containing_module = resulting_module;
2959 last_private = resulting_last_private;
2963 let name = segments.last().unwrap().identifier.name;
2964 let def = match self.resolve_definition_of_name_in_module(containing_module.clone(),
2967 NoNameDefinition => {
2968 // We failed to resolve the name. Report an error.
2971 ChildNameDefinition(def, lp) | ImportNameDefinition(def, lp) => {
2972 (def, last_private.or(lp))
2975 if let Some(DefId{krate: kid, ..}) = containing_module.def_id.get() {
2976 self.used_crates.insert(kid);
2981 /// Invariant: This must be called only during main resolution, not during
2982 /// import resolution.
2983 fn resolve_crate_relative_path(&mut self,
2985 segments: &[ast::PathSegment],
2986 namespace: Namespace)
2987 -> Option<(Def, LastPrivate)> {
2988 let module_path = segments.init().iter()
2989 .map(|ps| ps.identifier.name)
2990 .collect::<Vec<_>>();
2992 let root_module = self.graph_root.get_module();
2994 let containing_module;
2996 match self.resolve_module_path_from_root(root_module,
3001 LastMod(AllPublic)) {
3003 let (span, msg) = match err {
3004 Some((span, msg)) => (span, msg),
3006 let msg = format!("Use of undeclared module `::{}`",
3007 names_to_string(&module_path[..]));
3012 resolve_error(&ResolutionError::FailedToResolve(self, span),
3013 &*format!("failed to resolve. {}",
3020 panic!("indeterminate unexpected");
3023 Success((resulting_module, resulting_last_private)) => {
3024 containing_module = resulting_module;
3025 last_private = resulting_last_private;
3029 let name = segments.last().unwrap().identifier.name;
3030 match self.resolve_definition_of_name_in_module(containing_module,
3033 NoNameDefinition => {
3034 // We failed to resolve the name. Report an error.
3037 ChildNameDefinition(def, lp) | ImportNameDefinition(def, lp) => {
3038 return Some((def, last_private.or(lp)));
3043 fn resolve_identifier_in_local_ribs(&mut self,
3045 namespace: Namespace,
3048 // Check the local set of ribs.
3049 let search_result = match namespace {
3051 let renamed = mtwt::resolve(ident);
3052 self.search_ribs(&self.value_ribs, renamed, span)
3055 let name = ident.name;
3056 self.search_ribs(&self.type_ribs, name, span)
3060 match search_result {
3061 Some(DlDef(def)) => {
3062 debug!("(resolving path in local ribs) resolved `{}` to local: {:?}",
3063 token::get_ident(ident),
3067 Some(DlField) | Some(DlImpl(_)) | None => {
3073 fn resolve_item_by_name_in_lexical_scope(&mut self,
3075 namespace: Namespace)
3076 -> Option<(Def, LastPrivate)> {
3078 let module = self.current_module.clone();
3079 match self.resolve_item_in_lexical_scope(module,
3082 Success((target, _)) => {
3083 match (*target.bindings).def_for_namespace(namespace) {
3085 // This can happen if we were looking for a type and
3086 // found a module instead. Modules don't have defs.
3087 debug!("(resolving item path by identifier in lexical \
3088 scope) failed to resolve {} after success...",
3093 debug!("(resolving item path in lexical scope) \
3094 resolved `{}` to item",
3096 // This lookup is "all public" because it only searched
3097 // for one identifier in the current module (couldn't
3098 // have passed through reexports or anything like that.
3099 return Some((def, LastMod(AllPublic)));
3104 panic!("unexpected indeterminate result");
3107 debug!("(resolving item path by identifier in lexical scope) \
3108 failed to resolve {}", name);
3110 if let Some((span, msg)) = err {
3111 resolve_error(&ResolutionError::FailedToResolve(self, span),
3112 &*format!("failed to resolve. {}",
3122 fn with_no_errors<T, F>(&mut self, f: F) -> T where
3123 F: FnOnce(&mut Resolver) -> T,
3125 self.emit_errors = false;
3127 self.emit_errors = true;
3131 fn find_fallback_in_self_type(&mut self, name: Name) -> FallbackSuggestion {
3132 fn extract_path_and_node_id(t: &Ty, allow: FallbackChecks)
3133 -> Option<(Path, NodeId, FallbackChecks)> {
3135 TyPath(None, ref path) => Some((path.clone(), t.id, allow)),
3136 TyPtr(ref mut_ty) => extract_path_and_node_id(&*mut_ty.ty, OnlyTraitAndStatics),
3137 TyRptr(_, ref mut_ty) => extract_path_and_node_id(&*mut_ty.ty, allow),
3138 // This doesn't handle the remaining `Ty` variants as they are not
3139 // that commonly the self_type, it might be interesting to provide
3140 // support for those in future.
3145 fn get_module(this: &mut Resolver, span: Span, name_path: &[ast::Name])
3146 -> Option<Rc<Module>> {
3147 let root = this.current_module.clone();
3148 let last_name = name_path.last().unwrap();
3150 if name_path.len() == 1 {
3151 match this.primitive_type_table.primitive_types.get(last_name) {
3154 match this.current_module.children.borrow().get(last_name) {
3155 Some(child) => child.get_module_if_available(),
3161 match this.resolve_module_path(root,
3166 Success((module, _)) => Some(module),
3172 fn is_static_method(this: &Resolver, did: DefId) -> bool {
3173 if did.krate == ast::LOCAL_CRATE {
3174 let sig = match this.ast_map.get(did.node) {
3175 ast_map::NodeTraitItem(trait_item) => match trait_item.node {
3176 ast::MethodTraitItem(ref sig, _) => sig,
3179 ast_map::NodeImplItem(impl_item) => match impl_item.node {
3180 ast::MethodImplItem(ref sig, _) => sig,
3185 sig.explicit_self.node == ast::SelfStatic
3187 csearch::is_static_method(&this.session.cstore, did)
3191 let (path, node_id, allowed) = match self.current_self_type {
3192 Some(ref ty) => match extract_path_and_node_id(ty, Everything) {
3194 None => return NoSuggestion,
3196 None => return NoSuggestion,
3199 if allowed == Everything {
3200 // Look for a field with the same name in the current self_type.
3201 match self.def_map.borrow().get(&node_id).map(|d| d.full_def()) {
3202 Some(DefTy(did, _)) |
3203 Some(DefStruct(did)) |
3204 Some(DefVariant(_, did, _)) => match self.structs.get(&did) {
3207 if fields.iter().any(|&field_name| name == field_name) {
3212 _ => {} // Self type didn't resolve properly
3216 let name_path = path.segments.iter().map(|seg| seg.identifier.name).collect::<Vec<_>>();
3218 // Look for a method in the current self type's impl module.
3219 if let Some(module) = get_module(self, path.span, &name_path) {
3220 if let Some(binding) = module.children.borrow().get(&name) {
3221 if let Some(DefMethod(did, _)) = binding.def_for_namespace(ValueNS) {
3222 if is_static_method(self, did) {
3223 return StaticMethod(path_names_to_string(&path, 0))
3225 if self.current_trait_ref.is_some() {
3227 } else if allowed == Everything {
3234 // Look for a method in the current trait.
3235 if let Some((trait_did, ref trait_ref)) = self.current_trait_ref {
3236 if let Some(&did) = self.trait_item_map.get(&(name, trait_did)) {
3237 if is_static_method(self, did) {
3238 return TraitMethod(path_names_to_string(&trait_ref.path, 0));
3248 fn find_best_match_for_name(&mut self, name: &str) -> Option<String> {
3249 let mut maybes: Vec<token::InternedString> = Vec::new();
3250 let mut values: Vec<usize> = Vec::new();
3252 for rib in self.value_ribs.iter().rev() {
3253 for (&k, _) in &rib.bindings {
3254 maybes.push(token::get_name(k));
3255 values.push(usize::MAX);
3259 let mut smallest = 0;
3260 for (i, other) in maybes.iter().enumerate() {
3261 values[i] = lev_distance(name, &other);
3263 if values[i] <= values[smallest] {
3268 // As a loose rule to avoid obviously incorrect suggestions, clamp the
3269 // maximum edit distance we will accept for a suggestion to one third of
3270 // the typo'd name's length.
3271 let max_distance = std::cmp::max(name.len(), 3) / 3;
3273 if !values.is_empty() &&
3274 values[smallest] <= max_distance &&
3275 name != &maybes[smallest][..] {
3277 Some(maybes[smallest].to_string())
3284 fn resolve_expr(&mut self, expr: &Expr) {
3285 // First, record candidate traits for this expression if it could
3286 // result in the invocation of a method call.
3288 self.record_candidate_traits_for_expr_if_necessary(expr);
3290 // Next, resolve the node.
3292 ExprPath(ref maybe_qself, ref path) => {
3294 match self.resolve_possibly_assoc_item(expr.id,
3295 maybe_qself.as_ref(),
3299 // `<T>::a::b::c` is resolved by typeck alone.
3300 TypecheckRequired => {
3301 let method_name = path.segments.last().unwrap().identifier.name;
3302 let traits = self.get_traits_containing_item(method_name);
3303 self.trait_map.insert(expr.id, traits);
3304 visit::walk_expr(self, expr);
3307 ResolveAttempt(resolution) => resolution,
3310 // This is a local path in the value namespace. Walk through
3311 // scopes looking for it.
3312 if let Some(path_res) = resolution {
3313 // Check if struct variant
3314 if let DefVariant(_, _, true) = path_res.base_def {
3315 let path_name = path_names_to_string(path, 0);
3317 resolve_error(&ResolutionError::StructVariantUsedAsFunction(self, expr.span),
3318 &*format!("`{}` is a struct variant name, but \
3320 uses it like a function name",
3323 let msg = format!("did you mean to write: \
3324 `{} {{ /* fields */ }}`?",
3326 if self.emit_errors {
3327 self.session.fileline_help(expr.span, &msg);
3329 self.session.span_help(expr.span, &msg);
3332 // Write the result into the def map.
3333 debug!("(resolving expr) resolved `{}`",
3334 path_names_to_string(path, 0));
3336 // Partial resolutions will need the set of traits in scope,
3337 // so they can be completed during typeck.
3338 if path_res.depth != 0 {
3339 let method_name = path.segments.last().unwrap().identifier.name;
3340 let traits = self.get_traits_containing_item(method_name);
3341 self.trait_map.insert(expr.id, traits);
3344 self.record_def(expr.id, path_res);
3347 // Be helpful if the name refers to a struct
3348 // (The pattern matching def_tys where the id is in self.structs
3349 // matches on regular structs while excluding tuple- and enum-like
3350 // structs, which wouldn't result in this error.)
3351 let path_name = path_names_to_string(path, 0);
3352 let type_res = self.with_no_errors(|this| {
3353 this.resolve_path(expr.id, path, 0, TypeNS, false)
3355 match type_res.map(|r| r.base_def) {
3356 Some(DefTy(struct_id, _))
3357 if self.structs.contains_key(&struct_id) => {
3358 resolve_error(&ResolutionError::StructVariantUsedAsFunction(self, expr.span),
3359 &*format!("`{}` is a struct variant name, but \
3361 uses it like a function name",
3364 let msg = format!("did you mean to write: \
3365 `{} {{ /* fields */ }}`?",
3367 if self.emit_errors {
3368 self.session.fileline_help(expr.span, &msg);
3370 self.session.span_help(expr.span, &msg);
3374 // Keep reporting some errors even if they're ignored above.
3375 self.resolve_path(expr.id, path, 0, ValueNS, true);
3377 let mut method_scope = false;
3378 self.value_ribs.iter().rev().all(|rib| {
3379 method_scope = match rib.kind {
3380 MethodRibKind => true,
3381 ItemRibKind | ConstantItemRibKind => false,
3382 _ => return true, // Keep advancing
3384 false // Stop advancing
3388 &token::get_name(special_names::self_)[..] == path_name {
3389 resolve_err!(self, expr.span, E0424,
3391 "`self` is not available \
3392 in a static method. Maybe a \
3393 `self` argument is missing?");
3395 let last_name = path.segments.last().unwrap().identifier.name;
3396 let mut msg = match self.find_fallback_in_self_type(last_name) {
3398 // limit search to 5 to reduce the number
3399 // of stupid suggestions
3400 self.find_best_match_for_name(&path_name)
3401 .map_or("".to_string(),
3402 |x| format!("`{}`", x))
3404 Field => format!("`self.{}`", path_name),
3407 format!("to call `self.{}`", path_name),
3408 TraitMethod(path_str) |
3409 StaticMethod(path_str) =>
3410 format!("to call `{}::{}`", path_str, path_name)
3413 if !msg.is_empty() {
3414 msg = format!(". Did you mean {}?", msg)
3417 resolve_err!(self, expr.span, E0425,
3418 "unresolved name `{}`{}",
3426 visit::walk_expr(self, expr);
3429 ExprStruct(ref path, _, _) => {
3430 // Resolve the path to the structure it goes to. We don't
3431 // check to ensure that the path is actually a structure; that
3432 // is checked later during typeck.
3433 match self.resolve_path(expr.id, path, 0, TypeNS, false) {
3434 Some(definition) => self.record_def(expr.id, definition),
3436 debug!("(resolving expression) didn't find struct def",);
3438 resolve_error(&ResolutionError::DoesNotNameAStruct(self, path.span),
3439 &*format!("`{}` does not name a structure",
3440 path_names_to_string(path, 0)));
3444 visit::walk_expr(self, expr);
3447 ExprLoop(_, Some(label)) | ExprWhile(_, _, Some(label)) => {
3448 self.with_label_rib(|this| {
3449 let def_like = DlDef(DefLabel(expr.id));
3452 let rib = this.label_ribs.last_mut().unwrap();
3453 let renamed = mtwt::resolve(label);
3454 rib.bindings.insert(renamed, def_like);
3457 visit::walk_expr(this, expr);
3461 ExprBreak(Some(label)) | ExprAgain(Some(label)) => {
3462 let renamed = mtwt::resolve(label);
3463 match self.search_label(renamed) {
3465 resolve_err!(self, expr.span, E0426,
3466 "use of undeclared label `{}`",
3467 token::get_ident(label))
3469 Some(DlDef(def @ DefLabel(_))) => {
3470 // Since this def is a label, it is never read.
3471 self.record_def(expr.id, PathResolution {
3473 last_private: LastMod(AllPublic),
3478 self.session.span_bug(expr.span,
3479 "label wasn't mapped to a \
3486 visit::walk_expr(self, expr);
3491 fn record_candidate_traits_for_expr_if_necessary(&mut self, expr: &Expr) {
3493 ExprField(_, ident) => {
3494 // FIXME(#6890): Even though you can't treat a method like a
3495 // field, we need to add any trait methods we find that match
3496 // the field name so that we can do some nice error reporting
3497 // later on in typeck.
3498 let traits = self.get_traits_containing_item(ident.node.name);
3499 self.trait_map.insert(expr.id, traits);
3501 ExprMethodCall(ident, _, _) => {
3502 debug!("(recording candidate traits for expr) recording \
3505 let traits = self.get_traits_containing_item(ident.node.name);
3506 self.trait_map.insert(expr.id, traits);
3514 fn get_traits_containing_item(&mut self, name: Name) -> Vec<DefId> {
3515 debug!("(getting traits containing item) looking for '{}'",
3518 fn add_trait_info(found_traits: &mut Vec<DefId>,
3519 trait_def_id: DefId,
3521 debug!("(adding trait info) found trait {}:{} for method '{}'",
3525 found_traits.push(trait_def_id);
3528 let mut found_traits = Vec::new();
3529 let mut search_module = self.current_module.clone();
3531 // Look for the current trait.
3532 match self.current_trait_ref {
3533 Some((trait_def_id, _)) => {
3534 if self.trait_item_map.contains_key(&(name, trait_def_id)) {
3535 add_trait_info(&mut found_traits, trait_def_id, name);
3538 None => {} // Nothing to do.
3541 // Look for trait children.
3542 build_reduced_graph::populate_module_if_necessary(self, &search_module);
3545 for (_, child_names) in search_module.children.borrow().iter() {
3546 let def = match child_names.def_for_namespace(TypeNS) {
3550 let trait_def_id = match def {
3551 DefTrait(trait_def_id) => trait_def_id,
3554 if self.trait_item_map.contains_key(&(name, trait_def_id)) {
3555 add_trait_info(&mut found_traits, trait_def_id, name);
3560 // Look for imports.
3561 for (_, import) in search_module.import_resolutions.borrow().iter() {
3562 let target = match import.target_for_namespace(TypeNS) {
3564 Some(target) => target,
3566 let did = match target.bindings.def_for_namespace(TypeNS) {
3567 Some(DefTrait(trait_def_id)) => trait_def_id,
3568 Some(..) | None => continue,
3570 if self.trait_item_map.contains_key(&(name, did)) {
3571 add_trait_info(&mut found_traits, did, name);
3572 let id = import.type_id;
3573 self.used_imports.insert((id, TypeNS));
3574 let trait_name = self.get_trait_name(did);
3575 self.record_import_use(id, trait_name);
3576 if let Some(DefId{krate: kid, ..}) = target.target_module.def_id.get() {
3577 self.used_crates.insert(kid);
3582 match search_module.parent_link.clone() {
3583 NoParentLink | ModuleParentLink(..) => break,
3584 BlockParentLink(parent_module, _) => {
3585 search_module = parent_module.upgrade().unwrap();
3593 fn record_def(&mut self, node_id: NodeId, resolution: PathResolution) {
3594 debug!("(recording def) recording {:?} for {}", resolution, node_id);
3595 assert!(match resolution.last_private {LastImport{..} => false, _ => true},
3596 "Import should only be used for `use` directives");
3598 if let Some(prev_res) = self.def_map.borrow_mut().insert(node_id, resolution) {
3599 let span = self.ast_map.opt_span(node_id).unwrap_or(codemap::DUMMY_SP);
3600 self.session.span_bug(span, &format!("path resolved multiple times \
3601 ({:?} before, {:?} now)",
3602 prev_res, resolution));
3606 fn enforce_default_binding_mode(&mut self,
3608 pat_binding_mode: BindingMode,
3610 match pat_binding_mode {
3611 BindByValue(_) => {}
3613 resolve_err!(self, pat.span, E0427,
3614 "cannot use `ref` binding mode with {}",
3623 // Diagnostics are not particularly efficient, because they're rarely
3627 #[allow(dead_code)] // useful for debugging
3628 fn dump_module(&mut self, module_: Rc<Module>) {
3629 debug!("Dump of module `{}`:", module_to_string(&*module_));
3631 debug!("Children:");
3632 build_reduced_graph::populate_module_if_necessary(self, &module_);
3633 for (&name, _) in module_.children.borrow().iter() {
3634 debug!("* {}", name);
3637 debug!("Import resolutions:");
3638 let import_resolutions = module_.import_resolutions.borrow();
3639 for (&name, import_resolution) in import_resolutions.iter() {
3641 match import_resolution.target_for_namespace(ValueNS) {
3642 None => { value_repr = "".to_string(); }
3644 value_repr = " value:?".to_string();
3650 match import_resolution.target_for_namespace(TypeNS) {
3651 None => { type_repr = "".to_string(); }
3653 type_repr = " type:?".to_string();
3658 debug!("* {}:{}{}", name, value_repr, type_repr);
3664 fn names_to_string(names: &[Name]) -> String {
3665 let mut first = true;
3666 let mut result = String::new();
3671 result.push_str("::")
3673 result.push_str(&token::get_name(*name));
3678 fn path_names_to_string(path: &Path, depth: usize) -> String {
3679 let names: Vec<ast::Name> = path.segments[..path.segments.len()-depth]
3681 .map(|seg| seg.identifier.name)
3683 names_to_string(&names[..])
3686 /// A somewhat inefficient routine to obtain the name of a module.
3687 fn module_to_string(module: &Module) -> String {
3688 let mut names = Vec::new();
3690 fn collect_mod(names: &mut Vec<ast::Name>, module: &Module) {
3691 match module.parent_link {
3693 ModuleParentLink(ref module, name) => {
3695 collect_mod(names, &*module.upgrade().unwrap());
3697 BlockParentLink(ref module, _) => {
3698 // danger, shouldn't be ident?
3699 names.push(special_idents::opaque.name);
3700 collect_mod(names, &*module.upgrade().unwrap());
3704 collect_mod(&mut names, module);
3706 if names.is_empty() {
3707 return "???".to_string();
3709 names_to_string(&names.into_iter().rev().collect::<Vec<ast::Name>>())
3713 pub struct CrateMap {
3714 pub def_map: DefMap,
3715 pub freevars: RefCell<FreevarMap>,
3716 pub export_map: ExportMap,
3717 pub trait_map: TraitMap,
3718 pub external_exports: ExternalExports,
3719 pub glob_map: Option<GlobMap>
3722 #[derive(PartialEq,Copy, Clone)]
3723 pub enum MakeGlobMap {
3728 /// Entry point to crate resolution.
3729 pub fn resolve_crate<'a, 'tcx>(session: &'a Session,
3730 ast_map: &'a ast_map::Map<'tcx>,
3731 make_glob_map: MakeGlobMap)
3733 let krate = ast_map.krate();
3734 let mut resolver = Resolver::new(session, ast_map, krate.span, make_glob_map);
3736 build_reduced_graph::build_reduced_graph(&mut resolver, krate);
3737 session.abort_if_errors();
3739 resolve_imports::resolve_imports(&mut resolver);
3740 session.abort_if_errors();
3742 record_exports::record(&mut resolver);
3743 session.abort_if_errors();
3745 resolver.resolve_crate(krate);
3746 session.abort_if_errors();
3748 check_unused::check_crate(&mut resolver, krate);
3751 def_map: resolver.def_map,
3752 freevars: resolver.freevars,
3753 export_map: resolver.export_map,
3754 trait_map: resolver.trait_map,
3755 external_exports: resolver.external_exports,
3756 glob_map: if resolver.make_glob_map {
3757 Some(resolver.glob_map)
3764 __build_diagnostic_array! { librustc_resolve, DIAGNOSTICS }