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