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