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