]> git.lizzy.rs Git - rust.git/blob - src/librustc_resolve/lib.rs
Auto merge of #64716 - jonhoo:stabilize-mem-take, r=SimonSapin
[rust.git] / src / librustc_resolve / lib.rs
1 //! This crate is responsible for the part of name resolution that doesn't require type checker.
2 //!
3 //! Module structure of the crate is built here.
4 //! Paths in macros, imports, expressions, types, patterns are resolved here.
5 //! Label names are resolved here as well.
6 //!
7 //! Type-relative name resolution (methods, fields, associated items) happens in `librustc_typeck`.
8 //! Lifetime names are resolved in `librustc/middle/resolve_lifetime.rs`.
9
10 #![doc(html_root_url = "https://doc.rust-lang.org/nightly/")]
11
12 #![feature(crate_visibility_modifier)]
13 #![feature(label_break_value)]
14 #![feature(nll)]
15
16 #![recursion_limit="256"]
17
18 pub use rustc::hir::def::{Namespace, PerNS};
19
20 use Determinacy::*;
21
22 use rustc::hir::map::Definitions;
23 use rustc::hir::{self, PrimTy, Bool, Char, Float, Int, Uint, Str};
24 use rustc::middle::cstore::CrateStore;
25 use rustc::session::Session;
26 use rustc::lint;
27 use rustc::hir::def::{self, DefKind, PartialRes, CtorKind, CtorOf, NonMacroAttrKind, ExportMap};
28 use rustc::hir::def::Namespace::*;
29 use rustc::hir::def_id::{CRATE_DEF_INDEX, LOCAL_CRATE, DefId};
30 use rustc::hir::{TraitMap, GlobMap};
31 use rustc::ty::{self, DefIdTree};
32 use rustc::util::nodemap::{NodeMap, NodeSet, FxHashMap, FxHashSet, DefIdMap};
33 use rustc::span_bug;
34
35 use rustc_metadata::creader::CrateLoader;
36 use rustc_metadata::cstore::CStore;
37
38 use syntax::ext::hygiene::{ExpnId, Transparency, SyntaxContext};
39 use syntax::ast::{self, Name, NodeId, Ident, FloatTy, IntTy, UintTy};
40 use syntax::ext::base::{SyntaxExtension, MacroKind, SpecialDerives};
41 use syntax::symbol::{kw, sym};
42
43 use syntax::visit::{self, Visitor};
44 use syntax::attr;
45 use syntax::ast::{CRATE_NODE_ID, Crate};
46 use syntax::ast::{ItemKind, Path};
47 use syntax::{struct_span_err, unwrap_or};
48 use syntax::source_map::Spanned;
49
50 use syntax_pos::{Span, DUMMY_SP};
51 use errors::{Applicability, DiagnosticBuilder};
52
53 use log::debug;
54
55 use std::cell::{Cell, RefCell};
56 use std::{cmp, fmt, iter, ptr};
57 use std::collections::BTreeSet;
58 use rustc_data_structures::ptr_key::PtrKey;
59 use rustc_data_structures::sync::Lrc;
60 use rustc_data_structures::fx::FxIndexMap;
61
62 use diagnostics::{Suggestion, ImportSuggestion};
63 use diagnostics::{find_span_of_binding_until_next_binding, extend_span_to_previous_binding};
64 use late::{HasGenericParams, PathSource, Rib, RibKind::*};
65 use resolve_imports::{ImportDirective, ImportDirectiveSubclass, NameResolution, ImportResolver};
66 use macros::{LegacyBinding, LegacyScope};
67
68 type Res = def::Res<NodeId>;
69
70 pub mod error_codes;
71 mod diagnostics;
72 mod late;
73 mod macros;
74 mod check_unused;
75 mod build_reduced_graph;
76 mod resolve_imports;
77
78 const KNOWN_TOOLS: &[Name] = &[sym::clippy, sym::rustfmt];
79
80 enum Weak {
81     Yes,
82     No,
83 }
84
85 #[derive(Copy, Clone, PartialEq, Debug)]
86 pub enum Determinacy {
87     Determined,
88     Undetermined,
89 }
90
91 impl Determinacy {
92     fn determined(determined: bool) -> Determinacy {
93         if determined { Determinacy::Determined } else { Determinacy::Undetermined }
94     }
95 }
96
97 /// A specific scope in which a name can be looked up.
98 /// This enum is currently used only for early resolution (imports and macros),
99 /// but not for late resolution yet.
100 #[derive(Clone, Copy)]
101 enum Scope<'a> {
102     DeriveHelpers,
103     MacroRules(LegacyScope<'a>),
104     CrateRoot,
105     Module(Module<'a>),
106     MacroUsePrelude,
107     BuiltinAttrs,
108     LegacyPluginHelpers,
109     ExternPrelude,
110     ToolPrelude,
111     StdLibPrelude,
112     BuiltinTypes,
113 }
114
115 /// Names from different contexts may want to visit different subsets of all specific scopes
116 /// with different restrictions when looking up the resolution.
117 /// This enum is currently used only for early resolution (imports and macros),
118 /// but not for late resolution yet.
119 enum ScopeSet {
120     /// All scopes with the given namespace.
121     All(Namespace, /*is_import*/ bool),
122     /// Crate root, then extern prelude (used for mixed 2015-2018 mode in macros).
123     AbsolutePath(Namespace),
124     /// All scopes with macro namespace and the given macro kind restriction.
125     Macro(MacroKind),
126 }
127
128 /// Everything you need to know about a name's location to resolve it.
129 /// Serves as a starting point for the scope visitor.
130 /// This struct is currently used only for early resolution (imports and macros),
131 /// but not for late resolution yet.
132 #[derive(Clone, Copy, Debug)]
133 pub struct ParentScope<'a> {
134     module: Module<'a>,
135     expansion: ExpnId,
136     legacy: LegacyScope<'a>,
137     derives: &'a [ast::Path],
138 }
139
140 impl<'a> ParentScope<'a> {
141     /// Creates a parent scope with the passed argument used as the module scope component,
142     /// and other scope components set to default empty values.
143     pub fn module(module: Module<'a>) -> ParentScope<'a> {
144         ParentScope {
145             module,
146             expansion: ExpnId::root(),
147             legacy: LegacyScope::Empty,
148             derives: &[],
149         }
150     }
151 }
152
153 #[derive(Eq)]
154 struct BindingError {
155     name: Name,
156     origin: BTreeSet<Span>,
157     target: BTreeSet<Span>,
158     could_be_path: bool
159 }
160
161 impl PartialOrd for BindingError {
162     fn partial_cmp(&self, other: &BindingError) -> Option<cmp::Ordering> {
163         Some(self.cmp(other))
164     }
165 }
166
167 impl PartialEq for BindingError {
168     fn eq(&self, other: &BindingError) -> bool {
169         self.name == other.name
170     }
171 }
172
173 impl Ord for BindingError {
174     fn cmp(&self, other: &BindingError) -> cmp::Ordering {
175         self.name.cmp(&other.name)
176     }
177 }
178
179 enum ResolutionError<'a> {
180     /// Error E0401: can't use type or const parameters from outer function.
181     GenericParamsFromOuterFunction(Res, HasGenericParams),
182     /// Error E0403: the name is already used for a type or const parameter in this generic
183     /// parameter list.
184     NameAlreadyUsedInParameterList(Name, Span),
185     /// Error E0407: method is not a member of trait.
186     MethodNotMemberOfTrait(Name, &'a str),
187     /// Error E0437: type is not a member of trait.
188     TypeNotMemberOfTrait(Name, &'a str),
189     /// Error E0438: const is not a member of trait.
190     ConstNotMemberOfTrait(Name, &'a str),
191     /// Error E0408: variable `{}` is not bound in all patterns.
192     VariableNotBoundInPattern(&'a BindingError),
193     /// Error E0409: variable `{}` is bound in inconsistent ways within the same match arm.
194     VariableBoundWithDifferentMode(Name, Span),
195     /// Error E0415: identifier is bound more than once in this parameter list.
196     IdentifierBoundMoreThanOnceInParameterList(&'a str),
197     /// Error E0416: identifier is bound more than once in the same pattern.
198     IdentifierBoundMoreThanOnceInSamePattern(&'a str),
199     /// Error E0426: use of undeclared label.
200     UndeclaredLabel(&'a str, Option<Name>),
201     /// Error E0429: `self` imports are only allowed within a `{ }` list.
202     SelfImportsOnlyAllowedWithin,
203     /// Error E0430: `self` import can only appear once in the list.
204     SelfImportCanOnlyAppearOnceInTheList,
205     /// Error E0431: `self` import can only appear in an import list with a non-empty prefix.
206     SelfImportOnlyInImportListWithNonEmptyPrefix,
207     /// Error E0433: failed to resolve.
208     FailedToResolve { label: String, suggestion: Option<Suggestion> },
209     /// Error E0434: can't capture dynamic environment in a fn item.
210     CannotCaptureDynamicEnvironmentInFnItem,
211     /// Error E0435: attempt to use a non-constant value in a constant.
212     AttemptToUseNonConstantValueInConstant,
213     /// Error E0530: `X` bindings cannot shadow `Y`s.
214     BindingShadowsSomethingUnacceptable(&'a str, Name, &'a NameBinding<'a>),
215     /// Error E0128: type parameters with a default cannot use forward-declared identifiers.
216     ForwardDeclaredTyParam, // FIXME(const_generics:defaults)
217     /// Error E0735: type parameters with a default cannot use `Self`
218     SelfInTyParamDefault,
219     /// Error E0671: const parameter cannot depend on type parameter.
220     ConstParamDependentOnTypeParam,
221 }
222
223 // A minimal representation of a path segment. We use this in resolve because
224 // we synthesize 'path segments' which don't have the rest of an AST or HIR
225 // `PathSegment`.
226 #[derive(Clone, Copy, Debug)]
227 pub struct Segment {
228     ident: Ident,
229     id: Option<NodeId>,
230 }
231
232 impl Segment {
233     fn from_path(path: &Path) -> Vec<Segment> {
234         path.segments.iter().map(|s| s.into()).collect()
235     }
236
237     fn from_ident(ident: Ident) -> Segment {
238         Segment {
239             ident,
240             id: None,
241         }
242     }
243
244     fn names_to_string(segments: &[Segment]) -> String {
245         names_to_string(&segments.iter()
246                             .map(|seg| seg.ident.name)
247                             .collect::<Vec<_>>())
248     }
249 }
250
251 impl<'a> From<&'a ast::PathSegment> for Segment {
252     fn from(seg: &'a ast::PathSegment) -> Segment {
253         Segment {
254             ident: seg.ident,
255             id: Some(seg.id),
256         }
257     }
258 }
259
260 struct UsePlacementFinder {
261     target_module: NodeId,
262     span: Option<Span>,
263     found_use: bool,
264 }
265
266 impl UsePlacementFinder {
267     fn check(krate: &Crate, target_module: NodeId) -> (Option<Span>, bool) {
268         let mut finder = UsePlacementFinder {
269             target_module,
270             span: None,
271             found_use: false,
272         };
273         visit::walk_crate(&mut finder, krate);
274         (finder.span, finder.found_use)
275     }
276 }
277
278 impl<'tcx> Visitor<'tcx> for UsePlacementFinder {
279     fn visit_mod(
280         &mut self,
281         module: &'tcx ast::Mod,
282         _: Span,
283         _: &[ast::Attribute],
284         node_id: NodeId,
285     ) {
286         if self.span.is_some() {
287             return;
288         }
289         if node_id != self.target_module {
290             visit::walk_mod(self, module);
291             return;
292         }
293         // find a use statement
294         for item in &module.items {
295             match item.kind {
296                 ItemKind::Use(..) => {
297                     // don't suggest placing a use before the prelude
298                     // import or other generated ones
299                     if !item.span.from_expansion() {
300                         self.span = Some(item.span.shrink_to_lo());
301                         self.found_use = true;
302                         return;
303                     }
304                 },
305                 // don't place use before extern crate
306                 ItemKind::ExternCrate(_) => {}
307                 // but place them before the first other item
308                 _ => if self.span.map_or(true, |span| item.span < span ) {
309                     if !item.span.from_expansion() {
310                         // don't insert between attributes and an item
311                         if item.attrs.is_empty() {
312                             self.span = Some(item.span.shrink_to_lo());
313                         } else {
314                             // find the first attribute on the item
315                             for attr in &item.attrs {
316                                 if self.span.map_or(true, |span| attr.span < span) {
317                                     self.span = Some(attr.span.shrink_to_lo());
318                                 }
319                             }
320                         }
321                     }
322                 },
323             }
324         }
325     }
326 }
327
328 /// An intermediate resolution result.
329 ///
330 /// This refers to the thing referred by a name. The difference between `Res` and `Item` is that
331 /// items are visible in their whole block, while `Res`es only from the place they are defined
332 /// forward.
333 #[derive(Debug)]
334 enum LexicalScopeBinding<'a> {
335     Item(&'a NameBinding<'a>),
336     Res(Res),
337 }
338
339 impl<'a> LexicalScopeBinding<'a> {
340     fn item(self) -> Option<&'a NameBinding<'a>> {
341         match self {
342             LexicalScopeBinding::Item(binding) => Some(binding),
343             _ => None,
344         }
345     }
346
347     fn res(self) -> Res {
348         match self {
349             LexicalScopeBinding::Item(binding) => binding.res(),
350             LexicalScopeBinding::Res(res) => res,
351         }
352     }
353 }
354
355 #[derive(Copy, Clone, Debug)]
356 enum ModuleOrUniformRoot<'a> {
357     /// Regular module.
358     Module(Module<'a>),
359
360     /// Virtual module that denotes resolution in crate root with fallback to extern prelude.
361     CrateRootAndExternPrelude,
362
363     /// Virtual module that denotes resolution in extern prelude.
364     /// Used for paths starting with `::` on 2018 edition.
365     ExternPrelude,
366
367     /// Virtual module that denotes resolution in current scope.
368     /// Used only for resolving single-segment imports. The reason it exists is that import paths
369     /// are always split into two parts, the first of which should be some kind of module.
370     CurrentScope,
371 }
372
373 impl ModuleOrUniformRoot<'_> {
374     fn same_def(lhs: Self, rhs: Self) -> bool {
375         match (lhs, rhs) {
376             (ModuleOrUniformRoot::Module(lhs),
377              ModuleOrUniformRoot::Module(rhs)) => lhs.def_id() == rhs.def_id(),
378             (ModuleOrUniformRoot::CrateRootAndExternPrelude,
379              ModuleOrUniformRoot::CrateRootAndExternPrelude) |
380             (ModuleOrUniformRoot::ExternPrelude, ModuleOrUniformRoot::ExternPrelude) |
381             (ModuleOrUniformRoot::CurrentScope, ModuleOrUniformRoot::CurrentScope) => true,
382             _ => false,
383         }
384     }
385 }
386
387 #[derive(Clone, Debug)]
388 enum PathResult<'a> {
389     Module(ModuleOrUniformRoot<'a>),
390     NonModule(PartialRes),
391     Indeterminate,
392     Failed {
393         span: Span,
394         label: String,
395         suggestion: Option<Suggestion>,
396         is_error_from_last_segment: bool,
397     },
398 }
399
400 enum ModuleKind {
401     /// An anonymous module; e.g., just a block.
402     ///
403     /// ```
404     /// fn main() {
405     ///     fn f() {} // (1)
406     ///     { // This is an anonymous module
407     ///         f(); // This resolves to (2) as we are inside the block.
408     ///         fn f() {} // (2)
409     ///     }
410     ///     f(); // Resolves to (1)
411     /// }
412     /// ```
413     Block(NodeId),
414     /// Any module with a name.
415     ///
416     /// This could be:
417     ///
418     /// * A normal module â€’ either `mod from_file;` or `mod from_block { }`.
419     /// * A trait or an enum (it implicitly contains associated types, methods and variant
420     ///   constructors).
421     Def(DefKind, DefId, Name),
422 }
423
424 impl ModuleKind {
425     /// Get name of the module.
426     pub fn name(&self) -> Option<Name> {
427         match self {
428             ModuleKind::Block(..) => None,
429             ModuleKind::Def(.., name) => Some(*name),
430         }
431     }
432 }
433
434 type Resolutions<'a> = RefCell<FxIndexMap<(Ident, Namespace), &'a RefCell<NameResolution<'a>>>>;
435
436 /// One node in the tree of modules.
437 pub struct ModuleData<'a> {
438     parent: Option<Module<'a>>,
439     kind: ModuleKind,
440
441     // The def id of the closest normal module (`mod`) ancestor (including this module).
442     normal_ancestor_id: DefId,
443
444     // Mapping between names and their (possibly in-progress) resolutions in this module.
445     // Resolutions in modules from other crates are not populated until accessed.
446     lazy_resolutions: Resolutions<'a>,
447     // True if this is a module from other crate that needs to be populated on access.
448     populate_on_access: Cell<bool>,
449
450     // Macro invocations that can expand into items in this module.
451     unexpanded_invocations: RefCell<FxHashSet<ExpnId>>,
452
453     no_implicit_prelude: bool,
454
455     glob_importers: RefCell<Vec<&'a ImportDirective<'a>>>,
456     globs: RefCell<Vec<&'a ImportDirective<'a>>>,
457
458     // Used to memoize the traits in this module for faster searches through all traits in scope.
459     traits: RefCell<Option<Box<[(Ident, &'a NameBinding<'a>)]>>>,
460
461     /// Span of the module itself. Used for error reporting.
462     span: Span,
463
464     expansion: ExpnId,
465 }
466
467 type Module<'a> = &'a ModuleData<'a>;
468
469 impl<'a> ModuleData<'a> {
470     fn new(parent: Option<Module<'a>>,
471            kind: ModuleKind,
472            normal_ancestor_id: DefId,
473            expansion: ExpnId,
474            span: Span) -> Self {
475         ModuleData {
476             parent,
477             kind,
478             normal_ancestor_id,
479             lazy_resolutions: Default::default(),
480             populate_on_access: Cell::new(!normal_ancestor_id.is_local()),
481             unexpanded_invocations: Default::default(),
482             no_implicit_prelude: false,
483             glob_importers: RefCell::new(Vec::new()),
484             globs: RefCell::new(Vec::new()),
485             traits: RefCell::new(None),
486             span,
487             expansion,
488         }
489     }
490
491     fn for_each_child<R, F>(&'a self, resolver: &mut R, mut f: F)
492         where R: AsMut<Resolver<'a>>, F: FnMut(&mut R, Ident, Namespace, &'a NameBinding<'a>)
493     {
494         for (&(ident, ns), name_resolution) in resolver.as_mut().resolutions(self).borrow().iter() {
495             name_resolution.borrow().binding.map(|binding| f(resolver, ident, ns, binding));
496         }
497     }
498
499     fn res(&self) -> Option<Res> {
500         match self.kind {
501             ModuleKind::Def(kind, def_id, _) => Some(Res::Def(kind, def_id)),
502             _ => None,
503         }
504     }
505
506     fn def_id(&self) -> Option<DefId> {
507         match self.kind {
508             ModuleKind::Def(_, def_id, _) => Some(def_id),
509             _ => None,
510         }
511     }
512
513     // `self` resolves to the first module ancestor that `is_normal`.
514     fn is_normal(&self) -> bool {
515         match self.kind {
516             ModuleKind::Def(DefKind::Mod, _, _) => true,
517             _ => false,
518         }
519     }
520
521     fn is_trait(&self) -> bool {
522         match self.kind {
523             ModuleKind::Def(DefKind::Trait, _, _) => true,
524             _ => false,
525         }
526     }
527
528     fn nearest_item_scope(&'a self) -> Module<'a> {
529         match self.kind {
530             ModuleKind::Def(DefKind::Enum, ..) | ModuleKind::Def(DefKind::Trait, ..) =>
531                 self.parent.expect("enum or trait module without a parent"),
532             _ => self,
533         }
534     }
535
536     fn is_ancestor_of(&self, mut other: &Self) -> bool {
537         while !ptr::eq(self, other) {
538             if let Some(parent) = other.parent {
539                 other = parent;
540             } else {
541                 return false;
542             }
543         }
544         true
545     }
546 }
547
548 impl<'a> fmt::Debug for ModuleData<'a> {
549     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
550         write!(f, "{:?}", self.res())
551     }
552 }
553
554 /// Records a possibly-private value, type, or module definition.
555 #[derive(Clone, Debug)]
556 pub struct NameBinding<'a> {
557     kind: NameBindingKind<'a>,
558     ambiguity: Option<(&'a NameBinding<'a>, AmbiguityKind)>,
559     expansion: ExpnId,
560     span: Span,
561     vis: ty::Visibility,
562 }
563
564 pub trait ToNameBinding<'a> {
565     fn to_name_binding(self, arenas: &'a ResolverArenas<'a>) -> &'a NameBinding<'a>;
566 }
567
568 impl<'a> ToNameBinding<'a> for &'a NameBinding<'a> {
569     fn to_name_binding(self, _: &'a ResolverArenas<'a>) -> &'a NameBinding<'a> {
570         self
571     }
572 }
573
574 #[derive(Clone, Debug)]
575 enum NameBindingKind<'a> {
576     Res(Res, /* is_macro_export */ bool),
577     Module(Module<'a>),
578     Import {
579         binding: &'a NameBinding<'a>,
580         directive: &'a ImportDirective<'a>,
581         used: Cell<bool>,
582     },
583 }
584
585 impl<'a> NameBindingKind<'a> {
586     /// Is this a name binding of a import?
587     fn is_import(&self) -> bool {
588         match *self {
589             NameBindingKind::Import { .. } => true,
590             _ => false,
591         }
592     }
593 }
594
595 struct PrivacyError<'a>(Span, Ident, &'a NameBinding<'a>);
596
597 struct UseError<'a> {
598     err: DiagnosticBuilder<'a>,
599     /// Attach `use` statements for these candidates.
600     candidates: Vec<ImportSuggestion>,
601     /// The `NodeId` of the module to place the use-statements in.
602     node_id: NodeId,
603     /// Whether the diagnostic should state that it's "better".
604     better: bool,
605 }
606
607 #[derive(Clone, Copy, PartialEq, Debug)]
608 enum AmbiguityKind {
609     Import,
610     BuiltinAttr,
611     DeriveHelper,
612     LegacyHelperVsPrelude,
613     LegacyVsModern,
614     GlobVsOuter,
615     GlobVsGlob,
616     GlobVsExpanded,
617     MoreExpandedVsOuter,
618 }
619
620 impl AmbiguityKind {
621     fn descr(self) -> &'static str {
622         match self {
623             AmbiguityKind::Import =>
624                 "name vs any other name during import resolution",
625             AmbiguityKind::BuiltinAttr =>
626                 "built-in attribute vs any other name",
627             AmbiguityKind::DeriveHelper =>
628                 "derive helper attribute vs any other name",
629             AmbiguityKind::LegacyHelperVsPrelude =>
630                 "legacy plugin helper attribute vs name from prelude",
631             AmbiguityKind::LegacyVsModern =>
632                 "`macro_rules` vs non-`macro_rules` from other module",
633             AmbiguityKind::GlobVsOuter =>
634                 "glob import vs any other name from outer scope during import/macro resolution",
635             AmbiguityKind::GlobVsGlob =>
636                 "glob import vs glob import in the same module",
637             AmbiguityKind::GlobVsExpanded =>
638                 "glob import vs macro-expanded name in the same \
639                  module during import/macro resolution",
640             AmbiguityKind::MoreExpandedVsOuter =>
641                 "macro-expanded name vs less macro-expanded name \
642                  from outer scope during import/macro resolution",
643         }
644     }
645 }
646
647 /// Miscellaneous bits of metadata for better ambiguity error reporting.
648 #[derive(Clone, Copy, PartialEq)]
649 enum AmbiguityErrorMisc {
650     SuggestCrate,
651     SuggestSelf,
652     FromPrelude,
653     None,
654 }
655
656 struct AmbiguityError<'a> {
657     kind: AmbiguityKind,
658     ident: Ident,
659     b1: &'a NameBinding<'a>,
660     b2: &'a NameBinding<'a>,
661     misc1: AmbiguityErrorMisc,
662     misc2: AmbiguityErrorMisc,
663 }
664
665 impl<'a> NameBinding<'a> {
666     fn module(&self) -> Option<Module<'a>> {
667         match self.kind {
668             NameBindingKind::Module(module) => Some(module),
669             NameBindingKind::Import { binding, .. } => binding.module(),
670             _ => None,
671         }
672     }
673
674     fn res(&self) -> Res {
675         match self.kind {
676             NameBindingKind::Res(res, _) => res,
677             NameBindingKind::Module(module) => module.res().unwrap(),
678             NameBindingKind::Import { binding, .. } => binding.res(),
679         }
680     }
681
682     fn is_ambiguity(&self) -> bool {
683         self.ambiguity.is_some() || match self.kind {
684             NameBindingKind::Import { binding, .. } => binding.is_ambiguity(),
685             _ => false,
686         }
687     }
688
689     // We sometimes need to treat variants as `pub` for backwards compatibility.
690     fn pseudo_vis(&self) -> ty::Visibility {
691         if self.is_variant() && self.res().def_id().is_local() {
692             ty::Visibility::Public
693         } else {
694             self.vis
695         }
696     }
697
698     fn is_variant(&self) -> bool {
699         match self.kind {
700             NameBindingKind::Res(Res::Def(DefKind::Variant, _), _) |
701             NameBindingKind::Res(Res::Def(DefKind::Ctor(CtorOf::Variant, ..), _), _) => true,
702             _ => false,
703         }
704     }
705
706     fn is_extern_crate(&self) -> bool {
707         match self.kind {
708             NameBindingKind::Import {
709                 directive: &ImportDirective {
710                     subclass: ImportDirectiveSubclass::ExternCrate { .. }, ..
711                 }, ..
712             } => true,
713             NameBindingKind::Module(
714                 &ModuleData { kind: ModuleKind::Def(DefKind::Mod, def_id, _), .. }
715             ) => def_id.index == CRATE_DEF_INDEX,
716             _ => false,
717         }
718     }
719
720     fn is_import(&self) -> bool {
721         match self.kind {
722             NameBindingKind::Import { .. } => true,
723             _ => false,
724         }
725     }
726
727     fn is_glob_import(&self) -> bool {
728         match self.kind {
729             NameBindingKind::Import { directive, .. } => directive.is_glob(),
730             _ => false,
731         }
732     }
733
734     fn is_importable(&self) -> bool {
735         match self.res() {
736             Res::Def(DefKind::AssocConst, _)
737             | Res::Def(DefKind::Method, _)
738             | Res::Def(DefKind::AssocTy, _) => false,
739             _ => true,
740         }
741     }
742
743     fn is_macro_def(&self) -> bool {
744         match self.kind {
745             NameBindingKind::Res(Res::Def(DefKind::Macro(..), _), _) => true,
746             _ => false,
747         }
748     }
749
750     fn macro_kind(&self) -> Option<MacroKind> {
751         self.res().macro_kind()
752     }
753
754     // Suppose that we resolved macro invocation with `invoc_parent_expansion` to binding `binding`
755     // at some expansion round `max(invoc, binding)` when they both emerged from macros.
756     // Then this function returns `true` if `self` may emerge from a macro *after* that
757     // in some later round and screw up our previously found resolution.
758     // See more detailed explanation in
759     // https://github.com/rust-lang/rust/pull/53778#issuecomment-419224049
760     fn may_appear_after(&self, invoc_parent_expansion: ExpnId, binding: &NameBinding<'_>) -> bool {
761         // self > max(invoc, binding) => !(self <= invoc || self <= binding)
762         // Expansions are partially ordered, so "may appear after" is an inversion of
763         // "certainly appears before or simultaneously" and includes unordered cases.
764         let self_parent_expansion = self.expansion;
765         let other_parent_expansion = binding.expansion;
766         let certainly_before_other_or_simultaneously =
767             other_parent_expansion.is_descendant_of(self_parent_expansion);
768         let certainly_before_invoc_or_simultaneously =
769             invoc_parent_expansion.is_descendant_of(self_parent_expansion);
770         !(certainly_before_other_or_simultaneously || certainly_before_invoc_or_simultaneously)
771     }
772 }
773
774 /// Interns the names of the primitive types.
775 ///
776 /// All other types are defined somewhere and possibly imported, but the primitive ones need
777 /// special handling, since they have no place of origin.
778 struct PrimitiveTypeTable {
779     primitive_types: FxHashMap<Name, PrimTy>,
780 }
781
782 impl PrimitiveTypeTable {
783     fn new() -> PrimitiveTypeTable {
784         let mut table = FxHashMap::default();
785
786         table.insert(sym::bool, Bool);
787         table.insert(sym::char, Char);
788         table.insert(sym::f32, Float(FloatTy::F32));
789         table.insert(sym::f64, Float(FloatTy::F64));
790         table.insert(sym::isize, Int(IntTy::Isize));
791         table.insert(sym::i8, Int(IntTy::I8));
792         table.insert(sym::i16, Int(IntTy::I16));
793         table.insert(sym::i32, Int(IntTy::I32));
794         table.insert(sym::i64, Int(IntTy::I64));
795         table.insert(sym::i128, Int(IntTy::I128));
796         table.insert(sym::str, Str);
797         table.insert(sym::usize, Uint(UintTy::Usize));
798         table.insert(sym::u8, Uint(UintTy::U8));
799         table.insert(sym::u16, Uint(UintTy::U16));
800         table.insert(sym::u32, Uint(UintTy::U32));
801         table.insert(sym::u64, Uint(UintTy::U64));
802         table.insert(sym::u128, Uint(UintTy::U128));
803         Self { primitive_types: table }
804     }
805 }
806
807 #[derive(Debug, Default, Clone)]
808 pub struct ExternPreludeEntry<'a> {
809     extern_crate_item: Option<&'a NameBinding<'a>>,
810     pub introduced_by_item: bool,
811 }
812
813 /// The main resolver class.
814 ///
815 /// This is the visitor that walks the whole crate.
816 pub struct Resolver<'a> {
817     session: &'a Session,
818     cstore: &'a CStore,
819
820     pub definitions: Definitions,
821
822     pub graph_root: Module<'a>,
823
824     prelude: Option<Module<'a>>,
825     pub extern_prelude: FxHashMap<Ident, ExternPreludeEntry<'a>>,
826
827     /// N.B., this is used only for better diagnostics, not name resolution itself.
828     has_self: FxHashSet<DefId>,
829
830     /// Names of fields of an item `DefId` accessible with dot syntax.
831     /// Used for hints during error reporting.
832     field_names: FxHashMap<DefId, Vec<Spanned<Name>>>,
833
834     /// All imports known to succeed or fail.
835     determined_imports: Vec<&'a ImportDirective<'a>>,
836
837     /// All non-determined imports.
838     indeterminate_imports: Vec<&'a ImportDirective<'a>>,
839
840     /// FIXME: Refactor things so that these fields are passed through arguments and not resolver.
841     /// We are resolving a last import segment during import validation.
842     last_import_segment: bool,
843     /// This binding should be ignored during in-module resolution, so that we don't get
844     /// "self-confirming" import resolutions during import validation.
845     blacklisted_binding: Option<&'a NameBinding<'a>>,
846
847     /// The idents for the primitive types.
848     primitive_type_table: PrimitiveTypeTable,
849
850     /// Resolutions for nodes that have a single resolution.
851     partial_res_map: NodeMap<PartialRes>,
852     /// Resolutions for import nodes, which have multiple resolutions in different namespaces.
853     import_res_map: NodeMap<PerNS<Option<Res>>>,
854     /// Resolutions for labels (node IDs of their corresponding blocks or loops).
855     label_res_map: NodeMap<NodeId>,
856
857     pub export_map: ExportMap<NodeId>,
858     pub trait_map: TraitMap,
859
860     /// A map from nodes to anonymous modules.
861     /// Anonymous modules are pseudo-modules that are implicitly created around items
862     /// contained within blocks.
863     ///
864     /// For example, if we have this:
865     ///
866     ///  fn f() {
867     ///      fn g() {
868     ///          ...
869     ///      }
870     ///  }
871     ///
872     /// There will be an anonymous module created around `g` with the ID of the
873     /// entry block for `f`.
874     block_map: NodeMap<Module<'a>>,
875     /// A fake module that contains no definition and no prelude. Used so that
876     /// some AST passes can generate identifiers that only resolve to local or
877     /// language items.
878     empty_module: Module<'a>,
879     module_map: FxHashMap<DefId, Module<'a>>,
880     extern_module_map: FxHashMap<(DefId, bool /* MacrosOnly? */), Module<'a>>,
881     binding_parent_modules: FxHashMap<PtrKey<'a, NameBinding<'a>>, Module<'a>>,
882
883     /// Maps glob imports to the names of items actually imported.
884     pub glob_map: GlobMap,
885
886     used_imports: FxHashSet<(NodeId, Namespace)>,
887     pub maybe_unused_trait_imports: NodeSet,
888     pub maybe_unused_extern_crates: Vec<(NodeId, Span)>,
889
890     /// Privacy errors are delayed until the end in order to deduplicate them.
891     privacy_errors: Vec<PrivacyError<'a>>,
892     /// Ambiguity errors are delayed for deduplication.
893     ambiguity_errors: Vec<AmbiguityError<'a>>,
894     /// `use` injections are delayed for better placement and deduplication.
895     use_injections: Vec<UseError<'a>>,
896     /// Crate-local macro expanded `macro_export` referred to by a module-relative path.
897     macro_expanded_macro_export_errors: BTreeSet<(Span, Span)>,
898
899     arenas: &'a ResolverArenas<'a>,
900     dummy_binding: &'a NameBinding<'a>,
901
902     crate_loader: &'a mut CrateLoader<'a>,
903     macro_names: FxHashSet<Ident>,
904     builtin_macros: FxHashMap<Name, SyntaxExtension>,
905     macro_use_prelude: FxHashMap<Name, &'a NameBinding<'a>>,
906     pub all_macros: FxHashMap<Name, Res>,
907     macro_map: FxHashMap<DefId, Lrc<SyntaxExtension>>,
908     dummy_ext_bang: Lrc<SyntaxExtension>,
909     dummy_ext_derive: Lrc<SyntaxExtension>,
910     non_macro_attrs: [Lrc<SyntaxExtension>; 2],
911     macro_defs: FxHashMap<ExpnId, DefId>,
912     local_macro_def_scopes: FxHashMap<NodeId, Module<'a>>,
913     ast_transform_scopes: FxHashMap<ExpnId, Module<'a>>,
914     unused_macros: NodeMap<Span>,
915     proc_macro_stubs: NodeSet,
916     /// Traces collected during macro resolution and validated when it's complete.
917     single_segment_macro_resolutions: Vec<(Ident, MacroKind, ParentScope<'a>,
918                                            Option<&'a NameBinding<'a>>)>,
919     multi_segment_macro_resolutions: Vec<(Vec<Segment>, Span, MacroKind, ParentScope<'a>,
920                                           Option<Res>)>,
921     builtin_attrs: Vec<(Ident, ParentScope<'a>)>,
922     /// Some built-in derives mark items they are applied to so they are treated specially later.
923     /// Derive macros cannot modify the item themselves and have to store the markers in the global
924     /// context, so they attach the markers to derive container IDs using this resolver table.
925     /// FIXME: Find a way for `PartialEq` and `Eq` to emulate `#[structural_match]`
926     /// by marking the produced impls rather than the original items.
927     special_derives: FxHashMap<ExpnId, SpecialDerives>,
928     /// Parent scopes in which the macros were invoked.
929     /// FIXME: `derives` are missing in these parent scopes and need to be taken from elsewhere.
930     invocation_parent_scopes: FxHashMap<ExpnId, ParentScope<'a>>,
931     /// Legacy scopes *produced* by expanding the macro invocations,
932     /// include all the `macro_rules` items and other invocations generated by them.
933     output_legacy_scopes: FxHashMap<ExpnId, LegacyScope<'a>>,
934
935     /// Avoid duplicated errors for "name already defined".
936     name_already_seen: FxHashMap<Name, Span>,
937
938     potentially_unused_imports: Vec<&'a ImportDirective<'a>>,
939
940     /// Table for mapping struct IDs into struct constructor IDs,
941     /// it's not used during normal resolution, only for better error reporting.
942     struct_constructors: DefIdMap<(Res, ty::Visibility)>,
943
944     /// Features enabled for this crate.
945     active_features: FxHashSet<Name>,
946
947     /// Stores enum visibilities to properly build a reduced graph
948     /// when visiting the correspondent variants.
949     variant_vis: DefIdMap<ty::Visibility>,
950 }
951
952 /// Nothing really interesting here; it just provides memory for the rest of the crate.
953 #[derive(Default)]
954 pub struct ResolverArenas<'a> {
955     modules: arena::TypedArena<ModuleData<'a>>,
956     local_modules: RefCell<Vec<Module<'a>>>,
957     name_bindings: arena::TypedArena<NameBinding<'a>>,
958     import_directives: arena::TypedArena<ImportDirective<'a>>,
959     name_resolutions: arena::TypedArena<RefCell<NameResolution<'a>>>,
960     legacy_bindings: arena::TypedArena<LegacyBinding<'a>>,
961     ast_paths: arena::TypedArena<ast::Path>,
962 }
963
964 impl<'a> ResolverArenas<'a> {
965     fn alloc_module(&'a self, module: ModuleData<'a>) -> Module<'a> {
966         let module = self.modules.alloc(module);
967         if module.def_id().map(|def_id| def_id.is_local()).unwrap_or(true) {
968             self.local_modules.borrow_mut().push(module);
969         }
970         module
971     }
972     fn local_modules(&'a self) -> std::cell::Ref<'a, Vec<Module<'a>>> {
973         self.local_modules.borrow()
974     }
975     fn alloc_name_binding(&'a self, name_binding: NameBinding<'a>) -> &'a NameBinding<'a> {
976         self.name_bindings.alloc(name_binding)
977     }
978     fn alloc_import_directive(&'a self, import_directive: ImportDirective<'a>)
979                               -> &'a ImportDirective<'_> {
980         self.import_directives.alloc(import_directive)
981     }
982     fn alloc_name_resolution(&'a self) -> &'a RefCell<NameResolution<'a>> {
983         self.name_resolutions.alloc(Default::default())
984     }
985     fn alloc_legacy_binding(&'a self, binding: LegacyBinding<'a>) -> &'a LegacyBinding<'a> {
986         self.legacy_bindings.alloc(binding)
987     }
988     fn alloc_ast_paths(&'a self, paths: &[ast::Path]) -> &'a [ast::Path] {
989         self.ast_paths.alloc_from_iter(paths.iter().cloned())
990     }
991 }
992
993 impl<'a> AsMut<Resolver<'a>> for Resolver<'a> {
994     fn as_mut(&mut self) -> &mut Resolver<'a> { self }
995 }
996
997 impl<'a, 'b> DefIdTree for &'a Resolver<'b> {
998     fn parent(self, id: DefId) -> Option<DefId> {
999         match id.krate {
1000             LOCAL_CRATE => self.definitions.def_key(id.index).parent,
1001             _ => self.cstore.def_key(id).parent,
1002         }.map(|index| DefId { index, ..id })
1003     }
1004 }
1005
1006 /// This interface is used through the AST→HIR step, to embed full paths into the HIR. After that
1007 /// the resolver is no longer needed as all the relevant information is inline.
1008 impl<'a> hir::lowering::Resolver for Resolver<'a> {
1009     fn resolve_str_path(
1010         &mut self,
1011         span: Span,
1012         crate_root: Option<Name>,
1013         components: &[Name],
1014         ns: Namespace,
1015     ) -> (ast::Path, Res) {
1016         let root = if crate_root.is_some() {
1017             kw::PathRoot
1018         } else {
1019             kw::Crate
1020         };
1021         let segments = iter::once(Ident::with_dummy_span(root))
1022             .chain(
1023                 crate_root.into_iter()
1024                     .chain(components.iter().cloned())
1025                     .map(Ident::with_dummy_span)
1026             ).map(|i| self.new_ast_path_segment(i)).collect::<Vec<_>>();
1027
1028         let path = ast::Path {
1029             span,
1030             segments,
1031         };
1032
1033         let parent_scope = &ParentScope::module(self.graph_root);
1034         let res = match self.resolve_ast_path(&path, ns, parent_scope) {
1035             Ok(res) => res,
1036             Err((span, error)) => {
1037                 self.report_error(span, error);
1038                 Res::Err
1039             }
1040         };
1041         (path, res)
1042     }
1043
1044     fn get_partial_res(&mut self, id: NodeId) -> Option<PartialRes> {
1045         self.partial_res_map.get(&id).cloned()
1046     }
1047
1048     fn get_import_res(&mut self, id: NodeId) -> PerNS<Option<Res>> {
1049         self.import_res_map.get(&id).cloned().unwrap_or_default()
1050     }
1051
1052     fn get_label_res(&mut self, id: NodeId) -> Option<NodeId> {
1053         self.label_res_map.get(&id).cloned()
1054     }
1055
1056     fn definitions(&mut self) -> &mut Definitions {
1057         &mut self.definitions
1058     }
1059
1060     fn has_derives(&self, node_id: NodeId, derives: SpecialDerives) -> bool {
1061         let def_id = self.definitions.local_def_id(node_id);
1062         let expn_id = self.definitions.expansion_that_defined(def_id.index);
1063         self.has_derives(expn_id, derives)
1064     }
1065 }
1066
1067 impl<'a> Resolver<'a> {
1068     pub fn new(session: &'a Session,
1069                cstore: &'a CStore,
1070                krate: &Crate,
1071                crate_name: &str,
1072                crate_loader: &'a mut CrateLoader<'a>,
1073                arenas: &'a ResolverArenas<'a>)
1074                -> Resolver<'a> {
1075         let root_def_id = DefId::local(CRATE_DEF_INDEX);
1076         let root_module_kind = ModuleKind::Def(
1077             DefKind::Mod,
1078             root_def_id,
1079             kw::Invalid,
1080         );
1081         let graph_root = arenas.alloc_module(ModuleData {
1082             no_implicit_prelude: attr::contains_name(&krate.attrs, sym::no_implicit_prelude),
1083             ..ModuleData::new(None, root_module_kind, root_def_id, ExpnId::root(), krate.span)
1084         });
1085         let empty_module_kind = ModuleKind::Def(
1086             DefKind::Mod,
1087             root_def_id,
1088             kw::Invalid,
1089         );
1090         let empty_module = arenas.alloc_module(ModuleData {
1091             no_implicit_prelude: true,
1092             ..ModuleData::new(
1093                 Some(graph_root),
1094                 empty_module_kind,
1095                 root_def_id,
1096                 ExpnId::root(),
1097                 DUMMY_SP,
1098             )
1099         });
1100         let mut module_map = FxHashMap::default();
1101         module_map.insert(DefId::local(CRATE_DEF_INDEX), graph_root);
1102
1103         let mut definitions = Definitions::default();
1104         definitions.create_root_def(crate_name, session.local_crate_disambiguator());
1105
1106         let mut extern_prelude: FxHashMap<Ident, ExternPreludeEntry<'_>> =
1107             session.opts.externs.iter().map(|kv| (Ident::from_str(kv.0), Default::default()))
1108                                        .collect();
1109
1110         if !attr::contains_name(&krate.attrs, sym::no_core) {
1111             extern_prelude.insert(Ident::with_dummy_span(sym::core), Default::default());
1112             if !attr::contains_name(&krate.attrs, sym::no_std) {
1113                 extern_prelude.insert(Ident::with_dummy_span(sym::std), Default::default());
1114                 if session.rust_2018() {
1115                     extern_prelude.insert(Ident::with_dummy_span(sym::meta), Default::default());
1116                 }
1117             }
1118         }
1119
1120         let mut invocation_parent_scopes = FxHashMap::default();
1121         invocation_parent_scopes.insert(ExpnId::root(), ParentScope::module(graph_root));
1122
1123         let mut macro_defs = FxHashMap::default();
1124         macro_defs.insert(ExpnId::root(), root_def_id);
1125
1126         let features = session.features_untracked();
1127         let non_macro_attr =
1128             |mark_used| Lrc::new(SyntaxExtension::non_macro_attr(mark_used, session.edition()));
1129
1130         Resolver {
1131             session,
1132
1133             cstore,
1134
1135             definitions,
1136
1137             // The outermost module has def ID 0; this is not reflected in the
1138             // AST.
1139             graph_root,
1140             prelude: None,
1141             extern_prelude,
1142
1143             has_self: FxHashSet::default(),
1144             field_names: FxHashMap::default(),
1145
1146             determined_imports: Vec::new(),
1147             indeterminate_imports: Vec::new(),
1148
1149             last_import_segment: false,
1150             blacklisted_binding: None,
1151
1152             primitive_type_table: PrimitiveTypeTable::new(),
1153
1154             partial_res_map: Default::default(),
1155             import_res_map: Default::default(),
1156             label_res_map: Default::default(),
1157             export_map: FxHashMap::default(),
1158             trait_map: Default::default(),
1159             empty_module,
1160             module_map,
1161             block_map: Default::default(),
1162             extern_module_map: FxHashMap::default(),
1163             binding_parent_modules: FxHashMap::default(),
1164             ast_transform_scopes: FxHashMap::default(),
1165
1166             glob_map: Default::default(),
1167
1168             used_imports: FxHashSet::default(),
1169             maybe_unused_trait_imports: Default::default(),
1170             maybe_unused_extern_crates: Vec::new(),
1171
1172             privacy_errors: Vec::new(),
1173             ambiguity_errors: Vec::new(),
1174             use_injections: Vec::new(),
1175             macro_expanded_macro_export_errors: BTreeSet::new(),
1176
1177             arenas,
1178             dummy_binding: arenas.alloc_name_binding(NameBinding {
1179                 kind: NameBindingKind::Res(Res::Err, false),
1180                 ambiguity: None,
1181                 expansion: ExpnId::root(),
1182                 span: DUMMY_SP,
1183                 vis: ty::Visibility::Public,
1184             }),
1185
1186             crate_loader,
1187             macro_names: FxHashSet::default(),
1188             builtin_macros: Default::default(),
1189             macro_use_prelude: FxHashMap::default(),
1190             all_macros: FxHashMap::default(),
1191             macro_map: FxHashMap::default(),
1192             dummy_ext_bang: Lrc::new(SyntaxExtension::dummy_bang(session.edition())),
1193             dummy_ext_derive: Lrc::new(SyntaxExtension::dummy_derive(session.edition())),
1194             non_macro_attrs: [non_macro_attr(false), non_macro_attr(true)],
1195             invocation_parent_scopes,
1196             output_legacy_scopes: Default::default(),
1197             macro_defs,
1198             local_macro_def_scopes: FxHashMap::default(),
1199             name_already_seen: FxHashMap::default(),
1200             potentially_unused_imports: Vec::new(),
1201             struct_constructors: Default::default(),
1202             unused_macros: Default::default(),
1203             proc_macro_stubs: Default::default(),
1204             single_segment_macro_resolutions: Default::default(),
1205             multi_segment_macro_resolutions: Default::default(),
1206             builtin_attrs: Default::default(),
1207             special_derives: Default::default(),
1208             active_features:
1209                 features.declared_lib_features.iter().map(|(feat, ..)| *feat)
1210                     .chain(features.declared_lang_features.iter().map(|(feat, ..)| *feat))
1211                     .collect(),
1212             variant_vis: Default::default()
1213         }
1214     }
1215
1216     pub fn arenas() -> ResolverArenas<'a> {
1217         Default::default()
1218     }
1219
1220     fn non_macro_attr(&self, mark_used: bool) -> Lrc<SyntaxExtension> {
1221         self.non_macro_attrs[mark_used as usize].clone()
1222     }
1223
1224     fn dummy_ext(&self, macro_kind: MacroKind) -> Lrc<SyntaxExtension> {
1225         match macro_kind {
1226             MacroKind::Bang => self.dummy_ext_bang.clone(),
1227             MacroKind::Derive => self.dummy_ext_derive.clone(),
1228             MacroKind::Attr => self.non_macro_attr(true),
1229         }
1230     }
1231
1232     /// Runs the function on each namespace.
1233     fn per_ns<F: FnMut(&mut Self, Namespace)>(&mut self, mut f: F) {
1234         f(self, TypeNS);
1235         f(self, ValueNS);
1236         f(self, MacroNS);
1237     }
1238
1239     fn is_builtin_macro(&mut self, res: Res) -> bool {
1240         self.get_macro(res).map_or(false, |ext| ext.is_builtin)
1241     }
1242
1243     fn macro_def(&self, mut ctxt: SyntaxContext) -> DefId {
1244         loop {
1245             match self.macro_defs.get(&ctxt.outer_expn()) {
1246                 Some(&def_id) => return def_id,
1247                 None => ctxt.remove_mark(),
1248             };
1249         }
1250     }
1251
1252     fn has_derives(&self, expn_id: ExpnId, markers: SpecialDerives) -> bool {
1253         self.special_derives.get(&expn_id).map_or(false, |m| m.contains(markers))
1254     }
1255
1256     /// Entry point to crate resolution.
1257     pub fn resolve_crate(&mut self, krate: &Crate) {
1258         let _prof_timer =
1259             self.session.prof.generic_activity("resolve_crate");
1260
1261         ImportResolver { r: self }.finalize_imports();
1262         self.finalize_macro_resolutions();
1263
1264         self.late_resolve_crate(krate);
1265
1266         self.check_unused(krate);
1267         self.report_errors(krate);
1268         self.crate_loader.postprocess(krate);
1269     }
1270
1271     fn new_module(
1272         &self,
1273         parent: Module<'a>,
1274         kind: ModuleKind,
1275         normal_ancestor_id: DefId,
1276         expn_id: ExpnId,
1277         span: Span,
1278     ) -> Module<'a> {
1279         let module = ModuleData::new(Some(parent), kind, normal_ancestor_id, expn_id, span);
1280         self.arenas.alloc_module(module)
1281     }
1282
1283     fn resolutions(&mut self, module: Module<'a>) -> &'a Resolutions<'a> {
1284         if module.populate_on_access.get() {
1285             module.populate_on_access.set(false);
1286             self.build_reduced_graph_external(module);
1287         }
1288         &module.lazy_resolutions
1289     }
1290
1291     fn resolution(&mut self, module: Module<'a>, ident: Ident, ns: Namespace)
1292                   -> &'a RefCell<NameResolution<'a>> {
1293         *self.resolutions(module).borrow_mut().entry((ident.modern(), ns))
1294                .or_insert_with(|| self.arenas.alloc_name_resolution())
1295     }
1296
1297     fn record_use(&mut self, ident: Ident, ns: Namespace,
1298                   used_binding: &'a NameBinding<'a>, is_lexical_scope: bool) {
1299         if let Some((b2, kind)) = used_binding.ambiguity {
1300             self.ambiguity_errors.push(AmbiguityError {
1301                 kind, ident, b1: used_binding, b2,
1302                 misc1: AmbiguityErrorMisc::None,
1303                 misc2: AmbiguityErrorMisc::None,
1304             });
1305         }
1306         if let NameBindingKind::Import { directive, binding, ref used } = used_binding.kind {
1307             // Avoid marking `extern crate` items that refer to a name from extern prelude,
1308             // but not introduce it, as used if they are accessed from lexical scope.
1309             if is_lexical_scope {
1310                 if let Some(entry) = self.extern_prelude.get(&ident.modern()) {
1311                     if let Some(crate_item) = entry.extern_crate_item {
1312                         if ptr::eq(used_binding, crate_item) && !entry.introduced_by_item {
1313                             return;
1314                         }
1315                     }
1316                 }
1317             }
1318             used.set(true);
1319             directive.used.set(true);
1320             self.used_imports.insert((directive.id, ns));
1321             self.add_to_glob_map(&directive, ident);
1322             self.record_use(ident, ns, binding, false);
1323         }
1324     }
1325
1326     #[inline]
1327     fn add_to_glob_map(&mut self, directive: &ImportDirective<'_>, ident: Ident) {
1328         if directive.is_glob() {
1329             self.glob_map.entry(directive.id).or_default().insert(ident.name);
1330         }
1331     }
1332
1333     /// A generic scope visitor.
1334     /// Visits scopes in order to resolve some identifier in them or perform other actions.
1335     /// If the callback returns `Some` result, we stop visiting scopes and return it.
1336     fn visit_scopes<T>(
1337         &mut self,
1338         scope_set: ScopeSet,
1339         parent_scope: &ParentScope<'a>,
1340         ident: Ident,
1341         mut visitor: impl FnMut(&mut Self, Scope<'a>, /*use_prelude*/ bool, Ident) -> Option<T>,
1342     ) -> Option<T> {
1343         // General principles:
1344         // 1. Not controlled (user-defined) names should have higher priority than controlled names
1345         //    built into the language or standard library. This way we can add new names into the
1346         //    language or standard library without breaking user code.
1347         // 2. "Closed set" below means new names cannot appear after the current resolution attempt.
1348         // Places to search (in order of decreasing priority):
1349         // (Type NS)
1350         // 1. FIXME: Ribs (type parameters), there's no necessary infrastructure yet
1351         //    (open set, not controlled).
1352         // 2. Names in modules (both normal `mod`ules and blocks), loop through hygienic parents
1353         //    (open, not controlled).
1354         // 3. Extern prelude (open, the open part is from macro expansions, not controlled).
1355         // 4. Tool modules (closed, controlled right now, but not in the future).
1356         // 5. Standard library prelude (de-facto closed, controlled).
1357         // 6. Language prelude (closed, controlled).
1358         // (Value NS)
1359         // 1. FIXME: Ribs (local variables), there's no necessary infrastructure yet
1360         //    (open set, not controlled).
1361         // 2. Names in modules (both normal `mod`ules and blocks), loop through hygienic parents
1362         //    (open, not controlled).
1363         // 3. Standard library prelude (de-facto closed, controlled).
1364         // (Macro NS)
1365         // 1-3. Derive helpers (open, not controlled). All ambiguities with other names
1366         //    are currently reported as errors. They should be higher in priority than preludes
1367         //    and probably even names in modules according to the "general principles" above. They
1368         //    also should be subject to restricted shadowing because are effectively produced by
1369         //    derives (you need to resolve the derive first to add helpers into scope), but they
1370         //    should be available before the derive is expanded for compatibility.
1371         //    It's mess in general, so we are being conservative for now.
1372         // 1-3. `macro_rules` (open, not controlled), loop through legacy scopes. Have higher
1373         //    priority than prelude macros, but create ambiguities with macros in modules.
1374         // 1-3. Names in modules (both normal `mod`ules and blocks), loop through hygienic parents
1375         //    (open, not controlled). Have higher priority than prelude macros, but create
1376         //    ambiguities with `macro_rules`.
1377         // 4. `macro_use` prelude (open, the open part is from macro expansions, not controlled).
1378         // 4a. User-defined prelude from macro-use
1379         //    (open, the open part is from macro expansions, not controlled).
1380         // 4b. "Standard library prelude" part implemented through `macro-use` (closed, controlled).
1381         // 4c. Standard library prelude (de-facto closed, controlled).
1382         // 6. Language prelude: builtin attributes (closed, controlled).
1383         // 4-6. Legacy plugin helpers (open, not controlled). Similar to derive helpers,
1384         //    but introduced by legacy plugins using `register_attribute`. Priority is somewhere
1385         //    in prelude, not sure where exactly (creates ambiguities with any other prelude names).
1386
1387         let rust_2015 = ident.span.rust_2015();
1388         let (ns, is_absolute_path) = match scope_set {
1389             ScopeSet::All(ns, _) => (ns, false),
1390             ScopeSet::AbsolutePath(ns) => (ns, true),
1391             ScopeSet::Macro(_) => (MacroNS, false),
1392         };
1393         // Jump out of trait or enum modules, they do not act as scopes.
1394         let module = parent_scope.module.nearest_item_scope();
1395         let mut scope = match ns {
1396             _ if is_absolute_path => Scope::CrateRoot,
1397             TypeNS | ValueNS => Scope::Module(module),
1398             MacroNS => Scope::DeriveHelpers,
1399         };
1400         let mut ident = ident.modern();
1401         let mut use_prelude = !module.no_implicit_prelude;
1402
1403         loop {
1404             let visit = match scope {
1405                 Scope::DeriveHelpers => true,
1406                 Scope::MacroRules(..) => true,
1407                 Scope::CrateRoot => true,
1408                 Scope::Module(..) => true,
1409                 Scope::MacroUsePrelude => use_prelude || rust_2015,
1410                 Scope::BuiltinAttrs => true,
1411                 Scope::LegacyPluginHelpers => use_prelude || rust_2015,
1412                 Scope::ExternPrelude => use_prelude || is_absolute_path,
1413                 Scope::ToolPrelude => use_prelude,
1414                 Scope::StdLibPrelude => use_prelude || ns == MacroNS,
1415                 Scope::BuiltinTypes => true,
1416             };
1417
1418             if visit {
1419                 if let break_result @ Some(..) = visitor(self, scope, use_prelude, ident) {
1420                     return break_result;
1421                 }
1422             }
1423
1424             scope = match scope {
1425                 Scope::DeriveHelpers =>
1426                     Scope::MacroRules(parent_scope.legacy),
1427                 Scope::MacroRules(legacy_scope) => match legacy_scope {
1428                     LegacyScope::Binding(binding) => Scope::MacroRules(
1429                         binding.parent_legacy_scope
1430                     ),
1431                     LegacyScope::Invocation(invoc_id) => Scope::MacroRules(
1432                         self.output_legacy_scopes.get(&invoc_id).cloned()
1433                             .unwrap_or(self.invocation_parent_scopes[&invoc_id].legacy)
1434                     ),
1435                     LegacyScope::Empty => Scope::Module(module),
1436                 }
1437                 Scope::CrateRoot => match ns {
1438                     TypeNS => {
1439                         ident.span.adjust(ExpnId::root());
1440                         Scope::ExternPrelude
1441                     }
1442                     ValueNS | MacroNS => break,
1443                 }
1444                 Scope::Module(module) => {
1445                     use_prelude = !module.no_implicit_prelude;
1446                     match self.hygienic_lexical_parent(module, &mut ident.span) {
1447                         Some(parent_module) => Scope::Module(parent_module),
1448                         None => {
1449                             ident.span.adjust(ExpnId::root());
1450                             match ns {
1451                                 TypeNS => Scope::ExternPrelude,
1452                                 ValueNS => Scope::StdLibPrelude,
1453                                 MacroNS => Scope::MacroUsePrelude,
1454                             }
1455                         }
1456                     }
1457                 }
1458                 Scope::MacroUsePrelude => Scope::StdLibPrelude,
1459                 Scope::BuiltinAttrs => Scope::LegacyPluginHelpers,
1460                 Scope::LegacyPluginHelpers => break, // nowhere else to search
1461                 Scope::ExternPrelude if is_absolute_path => break,
1462                 Scope::ExternPrelude => Scope::ToolPrelude,
1463                 Scope::ToolPrelude => Scope::StdLibPrelude,
1464                 Scope::StdLibPrelude => match ns {
1465                     TypeNS => Scope::BuiltinTypes,
1466                     ValueNS => break, // nowhere else to search
1467                     MacroNS => Scope::BuiltinAttrs,
1468                 }
1469                 Scope::BuiltinTypes => break, // nowhere else to search
1470             };
1471         }
1472
1473         None
1474     }
1475
1476     /// This resolves the identifier `ident` in the namespace `ns` in the current lexical scope.
1477     /// More specifically, we proceed up the hierarchy of scopes and return the binding for
1478     /// `ident` in the first scope that defines it (or None if no scopes define it).
1479     ///
1480     /// A block's items are above its local variables in the scope hierarchy, regardless of where
1481     /// the items are defined in the block. For example,
1482     /// ```rust
1483     /// fn f() {
1484     ///    g(); // Since there are no local variables in scope yet, this resolves to the item.
1485     ///    let g = || {};
1486     ///    fn g() {}
1487     ///    g(); // This resolves to the local variable `g` since it shadows the item.
1488     /// }
1489     /// ```
1490     ///
1491     /// Invariant: This must only be called during main resolution, not during
1492     /// import resolution.
1493     fn resolve_ident_in_lexical_scope(&mut self,
1494                                       mut ident: Ident,
1495                                       ns: Namespace,
1496                                       parent_scope: &ParentScope<'a>,
1497                                       record_used_id: Option<NodeId>,
1498                                       path_span: Span,
1499                                       ribs: &[Rib<'a>])
1500                                       -> Option<LexicalScopeBinding<'a>> {
1501         assert!(ns == TypeNS || ns == ValueNS);
1502         if ident.name == kw::Invalid {
1503             return Some(LexicalScopeBinding::Res(Res::Err));
1504         }
1505         let (general_span, modern_span) = if ident.name == kw::SelfUpper {
1506             // FIXME(jseyfried) improve `Self` hygiene
1507             let empty_span = ident.span.with_ctxt(SyntaxContext::root());
1508             (empty_span, empty_span)
1509         } else if ns == TypeNS {
1510             let modern_span = ident.span.modern();
1511             (modern_span, modern_span)
1512         } else {
1513             (ident.span.modern_and_legacy(), ident.span.modern())
1514         };
1515         ident.span = general_span;
1516         let modern_ident = Ident { span: modern_span, ..ident };
1517
1518         // Walk backwards up the ribs in scope.
1519         let record_used = record_used_id.is_some();
1520         let mut module = self.graph_root;
1521         for i in (0 .. ribs.len()).rev() {
1522             debug!("walk rib\n{:?}", ribs[i].bindings);
1523             // Use the rib kind to determine whether we are resolving parameters
1524             // (modern hygiene) or local variables (legacy hygiene).
1525             let rib_ident = if ribs[i].kind.contains_params() {
1526                 modern_ident
1527             } else {
1528                 ident
1529             };
1530             if let Some(res) = ribs[i].bindings.get(&rib_ident).cloned() {
1531                 // The ident resolves to a type parameter or local variable.
1532                 return Some(LexicalScopeBinding::Res(
1533                     self.validate_res_from_ribs(i, rib_ident, res, record_used, path_span, ribs),
1534                 ));
1535             }
1536
1537             module = match ribs[i].kind {
1538                 ModuleRibKind(module) => module,
1539                 MacroDefinition(def) if def == self.macro_def(ident.span.ctxt()) => {
1540                     // If an invocation of this macro created `ident`, give up on `ident`
1541                     // and switch to `ident`'s source from the macro definition.
1542                     ident.span.remove_mark();
1543                     continue
1544                 }
1545                 _ => continue,
1546             };
1547
1548
1549             let item = self.resolve_ident_in_module_unadjusted(
1550                 ModuleOrUniformRoot::Module(module),
1551                 ident,
1552                 ns,
1553                 parent_scope,
1554                 record_used,
1555                 path_span,
1556             );
1557             if let Ok(binding) = item {
1558                 // The ident resolves to an item.
1559                 return Some(LexicalScopeBinding::Item(binding));
1560             }
1561
1562             match module.kind {
1563                 ModuleKind::Block(..) => {}, // We can see through blocks
1564                 _ => break,
1565             }
1566         }
1567
1568         ident = modern_ident;
1569         let mut poisoned = None;
1570         loop {
1571             let opt_module = if let Some(node_id) = record_used_id {
1572                 self.hygienic_lexical_parent_with_compatibility_fallback(module, &mut ident.span,
1573                                                                          node_id, &mut poisoned)
1574             } else {
1575                 self.hygienic_lexical_parent(module, &mut ident.span)
1576             };
1577             module = unwrap_or!(opt_module, break);
1578             let adjusted_parent_scope = &ParentScope { module, ..*parent_scope };
1579             let result = self.resolve_ident_in_module_unadjusted(
1580                 ModuleOrUniformRoot::Module(module),
1581                 ident,
1582                 ns,
1583                 adjusted_parent_scope,
1584                 record_used,
1585                 path_span,
1586             );
1587
1588             match result {
1589                 Ok(binding) => {
1590                     if let Some(node_id) = poisoned {
1591                         self.session.buffer_lint_with_diagnostic(
1592                             lint::builtin::PROC_MACRO_DERIVE_RESOLUTION_FALLBACK,
1593                             node_id, ident.span,
1594                             &format!("cannot find {} `{}` in this scope", ns.descr(), ident),
1595                             lint::builtin::BuiltinLintDiagnostics::
1596                                 ProcMacroDeriveResolutionFallback(ident.span),
1597                         );
1598                     }
1599                     return Some(LexicalScopeBinding::Item(binding))
1600                 }
1601                 Err(Determined) => continue,
1602                 Err(Undetermined) =>
1603                     span_bug!(ident.span, "undetermined resolution during main resolution pass"),
1604             }
1605         }
1606
1607         if !module.no_implicit_prelude {
1608             ident.span.adjust(ExpnId::root());
1609             if ns == TypeNS {
1610                 if let Some(binding) = self.extern_prelude_get(ident, !record_used) {
1611                     return Some(LexicalScopeBinding::Item(binding));
1612                 }
1613             }
1614             if ns == TypeNS && KNOWN_TOOLS.contains(&ident.name) {
1615                 let binding = (Res::ToolMod, ty::Visibility::Public,
1616                                DUMMY_SP, ExpnId::root()).to_name_binding(self.arenas);
1617                 return Some(LexicalScopeBinding::Item(binding));
1618             }
1619             if let Some(prelude) = self.prelude {
1620                 if let Ok(binding) = self.resolve_ident_in_module_unadjusted(
1621                     ModuleOrUniformRoot::Module(prelude),
1622                     ident,
1623                     ns,
1624                     parent_scope,
1625                     false,
1626                     path_span,
1627                 ) {
1628                     return Some(LexicalScopeBinding::Item(binding));
1629                 }
1630             }
1631         }
1632
1633         None
1634     }
1635
1636     fn hygienic_lexical_parent(&mut self, module: Module<'a>, span: &mut Span)
1637                                -> Option<Module<'a>> {
1638         if !module.expansion.outer_expn_is_descendant_of(span.ctxt()) {
1639             return Some(self.macro_def_scope(span.remove_mark()));
1640         }
1641
1642         if let ModuleKind::Block(..) = module.kind {
1643             return Some(module.parent.unwrap().nearest_item_scope());
1644         }
1645
1646         None
1647     }
1648
1649     fn hygienic_lexical_parent_with_compatibility_fallback(&mut self, module: Module<'a>,
1650                                                            span: &mut Span, node_id: NodeId,
1651                                                            poisoned: &mut Option<NodeId>)
1652                                                            -> Option<Module<'a>> {
1653         if let module @ Some(..) = self.hygienic_lexical_parent(module, span) {
1654             return module;
1655         }
1656
1657         // We need to support the next case under a deprecation warning
1658         // ```
1659         // struct MyStruct;
1660         // ---- begin: this comes from a proc macro derive
1661         // mod implementation_details {
1662         //     // Note that `MyStruct` is not in scope here.
1663         //     impl SomeTrait for MyStruct { ... }
1664         // }
1665         // ---- end
1666         // ```
1667         // So we have to fall back to the module's parent during lexical resolution in this case.
1668         if let Some(parent) = module.parent {
1669             // Inner module is inside the macro, parent module is outside of the macro.
1670             if module.expansion != parent.expansion &&
1671             module.expansion.is_descendant_of(parent.expansion) {
1672                 // The macro is a proc macro derive
1673                 if let Some(&def_id) = self.macro_defs.get(&module.expansion) {
1674                     if let Some(ext) = self.get_macro_by_def_id(def_id) {
1675                         if !ext.is_builtin && ext.macro_kind() == MacroKind::Derive {
1676                             if parent.expansion.outer_expn_is_descendant_of(span.ctxt()) {
1677                                 *poisoned = Some(node_id);
1678                                 return module.parent;
1679                             }
1680                         }
1681                     }
1682                 }
1683             }
1684         }
1685
1686         None
1687     }
1688
1689     fn resolve_ident_in_module(
1690         &mut self,
1691         module: ModuleOrUniformRoot<'a>,
1692         ident: Ident,
1693         ns: Namespace,
1694         parent_scope: &ParentScope<'a>,
1695         record_used: bool,
1696         path_span: Span
1697     ) -> Result<&'a NameBinding<'a>, Determinacy> {
1698         self.resolve_ident_in_module_ext(
1699             module, ident, ns, parent_scope, record_used, path_span
1700         ).map_err(|(determinacy, _)| determinacy)
1701     }
1702
1703     fn resolve_ident_in_module_ext(
1704         &mut self,
1705         module: ModuleOrUniformRoot<'a>,
1706         mut ident: Ident,
1707         ns: Namespace,
1708         parent_scope: &ParentScope<'a>,
1709         record_used: bool,
1710         path_span: Span
1711     ) -> Result<&'a NameBinding<'a>, (Determinacy, Weak)> {
1712         let tmp_parent_scope;
1713         let mut adjusted_parent_scope = parent_scope;
1714         match module {
1715             ModuleOrUniformRoot::Module(m) => {
1716                 if let Some(def) = ident.span.modernize_and_adjust(m.expansion) {
1717                     tmp_parent_scope =
1718                         ParentScope { module: self.macro_def_scope(def), ..*parent_scope };
1719                     adjusted_parent_scope = &tmp_parent_scope;
1720                 }
1721             }
1722             ModuleOrUniformRoot::ExternPrelude => {
1723                 ident.span.modernize_and_adjust(ExpnId::root());
1724             }
1725             ModuleOrUniformRoot::CrateRootAndExternPrelude |
1726             ModuleOrUniformRoot::CurrentScope => {
1727                 // No adjustments
1728             }
1729         }
1730         let result = self.resolve_ident_in_module_unadjusted_ext(
1731             module, ident, ns, adjusted_parent_scope, false, record_used, path_span,
1732         );
1733         result
1734     }
1735
1736     fn resolve_crate_root(&mut self, ident: Ident) -> Module<'a> {
1737         let mut ctxt = ident.span.ctxt();
1738         let mark = if ident.name == kw::DollarCrate {
1739             // When resolving `$crate` from a `macro_rules!` invoked in a `macro`,
1740             // we don't want to pretend that the `macro_rules!` definition is in the `macro`
1741             // as described in `SyntaxContext::apply_mark`, so we ignore prepended modern marks.
1742             // FIXME: This is only a guess and it doesn't work correctly for `macro_rules!`
1743             // definitions actually produced by `macro` and `macro` definitions produced by
1744             // `macro_rules!`, but at least such configurations are not stable yet.
1745             ctxt = ctxt.modern_and_legacy();
1746             let mut iter = ctxt.marks().into_iter().rev().peekable();
1747             let mut result = None;
1748             // Find the last modern mark from the end if it exists.
1749             while let Some(&(mark, transparency)) = iter.peek() {
1750                 if transparency == Transparency::Opaque {
1751                     result = Some(mark);
1752                     iter.next();
1753                 } else {
1754                     break;
1755                 }
1756             }
1757             // Then find the last legacy mark from the end if it exists.
1758             for (mark, transparency) in iter {
1759                 if transparency == Transparency::SemiTransparent {
1760                     result = Some(mark);
1761                 } else {
1762                     break;
1763                 }
1764             }
1765             result
1766         } else {
1767             ctxt = ctxt.modern();
1768             ctxt.adjust(ExpnId::root())
1769         };
1770         let module = match mark {
1771             Some(def) => self.macro_def_scope(def),
1772             None => return self.graph_root,
1773         };
1774         self.get_module(DefId { index: CRATE_DEF_INDEX, ..module.normal_ancestor_id })
1775     }
1776
1777     fn resolve_self(&mut self, ctxt: &mut SyntaxContext, module: Module<'a>) -> Module<'a> {
1778         let mut module = self.get_module(module.normal_ancestor_id);
1779         while module.span.ctxt().modern() != *ctxt {
1780             let parent = module.parent.unwrap_or_else(|| self.macro_def_scope(ctxt.remove_mark()));
1781             module = self.get_module(parent.normal_ancestor_id);
1782         }
1783         module
1784     }
1785
1786     fn resolve_path(
1787         &mut self,
1788         path: &[Segment],
1789         opt_ns: Option<Namespace>, // `None` indicates a module path in import
1790         parent_scope: &ParentScope<'a>,
1791         record_used: bool,
1792         path_span: Span,
1793         crate_lint: CrateLint,
1794     ) -> PathResult<'a> {
1795         self.resolve_path_with_ribs(
1796             path, opt_ns, parent_scope, record_used, path_span, crate_lint, None
1797         )
1798     }
1799
1800     fn resolve_path_with_ribs(
1801         &mut self,
1802         path: &[Segment],
1803         opt_ns: Option<Namespace>, // `None` indicates a module path in import
1804         parent_scope: &ParentScope<'a>,
1805         record_used: bool,
1806         path_span: Span,
1807         crate_lint: CrateLint,
1808         ribs: Option<&PerNS<Vec<Rib<'a>>>>,
1809     ) -> PathResult<'a> {
1810         let mut module = None;
1811         let mut allow_super = true;
1812         let mut second_binding = None;
1813
1814         debug!(
1815             "resolve_path(path={:?}, opt_ns={:?}, record_used={:?}, \
1816              path_span={:?}, crate_lint={:?})",
1817             path,
1818             opt_ns,
1819             record_used,
1820             path_span,
1821             crate_lint,
1822         );
1823
1824         for (i, &Segment { ident, id }) in path.iter().enumerate() {
1825             debug!("resolve_path ident {} {:?} {:?}", i, ident, id);
1826             let record_segment_res = |this: &mut Self, res| {
1827                 if record_used {
1828                     if let Some(id) = id {
1829                         if !this.partial_res_map.contains_key(&id) {
1830                             assert!(id != ast::DUMMY_NODE_ID, "Trying to resolve dummy id");
1831                             this.record_partial_res(id, PartialRes::new(res));
1832                         }
1833                     }
1834                 }
1835             };
1836
1837             let is_last = i == path.len() - 1;
1838             let ns = if is_last { opt_ns.unwrap_or(TypeNS) } else { TypeNS };
1839             let name = ident.name;
1840
1841             allow_super &= ns == TypeNS &&
1842                 (name == kw::SelfLower ||
1843                  name == kw::Super);
1844
1845             if ns == TypeNS {
1846                 if allow_super && name == kw::Super {
1847                     let mut ctxt = ident.span.ctxt().modern();
1848                     let self_module = match i {
1849                         0 => Some(self.resolve_self(&mut ctxt, parent_scope.module)),
1850                         _ => match module {
1851                             Some(ModuleOrUniformRoot::Module(module)) => Some(module),
1852                             _ => None,
1853                         },
1854                     };
1855                     if let Some(self_module) = self_module {
1856                         if let Some(parent) = self_module.parent {
1857                             module = Some(ModuleOrUniformRoot::Module(
1858                                 self.resolve_self(&mut ctxt, parent)));
1859                             continue;
1860                         }
1861                     }
1862                     let msg = "there are too many initial `super`s.".to_string();
1863                     return PathResult::Failed {
1864                         span: ident.span,
1865                         label: msg,
1866                         suggestion: None,
1867                         is_error_from_last_segment: false,
1868                     };
1869                 }
1870                 if i == 0 {
1871                     if name == kw::SelfLower {
1872                         let mut ctxt = ident.span.ctxt().modern();
1873                         module = Some(ModuleOrUniformRoot::Module(
1874                             self.resolve_self(&mut ctxt, parent_scope.module)));
1875                         continue;
1876                     }
1877                     if name == kw::PathRoot && ident.span.rust_2018() {
1878                         module = Some(ModuleOrUniformRoot::ExternPrelude);
1879                         continue;
1880                     }
1881                     if name == kw::PathRoot &&
1882                        ident.span.rust_2015() && self.session.rust_2018() {
1883                         // `::a::b` from 2015 macro on 2018 global edition
1884                         module = Some(ModuleOrUniformRoot::CrateRootAndExternPrelude);
1885                         continue;
1886                     }
1887                     if name == kw::PathRoot ||
1888                        name == kw::Crate ||
1889                        name == kw::DollarCrate {
1890                         // `::a::b`, `crate::a::b` or `$crate::a::b`
1891                         module = Some(ModuleOrUniformRoot::Module(
1892                             self.resolve_crate_root(ident)));
1893                         continue;
1894                     }
1895                 }
1896             }
1897
1898             // Report special messages for path segment keywords in wrong positions.
1899             if ident.is_path_segment_keyword() && i != 0 {
1900                 let name_str = if name == kw::PathRoot {
1901                     "crate root".to_string()
1902                 } else {
1903                     format!("`{}`", name)
1904                 };
1905                 let label = if i == 1 && path[0].ident.name == kw::PathRoot {
1906                     format!("global paths cannot start with {}", name_str)
1907                 } else {
1908                     format!("{} in paths can only be used in start position", name_str)
1909                 };
1910                 return PathResult::Failed {
1911                     span: ident.span,
1912                     label,
1913                     suggestion: None,
1914                     is_error_from_last_segment: false,
1915                 };
1916             }
1917
1918             let binding = if let Some(module) = module {
1919                 self.resolve_ident_in_module(
1920                     module, ident, ns, parent_scope, record_used, path_span
1921                 )
1922             } else if ribs.is_none() || opt_ns.is_none() || opt_ns == Some(MacroNS) {
1923                 let scopes = ScopeSet::All(ns, opt_ns.is_none());
1924                 self.early_resolve_ident_in_lexical_scope(ident, scopes, parent_scope, record_used,
1925                                                           record_used, path_span)
1926             } else {
1927                 let record_used_id =
1928                     if record_used { crate_lint.node_id().or(Some(CRATE_NODE_ID)) } else { None };
1929                 match self.resolve_ident_in_lexical_scope(
1930                     ident, ns, parent_scope, record_used_id, path_span, &ribs.unwrap()[ns]
1931                 ) {
1932                     // we found a locally-imported or available item/module
1933                     Some(LexicalScopeBinding::Item(binding)) => Ok(binding),
1934                     // we found a local variable or type param
1935                     Some(LexicalScopeBinding::Res(res))
1936                             if opt_ns == Some(TypeNS) || opt_ns == Some(ValueNS) => {
1937                         record_segment_res(self, res);
1938                         return PathResult::NonModule(PartialRes::with_unresolved_segments(
1939                             res, path.len() - 1
1940                         ));
1941                     }
1942                     _ => Err(Determinacy::determined(record_used)),
1943                 }
1944             };
1945
1946             match binding {
1947                 Ok(binding) => {
1948                     if i == 1 {
1949                         second_binding = Some(binding);
1950                     }
1951                     let res = binding.res();
1952                     let maybe_assoc = opt_ns != Some(MacroNS) && PathSource::Type.is_expected(res);
1953                     if let Some(next_module) = binding.module() {
1954                         module = Some(ModuleOrUniformRoot::Module(next_module));
1955                         record_segment_res(self, res);
1956                     } else if res == Res::ToolMod && i + 1 != path.len() {
1957                         if binding.is_import() {
1958                             self.session.struct_span_err(
1959                                 ident.span, "cannot use a tool module through an import"
1960                             ).span_note(
1961                                 binding.span, "the tool module imported here"
1962                             ).emit();
1963                         }
1964                         let res = Res::NonMacroAttr(NonMacroAttrKind::Tool);
1965                         return PathResult::NonModule(PartialRes::new(res));
1966                     } else if res == Res::Err {
1967                         return PathResult::NonModule(PartialRes::new(Res::Err));
1968                     } else if opt_ns.is_some() && (is_last || maybe_assoc) {
1969                         self.lint_if_path_starts_with_module(
1970                             crate_lint,
1971                             path,
1972                             path_span,
1973                             second_binding,
1974                         );
1975                         return PathResult::NonModule(PartialRes::with_unresolved_segments(
1976                             res, path.len() - i - 1
1977                         ));
1978                     } else {
1979                         let label = format!(
1980                             "`{}` is {} {}, not a module",
1981                             ident,
1982                             res.article(),
1983                             res.descr(),
1984                         );
1985
1986                         return PathResult::Failed {
1987                             span: ident.span,
1988                             label,
1989                             suggestion: None,
1990                             is_error_from_last_segment: is_last,
1991                         };
1992                     }
1993                 }
1994                 Err(Undetermined) => return PathResult::Indeterminate,
1995                 Err(Determined) => {
1996                     if let Some(ModuleOrUniformRoot::Module(module)) = module {
1997                         if opt_ns.is_some() && !module.is_normal() {
1998                             return PathResult::NonModule(PartialRes::with_unresolved_segments(
1999                                 module.res().unwrap(), path.len() - i
2000                             ));
2001                         }
2002                     }
2003                     let module_res = match module {
2004                         Some(ModuleOrUniformRoot::Module(module)) => module.res(),
2005                         _ => None,
2006                     };
2007                     let (label, suggestion) = if module_res == self.graph_root.res() {
2008                         let is_mod = |res| {
2009                             match res { Res::Def(DefKind::Mod, _) => true, _ => false }
2010                         };
2011                         let mut candidates =
2012                             self.lookup_import_candidates(ident, TypeNS, is_mod);
2013                         candidates.sort_by_cached_key(|c| {
2014                             (c.path.segments.len(), c.path.to_string())
2015                         });
2016                         if let Some(candidate) = candidates.get(0) {
2017                             (
2018                                 String::from("unresolved import"),
2019                                 Some((
2020                                     vec![(ident.span, candidate.path.to_string())],
2021                                     String::from("a similar path exists"),
2022                                     Applicability::MaybeIncorrect,
2023                                 )),
2024                             )
2025                         } else if !ident.is_reserved() {
2026                             (format!("maybe a missing crate `{}`?", ident), None)
2027                         } else {
2028                             // the parser will already have complained about the keyword being used
2029                             return PathResult::NonModule(PartialRes::new(Res::Err));
2030                         }
2031                     } else if i == 0 {
2032                         (format!("use of undeclared type or module `{}`", ident), None)
2033                     } else {
2034                         (format!("could not find `{}` in `{}`", ident, path[i - 1].ident), None)
2035                     };
2036                     return PathResult::Failed {
2037                         span: ident.span,
2038                         label,
2039                         suggestion,
2040                         is_error_from_last_segment: is_last,
2041                     };
2042                 }
2043             }
2044         }
2045
2046         self.lint_if_path_starts_with_module(crate_lint, path, path_span, second_binding);
2047
2048         PathResult::Module(match module {
2049             Some(module) => module,
2050             None if path.is_empty() => ModuleOrUniformRoot::CurrentScope,
2051             _ => span_bug!(path_span, "resolve_path: non-empty path `{:?}` has no module", path),
2052         })
2053     }
2054
2055     fn lint_if_path_starts_with_module(
2056         &self,
2057         crate_lint: CrateLint,
2058         path: &[Segment],
2059         path_span: Span,
2060         second_binding: Option<&NameBinding<'_>>,
2061     ) {
2062         let (diag_id, diag_span) = match crate_lint {
2063             CrateLint::No => return,
2064             CrateLint::SimplePath(id) => (id, path_span),
2065             CrateLint::UsePath { root_id, root_span } => (root_id, root_span),
2066             CrateLint::QPathTrait { qpath_id, qpath_span } => (qpath_id, qpath_span),
2067         };
2068
2069         let first_name = match path.get(0) {
2070             // In the 2018 edition this lint is a hard error, so nothing to do
2071             Some(seg) if seg.ident.span.rust_2015() && self.session.rust_2015() => seg.ident.name,
2072             _ => return,
2073         };
2074
2075         // We're only interested in `use` paths which should start with
2076         // `{{root}}` currently.
2077         if first_name != kw::PathRoot {
2078             return
2079         }
2080
2081         match path.get(1) {
2082             // If this import looks like `crate::...` it's already good
2083             Some(Segment { ident, .. }) if ident.name == kw::Crate => return,
2084             // Otherwise go below to see if it's an extern crate
2085             Some(_) => {}
2086             // If the path has length one (and it's `PathRoot` most likely)
2087             // then we don't know whether we're gonna be importing a crate or an
2088             // item in our crate. Defer this lint to elsewhere
2089             None => return,
2090         }
2091
2092         // If the first element of our path was actually resolved to an
2093         // `ExternCrate` (also used for `crate::...`) then no need to issue a
2094         // warning, this looks all good!
2095         if let Some(binding) = second_binding {
2096             if let NameBindingKind::Import { directive: d, .. } = binding.kind {
2097                 // Careful: we still want to rewrite paths from
2098                 // renamed extern crates.
2099                 if let ImportDirectiveSubclass::ExternCrate { source: None, .. } = d.subclass {
2100                     return
2101                 }
2102             }
2103         }
2104
2105         let diag = lint::builtin::BuiltinLintDiagnostics
2106             ::AbsPathWithModule(diag_span);
2107         self.session.buffer_lint_with_diagnostic(
2108             lint::builtin::ABSOLUTE_PATHS_NOT_STARTING_WITH_CRATE,
2109             diag_id, diag_span,
2110             "absolute paths must start with `self`, `super`, \
2111             `crate`, or an external crate name in the 2018 edition",
2112             diag);
2113     }
2114
2115     // Validate a local resolution (from ribs).
2116     fn validate_res_from_ribs(
2117         &mut self,
2118         rib_index: usize,
2119         rib_ident: Ident,
2120         res: Res,
2121         record_used: bool,
2122         span: Span,
2123         all_ribs: &[Rib<'a>],
2124     ) -> Res {
2125         debug!("validate_res_from_ribs({:?})", res);
2126         let ribs = &all_ribs[rib_index + 1..];
2127
2128         // An invalid forward use of a type parameter from a previous default.
2129         if let ForwardTyParamBanRibKind = all_ribs[rib_index].kind {
2130             if record_used {
2131                 let res_error = if rib_ident.name == kw::SelfUpper {
2132                     ResolutionError::SelfInTyParamDefault
2133                 } else {
2134                     ResolutionError::ForwardDeclaredTyParam
2135                 };
2136                 self.report_error(span, res_error);
2137             }
2138             assert_eq!(res, Res::Err);
2139             return Res::Err;
2140         }
2141
2142         // An invalid use of a type parameter as the type of a const parameter.
2143         if let TyParamAsConstParamTy = all_ribs[rib_index].kind {
2144             if record_used {
2145                 self.report_error(span, ResolutionError::ConstParamDependentOnTypeParam);
2146             }
2147             assert_eq!(res, Res::Err);
2148             return Res::Err;
2149         }
2150
2151         match res {
2152             Res::Local(_) => {
2153                 use ResolutionError::*;
2154                 let mut res_err = None;
2155
2156                 for rib in ribs {
2157                     match rib.kind {
2158                         NormalRibKind | ModuleRibKind(..) | MacroDefinition(..) |
2159                         ForwardTyParamBanRibKind | TyParamAsConstParamTy => {
2160                             // Nothing to do. Continue.
2161                         }
2162                         ItemRibKind(_) | FnItemRibKind | AssocItemRibKind => {
2163                             // This was an attempt to access an upvar inside a
2164                             // named function item. This is not allowed, so we
2165                             // report an error.
2166                             if record_used {
2167                                 // We don't immediately trigger a resolve error, because
2168                                 // we want certain other resolution errors (namely those
2169                                 // emitted for `ConstantItemRibKind` below) to take
2170                                 // precedence.
2171                                 res_err = Some(CannotCaptureDynamicEnvironmentInFnItem);
2172                             }
2173                         }
2174                         ConstantItemRibKind => {
2175                             // Still doesn't deal with upvars
2176                             if record_used {
2177                                 self.report_error(span, AttemptToUseNonConstantValueInConstant);
2178                             }
2179                             return Res::Err;
2180                         }
2181                     }
2182                 }
2183                 if let Some(res_err) = res_err {
2184                      self.report_error(span, res_err);
2185                      return Res::Err;
2186                 }
2187             }
2188             Res::Def(DefKind::TyParam, _) | Res::SelfTy(..) => {
2189                 for rib in ribs {
2190                     let has_generic_params = match rib.kind {
2191                         NormalRibKind | AssocItemRibKind |
2192                         ModuleRibKind(..) | MacroDefinition(..) | ForwardTyParamBanRibKind |
2193                         ConstantItemRibKind | TyParamAsConstParamTy => {
2194                             // Nothing to do. Continue.
2195                             continue;
2196                         }
2197                         // This was an attempt to use a type parameter outside its scope.
2198                         ItemRibKind(has_generic_params) => has_generic_params,
2199                         FnItemRibKind => HasGenericParams::Yes,
2200                     };
2201
2202                     if record_used {
2203                         self.report_error(span, ResolutionError::GenericParamsFromOuterFunction(
2204                             res, has_generic_params));
2205                     }
2206                     return Res::Err;
2207                 }
2208             }
2209             Res::Def(DefKind::ConstParam, _) => {
2210                 let mut ribs = ribs.iter().peekable();
2211                 if let Some(Rib { kind: FnItemRibKind, .. }) = ribs.peek() {
2212                     // When declaring const parameters inside function signatures, the first rib
2213                     // is always a `FnItemRibKind`. In this case, we can skip it, to avoid it
2214                     // (spuriously) conflicting with the const param.
2215                     ribs.next();
2216                 }
2217                 for rib in ribs {
2218                     let has_generic_params = match rib.kind {
2219                         ItemRibKind(has_generic_params) => has_generic_params,
2220                         FnItemRibKind => HasGenericParams::Yes,
2221                         _ => continue,
2222                     };
2223
2224                     // This was an attempt to use a const parameter outside its scope.
2225                     if record_used {
2226                         self.report_error(span, ResolutionError::GenericParamsFromOuterFunction(
2227                             res, has_generic_params));
2228                     }
2229                     return Res::Err;
2230                 }
2231             }
2232             _ => {}
2233         }
2234         res
2235     }
2236
2237     fn record_partial_res(&mut self, node_id: NodeId, resolution: PartialRes) {
2238         debug!("(recording res) recording {:?} for {}", resolution, node_id);
2239         if let Some(prev_res) = self.partial_res_map.insert(node_id, resolution) {
2240             panic!("path resolved multiple times ({:?} before, {:?} now)", prev_res, resolution);
2241         }
2242     }
2243
2244     fn is_accessible_from(&self, vis: ty::Visibility, module: Module<'a>) -> bool {
2245         vis.is_accessible_from(module.normal_ancestor_id, self)
2246     }
2247
2248     fn set_binding_parent_module(&mut self, binding: &'a NameBinding<'a>, module: Module<'a>) {
2249         if let Some(old_module) = self.binding_parent_modules.insert(PtrKey(binding), module) {
2250             if !ptr::eq(module, old_module) {
2251                 span_bug!(binding.span, "parent module is reset for binding");
2252             }
2253         }
2254     }
2255
2256     fn disambiguate_legacy_vs_modern(
2257         &self,
2258         legacy: &'a NameBinding<'a>,
2259         modern: &'a NameBinding<'a>,
2260     ) -> bool {
2261         // Some non-controversial subset of ambiguities "modern macro name" vs "macro_rules"
2262         // is disambiguated to mitigate regressions from macro modularization.
2263         // Scoping for `macro_rules` behaves like scoping for `let` at module level, in general.
2264         match (self.binding_parent_modules.get(&PtrKey(legacy)),
2265                self.binding_parent_modules.get(&PtrKey(modern))) {
2266             (Some(legacy), Some(modern)) =>
2267                 legacy.normal_ancestor_id == modern.normal_ancestor_id &&
2268                 modern.is_ancestor_of(legacy),
2269             _ => false,
2270         }
2271     }
2272
2273     fn binding_description(&self, b: &NameBinding<'_>, ident: Ident, from_prelude: bool) -> String {
2274         let res = b.res();
2275         if b.span.is_dummy() {
2276             let add_built_in = match b.res() {
2277                 // These already contain the "built-in" prefix or look bad with it.
2278                 Res::NonMacroAttr(..) | Res::PrimTy(..) | Res::ToolMod => false,
2279                 _ => true,
2280             };
2281             let (built_in, from) = if from_prelude {
2282                 ("", " from prelude")
2283             } else if b.is_extern_crate() && !b.is_import() &&
2284                         self.session.opts.externs.get(&ident.as_str()).is_some() {
2285                 ("", " passed with `--extern`")
2286             } else if add_built_in {
2287                 (" built-in", "")
2288             } else {
2289                 ("", "")
2290             };
2291
2292             let article = if built_in.is_empty() { res.article() } else { "a" };
2293             format!("{a}{built_in} {thing}{from}",
2294                     a = article, thing = res.descr(), built_in = built_in, from = from)
2295         } else {
2296             let introduced = if b.is_import() { "imported" } else { "defined" };
2297             format!("the {thing} {introduced} here",
2298                     thing = res.descr(), introduced = introduced)
2299         }
2300     }
2301
2302     fn report_ambiguity_error(&self, ambiguity_error: &AmbiguityError<'_>) {
2303         let AmbiguityError { kind, ident, b1, b2, misc1, misc2 } = *ambiguity_error;
2304         let (b1, b2, misc1, misc2, swapped) = if b2.span.is_dummy() && !b1.span.is_dummy() {
2305             // We have to print the span-less alternative first, otherwise formatting looks bad.
2306             (b2, b1, misc2, misc1, true)
2307         } else {
2308             (b1, b2, misc1, misc2, false)
2309         };
2310
2311         let mut err = struct_span_err!(self.session, ident.span, E0659,
2312                                        "`{ident}` is ambiguous ({why})",
2313                                        ident = ident, why = kind.descr());
2314         err.span_label(ident.span, "ambiguous name");
2315
2316         let mut could_refer_to = |b: &NameBinding<'_>, misc: AmbiguityErrorMisc, also: &str| {
2317             let what = self.binding_description(b, ident, misc == AmbiguityErrorMisc::FromPrelude);
2318             let note_msg = format!("`{ident}` could{also} refer to {what}",
2319                                    ident = ident, also = also, what = what);
2320
2321             let thing = b.res().descr();
2322             let mut help_msgs = Vec::new();
2323             if b.is_glob_import() && (kind == AmbiguityKind::GlobVsGlob ||
2324                                       kind == AmbiguityKind::GlobVsExpanded ||
2325                                       kind == AmbiguityKind::GlobVsOuter &&
2326                                       swapped != also.is_empty()) {
2327                 help_msgs.push(format!("consider adding an explicit import of \
2328                                         `{ident}` to disambiguate", ident = ident))
2329             }
2330             if b.is_extern_crate() && ident.span.rust_2018() {
2331                 help_msgs.push(format!(
2332                     "use `::{ident}` to refer to this {thing} unambiguously",
2333                     ident = ident, thing = thing,
2334                 ))
2335             }
2336             if misc == AmbiguityErrorMisc::SuggestCrate {
2337                 help_msgs.push(format!(
2338                     "use `crate::{ident}` to refer to this {thing} unambiguously",
2339                     ident = ident, thing = thing,
2340                 ))
2341             } else if misc == AmbiguityErrorMisc::SuggestSelf {
2342                 help_msgs.push(format!(
2343                     "use `self::{ident}` to refer to this {thing} unambiguously",
2344                     ident = ident, thing = thing,
2345                 ))
2346             }
2347
2348             err.span_note(b.span, &note_msg);
2349             for (i, help_msg) in help_msgs.iter().enumerate() {
2350                 let or = if i == 0 { "" } else { "or " };
2351                 err.help(&format!("{}{}", or, help_msg));
2352             }
2353         };
2354
2355         could_refer_to(b1, misc1, "");
2356         could_refer_to(b2, misc2, " also");
2357         err.emit();
2358     }
2359
2360     fn report_errors(&mut self, krate: &Crate) {
2361         self.report_with_use_injections(krate);
2362
2363         for &(span_use, span_def) in &self.macro_expanded_macro_export_errors {
2364             let msg = "macro-expanded `macro_export` macros from the current crate \
2365                        cannot be referred to by absolute paths";
2366             self.session.buffer_lint_with_diagnostic(
2367                 lint::builtin::MACRO_EXPANDED_MACRO_EXPORTS_ACCESSED_BY_ABSOLUTE_PATHS,
2368                 CRATE_NODE_ID, span_use, msg,
2369                 lint::builtin::BuiltinLintDiagnostics::
2370                     MacroExpandedMacroExportsAccessedByAbsolutePaths(span_def),
2371             );
2372         }
2373
2374         for ambiguity_error in &self.ambiguity_errors {
2375             self.report_ambiguity_error(ambiguity_error);
2376         }
2377
2378         let mut reported_spans = FxHashSet::default();
2379         for &PrivacyError(dedup_span, ident, binding) in &self.privacy_errors {
2380             if reported_spans.insert(dedup_span) {
2381                 let mut err = struct_span_err!(
2382                     self.session,
2383                     ident.span,
2384                     E0603,
2385                     "{} `{}` is private",
2386                     binding.res().descr(),
2387                     ident.name,
2388                 );
2389                 if let NameBindingKind::Res(
2390                     Res::Def(DefKind::Ctor(CtorOf::Struct, CtorKind::Fn), ctor_def_id), _
2391                 ) = binding.kind {
2392                     let def_id = (&*self).parent(ctor_def_id).expect("no parent for a constructor");
2393                     if let Some(fields) = self.field_names.get(&def_id) {
2394                         let first_field = fields.first().expect("empty field list in the map");
2395                         err.span_label(
2396                             fields.iter().fold(first_field.span, |acc, field| acc.to(field.span)),
2397                             "a tuple struct constructor is private if any of its fields is private",
2398                         );
2399                     }
2400                 }
2401                 err.emit();
2402             }
2403         }
2404     }
2405
2406     fn report_with_use_injections(&mut self, krate: &Crate) {
2407         for UseError { mut err, candidates, node_id, better } in self.use_injections.drain(..) {
2408             let (span, found_use) = UsePlacementFinder::check(krate, node_id);
2409             if !candidates.is_empty() {
2410                 diagnostics::show_candidates(&mut err, span, &candidates, better, found_use);
2411             }
2412             err.emit();
2413         }
2414     }
2415
2416     fn report_conflict<'b>(&mut self,
2417                        parent: Module<'_>,
2418                        ident: Ident,
2419                        ns: Namespace,
2420                        new_binding: &NameBinding<'b>,
2421                        old_binding: &NameBinding<'b>) {
2422         // Error on the second of two conflicting names
2423         if old_binding.span.lo() > new_binding.span.lo() {
2424             return self.report_conflict(parent, ident, ns, old_binding, new_binding);
2425         }
2426
2427         let container = match parent.kind {
2428             ModuleKind::Def(DefKind::Mod, _, _) => "module",
2429             ModuleKind::Def(DefKind::Trait, _, _) => "trait",
2430             ModuleKind::Block(..) => "block",
2431             _ => "enum",
2432         };
2433
2434         let old_noun = match old_binding.is_import() {
2435             true => "import",
2436             false => "definition",
2437         };
2438
2439         let new_participle = match new_binding.is_import() {
2440             true => "imported",
2441             false => "defined",
2442         };
2443
2444         let (name, span) = (ident.name, self.session.source_map().def_span(new_binding.span));
2445
2446         if let Some(s) = self.name_already_seen.get(&name) {
2447             if s == &span {
2448                 return;
2449             }
2450         }
2451
2452         let old_kind = match (ns, old_binding.module()) {
2453             (ValueNS, _) => "value",
2454             (MacroNS, _) => "macro",
2455             (TypeNS, _) if old_binding.is_extern_crate() => "extern crate",
2456             (TypeNS, Some(module)) if module.is_normal() => "module",
2457             (TypeNS, Some(module)) if module.is_trait() => "trait",
2458             (TypeNS, _) => "type",
2459         };
2460
2461         let msg = format!("the name `{}` is defined multiple times", name);
2462
2463         let mut err = match (old_binding.is_extern_crate(), new_binding.is_extern_crate()) {
2464             (true, true) => struct_span_err!(self.session, span, E0259, "{}", msg),
2465             (true, _) | (_, true) => match new_binding.is_import() && old_binding.is_import() {
2466                 true => struct_span_err!(self.session, span, E0254, "{}", msg),
2467                 false => struct_span_err!(self.session, span, E0260, "{}", msg),
2468             },
2469             _ => match (old_binding.is_import(), new_binding.is_import()) {
2470                 (false, false) => struct_span_err!(self.session, span, E0428, "{}", msg),
2471                 (true, true) => struct_span_err!(self.session, span, E0252, "{}", msg),
2472                 _ => struct_span_err!(self.session, span, E0255, "{}", msg),
2473             },
2474         };
2475
2476         err.note(&format!("`{}` must be defined only once in the {} namespace of this {}",
2477                           name,
2478                           ns.descr(),
2479                           container));
2480
2481         err.span_label(span, format!("`{}` re{} here", name, new_participle));
2482         err.span_label(
2483             self.session.source_map().def_span(old_binding.span),
2484             format!("previous {} of the {} `{}` here", old_noun, old_kind, name),
2485         );
2486
2487         // See https://github.com/rust-lang/rust/issues/32354
2488         use NameBindingKind::Import;
2489         let directive = match (&new_binding.kind, &old_binding.kind) {
2490             // If there are two imports where one or both have attributes then prefer removing the
2491             // import without attributes.
2492             (Import { directive: new, .. }, Import { directive: old, .. }) if {
2493                 !new_binding.span.is_dummy() && !old_binding.span.is_dummy() &&
2494                     (new.has_attributes || old.has_attributes)
2495             } => {
2496                 if old.has_attributes {
2497                     Some((new, new_binding.span, true))
2498                 } else {
2499                     Some((old, old_binding.span, true))
2500                 }
2501             },
2502             // Otherwise prioritize the new binding.
2503             (Import { directive, .. }, other) if !new_binding.span.is_dummy() =>
2504                 Some((directive, new_binding.span, other.is_import())),
2505             (other, Import { directive, .. }) if !old_binding.span.is_dummy() =>
2506                 Some((directive, old_binding.span, other.is_import())),
2507             _ => None,
2508         };
2509
2510         // Check if the target of the use for both bindings is the same.
2511         let duplicate = new_binding.res().opt_def_id() == old_binding.res().opt_def_id();
2512         let has_dummy_span = new_binding.span.is_dummy() || old_binding.span.is_dummy();
2513         let from_item = self.extern_prelude.get(&ident)
2514             .map(|entry| entry.introduced_by_item)
2515             .unwrap_or(true);
2516         // Only suggest removing an import if both bindings are to the same def, if both spans
2517         // aren't dummy spans. Further, if both bindings are imports, then the ident must have
2518         // been introduced by a item.
2519         let should_remove_import = duplicate && !has_dummy_span &&
2520             ((new_binding.is_extern_crate() || old_binding.is_extern_crate()) || from_item);
2521
2522         match directive {
2523             Some((directive, span, true)) if should_remove_import && directive.is_nested() =>
2524                 self.add_suggestion_for_duplicate_nested_use(&mut err, directive, span),
2525             Some((directive, _, true)) if should_remove_import && !directive.is_glob() => {
2526                 // Simple case - remove the entire import. Due to the above match arm, this can
2527                 // only be a single use so just remove it entirely.
2528                 err.tool_only_span_suggestion(
2529                     directive.use_span_with_attributes,
2530                     "remove unnecessary import",
2531                     String::new(),
2532                     Applicability::MaybeIncorrect,
2533                 );
2534             },
2535             Some((directive, span, _)) =>
2536                 self.add_suggestion_for_rename_of_use(&mut err, name, directive, span),
2537             _ => {},
2538         }
2539
2540         err.emit();
2541         self.name_already_seen.insert(name, span);
2542     }
2543
2544     /// This function adds a suggestion to change the binding name of a new import that conflicts
2545     /// with an existing import.
2546     ///
2547     /// ```ignore (diagnostic)
2548     /// help: you can use `as` to change the binding name of the import
2549     ///    |
2550     /// LL | use foo::bar as other_bar;
2551     ///    |     ^^^^^^^^^^^^^^^^^^^^^
2552     /// ```
2553     fn add_suggestion_for_rename_of_use(
2554         &self,
2555         err: &mut DiagnosticBuilder<'_>,
2556         name: Name,
2557         directive: &ImportDirective<'_>,
2558         binding_span: Span,
2559     ) {
2560         let suggested_name = if name.as_str().chars().next().unwrap().is_uppercase() {
2561             format!("Other{}", name)
2562         } else {
2563             format!("other_{}", name)
2564         };
2565
2566         let mut suggestion = None;
2567         match directive.subclass {
2568             ImportDirectiveSubclass::SingleImport { type_ns_only: true, .. } =>
2569                 suggestion = Some(format!("self as {}", suggested_name)),
2570             ImportDirectiveSubclass::SingleImport { source, .. } => {
2571                 if let Some(pos) = source.span.hi().0.checked_sub(binding_span.lo().0)
2572                                                      .map(|pos| pos as usize) {
2573                     if let Ok(snippet) = self.session.source_map()
2574                                                      .span_to_snippet(binding_span) {
2575                         if pos <= snippet.len() {
2576                             suggestion = Some(format!(
2577                                 "{} as {}{}",
2578                                 &snippet[..pos],
2579                                 suggested_name,
2580                                 if snippet.ends_with(";") { ";" } else { "" }
2581                             ))
2582                         }
2583                     }
2584                 }
2585             }
2586             ImportDirectiveSubclass::ExternCrate { source, target, .. } =>
2587                 suggestion = Some(format!(
2588                     "extern crate {} as {};",
2589                     source.unwrap_or(target.name),
2590                     suggested_name,
2591                 )),
2592             _ => unreachable!(),
2593         }
2594
2595         let rename_msg = "you can use `as` to change the binding name of the import";
2596         if let Some(suggestion) = suggestion {
2597             err.span_suggestion(
2598                 binding_span,
2599                 rename_msg,
2600                 suggestion,
2601                 Applicability::MaybeIncorrect,
2602             );
2603         } else {
2604             err.span_label(binding_span, rename_msg);
2605         }
2606     }
2607
2608     /// This function adds a suggestion to remove a unnecessary binding from an import that is
2609     /// nested. In the following example, this function will be invoked to remove the `a` binding
2610     /// in the second use statement:
2611     ///
2612     /// ```ignore (diagnostic)
2613     /// use issue_52891::a;
2614     /// use issue_52891::{d, a, e};
2615     /// ```
2616     ///
2617     /// The following suggestion will be added:
2618     ///
2619     /// ```ignore (diagnostic)
2620     /// use issue_52891::{d, a, e};
2621     ///                      ^-- help: remove unnecessary import
2622     /// ```
2623     ///
2624     /// If the nested use contains only one import then the suggestion will remove the entire
2625     /// line.
2626     ///
2627     /// It is expected that the directive provided is a nested import - this isn't checked by the
2628     /// function. If this invariant is not upheld, this function's behaviour will be unexpected
2629     /// as characters expected by span manipulations won't be present.
2630     fn add_suggestion_for_duplicate_nested_use(
2631         &self,
2632         err: &mut DiagnosticBuilder<'_>,
2633         directive: &ImportDirective<'_>,
2634         binding_span: Span,
2635     ) {
2636         assert!(directive.is_nested());
2637         let message = "remove unnecessary import";
2638
2639         // Two examples will be used to illustrate the span manipulations we're doing:
2640         //
2641         // - Given `use issue_52891::{d, a, e};` where `a` is a duplicate then `binding_span` is
2642         //   `a` and `directive.use_span` is `issue_52891::{d, a, e};`.
2643         // - Given `use issue_52891::{d, e, a};` where `a` is a duplicate then `binding_span` is
2644         //   `a` and `directive.use_span` is `issue_52891::{d, e, a};`.
2645
2646         let (found_closing_brace, span) = find_span_of_binding_until_next_binding(
2647             self.session, binding_span, directive.use_span,
2648         );
2649
2650         // If there was a closing brace then identify the span to remove any trailing commas from
2651         // previous imports.
2652         if found_closing_brace {
2653             if let Some(span) = extend_span_to_previous_binding(self.session, span) {
2654                 err.tool_only_span_suggestion(span, message, String::new(),
2655                                               Applicability::MaybeIncorrect);
2656             } else {
2657                 // Remove the entire line if we cannot extend the span back, this indicates a
2658                 // `issue_52891::{self}` case.
2659                 err.span_suggestion(directive.use_span_with_attributes, message, String::new(),
2660                                     Applicability::MaybeIncorrect);
2661             }
2662
2663             return;
2664         }
2665
2666         err.span_suggestion(span, message, String::new(), Applicability::MachineApplicable);
2667     }
2668
2669     fn extern_prelude_get(&mut self, ident: Ident, speculative: bool)
2670                           -> Option<&'a NameBinding<'a>> {
2671         if ident.is_path_segment_keyword() {
2672             // Make sure `self`, `super` etc produce an error when passed to here.
2673             return None;
2674         }
2675         self.extern_prelude.get(&ident.modern()).cloned().and_then(|entry| {
2676             if let Some(binding) = entry.extern_crate_item {
2677                 if !speculative && entry.introduced_by_item {
2678                     self.record_use(ident, TypeNS, binding, false);
2679                 }
2680                 Some(binding)
2681             } else {
2682                 let crate_id = if !speculative {
2683                     self.crate_loader.process_path_extern(ident.name, ident.span)
2684                 } else if let Some(crate_id) =
2685                         self.crate_loader.maybe_process_path_extern(ident.name, ident.span) {
2686                     crate_id
2687                 } else {
2688                     return None;
2689                 };
2690                 let crate_root = self.get_module(DefId { krate: crate_id, index: CRATE_DEF_INDEX });
2691                 Some((crate_root, ty::Visibility::Public, DUMMY_SP, ExpnId::root())
2692                     .to_name_binding(self.arenas))
2693             }
2694         })
2695     }
2696
2697     /// Rustdoc uses this to resolve things in a recoverable way. `ResolutionError<'a>`
2698     /// isn't something that can be returned because it can't be made to live that long,
2699     /// and also it's a private type. Fortunately rustdoc doesn't need to know the error,
2700     /// just that an error occurred.
2701     // FIXME(Manishearth): intra-doc links won't get warned of epoch changes.
2702     pub fn resolve_str_path_error(
2703         &mut self, span: Span, path_str: &str, ns: Namespace, module_id: NodeId
2704     ) -> Result<(ast::Path, Res), ()> {
2705         let path = if path_str.starts_with("::") {
2706             ast::Path {
2707                 span,
2708                 segments: iter::once(Ident::with_dummy_span(kw::PathRoot))
2709                     .chain({
2710                         path_str.split("::").skip(1).map(Ident::from_str)
2711                     })
2712                     .map(|i| self.new_ast_path_segment(i))
2713                     .collect(),
2714             }
2715         } else {
2716             ast::Path {
2717                 span,
2718                 segments: path_str
2719                     .split("::")
2720                     .map(Ident::from_str)
2721                     .map(|i| self.new_ast_path_segment(i))
2722                     .collect(),
2723             }
2724         };
2725         let module = self.block_map.get(&module_id).copied().unwrap_or_else(|| {
2726             let def_id = self.definitions.local_def_id(module_id);
2727             self.module_map.get(&def_id).copied().unwrap_or(self.graph_root)
2728         });
2729         let parent_scope = &ParentScope::module(module);
2730         let res = self.resolve_ast_path(&path, ns, parent_scope).map_err(|_| ())?;
2731         Ok((path, res))
2732     }
2733
2734     // Resolve a path passed from rustdoc or HIR lowering.
2735     fn resolve_ast_path(
2736         &mut self,
2737         path: &ast::Path,
2738         ns: Namespace,
2739         parent_scope: &ParentScope<'a>,
2740     ) -> Result<Res, (Span, ResolutionError<'a>)> {
2741         match self.resolve_path(
2742             &Segment::from_path(path), Some(ns), parent_scope, true, path.span, CrateLint::No
2743         ) {
2744             PathResult::Module(ModuleOrUniformRoot::Module(module)) =>
2745                 Ok(module.res().unwrap()),
2746             PathResult::NonModule(path_res) if path_res.unresolved_segments() == 0 =>
2747                 Ok(path_res.base_res()),
2748             PathResult::NonModule(..) => {
2749                 Err((path.span, ResolutionError::FailedToResolve {
2750                     label: String::from("type-relative paths are not supported in this context"),
2751                     suggestion: None,
2752                 }))
2753             }
2754             PathResult::Module(..) | PathResult::Indeterminate => unreachable!(),
2755             PathResult::Failed { span, label, suggestion, .. } => {
2756                 Err((span, ResolutionError::FailedToResolve {
2757                     label,
2758                     suggestion,
2759                 }))
2760             }
2761         }
2762     }
2763
2764     fn new_ast_path_segment(&self, ident: Ident) -> ast::PathSegment {
2765         let mut seg = ast::PathSegment::from_ident(ident);
2766         seg.id = self.session.next_node_id();
2767         seg
2768     }
2769 }
2770
2771 fn names_to_string(names: &[Name]) -> String {
2772     let mut result = String::new();
2773     for (i, name) in names.iter()
2774                             .filter(|name| **name != kw::PathRoot)
2775                             .enumerate() {
2776         if i > 0 {
2777             result.push_str("::");
2778         }
2779         result.push_str(&name.as_str());
2780     }
2781     result
2782 }
2783
2784 fn path_names_to_string(path: &Path) -> String {
2785     names_to_string(&path.segments.iter()
2786                         .map(|seg| seg.ident.name)
2787                         .collect::<Vec<_>>())
2788 }
2789
2790 /// A somewhat inefficient routine to obtain the name of a module.
2791 fn module_to_string(module: Module<'_>) -> Option<String> {
2792     let mut names = Vec::new();
2793
2794     fn collect_mod(names: &mut Vec<Name>, module: Module<'_>) {
2795         if let ModuleKind::Def(.., name) = module.kind {
2796             if let Some(parent) = module.parent {
2797                 names.push(name);
2798                 collect_mod(names, parent);
2799             }
2800         } else {
2801             names.push(Name::intern("<opaque>"));
2802             collect_mod(names, module.parent.unwrap());
2803         }
2804     }
2805     collect_mod(&mut names, module);
2806
2807     if names.is_empty() {
2808         return None;
2809     }
2810     names.reverse();
2811     Some(names_to_string(&names))
2812 }
2813
2814 #[derive(Copy, Clone, Debug)]
2815 enum CrateLint {
2816     /// Do not issue the lint.
2817     No,
2818
2819     /// This lint applies to some arbitrary path; e.g., `impl ::foo::Bar`.
2820     /// In this case, we can take the span of that path.
2821     SimplePath(NodeId),
2822
2823     /// This lint comes from a `use` statement. In this case, what we
2824     /// care about really is the *root* `use` statement; e.g., if we
2825     /// have nested things like `use a::{b, c}`, we care about the
2826     /// `use a` part.
2827     UsePath { root_id: NodeId, root_span: Span },
2828
2829     /// This is the "trait item" from a fully qualified path. For example,
2830     /// we might be resolving  `X::Y::Z` from a path like `<T as X::Y>::Z`.
2831     /// The `path_span` is the span of the to the trait itself (`X::Y`).
2832     QPathTrait { qpath_id: NodeId, qpath_span: Span },
2833 }
2834
2835 impl CrateLint {
2836     fn node_id(&self) -> Option<NodeId> {
2837         match *self {
2838             CrateLint::No => None,
2839             CrateLint::SimplePath(id) |
2840             CrateLint::UsePath { root_id: id, .. } |
2841             CrateLint::QPathTrait { qpath_id: id, .. } => Some(id),
2842         }
2843     }
2844 }