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