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