Refactor out some crate wide data in DefMap into nested struct

This commit is contained in:
Lukas Wirth 2023-06-01 15:04:38 +02:00
parent dc7c6d43c7
commit 5c466ccc2b
6 changed files with 73 additions and 58 deletions

View File

@ -148,8 +148,8 @@ fn f() {
}
"#,
expect![[r#"
BlockId(1) in ModuleId { krate: Idx::<CrateData>(0), block: Some(BlockId(0)), local_id: Idx::<ModuleData>(1) }
BlockId(0) in ModuleId { krate: Idx::<CrateData>(0), block: None, local_id: Idx::<ModuleData>(0) }
BlockId(1) in BlockRelativeModuleId { block: Some(BlockId(0)), local_id: Idx::<ModuleData>(1) }
BlockId(0) in BlockRelativeModuleId { block: None, local_id: Idx::<ModuleData>(0) }
crate scope
"#]],
);

View File

@ -109,14 +109,23 @@ pub struct DefMap {
/// this contains all kinds of macro, not just `macro_rules!` macro.
macro_use_prelude: FxHashMap<Name, MacroId>,
/// Tracks which custom derives are in scope for an item, to allow resolution of derive helper
/// attributes.
derive_helpers_in_scope: FxHashMap<AstId<ast::Item>, Vec<(Name, MacroId, MacroCallId)>>,
diagnostics: Vec<DefDiagnostic>,
// FIXME: Arc this so we can share it with block def maps
data: CrateData,
}
#[derive(Debug, PartialEq, Eq)]
struct CrateData {
/// Side table for resolving derive helpers.
exported_derives: FxHashMap<MacroDefId, Box<[Name]>>,
fn_proc_macro_mapping: FxHashMap<FunctionId, ProcMacroId>,
/// The error that occurred when failing to load the proc-macro dll.
proc_macro_loading_error: Option<Box<str>>,
/// Tracks which custom derives are in scope for an item, to allow resolution of derive helper
/// attributes.
derive_helpers_in_scope: FxHashMap<AstId<ast::Item>, Vec<(Name, MacroId, MacroCallId)>>,
/// Custom attributes registered with `#![register_attr]`.
registered_attrs: Vec<SmolStr>,
@ -131,7 +140,6 @@ pub struct DefMap {
edition: Edition,
recursion_limit: Option<u32>,
diagnostics: Vec<DefDiagnostic>,
}
/// For `DefMap`s computed for a block expression, this stores its location in the parent map.
@ -278,7 +286,7 @@ impl DefMap {
let module_data =
ModuleData::new(ModuleOrigin::BlockExpr { block: block.ast_id }, visibility);
let mut def_map = DefMap::empty(krate, parent_map.edition, module_data);
let mut def_map = DefMap::empty(krate, parent_map.data.edition, module_data);
def_map.block = Some(BlockInfo {
block: block_id,
parent: BlockRelativeModuleId {
@ -300,23 +308,25 @@ impl DefMap {
_c: Count::new(),
block: None,
krate,
edition,
recursion_limit: None,
extern_prelude: FxHashMap::default(),
macro_use_prelude: FxHashMap::default(),
exported_derives: FxHashMap::default(),
fn_proc_macro_mapping: FxHashMap::default(),
proc_macro_loading_error: None,
derive_helpers_in_scope: FxHashMap::default(),
prelude: None,
modules,
registered_attrs: Vec::new(),
registered_tools: Vec::new(),
unstable_features: FxHashSet::default(),
diagnostics: Vec::new(),
rustc_coherence_is_core: false,
no_core: false,
no_std: false,
data: CrateData {
recursion_limit: None,
exported_derives: FxHashMap::default(),
fn_proc_macro_mapping: FxHashMap::default(),
proc_macro_loading_error: None,
registered_attrs: Vec::new(),
registered_tools: Vec::new(),
unstable_features: FxHashSet::default(),
rustc_coherence_is_core: false,
no_core: false,
no_std: false,
edition,
},
}
}
@ -339,31 +349,31 @@ impl DefMap {
}
pub fn registered_tools(&self) -> &[SmolStr] {
&self.registered_tools
&self.data.registered_tools
}
pub fn registered_attrs(&self) -> &[SmolStr] {
&self.registered_attrs
&self.data.registered_attrs
}
pub fn is_unstable_feature_enabled(&self, feature: &str) -> bool {
self.unstable_features.contains(feature)
self.data.unstable_features.contains(feature)
}
pub fn is_rustc_coherence_is_core(&self) -> bool {
self.rustc_coherence_is_core
self.data.rustc_coherence_is_core
}
pub fn is_no_std(&self) -> bool {
self.no_std || self.no_core
self.data.no_std || self.data.no_core
}
pub fn fn_as_proc_macro(&self, id: FunctionId) -> Option<ProcMacroId> {
self.fn_proc_macro_mapping.get(&id).copied()
self.data.fn_proc_macro_mapping.get(&id).copied()
}
pub fn proc_macro_loading_error(&self) -> Option<&str> {
self.proc_macro_loading_error.as_deref()
self.data.proc_macro_loading_error.as_deref()
}
pub fn krate(&self) -> CrateId {
@ -540,25 +550,28 @@ impl DefMap {
// Exhaustive match to require handling new fields.
let Self {
_c: _,
exported_derives,
extern_prelude,
macro_use_prelude,
diagnostics,
modules,
registered_attrs,
registered_tools,
fn_proc_macro_mapping,
derive_helpers_in_scope,
unstable_features,
proc_macro_loading_error: _,
block: _,
edition: _,
recursion_limit: _,
krate: _,
prelude: _,
rustc_coherence_is_core: _,
no_core: _,
no_std: _,
data:
CrateData {
exported_derives,
fn_proc_macro_mapping,
registered_attrs,
registered_tools,
unstable_features,
proc_macro_loading_error: _,
rustc_coherence_is_core: _,
no_core: _,
no_std: _,
edition: _,
recursion_limit: _,
},
} = self;
extern_prelude.shrink_to_fit();
@ -583,7 +596,7 @@ impl DefMap {
}
pub fn recursion_limit(&self) -> Option<u32> {
self.recursion_limit
self.data.recursion_limit
}
}

View File

@ -78,7 +78,7 @@ impl DefMap {
let name = name.to_smol_str();
let pred = |n: &_| *n == name;
let registered = self.registered_tools.iter().map(SmolStr::as_str);
let registered = self.data.registered_tools.iter().map(SmolStr::as_str);
let is_tool = TOOL_MODULES.iter().copied().chain(registered).any(pred);
// FIXME: tool modules can be shadowed by actual modules
if is_tool {
@ -86,7 +86,7 @@ impl DefMap {
}
if segments.len() == 1 {
let mut registered = self.registered_attrs.iter().map(SmolStr::as_str);
let mut registered = self.data.registered_attrs.iter().map(SmolStr::as_str);
let is_inert = find_builtin_attr_idx(&name).is_some() || registered.any(pred);
return is_inert;
}

View File

@ -98,11 +98,11 @@ pub(super) fn collect_defs(db: &dyn DefDatabase, mut def_map: DefMap, tree_id: T
.collect()
}
Some(Err(e)) => {
def_map.proc_macro_loading_error = Some(e.clone().into_boxed_str());
def_map.data.proc_macro_loading_error = Some(e.clone().into_boxed_str());
Vec::new()
}
None => {
def_map.proc_macro_loading_error =
def_map.data.proc_macro_loading_error =
Some("No proc-macros present for crate".to_owned().into_boxed_str());
Vec::new()
}
@ -306,7 +306,7 @@ impl DefCollector<'_> {
if *attr_name == hir_expand::name![recursion_limit] {
if let Some(limit) = attr.string_value() {
if let Ok(limit) = limit.parse() {
self.def_map.recursion_limit = Some(limit);
self.def_map.data.recursion_limit = Some(limit);
}
}
continue;
@ -320,17 +320,17 @@ impl DefCollector<'_> {
}
if *attr_name == hir_expand::name![no_core] {
self.def_map.no_core = true;
self.def_map.data.no_core = true;
continue;
}
if *attr_name == hir_expand::name![no_std] {
self.def_map.no_std = true;
self.def_map.data.no_std = true;
continue;
}
if attr_name.as_text().as_deref() == Some("rustc_coherence_is_core") {
self.def_map.rustc_coherence_is_core = true;
self.def_map.data.rustc_coherence_is_core = true;
continue;
}
@ -344,7 +344,7 @@ impl DefCollector<'_> {
[name] => Some(name.to_smol_str()),
_ => None,
});
self.def_map.unstable_features.extend(features);
self.def_map.data.unstable_features.extend(features);
}
let attr_is_register_like = *attr_name == hir_expand::name![register_attr]
@ -359,10 +359,10 @@ impl DefCollector<'_> {
};
if *attr_name == hir_expand::name![register_attr] {
self.def_map.registered_attrs.push(registered_name.to_smol_str());
self.def_map.data.registered_attrs.push(registered_name.to_smol_str());
cov_mark::hit!(register_attr);
} else {
self.def_map.registered_tools.push(registered_name.to_smol_str());
self.def_map.data.registered_tools.push(registered_name.to_smol_str());
cov_mark::hit!(register_tool);
}
}
@ -530,12 +530,12 @@ impl DefCollector<'_> {
fn inject_prelude(&mut self) {
// See compiler/rustc_builtin_macros/src/standard_library_imports.rs
if self.def_map.no_core {
if self.def_map.data.no_core {
// libcore does not get a prelude.
return;
}
let krate = if self.def_map.no_std {
let krate = if self.def_map.data.no_std {
name![core]
} else {
let std = name![std];
@ -548,13 +548,13 @@ impl DefCollector<'_> {
}
};
let edition = match self.def_map.edition {
let edition = match self.def_map.data.edition {
Edition::Edition2015 => name![rust_2015],
Edition::Edition2018 => name![rust_2018],
Edition::Edition2021 => name![rust_2021],
};
let path_kind = match self.def_map.edition {
let path_kind = match self.def_map.data.edition {
Edition::Edition2015 => PathKind::Plain,
_ => PathKind::Abs,
};
@ -611,10 +611,11 @@ impl DefCollector<'_> {
self.define_proc_macro(def.name.clone(), proc_macro_id);
if let ProcMacroKind::CustomDerive { helpers } = def.kind {
self.def_map
.data
.exported_derives
.insert(macro_id_to_def_id(self.db, proc_macro_id.into()), helpers);
}
self.def_map.fn_proc_macro_mapping.insert(fn_id, proc_macro_id);
self.def_map.data.fn_proc_macro_mapping.insert(fn_id, proc_macro_id);
}
/// Define a macro with `macro_rules`.
@ -773,7 +774,7 @@ impl DefCollector<'_> {
fn resolve_import(&self, module_id: LocalModuleId, import: &Import) -> PartialResolvedImport {
let _p = profile::span("resolve_import")
.detail(|| format!("{}", import.path.display(self.db.upcast())));
tracing::debug!("resolving import: {:?} ({:?})", import, self.def_map.edition);
tracing::debug!("resolving import: {:?} ({:?})", import, self.def_map.data.edition);
if import.is_extern_crate {
let name = import
.path
@ -1153,7 +1154,7 @@ impl DefCollector<'_> {
// Record its helper attributes.
if def_id.krate != self.def_map.krate {
let def_map = self.db.crate_def_map(def_id.krate);
if let Some(helpers) = def_map.exported_derives.get(&def_id) {
if let Some(helpers) = def_map.data.exported_derives.get(&def_id) {
self.def_map
.derive_helpers_in_scope
.entry(ast_id.ast_id.map(|it| it.upcast()))
@ -2166,6 +2167,7 @@ impl ModCollector<'_, '_> {
if let Some(helpers) = helpers_opt {
self.def_collector
.def_map
.data
.exported_derives
.insert(macro_id_to_def_id(self.def_collector.db, macro_id.into()), helpers);
}

View File

@ -218,7 +218,7 @@ impl DefMap {
// rust-lang/rust#57745)
// FIXME there must be a nicer way to write this condition
PathKind::Plain | PathKind::Abs
if self.edition == Edition::Edition2015
if self.data.edition == Edition::Edition2015
&& (path.kind == PathKind::Abs || mode == ResolveMode::Import) =>
{
let (_, segment) = match segments.next() {

View File

@ -1094,8 +1094,8 @@ pub fn derive_macro_2(_item: TokenStream) -> TokenStream {
let krate = db.crate_graph().iter().next().unwrap();
let def_map = db.crate_def_map(krate);
assert_eq!(def_map.exported_derives.len(), 1);
match def_map.exported_derives.values().next() {
assert_eq!(def_map.data.exported_derives.len(), 1);
match def_map.data.exported_derives.values().next() {
Some(helpers) => match &**helpers {
[attr] => assert_eq!(attr.display(&db).to_string(), "helper_attr"),
_ => unreachable!(),