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