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