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