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