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