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