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