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