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