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