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