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