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