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