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