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