]> git.lizzy.rs Git - rust.git/blob - src/librustc_resolve/lib.rs
1fa8e63f57e17d4d8f378e6d4e782c435ba34584
[rust.git] / src / librustc_resolve / lib.rs
1 // Copyright 2012-2015 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 // Do not remove on snapshot creation. Needed for bootstrap. (Issue #22364)
12 #![cfg_attr(stage0, feature(custom_attribute))]
13 #![crate_name = "rustc_resolve"]
14 #![unstable(feature = "rustc_private")]
15 #![staged_api]
16 #![crate_type = "dylib"]
17 #![crate_type = "rlib"]
18 #![doc(html_logo_url = "http://www.rust-lang.org/logos/rust-logo-128x128-blk-v2.png",
19       html_favicon_url = "https://doc.rust-lang.org/favicon.ico",
20       html_root_url = "http://doc.rust-lang.org/nightly/")]
21
22 #![feature(associated_consts)]
23 #![feature(rc_weak)]
24 #![feature(rustc_diagnostic_macros)]
25 #![feature(rustc_private)]
26 #![feature(slice_extras)]
27 #![feature(staged_api)]
28
29 #[macro_use] extern crate log;
30 #[macro_use] extern crate syntax;
31 #[macro_use] #[no_link] extern crate rustc_bitflags;
32
33 extern crate rustc;
34
35 use self::PatternBindingMode::*;
36 use self::Namespace::*;
37 use self::NamespaceResult::*;
38 use self::NameDefinition::*;
39 use self::ResolveResult::*;
40 use self::FallbackSuggestion::*;
41 use self::TypeParameters::*;
42 use self::RibKind::*;
43 use self::UseLexicalScopeFlag::*;
44 use self::ModulePrefixResult::*;
45 use self::AssocItemResolveResult::*;
46 use self::NameSearchType::*;
47 use self::BareIdentifierPatternResolution::*;
48 use self::ParentLink::*;
49 use self::ModuleKind::*;
50 use self::FallbackChecks::*;
51
52 use rustc::ast_map;
53 use rustc::session::Session;
54 use rustc::lint;
55 use rustc::metadata::csearch;
56 use rustc::metadata::decoder::{DefLike, DlDef, DlField, DlImpl};
57 use rustc::middle::def::*;
58 use rustc::middle::pat_util::pat_bindings;
59 use rustc::middle::privacy::*;
60 use rustc::middle::subst::{ParamSpace, FnSpace, TypeSpace};
61 use rustc::middle::ty::{Freevar, FreevarMap, TraitMap, GlobMap};
62 use rustc::util::nodemap::{NodeMap, NodeSet, DefIdSet, FnvHashMap};
63 use rustc::util::lev_distance::lev_distance;
64
65 use syntax::ast::{Arm, BindByRef, BindByValue, BindingMode, Block};
66 use syntax::ast::{ConstImplItem, Crate, CrateNum};
67 use syntax::ast::{DefId, Expr, ExprAgain, ExprBreak, ExprField};
68 use syntax::ast::{ExprLoop, ExprWhile, ExprMethodCall};
69 use syntax::ast::{ExprPath, ExprStruct, FnDecl};
70 use syntax::ast::{ForeignItemFn, ForeignItemStatic, Generics};
71 use syntax::ast::{Ident, ImplItem, Item, ItemConst, ItemEnum, ItemExternCrate};
72 use syntax::ast::{ItemFn, ItemForeignMod, ItemImpl, ItemMac, ItemMod, ItemStatic, ItemDefaultImpl};
73 use syntax::ast::{ItemStruct, ItemTrait, ItemTy, ItemUse};
74 use syntax::ast::{Local, MethodImplItem, Name, NodeId};
75 use syntax::ast::{Pat, PatEnum, PatIdent, PatLit, PatQPath};
76 use syntax::ast::{PatRange, PatStruct, Path, PrimTy};
77 use syntax::ast::{TraitRef, Ty, TyBool, TyChar, TyF32};
78 use syntax::ast::{TyF64, TyFloat, TyIs, TyI8, TyI16, TyI32, TyI64, TyInt};
79 use syntax::ast::{TyPath, TyPtr};
80 use syntax::ast::{TyRptr, TyStr, TyUs, TyU8, TyU16, TyU32, TyU64, TyUint};
81 use syntax::ast::TypeImplItem;
82 use syntax::ast;
83 use syntax::ast_util::{local_def, walk_pat};
84 use syntax::attr::AttrMetaMethods;
85 use syntax::ext::mtwt;
86 use syntax::parse::token::{self, special_names, special_idents};
87 use syntax::ptr::P;
88 use syntax::codemap::{self, Span, Pos};
89 use syntax::visit::{self, Visitor};
90
91 use std::collections::{HashMap, HashSet};
92 use std::collections::hash_map::Entry::{Occupied, Vacant};
93 use std::cell::{Cell, RefCell};
94 use std::fmt;
95 use std::mem::replace;
96 use std::rc::{Rc, Weak};
97 use std::usize;
98
99 use resolve_imports::{Target, ImportDirective, ImportResolution};
100 use resolve_imports::Shadowable;
101
102 // NB: This module needs to be declared first so diagnostics are
103 // registered before they are used.
104 pub mod diagnostics;
105
106 macro_rules! resolve_err {
107     ($this:expr, $span:expr, $code:ident, $($rest:tt)*) => {
108         if $this.emit_errors {
109             span_err!($this.session, $span, $code, $($rest)*);
110         }
111     }
112 }
113
114 mod check_unused;
115 mod record_exports;
116 mod build_reduced_graph;
117 mod resolve_imports;
118
119 pub enum ResolutionError<'b, 'a:'b, 'tcx:'a> {
120     /// error: static variables cannot be referenced in a pattern
121     StaticVariableReference(&'b Resolver<'a, 'tcx>, syntax::codemap::Span),
122     /// error: does not name a struct
123     DoesNotNameAStruct(&'b Resolver<'a, 'tcx>, syntax::codemap::Span),
124     /// error: is a struct variant name, but this expression uses it like a function name
125     StructVariantUsedAsFunction(&'a Resolver<'a, 'tcx>, syntax::codemap::Span),
126     /// error: unresolved import
127     UnresolvedImport(&'b Resolver<'a, 'tcx>, syntax::codemap::Span),
128     /// error: failed to resolve
129     FailedToResolve(&'b Resolver<'a, 'tcx>, syntax::codemap::Span),
130 }
131
132 fn resolve_error<'b, 'a:'b, 'tcx:'a>(resolution_error: &ResolutionError<'b, 'a, 'tcx>, formatted: &str) {
133     match resolution_error {
134         &ResolutionError::StaticVariableReference(resolver, span) => {
135             resolve_err!(resolver, span, E0417, "{}", formatted);
136         },
137         &ResolutionError::DoesNotNameAStruct(resolver, span) => {
138             resolve_err!(resolver, span, E0422, "{}", formatted);
139         },
140         &ResolutionError::StructVariantUsedAsFunction(resolver, span) => {
141             resolve_err!(resolver, span, E0423, "{}", formatted);
142         },
143         &ResolutionError::UnresolvedImport(resolver, span) => {
144             resolve_err!(resolver, span, E0432, "{}", formatted);
145         },
146         &ResolutionError::FailedToResolve(resolver, span) => {
147             resolve_err!(resolver, span, E0433, "{}", formatted);
148         },
149     }
150 }
151
152 #[derive(Copy, Clone)]
153 struct BindingInfo {
154     span: Span,
155     binding_mode: BindingMode,
156 }
157
158 // Map from the name in a pattern to its binding mode.
159 type BindingMap = HashMap<Name, BindingInfo>;
160
161 #[derive(Copy, Clone, PartialEq)]
162 enum PatternBindingMode {
163     RefutableMode,
164     LocalIrrefutableMode,
165     ArgumentIrrefutableMode,
166 }
167
168 #[derive(Copy, Clone, PartialEq, Eq, Hash, Debug)]
169 enum Namespace {
170     TypeNS,
171     ValueNS
172 }
173
174 /// A NamespaceResult represents the result of resolving an import in
175 /// a particular namespace. The result is either definitely-resolved,
176 /// definitely- unresolved, or unknown.
177 #[derive(Clone)]
178 enum NamespaceResult {
179     /// Means that resolve hasn't gathered enough information yet to determine
180     /// whether the name is bound in this namespace. (That is, it hasn't
181     /// resolved all `use` directives yet.)
182     UnknownResult,
183     /// Means that resolve has determined that the name is definitely
184     /// not bound in the namespace.
185     UnboundResult,
186     /// Means that resolve has determined that the name is bound in the Module
187     /// argument, and specified by the NameBindings argument.
188     BoundResult(Rc<Module>, Rc<NameBindings>)
189 }
190
191 impl NamespaceResult {
192     fn is_unknown(&self) -> bool {
193         match *self {
194             UnknownResult => true,
195             _ => false
196         }
197     }
198     fn is_unbound(&self) -> bool {
199         match *self {
200             UnboundResult => true,
201             _ => false
202         }
203     }
204 }
205
206 enum NameDefinition {
207     // The name was unbound.
208     NoNameDefinition,
209     // The name identifies an immediate child.
210     ChildNameDefinition(Def, LastPrivate),
211     // The name identifies an import.
212     ImportNameDefinition(Def, LastPrivate),
213 }
214
215 impl<'a, 'v, 'tcx> Visitor<'v> for Resolver<'a, 'tcx> {
216     fn visit_item(&mut self, item: &Item) {
217         self.resolve_item(item);
218     }
219     fn visit_arm(&mut self, arm: &Arm) {
220         self.resolve_arm(arm);
221     }
222     fn visit_block(&mut self, block: &Block) {
223         self.resolve_block(block);
224     }
225     fn visit_expr(&mut self, expr: &Expr) {
226         self.resolve_expr(expr);
227     }
228     fn visit_local(&mut self, local: &Local) {
229         self.resolve_local(local);
230     }
231     fn visit_ty(&mut self, ty: &Ty) {
232         self.resolve_type(ty);
233     }
234     fn visit_generics(&mut self, generics: &Generics) {
235         self.resolve_generics(generics);
236     }
237     fn visit_poly_trait_ref(&mut self,
238                             tref: &ast::PolyTraitRef,
239                             m: &ast::TraitBoundModifier) {
240         match self.resolve_trait_reference(tref.trait_ref.ref_id, &tref.trait_ref.path, 0) {
241             Ok(def) => self.record_def(tref.trait_ref.ref_id, def),
242             Err(_) => { /* error already reported */ }
243         }
244         visit::walk_poly_trait_ref(self, tref, m);
245     }
246     fn visit_variant(&mut self, variant: &ast::Variant, generics: &Generics) {
247         if let Some(ref dis_expr) = variant.node.disr_expr {
248             // resolve the discriminator expr as a constant
249             self.with_constant_rib(|this| {
250                 this.visit_expr(&**dis_expr);
251             });
252         }
253
254         // `visit::walk_variant` without the discriminant expression.
255         match variant.node.kind {
256             ast::TupleVariantKind(ref variant_arguments) => {
257                 for variant_argument in variant_arguments {
258                     self.visit_ty(&*variant_argument.ty);
259                 }
260             }
261             ast::StructVariantKind(ref struct_definition) => {
262                 self.visit_struct_def(&**struct_definition,
263                                       variant.node.name,
264                                       generics,
265                                       variant.node.id);
266             }
267         }
268     }
269     fn visit_foreign_item(&mut self, foreign_item: &ast::ForeignItem) {
270         let type_parameters = match foreign_item.node {
271             ForeignItemFn(_, ref generics) => {
272                 HasTypeParameters(generics, FnSpace, ItemRibKind)
273             }
274             ForeignItemStatic(..) => NoTypeParameters
275         };
276         self.with_type_parameter_rib(type_parameters, |this| {
277             visit::walk_foreign_item(this, foreign_item);
278         });
279     }
280     fn visit_fn(&mut self,
281                 function_kind: visit::FnKind<'v>,
282                 declaration: &'v FnDecl,
283                 block: &'v Block,
284                 _: Span,
285                 node_id: NodeId) {
286         let rib_kind = match function_kind {
287             visit::FkItemFn(_, generics, _, _, _, _) => {
288                 self.visit_generics(generics);
289                 ItemRibKind
290             }
291             visit::FkMethod(_, sig, _) => {
292                 self.visit_generics(&sig.generics);
293                 self.visit_explicit_self(&sig.explicit_self);
294                 MethodRibKind
295             }
296             visit::FkFnBlock(..) => ClosureRibKind(node_id)
297         };
298         self.resolve_function(rib_kind, declaration, block);
299     }
300 }
301
302 type ErrorMessage = Option<(Span, String)>;
303
304 enum ResolveResult<T> {
305     Failed(ErrorMessage),   // Failed to resolve the name, optional helpful error message.
306     Indeterminate,          // Couldn't determine due to unresolved globs.
307     Success(T)              // Successfully resolved the import.
308 }
309
310 impl<T> ResolveResult<T> {
311     fn indeterminate(&self) -> bool {
312         match *self { Indeterminate => true, _ => false }
313     }
314 }
315
316 enum FallbackSuggestion {
317     NoSuggestion,
318     Field,
319     Method,
320     TraitItem,
321     StaticMethod(String),
322     TraitMethod(String),
323 }
324
325 #[derive(Copy, Clone)]
326 enum TypeParameters<'a> {
327     NoTypeParameters,
328     HasTypeParameters(
329         // Type parameters.
330         &'a Generics,
331
332         // Identifies the things that these parameters
333         // were declared on (type, fn, etc)
334         ParamSpace,
335
336         // The kind of the rib used for type parameters.
337         RibKind)
338 }
339
340 // The rib kind controls the translation of local
341 // definitions (`DefLocal`) to upvars (`DefUpvar`).
342 #[derive(Copy, Clone, Debug)]
343 enum RibKind {
344     // No translation needs to be applied.
345     NormalRibKind,
346
347     // We passed through a closure scope at the given node ID.
348     // Translate upvars as appropriate.
349     ClosureRibKind(NodeId /* func id */),
350
351     // We passed through an impl or trait and are now in one of its
352     // methods. Allow references to ty params that impl or trait
353     // binds. Disallow any other upvars (including other ty params that are
354     // upvars).
355     MethodRibKind,
356
357     // We passed through an item scope. Disallow upvars.
358     ItemRibKind,
359
360     // We're in a constant item. Can't refer to dynamic stuff.
361     ConstantItemRibKind
362 }
363
364 #[derive(Copy, Clone)]
365 enum UseLexicalScopeFlag {
366     DontUseLexicalScope,
367     UseLexicalScope
368 }
369
370 enum ModulePrefixResult {
371     NoPrefixFound,
372     PrefixFound(Rc<Module>, usize)
373 }
374
375 #[derive(Copy, Clone)]
376 enum AssocItemResolveResult {
377     /// Syntax such as `<T>::item`, which can't be resolved until type
378     /// checking.
379     TypecheckRequired,
380     /// We should have been able to resolve the associated item.
381     ResolveAttempt(Option<PathResolution>),
382 }
383
384 #[derive(Copy, Clone, PartialEq)]
385 enum NameSearchType {
386     /// We're doing a name search in order to resolve a `use` directive.
387     ImportSearch,
388
389     /// We're doing a name search in order to resolve a path type, a path
390     /// expression, or a path pattern.
391     PathSearch,
392 }
393
394 #[derive(Copy, Clone)]
395 enum BareIdentifierPatternResolution {
396     FoundStructOrEnumVariant(Def, LastPrivate),
397     FoundConst(Def, LastPrivate),
398     BareIdentifierPatternUnresolved
399 }
400
401 /// One local scope.
402 #[derive(Debug)]
403 struct Rib {
404     bindings: HashMap<Name, DefLike>,
405     kind: RibKind,
406 }
407
408 impl Rib {
409     fn new(kind: RibKind) -> Rib {
410         Rib {
411             bindings: HashMap::new(),
412             kind: kind
413         }
414     }
415 }
416
417 /// The link from a module up to its nearest parent node.
418 #[derive(Clone,Debug)]
419 enum ParentLink {
420     NoParentLink,
421     ModuleParentLink(Weak<Module>, Name),
422     BlockParentLink(Weak<Module>, NodeId)
423 }
424
425 /// The type of module this is.
426 #[derive(Copy, Clone, PartialEq, Debug)]
427 enum ModuleKind {
428     NormalModuleKind,
429     TraitModuleKind,
430     EnumModuleKind,
431     TypeModuleKind,
432     AnonymousModuleKind,
433 }
434
435 /// One node in the tree of modules.
436 pub struct Module {
437     parent_link: ParentLink,
438     def_id: Cell<Option<DefId>>,
439     kind: Cell<ModuleKind>,
440     is_public: bool,
441
442     children: RefCell<HashMap<Name, Rc<NameBindings>>>,
443     imports: RefCell<Vec<ImportDirective>>,
444
445     // The external module children of this node that were declared with
446     // `extern crate`.
447     external_module_children: RefCell<HashMap<Name, Rc<Module>>>,
448
449     // The anonymous children of this node. Anonymous children are pseudo-
450     // modules that are implicitly created around items contained within
451     // blocks.
452     //
453     // For example, if we have this:
454     //
455     //  fn f() {
456     //      fn g() {
457     //          ...
458     //      }
459     //  }
460     //
461     // There will be an anonymous module created around `g` with the ID of the
462     // entry block for `f`.
463     anonymous_children: RefCell<NodeMap<Rc<Module>>>,
464
465     // The status of resolving each import in this module.
466     import_resolutions: RefCell<HashMap<Name, ImportResolution>>,
467
468     // The number of unresolved globs that this module exports.
469     glob_count: Cell<usize>,
470
471     // The index of the import we're resolving.
472     resolved_import_count: Cell<usize>,
473
474     // Whether this module is populated. If not populated, any attempt to
475     // access the children must be preceded with a
476     // `populate_module_if_necessary` call.
477     populated: Cell<bool>,
478 }
479
480 impl Module {
481     fn new(parent_link: ParentLink,
482            def_id: Option<DefId>,
483            kind: ModuleKind,
484            external: bool,
485            is_public: bool)
486            -> Module {
487         Module {
488             parent_link: parent_link,
489             def_id: Cell::new(def_id),
490             kind: Cell::new(kind),
491             is_public: is_public,
492             children: RefCell::new(HashMap::new()),
493             imports: RefCell::new(Vec::new()),
494             external_module_children: RefCell::new(HashMap::new()),
495             anonymous_children: RefCell::new(NodeMap()),
496             import_resolutions: RefCell::new(HashMap::new()),
497             glob_count: Cell::new(0),
498             resolved_import_count: Cell::new(0),
499             populated: Cell::new(!external),
500         }
501     }
502
503     fn all_imports_resolved(&self) -> bool {
504         self.imports.borrow().len() == self.resolved_import_count.get()
505     }
506 }
507
508 impl fmt::Debug for Module {
509     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
510         write!(f, "{:?}, kind: {:?}, {}",
511                self.def_id,
512                self.kind,
513                if self.is_public { "public" } else { "private" } )
514     }
515 }
516
517 bitflags! {
518     #[derive(Debug)]
519     flags DefModifiers: u8 {
520         const PUBLIC     = 1 << 0,
521         const IMPORTABLE = 1 << 1,
522     }
523 }
524
525 // Records a possibly-private type definition.
526 #[derive(Clone,Debug)]
527 struct TypeNsDef {
528     modifiers: DefModifiers, // see note in ImportResolution about how to use this
529     module_def: Option<Rc<Module>>,
530     type_def: Option<Def>,
531     type_span: Option<Span>
532 }
533
534 // Records a possibly-private value definition.
535 #[derive(Clone, Copy, Debug)]
536 struct ValueNsDef {
537     modifiers: DefModifiers, // see note in ImportResolution about how to use this
538     def: Def,
539     value_span: Option<Span>,
540 }
541
542 // Records the definitions (at most one for each namespace) that a name is
543 // bound to.
544 #[derive(Debug)]
545 pub struct NameBindings {
546     type_def: RefCell<Option<TypeNsDef>>,   //< Meaning in type namespace.
547     value_def: RefCell<Option<ValueNsDef>>, //< Meaning in value namespace.
548 }
549
550 impl NameBindings {
551     fn new() -> NameBindings {
552         NameBindings {
553             type_def: RefCell::new(None),
554             value_def: RefCell::new(None),
555         }
556     }
557
558     /// Creates a new module in this set of name bindings.
559     fn define_module(&self,
560                      parent_link: ParentLink,
561                      def_id: Option<DefId>,
562                      kind: ModuleKind,
563                      external: bool,
564                      is_public: bool,
565                      sp: Span) {
566         // Merges the module with the existing type def or creates a new one.
567         let modifiers = if is_public {
568             DefModifiers::PUBLIC
569         } else {
570             DefModifiers::empty()
571         } | DefModifiers::IMPORTABLE;
572         let module_ = Rc::new(Module::new(parent_link,
573                                           def_id,
574                                           kind,
575                                           external,
576                                           is_public));
577         let type_def = self.type_def.borrow().clone();
578         match type_def {
579             None => {
580                 *self.type_def.borrow_mut() = Some(TypeNsDef {
581                     modifiers: modifiers,
582                     module_def: Some(module_),
583                     type_def: None,
584                     type_span: Some(sp)
585                 });
586             }
587             Some(type_def) => {
588                 *self.type_def.borrow_mut() = Some(TypeNsDef {
589                     modifiers: modifiers,
590                     module_def: Some(module_),
591                     type_span: Some(sp),
592                     type_def: type_def.type_def
593                 });
594             }
595         }
596     }
597
598     /// Sets the kind of the module, creating a new one if necessary.
599     fn set_module_kind(&self,
600                        parent_link: ParentLink,
601                        def_id: Option<DefId>,
602                        kind: ModuleKind,
603                        external: bool,
604                        is_public: bool,
605                        _sp: Span) {
606         let modifiers = if is_public {
607             DefModifiers::PUBLIC
608         } else {
609             DefModifiers::empty()
610         } | DefModifiers::IMPORTABLE;
611         let type_def = self.type_def.borrow().clone();
612         match type_def {
613             None => {
614                 let module = Module::new(parent_link,
615                                          def_id,
616                                          kind,
617                                          external,
618                                          is_public);
619                 *self.type_def.borrow_mut() = Some(TypeNsDef {
620                     modifiers: modifiers,
621                     module_def: Some(Rc::new(module)),
622                     type_def: None,
623                     type_span: None,
624                 });
625             }
626             Some(type_def) => {
627                 match type_def.module_def {
628                     None => {
629                         let module = Module::new(parent_link,
630                                                  def_id,
631                                                  kind,
632                                                  external,
633                                                  is_public);
634                         *self.type_def.borrow_mut() = Some(TypeNsDef {
635                             modifiers: modifiers,
636                             module_def: Some(Rc::new(module)),
637                             type_def: type_def.type_def,
638                             type_span: None,
639                         });
640                     }
641                     Some(module_def) => module_def.kind.set(kind),
642                 }
643             }
644         }
645     }
646
647     /// Records a type definition.
648     fn define_type(&self, def: Def, sp: Span, modifiers: DefModifiers) {
649         debug!("defining type for def {:?} with modifiers {:?}", def, modifiers);
650         // Merges the type with the existing type def or creates a new one.
651         let type_def = self.type_def.borrow().clone();
652         match type_def {
653             None => {
654                 *self.type_def.borrow_mut() = Some(TypeNsDef {
655                     module_def: None,
656                     type_def: Some(def),
657                     type_span: Some(sp),
658                     modifiers: modifiers,
659                 });
660             }
661             Some(type_def) => {
662                 *self.type_def.borrow_mut() = Some(TypeNsDef {
663                     module_def: type_def.module_def,
664                     type_def: Some(def),
665                     type_span: Some(sp),
666                     modifiers: modifiers,
667                 });
668             }
669         }
670     }
671
672     /// Records a value definition.
673     fn define_value(&self, def: Def, sp: Span, modifiers: DefModifiers) {
674         debug!("defining value for def {:?} with modifiers {:?}", def, modifiers);
675         *self.value_def.borrow_mut() = Some(ValueNsDef {
676             def: def,
677             value_span: Some(sp),
678             modifiers: modifiers,
679         });
680     }
681
682     /// Returns the module node if applicable.
683     fn get_module_if_available(&self) -> Option<Rc<Module>> {
684         match *self.type_def.borrow() {
685             Some(ref type_def) => type_def.module_def.clone(),
686             None => None
687         }
688     }
689
690     /// Returns the module node. Panics if this node does not have a module
691     /// definition.
692     fn get_module(&self) -> Rc<Module> {
693         match self.get_module_if_available() {
694             None => {
695                 panic!("get_module called on a node with no module \
696                        definition!")
697             }
698             Some(module_def) => module_def
699         }
700     }
701
702     fn defined_in_namespace(&self, namespace: Namespace) -> bool {
703         match namespace {
704             TypeNS   => return self.type_def.borrow().is_some(),
705             ValueNS  => return self.value_def.borrow().is_some()
706         }
707     }
708
709     fn defined_in_public_namespace(&self, namespace: Namespace) -> bool {
710         self.defined_in_namespace_with(namespace, DefModifiers::PUBLIC)
711     }
712
713     fn defined_in_namespace_with(&self, namespace: Namespace, modifiers: DefModifiers) -> bool {
714         match namespace {
715             TypeNS => match *self.type_def.borrow() {
716                 Some(ref def) => def.modifiers.contains(modifiers), None => false
717             },
718             ValueNS => match *self.value_def.borrow() {
719                 Some(ref def) => def.modifiers.contains(modifiers), None => false
720             }
721         }
722     }
723
724     fn def_for_namespace(&self, namespace: Namespace) -> Option<Def> {
725         match namespace {
726             TypeNS => {
727                 match *self.type_def.borrow() {
728                     None => None,
729                     Some(ref type_def) => {
730                         match type_def.type_def {
731                             Some(type_def) => Some(type_def),
732                             None => {
733                                 match type_def.module_def {
734                                     Some(ref module) => {
735                                         match module.def_id.get() {
736                                             Some(did) => Some(DefMod(did)),
737                                             None => None,
738                                         }
739                                     }
740                                     None => None,
741                                 }
742                             }
743                         }
744                     }
745                 }
746             }
747             ValueNS => {
748                 match *self.value_def.borrow() {
749                     None => None,
750                     Some(value_def) => Some(value_def.def)
751                 }
752             }
753         }
754     }
755
756     fn span_for_namespace(&self, namespace: Namespace) -> Option<Span> {
757         if self.defined_in_namespace(namespace) {
758             match namespace {
759                 TypeNS  => {
760                     match *self.type_def.borrow() {
761                         None => None,
762                         Some(ref type_def) => type_def.type_span
763                     }
764                 }
765                 ValueNS => {
766                     match *self.value_def.borrow() {
767                         None => None,
768                         Some(ref value_def) => value_def.value_span
769                     }
770                 }
771             }
772         } else {
773             None
774         }
775     }
776
777     fn is_public(&self, namespace: Namespace) -> bool {
778         match namespace {
779             TypeNS  => {
780                 let type_def = self.type_def.borrow();
781                 type_def.as_ref().unwrap().modifiers.contains(DefModifiers::PUBLIC)
782             }
783             ValueNS => {
784                 let value_def = self.value_def.borrow();
785                 value_def.as_ref().unwrap().modifiers.contains(DefModifiers::PUBLIC)
786             }
787         }
788     }
789 }
790
791 /// Interns the names of the primitive types.
792 struct PrimitiveTypeTable {
793     primitive_types: HashMap<Name, PrimTy>,
794 }
795
796 impl PrimitiveTypeTable {
797     fn new() -> PrimitiveTypeTable {
798         let mut table = PrimitiveTypeTable {
799             primitive_types: HashMap::new()
800         };
801
802         table.intern("bool",    TyBool);
803         table.intern("char",    TyChar);
804         table.intern("f32",     TyFloat(TyF32));
805         table.intern("f64",     TyFloat(TyF64));
806         table.intern("isize",   TyInt(TyIs));
807         table.intern("i8",      TyInt(TyI8));
808         table.intern("i16",     TyInt(TyI16));
809         table.intern("i32",     TyInt(TyI32));
810         table.intern("i64",     TyInt(TyI64));
811         table.intern("str",     TyStr);
812         table.intern("usize",   TyUint(TyUs));
813         table.intern("u8",      TyUint(TyU8));
814         table.intern("u16",     TyUint(TyU16));
815         table.intern("u32",     TyUint(TyU32));
816         table.intern("u64",     TyUint(TyU64));
817
818         table
819     }
820
821     fn intern(&mut self, string: &str, primitive_type: PrimTy) {
822         self.primitive_types.insert(token::intern(string), primitive_type);
823     }
824 }
825
826 /// The main resolver class.
827 pub struct Resolver<'a, 'tcx:'a> {
828     session: &'a Session,
829
830     ast_map: &'a ast_map::Map<'tcx>,
831
832     graph_root: NameBindings,
833
834     trait_item_map: FnvHashMap<(Name, DefId), DefId>,
835
836     structs: FnvHashMap<DefId, Vec<Name>>,
837
838     // The number of imports that are currently unresolved.
839     unresolved_imports: usize,
840
841     // The module that represents the current item scope.
842     current_module: Rc<Module>,
843
844     // The current set of local scopes, for values.
845     // FIXME #4948: Reuse ribs to avoid allocation.
846     value_ribs: Vec<Rib>,
847
848     // The current set of local scopes, for types.
849     type_ribs: Vec<Rib>,
850
851     // The current set of local scopes, for labels.
852     label_ribs: Vec<Rib>,
853
854     // The trait that the current context can refer to.
855     current_trait_ref: Option<(DefId, TraitRef)>,
856
857     // The current self type if inside an impl (used for better errors).
858     current_self_type: Option<Ty>,
859
860     // The idents for the primitive types.
861     primitive_type_table: PrimitiveTypeTable,
862
863     def_map: DefMap,
864     freevars: RefCell<FreevarMap>,
865     freevars_seen: RefCell<NodeMap<NodeSet>>,
866     export_map: ExportMap,
867     trait_map: TraitMap,
868     external_exports: ExternalExports,
869
870     // Whether or not to print error messages. Can be set to true
871     // when getting additional info for error message suggestions,
872     // so as to avoid printing duplicate errors
873     emit_errors: bool,
874
875     make_glob_map: bool,
876     // Maps imports to the names of items actually imported (this actually maps
877     // all imports, but only glob imports are actually interesting).
878     glob_map: GlobMap,
879
880     used_imports: HashSet<(NodeId, Namespace)>,
881     used_crates: HashSet<CrateNum>,
882 }
883
884 #[derive(PartialEq)]
885 enum FallbackChecks {
886     Everything,
887     OnlyTraitAndStatics
888 }
889
890 impl<'a, 'tcx> Resolver<'a, 'tcx> {
891     fn new(session: &'a Session,
892            ast_map: &'a ast_map::Map<'tcx>,
893            crate_span: Span,
894            make_glob_map: MakeGlobMap) -> Resolver<'a, 'tcx> {
895         let graph_root = NameBindings::new();
896
897         graph_root.define_module(NoParentLink,
898                                  Some(DefId { krate: 0, node: 0 }),
899                                  NormalModuleKind,
900                                  false,
901                                  true,
902                                  crate_span);
903
904         let current_module = graph_root.get_module();
905
906         Resolver {
907             session: session,
908
909             ast_map: ast_map,
910
911             // The outermost module has def ID 0; this is not reflected in the
912             // AST.
913
914             graph_root: graph_root,
915
916             trait_item_map: FnvHashMap(),
917             structs: FnvHashMap(),
918
919             unresolved_imports: 0,
920
921             current_module: current_module,
922             value_ribs: Vec::new(),
923             type_ribs: Vec::new(),
924             label_ribs: Vec::new(),
925
926             current_trait_ref: None,
927             current_self_type: None,
928
929             primitive_type_table: PrimitiveTypeTable::new(),
930
931             def_map: RefCell::new(NodeMap()),
932             freevars: RefCell::new(NodeMap()),
933             freevars_seen: RefCell::new(NodeMap()),
934             export_map: NodeMap(),
935             trait_map: NodeMap(),
936             used_imports: HashSet::new(),
937             used_crates: HashSet::new(),
938             external_exports: DefIdSet(),
939
940             emit_errors: true,
941             make_glob_map: make_glob_map == MakeGlobMap::Yes,
942             glob_map: HashMap::new(),
943         }
944     }
945
946     #[inline]
947     fn record_import_use(&mut self, import_id: NodeId, name: Name) {
948         if !self.make_glob_map {
949             return;
950         }
951         if self.glob_map.contains_key(&import_id) {
952             self.glob_map.get_mut(&import_id).unwrap().insert(name);
953             return;
954         }
955
956         let mut new_set = HashSet::new();
957         new_set.insert(name);
958         self.glob_map.insert(import_id, new_set);
959     }
960
961     fn get_trait_name(&self, did: DefId) -> Name {
962         if did.krate == ast::LOCAL_CRATE {
963             self.ast_map.expect_item(did.node).ident.name
964         } else {
965             csearch::get_trait_name(&self.session.cstore, did)
966         }
967     }
968
969     fn create_name_bindings_from_module(module: Rc<Module>) -> NameBindings {
970         NameBindings {
971             type_def: RefCell::new(Some(TypeNsDef {
972                 modifiers: DefModifiers::IMPORTABLE,
973                 module_def: Some(module),
974                 type_def: None,
975                 type_span: None
976             })),
977             value_def: RefCell::new(None),
978         }
979     }
980
981     /// Checks that the names of external crates don't collide with other
982     /// external crates.
983     fn check_for_conflicts_between_external_crates(&self,
984                                                    module: &Module,
985                                                    name: Name,
986                                                    span: Span) {
987         if module.external_module_children.borrow().contains_key(&name) {
988                 span_err!(self.session, span, E0259,
989                           "an external crate named `{}` has already \
990                            been imported into this module",
991                           name);
992         }
993     }
994
995     /// Checks that the names of items don't collide with external crates.
996     fn check_for_conflicts_between_external_crates_and_items(&self,
997                                                              module: &Module,
998                                                              name: Name,
999                                                              span: Span) {
1000         if module.external_module_children.borrow().contains_key(&name) {
1001                 span_err!(self.session, span, E0260,
1002                           "the name `{}` conflicts with an external \
1003                            crate that has been imported into this \
1004                            module",
1005                            name);
1006         }
1007     }
1008
1009     /// Resolves the given module path from the given root `module_`.
1010     fn resolve_module_path_from_root(&mut self,
1011                                      module_: Rc<Module>,
1012                                      module_path: &[Name],
1013                                      index: usize,
1014                                      span: Span,
1015                                      name_search_type: NameSearchType,
1016                                      lp: LastPrivate)
1017                                 -> ResolveResult<(Rc<Module>, LastPrivate)> {
1018         fn search_parent_externals(needle: Name, module: &Rc<Module>)
1019                                 -> Option<Rc<Module>> {
1020             match module.external_module_children.borrow().get(&needle) {
1021                 Some(_) => Some(module.clone()),
1022                 None => match module.parent_link {
1023                     ModuleParentLink(ref parent, _) => {
1024                         search_parent_externals(needle, &parent.upgrade().unwrap())
1025                     }
1026                    _ => None
1027                 }
1028             }
1029         }
1030
1031         let mut search_module = module_;
1032         let mut index = index;
1033         let module_path_len = module_path.len();
1034         let mut closest_private = lp;
1035
1036         // Resolve the module part of the path. This does not involve looking
1037         // upward though scope chains; we simply resolve names directly in
1038         // modules as we go.
1039         while index < module_path_len {
1040             let name = module_path[index];
1041             match self.resolve_name_in_module(search_module.clone(),
1042                                               name,
1043                                               TypeNS,
1044                                               name_search_type,
1045                                               false) {
1046                 Failed(None) => {
1047                     let segment_name = token::get_name(name);
1048                     let module_name = module_to_string(&*search_module);
1049                     let mut span = span;
1050                     let msg = if "???" == &module_name[..] {
1051                         span.hi = span.lo + Pos::from_usize(segment_name.len());
1052
1053                         match search_parent_externals(name,
1054                                                      &self.current_module) {
1055                             Some(module) => {
1056                                 let path_str = names_to_string(module_path);
1057                                 let target_mod_str = module_to_string(&*module);
1058                                 let current_mod_str =
1059                                     module_to_string(&*self.current_module);
1060
1061                                 let prefix = if target_mod_str == current_mod_str {
1062                                     "self::".to_string()
1063                                 } else {
1064                                     format!("{}::", target_mod_str)
1065                                 };
1066
1067                                 format!("Did you mean `{}{}`?", prefix, path_str)
1068                             },
1069                             None => format!("Maybe a missing `extern crate {}`?",
1070                                             segment_name),
1071                         }
1072                     } else {
1073                         format!("Could not find `{}` in `{}`",
1074                                 segment_name,
1075                                 module_name)
1076                     };
1077
1078                     return Failed(Some((span, msg)));
1079                 }
1080                 Failed(err) => return Failed(err),
1081                 Indeterminate => {
1082                     debug!("(resolving module path for import) module \
1083                             resolution is indeterminate: {}",
1084                             name);
1085                     return Indeterminate;
1086                 }
1087                 Success((target, used_proxy)) => {
1088                     // Check to see whether there are type bindings, and, if
1089                     // so, whether there is a module within.
1090                     match *target.bindings.type_def.borrow() {
1091                         Some(ref type_def) => {
1092                             match type_def.module_def {
1093                                 None => {
1094                                     let msg = format!("Not a module `{}`",
1095                                                         name);
1096
1097                                     return Failed(Some((span, msg)));
1098                                 }
1099                                 Some(ref module_def) => {
1100                                     search_module = module_def.clone();
1101
1102                                     // track extern crates for unused_extern_crate lint
1103                                     if let Some(did) = module_def.def_id.get() {
1104                                         self.used_crates.insert(did.krate);
1105                                     }
1106
1107                                     // Keep track of the closest
1108                                     // private module used when
1109                                     // resolving this import chain.
1110                                     if !used_proxy && !search_module.is_public {
1111                                         if let Some(did) = search_module.def_id.get() {
1112                                             closest_private = LastMod(DependsOn(did));
1113                                         }
1114                                     }
1115                                 }
1116                             }
1117                         }
1118                         None => {
1119                             // There are no type bindings at all.
1120                             let msg = format!("Not a module `{}`",
1121                                               name);
1122                             return Failed(Some((span, msg)));
1123                         }
1124                     }
1125                 }
1126             }
1127
1128             index += 1;
1129         }
1130
1131         return Success((search_module, closest_private));
1132     }
1133
1134     /// Attempts to resolve the module part of an import directive or path
1135     /// rooted at the given module.
1136     ///
1137     /// On success, returns the resolved module, and the closest *private*
1138     /// module found to the destination when resolving this path.
1139     fn resolve_module_path(&mut self,
1140                            module_: Rc<Module>,
1141                            module_path: &[Name],
1142                            use_lexical_scope: UseLexicalScopeFlag,
1143                            span: Span,
1144                            name_search_type: NameSearchType)
1145                            -> ResolveResult<(Rc<Module>, LastPrivate)> {
1146         let module_path_len = module_path.len();
1147         assert!(module_path_len > 0);
1148
1149         debug!("(resolving module path for import) processing `{}` rooted at `{}`",
1150                names_to_string(module_path),
1151                module_to_string(&*module_));
1152
1153         // Resolve the module prefix, if any.
1154         let module_prefix_result = self.resolve_module_prefix(module_.clone(),
1155                                                               module_path);
1156
1157         let search_module;
1158         let start_index;
1159         let last_private;
1160         match module_prefix_result {
1161             Failed(None) => {
1162                 let mpath = names_to_string(module_path);
1163                 let mpath = &mpath[..];
1164                 match mpath.rfind(':') {
1165                     Some(idx) => {
1166                         let msg = format!("Could not find `{}` in `{}`",
1167                                             // idx +- 1 to account for the
1168                                             // colons on either side
1169                                             &mpath[idx + 1..],
1170                                             &mpath[..idx - 1]);
1171                         return Failed(Some((span, msg)));
1172                     },
1173                     None => {
1174                         return Failed(None)
1175                     }
1176                 }
1177             }
1178             Failed(err) => return Failed(err),
1179             Indeterminate => {
1180                 debug!("(resolving module path for import) indeterminate; \
1181                         bailing");
1182                 return Indeterminate;
1183             }
1184             Success(NoPrefixFound) => {
1185                 // There was no prefix, so we're considering the first element
1186                 // of the path. How we handle this depends on whether we were
1187                 // instructed to use lexical scope or not.
1188                 match use_lexical_scope {
1189                     DontUseLexicalScope => {
1190                         // This is a crate-relative path. We will start the
1191                         // resolution process at index zero.
1192                         search_module = self.graph_root.get_module();
1193                         start_index = 0;
1194                         last_private = LastMod(AllPublic);
1195                     }
1196                     UseLexicalScope => {
1197                         // This is not a crate-relative path. We resolve the
1198                         // first component of the path in the current lexical
1199                         // scope and then proceed to resolve below that.
1200                         match self.resolve_module_in_lexical_scope(module_,
1201                                                                    module_path[0]) {
1202                             Failed(err) => return Failed(err),
1203                             Indeterminate => {
1204                                 debug!("(resolving module path for import) \
1205                                         indeterminate; bailing");
1206                                 return Indeterminate;
1207                             }
1208                             Success(containing_module) => {
1209                                 search_module = containing_module;
1210                                 start_index = 1;
1211                                 last_private = LastMod(AllPublic);
1212                             }
1213                         }
1214                     }
1215                 }
1216             }
1217             Success(PrefixFound(ref containing_module, index)) => {
1218                 search_module = containing_module.clone();
1219                 start_index = index;
1220                 last_private = LastMod(DependsOn(containing_module.def_id
1221                                                                   .get()
1222                                                                   .unwrap()));
1223             }
1224         }
1225
1226         self.resolve_module_path_from_root(search_module,
1227                                            module_path,
1228                                            start_index,
1229                                            span,
1230                                            name_search_type,
1231                                            last_private)
1232     }
1233
1234     /// Invariant: This must only be called during main resolution, not during
1235     /// import resolution.
1236     fn resolve_item_in_lexical_scope(&mut self,
1237                                      module_: Rc<Module>,
1238                                      name: Name,
1239                                      namespace: Namespace)
1240                                     -> ResolveResult<(Target, bool)> {
1241         debug!("(resolving item in lexical scope) resolving `{}` in \
1242                 namespace {:?} in `{}`",
1243                name,
1244                namespace,
1245                module_to_string(&*module_));
1246
1247         // The current module node is handled specially. First, check for
1248         // its immediate children.
1249         build_reduced_graph::populate_module_if_necessary(self, &module_);
1250
1251         match module_.children.borrow().get(&name) {
1252             Some(name_bindings)
1253                     if name_bindings.defined_in_namespace(namespace) => {
1254                 debug!("top name bindings succeeded");
1255                 return Success((Target::new(module_.clone(),
1256                                             name_bindings.clone(),
1257                                             Shadowable::Never),
1258                                false));
1259             }
1260             Some(_) | None => { /* Not found; continue. */ }
1261         }
1262
1263         // Now check for its import directives. We don't have to have resolved
1264         // all its imports in the usual way; this is because chains of
1265         // adjacent import statements are processed as though they mutated the
1266         // current scope.
1267         if let Some(import_resolution) = module_.import_resolutions.borrow().get(&name) {
1268             match (*import_resolution).target_for_namespace(namespace) {
1269                 None => {
1270                     // Not found; continue.
1271                     debug!("(resolving item in lexical scope) found \
1272                             import resolution, but not in namespace {:?}",
1273                            namespace);
1274                 }
1275                 Some(target) => {
1276                     debug!("(resolving item in lexical scope) using \
1277                             import resolution");
1278                     // track used imports and extern crates as well
1279                     let id = import_resolution.id(namespace);
1280                     self.used_imports.insert((id, namespace));
1281                     self.record_import_use(id, name);
1282                     if let Some(DefId{krate: kid, ..}) = target.target_module.def_id.get() {
1283                          self.used_crates.insert(kid);
1284                     }
1285                     return Success((target, false));
1286                 }
1287             }
1288         }
1289
1290         // Search for external modules.
1291         if namespace == TypeNS {
1292             // FIXME (21114): In principle unclear `child` *has* to be lifted.
1293             let child = module_.external_module_children.borrow().get(&name).cloned();
1294             if let Some(module) = child {
1295                 let name_bindings =
1296                     Rc::new(Resolver::create_name_bindings_from_module(module));
1297                 debug!("lower name bindings succeeded");
1298                 return Success((Target::new(module_,
1299                                             name_bindings,
1300                                             Shadowable::Never),
1301                                 false));
1302             }
1303         }
1304
1305         // Finally, proceed up the scope chain looking for parent modules.
1306         let mut search_module = module_;
1307         loop {
1308             // Go to the next parent.
1309             match search_module.parent_link.clone() {
1310                 NoParentLink => {
1311                     // No more parents. This module was unresolved.
1312                     debug!("(resolving item in lexical scope) unresolved \
1313                             module");
1314                     return Failed(None);
1315                 }
1316                 ModuleParentLink(parent_module_node, _) => {
1317                     match search_module.kind.get() {
1318                         NormalModuleKind => {
1319                             // We stop the search here.
1320                             debug!("(resolving item in lexical \
1321                                     scope) unresolved module: not \
1322                                     searching through module \
1323                                     parents");
1324                             return Failed(None);
1325                         }
1326                         TraitModuleKind |
1327                         EnumModuleKind |
1328                         TypeModuleKind |
1329                         AnonymousModuleKind => {
1330                             search_module = parent_module_node.upgrade().unwrap();
1331                         }
1332                     }
1333                 }
1334                 BlockParentLink(ref parent_module_node, _) => {
1335                     search_module = parent_module_node.upgrade().unwrap();
1336                 }
1337             }
1338
1339             // Resolve the name in the parent module.
1340             match self.resolve_name_in_module(search_module.clone(),
1341                                               name,
1342                                               namespace,
1343                                               PathSearch,
1344                                               true) {
1345                 Failed(Some((span, msg))) => {
1346                     resolve_error(&ResolutionError::FailedToResolve(self, span),
1347                                   &*format!("failed to resolve. {}",
1348                                         msg)
1349                                  );
1350                 },
1351                 Failed(None) => (), // Continue up the search chain.
1352                 Indeterminate => {
1353                     // We couldn't see through the higher scope because of an
1354                     // unresolved import higher up. Bail.
1355
1356                     debug!("(resolving item in lexical scope) indeterminate \
1357                             higher scope; bailing");
1358                     return Indeterminate;
1359                 }
1360                 Success((target, used_reexport)) => {
1361                     // We found the module.
1362                     debug!("(resolving item in lexical scope) found name \
1363                             in module, done");
1364                     return Success((target, used_reexport));
1365                 }
1366             }
1367         }
1368     }
1369
1370     /// Resolves a module name in the current lexical scope.
1371     fn resolve_module_in_lexical_scope(&mut self,
1372                                        module_: Rc<Module>,
1373                                        name: Name)
1374                                 -> ResolveResult<Rc<Module>> {
1375         // If this module is an anonymous module, resolve the item in the
1376         // lexical scope. Otherwise, resolve the item from the crate root.
1377         let resolve_result = self.resolve_item_in_lexical_scope(module_, name, TypeNS);
1378         match resolve_result {
1379             Success((target, _)) => {
1380                 let bindings = &*target.bindings;
1381                 match *bindings.type_def.borrow() {
1382                     Some(ref type_def) => {
1383                         match type_def.module_def {
1384                             None => {
1385                                 debug!("!!! (resolving module in lexical \
1386                                         scope) module wasn't actually a \
1387                                         module!");
1388                                 return Failed(None);
1389                             }
1390                             Some(ref module_def) => {
1391                                 return Success(module_def.clone());
1392                             }
1393                         }
1394                     }
1395                     None => {
1396                         debug!("!!! (resolving module in lexical scope) module
1397                                 wasn't actually a module!");
1398                         return Failed(None);
1399                     }
1400                 }
1401             }
1402             Indeterminate => {
1403                 debug!("(resolving module in lexical scope) indeterminate; \
1404                         bailing");
1405                 return Indeterminate;
1406             }
1407             Failed(err) => {
1408                 debug!("(resolving module in lexical scope) failed to resolve");
1409                 return Failed(err);
1410             }
1411         }
1412     }
1413
1414     /// Returns the nearest normal module parent of the given module.
1415     fn get_nearest_normal_module_parent(&mut self, module_: Rc<Module>)
1416                                             -> Option<Rc<Module>> {
1417         let mut module_ = module_;
1418         loop {
1419             match module_.parent_link.clone() {
1420                 NoParentLink => return None,
1421                 ModuleParentLink(new_module, _) |
1422                 BlockParentLink(new_module, _) => {
1423                     let new_module = new_module.upgrade().unwrap();
1424                     match new_module.kind.get() {
1425                         NormalModuleKind => return Some(new_module),
1426                         TraitModuleKind |
1427                         EnumModuleKind |
1428                         TypeModuleKind |
1429                         AnonymousModuleKind => module_ = new_module,
1430                     }
1431                 }
1432             }
1433         }
1434     }
1435
1436     /// Returns the nearest normal module parent of the given module, or the
1437     /// module itself if it is a normal module.
1438     fn get_nearest_normal_module_parent_or_self(&mut self, module_: Rc<Module>)
1439                                                 -> Rc<Module> {
1440         match module_.kind.get() {
1441             NormalModuleKind => return module_,
1442             TraitModuleKind |
1443             EnumModuleKind |
1444             TypeModuleKind |
1445             AnonymousModuleKind => {
1446                 match self.get_nearest_normal_module_parent(module_.clone()) {
1447                     None => module_,
1448                     Some(new_module) => new_module
1449                 }
1450             }
1451         }
1452     }
1453
1454     /// Resolves a "module prefix". A module prefix is one or both of (a) `self::`;
1455     /// (b) some chain of `super::`.
1456     /// grammar: (SELF MOD_SEP ) ? (SUPER MOD_SEP) *
1457     fn resolve_module_prefix(&mut self,
1458                              module_: Rc<Module>,
1459                              module_path: &[Name])
1460                                  -> ResolveResult<ModulePrefixResult> {
1461         // Start at the current module if we see `self` or `super`, or at the
1462         // top of the crate otherwise.
1463         let mut containing_module;
1464         let mut i;
1465         let first_module_path_string = token::get_name(module_path[0]);
1466         if "self" == &first_module_path_string[..] {
1467             containing_module =
1468                 self.get_nearest_normal_module_parent_or_self(module_);
1469             i = 1;
1470         } else if "super" == &first_module_path_string[..] {
1471             containing_module =
1472                 self.get_nearest_normal_module_parent_or_self(module_);
1473             i = 0;  // We'll handle `super` below.
1474         } else {
1475             return Success(NoPrefixFound);
1476         }
1477
1478         // Now loop through all the `super`s we find.
1479         while i < module_path.len() {
1480             let string = token::get_name(module_path[i]);
1481             if "super" != &string[..] {
1482                 break
1483             }
1484             debug!("(resolving module prefix) resolving `super` at {}",
1485                    module_to_string(&*containing_module));
1486             match self.get_nearest_normal_module_parent(containing_module) {
1487                 None => return Failed(None),
1488                 Some(new_module) => {
1489                     containing_module = new_module;
1490                     i += 1;
1491                 }
1492             }
1493         }
1494
1495         debug!("(resolving module prefix) finished resolving prefix at {}",
1496                module_to_string(&*containing_module));
1497
1498         return Success(PrefixFound(containing_module, i));
1499     }
1500
1501     /// Attempts to resolve the supplied name in the given module for the
1502     /// given namespace. If successful, returns the target corresponding to
1503     /// the name.
1504     ///
1505     /// The boolean returned on success is an indicator of whether this lookup
1506     /// passed through a public re-export proxy.
1507     fn resolve_name_in_module(&mut self,
1508                               module_: Rc<Module>,
1509                               name: Name,
1510                               namespace: Namespace,
1511                               name_search_type: NameSearchType,
1512                               allow_private_imports: bool)
1513                               -> ResolveResult<(Target, bool)> {
1514         debug!("(resolving name in module) resolving `{}` in `{}`",
1515                name,
1516                module_to_string(&*module_));
1517
1518         // First, check the direct children of the module.
1519         build_reduced_graph::populate_module_if_necessary(self, &module_);
1520
1521         match module_.children.borrow().get(&name) {
1522             Some(name_bindings)
1523                     if name_bindings.defined_in_namespace(namespace) => {
1524                 debug!("(resolving name in module) found node as child");
1525                 return Success((Target::new(module_.clone(),
1526                                             name_bindings.clone(),
1527                                             Shadowable::Never),
1528                                false));
1529             }
1530             Some(_) | None => {
1531                 // Continue.
1532             }
1533         }
1534
1535         // Next, check the module's imports if necessary.
1536
1537         // If this is a search of all imports, we should be done with glob
1538         // resolution at this point.
1539         if name_search_type == PathSearch {
1540             assert_eq!(module_.glob_count.get(), 0);
1541         }
1542
1543         // Check the list of resolved imports.
1544         match module_.import_resolutions.borrow().get(&name) {
1545             Some(import_resolution) if allow_private_imports ||
1546                                        import_resolution.is_public => {
1547
1548                 if import_resolution.is_public &&
1549                         import_resolution.outstanding_references != 0 {
1550                     debug!("(resolving name in module) import \
1551                            unresolved; bailing out");
1552                     return Indeterminate;
1553                 }
1554                 match import_resolution.target_for_namespace(namespace) {
1555                     None => {
1556                         debug!("(resolving name in module) name found, \
1557                                 but not in namespace {:?}",
1558                                namespace);
1559                     }
1560                     Some(target) => {
1561                         debug!("(resolving name in module) resolved to \
1562                                 import");
1563                         // track used imports and extern crates as well
1564                         let id = import_resolution.id(namespace);
1565                         self.used_imports.insert((id, namespace));
1566                         self.record_import_use(id, name);
1567                         if let Some(DefId{krate: kid, ..}) = target.target_module.def_id.get() {
1568                             self.used_crates.insert(kid);
1569                         }
1570                         return Success((target, true));
1571                     }
1572                 }
1573             }
1574             Some(..) | None => {} // Continue.
1575         }
1576
1577         // Finally, search through external children.
1578         if namespace == TypeNS {
1579             // FIXME (21114): In principle unclear `child` *has* to be lifted.
1580             let child = module_.external_module_children.borrow().get(&name).cloned();
1581             if let Some(module) = child {
1582                 let name_bindings =
1583                     Rc::new(Resolver::create_name_bindings_from_module(module));
1584                 return Success((Target::new(module_,
1585                                             name_bindings,
1586                                             Shadowable::Never),
1587                                 false));
1588             }
1589         }
1590
1591         // We're out of luck.
1592         debug!("(resolving name in module) failed to resolve `{}`",
1593                name);
1594         return Failed(None);
1595     }
1596
1597     fn report_unresolved_imports(&mut self, module_: Rc<Module>) {
1598         let index = module_.resolved_import_count.get();
1599         let imports = module_.imports.borrow();
1600         let import_count = imports.len();
1601         if index != import_count {
1602             let sn = self.session
1603                          .codemap()
1604                          .span_to_snippet((*imports)[index].span)
1605                          .unwrap();
1606             if sn.contains("::") {
1607                 resolve_error(&ResolutionError::UnresolvedImport(self, (*imports)[index].span),
1608                               "unresolved import");
1609             } else {
1610                 resolve_error(&ResolutionError::UnresolvedImport(self, (*imports)[index].span),
1611                               &*format!("unresolved import (maybe you meant `{}::*`?)",
1612                                     sn)
1613                              );
1614             }
1615         }
1616
1617         // Descend into children and anonymous children.
1618         build_reduced_graph::populate_module_if_necessary(self, &module_);
1619
1620         for (_, child_node) in module_.children.borrow().iter() {
1621             match child_node.get_module_if_available() {
1622                 None => {
1623                     // Continue.
1624                 }
1625                 Some(child_module) => {
1626                     self.report_unresolved_imports(child_module);
1627                 }
1628             }
1629         }
1630
1631         for (_, module_) in module_.anonymous_children.borrow().iter() {
1632             self.report_unresolved_imports(module_.clone());
1633         }
1634     }
1635
1636     // AST resolution
1637     //
1638     // We maintain a list of value ribs and type ribs.
1639     //
1640     // Simultaneously, we keep track of the current position in the module
1641     // graph in the `current_module` pointer. When we go to resolve a name in
1642     // the value or type namespaces, we first look through all the ribs and
1643     // then query the module graph. When we resolve a name in the module
1644     // namespace, we can skip all the ribs (since nested modules are not
1645     // allowed within blocks in Rust) and jump straight to the current module
1646     // graph node.
1647     //
1648     // Named implementations are handled separately. When we find a method
1649     // call, we consult the module node to find all of the implementations in
1650     // scope. This information is lazily cached in the module node. We then
1651     // generate a fake "implementation scope" containing all the
1652     // implementations thus found, for compatibility with old resolve pass.
1653
1654     fn with_scope<F>(&mut self, name: Option<Name>, f: F) where
1655         F: FnOnce(&mut Resolver),
1656     {
1657         let orig_module = self.current_module.clone();
1658
1659         // Move down in the graph.
1660         match name {
1661             None => {
1662                 // Nothing to do.
1663             }
1664             Some(name) => {
1665                 build_reduced_graph::populate_module_if_necessary(self, &orig_module);
1666
1667                 match orig_module.children.borrow().get(&name) {
1668                     None => {
1669                         debug!("!!! (with scope) didn't find `{}` in `{}`",
1670                                name,
1671                                module_to_string(&*orig_module));
1672                     }
1673                     Some(name_bindings) => {
1674                         match (*name_bindings).get_module_if_available() {
1675                             None => {
1676                                 debug!("!!! (with scope) didn't find module \
1677                                         for `{}` in `{}`",
1678                                        name,
1679                                        module_to_string(&*orig_module));
1680                             }
1681                             Some(module_) => {
1682                                 self.current_module = module_;
1683                             }
1684                         }
1685                     }
1686                 }
1687             }
1688         }
1689
1690         f(self);
1691
1692         self.current_module = orig_module;
1693     }
1694
1695     /// Wraps the given definition in the appropriate number of `DefUpvar`
1696     /// wrappers.
1697     fn upvarify(&self,
1698                 ribs: &[Rib],
1699                 def_like: DefLike,
1700                 span: Span)
1701                 -> Option<DefLike> {
1702         let mut def = match def_like {
1703             DlDef(def) => def,
1704             _ => return Some(def_like)
1705         };
1706         match def {
1707             DefUpvar(..) => {
1708                 self.session.span_bug(span,
1709                     &format!("unexpected {:?} in bindings", def))
1710             }
1711             DefLocal(node_id) => {
1712                 for rib in ribs {
1713                     match rib.kind {
1714                         NormalRibKind => {
1715                             // Nothing to do. Continue.
1716                         }
1717                         ClosureRibKind(function_id) => {
1718                             let prev_def = def;
1719                             def = DefUpvar(node_id, function_id);
1720
1721                             let mut seen = self.freevars_seen.borrow_mut();
1722                             let seen = match seen.entry(function_id) {
1723                                 Occupied(v) => v.into_mut(),
1724                                 Vacant(v) => v.insert(NodeSet()),
1725                             };
1726                             if seen.contains(&node_id) {
1727                                 continue;
1728                             }
1729                             match self.freevars.borrow_mut().entry(function_id) {
1730                                 Occupied(v) => v.into_mut(),
1731                                 Vacant(v) => v.insert(vec![]),
1732                             }.push(Freevar { def: prev_def, span: span });
1733                             seen.insert(node_id);
1734                         }
1735                         ItemRibKind | MethodRibKind => {
1736                             // This was an attempt to access an upvar inside a
1737                             // named function item. This is not allowed, so we
1738                             // report an error.
1739                             resolve_err!(self, span, E0434, "{}",
1740                                          "can't capture dynamic environment in a fn item; \
1741                                           use the || { ... } closure form instead");
1742                             return None;
1743                         }
1744                         ConstantItemRibKind => {
1745                             // Still doesn't deal with upvars
1746                             resolve_err!(self, span, E0435, "{}",
1747                                          "attempt to use a non-constant \
1748                                           value in a constant");
1749                             return None;
1750                         }
1751                     }
1752                 }
1753             }
1754             DefTyParam(..) | DefSelfTy(..) => {
1755                 for rib in ribs {
1756                     match rib.kind {
1757                         NormalRibKind | MethodRibKind | ClosureRibKind(..) => {
1758                             // Nothing to do. Continue.
1759                         }
1760                         ItemRibKind => {
1761                             // This was an attempt to use a type parameter outside
1762                             // its scope.
1763
1764                             resolve_err!(self, span, E0401, "{}",
1765                                          "can't use type parameters from \
1766                                           outer function; try using a local \
1767                                           type parameter instead");
1768                             return None;
1769                         }
1770                         ConstantItemRibKind => {
1771                             // see #9186
1772                             resolve_err!(self, span, E0402, "{}",
1773                                          "cannot use an outer type \
1774                                           parameter in this context");
1775                             return None;
1776                         }
1777                     }
1778                 }
1779             }
1780             _ => {}
1781         }
1782         Some(DlDef(def))
1783     }
1784
1785     /// Searches the current set of local scopes and
1786     /// applies translations for closures.
1787     fn search_ribs(&self,
1788                    ribs: &[Rib],
1789                    name: Name,
1790                    span: Span)
1791                    -> Option<DefLike> {
1792         // FIXME #4950: Try caching?
1793
1794         for (i, rib) in ribs.iter().enumerate().rev() {
1795             if let Some(def_like) = rib.bindings.get(&name).cloned() {
1796                 return self.upvarify(&ribs[i + 1..], def_like, span);
1797             }
1798         }
1799
1800         None
1801     }
1802
1803     /// Searches the current set of local scopes for labels.
1804     /// Stops after meeting a closure.
1805     fn search_label(&self, name: Name) -> Option<DefLike> {
1806         for rib in self.label_ribs.iter().rev() {
1807             match rib.kind {
1808                 NormalRibKind => {
1809                     // Continue
1810                 }
1811                 _ => {
1812                     // Do not resolve labels across function boundary
1813                     return None
1814                 }
1815             }
1816             let result = rib.bindings.get(&name).cloned();
1817             if result.is_some() {
1818                 return result
1819             }
1820         }
1821         None
1822     }
1823
1824     fn resolve_crate(&mut self, krate: &ast::Crate) {
1825         debug!("(resolving crate) starting");
1826
1827         visit::walk_crate(self, krate);
1828     }
1829
1830     fn check_if_primitive_type_name(&self, name: Name, span: Span) {
1831         if let Some(_) = self.primitive_type_table.primitive_types.get(&name) {
1832             span_err!(self.session, span, E0317,
1833                 "user-defined types or type parameters cannot shadow the primitive types");
1834         }
1835     }
1836
1837     fn resolve_item(&mut self, item: &Item) {
1838         let name = item.ident.name;
1839
1840         debug!("(resolving item) resolving {}",
1841                name);
1842
1843         match item.node {
1844             ItemEnum(_, ref generics) |
1845             ItemTy(_, ref generics) |
1846             ItemStruct(_, ref generics) => {
1847                 self.check_if_primitive_type_name(name, item.span);
1848
1849                 self.with_type_parameter_rib(HasTypeParameters(generics,
1850                                                                TypeSpace,
1851                                                                ItemRibKind),
1852                                              |this| visit::walk_item(this, item));
1853             }
1854             ItemFn(_, _, _, _, ref generics, _) => {
1855                 self.with_type_parameter_rib(HasTypeParameters(generics,
1856                                                                FnSpace,
1857                                                                ItemRibKind),
1858                                              |this| visit::walk_item(this, item));
1859             }
1860
1861             ItemDefaultImpl(_, ref trait_ref) => {
1862                 self.with_optional_trait_ref(Some(trait_ref), |_, _| {});
1863             }
1864             ItemImpl(_,
1865                      _,
1866                      ref generics,
1867                      ref opt_trait_ref,
1868                      ref self_type,
1869                      ref impl_items) => {
1870                 self.resolve_implementation(generics,
1871                                             opt_trait_ref,
1872                                             &**self_type,
1873                                             item.id,
1874                                             &impl_items[..]);
1875             }
1876
1877             ItemTrait(_, ref generics, ref bounds, ref trait_items) => {
1878                 self.check_if_primitive_type_name(name, item.span);
1879
1880                 // Create a new rib for the trait-wide type parameters.
1881                 self.with_type_parameter_rib(HasTypeParameters(generics,
1882                                                                TypeSpace,
1883                                                                ItemRibKind),
1884                                              |this| {
1885                     this.with_self_rib(DefSelfTy(Some(local_def(item.id)), None), |this| {
1886                         this.visit_generics(generics);
1887                         visit::walk_ty_param_bounds_helper(this, bounds);
1888
1889                         for trait_item in trait_items {
1890                             // Create a new rib for the trait_item-specific type
1891                             // parameters.
1892                             //
1893                             // FIXME #4951: Do we need a node ID here?
1894
1895                             match trait_item.node {
1896                                 ast::ConstTraitItem(_, ref default) => {
1897                                     // Only impose the restrictions of
1898                                     // ConstRibKind if there's an actual constant
1899                                     // expression in a provided default.
1900                                     if default.is_some() {
1901                                         this.with_constant_rib(|this| {
1902                                             visit::walk_trait_item(this, trait_item)
1903                                         });
1904                                     } else {
1905                                         visit::walk_trait_item(this, trait_item)
1906                                     }
1907                                 }
1908                                 ast::MethodTraitItem(ref sig, _) => {
1909                                     let type_parameters =
1910                                         HasTypeParameters(&sig.generics,
1911                                                           FnSpace,
1912                                                           MethodRibKind);
1913                                     this.with_type_parameter_rib(type_parameters, |this| {
1914                                         visit::walk_trait_item(this, trait_item)
1915                                     });
1916                                 }
1917                                 ast::TypeTraitItem(..) => {
1918                                     this.check_if_primitive_type_name(trait_item.ident.name,
1919                                                                       trait_item.span);
1920                                     this.with_type_parameter_rib(NoTypeParameters, |this| {
1921                                         visit::walk_trait_item(this, trait_item)
1922                                     });
1923                                 }
1924                             };
1925                         }
1926                     });
1927                 });
1928             }
1929
1930             ItemMod(_) | ItemForeignMod(_) => {
1931                 self.with_scope(Some(name), |this| {
1932                     visit::walk_item(this, item);
1933                 });
1934             }
1935
1936             ItemConst(..) | ItemStatic(..) => {
1937                 self.with_constant_rib(|this| {
1938                     visit::walk_item(this, item);
1939                 });
1940             }
1941
1942             ItemUse(ref view_path) => {
1943                 // check for imports shadowing primitive types
1944                 if let ast::ViewPathSimple(ident, _) = view_path.node {
1945                     match self.def_map.borrow().get(&item.id).map(|d| d.full_def()) {
1946                         Some(DefTy(..)) | Some(DefStruct(..)) | Some(DefTrait(..)) | None => {
1947                             self.check_if_primitive_type_name(ident.name, item.span);
1948                         }
1949                         _ => {}
1950                     }
1951                 }
1952             }
1953
1954             ItemExternCrate(_) | ItemMac(..) => {
1955                 // do nothing, these are just around to be encoded
1956             }
1957         }
1958     }
1959
1960     fn with_type_parameter_rib<F>(&mut self, type_parameters: TypeParameters, f: F) where
1961         F: FnOnce(&mut Resolver),
1962     {
1963         match type_parameters {
1964             HasTypeParameters(generics, space, rib_kind) => {
1965                 let mut function_type_rib = Rib::new(rib_kind);
1966                 let mut seen_bindings = HashSet::new();
1967                 for (index, type_parameter) in generics.ty_params.iter().enumerate() {
1968                     let name = type_parameter.ident.name;
1969                     debug!("with_type_parameter_rib: {}", type_parameter.id);
1970
1971                     if seen_bindings.contains(&name) {
1972                         resolve_err!(self, type_parameter.span, E0403,
1973                                      "the name `{}` is already \
1974                                       used for a type \
1975                                       parameter in this type \
1976                                       parameter list",
1977                                      name)
1978                     }
1979                     seen_bindings.insert(name);
1980
1981                     // plain insert (no renaming)
1982                     function_type_rib.bindings.insert(name,
1983                         DlDef(DefTyParam(space,
1984                                          index as u32,
1985                                          local_def(type_parameter.id),
1986                                          name)));
1987                 }
1988                 self.type_ribs.push(function_type_rib);
1989             }
1990
1991             NoTypeParameters => {
1992                 // Nothing to do.
1993             }
1994         }
1995
1996         f(self);
1997
1998         match type_parameters {
1999             HasTypeParameters(..) => { self.type_ribs.pop(); }
2000             NoTypeParameters => { }
2001         }
2002     }
2003
2004     fn with_label_rib<F>(&mut self, f: F) where
2005         F: FnOnce(&mut Resolver),
2006     {
2007         self.label_ribs.push(Rib::new(NormalRibKind));
2008         f(self);
2009         self.label_ribs.pop();
2010     }
2011
2012     fn with_constant_rib<F>(&mut self, f: F) where
2013         F: FnOnce(&mut Resolver),
2014     {
2015         self.value_ribs.push(Rib::new(ConstantItemRibKind));
2016         self.type_ribs.push(Rib::new(ConstantItemRibKind));
2017         f(self);
2018         self.type_ribs.pop();
2019         self.value_ribs.pop();
2020     }
2021
2022     fn resolve_function(&mut self,
2023                         rib_kind: RibKind,
2024                         declaration: &FnDecl,
2025                         block: &Block) {
2026         // Create a value rib for the function.
2027         self.value_ribs.push(Rib::new(rib_kind));
2028
2029         // Create a label rib for the function.
2030         self.label_ribs.push(Rib::new(rib_kind));
2031
2032         // Add each argument to the rib.
2033         let mut bindings_list = HashMap::new();
2034         for argument in &declaration.inputs {
2035             self.resolve_pattern(&*argument.pat,
2036                                  ArgumentIrrefutableMode,
2037                                  &mut bindings_list);
2038
2039             self.visit_ty(&*argument.ty);
2040
2041             debug!("(resolving function) recorded argument");
2042         }
2043         visit::walk_fn_ret_ty(self, &declaration.output);
2044
2045         // Resolve the function body.
2046         self.visit_block(&*block);
2047
2048         debug!("(resolving function) leaving function");
2049
2050         self.label_ribs.pop();
2051         self.value_ribs.pop();
2052     }
2053
2054     fn resolve_trait_reference(&mut self,
2055                                id: NodeId,
2056                                trait_path: &Path,
2057                                path_depth: usize)
2058                                -> Result<PathResolution, ()> {
2059         if let Some(path_res) = self.resolve_path(id, trait_path, path_depth, TypeNS, true) {
2060             if let DefTrait(_) = path_res.base_def {
2061                 debug!("(resolving trait) found trait def: {:?}", path_res);
2062                 Ok(path_res)
2063             } else {
2064                 resolve_err!(self, trait_path.span, E0404,
2065                              "`{}` is not a trait",
2066                              path_names_to_string(trait_path, path_depth));
2067
2068                 // If it's a typedef, give a note
2069                 if let DefTy(..) = path_res.base_def {
2070                     self.session.span_note(trait_path.span,
2071                                            "`type` aliases cannot be used for traits");
2072                 }
2073                 Err(())
2074             }
2075         } else {
2076             resolve_err!(self, trait_path.span, E0405,
2077                          "use of undeclared trait name `{}`",
2078                          path_names_to_string(trait_path, path_depth));
2079             Err(())
2080         }
2081     }
2082
2083     fn resolve_generics(&mut self, generics: &Generics) {
2084         for type_parameter in generics.ty_params.iter() {
2085             self.check_if_primitive_type_name(type_parameter.ident.name, type_parameter.span);
2086         }
2087         for predicate in &generics.where_clause.predicates {
2088             match predicate {
2089                 &ast::WherePredicate::BoundPredicate(_) |
2090                 &ast::WherePredicate::RegionPredicate(_) => {}
2091                 &ast::WherePredicate::EqPredicate(ref eq_pred) => {
2092                     let path_res = self.resolve_path(eq_pred.id, &eq_pred.path, 0, TypeNS, true);
2093                     if let Some(PathResolution { base_def: DefTyParam(..), .. }) = path_res {
2094                         self.record_def(eq_pred.id, path_res.unwrap());
2095                     } else {
2096                         resolve_err!(self, eq_pred.span, E0406, "{}",
2097                                      "undeclared associated type");
2098                     }
2099                 }
2100             }
2101         }
2102         visit::walk_generics(self, generics);
2103     }
2104
2105     fn with_current_self_type<T, F>(&mut self, self_type: &Ty, f: F) -> T
2106         where F: FnOnce(&mut Resolver) -> T
2107     {
2108         // Handle nested impls (inside fn bodies)
2109         let previous_value = replace(&mut self.current_self_type, Some(self_type.clone()));
2110         let result = f(self);
2111         self.current_self_type = previous_value;
2112         result
2113     }
2114
2115     fn with_optional_trait_ref<T, F>(&mut self,
2116                                      opt_trait_ref: Option<&TraitRef>,
2117                                      f: F)
2118                                      -> T
2119         where F: FnOnce(&mut Resolver, Option<DefId>) -> T
2120     {
2121         let mut new_val = None;
2122         let mut new_id = None;
2123         if let Some(trait_ref) = opt_trait_ref {
2124             if let Ok(path_res) = self.resolve_trait_reference(trait_ref.ref_id,
2125                                                                &trait_ref.path, 0) {
2126                 assert!(path_res.depth == 0);
2127                 self.record_def(trait_ref.ref_id, path_res);
2128                 new_val = Some((path_res.base_def.def_id(), trait_ref.clone()));
2129                 new_id = Some(path_res.base_def.def_id());
2130             }
2131             visit::walk_trait_ref(self, trait_ref);
2132         }
2133         let original_trait_ref = replace(&mut self.current_trait_ref, new_val);
2134         let result = f(self, new_id);
2135         self.current_trait_ref = original_trait_ref;
2136         result
2137     }
2138
2139     fn with_self_rib<F>(&mut self, self_def: Def, f: F)
2140         where F: FnOnce(&mut Resolver)
2141     {
2142         let mut self_type_rib = Rib::new(NormalRibKind);
2143
2144         // plain insert (no renaming, types are not currently hygienic....)
2145         let name = special_names::type_self;
2146         self_type_rib.bindings.insert(name, DlDef(self_def));
2147         self.type_ribs.push(self_type_rib);
2148         f(self);
2149         self.type_ribs.pop();
2150     }
2151
2152     fn resolve_implementation(&mut self,
2153                               generics: &Generics,
2154                               opt_trait_reference: &Option<TraitRef>,
2155                               self_type: &Ty,
2156                               item_id: NodeId,
2157                               impl_items: &[P<ImplItem>]) {
2158         // If applicable, create a rib for the type parameters.
2159         self.with_type_parameter_rib(HasTypeParameters(generics,
2160                                                        TypeSpace,
2161                                                        ItemRibKind),
2162                                      |this| {
2163             // Resolve the type parameters.
2164             this.visit_generics(generics);
2165
2166             // Resolve the trait reference, if necessary.
2167             this.with_optional_trait_ref(opt_trait_reference.as_ref(), |this, trait_id| {
2168                 // Resolve the self type.
2169                 this.visit_ty(self_type);
2170
2171                 this.with_self_rib(DefSelfTy(trait_id, Some((item_id, self_type.id))), |this| {
2172                     this.with_current_self_type(self_type, |this| {
2173                         for impl_item in impl_items {
2174                             match impl_item.node {
2175                                 ConstImplItem(..) => {
2176                                     // If this is a trait impl, ensure the method
2177                                     // exists in trait
2178                                     this.check_trait_item(impl_item.ident.name,
2179                                                           impl_item.span);
2180                                     this.with_constant_rib(|this| {
2181                                         visit::walk_impl_item(this, impl_item);
2182                                     });
2183                                 }
2184                                 MethodImplItem(ref sig, _) => {
2185                                     // If this is a trait impl, ensure the method
2186                                     // exists in trait
2187                                     this.check_trait_item(impl_item.ident.name,
2188                                                           impl_item.span);
2189
2190                                     // We also need a new scope for the method-
2191                                     // specific type parameters.
2192                                     let type_parameters =
2193                                         HasTypeParameters(&sig.generics,
2194                                                           FnSpace,
2195                                                           MethodRibKind);
2196                                     this.with_type_parameter_rib(type_parameters, |this| {
2197                                         visit::walk_impl_item(this, impl_item);
2198                                     });
2199                                 }
2200                                 TypeImplItem(ref ty) => {
2201                                     // If this is a trait impl, ensure the method
2202                                     // exists in trait
2203                                     this.check_trait_item(impl_item.ident.name,
2204                                                           impl_item.span);
2205
2206                                     this.visit_ty(ty);
2207                                 }
2208                                 ast::MacImplItem(_) => {}
2209                             }
2210                         }
2211                     });
2212                 });
2213             });
2214         });
2215     }
2216
2217     fn check_trait_item(&self, name: Name, span: Span) {
2218         // If there is a TraitRef in scope for an impl, then the method must be in the trait.
2219         if let Some((did, ref trait_ref)) = self.current_trait_ref {
2220             if !self.trait_item_map.contains_key(&(name, did)) {
2221                 let path_str = path_names_to_string(&trait_ref.path, 0);
2222                 resolve_err!(self, span, E0407, "method `{}` is not a member of trait `{}`",
2223                              name, path_str);
2224             }
2225         }
2226     }
2227
2228     fn resolve_local(&mut self, local: &Local) {
2229         // Resolve the type.
2230         visit::walk_ty_opt(self, &local.ty);
2231
2232         // Resolve the initializer.
2233         visit::walk_expr_opt(self, &local.init);
2234
2235         // Resolve the pattern.
2236         self.resolve_pattern(&*local.pat,
2237                              LocalIrrefutableMode,
2238                              &mut HashMap::new());
2239     }
2240
2241     // build a map from pattern identifiers to binding-info's.
2242     // this is done hygienically. This could arise for a macro
2243     // that expands into an or-pattern where one 'x' was from the
2244     // user and one 'x' came from the macro.
2245     fn binding_mode_map(&mut self, pat: &Pat) -> BindingMap {
2246         let mut result = HashMap::new();
2247         pat_bindings(&self.def_map, pat, |binding_mode, _id, sp, path1| {
2248             let name = mtwt::resolve(path1.node);
2249             result.insert(name, BindingInfo {
2250                 span: sp,
2251                 binding_mode: binding_mode
2252             });
2253         });
2254         return result;
2255     }
2256
2257     // check that all of the arms in an or-pattern have exactly the
2258     // same set of bindings, with the same binding modes for each.
2259     fn check_consistent_bindings(&mut self, arm: &Arm) {
2260         if arm.pats.is_empty() {
2261             return
2262         }
2263         let map_0 = self.binding_mode_map(&*arm.pats[0]);
2264         for (i, p) in arm.pats.iter().enumerate() {
2265             let map_i = self.binding_mode_map(&**p);
2266
2267             for (&key, &binding_0) in &map_0 {
2268                 match map_i.get(&key) {
2269                   None => {
2270                     resolve_err!(self, p.span, E0408,
2271                                  "variable `{}` from pattern #1 is \
2272                                   not bound in pattern #{}",
2273                                  key,
2274                                  i + 1);
2275                   }
2276                   Some(binding_i) => {
2277                     if binding_0.binding_mode != binding_i.binding_mode {
2278                         resolve_err!(self, binding_i.span, E0409,
2279                                      "variable `{}` is bound with different \
2280                                       mode in pattern #{} than in pattern #1",
2281                                      key,
2282                                      i + 1);
2283                     }
2284                   }
2285                 }
2286             }
2287
2288             for (&key, &binding) in &map_i {
2289                 if !map_0.contains_key(&key) {
2290                     resolve_err!(self, binding.span, E0410,
2291                                  "variable `{}` from pattern #{} is \
2292                                   not bound in pattern #1",
2293                                  key,
2294                                  i + 1);
2295                 }
2296             }
2297         }
2298     }
2299
2300     fn resolve_arm(&mut self, arm: &Arm) {
2301         self.value_ribs.push(Rib::new(NormalRibKind));
2302
2303         let mut bindings_list = HashMap::new();
2304         for pattern in &arm.pats {
2305             self.resolve_pattern(&**pattern, RefutableMode, &mut bindings_list);
2306         }
2307
2308         // This has to happen *after* we determine which
2309         // pat_idents are variants
2310         self.check_consistent_bindings(arm);
2311
2312         visit::walk_expr_opt(self, &arm.guard);
2313         self.visit_expr(&*arm.body);
2314
2315         self.value_ribs.pop();
2316     }
2317
2318     fn resolve_block(&mut self, block: &Block) {
2319         debug!("(resolving block) entering block");
2320         self.value_ribs.push(Rib::new(NormalRibKind));
2321
2322         // Move down in the graph, if there's an anonymous module rooted here.
2323         let orig_module = self.current_module.clone();
2324         match orig_module.anonymous_children.borrow().get(&block.id) {
2325             None => { /* Nothing to do. */ }
2326             Some(anonymous_module) => {
2327                 debug!("(resolving block) found anonymous module, moving \
2328                         down");
2329                 self.current_module = anonymous_module.clone();
2330             }
2331         }
2332
2333         // Check for imports appearing after non-item statements.
2334         let mut found_non_item = false;
2335         for statement in &block.stmts {
2336             if let ast::StmtDecl(ref declaration, _) = statement.node {
2337                 if let ast::DeclItem(ref i) = declaration.node {
2338                     match i.node {
2339                         ItemExternCrate(_) | ItemUse(_) if found_non_item => {
2340                             span_err!(self.session, i.span, E0154,
2341                                 "imports are not allowed after non-item statements");
2342                         }
2343                         _ => {}
2344                     }
2345                 } else {
2346                     found_non_item = true
2347                 }
2348             } else {
2349                 found_non_item = true;
2350             }
2351         }
2352
2353         // Descend into the block.
2354         visit::walk_block(self, block);
2355
2356         // Move back up.
2357         self.current_module = orig_module;
2358
2359         self.value_ribs.pop();
2360         debug!("(resolving block) leaving block");
2361     }
2362
2363     fn resolve_type(&mut self, ty: &Ty) {
2364         match ty.node {
2365             TyPath(ref maybe_qself, ref path) => {
2366                 let resolution =
2367                     match self.resolve_possibly_assoc_item(ty.id,
2368                                                            maybe_qself.as_ref(),
2369                                                            path,
2370                                                            TypeNS,
2371                                                            true) {
2372                         // `<T>::a::b::c` is resolved by typeck alone.
2373                         TypecheckRequired => {
2374                             // Resolve embedded types.
2375                             visit::walk_ty(self, ty);
2376                             return;
2377                         }
2378                         ResolveAttempt(resolution) => resolution,
2379                     };
2380
2381                 // This is a path in the type namespace. Walk through scopes
2382                 // looking for it.
2383                 match resolution {
2384                     Some(def) => {
2385                         // Write the result into the def map.
2386                         debug!("(resolving type) writing resolution for `{}` \
2387                                 (id {}) = {:?}",
2388                                path_names_to_string(path, 0),
2389                                ty.id, def);
2390                         self.record_def(ty.id, def);
2391                     }
2392                     None => {
2393                         // Keep reporting some errors even if they're ignored above.
2394                         self.resolve_path(ty.id, path, 0, TypeNS, true);
2395
2396                         let kind = if maybe_qself.is_some() {
2397                             "associated type"
2398                         } else {
2399                             "type name"
2400                         };
2401
2402                         let self_type_name = special_idents::type_self.name;
2403                         let is_invalid_self_type_name =
2404                             path.segments.len() > 0 &&
2405                             maybe_qself.is_none() &&
2406                             path.segments[0].identifier.name == self_type_name;
2407                         if is_invalid_self_type_name {
2408                             resolve_err!(self, ty.span, E0411,
2409                                          "use of `Self` outside of an impl or trait");
2410                         } else {
2411                             resolve_err!(self, ty.span, E0412,
2412                                          "use of undeclared {} `{}`",
2413                                          kind,
2414                                          path_names_to_string(path, 0));
2415                         }
2416                     }
2417                 }
2418             }
2419             _ => {}
2420         }
2421         // Resolve embedded types.
2422         visit::walk_ty(self, ty);
2423     }
2424
2425     fn resolve_pattern(&mut self,
2426                        pattern: &Pat,
2427                        mode: PatternBindingMode,
2428                        // Maps idents to the node ID for the (outermost)
2429                        // pattern that binds them
2430                        bindings_list: &mut HashMap<Name, NodeId>) {
2431         let pat_id = pattern.id;
2432         walk_pat(pattern, |pattern| {
2433             match pattern.node {
2434                 PatIdent(binding_mode, ref path1, _) => {
2435
2436                     // The meaning of pat_ident with no type parameters
2437                     // depends on whether an enum variant or unit-like struct
2438                     // with that name is in scope. The probing lookup has to
2439                     // be careful not to emit spurious errors. Only matching
2440                     // patterns (match) can match nullary variants or
2441                     // unit-like structs. For binding patterns (let), matching
2442                     // such a value is simply disallowed (since it's rarely
2443                     // what you want).
2444
2445                     let ident = path1.node;
2446                     let renamed = mtwt::resolve(ident);
2447
2448                     match self.resolve_bare_identifier_pattern(ident.name, pattern.span) {
2449                         FoundStructOrEnumVariant(def, lp)
2450                                 if mode == RefutableMode => {
2451                             debug!("(resolving pattern) resolving `{}` to \
2452                                     struct or enum variant",
2453                                    renamed);
2454
2455                             self.enforce_default_binding_mode(
2456                                 pattern,
2457                                 binding_mode,
2458                                 "an enum variant");
2459                             self.record_def(pattern.id, PathResolution {
2460                                 base_def: def,
2461                                 last_private: lp,
2462                                 depth: 0
2463                             });
2464                         }
2465                         FoundStructOrEnumVariant(..) => {
2466                             resolve_err!(self, pattern.span, E0413,
2467                                          "declaration of `{}` shadows an enum \
2468                                          variant or unit-like struct in \
2469                                          scope",
2470                                          renamed);
2471                         }
2472                         FoundConst(def, lp) if mode == RefutableMode => {
2473                             debug!("(resolving pattern) resolving `{}` to \
2474                                     constant",
2475                                    renamed);
2476
2477                             self.enforce_default_binding_mode(
2478                                 pattern,
2479                                 binding_mode,
2480                                 "a constant");
2481                             self.record_def(pattern.id, PathResolution {
2482                                 base_def: def,
2483                                 last_private: lp,
2484                                 depth: 0
2485                             });
2486                         }
2487                         FoundConst(..) => {
2488                             resolve_err!(self, pattern.span, E0414,
2489                                          "{}",
2490                                          "only irrefutable patterns \
2491                                           allowed here");
2492                         }
2493                         BareIdentifierPatternUnresolved => {
2494                             debug!("(resolving pattern) binding `{}`",
2495                                    renamed);
2496
2497                             let def = DefLocal(pattern.id);
2498
2499                             // Record the definition so that later passes
2500                             // will be able to distinguish variants from
2501                             // locals in patterns.
2502
2503                             self.record_def(pattern.id, PathResolution {
2504                                 base_def: def,
2505                                 last_private: LastMod(AllPublic),
2506                                 depth: 0
2507                             });
2508
2509                             // Add the binding to the local ribs, if it
2510                             // doesn't already exist in the bindings list. (We
2511                             // must not add it if it's in the bindings list
2512                             // because that breaks the assumptions later
2513                             // passes make about or-patterns.)
2514                             if !bindings_list.contains_key(&renamed) {
2515                                 let this = &mut *self;
2516                                 let last_rib = this.value_ribs.last_mut().unwrap();
2517                                 last_rib.bindings.insert(renamed, DlDef(def));
2518                                 bindings_list.insert(renamed, pat_id);
2519                             } else if mode == ArgumentIrrefutableMode &&
2520                                     bindings_list.contains_key(&renamed) {
2521                                 // Forbid duplicate bindings in the same
2522                                 // parameter list.
2523                                 resolve_err!(self, pattern.span, E0415,
2524                                              "identifier `{}` \
2525                                               is bound more \
2526                                               than once in \
2527                                               this parameter \
2528                                               list",
2529                                              token::get_ident(ident));
2530                             } else if bindings_list.get(&renamed) ==
2531                                     Some(&pat_id) {
2532                                 // Then this is a duplicate variable in the
2533                                 // same disjunction, which is an error.
2534                                 resolve_err!(self, pattern.span, E0416,
2535                                              "identifier `{}` is bound \
2536                                               more than once in the same \
2537                                               pattern",
2538                                              token::get_ident(ident));
2539                             }
2540                             // Else, not bound in the same pattern: do
2541                             // nothing.
2542                         }
2543                     }
2544                 }
2545
2546                 PatEnum(ref path, _) => {
2547                     // This must be an enum variant, struct or const.
2548                     let resolution =
2549                         match self.resolve_possibly_assoc_item(pat_id, None,
2550                                                                path, ValueNS,
2551                                                                false) {
2552                             // The below shouldn't happen because all
2553                             // qualified paths should be in PatQPath.
2554                             TypecheckRequired =>
2555                                 self.session.span_bug(
2556                                     path.span,
2557                                     "resolve_possibly_assoc_item claimed
2558                                      that a path in PatEnum requires typecheck
2559                                      to resolve, but qualified paths should be
2560                                      PatQPath"),
2561                             ResolveAttempt(resolution) => resolution,
2562                         };
2563                     if let Some(path_res) = resolution {
2564                         match path_res.base_def {
2565                             DefVariant(..) | DefStruct(..) | DefConst(..) => {
2566                                 self.record_def(pattern.id, path_res);
2567                             }
2568                             DefStatic(..) => {
2569                                 resolve_error(&ResolutionError::StaticVariableReference(&self, path.span),
2570                                               "static variables cannot be \
2571                                                referenced in a pattern, \
2572                                                use a `const` instead");
2573                             }
2574                             _ => {
2575                                 // If anything ends up here entirely resolved,
2576                                 // it's an error. If anything ends up here
2577                                 // partially resolved, that's OK, because it may
2578                                 // be a `T::CONST` that typeck will resolve.
2579                                 if path_res.depth == 0 {
2580                                     resolve_err!(self, path.span, E0418,
2581                                                  "`{}` is not an enum variant, struct or const",
2582                                                  token::get_ident(
2583                                                      path.segments.last().unwrap().identifier));
2584                                 } else {
2585                                     let const_name = path.segments.last().unwrap()
2586                                                          .identifier.name;
2587                                     let traits = self.get_traits_containing_item(const_name);
2588                                     self.trait_map.insert(pattern.id, traits);
2589                                     self.record_def(pattern.id, path_res);
2590                                 }
2591                             }
2592                         }
2593                     } else {
2594                         resolve_err!(self, path.span, E0419,
2595                                      "unresolved enum variant, struct or const `{}`",
2596                                      token::get_ident(path.segments.last().unwrap().identifier));
2597                     }
2598                     visit::walk_path(self, path);
2599                 }
2600
2601                 PatQPath(ref qself, ref path) => {
2602                     // Associated constants only.
2603                     let resolution =
2604                         match self.resolve_possibly_assoc_item(pat_id, Some(qself),
2605                                                                path, ValueNS,
2606                                                                false) {
2607                             TypecheckRequired => {
2608                                 // All `<T>::CONST` should end up here, and will
2609                                 // require use of the trait map to resolve
2610                                 // during typechecking.
2611                                 let const_name = path.segments.last().unwrap()
2612                                                      .identifier.name;
2613                                 let traits = self.get_traits_containing_item(const_name);
2614                                 self.trait_map.insert(pattern.id, traits);
2615                                 visit::walk_pat(self, pattern);
2616                                 return true;
2617                             }
2618                             ResolveAttempt(resolution) => resolution,
2619                         };
2620                     if let Some(path_res) = resolution {
2621                         match path_res.base_def {
2622                             // All `<T as Trait>::CONST` should end up here, and
2623                             // have the trait already selected.
2624                             DefAssociatedConst(..) => {
2625                                 self.record_def(pattern.id, path_res);
2626                             }
2627                             _ => {
2628                                 resolve_err!(self, path.span, E0420,
2629                                              "`{}` is not an associated const",
2630                                              token::get_ident(
2631                                                  path.segments.last().unwrap().identifier));
2632                             }
2633                         }
2634                     } else {
2635                         resolve_err!(self, path.span, E0421,
2636                                      "unresolved associated const `{}`",
2637                                      token::get_ident(path.segments.last().unwrap().identifier));
2638                     }
2639                     visit::walk_pat(self, pattern);
2640                 }
2641
2642                 PatStruct(ref path, _, _) => {
2643                     match self.resolve_path(pat_id, path, 0, TypeNS, false) {
2644                         Some(definition) => {
2645                             self.record_def(pattern.id, definition);
2646                         }
2647                         result => {
2648                             debug!("(resolving pattern) didn't find struct \
2649                                     def: {:?}", result);
2650                             resolve_error(&ResolutionError::DoesNotNameAStruct(self, path.span),
2651                                          &*format!("`{}` does not name a structure",
2652                                              path_names_to_string(path, 0)));
2653                         }
2654                     }
2655                     visit::walk_path(self, path);
2656                 }
2657
2658                 PatLit(_) | PatRange(..) => {
2659                     visit::walk_pat(self, pattern);
2660                 }
2661
2662                 _ => {
2663                     // Nothing to do.
2664                 }
2665             }
2666             true
2667         });
2668     }
2669
2670     fn resolve_bare_identifier_pattern(&mut self, name: Name, span: Span)
2671                                        -> BareIdentifierPatternResolution {
2672         let module = self.current_module.clone();
2673         match self.resolve_item_in_lexical_scope(module,
2674                                                  name,
2675                                                  ValueNS) {
2676             Success((target, _)) => {
2677                 debug!("(resolve bare identifier pattern) succeeded in \
2678                          finding {} at {:?}",
2679                         name,
2680                         target.bindings.value_def.borrow());
2681                 match *target.bindings.value_def.borrow() {
2682                     None => {
2683                         panic!("resolved name in the value namespace to a \
2684                               set of name bindings with no def?!");
2685                     }
2686                     Some(def) => {
2687                         // For the two success cases, this lookup can be
2688                         // considered as not having a private component because
2689                         // the lookup happened only within the current module.
2690                         match def.def {
2691                             def @ DefVariant(..) | def @ DefStruct(..) => {
2692                                 return FoundStructOrEnumVariant(def, LastMod(AllPublic));
2693                             }
2694                             def @ DefConst(..) | def @ DefAssociatedConst(..) => {
2695                                 return FoundConst(def, LastMod(AllPublic));
2696                             }
2697                             DefStatic(..) => {
2698                                 resolve_error(&ResolutionError::StaticVariableReference(self, span),
2699                                               "static variables cannot be \
2700                                                referenced in a pattern, \
2701                                                use a `const` instead");
2702                                 return BareIdentifierPatternUnresolved;
2703                             }
2704                             _ => {
2705                                 return BareIdentifierPatternUnresolved;
2706                             }
2707                         }
2708                     }
2709                 }
2710             }
2711
2712             Indeterminate => {
2713                 panic!("unexpected indeterminate result");
2714             }
2715             Failed(err) => {
2716                 match err {
2717                     Some((span, msg)) => {
2718                         resolve_error(&ResolutionError::FailedToResolve(self, span),
2719                                       &*format!("failed to resolve. {}",
2720                                             msg)
2721                                      );
2722                     }
2723                     None => ()
2724                 }
2725
2726                 debug!("(resolve bare identifier pattern) failed to find {}",
2727                         name);
2728                 return BareIdentifierPatternUnresolved;
2729             }
2730         }
2731     }
2732
2733     /// Handles paths that may refer to associated items
2734     fn resolve_possibly_assoc_item(&mut self,
2735                                    id: NodeId,
2736                                    maybe_qself: Option<&ast::QSelf>,
2737                                    path: &Path,
2738                                    namespace: Namespace,
2739                                    check_ribs: bool)
2740                                    -> AssocItemResolveResult
2741     {
2742         let max_assoc_types;
2743
2744         match maybe_qself {
2745             Some(qself) => {
2746                 if qself.position == 0 {
2747                     return TypecheckRequired;
2748                 }
2749                 max_assoc_types = path.segments.len() - qself.position;
2750                 // Make sure the trait is valid.
2751                 let _ = self.resolve_trait_reference(id, path, max_assoc_types);
2752             }
2753             None => {
2754                 max_assoc_types = path.segments.len();
2755             }
2756         }
2757
2758         let mut resolution = self.with_no_errors(|this| {
2759             this.resolve_path(id, path, 0, namespace, check_ribs)
2760         });
2761         for depth in 1..max_assoc_types {
2762             if resolution.is_some() {
2763                 break;
2764             }
2765             self.with_no_errors(|this| {
2766                 resolution = this.resolve_path(id, path, depth,
2767                                                TypeNS, true);
2768             });
2769         }
2770         if let Some(DefMod(_)) = resolution.map(|r| r.base_def) {
2771             // A module is not a valid type or value.
2772             resolution = None;
2773         }
2774         ResolveAttempt(resolution)
2775     }
2776
2777     /// If `check_ribs` is true, checks the local definitions first; i.e.
2778     /// doesn't skip straight to the containing module.
2779     /// Skips `path_depth` trailing segments, which is also reflected in the
2780     /// returned value. See `middle::def::PathResolution` for more info.
2781     fn resolve_path(&mut self,
2782                     id: NodeId,
2783                     path: &Path,
2784                     path_depth: usize,
2785                     namespace: Namespace,
2786                     check_ribs: bool) -> Option<PathResolution> {
2787         let span = path.span;
2788         let segments = &path.segments[..path.segments.len()-path_depth];
2789
2790         let mk_res = |(def, lp)| PathResolution::new(def, lp, path_depth);
2791
2792         if path.global {
2793             let def = self.resolve_crate_relative_path(span, segments, namespace);
2794             return def.map(mk_res);
2795         }
2796
2797         // Try to find a path to an item in a module.
2798         let unqualified_def =
2799                 self.resolve_identifier(segments.last().unwrap().identifier,
2800                                         namespace,
2801                                         check_ribs,
2802                                         span);
2803
2804         if segments.len() <= 1 {
2805             return unqualified_def.map(mk_res);
2806         }
2807
2808         let def = self.resolve_module_relative_path(span, segments, namespace);
2809         match (def, unqualified_def) {
2810             (Some((ref d, _)), Some((ref ud, _))) if *d == *ud => {
2811                 self.session
2812                     .add_lint(lint::builtin::UNUSED_QUALIFICATIONS,
2813                               id, span,
2814                               "unnecessary qualification".to_string());
2815             }
2816             _ => {}
2817         }
2818
2819         def.map(mk_res)
2820     }
2821
2822     // Resolve a single identifier.
2823     fn resolve_identifier(&mut self,
2824                           identifier: Ident,
2825                           namespace: Namespace,
2826                           check_ribs: bool,
2827                           span: Span)
2828                           -> Option<(Def, LastPrivate)> {
2829         // First, check to see whether the name is a primitive type.
2830         if namespace == TypeNS {
2831             if let Some(&prim_ty) = self.primitive_type_table
2832                                         .primitive_types
2833                                         .get(&identifier.name) {
2834                 return Some((DefPrimTy(prim_ty), LastMod(AllPublic)));
2835             }
2836         }
2837
2838         if check_ribs {
2839             if let Some(def) = self.resolve_identifier_in_local_ribs(identifier,
2840                                                                      namespace,
2841                                                                      span) {
2842                 return Some((def, LastMod(AllPublic)));
2843             }
2844         }
2845
2846         self.resolve_item_by_name_in_lexical_scope(identifier.name, namespace)
2847     }
2848
2849     // FIXME #4952: Merge me with resolve_name_in_module?
2850     fn resolve_definition_of_name_in_module(&mut self,
2851                                             containing_module: Rc<Module>,
2852                                             name: Name,
2853                                             namespace: Namespace)
2854                                             -> NameDefinition {
2855         // First, search children.
2856         build_reduced_graph::populate_module_if_necessary(self, &containing_module);
2857
2858         match containing_module.children.borrow().get(&name) {
2859             Some(child_name_bindings) => {
2860                 match child_name_bindings.def_for_namespace(namespace) {
2861                     Some(def) => {
2862                         // Found it. Stop the search here.
2863                         let p = child_name_bindings.defined_in_public_namespace(namespace);
2864                         let lp = if p {LastMod(AllPublic)} else {
2865                             LastMod(DependsOn(def.def_id()))
2866                         };
2867                         return ChildNameDefinition(def, lp);
2868                     }
2869                     None => {}
2870                 }
2871             }
2872             None => {}
2873         }
2874
2875         // Next, search import resolutions.
2876         match containing_module.import_resolutions.borrow().get(&name) {
2877             Some(import_resolution) if import_resolution.is_public => {
2878                 if let Some(target) = (*import_resolution).target_for_namespace(namespace) {
2879                     match target.bindings.def_for_namespace(namespace) {
2880                         Some(def) => {
2881                             // Found it.
2882                             let id = import_resolution.id(namespace);
2883                             // track imports and extern crates as well
2884                             self.used_imports.insert((id, namespace));
2885                             self.record_import_use(id, name);
2886                             match target.target_module.def_id.get() {
2887                                 Some(DefId{krate: kid, ..}) => {
2888                                     self.used_crates.insert(kid);
2889                                 },
2890                                 _ => {}
2891                             }
2892                             return ImportNameDefinition(def, LastMod(AllPublic));
2893                         }
2894                         None => {
2895                             // This can happen with external impls, due to
2896                             // the imperfect way we read the metadata.
2897                         }
2898                     }
2899                 }
2900             }
2901             Some(..) | None => {} // Continue.
2902         }
2903
2904         // Finally, search through external children.
2905         if namespace == TypeNS {
2906             if let Some(module) = containing_module.external_module_children.borrow()
2907                                                    .get(&name).cloned() {
2908                 if let Some(def_id) = module.def_id.get() {
2909                     // track used crates
2910                     self.used_crates.insert(def_id.krate);
2911                     let lp = if module.is_public {LastMod(AllPublic)} else {
2912                         LastMod(DependsOn(def_id))
2913                     };
2914                     return ChildNameDefinition(DefMod(def_id), lp);
2915                 }
2916             }
2917         }
2918
2919         return NoNameDefinition;
2920     }
2921
2922     // resolve a "module-relative" path, e.g. a::b::c
2923     fn resolve_module_relative_path(&mut self,
2924                                     span: Span,
2925                                     segments: &[ast::PathSegment],
2926                                     namespace: Namespace)
2927                                     -> Option<(Def, LastPrivate)> {
2928         let module_path = segments.init().iter()
2929                                          .map(|ps| ps.identifier.name)
2930                                          .collect::<Vec<_>>();
2931
2932         let containing_module;
2933         let last_private;
2934         let current_module = self.current_module.clone();
2935         match self.resolve_module_path(current_module,
2936                                        &module_path[..],
2937                                        UseLexicalScope,
2938                                        span,
2939                                        PathSearch) {
2940             Failed(err) => {
2941                 let (span, msg) = match err {
2942                     Some((span, msg)) => (span, msg),
2943                     None => {
2944                         let msg = format!("Use of undeclared type or module `{}`",
2945                                           names_to_string(&module_path));
2946                         (span, msg)
2947                     }
2948                 };
2949
2950                 resolve_error(&ResolutionError::FailedToResolve(self, span),
2951                               &*format!("failed to resolve. {}",
2952                                     msg)
2953                              );
2954                 return None;
2955             }
2956             Indeterminate => panic!("indeterminate unexpected"),
2957             Success((resulting_module, resulting_last_private)) => {
2958                 containing_module = resulting_module;
2959                 last_private = resulting_last_private;
2960             }
2961         }
2962
2963         let name = segments.last().unwrap().identifier.name;
2964         let def = match self.resolve_definition_of_name_in_module(containing_module.clone(),
2965                                                                   name,
2966                                                                   namespace) {
2967             NoNameDefinition => {
2968                 // We failed to resolve the name. Report an error.
2969                 return None;
2970             }
2971             ChildNameDefinition(def, lp) | ImportNameDefinition(def, lp) => {
2972                 (def, last_private.or(lp))
2973             }
2974         };
2975         if let Some(DefId{krate: kid, ..}) = containing_module.def_id.get() {
2976             self.used_crates.insert(kid);
2977         }
2978         return Some(def);
2979     }
2980
2981     /// Invariant: This must be called only during main resolution, not during
2982     /// import resolution.
2983     fn resolve_crate_relative_path(&mut self,
2984                                    span: Span,
2985                                    segments: &[ast::PathSegment],
2986                                    namespace: Namespace)
2987                                        -> Option<(Def, LastPrivate)> {
2988         let module_path = segments.init().iter()
2989                                          .map(|ps| ps.identifier.name)
2990                                          .collect::<Vec<_>>();
2991
2992         let root_module = self.graph_root.get_module();
2993
2994         let containing_module;
2995         let last_private;
2996         match self.resolve_module_path_from_root(root_module,
2997                                                  &module_path[..],
2998                                                  0,
2999                                                  span,
3000                                                  PathSearch,
3001                                                  LastMod(AllPublic)) {
3002             Failed(err) => {
3003                 let (span, msg) = match err {
3004                     Some((span, msg)) => (span, msg),
3005                     None => {
3006                         let msg = format!("Use of undeclared module `::{}`",
3007                                           names_to_string(&module_path[..]));
3008                         (span, msg)
3009                     }
3010                 };
3011
3012                 resolve_error(&ResolutionError::FailedToResolve(self, span),
3013                               &*format!("failed to resolve. {}",
3014                                     msg)
3015                              );
3016                 return None;
3017             }
3018
3019             Indeterminate => {
3020                 panic!("indeterminate unexpected");
3021             }
3022
3023             Success((resulting_module, resulting_last_private)) => {
3024                 containing_module = resulting_module;
3025                 last_private = resulting_last_private;
3026             }
3027         }
3028
3029         let name = segments.last().unwrap().identifier.name;
3030         match self.resolve_definition_of_name_in_module(containing_module,
3031                                                         name,
3032                                                         namespace) {
3033             NoNameDefinition => {
3034                 // We failed to resolve the name. Report an error.
3035                 return None;
3036             }
3037             ChildNameDefinition(def, lp) | ImportNameDefinition(def, lp) => {
3038                 return Some((def, last_private.or(lp)));
3039             }
3040         }
3041     }
3042
3043     fn resolve_identifier_in_local_ribs(&mut self,
3044                                         ident: Ident,
3045                                         namespace: Namespace,
3046                                         span: Span)
3047                                         -> Option<Def> {
3048         // Check the local set of ribs.
3049         let search_result = match namespace {
3050             ValueNS => {
3051                 let renamed = mtwt::resolve(ident);
3052                 self.search_ribs(&self.value_ribs, renamed, span)
3053             }
3054             TypeNS => {
3055                 let name = ident.name;
3056                 self.search_ribs(&self.type_ribs, name, span)
3057             }
3058         };
3059
3060         match search_result {
3061             Some(DlDef(def)) => {
3062                 debug!("(resolving path in local ribs) resolved `{}` to local: {:?}",
3063                        token::get_ident(ident),
3064                        def);
3065                 Some(def)
3066             }
3067             Some(DlField) | Some(DlImpl(_)) | None => {
3068                 None
3069             }
3070         }
3071     }
3072
3073     fn resolve_item_by_name_in_lexical_scope(&mut self,
3074                                              name: Name,
3075                                              namespace: Namespace)
3076                                             -> Option<(Def, LastPrivate)> {
3077         // Check the items.
3078         let module = self.current_module.clone();
3079         match self.resolve_item_in_lexical_scope(module,
3080                                                  name,
3081                                                  namespace) {
3082             Success((target, _)) => {
3083                 match (*target.bindings).def_for_namespace(namespace) {
3084                     None => {
3085                         // This can happen if we were looking for a type and
3086                         // found a module instead. Modules don't have defs.
3087                         debug!("(resolving item path by identifier in lexical \
3088                                  scope) failed to resolve {} after success...",
3089                                  name);
3090                         return None;
3091                     }
3092                     Some(def) => {
3093                         debug!("(resolving item path in lexical scope) \
3094                                 resolved `{}` to item",
3095                                name);
3096                         // This lookup is "all public" because it only searched
3097                         // for one identifier in the current module (couldn't
3098                         // have passed through reexports or anything like that.
3099                         return Some((def, LastMod(AllPublic)));
3100                     }
3101                 }
3102             }
3103             Indeterminate => {
3104                 panic!("unexpected indeterminate result");
3105             }
3106             Failed(err) => {
3107                 debug!("(resolving item path by identifier in lexical scope) \
3108                          failed to resolve {}", name);
3109
3110                 if let Some((span, msg)) = err {
3111                     resolve_error(&ResolutionError::FailedToResolve(self, span),
3112                                   &*format!("failed to resolve. {}",
3113                                         msg)
3114                                  )
3115                 }
3116
3117                 return None;
3118             }
3119         }
3120     }
3121
3122     fn with_no_errors<T, F>(&mut self, f: F) -> T where
3123         F: FnOnce(&mut Resolver) -> T,
3124     {
3125         self.emit_errors = false;
3126         let rs = f(self);
3127         self.emit_errors = true;
3128         rs
3129     }
3130
3131     fn find_fallback_in_self_type(&mut self, name: Name) -> FallbackSuggestion {
3132         fn extract_path_and_node_id(t: &Ty, allow: FallbackChecks)
3133                                                     -> Option<(Path, NodeId, FallbackChecks)> {
3134             match t.node {
3135                 TyPath(None, ref path) => Some((path.clone(), t.id, allow)),
3136                 TyPtr(ref mut_ty) => extract_path_and_node_id(&*mut_ty.ty, OnlyTraitAndStatics),
3137                 TyRptr(_, ref mut_ty) => extract_path_and_node_id(&*mut_ty.ty, allow),
3138                 // This doesn't handle the remaining `Ty` variants as they are not
3139                 // that commonly the self_type, it might be interesting to provide
3140                 // support for those in future.
3141                 _ => None,
3142             }
3143         }
3144
3145         fn get_module(this: &mut Resolver, span: Span, name_path: &[ast::Name])
3146                             -> Option<Rc<Module>> {
3147             let root = this.current_module.clone();
3148             let last_name = name_path.last().unwrap();
3149
3150             if name_path.len() == 1 {
3151                 match this.primitive_type_table.primitive_types.get(last_name) {
3152                     Some(_) => None,
3153                     None => {
3154                         match this.current_module.children.borrow().get(last_name) {
3155                             Some(child) => child.get_module_if_available(),
3156                             None => None
3157                         }
3158                     }
3159                 }
3160             } else {
3161                 match this.resolve_module_path(root,
3162                                                &name_path[..],
3163                                                UseLexicalScope,
3164                                                span,
3165                                                PathSearch) {
3166                     Success((module, _)) => Some(module),
3167                     _ => None
3168                 }
3169             }
3170         }
3171
3172         fn is_static_method(this: &Resolver, did: DefId) -> bool {
3173             if did.krate == ast::LOCAL_CRATE {
3174                 let sig = match this.ast_map.get(did.node) {
3175                     ast_map::NodeTraitItem(trait_item) => match trait_item.node {
3176                         ast::MethodTraitItem(ref sig, _) => sig,
3177                         _ => return false
3178                     },
3179                     ast_map::NodeImplItem(impl_item) => match impl_item.node {
3180                         ast::MethodImplItem(ref sig, _) => sig,
3181                         _ => return false
3182                     },
3183                     _ => return false
3184                 };
3185                 sig.explicit_self.node == ast::SelfStatic
3186             } else {
3187                 csearch::is_static_method(&this.session.cstore, did)
3188             }
3189         }
3190
3191         let (path, node_id, allowed) = match self.current_self_type {
3192             Some(ref ty) => match extract_path_and_node_id(ty, Everything) {
3193                 Some(x) => x,
3194                 None => return NoSuggestion,
3195             },
3196             None => return NoSuggestion,
3197         };
3198
3199         if allowed == Everything {
3200             // Look for a field with the same name in the current self_type.
3201             match self.def_map.borrow().get(&node_id).map(|d| d.full_def()) {
3202                 Some(DefTy(did, _)) |
3203                 Some(DefStruct(did)) |
3204                 Some(DefVariant(_, did, _)) => match self.structs.get(&did) {
3205                     None => {}
3206                     Some(fields) => {
3207                         if fields.iter().any(|&field_name| name == field_name) {
3208                             return Field;
3209                         }
3210                     }
3211                 },
3212                 _ => {} // Self type didn't resolve properly
3213             }
3214         }
3215
3216         let name_path = path.segments.iter().map(|seg| seg.identifier.name).collect::<Vec<_>>();
3217
3218         // Look for a method in the current self type's impl module.
3219         if let Some(module) = get_module(self, path.span, &name_path) {
3220             if let Some(binding) = module.children.borrow().get(&name) {
3221                 if let Some(DefMethod(did, _)) = binding.def_for_namespace(ValueNS) {
3222                     if is_static_method(self, did) {
3223                         return StaticMethod(path_names_to_string(&path, 0))
3224                     }
3225                     if self.current_trait_ref.is_some() {
3226                         return TraitItem;
3227                     } else if allowed == Everything {
3228                         return Method;
3229                     }
3230                 }
3231             }
3232         }
3233
3234         // Look for a method in the current trait.
3235         if let Some((trait_did, ref trait_ref)) = self.current_trait_ref {
3236             if let Some(&did) = self.trait_item_map.get(&(name, trait_did)) {
3237                 if is_static_method(self, did) {
3238                     return TraitMethod(path_names_to_string(&trait_ref.path, 0));
3239                 } else {
3240                     return TraitItem;
3241                 }
3242             }
3243         }
3244
3245         NoSuggestion
3246     }
3247
3248     fn find_best_match_for_name(&mut self, name: &str) -> Option<String> {
3249         let mut maybes: Vec<token::InternedString> = Vec::new();
3250         let mut values: Vec<usize> = Vec::new();
3251
3252         for rib in self.value_ribs.iter().rev() {
3253             for (&k, _) in &rib.bindings {
3254                 maybes.push(token::get_name(k));
3255                 values.push(usize::MAX);
3256             }
3257         }
3258
3259         let mut smallest = 0;
3260         for (i, other) in maybes.iter().enumerate() {
3261             values[i] = lev_distance(name, &other);
3262
3263             if values[i] <= values[smallest] {
3264                 smallest = i;
3265             }
3266         }
3267
3268         // As a loose rule to avoid obviously incorrect suggestions, clamp the
3269         // maximum edit distance we will accept for a suggestion to one third of
3270         // the typo'd name's length.
3271         let max_distance = std::cmp::max(name.len(), 3) / 3;
3272
3273         if !values.is_empty() &&
3274             values[smallest] <= max_distance &&
3275             name != &maybes[smallest][..] {
3276
3277             Some(maybes[smallest].to_string())
3278
3279         } else {
3280             None
3281         }
3282     }
3283
3284     fn resolve_expr(&mut self, expr: &Expr) {
3285         // First, record candidate traits for this expression if it could
3286         // result in the invocation of a method call.
3287
3288         self.record_candidate_traits_for_expr_if_necessary(expr);
3289
3290         // Next, resolve the node.
3291         match expr.node {
3292             ExprPath(ref maybe_qself, ref path) => {
3293                 let resolution =
3294                     match self.resolve_possibly_assoc_item(expr.id,
3295                                                            maybe_qself.as_ref(),
3296                                                            path,
3297                                                            ValueNS,
3298                                                            true) {
3299                         // `<T>::a::b::c` is resolved by typeck alone.
3300                         TypecheckRequired => {
3301                             let method_name = path.segments.last().unwrap().identifier.name;
3302                             let traits = self.get_traits_containing_item(method_name);
3303                             self.trait_map.insert(expr.id, traits);
3304                             visit::walk_expr(self, expr);
3305                             return;
3306                         }
3307                         ResolveAttempt(resolution) => resolution,
3308                     };
3309
3310                 // This is a local path in the value namespace. Walk through
3311                 // scopes looking for it.
3312                 if let Some(path_res) = resolution {
3313                     // Check if struct variant
3314                     if let DefVariant(_, _, true) = path_res.base_def {
3315                         let path_name = path_names_to_string(path, 0);
3316
3317                         resolve_error(&ResolutionError::StructVariantUsedAsFunction(self, expr.span),
3318                                       &*format!("`{}` is a struct variant name, but \
3319                                            this expression \
3320                                            uses it like a function name",
3321                                           path_name));
3322
3323                         let msg = format!("did you mean to write: \
3324                                            `{} {{ /* fields */ }}`?",
3325                                           path_name);
3326                         if self.emit_errors {
3327                             self.session.fileline_help(expr.span, &msg);
3328                         } else {
3329                             self.session.span_help(expr.span, &msg);
3330                         }
3331                     } else {
3332                         // Write the result into the def map.
3333                         debug!("(resolving expr) resolved `{}`",
3334                                path_names_to_string(path, 0));
3335
3336                         // Partial resolutions will need the set of traits in scope,
3337                         // so they can be completed during typeck.
3338                         if path_res.depth != 0 {
3339                             let method_name = path.segments.last().unwrap().identifier.name;
3340                             let traits = self.get_traits_containing_item(method_name);
3341                             self.trait_map.insert(expr.id, traits);
3342                         }
3343
3344                         self.record_def(expr.id, path_res);
3345                     }
3346                 } else {
3347                     // Be helpful if the name refers to a struct
3348                     // (The pattern matching def_tys where the id is in self.structs
3349                     // matches on regular structs while excluding tuple- and enum-like
3350                     // structs, which wouldn't result in this error.)
3351                     let path_name = path_names_to_string(path, 0);
3352                     let type_res = self.with_no_errors(|this| {
3353                         this.resolve_path(expr.id, path, 0, TypeNS, false)
3354                     });
3355                     match type_res.map(|r| r.base_def) {
3356                         Some(DefTy(struct_id, _))
3357                             if self.structs.contains_key(&struct_id) => {
3358                                 resolve_error(&ResolutionError::StructVariantUsedAsFunction(self, expr.span),
3359                                               &*format!("`{}` is a struct variant name, but \
3360                                                   this expression \
3361                                                   uses it like a function name",
3362                                                  path_name));
3363
3364                                 let msg = format!("did you mean to write: \
3365                                                      `{} {{ /* fields */ }}`?",
3366                                                     path_name);
3367                                 if self.emit_errors {
3368                                     self.session.fileline_help(expr.span, &msg);
3369                                 } else {
3370                                     self.session.span_help(expr.span, &msg);
3371                                 }
3372                             }
3373                         _ => {
3374                             // Keep reporting some errors even if they're ignored above.
3375                             self.resolve_path(expr.id, path, 0, ValueNS, true);
3376
3377                             let mut method_scope = false;
3378                             self.value_ribs.iter().rev().all(|rib| {
3379                                 method_scope = match rib.kind {
3380                                     MethodRibKind => true,
3381                                     ItemRibKind | ConstantItemRibKind => false,
3382                                     _ => return true, // Keep advancing
3383                                 };
3384                                 false // Stop advancing
3385                             });
3386
3387                             if method_scope &&
3388                                &token::get_name(special_names::self_)[..] == path_name {
3389                                     resolve_err!(self, expr.span, E0424,
3390                                                  "{}",
3391                                                  "`self` is not available \
3392                                                   in a static method. Maybe a \
3393                                                   `self` argument is missing?");
3394                             } else {
3395                                 let last_name = path.segments.last().unwrap().identifier.name;
3396                                 let mut msg = match self.find_fallback_in_self_type(last_name) {
3397                                     NoSuggestion => {
3398                                         // limit search to 5 to reduce the number
3399                                         // of stupid suggestions
3400                                         self.find_best_match_for_name(&path_name)
3401                                                             .map_or("".to_string(),
3402                                                                     |x| format!("`{}`", x))
3403                                     }
3404                                     Field => format!("`self.{}`", path_name),
3405                                     Method |
3406                                     TraitItem =>
3407                                         format!("to call `self.{}`", path_name),
3408                                     TraitMethod(path_str) |
3409                                     StaticMethod(path_str) =>
3410                                         format!("to call `{}::{}`", path_str, path_name)
3411                                 };
3412
3413                                 if !msg.is_empty() {
3414                                     msg = format!(". Did you mean {}?", msg)
3415                                 }
3416
3417                                 resolve_err!(self, expr.span, E0425,
3418                                              "unresolved name `{}`{}",
3419                                              path_name,
3420                                              msg);
3421                             }
3422                         }
3423                     }
3424                 }
3425
3426                 visit::walk_expr(self, expr);
3427             }
3428
3429             ExprStruct(ref path, _, _) => {
3430                 // Resolve the path to the structure it goes to. We don't
3431                 // check to ensure that the path is actually a structure; that
3432                 // is checked later during typeck.
3433                 match self.resolve_path(expr.id, path, 0, TypeNS, false) {
3434                     Some(definition) => self.record_def(expr.id, definition),
3435                     None => {
3436                         debug!("(resolving expression) didn't find struct def",);
3437
3438                         resolve_error(&ResolutionError::DoesNotNameAStruct(self, path.span),
3439                                      &*format!("`{}` does not name a structure",
3440                                          path_names_to_string(path, 0)));
3441                     }
3442                 }
3443
3444                 visit::walk_expr(self, expr);
3445             }
3446
3447             ExprLoop(_, Some(label)) | ExprWhile(_, _, Some(label)) => {
3448                 self.with_label_rib(|this| {
3449                     let def_like = DlDef(DefLabel(expr.id));
3450
3451                     {
3452                         let rib = this.label_ribs.last_mut().unwrap();
3453                         let renamed = mtwt::resolve(label);
3454                         rib.bindings.insert(renamed, def_like);
3455                     }
3456
3457                     visit::walk_expr(this, expr);
3458                 })
3459             }
3460
3461             ExprBreak(Some(label)) | ExprAgain(Some(label)) => {
3462                 let renamed = mtwt::resolve(label);
3463                 match self.search_label(renamed) {
3464                     None => {
3465                         resolve_err!(self, expr.span, E0426,
3466                                      "use of undeclared label `{}`",
3467                                      token::get_ident(label))
3468                     }
3469                     Some(DlDef(def @ DefLabel(_))) => {
3470                         // Since this def is a label, it is never read.
3471                         self.record_def(expr.id, PathResolution {
3472                             base_def: def,
3473                             last_private: LastMod(AllPublic),
3474                             depth: 0
3475                         })
3476                     }
3477                     Some(_) => {
3478                         self.session.span_bug(expr.span,
3479                                               "label wasn't mapped to a \
3480                                                label def!")
3481                     }
3482                 }
3483             }
3484
3485             _ => {
3486                 visit::walk_expr(self, expr);
3487             }
3488         }
3489     }
3490
3491     fn record_candidate_traits_for_expr_if_necessary(&mut self, expr: &Expr) {
3492         match expr.node {
3493             ExprField(_, ident) => {
3494                 // FIXME(#6890): Even though you can't treat a method like a
3495                 // field, we need to add any trait methods we find that match
3496                 // the field name so that we can do some nice error reporting
3497                 // later on in typeck.
3498                 let traits = self.get_traits_containing_item(ident.node.name);
3499                 self.trait_map.insert(expr.id, traits);
3500             }
3501             ExprMethodCall(ident, _, _) => {
3502                 debug!("(recording candidate traits for expr) recording \
3503                         traits for {}",
3504                        expr.id);
3505                 let traits = self.get_traits_containing_item(ident.node.name);
3506                 self.trait_map.insert(expr.id, traits);
3507             }
3508             _ => {
3509                 // Nothing to do.
3510             }
3511         }
3512     }
3513
3514     fn get_traits_containing_item(&mut self, name: Name) -> Vec<DefId> {
3515         debug!("(getting traits containing item) looking for '{}'",
3516                name);
3517
3518         fn add_trait_info(found_traits: &mut Vec<DefId>,
3519                           trait_def_id: DefId,
3520                           name: Name) {
3521             debug!("(adding trait info) found trait {}:{} for method '{}'",
3522                 trait_def_id.krate,
3523                 trait_def_id.node,
3524                 name);
3525             found_traits.push(trait_def_id);
3526         }
3527
3528         let mut found_traits = Vec::new();
3529         let mut search_module = self.current_module.clone();
3530         loop {
3531             // Look for the current trait.
3532             match self.current_trait_ref {
3533                 Some((trait_def_id, _)) => {
3534                     if self.trait_item_map.contains_key(&(name, trait_def_id)) {
3535                         add_trait_info(&mut found_traits, trait_def_id, name);
3536                     }
3537                 }
3538                 None => {} // Nothing to do.
3539             }
3540
3541             // Look for trait children.
3542             build_reduced_graph::populate_module_if_necessary(self, &search_module);
3543
3544             {
3545                 for (_, child_names) in search_module.children.borrow().iter() {
3546                     let def = match child_names.def_for_namespace(TypeNS) {
3547                         Some(def) => def,
3548                         None => continue
3549                     };
3550                     let trait_def_id = match def {
3551                         DefTrait(trait_def_id) => trait_def_id,
3552                         _ => continue,
3553                     };
3554                     if self.trait_item_map.contains_key(&(name, trait_def_id)) {
3555                         add_trait_info(&mut found_traits, trait_def_id, name);
3556                     }
3557                 }
3558             }
3559
3560             // Look for imports.
3561             for (_, import) in search_module.import_resolutions.borrow().iter() {
3562                 let target = match import.target_for_namespace(TypeNS) {
3563                     None => continue,
3564                     Some(target) => target,
3565                 };
3566                 let did = match target.bindings.def_for_namespace(TypeNS) {
3567                     Some(DefTrait(trait_def_id)) => trait_def_id,
3568                     Some(..) | None => continue,
3569                 };
3570                 if self.trait_item_map.contains_key(&(name, did)) {
3571                     add_trait_info(&mut found_traits, did, name);
3572                     let id = import.type_id;
3573                     self.used_imports.insert((id, TypeNS));
3574                     let trait_name = self.get_trait_name(did);
3575                     self.record_import_use(id, trait_name);
3576                     if let Some(DefId{krate: kid, ..}) = target.target_module.def_id.get() {
3577                         self.used_crates.insert(kid);
3578                     }
3579                 }
3580             }
3581
3582             match search_module.parent_link.clone() {
3583                 NoParentLink | ModuleParentLink(..) => break,
3584                 BlockParentLink(parent_module, _) => {
3585                     search_module = parent_module.upgrade().unwrap();
3586                 }
3587             }
3588         }
3589
3590         found_traits
3591     }
3592
3593     fn record_def(&mut self, node_id: NodeId, resolution: PathResolution) {
3594         debug!("(recording def) recording {:?} for {}", resolution, node_id);
3595         assert!(match resolution.last_private {LastImport{..} => false, _ => true},
3596                 "Import should only be used for `use` directives");
3597
3598         if let Some(prev_res) = self.def_map.borrow_mut().insert(node_id, resolution) {
3599             let span = self.ast_map.opt_span(node_id).unwrap_or(codemap::DUMMY_SP);
3600             self.session.span_bug(span, &format!("path resolved multiple times \
3601                                                   ({:?} before, {:?} now)",
3602                                                  prev_res, resolution));
3603         }
3604     }
3605
3606     fn enforce_default_binding_mode(&mut self,
3607                                         pat: &Pat,
3608                                         pat_binding_mode: BindingMode,
3609                                         descr: &str) {
3610         match pat_binding_mode {
3611             BindByValue(_) => {}
3612             BindByRef(..) => {
3613                 resolve_err!(self, pat.span, E0427,
3614                              "cannot use `ref` binding mode with {}",
3615                              descr);
3616             }
3617         }
3618     }
3619
3620     //
3621     // Diagnostics
3622     //
3623     // Diagnostics are not particularly efficient, because they're rarely
3624     // hit.
3625     //
3626
3627     #[allow(dead_code)]   // useful for debugging
3628     fn dump_module(&mut self, module_: Rc<Module>) {
3629         debug!("Dump of module `{}`:", module_to_string(&*module_));
3630
3631         debug!("Children:");
3632         build_reduced_graph::populate_module_if_necessary(self, &module_);
3633         for (&name, _) in module_.children.borrow().iter() {
3634             debug!("* {}", name);
3635         }
3636
3637         debug!("Import resolutions:");
3638         let import_resolutions = module_.import_resolutions.borrow();
3639         for (&name, import_resolution) in import_resolutions.iter() {
3640             let value_repr;
3641             match import_resolution.target_for_namespace(ValueNS) {
3642                 None => { value_repr = "".to_string(); }
3643                 Some(_) => {
3644                     value_repr = " value:?".to_string();
3645                     // FIXME #4954
3646                 }
3647             }
3648
3649             let type_repr;
3650             match import_resolution.target_for_namespace(TypeNS) {
3651                 None => { type_repr = "".to_string(); }
3652                 Some(_) => {
3653                     type_repr = " type:?".to_string();
3654                     // FIXME #4954
3655                 }
3656             }
3657
3658             debug!("* {}:{}{}", name, value_repr, type_repr);
3659         }
3660     }
3661 }
3662
3663
3664 fn names_to_string(names: &[Name]) -> String {
3665     let mut first = true;
3666     let mut result = String::new();
3667     for name in names {
3668         if first {
3669             first = false
3670         } else {
3671             result.push_str("::")
3672         }
3673         result.push_str(&token::get_name(*name));
3674     };
3675     result
3676 }
3677
3678 fn path_names_to_string(path: &Path, depth: usize) -> String {
3679     let names: Vec<ast::Name> = path.segments[..path.segments.len()-depth]
3680                                     .iter()
3681                                     .map(|seg| seg.identifier.name)
3682                                     .collect();
3683     names_to_string(&names[..])
3684 }
3685
3686 /// A somewhat inefficient routine to obtain the name of a module.
3687 fn module_to_string(module: &Module) -> String {
3688     let mut names = Vec::new();
3689
3690     fn collect_mod(names: &mut Vec<ast::Name>, module: &Module) {
3691         match module.parent_link {
3692             NoParentLink => {}
3693             ModuleParentLink(ref module, name) => {
3694                 names.push(name);
3695                 collect_mod(names, &*module.upgrade().unwrap());
3696             }
3697             BlockParentLink(ref module, _) => {
3698                 // danger, shouldn't be ident?
3699                 names.push(special_idents::opaque.name);
3700                 collect_mod(names, &*module.upgrade().unwrap());
3701             }
3702         }
3703     }
3704     collect_mod(&mut names, module);
3705
3706     if names.is_empty() {
3707         return "???".to_string();
3708     }
3709     names_to_string(&names.into_iter().rev().collect::<Vec<ast::Name>>())
3710 }
3711
3712
3713 pub struct CrateMap {
3714     pub def_map: DefMap,
3715     pub freevars: RefCell<FreevarMap>,
3716     pub export_map: ExportMap,
3717     pub trait_map: TraitMap,
3718     pub external_exports: ExternalExports,
3719     pub glob_map: Option<GlobMap>
3720 }
3721
3722 #[derive(PartialEq,Copy, Clone)]
3723 pub enum MakeGlobMap {
3724     Yes,
3725     No
3726 }
3727
3728 /// Entry point to crate resolution.
3729 pub fn resolve_crate<'a, 'tcx>(session: &'a Session,
3730                                ast_map: &'a ast_map::Map<'tcx>,
3731                                make_glob_map: MakeGlobMap)
3732                                -> CrateMap {
3733     let krate = ast_map.krate();
3734     let mut resolver = Resolver::new(session, ast_map, krate.span, make_glob_map);
3735
3736     build_reduced_graph::build_reduced_graph(&mut resolver, krate);
3737     session.abort_if_errors();
3738
3739     resolve_imports::resolve_imports(&mut resolver);
3740     session.abort_if_errors();
3741
3742     record_exports::record(&mut resolver);
3743     session.abort_if_errors();
3744
3745     resolver.resolve_crate(krate);
3746     session.abort_if_errors();
3747
3748     check_unused::check_crate(&mut resolver, krate);
3749
3750     CrateMap {
3751         def_map: resolver.def_map,
3752         freevars: resolver.freevars,
3753         export_map: resolver.export_map,
3754         trait_map: resolver.trait_map,
3755         external_exports: resolver.external_exports,
3756         glob_map: if resolver.make_glob_map {
3757                         Some(resolver.glob_map)
3758                     } else {
3759                         None
3760                     },
3761     }
3762 }
3763
3764 __build_diagnostic_array! { librustc_resolve, DIAGNOSTICS }