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