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