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