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