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