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