1 // Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
11 #[allow(non_camel_case_types)];
13 use driver::session::Session;
14 use metadata::csearch;
15 use metadata::decoder::{DefLike, DlDef, DlField, DlImpl};
16 use middle::lang_items::LanguageItems;
17 use middle::lint::{UnnecessaryQualification, UnusedImports};
18 use middle::pat_util::pat_bindings;
19 use util::nodemap::{NodeMap, DefIdSet};
23 use syntax::ast_util::{def_id_of_def, local_def};
24 use syntax::ast_util::{path_to_ident, walk_pat, trait_method_to_ty_method};
25 use syntax::ext::mtwt;
26 use syntax::parse::token::special_idents;
27 use syntax::parse::token;
28 use syntax::print::pprust::path_to_str;
29 use syntax::codemap::{Span, DUMMY_SP, Pos};
30 use syntax::opt_vec::OptVec;
32 use syntax::visit::Visitor;
34 use std::cell::{Cell, RefCell};
36 use std::mem::replace;
37 use collections::{HashMap, HashSet};
40 pub type DefMap = @RefCell<NodeMap<Def>>;
44 binding_mode: BindingMode,
47 // Map from the name in a pattern to its binding mode.
48 type BindingMap = HashMap<Name,binding_info>;
50 // Trait method resolution
51 pub type TraitMap = NodeMap<Vec<DefId> >;
53 // This is the replacement export map. It maps a module to all of the exports
55 pub type ExportMap2 = @RefCell<NodeMap<Vec<Export2> >>;
58 name: ~str, // The name of the target.
59 def_id: DefId, // The definition of the target.
62 // This set contains all exported definitions from external crates. The set does
63 // not contain any entries from local crates.
64 pub type ExternalExports = DefIdSet;
67 pub type LastPrivateMap = NodeMap<LastPrivate>;
69 pub enum LastPrivate {
71 // `use` directives (imports) can refer to two separate definitions in the
72 // type and value namespaces. We record here the last private node for each
73 // and whether the import is in fact used for each.
74 // If the Option<PrivateDep> fields are None, it means there is no defintion
76 LastImport{value_priv: Option<PrivateDep>,
77 value_used: ImportUse,
78 type_priv: Option<PrivateDep>,
79 type_used: ImportUse},
87 // How an import is used.
90 Unused, // The import is not used.
91 Used, // The import is used.
95 fn or(self, other: LastPrivate) -> LastPrivate {
97 (me, LastMod(AllPublic)) => me,
104 enum PatternBindingMode {
106 LocalIrrefutableMode,
107 ArgumentIrrefutableMode,
110 #[deriving(Eq, Hash)]
117 enum NamespaceError {
124 /// A NamespaceResult represents the result of resolving an import in
125 /// a particular namespace. The result is either definitely-resolved,
126 /// definitely- unresolved, or unknown.
127 enum NamespaceResult {
128 /// Means that resolve hasn't gathered enough information yet to determine
129 /// whether the name is bound in this namespace. (That is, it hasn't
130 /// resolved all `use` directives yet.)
132 /// Means that resolve has determined that the name is definitely
133 /// not bound in the namespace.
135 /// Means that resolve has determined that the name is bound in the Module
136 /// argument, and specified by the NameBindings argument.
137 BoundResult(@Module, @NameBindings)
140 impl NamespaceResult {
141 fn is_unknown(&self) -> bool {
143 UnknownResult => true,
149 enum NameDefinition {
150 NoNameDefinition, //< The name was unbound.
151 ChildNameDefinition(Def, LastPrivate), //< The name identifies an immediate child.
152 ImportNameDefinition(Def, LastPrivate) //< The name identifies an import.
155 impl Visitor<()> for Resolver {
156 fn visit_item(&mut self, item: &Item, _: ()) {
157 self.resolve_item(item);
159 fn visit_arm(&mut self, arm: &Arm, _: ()) {
160 self.resolve_arm(arm);
162 fn visit_block(&mut self, block: &Block, _: ()) {
163 self.resolve_block(block);
165 fn visit_expr(&mut self, expr: &Expr, _: ()) {
166 self.resolve_expr(expr);
168 fn visit_local(&mut self, local: &Local, _: ()) {
169 self.resolve_local(local);
171 fn visit_ty(&mut self, ty: &Ty, _: ()) {
172 self.resolve_type(ty);
176 /// Contains data for specific types of import directives.
177 enum ImportDirectiveSubclass {
178 SingleImport(Ident /* target */, Ident /* source */),
182 /// The context that we thread through while building the reduced graph.
184 enum ReducedGraphParent {
185 ModuleReducedGraphParent(@Module)
188 impl ReducedGraphParent {
189 fn module(&self) -> @Module {
191 ModuleReducedGraphParent(m) => {
198 enum ResolveResult<T> {
199 Failed, // Failed to resolve the name.
200 Indeterminate, // Couldn't determine due to unresolved globs.
201 Success(T) // Successfully resolved the import.
204 impl<T> ResolveResult<T> {
205 fn indeterminate(&self) -> bool {
206 match *self { Indeterminate => true, _ => false }
210 enum TypeParameters<'a> {
211 NoTypeParameters, //< No type parameters.
212 HasTypeParameters(&'a Generics, //< Type parameters.
213 NodeId, //< ID of the enclosing item
215 // The index to start numbering the type parameters at.
216 // This is zero if this is the outermost set of type
217 // parameters, or equal to the number of outer type
218 // parameters. For example, if we have:
221 // fn method<U>() { ... }
224 // The index at the method site will be 1, because the
225 // outer T had index 0.
228 // The kind of the rib used for type parameters.
232 // The rib kind controls the translation of argument or local definitions
233 // (`def_arg` or `def_local`) to upvars (`def_upvar`).
236 // No translation needs to be applied.
239 // We passed through a function scope at the given node ID. Translate
240 // upvars as appropriate.
241 FunctionRibKind(NodeId /* func id */, NodeId /* body id */),
243 // We passed through an impl or trait and are now in one of its
244 // methods. Allow references to ty params that impl or trait
245 // binds. Disallow any other upvars (including other ty params that are
247 // parent; method itself
248 MethodRibKind(NodeId, MethodSort),
250 // We passed through a function *item* scope. Disallow upvars.
251 OpaqueFunctionRibKind,
253 // We're in a constant item. Can't refer to dynamic stuff.
257 // Methods can be required or provided. Required methods only occur in traits.
263 enum UseLexicalScopeFlag {
268 enum SearchThroughModulesFlag {
269 DontSearchThroughModules,
273 enum ModulePrefixResult {
275 PrefixFound(@Module, uint)
279 enum NameSearchType {
280 /// We're doing a name search in order to resolve a `use` directive.
283 /// We're doing a name search in order to resolve a path type, a path
284 /// expression, or a path pattern.
288 enum BareIdentifierPatternResolution {
289 FoundStructOrEnumVariant(Def, LastPrivate),
290 FoundConst(Def, LastPrivate),
291 BareIdentifierPatternUnresolved
294 // Specifies how duplicates should be handled when adding a child item if
295 // another item exists with the same name in some namespace.
297 enum DuplicateCheckingMode {
298 ForbidDuplicateModules,
299 ForbidDuplicateTypes,
300 ForbidDuplicateValues,
301 ForbidDuplicateTypesAndValues,
307 bindings: RefCell<HashMap<Name, DefLike>>,
312 fn new(kind: RibKind) -> Rib {
314 bindings: RefCell::new(HashMap::new()),
320 /// One import directive.
321 struct ImportDirective {
322 module_path: Vec<Ident> ,
323 subclass: @ImportDirectiveSubclass,
326 is_public: bool, // see note in ImportResolution about how to use this
329 impl ImportDirective {
330 fn new(module_path: Vec<Ident> ,
331 subclass: @ImportDirectiveSubclass,
337 module_path: module_path,
341 is_public: is_public,
346 /// The item that an import resolves to.
349 target_module: @Module,
350 bindings: @NameBindings,
354 fn new(target_module: @Module, bindings: @NameBindings) -> Target {
356 target_module: target_module,
362 /// An ImportResolution represents a particular `use` directive.
363 struct ImportResolution {
364 /// Whether this resolution came from a `use` or a `pub use`. Note that this
365 /// should *not* be used whenever resolution is being performed, this is
366 /// only looked at for glob imports statements currently. Privacy testing
367 /// occurs during a later phase of compilation.
368 is_public: Cell<bool>,
370 // The number of outstanding references to this name. When this reaches
371 // zero, outside modules can count on the targets being correct. Before
372 // then, all bets are off; future imports could override this name.
373 outstanding_references: Cell<uint>,
375 /// The value that this `use` directive names, if there is one.
376 value_target: RefCell<Option<Target>>,
377 /// The source node of the `use` directive leading to the value target
379 value_id: Cell<NodeId>,
381 /// The type that this `use` directive names, if there is one.
382 type_target: RefCell<Option<Target>>,
383 /// The source node of the `use` directive leading to the type target
385 type_id: Cell<NodeId>,
388 impl ImportResolution {
389 fn new(id: NodeId, is_public: bool) -> ImportResolution {
391 type_id: Cell::new(id),
392 value_id: Cell::new(id),
393 outstanding_references: Cell::new(0),
394 value_target: RefCell::new(None),
395 type_target: RefCell::new(None),
396 is_public: Cell::new(is_public),
400 fn target_for_namespace(&self, namespace: Namespace)
403 TypeNS => return self.type_target.get(),
404 ValueNS => return self.value_target.get(),
408 fn id(&self, namespace: Namespace) -> NodeId {
410 TypeNS => self.type_id.get(),
411 ValueNS => self.value_id.get(),
416 /// The link from a module up to its nearest parent node.
419 ModuleParentLink(@Module, Ident),
420 BlockParentLink(@Module, NodeId)
423 /// The type of module this is.
433 /// One node in the tree of modules.
435 parent_link: ParentLink,
436 def_id: Cell<Option<DefId>>,
437 kind: Cell<ModuleKind>,
440 children: RefCell<HashMap<Name, @NameBindings>>,
441 imports: RefCell<Vec<@ImportDirective> >,
443 // The external module children of this node that were declared with
445 external_module_children: RefCell<HashMap<Name, @Module>>,
447 // The anonymous children of this node. Anonymous children are pseudo-
448 // modules that are implicitly created around items contained within
451 // For example, if we have this:
459 // There will be an anonymous module created around `g` with the ID of the
460 // entry block for `f`.
461 anonymous_children: RefCell<NodeMap<@Module>>,
463 // The status of resolving each import in this module.
464 import_resolutions: RefCell<HashMap<Name, @ImportResolution>>,
466 // The number of unresolved globs that this module exports.
467 glob_count: Cell<uint>,
469 // The index of the import we're resolving.
470 resolved_import_count: Cell<uint>,
472 // Whether this module is populated. If not populated, any attempt to
473 // access the children must be preceded with a
474 // `populate_module_if_necessary` call.
475 populated: Cell<bool>,
479 fn new(parent_link: ParentLink,
480 def_id: Option<DefId>,
486 parent_link: parent_link,
487 def_id: Cell::new(def_id),
488 kind: Cell::new(kind),
489 is_public: is_public,
490 children: RefCell::new(HashMap::new()),
491 imports: RefCell::new(Vec::new()),
492 external_module_children: RefCell::new(HashMap::new()),
493 anonymous_children: RefCell::new(NodeMap::new()),
494 import_resolutions: RefCell::new(HashMap::new()),
495 glob_count: Cell::new(0),
496 resolved_import_count: Cell::new(0),
497 populated: Cell::new(!external),
501 fn all_imports_resolved(&self) -> bool {
502 let mut imports = self.imports.borrow_mut();
503 return imports.get().len() == self.resolved_import_count.get();
507 // Records a possibly-private type definition.
510 is_public: bool, // see note in ImportResolution about how to use this
511 module_def: Option<@Module>,
512 type_def: Option<Def>,
513 type_span: Option<Span>
516 // Records a possibly-private value definition.
519 is_public: bool, // see note in ImportResolution about how to use this
521 value_span: Option<Span>,
524 // Records the definitions (at most one for each namespace) that a name is
526 struct NameBindings {
527 type_def: RefCell<Option<TypeNsDef>>, //< Meaning in type namespace.
528 value_def: RefCell<Option<ValueNsDef>>, //< Meaning in value namespace.
531 /// Ways in which a trait can be referenced
532 enum TraitReferenceType {
533 TraitImplementation, // impl SomeTrait for T { ... }
534 TraitDerivation, // trait T : SomeTrait { ... }
535 TraitBoundingTypeParameter, // fn f<T:SomeTrait>() { ... }
539 /// Creates a new module in this set of name bindings.
540 fn define_module(&self,
541 parent_link: ParentLink,
542 def_id: Option<DefId>,
547 // Merges the module with the existing type def or creates a new one.
548 let module_ = @Module::new(parent_link, def_id, kind, external,
550 match self.type_def.get() {
552 self.type_def.set(Some(TypeNsDef {
553 is_public: is_public,
554 module_def: Some(module_),
560 self.type_def.set(Some(TypeNsDef {
561 is_public: is_public,
562 module_def: Some(module_),
564 type_def: type_def.type_def
570 /// Sets the kind of the module, creating a new one if necessary.
571 fn set_module_kind(&self,
572 parent_link: ParentLink,
573 def_id: Option<DefId>,
578 match self.type_def.get() {
580 let module = @Module::new(parent_link, def_id, kind,
581 external, is_public);
582 self.type_def.set(Some(TypeNsDef {
583 is_public: is_public,
584 module_def: Some(module),
590 match type_def.module_def {
592 let module = @Module::new(parent_link,
597 self.type_def.set(Some(TypeNsDef {
598 is_public: is_public,
599 module_def: Some(module),
600 type_def: type_def.type_def,
604 Some(module_def) => module_def.kind.set(kind),
610 /// Records a type definition.
611 fn define_type(&self, def: Def, sp: Span, is_public: bool) {
612 // Merges the type with the existing type def or creates a new one.
613 match self.type_def.get() {
615 self.type_def.set(Some(TypeNsDef {
619 is_public: is_public,
623 self.type_def.set(Some(TypeNsDef {
626 module_def: type_def.module_def,
627 is_public: is_public,
633 /// Records a value definition.
634 fn define_value(&self, def: Def, sp: Span, is_public: bool) {
635 self.value_def.set(Some(ValueNsDef {
637 value_span: Some(sp),
638 is_public: is_public,
642 /// Returns the module node if applicable.
643 fn get_module_if_available(&self) -> Option<@Module> {
644 let type_def = self.type_def.borrow();
645 match *type_def.get() {
646 Some(ref type_def) => (*type_def).module_def,
652 * Returns the module node. Fails if this node does not have a module
655 fn get_module(&self) -> @Module {
656 match self.get_module_if_available() {
658 fail!("get_module called on a node with no module \
661 Some(module_def) => module_def
665 fn defined_in_namespace(&self, namespace: Namespace) -> bool {
667 TypeNS => return self.type_def.get().is_some(),
668 ValueNS => return self.value_def.get().is_some()
672 fn defined_in_public_namespace(&self, namespace: Namespace) -> bool {
674 TypeNS => match self.type_def.get() {
675 Some(def) => def.is_public, None => false
677 ValueNS => match self.value_def.get() {
678 Some(def) => def.is_public, None => false
683 fn def_for_namespace(&self, namespace: Namespace) -> Option<Def> {
686 match self.type_def.get() {
689 match type_def.type_def {
690 Some(type_def) => Some(type_def),
692 match type_def.module_def {
694 match module.def_id.get() {
695 Some(did) => Some(DefMod(did)),
707 match self.value_def.get() {
709 Some(value_def) => Some(value_def.def)
715 fn span_for_namespace(&self, namespace: Namespace) -> Option<Span> {
716 if self.defined_in_namespace(namespace) {
719 match self.type_def.get() {
721 Some(type_def) => type_def.type_span
725 match self.value_def.get() {
727 Some(value_def) => value_def.value_span
737 fn NameBindings() -> NameBindings {
739 type_def: RefCell::new(None),
740 value_def: RefCell::new(None),
744 /// Interns the names of the primitive types.
745 struct PrimitiveTypeTable {
746 primitive_types: HashMap<Name, PrimTy>,
749 impl PrimitiveTypeTable {
750 fn intern(&mut self, string: &str, primitive_type: PrimTy) {
751 self.primitive_types.insert(token::intern(string), primitive_type);
755 fn PrimitiveTypeTable() -> PrimitiveTypeTable {
756 let mut table = PrimitiveTypeTable {
757 primitive_types: HashMap::new()
760 table.intern("bool", TyBool);
761 table.intern("char", TyChar);
762 table.intern("f32", TyFloat(TyF32));
763 table.intern("f64", TyFloat(TyF64));
764 table.intern("int", TyInt(TyI));
765 table.intern("i8", TyInt(TyI8));
766 table.intern("i16", TyInt(TyI16));
767 table.intern("i32", TyInt(TyI32));
768 table.intern("i64", TyInt(TyI64));
769 table.intern("str", TyStr);
770 table.intern("uint", TyUint(TyU));
771 table.intern("u8", TyUint(TyU8));
772 table.intern("u16", TyUint(TyU16));
773 table.intern("u32", TyUint(TyU32));
774 table.intern("u64", TyUint(TyU64));
780 fn namespace_error_to_str(ns: NamespaceError) -> &'static str {
783 ModuleError => "module",
785 ValueError => "value",
789 fn Resolver(session: Session,
790 lang_items: @LanguageItems,
791 crate_span: Span) -> Resolver {
792 let graph_root = @NameBindings();
794 graph_root.define_module(NoParentLink,
795 Some(DefId { krate: 0, node: 0 }),
801 let current_module = graph_root.get_module();
803 let this = Resolver {
805 lang_items: lang_items,
807 // The outermost module has def ID 0; this is not reflected in the
810 graph_root: graph_root,
812 method_map: @RefCell::new(HashMap::new()),
813 structs: HashSet::new(),
815 unresolved_imports: 0,
817 current_module: current_module,
818 value_ribs: @RefCell::new(Vec::new()),
819 type_ribs: @RefCell::new(Vec::new()),
820 label_ribs: @RefCell::new(Vec::new()),
822 current_trait_refs: None,
824 self_ident: special_idents::self_,
825 type_self_ident: special_idents::type_self,
827 primitive_type_table: @PrimitiveTypeTable(),
829 namespaces: Vec<TypeNS, ValueNS > ,
831 def_map: @RefCell::new(NodeMap::new()),
832 export_map2: @RefCell::new(NodeMap::new()),
833 trait_map: NodeMap::new(),
834 used_imports: HashSet::new(),
835 external_exports: DefIdSet::new(),
836 last_private: NodeMap::new(),
844 /// The main resolver class.
847 lang_items: @LanguageItems,
849 graph_root: @NameBindings,
851 method_map: @RefCell<HashMap<Name, HashSet<DefId>>>,
852 structs: HashSet<DefId>,
854 // The number of imports that are currently unresolved.
855 unresolved_imports: uint,
857 // The module that represents the current item scope.
858 current_module: @Module,
860 // The current set of local scopes, for values.
861 // FIXME #4948: Reuse ribs to avoid allocation.
862 value_ribs: @RefCell<Vec<@Rib> >,
864 // The current set of local scopes, for types.
865 type_ribs: @RefCell<Vec<@Rib> >,
867 // The current set of local scopes, for labels.
868 label_ribs: @RefCell<Vec<@Rib> >,
870 // The trait that the current context can refer to.
871 current_trait_refs: Option<Vec<DefId> >,
873 // The ident for the keyword "self".
875 // The ident for the non-keyword "Self".
876 type_self_ident: Ident,
878 // The idents for the primitive types.
879 primitive_type_table: @PrimitiveTypeTable,
881 // The four namespaces.
882 namespaces: Vec<Namespace> ,
885 export_map2: ExportMap2,
887 external_exports: ExternalExports,
888 last_private: LastPrivateMap,
890 // Whether or not to print error messages. Can be set to true
891 // when getting additional info for error message suggestions,
892 // so as to avoid printing duplicate errors
895 used_imports: HashSet<(NodeId, Namespace)>,
898 struct BuildReducedGraphVisitor<'a> {
899 resolver: &'a mut Resolver,
902 impl<'a> Visitor<ReducedGraphParent> for BuildReducedGraphVisitor<'a> {
904 fn visit_item(&mut self, item: &Item, context: ReducedGraphParent) {
905 let p = self.resolver.build_reduced_graph_for_item(item, context);
906 visit::walk_item(self, item, p);
909 fn visit_foreign_item(&mut self, foreign_item: &ForeignItem,
910 context: ReducedGraphParent) {
911 self.resolver.build_reduced_graph_for_foreign_item(foreign_item,
914 let mut v = BuildReducedGraphVisitor{ resolver: r };
915 visit::walk_foreign_item(&mut v, foreign_item, c);
919 fn visit_view_item(&mut self, view_item: &ViewItem, context: ReducedGraphParent) {
920 self.resolver.build_reduced_graph_for_view_item(view_item, context);
923 fn visit_block(&mut self, block: &Block, context: ReducedGraphParent) {
924 let np = self.resolver.build_reduced_graph_for_block(block, context);
925 visit::walk_block(self, block, np);
930 struct UnusedImportCheckVisitor<'a> { resolver: &'a mut Resolver }
932 impl<'a> Visitor<()> for UnusedImportCheckVisitor<'a> {
933 fn visit_view_item(&mut self, vi: &ViewItem, _: ()) {
934 self.resolver.check_for_item_unused_imports(vi);
935 visit::walk_view_item(self, vi, ());
940 /// The main name resolution procedure.
941 fn resolve(&mut self, krate: &ast::Crate) {
942 self.build_reduced_graph(krate);
943 self.session.abort_if_errors();
945 self.resolve_imports();
946 self.session.abort_if_errors();
948 self.record_exports();
949 self.session.abort_if_errors();
951 self.resolve_crate(krate);
952 self.session.abort_if_errors();
954 self.check_for_unused_imports(krate);
958 // Reduced graph building
960 // Here we build the "reduced graph": the graph of the module tree without
961 // any imports resolved.
964 /// Constructs the reduced graph for the entire crate.
965 fn build_reduced_graph(&mut self, krate: &ast::Crate) {
967 ModuleReducedGraphParent(self.graph_root.get_module());
969 let mut visitor = BuildReducedGraphVisitor { resolver: self, };
970 visit::walk_crate(&mut visitor, krate, initial_parent);
973 /// Returns the current module tracked by the reduced graph parent.
974 fn get_module_from_parent(&mut self,
975 reduced_graph_parent: ReducedGraphParent)
977 match reduced_graph_parent {
978 ModuleReducedGraphParent(module_) => {
985 * Adds a new child item to the module definition of the parent node and
986 * returns its corresponding name bindings as well as the current parent.
987 * Or, if we're inside a block, creates (or reuses) an anonymous module
988 * corresponding to the innermost block ID and returns the name bindings
989 * as well as the newly-created parent.
991 * If this node does not have a module definition and we are not inside
994 fn add_child(&mut self,
996 reduced_graph_parent: ReducedGraphParent,
997 duplicate_checking_mode: DuplicateCheckingMode,
998 // For printing errors
1000 -> (@NameBindings, ReducedGraphParent) {
1001 // If this is the immediate descendant of a module, then we add the
1002 // child name directly. Otherwise, we create or reuse an anonymous
1003 // module and add the child to that.
1006 match reduced_graph_parent {
1007 ModuleReducedGraphParent(parent_module) => {
1008 module_ = parent_module;
1012 // Add or reuse the child.
1013 let new_parent = ModuleReducedGraphParent(module_);
1015 let children = module_.children.borrow();
1016 children.get().find_copy(&name.name)
1020 let child = @NameBindings();
1021 let mut children = module_.children.borrow_mut();
1022 children.get().insert(name.name, child);
1023 return (child, new_parent);
1026 // Enforce the duplicate checking mode:
1028 // * If we're requesting duplicate module checking, check that
1029 // there isn't a module in the module with the same name.
1031 // * If we're requesting duplicate type checking, check that
1032 // there isn't a type in the module with the same name.
1034 // * If we're requesting duplicate value checking, check that
1035 // there isn't a value in the module with the same name.
1037 // * If we're requesting duplicate type checking and duplicate
1038 // value checking, check that there isn't a duplicate type
1039 // and a duplicate value with the same name.
1041 // * If no duplicate checking was requested at all, do
1044 let mut duplicate_type = NoError;
1045 let ns = match duplicate_checking_mode {
1046 ForbidDuplicateModules => {
1047 if child.get_module_if_available().is_some() {
1048 duplicate_type = ModuleError;
1052 ForbidDuplicateTypes => {
1053 match child.def_for_namespace(TypeNS) {
1054 Some(DefMod(_)) | None => {}
1055 Some(_) => duplicate_type = TypeError
1059 ForbidDuplicateValues => {
1060 if child.defined_in_namespace(ValueNS) {
1061 duplicate_type = ValueError;
1065 ForbidDuplicateTypesAndValues => {
1067 match child.def_for_namespace(TypeNS) {
1068 Some(DefMod(_)) | None => {}
1071 duplicate_type = TypeError;
1074 if child.defined_in_namespace(ValueNS) {
1075 duplicate_type = ValueError;
1080 OverwriteDuplicates => None
1082 if duplicate_type != NoError {
1083 // Return an error here by looking up the namespace that
1084 // had the duplicate.
1085 let ns = ns.unwrap();
1086 self.resolve_error(sp,
1087 format!("duplicate definition of {} `{}`",
1088 namespace_error_to_str(duplicate_type),
1089 token::get_ident(name)));
1091 let r = child.span_for_namespace(ns);
1092 for sp in r.iter() {
1093 self.session.span_note(*sp,
1094 format!("first definition of {} `{}` here",
1095 namespace_error_to_str(duplicate_type),
1096 token::get_ident(name)));
1100 return (child, new_parent);
1105 fn block_needs_anonymous_module(&mut self, block: &Block) -> bool {
1106 // If the block has view items, we need an anonymous module.
1107 if block.view_items.len() > 0 {
1111 // Check each statement.
1112 for statement in block.stmts.iter() {
1113 match statement.node {
1114 StmtDecl(declaration, _) => {
1115 match declaration.node {
1130 // If we found neither view items nor items, we don't need to create
1131 // an anonymous module.
1136 fn get_parent_link(&mut self, parent: ReducedGraphParent, name: Ident)
1139 ModuleReducedGraphParent(module_) => {
1140 return ModuleParentLink(module_, name);
1145 /// Constructs the reduced graph for one item.
1146 fn build_reduced_graph_for_item(&mut self,
1148 parent: ReducedGraphParent)
1149 -> ReducedGraphParent
1151 let ident = item.ident;
1153 let is_public = item.vis == ast::Public;
1157 let (name_bindings, new_parent) =
1158 self.add_child(ident, parent, ForbidDuplicateModules, sp);
1160 let parent_link = self.get_parent_link(new_parent, ident);
1161 let def_id = DefId { krate: 0, node: item.id };
1162 name_bindings.define_module(parent_link,
1166 item.vis == ast::Public,
1169 ModuleReducedGraphParent(name_bindings.get_module())
1172 ItemForeignMod(..) => parent,
1174 // These items live in the value namespace.
1175 ItemStatic(_, m, _) => {
1176 let (name_bindings, _) =
1177 self.add_child(ident, parent, ForbidDuplicateValues, sp);
1178 let mutbl = m == ast::MutMutable;
1180 name_bindings.define_value
1181 (DefStatic(local_def(item.id), mutbl), sp, is_public);
1184 ItemFn(_, purity, _, _, _) => {
1185 let (name_bindings, new_parent) =
1186 self.add_child(ident, parent, ForbidDuplicateValues, sp);
1188 let def = DefFn(local_def(item.id), purity);
1189 name_bindings.define_value(def, sp, is_public);
1193 // These items live in the type namespace.
1195 let (name_bindings, _) =
1196 self.add_child(ident, parent, ForbidDuplicateTypes, sp);
1198 name_bindings.define_type
1199 (DefTy(local_def(item.id)), sp, is_public);
1203 ItemEnum(ref enum_definition, _) => {
1204 let (name_bindings, new_parent) =
1205 self.add_child(ident, parent, ForbidDuplicateTypes, sp);
1207 name_bindings.define_type
1208 (DefTy(local_def(item.id)), sp, is_public);
1210 for &variant in (*enum_definition).variants.iter() {
1211 self.build_reduced_graph_for_variant(
1220 // These items live in both the type and value namespaces.
1221 ItemStruct(struct_def, _) => {
1222 // Adding to both Type and Value namespaces or just Type?
1223 let (forbid, ctor_id) = match struct_def.ctor_id {
1224 Some(ctor_id) => (ForbidDuplicateTypesAndValues, Some(ctor_id)),
1225 None => (ForbidDuplicateTypes, None)
1228 let (name_bindings, new_parent) = self.add_child(ident, parent, forbid, sp);
1230 // Define a name in the type namespace.
1231 name_bindings.define_type(DefTy(local_def(item.id)), sp, is_public);
1233 // If this is a newtype or unit-like struct, define a name
1234 // in the value namespace as well
1235 ctor_id.while_some(|cid| {
1236 name_bindings.define_value(DefStruct(local_def(cid)), sp,
1241 // Record the def ID of this struct.
1242 self.structs.insert(local_def(item.id));
1247 ItemImpl(_, None, ty, ref methods) => {
1248 // If this implements an anonymous trait, then add all the
1249 // methods within to a new module, if the type was defined
1250 // within this module.
1252 // FIXME (#3785): This is quite unsatisfactory. Perhaps we
1253 // should modify anonymous traits to only be implementable in
1254 // the same module that declared the type.
1256 // Create the module and add all methods.
1258 TyPath(ref path, _, _) if path.segments.len() == 1 => {
1259 let name = path_to_ident(path);
1261 let existing_parent_opt = {
1262 let children = parent.module().children.borrow();
1263 children.get().find_copy(&name.name)
1265 let new_parent = match existing_parent_opt {
1266 // It already exists
1267 Some(child) if child.get_module_if_available()
1269 child.get_module().kind.get() ==
1271 ModuleReducedGraphParent(child.get_module())
1273 // Create the module
1275 let (name_bindings, new_parent) =
1276 self.add_child(name,
1278 ForbidDuplicateModules,
1282 self.get_parent_link(new_parent, ident);
1283 let def_id = local_def(item.id);
1286 !name_bindings.defined_in_namespace(ns) ||
1287 name_bindings.defined_in_public_namespace(ns);
1289 name_bindings.define_module(parent_link,
1296 ModuleReducedGraphParent(
1297 name_bindings.get_module())
1301 // For each method...
1302 for method in methods.iter() {
1303 // Add the method to the module.
1304 let ident = method.ident;
1305 let (method_name_bindings, _) =
1306 self.add_child(ident,
1308 ForbidDuplicateValues,
1310 let def = match method.explicit_self.node {
1312 // Static methods become
1313 // `def_static_method`s.
1314 DefStaticMethod(local_def(method.id),
1320 // Non-static methods become
1322 DefMethod(local_def(method.id), None)
1326 let is_public = method.vis == ast::Public;
1327 method_name_bindings.define_value(def,
1338 ItemImpl(_, Some(_), _, _) => parent,
1340 ItemTrait(_, _, ref methods) => {
1341 let (name_bindings, new_parent) =
1342 self.add_child(ident, parent, ForbidDuplicateTypes, sp);
1344 // Add all the methods within to a new module.
1345 let parent_link = self.get_parent_link(parent, ident);
1346 name_bindings.define_module(parent_link,
1347 Some(local_def(item.id)),
1350 item.vis == ast::Public,
1352 let module_parent = ModuleReducedGraphParent(name_bindings.
1355 // Add the names of all the methods to the trait info.
1356 let mut method_names = HashMap::new();
1357 for method in methods.iter() {
1358 let ty_m = trait_method_to_ty_method(method);
1360 let ident = ty_m.ident;
1362 // Add it as a name in the trait module.
1363 let def = match ty_m.explicit_self.node {
1365 // Static methods become `def_static_method`s.
1366 DefStaticMethod(local_def(ty_m.id),
1367 FromTrait(local_def(item.id)),
1371 // Non-static methods become `def_method`s.
1372 DefMethod(local_def(ty_m.id),
1373 Some(local_def(item.id)))
1377 let (method_name_bindings, _) =
1378 self.add_child(ident,
1380 ForbidDuplicateValues,
1382 method_name_bindings.define_value(def, ty_m.span, true);
1384 // Add it to the trait info if not static.
1385 match ty_m.explicit_self.node {
1388 method_names.insert(ident.name, ());
1393 let def_id = local_def(item.id);
1394 for (name, _) in method_names.iter() {
1395 let mut method_map = self.method_map.borrow_mut();
1396 if !method_map.get().contains_key(name) {
1397 method_map.get().insert(*name, HashSet::new());
1399 match method_map.get().find_mut(name) {
1400 Some(s) => { s.insert(def_id); },
1401 _ => fail!("can't happen"),
1405 name_bindings.define_type(DefTrait(def_id), sp, is_public);
1408 ItemMac(..) => parent
1412 // Constructs the reduced graph for one variant. Variants exist in the
1413 // type and/or value namespaces.
1414 fn build_reduced_graph_for_variant(&mut self,
1417 parent: ReducedGraphParent,
1418 parent_public: bool) {
1419 let ident = variant.node.name;
1420 // FIXME: this is unfortunate to have to do this privacy calculation
1421 // here. This should be living in middle::privacy, but it's
1422 // necessary to keep around in some form becaues of glob imports...
1423 let is_public = parent_public && variant.node.vis != ast::Private;
1425 match variant.node.kind {
1426 TupleVariantKind(_) => {
1427 let (child, _) = self.add_child(ident, parent, ForbidDuplicateValues,
1429 child.define_value(DefVariant(item_id,
1430 local_def(variant.node.id), false),
1431 variant.span, is_public);
1433 StructVariantKind(_) => {
1434 let (child, _) = self.add_child(ident, parent, ForbidDuplicateTypesAndValues,
1436 child.define_type(DefVariant(item_id,
1437 local_def(variant.node.id), true),
1438 variant.span, is_public);
1439 self.structs.insert(local_def(variant.node.id));
1444 /// Constructs the reduced graph for one 'view item'. View items consist
1445 /// of imports and use directives.
1446 fn build_reduced_graph_for_view_item(&mut self, view_item: &ViewItem,
1447 parent: ReducedGraphParent) {
1448 match view_item.node {
1449 ViewItemUse(ref view_paths) => {
1450 for view_path in view_paths.iter() {
1451 // Extract and intern the module part of the path. For
1452 // globs and lists, the path is found directly in the AST;
1453 // for simple paths we have to munge the path a little.
1455 let mut module_path = Vec::new();
1456 match view_path.node {
1457 ViewPathSimple(_, ref full_path, _) => {
1458 let path_len = full_path.segments.len();
1459 assert!(path_len != 0);
1461 for (i, segment) in full_path.segments
1464 if i != path_len - 1 {
1465 module_path.push(segment.identifier)
1470 ViewPathGlob(ref module_ident_path, _) |
1471 ViewPathList(ref module_ident_path, _, _) => {
1472 for segment in module_ident_path.segments.iter() {
1473 module_path.push(segment.identifier)
1478 // Build up the import directives.
1479 let module_ = self.get_module_from_parent(parent);
1480 let is_public = view_item.vis == ast::Public;
1481 match view_path.node {
1482 ViewPathSimple(binding, ref full_path, id) => {
1484 full_path.segments.last().unwrap().identifier;
1485 let subclass = @SingleImport(binding,
1487 self.build_import_directive(module_,
1494 ViewPathList(_, ref source_idents, _) => {
1495 for source_ident in source_idents.iter() {
1496 let name = source_ident.node.name;
1497 let subclass = @SingleImport(name, name);
1498 self.build_import_directive(
1500 module_path.clone(),
1503 source_ident.node.id,
1507 ViewPathGlob(_, id) => {
1508 self.build_import_directive(module_,
1519 ViewItemExternCrate(name, _, node_id) => {
1520 // n.b. we don't need to look at the path option here, because cstore already did
1521 match self.session.cstore.find_extern_mod_stmt_cnum(node_id) {
1523 let def_id = DefId { krate: crate_id, node: 0 };
1524 self.external_exports.insert(def_id);
1525 let parent_link = ModuleParentLink
1526 (self.get_module_from_parent(parent), name);
1527 let external_module = @Module::new(parent_link,
1534 let mut external_module_children =
1535 parent.module().external_module_children.borrow_mut();
1536 external_module_children.get().insert(
1541 self.build_reduced_graph_for_external_crate(
1544 None => {} // Ignore.
1550 /// Constructs the reduced graph for one foreign item.
1551 fn build_reduced_graph_for_foreign_item(&mut self,
1552 foreign_item: &ForeignItem,
1553 parent: ReducedGraphParent,
1555 ReducedGraphParent|) {
1556 let name = foreign_item.ident;
1557 let is_public = foreign_item.vis == ast::Public;
1558 let (name_bindings, new_parent) =
1559 self.add_child(name, parent, ForbidDuplicateValues,
1562 match foreign_item.node {
1563 ForeignItemFn(_, ref generics) => {
1564 let def = DefFn(local_def(foreign_item.id), UnsafeFn);
1565 name_bindings.define_value(def, foreign_item.span, is_public);
1567 self.with_type_parameter_rib(
1568 HasTypeParameters(generics,
1572 |this| f(this, new_parent));
1574 ForeignItemStatic(_, m) => {
1575 let def = DefStatic(local_def(foreign_item.id), m);
1576 name_bindings.define_value(def, foreign_item.span, is_public);
1583 fn build_reduced_graph_for_block(&mut self,
1585 parent: ReducedGraphParent)
1586 -> ReducedGraphParent
1588 if self.block_needs_anonymous_module(block) {
1589 let block_id = block.id;
1591 debug!("(building reduced graph for block) creating a new \
1592 anonymous module for block {}",
1595 let parent_module = self.get_module_from_parent(parent);
1596 let new_module = @Module::new(
1597 BlockParentLink(parent_module, block_id),
1599 AnonymousModuleKind,
1603 let mut anonymous_children = parent_module.anonymous_children
1605 anonymous_children.get().insert(block_id, new_module);
1606 ModuleReducedGraphParent(new_module)
1613 fn handle_external_def(&mut self,
1616 child_name_bindings: @NameBindings,
1619 new_parent: ReducedGraphParent) {
1620 debug!("(building reduced graph for \
1621 external crate) building external def, priv {:?}",
1623 let is_public = vis == ast::Public;
1624 let is_exported = is_public && match new_parent {
1625 ModuleReducedGraphParent(module) => {
1626 match module.def_id.get() {
1628 Some(did) => self.external_exports.contains(&did)
1633 self.external_exports.insert(def_id_of_def(def));
1636 DefMod(def_id) | DefForeignMod(def_id) | DefStruct(def_id) |
1638 match child_name_bindings.type_def.get() {
1639 Some(TypeNsDef { module_def: Some(module_def), .. }) => {
1640 debug!("(building reduced graph for external crate) \
1641 already created module");
1642 module_def.def_id.set(Some(def_id));
1645 debug!("(building reduced graph for \
1646 external crate) building module \
1648 let parent_link = self.get_parent_link(new_parent, ident);
1650 child_name_bindings.define_module(parent_link,
1663 DefMod(_) | DefForeignMod(_) => {}
1664 DefVariant(_, variant_id, is_struct) => {
1665 debug!("(building reduced graph for external crate) building \
1668 // We assume the parent is visible, or else we wouldn't have seen
1669 // it. Also variants are public-by-default if the parent was also
1671 let is_public = vis != ast::Private;
1673 child_name_bindings.define_type(def, DUMMY_SP, is_public);
1674 self.structs.insert(variant_id);
1676 child_name_bindings.define_value(def, DUMMY_SP, is_public);
1679 DefFn(..) | DefStaticMethod(..) | DefStatic(..) => {
1680 debug!("(building reduced graph for external \
1681 crate) building value (fn/static) {}", final_ident);
1682 child_name_bindings.define_value(def, DUMMY_SP, is_public);
1684 DefTrait(def_id) => {
1685 debug!("(building reduced graph for external \
1686 crate) building type {}", final_ident);
1688 // If this is a trait, add all the method names
1689 // to the trait info.
1691 let method_def_ids =
1692 csearch::get_trait_method_def_ids(self.session.cstore, def_id);
1693 let mut interned_method_names = HashSet::new();
1694 for &method_def_id in method_def_ids.iter() {
1695 let (method_name, explicit_self) =
1696 csearch::get_method_name_and_explicit_self(self.session.cstore,
1699 debug!("(building reduced graph for \
1700 external crate) ... adding \
1702 token::get_ident(method_name));
1704 // Add it to the trait info if not static.
1705 if explicit_self != SelfStatic {
1706 interned_method_names.insert(method_name.name);
1709 self.external_exports.insert(method_def_id);
1712 for name in interned_method_names.iter() {
1713 let mut method_map = self.method_map.borrow_mut();
1714 if !method_map.get().contains_key(name) {
1715 method_map.get().insert(*name, HashSet::new());
1717 match method_map.get().find_mut(name) {
1718 Some(s) => { s.insert(def_id); },
1719 _ => fail!("can't happen"),
1723 child_name_bindings.define_type(def, DUMMY_SP, is_public);
1725 // Define a module if necessary.
1726 let parent_link = self.get_parent_link(new_parent, ident);
1727 child_name_bindings.set_module_kind(parent_link,
1735 debug!("(building reduced graph for external \
1736 crate) building type {}", final_ident);
1738 child_name_bindings.define_type(def, DUMMY_SP, is_public);
1740 DefStruct(def_id) => {
1741 debug!("(building reduced graph for external \
1742 crate) building type and value for {}",
1744 child_name_bindings.define_type(def, DUMMY_SP, is_public);
1745 if csearch::get_struct_fields(self.session.cstore, def_id).len() == 0 {
1746 child_name_bindings.define_value(def, DUMMY_SP, is_public);
1748 self.structs.insert(def_id);
1751 debug!("(building reduced graph for external crate) \
1752 ignoring {:?}", def);
1753 // Ignored; handled elsewhere.
1755 DefArg(..) | DefLocal(..) | DefPrimTy(..) |
1756 DefTyParam(..) | DefBinding(..) |
1757 DefUse(..) | DefUpvar(..) | DefRegion(..) |
1758 DefTyParamBinder(..) | DefLabel(..) | DefSelfTy(..) => {
1759 fail!("didn't expect `{:?}`", def);
1764 /// Builds the reduced graph for a single item in an external crate.
1765 fn build_reduced_graph_for_external_crate_def(&mut self,
1769 visibility: Visibility) {
1772 // Add the new child item, if necessary.
1774 DefForeignMod(def_id) => {
1775 // Foreign modules have no names. Recur and populate
1777 csearch::each_child_of_item(self.session.cstore,
1782 self.build_reduced_graph_for_external_crate_def(
1790 let (child_name_bindings, new_parent) =
1791 self.add_child(ident,
1792 ModuleReducedGraphParent(root),
1793 OverwriteDuplicates,
1796 self.handle_external_def(def,
1798 child_name_bindings,
1799 token::get_ident(ident).get(),
1806 // We only process static methods of impls here.
1807 match csearch::get_type_name_if_impl(self.session.cstore, def) {
1809 Some(final_ident) => {
1810 let static_methods_opt =
1811 csearch::get_static_methods_if_impl(self.session.cstore, def);
1812 match static_methods_opt {
1813 Some(ref static_methods) if
1814 static_methods.len() >= 1 => {
1815 debug!("(building reduced graph for \
1816 external crate) processing \
1817 static methods for type name {}",
1818 token::get_ident(final_ident));
1820 let (child_name_bindings, new_parent) =
1823 ModuleReducedGraphParent(root),
1824 OverwriteDuplicates,
1827 // Process the static methods. First,
1828 // create the module.
1830 match child_name_bindings.type_def.get() {
1832 module_def: Some(module_def),
1835 // We already have a module. This
1837 type_module = module_def;
1839 // Mark it as an impl module if
1841 type_module.kind.set(ImplModuleKind);
1845 self.get_parent_link(new_parent,
1847 child_name_bindings.define_module(
1855 child_name_bindings.
1860 // Add each static method to the module.
1862 ModuleReducedGraphParent(type_module);
1863 for static_method_info in
1864 static_methods.iter() {
1865 let ident = static_method_info.ident;
1866 debug!("(building reduced graph for \
1867 external crate) creating \
1868 static method '{}'",
1869 token::get_ident(ident));
1871 let (method_name_bindings, _) =
1872 self.add_child(ident,
1874 OverwriteDuplicates,
1877 static_method_info.def_id,
1878 static_method_info.purity);
1880 method_name_bindings.define_value(
1882 visibility == ast::Public);
1886 // Otherwise, do nothing.
1887 Some(_) | None => {}
1893 debug!("(building reduced graph for external crate) \
1899 /// Builds the reduced graph rooted at the given external module.
1900 fn populate_external_module(&mut self, module: @Module) {
1901 debug!("(populating external module) attempting to populate {}",
1902 self.module_to_str(module));
1904 let def_id = match module.def_id.get() {
1906 debug!("(populating external module) ... no def ID!");
1909 Some(def_id) => def_id,
1912 csearch::each_child_of_item(self.session.cstore,
1914 |def_like, child_ident, visibility| {
1915 debug!("(populating external module) ... found ident: {}",
1916 token::get_ident(child_ident));
1917 self.build_reduced_graph_for_external_crate_def(module,
1922 module.populated.set(true)
1925 /// Ensures that the reduced graph rooted at the given external module
1926 /// is built, building it if it is not.
1927 fn populate_module_if_necessary(&mut self, module: @Module) {
1928 if !module.populated.get() {
1929 self.populate_external_module(module)
1931 assert!(module.populated.get())
1934 /// Builds the reduced graph rooted at the 'use' directive for an external
1936 fn build_reduced_graph_for_external_crate(&mut self,
1938 csearch::each_top_level_item_of_crate(self.session.cstore,
1943 |def_like, ident, visibility| {
1944 self.build_reduced_graph_for_external_crate_def(root,
1951 /// Creates and adds an import directive to the given module.
1952 fn build_import_directive(&mut self,
1954 module_path: Vec<Ident> ,
1955 subclass: @ImportDirectiveSubclass,
1959 let directive = @ImportDirective::new(module_path,
1964 let mut imports = module_.imports.borrow_mut();
1965 imports.get().push(directive);
1968 // Bump the reference count on the name. Or, if this is a glob, set
1969 // the appropriate flag.
1972 SingleImport(target, _) => {
1973 debug!("(building import directive) building import \
1975 self.idents_to_str(directive.module_path),
1976 token::get_ident(target));
1978 let mut import_resolutions = module_.import_resolutions
1980 match import_resolutions.get().find(&target.name) {
1981 Some(&resolution) => {
1982 debug!("(building import directive) bumping \
1984 resolution.outstanding_references.set(
1985 resolution.outstanding_references.get() + 1);
1987 // the source of this name is different now
1988 resolution.type_id.set(id);
1989 resolution.value_id.set(id);
1992 debug!("(building import directive) creating new");
1993 let resolution = @ImportResolution::new(id, is_public);
1994 resolution.outstanding_references.set(1);
1995 import_resolutions.get().insert(target.name,
2001 // Set the glob flag. This tells us that we don't know the
2002 // module's exports ahead of time.
2004 module_.glob_count.set(module_.glob_count.get() + 1);
2008 self.unresolved_imports += 1;
2011 // Import resolution
2013 // This is a fixed-point algorithm. We resolve imports until our efforts
2014 // are stymied by an unresolved import; then we bail out of the current
2015 // module and continue. We terminate successfully once no more imports
2016 // remain or unsuccessfully when no forward progress in resolving imports
2019 /// Resolves all imports for the crate. This method performs the fixed-
2020 /// point iteration.
2021 fn resolve_imports(&mut self) {
2023 let mut prev_unresolved_imports = 0;
2025 debug!("(resolving imports) iteration {}, {} imports left",
2026 i, self.unresolved_imports);
2028 let module_root = self.graph_root.get_module();
2029 self.resolve_imports_for_module_subtree(module_root);
2031 if self.unresolved_imports == 0 {
2032 debug!("(resolving imports) success");
2036 if self.unresolved_imports == prev_unresolved_imports {
2037 self.report_unresolved_imports(module_root);
2042 prev_unresolved_imports = self.unresolved_imports;
2046 /// Attempts to resolve imports for the given module and all of its
2048 fn resolve_imports_for_module_subtree(&mut self,
2050 debug!("(resolving imports for module subtree) resolving {}",
2051 self.module_to_str(module_));
2052 self.resolve_imports_for_module(module_);
2054 self.populate_module_if_necessary(module_);
2056 let children = module_.children.borrow();
2057 for (_, &child_node) in children.get().iter() {
2058 match child_node.get_module_if_available() {
2062 Some(child_module) => {
2063 self.resolve_imports_for_module_subtree(child_module);
2069 let anonymous_children = module_.anonymous_children.borrow();
2070 for (_, &child_module) in anonymous_children.get().iter() {
2071 self.resolve_imports_for_module_subtree(child_module);
2075 /// Attempts to resolve imports for the given module only.
2076 fn resolve_imports_for_module(&mut self, module: @Module) {
2077 if module.all_imports_resolved() {
2078 debug!("(resolving imports for module) all imports resolved for \
2080 self.module_to_str(module));
2084 let mut imports = module.imports.borrow_mut();
2085 let import_count = imports.get().len();
2086 while module.resolved_import_count.get() < import_count {
2087 let import_index = module.resolved_import_count.get();
2088 let import_directive = imports.get()[import_index];
2089 match self.resolve_import_for_module(module, import_directive) {
2091 // We presumably emitted an error. Continue.
2092 let msg = format!("failed to resolve import `{}`",
2093 self.import_path_to_str(
2094 import_directive.module_path,
2095 *import_directive.subclass));
2096 self.resolve_error(import_directive.span, msg);
2099 // Bail out. We'll come around next time.
2107 module.resolved_import_count
2108 .set(module.resolved_import_count.get() + 1);
2112 fn idents_to_str(&mut self, idents: &[Ident]) -> ~str {
2113 let mut first = true;
2114 let mut result = ~"";
2115 for ident in idents.iter() {
2119 result.push_str("::")
2121 result.push_str(token::get_ident(*ident).get());
2126 fn path_idents_to_str(&mut self, path: &Path) -> ~str {
2127 let identifiers: Vec<ast::Ident> = path.segments
2129 .map(|seg| seg.identifier)
2131 self.idents_to_str(identifiers)
2134 fn import_directive_subclass_to_str(&mut self,
2135 subclass: ImportDirectiveSubclass)
2138 SingleImport(_, source) => {
2139 token::get_ident(source).get().to_str()
2145 fn import_path_to_str(&mut self,
2147 subclass: ImportDirectiveSubclass)
2149 if idents.is_empty() {
2150 self.import_directive_subclass_to_str(subclass)
2153 self.idents_to_str(idents),
2154 self.import_directive_subclass_to_str(subclass)))
2158 /// Attempts to resolve the given import. The return value indicates
2159 /// failure if we're certain the name does not exist, indeterminate if we
2160 /// don't know whether the name exists at the moment due to other
2161 /// currently-unresolved imports, or success if we know the name exists.
2162 /// If successful, the resolved bindings are written into the module.
2163 fn resolve_import_for_module(&mut self,
2165 import_directive: @ImportDirective)
2166 -> ResolveResult<()> {
2167 let mut resolution_result = Failed;
2168 let module_path = &import_directive.module_path;
2170 debug!("(resolving import for module) resolving import `{}::...` in \
2172 self.idents_to_str(*module_path),
2173 self.module_to_str(module_));
2175 // First, resolve the module path for the directive, if necessary.
2176 let container = if module_path.len() == 0 {
2177 // Use the crate root.
2178 Some((self.graph_root.get_module(), LastMod(AllPublic)))
2180 match self.resolve_module_path(module_,
2182 DontUseLexicalScope,
2183 import_directive.span,
2188 resolution_result = Indeterminate;
2191 Success(container) => Some(container),
2197 Some((containing_module, lp)) => {
2198 // We found the module that the target is contained
2199 // within. Attempt to resolve the import within it.
2201 match *import_directive.subclass {
2202 SingleImport(target, source) => {
2204 self.resolve_single_import(module_,
2213 self.resolve_glob_import(module_,
2215 import_directive.id,
2216 import_directive.is_public,
2223 // Decrement the count of unresolved imports.
2224 match resolution_result {
2226 assert!(self.unresolved_imports >= 1);
2227 self.unresolved_imports -= 1;
2230 // Nothing to do here; just return the error.
2234 // Decrement the count of unresolved globs if necessary. But only if
2235 // the resolution result is indeterminate -- otherwise we'll stop
2236 // processing imports here. (See the loop in
2237 // resolve_imports_for_module.)
2239 if !resolution_result.indeterminate() {
2240 match *import_directive.subclass {
2242 assert!(module_.glob_count.get() >= 1);
2243 module_.glob_count.set(module_.glob_count.get() - 1);
2245 SingleImport(..) => {
2251 return resolution_result;
2254 fn create_name_bindings_from_module(module: @Module) -> NameBindings {
2256 type_def: RefCell::new(Some(TypeNsDef {
2258 module_def: Some(module),
2262 value_def: RefCell::new(None),
2266 fn resolve_single_import(&mut self,
2268 containing_module: @Module,
2271 directive: &ImportDirective,
2273 -> ResolveResult<()> {
2274 debug!("(resolving single import) resolving `{}` = `{}::{}` from \
2275 `{}` id {}, last private {:?}",
2276 token::get_ident(target),
2277 self.module_to_str(containing_module),
2278 token::get_ident(source),
2279 self.module_to_str(module_),
2285 LastImport{..} => self.session.span_bug(directive.span,
2286 "Not expecting Import here, must be LastMod"),
2289 // We need to resolve both namespaces for this to succeed.
2292 let mut value_result = UnknownResult;
2293 let mut type_result = UnknownResult;
2295 // Search for direct children of the containing module.
2296 self.populate_module_if_necessary(containing_module);
2299 let children = containing_module.children.borrow();
2300 match children.get().find(&source.name) {
2304 Some(child_name_bindings) => {
2305 if child_name_bindings.defined_in_namespace(ValueNS) {
2306 value_result = BoundResult(containing_module,
2307 *child_name_bindings);
2309 if child_name_bindings.defined_in_namespace(TypeNS) {
2310 type_result = BoundResult(containing_module,
2311 *child_name_bindings);
2317 // Unless we managed to find a result in both namespaces (unlikely),
2318 // search imports as well.
2319 let mut value_used_reexport = false;
2320 let mut type_used_reexport = false;
2321 match (value_result, type_result) {
2322 (BoundResult(..), BoundResult(..)) => {} // Continue.
2324 // If there is an unresolved glob at this point in the
2325 // containing module, bail out. We don't know enough to be
2326 // able to resolve this import.
2328 if containing_module.glob_count.get() > 0 {
2329 debug!("(resolving single import) unresolved glob; \
2331 return Indeterminate;
2334 // Now search the exported imports within the containing
2337 let import_resolutions = containing_module.import_resolutions
2339 match import_resolutions.get().find(&source.name) {
2341 // The containing module definitely doesn't have an
2342 // exported import with the name in question. We can
2343 // therefore accurately report that the names are
2346 if value_result.is_unknown() {
2347 value_result = UnboundResult;
2349 if type_result.is_unknown() {
2350 type_result = UnboundResult;
2353 Some(import_resolution)
2354 if import_resolution.outstanding_references.get()
2357 fn get_binding(this: &mut Resolver,
2358 import_resolution: @ImportResolution,
2359 namespace: Namespace)
2360 -> NamespaceResult {
2362 // Import resolutions must be declared with "pub"
2363 // in order to be exported.
2364 if !import_resolution.is_public.get() {
2365 return UnboundResult;
2368 match (*import_resolution).
2369 target_for_namespace(namespace) {
2371 return UnboundResult;
2374 let id = import_resolution.id(namespace);
2375 this.used_imports.insert((id, namespace));
2376 return BoundResult(target.target_module,
2382 // The name is an import which has been fully
2383 // resolved. We can, therefore, just follow it.
2384 if value_result.is_unknown() {
2385 value_result = get_binding(self, *import_resolution,
2387 value_used_reexport = import_resolution.is_public.get();
2389 if type_result.is_unknown() {
2390 type_result = get_binding(self, *import_resolution,
2392 type_used_reexport = import_resolution.is_public.get();
2397 // The import is unresolved. Bail out.
2398 debug!("(resolving single import) unresolved import; \
2400 return Indeterminate;
2406 // If we didn't find a result in the type namespace, search the
2407 // external modules.
2408 let mut value_used_public = false;
2409 let mut type_used_public = false;
2411 BoundResult(..) => {}
2414 let mut external_module_children =
2415 containing_module.external_module_children
2417 external_module_children.get().find_copy(&source.name)
2420 None => {} // Continue.
2423 @Resolver::create_name_bindings_from_module(
2425 type_result = BoundResult(containing_module,
2427 type_used_public = true;
2433 // We've successfully resolved the import. Write the results in.
2434 let import_resolution = {
2435 let import_resolutions = module_.import_resolutions.borrow();
2436 assert!(import_resolutions.get().contains_key(&target.name));
2437 import_resolutions.get().get_copy(&target.name)
2440 match value_result {
2441 BoundResult(target_module, name_bindings) => {
2442 debug!("(resolving single import) found value target");
2443 import_resolution.value_target.set(
2444 Some(Target::new(target_module, name_bindings)));
2445 import_resolution.value_id.set(directive.id);
2446 value_used_public = name_bindings.defined_in_public_namespace(ValueNS);
2448 UnboundResult => { /* Continue. */ }
2450 fail!("value result should be known at this point");
2454 BoundResult(target_module, name_bindings) => {
2455 debug!("(resolving single import) found type target: {:?}",
2456 {name_bindings.type_def.get().unwrap().type_def});
2457 import_resolution.type_target.set(
2458 Some(Target::new(target_module, name_bindings)));
2459 import_resolution.type_id.set(directive.id);
2460 type_used_public = name_bindings.defined_in_public_namespace(TypeNS);
2462 UnboundResult => { /* Continue. */ }
2464 fail!("type result should be known at this point");
2468 if import_resolution.value_target.get().is_none() &&
2469 import_resolution.type_target.get().is_none() {
2470 let msg = format!("unresolved import: there is no \
2472 token::get_ident(source),
2473 self.module_to_str(containing_module));
2474 self.resolve_error(directive.span, msg);
2477 let value_used_public = value_used_reexport || value_used_public;
2478 let type_used_public = type_used_reexport || type_used_public;
2480 assert!(import_resolution.outstanding_references.get() >= 1);
2481 import_resolution.outstanding_references.set(
2482 import_resolution.outstanding_references.get() - 1);
2484 // record what this import resolves to for later uses in documentation,
2485 // this may resolve to either a value or a type, but for documentation
2486 // purposes it's good enough to just favor one over the other.
2487 let value_private = match import_resolution.value_target.get() {
2489 let def = target.bindings.def_for_namespace(ValueNS).unwrap();
2490 let mut def_map = self.def_map.borrow_mut();
2491 def_map.get().insert(directive.id, def);
2492 let did = def_id_of_def(def);
2493 if value_used_public {Some(lp)} else {Some(DependsOn(did))}
2495 // AllPublic here and below is a dummy value, it should never be used because
2496 // _exists is false.
2499 let type_private = match import_resolution.type_target.get() {
2501 let def = target.bindings.def_for_namespace(TypeNS).unwrap();
2502 let mut def_map = self.def_map.borrow_mut();
2503 def_map.get().insert(directive.id, def);
2504 let did = def_id_of_def(def);
2505 if type_used_public {Some(lp)} else {Some(DependsOn(did))}
2510 self.last_private.insert(directive.id, LastImport{value_priv: value_private,
2512 type_priv: type_private,
2515 debug!("(resolving single import) successfully resolved import");
2519 // Resolves a glob import. Note that this function cannot fail; it either
2520 // succeeds or bails out (as importing * from an empty module or a module
2521 // that exports nothing is valid).
2522 fn resolve_glob_import(&mut self,
2524 containing_module: @Module,
2528 -> ResolveResult<()> {
2529 // This function works in a highly imperative manner; it eagerly adds
2530 // everything it can to the list of import resolutions of the module
2532 debug!("(resolving glob import) resolving glob import {}", id);
2534 // We must bail out if the node has unresolved imports of any kind
2535 // (including globs).
2536 if !(*containing_module).all_imports_resolved() {
2537 debug!("(resolving glob import) target module has unresolved \
2538 imports; bailing out");
2539 return Indeterminate;
2542 assert_eq!(containing_module.glob_count.get(), 0);
2544 // Add all resolved imports from the containing module.
2545 let import_resolutions = containing_module.import_resolutions
2547 for (ident, target_import_resolution) in import_resolutions.get()
2549 debug!("(resolving glob import) writing module resolution \
2551 target_import_resolution.type_target.get().is_none(),
2552 self.module_to_str(module_));
2554 if !target_import_resolution.is_public.get() {
2555 debug!("(resolving glob import) nevermind, just kidding");
2559 // Here we merge two import resolutions.
2560 let mut import_resolutions = module_.import_resolutions
2562 match import_resolutions.get().find(ident) {
2564 // Simple: just copy the old import resolution.
2565 let new_import_resolution =
2566 @ImportResolution::new(id, is_public);
2567 new_import_resolution.value_target.set(
2568 target_import_resolution.value_target.get());
2569 new_import_resolution.type_target.set(
2570 target_import_resolution.type_target.get());
2572 import_resolutions.get().insert
2573 (*ident, new_import_resolution);
2575 Some(&dest_import_resolution) => {
2576 // Merge the two import resolutions at a finer-grained
2579 match target_import_resolution.value_target.get() {
2583 Some(value_target) => {
2584 dest_import_resolution.value_target.set(
2585 Some(value_target));
2588 match target_import_resolution.type_target.get() {
2592 Some(type_target) => {
2593 dest_import_resolution.type_target.set(
2597 dest_import_resolution.is_public.set(is_public);
2602 // Add all children from the containing module.
2603 self.populate_module_if_necessary(containing_module);
2606 let children = containing_module.children.borrow();
2607 for (&name, name_bindings) in children.get().iter() {
2608 self.merge_import_resolution(module_, containing_module,
2610 name, *name_bindings);
2614 // Add external module children from the containing module.
2616 let external_module_children =
2617 containing_module.external_module_children.borrow();
2618 for (&name, module) in external_module_children.get().iter() {
2620 @Resolver::create_name_bindings_from_module(*module);
2621 self.merge_import_resolution(module_, containing_module,
2623 name, name_bindings);
2627 // Record the destination of this import
2628 match containing_module.def_id.get() {
2630 let mut def_map = self.def_map.borrow_mut();
2631 def_map.get().insert(id, DefMod(did));
2632 self.last_private.insert(id, lp);
2637 debug!("(resolving glob import) successfully resolved import");
2641 fn merge_import_resolution(&mut self,
2643 containing_module: @Module,
2647 name_bindings: @NameBindings) {
2648 let dest_import_resolution;
2649 let mut import_resolutions = module_.import_resolutions.borrow_mut();
2650 match import_resolutions.get().find(&name) {
2652 // Create a new import resolution from this child.
2653 dest_import_resolution =
2654 @ImportResolution::new(id, is_public);
2655 import_resolutions.get().insert(name,
2656 dest_import_resolution);
2658 Some(&existing_import_resolution) => {
2659 dest_import_resolution = existing_import_resolution;
2663 debug!("(resolving glob import) writing resolution `{}` in `{}` \
2665 token::get_name(name).get().to_str(),
2666 self.module_to_str(containing_module),
2667 self.module_to_str(module_));
2669 // Merge the child item into the import resolution.
2670 if name_bindings.defined_in_public_namespace(ValueNS) {
2671 debug!("(resolving glob import) ... for value target");
2672 dest_import_resolution.value_target.set(
2673 Some(Target::new(containing_module, name_bindings)));
2674 dest_import_resolution.value_id.set(id);
2676 if name_bindings.defined_in_public_namespace(TypeNS) {
2677 debug!("(resolving glob import) ... for type target");
2678 dest_import_resolution.type_target.set(
2679 Some(Target::new(containing_module, name_bindings)));
2680 dest_import_resolution.type_id.set(id);
2682 dest_import_resolution.is_public.set(is_public);
2685 /// Resolves the given module path from the given root `module_`.
2686 fn resolve_module_path_from_root(&mut self,
2688 module_path: &[Ident],
2691 name_search_type: NameSearchType,
2693 -> ResolveResult<(@Module, LastPrivate)> {
2694 let mut search_module = module_;
2695 let mut index = index;
2696 let module_path_len = module_path.len();
2697 let mut closest_private = lp;
2699 // Resolve the module part of the path. This does not involve looking
2700 // upward though scope chains; we simply resolve names directly in
2701 // modules as we go.
2702 while index < module_path_len {
2703 let name = module_path[index];
2704 match self.resolve_name_in_module(search_module,
2709 let segment_name = token::get_ident(name);
2710 let module_name = self.module_to_str(search_module);
2711 if "???" == module_name {
2714 hi: span.lo + Pos::from_uint(segment_name.get().len()),
2715 expn_info: span.expn_info,
2717 self.resolve_error(span,
2718 format!("unresolved import. maybe \
2719 a missing `extern crate \
2724 self.resolve_error(span, format!("unresolved import: could not find `{}` in \
2725 `{}`.", segment_name, module_name));
2729 debug!("(resolving module path for import) module \
2730 resolution is indeterminate: {}",
2731 token::get_ident(name));
2732 return Indeterminate;
2734 Success((target, used_proxy)) => {
2735 // Check to see whether there are type bindings, and, if
2736 // so, whether there is a module within.
2737 match target.bindings.type_def.get() {
2739 match type_def.module_def {
2742 self.resolve_error(span, format!("not a module `{}`",
2743 token::get_ident(name)));
2746 Some(module_def) => {
2747 // If we're doing the search for an
2748 // import, do not allow traits and impls
2750 match (name_search_type,
2751 module_def.kind.get()) {
2752 (ImportSearch, TraitModuleKind) |
2753 (ImportSearch, ImplModuleKind) => {
2756 "cannot import from a trait \
2757 or type implementation");
2761 search_module = module_def;
2763 // Keep track of the closest
2764 // private module used when
2765 // resolving this import chain.
2767 !search_module.is_public {
2768 match search_module.def_id
2772 LastMod(DependsOn(did));
2783 // There are no type bindings at all.
2784 self.resolve_error(span,
2785 format!("not a module `{}`",
2786 token::get_ident(name)));
2796 return Success((search_module, closest_private));
2799 /// Attempts to resolve the module part of an import directive or path
2800 /// rooted at the given module.
2802 /// On success, returns the resolved module, and the closest *private*
2803 /// module found to the destination when resolving this path.
2804 fn resolve_module_path(&mut self,
2806 module_path: &[Ident],
2807 use_lexical_scope: UseLexicalScopeFlag,
2809 name_search_type: NameSearchType)
2810 -> ResolveResult<(@Module, LastPrivate)> {
2811 let module_path_len = module_path.len();
2812 assert!(module_path_len > 0);
2814 debug!("(resolving module path for import) processing `{}` rooted at \
2816 self.idents_to_str(module_path),
2817 self.module_to_str(module_));
2819 // Resolve the module prefix, if any.
2820 let module_prefix_result = self.resolve_module_prefix(module_,
2826 match module_prefix_result {
2828 let mpath = self.idents_to_str(module_path);
2829 match mpath.rfind(':') {
2831 self.resolve_error(span, format!("unresolved import: could not find `{}` \
2833 // idx +- 1 to account for the colons
2835 mpath.slice_from(idx + 1),
2836 mpath.slice_to(idx - 1)));
2843 debug!("(resolving module path for import) indeterminate; \
2845 return Indeterminate;
2847 Success(NoPrefixFound) => {
2848 // There was no prefix, so we're considering the first element
2849 // of the path. How we handle this depends on whether we were
2850 // instructed to use lexical scope or not.
2851 match use_lexical_scope {
2852 DontUseLexicalScope => {
2853 // This is a crate-relative path. We will start the
2854 // resolution process at index zero.
2855 search_module = self.graph_root.get_module();
2857 last_private = LastMod(AllPublic);
2859 UseLexicalScope => {
2860 // This is not a crate-relative path. We resolve the
2861 // first component of the path in the current lexical
2862 // scope and then proceed to resolve below that.
2863 let result = self.resolve_module_in_lexical_scope(
2868 self.resolve_error(span, "unresolved name");
2872 debug!("(resolving module path for import) \
2873 indeterminate; bailing");
2874 return Indeterminate;
2876 Success(containing_module) => {
2877 search_module = containing_module;
2879 last_private = LastMod(AllPublic);
2885 Success(PrefixFound(containing_module, index)) => {
2886 search_module = containing_module;
2887 start_index = index;
2888 last_private = LastMod(DependsOn(containing_module.def_id
2894 self.resolve_module_path_from_root(search_module,
2902 /// Invariant: This must only be called during main resolution, not during
2903 /// import resolution.
2904 fn resolve_item_in_lexical_scope(&mut self,
2907 namespace: Namespace,
2908 search_through_modules:
2909 SearchThroughModulesFlag)
2910 -> ResolveResult<(Target, bool)> {
2911 debug!("(resolving item in lexical scope) resolving `{}` in \
2912 namespace {:?} in `{}`",
2913 token::get_ident(name),
2915 self.module_to_str(module_));
2917 // The current module node is handled specially. First, check for
2918 // its immediate children.
2919 self.populate_module_if_necessary(module_);
2922 let children = module_.children.borrow();
2923 match children.get().find(&name.name) {
2925 if name_bindings.defined_in_namespace(namespace) => {
2926 debug!("top name bindings succeeded");
2927 return Success((Target::new(module_, *name_bindings),
2930 Some(_) | None => { /* Not found; continue. */ }
2934 // Now check for its import directives. We don't have to have resolved
2935 // all its imports in the usual way; this is because chains of
2936 // adjacent import statements are processed as though they mutated the
2938 let import_resolutions = module_.import_resolutions.borrow();
2939 match import_resolutions.get().find(&name.name) {
2941 // Not found; continue.
2943 Some(import_resolution) => {
2944 match (*import_resolution).target_for_namespace(namespace) {
2946 // Not found; continue.
2947 debug!("(resolving item in lexical scope) found \
2948 import resolution, but not in namespace {:?}",
2952 debug!("(resolving item in lexical scope) using \
2953 import resolution");
2954 self.used_imports.insert((import_resolution.id(namespace), namespace));
2955 return Success((target, false));
2961 // Search for external modules.
2962 if namespace == TypeNS {
2964 let external_module_children =
2965 module_.external_module_children.borrow();
2966 external_module_children.get().find_copy(&name.name)
2972 @Resolver::create_name_bindings_from_module(module);
2973 debug!("lower name bindings succeeded");
2974 return Success((Target::new(module_, name_bindings), false));
2979 // Finally, proceed up the scope chain looking for parent modules.
2980 let mut search_module = module_;
2982 // Go to the next parent.
2983 match search_module.parent_link {
2985 // No more parents. This module was unresolved.
2986 debug!("(resolving item in lexical scope) unresolved \
2990 ModuleParentLink(parent_module_node, _) => {
2991 match search_through_modules {
2992 DontSearchThroughModules => {
2993 match search_module.kind.get() {
2994 NormalModuleKind => {
2995 // We stop the search here.
2996 debug!("(resolving item in lexical \
2997 scope) unresolved module: not \
2998 searching through module \
3005 AnonymousModuleKind => {
3006 search_module = parent_module_node;
3010 SearchThroughModules => {
3011 search_module = parent_module_node;
3015 BlockParentLink(parent_module_node, _) => {
3016 search_module = parent_module_node;
3020 // Resolve the name in the parent module.
3021 match self.resolve_name_in_module(search_module,
3026 // Continue up the search chain.
3029 // We couldn't see through the higher scope because of an
3030 // unresolved import higher up. Bail.
3032 debug!("(resolving item in lexical scope) indeterminate \
3033 higher scope; bailing");
3034 return Indeterminate;
3036 Success((target, used_reexport)) => {
3037 // We found the module.
3038 debug!("(resolving item in lexical scope) found name \
3040 return Success((target, used_reexport));
3046 /// Resolves a module name in the current lexical scope.
3047 fn resolve_module_in_lexical_scope(&mut self,
3050 -> ResolveResult<@Module> {
3051 // If this module is an anonymous module, resolve the item in the
3052 // lexical scope. Otherwise, resolve the item from the crate root.
3053 let resolve_result = self.resolve_item_in_lexical_scope(
3054 module_, name, TypeNS, DontSearchThroughModules);
3055 match resolve_result {
3056 Success((target, _)) => {
3057 let bindings = &*target.bindings;
3058 match bindings.type_def.get() {
3060 match type_def.module_def {
3062 error!("!!! (resolving module in lexical \
3063 scope) module wasn't actually a \
3067 Some(module_def) => {
3068 return Success(module_def);
3073 error!("!!! (resolving module in lexical scope) module
3074 wasn't actually a module!");
3080 debug!("(resolving module in lexical scope) indeterminate; \
3082 return Indeterminate;
3085 debug!("(resolving module in lexical scope) failed to \
3092 /// Returns the nearest normal module parent of the given module.
3093 fn get_nearest_normal_module_parent(&mut self, module_: @Module)
3094 -> Option<@Module> {
3095 let mut module_ = module_;
3097 match module_.parent_link {
3098 NoParentLink => return None,
3099 ModuleParentLink(new_module, _) |
3100 BlockParentLink(new_module, _) => {
3101 match new_module.kind.get() {
3102 NormalModuleKind => return Some(new_module),
3106 AnonymousModuleKind => module_ = new_module,
3113 /// Returns the nearest normal module parent of the given module, or the
3114 /// module itself if it is a normal module.
3115 fn get_nearest_normal_module_parent_or_self(&mut self, module_: @Module)
3117 match module_.kind.get() {
3118 NormalModuleKind => return module_,
3122 AnonymousModuleKind => {
3123 match self.get_nearest_normal_module_parent(module_) {
3125 Some(new_module) => new_module
3131 /// Resolves a "module prefix". A module prefix is one or both of (a) `self::`;
3132 /// (b) some chain of `super::`.
3133 /// grammar: (SELF MOD_SEP ) ? (SUPER MOD_SEP) *
3134 fn resolve_module_prefix(&mut self,
3136 module_path: &[Ident])
3137 -> ResolveResult<ModulePrefixResult> {
3138 // Start at the current module if we see `self` or `super`, or at the
3139 // top of the crate otherwise.
3140 let mut containing_module;
3142 let first_module_path_string = token::get_ident(module_path[0]);
3143 if "self" == first_module_path_string.get() {
3145 self.get_nearest_normal_module_parent_or_self(module_);
3147 } else if "super" == first_module_path_string.get() {
3149 self.get_nearest_normal_module_parent_or_self(module_);
3150 i = 0; // We'll handle `super` below.
3152 return Success(NoPrefixFound);
3155 // Now loop through all the `super`s we find.
3156 while i < module_path.len() {
3157 let string = token::get_ident(module_path[i]);
3158 if "super" != string.get() {
3161 debug!("(resolving module prefix) resolving `super` at {}",
3162 self.module_to_str(containing_module));
3163 match self.get_nearest_normal_module_parent(containing_module) {
3164 None => return Failed,
3165 Some(new_module) => {
3166 containing_module = new_module;
3172 debug!("(resolving module prefix) finished resolving prefix at {}",
3173 self.module_to_str(containing_module));
3175 return Success(PrefixFound(containing_module, i));
3178 /// Attempts to resolve the supplied name in the given module for the
3179 /// given namespace. If successful, returns the target corresponding to
3182 /// The boolean returned on success is an indicator of whether this lookup
3183 /// passed through a public re-export proxy.
3184 fn resolve_name_in_module(&mut self,
3187 namespace: Namespace,
3188 name_search_type: NameSearchType)
3189 -> ResolveResult<(Target, bool)> {
3190 debug!("(resolving name in module) resolving `{}` in `{}`",
3191 token::get_ident(name),
3192 self.module_to_str(module_));
3194 // First, check the direct children of the module.
3195 self.populate_module_if_necessary(module_);
3198 let children = module_.children.borrow();
3199 match children.get().find(&name.name) {
3201 if name_bindings.defined_in_namespace(namespace) => {
3202 debug!("(resolving name in module) found node as child");
3203 return Success((Target::new(module_, *name_bindings),
3212 // Next, check the module's imports if necessary.
3214 // If this is a search of all imports, we should be done with glob
3215 // resolution at this point.
3216 if name_search_type == PathSearch {
3217 assert_eq!(module_.glob_count.get(), 0);
3220 // Check the list of resolved imports.
3221 let import_resolutions = module_.import_resolutions.borrow();
3222 match import_resolutions.get().find(&name.name) {
3223 Some(import_resolution) => {
3224 if import_resolution.is_public.get() &&
3225 import_resolution.outstanding_references.get() != 0 {
3226 debug!("(resolving name in module) import \
3227 unresolved; bailing out");
3228 return Indeterminate;
3230 match import_resolution.target_for_namespace(namespace) {
3232 debug!("(resolving name in module) name found, \
3233 but not in namespace {:?}",
3237 debug!("(resolving name in module) resolved to \
3239 self.used_imports.insert((import_resolution.id(namespace), namespace));
3240 return Success((target, true));
3244 None => {} // Continue.
3247 // Finally, search through external children.
3248 if namespace == TypeNS {
3250 let external_module_children =
3251 module_.external_module_children.borrow();
3252 external_module_children.get().find_copy(&name.name)
3258 @Resolver::create_name_bindings_from_module(module);
3259 return Success((Target::new(module_, name_bindings), false));
3264 // We're out of luck.
3265 debug!("(resolving name in module) failed to resolve `{}`",
3266 token::get_ident(name));
3270 fn report_unresolved_imports(&mut self, module_: @Module) {
3271 let index = module_.resolved_import_count.get();
3272 let mut imports = module_.imports.borrow_mut();
3273 let import_count = imports.get().len();
3274 if index != import_count {
3275 let sn = self.session
3277 .span_to_snippet(imports.get()[index].span)
3279 if sn.contains("::") {
3280 self.resolve_error(imports.get()[index].span,
3281 "unresolved import");
3283 let err = format!("unresolved import (maybe you meant `{}::*`?)",
3284 sn.slice(0, sn.len()));
3285 self.resolve_error(imports.get()[index].span, err);
3289 // Descend into children and anonymous children.
3290 self.populate_module_if_necessary(module_);
3293 let children = module_.children.borrow();
3294 for (_, &child_node) in children.get().iter() {
3295 match child_node.get_module_if_available() {
3299 Some(child_module) => {
3300 self.report_unresolved_imports(child_module);
3306 let anonymous_children = module_.anonymous_children.borrow();
3307 for (_, &module_) in anonymous_children.get().iter() {
3308 self.report_unresolved_imports(module_);
3314 // This pass simply determines what all "export" keywords refer to and
3315 // writes the results into the export map.
3317 // FIXME #4953 This pass will be removed once exports change to per-item.
3318 // Then this operation can simply be performed as part of item (or import)
3321 fn record_exports(&mut self) {
3322 let root_module = self.graph_root.get_module();
3323 self.record_exports_for_module_subtree(root_module);
3326 fn record_exports_for_module_subtree(&mut self,
3328 // If this isn't a local krate, then bail out. We don't need to record
3329 // exports for nonlocal crates.
3331 match module_.def_id.get() {
3332 Some(def_id) if def_id.krate == LOCAL_CRATE => {
3334 debug!("(recording exports for module subtree) recording \
3335 exports for local module `{}`",
3336 self.module_to_str(module_));
3339 // Record exports for the root module.
3340 debug!("(recording exports for module subtree) recording \
3341 exports for root module `{}`",
3342 self.module_to_str(module_));
3346 debug!("(recording exports for module subtree) not recording \
3348 self.module_to_str(module_));
3353 self.record_exports_for_module(module_);
3354 self.populate_module_if_necessary(module_);
3357 let children = module_.children.borrow();
3358 for (_, &child_name_bindings) in children.get().iter() {
3359 match child_name_bindings.get_module_if_available() {
3363 Some(child_module) => {
3364 self.record_exports_for_module_subtree(child_module);
3370 let anonymous_children = module_.anonymous_children.borrow();
3371 for (_, &child_module) in anonymous_children.get().iter() {
3372 self.record_exports_for_module_subtree(child_module);
3376 fn record_exports_for_module(&mut self, module_: @Module) {
3377 let mut exports2 = Vec::new();
3379 self.add_exports_for_module(&mut exports2, module_);
3380 match module_.def_id.get() {
3382 let mut export_map2 = self.export_map2.borrow_mut();
3383 export_map2.get().insert(def_id.node, exports2);
3384 debug!("(computing exports) writing exports for {} (some)",
3391 fn add_exports_of_namebindings(&mut self,
3392 exports2: &mut Vec<Export2> ,
3394 namebindings: @NameBindings,
3396 match namebindings.def_for_namespace(ns) {
3398 let name = token::get_name(name);
3399 debug!("(computing exports) YES: export '{}' => {:?}",
3400 name, def_id_of_def(d));
3401 exports2.push(Export2 {
3402 name: name.get().to_str(),
3403 def_id: def_id_of_def(d)
3407 debug!("(computing exports) NO: {:?}", d_opt);
3412 fn add_exports_for_module(&mut self,
3413 exports2: &mut Vec<Export2> ,
3415 let import_resolutions = module_.import_resolutions.borrow();
3416 for (name, importresolution) in import_resolutions.get().iter() {
3417 if !importresolution.is_public.get() {
3420 let xs = [TypeNS, ValueNS];
3421 for &ns in xs.iter() {
3422 match importresolution.target_for_namespace(ns) {
3424 debug!("(computing exports) maybe export '{}'",
3425 token::get_name(*name));
3426 self.add_exports_of_namebindings(exports2,
3439 // We maintain a list of value ribs and type ribs.
3441 // Simultaneously, we keep track of the current position in the module
3442 // graph in the `current_module` pointer. When we go to resolve a name in
3443 // the value or type namespaces, we first look through all the ribs and
3444 // then query the module graph. When we resolve a name in the module
3445 // namespace, we can skip all the ribs (since nested modules are not
3446 // allowed within blocks in Rust) and jump straight to the current module
3449 // Named implementations are handled separately. When we find a method
3450 // call, we consult the module node to find all of the implementations in
3451 // scope. This information is lazily cached in the module node. We then
3452 // generate a fake "implementation scope" containing all the
3453 // implementations thus found, for compatibility with old resolve pass.
3455 fn with_scope(&mut self, name: Option<Ident>, f: |&mut Resolver|) {
3456 let orig_module = self.current_module;
3458 // Move down in the graph.
3464 self.populate_module_if_necessary(orig_module);
3466 let children = orig_module.children.borrow();
3467 match children.get().find(&name.name) {
3469 debug!("!!! (with scope) didn't find `{}` in `{}`",
3470 token::get_ident(name),
3471 self.module_to_str(orig_module));
3473 Some(name_bindings) => {
3474 match (*name_bindings).get_module_if_available() {
3476 debug!("!!! (with scope) didn't find module \
3478 token::get_ident(name),
3479 self.module_to_str(orig_module));
3482 self.current_module = module_;
3492 self.current_module = orig_module;
3495 /// Wraps the given definition in the appropriate number of `def_upvar`
3497 fn upvarify(&mut self,
3498 ribs: &mut Vec<@Rib> ,
3502 -> Option<DefLike> {
3507 DlDef(d @ DefLocal(..)) | DlDef(d @ DefUpvar(..)) |
3508 DlDef(d @ DefArg(..)) | DlDef(d @ DefBinding(..)) => {
3510 is_ty_param = false;
3512 DlDef(d @ DefTyParam(..)) => {
3517 return Some(def_like);
3521 let mut rib_index = rib_index + 1;
3522 while rib_index < ribs.len() {
3523 match ribs[rib_index].kind {
3525 // Nothing to do. Continue.
3527 FunctionRibKind(function_id, body_id) => {
3529 def = DefUpvar(def_id_of_def(def).node,
3535 MethodRibKind(item_id, _) => {
3536 // If the def is a ty param, and came from the parent
3539 DefTyParam(did, _) if {
3540 let def_map = self.def_map.borrow();
3541 def_map.get().find(&did.node).map(|x| *x)
3542 == Some(DefTyParamBinder(item_id))
3548 // This was an attempt to access an upvar inside a
3549 // named function item. This is not allowed, so we
3554 "can't capture dynamic environment in a fn item; \
3555 use the || { ... } closure form instead");
3557 // This was an attempt to use a type parameter outside
3560 self.resolve_error(span,
3561 "attempt to use a type \
3562 argument out of scope");
3569 OpaqueFunctionRibKind => {
3571 // This was an attempt to access an upvar inside a
3572 // named function item. This is not allowed, so we
3577 "can't capture dynamic environment in a fn item; \
3578 use the || { ... } closure form instead");
3580 // This was an attempt to use a type parameter outside
3583 self.resolve_error(span,
3584 "attempt to use a type \
3585 argument out of scope");
3590 ConstantItemRibKind => {
3593 self.resolve_error(span,
3594 "cannot use an outer type \
3595 parameter in this context");
3597 // Still doesn't deal with upvars
3598 self.resolve_error(span,
3599 "attempt to use a non-constant \
3600 value in a constant");
3609 return Some(DlDef(def));
3612 fn search_ribs(&mut self,
3613 ribs: &mut Vec<@Rib> ,
3616 -> Option<DefLike> {
3617 // FIXME #4950: This should not use a while loop.
3618 // FIXME #4950: Try caching?
3620 let mut i = ribs.len();
3624 let bindings = ribs[i].bindings.borrow();
3625 bindings.get().find_copy(&name)
3629 return self.upvarify(ribs, i, def_like, span);
3640 fn resolve_crate(&mut self, krate: &ast::Crate) {
3641 debug!("(resolving crate) starting");
3643 visit::walk_crate(self, krate, ());
3646 fn resolve_item(&mut self, item: &Item) {
3647 debug!("(resolving item) resolving {}",
3648 token::get_ident(item.ident));
3652 // enum item: resolve all the variants' discrs,
3653 // then resolve the ty params
3654 ItemEnum(ref enum_def, ref generics) => {
3655 for variant in (*enum_def).variants.iter() {
3656 for dis_expr in variant.node.disr_expr.iter() {
3657 // resolve the discriminator expr
3659 self.with_constant_rib(|this| {
3660 this.resolve_expr(*dis_expr);
3665 // n.b. the discr expr gets visted twice.
3666 // but maybe it's okay since the first time will signal an
3667 // error if there is one? -- tjc
3668 self.with_type_parameter_rib(HasTypeParameters(generics,
3673 visit::walk_item(this, item, ());
3677 ItemTy(_, ref generics) => {
3678 self.with_type_parameter_rib(HasTypeParameters(generics,
3683 visit::walk_item(this, item, ());
3687 ItemImpl(ref generics,
3688 ref implemented_traits,
3691 self.resolve_implementation(item.id,
3695 methods.as_slice());
3698 ItemTrait(ref generics, ref traits, ref methods) => {
3699 // Create a new rib for the self type.
3700 let self_type_rib = @Rib::new(NormalRibKind);
3702 let mut type_ribs = self.type_ribs.borrow_mut();
3703 type_ribs.get().push(self_type_rib);
3705 // plain insert (no renaming)
3706 let name = self.type_self_ident.name;
3708 let mut bindings = self_type_rib.bindings.borrow_mut();
3709 bindings.get().insert(name, DlDef(DefSelfTy(item.id)));
3712 // Create a new rib for the trait-wide type parameters.
3713 self.with_type_parameter_rib(HasTypeParameters(generics,
3718 this.resolve_type_parameters(&generics.ty_params);
3720 // Resolve derived traits.
3721 for trt in traits.iter() {
3722 this.resolve_trait_reference(item.id, trt, TraitDerivation);
3725 for method in (*methods).iter() {
3726 // Create a new rib for the method-specific type
3729 // FIXME #4951: Do we need a node ID here?
3732 ast::Required(ref ty_m) => {
3733 this.with_type_parameter_rib
3734 (HasTypeParameters(&ty_m.generics,
3736 generics.ty_params.len(),
3737 MethodRibKind(item.id, Required)),
3740 // Resolve the method-specific type
3742 this.resolve_type_parameters(
3743 &ty_m.generics.ty_params);
3745 for argument in ty_m.decl.inputs.iter() {
3746 this.resolve_type(argument.ty);
3749 this.resolve_type(ty_m.decl.output);
3752 ast::Provided(m) => {
3753 this.resolve_method(MethodRibKind(item.id,
3756 generics.ty_params.len())
3762 let mut type_ribs = self.type_ribs.borrow_mut();
3763 type_ribs.get().pop();
3766 ItemStruct(ref struct_def, ref generics) => {
3767 self.resolve_struct(item.id,
3769 struct_def.fields.as_slice());
3772 ItemMod(ref module_) => {
3773 self.with_scope(Some(item.ident), |this| {
3774 this.resolve_module(module_, item.span, item.ident,
3779 ItemForeignMod(ref foreign_module) => {
3780 self.with_scope(Some(item.ident), |this| {
3781 for foreign_item in foreign_module.items.iter() {
3782 match foreign_item.node {
3783 ForeignItemFn(_, ref generics) => {
3784 this.with_type_parameter_rib(
3786 generics, foreign_item.id, 0,
3788 |this| visit::walk_foreign_item(this,
3792 ForeignItemStatic(..) => {
3793 visit::walk_foreign_item(this,
3802 ItemFn(fn_decl, _, _, ref generics, block) => {
3803 self.resolve_function(OpaqueFunctionRibKind,
3809 OpaqueFunctionRibKind),
3814 self.with_constant_rib(|this| {
3815 visit::walk_item(this, item, ());
3820 // do nothing, these are just around to be encoded
3825 fn with_type_parameter_rib(&mut self,
3826 type_parameters: TypeParameters,
3827 f: |&mut Resolver|) {
3828 match type_parameters {
3829 HasTypeParameters(generics, node_id, initial_index,
3832 let function_type_rib = @Rib::new(rib_kind);
3834 let mut type_ribs = self.type_ribs.borrow_mut();
3835 type_ribs.get().push(function_type_rib);
3838 for (index, type_parameter) in generics.ty_params.iter().enumerate() {
3839 let ident = type_parameter.ident;
3840 debug!("with_type_parameter_rib: {} {}", node_id,
3842 let def_like = DlDef(DefTyParam
3843 (local_def(type_parameter.id),
3844 index + initial_index));
3845 // Associate this type parameter with
3846 // the item that bound it
3847 self.record_def(type_parameter.id,
3848 (DefTyParamBinder(node_id), LastMod(AllPublic)));
3849 // plain insert (no renaming)
3850 let mut bindings = function_type_rib.bindings
3852 bindings.get().insert(ident.name, def_like);
3856 NoTypeParameters => {
3863 match type_parameters {
3864 HasTypeParameters(..) => {
3865 let mut type_ribs = self.type_ribs.borrow_mut();
3866 type_ribs.get().pop();
3869 NoTypeParameters => {
3875 fn with_label_rib(&mut self, f: |&mut Resolver|) {
3877 let mut label_ribs = self.label_ribs.borrow_mut();
3878 label_ribs.get().push(@Rib::new(NormalRibKind));
3884 let mut label_ribs = self.label_ribs.borrow_mut();
3885 label_ribs.get().pop();
3889 fn with_constant_rib(&mut self, f: |&mut Resolver|) {
3891 let mut value_ribs = self.value_ribs.borrow_mut();
3892 let mut type_ribs = self.type_ribs.borrow_mut();
3893 value_ribs.get().push(@Rib::new(ConstantItemRibKind));
3894 type_ribs.get().push(@Rib::new(ConstantItemRibKind));
3898 let mut value_ribs = self.value_ribs.borrow_mut();
3899 let mut type_ribs = self.type_ribs.borrow_mut();
3900 type_ribs.get().pop();
3901 value_ribs.get().pop();
3905 fn resolve_function(&mut self,
3907 optional_declaration: Option<P<FnDecl>>,
3908 type_parameters: TypeParameters,
3910 // Create a value rib for the function.
3911 let function_value_rib = @Rib::new(rib_kind);
3913 let mut value_ribs = self.value_ribs.borrow_mut();
3914 value_ribs.get().push(function_value_rib);
3917 // Create a label rib for the function.
3919 let mut label_ribs = self.label_ribs.borrow_mut();
3920 let function_label_rib = @Rib::new(rib_kind);
3921 label_ribs.get().push(function_label_rib);
3924 // If this function has type parameters, add them now.
3925 self.with_type_parameter_rib(type_parameters, |this| {
3926 // Resolve the type parameters.
3927 match type_parameters {
3928 NoTypeParameters => {
3931 HasTypeParameters(ref generics, _, _, _) => {
3932 this.resolve_type_parameters(&generics.ty_params);
3936 // Add each argument to the rib.
3937 match optional_declaration {
3941 Some(declaration) => {
3942 for argument in declaration.inputs.iter() {
3943 let binding_mode = ArgumentIrrefutableMode;
3944 this.resolve_pattern(argument.pat,
3948 this.resolve_type(argument.ty);
3950 debug!("(resolving function) recorded argument");
3953 this.resolve_type(declaration.output);
3957 // Resolve the function body.
3958 this.resolve_block(block);
3960 debug!("(resolving function) leaving function");
3963 let mut label_ribs = self.label_ribs.borrow_mut();
3964 label_ribs.get().pop();
3966 let mut value_ribs = self.value_ribs.borrow_mut();
3967 value_ribs.get().pop();
3970 fn resolve_type_parameters(&mut self,
3971 type_parameters: &OptVec<TyParam>) {
3972 for type_parameter in type_parameters.iter() {
3973 for bound in type_parameter.bounds.iter() {
3974 self.resolve_type_parameter_bound(type_parameter.id, bound);
3976 match type_parameter.default {
3977 Some(ty) => self.resolve_type(ty),
3983 fn resolve_type_parameter_bound(&mut self,
3985 type_parameter_bound: &TyParamBound) {
3986 match *type_parameter_bound {
3987 TraitTyParamBound(ref tref) => {
3988 self.resolve_trait_reference(id, tref, TraitBoundingTypeParameter)
3990 RegionTyParamBound => {}
3994 fn resolve_trait_reference(&mut self,
3996 trait_reference: &TraitRef,
3997 reference_type: TraitReferenceType) {
3998 match self.resolve_path(id, &trait_reference.path, TypeNS, true) {
4000 let path_str = self.path_idents_to_str(&trait_reference.path);
4001 let usage_str = match reference_type {
4002 TraitBoundingTypeParameter => "bound type parameter with",
4003 TraitImplementation => "implement",
4004 TraitDerivation => "derive"
4007 let msg = format!("attempt to {} a nonexistent trait `{}`", usage_str, path_str);
4008 self.resolve_error(trait_reference.path.span, msg);
4011 debug!("(resolving trait) found trait def: {:?}", def);
4012 self.record_def(trait_reference.ref_id, def);
4017 fn resolve_struct(&mut self,
4019 generics: &Generics,
4020 fields: &[StructField]) {
4021 let mut ident_map: HashMap<ast::Ident, &StructField> = HashMap::new();
4022 for field in fields.iter() {
4023 match field.node.kind {
4024 NamedField(ident, _) => {
4025 match ident_map.find(&ident) {
4026 Some(&prev_field) => {
4027 let ident_str = token::get_ident(ident);
4028 self.resolve_error(field.span,
4029 format!("field `{}` is already declared", ident_str));
4030 self.session.span_note(prev_field.span,
4031 "previously declared here");
4034 ident_map.insert(ident, field);
4042 // If applicable, create a rib for the type parameters.
4043 self.with_type_parameter_rib(HasTypeParameters(generics,
4046 OpaqueFunctionRibKind),
4048 // Resolve the type parameters.
4049 this.resolve_type_parameters(&generics.ty_params);
4052 for field in fields.iter() {
4053 this.resolve_type(field.node.ty);
4058 // Does this really need to take a RibKind or is it always going
4059 // to be NormalRibKind?
4060 fn resolve_method(&mut self,
4063 outer_type_parameter_count: uint) {
4064 let method_generics = &method.generics;
4065 let type_parameters =
4066 HasTypeParameters(method_generics,
4068 outer_type_parameter_count,
4071 self.resolve_function(rib_kind, Some(method.decl), type_parameters, method.body);
4074 fn resolve_implementation(&mut self,
4076 generics: &Generics,
4077 opt_trait_reference: &Option<TraitRef>,
4079 methods: &[@Method]) {
4080 // If applicable, create a rib for the type parameters.
4081 let outer_type_parameter_count = generics.ty_params.len();
4082 self.with_type_parameter_rib(HasTypeParameters(generics,
4087 // Resolve the type parameters.
4088 this.resolve_type_parameters(&generics.ty_params);
4090 // Resolve the trait reference, if necessary.
4091 let original_trait_refs;
4092 match opt_trait_reference {
4093 &Some(ref trait_reference) => {
4094 this.resolve_trait_reference(id, trait_reference,
4095 TraitImplementation);
4097 // Record the current set of trait references.
4098 let mut new_trait_refs = Vec::new();
4100 let def_map = this.def_map.borrow();
4101 let r = def_map.get().find(&trait_reference.ref_id);
4102 for &def in r.iter() {
4103 new_trait_refs.push(def_id_of_def(*def));
4106 original_trait_refs = Some(replace(
4107 &mut this.current_trait_refs,
4108 Some(new_trait_refs)));
4111 original_trait_refs = None;
4115 // Resolve the self type.
4116 this.resolve_type(self_type);
4118 for method in methods.iter() {
4119 // We also need a new scope for the method-specific
4121 this.resolve_method(MethodRibKind(
4123 Provided(method.id)),
4125 outer_type_parameter_count);
4127 let borrowed_type_parameters = &method.tps;
4128 self.resolve_function(MethodRibKind(
4130 Provided(method.id)),
4133 (borrowed_type_parameters,
4135 outer_type_parameter_count,
4141 // Restore the original trait references.
4142 match original_trait_refs {
4143 Some(r) => { this.current_trait_refs = r; }
4149 fn resolve_module(&mut self, module: &Mod, _span: Span,
4150 _name: Ident, id: NodeId) {
4151 // Write the implementations in scope into the module metadata.
4152 debug!("(resolving module) resolving module ID {}", id);
4153 visit::walk_mod(self, module, ());
4156 fn resolve_local(&mut self, local: &Local) {
4157 // Resolve the type.
4158 self.resolve_type(local.ty);
4160 // Resolve the initializer, if necessary.
4165 Some(initializer) => {
4166 self.resolve_expr(initializer);
4170 // Resolve the pattern.
4171 self.resolve_pattern(local.pat, LocalIrrefutableMode, None);
4174 // build a map from pattern identifiers to binding-info's.
4175 // this is done hygienically. This could arise for a macro
4176 // that expands into an or-pattern where one 'x' was from the
4177 // user and one 'x' came from the macro.
4178 fn binding_mode_map(&mut self, pat: @Pat) -> BindingMap {
4179 let mut result = HashMap::new();
4180 pat_bindings(self.def_map, pat, |binding_mode, _id, sp, path| {
4181 let name = mtwt::resolve(path_to_ident(path));
4183 binding_info {span: sp,
4184 binding_mode: binding_mode});
4189 // check that all of the arms in an or-pattern have exactly the
4190 // same set of bindings, with the same binding modes for each.
4191 fn check_consistent_bindings(&mut self, arm: &Arm) {
4192 if arm.pats.len() == 0 {
4195 let map_0 = self.binding_mode_map(*arm.pats.get(0));
4196 for (i, p) in arm.pats.iter().enumerate() {
4197 let map_i = self.binding_mode_map(*p);
4199 for (&key, &binding_0) in map_0.iter() {
4200 match map_i.find(&key) {
4204 format!("variable `{}` from pattern \\#1 is \
4205 not bound in pattern \\#{}",
4206 token::get_name(key),
4209 Some(binding_i) => {
4210 if binding_0.binding_mode != binding_i.binding_mode {
4213 format!("variable `{}` is bound with different \
4214 mode in pattern \\#{} than in pattern \\#1",
4215 token::get_name(key),
4222 for (&key, &binding) in map_i.iter() {
4223 if !map_0.contains_key(&key) {
4226 format!("variable `{}` from pattern \\#{} is \
4227 not bound in pattern \\#1",
4228 token::get_name(key),
4235 fn resolve_arm(&mut self, arm: &Arm) {
4237 let mut value_ribs = self.value_ribs.borrow_mut();
4238 value_ribs.get().push(@Rib::new(NormalRibKind));
4241 let mut bindings_list = HashMap::new();
4242 for pattern in arm.pats.iter() {
4243 self.resolve_pattern(*pattern,
4245 Some(&mut bindings_list));
4248 // This has to happen *after* we determine which
4249 // pat_idents are variants
4250 self.check_consistent_bindings(arm);
4252 visit::walk_expr_opt(self, arm.guard, ());
4253 self.resolve_expr(arm.body);
4255 let mut value_ribs = self.value_ribs.borrow_mut();
4256 value_ribs.get().pop();
4259 fn resolve_block(&mut self, block: &Block) {
4260 debug!("(resolving block) entering block");
4262 let mut value_ribs = self.value_ribs.borrow_mut();
4263 value_ribs.get().push(@Rib::new(NormalRibKind));
4266 // Move down in the graph, if there's an anonymous module rooted here.
4267 let orig_module = self.current_module;
4268 let anonymous_children = self.current_module
4271 match anonymous_children.get().find(&block.id) {
4272 None => { /* Nothing to do. */ }
4273 Some(&anonymous_module) => {
4274 debug!("(resolving block) found anonymous module, moving \
4276 self.current_module = anonymous_module;
4280 // Descend into the block.
4281 visit::walk_block(self, block, ());
4284 self.current_module = orig_module;
4286 let mut value_ribs = self.value_ribs.borrow_mut();
4287 value_ribs.get().pop();
4288 debug!("(resolving block) leaving block");
4291 fn resolve_type(&mut self, ty: &Ty) {
4293 // Like path expressions, the interpretation of path types depends
4294 // on whether the path has multiple elements in it or not.
4296 TyPath(ref path, ref bounds, path_id) => {
4297 // This is a path in the type namespace. Walk through scopes
4299 let mut result_def = None;
4301 // First, check to see whether the name is a primitive type.
4302 if path.segments.len() == 1 {
4303 let id = path.segments.last().unwrap().identifier;
4305 match self.primitive_type_table
4309 Some(&primitive_type) => {
4311 Some((DefPrimTy(primitive_type), LastMod(AllPublic)));
4315 .any(|s| !s.lifetimes.is_empty()) {
4316 self.session.span_err(path.span,
4317 "lifetime parameters \
4318 are not allowed on \
4320 } else if path.segments
4322 .any(|s| s.types.len() > 0) {
4323 self.session.span_err(path.span,
4324 "type parameters are \
4325 not allowed on this \
4337 match self.resolve_path(ty.id, path, TypeNS, true) {
4339 debug!("(resolving type) resolved `{}` to \
4341 token::get_ident(path.segments
4345 result_def = Some(def);
4352 Some(_) => {} // Continue.
4357 // Write the result into the def map.
4358 debug!("(resolving type) writing resolution for `{}` \
4360 self.path_idents_to_str(path),
4362 self.record_def(path_id, def);
4365 let msg = format!("use of undeclared type name `{}`",
4366 self.path_idents_to_str(path));
4367 self.resolve_error(ty.span, msg);
4371 bounds.as_ref().map(|bound_vec| {
4372 for bound in bound_vec.iter() {
4373 self.resolve_type_parameter_bound(ty.id, bound);
4379 c.bounds.as_ref().map(|bounds| {
4380 for bound in bounds.iter() {
4381 self.resolve_type_parameter_bound(ty.id, bound);
4384 visit::walk_ty(self, ty, ());
4388 // Just resolve embedded types.
4389 visit::walk_ty(self, ty, ());
4394 fn resolve_pattern(&mut self,
4396 mode: PatternBindingMode,
4397 // Maps idents to the node ID for the (outermost)
4398 // pattern that binds them
4399 mut bindings_list: Option<&mut HashMap<Name,NodeId>>) {
4400 let pat_id = pattern.id;
4401 walk_pat(pattern, |pattern| {
4402 match pattern.node {
4403 PatIdent(binding_mode, ref path, _)
4404 if !path.global && path.segments.len() == 1 => {
4406 // The meaning of pat_ident with no type parameters
4407 // depends on whether an enum variant or unit-like struct
4408 // with that name is in scope. The probing lookup has to
4409 // be careful not to emit spurious errors. Only matching
4410 // patterns (match) can match nullary variants or
4411 // unit-like structs. For binding patterns (let), matching
4412 // such a value is simply disallowed (since it's rarely
4415 let ident = path.segments.get(0).identifier;
4416 let renamed = mtwt::resolve(ident);
4418 match self.resolve_bare_identifier_pattern(ident) {
4419 FoundStructOrEnumVariant(def, lp)
4420 if mode == RefutableMode => {
4421 debug!("(resolving pattern) resolving `{}` to \
4422 struct or enum variant",
4423 token::get_name(renamed));
4425 self.enforce_default_binding_mode(
4429 self.record_def(pattern.id, (def, lp));
4431 FoundStructOrEnumVariant(..) => {
4432 self.resolve_error(pattern.span,
4433 format!("declaration of `{}` \
4435 variant or unit-like \
4437 token::get_name(renamed)));
4439 FoundConst(def, lp) if mode == RefutableMode => {
4440 debug!("(resolving pattern) resolving `{}` to \
4442 token::get_name(renamed));
4444 self.enforce_default_binding_mode(
4448 self.record_def(pattern.id, (def, lp));
4451 self.resolve_error(pattern.span,
4452 "only irrefutable patterns \
4455 BareIdentifierPatternUnresolved => {
4456 debug!("(resolving pattern) binding `{}`",
4457 token::get_name(renamed));
4459 let def = match mode {
4461 // For pattern arms, we must use
4462 // `def_binding` definitions.
4464 DefBinding(pattern.id, binding_mode)
4466 LocalIrrefutableMode => {
4467 // But for locals, we use `def_local`.
4468 DefLocal(pattern.id, binding_mode)
4470 ArgumentIrrefutableMode => {
4471 // And for function arguments, `def_arg`.
4472 DefArg(pattern.id, binding_mode)
4476 // Record the definition so that later passes
4477 // will be able to distinguish variants from
4478 // locals in patterns.
4480 self.record_def(pattern.id, (def, LastMod(AllPublic)));
4482 // Add the binding to the local ribs, if it
4483 // doesn't already exist in the bindings list. (We
4484 // must not add it if it's in the bindings list
4485 // because that breaks the assumptions later
4486 // passes make about or-patterns.)
4488 match bindings_list {
4489 Some(ref mut bindings_list)
4490 if !bindings_list.contains_key(&renamed) => {
4491 let this = &mut *self;
4493 let mut value_ribs =
4494 this.value_ribs.borrow_mut();
4495 let last_rib = value_ribs.get()[
4496 value_ribs.get().len() - 1];
4498 last_rib.bindings.borrow_mut();
4499 bindings.get().insert(renamed,
4502 bindings_list.insert(renamed, pat_id);
4504 Some(ref mut b) => {
4505 if b.find(&renamed) == Some(&pat_id) {
4506 // Then this is a duplicate variable
4507 // in the same disjunct, which is an
4509 self.resolve_error(pattern.span,
4510 format!("identifier `{}` is bound more \
4511 than once in the same pattern",
4512 path_to_str(path)));
4514 // Not bound in the same pattern: do nothing
4517 let this = &mut *self;
4519 let mut value_ribs =
4520 this.value_ribs.borrow_mut();
4521 let last_rib = value_ribs.get()[
4522 value_ribs.get().len() - 1];
4524 last_rib.bindings.borrow_mut();
4525 bindings.get().insert(renamed,
4533 // Check the types in the path pattern.
4534 for &ty in path.segments
4536 .flat_map(|seg| seg.types.iter()) {
4537 self.resolve_type(ty);
4541 PatIdent(binding_mode, ref path, _) => {
4542 // This must be an enum variant, struct, or constant.
4543 match self.resolve_path(pat_id, path, ValueNS, false) {
4544 Some(def @ (DefVariant(..), _)) |
4545 Some(def @ (DefStruct(..), _)) => {
4546 self.record_def(pattern.id, def);
4548 Some(def @ (DefStatic(..), _)) => {
4549 self.enforce_default_binding_mode(
4553 self.record_def(pattern.id, def);
4558 format!("`{}` is not an enum variant or constant",
4560 path.segments.last().unwrap().identifier)))
4563 self.resolve_error(path.span,
4564 "unresolved enum variant");
4568 // Check the types in the path pattern.
4569 for &ty in path.segments
4571 .flat_map(|s| s.types.iter()) {
4572 self.resolve_type(ty);
4576 PatEnum(ref path, _) => {
4577 // This must be an enum variant, struct or const.
4578 match self.resolve_path(pat_id, path, ValueNS, false) {
4579 Some(def @ (DefFn(..), _)) |
4580 Some(def @ (DefVariant(..), _)) |
4581 Some(def @ (DefStruct(..), _)) |
4582 Some(def @ (DefStatic(..), _)) => {
4583 self.record_def(pattern.id, def);
4586 self.resolve_error(path.span,
4587 format!("`{}` is not an enum variant, struct or const",
4588 token::get_ident(path.segments
4593 self.resolve_error(path.span,
4594 format!("unresolved enum variant, struct or const `{}`",
4595 token::get_ident(path.segments
4601 // Check the types in the path pattern.
4602 for &ty in path.segments
4604 .flat_map(|s| s.types.iter()) {
4605 self.resolve_type(ty);
4610 self.resolve_expr(expr);
4613 PatRange(first_expr, last_expr) => {
4614 self.resolve_expr(first_expr);
4615 self.resolve_expr(last_expr);
4618 PatStruct(ref path, _, _) => {
4619 match self.resolve_path(pat_id, path, TypeNS, false) {
4620 Some((DefTy(class_id), lp))
4621 if self.structs.contains(&class_id) => {
4622 let class_def = DefStruct(class_id);
4623 self.record_def(pattern.id, (class_def, lp));
4625 Some(definition @ (DefStruct(class_id), _)) => {
4626 assert!(self.structs.contains(&class_id));
4627 self.record_def(pattern.id, definition);
4629 Some(definition @ (DefVariant(_, variant_id, _), _))
4630 if self.structs.contains(&variant_id) => {
4631 self.record_def(pattern.id, definition);
4634 debug!("(resolving pattern) didn't find struct \
4635 def: {:?}", result);
4636 let msg = format!("`{}` does not name a structure",
4637 self.path_idents_to_str(path));
4638 self.resolve_error(path.span, msg);
4651 fn resolve_bare_identifier_pattern(&mut self, name: Ident)
4653 BareIdentifierPatternResolution {
4654 match self.resolve_item_in_lexical_scope(self.current_module,
4657 SearchThroughModules) {
4658 Success((target, _)) => {
4659 debug!("(resolve bare identifier pattern) succeeded in \
4660 finding {} at {:?}",
4661 token::get_ident(name),
4662 target.bindings.value_def.get());
4663 match target.bindings.value_def.get() {
4665 fail!("resolved name in the value namespace to a \
4666 set of name bindings with no def?!");
4669 // For the two success cases, this lookup can be
4670 // considered as not having a private component because
4671 // the lookup happened only within the current module.
4673 def @ DefVariant(..) | def @ DefStruct(..) => {
4674 return FoundStructOrEnumVariant(def, LastMod(AllPublic));
4676 def @ DefStatic(_, false) => {
4677 return FoundConst(def, LastMod(AllPublic));
4680 return BareIdentifierPatternUnresolved;
4688 fail!("unexpected indeterminate result");
4692 debug!("(resolve bare identifier pattern) failed to find {}",
4693 token::get_ident(name));
4694 return BareIdentifierPatternUnresolved;
4699 /// If `check_ribs` is true, checks the local definitions first; i.e.
4700 /// doesn't skip straight to the containing module.
4701 fn resolve_path(&mut self,
4704 namespace: Namespace,
4705 check_ribs: bool) -> Option<(Def, LastPrivate)> {
4706 // First, resolve the types.
4707 for &ty in path.segments.iter().flat_map(|s| s.types.iter()) {
4708 self.resolve_type(ty);
4712 return self.resolve_crate_relative_path(path, namespace);
4715 let unqualified_def =
4716 self.resolve_identifier(path.segments
4723 if path.segments.len() > 1 {
4724 let def = self.resolve_module_relative_path(path, namespace);
4725 match (def, unqualified_def) {
4726 (Some((d, _)), Some((ud, _))) if d == ud => {
4727 self.session.add_lint(UnnecessaryQualification,
4730 ~"unnecessary qualification");
4738 return unqualified_def;
4741 // resolve a single identifier (used as a varref)
4742 fn resolve_identifier(&mut self,
4744 namespace: Namespace,
4747 -> Option<(Def, LastPrivate)> {
4749 match self.resolve_identifier_in_local_ribs(identifier,
4753 return Some((def, LastMod(AllPublic)));
4761 return self.resolve_item_by_identifier_in_lexical_scope(identifier,
4765 // FIXME #4952: Merge me with resolve_name_in_module?
4766 fn resolve_definition_of_name_in_module(&mut self,
4767 containing_module: @Module,
4769 namespace: Namespace)
4771 // First, search children.
4772 self.populate_module_if_necessary(containing_module);
4775 let children = containing_module.children.borrow();
4776 match children.get().find(&name.name) {
4777 Some(child_name_bindings) => {
4778 match child_name_bindings.def_for_namespace(namespace) {
4780 // Found it. Stop the search here.
4781 let p = child_name_bindings.defined_in_public_namespace(
4783 let lp = if p {LastMod(AllPublic)} else {
4784 LastMod(DependsOn(def_id_of_def(def)))
4786 return ChildNameDefinition(def, lp);
4795 // Next, search import resolutions.
4796 let import_resolutions = containing_module.import_resolutions
4798 match import_resolutions.get().find(&name.name) {
4799 Some(import_resolution) if import_resolution.is_public.get() => {
4800 match (*import_resolution).target_for_namespace(namespace) {
4802 match target.bindings.def_for_namespace(namespace) {
4805 let id = import_resolution.id(namespace);
4806 self.used_imports.insert((id, namespace));
4807 return ImportNameDefinition(def, LastMod(AllPublic));
4810 // This can happen with external impls, due to
4811 // the imperfect way we read the metadata.
4818 Some(..) | None => {} // Continue.
4821 // Finally, search through external children.
4822 if namespace == TypeNS {
4824 let external_module_children =
4825 containing_module.external_module_children.borrow();
4826 external_module_children.get().find_copy(&name.name)
4831 match module.def_id.get() {
4832 None => {} // Continue.
4834 let lp = if module.is_public {LastMod(AllPublic)} else {
4835 LastMod(DependsOn(def_id))
4837 return ChildNameDefinition(DefMod(def_id), lp);
4844 return NoNameDefinition;
4847 // resolve a "module-relative" path, e.g. a::b::c
4848 fn resolve_module_relative_path(&mut self,
4850 namespace: Namespace)
4851 -> Option<(Def, LastPrivate)> {
4852 let module_path_idents = path.segments.init().map(|ps| ps.identifier);
4854 let containing_module;
4856 match self.resolve_module_path(self.current_module,
4862 let msg = format!("use of undeclared module `{}`",
4863 self.idents_to_str(module_path_idents));
4864 self.resolve_error(path.span, msg);
4869 fail!("indeterminate unexpected");
4872 Success((resulting_module, resulting_last_private)) => {
4873 containing_module = resulting_module;
4874 last_private = resulting_last_private;
4878 let ident = path.segments.last().unwrap().identifier;
4879 let def = match self.resolve_definition_of_name_in_module(containing_module,
4882 NoNameDefinition => {
4883 // We failed to resolve the name. Report an error.
4886 ChildNameDefinition(def, lp) | ImportNameDefinition(def, lp) => {
4887 (def, last_private.or(lp))
4890 match containing_module.kind.get() {
4891 TraitModuleKind | ImplModuleKind => {
4892 let method_map = self.method_map.borrow();
4893 match method_map.get().find(&ident.name) {
4895 match containing_module.def_id.get() {
4896 Some(def_id) if s.contains(&def_id) => {
4897 debug!("containing module was a trait or impl \
4898 and name was a method -> not resolved");
4912 /// Invariant: This must be called only during main resolution, not during
4913 /// import resolution.
4914 fn resolve_crate_relative_path(&mut self,
4916 namespace: Namespace)
4917 -> Option<(Def, LastPrivate)> {
4918 let module_path_idents = path.segments.init().map(|ps| ps.identifier);
4920 let root_module = self.graph_root.get_module();
4922 let containing_module;
4924 match self.resolve_module_path_from_root(root_module,
4929 LastMod(AllPublic)) {
4931 let msg = format!("use of undeclared module `::{}`",
4932 self.idents_to_str(module_path_idents));
4933 self.resolve_error(path.span, msg);
4938 fail!("indeterminate unexpected");
4941 Success((resulting_module, resulting_last_private)) => {
4942 containing_module = resulting_module;
4943 last_private = resulting_last_private;
4947 let name = path.segments.last().unwrap().identifier;
4948 match self.resolve_definition_of_name_in_module(containing_module,
4951 NoNameDefinition => {
4952 // We failed to resolve the name. Report an error.
4955 ChildNameDefinition(def, lp) | ImportNameDefinition(def, lp) => {
4956 return Some((def, last_private.or(lp)));
4961 fn resolve_identifier_in_local_ribs(&mut self,
4963 namespace: Namespace,
4966 // Check the local set of ribs.
4970 let renamed = mtwt::resolve(ident);
4971 let mut value_ribs = self.value_ribs.borrow_mut();
4972 search_result = self.search_ribs(value_ribs.get(),
4977 let name = ident.name;
4978 let mut type_ribs = self.type_ribs.borrow_mut();
4979 search_result = self.search_ribs(type_ribs.get(),
4985 match search_result {
4986 Some(DlDef(def)) => {
4987 debug!("(resolving path in local ribs) resolved `{}` to \
4989 token::get_ident(ident),
4993 Some(DlField) | Some(DlImpl(_)) | None => {
4999 fn resolve_item_by_identifier_in_lexical_scope(&mut self,
5001 namespace: Namespace)
5002 -> Option<(Def, LastPrivate)> {
5004 match self.resolve_item_in_lexical_scope(self.current_module,
5007 DontSearchThroughModules) {
5008 Success((target, _)) => {
5009 match (*target.bindings).def_for_namespace(namespace) {
5011 // This can happen if we were looking for a type and
5012 // found a module instead. Modules don't have defs.
5013 debug!("(resolving item path by identifier in lexical \
5014 scope) failed to resolve {} after success...",
5015 token::get_ident(ident));
5019 debug!("(resolving item path in lexical scope) \
5020 resolved `{}` to item",
5021 token::get_ident(ident));
5022 // This lookup is "all public" because it only searched
5023 // for one identifier in the current module (couldn't
5024 // have passed through reexports or anything like that.
5025 return Some((def, LastMod(AllPublic)));
5030 fail!("unexpected indeterminate result");
5033 debug!("(resolving item path by identifier in lexical scope) \
5034 failed to resolve {}", token::get_ident(ident));
5040 fn with_no_errors<T>(&mut self, f: |&mut Resolver| -> T) -> T {
5041 self.emit_errors = false;
5043 self.emit_errors = true;
5047 fn resolve_error(&mut self, span: Span, s: &str) {
5048 if self.emit_errors {
5049 self.session.span_err(span, s);
5053 fn find_best_match_for_name(&mut self, name: &str, max_distance: uint)
5055 let this = &mut *self;
5057 let mut maybes: Vec<token::InternedString> = Vec::new();
5058 let mut values: Vec<uint> = Vec::new();
5061 let value_ribs = this.value_ribs.borrow();
5062 value_ribs.get().len()
5066 let value_ribs = this.value_ribs.borrow();
5067 let bindings = value_ribs.get()[j].bindings.borrow();
5068 for (&k, _) in bindings.get().iter() {
5069 maybes.push(token::get_name(k));
5070 values.push(uint::MAX);
5074 let mut smallest = 0;
5075 for (i, other) in maybes.iter().enumerate() {
5076 values[i] = name.lev_distance(other.get());
5078 if values[i] <= values[smallest] {
5083 if values.len() > 0 &&
5084 values[smallest] != uint::MAX &&
5085 values[smallest] < name.len() + 2 &&
5086 values[smallest] <= max_distance &&
5087 name != maybes[smallest].get() {
5089 Some(maybes[smallest].get().to_str())
5096 fn resolve_expr(&mut self, expr: &Expr) {
5097 // First, record candidate traits for this expression if it could
5098 // result in the invocation of a method call.
5100 self.record_candidate_traits_for_expr_if_necessary(expr);
5102 // Next, resolve the node.
5104 // The interpretation of paths depends on whether the path has
5105 // multiple elements in it or not.
5107 ExprPath(ref path) => {
5108 // This is a local path in the value namespace. Walk through
5109 // scopes looking for it.
5111 match self.resolve_path(expr.id, path, ValueNS, true) {
5113 // Write the result into the def map.
5114 debug!("(resolving expr) resolved `{}`",
5115 self.path_idents_to_str(path));
5117 // First-class methods are not supported yet; error
5120 (DefMethod(..), _) => {
5121 self.resolve_error(expr.span,
5122 "first-class methods \
5123 are not supported");
5124 self.session.span_note(expr.span,
5132 self.record_def(expr.id, def);
5135 let wrong_name = self.path_idents_to_str(path);
5136 // Be helpful if the name refers to a struct
5137 // (The pattern matching def_tys where the id is in self.structs
5138 // matches on regular structs while excluding tuple- and enum-like
5139 // structs, which wouldn't result in this error.)
5140 match self.with_no_errors(|this|
5141 this.resolve_path(expr.id, path, TypeNS, false)) {
5142 Some((DefTy(struct_id), _))
5143 if self.structs.contains(&struct_id) => {
5144 self.resolve_error(expr.span,
5145 format!("`{}` is a structure name, but \
5147 uses it like a function name",
5150 self.session.span_note(expr.span,
5151 format!("Did you mean to write: \
5152 `{} \\{ /* fields */ \\}`?",
5157 // limit search to 5 to reduce the number
5158 // of stupid suggestions
5159 match self.find_best_match_for_name(wrong_name, 5) {
5161 self.resolve_error(expr.span,
5162 format!("unresolved name `{}`. \
5163 Did you mean `{}`?",
5167 self.resolve_error(expr.span,
5168 format!("unresolved name `{}`.",
5176 visit::walk_expr(self, expr, ());
5179 ExprFnBlock(fn_decl, block) |
5180 ExprProc(fn_decl, block) => {
5181 self.resolve_function(FunctionRibKind(expr.id, block.id),
5182 Some(fn_decl), NoTypeParameters,
5186 ExprStruct(ref path, _, _) => {
5187 // Resolve the path to the structure it goes to.
5188 match self.resolve_path(expr.id, path, TypeNS, false) {
5189 Some((DefTy(class_id), lp)) | Some((DefStruct(class_id), lp))
5190 if self.structs.contains(&class_id) => {
5191 let class_def = DefStruct(class_id);
5192 self.record_def(expr.id, (class_def, lp));
5194 Some(definition @ (DefVariant(_, class_id, _), _))
5195 if self.structs.contains(&class_id) => {
5196 self.record_def(expr.id, definition);
5199 debug!("(resolving expression) didn't find struct \
5200 def: {:?}", result);
5201 let msg = format!("`{}` does not name a structure",
5202 self.path_idents_to_str(path));
5203 self.resolve_error(path.span, msg);
5207 visit::walk_expr(self, expr, ());
5210 ExprLoop(_, Some(label)) => {
5211 self.with_label_rib(|this| {
5212 let def_like = DlDef(DefLabel(expr.id));
5214 let mut label_ribs = this.label_ribs.borrow_mut();
5215 let rib = label_ribs.get()[label_ribs.get().len() -
5217 let mut bindings = rib.bindings.borrow_mut();
5218 let renamed = mtwt::resolve(label);
5219 bindings.get().insert(renamed, def_like);
5222 visit::walk_expr(this, expr, ());
5226 ExprForLoop(..) => fail!("non-desugared expr_for_loop"),
5228 ExprBreak(Some(label)) | ExprAgain(Some(label)) => {
5229 let mut label_ribs = self.label_ribs.borrow_mut();
5230 let renamed = mtwt::resolve(label);
5231 match self.search_ribs(label_ribs.get(), renamed, expr.span) {
5233 self.resolve_error(expr.span,
5234 format!("use of undeclared label `{}`",
5235 token::get_ident(label))),
5236 Some(DlDef(def @ DefLabel(_))) => {
5237 // Since this def is a label, it is never read.
5238 self.record_def(expr.id, (def, LastMod(AllPublic)))
5241 self.session.span_bug(expr.span,
5242 "label wasn't mapped to a \
5249 visit::walk_expr(self, expr, ());
5254 fn record_candidate_traits_for_expr_if_necessary(&mut self, expr: &Expr) {
5256 ExprField(_, ident, _) => {
5257 // FIXME(#6890): Even though you can't treat a method like a
5258 // field, we need to add any trait methods we find that match
5259 // the field name so that we can do some nice error reporting
5260 // later on in typeck.
5261 let traits = self.search_for_traits_containing_method(ident);
5262 self.trait_map.insert(expr.id, traits);
5264 ExprMethodCall(ident, _, _) => {
5265 debug!("(recording candidate traits for expr) recording \
5268 let traits = self.search_for_traits_containing_method(ident);
5269 self.trait_map.insert(expr.id, traits);
5277 fn search_for_traits_containing_method(&mut self, name: Ident) -> Vec<DefId> {
5278 debug!("(searching for traits containing method) looking for '{}'",
5279 token::get_ident(name));
5281 let mut found_traits = Vec::new();
5282 let mut search_module = self.current_module;
5283 let method_map = self.method_map.borrow();
5284 match method_map.get().find(&name.name) {
5285 Some(candidate_traits) => loop {
5286 // Look for the current trait.
5287 match self.current_trait_refs {
5288 Some(ref trait_def_ids) => {
5289 for trait_def_id in trait_def_ids.iter() {
5290 if candidate_traits.contains(trait_def_id) {
5291 self.add_trait_info(&mut found_traits,
5302 // Look for trait children.
5303 self.populate_module_if_necessary(search_module);
5305 let children = search_module.children.borrow();
5306 for (_, &child_names) in children.get().iter() {
5307 let def = match child_names.def_for_namespace(TypeNS) {
5311 let trait_def_id = match def {
5312 DefTrait(trait_def_id) => trait_def_id,
5315 if candidate_traits.contains(&trait_def_id) {
5316 self.add_trait_info(&mut found_traits, trait_def_id,
5321 // Look for imports.
5322 let import_resolutions = search_module.import_resolutions
5324 for (_, &import) in import_resolutions.get().iter() {
5325 let target = match import.target_for_namespace(TypeNS) {
5327 Some(target) => target,
5329 let did = match target.bindings.def_for_namespace(TypeNS) {
5330 Some(DefTrait(trait_def_id)) => trait_def_id,
5331 Some(..) | None => continue,
5333 if candidate_traits.contains(&did) {
5334 self.add_trait_info(&mut found_traits, did, name);
5335 self.used_imports.insert((import.type_id.get(), TypeNS));
5339 match search_module.parent_link {
5340 NoParentLink | ModuleParentLink(..) => break,
5341 BlockParentLink(parent_module, _) => {
5342 search_module = parent_module;
5349 return found_traits;
5352 fn add_trait_info(&self,
5353 found_traits: &mut Vec<DefId> ,
5354 trait_def_id: DefId,
5356 debug!("(adding trait info) found trait {}:{} for method '{}'",
5359 token::get_ident(name));
5360 found_traits.push(trait_def_id);
5363 fn record_def(&mut self, node_id: NodeId, (def, lp): (Def, LastPrivate)) {
5364 debug!("(recording def) recording {:?} for {:?}, last private {:?}",
5366 assert!(match lp {LastImport{..} => false, _ => true},
5367 "Import should only be used for `use` directives");
5368 self.last_private.insert(node_id, lp);
5369 let mut def_map = self.def_map.borrow_mut();
5370 def_map.get().insert_or_update_with(node_id, def, |_, old_value| {
5371 // Resolve appears to "resolve" the same ID multiple
5372 // times, so here is a sanity check it at least comes to
5373 // the same conclusion! - nmatsakis
5374 if def != *old_value {
5375 self.session.bug(format!("node_id {:?} resolved first to {:?} \
5376 and then {:?}", node_id, *old_value, def));
5381 fn enforce_default_binding_mode(&mut self,
5383 pat_binding_mode: BindingMode,
5385 match pat_binding_mode {
5386 BindByValue(_) => {}
5390 format!("cannot use `ref` binding mode with {}",
5397 // Unused import checking
5399 // Although this is mostly a lint pass, it lives in here because it depends on
5400 // resolve data structures and because it finalises the privacy information for
5401 // `use` directives.
5404 fn check_for_unused_imports(&mut self, krate: &ast::Crate) {
5405 let mut visitor = UnusedImportCheckVisitor{ resolver: self };
5406 visit::walk_crate(&mut visitor, krate, ());
5409 fn check_for_item_unused_imports(&mut self, vi: &ViewItem) {
5410 // Ignore is_public import statements because there's no way to be sure
5411 // whether they're used or not. Also ignore imports with a dummy span
5412 // because this means that they were generated in some fashion by the
5413 // compiler and we don't need to consider them.
5414 if vi.vis == Public { return }
5415 if vi.span == DUMMY_SP { return }
5418 ViewItemExternCrate(..) => {} // ignore
5419 ViewItemUse(ref path) => {
5420 for p in path.iter() {
5422 ViewPathSimple(_, _, id) => self.finalize_import(id, p.span),
5423 ViewPathList(_, ref list, _) => {
5424 for i in list.iter() {
5425 self.finalize_import(i.node.id, i.span);
5428 ViewPathGlob(_, id) => {
5429 if !self.used_imports.contains(&(id, TypeNS)) &&
5430 !self.used_imports.contains(&(id, ValueNS)) {
5431 self.session.add_lint(UnusedImports, id, p.span, ~"unused import");
5440 // We have information about whether `use` (import) directives are actually used now.
5441 // If an import is not used at all, we signal a lint error. If an import is only used
5442 // for a single namespace, we remove the other namespace from the recorded privacy
5443 // information. That means in privacy.rs, we will only check imports and namespaces
5444 // which are used. In particular, this means that if an import could name either a
5445 // public or private item, we will check the correct thing, dependent on how the import
5447 fn finalize_import(&mut self, id: NodeId, span: Span) {
5448 debug!("finalizing import uses for {}", self.session.codemap.span_to_snippet(span));
5450 if !self.used_imports.contains(&(id, TypeNS)) &&
5451 !self.used_imports.contains(&(id, ValueNS)) {
5452 self.session.add_lint(UnusedImports, id, span, ~"unused import");
5455 let (v_priv, t_priv) = match self.last_private.find(&id) {
5456 Some(&LastImport{value_priv: v,
5459 type_used: _}) => (v, t),
5460 Some(_) => fail!("We should only have LastImport for `use` directives"),
5464 let mut v_used = if self.used_imports.contains(&(id, ValueNS)) {
5469 let t_used = if self.used_imports.contains(&(id, TypeNS)) {
5475 match (v_priv, t_priv) {
5476 // Since some items may be both in the value _and_ type namespaces (e.g., structs)
5477 // we might have two LastPrivates pointing at the same thing. There is no point
5478 // checking both, so lets not check the value one.
5479 (Some(DependsOn(def_v)), Some(DependsOn(def_t))) if def_v == def_t => v_used = Unused,
5483 self.last_private.insert(id, LastImport{value_priv: v_priv,
5486 type_used: t_used});
5492 // Diagnostics are not particularly efficient, because they're rarely
5496 /// A somewhat inefficient routine to obtain the name of a module.
5497 fn module_to_str(&mut self, module_: @Module) -> ~str {
5498 let mut idents = Vec::new();
5499 let mut current_module = module_;
5501 match current_module.parent_link {
5505 ModuleParentLink(module_, name) => {
5507 current_module = module_;
5509 BlockParentLink(module_, _) => {
5510 idents.push(special_idents::opaque);
5511 current_module = module_;
5516 if idents.len() == 0 {
5519 return self.idents_to_str(idents.move_rev_iter().collect::<Vec<ast::Ident> >());
5522 #[allow(dead_code)] // useful for debugging
5523 fn dump_module(&mut self, module_: @Module) {
5524 debug!("Dump of module `{}`:", self.module_to_str(module_));
5526 debug!("Children:");
5527 self.populate_module_if_necessary(module_);
5528 let children = module_.children.borrow();
5529 for (&name, _) in children.get().iter() {
5530 debug!("* {}", token::get_name(name));
5533 debug!("Import resolutions:");
5534 let import_resolutions = module_.import_resolutions.borrow();
5535 for (&name, import_resolution) in import_resolutions.get().iter() {
5537 match import_resolution.target_for_namespace(ValueNS) {
5538 None => { value_repr = ~""; }
5540 value_repr = ~" value:?";
5546 match import_resolution.target_for_namespace(TypeNS) {
5547 None => { type_repr = ~""; }
5549 type_repr = ~" type:?";
5554 debug!("* {}:{}{}", token::get_name(name), value_repr, type_repr);
5559 pub struct CrateMap {
5561 exp_map2: ExportMap2,
5562 trait_map: TraitMap,
5563 external_exports: ExternalExports,
5564 last_private_map: LastPrivateMap,
5567 /// Entry point to crate resolution.
5568 pub fn resolve_crate(session: Session,
5569 lang_items: @LanguageItems,
5572 let mut resolver = Resolver(session, lang_items, krate.span);
5573 resolver.resolve(krate);
5574 let Resolver { def_map, export_map2, trait_map, last_private,
5575 external_exports, .. } = resolver;
5578 exp_map2: export_map2,
5579 trait_map: trait_map,
5580 external_exports: external_exports,
5581 last_private_map: last_private,