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