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