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 #[derive(Copy, Clone)]
122 binding_mode: BindingMode,
125 // Map from the name in a pattern to its binding mode.
126 type BindingMap = HashMap<Name, BindingInfo>;
128 #[derive(Copy, Clone, PartialEq)]
129 enum PatternBindingMode {
131 LocalIrrefutableMode,
132 ArgumentIrrefutableMode,
135 #[derive(Copy, Clone, PartialEq, Eq, Hash, Debug)]
141 /// A NamespaceResult represents the result of resolving an import in
142 /// a particular namespace. The result is either definitely-resolved,
143 /// definitely- unresolved, or unknown.
145 enum NamespaceResult {
146 /// Means that resolve hasn't gathered enough information yet to determine
147 /// whether the name is bound in this namespace. (That is, it hasn't
148 /// resolved all `use` directives yet.)
150 /// Means that resolve has determined that the name is definitely
151 /// not bound in the namespace.
153 /// Means that resolve has determined that the name is bound in the Module
154 /// argument, and specified by the NameBindings argument.
155 BoundResult(Rc<Module>, Rc<NameBindings>)
158 impl NamespaceResult {
159 fn is_unknown(&self) -> bool {
161 UnknownResult => true,
165 fn is_unbound(&self) -> bool {
167 UnboundResult => true,
173 enum NameDefinition {
174 // The name was unbound.
176 // The name identifies an immediate child.
177 ChildNameDefinition(Def, LastPrivate),
178 // The name identifies an import.
179 ImportNameDefinition(Def, LastPrivate),
182 impl<'a, 'v, 'tcx> Visitor<'v> for Resolver<'a, 'tcx> {
183 fn visit_item(&mut self, item: &Item) {
184 self.resolve_item(item);
186 fn visit_arm(&mut self, arm: &Arm) {
187 self.resolve_arm(arm);
189 fn visit_block(&mut self, block: &Block) {
190 self.resolve_block(block);
192 fn visit_expr(&mut self, expr: &Expr) {
193 self.resolve_expr(expr);
195 fn visit_local(&mut self, local: &Local) {
196 self.resolve_local(local);
198 fn visit_ty(&mut self, ty: &Ty) {
199 self.resolve_type(ty);
201 fn visit_generics(&mut self, generics: &Generics) {
202 self.resolve_generics(generics);
204 fn visit_poly_trait_ref(&mut self,
205 tref: &ast::PolyTraitRef,
206 m: &ast::TraitBoundModifier) {
207 match self.resolve_trait_reference(tref.trait_ref.ref_id, &tref.trait_ref.path, 0) {
208 Ok(def) => self.record_def(tref.trait_ref.ref_id, def),
209 Err(_) => { /* error already reported */ }
211 visit::walk_poly_trait_ref(self, tref, m);
213 fn visit_variant(&mut self, variant: &ast::Variant, generics: &Generics) {
214 if let Some(ref dis_expr) = variant.node.disr_expr {
215 // resolve the discriminator expr as a constant
216 self.with_constant_rib(|this| {
217 this.visit_expr(&**dis_expr);
221 // `visit::walk_variant` without the discriminant expression.
222 match variant.node.kind {
223 ast::TupleVariantKind(ref variant_arguments) => {
224 for variant_argument in variant_arguments {
225 self.visit_ty(&*variant_argument.ty);
228 ast::StructVariantKind(ref struct_definition) => {
229 self.visit_struct_def(&**struct_definition,
236 fn visit_foreign_item(&mut self, foreign_item: &ast::ForeignItem) {
237 let type_parameters = match foreign_item.node {
238 ForeignItemFn(_, ref generics) => {
239 HasTypeParameters(generics, FnSpace, ItemRibKind)
241 ForeignItemStatic(..) => NoTypeParameters
243 self.with_type_parameter_rib(type_parameters, |this| {
244 visit::walk_foreign_item(this, foreign_item);
247 fn visit_fn(&mut self,
248 function_kind: visit::FnKind<'v>,
249 declaration: &'v FnDecl,
253 let rib_kind = match function_kind {
254 visit::FkItemFn(_, generics, _, _, _, _) => {
255 self.visit_generics(generics);
258 visit::FkMethod(_, sig, _) => {
259 self.visit_generics(&sig.generics);
260 self.visit_explicit_self(&sig.explicit_self);
263 visit::FkFnBlock(..) => ClosureRibKind(node_id)
265 self.resolve_function(rib_kind, declaration, block);
269 type ErrorMessage = Option<(Span, String)>;
271 enum ResolveResult<T> {
272 Failed(ErrorMessage), // Failed to resolve the name, optional helpful error message.
273 Indeterminate, // Couldn't determine due to unresolved globs.
274 Success(T) // Successfully resolved the import.
277 impl<T> ResolveResult<T> {
278 fn indeterminate(&self) -> bool {
279 match *self { Indeterminate => true, _ => false }
283 enum FallbackSuggestion {
288 StaticMethod(String),
292 #[derive(Copy, Clone)]
293 enum TypeParameters<'a> {
299 // Identifies the things that these parameters
300 // were declared on (type, fn, etc)
303 // The kind of the rib used for type parameters.
307 // The rib kind controls the translation of local
308 // definitions (`DefLocal`) to upvars (`DefUpvar`).
309 #[derive(Copy, Clone, Debug)]
311 // No translation needs to be applied.
314 // We passed through a closure scope at the given node ID.
315 // Translate upvars as appropriate.
316 ClosureRibKind(NodeId /* func id */),
318 // We passed through an impl or trait and are now in one of its
319 // methods. Allow references to ty params that impl or trait
320 // binds. Disallow any other upvars (including other ty params that are
324 // We passed through an item scope. Disallow upvars.
327 // We're in a constant item. Can't refer to dynamic stuff.
331 #[derive(Copy, Clone)]
332 enum UseLexicalScopeFlag {
337 enum ModulePrefixResult {
339 PrefixFound(Rc<Module>, usize)
342 #[derive(Copy, Clone)]
343 enum AssocItemResolveResult {
344 /// Syntax such as `<T>::item`, which can't be resolved until type
347 /// We should have been able to resolve the associated item.
348 ResolveAttempt(Option<PathResolution>),
351 #[derive(Copy, Clone, PartialEq)]
352 enum NameSearchType {
353 /// We're doing a name search in order to resolve a `use` directive.
356 /// We're doing a name search in order to resolve a path type, a path
357 /// expression, or a path pattern.
361 #[derive(Copy, Clone)]
362 enum BareIdentifierPatternResolution {
363 FoundStructOrEnumVariant(Def, LastPrivate),
364 FoundConst(Def, LastPrivate),
365 BareIdentifierPatternUnresolved
371 bindings: HashMap<Name, DefLike>,
376 fn new(kind: RibKind) -> Rib {
378 bindings: HashMap::new(),
384 /// The link from a module up to its nearest parent node.
385 #[derive(Clone,Debug)]
388 ModuleParentLink(Weak<Module>, Name),
389 BlockParentLink(Weak<Module>, NodeId)
392 /// The type of module this is.
393 #[derive(Copy, Clone, PartialEq, Debug)]
402 /// One node in the tree of modules.
404 parent_link: ParentLink,
405 def_id: Cell<Option<DefId>>,
406 kind: Cell<ModuleKind>,
409 children: RefCell<HashMap<Name, Rc<NameBindings>>>,
410 imports: RefCell<Vec<ImportDirective>>,
412 // The external module children of this node that were declared with
414 external_module_children: RefCell<HashMap<Name, Rc<Module>>>,
416 // The anonymous children of this node. Anonymous children are pseudo-
417 // modules that are implicitly created around items contained within
420 // For example, if we have this:
428 // There will be an anonymous module created around `g` with the ID of the
429 // entry block for `f`.
430 anonymous_children: RefCell<NodeMap<Rc<Module>>>,
432 // The status of resolving each import in this module.
433 import_resolutions: RefCell<HashMap<Name, ImportResolution>>,
435 // The number of unresolved globs that this module exports.
436 glob_count: Cell<usize>,
438 // The index of the import we're resolving.
439 resolved_import_count: Cell<usize>,
441 // Whether this module is populated. If not populated, any attempt to
442 // access the children must be preceded with a
443 // `populate_module_if_necessary` call.
444 populated: Cell<bool>,
448 fn new(parent_link: ParentLink,
449 def_id: Option<DefId>,
455 parent_link: parent_link,
456 def_id: Cell::new(def_id),
457 kind: Cell::new(kind),
458 is_public: is_public,
459 children: RefCell::new(HashMap::new()),
460 imports: RefCell::new(Vec::new()),
461 external_module_children: RefCell::new(HashMap::new()),
462 anonymous_children: RefCell::new(NodeMap()),
463 import_resolutions: RefCell::new(HashMap::new()),
464 glob_count: Cell::new(0),
465 resolved_import_count: Cell::new(0),
466 populated: Cell::new(!external),
470 fn all_imports_resolved(&self) -> bool {
471 self.imports.borrow().len() == self.resolved_import_count.get()
475 impl fmt::Debug for Module {
476 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
477 write!(f, "{:?}, kind: {:?}, {}",
480 if self.is_public { "public" } else { "private" } )
486 flags DefModifiers: u8 {
487 const PUBLIC = 1 << 0,
488 const IMPORTABLE = 1 << 1,
492 // Records a possibly-private type definition.
493 #[derive(Clone,Debug)]
495 modifiers: DefModifiers, // see note in ImportResolution about how to use this
496 module_def: Option<Rc<Module>>,
497 type_def: Option<Def>,
498 type_span: Option<Span>
501 // Records a possibly-private value definition.
502 #[derive(Clone, Copy, Debug)]
504 modifiers: DefModifiers, // see note in ImportResolution about how to use this
506 value_span: Option<Span>,
509 // Records the definitions (at most one for each namespace) that a name is
512 pub struct NameBindings {
513 type_def: RefCell<Option<TypeNsDef>>, //< Meaning in type namespace.
514 value_def: RefCell<Option<ValueNsDef>>, //< Meaning in value namespace.
518 fn new() -> NameBindings {
520 type_def: RefCell::new(None),
521 value_def: RefCell::new(None),
525 /// Creates a new module in this set of name bindings.
526 fn define_module(&self,
527 parent_link: ParentLink,
528 def_id: Option<DefId>,
533 // Merges the module with the existing type def or creates a new one.
534 let modifiers = if is_public {
537 DefModifiers::empty()
538 } | DefModifiers::IMPORTABLE;
539 let module_ = Rc::new(Module::new(parent_link,
544 let type_def = self.type_def.borrow().clone();
547 *self.type_def.borrow_mut() = Some(TypeNsDef {
548 modifiers: modifiers,
549 module_def: Some(module_),
555 *self.type_def.borrow_mut() = Some(TypeNsDef {
556 modifiers: modifiers,
557 module_def: Some(module_),
559 type_def: type_def.type_def
565 /// Sets the kind of the module, creating a new one if necessary.
566 fn set_module_kind(&self,
567 parent_link: ParentLink,
568 def_id: Option<DefId>,
573 let modifiers = if is_public {
576 DefModifiers::empty()
577 } | DefModifiers::IMPORTABLE;
578 let type_def = self.type_def.borrow().clone();
581 let module = Module::new(parent_link,
586 *self.type_def.borrow_mut() = Some(TypeNsDef {
587 modifiers: modifiers,
588 module_def: Some(Rc::new(module)),
594 match type_def.module_def {
596 let module = Module::new(parent_link,
601 *self.type_def.borrow_mut() = Some(TypeNsDef {
602 modifiers: modifiers,
603 module_def: Some(Rc::new(module)),
604 type_def: type_def.type_def,
608 Some(module_def) => module_def.kind.set(kind),
614 /// Records a type definition.
615 fn define_type(&self, def: Def, sp: Span, modifiers: DefModifiers) {
616 debug!("defining type for def {:?} with modifiers {:?}", def, modifiers);
617 // Merges the type with the existing type def or creates a new one.
618 let type_def = self.type_def.borrow().clone();
621 *self.type_def.borrow_mut() = Some(TypeNsDef {
625 modifiers: modifiers,
629 *self.type_def.borrow_mut() = Some(TypeNsDef {
630 module_def: type_def.module_def,
633 modifiers: modifiers,
639 /// Records a value definition.
640 fn define_value(&self, def: Def, sp: Span, modifiers: DefModifiers) {
641 debug!("defining value for def {:?} with modifiers {:?}", def, modifiers);
642 *self.value_def.borrow_mut() = Some(ValueNsDef {
644 value_span: Some(sp),
645 modifiers: modifiers,
649 /// Returns the module node if applicable.
650 fn get_module_if_available(&self) -> Option<Rc<Module>> {
651 match *self.type_def.borrow() {
652 Some(ref type_def) => type_def.module_def.clone(),
657 /// Returns the module node. Panics if this node does not have a module
659 fn get_module(&self) -> Rc<Module> {
660 match self.get_module_if_available() {
662 panic!("get_module called on a node with no module \
665 Some(module_def) => module_def
669 fn defined_in_namespace(&self, namespace: Namespace) -> bool {
671 TypeNS => return self.type_def.borrow().is_some(),
672 ValueNS => return self.value_def.borrow().is_some()
676 fn defined_in_public_namespace(&self, namespace: Namespace) -> bool {
677 self.defined_in_namespace_with(namespace, DefModifiers::PUBLIC)
680 fn defined_in_namespace_with(&self, namespace: Namespace, modifiers: DefModifiers) -> bool {
682 TypeNS => match *self.type_def.borrow() {
683 Some(ref def) => def.modifiers.contains(modifiers), None => false
685 ValueNS => match *self.value_def.borrow() {
686 Some(ref def) => def.modifiers.contains(modifiers), None => false
691 fn def_for_namespace(&self, namespace: Namespace) -> Option<Def> {
694 match *self.type_def.borrow() {
696 Some(ref type_def) => {
697 match type_def.type_def {
698 Some(type_def) => Some(type_def),
700 match type_def.module_def {
701 Some(ref module) => {
702 match module.def_id.get() {
703 Some(did) => Some(DefMod(did)),
715 match *self.value_def.borrow() {
717 Some(value_def) => Some(value_def.def)
723 fn span_for_namespace(&self, namespace: Namespace) -> Option<Span> {
724 if self.defined_in_namespace(namespace) {
727 match *self.type_def.borrow() {
729 Some(ref type_def) => type_def.type_span
733 match *self.value_def.borrow() {
735 Some(ref value_def) => value_def.value_span
744 fn is_public(&self, namespace: Namespace) -> bool {
747 let type_def = self.type_def.borrow();
748 type_def.as_ref().unwrap().modifiers.contains(DefModifiers::PUBLIC)
751 let value_def = self.value_def.borrow();
752 value_def.as_ref().unwrap().modifiers.contains(DefModifiers::PUBLIC)
758 /// Interns the names of the primitive types.
759 struct PrimitiveTypeTable {
760 primitive_types: HashMap<Name, PrimTy>,
763 impl PrimitiveTypeTable {
764 fn new() -> PrimitiveTypeTable {
765 let mut table = PrimitiveTypeTable {
766 primitive_types: HashMap::new()
769 table.intern("bool", TyBool);
770 table.intern("char", TyChar);
771 table.intern("f32", TyFloat(TyF32));
772 table.intern("f64", TyFloat(TyF64));
773 table.intern("isize", TyInt(TyIs));
774 table.intern("i8", TyInt(TyI8));
775 table.intern("i16", TyInt(TyI16));
776 table.intern("i32", TyInt(TyI32));
777 table.intern("i64", TyInt(TyI64));
778 table.intern("str", TyStr);
779 table.intern("usize", TyUint(TyUs));
780 table.intern("u8", TyUint(TyU8));
781 table.intern("u16", TyUint(TyU16));
782 table.intern("u32", TyUint(TyU32));
783 table.intern("u64", TyUint(TyU64));
788 fn intern(&mut self, string: &str, primitive_type: PrimTy) {
789 self.primitive_types.insert(token::intern(string), primitive_type);
793 /// The main resolver class.
794 pub struct Resolver<'a, 'tcx:'a> {
795 session: &'a Session,
797 ast_map: &'a ast_map::Map<'tcx>,
799 graph_root: NameBindings,
801 trait_item_map: FnvHashMap<(Name, DefId), DefId>,
803 structs: FnvHashMap<DefId, Vec<Name>>,
805 // The number of imports that are currently unresolved.
806 unresolved_imports: usize,
808 // The module that represents the current item scope.
809 current_module: Rc<Module>,
811 // The current set of local scopes, for values.
812 // FIXME #4948: Reuse ribs to avoid allocation.
813 value_ribs: Vec<Rib>,
815 // The current set of local scopes, for types.
818 // The current set of local scopes, for labels.
819 label_ribs: Vec<Rib>,
821 // The trait that the current context can refer to.
822 current_trait_ref: Option<(DefId, TraitRef)>,
824 // The current self type if inside an impl (used for better errors).
825 current_self_type: Option<Ty>,
827 // The idents for the primitive types.
828 primitive_type_table: PrimitiveTypeTable,
831 freevars: RefCell<FreevarMap>,
832 freevars_seen: RefCell<NodeMap<NodeSet>>,
833 export_map: ExportMap,
835 external_exports: ExternalExports,
837 // Whether or not to print error messages. Can be set to true
838 // when getting additional info for error message suggestions,
839 // so as to avoid printing duplicate errors
843 // Maps imports to the names of items actually imported (this actually maps
844 // all imports, but only glob imports are actually interesting).
847 used_imports: HashSet<(NodeId, Namespace)>,
848 used_crates: HashSet<CrateNum>,
852 enum FallbackChecks {
857 impl<'a, 'tcx> Resolver<'a, 'tcx> {
858 fn new(session: &'a Session,
859 ast_map: &'a ast_map::Map<'tcx>,
861 make_glob_map: MakeGlobMap) -> Resolver<'a, 'tcx> {
862 let graph_root = NameBindings::new();
864 graph_root.define_module(NoParentLink,
865 Some(DefId { krate: 0, node: 0 }),
871 let current_module = graph_root.get_module();
878 // The outermost module has def ID 0; this is not reflected in the
881 graph_root: graph_root,
883 trait_item_map: FnvHashMap(),
884 structs: FnvHashMap(),
886 unresolved_imports: 0,
888 current_module: current_module,
889 value_ribs: Vec::new(),
890 type_ribs: Vec::new(),
891 label_ribs: Vec::new(),
893 current_trait_ref: None,
894 current_self_type: None,
896 primitive_type_table: PrimitiveTypeTable::new(),
898 def_map: RefCell::new(NodeMap()),
899 freevars: RefCell::new(NodeMap()),
900 freevars_seen: RefCell::new(NodeMap()),
901 export_map: NodeMap(),
902 trait_map: NodeMap(),
903 used_imports: HashSet::new(),
904 used_crates: HashSet::new(),
905 external_exports: DefIdSet(),
908 make_glob_map: make_glob_map == MakeGlobMap::Yes,
909 glob_map: HashMap::new(),
914 fn record_import_use(&mut self, import_id: NodeId, name: Name) {
915 if !self.make_glob_map {
918 if self.glob_map.contains_key(&import_id) {
919 self.glob_map.get_mut(&import_id).unwrap().insert(name);
923 let mut new_set = HashSet::new();
924 new_set.insert(name);
925 self.glob_map.insert(import_id, new_set);
928 fn get_trait_name(&self, did: DefId) -> Name {
929 if did.krate == ast::LOCAL_CRATE {
930 self.ast_map.expect_item(did.node).ident.name
932 csearch::get_trait_name(&self.session.cstore, did)
936 fn create_name_bindings_from_module(module: Rc<Module>) -> NameBindings {
938 type_def: RefCell::new(Some(TypeNsDef {
939 modifiers: DefModifiers::IMPORTABLE,
940 module_def: Some(module),
944 value_def: RefCell::new(None),
948 /// Checks that the names of external crates don't collide with other
950 fn check_for_conflicts_between_external_crates(&self,
954 if module.external_module_children.borrow().contains_key(&name) {
955 span_err!(self.session, span, E0259,
956 "an external crate named `{}` has already \
957 been imported into this module",
962 /// Checks that the names of items don't collide with external crates.
963 fn check_for_conflicts_between_external_crates_and_items(&self,
967 if module.external_module_children.borrow().contains_key(&name) {
968 span_err!(self.session, span, E0260,
969 "the name `{}` conflicts with an external \
970 crate that has been imported into this \
976 /// Resolves the given module path from the given root `module_`.
977 fn resolve_module_path_from_root(&mut self,
979 module_path: &[Name],
982 name_search_type: NameSearchType,
984 -> ResolveResult<(Rc<Module>, LastPrivate)> {
985 fn search_parent_externals(needle: Name, module: &Rc<Module>)
986 -> Option<Rc<Module>> {
987 match module.external_module_children.borrow().get(&needle) {
988 Some(_) => Some(module.clone()),
989 None => match module.parent_link {
990 ModuleParentLink(ref parent, _) => {
991 search_parent_externals(needle, &parent.upgrade().unwrap())
998 let mut search_module = module_;
999 let mut index = index;
1000 let module_path_len = module_path.len();
1001 let mut closest_private = lp;
1003 // Resolve the module part of the path. This does not involve looking
1004 // upward though scope chains; we simply resolve names directly in
1005 // modules as we go.
1006 while index < module_path_len {
1007 let name = module_path[index];
1008 match self.resolve_name_in_module(search_module.clone(),
1014 let segment_name = token::get_name(name);
1015 let module_name = module_to_string(&*search_module);
1016 let mut span = span;
1017 let msg = if "???" == &module_name[..] {
1018 span.hi = span.lo + Pos::from_usize(segment_name.len());
1020 match search_parent_externals(name,
1021 &self.current_module) {
1023 let path_str = names_to_string(module_path);
1024 let target_mod_str = module_to_string(&*module);
1025 let current_mod_str =
1026 module_to_string(&*self.current_module);
1028 let prefix = if target_mod_str == current_mod_str {
1029 "self::".to_string()
1031 format!("{}::", target_mod_str)
1034 format!("Did you mean `{}{}`?", prefix, path_str)
1036 None => format!("Maybe a missing `extern crate {}`?",
1040 format!("Could not find `{}` in `{}`",
1045 return Failed(Some((span, msg)));
1047 Failed(err) => return Failed(err),
1049 debug!("(resolving module path for import) module \
1050 resolution is indeterminate: {}",
1052 return Indeterminate;
1054 Success((target, used_proxy)) => {
1055 // Check to see whether there are type bindings, and, if
1056 // so, whether there is a module within.
1057 match *target.bindings.type_def.borrow() {
1058 Some(ref type_def) => {
1059 match type_def.module_def {
1061 let msg = format!("Not a module `{}`",
1064 return Failed(Some((span, msg)));
1066 Some(ref module_def) => {
1067 search_module = module_def.clone();
1069 // track extern crates for unused_extern_crate lint
1070 if let Some(did) = module_def.def_id.get() {
1071 self.used_crates.insert(did.krate);
1074 // Keep track of the closest
1075 // private module used when
1076 // resolving this import chain.
1077 if !used_proxy && !search_module.is_public {
1078 if let Some(did) = search_module.def_id.get() {
1079 closest_private = LastMod(DependsOn(did));
1086 // There are no type bindings at all.
1087 let msg = format!("Not a module `{}`",
1089 return Failed(Some((span, msg)));
1098 return Success((search_module, closest_private));
1101 /// Attempts to resolve the module part of an import directive or path
1102 /// rooted at the given module.
1104 /// On success, returns the resolved module, and the closest *private*
1105 /// module found to the destination when resolving this path.
1106 fn resolve_module_path(&mut self,
1107 module_: Rc<Module>,
1108 module_path: &[Name],
1109 use_lexical_scope: UseLexicalScopeFlag,
1111 name_search_type: NameSearchType)
1112 -> ResolveResult<(Rc<Module>, LastPrivate)> {
1113 let module_path_len = module_path.len();
1114 assert!(module_path_len > 0);
1116 debug!("(resolving module path for import) processing `{}` rooted at `{}`",
1117 names_to_string(module_path),
1118 module_to_string(&*module_));
1120 // Resolve the module prefix, if any.
1121 let module_prefix_result = self.resolve_module_prefix(module_.clone(),
1127 match module_prefix_result {
1129 let mpath = names_to_string(module_path);
1130 let mpath = &mpath[..];
1131 match mpath.rfind(':') {
1133 let msg = format!("Could not find `{}` in `{}`",
1134 // idx +- 1 to account for the
1135 // colons on either side
1138 return Failed(Some((span, msg)));
1145 Failed(err) => return Failed(err),
1147 debug!("(resolving module path for import) indeterminate; \
1149 return Indeterminate;
1151 Success(NoPrefixFound) => {
1152 // There was no prefix, so we're considering the first element
1153 // of the path. How we handle this depends on whether we were
1154 // instructed to use lexical scope or not.
1155 match use_lexical_scope {
1156 DontUseLexicalScope => {
1157 // This is a crate-relative path. We will start the
1158 // resolution process at index zero.
1159 search_module = self.graph_root.get_module();
1161 last_private = LastMod(AllPublic);
1163 UseLexicalScope => {
1164 // This is not a crate-relative path. We resolve the
1165 // first component of the path in the current lexical
1166 // scope and then proceed to resolve below that.
1167 match self.resolve_module_in_lexical_scope(module_,
1169 Failed(err) => return Failed(err),
1171 debug!("(resolving module path for import) \
1172 indeterminate; bailing");
1173 return Indeterminate;
1175 Success(containing_module) => {
1176 search_module = containing_module;
1178 last_private = LastMod(AllPublic);
1184 Success(PrefixFound(ref containing_module, index)) => {
1185 search_module = containing_module.clone();
1186 start_index = index;
1187 last_private = LastMod(DependsOn(containing_module.def_id
1193 self.resolve_module_path_from_root(search_module,
1201 /// Invariant: This must only be called during main resolution, not during
1202 /// import resolution.
1203 fn resolve_item_in_lexical_scope(&mut self,
1204 module_: Rc<Module>,
1206 namespace: Namespace)
1207 -> ResolveResult<(Target, bool)> {
1208 debug!("(resolving item in lexical scope) resolving `{}` in \
1209 namespace {:?} in `{}`",
1212 module_to_string(&*module_));
1214 // The current module node is handled specially. First, check for
1215 // its immediate children.
1216 build_reduced_graph::populate_module_if_necessary(self, &module_);
1218 match module_.children.borrow().get(&name) {
1220 if name_bindings.defined_in_namespace(namespace) => {
1221 debug!("top name bindings succeeded");
1222 return Success((Target::new(module_.clone(),
1223 name_bindings.clone(),
1227 Some(_) | None => { /* Not found; continue. */ }
1230 // Now check for its import directives. We don't have to have resolved
1231 // all its imports in the usual way; this is because chains of
1232 // adjacent import statements are processed as though they mutated the
1234 if let Some(import_resolution) = module_.import_resolutions.borrow().get(&name) {
1235 match (*import_resolution).target_for_namespace(namespace) {
1237 // Not found; continue.
1238 debug!("(resolving item in lexical scope) found \
1239 import resolution, but not in namespace {:?}",
1243 debug!("(resolving item in lexical scope) using \
1244 import resolution");
1245 // track used imports and extern crates as well
1246 let id = import_resolution.id(namespace);
1247 self.used_imports.insert((id, namespace));
1248 self.record_import_use(id, name);
1249 if let Some(DefId{krate: kid, ..}) = target.target_module.def_id.get() {
1250 self.used_crates.insert(kid);
1252 return Success((target, false));
1257 // Search for external modules.
1258 if namespace == TypeNS {
1259 // FIXME (21114): In principle unclear `child` *has* to be lifted.
1260 let child = module_.external_module_children.borrow().get(&name).cloned();
1261 if let Some(module) = child {
1263 Rc::new(Resolver::create_name_bindings_from_module(module));
1264 debug!("lower name bindings succeeded");
1265 return Success((Target::new(module_,
1272 // Finally, proceed up the scope chain looking for parent modules.
1273 let mut search_module = module_;
1275 // Go to the next parent.
1276 match search_module.parent_link.clone() {
1278 // No more parents. This module was unresolved.
1279 debug!("(resolving item in lexical scope) unresolved \
1281 return Failed(None);
1283 ModuleParentLink(parent_module_node, _) => {
1284 match search_module.kind.get() {
1285 NormalModuleKind => {
1286 // We stop the search here.
1287 debug!("(resolving item in lexical \
1288 scope) unresolved module: not \
1289 searching through module \
1291 return Failed(None);
1296 AnonymousModuleKind => {
1297 search_module = parent_module_node.upgrade().unwrap();
1301 BlockParentLink(ref parent_module_node, _) => {
1302 search_module = parent_module_node.upgrade().unwrap();
1306 // Resolve the name in the parent module.
1307 match self.resolve_name_in_module(search_module.clone(),
1312 Failed(Some((span, msg))) => {
1313 resolve_err!(self, span, E0433, "failed to resolve. {}", msg);
1315 Failed(None) => (), // Continue up the search chain.
1317 // We couldn't see through the higher scope because of an
1318 // unresolved import higher up. Bail.
1320 debug!("(resolving item in lexical scope) indeterminate \
1321 higher scope; bailing");
1322 return Indeterminate;
1324 Success((target, used_reexport)) => {
1325 // We found the module.
1326 debug!("(resolving item in lexical scope) found name \
1328 return Success((target, used_reexport));
1334 /// Resolves a module name in the current lexical scope.
1335 fn resolve_module_in_lexical_scope(&mut self,
1336 module_: Rc<Module>,
1338 -> ResolveResult<Rc<Module>> {
1339 // If this module is an anonymous module, resolve the item in the
1340 // lexical scope. Otherwise, resolve the item from the crate root.
1341 let resolve_result = self.resolve_item_in_lexical_scope(module_, name, TypeNS);
1342 match resolve_result {
1343 Success((target, _)) => {
1344 let bindings = &*target.bindings;
1345 match *bindings.type_def.borrow() {
1346 Some(ref type_def) => {
1347 match type_def.module_def {
1349 debug!("!!! (resolving module in lexical \
1350 scope) module wasn't actually a \
1352 return Failed(None);
1354 Some(ref module_def) => {
1355 return Success(module_def.clone());
1360 debug!("!!! (resolving module in lexical scope) module
1361 wasn't actually a module!");
1362 return Failed(None);
1367 debug!("(resolving module in lexical scope) indeterminate; \
1369 return Indeterminate;
1372 debug!("(resolving module in lexical scope) failed to resolve");
1378 /// Returns the nearest normal module parent of the given module.
1379 fn get_nearest_normal_module_parent(&mut self, module_: Rc<Module>)
1380 -> Option<Rc<Module>> {
1381 let mut module_ = module_;
1383 match module_.parent_link.clone() {
1384 NoParentLink => return None,
1385 ModuleParentLink(new_module, _) |
1386 BlockParentLink(new_module, _) => {
1387 let new_module = new_module.upgrade().unwrap();
1388 match new_module.kind.get() {
1389 NormalModuleKind => return Some(new_module),
1393 AnonymousModuleKind => module_ = new_module,
1400 /// Returns the nearest normal module parent of the given module, or the
1401 /// module itself if it is a normal module.
1402 fn get_nearest_normal_module_parent_or_self(&mut self, module_: Rc<Module>)
1404 match module_.kind.get() {
1405 NormalModuleKind => return module_,
1409 AnonymousModuleKind => {
1410 match self.get_nearest_normal_module_parent(module_.clone()) {
1412 Some(new_module) => new_module
1418 /// Resolves a "module prefix". A module prefix is one or both of (a) `self::`;
1419 /// (b) some chain of `super::`.
1420 /// grammar: (SELF MOD_SEP ) ? (SUPER MOD_SEP) *
1421 fn resolve_module_prefix(&mut self,
1422 module_: Rc<Module>,
1423 module_path: &[Name])
1424 -> ResolveResult<ModulePrefixResult> {
1425 // Start at the current module if we see `self` or `super`, or at the
1426 // top of the crate otherwise.
1427 let mut containing_module;
1429 let first_module_path_string = token::get_name(module_path[0]);
1430 if "self" == &first_module_path_string[..] {
1432 self.get_nearest_normal_module_parent_or_self(module_);
1434 } else if "super" == &first_module_path_string[..] {
1436 self.get_nearest_normal_module_parent_or_self(module_);
1437 i = 0; // We'll handle `super` below.
1439 return Success(NoPrefixFound);
1442 // Now loop through all the `super`s we find.
1443 while i < module_path.len() {
1444 let string = token::get_name(module_path[i]);
1445 if "super" != &string[..] {
1448 debug!("(resolving module prefix) resolving `super` at {}",
1449 module_to_string(&*containing_module));
1450 match self.get_nearest_normal_module_parent(containing_module) {
1451 None => return Failed(None),
1452 Some(new_module) => {
1453 containing_module = new_module;
1459 debug!("(resolving module prefix) finished resolving prefix at {}",
1460 module_to_string(&*containing_module));
1462 return Success(PrefixFound(containing_module, i));
1465 /// Attempts to resolve the supplied name in the given module for the
1466 /// given namespace. If successful, returns the target corresponding to
1469 /// The boolean returned on success is an indicator of whether this lookup
1470 /// passed through a public re-export proxy.
1471 fn resolve_name_in_module(&mut self,
1472 module_: Rc<Module>,
1474 namespace: Namespace,
1475 name_search_type: NameSearchType,
1476 allow_private_imports: bool)
1477 -> ResolveResult<(Target, bool)> {
1478 debug!("(resolving name in module) resolving `{}` in `{}`",
1480 module_to_string(&*module_));
1482 // First, check the direct children of the module.
1483 build_reduced_graph::populate_module_if_necessary(self, &module_);
1485 match module_.children.borrow().get(&name) {
1487 if name_bindings.defined_in_namespace(namespace) => {
1488 debug!("(resolving name in module) found node as child");
1489 return Success((Target::new(module_.clone(),
1490 name_bindings.clone(),
1499 // Next, check the module's imports if necessary.
1501 // If this is a search of all imports, we should be done with glob
1502 // resolution at this point.
1503 if name_search_type == PathSearch {
1504 assert_eq!(module_.glob_count.get(), 0);
1507 // Check the list of resolved imports.
1508 match module_.import_resolutions.borrow().get(&name) {
1509 Some(import_resolution) if allow_private_imports ||
1510 import_resolution.is_public => {
1512 if import_resolution.is_public &&
1513 import_resolution.outstanding_references != 0 {
1514 debug!("(resolving name in module) import \
1515 unresolved; bailing out");
1516 return Indeterminate;
1518 match import_resolution.target_for_namespace(namespace) {
1520 debug!("(resolving name in module) name found, \
1521 but not in namespace {:?}",
1525 debug!("(resolving name in module) resolved to \
1527 // track used imports and extern crates as well
1528 let id = import_resolution.id(namespace);
1529 self.used_imports.insert((id, namespace));
1530 self.record_import_use(id, name);
1531 if let Some(DefId{krate: kid, ..}) = target.target_module.def_id.get() {
1532 self.used_crates.insert(kid);
1534 return Success((target, true));
1538 Some(..) | None => {} // Continue.
1541 // Finally, search through external children.
1542 if namespace == TypeNS {
1543 // FIXME (21114): In principle unclear `child` *has* to be lifted.
1544 let child = module_.external_module_children.borrow().get(&name).cloned();
1545 if let Some(module) = child {
1547 Rc::new(Resolver::create_name_bindings_from_module(module));
1548 return Success((Target::new(module_,
1555 // We're out of luck.
1556 debug!("(resolving name in module) failed to resolve `{}`",
1558 return Failed(None);
1561 fn report_unresolved_imports(&mut self, module_: Rc<Module>) {
1562 let index = module_.resolved_import_count.get();
1563 let imports = module_.imports.borrow();
1564 let import_count = imports.len();
1565 if index != import_count {
1566 let sn = self.session
1568 .span_to_snippet((*imports)[index].span)
1570 if sn.contains("::") {
1571 resolve_err!(self, (*imports)[index].span, E0432,
1572 "{}", "unresolved import");
1574 resolve_err!(self, (*imports)[index].span, E0432,
1575 "unresolved import (maybe you meant `{}::*`?)", sn);
1579 // Descend into children and anonymous children.
1580 build_reduced_graph::populate_module_if_necessary(self, &module_);
1582 for (_, child_node) in module_.children.borrow().iter() {
1583 match child_node.get_module_if_available() {
1587 Some(child_module) => {
1588 self.report_unresolved_imports(child_module);
1593 for (_, module_) in module_.anonymous_children.borrow().iter() {
1594 self.report_unresolved_imports(module_.clone());
1600 // We maintain a list of value ribs and type ribs.
1602 // Simultaneously, we keep track of the current position in the module
1603 // graph in the `current_module` pointer. When we go to resolve a name in
1604 // the value or type namespaces, we first look through all the ribs and
1605 // then query the module graph. When we resolve a name in the module
1606 // namespace, we can skip all the ribs (since nested modules are not
1607 // allowed within blocks in Rust) and jump straight to the current module
1610 // Named implementations are handled separately. When we find a method
1611 // call, we consult the module node to find all of the implementations in
1612 // scope. This information is lazily cached in the module node. We then
1613 // generate a fake "implementation scope" containing all the
1614 // implementations thus found, for compatibility with old resolve pass.
1616 fn with_scope<F>(&mut self, name: Option<Name>, f: F) where
1617 F: FnOnce(&mut Resolver),
1619 let orig_module = self.current_module.clone();
1621 // Move down in the graph.
1627 build_reduced_graph::populate_module_if_necessary(self, &orig_module);
1629 match orig_module.children.borrow().get(&name) {
1631 debug!("!!! (with scope) didn't find `{}` in `{}`",
1633 module_to_string(&*orig_module));
1635 Some(name_bindings) => {
1636 match (*name_bindings).get_module_if_available() {
1638 debug!("!!! (with scope) didn't find module \
1641 module_to_string(&*orig_module));
1644 self.current_module = module_;
1654 self.current_module = orig_module;
1657 /// Wraps the given definition in the appropriate number of `DefUpvar`
1663 -> Option<DefLike> {
1664 let mut def = match def_like {
1666 _ => return Some(def_like)
1670 self.session.span_bug(span,
1671 &format!("unexpected {:?} in bindings", def))
1673 DefLocal(node_id) => {
1677 // Nothing to do. Continue.
1679 ClosureRibKind(function_id) => {
1681 def = DefUpvar(node_id, function_id);
1683 let mut seen = self.freevars_seen.borrow_mut();
1684 let seen = match seen.entry(function_id) {
1685 Occupied(v) => v.into_mut(),
1686 Vacant(v) => v.insert(NodeSet()),
1688 if seen.contains(&node_id) {
1691 match self.freevars.borrow_mut().entry(function_id) {
1692 Occupied(v) => v.into_mut(),
1693 Vacant(v) => v.insert(vec![]),
1694 }.push(Freevar { def: prev_def, span: span });
1695 seen.insert(node_id);
1697 ItemRibKind | MethodRibKind => {
1698 // This was an attempt to access an upvar inside a
1699 // named function item. This is not allowed, so we
1701 resolve_err!(self, span, E0434, "{}",
1702 "can't capture dynamic environment in a fn item; \
1703 use the || { ... } closure form instead");
1706 ConstantItemRibKind => {
1707 // Still doesn't deal with upvars
1708 resolve_err!(self, span, E0435, "{}",
1709 "attempt to use a non-constant \
1710 value in a constant");
1716 DefTyParam(..) | DefSelfTy(..) => {
1719 NormalRibKind | MethodRibKind | ClosureRibKind(..) => {
1720 // Nothing to do. Continue.
1723 // This was an attempt to use a type parameter outside
1726 resolve_err!(self, span, E0401, "{}",
1727 "can't use type parameters from \
1728 outer function; try using a local \
1729 type parameter instead");
1732 ConstantItemRibKind => {
1734 resolve_err!(self, span, E0402, "{}",
1735 "cannot use an outer type \
1736 parameter in this context");
1747 /// Searches the current set of local scopes and
1748 /// applies translations for closures.
1749 fn search_ribs(&self,
1753 -> Option<DefLike> {
1754 // FIXME #4950: Try caching?
1756 for (i, rib) in ribs.iter().enumerate().rev() {
1757 if let Some(def_like) = rib.bindings.get(&name).cloned() {
1758 return self.upvarify(&ribs[i + 1..], def_like, span);
1765 /// Searches the current set of local scopes for labels.
1766 /// Stops after meeting a closure.
1767 fn search_label(&self, name: Name) -> Option<DefLike> {
1768 for rib in self.label_ribs.iter().rev() {
1774 // Do not resolve labels across function boundary
1778 let result = rib.bindings.get(&name).cloned();
1779 if result.is_some() {
1786 fn resolve_crate(&mut self, krate: &ast::Crate) {
1787 debug!("(resolving crate) starting");
1789 visit::walk_crate(self, krate);
1792 fn check_if_primitive_type_name(&self, name: Name, span: Span) {
1793 if let Some(_) = self.primitive_type_table.primitive_types.get(&name) {
1794 span_err!(self.session, span, E0317,
1795 "user-defined types or type parameters cannot shadow the primitive types");
1799 fn resolve_item(&mut self, item: &Item) {
1800 let name = item.ident.name;
1802 debug!("(resolving item) resolving {}",
1806 ItemEnum(_, ref generics) |
1807 ItemTy(_, ref generics) |
1808 ItemStruct(_, ref generics) => {
1809 self.check_if_primitive_type_name(name, item.span);
1811 self.with_type_parameter_rib(HasTypeParameters(generics,
1814 |this| visit::walk_item(this, item));
1816 ItemFn(_, _, _, _, ref generics, _) => {
1817 self.with_type_parameter_rib(HasTypeParameters(generics,
1820 |this| visit::walk_item(this, item));
1823 ItemDefaultImpl(_, ref trait_ref) => {
1824 self.with_optional_trait_ref(Some(trait_ref), |_, _| {});
1831 ref impl_items) => {
1832 self.resolve_implementation(generics,
1839 ItemTrait(_, ref generics, ref bounds, ref trait_items) => {
1840 self.check_if_primitive_type_name(name, item.span);
1842 // Create a new rib for the trait-wide type parameters.
1843 self.with_type_parameter_rib(HasTypeParameters(generics,
1847 this.with_self_rib(DefSelfTy(Some(local_def(item.id)), None), |this| {
1848 this.visit_generics(generics);
1849 visit::walk_ty_param_bounds_helper(this, bounds);
1851 for trait_item in trait_items {
1852 // Create a new rib for the trait_item-specific type
1855 // FIXME #4951: Do we need a node ID here?
1857 match trait_item.node {
1858 ast::ConstTraitItem(_, ref default) => {
1859 // Only impose the restrictions of
1860 // ConstRibKind if there's an actual constant
1861 // expression in a provided default.
1862 if default.is_some() {
1863 this.with_constant_rib(|this| {
1864 visit::walk_trait_item(this, trait_item)
1867 visit::walk_trait_item(this, trait_item)
1870 ast::MethodTraitItem(ref sig, _) => {
1871 let type_parameters =
1872 HasTypeParameters(&sig.generics,
1875 this.with_type_parameter_rib(type_parameters, |this| {
1876 visit::walk_trait_item(this, trait_item)
1879 ast::TypeTraitItem(..) => {
1880 this.check_if_primitive_type_name(trait_item.ident.name,
1882 this.with_type_parameter_rib(NoTypeParameters, |this| {
1883 visit::walk_trait_item(this, trait_item)
1892 ItemMod(_) | ItemForeignMod(_) => {
1893 self.with_scope(Some(name), |this| {
1894 visit::walk_item(this, item);
1898 ItemConst(..) | ItemStatic(..) => {
1899 self.with_constant_rib(|this| {
1900 visit::walk_item(this, item);
1904 ItemUse(ref view_path) => {
1905 // check for imports shadowing primitive types
1906 if let ast::ViewPathSimple(ident, _) = view_path.node {
1907 match self.def_map.borrow().get(&item.id).map(|d| d.full_def()) {
1908 Some(DefTy(..)) | Some(DefStruct(..)) | Some(DefTrait(..)) | None => {
1909 self.check_if_primitive_type_name(ident.name, item.span);
1916 ItemExternCrate(_) | ItemMac(..) => {
1917 // do nothing, these are just around to be encoded
1922 fn with_type_parameter_rib<F>(&mut self, type_parameters: TypeParameters, f: F) where
1923 F: FnOnce(&mut Resolver),
1925 match type_parameters {
1926 HasTypeParameters(generics, space, rib_kind) => {
1927 let mut function_type_rib = Rib::new(rib_kind);
1928 let mut seen_bindings = HashSet::new();
1929 for (index, type_parameter) in generics.ty_params.iter().enumerate() {
1930 let name = type_parameter.ident.name;
1931 debug!("with_type_parameter_rib: {}", type_parameter.id);
1933 if seen_bindings.contains(&name) {
1934 resolve_err!(self, type_parameter.span, E0403,
1935 "the name `{}` is already \
1937 parameter in this type \
1941 seen_bindings.insert(name);
1943 // plain insert (no renaming)
1944 function_type_rib.bindings.insert(name,
1945 DlDef(DefTyParam(space,
1947 local_def(type_parameter.id),
1950 self.type_ribs.push(function_type_rib);
1953 NoTypeParameters => {
1960 match type_parameters {
1961 HasTypeParameters(..) => { self.type_ribs.pop(); }
1962 NoTypeParameters => { }
1966 fn with_label_rib<F>(&mut self, f: F) where
1967 F: FnOnce(&mut Resolver),
1969 self.label_ribs.push(Rib::new(NormalRibKind));
1971 self.label_ribs.pop();
1974 fn with_constant_rib<F>(&mut self, f: F) where
1975 F: FnOnce(&mut Resolver),
1977 self.value_ribs.push(Rib::new(ConstantItemRibKind));
1978 self.type_ribs.push(Rib::new(ConstantItemRibKind));
1980 self.type_ribs.pop();
1981 self.value_ribs.pop();
1984 fn resolve_function(&mut self,
1986 declaration: &FnDecl,
1988 // Create a value rib for the function.
1989 self.value_ribs.push(Rib::new(rib_kind));
1991 // Create a label rib for the function.
1992 self.label_ribs.push(Rib::new(rib_kind));
1994 // Add each argument to the rib.
1995 let mut bindings_list = HashMap::new();
1996 for argument in &declaration.inputs {
1997 self.resolve_pattern(&*argument.pat,
1998 ArgumentIrrefutableMode,
1999 &mut bindings_list);
2001 self.visit_ty(&*argument.ty);
2003 debug!("(resolving function) recorded argument");
2005 visit::walk_fn_ret_ty(self, &declaration.output);
2007 // Resolve the function body.
2008 self.visit_block(&*block);
2010 debug!("(resolving function) leaving function");
2012 self.label_ribs.pop();
2013 self.value_ribs.pop();
2016 fn resolve_trait_reference(&mut self,
2020 -> Result<PathResolution, ()> {
2021 if let Some(path_res) = self.resolve_path(id, trait_path, path_depth, TypeNS, true) {
2022 if let DefTrait(_) = path_res.base_def {
2023 debug!("(resolving trait) found trait def: {:?}", path_res);
2026 resolve_err!(self, trait_path.span, E0404,
2027 "`{}` is not a trait",
2028 path_names_to_string(trait_path, path_depth));
2030 // If it's a typedef, give a note
2031 if let DefTy(..) = path_res.base_def {
2032 self.session.span_note(trait_path.span,
2033 "`type` aliases cannot be used for traits");
2038 resolve_err!(self, trait_path.span, E0405,
2039 "use of undeclared trait name `{}`",
2040 path_names_to_string(trait_path, path_depth));
2045 fn resolve_generics(&mut self, generics: &Generics) {
2046 for type_parameter in generics.ty_params.iter() {
2047 self.check_if_primitive_type_name(type_parameter.ident.name, type_parameter.span);
2049 for predicate in &generics.where_clause.predicates {
2051 &ast::WherePredicate::BoundPredicate(_) |
2052 &ast::WherePredicate::RegionPredicate(_) => {}
2053 &ast::WherePredicate::EqPredicate(ref eq_pred) => {
2054 let path_res = self.resolve_path(eq_pred.id, &eq_pred.path, 0, TypeNS, true);
2055 if let Some(PathResolution { base_def: DefTyParam(..), .. }) = path_res {
2056 self.record_def(eq_pred.id, path_res.unwrap());
2058 resolve_err!(self, eq_pred.span, E0406, "{}",
2059 "undeclared associated type");
2064 visit::walk_generics(self, generics);
2067 fn with_current_self_type<T, F>(&mut self, self_type: &Ty, f: F) -> T
2068 where F: FnOnce(&mut Resolver) -> T
2070 // Handle nested impls (inside fn bodies)
2071 let previous_value = replace(&mut self.current_self_type, Some(self_type.clone()));
2072 let result = f(self);
2073 self.current_self_type = previous_value;
2077 fn with_optional_trait_ref<T, F>(&mut self,
2078 opt_trait_ref: Option<&TraitRef>,
2081 where F: FnOnce(&mut Resolver, Option<DefId>) -> T
2083 let mut new_val = None;
2084 let mut new_id = None;
2085 if let Some(trait_ref) = opt_trait_ref {
2086 if let Ok(path_res) = self.resolve_trait_reference(trait_ref.ref_id,
2087 &trait_ref.path, 0) {
2088 assert!(path_res.depth == 0);
2089 self.record_def(trait_ref.ref_id, path_res);
2090 new_val = Some((path_res.base_def.def_id(), trait_ref.clone()));
2091 new_id = Some(path_res.base_def.def_id());
2093 visit::walk_trait_ref(self, trait_ref);
2095 let original_trait_ref = replace(&mut self.current_trait_ref, new_val);
2096 let result = f(self, new_id);
2097 self.current_trait_ref = original_trait_ref;
2101 fn with_self_rib<F>(&mut self, self_def: Def, f: F)
2102 where F: FnOnce(&mut Resolver)
2104 let mut self_type_rib = Rib::new(NormalRibKind);
2106 // plain insert (no renaming, types are not currently hygienic....)
2107 let name = special_names::type_self;
2108 self_type_rib.bindings.insert(name, DlDef(self_def));
2109 self.type_ribs.push(self_type_rib);
2111 self.type_ribs.pop();
2114 fn resolve_implementation(&mut self,
2115 generics: &Generics,
2116 opt_trait_reference: &Option<TraitRef>,
2119 impl_items: &[P<ImplItem>]) {
2120 // If applicable, create a rib for the type parameters.
2121 self.with_type_parameter_rib(HasTypeParameters(generics,
2125 // Resolve the type parameters.
2126 this.visit_generics(generics);
2128 // Resolve the trait reference, if necessary.
2129 this.with_optional_trait_ref(opt_trait_reference.as_ref(), |this, trait_id| {
2130 // Resolve the self type.
2131 this.visit_ty(self_type);
2133 this.with_self_rib(DefSelfTy(trait_id, Some((item_id, self_type.id))), |this| {
2134 this.with_current_self_type(self_type, |this| {
2135 for impl_item in impl_items {
2136 match impl_item.node {
2137 ConstImplItem(..) => {
2138 // If this is a trait impl, ensure the method
2140 this.check_trait_item(impl_item.ident.name,
2142 this.with_constant_rib(|this| {
2143 visit::walk_impl_item(this, impl_item);
2146 MethodImplItem(ref sig, _) => {
2147 // If this is a trait impl, ensure the method
2149 this.check_trait_item(impl_item.ident.name,
2152 // We also need a new scope for the method-
2153 // specific type parameters.
2154 let type_parameters =
2155 HasTypeParameters(&sig.generics,
2158 this.with_type_parameter_rib(type_parameters, |this| {
2159 visit::walk_impl_item(this, impl_item);
2162 TypeImplItem(ref ty) => {
2163 // If this is a trait impl, ensure the method
2165 this.check_trait_item(impl_item.ident.name,
2170 ast::MacImplItem(_) => {}
2179 fn check_trait_item(&self, name: Name, span: Span) {
2180 // If there is a TraitRef in scope for an impl, then the method must be in the trait.
2181 if let Some((did, ref trait_ref)) = self.current_trait_ref {
2182 if !self.trait_item_map.contains_key(&(name, did)) {
2183 let path_str = path_names_to_string(&trait_ref.path, 0);
2184 resolve_err!(self, span, E0407, "method `{}` is not a member of trait `{}`",
2190 fn resolve_local(&mut self, local: &Local) {
2191 // Resolve the type.
2192 visit::walk_ty_opt(self, &local.ty);
2194 // Resolve the initializer.
2195 visit::walk_expr_opt(self, &local.init);
2197 // Resolve the pattern.
2198 self.resolve_pattern(&*local.pat,
2199 LocalIrrefutableMode,
2200 &mut HashMap::new());
2203 // build a map from pattern identifiers to binding-info's.
2204 // this is done hygienically. This could arise for a macro
2205 // that expands into an or-pattern where one 'x' was from the
2206 // user and one 'x' came from the macro.
2207 fn binding_mode_map(&mut self, pat: &Pat) -> BindingMap {
2208 let mut result = HashMap::new();
2209 pat_bindings(&self.def_map, pat, |binding_mode, _id, sp, path1| {
2210 let name = mtwt::resolve(path1.node);
2211 result.insert(name, BindingInfo {
2213 binding_mode: binding_mode
2219 // check that all of the arms in an or-pattern have exactly the
2220 // same set of bindings, with the same binding modes for each.
2221 fn check_consistent_bindings(&mut self, arm: &Arm) {
2222 if arm.pats.is_empty() {
2225 let map_0 = self.binding_mode_map(&*arm.pats[0]);
2226 for (i, p) in arm.pats.iter().enumerate() {
2227 let map_i = self.binding_mode_map(&**p);
2229 for (&key, &binding_0) in &map_0 {
2230 match map_i.get(&key) {
2232 resolve_err!(self, p.span, E0408,
2233 "variable `{}` from pattern #1 is \
2234 not bound in pattern #{}",
2238 Some(binding_i) => {
2239 if binding_0.binding_mode != binding_i.binding_mode {
2240 resolve_err!(self, binding_i.span, E0409,
2241 "variable `{}` is bound with different \
2242 mode in pattern #{} than in pattern #1",
2250 for (&key, &binding) in &map_i {
2251 if !map_0.contains_key(&key) {
2252 resolve_err!(self, binding.span, E0410,
2253 "variable `{}` from pattern #{} is \
2254 not bound in pattern #1",
2262 fn resolve_arm(&mut self, arm: &Arm) {
2263 self.value_ribs.push(Rib::new(NormalRibKind));
2265 let mut bindings_list = HashMap::new();
2266 for pattern in &arm.pats {
2267 self.resolve_pattern(&**pattern, RefutableMode, &mut bindings_list);
2270 // This has to happen *after* we determine which
2271 // pat_idents are variants
2272 self.check_consistent_bindings(arm);
2274 visit::walk_expr_opt(self, &arm.guard);
2275 self.visit_expr(&*arm.body);
2277 self.value_ribs.pop();
2280 fn resolve_block(&mut self, block: &Block) {
2281 debug!("(resolving block) entering block");
2282 self.value_ribs.push(Rib::new(NormalRibKind));
2284 // Move down in the graph, if there's an anonymous module rooted here.
2285 let orig_module = self.current_module.clone();
2286 match orig_module.anonymous_children.borrow().get(&block.id) {
2287 None => { /* Nothing to do. */ }
2288 Some(anonymous_module) => {
2289 debug!("(resolving block) found anonymous module, moving \
2291 self.current_module = anonymous_module.clone();
2295 // Check for imports appearing after non-item statements.
2296 let mut found_non_item = false;
2297 for statement in &block.stmts {
2298 if let ast::StmtDecl(ref declaration, _) = statement.node {
2299 if let ast::DeclItem(ref i) = declaration.node {
2301 ItemExternCrate(_) | ItemUse(_) if found_non_item => {
2302 span_err!(self.session, i.span, E0154,
2303 "imports are not allowed after non-item statements");
2308 found_non_item = true
2311 found_non_item = true;
2315 // Descend into the block.
2316 visit::walk_block(self, block);
2319 self.current_module = orig_module;
2321 self.value_ribs.pop();
2322 debug!("(resolving block) leaving block");
2325 fn resolve_type(&mut self, ty: &Ty) {
2327 TyPath(ref maybe_qself, ref path) => {
2329 match self.resolve_possibly_assoc_item(ty.id,
2330 maybe_qself.as_ref(),
2334 // `<T>::a::b::c` is resolved by typeck alone.
2335 TypecheckRequired => {
2336 // Resolve embedded types.
2337 visit::walk_ty(self, ty);
2340 ResolveAttempt(resolution) => resolution,
2343 // This is a path in the type namespace. Walk through scopes
2347 // Write the result into the def map.
2348 debug!("(resolving type) writing resolution for `{}` \
2350 path_names_to_string(path, 0),
2352 self.record_def(ty.id, def);
2355 // Keep reporting some errors even if they're ignored above.
2356 self.resolve_path(ty.id, path, 0, TypeNS, true);
2358 let kind = if maybe_qself.is_some() {
2364 let self_type_name = special_idents::type_self.name;
2365 let is_invalid_self_type_name =
2366 path.segments.len() > 0 &&
2367 maybe_qself.is_none() &&
2368 path.segments[0].identifier.name == self_type_name;
2369 if is_invalid_self_type_name {
2370 resolve_err!(self, ty.span, E0411,
2371 "use of `Self` outside of an impl or trait");
2373 resolve_err!(self, ty.span, E0412,
2374 "use of undeclared {} `{}`",
2376 path_names_to_string(path, 0));
2383 // Resolve embedded types.
2384 visit::walk_ty(self, ty);
2387 fn resolve_pattern(&mut self,
2389 mode: PatternBindingMode,
2390 // Maps idents to the node ID for the (outermost)
2391 // pattern that binds them
2392 bindings_list: &mut HashMap<Name, NodeId>) {
2393 let pat_id = pattern.id;
2394 walk_pat(pattern, |pattern| {
2395 match pattern.node {
2396 PatIdent(binding_mode, ref path1, _) => {
2398 // The meaning of pat_ident with no type parameters
2399 // depends on whether an enum variant or unit-like struct
2400 // with that name is in scope. The probing lookup has to
2401 // be careful not to emit spurious errors. Only matching
2402 // patterns (match) can match nullary variants or
2403 // unit-like structs. For binding patterns (let), matching
2404 // such a value is simply disallowed (since it's rarely
2407 let ident = path1.node;
2408 let renamed = mtwt::resolve(ident);
2410 match self.resolve_bare_identifier_pattern(ident.name, pattern.span) {
2411 FoundStructOrEnumVariant(def, lp)
2412 if mode == RefutableMode => {
2413 debug!("(resolving pattern) resolving `{}` to \
2414 struct or enum variant",
2417 self.enforce_default_binding_mode(
2421 self.record_def(pattern.id, PathResolution {
2427 FoundStructOrEnumVariant(..) => {
2428 resolve_err!(self, pattern.span, E0413,
2429 "declaration of `{}` shadows an enum \
2430 variant or unit-like struct in \
2434 FoundConst(def, lp) if mode == RefutableMode => {
2435 debug!("(resolving pattern) resolving `{}` to \
2439 self.enforce_default_binding_mode(
2443 self.record_def(pattern.id, PathResolution {
2450 resolve_err!(self, pattern.span, E0414,
2452 "only irrefutable patterns \
2455 BareIdentifierPatternUnresolved => {
2456 debug!("(resolving pattern) binding `{}`",
2459 let def = DefLocal(pattern.id);
2461 // Record the definition so that later passes
2462 // will be able to distinguish variants from
2463 // locals in patterns.
2465 self.record_def(pattern.id, PathResolution {
2467 last_private: LastMod(AllPublic),
2471 // Add the binding to the local ribs, if it
2472 // doesn't already exist in the bindings list. (We
2473 // must not add it if it's in the bindings list
2474 // because that breaks the assumptions later
2475 // passes make about or-patterns.)
2476 if !bindings_list.contains_key(&renamed) {
2477 let this = &mut *self;
2478 let last_rib = this.value_ribs.last_mut().unwrap();
2479 last_rib.bindings.insert(renamed, DlDef(def));
2480 bindings_list.insert(renamed, pat_id);
2481 } else if mode == ArgumentIrrefutableMode &&
2482 bindings_list.contains_key(&renamed) {
2483 // Forbid duplicate bindings in the same
2485 resolve_err!(self, pattern.span, E0415,
2491 token::get_ident(ident));
2492 } else if bindings_list.get(&renamed) ==
2494 // Then this is a duplicate variable in the
2495 // same disjunction, which is an error.
2496 resolve_err!(self, pattern.span, E0416,
2497 "identifier `{}` is bound \
2498 more than once in the same \
2500 token::get_ident(ident));
2502 // Else, not bound in the same pattern: do
2508 PatEnum(ref path, _) => {
2509 // This must be an enum variant, struct or const.
2511 match self.resolve_possibly_assoc_item(pat_id, None,
2514 // The below shouldn't happen because all
2515 // qualified paths should be in PatQPath.
2516 TypecheckRequired =>
2517 self.session.span_bug(
2519 "resolve_possibly_assoc_item claimed
2520 that a path in PatEnum requires typecheck
2521 to resolve, but qualified paths should be
2523 ResolveAttempt(resolution) => resolution,
2525 if let Some(path_res) = resolution {
2526 match path_res.base_def {
2527 DefVariant(..) | DefStruct(..) | DefConst(..) => {
2528 self.record_def(pattern.id, path_res);
2531 resolve_err!(self, path.span, E0417, "{}",
2532 "static variables cannot be \
2533 referenced in a pattern, \
2534 use a `const` instead");
2537 // If anything ends up here entirely resolved,
2538 // it's an error. If anything ends up here
2539 // partially resolved, that's OK, because it may
2540 // be a `T::CONST` that typeck will resolve.
2541 if path_res.depth == 0 {
2542 resolve_err!(self, path.span, E0418,
2543 "`{}` is not an enum variant, struct or const",
2545 path.segments.last().unwrap().identifier));
2547 let const_name = path.segments.last().unwrap()
2549 let traits = self.get_traits_containing_item(const_name);
2550 self.trait_map.insert(pattern.id, traits);
2551 self.record_def(pattern.id, path_res);
2556 resolve_err!(self, path.span, E0419,
2557 "unresolved enum variant, struct or const `{}`",
2558 token::get_ident(path.segments.last().unwrap().identifier));
2560 visit::walk_path(self, path);
2563 PatQPath(ref qself, ref path) => {
2564 // Associated constants only.
2566 match self.resolve_possibly_assoc_item(pat_id, Some(qself),
2569 TypecheckRequired => {
2570 // All `<T>::CONST` should end up here, and will
2571 // require use of the trait map to resolve
2572 // during typechecking.
2573 let const_name = path.segments.last().unwrap()
2575 let traits = self.get_traits_containing_item(const_name);
2576 self.trait_map.insert(pattern.id, traits);
2577 visit::walk_pat(self, pattern);
2580 ResolveAttempt(resolution) => resolution,
2582 if let Some(path_res) = resolution {
2583 match path_res.base_def {
2584 // All `<T as Trait>::CONST` should end up here, and
2585 // have the trait already selected.
2586 DefAssociatedConst(..) => {
2587 self.record_def(pattern.id, path_res);
2590 resolve_err!(self, path.span, E0420,
2591 "`{}` is not an associated const",
2593 path.segments.last().unwrap().identifier));
2597 resolve_err!(self, path.span, E0421,
2598 "unresolved associated const `{}`",
2599 token::get_ident(path.segments.last().unwrap().identifier));
2601 visit::walk_pat(self, pattern);
2604 PatStruct(ref path, _, _) => {
2605 match self.resolve_path(pat_id, path, 0, TypeNS, false) {
2606 Some(definition) => {
2607 self.record_def(pattern.id, definition);
2610 debug!("(resolving pattern) didn't find struct \
2611 def: {:?}", result);
2612 resolve_err!(self, path.span, E0422,
2613 "`{}` does not name a structure",
2614 path_names_to_string(path, 0));
2617 visit::walk_path(self, path);
2620 PatLit(_) | PatRange(..) => {
2621 visit::walk_pat(self, pattern);
2632 fn resolve_bare_identifier_pattern(&mut self, name: Name, span: Span)
2633 -> BareIdentifierPatternResolution {
2634 let module = self.current_module.clone();
2635 match self.resolve_item_in_lexical_scope(module,
2638 Success((target, _)) => {
2639 debug!("(resolve bare identifier pattern) succeeded in \
2640 finding {} at {:?}",
2642 target.bindings.value_def.borrow());
2643 match *target.bindings.value_def.borrow() {
2645 panic!("resolved name in the value namespace to a \
2646 set of name bindings with no def?!");
2649 // For the two success cases, this lookup can be
2650 // considered as not having a private component because
2651 // the lookup happened only within the current module.
2653 def @ DefVariant(..) | def @ DefStruct(..) => {
2654 return FoundStructOrEnumVariant(def, LastMod(AllPublic));
2656 def @ DefConst(..) | def @ DefAssociatedConst(..) => {
2657 return FoundConst(def, LastMod(AllPublic));
2660 resolve_err!(self, span, E0417,
2662 "static variables cannot be \
2663 referenced in a pattern, \
2664 use a `const` instead");
2665 return BareIdentifierPatternUnresolved;
2668 return BareIdentifierPatternUnresolved;
2676 panic!("unexpected indeterminate result");
2680 Some((span, msg)) => {
2681 resolve_err!(self, span, E0433,
2682 "failed to resolve: {}",
2688 debug!("(resolve bare identifier pattern) failed to find {}",
2690 return BareIdentifierPatternUnresolved;
2695 /// Handles paths that may refer to associated items
2696 fn resolve_possibly_assoc_item(&mut self,
2698 maybe_qself: Option<&ast::QSelf>,
2700 namespace: Namespace,
2702 -> AssocItemResolveResult
2704 let max_assoc_types;
2708 if qself.position == 0 {
2709 return TypecheckRequired;
2711 max_assoc_types = path.segments.len() - qself.position;
2712 // Make sure the trait is valid.
2713 let _ = self.resolve_trait_reference(id, path, max_assoc_types);
2716 max_assoc_types = path.segments.len();
2720 let mut resolution = self.with_no_errors(|this| {
2721 this.resolve_path(id, path, 0, namespace, check_ribs)
2723 for depth in 1..max_assoc_types {
2724 if resolution.is_some() {
2727 self.with_no_errors(|this| {
2728 resolution = this.resolve_path(id, path, depth,
2732 if let Some(DefMod(_)) = resolution.map(|r| r.base_def) {
2733 // A module is not a valid type or value.
2736 ResolveAttempt(resolution)
2739 /// If `check_ribs` is true, checks the local definitions first; i.e.
2740 /// doesn't skip straight to the containing module.
2741 /// Skips `path_depth` trailing segments, which is also reflected in the
2742 /// returned value. See `middle::def::PathResolution` for more info.
2743 fn resolve_path(&mut self,
2747 namespace: Namespace,
2748 check_ribs: bool) -> Option<PathResolution> {
2749 let span = path.span;
2750 let segments = &path.segments[..path.segments.len()-path_depth];
2752 let mk_res = |(def, lp)| PathResolution::new(def, lp, path_depth);
2755 let def = self.resolve_crate_relative_path(span, segments, namespace);
2756 return def.map(mk_res);
2759 // Try to find a path to an item in a module.
2760 let unqualified_def =
2761 self.resolve_identifier(segments.last().unwrap().identifier,
2766 if segments.len() <= 1 {
2767 return unqualified_def.map(mk_res);
2770 let def = self.resolve_module_relative_path(span, segments, namespace);
2771 match (def, unqualified_def) {
2772 (Some((ref d, _)), Some((ref ud, _))) if *d == *ud => {
2774 .add_lint(lint::builtin::UNUSED_QUALIFICATIONS,
2776 "unnecessary qualification".to_string());
2784 // Resolve a single identifier.
2785 fn resolve_identifier(&mut self,
2787 namespace: Namespace,
2790 -> Option<(Def, LastPrivate)> {
2791 // First, check to see whether the name is a primitive type.
2792 if namespace == TypeNS {
2793 if let Some(&prim_ty) = self.primitive_type_table
2795 .get(&identifier.name) {
2796 return Some((DefPrimTy(prim_ty), LastMod(AllPublic)));
2801 if let Some(def) = self.resolve_identifier_in_local_ribs(identifier,
2804 return Some((def, LastMod(AllPublic)));
2808 self.resolve_item_by_name_in_lexical_scope(identifier.name, namespace)
2811 // FIXME #4952: Merge me with resolve_name_in_module?
2812 fn resolve_definition_of_name_in_module(&mut self,
2813 containing_module: Rc<Module>,
2815 namespace: Namespace)
2817 // First, search children.
2818 build_reduced_graph::populate_module_if_necessary(self, &containing_module);
2820 match containing_module.children.borrow().get(&name) {
2821 Some(child_name_bindings) => {
2822 match child_name_bindings.def_for_namespace(namespace) {
2824 // Found it. Stop the search here.
2825 let p = child_name_bindings.defined_in_public_namespace(namespace);
2826 let lp = if p {LastMod(AllPublic)} else {
2827 LastMod(DependsOn(def.def_id()))
2829 return ChildNameDefinition(def, lp);
2837 // Next, search import resolutions.
2838 match containing_module.import_resolutions.borrow().get(&name) {
2839 Some(import_resolution) if import_resolution.is_public => {
2840 if let Some(target) = (*import_resolution).target_for_namespace(namespace) {
2841 match target.bindings.def_for_namespace(namespace) {
2844 let id = import_resolution.id(namespace);
2845 // track imports and extern crates as well
2846 self.used_imports.insert((id, namespace));
2847 self.record_import_use(id, name);
2848 match target.target_module.def_id.get() {
2849 Some(DefId{krate: kid, ..}) => {
2850 self.used_crates.insert(kid);
2854 return ImportNameDefinition(def, LastMod(AllPublic));
2857 // This can happen with external impls, due to
2858 // the imperfect way we read the metadata.
2863 Some(..) | None => {} // Continue.
2866 // Finally, search through external children.
2867 if namespace == TypeNS {
2868 if let Some(module) = containing_module.external_module_children.borrow()
2869 .get(&name).cloned() {
2870 if let Some(def_id) = module.def_id.get() {
2871 // track used crates
2872 self.used_crates.insert(def_id.krate);
2873 let lp = if module.is_public {LastMod(AllPublic)} else {
2874 LastMod(DependsOn(def_id))
2876 return ChildNameDefinition(DefMod(def_id), lp);
2881 return NoNameDefinition;
2884 // resolve a "module-relative" path, e.g. a::b::c
2885 fn resolve_module_relative_path(&mut self,
2887 segments: &[ast::PathSegment],
2888 namespace: Namespace)
2889 -> Option<(Def, LastPrivate)> {
2890 let module_path = segments.init().iter()
2891 .map(|ps| ps.identifier.name)
2892 .collect::<Vec<_>>();
2894 let containing_module;
2896 let current_module = self.current_module.clone();
2897 match self.resolve_module_path(current_module,
2903 let (span, msg) = match err {
2904 Some((span, msg)) => (span, msg),
2906 let msg = format!("Use of undeclared type or module `{}`",
2907 names_to_string(&module_path));
2912 resolve_err!(self, span, E0433,
2913 "failed to resolve: {}",
2917 Indeterminate => panic!("indeterminate unexpected"),
2918 Success((resulting_module, resulting_last_private)) => {
2919 containing_module = resulting_module;
2920 last_private = resulting_last_private;
2924 let name = segments.last().unwrap().identifier.name;
2925 let def = match self.resolve_definition_of_name_in_module(containing_module.clone(),
2928 NoNameDefinition => {
2929 // We failed to resolve the name. Report an error.
2932 ChildNameDefinition(def, lp) | ImportNameDefinition(def, lp) => {
2933 (def, last_private.or(lp))
2936 if let Some(DefId{krate: kid, ..}) = containing_module.def_id.get() {
2937 self.used_crates.insert(kid);
2942 /// Invariant: This must be called only during main resolution, not during
2943 /// import resolution.
2944 fn resolve_crate_relative_path(&mut self,
2946 segments: &[ast::PathSegment],
2947 namespace: Namespace)
2948 -> Option<(Def, LastPrivate)> {
2949 let module_path = segments.init().iter()
2950 .map(|ps| ps.identifier.name)
2951 .collect::<Vec<_>>();
2953 let root_module = self.graph_root.get_module();
2955 let containing_module;
2957 match self.resolve_module_path_from_root(root_module,
2962 LastMod(AllPublic)) {
2964 let (span, msg) = match err {
2965 Some((span, msg)) => (span, msg),
2967 let msg = format!("Use of undeclared module `::{}`",
2968 names_to_string(&module_path[..]));
2973 /*self.resolve_error(span, &format!("failed to resolve. {}",
2975 resolve_err!(self, span, E0433,
2976 "failed to resolve: {}",
2982 panic!("indeterminate unexpected");
2985 Success((resulting_module, resulting_last_private)) => {
2986 containing_module = resulting_module;
2987 last_private = resulting_last_private;
2991 let name = segments.last().unwrap().identifier.name;
2992 match self.resolve_definition_of_name_in_module(containing_module,
2995 NoNameDefinition => {
2996 // We failed to resolve the name. Report an error.
2999 ChildNameDefinition(def, lp) | ImportNameDefinition(def, lp) => {
3000 return Some((def, last_private.or(lp)));
3005 fn resolve_identifier_in_local_ribs(&mut self,
3007 namespace: Namespace,
3010 // Check the local set of ribs.
3011 let search_result = match namespace {
3013 let renamed = mtwt::resolve(ident);
3014 self.search_ribs(&self.value_ribs, renamed, span)
3017 let name = ident.name;
3018 self.search_ribs(&self.type_ribs, name, span)
3022 match search_result {
3023 Some(DlDef(def)) => {
3024 debug!("(resolving path in local ribs) resolved `{}` to local: {:?}",
3025 token::get_ident(ident),
3029 Some(DlField) | Some(DlImpl(_)) | None => {
3035 fn resolve_item_by_name_in_lexical_scope(&mut self,
3037 namespace: Namespace)
3038 -> Option<(Def, LastPrivate)> {
3040 let module = self.current_module.clone();
3041 match self.resolve_item_in_lexical_scope(module,
3044 Success((target, _)) => {
3045 match (*target.bindings).def_for_namespace(namespace) {
3047 // This can happen if we were looking for a type and
3048 // found a module instead. Modules don't have defs.
3049 debug!("(resolving item path by identifier in lexical \
3050 scope) failed to resolve {} after success...",
3055 debug!("(resolving item path in lexical scope) \
3056 resolved `{}` to item",
3058 // This lookup is "all public" because it only searched
3059 // for one identifier in the current module (couldn't
3060 // have passed through reexports or anything like that.
3061 return Some((def, LastMod(AllPublic)));
3066 panic!("unexpected indeterminate result");
3069 debug!("(resolving item path by identifier in lexical scope) \
3070 failed to resolve {}", name);
3072 if let Some((span, msg)) = err {
3073 resolve_err!(self, span, E0433,
3074 "failed to resolve: {}",
3083 fn with_no_errors<T, F>(&mut self, f: F) -> T where
3084 F: FnOnce(&mut Resolver) -> T,
3086 self.emit_errors = false;
3088 self.emit_errors = true;
3092 fn find_fallback_in_self_type(&mut self, name: Name) -> FallbackSuggestion {
3093 fn extract_path_and_node_id(t: &Ty, allow: FallbackChecks)
3094 -> Option<(Path, NodeId, FallbackChecks)> {
3096 TyPath(None, ref path) => Some((path.clone(), t.id, allow)),
3097 TyPtr(ref mut_ty) => extract_path_and_node_id(&*mut_ty.ty, OnlyTraitAndStatics),
3098 TyRptr(_, ref mut_ty) => extract_path_and_node_id(&*mut_ty.ty, allow),
3099 // This doesn't handle the remaining `Ty` variants as they are not
3100 // that commonly the self_type, it might be interesting to provide
3101 // support for those in future.
3106 fn get_module(this: &mut Resolver, span: Span, name_path: &[ast::Name])
3107 -> Option<Rc<Module>> {
3108 let root = this.current_module.clone();
3109 let last_name = name_path.last().unwrap();
3111 if name_path.len() == 1 {
3112 match this.primitive_type_table.primitive_types.get(last_name) {
3115 match this.current_module.children.borrow().get(last_name) {
3116 Some(child) => child.get_module_if_available(),
3122 match this.resolve_module_path(root,
3127 Success((module, _)) => Some(module),
3133 fn is_static_method(this: &Resolver, did: DefId) -> bool {
3134 if did.krate == ast::LOCAL_CRATE {
3135 let sig = match this.ast_map.get(did.node) {
3136 ast_map::NodeTraitItem(trait_item) => match trait_item.node {
3137 ast::MethodTraitItem(ref sig, _) => sig,
3140 ast_map::NodeImplItem(impl_item) => match impl_item.node {
3141 ast::MethodImplItem(ref sig, _) => sig,
3146 sig.explicit_self.node == ast::SelfStatic
3148 csearch::is_static_method(&this.session.cstore, did)
3152 let (path, node_id, allowed) = match self.current_self_type {
3153 Some(ref ty) => match extract_path_and_node_id(ty, Everything) {
3155 None => return NoSuggestion,
3157 None => return NoSuggestion,
3160 if allowed == Everything {
3161 // Look for a field with the same name in the current self_type.
3162 match self.def_map.borrow().get(&node_id).map(|d| d.full_def()) {
3163 Some(DefTy(did, _)) |
3164 Some(DefStruct(did)) |
3165 Some(DefVariant(_, did, _)) => match self.structs.get(&did) {
3168 if fields.iter().any(|&field_name| name == field_name) {
3173 _ => {} // Self type didn't resolve properly
3177 let name_path = path.segments.iter().map(|seg| seg.identifier.name).collect::<Vec<_>>();
3179 // Look for a method in the current self type's impl module.
3180 if let Some(module) = get_module(self, path.span, &name_path) {
3181 if let Some(binding) = module.children.borrow().get(&name) {
3182 if let Some(DefMethod(did, _)) = binding.def_for_namespace(ValueNS) {
3183 if is_static_method(self, did) {
3184 return StaticMethod(path_names_to_string(&path, 0))
3186 if self.current_trait_ref.is_some() {
3188 } else if allowed == Everything {
3195 // Look for a method in the current trait.
3196 if let Some((trait_did, ref trait_ref)) = self.current_trait_ref {
3197 if let Some(&did) = self.trait_item_map.get(&(name, trait_did)) {
3198 if is_static_method(self, did) {
3199 return TraitMethod(path_names_to_string(&trait_ref.path, 0));
3209 fn find_best_match_for_name(&mut self, name: &str) -> Option<String> {
3210 let mut maybes: Vec<token::InternedString> = Vec::new();
3211 let mut values: Vec<usize> = Vec::new();
3213 for rib in self.value_ribs.iter().rev() {
3214 for (&k, _) in &rib.bindings {
3215 maybes.push(token::get_name(k));
3216 values.push(usize::MAX);
3220 let mut smallest = 0;
3221 for (i, other) in maybes.iter().enumerate() {
3222 values[i] = lev_distance(name, &other);
3224 if values[i] <= values[smallest] {
3229 // As a loose rule to avoid obviously incorrect suggestions, clamp the
3230 // maximum edit distance we will accept for a suggestion to one third of
3231 // the typo'd name's length.
3232 let max_distance = std::cmp::max(name.len(), 3) / 3;
3234 if !values.is_empty() &&
3235 values[smallest] <= max_distance &&
3236 name != &maybes[smallest][..] {
3238 Some(maybes[smallest].to_string())
3245 fn resolve_expr(&mut self, expr: &Expr) {
3246 // First, record candidate traits for this expression if it could
3247 // result in the invocation of a method call.
3249 self.record_candidate_traits_for_expr_if_necessary(expr);
3251 // Next, resolve the node.
3253 ExprPath(ref maybe_qself, ref path) => {
3255 match self.resolve_possibly_assoc_item(expr.id,
3256 maybe_qself.as_ref(),
3260 // `<T>::a::b::c` is resolved by typeck alone.
3261 TypecheckRequired => {
3262 let method_name = path.segments.last().unwrap().identifier.name;
3263 let traits = self.get_traits_containing_item(method_name);
3264 self.trait_map.insert(expr.id, traits);
3265 visit::walk_expr(self, expr);
3268 ResolveAttempt(resolution) => resolution,
3271 // This is a local path in the value namespace. Walk through
3272 // scopes looking for it.
3273 if let Some(path_res) = resolution {
3274 // Check if struct variant
3275 if let DefVariant(_, _, true) = path_res.base_def {
3276 let path_name = path_names_to_string(path, 0);
3277 resolve_err!(self, expr.span, E0423,
3278 "`{}` is a struct variant name, but \
3280 uses it like a function name",
3283 let msg = format!("did you mean to write: \
3284 `{} {{ /* fields */ }}`?",
3286 if self.emit_errors {
3287 self.session.fileline_help(expr.span, &msg);
3289 self.session.span_help(expr.span, &msg);
3292 // Write the result into the def map.
3293 debug!("(resolving expr) resolved `{}`",
3294 path_names_to_string(path, 0));
3296 // Partial resolutions will need the set of traits in scope,
3297 // so they can be completed during typeck.
3298 if path_res.depth != 0 {
3299 let method_name = path.segments.last().unwrap().identifier.name;
3300 let traits = self.get_traits_containing_item(method_name);
3301 self.trait_map.insert(expr.id, traits);
3304 self.record_def(expr.id, path_res);
3307 // Be helpful if the name refers to a struct
3308 // (The pattern matching def_tys where the id is in self.structs
3309 // matches on regular structs while excluding tuple- and enum-like
3310 // structs, which wouldn't result in this error.)
3311 let path_name = path_names_to_string(path, 0);
3312 let type_res = self.with_no_errors(|this| {
3313 this.resolve_path(expr.id, path, 0, TypeNS, false)
3315 match type_res.map(|r| r.base_def) {
3316 Some(DefTy(struct_id, _))
3317 if self.structs.contains_key(&struct_id) => {
3318 resolve_err!(self, expr.span, E0423,
3319 "{}` is a structure name, but \
3321 uses it like a function name",
3324 let msg = format!("did you mean to write: \
3325 `{} {{ /* fields */ }}`?",
3327 if self.emit_errors {
3328 self.session.fileline_help(expr.span, &msg);
3330 self.session.span_help(expr.span, &msg);
3334 // Keep reporting some errors even if they're ignored above.
3335 self.resolve_path(expr.id, path, 0, ValueNS, true);
3337 let mut method_scope = false;
3338 self.value_ribs.iter().rev().all(|rib| {
3339 method_scope = match rib.kind {
3340 MethodRibKind => true,
3341 ItemRibKind | ConstantItemRibKind => false,
3342 _ => return true, // Keep advancing
3344 false // Stop advancing
3348 &token::get_name(special_names::self_)[..] == path_name {
3349 resolve_err!(self, expr.span, E0424,
3351 "`self` is not available \
3352 in a static method. Maybe a \
3353 `self` argument is missing?");
3355 let last_name = path.segments.last().unwrap().identifier.name;
3356 let mut msg = match self.find_fallback_in_self_type(last_name) {
3358 // limit search to 5 to reduce the number
3359 // of stupid suggestions
3360 self.find_best_match_for_name(&path_name)
3361 .map_or("".to_string(),
3362 |x| format!("`{}`", x))
3364 Field => format!("`self.{}`", path_name),
3367 format!("to call `self.{}`", path_name),
3368 TraitMethod(path_str) |
3369 StaticMethod(path_str) =>
3370 format!("to call `{}::{}`", path_str, path_name)
3373 if !msg.is_empty() {
3374 msg = format!(". Did you mean {}?", msg)
3377 resolve_err!(self, expr.span, E0425,
3378 "unresolved name `{}`{}",
3386 visit::walk_expr(self, expr);
3389 ExprStruct(ref path, _, _) => {
3390 // Resolve the path to the structure it goes to. We don't
3391 // check to ensure that the path is actually a structure; that
3392 // is checked later during typeck.
3393 match self.resolve_path(expr.id, path, 0, TypeNS, false) {
3394 Some(definition) => self.record_def(expr.id, definition),
3396 debug!("(resolving expression) didn't find struct def",);
3397 resolve_err!(self, path.span, E0422,
3398 "`{}` does not name a structure",
3399 path_names_to_string(path, 0));
3403 visit::walk_expr(self, expr);
3406 ExprLoop(_, Some(label)) | ExprWhile(_, _, Some(label)) => {
3407 self.with_label_rib(|this| {
3408 let def_like = DlDef(DefLabel(expr.id));
3411 let rib = this.label_ribs.last_mut().unwrap();
3412 let renamed = mtwt::resolve(label);
3413 rib.bindings.insert(renamed, def_like);
3416 visit::walk_expr(this, expr);
3420 ExprBreak(Some(label)) | ExprAgain(Some(label)) => {
3421 let renamed = mtwt::resolve(label);
3422 match self.search_label(renamed) {
3424 resolve_err!(self, expr.span, E0426,
3425 "use of undeclared label `{}`",
3426 token::get_ident(label))
3428 Some(DlDef(def @ DefLabel(_))) => {
3429 // Since this def is a label, it is never read.
3430 self.record_def(expr.id, PathResolution {
3432 last_private: LastMod(AllPublic),
3437 self.session.span_bug(expr.span,
3438 "label wasn't mapped to a \
3445 visit::walk_expr(self, expr);
3450 fn record_candidate_traits_for_expr_if_necessary(&mut self, expr: &Expr) {
3452 ExprField(_, ident) => {
3453 // FIXME(#6890): Even though you can't treat a method like a
3454 // field, we need to add any trait methods we find that match
3455 // the field name so that we can do some nice error reporting
3456 // later on in typeck.
3457 let traits = self.get_traits_containing_item(ident.node.name);
3458 self.trait_map.insert(expr.id, traits);
3460 ExprMethodCall(ident, _, _) => {
3461 debug!("(recording candidate traits for expr) recording \
3464 let traits = self.get_traits_containing_item(ident.node.name);
3465 self.trait_map.insert(expr.id, traits);
3473 fn get_traits_containing_item(&mut self, name: Name) -> Vec<DefId> {
3474 debug!("(getting traits containing item) looking for '{}'",
3477 fn add_trait_info(found_traits: &mut Vec<DefId>,
3478 trait_def_id: DefId,
3480 debug!("(adding trait info) found trait {}:{} for method '{}'",
3484 found_traits.push(trait_def_id);
3487 let mut found_traits = Vec::new();
3488 let mut search_module = self.current_module.clone();
3490 // Look for the current trait.
3491 match self.current_trait_ref {
3492 Some((trait_def_id, _)) => {
3493 if self.trait_item_map.contains_key(&(name, trait_def_id)) {
3494 add_trait_info(&mut found_traits, trait_def_id, name);
3497 None => {} // Nothing to do.
3500 // Look for trait children.
3501 build_reduced_graph::populate_module_if_necessary(self, &search_module);
3504 for (_, child_names) in search_module.children.borrow().iter() {
3505 let def = match child_names.def_for_namespace(TypeNS) {
3509 let trait_def_id = match def {
3510 DefTrait(trait_def_id) => trait_def_id,
3513 if self.trait_item_map.contains_key(&(name, trait_def_id)) {
3514 add_trait_info(&mut found_traits, trait_def_id, name);
3519 // Look for imports.
3520 for (_, import) in search_module.import_resolutions.borrow().iter() {
3521 let target = match import.target_for_namespace(TypeNS) {
3523 Some(target) => target,
3525 let did = match target.bindings.def_for_namespace(TypeNS) {
3526 Some(DefTrait(trait_def_id)) => trait_def_id,
3527 Some(..) | None => continue,
3529 if self.trait_item_map.contains_key(&(name, did)) {
3530 add_trait_info(&mut found_traits, did, name);
3531 let id = import.type_id;
3532 self.used_imports.insert((id, TypeNS));
3533 let trait_name = self.get_trait_name(did);
3534 self.record_import_use(id, trait_name);
3535 if let Some(DefId{krate: kid, ..}) = target.target_module.def_id.get() {
3536 self.used_crates.insert(kid);
3541 match search_module.parent_link.clone() {
3542 NoParentLink | ModuleParentLink(..) => break,
3543 BlockParentLink(parent_module, _) => {
3544 search_module = parent_module.upgrade().unwrap();
3552 fn record_def(&mut self, node_id: NodeId, resolution: PathResolution) {
3553 debug!("(recording def) recording {:?} for {}", resolution, node_id);
3554 assert!(match resolution.last_private {LastImport{..} => false, _ => true},
3555 "Import should only be used for `use` directives");
3557 if let Some(prev_res) = self.def_map.borrow_mut().insert(node_id, resolution) {
3558 let span = self.ast_map.opt_span(node_id).unwrap_or(codemap::DUMMY_SP);
3559 self.session.span_bug(span, &format!("path resolved multiple times \
3560 ({:?} before, {:?} now)",
3561 prev_res, resolution));
3565 fn enforce_default_binding_mode(&mut self,
3567 pat_binding_mode: BindingMode,
3569 match pat_binding_mode {
3570 BindByValue(_) => {}
3572 resolve_err!(self, pat.span, E0427,
3573 "cannot use `ref` binding mode with {}",
3582 // Diagnostics are not particularly efficient, because they're rarely
3586 #[allow(dead_code)] // useful for debugging
3587 fn dump_module(&mut self, module_: Rc<Module>) {
3588 debug!("Dump of module `{}`:", module_to_string(&*module_));
3590 debug!("Children:");
3591 build_reduced_graph::populate_module_if_necessary(self, &module_);
3592 for (&name, _) in module_.children.borrow().iter() {
3593 debug!("* {}", name);
3596 debug!("Import resolutions:");
3597 let import_resolutions = module_.import_resolutions.borrow();
3598 for (&name, import_resolution) in import_resolutions.iter() {
3600 match import_resolution.target_for_namespace(ValueNS) {
3601 None => { value_repr = "".to_string(); }
3603 value_repr = " value:?".to_string();
3609 match import_resolution.target_for_namespace(TypeNS) {
3610 None => { type_repr = "".to_string(); }
3612 type_repr = " type:?".to_string();
3617 debug!("* {}:{}{}", name, value_repr, type_repr);
3623 fn names_to_string(names: &[Name]) -> String {
3624 let mut first = true;
3625 let mut result = String::new();
3630 result.push_str("::")
3632 result.push_str(&token::get_name(*name));
3637 fn path_names_to_string(path: &Path, depth: usize) -> String {
3638 let names: Vec<ast::Name> = path.segments[..path.segments.len()-depth]
3640 .map(|seg| seg.identifier.name)
3642 names_to_string(&names[..])
3645 /// A somewhat inefficient routine to obtain the name of a module.
3646 fn module_to_string(module: &Module) -> String {
3647 let mut names = Vec::new();
3649 fn collect_mod(names: &mut Vec<ast::Name>, module: &Module) {
3650 match module.parent_link {
3652 ModuleParentLink(ref module, name) => {
3654 collect_mod(names, &*module.upgrade().unwrap());
3656 BlockParentLink(ref module, _) => {
3657 // danger, shouldn't be ident?
3658 names.push(special_idents::opaque.name);
3659 collect_mod(names, &*module.upgrade().unwrap());
3663 collect_mod(&mut names, module);
3665 if names.is_empty() {
3666 return "???".to_string();
3668 names_to_string(&names.into_iter().rev().collect::<Vec<ast::Name>>())
3672 pub struct CrateMap {
3673 pub def_map: DefMap,
3674 pub freevars: RefCell<FreevarMap>,
3675 pub export_map: ExportMap,
3676 pub trait_map: TraitMap,
3677 pub external_exports: ExternalExports,
3678 pub glob_map: Option<GlobMap>
3681 #[derive(PartialEq,Copy, Clone)]
3682 pub enum MakeGlobMap {
3687 /// Entry point to crate resolution.
3688 pub fn resolve_crate<'a, 'tcx>(session: &'a Session,
3689 ast_map: &'a ast_map::Map<'tcx>,
3690 make_glob_map: MakeGlobMap)
3692 let krate = ast_map.krate();
3693 let mut resolver = Resolver::new(session, ast_map, krate.span, make_glob_map);
3695 build_reduced_graph::build_reduced_graph(&mut resolver, krate);
3696 session.abort_if_errors();
3698 resolve_imports::resolve_imports(&mut resolver);
3699 session.abort_if_errors();
3701 record_exports::record(&mut resolver);
3702 session.abort_if_errors();
3704 resolver.resolve_crate(krate);
3705 session.abort_if_errors();
3707 check_unused::check_crate(&mut resolver, krate);
3710 def_map: resolver.def_map,
3711 freevars: resolver.freevars,
3712 export_map: resolver.export_map,
3713 trait_map: resolver.trait_map,
3714 external_exports: resolver.external_exports,
3715 glob_map: if resolver.make_glob_map {
3716 Some(resolver.glob_map)
3723 __build_diagnostic_array! { librustc_resolve, DIAGNOSTICS }