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