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