]> git.lizzy.rs Git - rust.git/blob - src/librustc_resolve/lib.rs
Rollup merge of #48966 - retep007:hir-fingerprint-optimization, r=michaelwoerister
[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 #![doc(html_logo_url = "https://www.rust-lang.org/logos/rust-logo-128x128-blk-v2.png",
12       html_favicon_url = "https://doc.rust-lang.org/favicon.ico",
13       html_root_url = "https://doc.rust-lang.org/nightly/")]
14 #![deny(warnings)]
15
16 #![feature(rustc_diagnostic_macros)]
17
18 #[macro_use]
19 extern crate log;
20 #[macro_use]
21 extern crate syntax;
22 extern crate syntax_pos;
23 extern crate rustc_errors as errors;
24 extern crate arena;
25 #[macro_use]
26 extern crate rustc;
27 extern crate rustc_data_structures;
28
29 use self::Namespace::*;
30 use self::TypeParameters::*;
31 use self::RibKind::*;
32
33 use rustc::hir::map::{Definitions, DefCollector};
34 use rustc::hir::{self, PrimTy, TyBool, TyChar, TyFloat, TyInt, TyUint, TyStr};
35 use rustc::middle::cstore::{CrateStore, CrateLoader};
36 use rustc::session::Session;
37 use rustc::lint;
38 use rustc::hir::def::*;
39 use rustc::hir::def_id::{CRATE_DEF_INDEX, LOCAL_CRATE, DefId};
40 use rustc::ty;
41 use rustc::hir::{Freevar, FreevarMap, TraitCandidate, TraitMap, GlobMap};
42 use rustc::util::nodemap::{NodeMap, NodeSet, FxHashMap, FxHashSet, DefIdMap};
43
44 use syntax::codemap::{dummy_spanned, respan, CodeMap};
45 use syntax::ext::hygiene::{Mark, MarkKind, SyntaxContext};
46 use syntax::ast::{self, Name, NodeId, Ident, SpannedIdent, FloatTy, IntTy, UintTy};
47 use syntax::ext::base::SyntaxExtension;
48 use syntax::ext::base::Determinacy::{self, Determined, Undetermined};
49 use syntax::ext::base::MacroKind;
50 use syntax::symbol::{Symbol, keywords};
51 use syntax::util::lev_distance::find_best_match_for_name;
52
53 use syntax::visit::{self, FnKind, Visitor};
54 use syntax::attr;
55 use syntax::ast::{Arm, BindingMode, Block, Crate, Expr, ExprKind};
56 use syntax::ast::{FnDecl, ForeignItem, ForeignItemKind, GenericParam, Generics};
57 use syntax::ast::{Item, ItemKind, ImplItem, ImplItemKind};
58 use syntax::ast::{Label, Local, Mutability, Pat, PatKind, Path};
59 use syntax::ast::{QSelf, TraitItemKind, TraitRef, Ty, TyKind};
60 use syntax::feature_gate::{feature_err, emit_feature_err, GateIssue};
61 use syntax::parse::token;
62 use syntax::ptr::P;
63
64 use syntax_pos::{Span, DUMMY_SP, MultiSpan};
65 use errors::{DiagnosticBuilder, DiagnosticId};
66
67 use std::cell::{Cell, RefCell};
68 use std::cmp;
69 use std::collections::BTreeSet;
70 use std::fmt;
71 use std::iter;
72 use std::mem::replace;
73 use rustc_data_structures::sync::Lrc;
74
75 use resolve_imports::{ImportDirective, ImportDirectiveSubclass, NameResolution, ImportResolver};
76 use macros::{InvocationData, LegacyBinding, LegacyScope, MacroBinding};
77
78 // NB: This module needs to be declared first so diagnostics are
79 // registered before they are used.
80 mod diagnostics;
81
82 mod macros;
83 mod check_unused;
84 mod build_reduced_graph;
85 mod resolve_imports;
86
87 /// A free importable items suggested in case of resolution failure.
88 struct ImportSuggestion {
89     path: Path,
90 }
91
92 /// A field or associated item from self type suggested in case of resolution failure.
93 enum AssocSuggestion {
94     Field,
95     MethodWithSelf,
96     AssocItem,
97 }
98
99 #[derive(Eq)]
100 struct BindingError {
101     name: Name,
102     origin: BTreeSet<Span>,
103     target: BTreeSet<Span>,
104 }
105
106 impl PartialOrd for BindingError {
107     fn partial_cmp(&self, other: &BindingError) -> Option<cmp::Ordering> {
108         Some(self.cmp(other))
109     }
110 }
111
112 impl PartialEq for BindingError {
113     fn eq(&self, other: &BindingError) -> bool {
114         self.name == other.name
115     }
116 }
117
118 impl Ord for BindingError {
119     fn cmp(&self, other: &BindingError) -> cmp::Ordering {
120         self.name.cmp(&other.name)
121     }
122 }
123
124 enum ResolutionError<'a> {
125     /// error E0401: can't use type parameters from outer function
126     TypeParametersFromOuterFunction(Def),
127     /// error E0403: the name is already used for a type parameter in this type parameter list
128     NameAlreadyUsedInTypeParameterList(Name, &'a Span),
129     /// error E0407: method is not a member of trait
130     MethodNotMemberOfTrait(Name, &'a str),
131     /// error E0437: type is not a member of trait
132     TypeNotMemberOfTrait(Name, &'a str),
133     /// error E0438: const is not a member of trait
134     ConstNotMemberOfTrait(Name, &'a str),
135     /// error E0408: variable `{}` is not bound in all patterns
136     VariableNotBoundInPattern(&'a BindingError),
137     /// error E0409: variable `{}` is bound in inconsistent ways within the same match arm
138     VariableBoundWithDifferentMode(Name, Span),
139     /// error E0415: identifier is bound more than once in this parameter list
140     IdentifierBoundMoreThanOnceInParameterList(&'a str),
141     /// error E0416: identifier is bound more than once in the same pattern
142     IdentifierBoundMoreThanOnceInSamePattern(&'a str),
143     /// error E0426: use of undeclared label
144     UndeclaredLabel(&'a str, Option<Name>),
145     /// error E0429: `self` imports are only allowed within a { } list
146     SelfImportsOnlyAllowedWithin,
147     /// error E0430: `self` import can only appear once in the list
148     SelfImportCanOnlyAppearOnceInTheList,
149     /// error E0431: `self` import can only appear in an import list with a non-empty prefix
150     SelfImportOnlyInImportListWithNonEmptyPrefix,
151     /// error E0432: unresolved import
152     UnresolvedImport(Option<(Span, &'a str, &'a str)>),
153     /// error E0433: failed to resolve
154     FailedToResolve(&'a str),
155     /// error E0434: can't capture dynamic environment in a fn item
156     CannotCaptureDynamicEnvironmentInFnItem,
157     /// error E0435: attempt to use a non-constant value in a constant
158     AttemptToUseNonConstantValueInConstant,
159     /// error E0530: X bindings cannot shadow Ys
160     BindingShadowsSomethingUnacceptable(&'a str, Name, &'a NameBinding<'a>),
161     /// error E0128: type parameters with a default cannot use forward declared identifiers
162     ForwardDeclaredTyParam,
163 }
164
165 fn resolve_error<'sess, 'a>(resolver: &'sess Resolver,
166                             span: Span,
167                             resolution_error: ResolutionError<'a>) {
168     resolve_struct_error(resolver, span, resolution_error).emit();
169 }
170
171 fn resolve_struct_error<'sess, 'a>(resolver: &'sess Resolver,
172                                    span: Span,
173                                    resolution_error: ResolutionError<'a>)
174                                    -> DiagnosticBuilder<'sess> {
175     match resolution_error {
176         ResolutionError::TypeParametersFromOuterFunction(outer_def) => {
177             let mut err = struct_span_err!(resolver.session,
178                                            span,
179                                            E0401,
180                                            "can't use type parameters from outer function");
181             err.span_label(span, "use of type variable from outer function");
182             match outer_def {
183                 Def::SelfTy(_, maybe_impl_defid) => {
184                     if let Some(impl_span) = maybe_impl_defid.map_or(None,
185                             |def_id| resolver.definitions.opt_span(def_id)) {
186                         let cm = resolver.session.codemap();
187                         err.span_label(reduce_impl_span_to_impl_keyword(cm, impl_span),
188                                     "`Self` type implicitely declared here, on the `impl`");
189                     }
190                 },
191                 Def::TyParam(typaram_defid) => {
192                     if let Some(typaram_span) = resolver.definitions.opt_span(typaram_defid) {
193                         err.span_label(typaram_span, "type variable from outer function");
194                     }
195                 },
196                 Def::Mod(..) | Def::Struct(..) | Def::Union(..) | Def::Enum(..) | Def::Variant(..) |
197                 Def::Trait(..) | Def::TyAlias(..) | Def::TyForeign(..) | Def::TraitAlias(..) |
198                 Def::AssociatedTy(..) | Def::PrimTy(..) | Def::Fn(..) | Def::Const(..) |
199                 Def::Static(..) | Def::StructCtor(..) | Def::VariantCtor(..) | Def::Method(..) |
200                 Def::AssociatedConst(..) | Def::Local(..) | Def::Upvar(..) | Def::Label(..) |
201                 Def::Macro(..) | Def::GlobalAsm(..) | Def::Err =>
202                     bug!("TypeParametersFromOuterFunction should only be used with Def::SelfTy or \
203                          Def::TyParam")
204             }
205
206             // Try to retrieve the span of the function signature and generate a new message with
207             // a local type parameter
208             let sugg_msg = "try using a local type parameter instead";
209             if let Some((sugg_span, new_snippet)) = generate_local_type_param_snippet(
210                                                         resolver.session.codemap(), span) {
211                 // Suggest the modification to the user
212                 err.span_suggestion(sugg_span,
213                                     sugg_msg,
214                                     new_snippet);
215             } else {
216                 err.help("try using a local type parameter instead");
217             }
218
219             err
220         }
221         ResolutionError::NameAlreadyUsedInTypeParameterList(name, first_use_span) => {
222              let mut err = struct_span_err!(resolver.session,
223                                             span,
224                                             E0403,
225                                             "the name `{}` is already used for a type parameter \
226                                             in this type parameter list",
227                                             name);
228              err.span_label(span, "already used");
229              err.span_label(first_use_span.clone(), format!("first use of `{}`", name));
230              err
231         }
232         ResolutionError::MethodNotMemberOfTrait(method, trait_) => {
233             let mut err = struct_span_err!(resolver.session,
234                                            span,
235                                            E0407,
236                                            "method `{}` is not a member of trait `{}`",
237                                            method,
238                                            trait_);
239             err.span_label(span, format!("not a member of trait `{}`", trait_));
240             err
241         }
242         ResolutionError::TypeNotMemberOfTrait(type_, trait_) => {
243             let mut err = struct_span_err!(resolver.session,
244                              span,
245                              E0437,
246                              "type `{}` is not a member of trait `{}`",
247                              type_,
248                              trait_);
249             err.span_label(span, format!("not a member of trait `{}`", trait_));
250             err
251         }
252         ResolutionError::ConstNotMemberOfTrait(const_, trait_) => {
253             let mut err = struct_span_err!(resolver.session,
254                              span,
255                              E0438,
256                              "const `{}` is not a member of trait `{}`",
257                              const_,
258                              trait_);
259             err.span_label(span, format!("not a member of trait `{}`", trait_));
260             err
261         }
262         ResolutionError::VariableNotBoundInPattern(binding_error) => {
263             let target_sp = binding_error.target.iter().map(|x| *x).collect::<Vec<_>>();
264             let msp = MultiSpan::from_spans(target_sp.clone());
265             let msg = format!("variable `{}` is not bound in all patterns", binding_error.name);
266             let mut err = resolver.session.struct_span_err_with_code(
267                 msp,
268                 &msg,
269                 DiagnosticId::Error("E0408".into()),
270             );
271             for sp in target_sp {
272                 err.span_label(sp, format!("pattern doesn't bind `{}`", binding_error.name));
273             }
274             let origin_sp = binding_error.origin.iter().map(|x| *x).collect::<Vec<_>>();
275             for sp in origin_sp {
276                 err.span_label(sp, "variable not in all patterns");
277             }
278             err
279         }
280         ResolutionError::VariableBoundWithDifferentMode(variable_name,
281                                                         first_binding_span) => {
282             let mut err = struct_span_err!(resolver.session,
283                              span,
284                              E0409,
285                              "variable `{}` is bound in inconsistent \
286                              ways within the same match arm",
287                              variable_name);
288             err.span_label(span, "bound in different ways");
289             err.span_label(first_binding_span, "first binding");
290             err
291         }
292         ResolutionError::IdentifierBoundMoreThanOnceInParameterList(identifier) => {
293             let mut err = struct_span_err!(resolver.session,
294                              span,
295                              E0415,
296                              "identifier `{}` is bound more than once in this parameter list",
297                              identifier);
298             err.span_label(span, "used as parameter more than once");
299             err
300         }
301         ResolutionError::IdentifierBoundMoreThanOnceInSamePattern(identifier) => {
302             let mut err = struct_span_err!(resolver.session,
303                              span,
304                              E0416,
305                              "identifier `{}` is bound more than once in the same pattern",
306                              identifier);
307             err.span_label(span, "used in a pattern more than once");
308             err
309         }
310         ResolutionError::UndeclaredLabel(name, lev_candidate) => {
311             let mut err = struct_span_err!(resolver.session,
312                                            span,
313                                            E0426,
314                                            "use of undeclared label `{}`",
315                                            name);
316             if let Some(lev_candidate) = lev_candidate {
317                 err.span_label(span, format!("did you mean `{}`?", lev_candidate));
318             } else {
319                 err.span_label(span, format!("undeclared label `{}`", name));
320             }
321             err
322         }
323         ResolutionError::SelfImportsOnlyAllowedWithin => {
324             struct_span_err!(resolver.session,
325                              span,
326                              E0429,
327                              "{}",
328                              "`self` imports are only allowed within a { } list")
329         }
330         ResolutionError::SelfImportCanOnlyAppearOnceInTheList => {
331             let mut err = struct_span_err!(resolver.session, span, E0430,
332                                            "`self` import can only appear once in an import list");
333             err.span_label(span, "can only appear once in an import list");
334             err
335         }
336         ResolutionError::SelfImportOnlyInImportListWithNonEmptyPrefix => {
337             let mut err = struct_span_err!(resolver.session, span, E0431,
338                                            "`self` import can only appear in an import list with \
339                                             a non-empty prefix");
340             err.span_label(span, "can only appear in an import list with a non-empty prefix");
341             err
342         }
343         ResolutionError::UnresolvedImport(name) => {
344             let (span, msg) = match name {
345                 Some((sp, n, _)) => (sp, format!("unresolved import `{}`", n)),
346                 None => (span, "unresolved import".to_owned()),
347             };
348             let mut err = struct_span_err!(resolver.session, span, E0432, "{}", msg);
349             if let Some((_, _, p)) = name {
350                 err.span_label(span, p);
351             }
352             err
353         }
354         ResolutionError::FailedToResolve(msg) => {
355             let mut err = struct_span_err!(resolver.session, span, E0433,
356                                            "failed to resolve. {}", msg);
357             err.span_label(span, msg);
358             err
359         }
360         ResolutionError::CannotCaptureDynamicEnvironmentInFnItem => {
361             let mut err = struct_span_err!(resolver.session,
362                                            span,
363                                            E0434,
364                                            "{}",
365                                            "can't capture dynamic environment in a fn item");
366             err.help("use the `|| { ... }` closure form instead");
367             err
368         }
369         ResolutionError::AttemptToUseNonConstantValueInConstant => {
370             let mut err = struct_span_err!(resolver.session, span, E0435,
371                                            "attempt to use a non-constant value in a constant");
372             err.span_label(span, "non-constant value");
373             err
374         }
375         ResolutionError::BindingShadowsSomethingUnacceptable(what_binding, name, binding) => {
376             let shadows_what = PathResolution::new(binding.def()).kind_name();
377             let mut err = struct_span_err!(resolver.session,
378                                            span,
379                                            E0530,
380                                            "{}s cannot shadow {}s", what_binding, shadows_what);
381             err.span_label(span, format!("cannot be named the same as a {}", shadows_what));
382             let participle = if binding.is_import() { "imported" } else { "defined" };
383             let msg = format!("a {} `{}` is {} here", shadows_what, name, participle);
384             err.span_label(binding.span, msg);
385             err
386         }
387         ResolutionError::ForwardDeclaredTyParam => {
388             let mut err = struct_span_err!(resolver.session, span, E0128,
389                                            "type parameters with a default cannot use \
390                                             forward declared identifiers");
391             err.span_label(span, format!("defaulted type parameters cannot be forward declared"));
392             err
393         }
394     }
395 }
396
397 /// Adjust the impl span so that just the `impl` keyword is taken by removing
398 /// everything after `<` (`"impl<T> Iterator for A<T> {}" -> "impl"`) and
399 /// everything after the first whitespace (`"impl Iterator for A" -> "impl"`)
400 ///
401 /// Attention: The method used is very fragile since it essentially duplicates the work of the
402 /// parser. If you need to use this function or something similar, please consider updating the
403 /// codemap functions and this function to something more robust.
404 fn reduce_impl_span_to_impl_keyword(cm: &CodeMap, impl_span: Span) -> Span {
405     let impl_span = cm.span_until_char(impl_span, '<');
406     let impl_span = cm.span_until_whitespace(impl_span);
407     impl_span
408 }
409
410 /// Take the span of a type parameter in a function signature and try to generate a span for the
411 /// function name (with generics) and a new snippet for this span with the pointed type parameter as
412 /// a new local type parameter.
413 ///
414 /// For instance:
415 /// ```
416 /// // Given span
417 /// fn my_function(param: T)
418 ///                       ^ Original span
419 ///
420 /// // Result
421 /// fn my_function(param: T)
422 ///    ^^^^^^^^^^^ Generated span with snippet `my_function<T>`
423 /// ```
424 ///
425 /// Attention: The method used is very fragile since it essentially duplicates the work of the
426 /// parser. If you need to use this function or something similar, please consider updating the
427 /// codemap functions and this function to something more robust.
428 fn generate_local_type_param_snippet(cm: &CodeMap, span: Span) -> Option<(Span, String)> {
429     // Try to extend the span to the previous "fn" keyword to retrieve the function
430     // signature
431     let sugg_span = cm.span_extend_to_prev_str(span, "fn");
432     if sugg_span != span {
433         if let Ok(snippet) = cm.span_to_snippet(sugg_span) {
434             use syntax::codemap::BytePos;
435
436             // Consume the function name
437             let mut offset = 0;
438             for c in snippet.chars().take_while(|c| c.is_ascii_alphanumeric() ||
439                                                     *c == '_') {
440                 offset += c.len_utf8();
441             }
442
443             // Consume the generics part of the function signature
444             let mut bracket_counter = 0;
445             let mut last_char = None;
446             for c in snippet[offset..].chars() {
447                 match c {
448                     '<' => bracket_counter += 1,
449                     '>' => bracket_counter -= 1,
450                     '(' => if bracket_counter == 0 { break; }
451                     _ => {}
452                 }
453                 offset += c.len_utf8();
454                 last_char = Some(c);
455             }
456
457             // Adjust the suggestion span to encompass the function name with its generics
458             let sugg_span = sugg_span.with_hi(BytePos(sugg_span.lo().0 + offset as u32));
459
460             // Prepare the new suggested snippet to append the type parameter that triggered
461             // the error in the generics of the function signature
462             let mut new_snippet = if last_char == Some('>') {
463                 format!("{}, ", &snippet[..(offset - '>'.len_utf8())])
464             } else {
465                 format!("{}<", &snippet[..offset])
466             };
467             new_snippet.push_str(&cm.span_to_snippet(span).unwrap_or("T".to_string()));
468             new_snippet.push('>');
469
470             return Some((sugg_span, new_snippet));
471         }
472     }
473
474     None
475 }
476
477 #[derive(Copy, Clone, Debug)]
478 struct BindingInfo {
479     span: Span,
480     binding_mode: BindingMode,
481 }
482
483 // Map from the name in a pattern to its binding mode.
484 type BindingMap = FxHashMap<Ident, BindingInfo>;
485
486 #[derive(Copy, Clone, PartialEq, Eq, Debug)]
487 enum PatternSource {
488     Match,
489     IfLet,
490     WhileLet,
491     Let,
492     For,
493     FnParam,
494 }
495
496 impl PatternSource {
497     fn descr(self) -> &'static str {
498         match self {
499             PatternSource::Match => "match binding",
500             PatternSource::IfLet => "if let binding",
501             PatternSource::WhileLet => "while let binding",
502             PatternSource::Let => "let binding",
503             PatternSource::For => "for binding",
504             PatternSource::FnParam => "function parameter",
505         }
506     }
507 }
508
509 #[derive(Copy, Clone, PartialEq, Eq, Debug)]
510 enum AliasPossibility {
511     No,
512     Maybe,
513 }
514
515 #[derive(Copy, Clone, PartialEq, Eq, Debug)]
516 enum PathSource<'a> {
517     // Type paths `Path`.
518     Type,
519     // Trait paths in bounds or impls.
520     Trait(AliasPossibility),
521     // Expression paths `path`, with optional parent context.
522     Expr(Option<&'a Expr>),
523     // Paths in path patterns `Path`.
524     Pat,
525     // Paths in struct expressions and patterns `Path { .. }`.
526     Struct,
527     // Paths in tuple struct patterns `Path(..)`.
528     TupleStruct,
529     // `m::A::B` in `<T as m::A>::B::C`.
530     TraitItem(Namespace),
531     // Path in `pub(path)`
532     Visibility,
533     // Path in `use a::b::{...};`
534     ImportPrefix,
535 }
536
537 impl<'a> PathSource<'a> {
538     fn namespace(self) -> Namespace {
539         match self {
540             PathSource::Type | PathSource::Trait(_) | PathSource::Struct |
541             PathSource::Visibility | PathSource::ImportPrefix => TypeNS,
542             PathSource::Expr(..) | PathSource::Pat | PathSource::TupleStruct => ValueNS,
543             PathSource::TraitItem(ns) => ns,
544         }
545     }
546
547     fn global_by_default(self) -> bool {
548         match self {
549             PathSource::Visibility | PathSource::ImportPrefix => true,
550             PathSource::Type | PathSource::Expr(..) | PathSource::Pat |
551             PathSource::Struct | PathSource::TupleStruct |
552             PathSource::Trait(_) | PathSource::TraitItem(..) => false,
553         }
554     }
555
556     fn defer_to_typeck(self) -> bool {
557         match self {
558             PathSource::Type | PathSource::Expr(..) | PathSource::Pat |
559             PathSource::Struct | PathSource::TupleStruct => true,
560             PathSource::Trait(_) | PathSource::TraitItem(..) |
561             PathSource::Visibility | PathSource::ImportPrefix => false,
562         }
563     }
564
565     fn descr_expected(self) -> &'static str {
566         match self {
567             PathSource::Type => "type",
568             PathSource::Trait(_) => "trait",
569             PathSource::Pat => "unit struct/variant or constant",
570             PathSource::Struct => "struct, variant or union type",
571             PathSource::TupleStruct => "tuple struct/variant",
572             PathSource::Visibility => "module",
573             PathSource::ImportPrefix => "module or enum",
574             PathSource::TraitItem(ns) => match ns {
575                 TypeNS => "associated type",
576                 ValueNS => "method or associated constant",
577                 MacroNS => bug!("associated macro"),
578             },
579             PathSource::Expr(parent) => match parent.map(|p| &p.node) {
580                 // "function" here means "anything callable" rather than `Def::Fn`,
581                 // this is not precise but usually more helpful than just "value".
582                 Some(&ExprKind::Call(..)) => "function",
583                 _ => "value",
584             },
585         }
586     }
587
588     fn is_expected(self, def: Def) -> bool {
589         match self {
590             PathSource::Type => match def {
591                 Def::Struct(..) | Def::Union(..) | Def::Enum(..) |
592                 Def::Trait(..) | Def::TyAlias(..) | Def::AssociatedTy(..) |
593                 Def::PrimTy(..) | Def::TyParam(..) | Def::SelfTy(..) |
594                 Def::TyForeign(..) => true,
595                 _ => false,
596             },
597             PathSource::Trait(AliasPossibility::No) => match def {
598                 Def::Trait(..) => true,
599                 _ => false,
600             },
601             PathSource::Trait(AliasPossibility::Maybe) => match def {
602                 Def::Trait(..) => true,
603                 Def::TraitAlias(..) => true,
604                 _ => false,
605             },
606             PathSource::Expr(..) => match def {
607                 Def::StructCtor(_, CtorKind::Const) | Def::StructCtor(_, CtorKind::Fn) |
608                 Def::VariantCtor(_, CtorKind::Const) | Def::VariantCtor(_, CtorKind::Fn) |
609                 Def::Const(..) | Def::Static(..) | Def::Local(..) | Def::Upvar(..) |
610                 Def::Fn(..) | Def::Method(..) | Def::AssociatedConst(..) => true,
611                 _ => false,
612             },
613             PathSource::Pat => match def {
614                 Def::StructCtor(_, CtorKind::Const) |
615                 Def::VariantCtor(_, CtorKind::Const) |
616                 Def::Const(..) | Def::AssociatedConst(..) => true,
617                 _ => false,
618             },
619             PathSource::TupleStruct => match def {
620                 Def::StructCtor(_, CtorKind::Fn) | Def::VariantCtor(_, CtorKind::Fn) => true,
621                 _ => false,
622             },
623             PathSource::Struct => match def {
624                 Def::Struct(..) | Def::Union(..) | Def::Variant(..) |
625                 Def::TyAlias(..) | Def::AssociatedTy(..) | Def::SelfTy(..) => true,
626                 _ => false,
627             },
628             PathSource::TraitItem(ns) => match def {
629                 Def::AssociatedConst(..) | Def::Method(..) if ns == ValueNS => true,
630                 Def::AssociatedTy(..) if ns == TypeNS => true,
631                 _ => false,
632             },
633             PathSource::ImportPrefix => match def {
634                 Def::Mod(..) | Def::Enum(..) => true,
635                 _ => false,
636             },
637             PathSource::Visibility => match def {
638                 Def::Mod(..) => true,
639                 _ => false,
640             },
641         }
642     }
643
644     fn error_code(self, has_unexpected_resolution: bool) -> &'static str {
645         __diagnostic_used!(E0404);
646         __diagnostic_used!(E0405);
647         __diagnostic_used!(E0412);
648         __diagnostic_used!(E0422);
649         __diagnostic_used!(E0423);
650         __diagnostic_used!(E0425);
651         __diagnostic_used!(E0531);
652         __diagnostic_used!(E0532);
653         __diagnostic_used!(E0573);
654         __diagnostic_used!(E0574);
655         __diagnostic_used!(E0575);
656         __diagnostic_used!(E0576);
657         __diagnostic_used!(E0577);
658         __diagnostic_used!(E0578);
659         match (self, has_unexpected_resolution) {
660             (PathSource::Trait(_), true) => "E0404",
661             (PathSource::Trait(_), false) => "E0405",
662             (PathSource::Type, true) => "E0573",
663             (PathSource::Type, false) => "E0412",
664             (PathSource::Struct, true) => "E0574",
665             (PathSource::Struct, false) => "E0422",
666             (PathSource::Expr(..), true) => "E0423",
667             (PathSource::Expr(..), false) => "E0425",
668             (PathSource::Pat, true) | (PathSource::TupleStruct, true) => "E0532",
669             (PathSource::Pat, false) | (PathSource::TupleStruct, false) => "E0531",
670             (PathSource::TraitItem(..), true) => "E0575",
671             (PathSource::TraitItem(..), false) => "E0576",
672             (PathSource::Visibility, true) | (PathSource::ImportPrefix, true) => "E0577",
673             (PathSource::Visibility, false) | (PathSource::ImportPrefix, false) => "E0578",
674         }
675     }
676 }
677
678 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Debug)]
679 pub enum Namespace {
680     TypeNS,
681     ValueNS,
682     MacroNS,
683 }
684
685 #[derive(Clone, Default, Debug)]
686 pub struct PerNS<T> {
687     value_ns: T,
688     type_ns: T,
689     macro_ns: Option<T>,
690 }
691
692 impl<T> ::std::ops::Index<Namespace> for PerNS<T> {
693     type Output = T;
694     fn index(&self, ns: Namespace) -> &T {
695         match ns {
696             ValueNS => &self.value_ns,
697             TypeNS => &self.type_ns,
698             MacroNS => self.macro_ns.as_ref().unwrap(),
699         }
700     }
701 }
702
703 impl<T> ::std::ops::IndexMut<Namespace> for PerNS<T> {
704     fn index_mut(&mut self, ns: Namespace) -> &mut T {
705         match ns {
706             ValueNS => &mut self.value_ns,
707             TypeNS => &mut self.type_ns,
708             MacroNS => self.macro_ns.as_mut().unwrap(),
709         }
710     }
711 }
712
713 struct UsePlacementFinder {
714     target_module: NodeId,
715     span: Option<Span>,
716     found_use: bool,
717 }
718
719 impl UsePlacementFinder {
720     fn check(krate: &Crate, target_module: NodeId) -> (Option<Span>, bool) {
721         let mut finder = UsePlacementFinder {
722             target_module,
723             span: None,
724             found_use: false,
725         };
726         visit::walk_crate(&mut finder, krate);
727         (finder.span, finder.found_use)
728     }
729 }
730
731 impl<'tcx> Visitor<'tcx> for UsePlacementFinder {
732     fn visit_mod(
733         &mut self,
734         module: &'tcx ast::Mod,
735         _: Span,
736         _: &[ast::Attribute],
737         node_id: NodeId,
738     ) {
739         if self.span.is_some() {
740             return;
741         }
742         if node_id != self.target_module {
743             visit::walk_mod(self, module);
744             return;
745         }
746         // find a use statement
747         for item in &module.items {
748             match item.node {
749                 ItemKind::Use(..) => {
750                     // don't suggest placing a use before the prelude
751                     // import or other generated ones
752                     if item.span.ctxt().outer().expn_info().is_none() {
753                         self.span = Some(item.span.with_hi(item.span.lo()));
754                         self.found_use = true;
755                         return;
756                     }
757                 },
758                 // don't place use before extern crate
759                 ItemKind::ExternCrate(_) => {}
760                 // but place them before the first other item
761                 _ => if self.span.map_or(true, |span| item.span < span ) {
762                     if item.span.ctxt().outer().expn_info().is_none() {
763                         // don't insert between attributes and an item
764                         if item.attrs.is_empty() {
765                             self.span = Some(item.span.with_hi(item.span.lo()));
766                         } else {
767                             // find the first attribute on the item
768                             for attr in &item.attrs {
769                                 if self.span.map_or(true, |span| attr.span < span) {
770                                     self.span = Some(attr.span.with_hi(attr.span.lo()));
771                                 }
772                             }
773                         }
774                     }
775                 },
776             }
777         }
778     }
779 }
780
781 impl<'a, 'tcx> Visitor<'tcx> for Resolver<'a> {
782     fn visit_item(&mut self, item: &'tcx Item) {
783         self.resolve_item(item);
784     }
785     fn visit_arm(&mut self, arm: &'tcx Arm) {
786         self.resolve_arm(arm);
787     }
788     fn visit_block(&mut self, block: &'tcx Block) {
789         self.resolve_block(block);
790     }
791     fn visit_expr(&mut self, expr: &'tcx Expr) {
792         self.resolve_expr(expr, None);
793     }
794     fn visit_local(&mut self, local: &'tcx Local) {
795         self.resolve_local(local);
796     }
797     fn visit_ty(&mut self, ty: &'tcx Ty) {
798         match ty.node {
799             TyKind::Path(ref qself, ref path) => {
800                 self.smart_resolve_path(ty.id, qself.as_ref(), path, PathSource::Type);
801             }
802             TyKind::ImplicitSelf => {
803                 let self_ty = keywords::SelfType.ident();
804                 let def = self.resolve_ident_in_lexical_scope(self_ty, TypeNS, true, ty.span)
805                               .map_or(Def::Err, |d| d.def());
806                 self.record_def(ty.id, PathResolution::new(def));
807             }
808             TyKind::Array(ref element, ref length) => {
809                 self.visit_ty(element);
810                 self.with_constant_rib(|this| {
811                     this.visit_expr(length);
812                 });
813                 return;
814             }
815             _ => (),
816         }
817         visit::walk_ty(self, ty);
818     }
819     fn visit_poly_trait_ref(&mut self,
820                             tref: &'tcx ast::PolyTraitRef,
821                             m: &'tcx ast::TraitBoundModifier) {
822         self.smart_resolve_path(tref.trait_ref.ref_id, None,
823                                 &tref.trait_ref.path, PathSource::Trait(AliasPossibility::Maybe));
824         visit::walk_poly_trait_ref(self, tref, m);
825     }
826     fn visit_variant(&mut self,
827                      variant: &'tcx ast::Variant,
828                      generics: &'tcx Generics,
829                      item_id: ast::NodeId) {
830         if let Some(ref dis_expr) = variant.node.disr_expr {
831             // resolve the discriminator expr as a constant
832             self.with_constant_rib(|this| {
833                 this.visit_expr(dis_expr);
834             });
835         }
836
837         // `visit::walk_variant` without the discriminant expression.
838         self.visit_variant_data(&variant.node.data,
839                                 variant.node.name,
840                                 generics,
841                                 item_id,
842                                 variant.span);
843     }
844     fn visit_foreign_item(&mut self, foreign_item: &'tcx ForeignItem) {
845         let type_parameters = match foreign_item.node {
846             ForeignItemKind::Fn(_, ref generics) => {
847                 HasTypeParameters(generics, ItemRibKind)
848             }
849             ForeignItemKind::Static(..) => NoTypeParameters,
850             ForeignItemKind::Ty => NoTypeParameters,
851         };
852         self.with_type_parameter_rib(type_parameters, |this| {
853             visit::walk_foreign_item(this, foreign_item);
854         });
855     }
856     fn visit_fn(&mut self,
857                 function_kind: FnKind<'tcx>,
858                 declaration: &'tcx FnDecl,
859                 _: Span,
860                 node_id: NodeId) {
861         let rib_kind = match function_kind {
862             FnKind::ItemFn(..) => {
863                 ItemRibKind
864             }
865             FnKind::Method(_, _, _, _) => {
866                 TraitOrImplItemRibKind
867             }
868             FnKind::Closure(_) => ClosureRibKind(node_id),
869         };
870
871         // Create a value rib for the function.
872         self.ribs[ValueNS].push(Rib::new(rib_kind));
873
874         // Create a label rib for the function.
875         self.label_ribs.push(Rib::new(rib_kind));
876
877         // Add each argument to the rib.
878         let mut bindings_list = FxHashMap();
879         for argument in &declaration.inputs {
880             self.resolve_pattern(&argument.pat, PatternSource::FnParam, &mut bindings_list);
881
882             self.visit_ty(&argument.ty);
883
884             debug!("(resolving function) recorded argument");
885         }
886         visit::walk_fn_ret_ty(self, &declaration.output);
887
888         // Resolve the function body.
889         match function_kind {
890             FnKind::ItemFn(.., body) |
891             FnKind::Method(.., body) => {
892                 self.visit_block(body);
893             }
894             FnKind::Closure(body) => {
895                 self.visit_expr(body);
896             }
897         };
898
899         debug!("(resolving function) leaving function");
900
901         self.label_ribs.pop();
902         self.ribs[ValueNS].pop();
903     }
904     fn visit_generics(&mut self, generics: &'tcx Generics) {
905         // For type parameter defaults, we have to ban access
906         // to following type parameters, as the Substs can only
907         // provide previous type parameters as they're built.
908         let mut default_ban_rib = Rib::new(ForwardTyParamBanRibKind);
909         default_ban_rib.bindings.extend(generics.params.iter()
910             .filter_map(|p| if let GenericParam::Type(ref tp) = *p { Some(tp) } else { None })
911             .skip_while(|p| p.default.is_none())
912             .map(|p| (Ident::with_empty_ctxt(p.ident.name), Def::Err)));
913
914         for param in &generics.params {
915             match *param {
916                 GenericParam::Lifetime(_) => self.visit_generic_param(param),
917                 GenericParam::Type(ref ty_param) => {
918                     for bound in &ty_param.bounds {
919                         self.visit_ty_param_bound(bound);
920                     }
921
922                     if let Some(ref ty) = ty_param.default {
923                         self.ribs[TypeNS].push(default_ban_rib);
924                         self.visit_ty(ty);
925                         default_ban_rib = self.ribs[TypeNS].pop().unwrap();
926                     }
927
928                     // Allow all following defaults to refer to this type parameter.
929                     default_ban_rib.bindings.remove(&Ident::with_empty_ctxt(ty_param.ident.name));
930                 }
931             }
932         }
933         for p in &generics.where_clause.predicates { self.visit_where_predicate(p); }
934     }
935 }
936
937 #[derive(Copy, Clone)]
938 enum TypeParameters<'a, 'b> {
939     NoTypeParameters,
940     HasTypeParameters(// Type parameters.
941                       &'b Generics,
942
943                       // The kind of the rib used for type parameters.
944                       RibKind<'a>),
945 }
946
947 // The rib kind controls the translation of local
948 // definitions (`Def::Local`) to upvars (`Def::Upvar`).
949 #[derive(Copy, Clone, Debug)]
950 enum RibKind<'a> {
951     // No translation needs to be applied.
952     NormalRibKind,
953
954     // We passed through a closure scope at the given node ID.
955     // Translate upvars as appropriate.
956     ClosureRibKind(NodeId /* func id */),
957
958     // We passed through an impl or trait and are now in one of its
959     // methods or associated types. Allow references to ty params that impl or trait
960     // binds. Disallow any other upvars (including other ty params that are
961     // upvars).
962     TraitOrImplItemRibKind,
963
964     // We passed through an item scope. Disallow upvars.
965     ItemRibKind,
966
967     // We're in a constant item. Can't refer to dynamic stuff.
968     ConstantItemRibKind,
969
970     // We passed through a module.
971     ModuleRibKind(Module<'a>),
972
973     // We passed through a `macro_rules!` statement
974     MacroDefinition(DefId),
975
976     // All bindings in this rib are type parameters that can't be used
977     // from the default of a type parameter because they're not declared
978     // before said type parameter. Also see the `visit_generics` override.
979     ForwardTyParamBanRibKind,
980 }
981
982 /// One local scope.
983 #[derive(Debug)]
984 struct Rib<'a> {
985     bindings: FxHashMap<Ident, Def>,
986     kind: RibKind<'a>,
987 }
988
989 impl<'a> Rib<'a> {
990     fn new(kind: RibKind<'a>) -> Rib<'a> {
991         Rib {
992             bindings: FxHashMap(),
993             kind,
994         }
995     }
996 }
997
998 enum LexicalScopeBinding<'a> {
999     Item(&'a NameBinding<'a>),
1000     Def(Def),
1001 }
1002
1003 impl<'a> LexicalScopeBinding<'a> {
1004     fn item(self) -> Option<&'a NameBinding<'a>> {
1005         match self {
1006             LexicalScopeBinding::Item(binding) => Some(binding),
1007             _ => None,
1008         }
1009     }
1010
1011     fn def(self) -> Def {
1012         match self {
1013             LexicalScopeBinding::Item(binding) => binding.def(),
1014             LexicalScopeBinding::Def(def) => def,
1015         }
1016     }
1017 }
1018
1019 #[derive(Clone, Debug)]
1020 enum PathResult<'a> {
1021     Module(Module<'a>),
1022     NonModule(PathResolution),
1023     Indeterminate,
1024     Failed(Span, String, bool /* is the error from the last segment? */),
1025 }
1026
1027 enum ModuleKind {
1028     Block(NodeId),
1029     Def(Def, Name),
1030 }
1031
1032 /// One node in the tree of modules.
1033 pub struct ModuleData<'a> {
1034     parent: Option<Module<'a>>,
1035     kind: ModuleKind,
1036
1037     // The def id of the closest normal module (`mod`) ancestor (including this module).
1038     normal_ancestor_id: DefId,
1039
1040     resolutions: RefCell<FxHashMap<(Ident, Namespace), &'a RefCell<NameResolution<'a>>>>,
1041     legacy_macro_resolutions: RefCell<Vec<(Mark, Ident, Span, MacroKind)>>,
1042     macro_resolutions: RefCell<Vec<(Box<[Ident]>, Span)>>,
1043
1044     // Macro invocations that can expand into items in this module.
1045     unresolved_invocations: RefCell<FxHashSet<Mark>>,
1046
1047     no_implicit_prelude: bool,
1048
1049     glob_importers: RefCell<Vec<&'a ImportDirective<'a>>>,
1050     globs: RefCell<Vec<&'a ImportDirective<'a>>>,
1051
1052     // Used to memoize the traits in this module for faster searches through all traits in scope.
1053     traits: RefCell<Option<Box<[(Ident, &'a NameBinding<'a>)]>>>,
1054
1055     // Whether this module is populated. If not populated, any attempt to
1056     // access the children must be preceded with a
1057     // `populate_module_if_necessary` call.
1058     populated: Cell<bool>,
1059
1060     /// Span of the module itself. Used for error reporting.
1061     span: Span,
1062
1063     expansion: Mark,
1064 }
1065
1066 type Module<'a> = &'a ModuleData<'a>;
1067
1068 impl<'a> ModuleData<'a> {
1069     fn new(parent: Option<Module<'a>>,
1070            kind: ModuleKind,
1071            normal_ancestor_id: DefId,
1072            expansion: Mark,
1073            span: Span) -> Self {
1074         ModuleData {
1075             parent,
1076             kind,
1077             normal_ancestor_id,
1078             resolutions: RefCell::new(FxHashMap()),
1079             legacy_macro_resolutions: RefCell::new(Vec::new()),
1080             macro_resolutions: RefCell::new(Vec::new()),
1081             unresolved_invocations: RefCell::new(FxHashSet()),
1082             no_implicit_prelude: false,
1083             glob_importers: RefCell::new(Vec::new()),
1084             globs: RefCell::new(Vec::new()),
1085             traits: RefCell::new(None),
1086             populated: Cell::new(normal_ancestor_id.is_local()),
1087             span,
1088             expansion,
1089         }
1090     }
1091
1092     fn for_each_child<F: FnMut(Ident, Namespace, &'a NameBinding<'a>)>(&self, mut f: F) {
1093         for (&(ident, ns), name_resolution) in self.resolutions.borrow().iter() {
1094             name_resolution.borrow().binding.map(|binding| f(ident, ns, binding));
1095         }
1096     }
1097
1098     fn for_each_child_stable<F: FnMut(Ident, Namespace, &'a NameBinding<'a>)>(&self, mut f: F) {
1099         let resolutions = self.resolutions.borrow();
1100         let mut resolutions = resolutions.iter().map(|(&(ident, ns), &resolution)| {
1101                                                     // Pre-compute keys for sorting
1102                                                     (ident.name.as_str(), ns, ident, resolution)
1103                                                 })
1104                                                 .collect::<Vec<_>>();
1105         resolutions.sort_unstable_by_key(|&(str, ns, ..)| (str, ns));
1106         for &(_, ns, ident, resolution) in resolutions.iter() {
1107             resolution.borrow().binding.map(|binding| f(ident, ns, binding));
1108         }
1109     }
1110
1111     fn def(&self) -> Option<Def> {
1112         match self.kind {
1113             ModuleKind::Def(def, _) => Some(def),
1114             _ => None,
1115         }
1116     }
1117
1118     fn def_id(&self) -> Option<DefId> {
1119         self.def().as_ref().map(Def::def_id)
1120     }
1121
1122     // `self` resolves to the first module ancestor that `is_normal`.
1123     fn is_normal(&self) -> bool {
1124         match self.kind {
1125             ModuleKind::Def(Def::Mod(_), _) => true,
1126             _ => false,
1127         }
1128     }
1129
1130     fn is_trait(&self) -> bool {
1131         match self.kind {
1132             ModuleKind::Def(Def::Trait(_), _) => true,
1133             _ => false,
1134         }
1135     }
1136
1137     fn is_local(&self) -> bool {
1138         self.normal_ancestor_id.is_local()
1139     }
1140
1141     fn nearest_item_scope(&'a self) -> Module<'a> {
1142         if self.is_trait() { self.parent.unwrap() } else { self }
1143     }
1144 }
1145
1146 impl<'a> fmt::Debug for ModuleData<'a> {
1147     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1148         write!(f, "{:?}", self.def())
1149     }
1150 }
1151
1152 // Records a possibly-private value, type, or module definition.
1153 #[derive(Clone, Debug)]
1154 pub struct NameBinding<'a> {
1155     kind: NameBindingKind<'a>,
1156     expansion: Mark,
1157     span: Span,
1158     vis: ty::Visibility,
1159 }
1160
1161 pub trait ToNameBinding<'a> {
1162     fn to_name_binding(self, arenas: &'a ResolverArenas<'a>) -> &'a NameBinding<'a>;
1163 }
1164
1165 impl<'a> ToNameBinding<'a> for &'a NameBinding<'a> {
1166     fn to_name_binding(self, _: &'a ResolverArenas<'a>) -> &'a NameBinding<'a> {
1167         self
1168     }
1169 }
1170
1171 #[derive(Clone, Debug)]
1172 enum NameBindingKind<'a> {
1173     Def(Def),
1174     Module(Module<'a>),
1175     Import {
1176         binding: &'a NameBinding<'a>,
1177         directive: &'a ImportDirective<'a>,
1178         used: Cell<bool>,
1179         legacy_self_import: bool,
1180     },
1181     Ambiguity {
1182         b1: &'a NameBinding<'a>,
1183         b2: &'a NameBinding<'a>,
1184         legacy: bool,
1185     }
1186 }
1187
1188 struct PrivacyError<'a>(Span, Name, &'a NameBinding<'a>);
1189
1190 struct UseError<'a> {
1191     err: DiagnosticBuilder<'a>,
1192     /// Attach `use` statements for these candidates
1193     candidates: Vec<ImportSuggestion>,
1194     /// The node id of the module to place the use statements in
1195     node_id: NodeId,
1196     /// Whether the diagnostic should state that it's "better"
1197     better: bool,
1198 }
1199
1200 struct AmbiguityError<'a> {
1201     span: Span,
1202     name: Name,
1203     lexical: bool,
1204     b1: &'a NameBinding<'a>,
1205     b2: &'a NameBinding<'a>,
1206     legacy: bool,
1207 }
1208
1209 impl<'a> NameBinding<'a> {
1210     fn module(&self) -> Option<Module<'a>> {
1211         match self.kind {
1212             NameBindingKind::Module(module) => Some(module),
1213             NameBindingKind::Import { binding, .. } => binding.module(),
1214             NameBindingKind::Ambiguity { legacy: true, b1, .. } => b1.module(),
1215             _ => None,
1216         }
1217     }
1218
1219     fn def(&self) -> Def {
1220         match self.kind {
1221             NameBindingKind::Def(def) => def,
1222             NameBindingKind::Module(module) => module.def().unwrap(),
1223             NameBindingKind::Import { binding, .. } => binding.def(),
1224             NameBindingKind::Ambiguity { legacy: true, b1, .. } => b1.def(),
1225             NameBindingKind::Ambiguity { .. } => Def::Err,
1226         }
1227     }
1228
1229     fn def_ignoring_ambiguity(&self) -> Def {
1230         match self.kind {
1231             NameBindingKind::Import { binding, .. } => binding.def_ignoring_ambiguity(),
1232             NameBindingKind::Ambiguity { b1, .. } => b1.def_ignoring_ambiguity(),
1233             _ => self.def(),
1234         }
1235     }
1236
1237     fn get_macro(&self, resolver: &mut Resolver<'a>) -> Lrc<SyntaxExtension> {
1238         resolver.get_macro(self.def_ignoring_ambiguity())
1239     }
1240
1241     // We sometimes need to treat variants as `pub` for backwards compatibility
1242     fn pseudo_vis(&self) -> ty::Visibility {
1243         if self.is_variant() && self.def().def_id().is_local() {
1244             ty::Visibility::Public
1245         } else {
1246             self.vis
1247         }
1248     }
1249
1250     fn is_variant(&self) -> bool {
1251         match self.kind {
1252             NameBindingKind::Def(Def::Variant(..)) |
1253             NameBindingKind::Def(Def::VariantCtor(..)) => true,
1254             _ => false,
1255         }
1256     }
1257
1258     fn is_extern_crate(&self) -> bool {
1259         match self.kind {
1260             NameBindingKind::Import {
1261                 directive: &ImportDirective {
1262                     subclass: ImportDirectiveSubclass::ExternCrate(_), ..
1263                 }, ..
1264             } => true,
1265             _ => false,
1266         }
1267     }
1268
1269     fn is_import(&self) -> bool {
1270         match self.kind {
1271             NameBindingKind::Import { .. } => true,
1272             _ => false,
1273         }
1274     }
1275
1276     fn is_renamed_extern_crate(&self) -> bool {
1277         if let NameBindingKind::Import { directive, ..} = self.kind {
1278             if let ImportDirectiveSubclass::ExternCrate(Some(_)) = directive.subclass {
1279                 return true;
1280             }
1281         }
1282         false
1283     }
1284
1285     fn is_glob_import(&self) -> bool {
1286         match self.kind {
1287             NameBindingKind::Import { directive, .. } => directive.is_glob(),
1288             NameBindingKind::Ambiguity { b1, .. } => b1.is_glob_import(),
1289             _ => false,
1290         }
1291     }
1292
1293     fn is_importable(&self) -> bool {
1294         match self.def() {
1295             Def::AssociatedConst(..) | Def::Method(..) | Def::AssociatedTy(..) => false,
1296             _ => true,
1297         }
1298     }
1299
1300     fn is_macro_def(&self) -> bool {
1301         match self.kind {
1302             NameBindingKind::Def(Def::Macro(..)) => true,
1303             _ => false,
1304         }
1305     }
1306
1307     fn descr(&self) -> &'static str {
1308         if self.is_extern_crate() { "extern crate" } else { self.def().kind_name() }
1309     }
1310 }
1311
1312 /// Interns the names of the primitive types.
1313 struct PrimitiveTypeTable {
1314     primitive_types: FxHashMap<Name, PrimTy>,
1315 }
1316
1317 impl PrimitiveTypeTable {
1318     fn new() -> PrimitiveTypeTable {
1319         let mut table = PrimitiveTypeTable { primitive_types: FxHashMap() };
1320
1321         table.intern("bool", TyBool);
1322         table.intern("char", TyChar);
1323         table.intern("f32", TyFloat(FloatTy::F32));
1324         table.intern("f64", TyFloat(FloatTy::F64));
1325         table.intern("isize", TyInt(IntTy::Isize));
1326         table.intern("i8", TyInt(IntTy::I8));
1327         table.intern("i16", TyInt(IntTy::I16));
1328         table.intern("i32", TyInt(IntTy::I32));
1329         table.intern("i64", TyInt(IntTy::I64));
1330         table.intern("i128", TyInt(IntTy::I128));
1331         table.intern("str", TyStr);
1332         table.intern("usize", TyUint(UintTy::Usize));
1333         table.intern("u8", TyUint(UintTy::U8));
1334         table.intern("u16", TyUint(UintTy::U16));
1335         table.intern("u32", TyUint(UintTy::U32));
1336         table.intern("u64", TyUint(UintTy::U64));
1337         table.intern("u128", TyUint(UintTy::U128));
1338         table
1339     }
1340
1341     fn intern(&mut self, string: &str, primitive_type: PrimTy) {
1342         self.primitive_types.insert(Symbol::intern(string), primitive_type);
1343     }
1344 }
1345
1346 /// The main resolver class.
1347 pub struct Resolver<'a> {
1348     session: &'a Session,
1349     cstore: &'a CrateStore,
1350
1351     pub definitions: Definitions,
1352
1353     graph_root: Module<'a>,
1354
1355     prelude: Option<Module<'a>>,
1356
1357     // n.b. This is used only for better diagnostics, not name resolution itself.
1358     has_self: FxHashSet<DefId>,
1359
1360     // Names of fields of an item `DefId` accessible with dot syntax.
1361     // Used for hints during error reporting.
1362     field_names: FxHashMap<DefId, Vec<Name>>,
1363
1364     // All imports known to succeed or fail.
1365     determined_imports: Vec<&'a ImportDirective<'a>>,
1366
1367     // All non-determined imports.
1368     indeterminate_imports: Vec<&'a ImportDirective<'a>>,
1369
1370     // The module that represents the current item scope.
1371     current_module: Module<'a>,
1372
1373     // The current set of local scopes for types and values.
1374     // FIXME #4948: Reuse ribs to avoid allocation.
1375     ribs: PerNS<Vec<Rib<'a>>>,
1376
1377     // The current set of local scopes, for labels.
1378     label_ribs: Vec<Rib<'a>>,
1379
1380     // The trait that the current context can refer to.
1381     current_trait_ref: Option<(Module<'a>, TraitRef)>,
1382
1383     // The current self type if inside an impl (used for better errors).
1384     current_self_type: Option<Ty>,
1385
1386     // The idents for the primitive types.
1387     primitive_type_table: PrimitiveTypeTable,
1388
1389     def_map: DefMap,
1390     pub freevars: FreevarMap,
1391     freevars_seen: NodeMap<NodeMap<usize>>,
1392     pub export_map: ExportMap,
1393     pub trait_map: TraitMap,
1394
1395     // A map from nodes to anonymous modules.
1396     // Anonymous modules are pseudo-modules that are implicitly created around items
1397     // contained within blocks.
1398     //
1399     // For example, if we have this:
1400     //
1401     //  fn f() {
1402     //      fn g() {
1403     //          ...
1404     //      }
1405     //  }
1406     //
1407     // There will be an anonymous module created around `g` with the ID of the
1408     // entry block for `f`.
1409     block_map: NodeMap<Module<'a>>,
1410     module_map: FxHashMap<DefId, Module<'a>>,
1411     extern_module_map: FxHashMap<(DefId, bool /* MacrosOnly? */), Module<'a>>,
1412
1413     pub make_glob_map: bool,
1414     /// Maps imports to the names of items actually imported (this actually maps
1415     /// all imports, but only glob imports are actually interesting).
1416     pub glob_map: GlobMap,
1417
1418     used_imports: FxHashSet<(NodeId, Namespace)>,
1419     pub maybe_unused_trait_imports: NodeSet,
1420     pub maybe_unused_extern_crates: Vec<(NodeId, Span)>,
1421
1422     /// privacy errors are delayed until the end in order to deduplicate them
1423     privacy_errors: Vec<PrivacyError<'a>>,
1424     /// ambiguity errors are delayed for deduplication
1425     ambiguity_errors: Vec<AmbiguityError<'a>>,
1426     /// `use` injections are delayed for better placement and deduplication
1427     use_injections: Vec<UseError<'a>>,
1428     /// `use` injections for proc macros wrongly imported with #[macro_use]
1429     proc_mac_errors: Vec<macros::ProcMacError>,
1430
1431     gated_errors: FxHashSet<Span>,
1432     disallowed_shadowing: Vec<&'a LegacyBinding<'a>>,
1433
1434     arenas: &'a ResolverArenas<'a>,
1435     dummy_binding: &'a NameBinding<'a>,
1436     use_extern_macros: bool, // true if `#![feature(use_extern_macros)]`
1437
1438     crate_loader: &'a mut CrateLoader,
1439     macro_names: FxHashSet<Ident>,
1440     global_macros: FxHashMap<Name, &'a NameBinding<'a>>,
1441     pub all_macros: FxHashMap<Name, Def>,
1442     lexical_macro_resolutions: Vec<(Ident, &'a Cell<LegacyScope<'a>>)>,
1443     macro_map: FxHashMap<DefId, Lrc<SyntaxExtension>>,
1444     macro_defs: FxHashMap<Mark, DefId>,
1445     local_macro_def_scopes: FxHashMap<NodeId, Module<'a>>,
1446     macro_exports: Vec<Export>,
1447     pub whitelisted_legacy_custom_derives: Vec<Name>,
1448     pub found_unresolved_macro: bool,
1449
1450     // List of crate local macros that we need to warn about as being unused.
1451     // Right now this only includes macro_rules! macros, and macros 2.0.
1452     unused_macros: FxHashSet<DefId>,
1453
1454     // Maps the `Mark` of an expansion to its containing module or block.
1455     invocations: FxHashMap<Mark, &'a InvocationData<'a>>,
1456
1457     // Avoid duplicated errors for "name already defined".
1458     name_already_seen: FxHashMap<Name, Span>,
1459
1460     // If `#![feature(proc_macro)]` is set
1461     proc_macro_enabled: bool,
1462
1463     // A set of procedural macros imported by `#[macro_use]` that have already been warned about
1464     warned_proc_macros: FxHashSet<Name>,
1465
1466     potentially_unused_imports: Vec<&'a ImportDirective<'a>>,
1467
1468     // This table maps struct IDs into struct constructor IDs,
1469     // it's not used during normal resolution, only for better error reporting.
1470     struct_constructors: DefIdMap<(Def, ty::Visibility)>,
1471
1472     // Only used for better errors on `fn(): fn()`
1473     current_type_ascription: Vec<Span>,
1474
1475     injected_crate: Option<Module<'a>>,
1476 }
1477
1478 pub struct ResolverArenas<'a> {
1479     modules: arena::TypedArena<ModuleData<'a>>,
1480     local_modules: RefCell<Vec<Module<'a>>>,
1481     name_bindings: arena::TypedArena<NameBinding<'a>>,
1482     import_directives: arena::TypedArena<ImportDirective<'a>>,
1483     name_resolutions: arena::TypedArena<RefCell<NameResolution<'a>>>,
1484     invocation_data: arena::TypedArena<InvocationData<'a>>,
1485     legacy_bindings: arena::TypedArena<LegacyBinding<'a>>,
1486 }
1487
1488 impl<'a> ResolverArenas<'a> {
1489     fn alloc_module(&'a self, module: ModuleData<'a>) -> Module<'a> {
1490         let module = self.modules.alloc(module);
1491         if module.def_id().map(|def_id| def_id.is_local()).unwrap_or(true) {
1492             self.local_modules.borrow_mut().push(module);
1493         }
1494         module
1495     }
1496     fn local_modules(&'a self) -> ::std::cell::Ref<'a, Vec<Module<'a>>> {
1497         self.local_modules.borrow()
1498     }
1499     fn alloc_name_binding(&'a self, name_binding: NameBinding<'a>) -> &'a NameBinding<'a> {
1500         self.name_bindings.alloc(name_binding)
1501     }
1502     fn alloc_import_directive(&'a self, import_directive: ImportDirective<'a>)
1503                               -> &'a ImportDirective {
1504         self.import_directives.alloc(import_directive)
1505     }
1506     fn alloc_name_resolution(&'a self) -> &'a RefCell<NameResolution<'a>> {
1507         self.name_resolutions.alloc(Default::default())
1508     }
1509     fn alloc_invocation_data(&'a self, expansion_data: InvocationData<'a>)
1510                              -> &'a InvocationData<'a> {
1511         self.invocation_data.alloc(expansion_data)
1512     }
1513     fn alloc_legacy_binding(&'a self, binding: LegacyBinding<'a>) -> &'a LegacyBinding<'a> {
1514         self.legacy_bindings.alloc(binding)
1515     }
1516 }
1517
1518 impl<'a, 'b: 'a> ty::DefIdTree for &'a Resolver<'b> {
1519     fn parent(self, id: DefId) -> Option<DefId> {
1520         match id.krate {
1521             LOCAL_CRATE => self.definitions.def_key(id.index).parent,
1522             _ => self.cstore.def_key(id).parent,
1523         }.map(|index| DefId { index: index, ..id })
1524     }
1525 }
1526
1527 impl<'a> hir::lowering::Resolver for Resolver<'a> {
1528     fn resolve_hir_path(&mut self, path: &mut hir::Path, is_value: bool) {
1529         self.resolve_hir_path_cb(path, is_value,
1530                                  |resolver, span, error| resolve_error(resolver, span, error))
1531     }
1532
1533     fn resolve_str_path(&mut self, span: Span, crate_root: Option<&str>,
1534                         components: &[&str], is_value: bool) -> hir::Path {
1535         let mut path = hir::Path {
1536             span,
1537             def: Def::Err,
1538             segments: iter::once(keywords::CrateRoot.name()).chain({
1539                 crate_root.into_iter().chain(components.iter().cloned()).map(Symbol::intern)
1540             }).map(hir::PathSegment::from_name).collect(),
1541         };
1542
1543         self.resolve_hir_path(&mut path, is_value);
1544         path
1545     }
1546
1547     fn get_resolution(&mut self, id: NodeId) -> Option<PathResolution> {
1548         self.def_map.get(&id).cloned()
1549     }
1550
1551     fn definitions(&mut self) -> &mut Definitions {
1552         &mut self.definitions
1553     }
1554 }
1555
1556 impl<'a> Resolver<'a> {
1557     /// Rustdoc uses this to resolve things in a recoverable way. ResolutionError<'a>
1558     /// isn't something that can be returned because it can't be made to live that long,
1559     /// and also it's a private type. Fortunately rustdoc doesn't need to know the error,
1560     /// just that an error occurred.
1561     pub fn resolve_str_path_error(&mut self, span: Span, path_str: &str, is_value: bool)
1562         -> Result<hir::Path, ()> {
1563         use std::iter;
1564         let mut errored = false;
1565
1566         let mut path = if path_str.starts_with("::") {
1567             hir::Path {
1568                 span,
1569                 def: Def::Err,
1570                 segments: iter::once(keywords::CrateRoot.name()).chain({
1571                     path_str.split("::").skip(1).map(Symbol::intern)
1572                 }).map(hir::PathSegment::from_name).collect(),
1573             }
1574         } else {
1575             hir::Path {
1576                 span,
1577                 def: Def::Err,
1578                 segments: path_str.split("::").map(Symbol::intern)
1579                                   .map(hir::PathSegment::from_name).collect(),
1580             }
1581         };
1582         self.resolve_hir_path_cb(&mut path, is_value, |_, _, _| errored = true);
1583         if errored || path.def == Def::Err {
1584             Err(())
1585         } else {
1586             Ok(path)
1587         }
1588     }
1589
1590     /// resolve_hir_path, but takes a callback in case there was an error
1591     fn resolve_hir_path_cb<F>(&mut self, path: &mut hir::Path, is_value: bool, error_callback: F)
1592             where F: for<'c, 'b> FnOnce(&'c mut Resolver, Span, ResolutionError<'b>)
1593         {
1594         let namespace = if is_value { ValueNS } else { TypeNS };
1595         let hir::Path { ref segments, span, ref mut def } = *path;
1596         let path: Vec<SpannedIdent> = segments.iter()
1597             .map(|seg| respan(span, Ident::with_empty_ctxt(seg.name)))
1598             .collect();
1599         match self.resolve_path(&path, Some(namespace), true, span) {
1600             PathResult::Module(module) => *def = module.def().unwrap(),
1601             PathResult::NonModule(path_res) if path_res.unresolved_segments() == 0 =>
1602                 *def = path_res.base_def(),
1603             PathResult::NonModule(..) => match self.resolve_path(&path, None, true, span) {
1604                 PathResult::Failed(span, msg, _) => {
1605                     error_callback(self, span, ResolutionError::FailedToResolve(&msg));
1606                 }
1607                 _ => {}
1608             },
1609             PathResult::Indeterminate => unreachable!(),
1610             PathResult::Failed(span, msg, _) => {
1611                 error_callback(self, span, ResolutionError::FailedToResolve(&msg));
1612             }
1613         }
1614     }
1615 }
1616
1617 impl<'a> Resolver<'a> {
1618     pub fn new(session: &'a Session,
1619                cstore: &'a CrateStore,
1620                krate: &Crate,
1621                crate_name: &str,
1622                make_glob_map: MakeGlobMap,
1623                crate_loader: &'a mut CrateLoader,
1624                arenas: &'a ResolverArenas<'a>)
1625                -> Resolver<'a> {
1626         let root_def_id = DefId::local(CRATE_DEF_INDEX);
1627         let root_module_kind = ModuleKind::Def(Def::Mod(root_def_id), keywords::Invalid.name());
1628         let graph_root = arenas.alloc_module(ModuleData {
1629             no_implicit_prelude: attr::contains_name(&krate.attrs, "no_implicit_prelude"),
1630             ..ModuleData::new(None, root_module_kind, root_def_id, Mark::root(), krate.span)
1631         });
1632         let mut module_map = FxHashMap();
1633         module_map.insert(DefId::local(CRATE_DEF_INDEX), graph_root);
1634
1635         let mut definitions = Definitions::new();
1636         DefCollector::new(&mut definitions, Mark::root())
1637             .collect_root(crate_name, session.local_crate_disambiguator());
1638
1639         let mut invocations = FxHashMap();
1640         invocations.insert(Mark::root(),
1641                            arenas.alloc_invocation_data(InvocationData::root(graph_root)));
1642
1643         let features = session.features_untracked();
1644
1645         let mut macro_defs = FxHashMap();
1646         macro_defs.insert(Mark::root(), root_def_id);
1647
1648         Resolver {
1649             session,
1650
1651             cstore,
1652
1653             definitions,
1654
1655             // The outermost module has def ID 0; this is not reflected in the
1656             // AST.
1657             graph_root,
1658             prelude: None,
1659
1660             has_self: FxHashSet(),
1661             field_names: FxHashMap(),
1662
1663             determined_imports: Vec::new(),
1664             indeterminate_imports: Vec::new(),
1665
1666             current_module: graph_root,
1667             ribs: PerNS {
1668                 value_ns: vec![Rib::new(ModuleRibKind(graph_root))],
1669                 type_ns: vec![Rib::new(ModuleRibKind(graph_root))],
1670                 macro_ns: Some(vec![Rib::new(ModuleRibKind(graph_root))]),
1671             },
1672             label_ribs: Vec::new(),
1673
1674             current_trait_ref: None,
1675             current_self_type: None,
1676
1677             primitive_type_table: PrimitiveTypeTable::new(),
1678
1679             def_map: NodeMap(),
1680             freevars: NodeMap(),
1681             freevars_seen: NodeMap(),
1682             export_map: FxHashMap(),
1683             trait_map: NodeMap(),
1684             module_map,
1685             block_map: NodeMap(),
1686             extern_module_map: FxHashMap(),
1687
1688             make_glob_map: make_glob_map == MakeGlobMap::Yes,
1689             glob_map: NodeMap(),
1690
1691             used_imports: FxHashSet(),
1692             maybe_unused_trait_imports: NodeSet(),
1693             maybe_unused_extern_crates: Vec::new(),
1694
1695             privacy_errors: Vec::new(),
1696             ambiguity_errors: Vec::new(),
1697             use_injections: Vec::new(),
1698             proc_mac_errors: Vec::new(),
1699             gated_errors: FxHashSet(),
1700             disallowed_shadowing: Vec::new(),
1701
1702             arenas,
1703             dummy_binding: arenas.alloc_name_binding(NameBinding {
1704                 kind: NameBindingKind::Def(Def::Err),
1705                 expansion: Mark::root(),
1706                 span: DUMMY_SP,
1707                 vis: ty::Visibility::Public,
1708             }),
1709
1710             // The `proc_macro` and `decl_macro` features imply `use_extern_macros`
1711             use_extern_macros:
1712                 features.use_extern_macros || features.proc_macro || features.decl_macro,
1713
1714             crate_loader,
1715             macro_names: FxHashSet(),
1716             global_macros: FxHashMap(),
1717             all_macros: FxHashMap(),
1718             lexical_macro_resolutions: Vec::new(),
1719             macro_map: FxHashMap(),
1720             macro_exports: Vec::new(),
1721             invocations,
1722             macro_defs,
1723             local_macro_def_scopes: FxHashMap(),
1724             name_already_seen: FxHashMap(),
1725             whitelisted_legacy_custom_derives: Vec::new(),
1726             proc_macro_enabled: features.proc_macro,
1727             warned_proc_macros: FxHashSet(),
1728             potentially_unused_imports: Vec::new(),
1729             struct_constructors: DefIdMap(),
1730             found_unresolved_macro: false,
1731             unused_macros: FxHashSet(),
1732             current_type_ascription: Vec::new(),
1733             injected_crate: None,
1734         }
1735     }
1736
1737     pub fn arenas() -> ResolverArenas<'a> {
1738         ResolverArenas {
1739             modules: arena::TypedArena::new(),
1740             local_modules: RefCell::new(Vec::new()),
1741             name_bindings: arena::TypedArena::new(),
1742             import_directives: arena::TypedArena::new(),
1743             name_resolutions: arena::TypedArena::new(),
1744             invocation_data: arena::TypedArena::new(),
1745             legacy_bindings: arena::TypedArena::new(),
1746         }
1747     }
1748
1749     fn per_ns<T, F: FnMut(&mut Self, Namespace) -> T>(&mut self, mut f: F) -> PerNS<T> {
1750         PerNS {
1751             type_ns: f(self, TypeNS),
1752             value_ns: f(self, ValueNS),
1753             macro_ns: match self.use_extern_macros {
1754                 true => Some(f(self, MacroNS)),
1755                 false => None,
1756             },
1757         }
1758     }
1759
1760     fn macro_def(&self, mut ctxt: SyntaxContext) -> DefId {
1761         loop {
1762             match self.macro_defs.get(&ctxt.outer()) {
1763                 Some(&def_id) => return def_id,
1764                 None => ctxt.remove_mark(),
1765             };
1766         }
1767     }
1768
1769     /// Entry point to crate resolution.
1770     pub fn resolve_crate(&mut self, krate: &Crate) {
1771         ImportResolver { resolver: self }.finalize_imports();
1772         self.current_module = self.graph_root;
1773         self.finalize_current_module_macro_resolutions();
1774
1775         visit::walk_crate(self, krate);
1776
1777         check_unused::check_crate(self, krate);
1778         self.report_errors(krate);
1779         self.crate_loader.postprocess(krate);
1780     }
1781
1782     fn new_module(
1783         &self,
1784         parent: Module<'a>,
1785         kind: ModuleKind,
1786         normal_ancestor_id: DefId,
1787         expansion: Mark,
1788         span: Span,
1789     ) -> Module<'a> {
1790         let module = ModuleData::new(Some(parent), kind, normal_ancestor_id, expansion, span);
1791         self.arenas.alloc_module(module)
1792     }
1793
1794     fn record_use(&mut self, ident: Ident, ns: Namespace, binding: &'a NameBinding<'a>, span: Span)
1795                   -> bool /* true if an error was reported */ {
1796         match binding.kind {
1797             NameBindingKind::Import { directive, binding, ref used, legacy_self_import }
1798                     if !used.get() => {
1799                 used.set(true);
1800                 directive.used.set(true);
1801                 if legacy_self_import {
1802                     self.warn_legacy_self_import(directive);
1803                     return false;
1804                 }
1805                 self.used_imports.insert((directive.id, ns));
1806                 self.add_to_glob_map(directive.id, ident);
1807                 self.record_use(ident, ns, binding, span)
1808             }
1809             NameBindingKind::Import { .. } => false,
1810             NameBindingKind::Ambiguity { b1, b2, legacy } => {
1811                 self.ambiguity_errors.push(AmbiguityError {
1812                     span: span, name: ident.name, lexical: false, b1: b1, b2: b2, legacy,
1813                 });
1814                 if legacy {
1815                     self.record_use(ident, ns, b1, span);
1816                 }
1817                 !legacy
1818             }
1819             _ => false
1820         }
1821     }
1822
1823     fn add_to_glob_map(&mut self, id: NodeId, ident: Ident) {
1824         if self.make_glob_map {
1825             self.glob_map.entry(id).or_insert_with(FxHashSet).insert(ident.name);
1826         }
1827     }
1828
1829     /// This resolves the identifier `ident` in the namespace `ns` in the current lexical scope.
1830     /// More specifically, we proceed up the hierarchy of scopes and return the binding for
1831     /// `ident` in the first scope that defines it (or None if no scopes define it).
1832     ///
1833     /// A block's items are above its local variables in the scope hierarchy, regardless of where
1834     /// the items are defined in the block. For example,
1835     /// ```rust
1836     /// fn f() {
1837     ///    g(); // Since there are no local variables in scope yet, this resolves to the item.
1838     ///    let g = || {};
1839     ///    fn g() {}
1840     ///    g(); // This resolves to the local variable `g` since it shadows the item.
1841     /// }
1842     /// ```
1843     ///
1844     /// Invariant: This must only be called during main resolution, not during
1845     /// import resolution.
1846     fn resolve_ident_in_lexical_scope(&mut self,
1847                                       mut ident: Ident,
1848                                       ns: Namespace,
1849                                       record_used: bool,
1850                                       path_span: Span)
1851                                       -> Option<LexicalScopeBinding<'a>> {
1852         if ns == TypeNS {
1853             ident.ctxt = if ident.name == keywords::SelfType.name() {
1854                 SyntaxContext::empty() // FIXME(jseyfried) improve `Self` hygiene
1855             } else {
1856                 ident.ctxt.modern()
1857             }
1858         }
1859
1860         // Walk backwards up the ribs in scope.
1861         let mut module = self.graph_root;
1862         for i in (0 .. self.ribs[ns].len()).rev() {
1863             if let Some(def) = self.ribs[ns][i].bindings.get(&ident).cloned() {
1864                 // The ident resolves to a type parameter or local variable.
1865                 return Some(LexicalScopeBinding::Def(
1866                     self.adjust_local_def(ns, i, def, record_used, path_span)
1867                 ));
1868             }
1869
1870             module = match self.ribs[ns][i].kind {
1871                 ModuleRibKind(module) => module,
1872                 MacroDefinition(def) if def == self.macro_def(ident.ctxt) => {
1873                     // If an invocation of this macro created `ident`, give up on `ident`
1874                     // and switch to `ident`'s source from the macro definition.
1875                     ident.ctxt.remove_mark();
1876                     continue
1877                 }
1878                 _ => continue,
1879             };
1880
1881             let item = self.resolve_ident_in_module_unadjusted(
1882                 module, ident, ns, false, record_used, path_span,
1883             );
1884             if let Ok(binding) = item {
1885                 // The ident resolves to an item.
1886                 return Some(LexicalScopeBinding::Item(binding));
1887             }
1888
1889             match module.kind {
1890                 ModuleKind::Block(..) => {}, // We can see through blocks
1891                 _ => break,
1892             }
1893         }
1894
1895         ident.ctxt = ident.ctxt.modern();
1896         loop {
1897             module = unwrap_or!(self.hygienic_lexical_parent(module, &mut ident.ctxt), break);
1898             let orig_current_module = self.current_module;
1899             self.current_module = module; // Lexical resolutions can never be a privacy error.
1900             let result = self.resolve_ident_in_module_unadjusted(
1901                 module, ident, ns, false, record_used, path_span,
1902             );
1903             self.current_module = orig_current_module;
1904
1905             match result {
1906                 Ok(binding) => return Some(LexicalScopeBinding::Item(binding)),
1907                 Err(Undetermined) => return None,
1908                 Err(Determined) => {}
1909             }
1910         }
1911
1912         match self.prelude {
1913             Some(prelude) if !module.no_implicit_prelude => {
1914                 self.resolve_ident_in_module_unadjusted(prelude, ident, ns, false, false, path_span)
1915                     .ok().map(LexicalScopeBinding::Item)
1916             }
1917             _ => None,
1918         }
1919     }
1920
1921     fn hygienic_lexical_parent(&mut self, mut module: Module<'a>, ctxt: &mut SyntaxContext)
1922                                -> Option<Module<'a>> {
1923         if !module.expansion.is_descendant_of(ctxt.outer()) {
1924             return Some(self.macro_def_scope(ctxt.remove_mark()));
1925         }
1926
1927         if let ModuleKind::Block(..) = module.kind {
1928             return Some(module.parent.unwrap());
1929         }
1930
1931         let mut module_expansion = module.expansion.modern(); // for backward compatibility
1932         while let Some(parent) = module.parent {
1933             let parent_expansion = parent.expansion.modern();
1934             if module_expansion.is_descendant_of(parent_expansion) &&
1935                parent_expansion != module_expansion {
1936                 return if parent_expansion.is_descendant_of(ctxt.outer()) {
1937                     Some(parent)
1938                 } else {
1939                     None
1940                 };
1941             }
1942             module = parent;
1943             module_expansion = parent_expansion;
1944         }
1945
1946         None
1947     }
1948
1949     fn resolve_ident_in_module(&mut self,
1950                                module: Module<'a>,
1951                                mut ident: Ident,
1952                                ns: Namespace,
1953                                ignore_unresolved_invocations: bool,
1954                                record_used: bool,
1955                                span: Span)
1956                                -> Result<&'a NameBinding<'a>, Determinacy> {
1957         ident.ctxt = ident.ctxt.modern();
1958         let orig_current_module = self.current_module;
1959         if let Some(def) = ident.ctxt.adjust(module.expansion) {
1960             self.current_module = self.macro_def_scope(def);
1961         }
1962         let result = self.resolve_ident_in_module_unadjusted(
1963             module, ident, ns, ignore_unresolved_invocations, record_used, span,
1964         );
1965         self.current_module = orig_current_module;
1966         result
1967     }
1968
1969     fn resolve_crate_root(&mut self, mut ctxt: SyntaxContext, legacy: bool) -> Module<'a> {
1970         let mark = if legacy {
1971             // When resolving `$crate` from a `macro_rules!` invoked in a `macro`,
1972             // we don't want to pretend that the `macro_rules!` definition is in the `macro`
1973             // as described in `SyntaxContext::apply_mark`, so we ignore prepended modern marks.
1974             ctxt.marks().into_iter().find(|&mark| mark.kind() != MarkKind::Modern)
1975         } else {
1976             ctxt = ctxt.modern();
1977             ctxt.adjust(Mark::root())
1978         };
1979         let module = match mark {
1980             Some(def) => self.macro_def_scope(def),
1981             None => return self.graph_root,
1982         };
1983         self.get_module(DefId { index: CRATE_DEF_INDEX, ..module.normal_ancestor_id })
1984     }
1985
1986     fn resolve_self(&mut self, ctxt: &mut SyntaxContext, module: Module<'a>) -> Module<'a> {
1987         let mut module = self.get_module(module.normal_ancestor_id);
1988         while module.span.ctxt().modern() != *ctxt {
1989             let parent = module.parent.unwrap_or_else(|| self.macro_def_scope(ctxt.remove_mark()));
1990             module = self.get_module(parent.normal_ancestor_id);
1991         }
1992         module
1993     }
1994
1995     // AST resolution
1996     //
1997     // We maintain a list of value ribs and type ribs.
1998     //
1999     // Simultaneously, we keep track of the current position in the module
2000     // graph in the `current_module` pointer. When we go to resolve a name in
2001     // the value or type namespaces, we first look through all the ribs and
2002     // then query the module graph. When we resolve a name in the module
2003     // namespace, we can skip all the ribs (since nested modules are not
2004     // allowed within blocks in Rust) and jump straight to the current module
2005     // graph node.
2006     //
2007     // Named implementations are handled separately. When we find a method
2008     // call, we consult the module node to find all of the implementations in
2009     // scope. This information is lazily cached in the module node. We then
2010     // generate a fake "implementation scope" containing all the
2011     // implementations thus found, for compatibility with old resolve pass.
2012
2013     pub fn with_scope<F, T>(&mut self, id: NodeId, f: F) -> T
2014         where F: FnOnce(&mut Resolver) -> T
2015     {
2016         let id = self.definitions.local_def_id(id);
2017         let module = self.module_map.get(&id).cloned(); // clones a reference
2018         if let Some(module) = module {
2019             // Move down in the graph.
2020             let orig_module = replace(&mut self.current_module, module);
2021             self.ribs[ValueNS].push(Rib::new(ModuleRibKind(module)));
2022             self.ribs[TypeNS].push(Rib::new(ModuleRibKind(module)));
2023
2024             self.finalize_current_module_macro_resolutions();
2025             let ret = f(self);
2026
2027             self.current_module = orig_module;
2028             self.ribs[ValueNS].pop();
2029             self.ribs[TypeNS].pop();
2030             ret
2031         } else {
2032             f(self)
2033         }
2034     }
2035
2036     /// Searches the current set of local scopes for labels. Returns the first non-None label that
2037     /// is returned by the given predicate function
2038     ///
2039     /// Stops after meeting a closure.
2040     fn search_label<P, R>(&self, mut ident: Ident, pred: P) -> Option<R>
2041         where P: Fn(&Rib, Ident) -> Option<R>
2042     {
2043         for rib in self.label_ribs.iter().rev() {
2044             match rib.kind {
2045                 NormalRibKind => {}
2046                 // If an invocation of this macro created `ident`, give up on `ident`
2047                 // and switch to `ident`'s source from the macro definition.
2048                 MacroDefinition(def) => {
2049                     if def == self.macro_def(ident.ctxt) {
2050                         ident.ctxt.remove_mark();
2051                     }
2052                 }
2053                 _ => {
2054                     // Do not resolve labels across function boundary
2055                     return None;
2056                 }
2057             }
2058             let r = pred(rib, ident);
2059             if r.is_some() {
2060                 return r;
2061             }
2062         }
2063         None
2064     }
2065
2066     fn resolve_item(&mut self, item: &Item) {
2067         let name = item.ident.name;
2068
2069         debug!("(resolving item) resolving {}", name);
2070
2071         self.check_proc_macro_attrs(&item.attrs);
2072
2073         match item.node {
2074             ItemKind::Enum(_, ref generics) |
2075             ItemKind::Ty(_, ref generics) |
2076             ItemKind::Struct(_, ref generics) |
2077             ItemKind::Union(_, ref generics) |
2078             ItemKind::Fn(.., ref generics, _) => {
2079                 self.with_type_parameter_rib(HasTypeParameters(generics, ItemRibKind),
2080                                              |this| visit::walk_item(this, item));
2081             }
2082
2083             ItemKind::Impl(.., ref generics, ref opt_trait_ref, ref self_type, ref impl_items) =>
2084                 self.resolve_implementation(generics,
2085                                             opt_trait_ref,
2086                                             &self_type,
2087                                             item.id,
2088                                             impl_items),
2089
2090             ItemKind::Trait(.., ref generics, ref bounds, ref trait_items) => {
2091                 // Create a new rib for the trait-wide type parameters.
2092                 self.with_type_parameter_rib(HasTypeParameters(generics, ItemRibKind), |this| {
2093                     let local_def_id = this.definitions.local_def_id(item.id);
2094                     this.with_self_rib(Def::SelfTy(Some(local_def_id), None), |this| {
2095                         this.visit_generics(generics);
2096                         walk_list!(this, visit_ty_param_bound, bounds);
2097
2098                         for trait_item in trait_items {
2099                             this.check_proc_macro_attrs(&trait_item.attrs);
2100
2101                             let type_parameters = HasTypeParameters(&trait_item.generics,
2102                                                                     TraitOrImplItemRibKind);
2103                             this.with_type_parameter_rib(type_parameters, |this| {
2104                                 match trait_item.node {
2105                                     TraitItemKind::Const(ref ty, ref default) => {
2106                                         this.visit_ty(ty);
2107
2108                                         // Only impose the restrictions of
2109                                         // ConstRibKind for an actual constant
2110                                         // expression in a provided default.
2111                                         if let Some(ref expr) = *default{
2112                                             this.with_constant_rib(|this| {
2113                                                 this.visit_expr(expr);
2114                                             });
2115                                         }
2116                                     }
2117                                     TraitItemKind::Method(_, _) => {
2118                                         visit::walk_trait_item(this, trait_item)
2119                                     }
2120                                     TraitItemKind::Type(..) => {
2121                                         visit::walk_trait_item(this, trait_item)
2122                                     }
2123                                     TraitItemKind::Macro(_) => {
2124                                         panic!("unexpanded macro in resolve!")
2125                                     }
2126                                 };
2127                             });
2128                         }
2129                     });
2130                 });
2131             }
2132
2133             ItemKind::TraitAlias(ref generics, ref bounds) => {
2134                 // Create a new rib for the trait-wide type parameters.
2135                 self.with_type_parameter_rib(HasTypeParameters(generics, ItemRibKind), |this| {
2136                     let local_def_id = this.definitions.local_def_id(item.id);
2137                     this.with_self_rib(Def::SelfTy(Some(local_def_id), None), |this| {
2138                         this.visit_generics(generics);
2139                         walk_list!(this, visit_ty_param_bound, bounds);
2140                     });
2141                 });
2142             }
2143
2144             ItemKind::Mod(_) | ItemKind::ForeignMod(_) => {
2145                 self.with_scope(item.id, |this| {
2146                     visit::walk_item(this, item);
2147                 });
2148             }
2149
2150             ItemKind::Static(ref ty, _, ref expr) |
2151             ItemKind::Const(ref ty, ref expr) => {
2152                 self.with_item_rib(|this| {
2153                     this.visit_ty(ty);
2154                     this.with_constant_rib(|this| {
2155                         this.visit_expr(expr);
2156                     });
2157                 });
2158             }
2159
2160             ItemKind::Use(ref use_tree) => {
2161                 let path = Path {
2162                     segments: vec![],
2163                     span: use_tree.span,
2164                 };
2165                 self.resolve_use_tree(item.id, use_tree, &path);
2166             }
2167
2168             ItemKind::ExternCrate(_) | ItemKind::MacroDef(..) | ItemKind::GlobalAsm(_) => {
2169                 // do nothing, these are just around to be encoded
2170             }
2171
2172             ItemKind::Mac(_) => panic!("unexpanded macro in resolve!"),
2173         }
2174     }
2175
2176     fn resolve_use_tree(&mut self, id: NodeId, use_tree: &ast::UseTree, prefix: &Path) {
2177         match use_tree.kind {
2178             ast::UseTreeKind::Nested(ref items) => {
2179                 let path = Path {
2180                     segments: prefix.segments
2181                         .iter()
2182                         .chain(use_tree.prefix.segments.iter())
2183                         .cloned()
2184                         .collect(),
2185                     span: prefix.span.to(use_tree.prefix.span),
2186                 };
2187
2188                 if items.len() == 0 {
2189                     // Resolve prefix of an import with empty braces (issue #28388).
2190                     self.smart_resolve_path(id, None, &path, PathSource::ImportPrefix);
2191                 } else {
2192                     for &(ref tree, nested_id) in items {
2193                         self.resolve_use_tree(nested_id, tree, &path);
2194                     }
2195                 }
2196             }
2197             ast::UseTreeKind::Simple(_) => {},
2198             ast::UseTreeKind::Glob => {},
2199         }
2200     }
2201
2202     fn with_type_parameter_rib<'b, F>(&'b mut self, type_parameters: TypeParameters<'a, 'b>, f: F)
2203         where F: FnOnce(&mut Resolver)
2204     {
2205         match type_parameters {
2206             HasTypeParameters(generics, rib_kind) => {
2207                 let mut function_type_rib = Rib::new(rib_kind);
2208                 let mut seen_bindings = FxHashMap();
2209                 for param in &generics.params {
2210                     if let GenericParam::Type(ref type_parameter) = *param {
2211                         let ident = type_parameter.ident.modern();
2212                         debug!("with_type_parameter_rib: {}", type_parameter.id);
2213
2214                         if seen_bindings.contains_key(&ident) {
2215                             let span = seen_bindings.get(&ident).unwrap();
2216                             let err = ResolutionError::NameAlreadyUsedInTypeParameterList(
2217                                 ident.name,
2218                                 span,
2219                             );
2220                             resolve_error(self, type_parameter.span, err);
2221                         }
2222                         seen_bindings.entry(ident).or_insert(type_parameter.span);
2223
2224                         // plain insert (no renaming)
2225                         let def_id = self.definitions.local_def_id(type_parameter.id);
2226                         let def = Def::TyParam(def_id);
2227                         function_type_rib.bindings.insert(ident, def);
2228                         self.record_def(type_parameter.id, PathResolution::new(def));
2229                     }
2230                 }
2231                 self.ribs[TypeNS].push(function_type_rib);
2232             }
2233
2234             NoTypeParameters => {
2235                 // Nothing to do.
2236             }
2237         }
2238
2239         f(self);
2240
2241         if let HasTypeParameters(..) = type_parameters {
2242             self.ribs[TypeNS].pop();
2243         }
2244     }
2245
2246     fn with_label_rib<F>(&mut self, f: F)
2247         where F: FnOnce(&mut Resolver)
2248     {
2249         self.label_ribs.push(Rib::new(NormalRibKind));
2250         f(self);
2251         self.label_ribs.pop();
2252     }
2253
2254     fn with_item_rib<F>(&mut self, f: F)
2255         where F: FnOnce(&mut Resolver)
2256     {
2257         self.ribs[ValueNS].push(Rib::new(ItemRibKind));
2258         self.ribs[TypeNS].push(Rib::new(ItemRibKind));
2259         f(self);
2260         self.ribs[TypeNS].pop();
2261         self.ribs[ValueNS].pop();
2262     }
2263
2264     fn with_constant_rib<F>(&mut self, f: F)
2265         where F: FnOnce(&mut Resolver)
2266     {
2267         self.ribs[ValueNS].push(Rib::new(ConstantItemRibKind));
2268         f(self);
2269         self.ribs[ValueNS].pop();
2270     }
2271
2272     fn with_current_self_type<T, F>(&mut self, self_type: &Ty, f: F) -> T
2273         where F: FnOnce(&mut Resolver) -> T
2274     {
2275         // Handle nested impls (inside fn bodies)
2276         let previous_value = replace(&mut self.current_self_type, Some(self_type.clone()));
2277         let result = f(self);
2278         self.current_self_type = previous_value;
2279         result
2280     }
2281
2282     /// This is called to resolve a trait reference from an `impl` (i.e. `impl Trait for Foo`)
2283     fn with_optional_trait_ref<T, F>(&mut self, opt_trait_ref: Option<&TraitRef>, f: F) -> T
2284         where F: FnOnce(&mut Resolver, Option<DefId>) -> T
2285     {
2286         let mut new_val = None;
2287         let mut new_id = None;
2288         if let Some(trait_ref) = opt_trait_ref {
2289             let path: Vec<_> = trait_ref.path.segments.iter()
2290                 .map(|seg| respan(seg.span, seg.identifier))
2291                 .collect();
2292             let def = self.smart_resolve_path_fragment(
2293                 trait_ref.ref_id,
2294                 None,
2295                 &path,
2296                 trait_ref.path.span,
2297                 trait_ref.path.segments.last().unwrap().span,
2298                 PathSource::Trait(AliasPossibility::No)
2299             ).base_def();
2300             if def != Def::Err {
2301                 new_id = Some(def.def_id());
2302                 let span = trait_ref.path.span;
2303                 if let PathResult::Module(module) = self.resolve_path(&path, None, false, span) {
2304                     new_val = Some((module, trait_ref.clone()));
2305                 }
2306             }
2307         }
2308         let original_trait_ref = replace(&mut self.current_trait_ref, new_val);
2309         let result = f(self, new_id);
2310         self.current_trait_ref = original_trait_ref;
2311         result
2312     }
2313
2314     fn with_self_rib<F>(&mut self, self_def: Def, f: F)
2315         where F: FnOnce(&mut Resolver)
2316     {
2317         let mut self_type_rib = Rib::new(NormalRibKind);
2318
2319         // plain insert (no renaming, types are not currently hygienic....)
2320         self_type_rib.bindings.insert(keywords::SelfType.ident(), self_def);
2321         self.ribs[TypeNS].push(self_type_rib);
2322         f(self);
2323         self.ribs[TypeNS].pop();
2324     }
2325
2326     fn resolve_implementation(&mut self,
2327                               generics: &Generics,
2328                               opt_trait_reference: &Option<TraitRef>,
2329                               self_type: &Ty,
2330                               item_id: NodeId,
2331                               impl_items: &[ImplItem]) {
2332         // If applicable, create a rib for the type parameters.
2333         self.with_type_parameter_rib(HasTypeParameters(generics, ItemRibKind), |this| {
2334             // Dummy self type for better errors if `Self` is used in the trait path.
2335             this.with_self_rib(Def::SelfTy(None, None), |this| {
2336                 // Resolve the trait reference, if necessary.
2337                 this.with_optional_trait_ref(opt_trait_reference.as_ref(), |this, trait_id| {
2338                     let item_def_id = this.definitions.local_def_id(item_id);
2339                     this.with_self_rib(Def::SelfTy(trait_id, Some(item_def_id)), |this| {
2340                         if let Some(trait_ref) = opt_trait_reference.as_ref() {
2341                             // Resolve type arguments in trait path
2342                             visit::walk_trait_ref(this, trait_ref);
2343                         }
2344                         // Resolve the self type.
2345                         this.visit_ty(self_type);
2346                         // Resolve the type parameters.
2347                         this.visit_generics(generics);
2348                         this.with_current_self_type(self_type, |this| {
2349                             for impl_item in impl_items {
2350                                 this.check_proc_macro_attrs(&impl_item.attrs);
2351                                 this.resolve_visibility(&impl_item.vis);
2352
2353                                 // We also need a new scope for the impl item type parameters.
2354                                 let type_parameters = HasTypeParameters(&impl_item.generics,
2355                                                                         TraitOrImplItemRibKind);
2356                                 this.with_type_parameter_rib(type_parameters, |this| {
2357                                     use self::ResolutionError::*;
2358                                     match impl_item.node {
2359                                         ImplItemKind::Const(..) => {
2360                                             // If this is a trait impl, ensure the const
2361                                             // exists in trait
2362                                             this.check_trait_item(impl_item.ident,
2363                                                                 ValueNS,
2364                                                                 impl_item.span,
2365                                                 |n, s| ConstNotMemberOfTrait(n, s));
2366                                             this.with_constant_rib(|this|
2367                                                 visit::walk_impl_item(this, impl_item)
2368                                             );
2369                                         }
2370                                         ImplItemKind::Method(_, _) => {
2371                                             // If this is a trait impl, ensure the method
2372                                             // exists in trait
2373                                             this.check_trait_item(impl_item.ident,
2374                                                                 ValueNS,
2375                                                                 impl_item.span,
2376                                                 |n, s| MethodNotMemberOfTrait(n, s));
2377
2378                                             visit::walk_impl_item(this, impl_item);
2379                                         }
2380                                         ImplItemKind::Type(ref ty) => {
2381                                             // If this is a trait impl, ensure the type
2382                                             // exists in trait
2383                                             this.check_trait_item(impl_item.ident,
2384                                                                 TypeNS,
2385                                                                 impl_item.span,
2386                                                 |n, s| TypeNotMemberOfTrait(n, s));
2387
2388                                             this.visit_ty(ty);
2389                                         }
2390                                         ImplItemKind::Macro(_) =>
2391                                             panic!("unexpanded macro in resolve!"),
2392                                     }
2393                                 });
2394                             }
2395                         });
2396                     });
2397                 });
2398             });
2399         });
2400     }
2401
2402     fn check_trait_item<F>(&mut self, ident: Ident, ns: Namespace, span: Span, err: F)
2403         where F: FnOnce(Name, &str) -> ResolutionError
2404     {
2405         // If there is a TraitRef in scope for an impl, then the method must be in the
2406         // trait.
2407         if let Some((module, _)) = self.current_trait_ref {
2408             if self.resolve_ident_in_module(module, ident, ns, false, false, span).is_err() {
2409                 let path = &self.current_trait_ref.as_ref().unwrap().1.path;
2410                 resolve_error(self, span, err(ident.name, &path_names_to_string(path)));
2411             }
2412         }
2413     }
2414
2415     fn resolve_local(&mut self, local: &Local) {
2416         // Resolve the type.
2417         walk_list!(self, visit_ty, &local.ty);
2418
2419         // Resolve the initializer.
2420         walk_list!(self, visit_expr, &local.init);
2421
2422         // Resolve the pattern.
2423         self.resolve_pattern(&local.pat, PatternSource::Let, &mut FxHashMap());
2424     }
2425
2426     // build a map from pattern identifiers to binding-info's.
2427     // this is done hygienically. This could arise for a macro
2428     // that expands into an or-pattern where one 'x' was from the
2429     // user and one 'x' came from the macro.
2430     fn binding_mode_map(&mut self, pat: &Pat) -> BindingMap {
2431         let mut binding_map = FxHashMap();
2432
2433         pat.walk(&mut |pat| {
2434             if let PatKind::Ident(binding_mode, ident, ref sub_pat) = pat.node {
2435                 if sub_pat.is_some() || match self.def_map.get(&pat.id).map(|res| res.base_def()) {
2436                     Some(Def::Local(..)) => true,
2437                     _ => false,
2438                 } {
2439                     let binding_info = BindingInfo { span: ident.span, binding_mode: binding_mode };
2440                     binding_map.insert(ident.node, binding_info);
2441                 }
2442             }
2443             true
2444         });
2445
2446         binding_map
2447     }
2448
2449     // check that all of the arms in an or-pattern have exactly the
2450     // same set of bindings, with the same binding modes for each.
2451     fn check_consistent_bindings(&mut self, pats: &[P<Pat>]) {
2452         if pats.is_empty() {
2453             return;
2454         }
2455
2456         let mut missing_vars = FxHashMap();
2457         let mut inconsistent_vars = FxHashMap();
2458         for (i, p) in pats.iter().enumerate() {
2459             let map_i = self.binding_mode_map(&p);
2460
2461             for (j, q) in pats.iter().enumerate() {
2462                 if i == j {
2463                     continue;
2464                 }
2465
2466                 let map_j = self.binding_mode_map(&q);
2467                 for (&key, &binding_i) in &map_i {
2468                     if map_j.len() == 0 {                   // Account for missing bindings when
2469                         let binding_error = missing_vars    // map_j has none.
2470                             .entry(key.name)
2471                             .or_insert(BindingError {
2472                                 name: key.name,
2473                                 origin: BTreeSet::new(),
2474                                 target: BTreeSet::new(),
2475                             });
2476                         binding_error.origin.insert(binding_i.span);
2477                         binding_error.target.insert(q.span);
2478                     }
2479                     for (&key_j, &binding_j) in &map_j {
2480                         match map_i.get(&key_j) {
2481                             None => {  // missing binding
2482                                 let binding_error = missing_vars
2483                                     .entry(key_j.name)
2484                                     .or_insert(BindingError {
2485                                         name: key_j.name,
2486                                         origin: BTreeSet::new(),
2487                                         target: BTreeSet::new(),
2488                                     });
2489                                 binding_error.origin.insert(binding_j.span);
2490                                 binding_error.target.insert(p.span);
2491                             }
2492                             Some(binding_i) => {  // check consistent binding
2493                                 if binding_i.binding_mode != binding_j.binding_mode {
2494                                     inconsistent_vars
2495                                         .entry(key.name)
2496                                         .or_insert((binding_j.span, binding_i.span));
2497                                 }
2498                             }
2499                         }
2500                     }
2501                 }
2502             }
2503         }
2504         let mut missing_vars = missing_vars.iter().collect::<Vec<_>>();
2505         missing_vars.sort();
2506         for (_, v) in missing_vars {
2507             resolve_error(self,
2508                           *v.origin.iter().next().unwrap(),
2509                           ResolutionError::VariableNotBoundInPattern(v));
2510         }
2511         let mut inconsistent_vars = inconsistent_vars.iter().collect::<Vec<_>>();
2512         inconsistent_vars.sort();
2513         for (name, v) in inconsistent_vars {
2514             resolve_error(self, v.0, ResolutionError::VariableBoundWithDifferentMode(*name, v.1));
2515         }
2516     }
2517
2518     fn resolve_arm(&mut self, arm: &Arm) {
2519         self.ribs[ValueNS].push(Rib::new(NormalRibKind));
2520
2521         let mut bindings_list = FxHashMap();
2522         for pattern in &arm.pats {
2523             self.resolve_pattern(&pattern, PatternSource::Match, &mut bindings_list);
2524         }
2525
2526         // This has to happen *after* we determine which pat_idents are variants
2527         self.check_consistent_bindings(&arm.pats);
2528
2529         walk_list!(self, visit_expr, &arm.guard);
2530         self.visit_expr(&arm.body);
2531
2532         self.ribs[ValueNS].pop();
2533     }
2534
2535     fn resolve_block(&mut self, block: &Block) {
2536         debug!("(resolving block) entering block");
2537         // Move down in the graph, if there's an anonymous module rooted here.
2538         let orig_module = self.current_module;
2539         let anonymous_module = self.block_map.get(&block.id).cloned(); // clones a reference
2540
2541         let mut num_macro_definition_ribs = 0;
2542         if let Some(anonymous_module) = anonymous_module {
2543             debug!("(resolving block) found anonymous module, moving down");
2544             self.ribs[ValueNS].push(Rib::new(ModuleRibKind(anonymous_module)));
2545             self.ribs[TypeNS].push(Rib::new(ModuleRibKind(anonymous_module)));
2546             self.current_module = anonymous_module;
2547             self.finalize_current_module_macro_resolutions();
2548         } else {
2549             self.ribs[ValueNS].push(Rib::new(NormalRibKind));
2550         }
2551
2552         // Descend into the block.
2553         for stmt in &block.stmts {
2554             if let ast::StmtKind::Item(ref item) = stmt.node {
2555                 if let ast::ItemKind::MacroDef(..) = item.node {
2556                     num_macro_definition_ribs += 1;
2557                     let def = self.definitions.local_def_id(item.id);
2558                     self.ribs[ValueNS].push(Rib::new(MacroDefinition(def)));
2559                     self.label_ribs.push(Rib::new(MacroDefinition(def)));
2560                 }
2561             }
2562
2563             self.visit_stmt(stmt);
2564         }
2565
2566         // Move back up.
2567         self.current_module = orig_module;
2568         for _ in 0 .. num_macro_definition_ribs {
2569             self.ribs[ValueNS].pop();
2570             self.label_ribs.pop();
2571         }
2572         self.ribs[ValueNS].pop();
2573         if let Some(_) = anonymous_module {
2574             self.ribs[TypeNS].pop();
2575         }
2576         debug!("(resolving block) leaving block");
2577     }
2578
2579     fn fresh_binding(&mut self,
2580                      ident: &SpannedIdent,
2581                      pat_id: NodeId,
2582                      outer_pat_id: NodeId,
2583                      pat_src: PatternSource,
2584                      bindings: &mut FxHashMap<Ident, NodeId>)
2585                      -> PathResolution {
2586         // Add the binding to the local ribs, if it
2587         // doesn't already exist in the bindings map. (We
2588         // must not add it if it's in the bindings map
2589         // because that breaks the assumptions later
2590         // passes make about or-patterns.)
2591         let mut def = Def::Local(pat_id);
2592         match bindings.get(&ident.node).cloned() {
2593             Some(id) if id == outer_pat_id => {
2594                 // `Variant(a, a)`, error
2595                 resolve_error(
2596                     self,
2597                     ident.span,
2598                     ResolutionError::IdentifierBoundMoreThanOnceInSamePattern(
2599                         &ident.node.name.as_str())
2600                 );
2601             }
2602             Some(..) if pat_src == PatternSource::FnParam => {
2603                 // `fn f(a: u8, a: u8)`, error
2604                 resolve_error(
2605                     self,
2606                     ident.span,
2607                     ResolutionError::IdentifierBoundMoreThanOnceInParameterList(
2608                         &ident.node.name.as_str())
2609                 );
2610             }
2611             Some(..) if pat_src == PatternSource::Match ||
2612                         pat_src == PatternSource::IfLet ||
2613                         pat_src == PatternSource::WhileLet => {
2614                 // `Variant1(a) | Variant2(a)`, ok
2615                 // Reuse definition from the first `a`.
2616                 def = self.ribs[ValueNS].last_mut().unwrap().bindings[&ident.node];
2617             }
2618             Some(..) => {
2619                 span_bug!(ident.span, "two bindings with the same name from \
2620                                        unexpected pattern source {:?}", pat_src);
2621             }
2622             None => {
2623                 // A completely fresh binding, add to the lists if it's valid.
2624                 if ident.node.name != keywords::Invalid.name() {
2625                     bindings.insert(ident.node, outer_pat_id);
2626                     self.ribs[ValueNS].last_mut().unwrap().bindings.insert(ident.node, def);
2627                 }
2628             }
2629         }
2630
2631         PathResolution::new(def)
2632     }
2633
2634     fn resolve_pattern(&mut self,
2635                        pat: &Pat,
2636                        pat_src: PatternSource,
2637                        // Maps idents to the node ID for the
2638                        // outermost pattern that binds them.
2639                        bindings: &mut FxHashMap<Ident, NodeId>) {
2640         // Visit all direct subpatterns of this pattern.
2641         let outer_pat_id = pat.id;
2642         pat.walk(&mut |pat| {
2643             match pat.node {
2644                 PatKind::Ident(bmode, ref ident, ref opt_pat) => {
2645                     // First try to resolve the identifier as some existing
2646                     // entity, then fall back to a fresh binding.
2647                     let binding = self.resolve_ident_in_lexical_scope(ident.node, ValueNS,
2648                                                                       false, pat.span)
2649                                       .and_then(LexicalScopeBinding::item);
2650                     let resolution = binding.map(NameBinding::def).and_then(|def| {
2651                         let is_syntactic_ambiguity = opt_pat.is_none() &&
2652                             bmode == BindingMode::ByValue(Mutability::Immutable);
2653                         match def {
2654                             Def::StructCtor(_, CtorKind::Const) |
2655                             Def::VariantCtor(_, CtorKind::Const) |
2656                             Def::Const(..) if is_syntactic_ambiguity => {
2657                                 // Disambiguate in favor of a unit struct/variant
2658                                 // or constant pattern.
2659                                 self.record_use(ident.node, ValueNS, binding.unwrap(), ident.span);
2660                                 Some(PathResolution::new(def))
2661                             }
2662                             Def::StructCtor(..) | Def::VariantCtor(..) |
2663                             Def::Const(..) | Def::Static(..) => {
2664                                 // This is unambiguously a fresh binding, either syntactically
2665                                 // (e.g. `IDENT @ PAT` or `ref IDENT`) or because `IDENT` resolves
2666                                 // to something unusable as a pattern (e.g. constructor function),
2667                                 // but we still conservatively report an error, see
2668                                 // issues/33118#issuecomment-233962221 for one reason why.
2669                                 resolve_error(
2670                                     self,
2671                                     ident.span,
2672                                     ResolutionError::BindingShadowsSomethingUnacceptable(
2673                                         pat_src.descr(), ident.node.name, binding.unwrap())
2674                                 );
2675                                 None
2676                             }
2677                             Def::Fn(..) | Def::Err => {
2678                                 // These entities are explicitly allowed
2679                                 // to be shadowed by fresh bindings.
2680                                 None
2681                             }
2682                             def => {
2683                                 span_bug!(ident.span, "unexpected definition for an \
2684                                                        identifier in pattern: {:?}", def);
2685                             }
2686                         }
2687                     }).unwrap_or_else(|| {
2688                         self.fresh_binding(ident, pat.id, outer_pat_id, pat_src, bindings)
2689                     });
2690
2691                     self.record_def(pat.id, resolution);
2692                 }
2693
2694                 PatKind::TupleStruct(ref path, ..) => {
2695                     self.smart_resolve_path(pat.id, None, path, PathSource::TupleStruct);
2696                 }
2697
2698                 PatKind::Path(ref qself, ref path) => {
2699                     self.smart_resolve_path(pat.id, qself.as_ref(), path, PathSource::Pat);
2700                 }
2701
2702                 PatKind::Struct(ref path, ..) => {
2703                     self.smart_resolve_path(pat.id, None, path, PathSource::Struct);
2704                 }
2705
2706                 _ => {}
2707             }
2708             true
2709         });
2710
2711         visit::walk_pat(self, pat);
2712     }
2713
2714     // High-level and context dependent path resolution routine.
2715     // Resolves the path and records the resolution into definition map.
2716     // If resolution fails tries several techniques to find likely
2717     // resolution candidates, suggest imports or other help, and report
2718     // errors in user friendly way.
2719     fn smart_resolve_path(&mut self,
2720                           id: NodeId,
2721                           qself: Option<&QSelf>,
2722                           path: &Path,
2723                           source: PathSource)
2724                           -> PathResolution {
2725         let segments = &path.segments.iter()
2726             .map(|seg| respan(seg.span, seg.identifier))
2727             .collect::<Vec<_>>();
2728         let ident_span = path.segments.last().map_or(path.span, |seg| seg.span);
2729         self.smart_resolve_path_fragment(id, qself, segments, path.span, ident_span, source)
2730     }
2731
2732     fn smart_resolve_path_fragment(&mut self,
2733                                    id: NodeId,
2734                                    qself: Option<&QSelf>,
2735                                    path: &[SpannedIdent],
2736                                    span: Span,
2737                                    ident_span: Span,
2738                                    source: PathSource)
2739                                    -> PathResolution {
2740         let ns = source.namespace();
2741         let is_expected = &|def| source.is_expected(def);
2742         let is_enum_variant = &|def| if let Def::Variant(..) = def { true } else { false };
2743
2744         // Base error is amended with one short label and possibly some longer helps/notes.
2745         let report_errors = |this: &mut Self, def: Option<Def>| {
2746             // Make the base error.
2747             let expected = source.descr_expected();
2748             let path_str = names_to_string(path);
2749             let code = source.error_code(def.is_some());
2750             let (base_msg, fallback_label, base_span) = if let Some(def) = def {
2751                 (format!("expected {}, found {} `{}`", expected, def.kind_name(), path_str),
2752                  format!("not a {}", expected),
2753                  span)
2754             } else {
2755                 let item_str = path[path.len() - 1].node;
2756                 let item_span = path[path.len() - 1].span;
2757                 let (mod_prefix, mod_str) = if path.len() == 1 {
2758                     (format!(""), format!("this scope"))
2759                 } else if path.len() == 2 && path[0].node.name == keywords::CrateRoot.name() {
2760                     (format!(""), format!("the crate root"))
2761                 } else {
2762                     let mod_path = &path[..path.len() - 1];
2763                     let mod_prefix = match this.resolve_path(mod_path, Some(TypeNS), false, span) {
2764                         PathResult::Module(module) => module.def(),
2765                         _ => None,
2766                     }.map_or(format!(""), |def| format!("{} ", def.kind_name()));
2767                     (mod_prefix, format!("`{}`", names_to_string(mod_path)))
2768                 };
2769                 (format!("cannot find {} `{}` in {}{}", expected, item_str, mod_prefix, mod_str),
2770                  format!("not found in {}", mod_str),
2771                  item_span)
2772             };
2773             let code = DiagnosticId::Error(code.into());
2774             let mut err = this.session.struct_span_err_with_code(base_span, &base_msg, code);
2775
2776             // Emit special messages for unresolved `Self` and `self`.
2777             if is_self_type(path, ns) {
2778                 __diagnostic_used!(E0411);
2779                 err.code(DiagnosticId::Error("E0411".into()));
2780                 err.span_label(span, "`Self` is only available in traits and impls");
2781                 return (err, Vec::new());
2782             }
2783             if is_self_value(path, ns) {
2784                 __diagnostic_used!(E0424);
2785                 err.code(DiagnosticId::Error("E0424".into()));
2786                 err.span_label(span, format!("`self` value is only available in \
2787                                                methods with `self` parameter"));
2788                 return (err, Vec::new());
2789             }
2790
2791             // Try to lookup the name in more relaxed fashion for better error reporting.
2792             let ident = *path.last().unwrap();
2793             let candidates = this.lookup_import_candidates(ident.node.name, ns, is_expected);
2794             if candidates.is_empty() && is_expected(Def::Enum(DefId::local(CRATE_DEF_INDEX))) {
2795                 let enum_candidates =
2796                     this.lookup_import_candidates(ident.node.name, ns, is_enum_variant);
2797                 let mut enum_candidates = enum_candidates.iter()
2798                     .map(|suggestion| import_candidate_to_paths(&suggestion)).collect::<Vec<_>>();
2799                 enum_candidates.sort();
2800                 for (sp, variant_path, enum_path) in enum_candidates {
2801                     if sp == DUMMY_SP {
2802                         let msg = format!("there is an enum variant `{}`, \
2803                                         try using `{}`?",
2804                                         variant_path,
2805                                         enum_path);
2806                         err.help(&msg);
2807                     } else {
2808                         err.span_suggestion(span, "you can try using the variant's enum",
2809                                             enum_path);
2810                     }
2811                 }
2812             }
2813             if path.len() == 1 && this.self_type_is_available(span) {
2814                 if let Some(candidate) = this.lookup_assoc_candidate(ident.node, ns, is_expected) {
2815                     let self_is_available = this.self_value_is_available(path[0].node.ctxt, span);
2816                     match candidate {
2817                         AssocSuggestion::Field => {
2818                             err.span_suggestion(span, "try",
2819                                                 format!("self.{}", path_str));
2820                             if !self_is_available {
2821                                 err.span_label(span, format!("`self` value is only available in \
2822                                                                methods with `self` parameter"));
2823                             }
2824                         }
2825                         AssocSuggestion::MethodWithSelf if self_is_available => {
2826                             err.span_suggestion(span, "try",
2827                                                 format!("self.{}", path_str));
2828                         }
2829                         AssocSuggestion::MethodWithSelf | AssocSuggestion::AssocItem => {
2830                             err.span_suggestion(span, "try",
2831                                                 format!("Self::{}", path_str));
2832                         }
2833                     }
2834                     return (err, candidates);
2835                 }
2836             }
2837
2838             let mut levenshtein_worked = false;
2839
2840             // Try Levenshtein.
2841             if let Some(candidate) = this.lookup_typo_candidate(path, ns, is_expected, span) {
2842                 err.span_label(ident_span, format!("did you mean `{}`?", candidate));
2843                 levenshtein_worked = true;
2844             }
2845
2846             // Try context dependent help if relaxed lookup didn't work.
2847             if let Some(def) = def {
2848                 match (def, source) {
2849                     (Def::Macro(..), _) => {
2850                         err.span_label(span, format!("did you mean `{}!(...)`?", path_str));
2851                         return (err, candidates);
2852                     }
2853                     (Def::TyAlias(..), PathSource::Trait(_)) => {
2854                         err.span_label(span, "type aliases cannot be used for traits");
2855                         return (err, candidates);
2856                     }
2857                     (Def::Mod(..), PathSource::Expr(Some(parent))) => match parent.node {
2858                         ExprKind::Field(_, ident) => {
2859                             err.span_label(parent.span, format!("did you mean `{}::{}`?",
2860                                                                  path_str, ident.node));
2861                             return (err, candidates);
2862                         }
2863                         ExprKind::MethodCall(ref segment, ..) => {
2864                             err.span_label(parent.span, format!("did you mean `{}::{}(...)`?",
2865                                                                  path_str, segment.identifier));
2866                             return (err, candidates);
2867                         }
2868                         _ => {}
2869                     },
2870                     (Def::Enum(..), PathSource::TupleStruct)
2871                         | (Def::Enum(..), PathSource::Expr(..))  => {
2872                         if let Some(variants) = this.collect_enum_variants(def) {
2873                             err.note(&format!("did you mean to use one \
2874                                                of the following variants?\n{}",
2875                                 variants.iter()
2876                                     .map(|suggestion| path_names_to_string(suggestion))
2877                                     .map(|suggestion| format!("- `{}`", suggestion))
2878                                     .collect::<Vec<_>>()
2879                                     .join("\n")));
2880
2881                         } else {
2882                             err.note("did you mean to use one of the enum's variants?");
2883                         }
2884                         return (err, candidates);
2885                     },
2886                     (Def::Struct(def_id), _) if ns == ValueNS => {
2887                         if let Some((ctor_def, ctor_vis))
2888                                 = this.struct_constructors.get(&def_id).cloned() {
2889                             let accessible_ctor = this.is_accessible(ctor_vis);
2890                             if is_expected(ctor_def) && !accessible_ctor {
2891                                 err.span_label(span, format!("constructor is not visible \
2892                                                               here due to private fields"));
2893                             }
2894                         } else {
2895                             err.span_label(span, format!("did you mean `{} {{ /* fields */ }}`?",
2896                                                          path_str));
2897                         }
2898                         return (err, candidates);
2899                     }
2900                     (Def::Union(..), _) |
2901                     (Def::Variant(..), _) |
2902                     (Def::VariantCtor(_, CtorKind::Fictive), _) if ns == ValueNS => {
2903                         err.span_label(span, format!("did you mean `{} {{ /* fields */ }}`?",
2904                                                      path_str));
2905                         return (err, candidates);
2906                     }
2907                     (Def::SelfTy(..), _) if ns == ValueNS => {
2908                         err.span_label(span, fallback_label);
2909                         err.note("can't use `Self` as a constructor, you must use the \
2910                                   implemented struct");
2911                         return (err, candidates);
2912                     }
2913                     (Def::TyAlias(_), _) | (Def::AssociatedTy(..), _) if ns == ValueNS => {
2914                         err.note("can't use a type alias as a constructor");
2915                         return (err, candidates);
2916                     }
2917                     _ => {}
2918                 }
2919             }
2920
2921             // Fallback label.
2922             if !levenshtein_worked {
2923                 err.span_label(base_span, fallback_label);
2924                 this.type_ascription_suggestion(&mut err, base_span);
2925             }
2926             (err, candidates)
2927         };
2928         let report_errors = |this: &mut Self, def: Option<Def>| {
2929             let (err, candidates) = report_errors(this, def);
2930             let def_id = this.current_module.normal_ancestor_id;
2931             let node_id = this.definitions.as_local_node_id(def_id).unwrap();
2932             let better = def.is_some();
2933             this.use_injections.push(UseError { err, candidates, node_id, better });
2934             err_path_resolution()
2935         };
2936
2937         let resolution = match self.resolve_qpath_anywhere(id, qself, path, ns, span,
2938                                                            source.defer_to_typeck(),
2939                                                            source.global_by_default()) {
2940             Some(resolution) if resolution.unresolved_segments() == 0 => {
2941                 if is_expected(resolution.base_def()) || resolution.base_def() == Def::Err {
2942                     resolution
2943                 } else {
2944                     // Add a temporary hack to smooth the transition to new struct ctor
2945                     // visibility rules. See #38932 for more details.
2946                     let mut res = None;
2947                     if let Def::Struct(def_id) = resolution.base_def() {
2948                         if let Some((ctor_def, ctor_vis))
2949                                 = self.struct_constructors.get(&def_id).cloned() {
2950                             if is_expected(ctor_def) && self.is_accessible(ctor_vis) {
2951                                 let lint = lint::builtin::LEGACY_CONSTRUCTOR_VISIBILITY;
2952                                 self.session.buffer_lint(lint, id, span,
2953                                     "private struct constructors are not usable through \
2954                                      re-exports in outer modules",
2955                                 );
2956                                 res = Some(PathResolution::new(ctor_def));
2957                             }
2958                         }
2959                     }
2960
2961                     res.unwrap_or_else(|| report_errors(self, Some(resolution.base_def())))
2962                 }
2963             }
2964             Some(resolution) if source.defer_to_typeck() => {
2965                 // Not fully resolved associated item `T::A::B` or `<T as Tr>::A::B`
2966                 // or `<T>::A::B`. If `B` should be resolved in value namespace then
2967                 // it needs to be added to the trait map.
2968                 if ns == ValueNS {
2969                     let item_name = path.last().unwrap().node;
2970                     let traits = self.get_traits_containing_item(item_name, ns);
2971                     self.trait_map.insert(id, traits);
2972                 }
2973                 resolution
2974             }
2975             _ => report_errors(self, None)
2976         };
2977
2978         if let PathSource::TraitItem(..) = source {} else {
2979             // Avoid recording definition of `A::B` in `<T as A>::B::C`.
2980             self.record_def(id, resolution);
2981         }
2982         resolution
2983     }
2984
2985     fn type_ascription_suggestion(&self,
2986                                   err: &mut DiagnosticBuilder,
2987                                   base_span: Span) {
2988         debug!("type_ascription_suggetion {:?}", base_span);
2989         let cm = self.session.codemap();
2990         debug!("self.current_type_ascription {:?}", self.current_type_ascription);
2991         if let Some(sp) = self.current_type_ascription.last() {
2992             let mut sp = *sp;
2993             loop {  // try to find the `:`, bail on first non-':'/non-whitespace
2994                 sp = cm.next_point(sp);
2995                 if let Ok(snippet) = cm.span_to_snippet(sp.to(cm.next_point(sp))) {
2996                     debug!("snippet {:?}", snippet);
2997                     let line_sp = cm.lookup_char_pos(sp.hi()).line;
2998                     let line_base_sp = cm.lookup_char_pos(base_span.lo()).line;
2999                     debug!("{:?} {:?}", line_sp, line_base_sp);
3000                     if snippet == ":" {
3001                         err.span_label(base_span,
3002                                        "expecting a type here because of type ascription");
3003                         if line_sp != line_base_sp {
3004                             err.span_suggestion_short(sp,
3005                                                       "did you mean to use `;` here instead?",
3006                                                       ";".to_string());
3007                         }
3008                         break;
3009                     } else if snippet.trim().len() != 0  {
3010                         debug!("tried to find type ascription `:` token, couldn't find it");
3011                         break;
3012                     }
3013                 } else {
3014                     break;
3015                 }
3016             }
3017         }
3018     }
3019
3020     fn self_type_is_available(&mut self, span: Span) -> bool {
3021         let binding = self.resolve_ident_in_lexical_scope(keywords::SelfType.ident(),
3022                                                           TypeNS, false, span);
3023         if let Some(LexicalScopeBinding::Def(def)) = binding { def != Def::Err } else { false }
3024     }
3025
3026     fn self_value_is_available(&mut self, ctxt: SyntaxContext, span: Span) -> bool {
3027         let ident = Ident { name: keywords::SelfValue.name(), ctxt: ctxt };
3028         let binding = self.resolve_ident_in_lexical_scope(ident, ValueNS, false, span);
3029         if let Some(LexicalScopeBinding::Def(def)) = binding { def != Def::Err } else { false }
3030     }
3031
3032     // Resolve in alternative namespaces if resolution in the primary namespace fails.
3033     fn resolve_qpath_anywhere(&mut self,
3034                               id: NodeId,
3035                               qself: Option<&QSelf>,
3036                               path: &[SpannedIdent],
3037                               primary_ns: Namespace,
3038                               span: Span,
3039                               defer_to_typeck: bool,
3040                               global_by_default: bool)
3041                               -> Option<PathResolution> {
3042         let mut fin_res = None;
3043         // FIXME: can't resolve paths in macro namespace yet, macros are
3044         // processed by the little special hack below.
3045         for (i, ns) in [primary_ns, TypeNS, ValueNS, /*MacroNS*/].iter().cloned().enumerate() {
3046             if i == 0 || ns != primary_ns {
3047                 match self.resolve_qpath(id, qself, path, ns, span, global_by_default) {
3048                     // If defer_to_typeck, then resolution > no resolution,
3049                     // otherwise full resolution > partial resolution > no resolution.
3050                     Some(res) if res.unresolved_segments() == 0 || defer_to_typeck =>
3051                         return Some(res),
3052                     res => if fin_res.is_none() { fin_res = res },
3053                 };
3054             }
3055         }
3056         let is_global = self.global_macros.get(&path[0].node.name).cloned()
3057             .map(|binding| binding.get_macro(self).kind() == MacroKind::Bang).unwrap_or(false);
3058         if primary_ns != MacroNS && (is_global ||
3059                                      self.macro_names.contains(&path[0].node.modern())) {
3060             // Return some dummy definition, it's enough for error reporting.
3061             return Some(
3062                 PathResolution::new(Def::Macro(DefId::local(CRATE_DEF_INDEX), MacroKind::Bang))
3063             );
3064         }
3065         fin_res
3066     }
3067
3068     /// Handles paths that may refer to associated items.
3069     fn resolve_qpath(&mut self,
3070                      id: NodeId,
3071                      qself: Option<&QSelf>,
3072                      path: &[SpannedIdent],
3073                      ns: Namespace,
3074                      span: Span,
3075                      global_by_default: bool)
3076                      -> Option<PathResolution> {
3077         if let Some(qself) = qself {
3078             if qself.position == 0 {
3079                 // FIXME: Create some fake resolution that can't possibly be a type.
3080                 return Some(PathResolution::with_unresolved_segments(
3081                     Def::Mod(DefId::local(CRATE_DEF_INDEX)), path.len()
3082                 ));
3083             }
3084             // Make sure `A::B` in `<T as A>::B::C` is a trait item.
3085             let ns = if qself.position + 1 == path.len() { ns } else { TypeNS };
3086             let res = self.smart_resolve_path_fragment(id, None, &path[..qself.position + 1],
3087                                                        span, span, PathSource::TraitItem(ns));
3088             return Some(PathResolution::with_unresolved_segments(
3089                 res.base_def(), res.unresolved_segments() + path.len() - qself.position - 1
3090             ));
3091         }
3092
3093         let result = match self.resolve_path(&path, Some(ns), true, span) {
3094             PathResult::NonModule(path_res) => path_res,
3095             PathResult::Module(module) if !module.is_normal() => {
3096                 PathResolution::new(module.def().unwrap())
3097             }
3098             // In `a(::assoc_item)*` `a` cannot be a module. If `a` does resolve to a module we
3099             // don't report an error right away, but try to fallback to a primitive type.
3100             // So, we are still able to successfully resolve something like
3101             //
3102             // use std::u8; // bring module u8 in scope
3103             // fn f() -> u8 { // OK, resolves to primitive u8, not to std::u8
3104             //     u8::max_value() // OK, resolves to associated function <u8>::max_value,
3105             //                     // not to non-existent std::u8::max_value
3106             // }
3107             //
3108             // Such behavior is required for backward compatibility.
3109             // The same fallback is used when `a` resolves to nothing.
3110             PathResult::Module(..) | PathResult::Failed(..)
3111                     if (ns == TypeNS || path.len() > 1) &&
3112                        self.primitive_type_table.primitive_types
3113                            .contains_key(&path[0].node.name) => {
3114                 let prim = self.primitive_type_table.primitive_types[&path[0].node.name];
3115                 match prim {
3116                     TyUint(UintTy::U128) | TyInt(IntTy::I128) => {
3117                         if !self.session.features_untracked().i128_type {
3118                             emit_feature_err(&self.session.parse_sess,
3119                                                 "i128_type", span, GateIssue::Language,
3120                                                 "128-bit type is unstable");
3121
3122                         }
3123                     }
3124                     _ => {}
3125                 }
3126                 PathResolution::with_unresolved_segments(Def::PrimTy(prim), path.len() - 1)
3127             }
3128             PathResult::Module(module) => PathResolution::new(module.def().unwrap()),
3129             PathResult::Failed(span, msg, false) => {
3130                 resolve_error(self, span, ResolutionError::FailedToResolve(&msg));
3131                 err_path_resolution()
3132             }
3133             PathResult::Failed(..) => return None,
3134             PathResult::Indeterminate => bug!("indetermined path result in resolve_qpath"),
3135         };
3136
3137         if path.len() > 1 && !global_by_default && result.base_def() != Def::Err &&
3138            path[0].node.name != keywords::CrateRoot.name() &&
3139            path[0].node.name != keywords::DollarCrate.name() {
3140             let unqualified_result = {
3141                 match self.resolve_path(&[*path.last().unwrap()], Some(ns), false, span) {
3142                     PathResult::NonModule(path_res) => path_res.base_def(),
3143                     PathResult::Module(module) => module.def().unwrap(),
3144                     _ => return Some(result),
3145                 }
3146             };
3147             if result.base_def() == unqualified_result {
3148                 let lint = lint::builtin::UNUSED_QUALIFICATIONS;
3149                 self.session.buffer_lint(lint, id, span, "unnecessary qualification")
3150             }
3151         }
3152
3153         Some(result)
3154     }
3155
3156     fn resolve_path(&mut self,
3157                     path: &[SpannedIdent],
3158                     opt_ns: Option<Namespace>, // `None` indicates a module path
3159                     record_used: bool,
3160                     path_span: Span)
3161                     -> PathResult<'a> {
3162         let mut module = None;
3163         let mut allow_super = true;
3164
3165         for (i, &ident) in path.iter().enumerate() {
3166             debug!("resolve_path ident {} {:?}", i, ident);
3167             let is_last = i == path.len() - 1;
3168             let ns = if is_last { opt_ns.unwrap_or(TypeNS) } else { TypeNS };
3169             let name = ident.node.name;
3170
3171             if i == 0 && ns == TypeNS && name == keywords::SelfValue.name() {
3172                 let mut ctxt = ident.node.ctxt.modern();
3173                 module = Some(self.resolve_self(&mut ctxt, self.current_module));
3174                 continue
3175             } else if allow_super && ns == TypeNS && name == keywords::Super.name() {
3176                 let mut ctxt = ident.node.ctxt.modern();
3177                 let self_module = match i {
3178                     0 => self.resolve_self(&mut ctxt, self.current_module),
3179                     _ => module.unwrap(),
3180                 };
3181                 if let Some(parent) = self_module.parent {
3182                     module = Some(self.resolve_self(&mut ctxt, parent));
3183                     continue
3184                 } else {
3185                     let msg = "There are too many initial `super`s.".to_string();
3186                     return PathResult::Failed(ident.span, msg, false);
3187                 }
3188             } else if i == 0 && ns == TypeNS && name == keywords::Extern.name() {
3189                 continue;
3190             }
3191             allow_super = false;
3192
3193             if ns == TypeNS {
3194                 if (i == 0 && name == keywords::CrateRoot.name()) ||
3195                    (i == 1 && name == keywords::Crate.name() &&
3196                               path[0].node.name == keywords::CrateRoot.name()) {
3197                     // `::a::b` or `::crate::a::b`
3198                     module = Some(self.resolve_crate_root(ident.node.ctxt, false));
3199                     continue
3200                 } else if i == 0 && name == keywords::DollarCrate.name() {
3201                     // `$crate::a::b`
3202                     module = Some(self.resolve_crate_root(ident.node.ctxt, true));
3203                     continue
3204                 } else if i == 1 && !token::Ident(ident.node).is_path_segment_keyword() {
3205                     let prev_name = path[0].node.name;
3206                     if prev_name == keywords::Extern.name() ||
3207                        prev_name == keywords::CrateRoot.name() &&
3208                        self.session.features_untracked().extern_absolute_paths {
3209                         // `::extern_crate::a::b`
3210                         let crate_id = self.crate_loader.resolve_crate_from_path(name, ident.span);
3211                         let crate_root =
3212                             self.get_module(DefId { krate: crate_id, index: CRATE_DEF_INDEX });
3213                         self.populate_module_if_necessary(crate_root);
3214                         module = Some(crate_root);
3215                         continue
3216                     }
3217                 }
3218             }
3219
3220             // Report special messages for path segment keywords in wrong positions.
3221             if name == keywords::CrateRoot.name() && i != 0 ||
3222                name == keywords::DollarCrate.name() && i != 0 ||
3223                name == keywords::SelfValue.name() && i != 0 ||
3224                name == keywords::SelfType.name() && i != 0 ||
3225                name == keywords::Super.name() && i != 0 ||
3226                name == keywords::Extern.name() && i != 0 ||
3227                name == keywords::Crate.name() && i != 1 &&
3228                     path[0].node.name != keywords::CrateRoot.name() {
3229                 let name_str = if name == keywords::CrateRoot.name() {
3230                     format!("crate root")
3231                 } else {
3232                     format!("`{}`", name)
3233                 };
3234                 let msg = if i == 1 && path[0].node.name == keywords::CrateRoot.name() {
3235                     format!("global paths cannot start with {}", name_str)
3236                 } else if i == 0 && name == keywords::Crate.name() {
3237                     format!("{} can only be used in absolute paths", name_str)
3238                 } else {
3239                     format!("{} in paths can only be used in start position", name_str)
3240                 };
3241                 return PathResult::Failed(ident.span, msg, false);
3242             }
3243
3244             let binding = if let Some(module) = module {
3245                 self.resolve_ident_in_module(module, ident.node, ns, false, record_used, path_span)
3246             } else if opt_ns == Some(MacroNS) {
3247                 self.resolve_lexical_macro_path_segment(ident.node, ns, record_used, path_span)
3248                     .map(MacroBinding::binding)
3249             } else {
3250                 match self.resolve_ident_in_lexical_scope(ident.node, ns, record_used, path_span) {
3251                     Some(LexicalScopeBinding::Item(binding)) => Ok(binding),
3252                     Some(LexicalScopeBinding::Def(def))
3253                             if opt_ns == Some(TypeNS) || opt_ns == Some(ValueNS) => {
3254                         return PathResult::NonModule(PathResolution::with_unresolved_segments(
3255                             def, path.len() - 1
3256                         ));
3257                     }
3258                     _ => Err(if record_used { Determined } else { Undetermined }),
3259                 }
3260             };
3261
3262             match binding {
3263                 Ok(binding) => {
3264                     let def = binding.def();
3265                     let maybe_assoc = opt_ns != Some(MacroNS) && PathSource::Type.is_expected(def);
3266                     if let Some(next_module) = binding.module() {
3267                         module = Some(next_module);
3268                     } else if def == Def::Err {
3269                         return PathResult::NonModule(err_path_resolution());
3270                     } else if opt_ns.is_some() && (is_last || maybe_assoc) {
3271                         return PathResult::NonModule(PathResolution::with_unresolved_segments(
3272                             def, path.len() - i - 1
3273                         ));
3274                     } else {
3275                         return PathResult::Failed(ident.span,
3276                                                   format!("Not a module `{}`", ident.node),
3277                                                   is_last);
3278                     }
3279                 }
3280                 Err(Undetermined) => return PathResult::Indeterminate,
3281                 Err(Determined) => {
3282                     if let Some(module) = module {
3283                         if opt_ns.is_some() && !module.is_normal() {
3284                             return PathResult::NonModule(PathResolution::with_unresolved_segments(
3285                                 module.def().unwrap(), path.len() - i
3286                             ));
3287                         }
3288                     }
3289                     let msg = if module.and_then(ModuleData::def) == self.graph_root.def() {
3290                         let is_mod = |def| match def { Def::Mod(..) => true, _ => false };
3291                         let mut candidates =
3292                             self.lookup_import_candidates(name, TypeNS, is_mod);
3293                         candidates.sort_by_key(|c| (c.path.segments.len(), c.path.to_string()));
3294                         if let Some(candidate) = candidates.get(0) {
3295                             format!("Did you mean `{}`?", candidate.path)
3296                         } else {
3297                             format!("Maybe a missing `extern crate {};`?", ident.node)
3298                         }
3299                     } else if i == 0 {
3300                         format!("Use of undeclared type or module `{}`", ident.node)
3301                     } else {
3302                         format!("Could not find `{}` in `{}`", ident.node, path[i - 1].node)
3303                     };
3304                     return PathResult::Failed(ident.span, msg, is_last);
3305                 }
3306             }
3307         }
3308
3309         PathResult::Module(module.unwrap_or(self.graph_root))
3310     }
3311
3312     // Resolve a local definition, potentially adjusting for closures.
3313     fn adjust_local_def(&mut self,
3314                         ns: Namespace,
3315                         rib_index: usize,
3316                         mut def: Def,
3317                         record_used: bool,
3318                         span: Span) -> Def {
3319         let ribs = &self.ribs[ns][rib_index + 1..];
3320
3321         // An invalid forward use of a type parameter from a previous default.
3322         if let ForwardTyParamBanRibKind = self.ribs[ns][rib_index].kind {
3323             if record_used {
3324                 resolve_error(self, span, ResolutionError::ForwardDeclaredTyParam);
3325             }
3326             assert_eq!(def, Def::Err);
3327             return Def::Err;
3328         }
3329
3330         match def {
3331             Def::Upvar(..) => {
3332                 span_bug!(span, "unexpected {:?} in bindings", def)
3333             }
3334             Def::Local(node_id) => {
3335                 for rib in ribs {
3336                     match rib.kind {
3337                         NormalRibKind | ModuleRibKind(..) | MacroDefinition(..) |
3338                         ForwardTyParamBanRibKind => {
3339                             // Nothing to do. Continue.
3340                         }
3341                         ClosureRibKind(function_id) => {
3342                             let prev_def = def;
3343
3344                             let seen = self.freevars_seen
3345                                            .entry(function_id)
3346                                            .or_insert_with(|| NodeMap());
3347                             if let Some(&index) = seen.get(&node_id) {
3348                                 def = Def::Upvar(node_id, index, function_id);
3349                                 continue;
3350                             }
3351                             let vec = self.freevars
3352                                           .entry(function_id)
3353                                           .or_insert_with(|| vec![]);
3354                             let depth = vec.len();
3355                             def = Def::Upvar(node_id, depth, function_id);
3356
3357                             if record_used {
3358                                 vec.push(Freevar {
3359                                     def: prev_def,
3360                                     span,
3361                                 });
3362                                 seen.insert(node_id, depth);
3363                             }
3364                         }
3365                         ItemRibKind | TraitOrImplItemRibKind => {
3366                             // This was an attempt to access an upvar inside a
3367                             // named function item. This is not allowed, so we
3368                             // report an error.
3369                             if record_used {
3370                                 resolve_error(self, span,
3371                                         ResolutionError::CannotCaptureDynamicEnvironmentInFnItem);
3372                             }
3373                             return Def::Err;
3374                         }
3375                         ConstantItemRibKind => {
3376                             // Still doesn't deal with upvars
3377                             if record_used {
3378                                 resolve_error(self, span,
3379                                         ResolutionError::AttemptToUseNonConstantValueInConstant);
3380                             }
3381                             return Def::Err;
3382                         }
3383                     }
3384                 }
3385             }
3386             Def::TyParam(..) | Def::SelfTy(..) => {
3387                 for rib in ribs {
3388                     match rib.kind {
3389                         NormalRibKind | TraitOrImplItemRibKind | ClosureRibKind(..) |
3390                         ModuleRibKind(..) | MacroDefinition(..) | ForwardTyParamBanRibKind |
3391                         ConstantItemRibKind => {
3392                             // Nothing to do. Continue.
3393                         }
3394                         ItemRibKind => {
3395                             // This was an attempt to use a type parameter outside
3396                             // its scope.
3397                             if record_used {
3398                                 resolve_error(self, span,
3399                                     ResolutionError::TypeParametersFromOuterFunction(def));
3400                             }
3401                             return Def::Err;
3402                         }
3403                     }
3404                 }
3405             }
3406             _ => {}
3407         }
3408         return def;
3409     }
3410
3411     fn lookup_assoc_candidate<FilterFn>(&mut self,
3412                                         ident: Ident,
3413                                         ns: Namespace,
3414                                         filter_fn: FilterFn)
3415                                         -> Option<AssocSuggestion>
3416         where FilterFn: Fn(Def) -> bool
3417     {
3418         fn extract_node_id(t: &Ty) -> Option<NodeId> {
3419             match t.node {
3420                 TyKind::Path(None, _) => Some(t.id),
3421                 TyKind::Rptr(_, ref mut_ty) => extract_node_id(&mut_ty.ty),
3422                 // This doesn't handle the remaining `Ty` variants as they are not
3423                 // that commonly the self_type, it might be interesting to provide
3424                 // support for those in future.
3425                 _ => None,
3426             }
3427         }
3428
3429         // Fields are generally expected in the same contexts as locals.
3430         if filter_fn(Def::Local(ast::DUMMY_NODE_ID)) {
3431             if let Some(node_id) = self.current_self_type.as_ref().and_then(extract_node_id) {
3432                 // Look for a field with the same name in the current self_type.
3433                 if let Some(resolution) = self.def_map.get(&node_id) {
3434                     match resolution.base_def() {
3435                         Def::Struct(did) | Def::Union(did)
3436                                 if resolution.unresolved_segments() == 0 => {
3437                             if let Some(field_names) = self.field_names.get(&did) {
3438                                 if field_names.iter().any(|&field_name| ident.name == field_name) {
3439                                     return Some(AssocSuggestion::Field);
3440                                 }
3441                             }
3442                         }
3443                         _ => {}
3444                     }
3445                 }
3446             }
3447         }
3448
3449         // Look for associated items in the current trait.
3450         if let Some((module, _)) = self.current_trait_ref {
3451             if let Ok(binding) =
3452                     self.resolve_ident_in_module(module, ident, ns, false, false, module.span) {
3453                 let def = binding.def();
3454                 if filter_fn(def) {
3455                     return Some(if self.has_self.contains(&def.def_id()) {
3456                         AssocSuggestion::MethodWithSelf
3457                     } else {
3458                         AssocSuggestion::AssocItem
3459                     });
3460                 }
3461             }
3462         }
3463
3464         None
3465     }
3466
3467     fn lookup_typo_candidate<FilterFn>(&mut self,
3468                                        path: &[SpannedIdent],
3469                                        ns: Namespace,
3470                                        filter_fn: FilterFn,
3471                                        span: Span)
3472                                        -> Option<Symbol>
3473         where FilterFn: Fn(Def) -> bool
3474     {
3475         let add_module_candidates = |module: Module, names: &mut Vec<Name>| {
3476             for (&(ident, _), resolution) in module.resolutions.borrow().iter() {
3477                 if let Some(binding) = resolution.borrow().binding {
3478                     if filter_fn(binding.def()) {
3479                         names.push(ident.name);
3480                     }
3481                 }
3482             }
3483         };
3484
3485         let mut names = Vec::new();
3486         if path.len() == 1 {
3487             // Search in lexical scope.
3488             // Walk backwards up the ribs in scope and collect candidates.
3489             for rib in self.ribs[ns].iter().rev() {
3490                 // Locals and type parameters
3491                 for (ident, def) in &rib.bindings {
3492                     if filter_fn(*def) {
3493                         names.push(ident.name);
3494                     }
3495                 }
3496                 // Items in scope
3497                 if let ModuleRibKind(module) = rib.kind {
3498                     // Items from this module
3499                     add_module_candidates(module, &mut names);
3500
3501                     if let ModuleKind::Block(..) = module.kind {
3502                         // We can see through blocks
3503                     } else {
3504                         // Items from the prelude
3505                         if let Some(prelude) = self.prelude {
3506                             if !module.no_implicit_prelude {
3507                                 add_module_candidates(prelude, &mut names);
3508                             }
3509                         }
3510                         break;
3511                     }
3512                 }
3513             }
3514             // Add primitive types to the mix
3515             if filter_fn(Def::PrimTy(TyBool)) {
3516                 for (name, _) in &self.primitive_type_table.primitive_types {
3517                     names.push(*name);
3518                 }
3519             }
3520         } else {
3521             // Search in module.
3522             let mod_path = &path[..path.len() - 1];
3523             if let PathResult::Module(module) = self.resolve_path(mod_path, Some(TypeNS),
3524                                                                   false, span) {
3525                 add_module_candidates(module, &mut names);
3526             }
3527         }
3528
3529         let name = path[path.len() - 1].node.name;
3530         // Make sure error reporting is deterministic.
3531         names.sort_by_key(|name| name.as_str());
3532         match find_best_match_for_name(names.iter(), &name.as_str(), None) {
3533             Some(found) if found != name => Some(found),
3534             _ => None,
3535         }
3536     }
3537
3538     fn with_resolved_label<F>(&mut self, label: Option<Label>, id: NodeId, f: F)
3539         where F: FnOnce(&mut Resolver)
3540     {
3541         if let Some(label) = label {
3542             let def = Def::Label(id);
3543             self.with_label_rib(|this| {
3544                 this.label_ribs.last_mut().unwrap().bindings.insert(label.ident, def);
3545                 f(this);
3546             });
3547         } else {
3548             f(self);
3549         }
3550     }
3551
3552     fn resolve_labeled_block(&mut self, label: Option<Label>, id: NodeId, block: &Block) {
3553         self.with_resolved_label(label, id, |this| this.visit_block(block));
3554     }
3555
3556     fn resolve_expr(&mut self, expr: &Expr, parent: Option<&Expr>) {
3557         // First, record candidate traits for this expression if it could
3558         // result in the invocation of a method call.
3559
3560         self.record_candidate_traits_for_expr_if_necessary(expr);
3561
3562         // Next, resolve the node.
3563         match expr.node {
3564             ExprKind::Path(ref qself, ref path) => {
3565                 self.smart_resolve_path(expr.id, qself.as_ref(), path, PathSource::Expr(parent));
3566                 visit::walk_expr(self, expr);
3567             }
3568
3569             ExprKind::Struct(ref path, ..) => {
3570                 self.smart_resolve_path(expr.id, None, path, PathSource::Struct);
3571                 visit::walk_expr(self, expr);
3572             }
3573
3574             ExprKind::Break(Some(label), _) | ExprKind::Continue(Some(label)) => {
3575                 match self.search_label(label.ident, |rib, id| rib.bindings.get(&id).cloned()) {
3576                     None => {
3577                         // Search again for close matches...
3578                         // Picks the first label that is "close enough", which is not necessarily
3579                         // the closest match
3580                         let close_match = self.search_label(label.ident, |rib, ident| {
3581                             let names = rib.bindings.iter().map(|(id, _)| &id.name);
3582                             find_best_match_for_name(names, &*ident.name.as_str(), None)
3583                         });
3584                         self.record_def(expr.id, err_path_resolution());
3585                         resolve_error(self,
3586                                       label.span,
3587                                       ResolutionError::UndeclaredLabel(&label.ident.name.as_str(),
3588                                                                        close_match));
3589                     }
3590                     Some(def @ Def::Label(_)) => {
3591                         // Since this def is a label, it is never read.
3592                         self.record_def(expr.id, PathResolution::new(def));
3593                     }
3594                     Some(_) => {
3595                         span_bug!(expr.span, "label wasn't mapped to a label def!");
3596                     }
3597                 }
3598
3599                 // visit `break` argument if any
3600                 visit::walk_expr(self, expr);
3601             }
3602
3603             ExprKind::IfLet(ref pats, ref subexpression, ref if_block, ref optional_else) => {
3604                 self.visit_expr(subexpression);
3605
3606                 self.ribs[ValueNS].push(Rib::new(NormalRibKind));
3607                 let mut bindings_list = FxHashMap();
3608                 for pat in pats {
3609                     self.resolve_pattern(pat, PatternSource::IfLet, &mut bindings_list);
3610                 }
3611                 // This has to happen *after* we determine which pat_idents are variants
3612                 self.check_consistent_bindings(pats);
3613                 self.visit_block(if_block);
3614                 self.ribs[ValueNS].pop();
3615
3616                 optional_else.as_ref().map(|expr| self.visit_expr(expr));
3617             }
3618
3619             ExprKind::Loop(ref block, label) => self.resolve_labeled_block(label, expr.id, &block),
3620
3621             ExprKind::While(ref subexpression, ref block, label) => {
3622                 self.with_resolved_label(label, expr.id, |this| {
3623                     this.visit_expr(subexpression);
3624                     this.visit_block(block);
3625                 });
3626             }
3627
3628             ExprKind::WhileLet(ref pats, ref subexpression, ref block, label) => {
3629                 self.with_resolved_label(label, expr.id, |this| {
3630                     this.visit_expr(subexpression);
3631                     this.ribs[ValueNS].push(Rib::new(NormalRibKind));
3632                     let mut bindings_list = FxHashMap();
3633                     for pat in pats {
3634                         this.resolve_pattern(pat, PatternSource::WhileLet, &mut bindings_list);
3635                     }
3636                     // This has to happen *after* we determine which pat_idents are variants
3637                     this.check_consistent_bindings(pats);
3638                     this.visit_block(block);
3639                     this.ribs[ValueNS].pop();
3640                 });
3641             }
3642
3643             ExprKind::ForLoop(ref pattern, ref subexpression, ref block, label) => {
3644                 self.visit_expr(subexpression);
3645                 self.ribs[ValueNS].push(Rib::new(NormalRibKind));
3646                 self.resolve_pattern(pattern, PatternSource::For, &mut FxHashMap());
3647
3648                 self.resolve_labeled_block(label, expr.id, block);
3649
3650                 self.ribs[ValueNS].pop();
3651             }
3652
3653             // Equivalent to `visit::walk_expr` + passing some context to children.
3654             ExprKind::Field(ref subexpression, _) => {
3655                 self.resolve_expr(subexpression, Some(expr));
3656             }
3657             ExprKind::MethodCall(ref segment, ref arguments) => {
3658                 let mut arguments = arguments.iter();
3659                 self.resolve_expr(arguments.next().unwrap(), Some(expr));
3660                 for argument in arguments {
3661                     self.resolve_expr(argument, None);
3662                 }
3663                 self.visit_path_segment(expr.span, segment);
3664             }
3665
3666             ExprKind::Repeat(ref element, ref count) => {
3667                 self.visit_expr(element);
3668                 self.with_constant_rib(|this| {
3669                     this.visit_expr(count);
3670                 });
3671             }
3672             ExprKind::Call(ref callee, ref arguments) => {
3673                 self.resolve_expr(callee, Some(expr));
3674                 for argument in arguments {
3675                     self.resolve_expr(argument, None);
3676                 }
3677             }
3678             ExprKind::Type(ref type_expr, _) => {
3679                 self.current_type_ascription.push(type_expr.span);
3680                 visit::walk_expr(self, expr);
3681                 self.current_type_ascription.pop();
3682             }
3683             _ => {
3684                 visit::walk_expr(self, expr);
3685             }
3686         }
3687     }
3688
3689     fn record_candidate_traits_for_expr_if_necessary(&mut self, expr: &Expr) {
3690         match expr.node {
3691             ExprKind::Field(_, name) => {
3692                 // FIXME(#6890): Even though you can't treat a method like a
3693                 // field, we need to add any trait methods we find that match
3694                 // the field name so that we can do some nice error reporting
3695                 // later on in typeck.
3696                 let traits = self.get_traits_containing_item(name.node, ValueNS);
3697                 self.trait_map.insert(expr.id, traits);
3698             }
3699             ExprKind::MethodCall(ref segment, ..) => {
3700                 debug!("(recording candidate traits for expr) recording traits for {}",
3701                        expr.id);
3702                 let traits = self.get_traits_containing_item(segment.identifier, ValueNS);
3703                 self.trait_map.insert(expr.id, traits);
3704             }
3705             _ => {
3706                 // Nothing to do.
3707             }
3708         }
3709     }
3710
3711     fn get_traits_containing_item(&mut self, mut ident: Ident, ns: Namespace)
3712                                   -> Vec<TraitCandidate> {
3713         debug!("(getting traits containing item) looking for '{}'", ident.name);
3714
3715         let mut found_traits = Vec::new();
3716         // Look for the current trait.
3717         if let Some((module, _)) = self.current_trait_ref {
3718             if self.resolve_ident_in_module(module, ident, ns, false, false, module.span).is_ok() {
3719                 let def_id = module.def_id().unwrap();
3720                 found_traits.push(TraitCandidate { def_id: def_id, import_id: None });
3721             }
3722         }
3723
3724         ident.ctxt = ident.ctxt.modern();
3725         let mut search_module = self.current_module;
3726         loop {
3727             self.get_traits_in_module_containing_item(ident, ns, search_module, &mut found_traits);
3728             search_module =
3729                 unwrap_or!(self.hygienic_lexical_parent(search_module, &mut ident.ctxt), break);
3730         }
3731
3732         if let Some(prelude) = self.prelude {
3733             if !search_module.no_implicit_prelude {
3734                 self.get_traits_in_module_containing_item(ident, ns, prelude, &mut found_traits);
3735             }
3736         }
3737
3738         found_traits
3739     }
3740
3741     fn get_traits_in_module_containing_item(&mut self,
3742                                             ident: Ident,
3743                                             ns: Namespace,
3744                                             module: Module<'a>,
3745                                             found_traits: &mut Vec<TraitCandidate>) {
3746         let mut traits = module.traits.borrow_mut();
3747         if traits.is_none() {
3748             let mut collected_traits = Vec::new();
3749             module.for_each_child(|name, ns, binding| {
3750                 if ns != TypeNS { return }
3751                 if let Def::Trait(_) = binding.def() {
3752                     collected_traits.push((name, binding));
3753                 }
3754             });
3755             *traits = Some(collected_traits.into_boxed_slice());
3756         }
3757
3758         for &(trait_name, binding) in traits.as_ref().unwrap().iter() {
3759             let module = binding.module().unwrap();
3760             let mut ident = ident;
3761             if ident.ctxt.glob_adjust(module.expansion, binding.span.ctxt().modern()).is_none() {
3762                 continue
3763             }
3764             if self.resolve_ident_in_module_unadjusted(module, ident, ns, false, false, module.span)
3765                    .is_ok() {
3766                 let import_id = match binding.kind {
3767                     NameBindingKind::Import { directive, .. } => {
3768                         self.maybe_unused_trait_imports.insert(directive.id);
3769                         self.add_to_glob_map(directive.id, trait_name);
3770                         Some(directive.id)
3771                     }
3772                     _ => None,
3773                 };
3774                 let trait_def_id = module.def_id().unwrap();
3775                 found_traits.push(TraitCandidate { def_id: trait_def_id, import_id: import_id });
3776             }
3777         }
3778     }
3779
3780     /// When name resolution fails, this method can be used to look up candidate
3781     /// entities with the expected name. It allows filtering them using the
3782     /// supplied predicate (which should be used to only accept the types of
3783     /// definitions expected e.g. traits). The lookup spans across all crates.
3784     ///
3785     /// NOTE: The method does not look into imports, but this is not a problem,
3786     /// since we report the definitions (thus, the de-aliased imports).
3787     fn lookup_import_candidates<FilterFn>(&mut self,
3788                                           lookup_name: Name,
3789                                           namespace: Namespace,
3790                                           filter_fn: FilterFn)
3791                                           -> Vec<ImportSuggestion>
3792         where FilterFn: Fn(Def) -> bool
3793     {
3794         let mut candidates = Vec::new();
3795         let mut worklist = Vec::new();
3796         let mut seen_modules = FxHashSet();
3797         worklist.push((self.graph_root, Vec::new(), false));
3798
3799         while let Some((in_module,
3800                         path_segments,
3801                         in_module_is_extern)) = worklist.pop() {
3802             self.populate_module_if_necessary(in_module);
3803
3804             // We have to visit module children in deterministic order to avoid
3805             // instabilities in reported imports (#43552).
3806             in_module.for_each_child_stable(|ident, ns, name_binding| {
3807                 // avoid imports entirely
3808                 if name_binding.is_import() && !name_binding.is_extern_crate() { return; }
3809                 // avoid non-importable candidates as well
3810                 if !name_binding.is_importable() { return; }
3811
3812                 // collect results based on the filter function
3813                 if ident.name == lookup_name && ns == namespace {
3814                     if filter_fn(name_binding.def()) {
3815                         // create the path
3816                         let mut segms = path_segments.clone();
3817                         segms.push(ast::PathSegment::from_ident(ident, name_binding.span));
3818                         let path = Path {
3819                             span: name_binding.span,
3820                             segments: segms,
3821                         };
3822                         // the entity is accessible in the following cases:
3823                         // 1. if it's defined in the same crate, it's always
3824                         // accessible (since private entities can be made public)
3825                         // 2. if it's defined in another crate, it's accessible
3826                         // only if both the module is public and the entity is
3827                         // declared as public (due to pruning, we don't explore
3828                         // outside crate private modules => no need to check this)
3829                         if !in_module_is_extern || name_binding.vis == ty::Visibility::Public {
3830                             candidates.push(ImportSuggestion { path: path });
3831                         }
3832                     }
3833                 }
3834
3835                 // collect submodules to explore
3836                 if let Some(module) = name_binding.module() {
3837                     // form the path
3838                     let mut path_segments = path_segments.clone();
3839                     path_segments.push(ast::PathSegment::from_ident(ident, name_binding.span));
3840
3841                     if !in_module_is_extern || name_binding.vis == ty::Visibility::Public {
3842                         // add the module to the lookup
3843                         let is_extern = in_module_is_extern || name_binding.is_extern_crate();
3844                         if seen_modules.insert(module.def_id().unwrap()) {
3845                             worklist.push((module, path_segments, is_extern));
3846                         }
3847                     }
3848                 }
3849             })
3850         }
3851
3852         candidates
3853     }
3854
3855     fn find_module(&mut self,
3856                    module_def: Def)
3857                    -> Option<(Module<'a>, ImportSuggestion)>
3858     {
3859         let mut result = None;
3860         let mut worklist = Vec::new();
3861         let mut seen_modules = FxHashSet();
3862         worklist.push((self.graph_root, Vec::new()));
3863
3864         while let Some((in_module, path_segments)) = worklist.pop() {
3865             // abort if the module is already found
3866             if let Some(_) = result { break; }
3867
3868             self.populate_module_if_necessary(in_module);
3869
3870             in_module.for_each_child_stable(|ident, _, name_binding| {
3871                 // abort if the module is already found or if name_binding is private external
3872                 if result.is_some() || !name_binding.vis.is_visible_locally() {
3873                     return
3874                 }
3875                 if let Some(module) = name_binding.module() {
3876                     // form the path
3877                     let mut path_segments = path_segments.clone();
3878                     path_segments.push(ast::PathSegment::from_ident(ident, name_binding.span));
3879                     if module.def() == Some(module_def) {
3880                         let path = Path {
3881                             span: name_binding.span,
3882                             segments: path_segments,
3883                         };
3884                         result = Some((module, ImportSuggestion { path: path }));
3885                     } else {
3886                         // add the module to the lookup
3887                         if seen_modules.insert(module.def_id().unwrap()) {
3888                             worklist.push((module, path_segments));
3889                         }
3890                     }
3891                 }
3892             });
3893         }
3894
3895         result
3896     }
3897
3898     fn collect_enum_variants(&mut self, enum_def: Def) -> Option<Vec<Path>> {
3899         if let Def::Enum(..) = enum_def {} else {
3900             panic!("Non-enum def passed to collect_enum_variants: {:?}", enum_def)
3901         }
3902
3903         self.find_module(enum_def).map(|(enum_module, enum_import_suggestion)| {
3904             self.populate_module_if_necessary(enum_module);
3905
3906             let mut variants = Vec::new();
3907             enum_module.for_each_child_stable(|ident, _, name_binding| {
3908                 if let Def::Variant(..) = name_binding.def() {
3909                     let mut segms = enum_import_suggestion.path.segments.clone();
3910                     segms.push(ast::PathSegment::from_ident(ident, name_binding.span));
3911                     variants.push(Path {
3912                         span: name_binding.span,
3913                         segments: segms,
3914                     });
3915                 }
3916             });
3917             variants
3918         })
3919     }
3920
3921     fn record_def(&mut self, node_id: NodeId, resolution: PathResolution) {
3922         debug!("(recording def) recording {:?} for {}", resolution, node_id);
3923         if let Some(prev_res) = self.def_map.insert(node_id, resolution) {
3924             panic!("path resolved multiple times ({:?} before, {:?} now)", prev_res, resolution);
3925         }
3926     }
3927
3928     fn resolve_visibility(&mut self, vis: &ast::Visibility) -> ty::Visibility {
3929         match vis.node {
3930             ast::VisibilityKind::Public => ty::Visibility::Public,
3931             ast::VisibilityKind::Crate(..) => {
3932                 ty::Visibility::Restricted(DefId::local(CRATE_DEF_INDEX))
3933             }
3934             ast::VisibilityKind::Inherited => {
3935                 ty::Visibility::Restricted(self.current_module.normal_ancestor_id)
3936             }
3937             ast::VisibilityKind::Restricted { ref path, id, .. } => {
3938                 let def = self.smart_resolve_path(id, None, path,
3939                                                   PathSource::Visibility).base_def();
3940                 if def == Def::Err {
3941                     ty::Visibility::Public
3942                 } else {
3943                     let vis = ty::Visibility::Restricted(def.def_id());
3944                     if self.is_accessible(vis) {
3945                         vis
3946                     } else {
3947                         self.session.span_err(path.span, "visibilities can only be restricted \
3948                                                           to ancestor modules");
3949                         ty::Visibility::Public
3950                     }
3951                 }
3952             }
3953         }
3954     }
3955
3956     fn is_accessible(&self, vis: ty::Visibility) -> bool {
3957         vis.is_accessible_from(self.current_module.normal_ancestor_id, self)
3958     }
3959
3960     fn is_accessible_from(&self, vis: ty::Visibility, module: Module<'a>) -> bool {
3961         vis.is_accessible_from(module.normal_ancestor_id, self)
3962     }
3963
3964     fn report_errors(&mut self, krate: &Crate) {
3965         self.report_shadowing_errors();
3966         self.report_with_use_injections(krate);
3967         self.report_proc_macro_import(krate);
3968         let mut reported_spans = FxHashSet();
3969
3970         for &AmbiguityError { span, name, b1, b2, lexical, legacy } in &self.ambiguity_errors {
3971             if !reported_spans.insert(span) { continue }
3972             let participle = |binding: &NameBinding| {
3973                 if binding.is_import() { "imported" } else { "defined" }
3974             };
3975             let msg1 = format!("`{}` could refer to the name {} here", name, participle(b1));
3976             let msg2 = format!("`{}` could also refer to the name {} here", name, participle(b2));
3977             let note = if b1.expansion == Mark::root() || !lexical && b1.is_glob_import() {
3978                 format!("consider adding an explicit import of `{}` to disambiguate", name)
3979             } else if let Def::Macro(..) = b1.def() {
3980                 format!("macro-expanded {} do not shadow",
3981                         if b1.is_import() { "macro imports" } else { "macros" })
3982             } else {
3983                 format!("macro-expanded {} do not shadow when used in a macro invocation path",
3984                         if b1.is_import() { "imports" } else { "items" })
3985             };
3986             if legacy {
3987                 let id = match b2.kind {
3988                     NameBindingKind::Import { directive, .. } => directive.id,
3989                     _ => unreachable!(),
3990                 };
3991                 let mut span = MultiSpan::from_span(span);
3992                 span.push_span_label(b1.span, msg1);
3993                 span.push_span_label(b2.span, msg2);
3994                 let msg = format!("`{}` is ambiguous", name);
3995                 self.session.buffer_lint(lint::builtin::LEGACY_IMPORTS, id, span, &msg);
3996             } else {
3997                 let mut err =
3998                     struct_span_err!(self.session, span, E0659, "`{}` is ambiguous", name);
3999                 err.span_note(b1.span, &msg1);
4000                 match b2.def() {
4001                     Def::Macro(..) if b2.span == DUMMY_SP =>
4002                         err.note(&format!("`{}` is also a builtin macro", name)),
4003                     _ => err.span_note(b2.span, &msg2),
4004                 };
4005                 err.note(&note).emit();
4006             }
4007         }
4008
4009         for &PrivacyError(span, name, binding) in &self.privacy_errors {
4010             if !reported_spans.insert(span) { continue }
4011             span_err!(self.session, span, E0603, "{} `{}` is private", binding.descr(), name);
4012         }
4013     }
4014
4015     fn report_with_use_injections(&mut self, krate: &Crate) {
4016         for UseError { mut err, candidates, node_id, better } in self.use_injections.drain(..) {
4017             let (span, found_use) = UsePlacementFinder::check(krate, node_id);
4018             if !candidates.is_empty() {
4019                 show_candidates(&mut err, span, &candidates, better, found_use);
4020             }
4021             err.emit();
4022         }
4023     }
4024
4025     fn report_shadowing_errors(&mut self) {
4026         for (ident, scope) in replace(&mut self.lexical_macro_resolutions, Vec::new()) {
4027             self.resolve_legacy_scope(scope, ident, true);
4028         }
4029
4030         let mut reported_errors = FxHashSet();
4031         for binding in replace(&mut self.disallowed_shadowing, Vec::new()) {
4032             if self.resolve_legacy_scope(&binding.parent, binding.ident, false).is_some() &&
4033                reported_errors.insert((binding.ident, binding.span)) {
4034                 let msg = format!("`{}` is already in scope", binding.ident);
4035                 self.session.struct_span_err(binding.span, &msg)
4036                     .note("macro-expanded `macro_rules!`s may not shadow \
4037                            existing macros (see RFC 1560)")
4038                     .emit();
4039             }
4040         }
4041     }
4042
4043     fn report_conflict<'b>(&mut self,
4044                        parent: Module,
4045                        ident: Ident,
4046                        ns: Namespace,
4047                        new_binding: &NameBinding<'b>,
4048                        old_binding: &NameBinding<'b>) {
4049         // Error on the second of two conflicting names
4050         if old_binding.span.lo() > new_binding.span.lo() {
4051             return self.report_conflict(parent, ident, ns, old_binding, new_binding);
4052         }
4053
4054         let container = match parent.kind {
4055             ModuleKind::Def(Def::Mod(_), _) => "module",
4056             ModuleKind::Def(Def::Trait(_), _) => "trait",
4057             ModuleKind::Block(..) => "block",
4058             _ => "enum",
4059         };
4060
4061         let old_noun = match old_binding.is_import() {
4062             true => "import",
4063             false => "definition",
4064         };
4065
4066         let new_participle = match new_binding.is_import() {
4067             true => "imported",
4068             false => "defined",
4069         };
4070
4071         let (name, span) = (ident.name, self.session.codemap().def_span(new_binding.span));
4072
4073         if let Some(s) = self.name_already_seen.get(&name) {
4074             if s == &span {
4075                 return;
4076             }
4077         }
4078
4079         let old_kind = match (ns, old_binding.module()) {
4080             (ValueNS, _) => "value",
4081             (MacroNS, _) => "macro",
4082             (TypeNS, _) if old_binding.is_extern_crate() => "extern crate",
4083             (TypeNS, Some(module)) if module.is_normal() => "module",
4084             (TypeNS, Some(module)) if module.is_trait() => "trait",
4085             (TypeNS, _) => "type",
4086         };
4087
4088         let namespace = match ns {
4089             ValueNS => "value",
4090             MacroNS => "macro",
4091             TypeNS => "type",
4092         };
4093
4094         let msg = format!("the name `{}` is defined multiple times", name);
4095
4096         let mut err = match (old_binding.is_extern_crate(), new_binding.is_extern_crate()) {
4097             (true, true) => struct_span_err!(self.session, span, E0259, "{}", msg),
4098             (true, _) | (_, true) => match new_binding.is_import() && old_binding.is_import() {
4099                 true => struct_span_err!(self.session, span, E0254, "{}", msg),
4100                 false => struct_span_err!(self.session, span, E0260, "{}", msg),
4101             },
4102             _ => match (old_binding.is_import(), new_binding.is_import()) {
4103                 (false, false) => struct_span_err!(self.session, span, E0428, "{}", msg),
4104                 (true, true) => struct_span_err!(self.session, span, E0252, "{}", msg),
4105                 _ => struct_span_err!(self.session, span, E0255, "{}", msg),
4106             },
4107         };
4108
4109         err.note(&format!("`{}` must be defined only once in the {} namespace of this {}",
4110                           name,
4111                           namespace,
4112                           container));
4113
4114         err.span_label(span, format!("`{}` re{} here", name, new_participle));
4115         if old_binding.span != DUMMY_SP {
4116             err.span_label(self.session.codemap().def_span(old_binding.span),
4117                            format!("previous {} of the {} `{}` here", old_noun, old_kind, name));
4118         }
4119
4120         // See https://github.com/rust-lang/rust/issues/32354
4121         if old_binding.is_import() || new_binding.is_import() {
4122             let binding = if new_binding.is_import() && new_binding.span != DUMMY_SP {
4123                 new_binding
4124             } else {
4125                 old_binding
4126             };
4127
4128             let cm = self.session.codemap();
4129             let rename_msg = "You can use `as` to change the binding name of the import";
4130
4131             if let (Ok(snippet), false) = (cm.span_to_snippet(binding.span),
4132                                            binding.is_renamed_extern_crate()) {
4133                 let suggested_name = if name.as_str().chars().next().unwrap().is_uppercase() {
4134                     format!("Other{}", name)
4135                 } else {
4136                     format!("other_{}", name)
4137                 };
4138
4139                 err.span_suggestion(binding.span,
4140                                     rename_msg,
4141                                     if snippet.ends_with(';') {
4142                                         format!("{} as {};",
4143                                                 &snippet[..snippet.len()-1],
4144                                                 suggested_name)
4145                                     } else {
4146                                         format!("{} as {}", snippet, suggested_name)
4147                                     });
4148             } else {
4149                 err.span_label(binding.span, rename_msg);
4150             }
4151         }
4152
4153         err.emit();
4154         self.name_already_seen.insert(name, span);
4155     }
4156
4157     fn warn_legacy_self_import(&self, directive: &'a ImportDirective<'a>) {
4158         let (id, span) = (directive.id, directive.span);
4159         let msg = "`self` no longer imports values";
4160         self.session.buffer_lint(lint::builtin::LEGACY_IMPORTS, id, span, msg);
4161     }
4162
4163     fn check_proc_macro_attrs(&mut self, attrs: &[ast::Attribute]) {
4164         if self.proc_macro_enabled { return; }
4165
4166         for attr in attrs {
4167             if attr.path.segments.len() > 1 {
4168                 continue
4169             }
4170             let ident = attr.path.segments[0].identifier;
4171             let result = self.resolve_lexical_macro_path_segment(ident,
4172                                                                  MacroNS,
4173                                                                  false,
4174                                                                  attr.path.span);
4175             if let Ok(binding) = result {
4176                 if let SyntaxExtension::AttrProcMacro(..) = *binding.binding().get_macro(self) {
4177                     attr::mark_known(attr);
4178
4179                     let msg = "attribute procedural macros are experimental";
4180                     let feature = "proc_macro";
4181
4182                     feature_err(&self.session.parse_sess, feature,
4183                                 attr.span, GateIssue::Language, msg)
4184                         .span_label(binding.span(), "procedural macro imported here")
4185                         .emit();
4186                 }
4187             }
4188         }
4189     }
4190 }
4191
4192 fn is_self_type(path: &[SpannedIdent], namespace: Namespace) -> bool {
4193     namespace == TypeNS && path.len() == 1 && path[0].node.name == keywords::SelfType.name()
4194 }
4195
4196 fn is_self_value(path: &[SpannedIdent], namespace: Namespace) -> bool {
4197     namespace == ValueNS && path.len() == 1 && path[0].node.name == keywords::SelfValue.name()
4198 }
4199
4200 fn names_to_string(idents: &[SpannedIdent]) -> String {
4201     let mut result = String::new();
4202     for (i, ident) in idents.iter()
4203                             .filter(|i| i.node.name != keywords::CrateRoot.name())
4204                             .enumerate() {
4205         if i > 0 {
4206             result.push_str("::");
4207         }
4208         result.push_str(&ident.node.name.as_str());
4209     }
4210     result
4211 }
4212
4213 fn path_names_to_string(path: &Path) -> String {
4214     names_to_string(&path.segments.iter()
4215                         .map(|seg| respan(seg.span, seg.identifier))
4216                         .collect::<Vec<_>>())
4217 }
4218
4219 /// Get the path for an enum and the variant from an `ImportSuggestion` for an enum variant.
4220 fn import_candidate_to_paths(suggestion: &ImportSuggestion) -> (Span, String, String) {
4221     let variant_path = &suggestion.path;
4222     let variant_path_string = path_names_to_string(variant_path);
4223
4224     let path_len = suggestion.path.segments.len();
4225     let enum_path = ast::Path {
4226         span: suggestion.path.span,
4227         segments: suggestion.path.segments[0..path_len - 1].to_vec(),
4228     };
4229     let enum_path_string = path_names_to_string(&enum_path);
4230
4231     (suggestion.path.span, variant_path_string, enum_path_string)
4232 }
4233
4234
4235 /// When an entity with a given name is not available in scope, we search for
4236 /// entities with that name in all crates. This method allows outputting the
4237 /// results of this search in a programmer-friendly way
4238 fn show_candidates(err: &mut DiagnosticBuilder,
4239                    // This is `None` if all placement locations are inside expansions
4240                    span: Option<Span>,
4241                    candidates: &[ImportSuggestion],
4242                    better: bool,
4243                    found_use: bool) {
4244
4245     // we want consistent results across executions, but candidates are produced
4246     // by iterating through a hash map, so make sure they are ordered:
4247     let mut path_strings: Vec<_> =
4248         candidates.into_iter().map(|c| path_names_to_string(&c.path)).collect();
4249     path_strings.sort();
4250
4251     let better = if better { "better " } else { "" };
4252     let msg_diff = match path_strings.len() {
4253         1 => " is found in another module, you can import it",
4254         _ => "s are found in other modules, you can import them",
4255     };
4256     let msg = format!("possible {}candidate{} into scope", better, msg_diff);
4257
4258     if let Some(span) = span {
4259         for candidate in &mut path_strings {
4260             // produce an additional newline to separate the new use statement
4261             // from the directly following item.
4262             let additional_newline = if found_use {
4263                 ""
4264             } else {
4265                 "\n"
4266             };
4267             *candidate = format!("use {};\n{}", candidate, additional_newline);
4268         }
4269
4270         err.span_suggestions(span, &msg, path_strings);
4271     } else {
4272         let mut msg = msg;
4273         msg.push(':');
4274         for candidate in path_strings {
4275             msg.push('\n');
4276             msg.push_str(&candidate);
4277         }
4278     }
4279 }
4280
4281 /// A somewhat inefficient routine to obtain the name of a module.
4282 fn module_to_string(module: Module) -> Option<String> {
4283     let mut names = Vec::new();
4284
4285     fn collect_mod(names: &mut Vec<Ident>, module: Module) {
4286         if let ModuleKind::Def(_, name) = module.kind {
4287             if let Some(parent) = module.parent {
4288                 names.push(Ident::with_empty_ctxt(name));
4289                 collect_mod(names, parent);
4290             }
4291         } else {
4292             // danger, shouldn't be ident?
4293             names.push(Ident::from_str("<opaque>"));
4294             collect_mod(names, module.parent.unwrap());
4295         }
4296     }
4297     collect_mod(&mut names, module);
4298
4299     if names.is_empty() {
4300         return None;
4301     }
4302     Some(names_to_string(&names.into_iter()
4303                         .rev()
4304                         .map(|n| dummy_spanned(n))
4305                         .collect::<Vec<_>>()))
4306 }
4307
4308 fn err_path_resolution() -> PathResolution {
4309     PathResolution::new(Def::Err)
4310 }
4311
4312 #[derive(PartialEq,Copy, Clone)]
4313 pub enum MakeGlobMap {
4314     Yes,
4315     No,
4316 }
4317
4318 __build_diagnostic_array! { librustc_resolve, DIAGNOSTICS }