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