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