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