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)]
31 macro_rules! resolve_err {
32 ($this:expr, $span:expr, $code:ident, $($rest:tt)*) => {
33 if $this.emit_errors {
34 span_err!($this.session, $span, $code, $($rest)*);
39 #[macro_use] extern crate log;
40 #[macro_use] extern crate syntax;
41 #[macro_use] #[no_link] extern crate rustc_bitflags;
45 use self::PatternBindingMode::*;
46 use self::Namespace::*;
47 use self::NamespaceResult::*;
48 use self::NameDefinition::*;
49 use self::ResolveResult::*;
50 use self::FallbackSuggestion::*;
51 use self::TypeParameters::*;
53 use self::UseLexicalScopeFlag::*;
54 use self::ModulePrefixResult::*;
55 use self::AssocItemResolveResult::*;
56 use self::NameSearchType::*;
57 use self::BareIdentifierPatternResolution::*;
58 use self::ParentLink::*;
59 use self::ModuleKind::*;
60 use self::FallbackChecks::*;
63 use rustc::session::Session;
65 use rustc::metadata::csearch;
66 use rustc::metadata::decoder::{DefLike, DlDef, DlField, DlImpl};
67 use rustc::middle::def::*;
68 use rustc::middle::pat_util::pat_bindings;
69 use rustc::middle::privacy::*;
70 use rustc::middle::subst::{ParamSpace, FnSpace, TypeSpace};
71 use rustc::middle::ty::{Freevar, FreevarMap, TraitMap, GlobMap};
72 use rustc::util::nodemap::{NodeMap, NodeSet, DefIdSet, FnvHashMap};
73 use rustc::util::lev_distance::lev_distance;
75 use syntax::ast::{Arm, BindByRef, BindByValue, BindingMode, Block};
76 use syntax::ast::{ConstImplItem, Crate, CrateNum};
77 use syntax::ast::{DefId, Expr, ExprAgain, ExprBreak, ExprField};
78 use syntax::ast::{ExprLoop, ExprWhile, ExprMethodCall};
79 use syntax::ast::{ExprPath, ExprStruct, FnDecl};
80 use syntax::ast::{ForeignItemFn, ForeignItemStatic, Generics};
81 use syntax::ast::{Ident, ImplItem, Item, ItemConst, ItemEnum, ItemExternCrate};
82 use syntax::ast::{ItemFn, ItemForeignMod, ItemImpl, ItemMac, ItemMod, ItemStatic, ItemDefaultImpl};
83 use syntax::ast::{ItemStruct, ItemTrait, ItemTy, ItemUse};
84 use syntax::ast::{Local, MethodImplItem, Name, NodeId};
85 use syntax::ast::{Pat, PatEnum, PatIdent, PatLit, PatQPath};
86 use syntax::ast::{PatRange, PatStruct, Path, PrimTy};
87 use syntax::ast::{TraitRef, Ty, TyBool, TyChar, TyF32};
88 use syntax::ast::{TyF64, TyFloat, TyIs, TyI8, TyI16, TyI32, TyI64, TyInt};
89 use syntax::ast::{TyPath, TyPtr};
90 use syntax::ast::{TyRptr, TyStr, TyUs, TyU8, TyU16, TyU32, TyU64, TyUint};
91 use syntax::ast::TypeImplItem;
93 use syntax::ast_util::{local_def, walk_pat};
94 use syntax::attr::AttrMetaMethods;
95 use syntax::ext::mtwt;
96 use syntax::parse::token::{self, special_names, special_idents};
98 use syntax::codemap::{self, Span, Pos};
99 use syntax::visit::{self, Visitor};
101 use std::collections::{HashMap, HashSet};
102 use std::collections::hash_map::Entry::{Occupied, Vacant};
103 use std::cell::{Cell, RefCell};
105 use std::mem::replace;
106 use std::rc::{Rc, Weak};
109 use resolve_imports::{Target, ImportDirective, ImportResolution};
110 use resolve_imports::Shadowable;
113 // NB: This module needs to be declared first so diagnostics are
114 // registered before they are used.
119 mod build_reduced_graph;
122 #[derive(Copy, Clone)]
125 binding_mode: BindingMode,
128 // Map from the name in a pattern to its binding mode.
129 type BindingMap = HashMap<Name, BindingInfo>;
131 #[derive(Copy, Clone, PartialEq)]
132 enum PatternBindingMode {
134 LocalIrrefutableMode,
135 ArgumentIrrefutableMode,
138 #[derive(Copy, Clone, PartialEq, Eq, Hash, Debug)]
144 /// A NamespaceResult represents the result of resolving an import in
145 /// a particular namespace. The result is either definitely-resolved,
146 /// definitely- unresolved, or unknown.
148 enum NamespaceResult {
149 /// Means that resolve hasn't gathered enough information yet to determine
150 /// whether the name is bound in this namespace. (That is, it hasn't
151 /// resolved all `use` directives yet.)
153 /// Means that resolve has determined that the name is definitely
154 /// not bound in the namespace.
156 /// Means that resolve has determined that the name is bound in the Module
157 /// argument, and specified by the NameBindings argument.
158 BoundResult(Rc<Module>, Rc<NameBindings>)
161 impl NamespaceResult {
162 fn is_unknown(&self) -> bool {
164 UnknownResult => true,
168 fn is_unbound(&self) -> bool {
170 UnboundResult => true,
176 enum NameDefinition {
177 // The name was unbound.
179 // The name identifies an immediate child.
180 ChildNameDefinition(Def, LastPrivate),
181 // The name identifies an import.
182 ImportNameDefinition(Def, LastPrivate),
185 impl<'a, 'v, 'tcx> Visitor<'v> for Resolver<'a, 'tcx> {
186 fn visit_item(&mut self, item: &Item) {
187 self.resolve_item(item);
189 fn visit_arm(&mut self, arm: &Arm) {
190 self.resolve_arm(arm);
192 fn visit_block(&mut self, block: &Block) {
193 self.resolve_block(block);
195 fn visit_expr(&mut self, expr: &Expr) {
196 self.resolve_expr(expr);
198 fn visit_local(&mut self, local: &Local) {
199 self.resolve_local(local);
201 fn visit_ty(&mut self, ty: &Ty) {
202 self.resolve_type(ty);
204 fn visit_generics(&mut self, generics: &Generics) {
205 self.resolve_generics(generics);
207 fn visit_poly_trait_ref(&mut self,
208 tref: &ast::PolyTraitRef,
209 m: &ast::TraitBoundModifier) {
210 match self.resolve_trait_reference(tref.trait_ref.ref_id, &tref.trait_ref.path, 0) {
211 Ok(def) => self.record_def(tref.trait_ref.ref_id, def),
212 Err(_) => { /* error already reported */ }
214 visit::walk_poly_trait_ref(self, tref, m);
216 fn visit_variant(&mut self, variant: &ast::Variant, generics: &Generics) {
217 if let Some(ref dis_expr) = variant.node.disr_expr {
218 // resolve the discriminator expr as a constant
219 self.with_constant_rib(|this| {
220 this.visit_expr(&**dis_expr);
224 // `visit::walk_variant` without the discriminant expression.
225 match variant.node.kind {
226 ast::TupleVariantKind(ref variant_arguments) => {
227 for variant_argument in variant_arguments {
228 self.visit_ty(&*variant_argument.ty);
231 ast::StructVariantKind(ref struct_definition) => {
232 self.visit_struct_def(&**struct_definition,
239 fn visit_foreign_item(&mut self, foreign_item: &ast::ForeignItem) {
240 let type_parameters = match foreign_item.node {
241 ForeignItemFn(_, ref generics) => {
242 HasTypeParameters(generics, FnSpace, ItemRibKind)
244 ForeignItemStatic(..) => NoTypeParameters
246 self.with_type_parameter_rib(type_parameters, |this| {
247 visit::walk_foreign_item(this, foreign_item);
250 fn visit_fn(&mut self,
251 function_kind: visit::FnKind<'v>,
252 declaration: &'v FnDecl,
256 let rib_kind = match function_kind {
257 visit::FkItemFn(_, generics, _, _, _, _) => {
258 self.visit_generics(generics);
261 visit::FkMethod(_, sig, _) => {
262 self.visit_generics(&sig.generics);
263 self.visit_explicit_self(&sig.explicit_self);
266 visit::FkFnBlock(..) => ClosureRibKind(node_id)
268 self.resolve_function(rib_kind, declaration, block);
272 type ErrorMessage = Option<(Span, String)>;
274 enum ResolveResult<T> {
275 Failed(ErrorMessage), // Failed to resolve the name, optional helpful error message.
276 Indeterminate, // Couldn't determine due to unresolved globs.
277 Success(T) // Successfully resolved the import.
280 impl<T> ResolveResult<T> {
281 fn indeterminate(&self) -> bool {
282 match *self { Indeterminate => true, _ => false }
286 enum FallbackSuggestion {
291 StaticMethod(String),
295 #[derive(Copy, Clone)]
296 enum TypeParameters<'a> {
302 // Identifies the things that these parameters
303 // were declared on (type, fn, etc)
306 // The kind of the rib used for type parameters.
310 // The rib kind controls the translation of local
311 // definitions (`DefLocal`) to upvars (`DefUpvar`).
312 #[derive(Copy, Clone, Debug)]
314 // No translation needs to be applied.
317 // We passed through a closure scope at the given node ID.
318 // Translate upvars as appropriate.
319 ClosureRibKind(NodeId /* func id */),
321 // We passed through an impl or trait and are now in one of its
322 // methods. Allow references to ty params that impl or trait
323 // binds. Disallow any other upvars (including other ty params that are
327 // We passed through an item scope. Disallow upvars.
330 // We're in a constant item. Can't refer to dynamic stuff.
334 #[derive(Copy, Clone)]
335 enum UseLexicalScopeFlag {
340 enum ModulePrefixResult {
342 PrefixFound(Rc<Module>, usize)
345 #[derive(Copy, Clone)]
346 enum AssocItemResolveResult {
347 /// Syntax such as `<T>::item`, which can't be resolved until type
350 /// We should have been able to resolve the associated item.
351 ResolveAttempt(Option<PathResolution>),
354 #[derive(Copy, Clone, PartialEq)]
355 enum NameSearchType {
356 /// We're doing a name search in order to resolve a `use` directive.
359 /// We're doing a name search in order to resolve a path type, a path
360 /// expression, or a path pattern.
364 #[derive(Copy, Clone)]
365 enum BareIdentifierPatternResolution {
366 FoundStructOrEnumVariant(Def, LastPrivate),
367 FoundConst(Def, LastPrivate),
368 BareIdentifierPatternUnresolved
374 bindings: HashMap<Name, DefLike>,
379 fn new(kind: RibKind) -> Rib {
381 bindings: HashMap::new(),
387 /// The link from a module up to its nearest parent node.
388 #[derive(Clone,Debug)]
391 ModuleParentLink(Weak<Module>, Name),
392 BlockParentLink(Weak<Module>, NodeId)
395 /// The type of module this is.
396 #[derive(Copy, Clone, PartialEq, Debug)]
405 /// One node in the tree of modules.
407 parent_link: ParentLink,
408 def_id: Cell<Option<DefId>>,
409 kind: Cell<ModuleKind>,
412 children: RefCell<HashMap<Name, Rc<NameBindings>>>,
413 imports: RefCell<Vec<ImportDirective>>,
415 // The external module children of this node that were declared with
417 external_module_children: RefCell<HashMap<Name, Rc<Module>>>,
419 // The anonymous children of this node. Anonymous children are pseudo-
420 // modules that are implicitly created around items contained within
423 // For example, if we have this:
431 // There will be an anonymous module created around `g` with the ID of the
432 // entry block for `f`.
433 anonymous_children: RefCell<NodeMap<Rc<Module>>>,
435 // The status of resolving each import in this module.
436 import_resolutions: RefCell<HashMap<Name, ImportResolution>>,
438 // The number of unresolved globs that this module exports.
439 glob_count: Cell<usize>,
441 // The index of the import we're resolving.
442 resolved_import_count: Cell<usize>,
444 // Whether this module is populated. If not populated, any attempt to
445 // access the children must be preceded with a
446 // `populate_module_if_necessary` call.
447 populated: Cell<bool>,
451 fn new(parent_link: ParentLink,
452 def_id: Option<DefId>,
458 parent_link: parent_link,
459 def_id: Cell::new(def_id),
460 kind: Cell::new(kind),
461 is_public: is_public,
462 children: RefCell::new(HashMap::new()),
463 imports: RefCell::new(Vec::new()),
464 external_module_children: RefCell::new(HashMap::new()),
465 anonymous_children: RefCell::new(NodeMap()),
466 import_resolutions: RefCell::new(HashMap::new()),
467 glob_count: Cell::new(0),
468 resolved_import_count: Cell::new(0),
469 populated: Cell::new(!external),
473 fn all_imports_resolved(&self) -> bool {
474 self.imports.borrow().len() == self.resolved_import_count.get()
478 impl fmt::Debug for Module {
479 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
480 write!(f, "{:?}, kind: {:?}, {}",
483 if self.is_public { "public" } else { "private" } )
489 flags DefModifiers: u8 {
490 const PUBLIC = 1 << 0,
491 const IMPORTABLE = 1 << 1,
495 // Records a possibly-private type definition.
496 #[derive(Clone,Debug)]
498 modifiers: DefModifiers, // see note in ImportResolution about how to use this
499 module_def: Option<Rc<Module>>,
500 type_def: Option<Def>,
501 type_span: Option<Span>
504 // Records a possibly-private value definition.
505 #[derive(Clone, Copy, Debug)]
507 modifiers: DefModifiers, // see note in ImportResolution about how to use this
509 value_span: Option<Span>,
512 // Records the definitions (at most one for each namespace) that a name is
515 pub struct NameBindings {
516 type_def: RefCell<Option<TypeNsDef>>, //< Meaning in type namespace.
517 value_def: RefCell<Option<ValueNsDef>>, //< Meaning in value namespace.
521 fn new() -> NameBindings {
523 type_def: RefCell::new(None),
524 value_def: RefCell::new(None),
528 /// Creates a new module in this set of name bindings.
529 fn define_module(&self,
530 parent_link: ParentLink,
531 def_id: Option<DefId>,
536 // Merges the module with the existing type def or creates a new one.
537 let modifiers = if is_public {
540 DefModifiers::empty()
541 } | DefModifiers::IMPORTABLE;
542 let module_ = Rc::new(Module::new(parent_link,
547 let type_def = self.type_def.borrow().clone();
550 *self.type_def.borrow_mut() = Some(TypeNsDef {
551 modifiers: modifiers,
552 module_def: Some(module_),
558 *self.type_def.borrow_mut() = Some(TypeNsDef {
559 modifiers: modifiers,
560 module_def: Some(module_),
562 type_def: type_def.type_def
568 /// Sets the kind of the module, creating a new one if necessary.
569 fn set_module_kind(&self,
570 parent_link: ParentLink,
571 def_id: Option<DefId>,
576 let modifiers = if is_public {
579 DefModifiers::empty()
580 } | DefModifiers::IMPORTABLE;
581 let type_def = self.type_def.borrow().clone();
584 let module = Module::new(parent_link,
589 *self.type_def.borrow_mut() = Some(TypeNsDef {
590 modifiers: modifiers,
591 module_def: Some(Rc::new(module)),
597 match type_def.module_def {
599 let module = Module::new(parent_link,
604 *self.type_def.borrow_mut() = Some(TypeNsDef {
605 modifiers: modifiers,
606 module_def: Some(Rc::new(module)),
607 type_def: type_def.type_def,
611 Some(module_def) => module_def.kind.set(kind),
617 /// Records a type definition.
618 fn define_type(&self, def: Def, sp: Span, modifiers: DefModifiers) {
619 debug!("defining type for def {:?} with modifiers {:?}", def, modifiers);
620 // Merges the type with the existing type def or creates a new one.
621 let type_def = self.type_def.borrow().clone();
624 *self.type_def.borrow_mut() = Some(TypeNsDef {
628 modifiers: modifiers,
632 *self.type_def.borrow_mut() = Some(TypeNsDef {
633 module_def: type_def.module_def,
636 modifiers: modifiers,
642 /// Records a value definition.
643 fn define_value(&self, def: Def, sp: Span, modifiers: DefModifiers) {
644 debug!("defining value for def {:?} with modifiers {:?}", def, modifiers);
645 *self.value_def.borrow_mut() = Some(ValueNsDef {
647 value_span: Some(sp),
648 modifiers: modifiers,
652 /// Returns the module node if applicable.
653 fn get_module_if_available(&self) -> Option<Rc<Module>> {
654 match *self.type_def.borrow() {
655 Some(ref type_def) => type_def.module_def.clone(),
660 /// Returns the module node. Panics if this node does not have a module
662 fn get_module(&self) -> Rc<Module> {
663 match self.get_module_if_available() {
665 panic!("get_module called on a node with no module \
668 Some(module_def) => module_def
672 fn defined_in_namespace(&self, namespace: Namespace) -> bool {
674 TypeNS => return self.type_def.borrow().is_some(),
675 ValueNS => return self.value_def.borrow().is_some()
679 fn defined_in_public_namespace(&self, namespace: Namespace) -> bool {
680 self.defined_in_namespace_with(namespace, DefModifiers::PUBLIC)
683 fn defined_in_namespace_with(&self, namespace: Namespace, modifiers: DefModifiers) -> bool {
685 TypeNS => match *self.type_def.borrow() {
686 Some(ref def) => def.modifiers.contains(modifiers), None => false
688 ValueNS => match *self.value_def.borrow() {
689 Some(ref def) => def.modifiers.contains(modifiers), None => false
694 fn def_for_namespace(&self, namespace: Namespace) -> Option<Def> {
697 match *self.type_def.borrow() {
699 Some(ref type_def) => {
700 match type_def.type_def {
701 Some(type_def) => Some(type_def),
703 match type_def.module_def {
704 Some(ref module) => {
705 match module.def_id.get() {
706 Some(did) => Some(DefMod(did)),
718 match *self.value_def.borrow() {
720 Some(value_def) => Some(value_def.def)
726 fn span_for_namespace(&self, namespace: Namespace) -> Option<Span> {
727 if self.defined_in_namespace(namespace) {
730 match *self.type_def.borrow() {
732 Some(ref type_def) => type_def.type_span
736 match *self.value_def.borrow() {
738 Some(ref value_def) => value_def.value_span
747 fn is_public(&self, namespace: Namespace) -> bool {
750 let type_def = self.type_def.borrow();
751 type_def.as_ref().unwrap().modifiers.contains(DefModifiers::PUBLIC)
754 let value_def = self.value_def.borrow();
755 value_def.as_ref().unwrap().modifiers.contains(DefModifiers::PUBLIC)
761 /// Interns the names of the primitive types.
762 struct PrimitiveTypeTable {
763 primitive_types: HashMap<Name, PrimTy>,
766 impl PrimitiveTypeTable {
767 fn new() -> PrimitiveTypeTable {
768 let mut table = PrimitiveTypeTable {
769 primitive_types: HashMap::new()
772 table.intern("bool", TyBool);
773 table.intern("char", TyChar);
774 table.intern("f32", TyFloat(TyF32));
775 table.intern("f64", TyFloat(TyF64));
776 table.intern("isize", TyInt(TyIs));
777 table.intern("i8", TyInt(TyI8));
778 table.intern("i16", TyInt(TyI16));
779 table.intern("i32", TyInt(TyI32));
780 table.intern("i64", TyInt(TyI64));
781 table.intern("str", TyStr);
782 table.intern("usize", TyUint(TyUs));
783 table.intern("u8", TyUint(TyU8));
784 table.intern("u16", TyUint(TyU16));
785 table.intern("u32", TyUint(TyU32));
786 table.intern("u64", TyUint(TyU64));
791 fn intern(&mut self, string: &str, primitive_type: PrimTy) {
792 self.primitive_types.insert(token::intern(string), primitive_type);
796 /// The main resolver class.
797 pub struct Resolver<'a, 'tcx:'a> {
798 session: &'a Session,
800 ast_map: &'a ast_map::Map<'tcx>,
802 graph_root: NameBindings,
804 trait_item_map: FnvHashMap<(Name, DefId), DefId>,
806 structs: FnvHashMap<DefId, Vec<Name>>,
808 // The number of imports that are currently unresolved.
809 unresolved_imports: usize,
811 // The module that represents the current item scope.
812 current_module: Rc<Module>,
814 // The current set of local scopes, for values.
815 // FIXME #4948: Reuse ribs to avoid allocation.
816 value_ribs: Vec<Rib>,
818 // The current set of local scopes, for types.
821 // The current set of local scopes, for labels.
822 label_ribs: Vec<Rib>,
824 // The trait that the current context can refer to.
825 current_trait_ref: Option<(DefId, TraitRef)>,
827 // The current self type if inside an impl (used for better errors).
828 current_self_type: Option<Ty>,
830 // The idents for the primitive types.
831 primitive_type_table: PrimitiveTypeTable,
834 freevars: RefCell<FreevarMap>,
835 freevars_seen: RefCell<NodeMap<NodeSet>>,
836 export_map: ExportMap,
838 external_exports: ExternalExports,
840 // Whether or not to print error messages. Can be set to true
841 // when getting additional info for error message suggestions,
842 // so as to avoid printing duplicate errors
846 // Maps imports to the names of items actually imported (this actually maps
847 // all imports, but only glob imports are actually interesting).
850 used_imports: HashSet<(NodeId, Namespace)>,
851 used_crates: HashSet<CrateNum>,
855 enum FallbackChecks {
860 impl<'a, 'tcx> Resolver<'a, 'tcx> {
861 fn new(session: &'a Session,
862 ast_map: &'a ast_map::Map<'tcx>,
864 make_glob_map: MakeGlobMap) -> Resolver<'a, 'tcx> {
865 let graph_root = NameBindings::new();
867 graph_root.define_module(NoParentLink,
868 Some(DefId { krate: 0, node: 0 }),
874 let current_module = graph_root.get_module();
881 // The outermost module has def ID 0; this is not reflected in the
884 graph_root: graph_root,
886 trait_item_map: FnvHashMap(),
887 structs: FnvHashMap(),
889 unresolved_imports: 0,
891 current_module: current_module,
892 value_ribs: Vec::new(),
893 type_ribs: Vec::new(),
894 label_ribs: Vec::new(),
896 current_trait_ref: None,
897 current_self_type: None,
899 primitive_type_table: PrimitiveTypeTable::new(),
901 def_map: RefCell::new(NodeMap()),
902 freevars: RefCell::new(NodeMap()),
903 freevars_seen: RefCell::new(NodeMap()),
904 export_map: NodeMap(),
905 trait_map: NodeMap(),
906 used_imports: HashSet::new(),
907 used_crates: HashSet::new(),
908 external_exports: DefIdSet(),
911 make_glob_map: make_glob_map == MakeGlobMap::Yes,
912 glob_map: HashMap::new(),
917 fn record_import_use(&mut self, import_id: NodeId, name: Name) {
918 if !self.make_glob_map {
921 if self.glob_map.contains_key(&import_id) {
922 self.glob_map.get_mut(&import_id).unwrap().insert(name);
926 let mut new_set = HashSet::new();
927 new_set.insert(name);
928 self.glob_map.insert(import_id, new_set);
931 fn get_trait_name(&self, did: DefId) -> Name {
932 if did.krate == ast::LOCAL_CRATE {
933 self.ast_map.expect_item(did.node).ident.name
935 csearch::get_trait_name(&self.session.cstore, did)
939 fn create_name_bindings_from_module(module: Rc<Module>) -> NameBindings {
941 type_def: RefCell::new(Some(TypeNsDef {
942 modifiers: DefModifiers::IMPORTABLE,
943 module_def: Some(module),
947 value_def: RefCell::new(None),
951 /// Checks that the names of external crates don't collide with other
953 fn check_for_conflicts_between_external_crates(&self,
957 if module.external_module_children.borrow().contains_key(&name) {
958 span_err!(self.session, span, E0259,
959 "an external crate named `{}` has already \
960 been imported into this module",
965 /// Checks that the names of items don't collide with external crates.
966 fn check_for_conflicts_between_external_crates_and_items(&self,
970 if module.external_module_children.borrow().contains_key(&name) {
971 span_err!(self.session, span, E0260,
972 "the name `{}` conflicts with an external \
973 crate that has been imported into this \
979 /// Resolves the given module path from the given root `module_`.
980 fn resolve_module_path_from_root(&mut self,
982 module_path: &[Name],
985 name_search_type: NameSearchType,
987 -> ResolveResult<(Rc<Module>, LastPrivate)> {
988 fn search_parent_externals(needle: Name, module: &Rc<Module>)
989 -> Option<Rc<Module>> {
990 match module.external_module_children.borrow().get(&needle) {
991 Some(_) => Some(module.clone()),
992 None => match module.parent_link {
993 ModuleParentLink(ref parent, _) => {
994 search_parent_externals(needle, &parent.upgrade().unwrap())
1001 let mut search_module = module_;
1002 let mut index = index;
1003 let module_path_len = module_path.len();
1004 let mut closest_private = lp;
1006 // Resolve the module part of the path. This does not involve looking
1007 // upward though scope chains; we simply resolve names directly in
1008 // modules as we go.
1009 while index < module_path_len {
1010 let name = module_path[index];
1011 match self.resolve_name_in_module(search_module.clone(),
1017 let segment_name = token::get_name(name);
1018 let module_name = module_to_string(&*search_module);
1019 let mut span = span;
1020 let msg = if "???" == &module_name[..] {
1021 span.hi = span.lo + Pos::from_usize(segment_name.len());
1023 match search_parent_externals(name,
1024 &self.current_module) {
1026 let path_str = names_to_string(module_path);
1027 let target_mod_str = module_to_string(&*module);
1028 let current_mod_str =
1029 module_to_string(&*self.current_module);
1031 let prefix = if target_mod_str == current_mod_str {
1032 "self::".to_string()
1034 format!("{}::", target_mod_str)
1037 format!("Did you mean `{}{}`?", prefix, path_str)
1039 None => format!("Maybe a missing `extern crate {}`?",
1043 format!("Could not find `{}` in `{}`",
1048 return Failed(Some((span, msg)));
1050 Failed(err) => return Failed(err),
1052 debug!("(resolving module path for import) module \
1053 resolution is indeterminate: {}",
1055 return Indeterminate;
1057 Success((target, used_proxy)) => {
1058 // Check to see whether there are type bindings, and, if
1059 // so, whether there is a module within.
1060 match *target.bindings.type_def.borrow() {
1061 Some(ref type_def) => {
1062 match type_def.module_def {
1064 let msg = format!("Not a module `{}`",
1067 return Failed(Some((span, msg)));
1069 Some(ref module_def) => {
1070 search_module = module_def.clone();
1072 // track extern crates for unused_extern_crate lint
1073 if let Some(did) = module_def.def_id.get() {
1074 self.used_crates.insert(did.krate);
1077 // Keep track of the closest
1078 // private module used when
1079 // resolving this import chain.
1080 if !used_proxy && !search_module.is_public {
1081 if let Some(did) = search_module.def_id.get() {
1082 closest_private = LastMod(DependsOn(did));
1089 // There are no type bindings at all.
1090 let msg = format!("Not a module `{}`",
1092 return Failed(Some((span, msg)));
1101 return Success((search_module, closest_private));
1104 /// Attempts to resolve the module part of an import directive or path
1105 /// rooted at the given module.
1107 /// On success, returns the resolved module, and the closest *private*
1108 /// module found to the destination when resolving this path.
1109 fn resolve_module_path(&mut self,
1110 module_: Rc<Module>,
1111 module_path: &[Name],
1112 use_lexical_scope: UseLexicalScopeFlag,
1114 name_search_type: NameSearchType)
1115 -> ResolveResult<(Rc<Module>, LastPrivate)> {
1116 let module_path_len = module_path.len();
1117 assert!(module_path_len > 0);
1119 debug!("(resolving module path for import) processing `{}` rooted at `{}`",
1120 names_to_string(module_path),
1121 module_to_string(&*module_));
1123 // Resolve the module prefix, if any.
1124 let module_prefix_result = self.resolve_module_prefix(module_.clone(),
1130 match module_prefix_result {
1132 let mpath = names_to_string(module_path);
1133 let mpath = &mpath[..];
1134 match mpath.rfind(':') {
1136 let msg = format!("Could not find `{}` in `{}`",
1137 // idx +- 1 to account for the
1138 // colons on either side
1141 return Failed(Some((span, msg)));
1148 Failed(err) => return Failed(err),
1150 debug!("(resolving module path for import) indeterminate; \
1152 return Indeterminate;
1154 Success(NoPrefixFound) => {
1155 // There was no prefix, so we're considering the first element
1156 // of the path. How we handle this depends on whether we were
1157 // instructed to use lexical scope or not.
1158 match use_lexical_scope {
1159 DontUseLexicalScope => {
1160 // This is a crate-relative path. We will start the
1161 // resolution process at index zero.
1162 search_module = self.graph_root.get_module();
1164 last_private = LastMod(AllPublic);
1166 UseLexicalScope => {
1167 // This is not a crate-relative path. We resolve the
1168 // first component of the path in the current lexical
1169 // scope and then proceed to resolve below that.
1170 match self.resolve_module_in_lexical_scope(module_,
1172 Failed(err) => return Failed(err),
1174 debug!("(resolving module path for import) \
1175 indeterminate; bailing");
1176 return Indeterminate;
1178 Success(containing_module) => {
1179 search_module = containing_module;
1181 last_private = LastMod(AllPublic);
1187 Success(PrefixFound(ref containing_module, index)) => {
1188 search_module = containing_module.clone();
1189 start_index = index;
1190 last_private = LastMod(DependsOn(containing_module.def_id
1196 self.resolve_module_path_from_root(search_module,
1204 /// Invariant: This must only be called during main resolution, not during
1205 /// import resolution.
1206 fn resolve_item_in_lexical_scope(&mut self,
1207 module_: Rc<Module>,
1209 namespace: Namespace)
1210 -> ResolveResult<(Target, bool)> {
1211 debug!("(resolving item in lexical scope) resolving `{}` in \
1212 namespace {:?} in `{}`",
1215 module_to_string(&*module_));
1217 // The current module node is handled specially. First, check for
1218 // its immediate children.
1219 build_reduced_graph::populate_module_if_necessary(self, &module_);
1221 match module_.children.borrow().get(&name) {
1223 if name_bindings.defined_in_namespace(namespace) => {
1224 debug!("top name bindings succeeded");
1225 return Success((Target::new(module_.clone(),
1226 name_bindings.clone(),
1230 Some(_) | None => { /* Not found; continue. */ }
1233 // Now check for its import directives. We don't have to have resolved
1234 // all its imports in the usual way; this is because chains of
1235 // adjacent import statements are processed as though they mutated the
1237 if let Some(import_resolution) = module_.import_resolutions.borrow().get(&name) {
1238 match (*import_resolution).target_for_namespace(namespace) {
1240 // Not found; continue.
1241 debug!("(resolving item in lexical scope) found \
1242 import resolution, but not in namespace {:?}",
1246 debug!("(resolving item in lexical scope) using \
1247 import resolution");
1248 // track used imports and extern crates as well
1249 let id = import_resolution.id(namespace);
1250 self.used_imports.insert((id, namespace));
1251 self.record_import_use(id, name);
1252 if let Some(DefId{krate: kid, ..}) = target.target_module.def_id.get() {
1253 self.used_crates.insert(kid);
1255 return Success((target, false));
1260 // Search for external modules.
1261 if namespace == TypeNS {
1262 // FIXME (21114): In principle unclear `child` *has* to be lifted.
1263 let child = module_.external_module_children.borrow().get(&name).cloned();
1264 if let Some(module) = child {
1266 Rc::new(Resolver::create_name_bindings_from_module(module));
1267 debug!("lower name bindings succeeded");
1268 return Success((Target::new(module_,
1275 // Finally, proceed up the scope chain looking for parent modules.
1276 let mut search_module = module_;
1278 // Go to the next parent.
1279 match search_module.parent_link.clone() {
1281 // No more parents. This module was unresolved.
1282 debug!("(resolving item in lexical scope) unresolved \
1284 return Failed(None);
1286 ModuleParentLink(parent_module_node, _) => {
1287 match search_module.kind.get() {
1288 NormalModuleKind => {
1289 // We stop the search here.
1290 debug!("(resolving item in lexical \
1291 scope) unresolved module: not \
1292 searching through module \
1294 return Failed(None);
1299 AnonymousModuleKind => {
1300 search_module = parent_module_node.upgrade().unwrap();
1304 BlockParentLink(ref parent_module_node, _) => {
1305 search_module = parent_module_node.upgrade().unwrap();
1309 // Resolve the name in the parent module.
1310 match self.resolve_name_in_module(search_module.clone(),
1315 Failed(Some((span, msg))) => {
1316 resolve_err!(self, span, E0397, "failed to resolve. {}", msg);
1318 Failed(None) => (), // Continue up the search chain.
1320 // We couldn't see through the higher scope because of an
1321 // unresolved import higher up. Bail.
1323 debug!("(resolving item in lexical scope) indeterminate \
1324 higher scope; bailing");
1325 return Indeterminate;
1327 Success((target, used_reexport)) => {
1328 // We found the module.
1329 debug!("(resolving item in lexical scope) found name \
1331 return Success((target, used_reexport));
1337 /// Resolves a module name in the current lexical scope.
1338 fn resolve_module_in_lexical_scope(&mut self,
1339 module_: Rc<Module>,
1341 -> ResolveResult<Rc<Module>> {
1342 // If this module is an anonymous module, resolve the item in the
1343 // lexical scope. Otherwise, resolve the item from the crate root.
1344 let resolve_result = self.resolve_item_in_lexical_scope(module_, name, TypeNS);
1345 match resolve_result {
1346 Success((target, _)) => {
1347 let bindings = &*target.bindings;
1348 match *bindings.type_def.borrow() {
1349 Some(ref type_def) => {
1350 match type_def.module_def {
1352 debug!("!!! (resolving module in lexical \
1353 scope) module wasn't actually a \
1355 return Failed(None);
1357 Some(ref module_def) => {
1358 return Success(module_def.clone());
1363 debug!("!!! (resolving module in lexical scope) module
1364 wasn't actually a module!");
1365 return Failed(None);
1370 debug!("(resolving module in lexical scope) indeterminate; \
1372 return Indeterminate;
1375 debug!("(resolving module in lexical scope) failed to resolve");
1381 /// Returns the nearest normal module parent of the given module.
1382 fn get_nearest_normal_module_parent(&mut self, module_: Rc<Module>)
1383 -> Option<Rc<Module>> {
1384 let mut module_ = module_;
1386 match module_.parent_link.clone() {
1387 NoParentLink => return None,
1388 ModuleParentLink(new_module, _) |
1389 BlockParentLink(new_module, _) => {
1390 let new_module = new_module.upgrade().unwrap();
1391 match new_module.kind.get() {
1392 NormalModuleKind => return Some(new_module),
1396 AnonymousModuleKind => module_ = new_module,
1403 /// Returns the nearest normal module parent of the given module, or the
1404 /// module itself if it is a normal module.
1405 fn get_nearest_normal_module_parent_or_self(&mut self, module_: Rc<Module>)
1407 match module_.kind.get() {
1408 NormalModuleKind => return module_,
1412 AnonymousModuleKind => {
1413 match self.get_nearest_normal_module_parent(module_.clone()) {
1415 Some(new_module) => new_module
1421 /// Resolves a "module prefix". A module prefix is one or both of (a) `self::`;
1422 /// (b) some chain of `super::`.
1423 /// grammar: (SELF MOD_SEP ) ? (SUPER MOD_SEP) *
1424 fn resolve_module_prefix(&mut self,
1425 module_: Rc<Module>,
1426 module_path: &[Name])
1427 -> ResolveResult<ModulePrefixResult> {
1428 // Start at the current module if we see `self` or `super`, or at the
1429 // top of the crate otherwise.
1430 let mut containing_module;
1432 let first_module_path_string = token::get_name(module_path[0]);
1433 if "self" == &first_module_path_string[..] {
1435 self.get_nearest_normal_module_parent_or_self(module_);
1437 } else if "super" == &first_module_path_string[..] {
1439 self.get_nearest_normal_module_parent_or_self(module_);
1440 i = 0; // We'll handle `super` below.
1442 return Success(NoPrefixFound);
1445 // Now loop through all the `super`s we find.
1446 while i < module_path.len() {
1447 let string = token::get_name(module_path[i]);
1448 if "super" != &string[..] {
1451 debug!("(resolving module prefix) resolving `super` at {}",
1452 module_to_string(&*containing_module));
1453 match self.get_nearest_normal_module_parent(containing_module) {
1454 None => return Failed(None),
1455 Some(new_module) => {
1456 containing_module = new_module;
1462 debug!("(resolving module prefix) finished resolving prefix at {}",
1463 module_to_string(&*containing_module));
1465 return Success(PrefixFound(containing_module, i));
1468 /// Attempts to resolve the supplied name in the given module for the
1469 /// given namespace. If successful, returns the target corresponding to
1472 /// The boolean returned on success is an indicator of whether this lookup
1473 /// passed through a public re-export proxy.
1474 fn resolve_name_in_module(&mut self,
1475 module_: Rc<Module>,
1477 namespace: Namespace,
1478 name_search_type: NameSearchType,
1479 allow_private_imports: bool)
1480 -> ResolveResult<(Target, bool)> {
1481 debug!("(resolving name in module) resolving `{}` in `{}`",
1483 module_to_string(&*module_));
1485 // First, check the direct children of the module.
1486 build_reduced_graph::populate_module_if_necessary(self, &module_);
1488 match module_.children.borrow().get(&name) {
1490 if name_bindings.defined_in_namespace(namespace) => {
1491 debug!("(resolving name in module) found node as child");
1492 return Success((Target::new(module_.clone(),
1493 name_bindings.clone(),
1502 // Next, check the module's imports if necessary.
1504 // If this is a search of all imports, we should be done with glob
1505 // resolution at this point.
1506 if name_search_type == PathSearch {
1507 assert_eq!(module_.glob_count.get(), 0);
1510 // Check the list of resolved imports.
1511 match module_.import_resolutions.borrow().get(&name) {
1512 Some(import_resolution) if allow_private_imports ||
1513 import_resolution.is_public => {
1515 if import_resolution.is_public &&
1516 import_resolution.outstanding_references != 0 {
1517 debug!("(resolving name in module) import \
1518 unresolved; bailing out");
1519 return Indeterminate;
1521 match import_resolution.target_for_namespace(namespace) {
1523 debug!("(resolving name in module) name found, \
1524 but not in namespace {:?}",
1528 debug!("(resolving name in module) resolved to \
1530 // track used imports and extern crates as well
1531 let id = import_resolution.id(namespace);
1532 self.used_imports.insert((id, namespace));
1533 self.record_import_use(id, name);
1534 if let Some(DefId{krate: kid, ..}) = target.target_module.def_id.get() {
1535 self.used_crates.insert(kid);
1537 return Success((target, true));
1541 Some(..) | None => {} // Continue.
1544 // Finally, search through external children.
1545 if namespace == TypeNS {
1546 // FIXME (21114): In principle unclear `child` *has* to be lifted.
1547 let child = module_.external_module_children.borrow().get(&name).cloned();
1548 if let Some(module) = child {
1550 Rc::new(Resolver::create_name_bindings_from_module(module));
1551 return Success((Target::new(module_,
1558 // We're out of luck.
1559 debug!("(resolving name in module) failed to resolve `{}`",
1561 return Failed(None);
1564 fn report_unresolved_imports(&mut self, module_: Rc<Module>) {
1565 let index = module_.resolved_import_count.get();
1566 let imports = module_.imports.borrow();
1567 let import_count = imports.len();
1568 if index != import_count {
1569 let sn = self.session
1571 .span_to_snippet((*imports)[index].span)
1573 if sn.contains("::") {
1574 resolve_err!(self, (*imports)[index].span, E0398,
1575 "{}", "unresolved import");
1577 resolve_err!(self, (*imports)[index].span, E0398,
1578 "unresolved import (maybe you meant `{}::*`?)", sn);
1582 // Descend into children and anonymous children.
1583 build_reduced_graph::populate_module_if_necessary(self, &module_);
1585 for (_, child_node) in module_.children.borrow().iter() {
1586 match child_node.get_module_if_available() {
1590 Some(child_module) => {
1591 self.report_unresolved_imports(child_module);
1596 for (_, module_) in module_.anonymous_children.borrow().iter() {
1597 self.report_unresolved_imports(module_.clone());
1603 // We maintain a list of value ribs and type ribs.
1605 // Simultaneously, we keep track of the current position in the module
1606 // graph in the `current_module` pointer. When we go to resolve a name in
1607 // the value or type namespaces, we first look through all the ribs and
1608 // then query the module graph. When we resolve a name in the module
1609 // namespace, we can skip all the ribs (since nested modules are not
1610 // allowed within blocks in Rust) and jump straight to the current module
1613 // Named implementations are handled separately. When we find a method
1614 // call, we consult the module node to find all of the implementations in
1615 // scope. This information is lazily cached in the module node. We then
1616 // generate a fake "implementation scope" containing all the
1617 // implementations thus found, for compatibility with old resolve pass.
1619 fn with_scope<F>(&mut self, name: Option<Name>, f: F) where
1620 F: FnOnce(&mut Resolver),
1622 let orig_module = self.current_module.clone();
1624 // Move down in the graph.
1630 build_reduced_graph::populate_module_if_necessary(self, &orig_module);
1632 match orig_module.children.borrow().get(&name) {
1634 debug!("!!! (with scope) didn't find `{}` in `{}`",
1636 module_to_string(&*orig_module));
1638 Some(name_bindings) => {
1639 match (*name_bindings).get_module_if_available() {
1641 debug!("!!! (with scope) didn't find module \
1644 module_to_string(&*orig_module));
1647 self.current_module = module_;
1657 self.current_module = orig_module;
1660 /// Wraps the given definition in the appropriate number of `DefUpvar`
1666 -> Option<DefLike> {
1667 let mut def = match def_like {
1669 _ => return Some(def_like)
1673 self.session.span_bug(span,
1674 &format!("unexpected {:?} in bindings", def))
1676 DefLocal(node_id) => {
1680 // Nothing to do. Continue.
1682 ClosureRibKind(function_id) => {
1684 def = DefUpvar(node_id, function_id);
1686 let mut seen = self.freevars_seen.borrow_mut();
1687 let seen = match seen.entry(function_id) {
1688 Occupied(v) => v.into_mut(),
1689 Vacant(v) => v.insert(NodeSet()),
1691 if seen.contains(&node_id) {
1694 match self.freevars.borrow_mut().entry(function_id) {
1695 Occupied(v) => v.into_mut(),
1696 Vacant(v) => v.insert(vec![]),
1697 }.push(Freevar { def: prev_def, span: span });
1698 seen.insert(node_id);
1700 ItemRibKind | MethodRibKind => {
1701 // This was an attempt to access an upvar inside a
1702 // named function item. This is not allowed, so we
1704 resolve_err!(self, span, E0399, "{}",
1705 "can't capture dynamic environment in a fn item; \
1706 use the || { ... } closure form instead");
1709 ConstantItemRibKind => {
1710 // Still doesn't deal with upvars
1711 resolve_err!(self, span, E0400, "{}",
1712 "attempt to use a non-constant \
1713 value in a constant");
1719 DefTyParam(..) | DefSelfTy(..) => {
1722 NormalRibKind | MethodRibKind | ClosureRibKind(..) => {
1723 // Nothing to do. Continue.
1726 // This was an attempt to use a type parameter outside
1729 resolve_err!(self, span, E0401, "{}",
1730 "can't use type parameters from \
1731 outer function; try using a local \
1732 type parameter instead");
1735 ConstantItemRibKind => {
1737 resolve_err!(self, span, E0402, "{}",
1738 "cannot use an outer type \
1739 parameter in this context");
1750 /// Searches the current set of local scopes and
1751 /// applies translations for closures.
1752 fn search_ribs(&self,
1756 -> Option<DefLike> {
1757 // FIXME #4950: Try caching?
1759 for (i, rib) in ribs.iter().enumerate().rev() {
1760 if let Some(def_like) = rib.bindings.get(&name).cloned() {
1761 return self.upvarify(&ribs[i + 1..], def_like, span);
1768 /// Searches the current set of local scopes for labels.
1769 /// Stops after meeting a closure.
1770 fn search_label(&self, name: Name) -> Option<DefLike> {
1771 for rib in self.label_ribs.iter().rev() {
1777 // Do not resolve labels across function boundary
1781 let result = rib.bindings.get(&name).cloned();
1782 if result.is_some() {
1789 fn resolve_crate(&mut self, krate: &ast::Crate) {
1790 debug!("(resolving crate) starting");
1792 visit::walk_crate(self, krate);
1795 fn check_if_primitive_type_name(&self, name: Name, span: Span) {
1796 if let Some(_) = self.primitive_type_table.primitive_types.get(&name) {
1797 span_err!(self.session, span, E0317,
1798 "user-defined types or type parameters cannot shadow the primitive types");
1802 fn resolve_item(&mut self, item: &Item) {
1803 let name = item.ident.name;
1805 debug!("(resolving item) resolving {}",
1809 ItemEnum(_, ref generics) |
1810 ItemTy(_, ref generics) |
1811 ItemStruct(_, ref generics) => {
1812 self.check_if_primitive_type_name(name, item.span);
1814 self.with_type_parameter_rib(HasTypeParameters(generics,
1817 |this| visit::walk_item(this, item));
1819 ItemFn(_, _, _, _, ref generics, _) => {
1820 self.with_type_parameter_rib(HasTypeParameters(generics,
1823 |this| visit::walk_item(this, item));
1826 ItemDefaultImpl(_, ref trait_ref) => {
1827 self.with_optional_trait_ref(Some(trait_ref), |_, _| {});
1834 ref impl_items) => {
1835 self.resolve_implementation(generics,
1842 ItemTrait(_, ref generics, ref bounds, ref trait_items) => {
1843 self.check_if_primitive_type_name(name, item.span);
1845 // Create a new rib for the trait-wide type parameters.
1846 self.with_type_parameter_rib(HasTypeParameters(generics,
1850 this.with_self_rib(DefSelfTy(Some(local_def(item.id)), None), |this| {
1851 this.visit_generics(generics);
1852 visit::walk_ty_param_bounds_helper(this, bounds);
1854 for trait_item in trait_items {
1855 // Create a new rib for the trait_item-specific type
1858 // FIXME #4951: Do we need a node ID here?
1860 match trait_item.node {
1861 ast::ConstTraitItem(_, ref default) => {
1862 // Only impose the restrictions of
1863 // ConstRibKind if there's an actual constant
1864 // expression in a provided default.
1865 if default.is_some() {
1866 this.with_constant_rib(|this| {
1867 visit::walk_trait_item(this, trait_item)
1870 visit::walk_trait_item(this, trait_item)
1873 ast::MethodTraitItem(ref sig, _) => {
1874 let type_parameters =
1875 HasTypeParameters(&sig.generics,
1878 this.with_type_parameter_rib(type_parameters, |this| {
1879 visit::walk_trait_item(this, trait_item)
1882 ast::TypeTraitItem(..) => {
1883 this.check_if_primitive_type_name(trait_item.ident.name,
1885 this.with_type_parameter_rib(NoTypeParameters, |this| {
1886 visit::walk_trait_item(this, trait_item)
1895 ItemMod(_) | ItemForeignMod(_) => {
1896 self.with_scope(Some(name), |this| {
1897 visit::walk_item(this, item);
1901 ItemConst(..) | ItemStatic(..) => {
1902 self.with_constant_rib(|this| {
1903 visit::walk_item(this, item);
1907 ItemUse(ref view_path) => {
1908 // check for imports shadowing primitive types
1909 if let ast::ViewPathSimple(ident, _) = view_path.node {
1910 match self.def_map.borrow().get(&item.id).map(|d| d.full_def()) {
1911 Some(DefTy(..)) | Some(DefStruct(..)) | Some(DefTrait(..)) | None => {
1912 self.check_if_primitive_type_name(ident.name, item.span);
1919 ItemExternCrate(_) | ItemMac(..) => {
1920 // do nothing, these are just around to be encoded
1925 fn with_type_parameter_rib<F>(&mut self, type_parameters: TypeParameters, f: F) where
1926 F: FnOnce(&mut Resolver),
1928 match type_parameters {
1929 HasTypeParameters(generics, space, rib_kind) => {
1930 let mut function_type_rib = Rib::new(rib_kind);
1931 let mut seen_bindings = HashSet::new();
1932 for (index, type_parameter) in generics.ty_params.iter().enumerate() {
1933 let name = type_parameter.ident.name;
1934 debug!("with_type_parameter_rib: {}", type_parameter.id);
1936 if seen_bindings.contains(&name) {
1937 resolve_err!(self, type_parameter.span, E0403,
1938 "the name `{}` is already \
1940 parameter in this type \
1944 seen_bindings.insert(name);
1946 // plain insert (no renaming)
1947 function_type_rib.bindings.insert(name,
1948 DlDef(DefTyParam(space,
1950 local_def(type_parameter.id),
1953 self.type_ribs.push(function_type_rib);
1956 NoTypeParameters => {
1963 match type_parameters {
1964 HasTypeParameters(..) => { self.type_ribs.pop(); }
1965 NoTypeParameters => { }
1969 fn with_label_rib<F>(&mut self, f: F) where
1970 F: FnOnce(&mut Resolver),
1972 self.label_ribs.push(Rib::new(NormalRibKind));
1974 self.label_ribs.pop();
1977 fn with_constant_rib<F>(&mut self, f: F) where
1978 F: FnOnce(&mut Resolver),
1980 self.value_ribs.push(Rib::new(ConstantItemRibKind));
1981 self.type_ribs.push(Rib::new(ConstantItemRibKind));
1983 self.type_ribs.pop();
1984 self.value_ribs.pop();
1987 fn resolve_function(&mut self,
1989 declaration: &FnDecl,
1991 // Create a value rib for the function.
1992 self.value_ribs.push(Rib::new(rib_kind));
1994 // Create a label rib for the function.
1995 self.label_ribs.push(Rib::new(rib_kind));
1997 // Add each argument to the rib.
1998 let mut bindings_list = HashMap::new();
1999 for argument in &declaration.inputs {
2000 self.resolve_pattern(&*argument.pat,
2001 ArgumentIrrefutableMode,
2002 &mut bindings_list);
2004 self.visit_ty(&*argument.ty);
2006 debug!("(resolving function) recorded argument");
2008 visit::walk_fn_ret_ty(self, &declaration.output);
2010 // Resolve the function body.
2011 self.visit_block(&*block);
2013 debug!("(resolving function) leaving function");
2015 self.label_ribs.pop();
2016 self.value_ribs.pop();
2019 fn resolve_trait_reference(&mut self,
2023 -> Result<PathResolution, ()> {
2024 if let Some(path_res) = self.resolve_path(id, trait_path, path_depth, TypeNS, true) {
2025 if let DefTrait(_) = path_res.base_def {
2026 debug!("(resolving trait) found trait def: {:?}", path_res);
2029 resolve_err!(self, trait_path.span, E0404,
2030 "`{}` is not a trait",
2031 path_names_to_string(trait_path, path_depth));
2033 // If it's a typedef, give a note
2034 if let DefTy(..) = path_res.base_def {
2035 self.session.span_note(trait_path.span,
2036 "`type` aliases cannot be used for traits");
2041 resolve_err!(self, trait_path.span, E0405,
2042 "use of undeclared trait name `{}`",
2043 path_names_to_string(trait_path, path_depth));
2048 fn resolve_generics(&mut self, generics: &Generics) {
2049 for type_parameter in generics.ty_params.iter() {
2050 self.check_if_primitive_type_name(type_parameter.ident.name, type_parameter.span);
2052 for predicate in &generics.where_clause.predicates {
2054 &ast::WherePredicate::BoundPredicate(_) |
2055 &ast::WherePredicate::RegionPredicate(_) => {}
2056 &ast::WherePredicate::EqPredicate(ref eq_pred) => {
2057 let path_res = self.resolve_path(eq_pred.id, &eq_pred.path, 0, TypeNS, true);
2058 if let Some(PathResolution { base_def: DefTyParam(..), .. }) = path_res {
2059 self.record_def(eq_pred.id, path_res.unwrap());
2061 resolve_err!(self, eq_pred.span, E0406, "{}",
2062 "undeclared associated type");
2067 visit::walk_generics(self, generics);
2070 fn with_current_self_type<T, F>(&mut self, self_type: &Ty, f: F) -> T
2071 where F: FnOnce(&mut Resolver) -> T
2073 // Handle nested impls (inside fn bodies)
2074 let previous_value = replace(&mut self.current_self_type, Some(self_type.clone()));
2075 let result = f(self);
2076 self.current_self_type = previous_value;
2080 fn with_optional_trait_ref<T, F>(&mut self,
2081 opt_trait_ref: Option<&TraitRef>,
2084 where F: FnOnce(&mut Resolver, Option<DefId>) -> T
2086 let mut new_val = None;
2087 let mut new_id = None;
2088 if let Some(trait_ref) = opt_trait_ref {
2089 if let Ok(path_res) = self.resolve_trait_reference(trait_ref.ref_id,
2090 &trait_ref.path, 0) {
2091 assert!(path_res.depth == 0);
2092 self.record_def(trait_ref.ref_id, path_res);
2093 new_val = Some((path_res.base_def.def_id(), trait_ref.clone()));
2094 new_id = Some(path_res.base_def.def_id());
2096 visit::walk_trait_ref(self, trait_ref);
2098 let original_trait_ref = replace(&mut self.current_trait_ref, new_val);
2099 let result = f(self, new_id);
2100 self.current_trait_ref = original_trait_ref;
2104 fn with_self_rib<F>(&mut self, self_def: Def, f: F)
2105 where F: FnOnce(&mut Resolver)
2107 let mut self_type_rib = Rib::new(NormalRibKind);
2109 // plain insert (no renaming, types are not currently hygienic....)
2110 let name = special_names::type_self;
2111 self_type_rib.bindings.insert(name, DlDef(self_def));
2112 self.type_ribs.push(self_type_rib);
2114 self.type_ribs.pop();
2117 fn resolve_implementation(&mut self,
2118 generics: &Generics,
2119 opt_trait_reference: &Option<TraitRef>,
2122 impl_items: &[P<ImplItem>]) {
2123 // If applicable, create a rib for the type parameters.
2124 self.with_type_parameter_rib(HasTypeParameters(generics,
2128 // Resolve the type parameters.
2129 this.visit_generics(generics);
2131 // Resolve the trait reference, if necessary.
2132 this.with_optional_trait_ref(opt_trait_reference.as_ref(), |this, trait_id| {
2133 // Resolve the self type.
2134 this.visit_ty(self_type);
2136 this.with_self_rib(DefSelfTy(trait_id, Some((item_id, self_type.id))), |this| {
2137 this.with_current_self_type(self_type, |this| {
2138 for impl_item in impl_items {
2139 match impl_item.node {
2140 ConstImplItem(..) => {
2141 // If this is a trait impl, ensure the method
2143 this.check_trait_item(impl_item.ident.name,
2145 this.with_constant_rib(|this| {
2146 visit::walk_impl_item(this, impl_item);
2149 MethodImplItem(ref sig, _) => {
2150 // If this is a trait impl, ensure the method
2152 this.check_trait_item(impl_item.ident.name,
2155 // We also need a new scope for the method-
2156 // specific type parameters.
2157 let type_parameters =
2158 HasTypeParameters(&sig.generics,
2161 this.with_type_parameter_rib(type_parameters, |this| {
2162 visit::walk_impl_item(this, impl_item);
2165 TypeImplItem(ref ty) => {
2166 // If this is a trait impl, ensure the method
2168 this.check_trait_item(impl_item.ident.name,
2173 ast::MacImplItem(_) => {}
2182 fn check_trait_item(&self, name: Name, span: Span) {
2183 // If there is a TraitRef in scope for an impl, then the method must be in the trait.
2184 if let Some((did, ref trait_ref)) = self.current_trait_ref {
2185 if !self.trait_item_map.contains_key(&(name, did)) {
2186 let path_str = path_names_to_string(&trait_ref.path, 0);
2187 resolve_err!(self, span, E0407, "method `{}` is not a member of trait `{}`",
2193 fn resolve_local(&mut self, local: &Local) {
2194 // Resolve the type.
2195 visit::walk_ty_opt(self, &local.ty);
2197 // Resolve the initializer.
2198 visit::walk_expr_opt(self, &local.init);
2200 // Resolve the pattern.
2201 self.resolve_pattern(&*local.pat,
2202 LocalIrrefutableMode,
2203 &mut HashMap::new());
2206 // build a map from pattern identifiers to binding-info's.
2207 // this is done hygienically. This could arise for a macro
2208 // that expands into an or-pattern where one 'x' was from the
2209 // user and one 'x' came from the macro.
2210 fn binding_mode_map(&mut self, pat: &Pat) -> BindingMap {
2211 let mut result = HashMap::new();
2212 pat_bindings(&self.def_map, pat, |binding_mode, _id, sp, path1| {
2213 let name = mtwt::resolve(path1.node);
2214 result.insert(name, BindingInfo {
2216 binding_mode: binding_mode
2222 // check that all of the arms in an or-pattern have exactly the
2223 // same set of bindings, with the same binding modes for each.
2224 fn check_consistent_bindings(&mut self, arm: &Arm) {
2225 if arm.pats.is_empty() {
2228 let map_0 = self.binding_mode_map(&*arm.pats[0]);
2229 for (i, p) in arm.pats.iter().enumerate() {
2230 let map_i = self.binding_mode_map(&**p);
2232 for (&key, &binding_0) in &map_0 {
2233 match map_i.get(&key) {
2235 resolve_err!(self, p.span, E0408,
2236 "variable `{}` from pattern #1 is \
2237 not bound in pattern #{}",
2241 Some(binding_i) => {
2242 if binding_0.binding_mode != binding_i.binding_mode {
2243 resolve_err!(self, binding_i.span, E0409,
2244 "variable `{}` is bound with different \
2245 mode in pattern #{} than in pattern #1",
2253 for (&key, &binding) in &map_i {
2254 if !map_0.contains_key(&key) {
2255 resolve_err!(self, binding.span, E0410,
2256 "variable `{}` from pattern {}{} is \
2257 not bound in pattern {}1",
2265 fn resolve_arm(&mut self, arm: &Arm) {
2266 self.value_ribs.push(Rib::new(NormalRibKind));
2268 let mut bindings_list = HashMap::new();
2269 for pattern in &arm.pats {
2270 self.resolve_pattern(&**pattern, RefutableMode, &mut bindings_list);
2273 // This has to happen *after* we determine which
2274 // pat_idents are variants
2275 self.check_consistent_bindings(arm);
2277 visit::walk_expr_opt(self, &arm.guard);
2278 self.visit_expr(&*arm.body);
2280 self.value_ribs.pop();
2283 fn resolve_block(&mut self, block: &Block) {
2284 debug!("(resolving block) entering block");
2285 self.value_ribs.push(Rib::new(NormalRibKind));
2287 // Move down in the graph, if there's an anonymous module rooted here.
2288 let orig_module = self.current_module.clone();
2289 match orig_module.anonymous_children.borrow().get(&block.id) {
2290 None => { /* Nothing to do. */ }
2291 Some(anonymous_module) => {
2292 debug!("(resolving block) found anonymous module, moving \
2294 self.current_module = anonymous_module.clone();
2298 // Check for imports appearing after non-item statements.
2299 let mut found_non_item = false;
2300 for statement in &block.stmts {
2301 if let ast::StmtDecl(ref declaration, _) = statement.node {
2302 if let ast::DeclItem(ref i) = declaration.node {
2304 ItemExternCrate(_) | ItemUse(_) if found_non_item => {
2305 span_err!(self.session, i.span, E0154,
2306 "imports are not allowed after non-item statements");
2311 found_non_item = true
2314 found_non_item = true;
2318 // Descend into the block.
2319 visit::walk_block(self, block);
2322 self.current_module = orig_module;
2324 self.value_ribs.pop();
2325 debug!("(resolving block) leaving block");
2328 fn resolve_type(&mut self, ty: &Ty) {
2330 TyPath(ref maybe_qself, ref path) => {
2332 match self.resolve_possibly_assoc_item(ty.id,
2333 maybe_qself.as_ref(),
2337 // `<T>::a::b::c` is resolved by typeck alone.
2338 TypecheckRequired => {
2339 // Resolve embedded types.
2340 visit::walk_ty(self, ty);
2343 ResolveAttempt(resolution) => resolution,
2346 // This is a path in the type namespace. Walk through scopes
2350 // Write the result into the def map.
2351 debug!("(resolving type) writing resolution for `{}` \
2353 path_names_to_string(path, 0),
2355 self.record_def(ty.id, def);
2358 // Keep reporting some errors even if they're ignored above.
2359 self.resolve_path(ty.id, path, 0, TypeNS, true);
2361 let kind = if maybe_qself.is_some() {
2367 let self_type_name = special_idents::type_self.name;
2368 let is_invalid_self_type_name =
2369 path.segments.len() > 0 &&
2370 maybe_qself.is_none() &&
2371 path.segments[0].identifier.name == self_type_name;
2372 if is_invalid_self_type_name {
2373 resolve_err!(self, ty.span, E0411,
2375 "use of `Self` outside of an impl or trait");
2377 resolve_err!(self, ty.span, E0412,
2378 "use of undeclared {} `{}`",
2380 path_names_to_string(path, 0));
2387 // Resolve embedded types.
2388 visit::walk_ty(self, ty);
2391 fn resolve_pattern(&mut self,
2393 mode: PatternBindingMode,
2394 // Maps idents to the node ID for the (outermost)
2395 // pattern that binds them
2396 bindings_list: &mut HashMap<Name, NodeId>) {
2397 let pat_id = pattern.id;
2398 walk_pat(pattern, |pattern| {
2399 match pattern.node {
2400 PatIdent(binding_mode, ref path1, _) => {
2402 // The meaning of pat_ident with no type parameters
2403 // depends on whether an enum variant or unit-like struct
2404 // with that name is in scope. The probing lookup has to
2405 // be careful not to emit spurious errors. Only matching
2406 // patterns (match) can match nullary variants or
2407 // unit-like structs. For binding patterns (let), matching
2408 // such a value is simply disallowed (since it's rarely
2411 let ident = path1.node;
2412 let renamed = mtwt::resolve(ident);
2414 match self.resolve_bare_identifier_pattern(ident.name, pattern.span) {
2415 FoundStructOrEnumVariant(def, lp)
2416 if mode == RefutableMode => {
2417 debug!("(resolving pattern) resolving `{}` to \
2418 struct or enum variant",
2421 self.enforce_default_binding_mode(
2425 self.record_def(pattern.id, PathResolution {
2431 FoundStructOrEnumVariant(..) => {
2432 resolve_err!(self, pattern.span, E0413,
2433 "declaration of `{}` shadows an enum \
2434 variant or unit-like struct in \
2438 FoundConst(def, lp) if mode == RefutableMode => {
2439 debug!("(resolving pattern) resolving `{}` to \
2443 self.enforce_default_binding_mode(
2447 self.record_def(pattern.id, PathResolution {
2454 resolve_err!(self, pattern.span, E0414,
2456 "only irrefutable patterns \
2459 BareIdentifierPatternUnresolved => {
2460 debug!("(resolving pattern) binding `{}`",
2463 let def = DefLocal(pattern.id);
2465 // Record the definition so that later passes
2466 // will be able to distinguish variants from
2467 // locals in patterns.
2469 self.record_def(pattern.id, PathResolution {
2471 last_private: LastMod(AllPublic),
2475 // Add the binding to the local ribs, if it
2476 // doesn't already exist in the bindings list. (We
2477 // must not add it if it's in the bindings list
2478 // because that breaks the assumptions later
2479 // passes make about or-patterns.)
2480 if !bindings_list.contains_key(&renamed) {
2481 let this = &mut *self;
2482 let last_rib = this.value_ribs.last_mut().unwrap();
2483 last_rib.bindings.insert(renamed, DlDef(def));
2484 bindings_list.insert(renamed, pat_id);
2485 } else if mode == ArgumentIrrefutableMode &&
2486 bindings_list.contains_key(&renamed) {
2487 // Forbid duplicate bindings in the same
2489 resolve_err!(self, pattern.span, E0415,
2495 token::get_ident(ident));
2496 } else if bindings_list.get(&renamed) ==
2498 // Then this is a duplicate variable in the
2499 // same disjunction, which is an error.
2500 resolve_err!(self, pattern.span, E0416,
2501 "identifier `{}` is bound \
2502 more than once in the same \
2504 token::get_ident(ident));
2506 // Else, not bound in the same pattern: do
2512 PatEnum(ref path, _) => {
2513 // This must be an enum variant, struct or const.
2515 match self.resolve_possibly_assoc_item(pat_id, None,
2518 // The below shouldn't happen because all
2519 // qualified paths should be in PatQPath.
2520 TypecheckRequired =>
2521 self.session.span_bug(
2523 "resolve_possibly_assoc_item claimed
2524 that a path in PatEnum requires typecheck
2525 to resolve, but qualified paths should be
2527 ResolveAttempt(resolution) => resolution,
2529 if let Some(path_res) = resolution {
2530 match path_res.base_def {
2531 DefVariant(..) | DefStruct(..) | DefConst(..) => {
2532 self.record_def(pattern.id, path_res);
2535 resolve_err!(self, path.span, E0417, "{}",
2536 "static variables cannot be \
2537 referenced in a pattern, \
2538 use a `const` instead");
2541 // If anything ends up here entirely resolved,
2542 // it's an error. If anything ends up here
2543 // partially resolved, that's OK, because it may
2544 // be a `T::CONST` that typeck will resolve.
2545 if path_res.depth == 0 {
2546 resolve_err!(self, path.span, E0418,
2547 "`{}` is not an enum variant, struct or const",
2549 path.segments.last().unwrap().identifier));
2551 let const_name = path.segments.last().unwrap()
2553 let traits = self.get_traits_containing_item(const_name);
2554 self.trait_map.insert(pattern.id, traits);
2555 self.record_def(pattern.id, path_res);
2560 resolve_err!(self, path.span, E0419,
2561 "unresolved enum variant, struct or const `{}`",
2562 token::get_ident(path.segments.last().unwrap().identifier));
2564 visit::walk_path(self, path);
2567 PatQPath(ref qself, ref path) => {
2568 // Associated constants only.
2570 match self.resolve_possibly_assoc_item(pat_id, Some(qself),
2573 TypecheckRequired => {
2574 // All `<T>::CONST` should end up here, and will
2575 // require use of the trait map to resolve
2576 // during typechecking.
2577 let const_name = path.segments.last().unwrap()
2579 let traits = self.get_traits_containing_item(const_name);
2580 self.trait_map.insert(pattern.id, traits);
2581 visit::walk_pat(self, pattern);
2584 ResolveAttempt(resolution) => resolution,
2586 if let Some(path_res) = resolution {
2587 match path_res.base_def {
2588 // All `<T as Trait>::CONST` should end up here, and
2589 // have the trait already selected.
2590 DefAssociatedConst(..) => {
2591 self.record_def(pattern.id, path_res);
2594 resolve_err!(self, path.span, E0420,
2595 "`{}` is not an associated const",
2597 path.segments.last().unwrap().identifier));
2601 resolve_err!(self, path.span, E0421,
2602 "unresolved associated const `{}`",
2603 token::get_ident(path.segments.last().unwrap().identifier));
2605 visit::walk_pat(self, pattern);
2608 PatStruct(ref path, _, _) => {
2609 match self.resolve_path(pat_id, path, 0, TypeNS, false) {
2610 Some(definition) => {
2611 self.record_def(pattern.id, definition);
2614 debug!("(resolving pattern) didn't find struct \
2615 def: {:?}", result);
2616 resolve_err!(self, path.span, E0422,
2617 "`{}` does not name a structure",
2618 path_names_to_string(path, 0));
2621 visit::walk_path(self, path);
2624 PatLit(_) | PatRange(..) => {
2625 visit::walk_pat(self, pattern);
2636 fn resolve_bare_identifier_pattern(&mut self, name: Name, span: Span)
2637 -> BareIdentifierPatternResolution {
2638 let module = self.current_module.clone();
2639 match self.resolve_item_in_lexical_scope(module,
2642 Success((target, _)) => {
2643 debug!("(resolve bare identifier pattern) succeeded in \
2644 finding {} at {:?}",
2646 target.bindings.value_def.borrow());
2647 match *target.bindings.value_def.borrow() {
2649 panic!("resolved name in the value namespace to a \
2650 set of name bindings with no def?!");
2653 // For the two success cases, this lookup can be
2654 // considered as not having a private component because
2655 // the lookup happened only within the current module.
2657 def @ DefVariant(..) | def @ DefStruct(..) => {
2658 return FoundStructOrEnumVariant(def, LastMod(AllPublic));
2660 def @ DefConst(..) | def @ DefAssociatedConst(..) => {
2661 return FoundConst(def, LastMod(AllPublic));
2664 resolve_err!(self, span, E0417,
2666 "static variables cannot be \
2667 referenced in a pattern, \
2668 use a `const` instead");
2669 return BareIdentifierPatternUnresolved;
2672 return BareIdentifierPatternUnresolved;
2680 panic!("unexpected indeterminate result");
2684 Some((span, msg)) => {
2685 resolve_err!(self, span, E0397,
2686 "failed to resolve: {}",
2692 debug!("(resolve bare identifier pattern) failed to find {}",
2694 return BareIdentifierPatternUnresolved;
2699 /// Handles paths that may refer to associated items
2700 fn resolve_possibly_assoc_item(&mut self,
2702 maybe_qself: Option<&ast::QSelf>,
2704 namespace: Namespace,
2706 -> AssocItemResolveResult
2708 let max_assoc_types;
2712 if qself.position == 0 {
2713 return TypecheckRequired;
2715 max_assoc_types = path.segments.len() - qself.position;
2716 // Make sure the trait is valid.
2717 let _ = self.resolve_trait_reference(id, path, max_assoc_types);
2720 max_assoc_types = path.segments.len();
2724 let mut resolution = self.with_no_errors(|this| {
2725 this.resolve_path(id, path, 0, namespace, check_ribs)
2727 for depth in 1..max_assoc_types {
2728 if resolution.is_some() {
2731 self.with_no_errors(|this| {
2732 resolution = this.resolve_path(id, path, depth,
2736 if let Some(DefMod(_)) = resolution.map(|r| r.base_def) {
2737 // A module is not a valid type or value.
2740 ResolveAttempt(resolution)
2743 /// If `check_ribs` is true, checks the local definitions first; i.e.
2744 /// doesn't skip straight to the containing module.
2745 /// Skips `path_depth` trailing segments, which is also reflected in the
2746 /// returned value. See `middle::def::PathResolution` for more info.
2747 fn resolve_path(&mut self,
2751 namespace: Namespace,
2752 check_ribs: bool) -> Option<PathResolution> {
2753 let span = path.span;
2754 let segments = &path.segments[..path.segments.len()-path_depth];
2756 let mk_res = |(def, lp)| PathResolution::new(def, lp, path_depth);
2759 let def = self.resolve_crate_relative_path(span, segments, namespace);
2760 return def.map(mk_res);
2763 // Try to find a path to an item in a module.
2764 let unqualified_def =
2765 self.resolve_identifier(segments.last().unwrap().identifier,
2770 if segments.len() <= 1 {
2771 return unqualified_def.map(mk_res);
2774 let def = self.resolve_module_relative_path(span, segments, namespace);
2775 match (def, unqualified_def) {
2776 (Some((ref d, _)), Some((ref ud, _))) if *d == *ud => {
2778 .add_lint(lint::builtin::UNUSED_QUALIFICATIONS,
2780 "unnecessary qualification".to_string());
2788 // Resolve a single identifier.
2789 fn resolve_identifier(&mut self,
2791 namespace: Namespace,
2794 -> Option<(Def, LastPrivate)> {
2795 // First, check to see whether the name is a primitive type.
2796 if namespace == TypeNS {
2797 if let Some(&prim_ty) = self.primitive_type_table
2799 .get(&identifier.name) {
2800 return Some((DefPrimTy(prim_ty), LastMod(AllPublic)));
2805 if let Some(def) = self.resolve_identifier_in_local_ribs(identifier,
2808 return Some((def, LastMod(AllPublic)));
2812 self.resolve_item_by_name_in_lexical_scope(identifier.name, namespace)
2815 // FIXME #4952: Merge me with resolve_name_in_module?
2816 fn resolve_definition_of_name_in_module(&mut self,
2817 containing_module: Rc<Module>,
2819 namespace: Namespace)
2821 // First, search children.
2822 build_reduced_graph::populate_module_if_necessary(self, &containing_module);
2824 match containing_module.children.borrow().get(&name) {
2825 Some(child_name_bindings) => {
2826 match child_name_bindings.def_for_namespace(namespace) {
2828 // Found it. Stop the search here.
2829 let p = child_name_bindings.defined_in_public_namespace(namespace);
2830 let lp = if p {LastMod(AllPublic)} else {
2831 LastMod(DependsOn(def.def_id()))
2833 return ChildNameDefinition(def, lp);
2841 // Next, search import resolutions.
2842 match containing_module.import_resolutions.borrow().get(&name) {
2843 Some(import_resolution) if import_resolution.is_public => {
2844 if let Some(target) = (*import_resolution).target_for_namespace(namespace) {
2845 match target.bindings.def_for_namespace(namespace) {
2848 let id = import_resolution.id(namespace);
2849 // track imports and extern crates as well
2850 self.used_imports.insert((id, namespace));
2851 self.record_import_use(id, name);
2852 match target.target_module.def_id.get() {
2853 Some(DefId{krate: kid, ..}) => {
2854 self.used_crates.insert(kid);
2858 return ImportNameDefinition(def, LastMod(AllPublic));
2861 // This can happen with external impls, due to
2862 // the imperfect way we read the metadata.
2867 Some(..) | None => {} // Continue.
2870 // Finally, search through external children.
2871 if namespace == TypeNS {
2872 if let Some(module) = containing_module.external_module_children.borrow()
2873 .get(&name).cloned() {
2874 if let Some(def_id) = module.def_id.get() {
2875 // track used crates
2876 self.used_crates.insert(def_id.krate);
2877 let lp = if module.is_public {LastMod(AllPublic)} else {
2878 LastMod(DependsOn(def_id))
2880 return ChildNameDefinition(DefMod(def_id), lp);
2885 return NoNameDefinition;
2888 // resolve a "module-relative" path, e.g. a::b::c
2889 fn resolve_module_relative_path(&mut self,
2891 segments: &[ast::PathSegment],
2892 namespace: Namespace)
2893 -> Option<(Def, LastPrivate)> {
2894 let module_path = segments.init().iter()
2895 .map(|ps| ps.identifier.name)
2896 .collect::<Vec<_>>();
2898 let containing_module;
2900 let current_module = self.current_module.clone();
2901 match self.resolve_module_path(current_module,
2907 let (span, msg) = match err {
2908 Some((span, msg)) => (span, msg),
2910 let msg = format!("Use of undeclared type or module `{}`",
2911 names_to_string(&module_path));
2916 resolve_err!(self, span, E0397,
2917 "failed to resolve: {}",
2921 Indeterminate => panic!("indeterminate unexpected"),
2922 Success((resulting_module, resulting_last_private)) => {
2923 containing_module = resulting_module;
2924 last_private = resulting_last_private;
2928 let name = segments.last().unwrap().identifier.name;
2929 let def = match self.resolve_definition_of_name_in_module(containing_module.clone(),
2932 NoNameDefinition => {
2933 // We failed to resolve the name. Report an error.
2936 ChildNameDefinition(def, lp) | ImportNameDefinition(def, lp) => {
2937 (def, last_private.or(lp))
2940 if let Some(DefId{krate: kid, ..}) = containing_module.def_id.get() {
2941 self.used_crates.insert(kid);
2946 /// Invariant: This must be called only during main resolution, not during
2947 /// import resolution.
2948 fn resolve_crate_relative_path(&mut self,
2950 segments: &[ast::PathSegment],
2951 namespace: Namespace)
2952 -> Option<(Def, LastPrivate)> {
2953 let module_path = segments.init().iter()
2954 .map(|ps| ps.identifier.name)
2955 .collect::<Vec<_>>();
2957 let root_module = self.graph_root.get_module();
2959 let containing_module;
2961 match self.resolve_module_path_from_root(root_module,
2966 LastMod(AllPublic)) {
2968 let (span, msg) = match err {
2969 Some((span, msg)) => (span, msg),
2971 let msg = format!("Use of undeclared module `::{}`",
2972 names_to_string(&module_path[..]));
2977 /*self.resolve_error(span, &format!("failed to resolve. {}",
2979 resolve_err!(self, span, E0397,
2980 "failed to resolve: {}",
2986 panic!("indeterminate unexpected");
2989 Success((resulting_module, resulting_last_private)) => {
2990 containing_module = resulting_module;
2991 last_private = resulting_last_private;
2995 let name = segments.last().unwrap().identifier.name;
2996 match self.resolve_definition_of_name_in_module(containing_module,
2999 NoNameDefinition => {
3000 // We failed to resolve the name. Report an error.
3003 ChildNameDefinition(def, lp) | ImportNameDefinition(def, lp) => {
3004 return Some((def, last_private.or(lp)));
3009 fn resolve_identifier_in_local_ribs(&mut self,
3011 namespace: Namespace,
3014 // Check the local set of ribs.
3015 let search_result = match namespace {
3017 let renamed = mtwt::resolve(ident);
3018 self.search_ribs(&self.value_ribs, renamed, span)
3021 let name = ident.name;
3022 self.search_ribs(&self.type_ribs, name, span)
3026 match search_result {
3027 Some(DlDef(def)) => {
3028 debug!("(resolving path in local ribs) resolved `{}` to local: {:?}",
3029 token::get_ident(ident),
3033 Some(DlField) | Some(DlImpl(_)) | None => {
3039 fn resolve_item_by_name_in_lexical_scope(&mut self,
3041 namespace: Namespace)
3042 -> Option<(Def, LastPrivate)> {
3044 let module = self.current_module.clone();
3045 match self.resolve_item_in_lexical_scope(module,
3048 Success((target, _)) => {
3049 match (*target.bindings).def_for_namespace(namespace) {
3051 // This can happen if we were looking for a type and
3052 // found a module instead. Modules don't have defs.
3053 debug!("(resolving item path by identifier in lexical \
3054 scope) failed to resolve {} after success...",
3059 debug!("(resolving item path in lexical scope) \
3060 resolved `{}` to item",
3062 // This lookup is "all public" because it only searched
3063 // for one identifier in the current module (couldn't
3064 // have passed through reexports or anything like that.
3065 return Some((def, LastMod(AllPublic)));
3070 panic!("unexpected indeterminate result");
3073 debug!("(resolving item path by identifier in lexical scope) \
3074 failed to resolve {}", name);
3076 if let Some((span, msg)) = err {
3077 resolve_err!(self, span, E0397,
3078 "failed to resolve: {}",
3087 fn with_no_errors<T, F>(&mut self, f: F) -> T where
3088 F: FnOnce(&mut Resolver) -> T,
3090 self.emit_errors = false;
3092 self.emit_errors = true;
3096 fn resolve_error(&self, span: Span, s: &str) {
3097 if self.emit_errors {
3098 self.session.span_err(span, s);
3102 fn find_fallback_in_self_type(&mut self, name: Name) -> FallbackSuggestion {
3103 fn extract_path_and_node_id(t: &Ty, allow: FallbackChecks)
3104 -> Option<(Path, NodeId, FallbackChecks)> {
3106 TyPath(None, ref path) => Some((path.clone(), t.id, allow)),
3107 TyPtr(ref mut_ty) => extract_path_and_node_id(&*mut_ty.ty, OnlyTraitAndStatics),
3108 TyRptr(_, ref mut_ty) => extract_path_and_node_id(&*mut_ty.ty, allow),
3109 // This doesn't handle the remaining `Ty` variants as they are not
3110 // that commonly the self_type, it might be interesting to provide
3111 // support for those in future.
3116 fn get_module(this: &mut Resolver, span: Span, name_path: &[ast::Name])
3117 -> Option<Rc<Module>> {
3118 let root = this.current_module.clone();
3119 let last_name = name_path.last().unwrap();
3121 if name_path.len() == 1 {
3122 match this.primitive_type_table.primitive_types.get(last_name) {
3125 match this.current_module.children.borrow().get(last_name) {
3126 Some(child) => child.get_module_if_available(),
3132 match this.resolve_module_path(root,
3137 Success((module, _)) => Some(module),
3143 fn is_static_method(this: &Resolver, did: DefId) -> bool {
3144 if did.krate == ast::LOCAL_CRATE {
3145 let sig = match this.ast_map.get(did.node) {
3146 ast_map::NodeTraitItem(trait_item) => match trait_item.node {
3147 ast::MethodTraitItem(ref sig, _) => sig,
3150 ast_map::NodeImplItem(impl_item) => match impl_item.node {
3151 ast::MethodImplItem(ref sig, _) => sig,
3156 sig.explicit_self.node == ast::SelfStatic
3158 csearch::is_static_method(&this.session.cstore, did)
3162 let (path, node_id, allowed) = match self.current_self_type {
3163 Some(ref ty) => match extract_path_and_node_id(ty, Everything) {
3165 None => return NoSuggestion,
3167 None => return NoSuggestion,
3170 if allowed == Everything {
3171 // Look for a field with the same name in the current self_type.
3172 match self.def_map.borrow().get(&node_id).map(|d| d.full_def()) {
3173 Some(DefTy(did, _)) |
3174 Some(DefStruct(did)) |
3175 Some(DefVariant(_, did, _)) => match self.structs.get(&did) {
3178 if fields.iter().any(|&field_name| name == field_name) {
3183 _ => {} // Self type didn't resolve properly
3187 let name_path = path.segments.iter().map(|seg| seg.identifier.name).collect::<Vec<_>>();
3189 // Look for a method in the current self type's impl module.
3190 if let Some(module) = get_module(self, path.span, &name_path) {
3191 if let Some(binding) = module.children.borrow().get(&name) {
3192 if let Some(DefMethod(did, _)) = binding.def_for_namespace(ValueNS) {
3193 if is_static_method(self, did) {
3194 return StaticMethod(path_names_to_string(&path, 0))
3196 if self.current_trait_ref.is_some() {
3198 } else if allowed == Everything {
3205 // Look for a method in the current trait.
3206 if let Some((trait_did, ref trait_ref)) = self.current_trait_ref {
3207 if let Some(&did) = self.trait_item_map.get(&(name, trait_did)) {
3208 if is_static_method(self, did) {
3209 return TraitMethod(path_names_to_string(&trait_ref.path, 0));
3219 fn find_best_match_for_name(&mut self, name: &str) -> Option<String> {
3220 let mut maybes: Vec<token::InternedString> = Vec::new();
3221 let mut values: Vec<usize> = Vec::new();
3223 for rib in self.value_ribs.iter().rev() {
3224 for (&k, _) in &rib.bindings {
3225 maybes.push(token::get_name(k));
3226 values.push(usize::MAX);
3230 let mut smallest = 0;
3231 for (i, other) in maybes.iter().enumerate() {
3232 values[i] = lev_distance(name, &other);
3234 if values[i] <= values[smallest] {
3239 // As a loose rule to avoid obviously incorrect suggestions, clamp the
3240 // maximum edit distance we will accept for a suggestion to one third of
3241 // the typo'd name's length.
3242 let max_distance = std::cmp::max(name.len(), 3) / 3;
3244 if !values.is_empty() &&
3245 values[smallest] <= max_distance &&
3246 name != &maybes[smallest][..] {
3248 Some(maybes[smallest].to_string())
3255 fn resolve_expr(&mut self, expr: &Expr) {
3256 // First, record candidate traits for this expression if it could
3257 // result in the invocation of a method call.
3259 self.record_candidate_traits_for_expr_if_necessary(expr);
3261 // Next, resolve the node.
3263 ExprPath(ref maybe_qself, ref path) => {
3265 match self.resolve_possibly_assoc_item(expr.id,
3266 maybe_qself.as_ref(),
3270 // `<T>::a::b::c` is resolved by typeck alone.
3271 TypecheckRequired => {
3272 let method_name = path.segments.last().unwrap().identifier.name;
3273 let traits = self.get_traits_containing_item(method_name);
3274 self.trait_map.insert(expr.id, traits);
3275 visit::walk_expr(self, expr);
3278 ResolveAttempt(resolution) => resolution,
3281 // This is a local path in the value namespace. Walk through
3282 // scopes looking for it.
3283 if let Some(path_res) = resolution {
3284 // Check if struct variant
3285 if let DefVariant(_, _, true) = path_res.base_def {
3286 let path_name = path_names_to_string(path, 0);
3287 resolve_err!(self, expr.span, E0423,
3288 "`{}` is a struct variant name, but \
3290 uses it like a function name",
3293 let msg = format!("did you mean to write: \
3294 `{} {{ /* fields */ }}`?",
3296 if self.emit_errors {
3297 self.session.fileline_help(expr.span, &msg);
3299 self.session.span_help(expr.span, &msg);
3302 // Write the result into the def map.
3303 debug!("(resolving expr) resolved `{}`",
3304 path_names_to_string(path, 0));
3306 // Partial resolutions will need the set of traits in scope,
3307 // so they can be completed during typeck.
3308 if path_res.depth != 0 {
3309 let method_name = path.segments.last().unwrap().identifier.name;
3310 let traits = self.get_traits_containing_item(method_name);
3311 self.trait_map.insert(expr.id, traits);
3314 self.record_def(expr.id, path_res);
3317 // Be helpful if the name refers to a struct
3318 // (The pattern matching def_tys where the id is in self.structs
3319 // matches on regular structs while excluding tuple- and enum-like
3320 // structs, which wouldn't result in this error.)
3321 let path_name = path_names_to_string(path, 0);
3322 let type_res = self.with_no_errors(|this| {
3323 this.resolve_path(expr.id, path, 0, TypeNS, false)
3325 match type_res.map(|r| r.base_def) {
3326 Some(DefTy(struct_id, _))
3327 if self.structs.contains_key(&struct_id) => {
3328 resolve_err!(self, expr.span, E0423,
3329 "{}` is a structure name, but \
3331 uses it like a function name",
3334 let msg = format!("did you mean to write: \
3335 `{} {{ /* fields */ }}`?",
3337 if self.emit_errors {
3338 self.session.fileline_help(expr.span, &msg);
3340 self.session.span_help(expr.span, &msg);
3344 // Keep reporting some errors even if they're ignored above.
3345 self.resolve_path(expr.id, path, 0, ValueNS, true);
3347 let mut method_scope = false;
3348 self.value_ribs.iter().rev().all(|rib| {
3349 method_scope = match rib.kind {
3350 MethodRibKind => true,
3351 ItemRibKind | ConstantItemRibKind => false,
3352 _ => return true, // Keep advancing
3354 false // Stop advancing
3358 &token::get_name(special_names::self_)[..] == path_name {
3359 resolve_err!(self, expr.span, E0424,
3361 "`self` is not available \
3362 in a static method. Maybe a \
3363 `self` argument is missing?");
3365 let last_name = path.segments.last().unwrap().identifier.name;
3366 let mut msg = match self.find_fallback_in_self_type(last_name) {
3368 // limit search to 5 to reduce the number
3369 // of stupid suggestions
3370 self.find_best_match_for_name(&path_name)
3371 .map_or("".to_string(),
3372 |x| format!("`{}`", x))
3374 Field => format!("`self.{}`", path_name),
3377 format!("to call `self.{}`", path_name),
3378 TraitMethod(path_str) |
3379 StaticMethod(path_str) =>
3380 format!("to call `{}::{}`", path_str, path_name)
3383 if !msg.is_empty() {
3384 msg = format!(". Did you mean {}?", msg)
3387 resolve_err!(self, expr.span, E0425,
3388 "unresolved name `{}`{}",
3396 visit::walk_expr(self, expr);
3399 ExprStruct(ref path, _, _) => {
3400 // Resolve the path to the structure it goes to. We don't
3401 // check to ensure that the path is actually a structure; that
3402 // is checked later during typeck.
3403 match self.resolve_path(expr.id, path, 0, TypeNS, false) {
3404 Some(definition) => self.record_def(expr.id, definition),
3406 debug!("(resolving expression) didn't find struct def",);
3407 resolve_err!(self, path.span, E0422,
3408 "`{}` does not name a structure",
3409 path_names_to_string(path, 0));
3413 visit::walk_expr(self, expr);
3416 ExprLoop(_, Some(label)) | ExprWhile(_, _, Some(label)) => {
3417 self.with_label_rib(|this| {
3418 let def_like = DlDef(DefLabel(expr.id));
3421 let rib = this.label_ribs.last_mut().unwrap();
3422 let renamed = mtwt::resolve(label);
3423 rib.bindings.insert(renamed, def_like);
3426 visit::walk_expr(this, expr);
3430 ExprBreak(Some(label)) | ExprAgain(Some(label)) => {
3431 let renamed = mtwt::resolve(label);
3432 match self.search_label(renamed) {
3434 resolve_err!(self, expr.span, E0426,
3435 "use of undeclared label `{}`",
3436 token::get_ident(label))
3438 Some(DlDef(def @ DefLabel(_))) => {
3439 // Since this def is a label, it is never read.
3440 self.record_def(expr.id, PathResolution {
3442 last_private: LastMod(AllPublic),
3447 self.session.span_bug(expr.span,
3448 "label wasn't mapped to a \
3455 visit::walk_expr(self, expr);
3460 fn record_candidate_traits_for_expr_if_necessary(&mut self, expr: &Expr) {
3462 ExprField(_, ident) => {
3463 // FIXME(#6890): Even though you can't treat a method like a
3464 // field, we need to add any trait methods we find that match
3465 // the field name so that we can do some nice error reporting
3466 // later on in typeck.
3467 let traits = self.get_traits_containing_item(ident.node.name);
3468 self.trait_map.insert(expr.id, traits);
3470 ExprMethodCall(ident, _, _) => {
3471 debug!("(recording candidate traits for expr) recording \
3474 let traits = self.get_traits_containing_item(ident.node.name);
3475 self.trait_map.insert(expr.id, traits);
3483 fn get_traits_containing_item(&mut self, name: Name) -> Vec<DefId> {
3484 debug!("(getting traits containing item) looking for '{}'",
3487 fn add_trait_info(found_traits: &mut Vec<DefId>,
3488 trait_def_id: DefId,
3490 debug!("(adding trait info) found trait {}:{} for method '{}'",
3494 found_traits.push(trait_def_id);
3497 let mut found_traits = Vec::new();
3498 let mut search_module = self.current_module.clone();
3500 // Look for the current trait.
3501 match self.current_trait_ref {
3502 Some((trait_def_id, _)) => {
3503 if self.trait_item_map.contains_key(&(name, trait_def_id)) {
3504 add_trait_info(&mut found_traits, trait_def_id, name);
3507 None => {} // Nothing to do.
3510 // Look for trait children.
3511 build_reduced_graph::populate_module_if_necessary(self, &search_module);
3514 for (_, child_names) in search_module.children.borrow().iter() {
3515 let def = match child_names.def_for_namespace(TypeNS) {
3519 let trait_def_id = match def {
3520 DefTrait(trait_def_id) => trait_def_id,
3523 if self.trait_item_map.contains_key(&(name, trait_def_id)) {
3524 add_trait_info(&mut found_traits, trait_def_id, name);
3529 // Look for imports.
3530 for (_, import) in search_module.import_resolutions.borrow().iter() {
3531 let target = match import.target_for_namespace(TypeNS) {
3533 Some(target) => target,
3535 let did = match target.bindings.def_for_namespace(TypeNS) {
3536 Some(DefTrait(trait_def_id)) => trait_def_id,
3537 Some(..) | None => continue,
3539 if self.trait_item_map.contains_key(&(name, did)) {
3540 add_trait_info(&mut found_traits, did, name);
3541 let id = import.type_id;
3542 self.used_imports.insert((id, TypeNS));
3543 let trait_name = self.get_trait_name(did);
3544 self.record_import_use(id, trait_name);
3545 if let Some(DefId{krate: kid, ..}) = target.target_module.def_id.get() {
3546 self.used_crates.insert(kid);
3551 match search_module.parent_link.clone() {
3552 NoParentLink | ModuleParentLink(..) => break,
3553 BlockParentLink(parent_module, _) => {
3554 search_module = parent_module.upgrade().unwrap();
3562 fn record_def(&mut self, node_id: NodeId, resolution: PathResolution) {
3563 debug!("(recording def) recording {:?} for {}", resolution, node_id);
3564 assert!(match resolution.last_private {LastImport{..} => false, _ => true},
3565 "Import should only be used for `use` directives");
3567 if let Some(prev_res) = self.def_map.borrow_mut().insert(node_id, resolution) {
3568 let span = self.ast_map.opt_span(node_id).unwrap_or(codemap::DUMMY_SP);
3569 self.session.span_bug(span, &format!("path resolved multiple times \
3570 ({:?} before, {:?} now)",
3571 prev_res, resolution));
3575 fn enforce_default_binding_mode(&mut self,
3577 pat_binding_mode: BindingMode,
3579 match pat_binding_mode {
3580 BindByValue(_) => {}
3582 resolve_err!(self, pat.span, E0427,
3583 "cannot use `ref` binding mode with {}",
3592 // Diagnostics are not particularly efficient, because they're rarely
3596 #[allow(dead_code)] // useful for debugging
3597 fn dump_module(&mut self, module_: Rc<Module>) {
3598 debug!("Dump of module `{}`:", module_to_string(&*module_));
3600 debug!("Children:");
3601 build_reduced_graph::populate_module_if_necessary(self, &module_);
3602 for (&name, _) in module_.children.borrow().iter() {
3603 debug!("* {}", name);
3606 debug!("Import resolutions:");
3607 let import_resolutions = module_.import_resolutions.borrow();
3608 for (&name, import_resolution) in import_resolutions.iter() {
3610 match import_resolution.target_for_namespace(ValueNS) {
3611 None => { value_repr = "".to_string(); }
3613 value_repr = " value:?".to_string();
3619 match import_resolution.target_for_namespace(TypeNS) {
3620 None => { type_repr = "".to_string(); }
3622 type_repr = " type:?".to_string();
3627 debug!("* {}:{}{}", name, value_repr, type_repr);
3633 fn names_to_string(names: &[Name]) -> String {
3634 let mut first = true;
3635 let mut result = String::new();
3640 result.push_str("::")
3642 result.push_str(&token::get_name(*name));
3647 fn path_names_to_string(path: &Path, depth: usize) -> String {
3648 let names: Vec<ast::Name> = path.segments[..path.segments.len()-depth]
3650 .map(|seg| seg.identifier.name)
3652 names_to_string(&names[..])
3655 /// A somewhat inefficient routine to obtain the name of a module.
3656 fn module_to_string(module: &Module) -> String {
3657 let mut names = Vec::new();
3659 fn collect_mod(names: &mut Vec<ast::Name>, module: &Module) {
3660 match module.parent_link {
3662 ModuleParentLink(ref module, name) => {
3664 collect_mod(names, &*module.upgrade().unwrap());
3666 BlockParentLink(ref module, _) => {
3667 // danger, shouldn't be ident?
3668 names.push(special_idents::opaque.name);
3669 collect_mod(names, &*module.upgrade().unwrap());
3673 collect_mod(&mut names, module);
3675 if names.is_empty() {
3676 return "???".to_string();
3678 names_to_string(&names.into_iter().rev().collect::<Vec<ast::Name>>())
3682 pub struct CrateMap {
3683 pub def_map: DefMap,
3684 pub freevars: RefCell<FreevarMap>,
3685 pub export_map: ExportMap,
3686 pub trait_map: TraitMap,
3687 pub external_exports: ExternalExports,
3688 pub glob_map: Option<GlobMap>
3691 #[derive(PartialEq,Copy, Clone)]
3692 pub enum MakeGlobMap {
3697 /// Entry point to crate resolution.
3698 pub fn resolve_crate<'a, 'tcx>(session: &'a Session,
3699 ast_map: &'a ast_map::Map<'tcx>,
3700 make_glob_map: MakeGlobMap)
3702 let krate = ast_map.krate();
3703 let mut resolver = Resolver::new(session, ast_map, krate.span, make_glob_map);
3705 build_reduced_graph::build_reduced_graph(&mut resolver, krate);
3706 session.abort_if_errors();
3708 resolve_imports::resolve_imports(&mut resolver);
3709 session.abort_if_errors();
3711 record_exports::record(&mut resolver);
3712 session.abort_if_errors();
3714 resolver.resolve_crate(krate);
3715 session.abort_if_errors();
3717 check_unused::check_crate(&mut resolver, krate);
3720 def_map: resolver.def_map,
3721 freevars: resolver.freevars,
3722 export_map: resolver.export_map,
3723 trait_map: resolver.trait_map,
3724 external_exports: resolver.external_exports,
3725 glob_map: if resolver.make_glob_map {
3726 Some(resolver.glob_map)
3733 __build_diagnostic_array! { librustc_resolve, DIAGNOSTICS }