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