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