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