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