resolve: Use Interned for Module

This commit is contained in:
Vadim Petrochenkov 2023-07-04 20:00:42 +03:00
parent 4abdaeb67e
commit c1f412f9a9
7 changed files with 59 additions and 65 deletions

View file

@ -31,7 +31,6 @@ use rustc_span::symbol::{kw, sym, Ident, Symbol};
use rustc_span::Span; use rustc_span::Span;
use std::cell::Cell; use std::cell::Cell;
use std::ptr;
type Res = def::Res<NodeId>; type Res = def::Res<NodeId>;
@ -142,8 +141,8 @@ impl<'a, 'tcx> Resolver<'a, 'tcx> {
Some(def_id) => self.macro_def_scope(def_id), Some(def_id) => self.macro_def_scope(def_id),
None => expn_id None => expn_id
.as_local() .as_local()
.and_then(|expn_id| self.ast_transform_scopes.get(&expn_id)) .and_then(|expn_id| self.ast_transform_scopes.get(&expn_id).copied())
.unwrap_or(&self.graph_root), .unwrap_or(self.graph_root),
} }
} }
@ -864,7 +863,7 @@ impl<'a, 'b, 'tcx> BuildReducedGraphVisitor<'a, 'b, 'tcx> {
}); });
self.r.potentially_unused_imports.push(import); self.r.potentially_unused_imports.push(import);
let imported_binding = self.r.import(binding, import); let imported_binding = self.r.import(binding, import);
if ptr::eq(parent, self.r.graph_root) { if parent == self.r.graph_root {
if let Some(entry) = self.r.extern_prelude.get(&ident.normalize_to_macros_2_0()) { if let Some(entry) = self.r.extern_prelude.get(&ident.normalize_to_macros_2_0()) {
if expansion != LocalExpnId::ROOT if expansion != LocalExpnId::ROOT
&& orig_name.is_some() && orig_name.is_some()

View file

@ -1,5 +1,3 @@
use std::ptr;
use rustc_ast::expand::StrippedCfgItem; use rustc_ast::expand::StrippedCfgItem;
use rustc_ast::ptr::P; use rustc_ast::ptr::P;
use rustc_ast::visit::{self, Visitor}; use rustc_ast::visit::{self, Visitor};
@ -1198,7 +1196,7 @@ impl<'a, 'tcx> Resolver<'a, 'tcx> {
// avoid suggesting anything with a hygienic name // avoid suggesting anything with a hygienic name
if ident.name == lookup_ident.name if ident.name == lookup_ident.name
&& ns == namespace && ns == namespace
&& !ptr::eq(in_module, parent_scope.module) && in_module != parent_scope.module
&& !ident.span.normalize_to_macros_2_0().from_expansion() && !ident.span.normalize_to_macros_2_0().from_expansion()
{ {
let res = name_binding.res(); let res = name_binding.res();
@ -1732,7 +1730,7 @@ impl<'a, 'tcx> Resolver<'a, 'tcx> {
pub(crate) fn find_similarly_named_module_or_crate( pub(crate) fn find_similarly_named_module_or_crate(
&mut self, &mut self,
ident: Symbol, ident: Symbol,
current_module: &Module<'a>, current_module: Module<'a>,
) -> Option<Symbol> { ) -> Option<Symbol> {
let mut candidates = self let mut candidates = self
.extern_prelude .extern_prelude
@ -1742,7 +1740,7 @@ impl<'a, 'tcx> Resolver<'a, 'tcx> {
self.module_map self.module_map
.iter() .iter()
.filter(|(_, module)| { .filter(|(_, module)| {
current_module.is_ancestor_of(module) && !ptr::eq(current_module, *module) current_module.is_ancestor_of(**module) && current_module != **module
}) })
.flat_map(|(_, module)| module.kind.name()), .flat_map(|(_, module)| module.kind.name()),
) )
@ -1945,7 +1943,7 @@ impl<'a, 'tcx> Resolver<'a, 'tcx> {
} }
suggestion = suggestion.or_else(|| { suggestion = suggestion.or_else(|| {
self.find_similarly_named_module_or_crate(ident.name, &parent_scope.module).map( self.find_similarly_named_module_or_crate(ident.name, parent_scope.module).map(
|sugg| { |sugg| {
( (
vec![(ident.span, sugg.to_string())], vec![(ident.span, sugg.to_string())],
@ -2126,9 +2124,8 @@ impl<'a, 'tcx> Resolver<'a, 'tcx> {
crate_module = parent; crate_module = parent;
} }
if ModuleOrUniformRoot::same_def(ModuleOrUniformRoot::Module(crate_module), module) { if module == ModuleOrUniformRoot::Module(crate_module) {
// Don't make a suggestion if the import was already from the root of the // Don't make a suggestion if the import was already from the root of the crate.
// crate.
return None; return None;
} }

View file

@ -11,8 +11,6 @@ use rustc_span::hygiene::{ExpnId, ExpnKind, LocalExpnId, MacroKind, SyntaxContex
use rustc_span::symbol::{kw, Ident}; use rustc_span::symbol::{kw, Ident};
use rustc_span::{Span, DUMMY_SP}; use rustc_span::{Span, DUMMY_SP};
use std::ptr;
use crate::errors::{ParamKindInEnumDiscriminant, ParamKindInNonTrivialAnonConst}; use crate::errors::{ParamKindInEnumDiscriminant, ParamKindInNonTrivialAnonConst};
use crate::late::{ use crate::late::{
ConstantHasGenerics, HasGenericParams, NoConstantGenericsReason, PathSource, Rib, RibKind, ConstantHasGenerics, HasGenericParams, NoConstantGenericsReason, PathSource, Rib, RibKind,
@ -538,7 +536,7 @@ impl<'a, 'tcx> Resolver<'a, 'tcx> {
), ),
); );
} }
let misc_flags = if ptr::eq(module, this.graph_root) { let misc_flags = if module == this.graph_root {
Flags::MISC_SUGGEST_CRATE Flags::MISC_SUGGEST_CRATE
} else if module.is_normal() { } else if module.is_normal() {
Flags::MISC_SUGGEST_SELF Flags::MISC_SUGGEST_SELF

View file

@ -35,7 +35,7 @@ use rustc_span::Span;
use smallvec::SmallVec; use smallvec::SmallVec;
use std::cell::Cell; use std::cell::Cell;
use std::{mem, ptr}; use std::mem;
type Res = def::Res<NodeId>; type Res = def::Res<NodeId>;
@ -463,7 +463,7 @@ impl<'a, 'tcx> Resolver<'a, 'tcx> {
pub(crate) fn finalize_imports(&mut self) { pub(crate) fn finalize_imports(&mut self) {
for module in self.arenas.local_modules().iter() { for module in self.arenas.local_modules().iter() {
self.finalize_resolutions_in(module); self.finalize_resolutions_in(*module);
} }
let mut seen_spans = FxHashSet::default(); let mut seen_spans = FxHashSet::default();
@ -537,7 +537,7 @@ impl<'a, 'tcx> Resolver<'a, 'tcx> {
exported_ambiguities: FxHashSet<NameBinding<'a>>, exported_ambiguities: FxHashSet<NameBinding<'a>>,
) { ) {
for module in self.arenas.local_modules().iter() { for module in self.arenas.local_modules().iter() {
for (key, resolution) in self.resolutions(module).borrow().iter() { for (key, resolution) in self.resolutions(*module).borrow().iter() {
let resolution = resolution.borrow(); let resolution = resolution.borrow();
if let Some(binding) = resolution.binding { if let Some(binding) = resolution.binding {
@ -812,7 +812,7 @@ impl<'a, 'tcx> Resolver<'a, 'tcx> {
PathResult::Module(module) => { PathResult::Module(module) => {
// Consistency checks, analogous to `finalize_macro_resolutions`. // Consistency checks, analogous to `finalize_macro_resolutions`.
if let Some(initial_module) = import.imported_module.get() { if let Some(initial_module) = import.imported_module.get() {
if !ModuleOrUniformRoot::same_def(module, initial_module) && no_ambiguity { if module != initial_module && no_ambiguity {
span_bug!(import.span, "inconsistent resolution for an import"); span_bug!(import.span, "inconsistent resolution for an import");
} }
} else if self.privacy_errors.is_empty() { } else if self.privacy_errors.is_empty() {
@ -914,7 +914,7 @@ impl<'a, 'tcx> Resolver<'a, 'tcx> {
} }
if let ModuleOrUniformRoot::Module(module) = module { if let ModuleOrUniformRoot::Module(module) = module {
if ptr::eq(module, import.parent_scope.module) { if module == import.parent_scope.module {
// Importing a module into itself is not allowed. // Importing a module into itself is not allowed.
return Some(UnresolvedImportError { return Some(UnresolvedImportError {
span: import.span, span: import.span,
@ -1307,7 +1307,7 @@ impl<'a, 'tcx> Resolver<'a, 'tcx> {
if module.is_trait() { if module.is_trait() {
self.tcx.sess.create_err(ItemsInTraitsAreNotImportable { span: import.span }).emit(); self.tcx.sess.create_err(ItemsInTraitsAreNotImportable { span: import.span }).emit();
return; return;
} else if ptr::eq(module, import.parent_scope.module) { } else if module == import.parent_scope.module {
return; return;
} else if is_prelude { } else if is_prelude {
self.prelude = Some(module); self.prelude = Some(module);

View file

@ -2972,7 +2972,7 @@ impl<'a: 'ast, 'b, 'ast, 'tcx> LateResolutionVisitor<'a, 'b, 'ast, 'tcx> {
F: FnOnce(Ident, String, Option<Symbol>) -> ResolutionError<'a>, F: FnOnce(Ident, String, Option<Symbol>) -> ResolutionError<'a>,
{ {
// If there is a TraitRef in scope for an impl, then the method must be in the trait. // If there is a TraitRef in scope for an impl, then the method must be in the trait.
let Some((module, _)) = &self.current_trait_ref else { return; }; let Some((module, _)) = self.current_trait_ref else { return; };
ident.span.normalize_to_macros_2_0_and_adjust(module.expansion); ident.span.normalize_to_macros_2_0_and_adjust(module.expansion);
let key = BindingKey::new(ident, ns); let key = BindingKey::new(ident, ns);
let mut binding = self.r.resolution(module, key).try_borrow().ok().and_then(|r| r.binding); let mut binding = self.r.resolution(module, key).try_borrow().ok().and_then(|r| r.binding);

View file

@ -1593,7 +1593,7 @@ impl<'a: 'ast, 'ast, 'tcx> LateResolutionVisitor<'a, '_, 'ast, 'tcx> {
return None; return None;
} }
let resolutions = self.r.resolutions(module); let resolutions = self.r.resolutions(*module);
let targets = resolutions let targets = resolutions
.borrow() .borrow()
.iter() .iter()

View file

@ -14,6 +14,7 @@
#![feature(iter_intersperse)] #![feature(iter_intersperse)]
#![feature(let_chains)] #![feature(let_chains)]
#![feature(never_type)] #![feature(never_type)]
#![feature(rustc_attrs)]
#![recursion_limit = "256"] #![recursion_limit = "256"]
#![allow(rustdoc::private_intra_doc_links)] #![allow(rustdoc::private_intra_doc_links)]
#![allow(rustc::potential_query_instability)] #![allow(rustc::potential_query_instability)]
@ -61,7 +62,7 @@ use rustc_span::{Span, DUMMY_SP};
use smallvec::{smallvec, SmallVec}; use smallvec::{smallvec, SmallVec};
use std::cell::{Cell, RefCell}; use std::cell::{Cell, RefCell};
use std::collections::BTreeSet; use std::collections::BTreeSet;
use std::{fmt, ptr}; use std::fmt;
use diagnostics::{ImportSuggestion, LabelSuggestion, Suggestion}; use diagnostics::{ImportSuggestion, LabelSuggestion, Suggestion};
use imports::{Import, ImportData, ImportKind, NameResolution}; use imports::{Import, ImportData, ImportKind, NameResolution};
@ -365,7 +366,7 @@ impl<'a> LexicalScopeBinding<'a> {
} }
} }
#[derive(Copy, Clone, Debug)] #[derive(Copy, Clone, PartialEq, Debug)]
enum ModuleOrUniformRoot<'a> { enum ModuleOrUniformRoot<'a> {
/// Regular module. /// Regular module.
Module(Module<'a>), Module(Module<'a>),
@ -383,23 +384,6 @@ enum ModuleOrUniformRoot<'a> {
CurrentScope, CurrentScope,
} }
impl ModuleOrUniformRoot<'_> {
fn same_def(lhs: Self, rhs: Self) -> bool {
match (lhs, rhs) {
(ModuleOrUniformRoot::Module(lhs), ModuleOrUniformRoot::Module(rhs)) => {
ptr::eq(lhs, rhs)
}
(
ModuleOrUniformRoot::CrateRootAndExternPrelude,
ModuleOrUniformRoot::CrateRootAndExternPrelude,
)
| (ModuleOrUniformRoot::ExternPrelude, ModuleOrUniformRoot::ExternPrelude)
| (ModuleOrUniformRoot::CurrentScope, ModuleOrUniformRoot::CurrentScope) => true,
_ => false,
}
}
}
#[derive(Debug)] #[derive(Debug)]
enum PathResult<'a> { enum PathResult<'a> {
Module(ModuleOrUniformRoot<'a>), Module(ModuleOrUniformRoot<'a>),
@ -530,7 +514,9 @@ struct ModuleData<'a> {
expansion: ExpnId, expansion: ExpnId,
} }
type Module<'a> = &'a ModuleData<'a>; #[derive(Clone, Copy, PartialEq)]
#[rustc_pass_by_value]
struct Module<'a>(Interned<'a, ModuleData<'a>>);
impl<'a> ModuleData<'a> { impl<'a> ModuleData<'a> {
fn new( fn new(
@ -558,8 +544,10 @@ impl<'a> ModuleData<'a> {
expansion, expansion,
} }
} }
}
fn for_each_child<'tcx, R, F>(&'a self, resolver: &mut R, mut f: F) impl<'a> Module<'a> {
fn for_each_child<'tcx, R, F>(self, resolver: &mut R, mut f: F)
where where
R: AsMut<Resolver<'a, 'tcx>>, R: AsMut<Resolver<'a, 'tcx>>,
F: FnMut(&mut R, Ident, Namespace, NameBinding<'a>), F: FnMut(&mut R, Ident, Namespace, NameBinding<'a>),
@ -572,7 +560,7 @@ impl<'a> ModuleData<'a> {
} }
/// This modifies `self` in place. The traits will be stored in `self.traits`. /// This modifies `self` in place. The traits will be stored in `self.traits`.
fn ensure_traits<'tcx, R>(&'a self, resolver: &mut R) fn ensure_traits<'tcx, R>(self, resolver: &mut R)
where where
R: AsMut<Resolver<'a, 'tcx>>, R: AsMut<Resolver<'a, 'tcx>>,
{ {
@ -591,7 +579,7 @@ impl<'a> ModuleData<'a> {
} }
} }
fn res(&self) -> Option<Res> { fn res(self) -> Option<Res> {
match self.kind { match self.kind {
ModuleKind::Def(kind, def_id, _) => Some(Res::Def(kind, def_id)), ModuleKind::Def(kind, def_id, _) => Some(Res::Def(kind, def_id)),
_ => None, _ => None,
@ -599,11 +587,11 @@ impl<'a> ModuleData<'a> {
} }
// Public for rustdoc. // Public for rustdoc.
fn def_id(&self) -> DefId { fn def_id(self) -> DefId {
self.opt_def_id().expect("`ModuleData::def_id` is called on a block module") self.opt_def_id().expect("`ModuleData::def_id` is called on a block module")
} }
fn opt_def_id(&self) -> Option<DefId> { fn opt_def_id(self) -> Option<DefId> {
match self.kind { match self.kind {
ModuleKind::Def(_, def_id, _) => Some(def_id), ModuleKind::Def(_, def_id, _) => Some(def_id),
_ => None, _ => None,
@ -611,15 +599,15 @@ impl<'a> ModuleData<'a> {
} }
// `self` resolves to the first module ancestor that `is_normal`. // `self` resolves to the first module ancestor that `is_normal`.
fn is_normal(&self) -> bool { fn is_normal(self) -> bool {
matches!(self.kind, ModuleKind::Def(DefKind::Mod, _, _)) matches!(self.kind, ModuleKind::Def(DefKind::Mod, _, _))
} }
fn is_trait(&self) -> bool { fn is_trait(self) -> bool {
matches!(self.kind, ModuleKind::Def(DefKind::Trait, _, _)) matches!(self.kind, ModuleKind::Def(DefKind::Trait, _, _))
} }
fn nearest_item_scope(&'a self) -> Module<'a> { fn nearest_item_scope(self) -> Module<'a> {
match self.kind { match self.kind {
ModuleKind::Def(DefKind::Enum | DefKind::Trait, ..) => { ModuleKind::Def(DefKind::Enum | DefKind::Trait, ..) => {
self.parent.expect("enum or trait module without a parent") self.parent.expect("enum or trait module without a parent")
@ -630,15 +618,15 @@ impl<'a> ModuleData<'a> {
/// The [`DefId`] of the nearest `mod` item ancestor (which may be this module). /// The [`DefId`] of the nearest `mod` item ancestor (which may be this module).
/// This may be the crate root. /// This may be the crate root.
fn nearest_parent_mod(&self) -> DefId { fn nearest_parent_mod(self) -> DefId {
match self.kind { match self.kind {
ModuleKind::Def(DefKind::Mod, def_id, _) => def_id, ModuleKind::Def(DefKind::Mod, def_id, _) => def_id,
_ => self.parent.expect("non-root module without parent").nearest_parent_mod(), _ => self.parent.expect("non-root module without parent").nearest_parent_mod(),
} }
} }
fn is_ancestor_of(&self, mut other: &Self) -> bool { fn is_ancestor_of(self, mut other: Self) -> bool {
while !ptr::eq(self, other) { while self != other {
if let Some(parent) = other.parent { if let Some(parent) = other.parent {
other = parent; other = parent;
} else { } else {
@ -649,7 +637,15 @@ impl<'a> ModuleData<'a> {
} }
} }
impl<'a> fmt::Debug for ModuleData<'a> { impl<'a> std::ops::Deref for Module<'a> {
type Target = ModuleData<'a>;
fn deref(&self) -> &Self::Target {
&self.0
}
}
impl<'a> fmt::Debug for Module<'a> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{:?}", self.res()) write!(f, "{:?}", self.res())
} }
@ -810,10 +806,9 @@ impl<'a> NameBindingData<'a> {
NameBindingKind::Import { import, .. } => { NameBindingKind::Import { import, .. } => {
matches!(import.kind, ImportKind::ExternCrate { .. }) matches!(import.kind, ImportKind::ExternCrate { .. })
} }
NameBindingKind::Module(&ModuleData { NameBindingKind::Module(module)
kind: ModuleKind::Def(DefKind::Mod, def_id, _), if let ModuleKind::Def(DefKind::Mod, def_id, _) = module.kind
.. => def_id.is_crate_root(),
}) => def_id.is_crate_root(),
_ => false, _ => false,
} }
} }
@ -1102,8 +1097,13 @@ impl<'a> ResolverArenas<'a> {
no_implicit_prelude: bool, no_implicit_prelude: bool,
module_map: &mut FxHashMap<DefId, Module<'a>>, module_map: &mut FxHashMap<DefId, Module<'a>>,
) -> Module<'a> { ) -> Module<'a> {
let module = let module = Module(Interned::new_unchecked(self.modules.alloc(ModuleData::new(
self.modules.alloc(ModuleData::new(parent, kind, expn_id, span, no_implicit_prelude)); parent,
kind,
expn_id,
span,
no_implicit_prelude,
))));
let def_id = module.opt_def_id(); let def_id = module.opt_def_id();
if def_id.map_or(true, |def_id| def_id.is_local()) { if def_id.map_or(true, |def_id| def_id.is_local()) {
self.local_modules.borrow_mut().push(module); self.local_modules.borrow_mut().push(module);
@ -1647,7 +1647,7 @@ impl<'a, 'tcx> Resolver<'a, 'tcx> {
module.populate_on_access.set(false); module.populate_on_access.set(false);
self.build_reduced_graph_external(module); self.build_reduced_graph_external(module);
} }
&module.lazy_resolutions &module.0.0.lazy_resolutions
} }
fn resolution( fn resolution(
@ -1827,7 +1827,7 @@ impl<'a, 'tcx> Resolver<'a, 'tcx> {
fn set_binding_parent_module(&mut self, binding: NameBinding<'a>, module: Module<'a>) { fn set_binding_parent_module(&mut self, binding: NameBinding<'a>, module: Module<'a>) {
if let Some(old_module) = self.binding_parent_modules.insert(binding, module) { if let Some(old_module) = self.binding_parent_modules.insert(binding, module) {
if !ptr::eq(module, old_module) { if module != old_module {
span_bug!(binding.span, "parent module is reset for binding"); span_bug!(binding.span, "parent module is reset for binding");
} }
} }
@ -1847,7 +1847,7 @@ impl<'a, 'tcx> Resolver<'a, 'tcx> {
) { ) {
(Some(macro_rules), Some(modularized)) => { (Some(macro_rules), Some(modularized)) => {
macro_rules.nearest_parent_mod() == modularized.nearest_parent_mod() macro_rules.nearest_parent_mod() == modularized.nearest_parent_mod()
&& modularized.is_ancestor_of(macro_rules) && modularized.is_ancestor_of(*macro_rules)
} }
_ => false, _ => false,
} }