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