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