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