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