]> git.lizzy.rs Git - rust.git/blob - src/librustc_resolve/lib.rs
rollup merge of #20608: nikomatsakis/assoc-types-method-dispatch
[rust.git] / src / librustc_resolve / lib.rs
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.
4 //
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.
10
11 #![crate_name = "rustc_resolve"]
12 #![experimental]
13 #![crate_type = "dylib"]
14 #![crate_type = "rlib"]
15 #![doc(html_logo_url = "http://www.rust-lang.org/logos/rust-logo-128x128-blk-v2.png",
16       html_favicon_url = "http://www.rust-lang.org/favicon.ico",
17       html_root_url = "http://doc.rust-lang.org/nightly/")]
18
19 #![feature(globs, phase, slicing_syntax)]
20 #![feature(rustc_diagnostic_macros)]
21 #![feature(associated_types)]
22 #![feature(old_orphan_check)]
23
24 #[phase(plugin, link)] extern crate log;
25 #[phase(plugin, link)] extern crate syntax;
26
27 extern crate rustc;
28
29 use self::PatternBindingMode::*;
30 use self::Namespace::*;
31 use self::NamespaceResult::*;
32 use self::NameDefinition::*;
33 use self::ImportDirectiveSubclass::*;
34 use self::ResolveResult::*;
35 use self::FallbackSuggestion::*;
36 use self::TypeParameters::*;
37 use self::RibKind::*;
38 use self::MethodSort::*;
39 use self::UseLexicalScopeFlag::*;
40 use self::ModulePrefixResult::*;
41 use self::NameSearchType::*;
42 use self::BareIdentifierPatternResolution::*;
43 use self::ParentLink::*;
44 use self::ModuleKind::*;
45 use self::TraitReferenceType::*;
46 use self::FallbackChecks::*;
47
48 use rustc::session::Session;
49 use rustc::lint;
50 use rustc::metadata::csearch;
51 use rustc::metadata::decoder::{DefLike, DlDef, DlField, DlImpl};
52 use rustc::middle::def::*;
53 use rustc::middle::lang_items::LanguageItems;
54 use rustc::middle::pat_util::pat_bindings;
55 use rustc::middle::privacy::*;
56 use rustc::middle::subst::{ParamSpace, FnSpace, TypeSpace};
57 use rustc::middle::ty::{CaptureModeMap, Freevar, FreevarMap, TraitMap, GlobMap};
58 use rustc::util::nodemap::{NodeMap, NodeSet, DefIdSet, FnvHashMap};
59 use rustc::util::lev_distance::lev_distance;
60
61 use syntax::ast::{Arm, BindByRef, BindByValue, BindingMode, Block, Crate, CrateNum};
62 use syntax::ast::{DefId, Expr, ExprAgain, ExprBreak, ExprField};
63 use syntax::ast::{ExprClosure, ExprForLoop, ExprLoop, ExprWhile, ExprMethodCall};
64 use syntax::ast::{ExprPath, ExprStruct, FnDecl};
65 use syntax::ast::{ForeignItemFn, ForeignItemStatic, Generics};
66 use syntax::ast::{Ident, ImplItem, Item, ItemConst, ItemEnum, ItemFn};
67 use syntax::ast::{ItemForeignMod, ItemImpl, ItemMac, ItemMod, ItemStatic};
68 use syntax::ast::{ItemStruct, ItemTrait, ItemTy, Local, LOCAL_CRATE};
69 use syntax::ast::{MethodImplItem, Mod, Name, NodeId};
70 use syntax::ast::{Pat, PatEnum, PatIdent, PatLit};
71 use syntax::ast::{PatRange, PatStruct, Path};
72 use syntax::ast::{PolyTraitRef, PrimTy, SelfExplicit};
73 use syntax::ast::{RegionTyParamBound, StructField};
74 use syntax::ast::{TraitRef, TraitTyParamBound};
75 use syntax::ast::{Ty, TyBool, TyChar, TyF32};
76 use syntax::ast::{TyF64, TyFloat, TyI, TyI8, TyI16, TyI32, TyI64, TyInt, TyObjectSum};
77 use syntax::ast::{TyParam, TyParamBound, TyPath, TyPtr, TyPolyTraitRef, TyQPath};
78 use syntax::ast::{TyRptr, TyStr, TyU, TyU8, TyU16, TyU32, TyU64, TyUint};
79 use syntax::ast::{TypeImplItem};
80 use syntax::ast;
81 use syntax::ast_map;
82 use syntax::ast_util::{PostExpansionMethod, local_def, walk_pat};
83 use syntax::attr::AttrMetaMethods;
84 use syntax::ext::mtwt;
85 use syntax::parse::token::{self, special_names, special_idents};
86 use syntax::codemap::{Span, Pos};
87 use syntax::owned_slice::OwnedSlice;
88 use syntax::visit::{self, Visitor};
89
90 use std::collections::{HashMap, HashSet};
91 use std::collections::hash_map::Entry::{Occupied, Vacant};
92 use std::cell::{Cell, RefCell};
93 use std::fmt;
94 use std::mem::replace;
95 use std::rc::{Rc, Weak};
96 use std::uint;
97
98 mod check_unused;
99 mod record_exports;
100 mod build_reduced_graph;
101
102 #[derive(Copy)]
103 struct BindingInfo {
104     span: Span,
105     binding_mode: BindingMode,
106 }
107
108 // Map from the name in a pattern to its binding mode.
109 type BindingMap = HashMap<Name, BindingInfo>;
110
111 #[derive(Copy, PartialEq)]
112 enum PatternBindingMode {
113     RefutableMode,
114     LocalIrrefutableMode,
115     ArgumentIrrefutableMode,
116 }
117
118 #[derive(Copy, PartialEq, Eq, Hash, Show)]
119 enum Namespace {
120     TypeNS,
121     ValueNS
122 }
123
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 #[derive(Clone)]
128 enum NamespaceResult {
129     /// Means that resolve hasn't gathered enough information yet to determine
130     /// whether the name is bound in this namespace. (That is, it hasn't
131     /// resolved all `use` directives yet.)
132     UnknownResult,
133     /// Means that resolve has determined that the name is definitely
134     /// not bound in the namespace.
135     UnboundResult,
136     /// Means that resolve has determined that the name is bound in the Module
137     /// argument, and specified by the NameBindings argument.
138     BoundResult(Rc<Module>, Rc<NameBindings>)
139 }
140
141 impl NamespaceResult {
142     fn is_unknown(&self) -> bool {
143         match *self {
144             UnknownResult => true,
145             _ => false
146         }
147     }
148     fn is_unbound(&self) -> bool {
149         match *self {
150             UnboundResult => true,
151             _ => false
152         }
153     }
154 }
155
156 enum NameDefinition {
157     NoNameDefinition,           //< The name was unbound.
158     ChildNameDefinition(Def, LastPrivate), //< The name identifies an immediate child.
159     ImportNameDefinition(Def, LastPrivate) //< The name identifies an import.
160 }
161
162 impl<'a, 'v, 'tcx> Visitor<'v> for Resolver<'a, 'tcx> {
163     fn visit_item(&mut self, item: &Item) {
164         self.resolve_item(item);
165     }
166     fn visit_arm(&mut self, arm: &Arm) {
167         self.resolve_arm(arm);
168     }
169     fn visit_block(&mut self, block: &Block) {
170         self.resolve_block(block);
171     }
172     fn visit_expr(&mut self, expr: &Expr) {
173         self.resolve_expr(expr);
174     }
175     fn visit_local(&mut self, local: &Local) {
176         self.resolve_local(local);
177     }
178     fn visit_ty(&mut self, ty: &Ty) {
179         self.resolve_type(ty);
180     }
181 }
182
183 /// Contains data for specific types of import directives.
184 #[derive(Copy,Show)]
185 enum ImportDirectiveSubclass {
186     SingleImport(Name /* target */, Name /* source */),
187     GlobImport
188 }
189
190 type ErrorMessage = Option<(Span, String)>;
191
192 enum ResolveResult<T> {
193     Failed(ErrorMessage),   // Failed to resolve the name, optional helpful error message.
194     Indeterminate,          // Couldn't determine due to unresolved globs.
195     Success(T)              // Successfully resolved the import.
196 }
197
198 impl<T> ResolveResult<T> {
199     fn indeterminate(&self) -> bool {
200         match *self { Indeterminate => true, _ => false }
201     }
202 }
203
204 enum FallbackSuggestion {
205     NoSuggestion,
206     Field,
207     Method,
208     TraitItem,
209     StaticMethod(String),
210     TraitMethod(String),
211 }
212
213 #[derive(Copy)]
214 enum TypeParameters<'a> {
215     NoTypeParameters,
216     HasTypeParameters(
217         // Type parameters.
218         &'a Generics,
219
220         // Identifies the things that these parameters
221         // were declared on (type, fn, etc)
222         ParamSpace,
223
224         // ID of the enclosing item.
225         NodeId,
226
227         // The kind of the rib used for type parameters.
228         RibKind)
229 }
230
231 // The rib kind controls the translation of local
232 // definitions (`DefLocal`) to upvars (`DefUpvar`).
233 #[derive(Copy, Show)]
234 enum RibKind {
235     // No translation needs to be applied.
236     NormalRibKind,
237
238     // We passed through a closure scope at the given node ID.
239     // Translate upvars as appropriate.
240     ClosureRibKind(NodeId /* func id */, NodeId /* body id if proc or unboxed */),
241
242     // We passed through an impl or trait and are now in one of its
243     // methods. Allow references to ty params that impl or trait
244     // binds. Disallow any other upvars (including other ty params that are
245     // upvars).
246               // parent;   method itself
247     MethodRibKind(NodeId, MethodSort),
248
249     // We passed through an item scope. Disallow upvars.
250     ItemRibKind,
251
252     // We're in a constant item. Can't refer to dynamic stuff.
253     ConstantItemRibKind
254 }
255
256 // Methods can be required or provided. RequiredMethod methods only occur in traits.
257 #[derive(Copy, Show)]
258 enum MethodSort {
259     RequiredMethod,
260     ProvidedMethod(NodeId)
261 }
262
263 #[derive(Copy)]
264 enum UseLexicalScopeFlag {
265     DontUseLexicalScope,
266     UseLexicalScope
267 }
268
269 enum ModulePrefixResult {
270     NoPrefixFound,
271     PrefixFound(Rc<Module>, uint)
272 }
273
274 #[derive(Copy, PartialEq)]
275 enum NameSearchType {
276     /// We're doing a name search in order to resolve a `use` directive.
277     ImportSearch,
278
279     /// We're doing a name search in order to resolve a path type, a path
280     /// expression, or a path pattern.
281     PathSearch,
282 }
283
284 #[derive(Copy)]
285 enum BareIdentifierPatternResolution {
286     FoundStructOrEnumVariant(Def, LastPrivate),
287     FoundConst(Def, LastPrivate),
288     BareIdentifierPatternUnresolved
289 }
290
291 /// One local scope.
292 #[derive(Show)]
293 struct Rib {
294     bindings: HashMap<Name, DefLike>,
295     kind: RibKind,
296 }
297
298 impl Rib {
299     fn new(kind: RibKind) -> Rib {
300         Rib {
301             bindings: HashMap::new(),
302             kind: kind
303         }
304     }
305 }
306
307 /// Whether an import can be shadowed by another import.
308 #[derive(Show,PartialEq,Clone,Copy)]
309 enum Shadowable {
310     Always,
311     Never
312 }
313
314 /// One import directive.
315 #[derive(Show)]
316 struct ImportDirective {
317     module_path: Vec<Name>,
318     subclass: ImportDirectiveSubclass,
319     span: Span,
320     id: NodeId,
321     is_public: bool, // see note in ImportResolution about how to use this
322     shadowable: Shadowable,
323 }
324
325 impl ImportDirective {
326     fn new(module_path: Vec<Name> ,
327            subclass: ImportDirectiveSubclass,
328            span: Span,
329            id: NodeId,
330            is_public: bool,
331            shadowable: Shadowable)
332            -> ImportDirective {
333         ImportDirective {
334             module_path: module_path,
335             subclass: subclass,
336             span: span,
337             id: id,
338             is_public: is_public,
339             shadowable: shadowable,
340         }
341     }
342 }
343
344 /// The item that an import resolves to.
345 #[derive(Clone,Show)]
346 struct Target {
347     target_module: Rc<Module>,
348     bindings: Rc<NameBindings>,
349     shadowable: Shadowable,
350 }
351
352 impl Target {
353     fn new(target_module: Rc<Module>,
354            bindings: Rc<NameBindings>,
355            shadowable: Shadowable)
356            -> Target {
357         Target {
358             target_module: target_module,
359             bindings: bindings,
360             shadowable: shadowable,
361         }
362     }
363 }
364
365 /// An ImportResolution represents a particular `use` directive.
366 #[derive(Show)]
367 struct ImportResolution {
368     /// Whether this resolution came from a `use` or a `pub use`. Note that this
369     /// should *not* be used whenever resolution is being performed, this is
370     /// only looked at for glob imports statements currently. Privacy testing
371     /// occurs during a later phase of compilation.
372     is_public: bool,
373
374     // The number of outstanding references to this name. When this reaches
375     // zero, outside modules can count on the targets being correct. Before
376     // then, all bets are off; future imports could override this name.
377     outstanding_references: uint,
378
379     /// The value that this `use` directive names, if there is one.
380     value_target: Option<Target>,
381     /// The source node of the `use` directive leading to the value target
382     /// being non-none
383     value_id: NodeId,
384
385     /// The type that this `use` directive names, if there is one.
386     type_target: Option<Target>,
387     /// The source node of the `use` directive leading to the type target
388     /// being non-none
389     type_id: NodeId,
390 }
391
392 impl ImportResolution {
393     fn new(id: NodeId, is_public: bool) -> ImportResolution {
394         ImportResolution {
395             type_id: id,
396             value_id: id,
397             outstanding_references: 0,
398             value_target: None,
399             type_target: None,
400             is_public: is_public,
401         }
402     }
403
404     fn target_for_namespace(&self, namespace: Namespace)
405                                 -> Option<Target> {
406         match namespace {
407             TypeNS  => self.type_target.clone(),
408             ValueNS => self.value_target.clone(),
409         }
410     }
411
412     fn id(&self, namespace: Namespace) -> NodeId {
413         match namespace {
414             TypeNS  => self.type_id,
415             ValueNS => self.value_id,
416         }
417     }
418
419     fn shadowable(&self, namespace: Namespace) -> Shadowable {
420         let target = self.target_for_namespace(namespace);
421         if target.is_none() {
422             return Shadowable::Always;
423         }
424
425         target.unwrap().shadowable
426     }
427
428     fn set_target_and_id(&mut self,
429                          namespace: Namespace,
430                          target: Option<Target>,
431                          id: NodeId) {
432         match namespace {
433             TypeNS  => {
434                 self.type_target = target;
435                 self.type_id = id;
436             }
437             ValueNS => {
438                 self.value_target = target;
439                 self.value_id = id;
440             }
441         }
442     }
443 }
444
445 /// The link from a module up to its nearest parent node.
446 #[derive(Clone,Show)]
447 enum ParentLink {
448     NoParentLink,
449     ModuleParentLink(Weak<Module>, Name),
450     BlockParentLink(Weak<Module>, NodeId)
451 }
452
453 /// The type of module this is.
454 #[derive(Copy, PartialEq, Show)]
455 enum ModuleKind {
456     NormalModuleKind,
457     TraitModuleKind,
458     ImplModuleKind,
459     EnumModuleKind,
460     AnonymousModuleKind,
461 }
462
463 /// One node in the tree of modules.
464 struct Module {
465     parent_link: ParentLink,
466     def_id: Cell<Option<DefId>>,
467     kind: Cell<ModuleKind>,
468     is_public: bool,
469
470     children: RefCell<HashMap<Name, Rc<NameBindings>>>,
471     imports: RefCell<Vec<ImportDirective>>,
472
473     // The external module children of this node that were declared with
474     // `extern crate`.
475     external_module_children: RefCell<HashMap<Name, Rc<Module>>>,
476
477     // The anonymous children of this node. Anonymous children are pseudo-
478     // modules that are implicitly created around items contained within
479     // blocks.
480     //
481     // For example, if we have this:
482     //
483     //  fn f() {
484     //      fn g() {
485     //          ...
486     //      }
487     //  }
488     //
489     // There will be an anonymous module created around `g` with the ID of the
490     // entry block for `f`.
491     anonymous_children: RefCell<NodeMap<Rc<Module>>>,
492
493     // The status of resolving each import in this module.
494     import_resolutions: RefCell<HashMap<Name, ImportResolution>>,
495
496     // The number of unresolved globs that this module exports.
497     glob_count: Cell<uint>,
498
499     // The index of the import we're resolving.
500     resolved_import_count: Cell<uint>,
501
502     // Whether this module is populated. If not populated, any attempt to
503     // access the children must be preceded with a
504     // `populate_module_if_necessary` call.
505     populated: Cell<bool>,
506 }
507
508 impl Module {
509     fn new(parent_link: ParentLink,
510            def_id: Option<DefId>,
511            kind: ModuleKind,
512            external: bool,
513            is_public: bool)
514            -> Module {
515         Module {
516             parent_link: parent_link,
517             def_id: Cell::new(def_id),
518             kind: Cell::new(kind),
519             is_public: is_public,
520             children: RefCell::new(HashMap::new()),
521             imports: RefCell::new(Vec::new()),
522             external_module_children: RefCell::new(HashMap::new()),
523             anonymous_children: RefCell::new(NodeMap::new()),
524             import_resolutions: RefCell::new(HashMap::new()),
525             glob_count: Cell::new(0),
526             resolved_import_count: Cell::new(0),
527             populated: Cell::new(!external),
528         }
529     }
530
531     fn all_imports_resolved(&self) -> bool {
532         self.imports.borrow().len() == self.resolved_import_count.get()
533     }
534 }
535
536 impl fmt::Show for Module {
537     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
538         write!(f, "{}, kind: {}, {}",
539                self.def_id,
540                self.kind,
541                if self.is_public { "public" } else { "private" } )
542     }
543 }
544
545 bitflags! {
546     #[derive(Show)]
547     flags DefModifiers: u8 {
548         const PUBLIC            = 0b0000_0001,
549         const IMPORTABLE        = 0b0000_0010,
550     }
551 }
552
553 // Records a possibly-private type definition.
554 #[derive(Clone,Show)]
555 struct TypeNsDef {
556     modifiers: DefModifiers, // see note in ImportResolution about how to use this
557     module_def: Option<Rc<Module>>,
558     type_def: Option<Def>,
559     type_span: Option<Span>
560 }
561
562 // Records a possibly-private value definition.
563 #[derive(Clone, Copy, Show)]
564 struct ValueNsDef {
565     modifiers: DefModifiers, // see note in ImportResolution about how to use this
566     def: Def,
567     value_span: Option<Span>,
568 }
569
570 // Records the definitions (at most one for each namespace) that a name is
571 // bound to.
572 #[derive(Show)]
573 struct NameBindings {
574     type_def: RefCell<Option<TypeNsDef>>,   //< Meaning in type namespace.
575     value_def: RefCell<Option<ValueNsDef>>, //< Meaning in value namespace.
576 }
577
578 /// Ways in which a trait can be referenced
579 #[derive(Copy)]
580 enum TraitReferenceType {
581     TraitImplementation,             // impl SomeTrait for T { ... }
582     TraitDerivation,                 // trait T : SomeTrait { ... }
583     TraitBoundingTypeParameter,      // fn f<T:SomeTrait>() { ... }
584     TraitObject,                     // Box<for<'a> SomeTrait>
585     TraitQPath,                      // <T as SomeTrait>::
586 }
587
588 impl NameBindings {
589     fn new() -> NameBindings {
590         NameBindings {
591             type_def: RefCell::new(None),
592             value_def: RefCell::new(None),
593         }
594     }
595
596     /// Creates a new module in this set of name bindings.
597     fn define_module(&self,
598                      parent_link: ParentLink,
599                      def_id: Option<DefId>,
600                      kind: ModuleKind,
601                      external: bool,
602                      is_public: bool,
603                      sp: Span) {
604         // Merges the module with the existing type def or creates a new one.
605         let modifiers = if is_public { PUBLIC } else { DefModifiers::empty() } | IMPORTABLE;
606         let module_ = Rc::new(Module::new(parent_link,
607                                           def_id,
608                                           kind,
609                                           external,
610                                           is_public));
611         let type_def = self.type_def.borrow().clone();
612         match type_def {
613             None => {
614                 *self.type_def.borrow_mut() = Some(TypeNsDef {
615                     modifiers: modifiers,
616                     module_def: Some(module_),
617                     type_def: None,
618                     type_span: Some(sp)
619                 });
620             }
621             Some(type_def) => {
622                 *self.type_def.borrow_mut() = Some(TypeNsDef {
623                     modifiers: modifiers,
624                     module_def: Some(module_),
625                     type_span: Some(sp),
626                     type_def: type_def.type_def
627                 });
628             }
629         }
630     }
631
632     /// Sets the kind of the module, creating a new one if necessary.
633     fn set_module_kind(&self,
634                        parent_link: ParentLink,
635                        def_id: Option<DefId>,
636                        kind: ModuleKind,
637                        external: bool,
638                        is_public: bool,
639                        _sp: Span) {
640         let modifiers = if is_public { PUBLIC } else { DefModifiers::empty() } | IMPORTABLE;
641         let type_def = self.type_def.borrow().clone();
642         match type_def {
643             None => {
644                 let module = Module::new(parent_link,
645                                          def_id,
646                                          kind,
647                                          external,
648                                          is_public);
649                 *self.type_def.borrow_mut() = Some(TypeNsDef {
650                     modifiers: modifiers,
651                     module_def: Some(Rc::new(module)),
652                     type_def: None,
653                     type_span: None,
654                 });
655             }
656             Some(type_def) => {
657                 match type_def.module_def {
658                     None => {
659                         let module = Module::new(parent_link,
660                                                  def_id,
661                                                  kind,
662                                                  external,
663                                                  is_public);
664                         *self.type_def.borrow_mut() = Some(TypeNsDef {
665                             modifiers: modifiers,
666                             module_def: Some(Rc::new(module)),
667                             type_def: type_def.type_def,
668                             type_span: None,
669                         });
670                     }
671                     Some(module_def) => module_def.kind.set(kind),
672                 }
673             }
674         }
675     }
676
677     /// Records a type definition.
678     fn define_type(&self, def: Def, sp: Span, modifiers: DefModifiers) {
679         debug!("defining type for def {} with modifiers {}", def, modifiers);
680         // Merges the type with the existing type def or creates a new one.
681         let type_def = self.type_def.borrow().clone();
682         match type_def {
683             None => {
684                 *self.type_def.borrow_mut() = Some(TypeNsDef {
685                     module_def: None,
686                     type_def: Some(def),
687                     type_span: Some(sp),
688                     modifiers: modifiers,
689                 });
690             }
691             Some(type_def) => {
692                 *self.type_def.borrow_mut() = Some(TypeNsDef {
693                     module_def: type_def.module_def,
694                     type_def: Some(def),
695                     type_span: Some(sp),
696                     modifiers: modifiers,
697                 });
698             }
699         }
700     }
701
702     /// Records a value definition.
703     fn define_value(&self, def: Def, sp: Span, modifiers: DefModifiers) {
704         debug!("defining value for def {} with modifiers {}", def, modifiers);
705         *self.value_def.borrow_mut() = Some(ValueNsDef {
706             def: def,
707             value_span: Some(sp),
708             modifiers: modifiers,
709         });
710     }
711
712     /// Returns the module node if applicable.
713     fn get_module_if_available(&self) -> Option<Rc<Module>> {
714         match *self.type_def.borrow() {
715             Some(ref type_def) => type_def.module_def.clone(),
716             None => None
717         }
718     }
719
720     /// Returns the module node. Panics if this node does not have a module
721     /// definition.
722     fn get_module(&self) -> Rc<Module> {
723         match self.get_module_if_available() {
724             None => {
725                 panic!("get_module called on a node with no module \
726                        definition!")
727             }
728             Some(module_def) => module_def
729         }
730     }
731
732     fn defined_in_namespace(&self, namespace: Namespace) -> bool {
733         match namespace {
734             TypeNS   => return self.type_def.borrow().is_some(),
735             ValueNS  => return self.value_def.borrow().is_some()
736         }
737     }
738
739     fn defined_in_public_namespace(&self, namespace: Namespace) -> bool {
740         self.defined_in_namespace_with(namespace, PUBLIC)
741     }
742
743     fn defined_in_namespace_with(&self, namespace: Namespace, modifiers: DefModifiers) -> bool {
744         match namespace {
745             TypeNS => match *self.type_def.borrow() {
746                 Some(ref def) => def.modifiers.contains(modifiers), None => false
747             },
748             ValueNS => match *self.value_def.borrow() {
749                 Some(ref def) => def.modifiers.contains(modifiers), None => false
750             }
751         }
752     }
753
754     fn def_for_namespace(&self, namespace: Namespace) -> Option<Def> {
755         match namespace {
756             TypeNS => {
757                 match *self.type_def.borrow() {
758                     None => None,
759                     Some(ref type_def) => {
760                         match type_def.type_def {
761                             Some(type_def) => Some(type_def),
762                             None => {
763                                 match type_def.module_def {
764                                     Some(ref module) => {
765                                         match module.def_id.get() {
766                                             Some(did) => Some(DefMod(did)),
767                                             None => None,
768                                         }
769                                     }
770                                     None => None,
771                                 }
772                             }
773                         }
774                     }
775                 }
776             }
777             ValueNS => {
778                 match *self.value_def.borrow() {
779                     None => None,
780                     Some(value_def) => Some(value_def.def)
781                 }
782             }
783         }
784     }
785
786     fn span_for_namespace(&self, namespace: Namespace) -> Option<Span> {
787         if self.defined_in_namespace(namespace) {
788             match namespace {
789                 TypeNS  => {
790                     match *self.type_def.borrow() {
791                         None => None,
792                         Some(ref type_def) => type_def.type_span
793                     }
794                 }
795                 ValueNS => {
796                     match *self.value_def.borrow() {
797                         None => None,
798                         Some(ref value_def) => value_def.value_span
799                     }
800                 }
801             }
802         } else {
803             None
804         }
805     }
806 }
807
808 /// Interns the names of the primitive types.
809 struct PrimitiveTypeTable {
810     primitive_types: HashMap<Name, PrimTy>,
811 }
812
813 impl PrimitiveTypeTable {
814     fn new() -> PrimitiveTypeTable {
815         let mut table = PrimitiveTypeTable {
816             primitive_types: HashMap::new()
817         };
818
819         table.intern("bool",    TyBool);
820         table.intern("char",    TyChar);
821         table.intern("f32",     TyFloat(TyF32));
822         table.intern("f64",     TyFloat(TyF64));
823         table.intern("int",     TyInt(TyI));
824         table.intern("i8",      TyInt(TyI8));
825         table.intern("i16",     TyInt(TyI16));
826         table.intern("i32",     TyInt(TyI32));
827         table.intern("i64",     TyInt(TyI64));
828         table.intern("str",     TyStr);
829         table.intern("uint",    TyUint(TyU));
830         table.intern("u8",      TyUint(TyU8));
831         table.intern("u16",     TyUint(TyU16));
832         table.intern("u32",     TyUint(TyU32));
833         table.intern("u64",     TyUint(TyU64));
834
835         table
836     }
837
838     fn intern(&mut self, string: &str, primitive_type: PrimTy) {
839         self.primitive_types.insert(token::intern(string), primitive_type);
840     }
841 }
842
843 /// The main resolver class.
844 struct Resolver<'a, 'tcx:'a> {
845     session: &'a Session,
846
847     ast_map: &'a ast_map::Map<'tcx>,
848
849     graph_root: NameBindings,
850
851     trait_item_map: FnvHashMap<(Name, DefId), TraitItemKind>,
852
853     structs: FnvHashMap<DefId, Vec<Name>>,
854
855     // The number of imports that are currently unresolved.
856     unresolved_imports: uint,
857
858     // The module that represents the current item scope.
859     current_module: Rc<Module>,
860
861     // The current set of local scopes, for values.
862     // FIXME #4948: Reuse ribs to avoid allocation.
863     value_ribs: Vec<Rib>,
864
865     // The current set of local scopes, for types.
866     type_ribs: Vec<Rib>,
867
868     // The current set of local scopes, for labels.
869     label_ribs: Vec<Rib>,
870
871     // The trait that the current context can refer to.
872     current_trait_ref: Option<(DefId, TraitRef)>,
873
874     // The current self type if inside an impl (used for better errors).
875     current_self_type: Option<Ty>,
876
877     // The ident for the keyword "self".
878     self_name: Name,
879     // The ident for the non-keyword "Self".
880     type_self_name: Name,
881
882     // The idents for the primitive types.
883     primitive_type_table: PrimitiveTypeTable,
884
885     def_map: DefMap,
886     freevars: RefCell<FreevarMap>,
887     freevars_seen: RefCell<NodeMap<NodeSet>>,
888     capture_mode_map: CaptureModeMap,
889     export_map: ExportMap,
890     trait_map: TraitMap,
891     external_exports: ExternalExports,
892     last_private: LastPrivateMap,
893
894     // Whether or not to print error messages. Can be set to true
895     // when getting additional info for error message suggestions,
896     // so as to avoid printing duplicate errors
897     emit_errors: bool,
898
899     make_glob_map: bool,
900     // Maps imports to the names of items actually imported (this actually maps
901     // all imports, but only glob imports are actually interesting).
902     glob_map: GlobMap,
903
904     used_imports: HashSet<(NodeId, Namespace)>,
905     used_crates: HashSet<CrateNum>,
906 }
907
908 #[derive(PartialEq)]
909 enum FallbackChecks {
910     Everything,
911     OnlyTraitAndStatics
912 }
913
914
915 impl<'a, 'tcx> Resolver<'a, 'tcx> {
916     fn new(session: &'a Session,
917            ast_map: &'a ast_map::Map<'tcx>,
918            crate_span: Span,
919            make_glob_map: MakeGlobMap) -> Resolver<'a, 'tcx> {
920         let graph_root = NameBindings::new();
921
922         graph_root.define_module(NoParentLink,
923                                  Some(DefId { krate: 0, node: 0 }),
924                                  NormalModuleKind,
925                                  false,
926                                  true,
927                                  crate_span);
928
929         let current_module = graph_root.get_module();
930
931         Resolver {
932             session: session,
933
934             ast_map: ast_map,
935
936             // The outermost module has def ID 0; this is not reflected in the
937             // AST.
938
939             graph_root: graph_root,
940
941             trait_item_map: FnvHashMap::new(),
942             structs: FnvHashMap::new(),
943
944             unresolved_imports: 0,
945
946             current_module: current_module,
947             value_ribs: Vec::new(),
948             type_ribs: Vec::new(),
949             label_ribs: Vec::new(),
950
951             current_trait_ref: None,
952             current_self_type: None,
953
954             self_name: special_names::self_,
955             type_self_name: special_names::type_self,
956
957             primitive_type_table: PrimitiveTypeTable::new(),
958
959             def_map: RefCell::new(NodeMap::new()),
960             freevars: RefCell::new(NodeMap::new()),
961             freevars_seen: RefCell::new(NodeMap::new()),
962             capture_mode_map: NodeMap::new(),
963             export_map: NodeMap::new(),
964             trait_map: NodeMap::new(),
965             used_imports: HashSet::new(),
966             used_crates: HashSet::new(),
967             external_exports: DefIdSet::new(),
968             last_private: NodeMap::new(),
969
970             emit_errors: true,
971             make_glob_map: make_glob_map == MakeGlobMap::Yes,
972             glob_map: HashMap::new(),
973         }
974     }
975
976     // Import resolution
977     //
978     // This is a fixed-point algorithm. We resolve imports until our efforts
979     // are stymied by an unresolved import; then we bail out of the current
980     // module and continue. We terminate successfully once no more imports
981     // remain or unsuccessfully when no forward progress in resolving imports
982     // is made.
983
984     /// Resolves all imports for the crate. This method performs the fixed-
985     /// point iteration.
986     fn resolve_imports(&mut self) {
987         let mut i = 0u;
988         let mut prev_unresolved_imports = 0;
989         loop {
990             debug!("(resolving imports) iteration {}, {} imports left",
991                    i, self.unresolved_imports);
992
993             let module_root = self.graph_root.get_module();
994             self.resolve_imports_for_module_subtree(module_root.clone());
995
996             if self.unresolved_imports == 0 {
997                 debug!("(resolving imports) success");
998                 break;
999             }
1000
1001             if self.unresolved_imports == prev_unresolved_imports {
1002                 self.report_unresolved_imports(module_root);
1003                 break;
1004             }
1005
1006             i += 1;
1007             prev_unresolved_imports = self.unresolved_imports;
1008         }
1009     }
1010
1011     /// Attempts to resolve imports for the given module and all of its
1012     /// submodules.
1013     fn resolve_imports_for_module_subtree(&mut self, module_: Rc<Module>) {
1014         debug!("(resolving imports for module subtree) resolving {}",
1015                self.module_to_string(&*module_));
1016         let orig_module = replace(&mut self.current_module, module_.clone());
1017         self.resolve_imports_for_module(module_.clone());
1018         self.current_module = orig_module;
1019
1020         build_reduced_graph::populate_module_if_necessary(self, &module_);
1021         for (_, child_node) in module_.children.borrow().iter() {
1022             match child_node.get_module_if_available() {
1023                 None => {
1024                     // Nothing to do.
1025                 }
1026                 Some(child_module) => {
1027                     self.resolve_imports_for_module_subtree(child_module);
1028                 }
1029             }
1030         }
1031
1032         for (_, child_module) in module_.anonymous_children.borrow().iter() {
1033             self.resolve_imports_for_module_subtree(child_module.clone());
1034         }
1035     }
1036
1037     /// Attempts to resolve imports for the given module only.
1038     fn resolve_imports_for_module(&mut self, module: Rc<Module>) {
1039         if module.all_imports_resolved() {
1040             debug!("(resolving imports for module) all imports resolved for \
1041                    {}",
1042                    self.module_to_string(&*module));
1043             return;
1044         }
1045
1046         let imports = module.imports.borrow();
1047         let import_count = imports.len();
1048         while module.resolved_import_count.get() < import_count {
1049             let import_index = module.resolved_import_count.get();
1050             let import_directive = &(*imports)[import_index];
1051             match self.resolve_import_for_module(module.clone(),
1052                                                  import_directive) {
1053                 Failed(err) => {
1054                     let (span, help) = match err {
1055                         Some((span, msg)) => (span, format!(". {}", msg)),
1056                         None => (import_directive.span, String::new())
1057                     };
1058                     let msg = format!("unresolved import `{}`{}",
1059                                       self.import_path_to_string(
1060                                           import_directive.module_path
1061                                                           [],
1062                                           import_directive.subclass),
1063                                       help);
1064                     self.resolve_error(span, msg[]);
1065                 }
1066                 Indeterminate => break, // Bail out. We'll come around next time.
1067                 Success(()) => () // Good. Continue.
1068             }
1069
1070             module.resolved_import_count
1071                   .set(module.resolved_import_count.get() + 1);
1072         }
1073     }
1074
1075     fn names_to_string(&self, names: &[Name]) -> String {
1076         let mut first = true;
1077         let mut result = String::new();
1078         for name in names.iter() {
1079             if first {
1080                 first = false
1081             } else {
1082                 result.push_str("::")
1083             }
1084             result.push_str(token::get_name(*name).get());
1085         };
1086         result
1087     }
1088
1089     fn path_names_to_string(&self, path: &Path) -> String {
1090         let names: Vec<ast::Name> = path.segments
1091                                         .iter()
1092                                         .map(|seg| seg.identifier.name)
1093                                         .collect();
1094         self.names_to_string(names[])
1095     }
1096
1097     fn import_directive_subclass_to_string(&mut self,
1098                                         subclass: ImportDirectiveSubclass)
1099                                         -> String {
1100         match subclass {
1101             SingleImport(_, source) => {
1102                 token::get_name(source).get().to_string()
1103             }
1104             GlobImport => "*".to_string()
1105         }
1106     }
1107
1108     fn import_path_to_string(&mut self,
1109                           names: &[Name],
1110                           subclass: ImportDirectiveSubclass)
1111                           -> String {
1112         if names.is_empty() {
1113             self.import_directive_subclass_to_string(subclass)
1114         } else {
1115             (format!("{}::{}",
1116                      self.names_to_string(names),
1117                      self.import_directive_subclass_to_string(
1118                          subclass))).to_string()
1119         }
1120     }
1121
1122     #[inline]
1123     fn record_import_use(&mut self, import_id: NodeId, name: Name) {
1124         if !self.make_glob_map {
1125             return;
1126         }
1127         if self.glob_map.contains_key(&import_id) {
1128             self.glob_map[import_id].insert(name);
1129             return;
1130         }
1131
1132         let mut new_set = HashSet::new();
1133         new_set.insert(name);
1134         self.glob_map.insert(import_id, new_set);
1135     }
1136
1137     fn get_trait_name(&self, did: DefId) -> Name {
1138         if did.krate == LOCAL_CRATE {
1139             self.ast_map.expect_item(did.node).ident.name
1140         } else {
1141             csearch::get_trait_name(&self.session.cstore, did)
1142         }
1143     }
1144
1145     /// Attempts to resolve the given import. The return value indicates
1146     /// failure if we're certain the name does not exist, indeterminate if we
1147     /// don't know whether the name exists at the moment due to other
1148     /// currently-unresolved imports, or success if we know the name exists.
1149     /// If successful, the resolved bindings are written into the module.
1150     fn resolve_import_for_module(&mut self,
1151                                  module_: Rc<Module>,
1152                                  import_directive: &ImportDirective)
1153                                  -> ResolveResult<()> {
1154         let mut resolution_result = Failed(None);
1155         let module_path = &import_directive.module_path;
1156
1157         debug!("(resolving import for module) resolving import `{}::...` in `{}`",
1158                self.names_to_string(module_path[]),
1159                self.module_to_string(&*module_));
1160
1161         // First, resolve the module path for the directive, if necessary.
1162         let container = if module_path.len() == 0 {
1163             // Use the crate root.
1164             Some((self.graph_root.get_module(), LastMod(AllPublic)))
1165         } else {
1166             match self.resolve_module_path(module_.clone(),
1167                                            module_path[],
1168                                            DontUseLexicalScope,
1169                                            import_directive.span,
1170                                            ImportSearch) {
1171                 Failed(err) => {
1172                     resolution_result = Failed(err);
1173                     None
1174                 },
1175                 Indeterminate => {
1176                     resolution_result = Indeterminate;
1177                     None
1178                 }
1179                 Success(container) => Some(container),
1180             }
1181         };
1182
1183         match container {
1184             None => {}
1185             Some((containing_module, lp)) => {
1186                 // We found the module that the target is contained
1187                 // within. Attempt to resolve the import within it.
1188
1189                 match import_directive.subclass {
1190                     SingleImport(target, source) => {
1191                         resolution_result =
1192                             self.resolve_single_import(&*module_,
1193                                                        containing_module,
1194                                                        target,
1195                                                        source,
1196                                                        import_directive,
1197                                                        lp);
1198                     }
1199                     GlobImport => {
1200                         resolution_result =
1201                             self.resolve_glob_import(&*module_,
1202                                                      containing_module,
1203                                                      import_directive,
1204                                                      lp);
1205                     }
1206                 }
1207             }
1208         }
1209
1210         // Decrement the count of unresolved imports.
1211         match resolution_result {
1212             Success(()) => {
1213                 assert!(self.unresolved_imports >= 1);
1214                 self.unresolved_imports -= 1;
1215             }
1216             _ => {
1217                 // Nothing to do here; just return the error.
1218             }
1219         }
1220
1221         // Decrement the count of unresolved globs if necessary. But only if
1222         // the resolution result is indeterminate -- otherwise we'll stop
1223         // processing imports here. (See the loop in
1224         // resolve_imports_for_module.)
1225
1226         if !resolution_result.indeterminate() {
1227             match import_directive.subclass {
1228                 GlobImport => {
1229                     assert!(module_.glob_count.get() >= 1);
1230                     module_.glob_count.set(module_.glob_count.get() - 1);
1231                 }
1232                 SingleImport(..) => {
1233                     // Ignore.
1234                 }
1235             }
1236         }
1237
1238         return resolution_result;
1239     }
1240
1241     fn create_name_bindings_from_module(module: Rc<Module>) -> NameBindings {
1242         NameBindings {
1243             type_def: RefCell::new(Some(TypeNsDef {
1244                 modifiers: IMPORTABLE,
1245                 module_def: Some(module),
1246                 type_def: None,
1247                 type_span: None
1248             })),
1249             value_def: RefCell::new(None),
1250         }
1251     }
1252
1253     fn resolve_single_import(&mut self,
1254                              module_: &Module,
1255                              containing_module: Rc<Module>,
1256                              target: Name,
1257                              source: Name,
1258                              directive: &ImportDirective,
1259                              lp: LastPrivate)
1260                                  -> ResolveResult<()> {
1261         debug!("(resolving single import) resolving `{}` = `{}::{}` from \
1262                 `{}` id {}, last private {}",
1263                token::get_name(target),
1264                self.module_to_string(&*containing_module),
1265                token::get_name(source),
1266                self.module_to_string(module_),
1267                directive.id,
1268                lp);
1269
1270         let lp = match lp {
1271             LastMod(lp) => lp,
1272             LastImport {..} => {
1273                 self.session
1274                     .span_bug(directive.span,
1275                               "not expecting Import here, must be LastMod")
1276             }
1277         };
1278
1279         // We need to resolve both namespaces for this to succeed.
1280         //
1281
1282         let mut value_result = UnknownResult;
1283         let mut type_result = UnknownResult;
1284
1285         // Search for direct children of the containing module.
1286         build_reduced_graph::populate_module_if_necessary(self, &containing_module);
1287
1288         match containing_module.children.borrow().get(&source) {
1289             None => {
1290                 // Continue.
1291             }
1292             Some(ref child_name_bindings) => {
1293                 if child_name_bindings.defined_in_namespace(ValueNS) {
1294                     debug!("(resolving single import) found value binding");
1295                     value_result = BoundResult(containing_module.clone(),
1296                                                (*child_name_bindings).clone());
1297                 }
1298                 if child_name_bindings.defined_in_namespace(TypeNS) {
1299                     debug!("(resolving single import) found type binding");
1300                     type_result = BoundResult(containing_module.clone(),
1301                                               (*child_name_bindings).clone());
1302                 }
1303             }
1304         }
1305
1306         // Unless we managed to find a result in both namespaces (unlikely),
1307         // search imports as well.
1308         let mut value_used_reexport = false;
1309         let mut type_used_reexport = false;
1310         match (value_result.clone(), type_result.clone()) {
1311             (BoundResult(..), BoundResult(..)) => {} // Continue.
1312             _ => {
1313                 // If there is an unresolved glob at this point in the
1314                 // containing module, bail out. We don't know enough to be
1315                 // able to resolve this import.
1316
1317                 if containing_module.glob_count.get() > 0 {
1318                     debug!("(resolving single import) unresolved glob; \
1319                             bailing out");
1320                     return Indeterminate;
1321                 }
1322
1323                 // Now search the exported imports within the containing module.
1324                 match containing_module.import_resolutions.borrow().get(&source) {
1325                     None => {
1326                         debug!("(resolving single import) no import");
1327                         // The containing module definitely doesn't have an
1328                         // exported import with the name in question. We can
1329                         // therefore accurately report that the names are
1330                         // unbound.
1331
1332                         if value_result.is_unknown() {
1333                             value_result = UnboundResult;
1334                         }
1335                         if type_result.is_unknown() {
1336                             type_result = UnboundResult;
1337                         }
1338                     }
1339                     Some(import_resolution)
1340                             if import_resolution.outstanding_references == 0 => {
1341
1342                         fn get_binding(this: &mut Resolver,
1343                                        import_resolution: &ImportResolution,
1344                                        namespace: Namespace,
1345                                        source: &Name)
1346                                     -> NamespaceResult {
1347
1348                             // Import resolutions must be declared with "pub"
1349                             // in order to be exported.
1350                             if !import_resolution.is_public {
1351                                 return UnboundResult;
1352                             }
1353
1354                             match import_resolution.
1355                                     target_for_namespace(namespace) {
1356                                 None => {
1357                                     return UnboundResult;
1358                                 }
1359                                 Some(Target {
1360                                     target_module,
1361                                     bindings,
1362                                     shadowable: _
1363                                 }) => {
1364                                     debug!("(resolving single import) found \
1365                                             import in ns {}", namespace);
1366                                     let id = import_resolution.id(namespace);
1367                                     // track used imports and extern crates as well
1368                                     this.used_imports.insert((id, namespace));
1369                                     this.record_import_use(id, *source);
1370                                     match target_module.def_id.get() {
1371                                         Some(DefId{krate: kid, ..}) => {
1372                                             this.used_crates.insert(kid);
1373                                         },
1374                                         _ => {}
1375                                     }
1376                                     return BoundResult(target_module, bindings);
1377                                 }
1378                             }
1379                         }
1380
1381                         // The name is an import which has been fully
1382                         // resolved. We can, therefore, just follow it.
1383                         if value_result.is_unknown() {
1384                             value_result = get_binding(self,
1385                                                        import_resolution,
1386                                                        ValueNS,
1387                                                        &source);
1388                             value_used_reexport = import_resolution.is_public;
1389                         }
1390                         if type_result.is_unknown() {
1391                             type_result = get_binding(self,
1392                                                       import_resolution,
1393                                                       TypeNS,
1394                                                       &source);
1395                             type_used_reexport = import_resolution.is_public;
1396                         }
1397
1398                     }
1399                     Some(_) => {
1400                         // If containing_module is the same module whose import we are resolving
1401                         // and there it has an unresolved import with the same name as `source`,
1402                         // then the user is actually trying to import an item that is declared
1403                         // in the same scope
1404                         //
1405                         // e.g
1406                         // use self::submodule;
1407                         // pub mod submodule;
1408                         //
1409                         // In this case we continue as if we resolved the import and let the
1410                         // check_for_conflicts_between_imports_and_items call below handle
1411                         // the conflict
1412                         match (module_.def_id.get(),  containing_module.def_id.get()) {
1413                             (Some(id1), Some(id2)) if id1 == id2  => {
1414                                 if value_result.is_unknown() {
1415                                     value_result = UnboundResult;
1416                                 }
1417                                 if type_result.is_unknown() {
1418                                     type_result = UnboundResult;
1419                                 }
1420                             }
1421                             _ =>  {
1422                                 // The import is unresolved. Bail out.
1423                                 debug!("(resolving single import) unresolved import; \
1424                                         bailing out");
1425                                 return Indeterminate;
1426                             }
1427                         }
1428                     }
1429                 }
1430             }
1431         }
1432
1433         // If we didn't find a result in the type namespace, search the
1434         // external modules.
1435         let mut value_used_public = false;
1436         let mut type_used_public = false;
1437         match type_result {
1438             BoundResult(..) => {}
1439             _ => {
1440                 match containing_module.external_module_children.borrow_mut()
1441                                        .get(&source).cloned() {
1442                     None => {} // Continue.
1443                     Some(module) => {
1444                         debug!("(resolving single import) found external \
1445                                 module");
1446                         // track the module as used.
1447                         match module.def_id.get() {
1448                             Some(DefId{krate: kid, ..}) => { self.used_crates.insert(kid); },
1449                             _ => {}
1450                         }
1451                         let name_bindings =
1452                             Rc::new(Resolver::create_name_bindings_from_module(
1453                                 module));
1454                         type_result = BoundResult(containing_module.clone(),
1455                                                   name_bindings);
1456                         type_used_public = true;
1457                     }
1458                 }
1459             }
1460         }
1461
1462         // We've successfully resolved the import. Write the results in.
1463         let mut import_resolutions = module_.import_resolutions.borrow_mut();
1464         let import_resolution = &mut (*import_resolutions)[target];
1465         {
1466             let mut check_and_write_import = |&mut: namespace, result: &_, used_public: &mut bool| {
1467                 let namespace_name = match namespace {
1468                     TypeNS => "type",
1469                     ValueNS => "value",
1470                 };
1471
1472                 match *result {
1473                     BoundResult(ref target_module, ref name_bindings) => {
1474                         debug!("(resolving single import) found {} target: {}",
1475                                namespace_name,
1476                                name_bindings.def_for_namespace(namespace));
1477                         self.check_for_conflicting_import(
1478                             &import_resolution.target_for_namespace(namespace),
1479                             directive.span,
1480                             target,
1481                             namespace);
1482
1483                         self.check_that_import_is_importable(
1484                             &**name_bindings,
1485                             directive.span,
1486                             target,
1487                             namespace);
1488
1489                         let target = Some(Target::new(target_module.clone(),
1490                                                       name_bindings.clone(),
1491                                                       directive.shadowable));
1492                         import_resolution.set_target_and_id(namespace, target, directive.id);
1493                         import_resolution.is_public = directive.is_public;
1494                         *used_public = name_bindings.defined_in_public_namespace(namespace);
1495                     }
1496                     UnboundResult => { /* Continue. */ }
1497                     UnknownResult => {
1498                         panic!("{} result should be known at this point", namespace_name);
1499                     }
1500                 }
1501             };
1502             check_and_write_import(ValueNS, &value_result, &mut value_used_public);
1503             check_and_write_import(TypeNS, &type_result, &mut type_used_public);
1504         }
1505
1506         self.check_for_conflicts_between_imports_and_items(
1507             module_,
1508             import_resolution,
1509             directive.span,
1510             target);
1511
1512         if value_result.is_unbound() && type_result.is_unbound() {
1513             let msg = format!("There is no `{}` in `{}`",
1514                               token::get_name(source),
1515                               self.module_to_string(&*containing_module));
1516             return Failed(Some((directive.span, msg)));
1517         }
1518         let value_used_public = value_used_reexport || value_used_public;
1519         let type_used_public = type_used_reexport || type_used_public;
1520
1521         assert!(import_resolution.outstanding_references >= 1);
1522         import_resolution.outstanding_references -= 1;
1523
1524         // record what this import resolves to for later uses in documentation,
1525         // this may resolve to either a value or a type, but for documentation
1526         // purposes it's good enough to just favor one over the other.
1527         let value_private = match import_resolution.value_target {
1528             Some(ref target) => {
1529                 let def = target.bindings.def_for_namespace(ValueNS).unwrap();
1530                 self.def_map.borrow_mut().insert(directive.id, def);
1531                 let did = def.def_id();
1532                 if value_used_public {Some(lp)} else {Some(DependsOn(did))}
1533             },
1534             // AllPublic here and below is a dummy value, it should never be used because
1535             // _exists is false.
1536             None => None,
1537         };
1538         let type_private = match import_resolution.type_target {
1539             Some(ref target) => {
1540                 let def = target.bindings.def_for_namespace(TypeNS).unwrap();
1541                 self.def_map.borrow_mut().insert(directive.id, def);
1542                 let did = def.def_id();
1543                 if type_used_public {Some(lp)} else {Some(DependsOn(did))}
1544             },
1545             None => None,
1546         };
1547
1548         self.last_private.insert(directive.id, LastImport{value_priv: value_private,
1549                                                           value_used: Used,
1550                                                           type_priv: type_private,
1551                                                           type_used: Used});
1552
1553         debug!("(resolving single import) successfully resolved import");
1554         return Success(());
1555     }
1556
1557     // Resolves a glob import. Note that this function cannot fail; it either
1558     // succeeds or bails out (as importing * from an empty module or a module
1559     // that exports nothing is valid). containing_module is the module we are
1560     // actually importing, i.e., `foo` in `use foo::*`.
1561     fn resolve_glob_import(&mut self,
1562                            module_: &Module,
1563                            containing_module: Rc<Module>,
1564                            import_directive: &ImportDirective,
1565                            lp: LastPrivate)
1566                            -> ResolveResult<()> {
1567         let id = import_directive.id;
1568         let is_public = import_directive.is_public;
1569
1570         // This function works in a highly imperative manner; it eagerly adds
1571         // everything it can to the list of import resolutions of the module
1572         // node.
1573         debug!("(resolving glob import) resolving glob import {}", id);
1574
1575         // We must bail out if the node has unresolved imports of any kind
1576         // (including globs).
1577         if !(*containing_module).all_imports_resolved() {
1578             debug!("(resolving glob import) target module has unresolved \
1579                     imports; bailing out");
1580             return Indeterminate;
1581         }
1582
1583         assert_eq!(containing_module.glob_count.get(), 0);
1584
1585         // Add all resolved imports from the containing module.
1586         let import_resolutions = containing_module.import_resolutions.borrow();
1587         for (ident, target_import_resolution) in import_resolutions.iter() {
1588             debug!("(resolving glob import) writing module resolution \
1589                     {} into `{}`",
1590                    token::get_name(*ident),
1591                    self.module_to_string(module_));
1592
1593             if !target_import_resolution.is_public {
1594                 debug!("(resolving glob import) nevermind, just kidding");
1595                 continue
1596             }
1597
1598             // Here we merge two import resolutions.
1599             let mut import_resolutions = module_.import_resolutions.borrow_mut();
1600             match import_resolutions.get_mut(ident) {
1601                 Some(dest_import_resolution) => {
1602                     // Merge the two import resolutions at a finer-grained
1603                     // level.
1604
1605                     match target_import_resolution.value_target {
1606                         None => {
1607                             // Continue.
1608                         }
1609                         Some(ref value_target) => {
1610                             self.check_for_conflicting_import(&dest_import_resolution.value_target,
1611                                                               import_directive.span,
1612                                                               *ident,
1613                                                               ValueNS);
1614                             dest_import_resolution.value_target = Some(value_target.clone());
1615                         }
1616                     }
1617                     match target_import_resolution.type_target {
1618                         None => {
1619                             // Continue.
1620                         }
1621                         Some(ref type_target) => {
1622                             self.check_for_conflicting_import(&dest_import_resolution.type_target,
1623                                                               import_directive.span,
1624                                                               *ident,
1625                                                               TypeNS);
1626                             dest_import_resolution.type_target = Some(type_target.clone());
1627                         }
1628                     }
1629                     dest_import_resolution.is_public = is_public;
1630                     continue;
1631                 }
1632                 None => {}
1633             }
1634
1635             // Simple: just copy the old import resolution.
1636             let mut new_import_resolution = ImportResolution::new(id, is_public);
1637             new_import_resolution.value_target =
1638                 target_import_resolution.value_target.clone();
1639             new_import_resolution.type_target =
1640                 target_import_resolution.type_target.clone();
1641
1642             import_resolutions.insert(*ident, new_import_resolution);
1643         }
1644
1645         // Add all children from the containing module.
1646         build_reduced_graph::populate_module_if_necessary(self, &containing_module);
1647
1648         for (&name, name_bindings) in containing_module.children.borrow().iter() {
1649             self.merge_import_resolution(module_,
1650                                          containing_module.clone(),
1651                                          import_directive,
1652                                          name,
1653                                          name_bindings.clone());
1654
1655         }
1656
1657         // Add external module children from the containing module.
1658         for (&name, module) in containing_module.external_module_children.borrow().iter() {
1659             let name_bindings =
1660                 Rc::new(Resolver::create_name_bindings_from_module(module.clone()));
1661             self.merge_import_resolution(module_,
1662                                          containing_module.clone(),
1663                                          import_directive,
1664                                          name,
1665                                          name_bindings);
1666         }
1667
1668         // Record the destination of this import
1669         match containing_module.def_id.get() {
1670             Some(did) => {
1671                 self.def_map.borrow_mut().insert(id, DefMod(did));
1672                 self.last_private.insert(id, lp);
1673             }
1674             None => {}
1675         }
1676
1677         debug!("(resolving glob import) successfully resolved import");
1678         return Success(());
1679     }
1680
1681     fn merge_import_resolution(&mut self,
1682                                module_: &Module,
1683                                containing_module: Rc<Module>,
1684                                import_directive: &ImportDirective,
1685                                name: Name,
1686                                name_bindings: Rc<NameBindings>) {
1687         let id = import_directive.id;
1688         let is_public = import_directive.is_public;
1689
1690         let mut import_resolutions = module_.import_resolutions.borrow_mut();
1691         let dest_import_resolution = import_resolutions.entry(&name).get().unwrap_or_else(
1692             |vacant_entry| {
1693                 // Create a new import resolution from this child.
1694                 vacant_entry.insert(ImportResolution::new(id, is_public))
1695             });
1696
1697         debug!("(resolving glob import) writing resolution `{}` in `{}` \
1698                to `{}`",
1699                token::get_name(name).get(),
1700                self.module_to_string(&*containing_module),
1701                self.module_to_string(module_));
1702
1703         // Merge the child item into the import resolution.
1704         {
1705             let mut merge_child_item = |&mut : namespace| {
1706                 if name_bindings.defined_in_namespace_with(namespace, IMPORTABLE | PUBLIC) {
1707                     let namespace_name = match namespace {
1708                         TypeNS => "type",
1709                         ValueNS => "value",
1710                     };
1711                     debug!("(resolving glob import) ... for {} target", namespace_name);
1712                     if dest_import_resolution.shadowable(namespace) == Shadowable::Never {
1713                         let msg = format!("a {} named `{}` has already been imported \
1714                                            in this module",
1715                                           namespace_name,
1716                                           token::get_name(name).get());
1717                         self.session.span_err(import_directive.span, msg.as_slice());
1718                     } else {
1719                         let target = Target::new(containing_module.clone(),
1720                                                  name_bindings.clone(),
1721                                                  import_directive.shadowable);
1722                         dest_import_resolution.set_target_and_id(namespace,
1723                                                                  Some(target),
1724                                                                  id);
1725                     }
1726                 }
1727             };
1728             merge_child_item(ValueNS);
1729             merge_child_item(TypeNS);
1730         }
1731
1732         dest_import_resolution.is_public = is_public;
1733
1734         self.check_for_conflicts_between_imports_and_items(
1735             module_,
1736             dest_import_resolution,
1737             import_directive.span,
1738             name);
1739     }
1740
1741     /// Checks that imported names and items don't have the same name.
1742     fn check_for_conflicting_import(&mut self,
1743                                     target: &Option<Target>,
1744                                     import_span: Span,
1745                                     name: Name,
1746                                     namespace: Namespace) {
1747         if self.session.features.borrow().import_shadowing {
1748             return
1749         }
1750
1751         debug!("check_for_conflicting_import: {}; target exists: {}",
1752                token::get_name(name).get(),
1753                target.is_some());
1754
1755         match *target {
1756             Some(ref target) if target.shadowable != Shadowable::Always => {
1757                 let msg = format!("a {} named `{}` has already been imported \
1758                                    in this module",
1759                                   match namespace {
1760                                     TypeNS => "type",
1761                                     ValueNS => "value",
1762                                   },
1763                                   token::get_name(name).get());
1764                 self.session.span_err(import_span, msg[]);
1765             }
1766             Some(_) | None => {}
1767         }
1768     }
1769
1770     /// Checks that an import is actually importable
1771     fn check_that_import_is_importable(&mut self,
1772                                        name_bindings: &NameBindings,
1773                                        import_span: Span,
1774                                        name: Name,
1775                                        namespace: Namespace) {
1776         if !name_bindings.defined_in_namespace_with(namespace, IMPORTABLE) {
1777             let msg = format!("`{}` is not directly importable",
1778                               token::get_name(name));
1779             self.session.span_err(import_span, msg[]);
1780         }
1781     }
1782
1783     /// Checks that imported names and items don't have the same name.
1784     fn check_for_conflicts_between_imports_and_items(&mut self,
1785                                                      module: &Module,
1786                                                      import_resolution:
1787                                                      &ImportResolution,
1788                                                      import_span: Span,
1789                                                      name: Name) {
1790         if self.session.features.borrow().import_shadowing {
1791             return
1792         }
1793
1794         // First, check for conflicts between imports and `extern crate`s.
1795         if module.external_module_children
1796                  .borrow()
1797                  .contains_key(&name) {
1798             match import_resolution.type_target {
1799                 Some(ref target) if target.shadowable != Shadowable::Always => {
1800                     let msg = format!("import `{0}` conflicts with imported \
1801                                        crate in this module \
1802                                        (maybe you meant `use {0}::*`?)",
1803                                       token::get_name(name).get());
1804                     self.session.span_err(import_span, msg[]);
1805                 }
1806                 Some(_) | None => {}
1807             }
1808         }
1809
1810         // Check for item conflicts.
1811         let children = module.children.borrow();
1812         let name_bindings = match children.get(&name) {
1813             None => {
1814                 // There can't be any conflicts.
1815                 return
1816             }
1817             Some(ref name_bindings) => (*name_bindings).clone(),
1818         };
1819
1820         match import_resolution.value_target {
1821             Some(ref target) if target.shadowable != Shadowable::Always => {
1822                 if let Some(ref value) = *name_bindings.value_def.borrow() {
1823                     let msg = format!("import `{}` conflicts with value \
1824                                        in this module",
1825                                       token::get_name(name).get());
1826                     self.session.span_err(import_span, msg[]);
1827                     if let Some(span) = value.value_span {
1828                         self.session.span_note(span,
1829                                                "conflicting value here");
1830                     }
1831                 }
1832             }
1833             Some(_) | None => {}
1834         }
1835
1836         match import_resolution.type_target {
1837             Some(ref target) if target.shadowable != Shadowable::Always => {
1838                 if let Some(ref ty) = *name_bindings.type_def.borrow() {
1839                     match ty.module_def {
1840                         None => {
1841                             let msg = format!("import `{}` conflicts with type in \
1842                                                this module",
1843                                               token::get_name(name).get());
1844                             self.session.span_err(import_span, msg[]);
1845                             if let Some(span) = ty.type_span {
1846                                 self.session.span_note(span,
1847                                                        "note conflicting type here")
1848                             }
1849                         }
1850                         Some(ref module_def) => {
1851                             match module_def.kind.get() {
1852                                 ImplModuleKind => {
1853                                     if let Some(span) = ty.type_span {
1854                                         let msg = format!("inherent implementations \
1855                                                            are only allowed on types \
1856                                                            defined in the current module");
1857                                         self.session.span_err(span, msg[]);
1858                                         self.session.span_note(import_span,
1859                                                                "import from other module here")
1860                                     }
1861                                 }
1862                                 _ => {
1863                                     let msg = format!("import `{}` conflicts with existing \
1864                                                        submodule",
1865                                                       token::get_name(name).get());
1866                                     self.session.span_err(import_span, msg[]);
1867                                     if let Some(span) = ty.type_span {
1868                                         self.session.span_note(span,
1869                                                                "note conflicting module here")
1870                                     }
1871                                 }
1872                             }
1873                         }
1874                     }
1875                 }
1876             }
1877             Some(_) | None => {}
1878         }
1879     }
1880
1881     /// Checks that the names of external crates don't collide with other
1882     /// external crates.
1883     fn check_for_conflicts_between_external_crates(&self,
1884                                                    module: &Module,
1885                                                    name: Name,
1886                                                    span: Span) {
1887         if self.session.features.borrow().import_shadowing {
1888             return
1889         }
1890
1891         if module.external_module_children.borrow().contains_key(&name) {
1892             self.session
1893                 .span_err(span,
1894                           format!("an external crate named `{}` has already \
1895                                    been imported into this module",
1896                                   token::get_name(name).get())[]);
1897         }
1898     }
1899
1900     /// Checks that the names of items don't collide with external crates.
1901     fn check_for_conflicts_between_external_crates_and_items(&self,
1902                                                              module: &Module,
1903                                                              name: Name,
1904                                                              span: Span) {
1905         if self.session.features.borrow().import_shadowing {
1906             return
1907         }
1908
1909         if module.external_module_children.borrow().contains_key(&name) {
1910             self.session
1911                 .span_err(span,
1912                           format!("the name `{}` conflicts with an external \
1913                                    crate that has been imported into this \
1914                                    module",
1915                                   token::get_name(name).get())[]);
1916         }
1917     }
1918
1919     /// Resolves the given module path from the given root `module_`.
1920     fn resolve_module_path_from_root(&mut self,
1921                                      module_: Rc<Module>,
1922                                      module_path: &[Name],
1923                                      index: uint,
1924                                      span: Span,
1925                                      name_search_type: NameSearchType,
1926                                      lp: LastPrivate)
1927                                 -> ResolveResult<(Rc<Module>, LastPrivate)> {
1928         fn search_parent_externals(needle: Name, module: &Rc<Module>)
1929                                 -> Option<Rc<Module>> {
1930             module.external_module_children.borrow()
1931                                             .get(&needle).cloned()
1932                                             .map(|_| module.clone())
1933                                             .or_else(|| {
1934                 match module.parent_link.clone() {
1935                     ModuleParentLink(parent, _) => {
1936                         search_parent_externals(needle,
1937                                                 &parent.upgrade().unwrap())
1938                     }
1939                    _ => None
1940                 }
1941             })
1942         }
1943
1944         let mut search_module = module_;
1945         let mut index = index;
1946         let module_path_len = module_path.len();
1947         let mut closest_private = lp;
1948
1949         // Resolve the module part of the path. This does not involve looking
1950         // upward though scope chains; we simply resolve names directly in
1951         // modules as we go.
1952         while index < module_path_len {
1953             let name = module_path[index];
1954             match self.resolve_name_in_module(search_module.clone(),
1955                                               name,
1956                                               TypeNS,
1957                                               name_search_type,
1958                                               false) {
1959                 Failed(None) => {
1960                     let segment_name = token::get_name(name);
1961                     let module_name = self.module_to_string(&*search_module);
1962                     let mut span = span;
1963                     let msg = if "???" == module_name[] {
1964                         span.hi = span.lo + Pos::from_uint(segment_name.get().len());
1965
1966                         match search_parent_externals(name,
1967                                                      &self.current_module) {
1968                             Some(module) => {
1969                                 let path_str = self.names_to_string(module_path);
1970                                 let target_mod_str = self.module_to_string(&*module);
1971                                 let current_mod_str =
1972                                     self.module_to_string(&*self.current_module);
1973
1974                                 let prefix = if target_mod_str == current_mod_str {
1975                                     "self::".to_string()
1976                                 } else {
1977                                     format!("{}::", target_mod_str)
1978                                 };
1979
1980                                 format!("Did you mean `{}{}`?", prefix, path_str)
1981                             },
1982                             None => format!("Maybe a missing `extern crate {}`?",
1983                                             segment_name),
1984                         }
1985                     } else {
1986                         format!("Could not find `{}` in `{}`",
1987                                 segment_name,
1988                                 module_name)
1989                     };
1990
1991                     return Failed(Some((span, msg)));
1992                 }
1993                 Failed(err) => return Failed(err),
1994                 Indeterminate => {
1995                     debug!("(resolving module path for import) module \
1996                             resolution is indeterminate: {}",
1997                             token::get_name(name));
1998                     return Indeterminate;
1999                 }
2000                 Success((target, used_proxy)) => {
2001                     // Check to see whether there are type bindings, and, if
2002                     // so, whether there is a module within.
2003                     match *target.bindings.type_def.borrow() {
2004                         Some(ref type_def) => {
2005                             match type_def.module_def {
2006                                 None => {
2007                                     let msg = format!("Not a module `{}`",
2008                                                         token::get_name(name));
2009
2010                                     return Failed(Some((span, msg)));
2011                                 }
2012                                 Some(ref module_def) => {
2013                                     search_module = module_def.clone();
2014
2015                                     // track extern crates for unused_extern_crate lint
2016                                     if let Some(did) = module_def.def_id.get() {
2017                                         self.used_crates.insert(did.krate);
2018                                     }
2019
2020                                     // Keep track of the closest
2021                                     // private module used when
2022                                     // resolving this import chain.
2023                                     if !used_proxy && !search_module.is_public {
2024                                         if let Some(did) = search_module.def_id.get() {
2025                                             closest_private = LastMod(DependsOn(did));
2026                                         }
2027                                     }
2028                                 }
2029                             }
2030                         }
2031                         None => {
2032                             // There are no type bindings at all.
2033                             let msg = format!("Not a module `{}`",
2034                                               token::get_name(name));
2035                             return Failed(Some((span, msg)));
2036                         }
2037                     }
2038                 }
2039             }
2040
2041             index += 1;
2042         }
2043
2044         return Success((search_module, closest_private));
2045     }
2046
2047     /// Attempts to resolve the module part of an import directive or path
2048     /// rooted at the given module.
2049     ///
2050     /// On success, returns the resolved module, and the closest *private*
2051     /// module found to the destination when resolving this path.
2052     fn resolve_module_path(&mut self,
2053                            module_: Rc<Module>,
2054                            module_path: &[Name],
2055                            use_lexical_scope: UseLexicalScopeFlag,
2056                            span: Span,
2057                            name_search_type: NameSearchType)
2058                            -> ResolveResult<(Rc<Module>, LastPrivate)> {
2059         let module_path_len = module_path.len();
2060         assert!(module_path_len > 0);
2061
2062         debug!("(resolving module path for import) processing `{}` rooted at `{}`",
2063                self.names_to_string(module_path),
2064                self.module_to_string(&*module_));
2065
2066         // Resolve the module prefix, if any.
2067         let module_prefix_result = self.resolve_module_prefix(module_.clone(),
2068                                                               module_path);
2069
2070         let search_module;
2071         let start_index;
2072         let last_private;
2073         match module_prefix_result {
2074             Failed(None) => {
2075                 let mpath = self.names_to_string(module_path);
2076                 let mpath = mpath[];
2077                 match mpath.rfind(':') {
2078                     Some(idx) => {
2079                         let msg = format!("Could not find `{}` in `{}`",
2080                                             // idx +- 1 to account for the
2081                                             // colons on either side
2082                                             mpath[idx + 1..],
2083                                             mpath[0..idx - 1]);
2084                         return Failed(Some((span, msg)));
2085                     },
2086                     None => {
2087                         return Failed(None)
2088                     }
2089                 }
2090             }
2091             Failed(err) => return Failed(err),
2092             Indeterminate => {
2093                 debug!("(resolving module path for import) indeterminate; \
2094                         bailing");
2095                 return Indeterminate;
2096             }
2097             Success(NoPrefixFound) => {
2098                 // There was no prefix, so we're considering the first element
2099                 // of the path. How we handle this depends on whether we were
2100                 // instructed to use lexical scope or not.
2101                 match use_lexical_scope {
2102                     DontUseLexicalScope => {
2103                         // This is a crate-relative path. We will start the
2104                         // resolution process at index zero.
2105                         search_module = self.graph_root.get_module();
2106                         start_index = 0;
2107                         last_private = LastMod(AllPublic);
2108                     }
2109                     UseLexicalScope => {
2110                         // This is not a crate-relative path. We resolve the
2111                         // first component of the path in the current lexical
2112                         // scope and then proceed to resolve below that.
2113                         match self.resolve_module_in_lexical_scope(module_,
2114                                                                    module_path[0]) {
2115                             Failed(err) => return Failed(err),
2116                             Indeterminate => {
2117                                 debug!("(resolving module path for import) \
2118                                         indeterminate; bailing");
2119                                 return Indeterminate;
2120                             }
2121                             Success(containing_module) => {
2122                                 search_module = containing_module;
2123                                 start_index = 1;
2124                                 last_private = LastMod(AllPublic);
2125                             }
2126                         }
2127                     }
2128                 }
2129             }
2130             Success(PrefixFound(ref containing_module, index)) => {
2131                 search_module = containing_module.clone();
2132                 start_index = index;
2133                 last_private = LastMod(DependsOn(containing_module.def_id
2134                                                                   .get()
2135                                                                   .unwrap()));
2136             }
2137         }
2138
2139         self.resolve_module_path_from_root(search_module,
2140                                            module_path,
2141                                            start_index,
2142                                            span,
2143                                            name_search_type,
2144                                            last_private)
2145     }
2146
2147     /// Invariant: This must only be called during main resolution, not during
2148     /// import resolution.
2149     fn resolve_item_in_lexical_scope(&mut self,
2150                                      module_: Rc<Module>,
2151                                      name: Name,
2152                                      namespace: Namespace)
2153                                     -> ResolveResult<(Target, bool)> {
2154         debug!("(resolving item in lexical scope) resolving `{}` in \
2155                 namespace {} in `{}`",
2156                token::get_name(name),
2157                namespace,
2158                self.module_to_string(&*module_));
2159
2160         // The current module node is handled specially. First, check for
2161         // its immediate children.
2162         build_reduced_graph::populate_module_if_necessary(self, &module_);
2163
2164         match module_.children.borrow().get(&name) {
2165             Some(name_bindings)
2166                     if name_bindings.defined_in_namespace(namespace) => {
2167                 debug!("top name bindings succeeded");
2168                 return Success((Target::new(module_.clone(),
2169                                             name_bindings.clone(),
2170                                             Shadowable::Never),
2171                                false));
2172             }
2173             Some(_) | None => { /* Not found; continue. */ }
2174         }
2175
2176         // Now check for its import directives. We don't have to have resolved
2177         // all its imports in the usual way; this is because chains of
2178         // adjacent import statements are processed as though they mutated the
2179         // current scope.
2180         if let Some(import_resolution) = module_.import_resolutions.borrow().get(&name) {
2181             match (*import_resolution).target_for_namespace(namespace) {
2182                 None => {
2183                     // Not found; continue.
2184                     debug!("(resolving item in lexical scope) found \
2185                             import resolution, but not in namespace {}",
2186                            namespace);
2187                 }
2188                 Some(target) => {
2189                     debug!("(resolving item in lexical scope) using \
2190                             import resolution");
2191                     // track used imports and extern crates as well
2192                     let id = import_resolution.id(namespace);
2193                     self.used_imports.insert((id, namespace));
2194                     self.record_import_use(id, name);
2195                     if let Some(DefId{krate: kid, ..}) = target.target_module.def_id.get() {
2196                          self.used_crates.insert(kid);
2197                     }
2198                     return Success((target, false));
2199                 }
2200             }
2201         }
2202
2203         // Search for external modules.
2204         if namespace == TypeNS {
2205             if let Some(module) = module_.external_module_children.borrow().get(&name).cloned() {
2206                 let name_bindings =
2207                     Rc::new(Resolver::create_name_bindings_from_module(module));
2208                 debug!("lower name bindings succeeded");
2209                 return Success((Target::new(module_,
2210                                             name_bindings,
2211                                             Shadowable::Never),
2212                                 false));
2213             }
2214         }
2215
2216         // Finally, proceed up the scope chain looking for parent modules.
2217         let mut search_module = module_;
2218         loop {
2219             // Go to the next parent.
2220             match search_module.parent_link.clone() {
2221                 NoParentLink => {
2222                     // No more parents. This module was unresolved.
2223                     debug!("(resolving item in lexical scope) unresolved \
2224                             module");
2225                     return Failed(None);
2226                 }
2227                 ModuleParentLink(parent_module_node, _) => {
2228                     match search_module.kind.get() {
2229                         NormalModuleKind => {
2230                             // We stop the search here.
2231                             debug!("(resolving item in lexical \
2232                                     scope) unresolved module: not \
2233                                     searching through module \
2234                                     parents");
2235                             return Failed(None);
2236                         }
2237                         TraitModuleKind |
2238                         ImplModuleKind |
2239                         EnumModuleKind |
2240                         AnonymousModuleKind => {
2241                             search_module = parent_module_node.upgrade().unwrap();
2242                         }
2243                     }
2244                 }
2245                 BlockParentLink(ref parent_module_node, _) => {
2246                     search_module = parent_module_node.upgrade().unwrap();
2247                 }
2248             }
2249
2250             // Resolve the name in the parent module.
2251             match self.resolve_name_in_module(search_module.clone(),
2252                                               name,
2253                                               namespace,
2254                                               PathSearch,
2255                                               true) {
2256                 Failed(Some((span, msg))) =>
2257                     self.resolve_error(span, format!("failed to resolve. {}",
2258                                                      msg)[]),
2259                 Failed(None) => (), // Continue up the search chain.
2260                 Indeterminate => {
2261                     // We couldn't see through the higher scope because of an
2262                     // unresolved import higher up. Bail.
2263
2264                     debug!("(resolving item in lexical scope) indeterminate \
2265                             higher scope; bailing");
2266                     return Indeterminate;
2267                 }
2268                 Success((target, used_reexport)) => {
2269                     // We found the module.
2270                     debug!("(resolving item in lexical scope) found name \
2271                             in module, done");
2272                     return Success((target, used_reexport));
2273                 }
2274             }
2275         }
2276     }
2277
2278     /// Resolves a module name in the current lexical scope.
2279     fn resolve_module_in_lexical_scope(&mut self,
2280                                        module_: Rc<Module>,
2281                                        name: Name)
2282                                 -> ResolveResult<Rc<Module>> {
2283         // If this module is an anonymous module, resolve the item in the
2284         // lexical scope. Otherwise, resolve the item from the crate root.
2285         let resolve_result = self.resolve_item_in_lexical_scope(module_, name, TypeNS);
2286         match resolve_result {
2287             Success((target, _)) => {
2288                 let bindings = &*target.bindings;
2289                 match *bindings.type_def.borrow() {
2290                     Some(ref type_def) => {
2291                         match type_def.module_def {
2292                             None => {
2293                                 debug!("!!! (resolving module in lexical \
2294                                         scope) module wasn't actually a \
2295                                         module!");
2296                                 return Failed(None);
2297                             }
2298                             Some(ref module_def) => {
2299                                 return Success(module_def.clone());
2300                             }
2301                         }
2302                     }
2303                     None => {
2304                         debug!("!!! (resolving module in lexical scope) module
2305                                 wasn't actually a module!");
2306                         return Failed(None);
2307                     }
2308                 }
2309             }
2310             Indeterminate => {
2311                 debug!("(resolving module in lexical scope) indeterminate; \
2312                         bailing");
2313                 return Indeterminate;
2314             }
2315             Failed(err) => {
2316                 debug!("(resolving module in lexical scope) failed to resolve");
2317                 return Failed(err);
2318             }
2319         }
2320     }
2321
2322     /// Returns the nearest normal module parent of the given module.
2323     fn get_nearest_normal_module_parent(&mut self, module_: Rc<Module>)
2324                                             -> Option<Rc<Module>> {
2325         let mut module_ = module_;
2326         loop {
2327             match module_.parent_link.clone() {
2328                 NoParentLink => return None,
2329                 ModuleParentLink(new_module, _) |
2330                 BlockParentLink(new_module, _) => {
2331                     let new_module = new_module.upgrade().unwrap();
2332                     match new_module.kind.get() {
2333                         NormalModuleKind => return Some(new_module),
2334                         TraitModuleKind |
2335                         ImplModuleKind |
2336                         EnumModuleKind |
2337                         AnonymousModuleKind => module_ = new_module,
2338                     }
2339                 }
2340             }
2341         }
2342     }
2343
2344     /// Returns the nearest normal module parent of the given module, or the
2345     /// module itself if it is a normal module.
2346     fn get_nearest_normal_module_parent_or_self(&mut self, module_: Rc<Module>)
2347                                                 -> Rc<Module> {
2348         match module_.kind.get() {
2349             NormalModuleKind => return module_,
2350             TraitModuleKind |
2351             ImplModuleKind |
2352             EnumModuleKind |
2353             AnonymousModuleKind => {
2354                 match self.get_nearest_normal_module_parent(module_.clone()) {
2355                     None => module_,
2356                     Some(new_module) => new_module
2357                 }
2358             }
2359         }
2360     }
2361
2362     /// Resolves a "module prefix". A module prefix is one or both of (a) `self::`;
2363     /// (b) some chain of `super::`.
2364     /// grammar: (SELF MOD_SEP ) ? (SUPER MOD_SEP) *
2365     fn resolve_module_prefix(&mut self,
2366                              module_: Rc<Module>,
2367                              module_path: &[Name])
2368                                  -> ResolveResult<ModulePrefixResult> {
2369         // Start at the current module if we see `self` or `super`, or at the
2370         // top of the crate otherwise.
2371         let mut containing_module;
2372         let mut i;
2373         let first_module_path_string = token::get_name(module_path[0]);
2374         if "self" == first_module_path_string.get() {
2375             containing_module =
2376                 self.get_nearest_normal_module_parent_or_self(module_);
2377             i = 1;
2378         } else if "super" == first_module_path_string.get() {
2379             containing_module =
2380                 self.get_nearest_normal_module_parent_or_self(module_);
2381             i = 0;  // We'll handle `super` below.
2382         } else {
2383             return Success(NoPrefixFound);
2384         }
2385
2386         // Now loop through all the `super`s we find.
2387         while i < module_path.len() {
2388             let string = token::get_name(module_path[i]);
2389             if "super" != string.get() {
2390                 break
2391             }
2392             debug!("(resolving module prefix) resolving `super` at {}",
2393                    self.module_to_string(&*containing_module));
2394             match self.get_nearest_normal_module_parent(containing_module) {
2395                 None => return Failed(None),
2396                 Some(new_module) => {
2397                     containing_module = new_module;
2398                     i += 1;
2399                 }
2400             }
2401         }
2402
2403         debug!("(resolving module prefix) finished resolving prefix at {}",
2404                self.module_to_string(&*containing_module));
2405
2406         return Success(PrefixFound(containing_module, i));
2407     }
2408
2409     /// Attempts to resolve the supplied name in the given module for the
2410     /// given namespace. If successful, returns the target corresponding to
2411     /// the name.
2412     ///
2413     /// The boolean returned on success is an indicator of whether this lookup
2414     /// passed through a public re-export proxy.
2415     fn resolve_name_in_module(&mut self,
2416                               module_: Rc<Module>,
2417                               name: Name,
2418                               namespace: Namespace,
2419                               name_search_type: NameSearchType,
2420                               allow_private_imports: bool)
2421                               -> ResolveResult<(Target, bool)> {
2422         debug!("(resolving name in module) resolving `{}` in `{}`",
2423                token::get_name(name).get(),
2424                self.module_to_string(&*module_));
2425
2426         // First, check the direct children of the module.
2427         build_reduced_graph::populate_module_if_necessary(self, &module_);
2428
2429         match module_.children.borrow().get(&name) {
2430             Some(name_bindings)
2431                     if name_bindings.defined_in_namespace(namespace) => {
2432                 debug!("(resolving name in module) found node as child");
2433                 return Success((Target::new(module_.clone(),
2434                                             name_bindings.clone(),
2435                                             Shadowable::Never),
2436                                false));
2437             }
2438             Some(_) | None => {
2439                 // Continue.
2440             }
2441         }
2442
2443         // Next, check the module's imports if necessary.
2444
2445         // If this is a search of all imports, we should be done with glob
2446         // resolution at this point.
2447         if name_search_type == PathSearch {
2448             assert_eq!(module_.glob_count.get(), 0);
2449         }
2450
2451         // Check the list of resolved imports.
2452         match module_.import_resolutions.borrow().get(&name) {
2453             Some(import_resolution) if allow_private_imports ||
2454                                        import_resolution.is_public => {
2455
2456                 if import_resolution.is_public &&
2457                         import_resolution.outstanding_references != 0 {
2458                     debug!("(resolving name in module) import \
2459                            unresolved; bailing out");
2460                     return Indeterminate;
2461                 }
2462                 match import_resolution.target_for_namespace(namespace) {
2463                     None => {
2464                         debug!("(resolving name in module) name found, \
2465                                 but not in namespace {}",
2466                                namespace);
2467                     }
2468                     Some(target) => {
2469                         debug!("(resolving name in module) resolved to \
2470                                 import");
2471                         // track used imports and extern crates as well
2472                         let id = import_resolution.id(namespace);
2473                         self.used_imports.insert((id, namespace));
2474                         self.record_import_use(id, name);
2475                         if let Some(DefId{krate: kid, ..}) = target.target_module.def_id.get() {
2476                             self.used_crates.insert(kid);
2477                         }
2478                         return Success((target, true));
2479                     }
2480                 }
2481             }
2482             Some(..) | None => {} // Continue.
2483         }
2484
2485         // Finally, search through external children.
2486         if namespace == TypeNS {
2487             if let Some(module) = module_.external_module_children.borrow().get(&name).cloned() {
2488                 let name_bindings =
2489                     Rc::new(Resolver::create_name_bindings_from_module(module));
2490                 return Success((Target::new(module_,
2491                                             name_bindings,
2492                                             Shadowable::Never),
2493                                 false));
2494             }
2495         }
2496
2497         // We're out of luck.
2498         debug!("(resolving name in module) failed to resolve `{}`",
2499                token::get_name(name).get());
2500         return Failed(None);
2501     }
2502
2503     fn report_unresolved_imports(&mut self, module_: Rc<Module>) {
2504         let index = module_.resolved_import_count.get();
2505         let imports = module_.imports.borrow();
2506         let import_count = imports.len();
2507         if index != import_count {
2508             let sn = self.session
2509                          .codemap()
2510                          .span_to_snippet((*imports)[index].span)
2511                          .unwrap();
2512             if sn.contains("::") {
2513                 self.resolve_error((*imports)[index].span,
2514                                    "unresolved import");
2515             } else {
2516                 let err = format!("unresolved import (maybe you meant `{}::*`?)",
2517                                   sn);
2518                 self.resolve_error((*imports)[index].span, err[]);
2519             }
2520         }
2521
2522         // Descend into children and anonymous children.
2523         build_reduced_graph::populate_module_if_necessary(self, &module_);
2524
2525         for (_, child_node) in module_.children.borrow().iter() {
2526             match child_node.get_module_if_available() {
2527                 None => {
2528                     // Continue.
2529                 }
2530                 Some(child_module) => {
2531                     self.report_unresolved_imports(child_module);
2532                 }
2533             }
2534         }
2535
2536         for (_, module_) in module_.anonymous_children.borrow().iter() {
2537             self.report_unresolved_imports(module_.clone());
2538         }
2539     }
2540
2541     // AST resolution
2542     //
2543     // We maintain a list of value ribs and type ribs.
2544     //
2545     // Simultaneously, we keep track of the current position in the module
2546     // graph in the `current_module` pointer. When we go to resolve a name in
2547     // the value or type namespaces, we first look through all the ribs and
2548     // then query the module graph. When we resolve a name in the module
2549     // namespace, we can skip all the ribs (since nested modules are not
2550     // allowed within blocks in Rust) and jump straight to the current module
2551     // graph node.
2552     //
2553     // Named implementations are handled separately. When we find a method
2554     // call, we consult the module node to find all of the implementations in
2555     // scope. This information is lazily cached in the module node. We then
2556     // generate a fake "implementation scope" containing all the
2557     // implementations thus found, for compatibility with old resolve pass.
2558
2559     fn with_scope<F>(&mut self, name: Option<Name>, f: F) where
2560         F: FnOnce(&mut Resolver),
2561     {
2562         let orig_module = self.current_module.clone();
2563
2564         // Move down in the graph.
2565         match name {
2566             None => {
2567                 // Nothing to do.
2568             }
2569             Some(name) => {
2570                 build_reduced_graph::populate_module_if_necessary(self, &orig_module);
2571
2572                 match orig_module.children.borrow().get(&name) {
2573                     None => {
2574                         debug!("!!! (with scope) didn't find `{}` in `{}`",
2575                                token::get_name(name),
2576                                self.module_to_string(&*orig_module));
2577                     }
2578                     Some(name_bindings) => {
2579                         match (*name_bindings).get_module_if_available() {
2580                             None => {
2581                                 debug!("!!! (with scope) didn't find module \
2582                                         for `{}` in `{}`",
2583                                        token::get_name(name),
2584                                        self.module_to_string(&*orig_module));
2585                             }
2586                             Some(module_) => {
2587                                 self.current_module = module_;
2588                             }
2589                         }
2590                     }
2591                 }
2592             }
2593         }
2594
2595         f(self);
2596
2597         self.current_module = orig_module;
2598     }
2599
2600     /// Wraps the given definition in the appropriate number of `DefUpvar`
2601     /// wrappers.
2602     fn upvarify(&self,
2603                 ribs: &[Rib],
2604                 def_like: DefLike,
2605                 span: Span)
2606                 -> Option<DefLike> {
2607         match def_like {
2608             DlDef(d @ DefUpvar(..)) => {
2609                 self.session.span_bug(span,
2610                     format!("unexpected {} in bindings", d)[])
2611             }
2612             DlDef(d @ DefLocal(_)) => {
2613                 let node_id = d.def_id().node;
2614                 let mut def = d;
2615                 let mut last_proc_body_id = ast::DUMMY_NODE_ID;
2616                 for rib in ribs.iter() {
2617                     match rib.kind {
2618                         NormalRibKind => {
2619                             // Nothing to do. Continue.
2620                         }
2621                         ClosureRibKind(function_id, maybe_proc_body) => {
2622                             let prev_def = def;
2623                             if maybe_proc_body != ast::DUMMY_NODE_ID {
2624                                 last_proc_body_id = maybe_proc_body;
2625                             }
2626                             def = DefUpvar(node_id, function_id, last_proc_body_id);
2627
2628                             let mut seen = self.freevars_seen.borrow_mut();
2629                             let seen = match seen.entry(&function_id) {
2630                                 Occupied(v) => v.into_mut(),
2631                                 Vacant(v) => v.insert(NodeSet::new()),
2632                             };
2633                             if seen.contains(&node_id) {
2634                                 continue;
2635                             }
2636                             match self.freevars.borrow_mut().entry(&function_id) {
2637                                 Occupied(v) => v.into_mut(),
2638                                 Vacant(v) => v.insert(vec![]),
2639                             }.push(Freevar { def: prev_def, span: span });
2640                             seen.insert(node_id);
2641                         }
2642                         MethodRibKind(item_id, _) => {
2643                             // If the def is a ty param, and came from the parent
2644                             // item, it's ok
2645                             match def {
2646                                 DefTyParam(_, _, did, _) if {
2647                                     self.def_map.borrow().get(&did.node).cloned()
2648                                         == Some(DefTyParamBinder(item_id))
2649                                 } => {} // ok
2650                                 DefSelfTy(did) if did == item_id => {} // ok
2651                                 _ => {
2652                                     // This was an attempt to access an upvar inside a
2653                                     // named function item. This is not allowed, so we
2654                                     // report an error.
2655
2656                                     self.resolve_error(
2657                                         span,
2658                                         "can't capture dynamic environment in a fn item; \
2659                                         use the || { ... } closure form instead");
2660
2661                                     return None;
2662                                 }
2663                             }
2664                         }
2665                         ItemRibKind => {
2666                             // This was an attempt to access an upvar inside a
2667                             // named function item. This is not allowed, so we
2668                             // report an error.
2669
2670                             self.resolve_error(
2671                                 span,
2672                                 "can't capture dynamic environment in a fn item; \
2673                                 use the || { ... } closure form instead");
2674
2675                             return None;
2676                         }
2677                         ConstantItemRibKind => {
2678                             // Still doesn't deal with upvars
2679                             self.resolve_error(span,
2680                                                "attempt to use a non-constant \
2681                                                 value in a constant");
2682
2683                         }
2684                     }
2685                 }
2686                 Some(DlDef(def))
2687             }
2688             DlDef(def @ DefTyParam(..)) |
2689             DlDef(def @ DefSelfTy(..)) => {
2690                 for rib in ribs.iter() {
2691                     match rib.kind {
2692                         NormalRibKind | ClosureRibKind(..) => {
2693                             // Nothing to do. Continue.
2694                         }
2695                         MethodRibKind(item_id, _) => {
2696                             // If the def is a ty param, and came from the parent
2697                             // item, it's ok
2698                             match def {
2699                                 DefTyParam(_, _, did, _) if {
2700                                     self.def_map.borrow().get(&did.node).cloned()
2701                                         == Some(DefTyParamBinder(item_id))
2702                                 } => {} // ok
2703                                 DefSelfTy(did) if did == item_id => {} // ok
2704
2705                                 _ => {
2706                                     // This was an attempt to use a type parameter outside
2707                                     // its scope.
2708
2709                                     self.resolve_error(span,
2710                                                         "can't use type parameters from \
2711                                                         outer function; try using a local \
2712                                                         type parameter instead");
2713
2714                                     return None;
2715                                 }
2716                             }
2717                         }
2718                         ItemRibKind => {
2719                             // This was an attempt to use a type parameter outside
2720                             // its scope.
2721
2722                             self.resolve_error(span,
2723                                                "can't use type parameters from \
2724                                                 outer function; try using a local \
2725                                                 type parameter instead");
2726
2727                             return None;
2728                         }
2729                         ConstantItemRibKind => {
2730                             // see #9186
2731                             self.resolve_error(span,
2732                                                "cannot use an outer type \
2733                                                 parameter in this context");
2734
2735                         }
2736                     }
2737                 }
2738                 Some(DlDef(def))
2739             }
2740             _ => Some(def_like)
2741         }
2742     }
2743
2744     /// Searches the current set of local scopes and
2745     /// applies translations for closures.
2746     fn search_ribs(&self,
2747                    ribs: &[Rib],
2748                    name: Name,
2749                    span: Span)
2750                    -> Option<DefLike> {
2751         // FIXME #4950: Try caching?
2752
2753         for (i, rib) in ribs.iter().enumerate().rev() {
2754             match rib.bindings.get(&name).cloned() {
2755                 Some(def_like) => {
2756                     return self.upvarify(ribs[i + 1..], def_like, span);
2757                 }
2758                 None => {
2759                     // Continue.
2760                 }
2761             }
2762         }
2763
2764         None
2765     }
2766
2767     /// Searches the current set of local scopes for labels.
2768     /// Stops after meeting a closure.
2769     fn search_label(&self, name: Name) -> Option<DefLike> {
2770         for rib in self.label_ribs.iter().rev() {
2771             match rib.kind {
2772                 NormalRibKind => {
2773                     // Continue
2774                 }
2775                 _ => {
2776                     // Do not resolve labels across function boundary
2777                     return None
2778                 }
2779             }
2780             let result = rib.bindings.get(&name).cloned();
2781             if result.is_some() {
2782                 return result
2783             }
2784         }
2785         None
2786     }
2787
2788     fn resolve_crate(&mut self, krate: &ast::Crate) {
2789         debug!("(resolving crate) starting");
2790
2791         visit::walk_crate(self, krate);
2792     }
2793
2794     fn resolve_item(&mut self, item: &Item) {
2795         let name = item.ident.name;
2796
2797         debug!("(resolving item) resolving {}",
2798                token::get_name(name));
2799
2800         match item.node {
2801
2802             // enum item: resolve all the variants' discrs,
2803             // then resolve the ty params
2804             ItemEnum(ref enum_def, ref generics) => {
2805                 for variant in (*enum_def).variants.iter() {
2806                     for dis_expr in variant.node.disr_expr.iter() {
2807                         // resolve the discriminator expr
2808                         // as a constant
2809                         self.with_constant_rib(|this| {
2810                             this.resolve_expr(&**dis_expr);
2811                         });
2812                     }
2813                 }
2814
2815                 // n.b. the discr expr gets visited twice.
2816                 // but maybe it's okay since the first time will signal an
2817                 // error if there is one? -- tjc
2818                 self.with_type_parameter_rib(HasTypeParameters(generics,
2819                                                                TypeSpace,
2820                                                                item.id,
2821                                                                ItemRibKind),
2822                                              |this| {
2823                     this.resolve_type_parameters(&generics.ty_params);
2824                     this.resolve_where_clause(&generics.where_clause);
2825                     visit::walk_item(this, item);
2826                 });
2827             }
2828
2829             ItemTy(_, ref generics) => {
2830                 self.with_type_parameter_rib(HasTypeParameters(generics,
2831                                                                TypeSpace,
2832                                                                item.id,
2833                                                                ItemRibKind),
2834                                              |this| {
2835                     this.resolve_type_parameters(&generics.ty_params);
2836                     visit::walk_item(this, item);
2837                 });
2838             }
2839
2840             ItemImpl(_, _,
2841                      ref generics,
2842                      ref implemented_traits,
2843                      ref self_type,
2844                      ref impl_items) => {
2845                 self.resolve_implementation(item.id,
2846                                             generics,
2847                                             implemented_traits,
2848                                             &**self_type,
2849                                             impl_items[]);
2850             }
2851
2852             ItemTrait(_, ref generics, ref bounds, ref trait_items) => {
2853                 // Create a new rib for the self type.
2854                 let mut self_type_rib = Rib::new(ItemRibKind);
2855
2856                 // plain insert (no renaming, types are not currently hygienic....)
2857                 let name = self.type_self_name;
2858                 self_type_rib.bindings.insert(name, DlDef(DefSelfTy(item.id)));
2859                 self.type_ribs.push(self_type_rib);
2860
2861                 // Create a new rib for the trait-wide type parameters.
2862                 self.with_type_parameter_rib(HasTypeParameters(generics,
2863                                                                TypeSpace,
2864                                                                item.id,
2865                                                                NormalRibKind),
2866                                              |this| {
2867                     this.resolve_type_parameters(&generics.ty_params);
2868                     this.resolve_where_clause(&generics.where_clause);
2869
2870                     this.resolve_type_parameter_bounds(item.id, bounds,
2871                                                        TraitDerivation);
2872
2873                     for trait_item in (*trait_items).iter() {
2874                         // Create a new rib for the trait_item-specific type
2875                         // parameters.
2876                         //
2877                         // FIXME #4951: Do we need a node ID here?
2878
2879                         match *trait_item {
2880                           ast::RequiredMethod(ref ty_m) => {
2881                             this.with_type_parameter_rib
2882                                 (HasTypeParameters(&ty_m.generics,
2883                                                    FnSpace,
2884                                                    item.id,
2885                                         MethodRibKind(item.id, RequiredMethod)),
2886                                  |this| {
2887
2888                                 // Resolve the method-specific type
2889                                 // parameters.
2890                                 this.resolve_type_parameters(
2891                                     &ty_m.generics.ty_params);
2892                                 this.resolve_where_clause(&ty_m.generics
2893                                                                .where_clause);
2894
2895                                 for argument in ty_m.decl.inputs.iter() {
2896                                     this.resolve_type(&*argument.ty);
2897                                 }
2898
2899                                 if let SelfExplicit(ref typ, _) = ty_m.explicit_self.node {
2900                                     this.resolve_type(&**typ)
2901                                 }
2902
2903                                 if let ast::Return(ref ret_ty) = ty_m.decl.output {
2904                                     this.resolve_type(&**ret_ty);
2905                                 }
2906                             });
2907                           }
2908                           ast::ProvidedMethod(ref m) => {
2909                               this.resolve_method(MethodRibKind(item.id,
2910                                                                 ProvidedMethod(m.id)),
2911                                                   &**m)
2912                           }
2913                           ast::TypeTraitItem(ref data) => {
2914                               this.resolve_type_parameter(&data.ty_param);
2915                               visit::walk_trait_item(this, trait_item);
2916                           }
2917                         }
2918                     }
2919                 });
2920
2921                 self.type_ribs.pop();
2922             }
2923
2924             ItemStruct(ref struct_def, ref generics) => {
2925                 self.resolve_struct(item.id,
2926                                     generics,
2927                                     struct_def.fields[]);
2928             }
2929
2930             ItemMod(ref module_) => {
2931                 self.with_scope(Some(name), |this| {
2932                     this.resolve_module(module_, item.span, name,
2933                                         item.id);
2934                 });
2935             }
2936
2937             ItemForeignMod(ref foreign_module) => {
2938                 self.with_scope(Some(name), |this| {
2939                     for foreign_item in foreign_module.items.iter() {
2940                         match foreign_item.node {
2941                             ForeignItemFn(_, ref generics) => {
2942                                 this.with_type_parameter_rib(
2943                                     HasTypeParameters(
2944                                         generics, FnSpace, foreign_item.id,
2945                                         ItemRibKind),
2946                                     |this| visit::walk_foreign_item(this,
2947                                                                     &**foreign_item));
2948                             }
2949                             ForeignItemStatic(..) => {
2950                                 visit::walk_foreign_item(this,
2951                                                          &**foreign_item);
2952                             }
2953                         }
2954                     }
2955                 });
2956             }
2957
2958             ItemFn(ref fn_decl, _, _, ref generics, ref block) => {
2959                 self.resolve_function(ItemRibKind,
2960                                       Some(&**fn_decl),
2961                                       HasTypeParameters
2962                                         (generics,
2963                                          FnSpace,
2964                                          item.id,
2965                                          ItemRibKind),
2966                                       &**block);
2967             }
2968
2969             ItemConst(..) | ItemStatic(..) => {
2970                 self.with_constant_rib(|this| {
2971                     visit::walk_item(this, item);
2972                 });
2973             }
2974
2975            ItemMac(..) => {
2976                 // do nothing, these are just around to be encoded
2977            }
2978         }
2979     }
2980
2981     fn with_type_parameter_rib<F>(&mut self, type_parameters: TypeParameters, f: F) where
2982         F: FnOnce(&mut Resolver),
2983     {
2984         match type_parameters {
2985             HasTypeParameters(generics, space, node_id, rib_kind) => {
2986                 let mut function_type_rib = Rib::new(rib_kind);
2987                 let mut seen_bindings = HashSet::new();
2988                 for (index, type_parameter) in generics.ty_params.iter().enumerate() {
2989                     let name = type_parameter.ident.name;
2990                     debug!("with_type_parameter_rib: {} {}", node_id,
2991                            type_parameter.id);
2992
2993                     if seen_bindings.contains(&name) {
2994                         self.resolve_error(type_parameter.span,
2995                                            format!("the name `{}` is already \
2996                                                     used for a type \
2997                                                     parameter in this type \
2998                                                     parameter list",
2999                                                    token::get_name(
3000                                                        name))[])
3001                     }
3002                     seen_bindings.insert(name);
3003
3004                     let def_like = DlDef(DefTyParam(space,
3005                                                     index as u32,
3006                                                     local_def(type_parameter.id),
3007                                                     name));
3008                     // Associate this type parameter with
3009                     // the item that bound it
3010                     self.record_def(type_parameter.id,
3011                                     (DefTyParamBinder(node_id), LastMod(AllPublic)));
3012                     // plain insert (no renaming)
3013                     function_type_rib.bindings.insert(name, def_like);
3014                 }
3015                 self.type_ribs.push(function_type_rib);
3016             }
3017
3018             NoTypeParameters => {
3019                 // Nothing to do.
3020             }
3021         }
3022
3023         f(self);
3024
3025         match type_parameters {
3026             HasTypeParameters(..) => { self.type_ribs.pop(); }
3027             NoTypeParameters => { }
3028         }
3029     }
3030
3031     fn with_label_rib<F>(&mut self, f: F) where
3032         F: FnOnce(&mut Resolver),
3033     {
3034         self.label_ribs.push(Rib::new(NormalRibKind));
3035         f(self);
3036         self.label_ribs.pop();
3037     }
3038
3039     fn with_constant_rib<F>(&mut self, f: F) where
3040         F: FnOnce(&mut Resolver),
3041     {
3042         self.value_ribs.push(Rib::new(ConstantItemRibKind));
3043         self.type_ribs.push(Rib::new(ConstantItemRibKind));
3044         f(self);
3045         self.type_ribs.pop();
3046         self.value_ribs.pop();
3047     }
3048
3049     fn resolve_function(&mut self,
3050                         rib_kind: RibKind,
3051                         optional_declaration: Option<&FnDecl>,
3052                         type_parameters: TypeParameters,
3053                         block: &Block) {
3054         // Create a value rib for the function.
3055         let function_value_rib = Rib::new(rib_kind);
3056         self.value_ribs.push(function_value_rib);
3057
3058         // Create a label rib for the function.
3059         let function_label_rib = Rib::new(rib_kind);
3060         self.label_ribs.push(function_label_rib);
3061
3062         // If this function has type parameters, add them now.
3063         self.with_type_parameter_rib(type_parameters, |this| {
3064             // Resolve the type parameters.
3065             match type_parameters {
3066                 NoTypeParameters => {
3067                     // Continue.
3068                 }
3069                 HasTypeParameters(ref generics, _, _, _) => {
3070                     this.resolve_type_parameters(&generics.ty_params);
3071                     this.resolve_where_clause(&generics.where_clause);
3072                 }
3073             }
3074
3075             // Add each argument to the rib.
3076             match optional_declaration {
3077                 None => {
3078                     // Nothing to do.
3079                 }
3080                 Some(declaration) => {
3081                     let mut bindings_list = HashMap::new();
3082                     for argument in declaration.inputs.iter() {
3083                         this.resolve_pattern(&*argument.pat,
3084                                              ArgumentIrrefutableMode,
3085                                              &mut bindings_list);
3086
3087                         this.resolve_type(&*argument.ty);
3088
3089                         debug!("(resolving function) recorded argument");
3090                     }
3091
3092                     if let ast::Return(ref ret_ty) = declaration.output {
3093                         this.resolve_type(&**ret_ty);
3094                     }
3095                 }
3096             }
3097
3098             // Resolve the function body.
3099             this.resolve_block(&*block);
3100
3101             debug!("(resolving function) leaving function");
3102         });
3103
3104         self.label_ribs.pop();
3105         self.value_ribs.pop();
3106     }
3107
3108     fn resolve_type_parameters(&mut self,
3109                                type_parameters: &OwnedSlice<TyParam>) {
3110         for type_parameter in type_parameters.iter() {
3111             self.resolve_type_parameter(type_parameter);
3112         }
3113     }
3114
3115     fn resolve_type_parameter(&mut self,
3116                               type_parameter: &TyParam) {
3117         for bound in type_parameter.bounds.iter() {
3118             self.resolve_type_parameter_bound(type_parameter.id, bound,
3119                                               TraitBoundingTypeParameter);
3120         }
3121         match type_parameter.default {
3122             Some(ref ty) => self.resolve_type(&**ty),
3123             None => {}
3124         }
3125     }
3126
3127     fn resolve_type_parameter_bounds(&mut self,
3128                                      id: NodeId,
3129                                      type_parameter_bounds: &OwnedSlice<TyParamBound>,
3130                                      reference_type: TraitReferenceType) {
3131         for type_parameter_bound in type_parameter_bounds.iter() {
3132             self.resolve_type_parameter_bound(id, type_parameter_bound,
3133                                               reference_type);
3134         }
3135     }
3136
3137     fn resolve_type_parameter_bound(&mut self,
3138                                     id: NodeId,
3139                                     type_parameter_bound: &TyParamBound,
3140                                     reference_type: TraitReferenceType) {
3141         match *type_parameter_bound {
3142             TraitTyParamBound(ref tref, _) => {
3143                 self.resolve_poly_trait_reference(id, tref, reference_type)
3144             }
3145             RegionTyParamBound(..) => {}
3146         }
3147     }
3148
3149     fn resolve_poly_trait_reference(&mut self,
3150                                     id: NodeId,
3151                                     poly_trait_reference: &PolyTraitRef,
3152                                     reference_type: TraitReferenceType) {
3153         self.resolve_trait_reference(id, &poly_trait_reference.trait_ref, reference_type)
3154     }
3155
3156     fn resolve_trait_reference(&mut self,
3157                                id: NodeId,
3158                                trait_reference: &TraitRef,
3159                                reference_type: TraitReferenceType) {
3160         match self.resolve_path(id, &trait_reference.path, TypeNS, true) {
3161             None => {
3162                 let path_str = self.path_names_to_string(&trait_reference.path);
3163                 let usage_str = match reference_type {
3164                     TraitBoundingTypeParameter => "bound type parameter with",
3165                     TraitImplementation        => "implement",
3166                     TraitDerivation            => "derive",
3167                     TraitObject                => "reference",
3168                     TraitQPath                 => "extract an associated type from",
3169                 };
3170
3171                 let msg = format!("attempt to {} a nonexistent trait `{}`", usage_str, path_str);
3172                 self.resolve_error(trait_reference.path.span, msg[]);
3173             }
3174             Some(def) => {
3175                 match def {
3176                     (DefTrait(_), _) => {
3177                         debug!("(resolving trait) found trait def: {}", def);
3178                         self.record_def(trait_reference.ref_id, def);
3179                     }
3180                     (def, _) => {
3181                         self.resolve_error(trait_reference.path.span,
3182                                            format!("`{}` is not a trait",
3183                                                    self.path_names_to_string(
3184                                                        &trait_reference.path))[]);
3185
3186                         // If it's a typedef, give a note
3187                         if let DefTy(..) = def {
3188                             self.session.span_note(
3189                                 trait_reference.path.span,
3190                                 format!("`type` aliases cannot be used for traits")
3191                                     []);
3192                         }
3193                     }
3194                 }
3195             }
3196         }
3197     }
3198
3199     fn resolve_where_clause(&mut self, where_clause: &ast::WhereClause) {
3200         for predicate in where_clause.predicates.iter() {
3201             match predicate {
3202                 &ast::WherePredicate::BoundPredicate(ref bound_pred) => {
3203                     self.resolve_type(&*bound_pred.bounded_ty);
3204
3205                     for bound in bound_pred.bounds.iter() {
3206                         self.resolve_type_parameter_bound(bound_pred.bounded_ty.id, bound,
3207                                                           TraitBoundingTypeParameter);
3208                     }
3209                 }
3210                 &ast::WherePredicate::RegionPredicate(_) => {}
3211                 &ast::WherePredicate::EqPredicate(ref eq_pred) => {
3212                     match self.resolve_path(eq_pred.id, &eq_pred.path, TypeNS, true) {
3213                         Some((def @ DefTyParam(..), last_private)) => {
3214                             self.record_def(eq_pred.id, (def, last_private));
3215                         }
3216                         _ => {
3217                             self.resolve_error(eq_pred.path.span,
3218                                                "undeclared associated type");
3219                         }
3220                     }
3221
3222                     self.resolve_type(&*eq_pred.ty);
3223                 }
3224             }
3225         }
3226     }
3227
3228     fn resolve_struct(&mut self,
3229                       id: NodeId,
3230                       generics: &Generics,
3231                       fields: &[StructField]) {
3232         // If applicable, create a rib for the type parameters.
3233         self.with_type_parameter_rib(HasTypeParameters(generics,
3234                                                        TypeSpace,
3235                                                        id,
3236                                                        ItemRibKind),
3237                                      |this| {
3238             // Resolve the type parameters.
3239             this.resolve_type_parameters(&generics.ty_params);
3240             this.resolve_where_clause(&generics.where_clause);
3241
3242             // Resolve fields.
3243             for field in fields.iter() {
3244                 this.resolve_type(&*field.node.ty);
3245             }
3246         });
3247     }
3248
3249     // Does this really need to take a RibKind or is it always going
3250     // to be NormalRibKind?
3251     fn resolve_method(&mut self,
3252                       rib_kind: RibKind,
3253                       method: &ast::Method) {
3254         let method_generics = method.pe_generics();
3255         let type_parameters = HasTypeParameters(method_generics,
3256                                                 FnSpace,
3257                                                 method.id,
3258                                                 rib_kind);
3259
3260         if let SelfExplicit(ref typ, _) = method.pe_explicit_self().node {
3261             self.resolve_type(&**typ);
3262         }
3263
3264         self.resolve_function(rib_kind,
3265                               Some(method.pe_fn_decl()),
3266                               type_parameters,
3267                               method.pe_body());
3268     }
3269
3270     fn with_current_self_type<T, F>(&mut self, self_type: &Ty, f: F) -> T where
3271         F: FnOnce(&mut Resolver) -> T,
3272     {
3273         // Handle nested impls (inside fn bodies)
3274         let previous_value = replace(&mut self.current_self_type, Some(self_type.clone()));
3275         let result = f(self);
3276         self.current_self_type = previous_value;
3277         result
3278     }
3279
3280     fn with_optional_trait_ref<T, F>(&mut self, id: NodeId,
3281                                      opt_trait_ref: &Option<TraitRef>,
3282                                      f: F) -> T where
3283         F: FnOnce(&mut Resolver) -> T,
3284     {
3285         let new_val = match *opt_trait_ref {
3286             Some(ref trait_ref) => {
3287                 self.resolve_trait_reference(id, trait_ref, TraitImplementation);
3288
3289                 match self.def_map.borrow().get(&trait_ref.ref_id) {
3290                     Some(def) => {
3291                         let did = def.def_id();
3292                         Some((did, trait_ref.clone()))
3293                     }
3294                     None => None
3295                 }
3296             }
3297             None => None
3298         };
3299         let original_trait_ref = replace(&mut self.current_trait_ref, new_val);
3300         let result = f(self);
3301         self.current_trait_ref = original_trait_ref;
3302         result
3303     }
3304
3305     fn resolve_implementation(&mut self,
3306                               id: NodeId,
3307                               generics: &Generics,
3308                               opt_trait_reference: &Option<TraitRef>,
3309                               self_type: &Ty,
3310                               impl_items: &[ImplItem]) {
3311         // If applicable, create a rib for the type parameters.
3312         self.with_type_parameter_rib(HasTypeParameters(generics,
3313                                                        TypeSpace,
3314                                                        id,
3315                                                        NormalRibKind),
3316                                      |this| {
3317             // Resolve the type parameters.
3318             this.resolve_type_parameters(&generics.ty_params);
3319             this.resolve_where_clause(&generics.where_clause);
3320
3321             // Resolve the trait reference, if necessary.
3322             this.with_optional_trait_ref(id, opt_trait_reference, |this| {
3323                 // Resolve the self type.
3324                 this.resolve_type(self_type);
3325
3326                 this.with_current_self_type(self_type, |this| {
3327                     for impl_item in impl_items.iter() {
3328                         match *impl_item {
3329                             MethodImplItem(ref method) => {
3330                                 // If this is a trait impl, ensure the method
3331                                 // exists in trait
3332                                 this.check_trait_item(method.pe_ident().name,
3333                                                       method.span);
3334
3335                                 // We also need a new scope for the method-
3336                                 // specific type parameters.
3337                                 this.resolve_method(
3338                                     MethodRibKind(id, ProvidedMethod(method.id)),
3339                                     &**method);
3340                             }
3341                             TypeImplItem(ref typedef) => {
3342                                 // If this is a trait impl, ensure the method
3343                                 // exists in trait
3344                                 this.check_trait_item(typedef.ident.name,
3345                                                       typedef.span);
3346
3347                                 this.resolve_type(&*typedef.typ);
3348                             }
3349                         }
3350                     }
3351                 });
3352             });
3353         });
3354
3355         // Check that the current type is indeed a type, if we have an anonymous impl
3356         if opt_trait_reference.is_none() {
3357             match self_type.node {
3358                 // TyPath is the only thing that we handled in `build_reduced_graph_for_item`,
3359                 // where we created a module with the name of the type in order to implement
3360                 // an anonymous trait. In the case that the path does not resolve to an actual
3361                 // type, the result will be that the type name resolves to a module but not
3362                 // a type (shadowing any imported modules or types with this name), leading
3363                 // to weird user-visible bugs. So we ward this off here. See #15060.
3364                 TyPath(ref path, path_id) => {
3365                     match self.def_map.borrow().get(&path_id) {
3366                         // FIXME: should we catch other options and give more precise errors?
3367                         Some(&DefMod(_)) => {
3368                             self.resolve_error(path.span, "inherent implementations are not \
3369                                                            allowed for types not defined in \
3370                                                            the current module");
3371                         }
3372                         _ => {}
3373                     }
3374                 }
3375                 _ => { }
3376             }
3377         }
3378     }
3379
3380     fn check_trait_item(&self, name: Name, span: Span) {
3381         // If there is a TraitRef in scope for an impl, then the method must be in the trait.
3382         for &(did, ref trait_ref) in self.current_trait_ref.iter() {
3383             if self.trait_item_map.get(&(name, did)).is_none() {
3384                 let path_str = self.path_names_to_string(&trait_ref.path);
3385                 self.resolve_error(span,
3386                                     format!("method `{}` is not a member of trait `{}`",
3387                                             token::get_name(name),
3388                                             path_str)[]);
3389             }
3390         }
3391     }
3392
3393     fn resolve_module(&mut self, module: &Mod, _span: Span,
3394                       _name: Name, id: NodeId) {
3395         // Write the implementations in scope into the module metadata.
3396         debug!("(resolving module) resolving module ID {}", id);
3397         visit::walk_mod(self, module);
3398     }
3399
3400     fn resolve_local(&mut self, local: &Local) {
3401         // Resolve the type.
3402         if let Some(ref ty) = local.ty {
3403             self.resolve_type(&**ty);
3404         }
3405
3406         // Resolve the initializer, if necessary.
3407         match local.init {
3408             None => {
3409                 // Nothing to do.
3410             }
3411             Some(ref initializer) => {
3412                 self.resolve_expr(&**initializer);
3413             }
3414         }
3415
3416         // Resolve the pattern.
3417         let mut bindings_list = HashMap::new();
3418         self.resolve_pattern(&*local.pat,
3419                              LocalIrrefutableMode,
3420                              &mut bindings_list);
3421     }
3422
3423     // build a map from pattern identifiers to binding-info's.
3424     // this is done hygienically. This could arise for a macro
3425     // that expands into an or-pattern where one 'x' was from the
3426     // user and one 'x' came from the macro.
3427     fn binding_mode_map(&mut self, pat: &Pat) -> BindingMap {
3428         let mut result = HashMap::new();
3429         pat_bindings(&self.def_map, pat, |binding_mode, _id, sp, path1| {
3430             let name = mtwt::resolve(path1.node);
3431             result.insert(name, BindingInfo {
3432                 span: sp,
3433                 binding_mode: binding_mode
3434             });
3435         });
3436         return result;
3437     }
3438
3439     // check that all of the arms in an or-pattern have exactly the
3440     // same set of bindings, with the same binding modes for each.
3441     fn check_consistent_bindings(&mut self, arm: &Arm) {
3442         if arm.pats.len() == 0 {
3443             return
3444         }
3445         let map_0 = self.binding_mode_map(&*arm.pats[0]);
3446         for (i, p) in arm.pats.iter().enumerate() {
3447             let map_i = self.binding_mode_map(&**p);
3448
3449             for (&key, &binding_0) in map_0.iter() {
3450                 match map_i.get(&key) {
3451                   None => {
3452                     self.resolve_error(
3453                         p.span,
3454                         format!("variable `{}` from pattern #1 is \
3455                                   not bound in pattern #{}",
3456                                 token::get_name(key),
3457                                 i + 1)[]);
3458                   }
3459                   Some(binding_i) => {
3460                     if binding_0.binding_mode != binding_i.binding_mode {
3461                         self.resolve_error(
3462                             binding_i.span,
3463                             format!("variable `{}` is bound with different \
3464                                       mode in pattern #{} than in pattern #1",
3465                                     token::get_name(key),
3466                                     i + 1)[]);
3467                     }
3468                   }
3469                 }
3470             }
3471
3472             for (&key, &binding) in map_i.iter() {
3473                 if !map_0.contains_key(&key) {
3474                     self.resolve_error(
3475                         binding.span,
3476                         format!("variable `{}` from pattern {}{} is \
3477                                   not bound in pattern {}1",
3478                                 token::get_name(key),
3479                                 "#", i + 1, "#")[]);
3480                 }
3481             }
3482         }
3483     }
3484
3485     fn resolve_arm(&mut self, arm: &Arm) {
3486         self.value_ribs.push(Rib::new(NormalRibKind));
3487
3488         let mut bindings_list = HashMap::new();
3489         for pattern in arm.pats.iter() {
3490             self.resolve_pattern(&**pattern, RefutableMode, &mut bindings_list);
3491         }
3492
3493         // This has to happen *after* we determine which
3494         // pat_idents are variants
3495         self.check_consistent_bindings(arm);
3496
3497         visit::walk_expr_opt(self, &arm.guard);
3498         self.resolve_expr(&*arm.body);
3499
3500         self.value_ribs.pop();
3501     }
3502
3503     fn resolve_block(&mut self, block: &Block) {
3504         debug!("(resolving block) entering block");
3505         self.value_ribs.push(Rib::new(NormalRibKind));
3506
3507         // Move down in the graph, if there's an anonymous module rooted here.
3508         let orig_module = self.current_module.clone();
3509         match orig_module.anonymous_children.borrow().get(&block.id) {
3510             None => { /* Nothing to do. */ }
3511             Some(anonymous_module) => {
3512                 debug!("(resolving block) found anonymous module, moving \
3513                         down");
3514                 self.current_module = anonymous_module.clone();
3515             }
3516         }
3517
3518         // Descend into the block.
3519         visit::walk_block(self, block);
3520
3521         // Move back up.
3522         self.current_module = orig_module;
3523
3524         self.value_ribs.pop();
3525         debug!("(resolving block) leaving block");
3526     }
3527
3528     fn resolve_type(&mut self, ty: &Ty) {
3529         match ty.node {
3530             // Like path expressions, the interpretation of path types depends
3531             // on whether the path has multiple elements in it or not.
3532
3533             TyPath(ref path, path_id) => {
3534                 // This is a path in the type namespace. Walk through scopes
3535                 // looking for it.
3536                 let mut result_def = None;
3537
3538                 // First, check to see whether the name is a primitive type.
3539                 if path.segments.len() == 1 {
3540                     let id = path.segments.last().unwrap().identifier;
3541
3542                     match self.primitive_type_table
3543                             .primitive_types
3544                             .get(&id.name) {
3545
3546                         Some(&primitive_type) => {
3547                             result_def =
3548                                 Some((DefPrimTy(primitive_type), LastMod(AllPublic)));
3549
3550                             if path.segments[0].parameters.has_lifetimes() {
3551                                 span_err!(self.session, path.span, E0157,
3552                                     "lifetime parameters are not allowed on this type");
3553                             } else if !path.segments[0].parameters.is_empty() {
3554                                 span_err!(self.session, path.span, E0153,
3555                                     "type parameters are not allowed on this type");
3556                             }
3557                         }
3558                         None => {
3559                             // Continue.
3560                         }
3561                     }
3562                 }
3563
3564                 match result_def {
3565                     None => {
3566                         match self.resolve_path(ty.id, path, TypeNS, true) {
3567                             Some(def) => {
3568                                 debug!("(resolving type) resolved `{}` to \
3569                                         type {}",
3570                                        token::get_ident(path.segments.last().unwrap() .identifier),
3571                                        def);
3572                                 result_def = Some(def);
3573                             }
3574                             None => {
3575                                 result_def = None;
3576                             }
3577                         }
3578                     }
3579                     Some(_) => {}   // Continue.
3580                 }
3581
3582                 match result_def {
3583                     Some(def) => {
3584                         // Write the result into the def map.
3585                         debug!("(resolving type) writing resolution for `{}` \
3586                                 (id {})",
3587                                self.path_names_to_string(path),
3588                                path_id);
3589                         self.record_def(path_id, def);
3590                     }
3591                     None => {
3592                         let msg = format!("use of undeclared type name `{}`",
3593                                           self.path_names_to_string(path));
3594                         self.resolve_error(ty.span, msg[]);
3595                     }
3596                 }
3597             }
3598
3599             TyObjectSum(ref ty, ref bound_vec) => {
3600                 self.resolve_type(&**ty);
3601                 self.resolve_type_parameter_bounds(ty.id, bound_vec,
3602                                                        TraitBoundingTypeParameter);
3603             }
3604
3605             TyQPath(ref qpath) => {
3606                 self.resolve_type(&*qpath.self_type);
3607                 self.resolve_trait_reference(ty.id, &*qpath.trait_ref, TraitQPath);
3608             }
3609
3610             TyPolyTraitRef(ref bounds) => {
3611                 self.resolve_type_parameter_bounds(
3612                     ty.id,
3613                     bounds,
3614                     TraitObject);
3615                 visit::walk_ty(self, ty);
3616             }
3617             _ => {
3618                 // Just resolve embedded types.
3619                 visit::walk_ty(self, ty);
3620             }
3621         }
3622     }
3623
3624     fn resolve_pattern(&mut self,
3625                        pattern: &Pat,
3626                        mode: PatternBindingMode,
3627                        // Maps idents to the node ID for the (outermost)
3628                        // pattern that binds them
3629                        bindings_list: &mut HashMap<Name, NodeId>) {
3630         let pat_id = pattern.id;
3631         walk_pat(pattern, |pattern| {
3632             match pattern.node {
3633                 PatIdent(binding_mode, ref path1, _) => {
3634
3635                     // The meaning of pat_ident with no type parameters
3636                     // depends on whether an enum variant or unit-like struct
3637                     // with that name is in scope. The probing lookup has to
3638                     // be careful not to emit spurious errors. Only matching
3639                     // patterns (match) can match nullary variants or
3640                     // unit-like structs. For binding patterns (let), matching
3641                     // such a value is simply disallowed (since it's rarely
3642                     // what you want).
3643
3644                     let ident = path1.node;
3645                     let renamed = mtwt::resolve(ident);
3646
3647                     match self.resolve_bare_identifier_pattern(ident.name, pattern.span) {
3648                         FoundStructOrEnumVariant(ref def, lp)
3649                                 if mode == RefutableMode => {
3650                             debug!("(resolving pattern) resolving `{}` to \
3651                                     struct or enum variant",
3652                                    token::get_name(renamed));
3653
3654                             self.enforce_default_binding_mode(
3655                                 pattern,
3656                                 binding_mode,
3657                                 "an enum variant");
3658                             self.record_def(pattern.id, (def.clone(), lp));
3659                         }
3660                         FoundStructOrEnumVariant(..) => {
3661                             self.resolve_error(
3662                                 pattern.span,
3663                                 format!("declaration of `{}` shadows an enum \
3664                                          variant or unit-like struct in \
3665                                          scope",
3666                                         token::get_name(renamed))[]);
3667                         }
3668                         FoundConst(ref def, lp) if mode == RefutableMode => {
3669                             debug!("(resolving pattern) resolving `{}` to \
3670                                     constant",
3671                                    token::get_name(renamed));
3672
3673                             self.enforce_default_binding_mode(
3674                                 pattern,
3675                                 binding_mode,
3676                                 "a constant");
3677                             self.record_def(pattern.id, (def.clone(), lp));
3678                         }
3679                         FoundConst(..) => {
3680                             self.resolve_error(pattern.span,
3681                                                   "only irrefutable patterns \
3682                                                    allowed here");
3683                         }
3684                         BareIdentifierPatternUnresolved => {
3685                             debug!("(resolving pattern) binding `{}`",
3686                                    token::get_name(renamed));
3687
3688                             let def = DefLocal(pattern.id);
3689
3690                             // Record the definition so that later passes
3691                             // will be able to distinguish variants from
3692                             // locals in patterns.
3693
3694                             self.record_def(pattern.id, (def, LastMod(AllPublic)));
3695
3696                             // Add the binding to the local ribs, if it
3697                             // doesn't already exist in the bindings list. (We
3698                             // must not add it if it's in the bindings list
3699                             // because that breaks the assumptions later
3700                             // passes make about or-patterns.)
3701                             if !bindings_list.contains_key(&renamed) {
3702                                 let this = &mut *self;
3703                                 let last_rib = this.value_ribs.last_mut().unwrap();
3704                                 last_rib.bindings.insert(renamed, DlDef(def));
3705                                 bindings_list.insert(renamed, pat_id);
3706                             } else if mode == ArgumentIrrefutableMode &&
3707                                     bindings_list.contains_key(&renamed) {
3708                                 // Forbid duplicate bindings in the same
3709                                 // parameter list.
3710                                 self.resolve_error(pattern.span,
3711                                                    format!("identifier `{}` \
3712                                                             is bound more \
3713                                                             than once in \
3714                                                             this parameter \
3715                                                             list",
3716                                                            token::get_ident(
3717                                                                ident))
3718                                                    [])
3719                             } else if bindings_list.get(&renamed) ==
3720                                     Some(&pat_id) {
3721                                 // Then this is a duplicate variable in the
3722                                 // same disjunction, which is an error.
3723                                 self.resolve_error(pattern.span,
3724                                     format!("identifier `{}` is bound \
3725                                              more than once in the same \
3726                                              pattern",
3727                                             token::get_ident(ident))[]);
3728                             }
3729                             // Else, not bound in the same pattern: do
3730                             // nothing.
3731                         }
3732                     }
3733                 }
3734
3735                 PatEnum(ref path, _) => {
3736                     // This must be an enum variant, struct or const.
3737                     match self.resolve_path(pat_id, path, ValueNS, false) {
3738                         Some(def @ (DefVariant(..), _)) |
3739                         Some(def @ (DefStruct(..), _))  |
3740                         Some(def @ (DefConst(..), _)) => {
3741                             self.record_def(pattern.id, def);
3742                         }
3743                         Some((DefStatic(..), _)) => {
3744                             self.resolve_error(path.span,
3745                                                "static variables cannot be \
3746                                                 referenced in a pattern, \
3747                                                 use a `const` instead");
3748                         }
3749                         Some(_) => {
3750                             self.resolve_error(path.span,
3751                                 format!("`{}` is not an enum variant, struct or const",
3752                                     token::get_ident(
3753                                         path.segments.last().unwrap().identifier))[]);
3754                         }
3755                         None => {
3756                             self.resolve_error(path.span,
3757                                 format!("unresolved enum variant, struct or const `{}`",
3758                                     token::get_ident(
3759                                         path.segments.last().unwrap().identifier))[]);
3760                         }
3761                     }
3762
3763                     // Check the types in the path pattern.
3764                     for ty in path.segments
3765                                   .iter()
3766                                   .flat_map(|s| s.parameters.types().into_iter()) {
3767                         self.resolve_type(&**ty);
3768                     }
3769                 }
3770
3771                 PatLit(ref expr) => {
3772                     self.resolve_expr(&**expr);
3773                 }
3774
3775                 PatRange(ref first_expr, ref last_expr) => {
3776                     self.resolve_expr(&**first_expr);
3777                     self.resolve_expr(&**last_expr);
3778                 }
3779
3780                 PatStruct(ref path, _, _) => {
3781                     match self.resolve_path(pat_id, path, TypeNS, false) {
3782                         Some(definition) => {
3783                             self.record_def(pattern.id, definition);
3784                         }
3785                         result => {
3786                             debug!("(resolving pattern) didn't find struct \
3787                                     def: {}", result);
3788                             let msg = format!("`{}` does not name a structure",
3789                                               self.path_names_to_string(path));
3790                             self.resolve_error(path.span, msg[]);
3791                         }
3792                     }
3793                 }
3794
3795                 _ => {
3796                     // Nothing to do.
3797                 }
3798             }
3799             true
3800         });
3801     }
3802
3803     fn resolve_bare_identifier_pattern(&mut self, name: Name, span: Span)
3804                                        -> BareIdentifierPatternResolution {
3805         let module = self.current_module.clone();
3806         match self.resolve_item_in_lexical_scope(module,
3807                                                  name,
3808                                                  ValueNS) {
3809             Success((target, _)) => {
3810                 debug!("(resolve bare identifier pattern) succeeded in \
3811                          finding {} at {}",
3812                         token::get_name(name),
3813                         target.bindings.value_def.borrow());
3814                 match *target.bindings.value_def.borrow() {
3815                     None => {
3816                         panic!("resolved name in the value namespace to a \
3817                               set of name bindings with no def?!");
3818                     }
3819                     Some(def) => {
3820                         // For the two success cases, this lookup can be
3821                         // considered as not having a private component because
3822                         // the lookup happened only within the current module.
3823                         match def.def {
3824                             def @ DefVariant(..) | def @ DefStruct(..) => {
3825                                 return FoundStructOrEnumVariant(def, LastMod(AllPublic));
3826                             }
3827                             def @ DefConst(..) => {
3828                                 return FoundConst(def, LastMod(AllPublic));
3829                             }
3830                             DefStatic(..) => {
3831                                 self.resolve_error(span,
3832                                                    "static variables cannot be \
3833                                                     referenced in a pattern, \
3834                                                     use a `const` instead");
3835                                 return BareIdentifierPatternUnresolved;
3836                             }
3837                             _ => {
3838                                 return BareIdentifierPatternUnresolved;
3839                             }
3840                         }
3841                     }
3842                 }
3843             }
3844
3845             Indeterminate => {
3846                 panic!("unexpected indeterminate result");
3847             }
3848             Failed(err) => {
3849                 match err {
3850                     Some((span, msg)) => {
3851                         self.resolve_error(span, format!("failed to resolve: {}",
3852                                                          msg)[]);
3853                     }
3854                     None => ()
3855                 }
3856
3857                 debug!("(resolve bare identifier pattern) failed to find {}",
3858                         token::get_name(name));
3859                 return BareIdentifierPatternUnresolved;
3860             }
3861         }
3862     }
3863
3864     /// If `check_ribs` is true, checks the local definitions first; i.e.
3865     /// doesn't skip straight to the containing module.
3866     fn resolve_path(&mut self,
3867                     id: NodeId,
3868                     path: &Path,
3869                     namespace: Namespace,
3870                     check_ribs: bool) -> Option<(Def, LastPrivate)> {
3871         // First, resolve the types and associated type bindings.
3872         for ty in path.segments.iter().flat_map(|s| s.parameters.types().into_iter()) {
3873             self.resolve_type(&**ty);
3874         }
3875         for binding in path.segments.iter().flat_map(|s| s.parameters.bindings().into_iter()) {
3876             self.resolve_type(&*binding.ty);
3877         }
3878
3879         // A special case for sugared associated type paths `T::A` where `T` is
3880         // a type parameter and `A` is an associated type on some bound of `T`.
3881         if namespace == TypeNS && path.segments.len() == 2 {
3882             match self.resolve_identifier(path.segments[0].identifier,
3883                                           TypeNS,
3884                                           true,
3885                                           path.span) {
3886                 Some((def, last_private)) => {
3887                     match def {
3888                         DefTyParam(_, _, did, _) => {
3889                             let def = DefAssociatedPath(TyParamProvenance::FromParam(did),
3890                                                         path.segments.last()
3891                                                             .unwrap().identifier);
3892                             return Some((def, last_private));
3893                         }
3894                         DefSelfTy(nid) => {
3895                             let def = DefAssociatedPath(TyParamProvenance::FromSelf(local_def(nid)),
3896                                                         path.segments.last()
3897                                                             .unwrap().identifier);
3898                             return Some((def, last_private));
3899                         }
3900                         _ => {}
3901                     }
3902                 }
3903                 _ => {}
3904             }
3905         }
3906
3907         if path.global {
3908             return self.resolve_crate_relative_path(path, namespace);
3909         }
3910
3911         // Try to find a path to an item in a module.
3912         let unqualified_def =
3913                 self.resolve_identifier(path.segments.last().unwrap().identifier,
3914                                         namespace,
3915                                         check_ribs,
3916                                         path.span);
3917
3918         if path.segments.len() > 1 {
3919             let def = self.resolve_module_relative_path(path, namespace);
3920             match (def, unqualified_def) {
3921                 (Some((ref d, _)), Some((ref ud, _))) if *d == *ud => {
3922                     self.session
3923                         .add_lint(lint::builtin::UNUSED_QUALIFICATIONS,
3924                                   id,
3925                                   path.span,
3926                                   "unnecessary qualification".to_string());
3927                 }
3928                 _ => ()
3929             }
3930
3931             return def;
3932         }
3933
3934         return unqualified_def;
3935     }
3936
3937     // resolve a single identifier (used as a varref)
3938     fn resolve_identifier(&mut self,
3939                           identifier: Ident,
3940                           namespace: Namespace,
3941                           check_ribs: bool,
3942                           span: Span)
3943                           -> Option<(Def, LastPrivate)> {
3944         if check_ribs {
3945             match self.resolve_identifier_in_local_ribs(identifier,
3946                                                         namespace,
3947                                                         span) {
3948                 Some(def) => {
3949                     return Some((def, LastMod(AllPublic)));
3950                 }
3951                 None => {
3952                     // Continue.
3953                 }
3954             }
3955         }
3956
3957         return self.resolve_item_by_name_in_lexical_scope(identifier.name, namespace);
3958     }
3959
3960     // FIXME #4952: Merge me with resolve_name_in_module?
3961     fn resolve_definition_of_name_in_module(&mut self,
3962                                             containing_module: Rc<Module>,
3963                                             name: Name,
3964                                             namespace: Namespace)
3965                                             -> NameDefinition {
3966         // First, search children.
3967         build_reduced_graph::populate_module_if_necessary(self, &containing_module);
3968
3969         match containing_module.children.borrow().get(&name) {
3970             Some(child_name_bindings) => {
3971                 match child_name_bindings.def_for_namespace(namespace) {
3972                     Some(def) => {
3973                         // Found it. Stop the search here.
3974                         let p = child_name_bindings.defined_in_public_namespace(
3975                                         namespace);
3976                         let lp = if p {LastMod(AllPublic)} else {
3977                             LastMod(DependsOn(def.def_id()))
3978                         };
3979                         return ChildNameDefinition(def, lp);
3980                     }
3981                     None => {}
3982                 }
3983             }
3984             None => {}
3985         }
3986
3987         // Next, search import resolutions.
3988         match containing_module.import_resolutions.borrow().get(&name) {
3989             Some(import_resolution) if import_resolution.is_public => {
3990                 if let Some(target) = (*import_resolution).target_for_namespace(namespace) {
3991                     match target.bindings.def_for_namespace(namespace) {
3992                         Some(def) => {
3993                             // Found it.
3994                             let id = import_resolution.id(namespace);
3995                             // track imports and extern crates as well
3996                             self.used_imports.insert((id, namespace));
3997                             self.record_import_use(id, name);
3998                             match target.target_module.def_id.get() {
3999                                 Some(DefId{krate: kid, ..}) => {
4000                                     self.used_crates.insert(kid);
4001                                 },
4002                                 _ => {}
4003                             }
4004                             return ImportNameDefinition(def, LastMod(AllPublic));
4005                         }
4006                         None => {
4007                             // This can happen with external impls, due to
4008                             // the imperfect way we read the metadata.
4009                         }
4010                     }
4011                 }
4012             }
4013             Some(..) | None => {} // Continue.
4014         }
4015
4016         // Finally, search through external children.
4017         if namespace == TypeNS {
4018             if let Some(module) = containing_module.external_module_children.borrow()
4019                                                    .get(&name).cloned() {
4020                 if let Some(def_id) = module.def_id.get() {
4021                     // track used crates
4022                     self.used_crates.insert(def_id.krate);
4023                     let lp = if module.is_public {LastMod(AllPublic)} else {
4024                         LastMod(DependsOn(def_id))
4025                     };
4026                     return ChildNameDefinition(DefMod(def_id), lp);
4027                 }
4028             }
4029         }
4030
4031         return NoNameDefinition;
4032     }
4033
4034     // resolve a "module-relative" path, e.g. a::b::c
4035     fn resolve_module_relative_path(&mut self,
4036                                     path: &Path,
4037                                     namespace: Namespace)
4038                                     -> Option<(Def, LastPrivate)> {
4039         let module_path = path.segments.init().iter()
4040                                               .map(|ps| ps.identifier.name)
4041                                               .collect::<Vec<_>>();
4042
4043         let containing_module;
4044         let last_private;
4045         let module = self.current_module.clone();
4046         match self.resolve_module_path(module,
4047                                        module_path[],
4048                                        UseLexicalScope,
4049                                        path.span,
4050                                        PathSearch) {
4051             Failed(err) => {
4052                 let (span, msg) = match err {
4053                     Some((span, msg)) => (span, msg),
4054                     None => {
4055                         let msg = format!("Use of undeclared type or module `{}`",
4056                                           self.names_to_string(module_path.as_slice()));
4057                         (path.span, msg)
4058                     }
4059                 };
4060
4061                 self.resolve_error(span, format!("failed to resolve. {}",
4062                                                  msg)[]);
4063                 return None;
4064             }
4065             Indeterminate => panic!("indeterminate unexpected"),
4066             Success((resulting_module, resulting_last_private)) => {
4067                 containing_module = resulting_module;
4068                 last_private = resulting_last_private;
4069             }
4070         }
4071
4072         let name = path.segments.last().unwrap().identifier.name;
4073         let def = match self.resolve_definition_of_name_in_module(containing_module.clone(),
4074                                                                   name,
4075                                                                   namespace) {
4076             NoNameDefinition => {
4077                 // We failed to resolve the name. Report an error.
4078                 return None;
4079             }
4080             ChildNameDefinition(def, lp) | ImportNameDefinition(def, lp) => {
4081                 (def, last_private.or(lp))
4082             }
4083         };
4084         if let Some(DefId{krate: kid, ..}) = containing_module.def_id.get() {
4085             self.used_crates.insert(kid);
4086         }
4087         return Some(def);
4088     }
4089
4090     /// Invariant: This must be called only during main resolution, not during
4091     /// import resolution.
4092     fn resolve_crate_relative_path(&mut self,
4093                                    path: &Path,
4094                                    namespace: Namespace)
4095                                        -> Option<(Def, LastPrivate)> {
4096         let module_path = path.segments.init().iter()
4097                                               .map(|ps| ps.identifier.name)
4098                                               .collect::<Vec<_>>();
4099
4100         let root_module = self.graph_root.get_module();
4101
4102         let containing_module;
4103         let last_private;
4104         match self.resolve_module_path_from_root(root_module,
4105                                                  module_path[],
4106                                                  0,
4107                                                  path.span,
4108                                                  PathSearch,
4109                                                  LastMod(AllPublic)) {
4110             Failed(err) => {
4111                 let (span, msg) = match err {
4112                     Some((span, msg)) => (span, msg),
4113                     None => {
4114                         let msg = format!("Use of undeclared module `::{}`",
4115                                           self.names_to_string(module_path[]));
4116                         (path.span, msg)
4117                     }
4118                 };
4119
4120                 self.resolve_error(span, format!("failed to resolve. {}",
4121                                                  msg)[]);
4122                 return None;
4123             }
4124
4125             Indeterminate => {
4126                 panic!("indeterminate unexpected");
4127             }
4128
4129             Success((resulting_module, resulting_last_private)) => {
4130                 containing_module = resulting_module;
4131                 last_private = resulting_last_private;
4132             }
4133         }
4134
4135         let name = path.segments.last().unwrap().identifier.name;
4136         match self.resolve_definition_of_name_in_module(containing_module,
4137                                                         name,
4138                                                         namespace) {
4139             NoNameDefinition => {
4140                 // We failed to resolve the name. Report an error.
4141                 return None;
4142             }
4143             ChildNameDefinition(def, lp) | ImportNameDefinition(def, lp) => {
4144                 return Some((def, last_private.or(lp)));
4145             }
4146         }
4147     }
4148
4149     fn resolve_identifier_in_local_ribs(&mut self,
4150                                         ident: Ident,
4151                                         namespace: Namespace,
4152                                         span: Span)
4153                                         -> Option<Def> {
4154         // Check the local set of ribs.
4155         let search_result = match namespace {
4156             ValueNS => {
4157                 let renamed = mtwt::resolve(ident);
4158                 self.search_ribs(self.value_ribs.as_slice(), renamed, span)
4159             }
4160             TypeNS => {
4161                 let name = ident.name;
4162                 self.search_ribs(self.type_ribs[], name, span)
4163             }
4164         };
4165
4166         match search_result {
4167             Some(DlDef(def)) => {
4168                 debug!("(resolving path in local ribs) resolved `{}` to \
4169                         local: {}",
4170                        token::get_ident(ident),
4171                        def);
4172                 return Some(def);
4173             }
4174             Some(DlField) | Some(DlImpl(_)) | None => {
4175                 return None;
4176             }
4177         }
4178     }
4179
4180     fn resolve_item_by_name_in_lexical_scope(&mut self,
4181                                              name: Name,
4182                                              namespace: Namespace)
4183                                             -> Option<(Def, LastPrivate)> {
4184         // Check the items.
4185         let module = self.current_module.clone();
4186         match self.resolve_item_in_lexical_scope(module,
4187                                                  name,
4188                                                  namespace) {
4189             Success((target, _)) => {
4190                 match (*target.bindings).def_for_namespace(namespace) {
4191                     None => {
4192                         // This can happen if we were looking for a type and
4193                         // found a module instead. Modules don't have defs.
4194                         debug!("(resolving item path by identifier in lexical \
4195                                  scope) failed to resolve {} after success...",
4196                                  token::get_name(name));
4197                         return None;
4198                     }
4199                     Some(def) => {
4200                         debug!("(resolving item path in lexical scope) \
4201                                 resolved `{}` to item",
4202                                token::get_name(name));
4203                         // This lookup is "all public" because it only searched
4204                         // for one identifier in the current module (couldn't
4205                         // have passed through reexports or anything like that.
4206                         return Some((def, LastMod(AllPublic)));
4207                     }
4208                 }
4209             }
4210             Indeterminate => {
4211                 panic!("unexpected indeterminate result");
4212             }
4213             Failed(err) => {
4214                 match err {
4215                     Some((span, msg)) =>
4216                         self.resolve_error(span, format!("failed to resolve. {}",
4217                                                          msg)[]),
4218                     None => ()
4219                 }
4220
4221                 debug!("(resolving item path by identifier in lexical scope) \
4222                          failed to resolve {}", token::get_name(name));
4223                 return None;
4224             }
4225         }
4226     }
4227
4228     fn with_no_errors<T, F>(&mut self, f: F) -> T where
4229         F: FnOnce(&mut Resolver) -> T,
4230     {
4231         self.emit_errors = false;
4232         let rs = f(self);
4233         self.emit_errors = true;
4234         rs
4235     }
4236
4237     fn resolve_error(&self, span: Span, s: &str) {
4238         if self.emit_errors {
4239             self.session.span_err(span, s);
4240         }
4241     }
4242
4243     fn find_fallback_in_self_type(&mut self, name: Name) -> FallbackSuggestion {
4244         fn extract_path_and_node_id(t: &Ty, allow: FallbackChecks)
4245                                                     -> Option<(Path, NodeId, FallbackChecks)> {
4246             match t.node {
4247                 TyPath(ref path, node_id) => Some((path.clone(), node_id, allow)),
4248                 TyPtr(ref mut_ty) => extract_path_and_node_id(&*mut_ty.ty, OnlyTraitAndStatics),
4249                 TyRptr(_, ref mut_ty) => extract_path_and_node_id(&*mut_ty.ty, allow),
4250                 // This doesn't handle the remaining `Ty` variants as they are not
4251                 // that commonly the self_type, it might be interesting to provide
4252                 // support for those in future.
4253                 _ => None,
4254             }
4255         }
4256
4257         fn get_module(this: &mut Resolver, span: Span, name_path: &[ast::Name])
4258                             -> Option<Rc<Module>> {
4259             let root = this.current_module.clone();
4260             let last_name = name_path.last().unwrap();
4261
4262             if name_path.len() == 1 {
4263                 match this.primitive_type_table.primitive_types.get(last_name) {
4264                     Some(_) => None,
4265                     None => {
4266                         match this.current_module.children.borrow().get(last_name) {
4267                             Some(child) => child.get_module_if_available(),
4268                             None => None
4269                         }
4270                     }
4271                 }
4272             } else {
4273                 match this.resolve_module_path(root,
4274                                                 name_path[],
4275                                                 UseLexicalScope,
4276                                                 span,
4277                                                 PathSearch) {
4278                     Success((module, _)) => Some(module),
4279                     _ => None
4280                 }
4281             }
4282         }
4283
4284         let (path, node_id, allowed) = match self.current_self_type {
4285             Some(ref ty) => match extract_path_and_node_id(ty, Everything) {
4286                 Some(x) => x,
4287                 None => return NoSuggestion,
4288             },
4289             None => return NoSuggestion,
4290         };
4291
4292         if allowed == Everything {
4293             // Look for a field with the same name in the current self_type.
4294             match self.def_map.borrow().get(&node_id) {
4295                  Some(&DefTy(did, _))
4296                 | Some(&DefStruct(did))
4297                 | Some(&DefVariant(_, did, _)) => match self.structs.get(&did) {
4298                     None => {}
4299                     Some(fields) => {
4300                         if fields.iter().any(|&field_name| name == field_name) {
4301                             return Field;
4302                         }
4303                     }
4304                 },
4305                 _ => {} // Self type didn't resolve properly
4306             }
4307         }
4308
4309         let name_path = path.segments.iter().map(|seg| seg.identifier.name).collect::<Vec<_>>();
4310
4311         // Look for a method in the current self type's impl module.
4312         match get_module(self, path.span, name_path[]) {
4313             Some(module) => match module.children.borrow().get(&name) {
4314                 Some(binding) => {
4315                     let p_str = self.path_names_to_string(&path);
4316                     match binding.def_for_namespace(ValueNS) {
4317                         Some(DefStaticMethod(_, provenance)) => {
4318                             match provenance {
4319                                 FromImpl(_) => return StaticMethod(p_str),
4320                                 FromTrait(_) => unreachable!()
4321                             }
4322                         }
4323                         Some(DefMethod(_, None, _)) if allowed == Everything => return Method,
4324                         Some(DefMethod(_, Some(_), _)) => return TraitItem,
4325                         _ => ()
4326                     }
4327                 }
4328                 None => {}
4329             },
4330             None => {}
4331         }
4332
4333         // Look for a method in the current trait.
4334         match self.current_trait_ref {
4335             Some((did, ref trait_ref)) => {
4336                 let path_str = self.path_names_to_string(&trait_ref.path);
4337
4338                 match self.trait_item_map.get(&(name, did)) {
4339                     Some(&StaticMethodTraitItemKind) => {
4340                         return TraitMethod(path_str)
4341                     }
4342                     Some(_) => return TraitItem,
4343                     None => {}
4344                 }
4345             }
4346             None => {}
4347         }
4348
4349         NoSuggestion
4350     }
4351
4352     fn find_best_match_for_name(&mut self, name: &str, max_distance: uint)
4353                                 -> Option<String> {
4354         let this = &mut *self;
4355
4356         let mut maybes: Vec<token::InternedString> = Vec::new();
4357         let mut values: Vec<uint> = Vec::new();
4358
4359         for rib in this.value_ribs.iter().rev() {
4360             for (&k, _) in rib.bindings.iter() {
4361                 maybes.push(token::get_name(k));
4362                 values.push(uint::MAX);
4363             }
4364         }
4365
4366         let mut smallest = 0;
4367         for (i, other) in maybes.iter().enumerate() {
4368             values[i] = lev_distance(name, other.get());
4369
4370             if values[i] <= values[smallest] {
4371                 smallest = i;
4372             }
4373         }
4374
4375         if values.len() > 0 &&
4376             values[smallest] != uint::MAX &&
4377             values[smallest] < name.len() + 2 &&
4378             values[smallest] <= max_distance &&
4379             name != maybes[smallest].get() {
4380
4381             Some(maybes[smallest].get().to_string())
4382
4383         } else {
4384             None
4385         }
4386     }
4387
4388     fn resolve_expr(&mut self, expr: &Expr) {
4389         // First, record candidate traits for this expression if it could
4390         // result in the invocation of a method call.
4391
4392         self.record_candidate_traits_for_expr_if_necessary(expr);
4393
4394         // Next, resolve the node.
4395         match expr.node {
4396             // The interpretation of paths depends on whether the path has
4397             // multiple elements in it or not.
4398
4399             ExprPath(ref path) => {
4400                 // This is a local path in the value namespace. Walk through
4401                 // scopes looking for it.
4402
4403                 let path_name = self.path_names_to_string(path);
4404
4405                 match self.resolve_path(expr.id, path, ValueNS, true) {
4406                     // Check if struct variant
4407                     Some((DefVariant(_, _, true), _)) => {
4408                         self.resolve_error(expr.span,
4409                                 format!("`{}` is a struct variant name, but \
4410                                          this expression \
4411                                          uses it like a function name",
4412                                         path_name).as_slice());
4413
4414                         self.session.span_help(expr.span,
4415                             format!("Did you mean to write: \
4416                                     `{} {{ /* fields */ }}`?",
4417                                     path_name).as_slice());
4418                     }
4419                     Some(def) => {
4420                         // Write the result into the def map.
4421                         debug!("(resolving expr) resolved `{}`",
4422                                path_name);
4423
4424                         self.record_def(expr.id, def);
4425                     }
4426                     None => {
4427                         // Be helpful if the name refers to a struct
4428                         // (The pattern matching def_tys where the id is in self.structs
4429                         // matches on regular structs while excluding tuple- and enum-like
4430                         // structs, which wouldn't result in this error.)
4431                         match self.with_no_errors(|this|
4432                             this.resolve_path(expr.id, path, TypeNS, false)) {
4433                             Some((DefTy(struct_id, _), _))
4434                               if self.structs.contains_key(&struct_id) => {
4435                                 self.resolve_error(expr.span,
4436                                         format!("`{}` is a structure name, but \
4437                                                  this expression \
4438                                                  uses it like a function name",
4439                                                 path_name).as_slice());
4440
4441                                 self.session.span_help(expr.span,
4442                                     format!("Did you mean to write: \
4443                                             `{} {{ /* fields */ }}`?",
4444                                             path_name).as_slice());
4445
4446                             }
4447                             _ => {
4448                                 let mut method_scope = false;
4449                                 self.value_ribs.iter().rev().all(|rib| {
4450                                     let res = match *rib {
4451                                         Rib { bindings: _, kind: MethodRibKind(_, _) } => true,
4452                                         Rib { bindings: _, kind: ItemRibKind } => false,
4453                                         _ => return true, // Keep advancing
4454                                     };
4455
4456                                     method_scope = res;
4457                                     false // Stop advancing
4458                                 });
4459
4460                                 if method_scope && token::get_name(self.self_name).get()
4461                                                                    == path_name {
4462                                         self.resolve_error(
4463                                             expr.span,
4464                                             "`self` is not available \
4465                                              in a static method. Maybe a \
4466                                              `self` argument is missing?");
4467                                 } else {
4468                                     let last_name = path.segments.last().unwrap().identifier.name;
4469                                     let mut msg = match self.find_fallback_in_self_type(last_name) {
4470                                         NoSuggestion => {
4471                                             // limit search to 5 to reduce the number
4472                                             // of stupid suggestions
4473                                             self.find_best_match_for_name(path_name.as_slice(), 5)
4474                                                                 .map_or("".to_string(),
4475                                                                         |x| format!("`{}`", x))
4476                                         }
4477                                         Field =>
4478                                             format!("`self.{}`", path_name),
4479                                         Method
4480                                         | TraitItem =>
4481                                             format!("to call `self.{}`", path_name),
4482                                         TraitMethod(path_str)
4483                                         | StaticMethod(path_str) =>
4484                                             format!("to call `{}::{}`", path_str, path_name)
4485                                     };
4486
4487                                     if msg.len() > 0 {
4488                                         msg = format!(". Did you mean {}?", msg)
4489                                     }
4490
4491                                     self.resolve_error(
4492                                         expr.span,
4493                                         format!("unresolved name `{}`{}",
4494                                                 path_name,
4495                                                 msg).as_slice());
4496                                 }
4497                             }
4498                         }
4499                     }
4500                 }
4501
4502                 visit::walk_expr(self, expr);
4503             }
4504
4505             ExprClosure(capture_clause, _, ref fn_decl, ref block) => {
4506                 self.capture_mode_map.insert(expr.id, capture_clause);
4507                 self.resolve_function(ClosureRibKind(expr.id, ast::DUMMY_NODE_ID),
4508                                       Some(&**fn_decl), NoTypeParameters,
4509                                       &**block);
4510             }
4511
4512             ExprStruct(ref path, _, _) => {
4513                 // Resolve the path to the structure it goes to. We don't
4514                 // check to ensure that the path is actually a structure; that
4515                 // is checked later during typeck.
4516                 match self.resolve_path(expr.id, path, TypeNS, false) {
4517                     Some(definition) => self.record_def(expr.id, definition),
4518                     result => {
4519                         debug!("(resolving expression) didn't find struct \
4520                                 def: {}", result);
4521                         let msg = format!("`{}` does not name a structure",
4522                                           self.path_names_to_string(path));
4523                         self.resolve_error(path.span, msg[]);
4524                     }
4525                 }
4526
4527                 visit::walk_expr(self, expr);
4528             }
4529
4530             ExprLoop(_, Some(label)) | ExprWhile(_, _, Some(label)) => {
4531                 self.with_label_rib(|this| {
4532                     let def_like = DlDef(DefLabel(expr.id));
4533
4534                     {
4535                         let rib = this.label_ribs.last_mut().unwrap();
4536                         let renamed = mtwt::resolve(label);
4537                         rib.bindings.insert(renamed, def_like);
4538                     }
4539
4540                     visit::walk_expr(this, expr);
4541                 })
4542             }
4543
4544             ExprForLoop(ref pattern, ref head, ref body, optional_label) => {
4545                 self.resolve_expr(&**head);
4546
4547                 self.value_ribs.push(Rib::new(NormalRibKind));
4548
4549                 self.resolve_pattern(&**pattern,
4550                                      LocalIrrefutableMode,
4551                                      &mut HashMap::new());
4552
4553                 match optional_label {
4554                     None => {}
4555                     Some(label) => {
4556                         self.label_ribs
4557                             .push(Rib::new(NormalRibKind));
4558                         let def_like = DlDef(DefLabel(expr.id));
4559
4560                         {
4561                             let rib = self.label_ribs.last_mut().unwrap();
4562                             let renamed = mtwt::resolve(label);
4563                             rib.bindings.insert(renamed, def_like);
4564                         }
4565                     }
4566                 }
4567
4568                 self.resolve_block(&**body);
4569
4570                 if optional_label.is_some() {
4571                     drop(self.label_ribs.pop())
4572                 }
4573
4574                 self.value_ribs.pop();
4575             }
4576
4577             ExprBreak(Some(label)) | ExprAgain(Some(label)) => {
4578                 let renamed = mtwt::resolve(label);
4579                 match self.search_label(renamed) {
4580                     None => {
4581                         self.resolve_error(
4582                             expr.span,
4583                             format!("use of undeclared label `{}`",
4584                                     token::get_ident(label))[])
4585                     }
4586                     Some(DlDef(def @ DefLabel(_))) => {
4587                         // Since this def is a label, it is never read.
4588                         self.record_def(expr.id, (def, LastMod(AllPublic)))
4589                     }
4590                     Some(_) => {
4591                         self.session.span_bug(expr.span,
4592                                               "label wasn't mapped to a \
4593                                                label def!")
4594                     }
4595                 }
4596             }
4597
4598             _ => {
4599                 visit::walk_expr(self, expr);
4600             }
4601         }
4602     }
4603
4604     fn record_candidate_traits_for_expr_if_necessary(&mut self, expr: &Expr) {
4605         match expr.node {
4606             ExprField(_, ident) => {
4607                 // FIXME(#6890): Even though you can't treat a method like a
4608                 // field, we need to add any trait methods we find that match
4609                 // the field name so that we can do some nice error reporting
4610                 // later on in typeck.
4611                 let traits = self.search_for_traits_containing_method(ident.node.name);
4612                 self.trait_map.insert(expr.id, traits);
4613             }
4614             ExprMethodCall(ident, _, _) => {
4615                 debug!("(recording candidate traits for expr) recording \
4616                         traits for {}",
4617                        expr.id);
4618                 let traits = self.search_for_traits_containing_method(ident.node.name);
4619                 self.trait_map.insert(expr.id, traits);
4620             }
4621             _ => {
4622                 // Nothing to do.
4623             }
4624         }
4625     }
4626
4627     fn search_for_traits_containing_method(&mut self, name: Name) -> Vec<DefId> {
4628         debug!("(searching for traits containing method) looking for '{}'",
4629                token::get_name(name));
4630
4631         fn add_trait_info(found_traits: &mut Vec<DefId>,
4632                           trait_def_id: DefId,
4633                           name: Name) {
4634             debug!("(adding trait info) found trait {}:{} for method '{}'",
4635                 trait_def_id.krate,
4636                 trait_def_id.node,
4637                 token::get_name(name));
4638             found_traits.push(trait_def_id);
4639         }
4640
4641         let mut found_traits = Vec::new();
4642         let mut search_module = self.current_module.clone();
4643         loop {
4644             // Look for the current trait.
4645             match self.current_trait_ref {
4646                 Some((trait_def_id, _)) => {
4647                     if self.trait_item_map.contains_key(&(name, trait_def_id)) {
4648                         add_trait_info(&mut found_traits, trait_def_id, name);
4649                     }
4650                 }
4651                 None => {} // Nothing to do.
4652             }
4653
4654             // Look for trait children.
4655             build_reduced_graph::populate_module_if_necessary(self, &search_module);
4656
4657             {
4658                 for (_, child_names) in search_module.children.borrow().iter() {
4659                     let def = match child_names.def_for_namespace(TypeNS) {
4660                         Some(def) => def,
4661                         None => continue
4662                     };
4663                     let trait_def_id = match def {
4664                         DefTrait(trait_def_id) => trait_def_id,
4665                         _ => continue,
4666                     };
4667                     if self.trait_item_map.contains_key(&(name, trait_def_id)) {
4668                         add_trait_info(&mut found_traits, trait_def_id, name);
4669                     }
4670                 }
4671             }
4672
4673             // Look for imports.
4674             for (_, import) in search_module.import_resolutions.borrow().iter() {
4675                 let target = match import.target_for_namespace(TypeNS) {
4676                     None => continue,
4677                     Some(target) => target,
4678                 };
4679                 let did = match target.bindings.def_for_namespace(TypeNS) {
4680                     Some(DefTrait(trait_def_id)) => trait_def_id,
4681                     Some(..) | None => continue,
4682                 };
4683                 if self.trait_item_map.contains_key(&(name, did)) {
4684                     add_trait_info(&mut found_traits, did, name);
4685                     let id = import.type_id;
4686                     self.used_imports.insert((id, TypeNS));
4687                     let trait_name = self.get_trait_name(did);
4688                     self.record_import_use(id, trait_name);
4689                     if let Some(DefId{krate: kid, ..}) = target.target_module.def_id.get() {
4690                         self.used_crates.insert(kid);
4691                     }
4692                 }
4693             }
4694
4695             match search_module.parent_link.clone() {
4696                 NoParentLink | ModuleParentLink(..) => break,
4697                 BlockParentLink(parent_module, _) => {
4698                     search_module = parent_module.upgrade().unwrap();
4699                 }
4700             }
4701         }
4702
4703         found_traits
4704     }
4705
4706     fn record_def(&mut self, node_id: NodeId, (def, lp): (Def, LastPrivate)) {
4707         debug!("(recording def) recording {} for {}, last private {}",
4708                 def, node_id, lp);
4709         assert!(match lp {LastImport{..} => false, _ => true},
4710                 "Import should only be used for `use` directives");
4711         self.last_private.insert(node_id, lp);
4712
4713         match self.def_map.borrow_mut().entry(&node_id) {
4714             // Resolve appears to "resolve" the same ID multiple
4715             // times, so here is a sanity check it at least comes to
4716             // the same conclusion! - nmatsakis
4717             Occupied(entry) => if def != *entry.get() {
4718                 self.session
4719                     .bug(format!("node_id {} resolved first to {} and \
4720                                   then {}",
4721                                  node_id,
4722                                  *entry.get(),
4723                                  def)[]);
4724             },
4725             Vacant(entry) => { entry.insert(def); },
4726         }
4727     }
4728
4729     fn enforce_default_binding_mode(&mut self,
4730                                         pat: &Pat,
4731                                         pat_binding_mode: BindingMode,
4732                                         descr: &str) {
4733         match pat_binding_mode {
4734             BindByValue(_) => {}
4735             BindByRef(..) => {
4736                 self.resolve_error(pat.span,
4737                                    format!("cannot use `ref` binding mode \
4738                                             with {}",
4739                                            descr)[]);
4740             }
4741         }
4742     }
4743
4744     //
4745     // Diagnostics
4746     //
4747     // Diagnostics are not particularly efficient, because they're rarely
4748     // hit.
4749     //
4750
4751     /// A somewhat inefficient routine to obtain the name of a module.
4752     fn module_to_string(&self, module: &Module) -> String {
4753         let mut names = Vec::new();
4754
4755         fn collect_mod(names: &mut Vec<ast::Name>, module: &Module) {
4756             match module.parent_link {
4757                 NoParentLink => {}
4758                 ModuleParentLink(ref module, name) => {
4759                     names.push(name);
4760                     collect_mod(names, &*module.upgrade().unwrap());
4761                 }
4762                 BlockParentLink(ref module, _) => {
4763                     // danger, shouldn't be ident?
4764                     names.push(special_idents::opaque.name);
4765                     collect_mod(names, &*module.upgrade().unwrap());
4766                 }
4767             }
4768         }
4769         collect_mod(&mut names, module);
4770
4771         if names.len() == 0 {
4772             return "???".to_string();
4773         }
4774         self.names_to_string(names.into_iter().rev()
4775                                   .collect::<Vec<ast::Name>>()[])
4776     }
4777
4778     #[allow(dead_code)]   // useful for debugging
4779     fn dump_module(&mut self, module_: Rc<Module>) {
4780         debug!("Dump of module `{}`:", self.module_to_string(&*module_));
4781
4782         debug!("Children:");
4783         build_reduced_graph::populate_module_if_necessary(self, &module_);
4784         for (&name, _) in module_.children.borrow().iter() {
4785             debug!("* {}", token::get_name(name));
4786         }
4787
4788         debug!("Import resolutions:");
4789         let import_resolutions = module_.import_resolutions.borrow();
4790         for (&name, import_resolution) in import_resolutions.iter() {
4791             let value_repr;
4792             match import_resolution.target_for_namespace(ValueNS) {
4793                 None => { value_repr = "".to_string(); }
4794                 Some(_) => {
4795                     value_repr = " value:?".to_string();
4796                     // FIXME #4954
4797                 }
4798             }
4799
4800             let type_repr;
4801             match import_resolution.target_for_namespace(TypeNS) {
4802                 None => { type_repr = "".to_string(); }
4803                 Some(_) => {
4804                     type_repr = " type:?".to_string();
4805                     // FIXME #4954
4806                 }
4807             }
4808
4809             debug!("* {}:{}{}", token::get_name(name), value_repr, type_repr);
4810         }
4811     }
4812 }
4813
4814 pub struct CrateMap {
4815     pub def_map: DefMap,
4816     pub freevars: RefCell<FreevarMap>,
4817     pub capture_mode_map: RefCell<CaptureModeMap>,
4818     pub export_map: ExportMap,
4819     pub trait_map: TraitMap,
4820     pub external_exports: ExternalExports,
4821     pub last_private_map: LastPrivateMap,
4822     pub glob_map: Option<GlobMap>
4823 }
4824
4825 #[derive(PartialEq,Copy)]
4826 pub enum MakeGlobMap {
4827     Yes,
4828     No
4829 }
4830
4831 /// Entry point to crate resolution.
4832 pub fn resolve_crate<'a, 'tcx>(session: &'a Session,
4833                                ast_map: &'a ast_map::Map<'tcx>,
4834                                _: &LanguageItems,
4835                                krate: &Crate,
4836                                make_glob_map: MakeGlobMap)
4837                                -> CrateMap {
4838     let mut resolver = Resolver::new(session, ast_map, krate.span, make_glob_map);
4839
4840     build_reduced_graph::build_reduced_graph(&mut resolver, krate);
4841     session.abort_if_errors();
4842
4843     resolver.resolve_imports();
4844     session.abort_if_errors();
4845
4846     record_exports::record(&mut resolver);
4847     session.abort_if_errors();
4848
4849     resolver.resolve_crate(krate);
4850     session.abort_if_errors();
4851
4852     check_unused::check_crate(&mut resolver, krate);
4853
4854     CrateMap {
4855         def_map: resolver.def_map,
4856         freevars: resolver.freevars,
4857         capture_mode_map: RefCell::new(resolver.capture_mode_map),
4858         export_map: resolver.export_map,
4859         trait_map: resolver.trait_map,
4860         external_exports: resolver.external_exports,
4861         last_private_map: resolver.last_private,
4862         glob_map: if resolver.make_glob_map {
4863                         Some(resolver.glob_map)
4864                     } else {
4865                         None
4866                     },
4867     }
4868 }