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