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