]> git.lizzy.rs Git - rust.git/blob - src/librustc_resolve/lib.rs
Rollup merge of #28400 - badboy:disable-browser-history-on-file, r=steveklabnik
[rust.git] / src / librustc_resolve / lib.rs
1 // Copyright 2012-2015 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
4 //
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
10
11 // Do not remove on snapshot creation. Needed for bootstrap. (Issue #22364)
12 #![cfg_attr(stage0, feature(custom_attribute))]
13 #![crate_name = "rustc_resolve"]
14 #![unstable(feature = "rustc_private", issue = "27812")]
15 #![staged_api]
16 #![crate_type = "dylib"]
17 #![crate_type = "rlib"]
18 #![doc(html_logo_url = "https://www.rust-lang.org/logos/rust-logo-128x128-blk-v2.png",
19       html_favicon_url = "https://doc.rust-lang.org/favicon.ico",
20       html_root_url = "https://doc.rust-lang.org/nightly/")]
21
22 #![feature(associated_consts)]
23 #![feature(borrow_state)]
24 #![feature(rustc_diagnostic_macros)]
25 #![feature(rustc_private)]
26 #![feature(slice_splits)]
27 #![feature(staged_api)]
28
29 #[macro_use] extern crate log;
30 #[macro_use] extern crate syntax;
31 #[macro_use] #[no_link] extern crate rustc_bitflags;
32 extern crate rustc_front;
33
34 extern crate rustc;
35
36 use self::PatternBindingMode::*;
37 use self::Namespace::*;
38 use self::NamespaceResult::*;
39 use self::NameDefinition::*;
40 use self::ResolveResult::*;
41 use self::FallbackSuggestion::*;
42 use self::TypeParameters::*;
43 use self::RibKind::*;
44 use self::UseLexicalScopeFlag::*;
45 use self::ModulePrefixResult::*;
46 use self::AssocItemResolveResult::*;
47 use self::NameSearchType::*;
48 use self::BareIdentifierPatternResolution::*;
49 use self::ParentLink::*;
50 use self::ModuleKind::*;
51 use self::FallbackChecks::*;
52
53 use rustc::front::map as hir_map;
54 use rustc::session::Session;
55 use rustc::lint;
56 use rustc::metadata::csearch;
57 use rustc::metadata::decoder::{DefLike, DlDef, DlField, DlImpl};
58 use rustc::middle::def::*;
59 use rustc::middle::def_id::DefId;
60 use rustc::middle::pat_util::pat_bindings;
61 use rustc::middle::privacy::*;
62 use rustc::middle::subst::{ParamSpace, FnSpace, TypeSpace};
63 use rustc::middle::ty::{Freevar, FreevarMap, TraitMap, GlobMap};
64 use rustc::util::nodemap::{NodeMap, DefIdSet, FnvHashMap};
65 use rustc::util::lev_distance::lev_distance;
66
67 use syntax::ast;
68 use syntax::ast::{Ident, Name, NodeId, CrateNum, 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         graph_root.define_module(NoParentLink,
1192                                  Some(DefId { krate: 0, node: 0 }),
1193                                  NormalModuleKind,
1194                                  false,
1195                                  true,
1196                                  crate_span);
1197
1198         let current_module = graph_root.get_module();
1199
1200         Resolver {
1201             session: session,
1202
1203             ast_map: ast_map,
1204
1205             // The outermost module has def ID 0; this is not reflected in the
1206             // AST.
1207
1208             graph_root: graph_root,
1209
1210             trait_item_map: FnvHashMap(),
1211             structs: FnvHashMap(),
1212
1213             unresolved_imports: 0,
1214
1215             current_module: current_module,
1216             value_ribs: Vec::new(),
1217             type_ribs: Vec::new(),
1218             label_ribs: Vec::new(),
1219
1220             current_trait_ref: None,
1221             current_self_type: None,
1222
1223             primitive_type_table: PrimitiveTypeTable::new(),
1224
1225             def_map: RefCell::new(NodeMap()),
1226             freevars: RefCell::new(NodeMap()),
1227             freevars_seen: RefCell::new(NodeMap()),
1228             export_map: NodeMap(),
1229             trait_map: NodeMap(),
1230             used_imports: HashSet::new(),
1231             used_crates: HashSet::new(),
1232             external_exports: DefIdSet(),
1233
1234             emit_errors: true,
1235             make_glob_map: make_glob_map == MakeGlobMap::Yes,
1236             glob_map: HashMap::new(),
1237
1238             callback: None,
1239             resolved: false,
1240
1241         }
1242     }
1243
1244     #[inline]
1245     fn record_import_use(&mut self, import_id: NodeId, name: Name) {
1246         if !self.make_glob_map {
1247             return;
1248         }
1249         if self.glob_map.contains_key(&import_id) {
1250             self.glob_map.get_mut(&import_id).unwrap().insert(name);
1251             return;
1252         }
1253
1254         let mut new_set = HashSet::new();
1255         new_set.insert(name);
1256         self.glob_map.insert(import_id, new_set);
1257     }
1258
1259     fn get_trait_name(&self, did: DefId) -> Name {
1260         if did.is_local() {
1261             self.ast_map.expect_item(did.node).ident.name
1262         } else {
1263             csearch::get_trait_name(&self.session.cstore, did)
1264         }
1265     }
1266
1267     fn create_name_bindings_from_module(module: Rc<Module>) -> NameBindings {
1268         NameBindings {
1269             type_def: RefCell::new(Some(TypeNsDef {
1270                 modifiers: DefModifiers::IMPORTABLE,
1271                 module_def: Some(module),
1272                 type_def: None,
1273                 type_span: None
1274             })),
1275             value_def: RefCell::new(None),
1276         }
1277     }
1278
1279     /// Checks that the names of external crates don't collide with other
1280     /// external crates.
1281     fn check_for_conflicts_between_external_crates(&self,
1282                                                    module: &Module,
1283                                                    name: Name,
1284                                                    span: Span) {
1285         if module.external_module_children.borrow().contains_key(&name) {
1286                 span_err!(self.session, span, E0259,
1287                           "an external crate named `{}` has already \
1288                            been imported into this module",
1289                           name);
1290         }
1291     }
1292
1293     /// Checks that the names of items don't collide with external crates.
1294     fn check_for_conflicts_between_external_crates_and_items(&self,
1295                                                              module: &Module,
1296                                                              name: Name,
1297                                                              span: Span) {
1298         if module.external_module_children.borrow().contains_key(&name) {
1299                 span_err!(self.session, span, E0260,
1300                           "the name `{}` conflicts with an external \
1301                            crate that has been imported into this \
1302                            module",
1303                            name);
1304         }
1305     }
1306
1307     /// Resolves the given module path from the given root `module_`.
1308     fn resolve_module_path_from_root(&mut self,
1309                                      module_: Rc<Module>,
1310                                      module_path: &[Name],
1311                                      index: usize,
1312                                      span: Span,
1313                                      name_search_type: NameSearchType,
1314                                      lp: LastPrivate)
1315                                 -> ResolveResult<(Rc<Module>, LastPrivate)> {
1316         fn search_parent_externals(needle: Name, module: &Rc<Module>)
1317                                 -> Option<Rc<Module>> {
1318             match module.external_module_children.borrow().get(&needle) {
1319                 Some(_) => Some(module.clone()),
1320                 None => match module.parent_link {
1321                     ModuleParentLink(ref parent, _) => {
1322                         search_parent_externals(needle, &parent.upgrade().unwrap())
1323                     }
1324                    _ => None
1325                 }
1326             }
1327         }
1328
1329         let mut search_module = module_;
1330         let mut index = index;
1331         let module_path_len = module_path.len();
1332         let mut closest_private = lp;
1333
1334         // Resolve the module part of the path. This does not involve looking
1335         // upward though scope chains; we simply resolve names directly in
1336         // modules as we go.
1337         while index < module_path_len {
1338             let name = module_path[index];
1339             match self.resolve_name_in_module(search_module.clone(),
1340                                               name,
1341                                               TypeNS,
1342                                               name_search_type,
1343                                               false) {
1344                 Failed(None) => {
1345                     let segment_name = name.as_str();
1346                     let module_name = module_to_string(&*search_module);
1347                     let mut span = span;
1348                     let msg = if "???" == &module_name[..] {
1349                         span.hi = span.lo + Pos::from_usize(segment_name.len());
1350
1351                         match search_parent_externals(name,
1352                                                      &self.current_module) {
1353                             Some(module) => {
1354                                 let path_str = names_to_string(module_path);
1355                                 let target_mod_str = module_to_string(&*module);
1356                                 let current_mod_str =
1357                                     module_to_string(&*self.current_module);
1358
1359                                 let prefix = if target_mod_str == current_mod_str {
1360                                     "self::".to_string()
1361                                 } else {
1362                                     format!("{}::", target_mod_str)
1363                                 };
1364
1365                                 format!("Did you mean `{}{}`?", prefix, path_str)
1366                             },
1367                             None => format!("Maybe a missing `extern crate {}`?",
1368                                             segment_name),
1369                         }
1370                     } else {
1371                         format!("Could not find `{}` in `{}`",
1372                                 segment_name,
1373                                 module_name)
1374                     };
1375
1376                     return Failed(Some((span, msg)));
1377                 }
1378                 Failed(err) => return Failed(err),
1379                 Indeterminate => {
1380                     debug!("(resolving module path for import) module \
1381                             resolution is indeterminate: {}",
1382                             name);
1383                     return Indeterminate;
1384                 }
1385                 Success((target, used_proxy)) => {
1386                     // Check to see whether there are type bindings, and, if
1387                     // so, whether there is a module within.
1388                     match *target.bindings.type_def.borrow() {
1389                         Some(ref type_def) => {
1390                             match type_def.module_def {
1391                                 None => {
1392                                     let msg = format!("Not a module `{}`",
1393                                                         name);
1394
1395                                     return Failed(Some((span, msg)));
1396                                 }
1397                                 Some(ref module_def) => {
1398                                     search_module = module_def.clone();
1399
1400                                     // track extern crates for unused_extern_crate lint
1401                                     if let Some(did) = module_def.def_id.get() {
1402                                         self.used_crates.insert(did.krate);
1403                                     }
1404
1405                                     // Keep track of the closest
1406                                     // private module used when
1407                                     // resolving this import chain.
1408                                     if !used_proxy && !search_module.is_public {
1409                                         if let Some(did) = search_module.def_id.get() {
1410                                             closest_private = LastMod(DependsOn(did));
1411                                         }
1412                                     }
1413                                 }
1414                             }
1415                         }
1416                         None => {
1417                             // There are no type bindings at all.
1418                             let msg = format!("Not a module `{}`",
1419                                               name);
1420                             return Failed(Some((span, msg)));
1421                         }
1422                     }
1423                 }
1424             }
1425
1426             index += 1;
1427         }
1428
1429         return Success((search_module, closest_private));
1430     }
1431
1432     /// Attempts to resolve the module part of an import directive or path
1433     /// rooted at the given module.
1434     ///
1435     /// On success, returns the resolved module, and the closest *private*
1436     /// module found to the destination when resolving this path.
1437     fn resolve_module_path(&mut self,
1438                            module_: Rc<Module>,
1439                            module_path: &[Name],
1440                            use_lexical_scope: UseLexicalScopeFlag,
1441                            span: Span,
1442                            name_search_type: NameSearchType)
1443                            -> ResolveResult<(Rc<Module>, LastPrivate)> {
1444         let module_path_len = module_path.len();
1445         assert!(module_path_len > 0);
1446
1447         debug!("(resolving module path for import) processing `{}` rooted at `{}`",
1448                names_to_string(module_path),
1449                module_to_string(&*module_));
1450
1451         // Resolve the module prefix, if any.
1452         let module_prefix_result = self.resolve_module_prefix(module_.clone(),
1453                                                               module_path);
1454
1455         let search_module;
1456         let start_index;
1457         let last_private;
1458         match module_prefix_result {
1459             Failed(None) => {
1460                 let mpath = names_to_string(module_path);
1461                 let mpath = &mpath[..];
1462                 match mpath.rfind(':') {
1463                     Some(idx) => {
1464                         let msg = format!("Could not find `{}` in `{}`",
1465                                             // idx +- 1 to account for the
1466                                             // colons on either side
1467                                             &mpath[idx + 1..],
1468                                             &mpath[..idx - 1]);
1469                         return Failed(Some((span, msg)));
1470                     },
1471                     None => {
1472                         return Failed(None)
1473                     }
1474                 }
1475             }
1476             Failed(err) => return Failed(err),
1477             Indeterminate => {
1478                 debug!("(resolving module path for import) indeterminate; \
1479                         bailing");
1480                 return Indeterminate;
1481             }
1482             Success(NoPrefixFound) => {
1483                 // There was no prefix, so we're considering the first element
1484                 // of the path. How we handle this depends on whether we were
1485                 // instructed to use lexical scope or not.
1486                 match use_lexical_scope {
1487                     DontUseLexicalScope => {
1488                         // This is a crate-relative path. We will start the
1489                         // resolution process at index zero.
1490                         search_module = self.graph_root.get_module();
1491                         start_index = 0;
1492                         last_private = LastMod(AllPublic);
1493                     }
1494                     UseLexicalScope => {
1495                         // This is not a crate-relative path. We resolve the
1496                         // first component of the path in the current lexical
1497                         // scope and then proceed to resolve below that.
1498                         match self.resolve_module_in_lexical_scope(module_,
1499                                                                    module_path[0]) {
1500                             Failed(err) => return Failed(err),
1501                             Indeterminate => {
1502                                 debug!("(resolving module path for import) \
1503                                         indeterminate; bailing");
1504                                 return Indeterminate;
1505                             }
1506                             Success(containing_module) => {
1507                                 search_module = containing_module;
1508                                 start_index = 1;
1509                                 last_private = LastMod(AllPublic);
1510                             }
1511                         }
1512                     }
1513                 }
1514             }
1515             Success(PrefixFound(ref containing_module, index)) => {
1516                 search_module = containing_module.clone();
1517                 start_index = index;
1518                 last_private = LastMod(DependsOn(containing_module.def_id
1519                                                                   .get()
1520                                                                   .unwrap()));
1521             }
1522         }
1523
1524         self.resolve_module_path_from_root(search_module,
1525                                            module_path,
1526                                            start_index,
1527                                            span,
1528                                            name_search_type,
1529                                            last_private)
1530     }
1531
1532     /// Invariant: This must only be called during main resolution, not during
1533     /// import resolution.
1534     fn resolve_item_in_lexical_scope(&mut self,
1535                                      module_: Rc<Module>,
1536                                      name: Name,
1537                                      namespace: Namespace)
1538                                     -> ResolveResult<(Target, bool)> {
1539         debug!("(resolving item in lexical scope) resolving `{}` in \
1540                 namespace {:?} in `{}`",
1541                name,
1542                namespace,
1543                module_to_string(&*module_));
1544
1545         // The current module node is handled specially. First, check for
1546         // its immediate children.
1547         build_reduced_graph::populate_module_if_necessary(self, &module_);
1548
1549         match module_.children.borrow().get(&name) {
1550             Some(name_bindings)
1551                     if name_bindings.defined_in_namespace(namespace) => {
1552                 debug!("top name bindings succeeded");
1553                 return Success((Target::new(module_.clone(),
1554                                             name_bindings.clone(),
1555                                             Shadowable::Never),
1556                                false));
1557             }
1558             Some(_) | None => { /* Not found; continue. */ }
1559         }
1560
1561         // Now check for its import directives. We don't have to have resolved
1562         // all its imports in the usual way; this is because chains of
1563         // adjacent import statements are processed as though they mutated the
1564         // current scope.
1565         if let Some(import_resolution) = module_.import_resolutions.borrow().get(&name) {
1566             match (*import_resolution).target_for_namespace(namespace) {
1567                 None => {
1568                     // Not found; continue.
1569                     debug!("(resolving item in lexical scope) found \
1570                             import resolution, but not in namespace {:?}",
1571                            namespace);
1572                 }
1573                 Some(target) => {
1574                     debug!("(resolving item in lexical scope) using \
1575                             import resolution");
1576                     // track used imports and extern crates as well
1577                     let id = import_resolution.id(namespace);
1578                     self.used_imports.insert((id, namespace));
1579                     self.record_import_use(id, name);
1580                     if let Some(DefId{krate: kid, ..}) = target.target_module.def_id.get() {
1581                          self.used_crates.insert(kid);
1582                     }
1583                     return Success((target, false));
1584                 }
1585             }
1586         }
1587
1588         // Search for external modules.
1589         if namespace == TypeNS {
1590             // FIXME (21114): In principle unclear `child` *has* to be lifted.
1591             let child = module_.external_module_children.borrow().get(&name).cloned();
1592             if let Some(module) = child {
1593                 let name_bindings =
1594                     Rc::new(Resolver::create_name_bindings_from_module(module));
1595                 debug!("lower name bindings succeeded");
1596                 return Success((Target::new(module_,
1597                                             name_bindings,
1598                                             Shadowable::Never),
1599                                 false));
1600             }
1601         }
1602
1603         // Finally, proceed up the scope chain looking for parent modules.
1604         let mut search_module = module_;
1605         loop {
1606             // Go to the next parent.
1607             match search_module.parent_link.clone() {
1608                 NoParentLink => {
1609                     // No more parents. This module was unresolved.
1610                     debug!("(resolving item in lexical scope) unresolved \
1611                             module");
1612                     return Failed(None);
1613                 }
1614                 ModuleParentLink(parent_module_node, _) => {
1615                     match search_module.kind.get() {
1616                         NormalModuleKind => {
1617                             // We stop the search here.
1618                             debug!("(resolving item in lexical \
1619                                     scope) unresolved module: not \
1620                                     searching through module \
1621                                     parents");
1622                             return Failed(None);
1623                         }
1624                         TraitModuleKind |
1625                         EnumModuleKind |
1626                         TypeModuleKind |
1627                         AnonymousModuleKind => {
1628                             search_module = parent_module_node.upgrade().unwrap();
1629                         }
1630                     }
1631                 }
1632                 BlockParentLink(ref parent_module_node, _) => {
1633                     search_module = parent_module_node.upgrade().unwrap();
1634                 }
1635             }
1636
1637             // Resolve the name in the parent module.
1638             match self.resolve_name_in_module(search_module.clone(),
1639                                               name,
1640                                               namespace,
1641                                               PathSearch,
1642                                               true) {
1643                 Failed(Some((span, msg))) => {
1644                     resolve_error(self, span, ResolutionError::FailedToResolve(&*msg));
1645                 },
1646                 Failed(None) => (), // Continue up the search chain.
1647                 Indeterminate => {
1648                     // We couldn't see through the higher scope because of an
1649                     // unresolved import higher up. Bail.
1650
1651                     debug!("(resolving item in lexical scope) indeterminate \
1652                             higher scope; bailing");
1653                     return Indeterminate;
1654                 }
1655                 Success((target, used_reexport)) => {
1656                     // We found the module.
1657                     debug!("(resolving item in lexical scope) found name \
1658                             in module, done");
1659                     return Success((target, used_reexport));
1660                 }
1661             }
1662         }
1663     }
1664
1665     /// Resolves a module name in the current lexical scope.
1666     fn resolve_module_in_lexical_scope(&mut self,
1667                                        module_: Rc<Module>,
1668                                        name: Name)
1669                                 -> ResolveResult<Rc<Module>> {
1670         // If this module is an anonymous module, resolve the item in the
1671         // lexical scope. Otherwise, resolve the item from the crate root.
1672         let resolve_result = self.resolve_item_in_lexical_scope(module_, name, TypeNS);
1673         match resolve_result {
1674             Success((target, _)) => {
1675                 let bindings = &*target.bindings;
1676                 match *bindings.type_def.borrow() {
1677                     Some(ref type_def) => {
1678                         match type_def.module_def {
1679                             None => {
1680                                 debug!("!!! (resolving module in lexical \
1681                                         scope) module wasn't actually a \
1682                                         module!");
1683                                 return Failed(None);
1684                             }
1685                             Some(ref module_def) => {
1686                                 return Success(module_def.clone());
1687                             }
1688                         }
1689                     }
1690                     None => {
1691                         debug!("!!! (resolving module in lexical scope) module
1692                                 wasn't actually a module!");
1693                         return Failed(None);
1694                     }
1695                 }
1696             }
1697             Indeterminate => {
1698                 debug!("(resolving module in lexical scope) indeterminate; \
1699                         bailing");
1700                 return Indeterminate;
1701             }
1702             Failed(err) => {
1703                 debug!("(resolving module in lexical scope) failed to resolve");
1704                 return Failed(err);
1705             }
1706         }
1707     }
1708
1709     /// Returns the nearest normal module parent of the given module.
1710     fn get_nearest_normal_module_parent(&mut self, module_: Rc<Module>)
1711                                             -> Option<Rc<Module>> {
1712         let mut module_ = module_;
1713         loop {
1714             match module_.parent_link.clone() {
1715                 NoParentLink => return None,
1716                 ModuleParentLink(new_module, _) |
1717                 BlockParentLink(new_module, _) => {
1718                     let new_module = new_module.upgrade().unwrap();
1719                     match new_module.kind.get() {
1720                         NormalModuleKind => return Some(new_module),
1721                         TraitModuleKind |
1722                         EnumModuleKind |
1723                         TypeModuleKind |
1724                         AnonymousModuleKind => module_ = new_module,
1725                     }
1726                 }
1727             }
1728         }
1729     }
1730
1731     /// Returns the nearest normal module parent of the given module, or the
1732     /// module itself if it is a normal module.
1733     fn get_nearest_normal_module_parent_or_self(&mut self, module_: Rc<Module>)
1734                                                 -> Rc<Module> {
1735         match module_.kind.get() {
1736             NormalModuleKind => return module_,
1737             TraitModuleKind |
1738             EnumModuleKind |
1739             TypeModuleKind |
1740             AnonymousModuleKind => {
1741                 match self.get_nearest_normal_module_parent(module_.clone()) {
1742                     None => module_,
1743                     Some(new_module) => new_module
1744                 }
1745             }
1746         }
1747     }
1748
1749     /// Resolves a "module prefix". A module prefix is one or both of (a) `self::`;
1750     /// (b) some chain of `super::`.
1751     /// grammar: (SELF MOD_SEP ) ? (SUPER MOD_SEP) *
1752     fn resolve_module_prefix(&mut self,
1753                              module_: Rc<Module>,
1754                              module_path: &[Name])
1755                                  -> ResolveResult<ModulePrefixResult> {
1756         // Start at the current module if we see `self` or `super`, or at the
1757         // top of the crate otherwise.
1758         let mut i = match &*module_path[0].as_str() {
1759             "self" => 1,
1760             "super" => 0,
1761             _ => return Success(NoPrefixFound),
1762         };
1763         let mut containing_module = self.get_nearest_normal_module_parent_or_self(module_);
1764
1765         // Now loop through all the `super`s we find.
1766         while i < module_path.len() && "super" == module_path[i].as_str() {
1767             debug!("(resolving module prefix) resolving `super` at {}",
1768                    module_to_string(&*containing_module));
1769             match self.get_nearest_normal_module_parent(containing_module) {
1770                 None => return Failed(None),
1771                 Some(new_module) => {
1772                     containing_module = new_module;
1773                     i += 1;
1774                 }
1775             }
1776         }
1777
1778         debug!("(resolving module prefix) finished resolving prefix at {}",
1779                module_to_string(&*containing_module));
1780
1781         return Success(PrefixFound(containing_module, i));
1782     }
1783
1784     /// Attempts to resolve the supplied name in the given module for the
1785     /// given namespace. If successful, returns the target corresponding to
1786     /// the name.
1787     ///
1788     /// The boolean returned on success is an indicator of whether this lookup
1789     /// passed through a public re-export proxy.
1790     fn resolve_name_in_module(&mut self,
1791                               module_: Rc<Module>,
1792                               name: Name,
1793                               namespace: Namespace,
1794                               name_search_type: NameSearchType,
1795                               allow_private_imports: bool)
1796                               -> ResolveResult<(Target, bool)> {
1797         debug!("(resolving name in module) resolving `{}` in `{}`",
1798                name,
1799                module_to_string(&*module_));
1800
1801         // First, check the direct children of the module.
1802         build_reduced_graph::populate_module_if_necessary(self, &module_);
1803
1804         match module_.children.borrow().get(&name) {
1805             Some(name_bindings)
1806                     if name_bindings.defined_in_namespace(namespace) => {
1807                 debug!("(resolving name in module) found node as child");
1808                 return Success((Target::new(module_.clone(),
1809                                             name_bindings.clone(),
1810                                             Shadowable::Never),
1811                                false));
1812             }
1813             Some(_) | None => {
1814                 // Continue.
1815             }
1816         }
1817
1818         // Next, check the module's imports if necessary.
1819
1820         // If this is a search of all imports, we should be done with glob
1821         // resolution at this point.
1822         if name_search_type == PathSearch {
1823             assert_eq!(module_.glob_count.get(), 0);
1824         }
1825
1826         // Check the list of resolved imports.
1827         match module_.import_resolutions.borrow().get(&name) {
1828             Some(import_resolution) if allow_private_imports ||
1829                                        import_resolution.is_public => {
1830
1831                 if import_resolution.is_public &&
1832                         import_resolution.outstanding_references != 0 {
1833                     debug!("(resolving name in module) import \
1834                            unresolved; bailing out");
1835                     return Indeterminate;
1836                 }
1837                 match import_resolution.target_for_namespace(namespace) {
1838                     None => {
1839                         debug!("(resolving name in module) name found, \
1840                                 but not in namespace {:?}",
1841                                namespace);
1842                     }
1843                     Some(target) => {
1844                         debug!("(resolving name in module) resolved to \
1845                                 import");
1846                         // track used imports and extern crates as well
1847                         let id = import_resolution.id(namespace);
1848                         self.used_imports.insert((id, namespace));
1849                         self.record_import_use(id, name);
1850                         if let Some(DefId{krate: kid, ..}) = target.target_module.def_id.get() {
1851                             self.used_crates.insert(kid);
1852                         }
1853                         return Success((target, true));
1854                     }
1855                 }
1856             }
1857             Some(..) | None => {} // Continue.
1858         }
1859
1860         // Finally, search through external children.
1861         if namespace == TypeNS {
1862             // FIXME (21114): In principle unclear `child` *has* to be lifted.
1863             let child = module_.external_module_children.borrow().get(&name).cloned();
1864             if let Some(module) = child {
1865                 let name_bindings =
1866                     Rc::new(Resolver::create_name_bindings_from_module(module));
1867                 return Success((Target::new(module_,
1868                                             name_bindings,
1869                                             Shadowable::Never),
1870                                 false));
1871             }
1872         }
1873
1874         // We're out of luck.
1875         debug!("(resolving name in module) failed to resolve `{}`",
1876                name);
1877         return Failed(None);
1878     }
1879
1880     fn report_unresolved_imports(&mut self, module_: Rc<Module>) {
1881         let index = module_.resolved_import_count.get();
1882         let imports = module_.imports.borrow();
1883         let import_count = imports.len();
1884         if index != import_count {
1885             resolve_error(self,
1886                           (*imports)[index].span,
1887                           ResolutionError::UnresolvedImport(None));
1888         }
1889
1890         // Descend into children and anonymous children.
1891         build_reduced_graph::populate_module_if_necessary(self, &module_);
1892
1893         for (_, child_node) in module_.children.borrow().iter() {
1894             match child_node.get_module_if_available() {
1895                 None => {
1896                     // Continue.
1897                 }
1898                 Some(child_module) => {
1899                     self.report_unresolved_imports(child_module);
1900                 }
1901             }
1902         }
1903
1904         for (_, module_) in module_.anonymous_children.borrow().iter() {
1905             self.report_unresolved_imports(module_.clone());
1906         }
1907     }
1908
1909     // AST resolution
1910     //
1911     // We maintain a list of value ribs and type ribs.
1912     //
1913     // Simultaneously, we keep track of the current position in the module
1914     // graph in the `current_module` pointer. When we go to resolve a name in
1915     // the value or type namespaces, we first look through all the ribs and
1916     // then query the module graph. When we resolve a name in the module
1917     // namespace, we can skip all the ribs (since nested modules are not
1918     // allowed within blocks in Rust) and jump straight to the current module
1919     // graph node.
1920     //
1921     // Named implementations are handled separately. When we find a method
1922     // call, we consult the module node to find all of the implementations in
1923     // scope. This information is lazily cached in the module node. We then
1924     // generate a fake "implementation scope" containing all the
1925     // implementations thus found, for compatibility with old resolve pass.
1926
1927     fn with_scope<F>(&mut self, name: Option<Name>, f: F) where
1928         F: FnOnce(&mut Resolver),
1929     {
1930         let orig_module = self.current_module.clone();
1931
1932         // Move down in the graph.
1933         match name {
1934             None => {
1935                 // Nothing to do.
1936             }
1937             Some(name) => {
1938                 build_reduced_graph::populate_module_if_necessary(self, &orig_module);
1939
1940                 match orig_module.children.borrow().get(&name) {
1941                     None => {
1942                         debug!("!!! (with scope) didn't find `{}` in `{}`",
1943                                name,
1944                                module_to_string(&*orig_module));
1945                     }
1946                     Some(name_bindings) => {
1947                         match (*name_bindings).get_module_if_available() {
1948                             None => {
1949                                 debug!("!!! (with scope) didn't find module \
1950                                         for `{}` in `{}`",
1951                                        name,
1952                                        module_to_string(&*orig_module));
1953                             }
1954                             Some(module_) => {
1955                                 self.current_module = module_;
1956                             }
1957                         }
1958                     }
1959                 }
1960             }
1961         }
1962
1963         f(self);
1964
1965         self.current_module = orig_module;
1966     }
1967
1968     /// Wraps the given definition in the appropriate number of `DefUpvar`
1969     /// wrappers.
1970     fn upvarify(&self,
1971                 ribs: &[Rib],
1972                 def_like: DefLike,
1973                 span: Span)
1974                 -> Option<DefLike> {
1975         let mut def = match def_like {
1976             DlDef(def) => def,
1977             _ => return Some(def_like)
1978         };
1979         match def {
1980             DefUpvar(..) => {
1981                 self.session.span_bug(span,
1982                     &format!("unexpected {:?} in bindings", def))
1983             }
1984             DefLocal(node_id) => {
1985                 for rib in ribs {
1986                     match rib.kind {
1987                         NormalRibKind => {
1988                             // Nothing to do. Continue.
1989                         }
1990                         ClosureRibKind(function_id) => {
1991                             let prev_def = def;
1992
1993                             let mut seen = self.freevars_seen.borrow_mut();
1994                             let seen = seen.entry(function_id).or_insert_with(|| NodeMap());
1995                             if let Some(&index) = seen.get(&node_id) {
1996                                 def = DefUpvar(node_id, index, function_id);
1997                                 continue;
1998                             }
1999                             let mut freevars = self.freevars.borrow_mut();
2000                             let vec = freevars.entry(function_id)
2001                                               .or_insert_with(|| vec![]);
2002                             let depth = vec.len();
2003                             vec.push(Freevar { def: prev_def, span: span });
2004
2005                             def = DefUpvar(node_id, depth, function_id);
2006                             seen.insert(node_id, depth);
2007                         }
2008                         ItemRibKind | MethodRibKind => {
2009                             // This was an attempt to access an upvar inside a
2010                             // named function item. This is not allowed, so we
2011                             // report an error.
2012                             resolve_error(
2013                                 self,
2014                                 span,
2015                                 ResolutionError::CannotCaptureDynamicEnvironmentInFnItem
2016                             );
2017                             return None;
2018                         }
2019                         ConstantItemRibKind => {
2020                             // Still doesn't deal with upvars
2021                             resolve_error(
2022                                 self,
2023                                 span,
2024                                 ResolutionError::AttemptToUseNonConstantValueInConstant
2025                             );
2026                             return None;
2027                         }
2028                     }
2029                 }
2030             }
2031             DefTyParam(..) | DefSelfTy(..) => {
2032                 for rib in ribs {
2033                     match rib.kind {
2034                         NormalRibKind | MethodRibKind | ClosureRibKind(..) => {
2035                             // Nothing to do. Continue.
2036                         }
2037                         ItemRibKind => {
2038                             // This was an attempt to use a type parameter outside
2039                             // its scope.
2040
2041                             resolve_error(self,
2042                                           span,
2043                                           ResolutionError::TypeParametersFromOuterFunction);
2044                             return None;
2045                         }
2046                         ConstantItemRibKind => {
2047                             // see #9186
2048                             resolve_error(self, span, ResolutionError::OuterTypeParameterContext);
2049                             return None;
2050                         }
2051                     }
2052                 }
2053             }
2054             _ => {}
2055         }
2056         Some(DlDef(def))
2057     }
2058
2059     /// Searches the current set of local scopes and
2060     /// applies translations for closures.
2061     fn search_ribs(&self,
2062                    ribs: &[Rib],
2063                    name: Name,
2064                    span: Span)
2065                    -> Option<DefLike> {
2066         // FIXME #4950: Try caching?
2067
2068         for (i, rib) in ribs.iter().enumerate().rev() {
2069             if let Some(def_like) = rib.bindings.get(&name).cloned() {
2070                 return self.upvarify(&ribs[i + 1..], def_like, span);
2071             }
2072         }
2073
2074         None
2075     }
2076
2077     /// Searches the current set of local scopes for labels.
2078     /// Stops after meeting a closure.
2079     fn search_label(&self, name: Name) -> Option<DefLike> {
2080         for rib in self.label_ribs.iter().rev() {
2081             match rib.kind {
2082                 NormalRibKind => {
2083                     // Continue
2084                 }
2085                 _ => {
2086                     // Do not resolve labels across function boundary
2087                     return None
2088                 }
2089             }
2090             let result = rib.bindings.get(&name).cloned();
2091             if result.is_some() {
2092                 return result
2093             }
2094         }
2095         None
2096     }
2097
2098     fn resolve_crate(&mut self, krate: &hir::Crate) {
2099         debug!("(resolving crate) starting");
2100
2101         visit::walk_crate(self, krate);
2102     }
2103
2104     fn check_if_primitive_type_name(&self, name: Name, span: Span) {
2105         if let Some(_) = self.primitive_type_table.primitive_types.get(&name) {
2106             span_err!(self.session, span, E0317,
2107                 "user-defined types or type parameters cannot shadow the primitive types");
2108         }
2109     }
2110
2111     fn resolve_item(&mut self, item: &Item) {
2112         let name = item.ident.name;
2113
2114         debug!("(resolving item) resolving {}",
2115                name);
2116
2117         match item.node {
2118             ItemEnum(_, ref generics) |
2119             ItemTy(_, ref generics) |
2120             ItemStruct(_, ref generics) => {
2121                 self.check_if_primitive_type_name(name, item.span);
2122
2123                 self.with_type_parameter_rib(HasTypeParameters(generics,
2124                                                                TypeSpace,
2125                                                                ItemRibKind),
2126                                              |this| visit::walk_item(this, item));
2127             }
2128             ItemFn(_, _, _, _, ref generics, _) => {
2129                 self.with_type_parameter_rib(HasTypeParameters(generics,
2130                                                                FnSpace,
2131                                                                ItemRibKind),
2132                                              |this| visit::walk_item(this, item));
2133             }
2134
2135             ItemDefaultImpl(_, ref trait_ref) => {
2136                 self.with_optional_trait_ref(Some(trait_ref), |_, _| {});
2137             }
2138             ItemImpl(_,
2139                      _,
2140                      ref generics,
2141                      ref opt_trait_ref,
2142                      ref self_type,
2143                      ref impl_items) => {
2144                 self.resolve_implementation(generics,
2145                                             opt_trait_ref,
2146                                             &**self_type,
2147                                             item.id,
2148                                             &impl_items[..]);
2149             }
2150
2151             ItemTrait(_, ref generics, ref bounds, ref trait_items) => {
2152                 self.check_if_primitive_type_name(name, item.span);
2153
2154                 // Create a new rib for the trait-wide type parameters.
2155                 self.with_type_parameter_rib(HasTypeParameters(generics,
2156                                                                TypeSpace,
2157                                                                ItemRibKind),
2158                                              |this| {
2159                     this.with_self_rib(DefSelfTy(Some(DefId::local(item.id)), None), |this| {
2160                         this.visit_generics(generics);
2161                         visit::walk_ty_param_bounds_helper(this, bounds);
2162
2163                         for trait_item in trait_items {
2164                             match trait_item.node {
2165                                 hir::ConstTraitItem(_, ref default) => {
2166                                     // Only impose the restrictions of
2167                                     // ConstRibKind if there's an actual constant
2168                                     // expression in a provided default.
2169                                     if default.is_some() {
2170                                         this.with_constant_rib(|this| {
2171                                             visit::walk_trait_item(this, trait_item)
2172                                         });
2173                                     } else {
2174                                         visit::walk_trait_item(this, trait_item)
2175                                     }
2176                                 }
2177                                 hir::MethodTraitItem(ref sig, _) => {
2178                                     let type_parameters =
2179                                         HasTypeParameters(&sig.generics,
2180                                                           FnSpace,
2181                                                           MethodRibKind);
2182                                     this.with_type_parameter_rib(type_parameters, |this| {
2183                                         visit::walk_trait_item(this, trait_item)
2184                                     });
2185                                 }
2186                                 hir::TypeTraitItem(..) => {
2187                                     this.check_if_primitive_type_name(trait_item.ident.name,
2188                                                                       trait_item.span);
2189                                     this.with_type_parameter_rib(NoTypeParameters, |this| {
2190                                         visit::walk_trait_item(this, trait_item)
2191                                     });
2192                                 }
2193                             };
2194                         }
2195                     });
2196                 });
2197             }
2198
2199             ItemMod(_) | ItemForeignMod(_) => {
2200                 self.with_scope(Some(name), |this| {
2201                     visit::walk_item(this, item);
2202                 });
2203             }
2204
2205             ItemConst(..) | ItemStatic(..) => {
2206                 self.with_constant_rib(|this| {
2207                     visit::walk_item(this, item);
2208                 });
2209             }
2210
2211             ItemUse(ref view_path) => {
2212                 // check for imports shadowing primitive types
2213                 let check_rename = |id, ident: Ident| {
2214                     match self.def_map.borrow().get(&id).map(|d| d.full_def()) {
2215                         Some(DefTy(..)) | Some(DefStruct(..)) | Some(DefTrait(..)) | None => {
2216                             self.check_if_primitive_type_name(ident.name, item.span);
2217                         }
2218                         _ => {}
2219                     }
2220                 };
2221
2222                 match view_path.node {
2223                     hir::ViewPathSimple(ident, _) => {
2224                         check_rename(item.id, ident);
2225                     }
2226                     hir::ViewPathList(_, ref items) => {
2227                         for item in items {
2228                             if let Some(ident) = item.node.rename() {
2229                                 check_rename(item.node.id(), ident);
2230                             }
2231                         }
2232                     }
2233                     _ => {}
2234                 }
2235             }
2236
2237             ItemExternCrate(_) => {
2238                 // do nothing, these are just around to be encoded
2239             }
2240         }
2241     }
2242
2243     fn with_type_parameter_rib<F>(&mut self, type_parameters: TypeParameters, f: F) where
2244         F: FnOnce(&mut Resolver),
2245     {
2246         match type_parameters {
2247             HasTypeParameters(generics, space, rib_kind) => {
2248                 let mut function_type_rib = Rib::new(rib_kind);
2249                 let mut seen_bindings = HashSet::new();
2250                 for (index, type_parameter) in generics.ty_params.iter().enumerate() {
2251                     let name = type_parameter.ident.name;
2252                     debug!("with_type_parameter_rib: {}", type_parameter.id);
2253
2254                     if seen_bindings.contains(&name) {
2255                         resolve_error(self,
2256                                       type_parameter.span,
2257                                       ResolutionError::NameAlreadyUsedInTypeParameterList(
2258                                         name)
2259                         );
2260                     }
2261                     seen_bindings.insert(name);
2262
2263                     // plain insert (no renaming)
2264                     function_type_rib.bindings.insert(name,
2265                         DlDef(DefTyParam(space,
2266                                          index as u32,
2267                                          DefId::local(type_parameter.id),
2268                                          name)));
2269                 }
2270                 self.type_ribs.push(function_type_rib);
2271             }
2272
2273             NoTypeParameters => {
2274                 // Nothing to do.
2275             }
2276         }
2277
2278         f(self);
2279
2280         match type_parameters {
2281             HasTypeParameters(..) => { if !self.resolved { self.type_ribs.pop(); } }
2282             NoTypeParameters => { }
2283         }
2284     }
2285
2286     fn with_label_rib<F>(&mut self, f: F) where
2287         F: FnOnce(&mut Resolver),
2288     {
2289         self.label_ribs.push(Rib::new(NormalRibKind));
2290         f(self);
2291         if !self.resolved {
2292             self.label_ribs.pop();
2293         }
2294     }
2295
2296     fn with_constant_rib<F>(&mut self, f: F) where
2297         F: FnOnce(&mut Resolver),
2298     {
2299         self.value_ribs.push(Rib::new(ConstantItemRibKind));
2300         self.type_ribs.push(Rib::new(ConstantItemRibKind));
2301         f(self);
2302         if !self.resolved {
2303             self.type_ribs.pop();
2304             self.value_ribs.pop();
2305         }
2306     }
2307
2308     fn resolve_function(&mut self,
2309                         rib_kind: RibKind,
2310                         declaration: &FnDecl,
2311                         block: &Block) {
2312         // Create a value rib for the function.
2313         self.value_ribs.push(Rib::new(rib_kind));
2314
2315         // Create a label rib for the function.
2316         self.label_ribs.push(Rib::new(rib_kind));
2317
2318         // Add each argument to the rib.
2319         let mut bindings_list = HashMap::new();
2320         for argument in &declaration.inputs {
2321             self.resolve_pattern(&*argument.pat,
2322                                  ArgumentIrrefutableMode,
2323                                  &mut bindings_list);
2324
2325             self.visit_ty(&*argument.ty);
2326
2327             debug!("(resolving function) recorded argument");
2328         }
2329         visit::walk_fn_ret_ty(self, &declaration.output);
2330
2331         // Resolve the function body.
2332         self.visit_block(&*block);
2333
2334         debug!("(resolving function) leaving function");
2335
2336         if !self.resolved {
2337             self.label_ribs.pop();
2338             self.value_ribs.pop();
2339         }
2340     }
2341
2342     fn resolve_trait_reference(&mut self,
2343                                id: NodeId,
2344                                trait_path: &Path,
2345                                path_depth: usize)
2346                                -> Result<PathResolution, ()> {
2347         if let Some(path_res) = self.resolve_path(id, trait_path, path_depth, TypeNS, true) {
2348             if let DefTrait(_) = path_res.base_def {
2349                 debug!("(resolving trait) found trait def: {:?}", path_res);
2350                 Ok(path_res)
2351             } else {
2352                 resolve_error(self,
2353                               trait_path.span,
2354                               ResolutionError::IsNotATrait(&*path_names_to_string(trait_path,
2355                                                                                    path_depth))
2356                              );
2357
2358                 // If it's a typedef, give a note
2359                 if let DefTy(..) = path_res.base_def {
2360                     self.session.span_note(trait_path.span,
2361                                            "`type` aliases cannot be used for traits");
2362                 }
2363                 Err(())
2364             }
2365         } else {
2366             resolve_error(self,
2367                           trait_path.span,
2368                           ResolutionError::UndeclaredTraitName(
2369                             &*path_names_to_string(trait_path, path_depth))
2370                          );
2371             Err(())
2372         }
2373     }
2374
2375     fn resolve_generics(&mut self, generics: &Generics) {
2376         for type_parameter in generics.ty_params.iter() {
2377             self.check_if_primitive_type_name(type_parameter.ident.name, type_parameter.span);
2378         }
2379         for predicate in &generics.where_clause.predicates {
2380             match predicate {
2381                 &hir::WherePredicate::BoundPredicate(_) |
2382                 &hir::WherePredicate::RegionPredicate(_) => {}
2383                 &hir::WherePredicate::EqPredicate(ref eq_pred) => {
2384                     let path_res = self.resolve_path(eq_pred.id, &eq_pred.path, 0, TypeNS, true);
2385                     if let Some(PathResolution { base_def: DefTyParam(..), .. }) = path_res {
2386                         self.record_def(eq_pred.id, path_res.unwrap());
2387                     } else {
2388                         resolve_error(self,
2389                                       eq_pred.span,
2390                                       ResolutionError::UndeclaredAssociatedType);
2391                     }
2392                 }
2393             }
2394         }
2395         visit::walk_generics(self, generics);
2396     }
2397
2398     fn with_current_self_type<T, F>(&mut self, self_type: &Ty, f: F) -> T
2399         where F: FnOnce(&mut Resolver) -> T
2400     {
2401         // Handle nested impls (inside fn bodies)
2402         let previous_value = replace(&mut self.current_self_type, Some(self_type.clone()));
2403         let result = f(self);
2404         self.current_self_type = previous_value;
2405         result
2406     }
2407
2408     fn with_optional_trait_ref<T, F>(&mut self,
2409                                      opt_trait_ref: Option<&TraitRef>,
2410                                      f: F)
2411                                      -> T
2412         where F: FnOnce(&mut Resolver, Option<DefId>) -> T
2413     {
2414         let mut new_val = None;
2415         let mut new_id = None;
2416         if let Some(trait_ref) = opt_trait_ref {
2417             if let Ok(path_res) = self.resolve_trait_reference(trait_ref.ref_id,
2418                                                                &trait_ref.path, 0) {
2419                 assert!(path_res.depth == 0);
2420                 self.record_def(trait_ref.ref_id, path_res);
2421                 new_val = Some((path_res.base_def.def_id(), trait_ref.clone()));
2422                 new_id = Some(path_res.base_def.def_id());
2423             }
2424             visit::walk_trait_ref(self, trait_ref);
2425         }
2426         let original_trait_ref = replace(&mut self.current_trait_ref, new_val);
2427         let result = f(self, new_id);
2428         self.current_trait_ref = original_trait_ref;
2429         result
2430     }
2431
2432     fn with_self_rib<F>(&mut self, self_def: Def, f: F)
2433         where F: FnOnce(&mut Resolver)
2434     {
2435         let mut self_type_rib = Rib::new(NormalRibKind);
2436
2437         // plain insert (no renaming, types are not currently hygienic....)
2438         let name = special_names::type_self;
2439         self_type_rib.bindings.insert(name, DlDef(self_def));
2440         self.type_ribs.push(self_type_rib);
2441         f(self);
2442         if !self.resolved {
2443             self.type_ribs.pop();
2444         }
2445     }
2446
2447     fn resolve_implementation(&mut self,
2448                               generics: &Generics,
2449                               opt_trait_reference: &Option<TraitRef>,
2450                               self_type: &Ty,
2451                               item_id: NodeId,
2452                               impl_items: &[P<ImplItem>]) {
2453         // If applicable, create a rib for the type parameters.
2454         self.with_type_parameter_rib(HasTypeParameters(generics,
2455                                                        TypeSpace,
2456                                                        ItemRibKind),
2457                                      |this| {
2458             // Resolve the type parameters.
2459             this.visit_generics(generics);
2460
2461             // Resolve the trait reference, if necessary.
2462             this.with_optional_trait_ref(opt_trait_reference.as_ref(), |this, trait_id| {
2463                 // Resolve the self type.
2464                 this.visit_ty(self_type);
2465
2466                 this.with_self_rib(DefSelfTy(trait_id, Some((item_id, self_type.id))), |this| {
2467                     this.with_current_self_type(self_type, |this| {
2468                         for impl_item in impl_items {
2469                             match impl_item.node {
2470                                 ConstImplItem(..) => {
2471                                     // If this is a trait impl, ensure the const
2472                                     // exists in trait
2473                                     this.check_trait_item(impl_item.ident.name,
2474                                                           impl_item.span,
2475                                         |n, s| ResolutionError::ConstNotMemberOfTrait(n, s));
2476                                     this.with_constant_rib(|this| {
2477                                         visit::walk_impl_item(this, impl_item);
2478                                     });
2479                                 }
2480                                 MethodImplItem(ref sig, _) => {
2481                                     // If this is a trait impl, ensure the method
2482                                     // exists in trait
2483                                     this.check_trait_item(impl_item.ident.name,
2484                                                           impl_item.span,
2485                                         |n, s| ResolutionError::MethodNotMemberOfTrait(n, s));
2486
2487                                     // We also need a new scope for the method-
2488                                     // specific type parameters.
2489                                     let type_parameters =
2490                                         HasTypeParameters(&sig.generics,
2491                                                           FnSpace,
2492                                                           MethodRibKind);
2493                                     this.with_type_parameter_rib(type_parameters, |this| {
2494                                         visit::walk_impl_item(this, impl_item);
2495                                     });
2496                                 }
2497                                 TypeImplItem(ref ty) => {
2498                                     // If this is a trait impl, ensure the type
2499                                     // exists in trait
2500                                     this.check_trait_item(impl_item.ident.name,
2501                                                           impl_item.span,
2502                                         |n, s| ResolutionError::TypeNotMemberOfTrait(n, s));
2503
2504                                     this.visit_ty(ty);
2505                                 }
2506                             }
2507                         }
2508                     });
2509                 });
2510             });
2511         });
2512     }
2513
2514     fn check_trait_item<F>(&self, name: Name, span: Span, err: F)
2515         where F: FnOnce(Name, &str) -> ResolutionError {
2516         // If there is a TraitRef in scope for an impl, then the method must be in the trait.
2517         if let Some((did, ref trait_ref)) = self.current_trait_ref {
2518             if !self.trait_item_map.contains_key(&(name, did)) {
2519                 let path_str = path_names_to_string(&trait_ref.path, 0);
2520                 resolve_error(self,
2521                               span,
2522                               err(name, &*path_str));
2523             }
2524         }
2525     }
2526
2527     fn resolve_local(&mut self, local: &Local) {
2528         // Resolve the type.
2529         visit::walk_ty_opt(self, &local.ty);
2530
2531         // Resolve the initializer.
2532         visit::walk_expr_opt(self, &local.init);
2533
2534         // Resolve the pattern.
2535         self.resolve_pattern(&*local.pat,
2536                              LocalIrrefutableMode,
2537                              &mut HashMap::new());
2538     }
2539
2540     // build a map from pattern identifiers to binding-info's.
2541     // this is done hygienically. This could arise for a macro
2542     // that expands into an or-pattern where one 'x' was from the
2543     // user and one 'x' came from the macro.
2544     fn binding_mode_map(&mut self, pat: &Pat) -> BindingMap {
2545         let mut result = HashMap::new();
2546         pat_bindings(&self.def_map, pat, |binding_mode, _id, sp, path1| {
2547             let name = mtwt::resolve(path1.node);
2548             result.insert(name, BindingInfo {
2549                 span: sp,
2550                 binding_mode: binding_mode
2551             });
2552         });
2553         return result;
2554     }
2555
2556     // check that all of the arms in an or-pattern have exactly the
2557     // same set of bindings, with the same binding modes for each.
2558     fn check_consistent_bindings(&mut self, arm: &Arm) {
2559         if arm.pats.is_empty() {
2560             return
2561         }
2562         let map_0 = self.binding_mode_map(&*arm.pats[0]);
2563         for (i, p) in arm.pats.iter().enumerate() {
2564             let map_i = self.binding_mode_map(&**p);
2565
2566             for (&key, &binding_0) in &map_0 {
2567                 match map_i.get(&key) {
2568                   None => {
2569                     resolve_error(self,
2570                                   p.span,
2571                                   ResolutionError::VariableNotBoundInPattern(key,
2572                                                                               i + 1));
2573                   }
2574                   Some(binding_i) => {
2575                     if binding_0.binding_mode != binding_i.binding_mode {
2576                         resolve_error(self,
2577                                       binding_i.span,
2578                                       ResolutionError::VariableBoundWithDifferentMode(key,
2579                                                                                        i + 1)
2580                                      );
2581                     }
2582                   }
2583                 }
2584             }
2585
2586             for (&key, &binding) in &map_i {
2587                 if !map_0.contains_key(&key) {
2588                     resolve_error(self,
2589                                   binding.span,
2590                                   ResolutionError::VariableNotBoundInParentPattern(key,
2591                                                                                     i + 1));
2592                 }
2593             }
2594         }
2595     }
2596
2597     fn resolve_arm(&mut self, arm: &Arm) {
2598         self.value_ribs.push(Rib::new(NormalRibKind));
2599
2600         let mut bindings_list = HashMap::new();
2601         for pattern in &arm.pats {
2602             self.resolve_pattern(&**pattern, RefutableMode, &mut bindings_list);
2603         }
2604
2605         // This has to happen *after* we determine which
2606         // pat_idents are variants
2607         self.check_consistent_bindings(arm);
2608
2609         visit::walk_expr_opt(self, &arm.guard);
2610         self.visit_expr(&*arm.body);
2611
2612         if !self.resolved {
2613             self.value_ribs.pop();
2614         }
2615     }
2616
2617     fn resolve_block(&mut self, block: &Block) {
2618         debug!("(resolving block) entering block");
2619         self.value_ribs.push(Rib::new(NormalRibKind));
2620
2621         // Move down in the graph, if there's an anonymous module rooted here.
2622         let orig_module = self.current_module.clone();
2623         match orig_module.anonymous_children.borrow().get(&block.id) {
2624             None => { /* Nothing to do. */ }
2625             Some(anonymous_module) => {
2626                 debug!("(resolving block) found anonymous module, moving \
2627                         down");
2628                 self.current_module = anonymous_module.clone();
2629             }
2630         }
2631
2632         // Check for imports appearing after non-item statements.
2633         let mut found_non_item = false;
2634         for statement in &block.stmts {
2635             if let hir::StmtDecl(ref declaration, _) = statement.node {
2636                 if let hir::DeclItem(ref i) = declaration.node {
2637                     match i.node {
2638                         ItemExternCrate(_) | ItemUse(_) if found_non_item => {
2639                             span_err!(self.session, i.span, E0154,
2640                                 "imports are not allowed after non-item statements");
2641                         }
2642                         _ => {}
2643                     }
2644                 } else {
2645                     found_non_item = true
2646                 }
2647             } else {
2648                 found_non_item = true;
2649             }
2650         }
2651
2652         // Descend into the block.
2653         visit::walk_block(self, block);
2654
2655         // Move back up.
2656         if !self.resolved {
2657             self.current_module = orig_module;
2658             self.value_ribs.pop();
2659         }
2660         debug!("(resolving block) leaving block");
2661     }
2662
2663     fn resolve_type(&mut self, ty: &Ty) {
2664         match ty.node {
2665             TyPath(ref maybe_qself, ref path) => {
2666                 let resolution =
2667                     match self.resolve_possibly_assoc_item(ty.id,
2668                                                            maybe_qself.as_ref(),
2669                                                            path,
2670                                                            TypeNS,
2671                                                            true) {
2672                         // `<T>::a::b::c` is resolved by typeck alone.
2673                         TypecheckRequired => {
2674                             // Resolve embedded types.
2675                             visit::walk_ty(self, ty);
2676                             return;
2677                         }
2678                         ResolveAttempt(resolution) => resolution,
2679                     };
2680
2681                 // This is a path in the type namespace. Walk through scopes
2682                 // looking for it.
2683                 match resolution {
2684                     Some(def) => {
2685                         // Write the result into the def map.
2686                         debug!("(resolving type) writing resolution for `{}` \
2687                                 (id {}) = {:?}",
2688                                path_names_to_string(path, 0),
2689                                ty.id, def);
2690                         self.record_def(ty.id, def);
2691                     }
2692                     None => {
2693                         // Keep reporting some errors even if they're ignored above.
2694                         self.resolve_path(ty.id, path, 0, TypeNS, true);
2695
2696                         let kind = if maybe_qself.is_some() {
2697                             "associated type"
2698                         } else {
2699                             "type name"
2700                         };
2701
2702                         let self_type_name = special_idents::type_self.name;
2703                         let is_invalid_self_type_name =
2704                             path.segments.len() > 0 &&
2705                             maybe_qself.is_none() &&
2706                             path.segments[0].identifier.name == self_type_name;
2707                         if is_invalid_self_type_name {
2708                             resolve_error(self,
2709                                           ty.span,
2710                                           ResolutionError::SelfUsedOutsideImplOrTrait);
2711                         } else {
2712                             resolve_error(self,
2713                                           ty.span,
2714                                           ResolutionError::UseOfUndeclared(
2715                                                                     kind,
2716                                                                     &*path_names_to_string(path,
2717                                                                                            0))
2718                                          );
2719                         }
2720                     }
2721                 }
2722             }
2723             _ => {}
2724         }
2725         // Resolve embedded types.
2726         visit::walk_ty(self, ty);
2727     }
2728
2729     fn resolve_pattern(&mut self,
2730                        pattern: &Pat,
2731                        mode: PatternBindingMode,
2732                        // Maps idents to the node ID for the (outermost)
2733                        // pattern that binds them
2734                        bindings_list: &mut HashMap<Name, NodeId>) {
2735         let pat_id = pattern.id;
2736         walk_pat(pattern, |pattern| {
2737             match pattern.node {
2738                 PatIdent(binding_mode, ref path1, ref at_rhs) => {
2739                     // The meaning of PatIdent with no type parameters
2740                     // depends on whether an enum variant or unit-like struct
2741                     // with that name is in scope. The probing lookup has to
2742                     // be careful not to emit spurious errors. Only matching
2743                     // patterns (match) can match nullary variants or
2744                     // unit-like structs. For binding patterns (let
2745                     // and the LHS of @-patterns), matching such a value is
2746                     // simply disallowed (since it's rarely what you want).
2747                     let const_ok = mode == RefutableMode && at_rhs.is_none();
2748
2749                     let ident = path1.node;
2750                     let renamed = mtwt::resolve(ident);
2751
2752                     match self.resolve_bare_identifier_pattern(ident.name, pattern.span) {
2753                         FoundStructOrEnumVariant(def, lp) if const_ok => {
2754                             debug!("(resolving pattern) resolving `{}` to \
2755                                     struct or enum variant",
2756                                    renamed);
2757
2758                             self.enforce_default_binding_mode(
2759                                 pattern,
2760                                 binding_mode,
2761                                 "an enum variant");
2762                             self.record_def(pattern.id, PathResolution {
2763                                 base_def: def,
2764                                 last_private: lp,
2765                                 depth: 0
2766                             });
2767                         }
2768                         FoundStructOrEnumVariant(..) => {
2769                             resolve_error(
2770                                 self,
2771                                 pattern.span,
2772                                 ResolutionError::DeclarationShadowsEnumVariantOrUnitLikeStruct(
2773                                     renamed)
2774                             );
2775                         }
2776                         FoundConst(def, lp) if const_ok => {
2777                             debug!("(resolving pattern) resolving `{}` to \
2778                                     constant",
2779                                    renamed);
2780
2781                             self.enforce_default_binding_mode(
2782                                 pattern,
2783                                 binding_mode,
2784                                 "a constant");
2785                             self.record_def(pattern.id, PathResolution {
2786                                 base_def: def,
2787                                 last_private: lp,
2788                                 depth: 0
2789                             });
2790                         }
2791                         FoundConst(..) => {
2792                             resolve_error(
2793                                 self,
2794                                 pattern.span,
2795                                 ResolutionError::OnlyIrrefutablePatternsAllowedHere
2796                             );
2797                         }
2798                         BareIdentifierPatternUnresolved => {
2799                             debug!("(resolving pattern) binding `{}`",
2800                                    renamed);
2801
2802                             let def = DefLocal(pattern.id);
2803
2804                             // Record the definition so that later passes
2805                             // will be able to distinguish variants from
2806                             // locals in patterns.
2807
2808                             self.record_def(pattern.id, PathResolution {
2809                                 base_def: def,
2810                                 last_private: LastMod(AllPublic),
2811                                 depth: 0
2812                             });
2813
2814                             // Add the binding to the local ribs, if it
2815                             // doesn't already exist in the bindings list. (We
2816                             // must not add it if it's in the bindings list
2817                             // because that breaks the assumptions later
2818                             // passes make about or-patterns.)
2819                             if !bindings_list.contains_key(&renamed) {
2820                                 let this = &mut *self;
2821                                 let last_rib = this.value_ribs.last_mut().unwrap();
2822                                 last_rib.bindings.insert(renamed, DlDef(def));
2823                                 bindings_list.insert(renamed, pat_id);
2824                             } else if mode == ArgumentIrrefutableMode &&
2825                                     bindings_list.contains_key(&renamed) {
2826                                 // Forbid duplicate bindings in the same
2827                                 // parameter list.
2828                                 resolve_error(
2829                                     self,
2830                                     pattern.span,
2831                                     ResolutionError::IdentifierBoundMoreThanOnceInParameterList(
2832                                         &ident.name.as_str())
2833                                 );
2834                             } else if bindings_list.get(&renamed) ==
2835                                     Some(&pat_id) {
2836                                 // Then this is a duplicate variable in the
2837                                 // same disjunction, which is an error.
2838                                 resolve_error(
2839                                     self,
2840                                     pattern.span,
2841                                     ResolutionError::IdentifierBoundMoreThanOnceInSamePattern(
2842                                         &ident.name.as_str())
2843                                 );
2844                             }
2845                             // Else, not bound in the same pattern: do
2846                             // nothing.
2847                         }
2848                     }
2849                 }
2850
2851                 PatEnum(ref path, _) => {
2852                     // This must be an enum variant, struct or const.
2853                     let resolution =
2854                         match self.resolve_possibly_assoc_item(pat_id, None,
2855                                                                path, ValueNS,
2856                                                                false) {
2857                             // The below shouldn't happen because all
2858                             // qualified paths should be in PatQPath.
2859                             TypecheckRequired =>
2860                                 self.session.span_bug(
2861                                     path.span,
2862                                     "resolve_possibly_assoc_item claimed
2863                                      that a path in PatEnum requires typecheck
2864                                      to resolve, but qualified paths should be
2865                                      PatQPath"),
2866                             ResolveAttempt(resolution) => resolution,
2867                         };
2868                     if let Some(path_res) = resolution {
2869                         match path_res.base_def {
2870                             DefVariant(..) | DefStruct(..) | DefConst(..) => {
2871                                 self.record_def(pattern.id, path_res);
2872                             }
2873                             DefStatic(..) => {
2874                                 resolve_error(&self,
2875                                               path.span,
2876                                               ResolutionError::StaticVariableReference);
2877                             }
2878                             _ => {
2879                                 // If anything ends up here entirely resolved,
2880                                 // it's an error. If anything ends up here
2881                                 // partially resolved, that's OK, because it may
2882                                 // be a `T::CONST` that typeck will resolve.
2883                                 if path_res.depth == 0 {
2884                                     resolve_error(
2885                                         self,
2886                                         path.span,
2887                                         ResolutionError::NotAnEnumVariantStructOrConst(
2888                                             &path.segments
2889                                                  .last()
2890                                                  .unwrap()
2891                                                  .identifier
2892                                                  .name
2893                                                  .as_str())
2894                                     );
2895                                 } else {
2896                                     let const_name = path.segments.last().unwrap()
2897                                                          .identifier.name;
2898                                     let traits = self.get_traits_containing_item(const_name);
2899                                     self.trait_map.insert(pattern.id, traits);
2900                                     self.record_def(pattern.id, path_res);
2901                                 }
2902                             }
2903                         }
2904                     } else {
2905                         resolve_error(
2906                             self,
2907                             path.span,
2908                             ResolutionError::UnresolvedEnumVariantStructOrConst(
2909                                 &path.segments.last().unwrap().identifier.name.as_str())
2910                         );
2911                     }
2912                     visit::walk_path(self, path);
2913                 }
2914
2915                 PatQPath(ref qself, ref path) => {
2916                     // Associated constants only.
2917                     let resolution =
2918                         match self.resolve_possibly_assoc_item(pat_id, Some(qself),
2919                                                                path, ValueNS,
2920                                                                false) {
2921                             TypecheckRequired => {
2922                                 // All `<T>::CONST` should end up here, and will
2923                                 // require use of the trait map to resolve
2924                                 // during typechecking.
2925                                 let const_name = path.segments.last().unwrap()
2926                                                      .identifier.name;
2927                                 let traits = self.get_traits_containing_item(const_name);
2928                                 self.trait_map.insert(pattern.id, traits);
2929                                 visit::walk_pat(self, pattern);
2930                                 return true;
2931                             }
2932                             ResolveAttempt(resolution) => resolution,
2933                         };
2934                     if let Some(path_res) = resolution {
2935                         match path_res.base_def {
2936                             // All `<T as Trait>::CONST` should end up here, and
2937                             // have the trait already selected.
2938                             DefAssociatedConst(..) => {
2939                                 self.record_def(pattern.id, path_res);
2940                             }
2941                             _ => {
2942                                 resolve_error(
2943                                     self,
2944                                     path.span,
2945                                     ResolutionError::NotAnAssociatedConst(
2946                                         &path.segments.last().unwrap().identifier.name.as_str()
2947                                     )
2948                                 );
2949                             }
2950                         }
2951                     } else {
2952                         resolve_error(
2953                             self,
2954                             path.span,
2955                             ResolutionError::UnresolvedAssociatedConst(
2956                                 &path.segments.last().unwrap().identifier.name.as_str()
2957                             )
2958                         );
2959                     }
2960                     visit::walk_pat(self, pattern);
2961                 }
2962
2963                 PatStruct(ref path, _, _) => {
2964                     match self.resolve_path(pat_id, path, 0, TypeNS, false) {
2965                         Some(definition) => {
2966                             self.record_def(pattern.id, definition);
2967                         }
2968                         result => {
2969                             debug!("(resolving pattern) didn't find struct \
2970                                     def: {:?}", result);
2971                             resolve_error(
2972                                 self,
2973                                 path.span,
2974                                 ResolutionError::DoesNotNameAStruct(
2975                                     &*path_names_to_string(path, 0))
2976                             );
2977                         }
2978                     }
2979                     visit::walk_path(self, path);
2980                 }
2981
2982                 PatLit(_) | PatRange(..) => {
2983                     visit::walk_pat(self, pattern);
2984                 }
2985
2986                 _ => {
2987                     // Nothing to do.
2988                 }
2989             }
2990             true
2991         });
2992     }
2993
2994     fn resolve_bare_identifier_pattern(&mut self, name: Name, span: Span)
2995                                        -> BareIdentifierPatternResolution {
2996         let module = self.current_module.clone();
2997         match self.resolve_item_in_lexical_scope(module,
2998                                                  name,
2999                                                  ValueNS) {
3000             Success((target, _)) => {
3001                 debug!("(resolve bare identifier pattern) succeeded in \
3002                          finding {} at {:?}",
3003                         name,
3004                         target.bindings.value_def.borrow());
3005                 match *target.bindings.value_def.borrow() {
3006                     None => {
3007                         panic!("resolved name in the value namespace to a \
3008                               set of name bindings with no def?!");
3009                     }
3010                     Some(def) => {
3011                         // For the two success cases, this lookup can be
3012                         // considered as not having a private component because
3013                         // the lookup happened only within the current module.
3014                         match def.def {
3015                             def @ DefVariant(..) | def @ DefStruct(..) => {
3016                                 return FoundStructOrEnumVariant(def, LastMod(AllPublic));
3017                             }
3018                             def @ DefConst(..) | def @ DefAssociatedConst(..) => {
3019                                 return FoundConst(def, LastMod(AllPublic));
3020                             }
3021                             DefStatic(..) => {
3022                                 resolve_error(self,
3023                                               span,
3024                                               ResolutionError::StaticVariableReference);
3025                                 return BareIdentifierPatternUnresolved;
3026                             }
3027                             _ => {
3028                                 return BareIdentifierPatternUnresolved;
3029                             }
3030                         }
3031                     }
3032                 }
3033             }
3034
3035             Indeterminate => {
3036                 panic!("unexpected indeterminate result");
3037             }
3038             Failed(err) => {
3039                 match err {
3040                     Some((span, msg)) => {
3041                         resolve_error(self, span, ResolutionError::FailedToResolve(&*msg));
3042                     }
3043                     None => ()
3044                 }
3045
3046                 debug!("(resolve bare identifier pattern) failed to find {}",
3047                         name);
3048                 return BareIdentifierPatternUnresolved;
3049             }
3050         }
3051     }
3052
3053     /// Handles paths that may refer to associated items
3054     fn resolve_possibly_assoc_item(&mut self,
3055                                    id: NodeId,
3056                                    maybe_qself: Option<&hir::QSelf>,
3057                                    path: &Path,
3058                                    namespace: Namespace,
3059                                    check_ribs: bool)
3060                                    -> AssocItemResolveResult
3061     {
3062         let max_assoc_types;
3063
3064         match maybe_qself {
3065             Some(qself) => {
3066                 if qself.position == 0 {
3067                     return TypecheckRequired;
3068                 }
3069                 max_assoc_types = path.segments.len() - qself.position;
3070                 // Make sure the trait is valid.
3071                 let _ = self.resolve_trait_reference(id, path, max_assoc_types);
3072             }
3073             None => {
3074                 max_assoc_types = path.segments.len();
3075             }
3076         }
3077
3078         let mut resolution = self.with_no_errors(|this| {
3079             this.resolve_path(id, path, 0, namespace, check_ribs)
3080         });
3081         for depth in 1..max_assoc_types {
3082             if resolution.is_some() {
3083                 break;
3084             }
3085             self.with_no_errors(|this| {
3086                 resolution = this.resolve_path(id, path, depth,
3087                                                TypeNS, true);
3088             });
3089         }
3090         if let Some(DefMod(_)) = resolution.map(|r| r.base_def) {
3091             // A module is not a valid type or value.
3092             resolution = None;
3093         }
3094         ResolveAttempt(resolution)
3095     }
3096
3097     /// If `check_ribs` is true, checks the local definitions first; i.e.
3098     /// doesn't skip straight to the containing module.
3099     /// Skips `path_depth` trailing segments, which is also reflected in the
3100     /// returned value. See `middle::def::PathResolution` for more info.
3101     pub fn resolve_path(&mut self,
3102                         id: NodeId,
3103                         path: &Path,
3104                         path_depth: usize,
3105                         namespace: Namespace,
3106                         check_ribs: bool) -> Option<PathResolution> {
3107         let span = path.span;
3108         let segments = &path.segments[..path.segments.len()-path_depth];
3109
3110         let mk_res = |(def, lp)| PathResolution::new(def, lp, path_depth);
3111
3112         if path.global {
3113             let def = self.resolve_crate_relative_path(span, segments, namespace);
3114             return def.map(mk_res);
3115         }
3116
3117         // Try to find a path to an item in a module.
3118         let unqualified_def =
3119                 self.resolve_identifier(segments.last().unwrap().identifier,
3120                                         namespace,
3121                                         check_ribs,
3122                                         span);
3123
3124         if segments.len() <= 1 {
3125             return unqualified_def.map(mk_res);
3126         }
3127
3128         let def = self.resolve_module_relative_path(span, segments, namespace);
3129         match (def, unqualified_def) {
3130             (Some((ref d, _)), Some((ref ud, _))) if *d == *ud => {
3131                 self.session
3132                     .add_lint(lint::builtin::UNUSED_QUALIFICATIONS,
3133                               id, span,
3134                               "unnecessary qualification".to_string());
3135             }
3136             _ => {}
3137         }
3138
3139         def.map(mk_res)
3140     }
3141
3142     // Resolve a single identifier.
3143     fn resolve_identifier(&mut self,
3144                           identifier: Ident,
3145                           namespace: Namespace,
3146                           check_ribs: bool,
3147                           span: Span)
3148                           -> Option<(Def, LastPrivate)> {
3149         // First, check to see whether the name is a primitive type.
3150         if namespace == TypeNS {
3151             if let Some(&prim_ty) = self.primitive_type_table
3152                                         .primitive_types
3153                                         .get(&identifier.name) {
3154                 return Some((DefPrimTy(prim_ty), LastMod(AllPublic)));
3155             }
3156         }
3157
3158         if check_ribs {
3159             if let Some(def) = self.resolve_identifier_in_local_ribs(identifier,
3160                                                                      namespace,
3161                                                                      span) {
3162                 return Some((def, LastMod(AllPublic)));
3163             }
3164         }
3165
3166         self.resolve_item_by_name_in_lexical_scope(identifier.name, namespace)
3167     }
3168
3169     // FIXME #4952: Merge me with resolve_name_in_module?
3170     fn resolve_definition_of_name_in_module(&mut self,
3171                                             containing_module: Rc<Module>,
3172                                             name: Name,
3173                                             namespace: Namespace)
3174                                             -> NameDefinition {
3175         // First, search children.
3176         build_reduced_graph::populate_module_if_necessary(self, &containing_module);
3177
3178         match containing_module.children.borrow().get(&name) {
3179             Some(child_name_bindings) => {
3180                 match child_name_bindings.def_for_namespace(namespace) {
3181                     Some(def) => {
3182                         // Found it. Stop the search here.
3183                         let p = child_name_bindings.defined_in_public_namespace(namespace);
3184                         let lp = if p {LastMod(AllPublic)} else {
3185                             LastMod(DependsOn(def.def_id()))
3186                         };
3187                         return ChildNameDefinition(def, lp);
3188                     }
3189                     None => {}
3190                 }
3191             }
3192             None => {}
3193         }
3194
3195         // Next, search import resolutions.
3196         match containing_module.import_resolutions.borrow().get(&name) {
3197             Some(import_resolution) if import_resolution.is_public => {
3198                 if let Some(target) = (*import_resolution).target_for_namespace(namespace) {
3199                     match target.bindings.def_for_namespace(namespace) {
3200                         Some(def) => {
3201                             // Found it.
3202                             let id = import_resolution.id(namespace);
3203                             // track imports and extern crates as well
3204                             self.used_imports.insert((id, namespace));
3205                             self.record_import_use(id, name);
3206                             match target.target_module.def_id.get() {
3207                                 Some(DefId{krate: kid, ..}) => {
3208                                     self.used_crates.insert(kid);
3209                                 },
3210                                 _ => {}
3211                             }
3212                             return ImportNameDefinition(def, LastMod(AllPublic));
3213                         }
3214                         None => {
3215                             // This can happen with external impls, due to
3216                             // the imperfect way we read the metadata.
3217                         }
3218                     }
3219                 }
3220             }
3221             Some(..) | None => {} // Continue.
3222         }
3223
3224         // Finally, search through external children.
3225         if namespace == TypeNS {
3226             if let Some(module) = containing_module.external_module_children.borrow()
3227                                                    .get(&name).cloned() {
3228                 if let Some(def_id) = module.def_id.get() {
3229                     // track used crates
3230                     self.used_crates.insert(def_id.krate);
3231                     let lp = if module.is_public {LastMod(AllPublic)} else {
3232                         LastMod(DependsOn(def_id))
3233                     };
3234                     return ChildNameDefinition(DefMod(def_id), lp);
3235                 }
3236             }
3237         }
3238
3239         return NoNameDefinition;
3240     }
3241
3242     // resolve a "module-relative" path, e.g. a::b::c
3243     fn resolve_module_relative_path(&mut self,
3244                                     span: Span,
3245                                     segments: &[hir::PathSegment],
3246                                     namespace: Namespace)
3247                                     -> Option<(Def, LastPrivate)> {
3248         let module_path = segments.split_last().unwrap().1.iter()
3249                                          .map(|ps| ps.identifier.name)
3250                                          .collect::<Vec<_>>();
3251
3252         let containing_module;
3253         let last_private;
3254         let current_module = self.current_module.clone();
3255         match self.resolve_module_path(current_module,
3256                                        &module_path[..],
3257                                        UseLexicalScope,
3258                                        span,
3259                                        PathSearch) {
3260             Failed(err) => {
3261                 let (span, msg) = match err {
3262                     Some((span, msg)) => (span, msg),
3263                     None => {
3264                         let msg = format!("Use of undeclared type or module `{}`",
3265                                           names_to_string(&module_path));
3266                         (span, msg)
3267                     }
3268                 };
3269
3270                 resolve_error(self, span, ResolutionError::FailedToResolve(&*msg));
3271                 return None;
3272             }
3273             Indeterminate => panic!("indeterminate unexpected"),
3274             Success((resulting_module, resulting_last_private)) => {
3275                 containing_module = resulting_module;
3276                 last_private = resulting_last_private;
3277             }
3278         }
3279
3280         let name = segments.last().unwrap().identifier.name;
3281         let def = match self.resolve_definition_of_name_in_module(containing_module.clone(),
3282                                                                   name,
3283                                                                   namespace) {
3284             NoNameDefinition => {
3285                 // We failed to resolve the name. Report an error.
3286                 return None;
3287             }
3288             ChildNameDefinition(def, lp) | ImportNameDefinition(def, lp) => {
3289                 (def, last_private.or(lp))
3290             }
3291         };
3292         if let Some(DefId{krate: kid, ..}) = containing_module.def_id.get() {
3293             self.used_crates.insert(kid);
3294         }
3295         return Some(def);
3296     }
3297
3298     /// Invariant: This must be called only during main resolution, not during
3299     /// import resolution.
3300     fn resolve_crate_relative_path(&mut self,
3301                                    span: Span,
3302                                    segments: &[hir::PathSegment],
3303                                    namespace: Namespace)
3304                                        -> Option<(Def, LastPrivate)> {
3305         let module_path = segments.split_last().unwrap().1.iter()
3306                                          .map(|ps| ps.identifier.name)
3307                                          .collect::<Vec<_>>();
3308
3309         let root_module = self.graph_root.get_module();
3310
3311         let containing_module;
3312         let last_private;
3313         match self.resolve_module_path_from_root(root_module,
3314                                                  &module_path[..],
3315                                                  0,
3316                                                  span,
3317                                                  PathSearch,
3318                                                  LastMod(AllPublic)) {
3319             Failed(err) => {
3320                 let (span, msg) = match err {
3321                     Some((span, msg)) => (span, msg),
3322                     None => {
3323                         let msg = format!("Use of undeclared module `::{}`",
3324                                           names_to_string(&module_path[..]));
3325                         (span, msg)
3326                     }
3327                 };
3328
3329                 resolve_error(self, span, ResolutionError::FailedToResolve(&*msg));
3330                 return None;
3331             }
3332
3333             Indeterminate => {
3334                 panic!("indeterminate unexpected");
3335             }
3336
3337             Success((resulting_module, resulting_last_private)) => {
3338                 containing_module = resulting_module;
3339                 last_private = resulting_last_private;
3340             }
3341         }
3342
3343         let name = segments.last().unwrap().identifier.name;
3344         match self.resolve_definition_of_name_in_module(containing_module,
3345                                                         name,
3346                                                         namespace) {
3347             NoNameDefinition => {
3348                 // We failed to resolve the name. Report an error.
3349                 return None;
3350             }
3351             ChildNameDefinition(def, lp) | ImportNameDefinition(def, lp) => {
3352                 return Some((def, last_private.or(lp)));
3353             }
3354         }
3355     }
3356
3357     fn resolve_identifier_in_local_ribs(&mut self,
3358                                         ident: Ident,
3359                                         namespace: Namespace,
3360                                         span: Span)
3361                                         -> Option<Def> {
3362         // Check the local set of ribs.
3363         let search_result = match namespace {
3364             ValueNS => {
3365                 let renamed = mtwt::resolve(ident);
3366                 self.search_ribs(&self.value_ribs, renamed, span)
3367             }
3368             TypeNS => {
3369                 let name = ident.name;
3370                 self.search_ribs(&self.type_ribs, name, span)
3371             }
3372         };
3373
3374         match search_result {
3375             Some(DlDef(def)) => {
3376                 debug!("(resolving path in local ribs) resolved `{}` to local: {:?}",
3377                        ident,
3378                        def);
3379                 Some(def)
3380             }
3381             Some(DlField) | Some(DlImpl(_)) | None => {
3382                 None
3383             }
3384         }
3385     }
3386
3387     fn resolve_item_by_name_in_lexical_scope(&mut self,
3388                                              name: Name,
3389                                              namespace: Namespace)
3390                                             -> Option<(Def, LastPrivate)> {
3391         // Check the items.
3392         let module = self.current_module.clone();
3393         match self.resolve_item_in_lexical_scope(module,
3394                                                  name,
3395                                                  namespace) {
3396             Success((target, _)) => {
3397                 match (*target.bindings).def_for_namespace(namespace) {
3398                     None => {
3399                         // This can happen if we were looking for a type and
3400                         // found a module instead. Modules don't have defs.
3401                         debug!("(resolving item path by identifier in lexical \
3402                                  scope) failed to resolve {} after success...",
3403                                  name);
3404                         return None;
3405                     }
3406                     Some(def) => {
3407                         debug!("(resolving item path in lexical scope) \
3408                                 resolved `{}` to item",
3409                                name);
3410                         // This lookup is "all public" because it only searched
3411                         // for one identifier in the current module (couldn't
3412                         // have passed through reexports or anything like that.
3413                         return Some((def, LastMod(AllPublic)));
3414                     }
3415                 }
3416             }
3417             Indeterminate => {
3418                 panic!("unexpected indeterminate result");
3419             }
3420             Failed(err) => {
3421                 debug!("(resolving item path by identifier in lexical scope) \
3422                          failed to resolve {}", name);
3423
3424                 if let Some((span, msg)) = err {
3425                     resolve_error(self, span, ResolutionError::FailedToResolve(&*msg))
3426                 }
3427
3428                 return None;
3429             }
3430         }
3431     }
3432
3433     fn with_no_errors<T, F>(&mut self, f: F) -> T where
3434         F: FnOnce(&mut Resolver) -> T,
3435     {
3436         self.emit_errors = false;
3437         let rs = f(self);
3438         self.emit_errors = true;
3439         rs
3440     }
3441
3442     fn find_fallback_in_self_type(&mut self, name: Name) -> FallbackSuggestion {
3443         fn extract_path_and_node_id(t: &Ty, allow: FallbackChecks)
3444                                                     -> Option<(Path, NodeId, FallbackChecks)> {
3445             match t.node {
3446                 TyPath(None, ref path) => Some((path.clone(), t.id, allow)),
3447                 TyPtr(ref mut_ty) => extract_path_and_node_id(&*mut_ty.ty, OnlyTraitAndStatics),
3448                 TyRptr(_, ref mut_ty) => extract_path_and_node_id(&*mut_ty.ty, allow),
3449                 // This doesn't handle the remaining `Ty` variants as they are not
3450                 // that commonly the self_type, it might be interesting to provide
3451                 // support for those in future.
3452                 _ => None,
3453             }
3454         }
3455
3456         fn get_module(this: &mut Resolver, span: Span, name_path: &[ast::Name])
3457                             -> Option<Rc<Module>> {
3458             let root = this.current_module.clone();
3459             let last_name = name_path.last().unwrap();
3460
3461             if name_path.len() == 1 {
3462                 match this.primitive_type_table.primitive_types.get(last_name) {
3463                     Some(_) => None,
3464                     None => {
3465                         match this.current_module.children.borrow().get(last_name) {
3466                             Some(child) => child.get_module_if_available(),
3467                             None => None
3468                         }
3469                     }
3470                 }
3471             } else {
3472                 match this.resolve_module_path(root,
3473                                                &name_path[..],
3474                                                UseLexicalScope,
3475                                                span,
3476                                                PathSearch) {
3477                     Success((module, _)) => Some(module),
3478                     _ => None
3479                 }
3480             }
3481         }
3482
3483         fn is_static_method(this: &Resolver, did: DefId) -> bool {
3484             if did.is_local() {
3485                 let sig = match this.ast_map.get(did.node) {
3486                     hir_map::NodeTraitItem(trait_item) => match trait_item.node {
3487                         hir::MethodTraitItem(ref sig, _) => sig,
3488                         _ => return false
3489                     },
3490                     hir_map::NodeImplItem(impl_item) => match impl_item.node {
3491                         hir::MethodImplItem(ref sig, _) => sig,
3492                         _ => return false
3493                     },
3494                     _ => return false
3495                 };
3496                 sig.explicit_self.node == hir::SelfStatic
3497             } else {
3498                 csearch::is_static_method(&this.session.cstore, did)
3499             }
3500         }
3501
3502         let (path, node_id, allowed) = match self.current_self_type {
3503             Some(ref ty) => match extract_path_and_node_id(ty, Everything) {
3504                 Some(x) => x,
3505                 None => return NoSuggestion,
3506             },
3507             None => return NoSuggestion,
3508         };
3509
3510         if allowed == Everything {
3511             // Look for a field with the same name in the current self_type.
3512             match self.def_map.borrow().get(&node_id).map(|d| d.full_def()) {
3513                 Some(DefTy(did, _)) |
3514                 Some(DefStruct(did)) |
3515                 Some(DefVariant(_, did, _)) => match self.structs.get(&did) {
3516                     None => {}
3517                     Some(fields) => {
3518                         if fields.iter().any(|&field_name| name == field_name) {
3519                             return Field;
3520                         }
3521                     }
3522                 },
3523                 _ => {} // Self type didn't resolve properly
3524             }
3525         }
3526
3527         let name_path = path.segments.iter().map(|seg| seg.identifier.name).collect::<Vec<_>>();
3528
3529         // Look for a method in the current self type's impl module.
3530         if let Some(module) = get_module(self, path.span, &name_path) {
3531             if let Some(binding) = module.children.borrow().get(&name) {
3532                 if let Some(DefMethod(did)) = binding.def_for_namespace(ValueNS) {
3533                     if is_static_method(self, did) {
3534                         return StaticMethod(path_names_to_string(&path, 0))
3535                     }
3536                     if self.current_trait_ref.is_some() {
3537                         return TraitItem;
3538                     } else if allowed == Everything {
3539                         return Method;
3540                     }
3541                 }
3542             }
3543         }
3544
3545         // Look for a method in the current trait.
3546         if let Some((trait_did, ref trait_ref)) = self.current_trait_ref {
3547             if let Some(&did) = self.trait_item_map.get(&(name, trait_did)) {
3548                 if is_static_method(self, did) {
3549                     return TraitMethod(path_names_to_string(&trait_ref.path, 0));
3550                 } else {
3551                     return TraitItem;
3552                 }
3553             }
3554         }
3555
3556         NoSuggestion
3557     }
3558
3559     fn find_best_match_for_name(&mut self, name: &str) -> Option<String> {
3560         let mut maybes: Vec<token::InternedString> = Vec::new();
3561         let mut values: Vec<usize> = Vec::new();
3562
3563         for rib in self.value_ribs.iter().rev() {
3564             for (&k, _) in &rib.bindings {
3565                 maybes.push(k.as_str());
3566                 values.push(usize::MAX);
3567             }
3568         }
3569
3570         let mut smallest = 0;
3571         for (i, other) in maybes.iter().enumerate() {
3572             values[i] = lev_distance(name, &other);
3573
3574             if values[i] <= values[smallest] {
3575                 smallest = i;
3576             }
3577         }
3578
3579         // As a loose rule to avoid obviously incorrect suggestions, clamp the
3580         // maximum edit distance we will accept for a suggestion to one third of
3581         // the typo'd name's length.
3582         let max_distance = std::cmp::max(name.len(), 3) / 3;
3583
3584         if !values.is_empty() &&
3585             values[smallest] <= max_distance &&
3586             name != &maybes[smallest][..] {
3587
3588             Some(maybes[smallest].to_string())
3589
3590         } else {
3591             None
3592         }
3593     }
3594
3595     fn resolve_expr(&mut self, expr: &Expr) {
3596         // First, record candidate traits for this expression if it could
3597         // result in the invocation of a method call.
3598
3599         self.record_candidate_traits_for_expr_if_necessary(expr);
3600
3601         // Next, resolve the node.
3602         match expr.node {
3603             ExprPath(ref maybe_qself, ref path) => {
3604                 let resolution =
3605                     match self.resolve_possibly_assoc_item(expr.id,
3606                                                            maybe_qself.as_ref(),
3607                                                            path,
3608                                                            ValueNS,
3609                                                            true) {
3610                         // `<T>::a::b::c` is resolved by typeck alone.
3611                         TypecheckRequired => {
3612                             let method_name = path.segments.last().unwrap().identifier.name;
3613                             let traits = self.get_traits_containing_item(method_name);
3614                             self.trait_map.insert(expr.id, traits);
3615                             visit::walk_expr(self, expr);
3616                             return;
3617                         }
3618                         ResolveAttempt(resolution) => resolution,
3619                     };
3620
3621                 // This is a local path in the value namespace. Walk through
3622                 // scopes looking for it.
3623                 if let Some(path_res) = resolution {
3624                     // Check if struct variant
3625                     if let DefVariant(_, _, true) = path_res.base_def {
3626                         let path_name = path_names_to_string(path, 0);
3627
3628                         resolve_error(self,
3629                                       expr.span,
3630                                       ResolutionError::StructVariantUsedAsFunction(&*path_name));
3631
3632                         let msg = format!("did you mean to write: \
3633                                            `{} {{ /* fields */ }}`?",
3634                                           path_name);
3635                         if self.emit_errors {
3636                             self.session.fileline_help(expr.span, &msg);
3637                         } else {
3638                             self.session.span_help(expr.span, &msg);
3639                         }
3640                     } else {
3641                         // Write the result into the def map.
3642                         debug!("(resolving expr) resolved `{}`",
3643                                path_names_to_string(path, 0));
3644
3645                         // Partial resolutions will need the set of traits in scope,
3646                         // so they can be completed during typeck.
3647                         if path_res.depth != 0 {
3648                             let method_name = path.segments.last().unwrap().identifier.name;
3649                             let traits = self.get_traits_containing_item(method_name);
3650                             self.trait_map.insert(expr.id, traits);
3651                         }
3652
3653                         self.record_def(expr.id, path_res);
3654                     }
3655                 } else {
3656                     // Be helpful if the name refers to a struct
3657                     // (The pattern matching def_tys where the id is in self.structs
3658                     // matches on regular structs while excluding tuple- and enum-like
3659                     // structs, which wouldn't result in this error.)
3660                     let path_name = path_names_to_string(path, 0);
3661                     let type_res = self.with_no_errors(|this| {
3662                         this.resolve_path(expr.id, path, 0, TypeNS, false)
3663                     });
3664                     match type_res.map(|r| r.base_def) {
3665                         Some(DefTy(struct_id, _))
3666                             if self.structs.contains_key(&struct_id) => {
3667                                 resolve_error(
3668                                     self,
3669                                     expr.span,
3670                                     ResolutionError::StructVariantUsedAsFunction(
3671                                         &*path_name)
3672                                 );
3673
3674                                 let msg = format!("did you mean to write: \
3675                                                      `{} {{ /* fields */ }}`?",
3676                                                     path_name);
3677                                 if self.emit_errors {
3678                                     self.session.fileline_help(expr.span, &msg);
3679                                 } else {
3680                                     self.session.span_help(expr.span, &msg);
3681                                 }
3682                             }
3683                         _ => {
3684                             // Keep reporting some errors even if they're ignored above.
3685                             self.resolve_path(expr.id, path, 0, ValueNS, true);
3686
3687                             let mut method_scope = false;
3688                             self.value_ribs.iter().rev().all(|rib| {
3689                                 method_scope = match rib.kind {
3690                                     MethodRibKind => true,
3691                                     ItemRibKind | ConstantItemRibKind => false,
3692                                     _ => return true, // Keep advancing
3693                                 };
3694                                 false // Stop advancing
3695                             });
3696
3697                             if method_scope && special_names::self_ == path_name {
3698                                 resolve_error(
3699                                     self,
3700                                     expr.span,
3701                                     ResolutionError::SelfNotAvailableInStaticMethod
3702                                 );
3703                             } else {
3704                                 let last_name = path.segments.last().unwrap().identifier.name;
3705                                 let mut msg = match self.find_fallback_in_self_type(last_name) {
3706                                     NoSuggestion => {
3707                                         // limit search to 5 to reduce the number
3708                                         // of stupid suggestions
3709                                         self.find_best_match_for_name(&path_name)
3710                                                             .map_or("".to_string(),
3711                                                                     |x| format!("`{}`", x))
3712                                     }
3713                                     Field => format!("`self.{}`", path_name),
3714                                     Method |
3715                                     TraitItem =>
3716                                         format!("to call `self.{}`", path_name),
3717                                     TraitMethod(path_str) |
3718                                     StaticMethod(path_str) =>
3719                                         format!("to call `{}::{}`", path_str, path_name)
3720                                 };
3721
3722                                 if !msg.is_empty() {
3723                                     msg = format!(". Did you mean {}?", msg)
3724                                 }
3725
3726                                 resolve_error(self,
3727                                               expr.span,
3728                                               ResolutionError::UnresolvedName(&*path_name,
3729                                                                                &*msg));
3730                             }
3731                         }
3732                     }
3733                 }
3734
3735                 visit::walk_expr(self, expr);
3736             }
3737
3738             ExprStruct(ref path, _, _) => {
3739                 // Resolve the path to the structure it goes to. We don't
3740                 // check to ensure that the path is actually a structure; that
3741                 // is checked later during typeck.
3742                 match self.resolve_path(expr.id, path, 0, TypeNS, false) {
3743                     Some(definition) => self.record_def(expr.id, definition),
3744                     None => {
3745                         debug!("(resolving expression) didn't find struct def",);
3746
3747                         resolve_error(self,
3748                                       path.span,
3749                                       ResolutionError::DoesNotNameAStruct(
3750                                                                 &*path_names_to_string(path, 0))
3751                                      );
3752                     }
3753                 }
3754
3755                 visit::walk_expr(self, expr);
3756             }
3757
3758             ExprLoop(_, Some(label)) | ExprWhile(_, _, Some(label)) => {
3759                 self.with_label_rib(|this| {
3760                     let def_like = DlDef(DefLabel(expr.id));
3761
3762                     {
3763                         let rib = this.label_ribs.last_mut().unwrap();
3764                         let renamed = mtwt::resolve(label);
3765                         rib.bindings.insert(renamed, def_like);
3766                     }
3767
3768                     visit::walk_expr(this, expr);
3769                 })
3770             }
3771
3772             ExprBreak(Some(label)) | ExprAgain(Some(label)) => {
3773                 let renamed = mtwt::resolve(label.node);
3774                 match self.search_label(renamed) {
3775                     None => {
3776                         resolve_error(self,
3777                                       label.span,
3778                                       ResolutionError::UndeclaredLabel(&label.node.name.as_str()))
3779                     }
3780                     Some(DlDef(def @ DefLabel(_))) => {
3781                         // Since this def is a label, it is never read.
3782                         self.record_def(expr.id, PathResolution {
3783                             base_def: def,
3784                             last_private: LastMod(AllPublic),
3785                             depth: 0
3786                         })
3787                     }
3788                     Some(_) => {
3789                         self.session.span_bug(expr.span,
3790                                               "label wasn't mapped to a \
3791                                                label def!")
3792                     }
3793                 }
3794             }
3795
3796             _ => {
3797                 visit::walk_expr(self, expr);
3798             }
3799         }
3800     }
3801
3802     fn record_candidate_traits_for_expr_if_necessary(&mut self, expr: &Expr) {
3803         match expr.node {
3804             ExprField(_, ident) => {
3805                 // FIXME(#6890): Even though you can't treat a method like a
3806                 // field, we need to add any trait methods we find that match
3807                 // the field name so that we can do some nice error reporting
3808                 // later on in typeck.
3809                 let traits = self.get_traits_containing_item(ident.node.name);
3810                 self.trait_map.insert(expr.id, traits);
3811             }
3812             ExprMethodCall(ident, _, _) => {
3813                 debug!("(recording candidate traits for expr) recording \
3814                         traits for {}",
3815                        expr.id);
3816                 let traits = self.get_traits_containing_item(ident.node.name);
3817                 self.trait_map.insert(expr.id, traits);
3818             }
3819             _ => {
3820                 // Nothing to do.
3821             }
3822         }
3823     }
3824
3825     fn get_traits_containing_item(&mut self, name: Name) -> Vec<DefId> {
3826         debug!("(getting traits containing item) looking for '{}'",
3827                name);
3828
3829         fn add_trait_info(found_traits: &mut Vec<DefId>,
3830                           trait_def_id: DefId,
3831                           name: Name) {
3832             debug!("(adding trait info) found trait {}:{} for method '{}'",
3833                 trait_def_id.krate,
3834                 trait_def_id.node,
3835                 name);
3836             found_traits.push(trait_def_id);
3837         }
3838
3839         let mut found_traits = Vec::new();
3840         let mut search_module = self.current_module.clone();
3841         loop {
3842             // Look for the current trait.
3843             match self.current_trait_ref {
3844                 Some((trait_def_id, _)) => {
3845                     if self.trait_item_map.contains_key(&(name, trait_def_id)) {
3846                         add_trait_info(&mut found_traits, trait_def_id, name);
3847                     }
3848                 }
3849                 None => {} // Nothing to do.
3850             }
3851
3852             // Look for trait children.
3853             build_reduced_graph::populate_module_if_necessary(self, &search_module);
3854
3855             {
3856                 for (_, child_names) in search_module.children.borrow().iter() {
3857                     let def = match child_names.def_for_namespace(TypeNS) {
3858                         Some(def) => def,
3859                         None => continue
3860                     };
3861                     let trait_def_id = match def {
3862                         DefTrait(trait_def_id) => trait_def_id,
3863                         _ => continue,
3864                     };
3865                     if self.trait_item_map.contains_key(&(name, trait_def_id)) {
3866                         add_trait_info(&mut found_traits, trait_def_id, name);
3867                     }
3868                 }
3869             }
3870
3871             // Look for imports.
3872             for (_, import) in search_module.import_resolutions.borrow().iter() {
3873                 let target = match import.target_for_namespace(TypeNS) {
3874                     None => continue,
3875                     Some(target) => target,
3876                 };
3877                 let did = match target.bindings.def_for_namespace(TypeNS) {
3878                     Some(DefTrait(trait_def_id)) => trait_def_id,
3879                     Some(..) | None => continue,
3880                 };
3881                 if self.trait_item_map.contains_key(&(name, did)) {
3882                     add_trait_info(&mut found_traits, did, name);
3883                     let id = import.type_id;
3884                     self.used_imports.insert((id, TypeNS));
3885                     let trait_name = self.get_trait_name(did);
3886                     self.record_import_use(id, trait_name);
3887                     if let Some(DefId{krate: kid, ..}) = target.target_module.def_id.get() {
3888                         self.used_crates.insert(kid);
3889                     }
3890                 }
3891             }
3892
3893             match search_module.parent_link.clone() {
3894                 NoParentLink | ModuleParentLink(..) => break,
3895                 BlockParentLink(parent_module, _) => {
3896                     search_module = parent_module.upgrade().unwrap();
3897                 }
3898             }
3899         }
3900
3901         found_traits
3902     }
3903
3904     fn record_def(&mut self, node_id: NodeId, resolution: PathResolution) {
3905         debug!("(recording def) recording {:?} for {}", resolution, node_id);
3906         assert!(match resolution.last_private {LastImport{..} => false, _ => true},
3907                 "Import should only be used for `use` directives");
3908
3909         if let Some(prev_res) = self.def_map.borrow_mut().insert(node_id, resolution) {
3910             let span = self.ast_map.opt_span(node_id).unwrap_or(codemap::DUMMY_SP);
3911             self.session.span_bug(span, &format!("path resolved multiple times \
3912                                                   ({:?} before, {:?} now)",
3913                                                  prev_res, resolution));
3914         }
3915     }
3916
3917     fn enforce_default_binding_mode(&mut self,
3918                                         pat: &Pat,
3919                                         pat_binding_mode: BindingMode,
3920                                         descr: &str) {
3921         match pat_binding_mode {
3922             BindByValue(_) => {}
3923             BindByRef(..) => {
3924                 resolve_error(self,
3925                               pat.span,
3926                               ResolutionError::CannotUseRefBindingModeWith(descr));
3927             }
3928         }
3929     }
3930
3931     //
3932     // Diagnostics
3933     //
3934     // Diagnostics are not particularly efficient, because they're rarely
3935     // hit.
3936     //
3937
3938     #[allow(dead_code)]   // useful for debugging
3939     fn dump_module(&mut self, module_: Rc<Module>) {
3940         debug!("Dump of module `{}`:", module_to_string(&*module_));
3941
3942         debug!("Children:");
3943         build_reduced_graph::populate_module_if_necessary(self, &module_);
3944         for (&name, _) in module_.children.borrow().iter() {
3945             debug!("* {}", name);
3946         }
3947
3948         debug!("Import resolutions:");
3949         let import_resolutions = module_.import_resolutions.borrow();
3950         for (&name, import_resolution) in import_resolutions.iter() {
3951             let value_repr;
3952             match import_resolution.target_for_namespace(ValueNS) {
3953                 None => { value_repr = "".to_string(); }
3954                 Some(_) => {
3955                     value_repr = " value:?".to_string();
3956                     // FIXME #4954
3957                 }
3958             }
3959
3960             let type_repr;
3961             match import_resolution.target_for_namespace(TypeNS) {
3962                 None => { type_repr = "".to_string(); }
3963                 Some(_) => {
3964                     type_repr = " type:?".to_string();
3965                     // FIXME #4954
3966                 }
3967             }
3968
3969             debug!("* {}:{}{}", name, value_repr, type_repr);
3970         }
3971     }
3972 }
3973
3974
3975 fn names_to_string(names: &[Name]) -> String {
3976     let mut first = true;
3977     let mut result = String::new();
3978     for name in names {
3979         if first {
3980             first = false
3981         } else {
3982             result.push_str("::")
3983         }
3984         result.push_str(&name.as_str());
3985     };
3986     result
3987 }
3988
3989 fn path_names_to_string(path: &Path, depth: usize) -> String {
3990     let names: Vec<ast::Name> = path.segments[..path.segments.len()-depth]
3991                                     .iter()
3992                                     .map(|seg| seg.identifier.name)
3993                                     .collect();
3994     names_to_string(&names[..])
3995 }
3996
3997 /// A somewhat inefficient routine to obtain the name of a module.
3998 fn module_to_string(module: &Module) -> String {
3999     let mut names = Vec::new();
4000
4001     fn collect_mod(names: &mut Vec<ast::Name>, module: &Module) {
4002         match module.parent_link {
4003             NoParentLink => {}
4004             ModuleParentLink(ref module, name) => {
4005                 names.push(name);
4006                 collect_mod(names, &*module.upgrade().unwrap());
4007             }
4008             BlockParentLink(ref module, _) => {
4009                 // danger, shouldn't be ident?
4010                 names.push(special_idents::opaque.name);
4011                 collect_mod(names, &*module.upgrade().unwrap());
4012             }
4013         }
4014     }
4015     collect_mod(&mut names, module);
4016
4017     if names.is_empty() {
4018         return "???".to_string();
4019     }
4020     names_to_string(&names.into_iter().rev().collect::<Vec<ast::Name>>())
4021 }
4022
4023
4024 pub struct CrateMap {
4025     pub def_map: DefMap,
4026     pub freevars: RefCell<FreevarMap>,
4027     pub export_map: ExportMap,
4028     pub trait_map: TraitMap,
4029     pub external_exports: ExternalExports,
4030     pub glob_map: Option<GlobMap>
4031 }
4032
4033 #[derive(PartialEq,Copy, Clone)]
4034 pub enum MakeGlobMap {
4035     Yes,
4036     No
4037 }
4038
4039 /// Entry point to crate resolution.
4040 pub fn resolve_crate<'a, 'tcx>(session: &'a Session,
4041                                ast_map: &'a hir_map::Map<'tcx>,
4042                                make_glob_map: MakeGlobMap)
4043                                -> CrateMap {
4044     let krate = ast_map.krate();
4045     let mut resolver = create_resolver(session, ast_map, krate, make_glob_map, None);
4046
4047     resolver.resolve_crate(krate);
4048     session.abort_if_errors();
4049
4050     check_unused::check_crate(&mut resolver, krate);
4051
4052     CrateMap {
4053         def_map: resolver.def_map,
4054         freevars: resolver.freevars,
4055         export_map: resolver.export_map,
4056         trait_map: resolver.trait_map,
4057         external_exports: resolver.external_exports,
4058         glob_map: if resolver.make_glob_map {
4059                         Some(resolver.glob_map)
4060                     } else {
4061                         None
4062                     },
4063     }
4064 }
4065
4066 /// Builds a name resolution walker to be used within this module,
4067 /// or used externally, with an optional callback function.
4068 ///
4069 /// The callback takes a &mut bool which allows callbacks to end a
4070 /// walk when set to true, passing through the rest of the walk, while
4071 /// preserving the ribs + current module. This allows resolve_path
4072 /// calls to be made with the correct scope info. The node in the
4073 /// callback corresponds to the current node in the walk.
4074 pub fn create_resolver<'a, 'tcx>(session: &'a Session,
4075                                  ast_map: &'a hir_map::Map<'tcx>,
4076                                  krate: &'a Crate,
4077                                  make_glob_map: MakeGlobMap,
4078                                  callback: Option<Box<Fn(hir_map::Node, &mut bool) -> bool>>)
4079                                  -> Resolver<'a, 'tcx> {
4080     let mut resolver = Resolver::new(session, ast_map, krate.span, make_glob_map);
4081
4082     resolver.callback = callback;
4083
4084     build_reduced_graph::build_reduced_graph(&mut resolver, krate);
4085     session.abort_if_errors();
4086
4087     resolve_imports::resolve_imports(&mut resolver);
4088     session.abort_if_errors();
4089
4090     record_exports::record(&mut resolver);
4091     session.abort_if_errors();
4092
4093     resolver
4094 }
4095
4096 __build_diagnostic_array! { librustc_resolve, DIAGNOSTICS }