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