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