]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_resolve/src/lib.rs
Use newtype `enum`s instead of `bool`
[rust.git] / compiler / rustc_resolve / src / 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 `rustc_typeck`.
8
9 #![doc(html_root_url = "https://doc.rust-lang.org/nightly/nightly-rustc/")]
10 #![feature(box_patterns)]
11 #![feature(drain_filter)]
12 #![feature(bool_to_option)]
13 #![feature(crate_visibility_modifier)]
14 #![feature(if_let_guard)]
15 #![feature(let_chains)]
16 #![feature(let_else)]
17 #![feature(never_type)]
18 #![feature(nll)]
19 #![recursion_limit = "256"]
20 #![allow(rustdoc::private_intra_doc_links)]
21 #![allow(rustc::potential_query_instability)]
22
23 #[macro_use]
24 extern crate tracing;
25
26 pub use rustc_hir::def::{Namespace, PerNS};
27
28 use rustc_arena::{DroplessArena, TypedArena};
29 use rustc_ast::node_id::NodeMap;
30 use rustc_ast::{self as ast, NodeId, CRATE_NODE_ID};
31 use rustc_ast::{AngleBracketedArg, Crate, Expr, ExprKind, GenericArg, GenericArgs, LitKind, Path};
32 use rustc_ast_lowering::{LifetimeRes, ResolverAstLowering};
33 use rustc_data_structures::fx::{FxHashMap, FxHashSet, FxIndexMap};
34 use rustc_data_structures::intern::Interned;
35 use rustc_data_structures::sync::Lrc;
36 use rustc_errors::{Applicability, DiagnosticBuilder, ErrorGuaranteed};
37 use rustc_expand::base::{DeriveResolutions, SyntaxExtension, SyntaxExtensionKind};
38 use rustc_hir::def::Namespace::*;
39 use rustc_hir::def::{self, CtorOf, DefKind, PartialRes};
40 use rustc_hir::def_id::{CrateNum, DefId, DefIdMap, DefPathHash, LocalDefId};
41 use rustc_hir::def_id::{CRATE_DEF_ID, LOCAL_CRATE};
42 use rustc_hir::definitions::{DefKey, DefPathData, Definitions};
43 use rustc_hir::TraitCandidate;
44 use rustc_index::vec::IndexVec;
45 use rustc_metadata::creader::{CStore, CrateLoader};
46 use rustc_middle::metadata::ModChild;
47 use rustc_middle::middle::privacy::AccessLevels;
48 use rustc_middle::span_bug;
49 use rustc_middle::ty::query::Providers;
50 use rustc_middle::ty::{self, DefIdTree, MainDefinition, RegisteredTools, ResolverOutputs};
51 use rustc_query_system::ich::StableHashingContext;
52 use rustc_session::cstore::{CrateStore, MetadataLoaderDyn};
53 use rustc_session::lint::LintBuffer;
54 use rustc_session::Session;
55 use rustc_span::hygiene::{ExpnId, LocalExpnId, MacroKind, SyntaxContext, Transparency};
56 use rustc_span::source_map::Spanned;
57 use rustc_span::symbol::{kw, sym, Ident, Symbol};
58 use rustc_span::{Span, DUMMY_SP};
59
60 use smallvec::{smallvec, SmallVec};
61 use std::cell::{Cell, RefCell};
62 use std::collections::BTreeSet;
63 use std::{cmp, fmt, mem, ptr};
64 use tracing::debug;
65
66 use diagnostics::{ImportSuggestion, LabelSuggestion, Suggestion};
67 use imports::{Import, ImportKind, ImportResolver, NameResolution};
68 use late::{HasGenericParams, PathSource};
69 use macros::{MacroRulesBinding, MacroRulesScope, MacroRulesScopeRef};
70
71 use crate::access_levels::AccessLevelsVisitor;
72
73 type Res = def::Res<NodeId>;
74
75 mod access_levels;
76 mod build_reduced_graph;
77 mod check_unused;
78 mod def_collector;
79 mod diagnostics;
80 mod ident;
81 mod imports;
82 mod late;
83 mod macros;
84
85 enum Weak {
86     Yes,
87     No,
88 }
89
90 #[derive(Copy, Clone, PartialEq, Debug)]
91 pub enum Determinacy {
92     Determined,
93     Undetermined,
94 }
95
96 impl Determinacy {
97     fn determined(determined: bool) -> Determinacy {
98         if determined { Determinacy::Determined } else { Determinacy::Undetermined }
99     }
100 }
101
102 /// A specific scope in which a name can be looked up.
103 /// This enum is currently used only for early resolution (imports and macros),
104 /// but not for late resolution yet.
105 #[derive(Clone, Copy)]
106 enum Scope<'a> {
107     DeriveHelpers(LocalExpnId),
108     DeriveHelpersCompat,
109     MacroRules(MacroRulesScopeRef<'a>),
110     CrateRoot,
111     // The node ID is for reporting the `PROC_MACRO_DERIVE_RESOLUTION_FALLBACK`
112     // lint if it should be reported.
113     Module(Module<'a>, Option<NodeId>),
114     RegisteredAttrs,
115     MacroUsePrelude,
116     BuiltinAttrs,
117     ExternPrelude,
118     ToolPrelude,
119     StdLibPrelude,
120     BuiltinTypes,
121 }
122
123 /// Names from different contexts may want to visit different subsets of all specific scopes
124 /// with different restrictions when looking up the resolution.
125 /// This enum is currently used only for early resolution (imports and macros),
126 /// but not for late resolution yet.
127 #[derive(Clone, Copy)]
128 enum ScopeSet<'a> {
129     /// All scopes with the given namespace.
130     All(Namespace, /*is_import*/ bool),
131     /// Crate root, then extern prelude (used for mixed 2015-2018 mode in macros).
132     AbsolutePath(Namespace),
133     /// All scopes with macro namespace and the given macro kind restriction.
134     Macro(MacroKind),
135     /// All scopes with the given namespace, used for partially performing late resolution.
136     /// The node id enables lints and is used for reporting them.
137     Late(Namespace, Module<'a>, Option<NodeId>),
138 }
139
140 /// Everything you need to know about a name's location to resolve it.
141 /// Serves as a starting point for the scope visitor.
142 /// This struct is currently used only for early resolution (imports and macros),
143 /// but not for late resolution yet.
144 #[derive(Clone, Copy, Debug)]
145 pub struct ParentScope<'a> {
146     module: Module<'a>,
147     expansion: LocalExpnId,
148     macro_rules: MacroRulesScopeRef<'a>,
149     derives: &'a [ast::Path],
150 }
151
152 impl<'a> ParentScope<'a> {
153     /// Creates a parent scope with the passed argument used as the module scope component,
154     /// and other scope components set to default empty values.
155     pub fn module(module: Module<'a>, resolver: &Resolver<'a>) -> ParentScope<'a> {
156         ParentScope {
157             module,
158             expansion: LocalExpnId::ROOT,
159             macro_rules: resolver.arenas.alloc_macro_rules_scope(MacroRulesScope::Empty),
160             derives: &[],
161         }
162     }
163 }
164
165 #[derive(Copy, Debug, Clone)]
166 enum ImplTraitContext {
167     Existential,
168     Universal(LocalDefId),
169 }
170
171 #[derive(Eq)]
172 struct BindingError {
173     name: Symbol,
174     origin: BTreeSet<Span>,
175     target: BTreeSet<Span>,
176     could_be_path: bool,
177 }
178
179 impl PartialOrd for BindingError {
180     fn partial_cmp(&self, other: &BindingError) -> Option<cmp::Ordering> {
181         Some(self.cmp(other))
182     }
183 }
184
185 impl PartialEq for BindingError {
186     fn eq(&self, other: &BindingError) -> bool {
187         self.name == other.name
188     }
189 }
190
191 impl Ord for BindingError {
192     fn cmp(&self, other: &BindingError) -> cmp::Ordering {
193         self.name.cmp(&other.name)
194     }
195 }
196
197 enum ResolutionError<'a> {
198     /// Error E0401: can't use type or const parameters from outer function.
199     GenericParamsFromOuterFunction(Res, HasGenericParams),
200     /// Error E0403: the name is already used for a type or const parameter in this generic
201     /// parameter list.
202     NameAlreadyUsedInParameterList(Symbol, Span),
203     /// Error E0407: method is not a member of trait.
204     MethodNotMemberOfTrait(Ident, String, Option<Symbol>),
205     /// Error E0437: type is not a member of trait.
206     TypeNotMemberOfTrait(Ident, String, Option<Symbol>),
207     /// Error E0438: const is not a member of trait.
208     ConstNotMemberOfTrait(Ident, String, Option<Symbol>),
209     /// Error E0408: variable `{}` is not bound in all patterns.
210     VariableNotBoundInPattern(BindingError, ParentScope<'a>),
211     /// Error E0409: variable `{}` is bound in inconsistent ways within the same match arm.
212     VariableBoundWithDifferentMode(Symbol, Span),
213     /// Error E0415: identifier is bound more than once in this parameter list.
214     IdentifierBoundMoreThanOnceInParameterList(Symbol),
215     /// Error E0416: identifier is bound more than once in the same pattern.
216     IdentifierBoundMoreThanOnceInSamePattern(Symbol),
217     /// Error E0426: use of undeclared label.
218     UndeclaredLabel { name: Symbol, suggestion: Option<LabelSuggestion> },
219     /// Error E0429: `self` imports are only allowed within a `{ }` list.
220     SelfImportsOnlyAllowedWithin { root: bool, span_with_rename: Span },
221     /// Error E0430: `self` import can only appear once in the list.
222     SelfImportCanOnlyAppearOnceInTheList,
223     /// Error E0431: `self` import can only appear in an import list with a non-empty prefix.
224     SelfImportOnlyInImportListWithNonEmptyPrefix,
225     /// Error E0433: failed to resolve.
226     FailedToResolve { label: String, suggestion: Option<Suggestion> },
227     /// Error E0434: can't capture dynamic environment in a fn item.
228     CannotCaptureDynamicEnvironmentInFnItem,
229     /// Error E0435: attempt to use a non-constant value in a constant.
230     AttemptToUseNonConstantValueInConstant(
231         Ident,
232         /* suggestion */ &'static str,
233         /* current */ &'static str,
234     ),
235     /// Error E0530: `X` bindings cannot shadow `Y`s.
236     BindingShadowsSomethingUnacceptable {
237         shadowing_binding_descr: &'static str,
238         name: Symbol,
239         participle: &'static str,
240         article: &'static str,
241         shadowed_binding_descr: &'static str,
242         shadowed_binding_span: Span,
243     },
244     /// Error E0128: generic parameters with a default cannot use forward-declared identifiers.
245     ForwardDeclaredGenericParam,
246     /// ERROR E0770: the type of const parameters must not depend on other generic parameters.
247     ParamInTyOfConstParam(Symbol),
248     /// generic parameters must not be used inside const evaluations.
249     ///
250     /// This error is only emitted when using `min_const_generics`.
251     ParamInNonTrivialAnonConst { name: Symbol, is_type: bool },
252     /// Error E0735: generic parameters with a default cannot use `Self`
253     SelfInGenericParamDefault,
254     /// Error E0767: use of unreachable label
255     UnreachableLabel { name: Symbol, definition_span: Span, suggestion: Option<LabelSuggestion> },
256     /// Error E0323, E0324, E0325: mismatch between trait item and impl item.
257     TraitImplMismatch {
258         name: Symbol,
259         kind: &'static str,
260         trait_path: String,
261         trait_item_span: Span,
262         code: rustc_errors::DiagnosticId,
263     },
264     /// Inline asm `sym` operand must refer to a `fn` or `static`.
265     InvalidAsmSym,
266 }
267
268 enum VisResolutionError<'a> {
269     Relative2018(Span, &'a ast::Path),
270     AncestorOnly(Span),
271     FailedToResolve(Span, String, Option<Suggestion>),
272     ExpectedFound(Span, String, Res),
273     Indeterminate(Span),
274     ModuleOnly(Span),
275 }
276
277 /// A minimal representation of a path segment. We use this in resolve because we synthesize 'path
278 /// segments' which don't have the rest of an AST or HIR `PathSegment`.
279 #[derive(Clone, Copy, Debug)]
280 pub struct Segment {
281     ident: Ident,
282     id: Option<NodeId>,
283     /// Signals whether this `PathSegment` has generic arguments. Used to avoid providing
284     /// nonsensical suggestions.
285     has_generic_args: bool,
286     /// Signals whether this `PathSegment` has lifetime arguments.
287     has_lifetime_args: bool,
288     args_span: Span,
289 }
290
291 impl Segment {
292     fn from_path(path: &Path) -> Vec<Segment> {
293         path.segments.iter().map(|s| s.into()).collect()
294     }
295
296     fn from_ident(ident: Ident) -> Segment {
297         Segment {
298             ident,
299             id: None,
300             has_generic_args: false,
301             has_lifetime_args: false,
302             args_span: DUMMY_SP,
303         }
304     }
305
306     fn from_ident_and_id(ident: Ident, id: NodeId) -> Segment {
307         Segment {
308             ident,
309             id: Some(id),
310             has_generic_args: false,
311             has_lifetime_args: false,
312             args_span: DUMMY_SP,
313         }
314     }
315
316     fn names_to_string(segments: &[Segment]) -> String {
317         names_to_string(&segments.iter().map(|seg| seg.ident.name).collect::<Vec<_>>())
318     }
319 }
320
321 impl<'a> From<&'a ast::PathSegment> for Segment {
322     fn from(seg: &'a ast::PathSegment) -> Segment {
323         let has_generic_args = seg.args.is_some();
324         let (args_span, has_lifetime_args) = if let Some(args) = seg.args.as_deref() {
325             match args {
326                 GenericArgs::AngleBracketed(args) => {
327                     let found_lifetimes = args
328                         .args
329                         .iter()
330                         .any(|arg| matches!(arg, AngleBracketedArg::Arg(GenericArg::Lifetime(_))));
331                     (args.span, found_lifetimes)
332                 }
333                 GenericArgs::Parenthesized(args) => (args.span, true),
334             }
335         } else {
336             (DUMMY_SP, false)
337         };
338         Segment {
339             ident: seg.ident,
340             id: Some(seg.id),
341             has_generic_args,
342             has_lifetime_args,
343             args_span,
344         }
345     }
346 }
347
348 /// An intermediate resolution result.
349 ///
350 /// This refers to the thing referred by a name. The difference between `Res` and `Item` is that
351 /// items are visible in their whole block, while `Res`es only from the place they are defined
352 /// forward.
353 #[derive(Debug)]
354 enum LexicalScopeBinding<'a> {
355     Item(&'a NameBinding<'a>),
356     Res(Res),
357 }
358
359 impl<'a> LexicalScopeBinding<'a> {
360     fn res(self) -> Res {
361         match self {
362             LexicalScopeBinding::Item(binding) => binding.res(),
363             LexicalScopeBinding::Res(res) => res,
364         }
365     }
366 }
367
368 #[derive(Copy, Clone, Debug)]
369 enum ModuleOrUniformRoot<'a> {
370     /// Regular module.
371     Module(Module<'a>),
372
373     /// Virtual module that denotes resolution in crate root with fallback to extern prelude.
374     CrateRootAndExternPrelude,
375
376     /// Virtual module that denotes resolution in extern prelude.
377     /// Used for paths starting with `::` on 2018 edition.
378     ExternPrelude,
379
380     /// Virtual module that denotes resolution in current scope.
381     /// Used only for resolving single-segment imports. The reason it exists is that import paths
382     /// are always split into two parts, the first of which should be some kind of module.
383     CurrentScope,
384 }
385
386 impl ModuleOrUniformRoot<'_> {
387     fn same_def(lhs: Self, rhs: Self) -> bool {
388         match (lhs, rhs) {
389             (ModuleOrUniformRoot::Module(lhs), ModuleOrUniformRoot::Module(rhs)) => {
390                 ptr::eq(lhs, rhs)
391             }
392             (
393                 ModuleOrUniformRoot::CrateRootAndExternPrelude,
394                 ModuleOrUniformRoot::CrateRootAndExternPrelude,
395             )
396             | (ModuleOrUniformRoot::ExternPrelude, ModuleOrUniformRoot::ExternPrelude)
397             | (ModuleOrUniformRoot::CurrentScope, ModuleOrUniformRoot::CurrentScope) => true,
398             _ => false,
399         }
400     }
401 }
402
403 #[derive(Clone, Debug)]
404 enum PathResult<'a> {
405     Module(ModuleOrUniformRoot<'a>),
406     NonModule(PartialRes),
407     Indeterminate,
408     Failed {
409         span: Span,
410         label: String,
411         suggestion: Option<Suggestion>,
412         is_error_from_last_segment: bool,
413     },
414 }
415
416 impl<'a> PathResult<'a> {
417     fn failed(
418         span: Span,
419         is_error_from_last_segment: bool,
420         finalize: bool,
421         label_and_suggestion: impl FnOnce() -> (String, Option<Suggestion>),
422     ) -> PathResult<'a> {
423         let (label, suggestion) =
424             if finalize { label_and_suggestion() } else { (String::new(), None) };
425         PathResult::Failed { span, label, suggestion, is_error_from_last_segment }
426     }
427 }
428
429 #[derive(Debug)]
430 enum ModuleKind {
431     /// An anonymous module; e.g., just a block.
432     ///
433     /// ```
434     /// fn main() {
435     ///     fn f() {} // (1)
436     ///     { // This is an anonymous module
437     ///         f(); // This resolves to (2) as we are inside the block.
438     ///         fn f() {} // (2)
439     ///     }
440     ///     f(); // Resolves to (1)
441     /// }
442     /// ```
443     Block(NodeId),
444     /// Any module with a name.
445     ///
446     /// This could be:
447     ///
448     /// * A normal module â€“ either `mod from_file;` or `mod from_block { }` â€“
449     ///   or the crate root (which is conceptually a top-level module).
450     ///   Note that the crate root's [name][Self::name] will be [`kw::Empty`].
451     /// * A trait or an enum (it implicitly contains associated types, methods and variant
452     ///   constructors).
453     Def(DefKind, DefId, Symbol),
454 }
455
456 impl ModuleKind {
457     /// Get name of the module.
458     pub fn name(&self) -> Option<Symbol> {
459         match self {
460             ModuleKind::Block(..) => None,
461             ModuleKind::Def(.., name) => Some(*name),
462         }
463     }
464 }
465
466 /// A key that identifies a binding in a given `Module`.
467 ///
468 /// Multiple bindings in the same module can have the same key (in a valid
469 /// program) if all but one of them come from glob imports.
470 #[derive(Copy, Clone, PartialEq, Eq, Hash, Debug)]
471 struct BindingKey {
472     /// The identifier for the binding, always the `normalize_to_macros_2_0` version of the
473     /// identifier.
474     ident: Ident,
475     ns: Namespace,
476     /// 0 if ident is not `_`, otherwise a value that's unique to the specific
477     /// `_` in the expanded AST that introduced this binding.
478     disambiguator: u32,
479 }
480
481 type Resolutions<'a> = RefCell<FxIndexMap<BindingKey, &'a RefCell<NameResolution<'a>>>>;
482
483 /// One node in the tree of modules.
484 ///
485 /// Note that a "module" in resolve is broader than a `mod` that you declare in Rust code. It may be one of these:
486 ///
487 /// * `mod`
488 /// * crate root (aka, top-level anonymous module)
489 /// * `enum`
490 /// * `trait`
491 /// * curly-braced block with statements
492 ///
493 /// You can use [`ModuleData::kind`] to determine the kind of module this is.
494 pub struct ModuleData<'a> {
495     /// The direct parent module (it may not be a `mod`, however).
496     parent: Option<Module<'a>>,
497     /// What kind of module this is, because this may not be a `mod`.
498     kind: ModuleKind,
499
500     /// Mapping between names and their (possibly in-progress) resolutions in this module.
501     /// Resolutions in modules from other crates are not populated until accessed.
502     lazy_resolutions: Resolutions<'a>,
503     /// True if this is a module from other crate that needs to be populated on access.
504     populate_on_access: Cell<bool>,
505
506     /// Macro invocations that can expand into items in this module.
507     unexpanded_invocations: RefCell<FxHashSet<LocalExpnId>>,
508
509     /// Whether `#[no_implicit_prelude]` is active.
510     no_implicit_prelude: bool,
511
512     glob_importers: RefCell<Vec<&'a Import<'a>>>,
513     globs: RefCell<Vec<&'a Import<'a>>>,
514
515     /// Used to memoize the traits in this module for faster searches through all traits in scope.
516     traits: RefCell<Option<Box<[(Ident, &'a NameBinding<'a>)]>>>,
517
518     /// Span of the module itself. Used for error reporting.
519     span: Span,
520
521     expansion: ExpnId,
522 }
523
524 type Module<'a> = &'a ModuleData<'a>;
525
526 impl<'a> ModuleData<'a> {
527     fn new(
528         parent: Option<Module<'a>>,
529         kind: ModuleKind,
530         expansion: ExpnId,
531         span: Span,
532         no_implicit_prelude: bool,
533     ) -> Self {
534         let is_foreign = match kind {
535             ModuleKind::Def(_, def_id, _) => !def_id.is_local(),
536             ModuleKind::Block(_) => false,
537         };
538         ModuleData {
539             parent,
540             kind,
541             lazy_resolutions: Default::default(),
542             populate_on_access: Cell::new(is_foreign),
543             unexpanded_invocations: Default::default(),
544             no_implicit_prelude,
545             glob_importers: RefCell::new(Vec::new()),
546             globs: RefCell::new(Vec::new()),
547             traits: RefCell::new(None),
548             span,
549             expansion,
550         }
551     }
552
553     fn for_each_child<R, F>(&'a self, resolver: &mut R, mut f: F)
554     where
555         R: AsMut<Resolver<'a>>,
556         F: FnMut(&mut R, Ident, Namespace, &'a NameBinding<'a>),
557     {
558         for (key, name_resolution) in resolver.as_mut().resolutions(self).borrow().iter() {
559             if let Some(binding) = name_resolution.borrow().binding {
560                 f(resolver, key.ident, key.ns, binding);
561             }
562         }
563     }
564
565     /// This modifies `self` in place. The traits will be stored in `self.traits`.
566     fn ensure_traits<R>(&'a self, resolver: &mut R)
567     where
568         R: AsMut<Resolver<'a>>,
569     {
570         let mut traits = self.traits.borrow_mut();
571         if traits.is_none() {
572             let mut collected_traits = Vec::new();
573             self.for_each_child(resolver, |_, name, ns, binding| {
574                 if ns != TypeNS {
575                     return;
576                 }
577                 if let Res::Def(DefKind::Trait | DefKind::TraitAlias, _) = binding.res() {
578                     collected_traits.push((name, binding))
579                 }
580             });
581             *traits = Some(collected_traits.into_boxed_slice());
582         }
583     }
584
585     fn res(&self) -> Option<Res> {
586         match self.kind {
587             ModuleKind::Def(kind, def_id, _) => Some(Res::Def(kind, def_id)),
588             _ => None,
589         }
590     }
591
592     // Public for rustdoc.
593     pub fn def_id(&self) -> DefId {
594         self.opt_def_id().expect("`ModuleData::def_id` is called on a block module")
595     }
596
597     fn opt_def_id(&self) -> Option<DefId> {
598         match self.kind {
599             ModuleKind::Def(_, def_id, _) => Some(def_id),
600             _ => None,
601         }
602     }
603
604     // `self` resolves to the first module ancestor that `is_normal`.
605     fn is_normal(&self) -> bool {
606         matches!(self.kind, ModuleKind::Def(DefKind::Mod, _, _))
607     }
608
609     fn is_trait(&self) -> bool {
610         matches!(self.kind, ModuleKind::Def(DefKind::Trait, _, _))
611     }
612
613     fn nearest_item_scope(&'a self) -> Module<'a> {
614         match self.kind {
615             ModuleKind::Def(DefKind::Enum | DefKind::Trait, ..) => {
616                 self.parent.expect("enum or trait module without a parent")
617             }
618             _ => self,
619         }
620     }
621
622     /// The [`DefId`] of the nearest `mod` item ancestor (which may be this module).
623     /// This may be the crate root.
624     fn nearest_parent_mod(&self) -> DefId {
625         match self.kind {
626             ModuleKind::Def(DefKind::Mod, def_id, _) => def_id,
627             _ => self.parent.expect("non-root module without parent").nearest_parent_mod(),
628         }
629     }
630
631     fn is_ancestor_of(&self, mut other: &Self) -> bool {
632         while !ptr::eq(self, other) {
633             if let Some(parent) = other.parent {
634                 other = parent;
635             } else {
636                 return false;
637             }
638         }
639         true
640     }
641 }
642
643 impl<'a> fmt::Debug for ModuleData<'a> {
644     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
645         write!(f, "{:?}", self.res())
646     }
647 }
648
649 /// Records a possibly-private value, type, or module definition.
650 #[derive(Clone, Debug)]
651 pub struct NameBinding<'a> {
652     kind: NameBindingKind<'a>,
653     ambiguity: Option<(&'a NameBinding<'a>, AmbiguityKind)>,
654     expansion: LocalExpnId,
655     span: Span,
656     vis: ty::Visibility,
657 }
658
659 pub trait ToNameBinding<'a> {
660     fn to_name_binding(self, arenas: &'a ResolverArenas<'a>) -> &'a NameBinding<'a>;
661 }
662
663 impl<'a> ToNameBinding<'a> for &'a NameBinding<'a> {
664     fn to_name_binding(self, _: &'a ResolverArenas<'a>) -> &'a NameBinding<'a> {
665         self
666     }
667 }
668
669 #[derive(Clone, Debug)]
670 enum NameBindingKind<'a> {
671     Res(Res, /* is_macro_export */ bool),
672     Module(Module<'a>),
673     Import { binding: &'a NameBinding<'a>, import: &'a Import<'a>, used: Cell<bool> },
674 }
675
676 impl<'a> NameBindingKind<'a> {
677     /// Is this a name binding of an import?
678     fn is_import(&self) -> bool {
679         matches!(*self, NameBindingKind::Import { .. })
680     }
681 }
682
683 struct PrivacyError<'a> {
684     ident: Ident,
685     binding: &'a NameBinding<'a>,
686     dedup_span: Span,
687 }
688
689 struct UseError<'a> {
690     err: DiagnosticBuilder<'a, ErrorGuaranteed>,
691     /// Candidates which user could `use` to access the missing type.
692     candidates: Vec<ImportSuggestion>,
693     /// The `DefId` of the module to place the use-statements in.
694     def_id: DefId,
695     /// Whether the diagnostic should say "instead" (as in `consider importing ... instead`).
696     instead: bool,
697     /// Extra free-form suggestion.
698     suggestion: Option<(Span, &'static str, String, Applicability)>,
699 }
700
701 #[derive(Clone, Copy, PartialEq, Debug)]
702 enum AmbiguityKind {
703     Import,
704     BuiltinAttr,
705     DeriveHelper,
706     MacroRulesVsModularized,
707     GlobVsOuter,
708     GlobVsGlob,
709     GlobVsExpanded,
710     MoreExpandedVsOuter,
711 }
712
713 impl AmbiguityKind {
714     fn descr(self) -> &'static str {
715         match self {
716             AmbiguityKind::Import => "multiple potential import sources",
717             AmbiguityKind::BuiltinAttr => "a name conflict with a builtin attribute",
718             AmbiguityKind::DeriveHelper => "a name conflict with a derive helper attribute",
719             AmbiguityKind::MacroRulesVsModularized => {
720                 "a conflict between a `macro_rules` name and a non-`macro_rules` name from another module"
721             }
722             AmbiguityKind::GlobVsOuter => {
723                 "a conflict between a name from a glob import and an outer scope during import or macro resolution"
724             }
725             AmbiguityKind::GlobVsGlob => "multiple glob imports of a name in the same module",
726             AmbiguityKind::GlobVsExpanded => {
727                 "a conflict between a name from a glob import and a macro-expanded name in the same module during import or macro resolution"
728             }
729             AmbiguityKind::MoreExpandedVsOuter => {
730                 "a conflict between a macro-expanded name and a less macro-expanded name from outer scope during import or macro resolution"
731             }
732         }
733     }
734 }
735
736 /// Miscellaneous bits of metadata for better ambiguity error reporting.
737 #[derive(Clone, Copy, PartialEq)]
738 enum AmbiguityErrorMisc {
739     SuggestCrate,
740     SuggestSelf,
741     FromPrelude,
742     None,
743 }
744
745 struct AmbiguityError<'a> {
746     kind: AmbiguityKind,
747     ident: Ident,
748     b1: &'a NameBinding<'a>,
749     b2: &'a NameBinding<'a>,
750     misc1: AmbiguityErrorMisc,
751     misc2: AmbiguityErrorMisc,
752 }
753
754 impl<'a> NameBinding<'a> {
755     fn module(&self) -> Option<Module<'a>> {
756         match self.kind {
757             NameBindingKind::Module(module) => Some(module),
758             NameBindingKind::Import { binding, .. } => binding.module(),
759             _ => None,
760         }
761     }
762
763     fn res(&self) -> Res {
764         match self.kind {
765             NameBindingKind::Res(res, _) => res,
766             NameBindingKind::Module(module) => module.res().unwrap(),
767             NameBindingKind::Import { binding, .. } => binding.res(),
768         }
769     }
770
771     fn is_ambiguity(&self) -> bool {
772         self.ambiguity.is_some()
773             || match self.kind {
774                 NameBindingKind::Import { binding, .. } => binding.is_ambiguity(),
775                 _ => false,
776             }
777     }
778
779     fn is_possibly_imported_variant(&self) -> bool {
780         match self.kind {
781             NameBindingKind::Import { binding, .. } => binding.is_possibly_imported_variant(),
782             NameBindingKind::Res(
783                 Res::Def(DefKind::Variant | DefKind::Ctor(CtorOf::Variant, ..), _),
784                 _,
785             ) => true,
786             NameBindingKind::Res(..) | NameBindingKind::Module(..) => false,
787         }
788     }
789
790     fn is_extern_crate(&self) -> bool {
791         match self.kind {
792             NameBindingKind::Import {
793                 import: &Import { kind: ImportKind::ExternCrate { .. }, .. },
794                 ..
795             } => true,
796             NameBindingKind::Module(&ModuleData {
797                 kind: ModuleKind::Def(DefKind::Mod, def_id, _),
798                 ..
799             }) => def_id.is_crate_root(),
800             _ => false,
801         }
802     }
803
804     fn is_import(&self) -> bool {
805         matches!(self.kind, NameBindingKind::Import { .. })
806     }
807
808     fn is_glob_import(&self) -> bool {
809         match self.kind {
810             NameBindingKind::Import { import, .. } => import.is_glob(),
811             _ => false,
812         }
813     }
814
815     fn is_importable(&self) -> bool {
816         !matches!(
817             self.res(),
818             Res::Def(DefKind::AssocConst | DefKind::AssocFn | DefKind::AssocTy, _)
819         )
820     }
821
822     fn macro_kind(&self) -> Option<MacroKind> {
823         self.res().macro_kind()
824     }
825
826     // Suppose that we resolved macro invocation with `invoc_parent_expansion` to binding `binding`
827     // at some expansion round `max(invoc, binding)` when they both emerged from macros.
828     // Then this function returns `true` if `self` may emerge from a macro *after* that
829     // in some later round and screw up our previously found resolution.
830     // See more detailed explanation in
831     // https://github.com/rust-lang/rust/pull/53778#issuecomment-419224049
832     fn may_appear_after(
833         &self,
834         invoc_parent_expansion: LocalExpnId,
835         binding: &NameBinding<'_>,
836     ) -> bool {
837         // self > max(invoc, binding) => !(self <= invoc || self <= binding)
838         // Expansions are partially ordered, so "may appear after" is an inversion of
839         // "certainly appears before or simultaneously" and includes unordered cases.
840         let self_parent_expansion = self.expansion;
841         let other_parent_expansion = binding.expansion;
842         let certainly_before_other_or_simultaneously =
843             other_parent_expansion.is_descendant_of(self_parent_expansion);
844         let certainly_before_invoc_or_simultaneously =
845             invoc_parent_expansion.is_descendant_of(self_parent_expansion);
846         !(certainly_before_other_or_simultaneously || certainly_before_invoc_or_simultaneously)
847     }
848 }
849
850 #[derive(Debug, Default, Clone)]
851 pub struct ExternPreludeEntry<'a> {
852     extern_crate_item: Option<&'a NameBinding<'a>>,
853     pub introduced_by_item: bool,
854 }
855
856 /// Used for better errors for E0773
857 enum BuiltinMacroState {
858     NotYetSeen(SyntaxExtensionKind),
859     AlreadySeen(Span),
860 }
861
862 struct DeriveData {
863     resolutions: DeriveResolutions,
864     helper_attrs: Vec<(usize, Ident)>,
865     has_derive_copy: bool,
866 }
867
868 /// The main resolver class.
869 ///
870 /// This is the visitor that walks the whole crate.
871 pub struct Resolver<'a> {
872     session: &'a Session,
873
874     definitions: Definitions,
875
876     graph_root: Module<'a>,
877
878     prelude: Option<Module<'a>>,
879     extern_prelude: FxHashMap<Ident, ExternPreludeEntry<'a>>,
880
881     /// N.B., this is used only for better diagnostics, not name resolution itself.
882     has_self: FxHashSet<DefId>,
883
884     /// Names of fields of an item `DefId` accessible with dot syntax.
885     /// Used for hints during error reporting.
886     field_names: FxHashMap<DefId, Vec<Spanned<Symbol>>>,
887
888     /// All imports known to succeed or fail.
889     determined_imports: Vec<&'a Import<'a>>,
890
891     /// All non-determined imports.
892     indeterminate_imports: Vec<&'a Import<'a>>,
893
894     // Spans for local variables found during pattern resolution.
895     // Used for suggestions during error reporting.
896     pat_span_map: NodeMap<Span>,
897
898     /// Resolutions for nodes that have a single resolution.
899     partial_res_map: NodeMap<PartialRes>,
900     /// Resolutions for import nodes, which have multiple resolutions in different namespaces.
901     import_res_map: NodeMap<PerNS<Option<Res>>>,
902     /// Resolutions for labels (node IDs of their corresponding blocks or loops).
903     label_res_map: NodeMap<NodeId>,
904     /// Resolutions for lifetimes.
905     lifetimes_res_map: NodeMap<LifetimeRes>,
906     /// Lifetime parameters that lowering will have to introduce.
907     extra_lifetime_params_map: NodeMap<Vec<(Ident, NodeId, LifetimeRes)>>,
908
909     /// `CrateNum` resolutions of `extern crate` items.
910     extern_crate_map: FxHashMap<LocalDefId, CrateNum>,
911     reexport_map: FxHashMap<LocalDefId, Vec<ModChild>>,
912     trait_map: NodeMap<Vec<TraitCandidate>>,
913
914     /// A map from nodes to anonymous modules.
915     /// Anonymous modules are pseudo-modules that are implicitly created around items
916     /// contained within blocks.
917     ///
918     /// For example, if we have this:
919     ///
920     ///  fn f() {
921     ///      fn g() {
922     ///          ...
923     ///      }
924     ///  }
925     ///
926     /// There will be an anonymous module created around `g` with the ID of the
927     /// entry block for `f`.
928     block_map: NodeMap<Module<'a>>,
929     /// A fake module that contains no definition and no prelude. Used so that
930     /// some AST passes can generate identifiers that only resolve to local or
931     /// language items.
932     empty_module: Module<'a>,
933     module_map: FxHashMap<DefId, Module<'a>>,
934     binding_parent_modules: FxHashMap<Interned<'a, NameBinding<'a>>, Module<'a>>,
935     underscore_disambiguator: u32,
936
937     /// Maps glob imports to the names of items actually imported.
938     glob_map: FxHashMap<LocalDefId, FxHashSet<Symbol>>,
939     /// Visibilities in "lowered" form, for all entities that have them.
940     visibilities: FxHashMap<LocalDefId, ty::Visibility>,
941     has_pub_restricted: bool,
942     used_imports: FxHashSet<NodeId>,
943     maybe_unused_trait_imports: FxHashSet<LocalDefId>,
944     maybe_unused_extern_crates: Vec<(LocalDefId, Span)>,
945
946     /// Privacy errors are delayed until the end in order to deduplicate them.
947     privacy_errors: Vec<PrivacyError<'a>>,
948     /// Ambiguity errors are delayed for deduplication.
949     ambiguity_errors: Vec<AmbiguityError<'a>>,
950     /// `use` injections are delayed for better placement and deduplication.
951     use_injections: Vec<UseError<'a>>,
952     /// Crate-local macro expanded `macro_export` referred to by a module-relative path.
953     macro_expanded_macro_export_errors: BTreeSet<(Span, Span)>,
954
955     arenas: &'a ResolverArenas<'a>,
956     dummy_binding: &'a NameBinding<'a>,
957
958     crate_loader: CrateLoader<'a>,
959     macro_names: FxHashSet<Ident>,
960     builtin_macros: FxHashMap<Symbol, BuiltinMacroState>,
961     /// A small map keeping true kinds of built-in macros that appear to be fn-like on
962     /// the surface (`macro` items in libcore), but are actually attributes or derives.
963     builtin_macro_kinds: FxHashMap<LocalDefId, MacroKind>,
964     registered_attrs: FxHashSet<Ident>,
965     registered_tools: RegisteredTools,
966     macro_use_prelude: FxHashMap<Symbol, &'a NameBinding<'a>>,
967     /// FIXME: The only user of this is a doc link resolution hack for rustdoc.
968     all_macro_rules: FxHashMap<Symbol, Res>,
969     macro_map: FxHashMap<DefId, Lrc<SyntaxExtension>>,
970     dummy_ext_bang: Lrc<SyntaxExtension>,
971     dummy_ext_derive: Lrc<SyntaxExtension>,
972     non_macro_attr: Lrc<SyntaxExtension>,
973     local_macro_def_scopes: FxHashMap<LocalDefId, Module<'a>>,
974     ast_transform_scopes: FxHashMap<LocalExpnId, Module<'a>>,
975     unused_macros: FxHashMap<LocalDefId, (NodeId, Ident)>,
976     proc_macro_stubs: FxHashSet<LocalDefId>,
977     /// Traces collected during macro resolution and validated when it's complete.
978     single_segment_macro_resolutions:
979         Vec<(Ident, MacroKind, ParentScope<'a>, Option<&'a NameBinding<'a>>)>,
980     multi_segment_macro_resolutions:
981         Vec<(Vec<Segment>, Span, MacroKind, ParentScope<'a>, Option<Res>)>,
982     builtin_attrs: Vec<(Ident, ParentScope<'a>)>,
983     /// `derive(Copy)` marks items they are applied to so they are treated specially later.
984     /// Derive macros cannot modify the item themselves and have to store the markers in the global
985     /// context, so they attach the markers to derive container IDs using this resolver table.
986     containers_deriving_copy: FxHashSet<LocalExpnId>,
987     /// Parent scopes in which the macros were invoked.
988     /// FIXME: `derives` are missing in these parent scopes and need to be taken from elsewhere.
989     invocation_parent_scopes: FxHashMap<LocalExpnId, ParentScope<'a>>,
990     /// `macro_rules` scopes *produced* by expanding the macro invocations,
991     /// include all the `macro_rules` items and other invocations generated by them.
992     output_macro_rules_scopes: FxHashMap<LocalExpnId, MacroRulesScopeRef<'a>>,
993     /// Helper attributes that are in scope for the given expansion.
994     helper_attrs: FxHashMap<LocalExpnId, Vec<Ident>>,
995     /// Ready or in-progress results of resolving paths inside the `#[derive(...)]` attribute
996     /// with the given `ExpnId`.
997     derive_data: FxHashMap<LocalExpnId, DeriveData>,
998
999     /// Avoid duplicated errors for "name already defined".
1000     name_already_seen: FxHashMap<Symbol, Span>,
1001
1002     potentially_unused_imports: Vec<&'a Import<'a>>,
1003
1004     /// Table for mapping struct IDs into struct constructor IDs,
1005     /// it's not used during normal resolution, only for better error reporting.
1006     /// Also includes of list of each fields visibility
1007     struct_constructors: DefIdMap<(Res, ty::Visibility, Vec<ty::Visibility>)>,
1008
1009     /// Features enabled for this crate.
1010     active_features: FxHashSet<Symbol>,
1011
1012     lint_buffer: LintBuffer,
1013
1014     next_node_id: NodeId,
1015
1016     node_id_to_def_id: FxHashMap<ast::NodeId, LocalDefId>,
1017     def_id_to_node_id: IndexVec<LocalDefId, ast::NodeId>,
1018
1019     /// Indices of unnamed struct or variant fields with unresolved attributes.
1020     placeholder_field_indices: FxHashMap<NodeId, usize>,
1021     /// When collecting definitions from an AST fragment produced by a macro invocation `ExpnId`
1022     /// we know what parent node that fragment should be attached to thanks to this table,
1023     /// and how the `impl Trait` fragments were introduced.
1024     invocation_parents: FxHashMap<LocalExpnId, (LocalDefId, ImplTraitContext)>,
1025
1026     /// Some way to know that we are in a *trait* impl in `visit_assoc_item`.
1027     /// FIXME: Replace with a more general AST map (together with some other fields).
1028     trait_impl_items: FxHashSet<LocalDefId>,
1029
1030     legacy_const_generic_args: FxHashMap<DefId, Option<Vec<usize>>>,
1031     /// Amount of lifetime parameters for each item in the crate.
1032     item_generics_num_lifetimes: FxHashMap<LocalDefId, usize>,
1033
1034     main_def: Option<MainDefinition>,
1035     trait_impls: FxIndexMap<DefId, Vec<LocalDefId>>,
1036     /// A list of proc macro LocalDefIds, written out in the order in which
1037     /// they are declared in the static array generated by proc_macro_harness.
1038     proc_macros: Vec<NodeId>,
1039     confused_type_with_std_module: FxHashMap<Span, Span>,
1040
1041     access_levels: AccessLevels,
1042 }
1043
1044 /// Nothing really interesting here; it just provides memory for the rest of the crate.
1045 #[derive(Default)]
1046 pub struct ResolverArenas<'a> {
1047     modules: TypedArena<ModuleData<'a>>,
1048     local_modules: RefCell<Vec<Module<'a>>>,
1049     imports: TypedArena<Import<'a>>,
1050     name_resolutions: TypedArena<RefCell<NameResolution<'a>>>,
1051     ast_paths: TypedArena<ast::Path>,
1052     dropless: DroplessArena,
1053 }
1054
1055 impl<'a> ResolverArenas<'a> {
1056     fn new_module(
1057         &'a self,
1058         parent: Option<Module<'a>>,
1059         kind: ModuleKind,
1060         expn_id: ExpnId,
1061         span: Span,
1062         no_implicit_prelude: bool,
1063         module_map: &mut FxHashMap<DefId, Module<'a>>,
1064     ) -> Module<'a> {
1065         let module =
1066             self.modules.alloc(ModuleData::new(parent, kind, expn_id, span, no_implicit_prelude));
1067         let def_id = module.opt_def_id();
1068         if def_id.map_or(true, |def_id| def_id.is_local()) {
1069             self.local_modules.borrow_mut().push(module);
1070         }
1071         if let Some(def_id) = def_id {
1072             module_map.insert(def_id, module);
1073         }
1074         module
1075     }
1076     fn local_modules(&'a self) -> std::cell::Ref<'a, Vec<Module<'a>>> {
1077         self.local_modules.borrow()
1078     }
1079     fn alloc_name_binding(&'a self, name_binding: NameBinding<'a>) -> &'a NameBinding<'a> {
1080         self.dropless.alloc(name_binding)
1081     }
1082     fn alloc_import(&'a self, import: Import<'a>) -> &'a Import<'_> {
1083         self.imports.alloc(import)
1084     }
1085     fn alloc_name_resolution(&'a self) -> &'a RefCell<NameResolution<'a>> {
1086         self.name_resolutions.alloc(Default::default())
1087     }
1088     fn alloc_macro_rules_scope(&'a self, scope: MacroRulesScope<'a>) -> MacroRulesScopeRef<'a> {
1089         Interned::new_unchecked(self.dropless.alloc(Cell::new(scope)))
1090     }
1091     fn alloc_macro_rules_binding(
1092         &'a self,
1093         binding: MacroRulesBinding<'a>,
1094     ) -> &'a MacroRulesBinding<'a> {
1095         self.dropless.alloc(binding)
1096     }
1097     fn alloc_ast_paths(&'a self, paths: &[ast::Path]) -> &'a [ast::Path] {
1098         self.ast_paths.alloc_from_iter(paths.iter().cloned())
1099     }
1100     fn alloc_pattern_spans(&'a self, spans: impl Iterator<Item = Span>) -> &'a [Span] {
1101         self.dropless.alloc_from_iter(spans)
1102     }
1103 }
1104
1105 impl<'a> AsMut<Resolver<'a>> for Resolver<'a> {
1106     fn as_mut(&mut self) -> &mut Resolver<'a> {
1107         self
1108     }
1109 }
1110
1111 impl<'a, 'b> DefIdTree for &'a Resolver<'b> {
1112     fn parent(self, id: DefId) -> Option<DefId> {
1113         match id.as_local() {
1114             Some(id) => self.definitions.def_key(id).parent,
1115             None => self.cstore().def_key(id).parent,
1116         }
1117         .map(|index| DefId { index, ..id })
1118     }
1119 }
1120
1121 /// This interface is used through the AST→HIR step, to embed full paths into the HIR. After that
1122 /// the resolver is no longer needed as all the relevant information is inline.
1123 impl ResolverAstLowering for Resolver<'_> {
1124     fn def_key(&self, id: DefId) -> DefKey {
1125         if let Some(id) = id.as_local() {
1126             self.definitions.def_key(id)
1127         } else {
1128             self.cstore().def_key(id)
1129         }
1130     }
1131
1132     #[inline]
1133     fn def_span(&self, id: LocalDefId) -> Span {
1134         self.definitions.def_span(id)
1135     }
1136
1137     fn item_generics_num_lifetimes(&self, def_id: DefId) -> usize {
1138         if let Some(def_id) = def_id.as_local() {
1139             self.item_generics_num_lifetimes[&def_id]
1140         } else {
1141             self.cstore().item_generics_num_lifetimes(def_id, self.session)
1142         }
1143     }
1144
1145     fn legacy_const_generic_args(&mut self, expr: &Expr) -> Option<Vec<usize>> {
1146         self.legacy_const_generic_args(expr)
1147     }
1148
1149     fn get_partial_res(&self, id: NodeId) -> Option<PartialRes> {
1150         self.partial_res_map.get(&id).cloned()
1151     }
1152
1153     fn get_import_res(&self, id: NodeId) -> PerNS<Option<Res>> {
1154         self.import_res_map.get(&id).cloned().unwrap_or_default()
1155     }
1156
1157     fn get_label_res(&self, id: NodeId) -> Option<NodeId> {
1158         self.label_res_map.get(&id).cloned()
1159     }
1160
1161     fn get_lifetime_res(&self, id: NodeId) -> Option<LifetimeRes> {
1162         self.lifetimes_res_map.get(&id).copied()
1163     }
1164
1165     fn take_extra_lifetime_params(&mut self, id: NodeId) -> Vec<(Ident, NodeId, LifetimeRes)> {
1166         self.extra_lifetime_params_map.remove(&id).unwrap_or_default()
1167     }
1168
1169     fn create_stable_hashing_context(&self) -> StableHashingContext<'_> {
1170         StableHashingContext::new(self.session, &self.definitions, self.crate_loader.cstore())
1171     }
1172
1173     fn definitions(&self) -> &Definitions {
1174         &self.definitions
1175     }
1176
1177     fn next_node_id(&mut self) -> NodeId {
1178         self.next_node_id()
1179     }
1180
1181     fn take_trait_map(&mut self, node: NodeId) -> Option<Vec<TraitCandidate>> {
1182         self.trait_map.remove(&node)
1183     }
1184
1185     fn opt_local_def_id(&self, node: NodeId) -> Option<LocalDefId> {
1186         self.node_id_to_def_id.get(&node).copied()
1187     }
1188
1189     fn local_def_id(&self, node: NodeId) -> LocalDefId {
1190         self.opt_local_def_id(node).unwrap_or_else(|| panic!("no entry for node id: `{:?}`", node))
1191     }
1192
1193     fn def_path_hash(&self, def_id: DefId) -> DefPathHash {
1194         match def_id.as_local() {
1195             Some(def_id) => self.definitions.def_path_hash(def_id),
1196             None => self.cstore().def_path_hash(def_id),
1197         }
1198     }
1199
1200     /// Adds a definition with a parent definition.
1201     fn create_def(
1202         &mut self,
1203         parent: LocalDefId,
1204         node_id: ast::NodeId,
1205         data: DefPathData,
1206         expn_id: ExpnId,
1207         span: Span,
1208     ) -> LocalDefId {
1209         assert!(
1210             !self.node_id_to_def_id.contains_key(&node_id),
1211             "adding a def'n for node-id {:?} and data {:?} but a previous def'n exists: {:?}",
1212             node_id,
1213             data,
1214             self.definitions.def_key(self.node_id_to_def_id[&node_id]),
1215         );
1216
1217         let def_id = self.definitions.create_def(parent, data, expn_id, span);
1218
1219         // Some things for which we allocate `LocalDefId`s don't correspond to
1220         // anything in the AST, so they don't have a `NodeId`. For these cases
1221         // we don't need a mapping from `NodeId` to `LocalDefId`.
1222         if node_id != ast::DUMMY_NODE_ID {
1223             debug!("create_def: def_id_to_node_id[{:?}] <-> {:?}", def_id, node_id);
1224             self.node_id_to_def_id.insert(node_id, def_id);
1225         }
1226         assert_eq!(self.def_id_to_node_id.push(node_id), def_id);
1227
1228         def_id
1229     }
1230
1231     fn decl_macro_kind(&self, def_id: LocalDefId) -> MacroKind {
1232         self.builtin_macro_kinds.get(&def_id).copied().unwrap_or(MacroKind::Bang)
1233     }
1234 }
1235
1236 impl<'a> Resolver<'a> {
1237     pub fn new(
1238         session: &'a Session,
1239         krate: &Crate,
1240         crate_name: &str,
1241         metadata_loader: Box<MetadataLoaderDyn>,
1242         arenas: &'a ResolverArenas<'a>,
1243     ) -> Resolver<'a> {
1244         let root_def_id = CRATE_DEF_ID.to_def_id();
1245         let mut module_map = FxHashMap::default();
1246         let graph_root = arenas.new_module(
1247             None,
1248             ModuleKind::Def(DefKind::Mod, root_def_id, kw::Empty),
1249             ExpnId::root(),
1250             krate.spans.inner_span,
1251             session.contains_name(&krate.attrs, sym::no_implicit_prelude),
1252             &mut module_map,
1253         );
1254         let empty_module = arenas.new_module(
1255             None,
1256             ModuleKind::Def(DefKind::Mod, root_def_id, kw::Empty),
1257             ExpnId::root(),
1258             DUMMY_SP,
1259             true,
1260             &mut FxHashMap::default(),
1261         );
1262
1263         let definitions = Definitions::new(session.local_stable_crate_id(), krate.spans.inner_span);
1264
1265         let mut visibilities = FxHashMap::default();
1266         visibilities.insert(CRATE_DEF_ID, ty::Visibility::Public);
1267
1268         let mut def_id_to_node_id = IndexVec::default();
1269         assert_eq!(def_id_to_node_id.push(CRATE_NODE_ID), CRATE_DEF_ID);
1270         let mut node_id_to_def_id = FxHashMap::default();
1271         node_id_to_def_id.insert(CRATE_NODE_ID, CRATE_DEF_ID);
1272
1273         let mut invocation_parents = FxHashMap::default();
1274         invocation_parents.insert(LocalExpnId::ROOT, (CRATE_DEF_ID, ImplTraitContext::Existential));
1275
1276         let mut extern_prelude: FxHashMap<Ident, ExternPreludeEntry<'_>> = session
1277             .opts
1278             .externs
1279             .iter()
1280             .filter(|(_, entry)| entry.add_prelude)
1281             .map(|(name, _)| (Ident::from_str(name), Default::default()))
1282             .collect();
1283
1284         if !session.contains_name(&krate.attrs, sym::no_core) {
1285             extern_prelude.insert(Ident::with_dummy_span(sym::core), Default::default());
1286             if !session.contains_name(&krate.attrs, sym::no_std) {
1287                 extern_prelude.insert(Ident::with_dummy_span(sym::std), Default::default());
1288             }
1289         }
1290
1291         let (registered_attrs, registered_tools) =
1292             macros::registered_attrs_and_tools(session, &krate.attrs);
1293
1294         let features = session.features_untracked();
1295
1296         let mut resolver = Resolver {
1297             session,
1298
1299             definitions,
1300
1301             // The outermost module has def ID 0; this is not reflected in the
1302             // AST.
1303             graph_root,
1304             prelude: None,
1305             extern_prelude,
1306
1307             has_self: FxHashSet::default(),
1308             field_names: FxHashMap::default(),
1309
1310             determined_imports: Vec::new(),
1311             indeterminate_imports: Vec::new(),
1312
1313             pat_span_map: Default::default(),
1314             partial_res_map: Default::default(),
1315             import_res_map: Default::default(),
1316             label_res_map: Default::default(),
1317             lifetimes_res_map: Default::default(),
1318             extra_lifetime_params_map: Default::default(),
1319             extern_crate_map: Default::default(),
1320             reexport_map: FxHashMap::default(),
1321             trait_map: NodeMap::default(),
1322             underscore_disambiguator: 0,
1323             empty_module,
1324             module_map,
1325             block_map: Default::default(),
1326             binding_parent_modules: FxHashMap::default(),
1327             ast_transform_scopes: FxHashMap::default(),
1328
1329             glob_map: Default::default(),
1330             visibilities,
1331             has_pub_restricted: false,
1332             used_imports: FxHashSet::default(),
1333             maybe_unused_trait_imports: Default::default(),
1334             maybe_unused_extern_crates: Vec::new(),
1335
1336             privacy_errors: Vec::new(),
1337             ambiguity_errors: Vec::new(),
1338             use_injections: Vec::new(),
1339             macro_expanded_macro_export_errors: BTreeSet::new(),
1340
1341             arenas,
1342             dummy_binding: arenas.alloc_name_binding(NameBinding {
1343                 kind: NameBindingKind::Res(Res::Err, false),
1344                 ambiguity: None,
1345                 expansion: LocalExpnId::ROOT,
1346                 span: DUMMY_SP,
1347                 vis: ty::Visibility::Public,
1348             }),
1349
1350             crate_loader: CrateLoader::new(session, metadata_loader, crate_name),
1351             macro_names: FxHashSet::default(),
1352             builtin_macros: Default::default(),
1353             builtin_macro_kinds: Default::default(),
1354             registered_attrs,
1355             registered_tools,
1356             macro_use_prelude: FxHashMap::default(),
1357             all_macro_rules: Default::default(),
1358             macro_map: FxHashMap::default(),
1359             dummy_ext_bang: Lrc::new(SyntaxExtension::dummy_bang(session.edition())),
1360             dummy_ext_derive: Lrc::new(SyntaxExtension::dummy_derive(session.edition())),
1361             non_macro_attr: Lrc::new(SyntaxExtension::non_macro_attr(session.edition())),
1362             invocation_parent_scopes: Default::default(),
1363             output_macro_rules_scopes: Default::default(),
1364             helper_attrs: Default::default(),
1365             derive_data: Default::default(),
1366             local_macro_def_scopes: FxHashMap::default(),
1367             name_already_seen: FxHashMap::default(),
1368             potentially_unused_imports: Vec::new(),
1369             struct_constructors: Default::default(),
1370             unused_macros: Default::default(),
1371             proc_macro_stubs: Default::default(),
1372             single_segment_macro_resolutions: Default::default(),
1373             multi_segment_macro_resolutions: Default::default(),
1374             builtin_attrs: Default::default(),
1375             containers_deriving_copy: Default::default(),
1376             active_features: features
1377                 .declared_lib_features
1378                 .iter()
1379                 .map(|(feat, ..)| *feat)
1380                 .chain(features.declared_lang_features.iter().map(|(feat, ..)| *feat))
1381                 .collect(),
1382             lint_buffer: LintBuffer::default(),
1383             next_node_id: CRATE_NODE_ID,
1384             node_id_to_def_id,
1385             def_id_to_node_id,
1386             placeholder_field_indices: Default::default(),
1387             invocation_parents,
1388             trait_impl_items: Default::default(),
1389             legacy_const_generic_args: Default::default(),
1390             item_generics_num_lifetimes: Default::default(),
1391             main_def: Default::default(),
1392             trait_impls: Default::default(),
1393             proc_macros: Default::default(),
1394             confused_type_with_std_module: Default::default(),
1395             access_levels: Default::default(),
1396         };
1397
1398         let root_parent_scope = ParentScope::module(graph_root, &resolver);
1399         resolver.invocation_parent_scopes.insert(LocalExpnId::ROOT, root_parent_scope);
1400
1401         resolver
1402     }
1403
1404     fn new_module(
1405         &mut self,
1406         parent: Option<Module<'a>>,
1407         kind: ModuleKind,
1408         expn_id: ExpnId,
1409         span: Span,
1410         no_implicit_prelude: bool,
1411     ) -> Module<'a> {
1412         let module_map = &mut self.module_map;
1413         self.arenas.new_module(parent, kind, expn_id, span, no_implicit_prelude, module_map)
1414     }
1415
1416     pub fn next_node_id(&mut self) -> NodeId {
1417         let start = self.next_node_id;
1418         let next = start.as_u32().checked_add(1).expect("input too large; ran out of NodeIds");
1419         self.next_node_id = ast::NodeId::from_u32(next);
1420         start
1421     }
1422
1423     pub fn next_node_ids(&mut self, count: usize) -> std::ops::Range<NodeId> {
1424         let start = self.next_node_id;
1425         let end = start.as_usize().checked_add(count).expect("input too large; ran out of NodeIds");
1426         self.next_node_id = ast::NodeId::from_usize(end);
1427         start..self.next_node_id
1428     }
1429
1430     pub fn lint_buffer(&mut self) -> &mut LintBuffer {
1431         &mut self.lint_buffer
1432     }
1433
1434     pub fn arenas() -> ResolverArenas<'a> {
1435         Default::default()
1436     }
1437
1438     pub fn into_outputs(self) -> ResolverOutputs {
1439         let proc_macros = self.proc_macros.iter().map(|id| self.local_def_id(*id)).collect();
1440         let definitions = self.definitions;
1441         let visibilities = self.visibilities;
1442         let has_pub_restricted = self.has_pub_restricted;
1443         let extern_crate_map = self.extern_crate_map;
1444         let reexport_map = self.reexport_map;
1445         let maybe_unused_trait_imports = self.maybe_unused_trait_imports;
1446         let maybe_unused_extern_crates = self.maybe_unused_extern_crates;
1447         let glob_map = self.glob_map;
1448         let main_def = self.main_def;
1449         let confused_type_with_std_module = self.confused_type_with_std_module;
1450         let access_levels = self.access_levels;
1451         ResolverOutputs {
1452             definitions,
1453             cstore: Box::new(self.crate_loader.into_cstore()),
1454             visibilities,
1455             has_pub_restricted,
1456             access_levels,
1457             extern_crate_map,
1458             reexport_map,
1459             glob_map,
1460             maybe_unused_trait_imports,
1461             maybe_unused_extern_crates,
1462             extern_prelude: self
1463                 .extern_prelude
1464                 .iter()
1465                 .map(|(ident, entry)| (ident.name, entry.introduced_by_item))
1466                 .collect(),
1467             main_def,
1468             trait_impls: self.trait_impls,
1469             proc_macros,
1470             confused_type_with_std_module,
1471             registered_tools: self.registered_tools,
1472         }
1473     }
1474
1475     pub fn clone_outputs(&self) -> ResolverOutputs {
1476         let proc_macros = self.proc_macros.iter().map(|id| self.local_def_id(*id)).collect();
1477         ResolverOutputs {
1478             definitions: self.definitions.clone(),
1479             access_levels: self.access_levels.clone(),
1480             cstore: Box::new(self.cstore().clone()),
1481             visibilities: self.visibilities.clone(),
1482             has_pub_restricted: self.has_pub_restricted,
1483             extern_crate_map: self.extern_crate_map.clone(),
1484             reexport_map: self.reexport_map.clone(),
1485             glob_map: self.glob_map.clone(),
1486             maybe_unused_trait_imports: self.maybe_unused_trait_imports.clone(),
1487             maybe_unused_extern_crates: self.maybe_unused_extern_crates.clone(),
1488             extern_prelude: self
1489                 .extern_prelude
1490                 .iter()
1491                 .map(|(ident, entry)| (ident.name, entry.introduced_by_item))
1492                 .collect(),
1493             main_def: self.main_def,
1494             trait_impls: self.trait_impls.clone(),
1495             proc_macros,
1496             confused_type_with_std_module: self.confused_type_with_std_module.clone(),
1497             registered_tools: self.registered_tools.clone(),
1498         }
1499     }
1500
1501     pub fn cstore(&self) -> &CStore {
1502         self.crate_loader.cstore()
1503     }
1504
1505     fn dummy_ext(&self, macro_kind: MacroKind) -> Lrc<SyntaxExtension> {
1506         match macro_kind {
1507             MacroKind::Bang => self.dummy_ext_bang.clone(),
1508             MacroKind::Derive => self.dummy_ext_derive.clone(),
1509             MacroKind::Attr => self.non_macro_attr.clone(),
1510         }
1511     }
1512
1513     /// Runs the function on each namespace.
1514     fn per_ns<F: FnMut(&mut Self, Namespace)>(&mut self, mut f: F) {
1515         f(self, TypeNS);
1516         f(self, ValueNS);
1517         f(self, MacroNS);
1518     }
1519
1520     fn is_builtin_macro(&mut self, res: Res) -> bool {
1521         self.get_macro(res).map_or(false, |ext| ext.builtin_name.is_some())
1522     }
1523
1524     fn macro_def(&self, mut ctxt: SyntaxContext) -> DefId {
1525         loop {
1526             match ctxt.outer_expn_data().macro_def_id {
1527                 Some(def_id) => return def_id,
1528                 None => ctxt.remove_mark(),
1529             };
1530         }
1531     }
1532
1533     /// Entry point to crate resolution.
1534     pub fn resolve_crate(&mut self, krate: &Crate) {
1535         self.session.time("resolve_crate", || {
1536             self.session.time("finalize_imports", || ImportResolver { r: self }.finalize_imports());
1537             self.session.time("resolve_access_levels", || {
1538                 AccessLevelsVisitor::compute_access_levels(self, krate)
1539             });
1540             self.session.time("finalize_macro_resolutions", || self.finalize_macro_resolutions());
1541             self.session.time("late_resolve_crate", || self.late_resolve_crate(krate));
1542             self.session.time("resolve_main", || self.resolve_main());
1543             self.session.time("resolve_check_unused", || self.check_unused(krate));
1544             self.session.time("resolve_report_errors", || self.report_errors(krate));
1545             self.session.time("resolve_postprocess", || self.crate_loader.postprocess(krate));
1546         });
1547     }
1548
1549     pub fn traits_in_scope(
1550         &mut self,
1551         current_trait: Option<Module<'a>>,
1552         parent_scope: &ParentScope<'a>,
1553         ctxt: SyntaxContext,
1554         assoc_item: Option<(Symbol, Namespace)>,
1555     ) -> Vec<TraitCandidate> {
1556         let mut found_traits = Vec::new();
1557
1558         if let Some(module) = current_trait {
1559             if self.trait_may_have_item(Some(module), assoc_item) {
1560                 let def_id = module.def_id();
1561                 found_traits.push(TraitCandidate { def_id, import_ids: smallvec![] });
1562             }
1563         }
1564
1565         self.visit_scopes(ScopeSet::All(TypeNS, false), parent_scope, ctxt, |this, scope, _, _| {
1566             match scope {
1567                 Scope::Module(module, _) => {
1568                     this.traits_in_module(module, assoc_item, &mut found_traits);
1569                 }
1570                 Scope::StdLibPrelude => {
1571                     if let Some(module) = this.prelude {
1572                         this.traits_in_module(module, assoc_item, &mut found_traits);
1573                     }
1574                 }
1575                 Scope::ExternPrelude | Scope::ToolPrelude | Scope::BuiltinTypes => {}
1576                 _ => unreachable!(),
1577             }
1578             None::<()>
1579         });
1580
1581         found_traits
1582     }
1583
1584     fn traits_in_module(
1585         &mut self,
1586         module: Module<'a>,
1587         assoc_item: Option<(Symbol, Namespace)>,
1588         found_traits: &mut Vec<TraitCandidate>,
1589     ) {
1590         module.ensure_traits(self);
1591         let traits = module.traits.borrow();
1592         for (trait_name, trait_binding) in traits.as_ref().unwrap().iter() {
1593             if self.trait_may_have_item(trait_binding.module(), assoc_item) {
1594                 let def_id = trait_binding.res().def_id();
1595                 let import_ids = self.find_transitive_imports(&trait_binding.kind, *trait_name);
1596                 found_traits.push(TraitCandidate { def_id, import_ids });
1597             }
1598         }
1599     }
1600
1601     // List of traits in scope is pruned on best effort basis. We reject traits not having an
1602     // associated item with the given name and namespace (if specified). This is a conservative
1603     // optimization, proper hygienic type-based resolution of associated items is done in typeck.
1604     // We don't reject trait aliases (`trait_module == None`) because we don't have access to their
1605     // associated items.
1606     fn trait_may_have_item(
1607         &mut self,
1608         trait_module: Option<Module<'a>>,
1609         assoc_item: Option<(Symbol, Namespace)>,
1610     ) -> bool {
1611         match (trait_module, assoc_item) {
1612             (Some(trait_module), Some((name, ns))) => {
1613                 self.resolutions(trait_module).borrow().iter().any(|resolution| {
1614                     let (&BindingKey { ident: assoc_ident, ns: assoc_ns, .. }, _) = resolution;
1615                     assoc_ns == ns && assoc_ident.name == name
1616                 })
1617             }
1618             _ => true,
1619         }
1620     }
1621
1622     fn find_transitive_imports(
1623         &mut self,
1624         mut kind: &NameBindingKind<'_>,
1625         trait_name: Ident,
1626     ) -> SmallVec<[LocalDefId; 1]> {
1627         let mut import_ids = smallvec![];
1628         while let NameBindingKind::Import { import, binding, .. } = kind {
1629             let id = self.local_def_id(import.id);
1630             self.maybe_unused_trait_imports.insert(id);
1631             self.add_to_glob_map(&import, trait_name);
1632             import_ids.push(id);
1633             kind = &binding.kind;
1634         }
1635         import_ids
1636     }
1637
1638     fn new_key(&mut self, ident: Ident, ns: Namespace) -> BindingKey {
1639         let ident = ident.normalize_to_macros_2_0();
1640         let disambiguator = if ident.name == kw::Underscore {
1641             self.underscore_disambiguator += 1;
1642             self.underscore_disambiguator
1643         } else {
1644             0
1645         };
1646         BindingKey { ident, ns, disambiguator }
1647     }
1648
1649     fn resolutions(&mut self, module: Module<'a>) -> &'a Resolutions<'a> {
1650         if module.populate_on_access.get() {
1651             module.populate_on_access.set(false);
1652             self.build_reduced_graph_external(module);
1653         }
1654         &module.lazy_resolutions
1655     }
1656
1657     fn resolution(
1658         &mut self,
1659         module: Module<'a>,
1660         key: BindingKey,
1661     ) -> &'a RefCell<NameResolution<'a>> {
1662         *self
1663             .resolutions(module)
1664             .borrow_mut()
1665             .entry(key)
1666             .or_insert_with(|| self.arenas.alloc_name_resolution())
1667     }
1668
1669     fn record_use(
1670         &mut self,
1671         ident: Ident,
1672         used_binding: &'a NameBinding<'a>,
1673         is_lexical_scope: bool,
1674     ) {
1675         if let Some((b2, kind)) = used_binding.ambiguity {
1676             self.ambiguity_errors.push(AmbiguityError {
1677                 kind,
1678                 ident,
1679                 b1: used_binding,
1680                 b2,
1681                 misc1: AmbiguityErrorMisc::None,
1682                 misc2: AmbiguityErrorMisc::None,
1683             });
1684         }
1685         if let NameBindingKind::Import { import, binding, ref used } = used_binding.kind {
1686             // Avoid marking `extern crate` items that refer to a name from extern prelude,
1687             // but not introduce it, as used if they are accessed from lexical scope.
1688             if is_lexical_scope {
1689                 if let Some(entry) = self.extern_prelude.get(&ident.normalize_to_macros_2_0()) {
1690                     if let Some(crate_item) = entry.extern_crate_item {
1691                         if ptr::eq(used_binding, crate_item) && !entry.introduced_by_item {
1692                             return;
1693                         }
1694                     }
1695                 }
1696             }
1697             used.set(true);
1698             import.used.set(true);
1699             self.used_imports.insert(import.id);
1700             self.add_to_glob_map(&import, ident);
1701             self.record_use(ident, binding, false);
1702         }
1703     }
1704
1705     #[inline]
1706     fn add_to_glob_map(&mut self, import: &Import<'_>, ident: Ident) {
1707         if import.is_glob() {
1708             let def_id = self.local_def_id(import.id);
1709             self.glob_map.entry(def_id).or_default().insert(ident.name);
1710         }
1711     }
1712
1713     fn resolve_crate_root(&mut self, ident: Ident) -> Module<'a> {
1714         debug!("resolve_crate_root({:?})", ident);
1715         let mut ctxt = ident.span.ctxt();
1716         let mark = if ident.name == kw::DollarCrate {
1717             // When resolving `$crate` from a `macro_rules!` invoked in a `macro`,
1718             // we don't want to pretend that the `macro_rules!` definition is in the `macro`
1719             // as described in `SyntaxContext::apply_mark`, so we ignore prepended opaque marks.
1720             // FIXME: This is only a guess and it doesn't work correctly for `macro_rules!`
1721             // definitions actually produced by `macro` and `macro` definitions produced by
1722             // `macro_rules!`, but at least such configurations are not stable yet.
1723             ctxt = ctxt.normalize_to_macro_rules();
1724             debug!(
1725                 "resolve_crate_root: marks={:?}",
1726                 ctxt.marks().into_iter().map(|(i, t)| (i.expn_data(), t)).collect::<Vec<_>>()
1727             );
1728             let mut iter = ctxt.marks().into_iter().rev().peekable();
1729             let mut result = None;
1730             // Find the last opaque mark from the end if it exists.
1731             while let Some(&(mark, transparency)) = iter.peek() {
1732                 if transparency == Transparency::Opaque {
1733                     result = Some(mark);
1734                     iter.next();
1735                 } else {
1736                     break;
1737                 }
1738             }
1739             debug!(
1740                 "resolve_crate_root: found opaque mark {:?} {:?}",
1741                 result,
1742                 result.map(|r| r.expn_data())
1743             );
1744             // Then find the last semi-transparent mark from the end if it exists.
1745             for (mark, transparency) in iter {
1746                 if transparency == Transparency::SemiTransparent {
1747                     result = Some(mark);
1748                 } else {
1749                     break;
1750                 }
1751             }
1752             debug!(
1753                 "resolve_crate_root: found semi-transparent mark {:?} {:?}",
1754                 result,
1755                 result.map(|r| r.expn_data())
1756             );
1757             result
1758         } else {
1759             debug!("resolve_crate_root: not DollarCrate");
1760             ctxt = ctxt.normalize_to_macros_2_0();
1761             ctxt.adjust(ExpnId::root())
1762         };
1763         let module = match mark {
1764             Some(def) => self.expn_def_scope(def),
1765             None => {
1766                 debug!(
1767                     "resolve_crate_root({:?}): found no mark (ident.span = {:?})",
1768                     ident, ident.span
1769                 );
1770                 return self.graph_root;
1771             }
1772         };
1773         let module = self.expect_module(
1774             module.opt_def_id().map_or(LOCAL_CRATE, |def_id| def_id.krate).as_def_id(),
1775         );
1776         debug!(
1777             "resolve_crate_root({:?}): got module {:?} ({:?}) (ident.span = {:?})",
1778             ident,
1779             module,
1780             module.kind.name(),
1781             ident.span
1782         );
1783         module
1784     }
1785
1786     fn resolve_self(&mut self, ctxt: &mut SyntaxContext, module: Module<'a>) -> Module<'a> {
1787         let mut module = self.expect_module(module.nearest_parent_mod());
1788         while module.span.ctxt().normalize_to_macros_2_0() != *ctxt {
1789             let parent = module.parent.unwrap_or_else(|| self.expn_def_scope(ctxt.remove_mark()));
1790             module = self.expect_module(parent.nearest_parent_mod());
1791         }
1792         module
1793     }
1794
1795     fn record_partial_res(&mut self, node_id: NodeId, resolution: PartialRes) {
1796         debug!("(recording res) recording {:?} for {}", resolution, node_id);
1797         if let Some(prev_res) = self.partial_res_map.insert(node_id, resolution) {
1798             panic!("path resolved multiple times ({:?} before, {:?} now)", prev_res, resolution);
1799         }
1800     }
1801
1802     fn record_pat_span(&mut self, node: NodeId, span: Span) {
1803         debug!("(recording pat) recording {:?} for {:?}", node, span);
1804         self.pat_span_map.insert(node, span);
1805     }
1806
1807     fn is_accessible_from(&self, vis: ty::Visibility, module: Module<'a>) -> bool {
1808         vis.is_accessible_from(module.nearest_parent_mod(), self)
1809     }
1810
1811     fn set_binding_parent_module(&mut self, binding: &'a NameBinding<'a>, module: Module<'a>) {
1812         if let Some(old_module) =
1813             self.binding_parent_modules.insert(Interned::new_unchecked(binding), module)
1814         {
1815             if !ptr::eq(module, old_module) {
1816                 span_bug!(binding.span, "parent module is reset for binding");
1817             }
1818         }
1819     }
1820
1821     fn disambiguate_macro_rules_vs_modularized(
1822         &self,
1823         macro_rules: &'a NameBinding<'a>,
1824         modularized: &'a NameBinding<'a>,
1825     ) -> bool {
1826         // Some non-controversial subset of ambiguities "modularized macro name" vs "macro_rules"
1827         // is disambiguated to mitigate regressions from macro modularization.
1828         // Scoping for `macro_rules` behaves like scoping for `let` at module level, in general.
1829         match (
1830             self.binding_parent_modules.get(&Interned::new_unchecked(macro_rules)),
1831             self.binding_parent_modules.get(&Interned::new_unchecked(modularized)),
1832         ) {
1833             (Some(macro_rules), Some(modularized)) => {
1834                 macro_rules.nearest_parent_mod() == modularized.nearest_parent_mod()
1835                     && modularized.is_ancestor_of(macro_rules)
1836             }
1837             _ => false,
1838         }
1839     }
1840
1841     fn extern_prelude_get(&mut self, ident: Ident, finalize: bool) -> Option<&'a NameBinding<'a>> {
1842         if ident.is_path_segment_keyword() {
1843             // Make sure `self`, `super` etc produce an error when passed to here.
1844             return None;
1845         }
1846         self.extern_prelude.get(&ident.normalize_to_macros_2_0()).cloned().and_then(|entry| {
1847             if let Some(binding) = entry.extern_crate_item {
1848                 if finalize && entry.introduced_by_item {
1849                     self.record_use(ident, binding, false);
1850                 }
1851                 Some(binding)
1852             } else {
1853                 let crate_id = if finalize {
1854                     let Some(crate_id) =
1855                         self.crate_loader.process_path_extern(ident.name, ident.span) else { return Some(self.dummy_binding); };
1856                     crate_id
1857                 } else {
1858                     self.crate_loader.maybe_process_path_extern(ident.name)?
1859                 };
1860                 let crate_root = self.expect_module(crate_id.as_def_id());
1861                 Some(
1862                     (crate_root, ty::Visibility::Public, DUMMY_SP, LocalExpnId::ROOT)
1863                         .to_name_binding(self.arenas),
1864                 )
1865             }
1866         })
1867     }
1868
1869     /// Rustdoc uses this to resolve doc link paths in a recoverable way. `PathResult<'a>`
1870     /// isn't something that can be returned because it can't be made to live that long,
1871     /// and also it's a private type. Fortunately rustdoc doesn't need to know the error,
1872     /// just that an error occurred.
1873     pub fn resolve_rustdoc_path(
1874         &mut self,
1875         path_str: &str,
1876         ns: Namespace,
1877         mut module_id: DefId,
1878     ) -> Option<Res> {
1879         let mut segments =
1880             Vec::from_iter(path_str.split("::").map(Ident::from_str).map(Segment::from_ident));
1881         if let Some(segment) = segments.first_mut() {
1882             if segment.ident.name == kw::Crate {
1883                 // FIXME: `resolve_path` always resolves `crate` to the current crate root, but
1884                 // rustdoc wants it to resolve to the `module_id`'s crate root. This trick of
1885                 // replacing `crate` with `self` and changing the current module should achieve
1886                 // the same effect.
1887                 segment.ident.name = kw::SelfLower;
1888                 module_id = module_id.krate.as_def_id();
1889             } else if segment.ident.name == kw::Empty {
1890                 segment.ident.name = kw::PathRoot;
1891             }
1892         }
1893
1894         let module = self.expect_module(module_id);
1895         match self.maybe_resolve_path(&segments, Some(ns), &ParentScope::module(module, self)) {
1896             PathResult::Module(ModuleOrUniformRoot::Module(module)) => Some(module.res().unwrap()),
1897             PathResult::NonModule(path_res) if path_res.unresolved_segments() == 0 => {
1898                 Some(path_res.base_res())
1899             }
1900             PathResult::Module(ModuleOrUniformRoot::ExternPrelude)
1901             | PathResult::NonModule(..)
1902             | PathResult::Failed { .. } => None,
1903             PathResult::Module(..) | PathResult::Indeterminate => unreachable!(),
1904         }
1905     }
1906
1907     // For rustdoc.
1908     pub fn graph_root(&self) -> Module<'a> {
1909         self.graph_root
1910     }
1911
1912     // For rustdoc.
1913     pub fn take_all_macro_rules(&mut self) -> FxHashMap<Symbol, Res> {
1914         mem::take(&mut self.all_macro_rules)
1915     }
1916
1917     /// For rustdoc.
1918     /// For local modules returns only reexports, for external modules returns all children.
1919     pub fn module_children_or_reexports(&self, def_id: DefId) -> Vec<ModChild> {
1920         if let Some(def_id) = def_id.as_local() {
1921             self.reexport_map.get(&def_id).cloned().unwrap_or_default()
1922         } else {
1923             self.cstore().module_children_untracked(def_id, self.session)
1924         }
1925     }
1926
1927     /// Retrieves the span of the given `DefId` if `DefId` is in the local crate.
1928     #[inline]
1929     pub fn opt_span(&self, def_id: DefId) -> Option<Span> {
1930         def_id.as_local().map(|def_id| self.definitions.def_span(def_id))
1931     }
1932
1933     /// Checks if an expression refers to a function marked with
1934     /// `#[rustc_legacy_const_generics]` and returns the argument index list
1935     /// from the attribute.
1936     pub fn legacy_const_generic_args(&mut self, expr: &Expr) -> Option<Vec<usize>> {
1937         if let ExprKind::Path(None, path) = &expr.kind {
1938             // Don't perform legacy const generics rewriting if the path already
1939             // has generic arguments.
1940             if path.segments.last().unwrap().args.is_some() {
1941                 return None;
1942             }
1943
1944             let partial_res = self.partial_res_map.get(&expr.id)?;
1945             if partial_res.unresolved_segments() != 0 {
1946                 return None;
1947             }
1948
1949             if let Res::Def(def::DefKind::Fn, def_id) = partial_res.base_res() {
1950                 // We only support cross-crate argument rewriting. Uses
1951                 // within the same crate should be updated to use the new
1952                 // const generics style.
1953                 if def_id.is_local() {
1954                     return None;
1955                 }
1956
1957                 if let Some(v) = self.legacy_const_generic_args.get(&def_id) {
1958                     return v.clone();
1959                 }
1960
1961                 let attr = self
1962                     .cstore()
1963                     .item_attrs_untracked(def_id, self.session)
1964                     .find(|a| a.has_name(sym::rustc_legacy_const_generics))?;
1965                 let mut ret = Vec::new();
1966                 for meta in attr.meta_item_list()? {
1967                     match meta.literal()?.kind {
1968                         LitKind::Int(a, _) => ret.push(a as usize),
1969                         _ => panic!("invalid arg index"),
1970                     }
1971                 }
1972                 // Cache the lookup to avoid parsing attributes for an iterm multiple times.
1973                 self.legacy_const_generic_args.insert(def_id, Some(ret.clone()));
1974                 return Some(ret);
1975             }
1976         }
1977         None
1978     }
1979
1980     fn resolve_main(&mut self) {
1981         let module = self.graph_root;
1982         let ident = Ident::with_dummy_span(sym::main);
1983         let parent_scope = &ParentScope::module(module, self);
1984
1985         let Ok(name_binding) = self.maybe_resolve_ident_in_module(
1986             ModuleOrUniformRoot::Module(module),
1987             ident,
1988             ValueNS,
1989             parent_scope,
1990         ) else {
1991             return;
1992         };
1993
1994         let res = name_binding.res();
1995         let is_import = name_binding.is_import();
1996         let span = name_binding.span;
1997         if let Res::Def(DefKind::Fn, _) = res {
1998             self.record_use(ident, name_binding, false);
1999         }
2000         self.main_def = Some(MainDefinition { res, is_import, span });
2001     }
2002 }
2003
2004 fn names_to_string(names: &[Symbol]) -> String {
2005     let mut result = String::new();
2006     for (i, name) in names.iter().filter(|name| **name != kw::PathRoot).enumerate() {
2007         if i > 0 {
2008             result.push_str("::");
2009         }
2010         if Ident::with_dummy_span(*name).is_raw_guess() {
2011             result.push_str("r#");
2012         }
2013         result.push_str(name.as_str());
2014     }
2015     result
2016 }
2017
2018 fn path_names_to_string(path: &Path) -> String {
2019     names_to_string(&path.segments.iter().map(|seg| seg.ident.name).collect::<Vec<_>>())
2020 }
2021
2022 /// A somewhat inefficient routine to obtain the name of a module.
2023 fn module_to_string(module: Module<'_>) -> Option<String> {
2024     let mut names = Vec::new();
2025
2026     fn collect_mod(names: &mut Vec<Symbol>, module: Module<'_>) {
2027         if let ModuleKind::Def(.., name) = module.kind {
2028             if let Some(parent) = module.parent {
2029                 names.push(name);
2030                 collect_mod(names, parent);
2031             }
2032         } else {
2033             names.push(Symbol::intern("<opaque>"));
2034             collect_mod(names, module.parent.unwrap());
2035         }
2036     }
2037     collect_mod(&mut names, module);
2038
2039     if names.is_empty() {
2040         return None;
2041     }
2042     names.reverse();
2043     Some(names_to_string(&names))
2044 }
2045
2046 #[derive(Copy, Clone, Debug)]
2047 enum Finalize {
2048     /// Do not issue the lint.
2049     No,
2050
2051     /// This lint applies to some arbitrary path; e.g., `impl ::foo::Bar`.
2052     /// In this case, we can take the span of that path.
2053     SimplePath(NodeId, Span),
2054
2055     /// This lint comes from a `use` statement. In this case, what we
2056     /// care about really is the *root* `use` statement; e.g., if we
2057     /// have nested things like `use a::{b, c}`, we care about the
2058     /// `use a` part.
2059     UsePath { root_id: NodeId, root_span: Span, path_span: Span },
2060
2061     /// This is the "trait item" from a fully qualified path. For example,
2062     /// we might be resolving  `X::Y::Z` from a path like `<T as X::Y>::Z`.
2063     /// The `path_span` is the span of the to the trait itself (`X::Y`).
2064     QPathTrait { qpath_id: NodeId, qpath_span: Span, path_span: Span },
2065 }
2066
2067 impl Finalize {
2068     fn node_id_and_path_span(&self) -> Option<(NodeId, Span)> {
2069         match *self {
2070             Finalize::No => None,
2071             Finalize::SimplePath(id, path_span)
2072             | Finalize::UsePath { root_id: id, path_span, .. }
2073             | Finalize::QPathTrait { qpath_id: id, path_span, .. } => Some((id, path_span)),
2074         }
2075     }
2076
2077     fn node_id(&self) -> Option<NodeId> {
2078         self.node_id_and_path_span().map(|(id, _)| id)
2079     }
2080
2081     fn path_span(&self) -> Option<Span> {
2082         self.node_id_and_path_span().map(|(_, path_span)| path_span)
2083     }
2084 }
2085
2086 pub fn provide(providers: &mut Providers) {
2087     late::lifetimes::provide(providers);
2088 }