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