]> git.lizzy.rs Git - rust.git/blob - src/librustc_resolve/lib.rs
track, for each upvar, its index in list of upvars
[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                 if let hir::ViewPathSimple(ident, _) = view_path.node {
2216                     match self.def_map.borrow().get(&item.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
2225             ItemExternCrate(_) => {
2226                 // do nothing, these are just around to be encoded
2227             }
2228         }
2229     }
2230
2231     fn with_type_parameter_rib<F>(&mut self, type_parameters: TypeParameters, f: F) where
2232         F: FnOnce(&mut Resolver),
2233     {
2234         match type_parameters {
2235             HasTypeParameters(generics, space, rib_kind) => {
2236                 let mut function_type_rib = Rib::new(rib_kind);
2237                 let mut seen_bindings = HashSet::new();
2238                 for (index, type_parameter) in generics.ty_params.iter().enumerate() {
2239                     let name = type_parameter.ident.name;
2240                     debug!("with_type_parameter_rib: {}", type_parameter.id);
2241
2242                     if seen_bindings.contains(&name) {
2243                         resolve_error(self,
2244                                       type_parameter.span,
2245                                       ResolutionError::NameAlreadyUsedInTypeParameterList(
2246                                         name)
2247                         );
2248                     }
2249                     seen_bindings.insert(name);
2250
2251                     // plain insert (no renaming)
2252                     function_type_rib.bindings.insert(name,
2253                         DlDef(DefTyParam(space,
2254                                          index as u32,
2255                                          DefId::local(type_parameter.id),
2256                                          name)));
2257                 }
2258                 self.type_ribs.push(function_type_rib);
2259             }
2260
2261             NoTypeParameters => {
2262                 // Nothing to do.
2263             }
2264         }
2265
2266         f(self);
2267
2268         match type_parameters {
2269             HasTypeParameters(..) => { if !self.resolved { self.type_ribs.pop(); } }
2270             NoTypeParameters => { }
2271         }
2272     }
2273
2274     fn with_label_rib<F>(&mut self, f: F) where
2275         F: FnOnce(&mut Resolver),
2276     {
2277         self.label_ribs.push(Rib::new(NormalRibKind));
2278         f(self);
2279         if !self.resolved {
2280             self.label_ribs.pop();
2281         }
2282     }
2283
2284     fn with_constant_rib<F>(&mut self, f: F) where
2285         F: FnOnce(&mut Resolver),
2286     {
2287         self.value_ribs.push(Rib::new(ConstantItemRibKind));
2288         self.type_ribs.push(Rib::new(ConstantItemRibKind));
2289         f(self);
2290         if !self.resolved {
2291             self.type_ribs.pop();
2292             self.value_ribs.pop();
2293         }
2294     }
2295
2296     fn resolve_function(&mut self,
2297                         rib_kind: RibKind,
2298                         declaration: &FnDecl,
2299                         block: &Block) {
2300         // Create a value rib for the function.
2301         self.value_ribs.push(Rib::new(rib_kind));
2302
2303         // Create a label rib for the function.
2304         self.label_ribs.push(Rib::new(rib_kind));
2305
2306         // Add each argument to the rib.
2307         let mut bindings_list = HashMap::new();
2308         for argument in &declaration.inputs {
2309             self.resolve_pattern(&*argument.pat,
2310                                  ArgumentIrrefutableMode,
2311                                  &mut bindings_list);
2312
2313             self.visit_ty(&*argument.ty);
2314
2315             debug!("(resolving function) recorded argument");
2316         }
2317         visit::walk_fn_ret_ty(self, &declaration.output);
2318
2319         // Resolve the function body.
2320         self.visit_block(&*block);
2321
2322         debug!("(resolving function) leaving function");
2323
2324         if !self.resolved {
2325             self.label_ribs.pop();
2326             self.value_ribs.pop();
2327         }
2328     }
2329
2330     fn resolve_trait_reference(&mut self,
2331                                id: NodeId,
2332                                trait_path: &Path,
2333                                path_depth: usize)
2334                                -> Result<PathResolution, ()> {
2335         if let Some(path_res) = self.resolve_path(id, trait_path, path_depth, TypeNS, true) {
2336             if let DefTrait(_) = path_res.base_def {
2337                 debug!("(resolving trait) found trait def: {:?}", path_res);
2338                 Ok(path_res)
2339             } else {
2340                 resolve_error(self,
2341                               trait_path.span,
2342                               ResolutionError::IsNotATrait(&*path_names_to_string(trait_path,
2343                                                                                    path_depth))
2344                              );
2345
2346                 // If it's a typedef, give a note
2347                 if let DefTy(..) = path_res.base_def {
2348                     self.session.span_note(trait_path.span,
2349                                            "`type` aliases cannot be used for traits");
2350                 }
2351                 Err(())
2352             }
2353         } else {
2354             resolve_error(self,
2355                           trait_path.span,
2356                           ResolutionError::UndeclaredTraitName(
2357                             &*path_names_to_string(trait_path, path_depth))
2358                          );
2359             Err(())
2360         }
2361     }
2362
2363     fn resolve_generics(&mut self, generics: &Generics) {
2364         for type_parameter in generics.ty_params.iter() {
2365             self.check_if_primitive_type_name(type_parameter.ident.name, type_parameter.span);
2366         }
2367         for predicate in &generics.where_clause.predicates {
2368             match predicate {
2369                 &hir::WherePredicate::BoundPredicate(_) |
2370                 &hir::WherePredicate::RegionPredicate(_) => {}
2371                 &hir::WherePredicate::EqPredicate(ref eq_pred) => {
2372                     let path_res = self.resolve_path(eq_pred.id, &eq_pred.path, 0, TypeNS, true);
2373                     if let Some(PathResolution { base_def: DefTyParam(..), .. }) = path_res {
2374                         self.record_def(eq_pred.id, path_res.unwrap());
2375                     } else {
2376                         resolve_error(self,
2377                                       eq_pred.span,
2378                                       ResolutionError::UndeclaredAssociatedType);
2379                     }
2380                 }
2381             }
2382         }
2383         visit::walk_generics(self, generics);
2384     }
2385
2386     fn with_current_self_type<T, F>(&mut self, self_type: &Ty, f: F) -> T
2387         where F: FnOnce(&mut Resolver) -> T
2388     {
2389         // Handle nested impls (inside fn bodies)
2390         let previous_value = replace(&mut self.current_self_type, Some(self_type.clone()));
2391         let result = f(self);
2392         self.current_self_type = previous_value;
2393         result
2394     }
2395
2396     fn with_optional_trait_ref<T, F>(&mut self,
2397                                      opt_trait_ref: Option<&TraitRef>,
2398                                      f: F)
2399                                      -> T
2400         where F: FnOnce(&mut Resolver, Option<DefId>) -> T
2401     {
2402         let mut new_val = None;
2403         let mut new_id = None;
2404         if let Some(trait_ref) = opt_trait_ref {
2405             if let Ok(path_res) = self.resolve_trait_reference(trait_ref.ref_id,
2406                                                                &trait_ref.path, 0) {
2407                 assert!(path_res.depth == 0);
2408                 self.record_def(trait_ref.ref_id, path_res);
2409                 new_val = Some((path_res.base_def.def_id(), trait_ref.clone()));
2410                 new_id = Some(path_res.base_def.def_id());
2411             }
2412             visit::walk_trait_ref(self, trait_ref);
2413         }
2414         let original_trait_ref = replace(&mut self.current_trait_ref, new_val);
2415         let result = f(self, new_id);
2416         self.current_trait_ref = original_trait_ref;
2417         result
2418     }
2419
2420     fn with_self_rib<F>(&mut self, self_def: Def, f: F)
2421         where F: FnOnce(&mut Resolver)
2422     {
2423         let mut self_type_rib = Rib::new(NormalRibKind);
2424
2425         // plain insert (no renaming, types are not currently hygienic....)
2426         let name = special_names::type_self;
2427         self_type_rib.bindings.insert(name, DlDef(self_def));
2428         self.type_ribs.push(self_type_rib);
2429         f(self);
2430         if !self.resolved {
2431             self.type_ribs.pop();
2432         }
2433     }
2434
2435     fn resolve_implementation(&mut self,
2436                               generics: &Generics,
2437                               opt_trait_reference: &Option<TraitRef>,
2438                               self_type: &Ty,
2439                               item_id: NodeId,
2440                               impl_items: &[P<ImplItem>]) {
2441         // If applicable, create a rib for the type parameters.
2442         self.with_type_parameter_rib(HasTypeParameters(generics,
2443                                                        TypeSpace,
2444                                                        ItemRibKind),
2445                                      |this| {
2446             // Resolve the type parameters.
2447             this.visit_generics(generics);
2448
2449             // Resolve the trait reference, if necessary.
2450             this.with_optional_trait_ref(opt_trait_reference.as_ref(), |this, trait_id| {
2451                 // Resolve the self type.
2452                 this.visit_ty(self_type);
2453
2454                 this.with_self_rib(DefSelfTy(trait_id, Some((item_id, self_type.id))), |this| {
2455                     this.with_current_self_type(self_type, |this| {
2456                         for impl_item in impl_items {
2457                             match impl_item.node {
2458                                 ConstImplItem(..) => {
2459                                     // If this is a trait impl, ensure the const
2460                                     // exists in trait
2461                                     this.check_trait_item(impl_item.ident.name,
2462                                                           impl_item.span,
2463                                         |n, s| ResolutionError::ConstNotMemberOfTrait(n, s));
2464                                     this.with_constant_rib(|this| {
2465                                         visit::walk_impl_item(this, impl_item);
2466                                     });
2467                                 }
2468                                 MethodImplItem(ref sig, _) => {
2469                                     // If this is a trait impl, ensure the method
2470                                     // exists in trait
2471                                     this.check_trait_item(impl_item.ident.name,
2472                                                           impl_item.span,
2473                                         |n, s| ResolutionError::MethodNotMemberOfTrait(n, s));
2474
2475                                     // We also need a new scope for the method-
2476                                     // specific type parameters.
2477                                     let type_parameters =
2478                                         HasTypeParameters(&sig.generics,
2479                                                           FnSpace,
2480                                                           MethodRibKind);
2481                                     this.with_type_parameter_rib(type_parameters, |this| {
2482                                         visit::walk_impl_item(this, impl_item);
2483                                     });
2484                                 }
2485                                 TypeImplItem(ref ty) => {
2486                                     // If this is a trait impl, ensure the type
2487                                     // exists in trait
2488                                     this.check_trait_item(impl_item.ident.name,
2489                                                           impl_item.span,
2490                                         |n, s| ResolutionError::TypeNotMemberOfTrait(n, s));
2491
2492                                     this.visit_ty(ty);
2493                                 }
2494                             }
2495                         }
2496                     });
2497                 });
2498             });
2499         });
2500     }
2501
2502     fn check_trait_item<F>(&self, name: Name, span: Span, err: F)
2503         where F: FnOnce(Name, &str) -> ResolutionError {
2504         // If there is a TraitRef in scope for an impl, then the method must be in the trait.
2505         if let Some((did, ref trait_ref)) = self.current_trait_ref {
2506             if !self.trait_item_map.contains_key(&(name, did)) {
2507                 let path_str = path_names_to_string(&trait_ref.path, 0);
2508                 resolve_error(self,
2509                               span,
2510                               err(name, &*path_str));
2511             }
2512         }
2513     }
2514
2515     fn resolve_local(&mut self, local: &Local) {
2516         // Resolve the type.
2517         visit::walk_ty_opt(self, &local.ty);
2518
2519         // Resolve the initializer.
2520         visit::walk_expr_opt(self, &local.init);
2521
2522         // Resolve the pattern.
2523         self.resolve_pattern(&*local.pat,
2524                              LocalIrrefutableMode,
2525                              &mut HashMap::new());
2526     }
2527
2528     // build a map from pattern identifiers to binding-info's.
2529     // this is done hygienically. This could arise for a macro
2530     // that expands into an or-pattern where one 'x' was from the
2531     // user and one 'x' came from the macro.
2532     fn binding_mode_map(&mut self, pat: &Pat) -> BindingMap {
2533         let mut result = HashMap::new();
2534         pat_bindings(&self.def_map, pat, |binding_mode, _id, sp, path1| {
2535             let name = mtwt::resolve(path1.node);
2536             result.insert(name, BindingInfo {
2537                 span: sp,
2538                 binding_mode: binding_mode
2539             });
2540         });
2541         return result;
2542     }
2543
2544     // check that all of the arms in an or-pattern have exactly the
2545     // same set of bindings, with the same binding modes for each.
2546     fn check_consistent_bindings(&mut self, arm: &Arm) {
2547         if arm.pats.is_empty() {
2548             return
2549         }
2550         let map_0 = self.binding_mode_map(&*arm.pats[0]);
2551         for (i, p) in arm.pats.iter().enumerate() {
2552             let map_i = self.binding_mode_map(&**p);
2553
2554             for (&key, &binding_0) in &map_0 {
2555                 match map_i.get(&key) {
2556                   None => {
2557                     resolve_error(self,
2558                                   p.span,
2559                                   ResolutionError::VariableNotBoundInPattern(key,
2560                                                                               i + 1));
2561                   }
2562                   Some(binding_i) => {
2563                     if binding_0.binding_mode != binding_i.binding_mode {
2564                         resolve_error(self,
2565                                       binding_i.span,
2566                                       ResolutionError::VariableBoundWithDifferentMode(key,
2567                                                                                        i + 1)
2568                                      );
2569                     }
2570                   }
2571                 }
2572             }
2573
2574             for (&key, &binding) in &map_i {
2575                 if !map_0.contains_key(&key) {
2576                     resolve_error(self,
2577                                   binding.span,
2578                                   ResolutionError::VariableNotBoundInParentPattern(key,
2579                                                                                     i + 1));
2580                 }
2581             }
2582         }
2583     }
2584
2585     fn resolve_arm(&mut self, arm: &Arm) {
2586         self.value_ribs.push(Rib::new(NormalRibKind));
2587
2588         let mut bindings_list = HashMap::new();
2589         for pattern in &arm.pats {
2590             self.resolve_pattern(&**pattern, RefutableMode, &mut bindings_list);
2591         }
2592
2593         // This has to happen *after* we determine which
2594         // pat_idents are variants
2595         self.check_consistent_bindings(arm);
2596
2597         visit::walk_expr_opt(self, &arm.guard);
2598         self.visit_expr(&*arm.body);
2599
2600         if !self.resolved {
2601             self.value_ribs.pop();
2602         }
2603     }
2604
2605     fn resolve_block(&mut self, block: &Block) {
2606         debug!("(resolving block) entering block");
2607         self.value_ribs.push(Rib::new(NormalRibKind));
2608
2609         // Move down in the graph, if there's an anonymous module rooted here.
2610         let orig_module = self.current_module.clone();
2611         match orig_module.anonymous_children.borrow().get(&block.id) {
2612             None => { /* Nothing to do. */ }
2613             Some(anonymous_module) => {
2614                 debug!("(resolving block) found anonymous module, moving \
2615                         down");
2616                 self.current_module = anonymous_module.clone();
2617             }
2618         }
2619
2620         // Check for imports appearing after non-item statements.
2621         let mut found_non_item = false;
2622         for statement in &block.stmts {
2623             if let hir::StmtDecl(ref declaration, _) = statement.node {
2624                 if let hir::DeclItem(ref i) = declaration.node {
2625                     match i.node {
2626                         ItemExternCrate(_) | ItemUse(_) if found_non_item => {
2627                             span_err!(self.session, i.span, E0154,
2628                                 "imports are not allowed after non-item statements");
2629                         }
2630                         _ => {}
2631                     }
2632                 } else {
2633                     found_non_item = true
2634                 }
2635             } else {
2636                 found_non_item = true;
2637             }
2638         }
2639
2640         // Descend into the block.
2641         visit::walk_block(self, block);
2642
2643         // Move back up.
2644         if !self.resolved {
2645             self.current_module = orig_module;
2646             self.value_ribs.pop();
2647         }
2648         debug!("(resolving block) leaving block");
2649     }
2650
2651     fn resolve_type(&mut self, ty: &Ty) {
2652         match ty.node {
2653             TyPath(ref maybe_qself, ref path) => {
2654                 let resolution =
2655                     match self.resolve_possibly_assoc_item(ty.id,
2656                                                            maybe_qself.as_ref(),
2657                                                            path,
2658                                                            TypeNS,
2659                                                            true) {
2660                         // `<T>::a::b::c` is resolved by typeck alone.
2661                         TypecheckRequired => {
2662                             // Resolve embedded types.
2663                             visit::walk_ty(self, ty);
2664                             return;
2665                         }
2666                         ResolveAttempt(resolution) => resolution,
2667                     };
2668
2669                 // This is a path in the type namespace. Walk through scopes
2670                 // looking for it.
2671                 match resolution {
2672                     Some(def) => {
2673                         // Write the result into the def map.
2674                         debug!("(resolving type) writing resolution for `{}` \
2675                                 (id {}) = {:?}",
2676                                path_names_to_string(path, 0),
2677                                ty.id, def);
2678                         self.record_def(ty.id, def);
2679                     }
2680                     None => {
2681                         // Keep reporting some errors even if they're ignored above.
2682                         self.resolve_path(ty.id, path, 0, TypeNS, true);
2683
2684                         let kind = if maybe_qself.is_some() {
2685                             "associated type"
2686                         } else {
2687                             "type name"
2688                         };
2689
2690                         let self_type_name = special_idents::type_self.name;
2691                         let is_invalid_self_type_name =
2692                             path.segments.len() > 0 &&
2693                             maybe_qself.is_none() &&
2694                             path.segments[0].identifier.name == self_type_name;
2695                         if is_invalid_self_type_name {
2696                             resolve_error(self,
2697                                           ty.span,
2698                                           ResolutionError::SelfUsedOutsideImplOrTrait);
2699                         } else {
2700                             resolve_error(self,
2701                                           ty.span,
2702                                           ResolutionError::UseOfUndeclared(
2703                                                                     kind,
2704                                                                     &*path_names_to_string(path,
2705                                                                                            0))
2706                                          );
2707                         }
2708                     }
2709                 }
2710             }
2711             _ => {}
2712         }
2713         // Resolve embedded types.
2714         visit::walk_ty(self, ty);
2715     }
2716
2717     fn resolve_pattern(&mut self,
2718                        pattern: &Pat,
2719                        mode: PatternBindingMode,
2720                        // Maps idents to the node ID for the (outermost)
2721                        // pattern that binds them
2722                        bindings_list: &mut HashMap<Name, NodeId>) {
2723         let pat_id = pattern.id;
2724         walk_pat(pattern, |pattern| {
2725             match pattern.node {
2726                 PatIdent(binding_mode, ref path1, ref at_rhs) => {
2727                     // The meaning of PatIdent with no type parameters
2728                     // depends on whether an enum variant or unit-like struct
2729                     // with that name is in scope. The probing lookup has to
2730                     // be careful not to emit spurious errors. Only matching
2731                     // patterns (match) can match nullary variants or
2732                     // unit-like structs. For binding patterns (let
2733                     // and the LHS of @-patterns), matching such a value is
2734                     // simply disallowed (since it's rarely what you want).
2735                     let const_ok = mode == RefutableMode && at_rhs.is_none();
2736
2737                     let ident = path1.node;
2738                     let renamed = mtwt::resolve(ident);
2739
2740                     match self.resolve_bare_identifier_pattern(ident.name, pattern.span) {
2741                         FoundStructOrEnumVariant(def, lp) if const_ok => {
2742                             debug!("(resolving pattern) resolving `{}` to \
2743                                     struct or enum variant",
2744                                    renamed);
2745
2746                             self.enforce_default_binding_mode(
2747                                 pattern,
2748                                 binding_mode,
2749                                 "an enum variant");
2750                             self.record_def(pattern.id, PathResolution {
2751                                 base_def: def,
2752                                 last_private: lp,
2753                                 depth: 0
2754                             });
2755                         }
2756                         FoundStructOrEnumVariant(..) => {
2757                             resolve_error(
2758                                 self,
2759                                 pattern.span,
2760                                 ResolutionError::DeclarationShadowsEnumVariantOrUnitLikeStruct(
2761                                     renamed)
2762                             );
2763                         }
2764                         FoundConst(def, lp) if const_ok => {
2765                             debug!("(resolving pattern) resolving `{}` to \
2766                                     constant",
2767                                    renamed);
2768
2769                             self.enforce_default_binding_mode(
2770                                 pattern,
2771                                 binding_mode,
2772                                 "a constant");
2773                             self.record_def(pattern.id, PathResolution {
2774                                 base_def: def,
2775                                 last_private: lp,
2776                                 depth: 0
2777                             });
2778                         }
2779                         FoundConst(..) => {
2780                             resolve_error(
2781                                 self,
2782                                 pattern.span,
2783                                 ResolutionError::OnlyIrrefutablePatternsAllowedHere
2784                             );
2785                         }
2786                         BareIdentifierPatternUnresolved => {
2787                             debug!("(resolving pattern) binding `{}`",
2788                                    renamed);
2789
2790                             let def = DefLocal(pattern.id);
2791
2792                             // Record the definition so that later passes
2793                             // will be able to distinguish variants from
2794                             // locals in patterns.
2795
2796                             self.record_def(pattern.id, PathResolution {
2797                                 base_def: def,
2798                                 last_private: LastMod(AllPublic),
2799                                 depth: 0
2800                             });
2801
2802                             // Add the binding to the local ribs, if it
2803                             // doesn't already exist in the bindings list. (We
2804                             // must not add it if it's in the bindings list
2805                             // because that breaks the assumptions later
2806                             // passes make about or-patterns.)
2807                             if !bindings_list.contains_key(&renamed) {
2808                                 let this = &mut *self;
2809                                 let last_rib = this.value_ribs.last_mut().unwrap();
2810                                 last_rib.bindings.insert(renamed, DlDef(def));
2811                                 bindings_list.insert(renamed, pat_id);
2812                             } else if mode == ArgumentIrrefutableMode &&
2813                                     bindings_list.contains_key(&renamed) {
2814                                 // Forbid duplicate bindings in the same
2815                                 // parameter list.
2816                                 resolve_error(
2817                                     self,
2818                                     pattern.span,
2819                                     ResolutionError::IdentifierBoundMoreThanOnceInParameterList(
2820                                         &ident.name.as_str())
2821                                 );
2822                             } else if bindings_list.get(&renamed) ==
2823                                     Some(&pat_id) {
2824                                 // Then this is a duplicate variable in the
2825                                 // same disjunction, which is an error.
2826                                 resolve_error(
2827                                     self,
2828                                     pattern.span,
2829                                     ResolutionError::IdentifierBoundMoreThanOnceInSamePattern(
2830                                         &ident.name.as_str())
2831                                 );
2832                             }
2833                             // Else, not bound in the same pattern: do
2834                             // nothing.
2835                         }
2836                     }
2837                 }
2838
2839                 PatEnum(ref path, _) => {
2840                     // This must be an enum variant, struct or const.
2841                     let resolution =
2842                         match self.resolve_possibly_assoc_item(pat_id, None,
2843                                                                path, ValueNS,
2844                                                                false) {
2845                             // The below shouldn't happen because all
2846                             // qualified paths should be in PatQPath.
2847                             TypecheckRequired =>
2848                                 self.session.span_bug(
2849                                     path.span,
2850                                     "resolve_possibly_assoc_item claimed
2851                                      that a path in PatEnum requires typecheck
2852                                      to resolve, but qualified paths should be
2853                                      PatQPath"),
2854                             ResolveAttempt(resolution) => resolution,
2855                         };
2856                     if let Some(path_res) = resolution {
2857                         match path_res.base_def {
2858                             DefVariant(..) | DefStruct(..) | DefConst(..) => {
2859                                 self.record_def(pattern.id, path_res);
2860                             }
2861                             DefStatic(..) => {
2862                                 resolve_error(&self,
2863                                               path.span,
2864                                               ResolutionError::StaticVariableReference);
2865                             }
2866                             _ => {
2867                                 // If anything ends up here entirely resolved,
2868                                 // it's an error. If anything ends up here
2869                                 // partially resolved, that's OK, because it may
2870                                 // be a `T::CONST` that typeck will resolve.
2871                                 if path_res.depth == 0 {
2872                                     resolve_error(
2873                                         self,
2874                                         path.span,
2875                                         ResolutionError::NotAnEnumVariantStructOrConst(
2876                                             &path.segments
2877                                                  .last()
2878                                                  .unwrap()
2879                                                  .identifier
2880                                                  .name
2881                                                  .as_str())
2882                                     );
2883                                 } else {
2884                                     let const_name = path.segments.last().unwrap()
2885                                                          .identifier.name;
2886                                     let traits = self.get_traits_containing_item(const_name);
2887                                     self.trait_map.insert(pattern.id, traits);
2888                                     self.record_def(pattern.id, path_res);
2889                                 }
2890                             }
2891                         }
2892                     } else {
2893                         resolve_error(
2894                             self,
2895                             path.span,
2896                             ResolutionError::UnresolvedEnumVariantStructOrConst(
2897                                 &path.segments.last().unwrap().identifier.name.as_str())
2898                         );
2899                     }
2900                     visit::walk_path(self, path);
2901                 }
2902
2903                 PatQPath(ref qself, ref path) => {
2904                     // Associated constants only.
2905                     let resolution =
2906                         match self.resolve_possibly_assoc_item(pat_id, Some(qself),
2907                                                                path, ValueNS,
2908                                                                false) {
2909                             TypecheckRequired => {
2910                                 // All `<T>::CONST` should end up here, and will
2911                                 // require use of the trait map to resolve
2912                                 // during typechecking.
2913                                 let const_name = path.segments.last().unwrap()
2914                                                      .identifier.name;
2915                                 let traits = self.get_traits_containing_item(const_name);
2916                                 self.trait_map.insert(pattern.id, traits);
2917                                 visit::walk_pat(self, pattern);
2918                                 return true;
2919                             }
2920                             ResolveAttempt(resolution) => resolution,
2921                         };
2922                     if let Some(path_res) = resolution {
2923                         match path_res.base_def {
2924                             // All `<T as Trait>::CONST` should end up here, and
2925                             // have the trait already selected.
2926                             DefAssociatedConst(..) => {
2927                                 self.record_def(pattern.id, path_res);
2928                             }
2929                             _ => {
2930                                 resolve_error(
2931                                     self,
2932                                     path.span,
2933                                     ResolutionError::NotAnAssociatedConst(
2934                                         &path.segments.last().unwrap().identifier.name.as_str()
2935                                     )
2936                                 );
2937                             }
2938                         }
2939                     } else {
2940                         resolve_error(
2941                             self,
2942                             path.span,
2943                             ResolutionError::UnresolvedAssociatedConst(
2944                                 &path.segments.last().unwrap().identifier.name.as_str()
2945                             )
2946                         );
2947                     }
2948                     visit::walk_pat(self, pattern);
2949                 }
2950
2951                 PatStruct(ref path, _, _) => {
2952                     match self.resolve_path(pat_id, path, 0, TypeNS, false) {
2953                         Some(definition) => {
2954                             self.record_def(pattern.id, definition);
2955                         }
2956                         result => {
2957                             debug!("(resolving pattern) didn't find struct \
2958                                     def: {:?}", result);
2959                             resolve_error(
2960                                 self,
2961                                 path.span,
2962                                 ResolutionError::DoesNotNameAStruct(
2963                                     &*path_names_to_string(path, 0))
2964                             );
2965                         }
2966                     }
2967                     visit::walk_path(self, path);
2968                 }
2969
2970                 PatLit(_) | PatRange(..) => {
2971                     visit::walk_pat(self, pattern);
2972                 }
2973
2974                 _ => {
2975                     // Nothing to do.
2976                 }
2977             }
2978             true
2979         });
2980     }
2981
2982     fn resolve_bare_identifier_pattern(&mut self, name: Name, span: Span)
2983                                        -> BareIdentifierPatternResolution {
2984         let module = self.current_module.clone();
2985         match self.resolve_item_in_lexical_scope(module,
2986                                                  name,
2987                                                  ValueNS) {
2988             Success((target, _)) => {
2989                 debug!("(resolve bare identifier pattern) succeeded in \
2990                          finding {} at {:?}",
2991                         name,
2992                         target.bindings.value_def.borrow());
2993                 match *target.bindings.value_def.borrow() {
2994                     None => {
2995                         panic!("resolved name in the value namespace to a \
2996                               set of name bindings with no def?!");
2997                     }
2998                     Some(def) => {
2999                         // For the two success cases, this lookup can be
3000                         // considered as not having a private component because
3001                         // the lookup happened only within the current module.
3002                         match def.def {
3003                             def @ DefVariant(..) | def @ DefStruct(..) => {
3004                                 return FoundStructOrEnumVariant(def, LastMod(AllPublic));
3005                             }
3006                             def @ DefConst(..) | def @ DefAssociatedConst(..) => {
3007                                 return FoundConst(def, LastMod(AllPublic));
3008                             }
3009                             DefStatic(..) => {
3010                                 resolve_error(self,
3011                                               span,
3012                                               ResolutionError::StaticVariableReference);
3013                                 return BareIdentifierPatternUnresolved;
3014                             }
3015                             _ => {
3016                                 return BareIdentifierPatternUnresolved;
3017                             }
3018                         }
3019                     }
3020                 }
3021             }
3022
3023             Indeterminate => {
3024                 panic!("unexpected indeterminate result");
3025             }
3026             Failed(err) => {
3027                 match err {
3028                     Some((span, msg)) => {
3029                         resolve_error(self, span, ResolutionError::FailedToResolve(&*msg));
3030                     }
3031                     None => ()
3032                 }
3033
3034                 debug!("(resolve bare identifier pattern) failed to find {}",
3035                         name);
3036                 return BareIdentifierPatternUnresolved;
3037             }
3038         }
3039     }
3040
3041     /// Handles paths that may refer to associated items
3042     fn resolve_possibly_assoc_item(&mut self,
3043                                    id: NodeId,
3044                                    maybe_qself: Option<&hir::QSelf>,
3045                                    path: &Path,
3046                                    namespace: Namespace,
3047                                    check_ribs: bool)
3048                                    -> AssocItemResolveResult
3049     {
3050         let max_assoc_types;
3051
3052         match maybe_qself {
3053             Some(qself) => {
3054                 if qself.position == 0 {
3055                     return TypecheckRequired;
3056                 }
3057                 max_assoc_types = path.segments.len() - qself.position;
3058                 // Make sure the trait is valid.
3059                 let _ = self.resolve_trait_reference(id, path, max_assoc_types);
3060             }
3061             None => {
3062                 max_assoc_types = path.segments.len();
3063             }
3064         }
3065
3066         let mut resolution = self.with_no_errors(|this| {
3067             this.resolve_path(id, path, 0, namespace, check_ribs)
3068         });
3069         for depth in 1..max_assoc_types {
3070             if resolution.is_some() {
3071                 break;
3072             }
3073             self.with_no_errors(|this| {
3074                 resolution = this.resolve_path(id, path, depth,
3075                                                TypeNS, true);
3076             });
3077         }
3078         if let Some(DefMod(_)) = resolution.map(|r| r.base_def) {
3079             // A module is not a valid type or value.
3080             resolution = None;
3081         }
3082         ResolveAttempt(resolution)
3083     }
3084
3085     /// If `check_ribs` is true, checks the local definitions first; i.e.
3086     /// doesn't skip straight to the containing module.
3087     /// Skips `path_depth` trailing segments, which is also reflected in the
3088     /// returned value. See `middle::def::PathResolution` for more info.
3089     pub fn resolve_path(&mut self,
3090                         id: NodeId,
3091                         path: &Path,
3092                         path_depth: usize,
3093                         namespace: Namespace,
3094                         check_ribs: bool) -> Option<PathResolution> {
3095         let span = path.span;
3096         let segments = &path.segments[..path.segments.len()-path_depth];
3097
3098         let mk_res = |(def, lp)| PathResolution::new(def, lp, path_depth);
3099
3100         if path.global {
3101             let def = self.resolve_crate_relative_path(span, segments, namespace);
3102             return def.map(mk_res);
3103         }
3104
3105         // Try to find a path to an item in a module.
3106         let unqualified_def =
3107                 self.resolve_identifier(segments.last().unwrap().identifier,
3108                                         namespace,
3109                                         check_ribs,
3110                                         span);
3111
3112         if segments.len() <= 1 {
3113             return unqualified_def.map(mk_res);
3114         }
3115
3116         let def = self.resolve_module_relative_path(span, segments, namespace);
3117         match (def, unqualified_def) {
3118             (Some((ref d, _)), Some((ref ud, _))) if *d == *ud => {
3119                 self.session
3120                     .add_lint(lint::builtin::UNUSED_QUALIFICATIONS,
3121                               id, span,
3122                               "unnecessary qualification".to_string());
3123             }
3124             _ => {}
3125         }
3126
3127         def.map(mk_res)
3128     }
3129
3130     // Resolve a single identifier.
3131     fn resolve_identifier(&mut self,
3132                           identifier: Ident,
3133                           namespace: Namespace,
3134                           check_ribs: bool,
3135                           span: Span)
3136                           -> Option<(Def, LastPrivate)> {
3137         // First, check to see whether the name is a primitive type.
3138         if namespace == TypeNS {
3139             if let Some(&prim_ty) = self.primitive_type_table
3140                                         .primitive_types
3141                                         .get(&identifier.name) {
3142                 return Some((DefPrimTy(prim_ty), LastMod(AllPublic)));
3143             }
3144         }
3145
3146         if check_ribs {
3147             if let Some(def) = self.resolve_identifier_in_local_ribs(identifier,
3148                                                                      namespace,
3149                                                                      span) {
3150                 return Some((def, LastMod(AllPublic)));
3151             }
3152         }
3153
3154         self.resolve_item_by_name_in_lexical_scope(identifier.name, namespace)
3155     }
3156
3157     // FIXME #4952: Merge me with resolve_name_in_module?
3158     fn resolve_definition_of_name_in_module(&mut self,
3159                                             containing_module: Rc<Module>,
3160                                             name: Name,
3161                                             namespace: Namespace)
3162                                             -> NameDefinition {
3163         // First, search children.
3164         build_reduced_graph::populate_module_if_necessary(self, &containing_module);
3165
3166         match containing_module.children.borrow().get(&name) {
3167             Some(child_name_bindings) => {
3168                 match child_name_bindings.def_for_namespace(namespace) {
3169                     Some(def) => {
3170                         // Found it. Stop the search here.
3171                         let p = child_name_bindings.defined_in_public_namespace(namespace);
3172                         let lp = if p {LastMod(AllPublic)} else {
3173                             LastMod(DependsOn(def.def_id()))
3174                         };
3175                         return ChildNameDefinition(def, lp);
3176                     }
3177                     None => {}
3178                 }
3179             }
3180             None => {}
3181         }
3182
3183         // Next, search import resolutions.
3184         match containing_module.import_resolutions.borrow().get(&name) {
3185             Some(import_resolution) if import_resolution.is_public => {
3186                 if let Some(target) = (*import_resolution).target_for_namespace(namespace) {
3187                     match target.bindings.def_for_namespace(namespace) {
3188                         Some(def) => {
3189                             // Found it.
3190                             let id = import_resolution.id(namespace);
3191                             // track imports and extern crates as well
3192                             self.used_imports.insert((id, namespace));
3193                             self.record_import_use(id, name);
3194                             match target.target_module.def_id.get() {
3195                                 Some(DefId{krate: kid, ..}) => {
3196                                     self.used_crates.insert(kid);
3197                                 },
3198                                 _ => {}
3199                             }
3200                             return ImportNameDefinition(def, LastMod(AllPublic));
3201                         }
3202                         None => {
3203                             // This can happen with external impls, due to
3204                             // the imperfect way we read the metadata.
3205                         }
3206                     }
3207                 }
3208             }
3209             Some(..) | None => {} // Continue.
3210         }
3211
3212         // Finally, search through external children.
3213         if namespace == TypeNS {
3214             if let Some(module) = containing_module.external_module_children.borrow()
3215                                                    .get(&name).cloned() {
3216                 if let Some(def_id) = module.def_id.get() {
3217                     // track used crates
3218                     self.used_crates.insert(def_id.krate);
3219                     let lp = if module.is_public {LastMod(AllPublic)} else {
3220                         LastMod(DependsOn(def_id))
3221                     };
3222                     return ChildNameDefinition(DefMod(def_id), lp);
3223                 }
3224             }
3225         }
3226
3227         return NoNameDefinition;
3228     }
3229
3230     // resolve a "module-relative" path, e.g. a::b::c
3231     fn resolve_module_relative_path(&mut self,
3232                                     span: Span,
3233                                     segments: &[hir::PathSegment],
3234                                     namespace: Namespace)
3235                                     -> Option<(Def, LastPrivate)> {
3236         let module_path = segments.split_last().unwrap().1.iter()
3237                                          .map(|ps| ps.identifier.name)
3238                                          .collect::<Vec<_>>();
3239
3240         let containing_module;
3241         let last_private;
3242         let current_module = self.current_module.clone();
3243         match self.resolve_module_path(current_module,
3244                                        &module_path[..],
3245                                        UseLexicalScope,
3246                                        span,
3247                                        PathSearch) {
3248             Failed(err) => {
3249                 let (span, msg) = match err {
3250                     Some((span, msg)) => (span, msg),
3251                     None => {
3252                         let msg = format!("Use of undeclared type or module `{}`",
3253                                           names_to_string(&module_path));
3254                         (span, msg)
3255                     }
3256                 };
3257
3258                 resolve_error(self, span, ResolutionError::FailedToResolve(&*msg));
3259                 return None;
3260             }
3261             Indeterminate => panic!("indeterminate unexpected"),
3262             Success((resulting_module, resulting_last_private)) => {
3263                 containing_module = resulting_module;
3264                 last_private = resulting_last_private;
3265             }
3266         }
3267
3268         let name = segments.last().unwrap().identifier.name;
3269         let def = match self.resolve_definition_of_name_in_module(containing_module.clone(),
3270                                                                   name,
3271                                                                   namespace) {
3272             NoNameDefinition => {
3273                 // We failed to resolve the name. Report an error.
3274                 return None;
3275             }
3276             ChildNameDefinition(def, lp) | ImportNameDefinition(def, lp) => {
3277                 (def, last_private.or(lp))
3278             }
3279         };
3280         if let Some(DefId{krate: kid, ..}) = containing_module.def_id.get() {
3281             self.used_crates.insert(kid);
3282         }
3283         return Some(def);
3284     }
3285
3286     /// Invariant: This must be called only during main resolution, not during
3287     /// import resolution.
3288     fn resolve_crate_relative_path(&mut self,
3289                                    span: Span,
3290                                    segments: &[hir::PathSegment],
3291                                    namespace: Namespace)
3292                                        -> Option<(Def, LastPrivate)> {
3293         let module_path = segments.split_last().unwrap().1.iter()
3294                                          .map(|ps| ps.identifier.name)
3295                                          .collect::<Vec<_>>();
3296
3297         let root_module = self.graph_root.get_module();
3298
3299         let containing_module;
3300         let last_private;
3301         match self.resolve_module_path_from_root(root_module,
3302                                                  &module_path[..],
3303                                                  0,
3304                                                  span,
3305                                                  PathSearch,
3306                                                  LastMod(AllPublic)) {
3307             Failed(err) => {
3308                 let (span, msg) = match err {
3309                     Some((span, msg)) => (span, msg),
3310                     None => {
3311                         let msg = format!("Use of undeclared module `::{}`",
3312                                           names_to_string(&module_path[..]));
3313                         (span, msg)
3314                     }
3315                 };
3316
3317                 resolve_error(self, span, ResolutionError::FailedToResolve(&*msg));
3318                 return None;
3319             }
3320
3321             Indeterminate => {
3322                 panic!("indeterminate unexpected");
3323             }
3324
3325             Success((resulting_module, resulting_last_private)) => {
3326                 containing_module = resulting_module;
3327                 last_private = resulting_last_private;
3328             }
3329         }
3330
3331         let name = segments.last().unwrap().identifier.name;
3332         match self.resolve_definition_of_name_in_module(containing_module,
3333                                                         name,
3334                                                         namespace) {
3335             NoNameDefinition => {
3336                 // We failed to resolve the name. Report an error.
3337                 return None;
3338             }
3339             ChildNameDefinition(def, lp) | ImportNameDefinition(def, lp) => {
3340                 return Some((def, last_private.or(lp)));
3341             }
3342         }
3343     }
3344
3345     fn resolve_identifier_in_local_ribs(&mut self,
3346                                         ident: Ident,
3347                                         namespace: Namespace,
3348                                         span: Span)
3349                                         -> Option<Def> {
3350         // Check the local set of ribs.
3351         let search_result = match namespace {
3352             ValueNS => {
3353                 let renamed = mtwt::resolve(ident);
3354                 self.search_ribs(&self.value_ribs, renamed, span)
3355             }
3356             TypeNS => {
3357                 let name = ident.name;
3358                 self.search_ribs(&self.type_ribs, name, span)
3359             }
3360         };
3361
3362         match search_result {
3363             Some(DlDef(def)) => {
3364                 debug!("(resolving path in local ribs) resolved `{}` to local: {:?}",
3365                        ident,
3366                        def);
3367                 Some(def)
3368             }
3369             Some(DlField) | Some(DlImpl(_)) | None => {
3370                 None
3371             }
3372         }
3373     }
3374
3375     fn resolve_item_by_name_in_lexical_scope(&mut self,
3376                                              name: Name,
3377                                              namespace: Namespace)
3378                                             -> Option<(Def, LastPrivate)> {
3379         // Check the items.
3380         let module = self.current_module.clone();
3381         match self.resolve_item_in_lexical_scope(module,
3382                                                  name,
3383                                                  namespace) {
3384             Success((target, _)) => {
3385                 match (*target.bindings).def_for_namespace(namespace) {
3386                     None => {
3387                         // This can happen if we were looking for a type and
3388                         // found a module instead. Modules don't have defs.
3389                         debug!("(resolving item path by identifier in lexical \
3390                                  scope) failed to resolve {} after success...",
3391                                  name);
3392                         return None;
3393                     }
3394                     Some(def) => {
3395                         debug!("(resolving item path in lexical scope) \
3396                                 resolved `{}` to item",
3397                                name);
3398                         // This lookup is "all public" because it only searched
3399                         // for one identifier in the current module (couldn't
3400                         // have passed through reexports or anything like that.
3401                         return Some((def, LastMod(AllPublic)));
3402                     }
3403                 }
3404             }
3405             Indeterminate => {
3406                 panic!("unexpected indeterminate result");
3407             }
3408             Failed(err) => {
3409                 debug!("(resolving item path by identifier in lexical scope) \
3410                          failed to resolve {}", name);
3411
3412                 if let Some((span, msg)) = err {
3413                     resolve_error(self, span, ResolutionError::FailedToResolve(&*msg))
3414                 }
3415
3416                 return None;
3417             }
3418         }
3419     }
3420
3421     fn with_no_errors<T, F>(&mut self, f: F) -> T where
3422         F: FnOnce(&mut Resolver) -> T,
3423     {
3424         self.emit_errors = false;
3425         let rs = f(self);
3426         self.emit_errors = true;
3427         rs
3428     }
3429
3430     fn find_fallback_in_self_type(&mut self, name: Name) -> FallbackSuggestion {
3431         fn extract_path_and_node_id(t: &Ty, allow: FallbackChecks)
3432                                                     -> Option<(Path, NodeId, FallbackChecks)> {
3433             match t.node {
3434                 TyPath(None, ref path) => Some((path.clone(), t.id, allow)),
3435                 TyPtr(ref mut_ty) => extract_path_and_node_id(&*mut_ty.ty, OnlyTraitAndStatics),
3436                 TyRptr(_, ref mut_ty) => extract_path_and_node_id(&*mut_ty.ty, allow),
3437                 // This doesn't handle the remaining `Ty` variants as they are not
3438                 // that commonly the self_type, it might be interesting to provide
3439                 // support for those in future.
3440                 _ => None,
3441             }
3442         }
3443
3444         fn get_module(this: &mut Resolver, span: Span, name_path: &[ast::Name])
3445                             -> Option<Rc<Module>> {
3446             let root = this.current_module.clone();
3447             let last_name = name_path.last().unwrap();
3448
3449             if name_path.len() == 1 {
3450                 match this.primitive_type_table.primitive_types.get(last_name) {
3451                     Some(_) => None,
3452                     None => {
3453                         match this.current_module.children.borrow().get(last_name) {
3454                             Some(child) => child.get_module_if_available(),
3455                             None => None
3456                         }
3457                     }
3458                 }
3459             } else {
3460                 match this.resolve_module_path(root,
3461                                                &name_path[..],
3462                                                UseLexicalScope,
3463                                                span,
3464                                                PathSearch) {
3465                     Success((module, _)) => Some(module),
3466                     _ => None
3467                 }
3468             }
3469         }
3470
3471         fn is_static_method(this: &Resolver, did: DefId) -> bool {
3472             if did.is_local() {
3473                 let sig = match this.ast_map.get(did.node) {
3474                     hir_map::NodeTraitItem(trait_item) => match trait_item.node {
3475                         hir::MethodTraitItem(ref sig, _) => sig,
3476                         _ => return false
3477                     },
3478                     hir_map::NodeImplItem(impl_item) => match impl_item.node {
3479                         hir::MethodImplItem(ref sig, _) => sig,
3480                         _ => return false
3481                     },
3482                     _ => return false
3483                 };
3484                 sig.explicit_self.node == hir::SelfStatic
3485             } else {
3486                 csearch::is_static_method(&this.session.cstore, did)
3487             }
3488         }
3489
3490         let (path, node_id, allowed) = match self.current_self_type {
3491             Some(ref ty) => match extract_path_and_node_id(ty, Everything) {
3492                 Some(x) => x,
3493                 None => return NoSuggestion,
3494             },
3495             None => return NoSuggestion,
3496         };
3497
3498         if allowed == Everything {
3499             // Look for a field with the same name in the current self_type.
3500             match self.def_map.borrow().get(&node_id).map(|d| d.full_def()) {
3501                 Some(DefTy(did, _)) |
3502                 Some(DefStruct(did)) |
3503                 Some(DefVariant(_, did, _)) => match self.structs.get(&did) {
3504                     None => {}
3505                     Some(fields) => {
3506                         if fields.iter().any(|&field_name| name == field_name) {
3507                             return Field;
3508                         }
3509                     }
3510                 },
3511                 _ => {} // Self type didn't resolve properly
3512             }
3513         }
3514
3515         let name_path = path.segments.iter().map(|seg| seg.identifier.name).collect::<Vec<_>>();
3516
3517         // Look for a method in the current self type's impl module.
3518         if let Some(module) = get_module(self, path.span, &name_path) {
3519             if let Some(binding) = module.children.borrow().get(&name) {
3520                 if let Some(DefMethod(did)) = binding.def_for_namespace(ValueNS) {
3521                     if is_static_method(self, did) {
3522                         return StaticMethod(path_names_to_string(&path, 0))
3523                     }
3524                     if self.current_trait_ref.is_some() {
3525                         return TraitItem;
3526                     } else if allowed == Everything {
3527                         return Method;
3528                     }
3529                 }
3530             }
3531         }
3532
3533         // Look for a method in the current trait.
3534         if let Some((trait_did, ref trait_ref)) = self.current_trait_ref {
3535             if let Some(&did) = self.trait_item_map.get(&(name, trait_did)) {
3536                 if is_static_method(self, did) {
3537                     return TraitMethod(path_names_to_string(&trait_ref.path, 0));
3538                 } else {
3539                     return TraitItem;
3540                 }
3541             }
3542         }
3543
3544         NoSuggestion
3545     }
3546
3547     fn find_best_match_for_name(&mut self, name: &str) -> Option<String> {
3548         let mut maybes: Vec<token::InternedString> = Vec::new();
3549         let mut values: Vec<usize> = Vec::new();
3550
3551         for rib in self.value_ribs.iter().rev() {
3552             for (&k, _) in &rib.bindings {
3553                 maybes.push(k.as_str());
3554                 values.push(usize::MAX);
3555             }
3556         }
3557
3558         let mut smallest = 0;
3559         for (i, other) in maybes.iter().enumerate() {
3560             values[i] = lev_distance(name, &other);
3561
3562             if values[i] <= values[smallest] {
3563                 smallest = i;
3564             }
3565         }
3566
3567         // As a loose rule to avoid obviously incorrect suggestions, clamp the
3568         // maximum edit distance we will accept for a suggestion to one third of
3569         // the typo'd name's length.
3570         let max_distance = std::cmp::max(name.len(), 3) / 3;
3571
3572         if !values.is_empty() &&
3573             values[smallest] <= max_distance &&
3574             name != &maybes[smallest][..] {
3575
3576             Some(maybes[smallest].to_string())
3577
3578         } else {
3579             None
3580         }
3581     }
3582
3583     fn resolve_expr(&mut self, expr: &Expr) {
3584         // First, record candidate traits for this expression if it could
3585         // result in the invocation of a method call.
3586
3587         self.record_candidate_traits_for_expr_if_necessary(expr);
3588
3589         // Next, resolve the node.
3590         match expr.node {
3591             ExprPath(ref maybe_qself, ref path) => {
3592                 let resolution =
3593                     match self.resolve_possibly_assoc_item(expr.id,
3594                                                            maybe_qself.as_ref(),
3595                                                            path,
3596                                                            ValueNS,
3597                                                            true) {
3598                         // `<T>::a::b::c` is resolved by typeck alone.
3599                         TypecheckRequired => {
3600                             let method_name = path.segments.last().unwrap().identifier.name;
3601                             let traits = self.get_traits_containing_item(method_name);
3602                             self.trait_map.insert(expr.id, traits);
3603                             visit::walk_expr(self, expr);
3604                             return;
3605                         }
3606                         ResolveAttempt(resolution) => resolution,
3607                     };
3608
3609                 // This is a local path in the value namespace. Walk through
3610                 // scopes looking for it.
3611                 if let Some(path_res) = resolution {
3612                     // Check if struct variant
3613                     if let DefVariant(_, _, true) = path_res.base_def {
3614                         let path_name = path_names_to_string(path, 0);
3615
3616                         resolve_error(self,
3617                                       expr.span,
3618                                       ResolutionError::StructVariantUsedAsFunction(&*path_name));
3619
3620                         let msg = format!("did you mean to write: \
3621                                            `{} {{ /* fields */ }}`?",
3622                                           path_name);
3623                         if self.emit_errors {
3624                             self.session.fileline_help(expr.span, &msg);
3625                         } else {
3626                             self.session.span_help(expr.span, &msg);
3627                         }
3628                     } else {
3629                         // Write the result into the def map.
3630                         debug!("(resolving expr) resolved `{}`",
3631                                path_names_to_string(path, 0));
3632
3633                         // Partial resolutions will need the set of traits in scope,
3634                         // so they can be completed during typeck.
3635                         if path_res.depth != 0 {
3636                             let method_name = path.segments.last().unwrap().identifier.name;
3637                             let traits = self.get_traits_containing_item(method_name);
3638                             self.trait_map.insert(expr.id, traits);
3639                         }
3640
3641                         self.record_def(expr.id, path_res);
3642                     }
3643                 } else {
3644                     // Be helpful if the name refers to a struct
3645                     // (The pattern matching def_tys where the id is in self.structs
3646                     // matches on regular structs while excluding tuple- and enum-like
3647                     // structs, which wouldn't result in this error.)
3648                     let path_name = path_names_to_string(path, 0);
3649                     let type_res = self.with_no_errors(|this| {
3650                         this.resolve_path(expr.id, path, 0, TypeNS, false)
3651                     });
3652                     match type_res.map(|r| r.base_def) {
3653                         Some(DefTy(struct_id, _))
3654                             if self.structs.contains_key(&struct_id) => {
3655                                 resolve_error(
3656                                     self,
3657                                     expr.span,
3658                                     ResolutionError::StructVariantUsedAsFunction(
3659                                         &*path_name)
3660                                 );
3661
3662                                 let msg = format!("did you mean to write: \
3663                                                      `{} {{ /* fields */ }}`?",
3664                                                     path_name);
3665                                 if self.emit_errors {
3666                                     self.session.fileline_help(expr.span, &msg);
3667                                 } else {
3668                                     self.session.span_help(expr.span, &msg);
3669                                 }
3670                             }
3671                         _ => {
3672                             // Keep reporting some errors even if they're ignored above.
3673                             self.resolve_path(expr.id, path, 0, ValueNS, true);
3674
3675                             let mut method_scope = false;
3676                             self.value_ribs.iter().rev().all(|rib| {
3677                                 method_scope = match rib.kind {
3678                                     MethodRibKind => true,
3679                                     ItemRibKind | ConstantItemRibKind => false,
3680                                     _ => return true, // Keep advancing
3681                                 };
3682                                 false // Stop advancing
3683                             });
3684
3685                             if method_scope && special_names::self_ == path_name {
3686                                 resolve_error(
3687                                     self,
3688                                     expr.span,
3689                                     ResolutionError::SelfNotAvailableInStaticMethod
3690                                 );
3691                             } else {
3692                                 let last_name = path.segments.last().unwrap().identifier.name;
3693                                 let mut msg = match self.find_fallback_in_self_type(last_name) {
3694                                     NoSuggestion => {
3695                                         // limit search to 5 to reduce the number
3696                                         // of stupid suggestions
3697                                         self.find_best_match_for_name(&path_name)
3698                                                             .map_or("".to_string(),
3699                                                                     |x| format!("`{}`", x))
3700                                     }
3701                                     Field => format!("`self.{}`", path_name),
3702                                     Method |
3703                                     TraitItem =>
3704                                         format!("to call `self.{}`", path_name),
3705                                     TraitMethod(path_str) |
3706                                     StaticMethod(path_str) =>
3707                                         format!("to call `{}::{}`", path_str, path_name)
3708                                 };
3709
3710                                 if !msg.is_empty() {
3711                                     msg = format!(". Did you mean {}?", msg)
3712                                 }
3713
3714                                 resolve_error(self,
3715                                               expr.span,
3716                                               ResolutionError::UnresolvedName(&*path_name,
3717                                                                                &*msg));
3718                             }
3719                         }
3720                     }
3721                 }
3722
3723                 visit::walk_expr(self, expr);
3724             }
3725
3726             ExprStruct(ref path, _, _) => {
3727                 // Resolve the path to the structure it goes to. We don't
3728                 // check to ensure that the path is actually a structure; that
3729                 // is checked later during typeck.
3730                 match self.resolve_path(expr.id, path, 0, TypeNS, false) {
3731                     Some(definition) => self.record_def(expr.id, definition),
3732                     None => {
3733                         debug!("(resolving expression) didn't find struct def",);
3734
3735                         resolve_error(self,
3736                                       path.span,
3737                                       ResolutionError::DoesNotNameAStruct(
3738                                                                 &*path_names_to_string(path, 0))
3739                                      );
3740                     }
3741                 }
3742
3743                 visit::walk_expr(self, expr);
3744             }
3745
3746             ExprLoop(_, Some(label)) | ExprWhile(_, _, Some(label)) => {
3747                 self.with_label_rib(|this| {
3748                     let def_like = DlDef(DefLabel(expr.id));
3749
3750                     {
3751                         let rib = this.label_ribs.last_mut().unwrap();
3752                         let renamed = mtwt::resolve(label);
3753                         rib.bindings.insert(renamed, def_like);
3754                     }
3755
3756                     visit::walk_expr(this, expr);
3757                 })
3758             }
3759
3760             ExprBreak(Some(label)) | ExprAgain(Some(label)) => {
3761                 let renamed = mtwt::resolve(label.node);
3762                 match self.search_label(renamed) {
3763                     None => {
3764                         resolve_error(self,
3765                                       label.span,
3766                                       ResolutionError::UndeclaredLabel(&label.node.name.as_str()))
3767                     }
3768                     Some(DlDef(def @ DefLabel(_))) => {
3769                         // Since this def is a label, it is never read.
3770                         self.record_def(expr.id, PathResolution {
3771                             base_def: def,
3772                             last_private: LastMod(AllPublic),
3773                             depth: 0
3774                         })
3775                     }
3776                     Some(_) => {
3777                         self.session.span_bug(expr.span,
3778                                               "label wasn't mapped to a \
3779                                                label def!")
3780                     }
3781                 }
3782             }
3783
3784             _ => {
3785                 visit::walk_expr(self, expr);
3786             }
3787         }
3788     }
3789
3790     fn record_candidate_traits_for_expr_if_necessary(&mut self, expr: &Expr) {
3791         match expr.node {
3792             ExprField(_, ident) => {
3793                 // FIXME(#6890): Even though you can't treat a method like a
3794                 // field, we need to add any trait methods we find that match
3795                 // the field name so that we can do some nice error reporting
3796                 // later on in typeck.
3797                 let traits = self.get_traits_containing_item(ident.node.name);
3798                 self.trait_map.insert(expr.id, traits);
3799             }
3800             ExprMethodCall(ident, _, _) => {
3801                 debug!("(recording candidate traits for expr) recording \
3802                         traits for {}",
3803                        expr.id);
3804                 let traits = self.get_traits_containing_item(ident.node.name);
3805                 self.trait_map.insert(expr.id, traits);
3806             }
3807             _ => {
3808                 // Nothing to do.
3809             }
3810         }
3811     }
3812
3813     fn get_traits_containing_item(&mut self, name: Name) -> Vec<DefId> {
3814         debug!("(getting traits containing item) looking for '{}'",
3815                name);
3816
3817         fn add_trait_info(found_traits: &mut Vec<DefId>,
3818                           trait_def_id: DefId,
3819                           name: Name) {
3820             debug!("(adding trait info) found trait {}:{} for method '{}'",
3821                 trait_def_id.krate,
3822                 trait_def_id.node,
3823                 name);
3824             found_traits.push(trait_def_id);
3825         }
3826
3827         let mut found_traits = Vec::new();
3828         let mut search_module = self.current_module.clone();
3829         loop {
3830             // Look for the current trait.
3831             match self.current_trait_ref {
3832                 Some((trait_def_id, _)) => {
3833                     if self.trait_item_map.contains_key(&(name, trait_def_id)) {
3834                         add_trait_info(&mut found_traits, trait_def_id, name);
3835                     }
3836                 }
3837                 None => {} // Nothing to do.
3838             }
3839
3840             // Look for trait children.
3841             build_reduced_graph::populate_module_if_necessary(self, &search_module);
3842
3843             {
3844                 for (_, child_names) in search_module.children.borrow().iter() {
3845                     let def = match child_names.def_for_namespace(TypeNS) {
3846                         Some(def) => def,
3847                         None => continue
3848                     };
3849                     let trait_def_id = match def {
3850                         DefTrait(trait_def_id) => trait_def_id,
3851                         _ => continue,
3852                     };
3853                     if self.trait_item_map.contains_key(&(name, trait_def_id)) {
3854                         add_trait_info(&mut found_traits, trait_def_id, name);
3855                     }
3856                 }
3857             }
3858
3859             // Look for imports.
3860             for (_, import) in search_module.import_resolutions.borrow().iter() {
3861                 let target = match import.target_for_namespace(TypeNS) {
3862                     None => continue,
3863                     Some(target) => target,
3864                 };
3865                 let did = match target.bindings.def_for_namespace(TypeNS) {
3866                     Some(DefTrait(trait_def_id)) => trait_def_id,
3867                     Some(..) | None => continue,
3868                 };
3869                 if self.trait_item_map.contains_key(&(name, did)) {
3870                     add_trait_info(&mut found_traits, did, name);
3871                     let id = import.type_id;
3872                     self.used_imports.insert((id, TypeNS));
3873                     let trait_name = self.get_trait_name(did);
3874                     self.record_import_use(id, trait_name);
3875                     if let Some(DefId{krate: kid, ..}) = target.target_module.def_id.get() {
3876                         self.used_crates.insert(kid);
3877                     }
3878                 }
3879             }
3880
3881             match search_module.parent_link.clone() {
3882                 NoParentLink | ModuleParentLink(..) => break,
3883                 BlockParentLink(parent_module, _) => {
3884                     search_module = parent_module.upgrade().unwrap();
3885                 }
3886             }
3887         }
3888
3889         found_traits
3890     }
3891
3892     fn record_def(&mut self, node_id: NodeId, resolution: PathResolution) {
3893         debug!("(recording def) recording {:?} for {}", resolution, node_id);
3894         assert!(match resolution.last_private {LastImport{..} => false, _ => true},
3895                 "Import should only be used for `use` directives");
3896
3897         if let Some(prev_res) = self.def_map.borrow_mut().insert(node_id, resolution) {
3898             let span = self.ast_map.opt_span(node_id).unwrap_or(codemap::DUMMY_SP);
3899             self.session.span_bug(span, &format!("path resolved multiple times \
3900                                                   ({:?} before, {:?} now)",
3901                                                  prev_res, resolution));
3902         }
3903     }
3904
3905     fn enforce_default_binding_mode(&mut self,
3906                                         pat: &Pat,
3907                                         pat_binding_mode: BindingMode,
3908                                         descr: &str) {
3909         match pat_binding_mode {
3910             BindByValue(_) => {}
3911             BindByRef(..) => {
3912                 resolve_error(self,
3913                               pat.span,
3914                               ResolutionError::CannotUseRefBindingModeWith(descr));
3915             }
3916         }
3917     }
3918
3919     //
3920     // Diagnostics
3921     //
3922     // Diagnostics are not particularly efficient, because they're rarely
3923     // hit.
3924     //
3925
3926     #[allow(dead_code)]   // useful for debugging
3927     fn dump_module(&mut self, module_: Rc<Module>) {
3928         debug!("Dump of module `{}`:", module_to_string(&*module_));
3929
3930         debug!("Children:");
3931         build_reduced_graph::populate_module_if_necessary(self, &module_);
3932         for (&name, _) in module_.children.borrow().iter() {
3933             debug!("* {}", name);
3934         }
3935
3936         debug!("Import resolutions:");
3937         let import_resolutions = module_.import_resolutions.borrow();
3938         for (&name, import_resolution) in import_resolutions.iter() {
3939             let value_repr;
3940             match import_resolution.target_for_namespace(ValueNS) {
3941                 None => { value_repr = "".to_string(); }
3942                 Some(_) => {
3943                     value_repr = " value:?".to_string();
3944                     // FIXME #4954
3945                 }
3946             }
3947
3948             let type_repr;
3949             match import_resolution.target_for_namespace(TypeNS) {
3950                 None => { type_repr = "".to_string(); }
3951                 Some(_) => {
3952                     type_repr = " type:?".to_string();
3953                     // FIXME #4954
3954                 }
3955             }
3956
3957             debug!("* {}:{}{}", name, value_repr, type_repr);
3958         }
3959     }
3960 }
3961
3962
3963 fn names_to_string(names: &[Name]) -> String {
3964     let mut first = true;
3965     let mut result = String::new();
3966     for name in names {
3967         if first {
3968             first = false
3969         } else {
3970             result.push_str("::")
3971         }
3972         result.push_str(&name.as_str());
3973     };
3974     result
3975 }
3976
3977 fn path_names_to_string(path: &Path, depth: usize) -> String {
3978     let names: Vec<ast::Name> = path.segments[..path.segments.len()-depth]
3979                                     .iter()
3980                                     .map(|seg| seg.identifier.name)
3981                                     .collect();
3982     names_to_string(&names[..])
3983 }
3984
3985 /// A somewhat inefficient routine to obtain the name of a module.
3986 fn module_to_string(module: &Module) -> String {
3987     let mut names = Vec::new();
3988
3989     fn collect_mod(names: &mut Vec<ast::Name>, module: &Module) {
3990         match module.parent_link {
3991             NoParentLink => {}
3992             ModuleParentLink(ref module, name) => {
3993                 names.push(name);
3994                 collect_mod(names, &*module.upgrade().unwrap());
3995             }
3996             BlockParentLink(ref module, _) => {
3997                 // danger, shouldn't be ident?
3998                 names.push(special_idents::opaque.name);
3999                 collect_mod(names, &*module.upgrade().unwrap());
4000             }
4001         }
4002     }
4003     collect_mod(&mut names, module);
4004
4005     if names.is_empty() {
4006         return "???".to_string();
4007     }
4008     names_to_string(&names.into_iter().rev().collect::<Vec<ast::Name>>())
4009 }
4010
4011
4012 pub struct CrateMap {
4013     pub def_map: DefMap,
4014     pub freevars: RefCell<FreevarMap>,
4015     pub export_map: ExportMap,
4016     pub trait_map: TraitMap,
4017     pub external_exports: ExternalExports,
4018     pub glob_map: Option<GlobMap>
4019 }
4020
4021 #[derive(PartialEq,Copy, Clone)]
4022 pub enum MakeGlobMap {
4023     Yes,
4024     No
4025 }
4026
4027 /// Entry point to crate resolution.
4028 pub fn resolve_crate<'a, 'tcx>(session: &'a Session,
4029                                ast_map: &'a hir_map::Map<'tcx>,
4030                                make_glob_map: MakeGlobMap)
4031                                -> CrateMap {
4032     let krate = ast_map.krate();
4033     let mut resolver = create_resolver(session, ast_map, krate, make_glob_map, None);
4034
4035     resolver.resolve_crate(krate);
4036     session.abort_if_errors();
4037
4038     check_unused::check_crate(&mut resolver, krate);
4039
4040     CrateMap {
4041         def_map: resolver.def_map,
4042         freevars: resolver.freevars,
4043         export_map: resolver.export_map,
4044         trait_map: resolver.trait_map,
4045         external_exports: resolver.external_exports,
4046         glob_map: if resolver.make_glob_map {
4047                         Some(resolver.glob_map)
4048                     } else {
4049                         None
4050                     },
4051     }
4052 }
4053
4054 /// Builds a name resolution walker to be used within this module,
4055 /// or used externally, with an optional callback function.
4056 ///
4057 /// The callback takes a &mut bool which allows callbacks to end a
4058 /// walk when set to true, passing through the rest of the walk, while
4059 /// preserving the ribs + current module. This allows resolve_path
4060 /// calls to be made with the correct scope info. The node in the
4061 /// callback corresponds to the current node in the walk.
4062 pub fn create_resolver<'a, 'tcx>(session: &'a Session,
4063                                  ast_map: &'a hir_map::Map<'tcx>,
4064                                  krate: &'a Crate,
4065                                  make_glob_map: MakeGlobMap,
4066                                  callback: Option<Box<Fn(hir_map::Node, &mut bool) -> bool>>)
4067                                  -> Resolver<'a, 'tcx> {
4068     let mut resolver = Resolver::new(session, ast_map, krate.span, make_glob_map);
4069
4070     resolver.callback = callback;
4071
4072     build_reduced_graph::build_reduced_graph(&mut resolver, krate);
4073     session.abort_if_errors();
4074
4075     resolve_imports::resolve_imports(&mut resolver);
4076     session.abort_if_errors();
4077
4078     record_exports::record(&mut resolver);
4079     session.abort_if_errors();
4080
4081     resolver
4082 }
4083
4084 __build_diagnostic_array! { librustc_resolve, DIAGNOSTICS }