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