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