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