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