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