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