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