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