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