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