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