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