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