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