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