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