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