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