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