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