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