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