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