Skip to content

refactor: De-arc defmap queries #19707

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
May 5, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 2 additions & 12 deletions crates/hir-def/src/db.rs
Original file line number Diff line number Diff line change
Expand Up @@ -24,8 +24,8 @@ use crate::{
item_tree::{AttrOwner, ItemTree},
lang_item::{self, LangItem},
nameres::{
DefMap, LocalDefMap,
assoc::{ImplItems, TraitItems},
crate_def_map,
diagnostics::DefDiagnostics,
},
signatures::{
Expand Down Expand Up @@ -111,16 +111,6 @@ pub trait DefDatabase: InternDatabase + ExpandDatabase + SourceDatabase {
#[salsa::invoke(ItemTree::block_item_tree_query)]
fn block_item_tree(&self, block_id: BlockId) -> Arc<ItemTree>;

#[salsa::invoke(DefMap::crate_local_def_map_query)]
fn crate_local_def_map(&self, krate: Crate) -> (Arc<DefMap>, Arc<LocalDefMap>);

#[salsa::invoke(DefMap::crate_def_map_query)]
fn crate_def_map(&self, krate: Crate) -> Arc<DefMap>;

/// Computes the block-level `DefMap`.
#[salsa::invoke(DefMap::block_def_map_query)]
fn block_def_map(&self, block: BlockId) -> Arc<DefMap>;

/// Turns a MacroId into a MacroDefId, describing the macro's definition post name resolution.
#[salsa::invoke(macro_def)]
fn macro_def(&self, m: MacroId) -> MacroDefId;
Expand Down Expand Up @@ -363,7 +353,7 @@ fn include_macro_invoc(
db: &dyn DefDatabase,
krate: Crate,
) -> Arc<[(MacroCallId, EditionedFileId)]> {
db.crate_def_map(krate)
crate_def_map(db, krate)
.modules
.values()
.flat_map(|m| m.scope.iter_macro_invoc())
Expand Down
7 changes: 3 additions & 4 deletions crates/hir-def/src/expr_store.rs
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,6 @@ use rustc_hash::FxHashMap;
use smallvec::SmallVec;
use span::{Edition, SyntaxContext};
use syntax::{AstPtr, SyntaxNodePtr, ast};
use triomphe::Arc;
use tt::TextRange;

use crate::{
Expand All @@ -30,7 +29,7 @@ use crate::{
Array, AsmOperand, Binding, BindingId, Expr, ExprId, ExprOrPatId, Label, LabelId, Pat,
PatId, RecordFieldPat, Statement,
},
nameres::DefMap,
nameres::{DefMap, block_def_map},
type_ref::{LifetimeRef, LifetimeRefId, PathId, TypeRef, TypeRefId},
};

Expand Down Expand Up @@ -225,8 +224,8 @@ impl ExpressionStore {
pub fn blocks<'a>(
&'a self,
db: &'a dyn DefDatabase,
) -> impl Iterator<Item = (BlockId, Arc<DefMap>)> + 'a {
self.block_scopes.iter().map(move |&block| (block, db.block_def_map(block)))
) -> impl Iterator<Item = (BlockId, &'a DefMap)> + 'a {
self.block_scopes.iter().map(move |&block| (block, block_def_map(db, block)))
}

pub fn walk_bindings_in_pat(&self, pat_id: PatId, mut f: impl FnMut(BindingId)) {
Expand Down
16 changes: 8 additions & 8 deletions crates/hir-def/src/expr_store/lower.rs
Original file line number Diff line number Diff line change
Expand Up @@ -56,7 +56,7 @@ use crate::{
item_scope::BuiltinShadowMode,
item_tree::FieldsShape,
lang_item::LangItem,
nameres::{DefMap, LocalDefMap, MacroSubNs},
nameres::{DefMap, LocalDefMap, MacroSubNs, block_def_map},
type_ref::{
ArrayType, ConstRef, FnType, LifetimeRef, LifetimeRefId, Mutability, PathId, Rawness,
RefType, TraitBoundModifier, TraitRef, TypeBound, TypeRef, TypeRefId, UseArgRef,
Expand Down Expand Up @@ -436,8 +436,8 @@ pub struct ExprCollector<'db> {
db: &'db dyn DefDatabase,
cfg_options: &'db CfgOptions,
expander: Expander,
def_map: Arc<DefMap>,
local_def_map: Arc<LocalDefMap>,
def_map: &'db DefMap,
local_def_map: &'db LocalDefMap,
module: ModuleId,
pub store: ExpressionStoreBuilder,
pub(crate) source_map: ExpressionStoreSourceMap,
Expand Down Expand Up @@ -544,7 +544,7 @@ impl ExprCollector<'_> {
current_file_id: HirFileId,
) -> ExprCollector<'_> {
let (def_map, local_def_map) = module.local_def_map(db);
let expander = Expander::new(db, current_file_id, &def_map);
let expander = Expander::new(db, current_file_id, def_map);
ExprCollector {
db,
cfg_options: module.krate().cfg_options(db),
Expand Down Expand Up @@ -1947,7 +1947,7 @@ impl ExprCollector<'_> {
let resolver = |path: &_| {
self.def_map
.resolve_path(
&self.local_def_map,
self.local_def_map,
self.db,
module,
path,
Expand Down Expand Up @@ -2163,12 +2163,12 @@ impl ExprCollector<'_> {
};

let (module, def_map) =
match block_id.map(|block_id| (self.db.block_def_map(block_id), block_id)) {
match block_id.map(|block_id| (block_def_map(self.db, block_id), block_id)) {
Some((def_map, block_id)) => {
self.store.block_scopes.push(block_id);
(def_map.module_id(DefMap::ROOT), def_map)
}
None => (self.module, self.def_map.clone()),
None => (self.module, self.def_map),
};
let prev_def_map = mem::replace(&mut self.def_map, def_map);
let prev_local_module = mem::replace(&mut self.module, module);
Expand Down Expand Up @@ -2247,7 +2247,7 @@ impl ExprCollector<'_> {
// This could also be a single-segment path pattern. To
// decide that, we need to try resolving the name.
let (resolved, _) = self.def_map.resolve_path(
&self.local_def_map,
self.local_def_map,
self.db,
self.module.local_id,
&name.clone().into(),
Expand Down
5 changes: 3 additions & 2 deletions crates/hir-def/src/expr_store/lower/path/tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,6 @@ use syntax::ast::{self, make};
use test_fixture::WithFixture;

use crate::{
db::DefDatabase,
expr_store::{
ExpressionStore,
lower::{
Expand All @@ -14,13 +13,15 @@ use crate::{
path::Path,
pretty,
},
nameres::crate_def_map,
test_db::TestDB,
};

fn lower_path(path: ast::Path) -> (TestDB, ExpressionStore, Option<Path>) {
let (db, file_id) = TestDB::with_single_file("");
let krate = db.fetch_test_crate();
let mut ctx = ExprCollector::new(&db, db.crate_def_map(krate).root_module_id(), file_id.into());
let mut ctx =
ExprCollector::new(&db, crate_def_map(&db, krate).root_module_id(), file_id.into());
let lowered_path = ctx.lower_path(path, &mut ExprCollector::impl_trait_allocator);
let store = ctx.store.finish();
(db, store, lowered_path)
Expand Down
6 changes: 4 additions & 2 deletions crates/hir-def/src/expr_store/scope.rs
Original file line number Diff line number Diff line change
Expand Up @@ -324,11 +324,13 @@ mod tests {
use test_fixture::WithFixture;
use test_utils::{assert_eq_text, extract_offset};

use crate::{FunctionId, ModuleDefId, db::DefDatabase, test_db::TestDB};
use crate::{
FunctionId, ModuleDefId, db::DefDatabase, nameres::crate_def_map, test_db::TestDB,
};

fn find_function(db: &TestDB, file_id: FileId) -> FunctionId {
let krate = db.test_crate();
let crate_def_map = db.crate_def_map(krate);
let crate_def_map = crate_def_map(db, krate);

let module = crate_def_map.modules_for_file(db, file_id).next().unwrap();
let (_, def) = crate_def_map[module].scope.entries().next().unwrap();
Expand Down
5 changes: 3 additions & 2 deletions crates/hir-def/src/expr_store/tests/body.rs
Original file line number Diff line number Diff line change
@@ -1,17 +1,18 @@
mod block;

use crate::{DefWithBodyId, ModuleDefId, hir::MatchArm, test_db::TestDB};
use crate::{DefWithBodyId, ModuleDefId, hir::MatchArm, nameres::crate_def_map, test_db::TestDB};
use expect_test::{Expect, expect};
use la_arena::RawIdx;
use test_fixture::WithFixture;
use triomphe::Arc;

use super::super::*;

fn lower(#[rust_analyzer::rust_fixture] ra_fixture: &str) -> (TestDB, Arc<Body>, DefWithBodyId) {
let db = TestDB::with_files(ra_fixture);

let krate = db.fetch_test_crate();
let def_map = db.crate_def_map(krate);
let def_map = crate_def_map(&db, krate);
let mut fn_def = None;
'outer: for (_, module) in def_map.modules() {
for decl in module.scope.declarations() {
Expand Down
4 changes: 2 additions & 2 deletions crates/hir-def/src/expr_store/tests/body/block.rs
Original file line number Diff line number Diff line change
Expand Up @@ -189,8 +189,8 @@ fn f() {
}
"#,
expect![[r#"
BlockId(3801) in BlockRelativeModuleId { block: Some(BlockId(3800)), local_id: Idx::<ModuleData>(1) }
BlockId(3800) in BlockRelativeModuleId { block: None, local_id: Idx::<ModuleData>(0) }
BlockId(3c01) in BlockRelativeModuleId { block: Some(BlockId(3c00)), local_id: Idx::<ModuleData>(1) }
BlockId(3c00) in BlockRelativeModuleId { block: None, local_id: Idx::<ModuleData>(0) }
crate scope
"#]],
);
Expand Down
3 changes: 2 additions & 1 deletion crates/hir-def/src/expr_store/tests/signatures.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
use crate::{
GenericDefId, ModuleDefId,
expr_store::pretty::{print_function, print_struct},
nameres::crate_def_map,
test_db::TestDB,
};
use expect_test::{Expect, expect};
Expand All @@ -12,7 +13,7 @@ fn lower_and_print(#[rust_analyzer::rust_fixture] ra_fixture: &str, expect: Expe
let db = TestDB::with_files(ra_fixture);

let krate = db.fetch_test_crate();
let def_map = db.crate_def_map(krate);
let def_map = crate_def_map(&db, krate);
let mut defs = vec![];
for (_, module) in def_map.modules() {
for decl in module.scope.declarations() {
Expand Down
4 changes: 2 additions & 2 deletions crates/hir-def/src/find_path.rs
Original file line number Diff line number Diff line change
Expand Up @@ -52,7 +52,7 @@ pub fn find_path(
ignore_local_imports,
is_std_item: item_module.krate().data(db).origin.is_lang(),
from,
from_def_map: &from.def_map(db),
from_def_map: from.def_map(db),
fuel: Cell::new(FIND_PATH_FUEL),
},
item,
Expand Down Expand Up @@ -691,7 +691,7 @@ mod tests {
let (def_map, local_def_map) = module.local_def_map(&db);
let resolved = def_map
.resolve_path(
&local_def_map,
local_def_map,
&db,
module.local_id,
&mod_path,
Expand Down
4 changes: 2 additions & 2 deletions crates/hir-def/src/import_map.rs
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ use crate::{
AssocItemId, AttrDefId, Complete, FxIndexMap, ModuleDefId, ModuleId, TraitId,
db::DefDatabase,
item_scope::{ImportOrExternCrate, ItemInNs},
nameres::DefMap,
nameres::{DefMap, crate_def_map},
visibility::Visibility,
};

Expand Down Expand Up @@ -129,7 +129,7 @@ impl ImportMap {
fn collect_import_map(db: &dyn DefDatabase, krate: Crate) -> ImportMapIndex {
let _p = tracing::info_span!("collect_import_map").entered();

let def_map = db.crate_def_map(krate);
let def_map = crate_def_map(db, krate);
let mut map = FxIndexMap::default();

// We look only into modules that are public(ly reexported), starting with the crate root.
Expand Down
5 changes: 3 additions & 2 deletions crates/hir-def/src/lang_item.rs
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ use triomphe::Arc;
use crate::{
AdtId, AssocItemId, AttrDefId, Crate, EnumId, EnumVariantId, FunctionId, ImplId, ModuleDefId,
StaticId, StructId, TraitId, TypeAliasId, UnionId, db::DefDatabase, expr_store::path::Path,
nameres::crate_def_map,
};

#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
Expand Down Expand Up @@ -90,7 +91,7 @@ pub fn crate_lang_items(db: &dyn DefDatabase, krate: Crate) -> Option<Box<LangIt

let mut lang_items = LangItems::default();

let crate_def_map = db.crate_def_map(krate);
let crate_def_map = crate_def_map(db, krate);

for (_, module_data) in crate_def_map.modules() {
for impl_def in module_data.scope.impls() {
Expand Down Expand Up @@ -209,7 +210,7 @@ pub(crate) fn crate_notable_traits(db: &dyn DefDatabase, krate: Crate) -> Option

let mut traits = Vec::new();

let crate_def_map = db.crate_def_map(krate);
let crate_def_map = crate_def_map(db, krate);

for (_, module_data) in crate_def_map.modules() {
for def in module_data.scope.declarations() {
Expand Down
34 changes: 19 additions & 15 deletions crates/hir-def/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -92,7 +92,7 @@ use crate::{
Const, Enum, ExternCrate, Function, Impl, ItemTreeId, ItemTreeNode, Macro2, MacroRules,
Static, Struct, Trait, TraitAlias, TypeAlias, Union, Use, Variant,
},
nameres::LocalDefMap,
nameres::{LocalDefMap, block_def_map, crate_def_map, crate_local_def_map},
signatures::VariantFields,
};

Expand Down Expand Up @@ -324,12 +324,13 @@ pub struct CrateRootModuleId {
}

impl CrateRootModuleId {
pub fn def_map(&self, db: &dyn DefDatabase) -> Arc<DefMap> {
db.crate_def_map(self.krate)
pub fn def_map(self, db: &dyn DefDatabase) -> &DefMap {
crate_def_map(db, self.krate)
}

pub(crate) fn local_def_map(&self, db: &dyn DefDatabase) -> (Arc<DefMap>, Arc<LocalDefMap>) {
db.crate_local_def_map(self.krate)
pub(crate) fn local_def_map(self, db: &dyn DefDatabase) -> (&DefMap, &LocalDefMap) {
let def_map = crate_local_def_map(db, self.krate);
(def_map.def_map(db), def_map.local(db))
}

pub fn krate(self) -> Crate {
Expand Down Expand Up @@ -390,26 +391,29 @@ pub struct ModuleId {
}

impl ModuleId {
pub fn def_map(self, db: &dyn DefDatabase) -> Arc<DefMap> {
pub fn def_map(self, db: &dyn DefDatabase) -> &DefMap {
match self.block {
Some(block) => db.block_def_map(block),
None => db.crate_def_map(self.krate),
Some(block) => block_def_map(db, block),
None => crate_def_map(db, self.krate),
}
}

pub(crate) fn local_def_map(self, db: &dyn DefDatabase) -> (Arc<DefMap>, Arc<LocalDefMap>) {
pub(crate) fn local_def_map(self, db: &dyn DefDatabase) -> (&DefMap, &LocalDefMap) {
match self.block {
Some(block) => (db.block_def_map(block), self.only_local_def_map(db)),
None => db.crate_local_def_map(self.krate),
Some(block) => (block_def_map(db, block), self.only_local_def_map(db)),
None => {
let def_map = crate_local_def_map(db, self.krate);
(def_map.def_map(db), def_map.local(db))
}
}
}

pub(crate) fn only_local_def_map(self, db: &dyn DefDatabase) -> Arc<LocalDefMap> {
db.crate_local_def_map(self.krate).1
pub(crate) fn only_local_def_map(self, db: &dyn DefDatabase) -> &LocalDefMap {
crate_local_def_map(db, self.krate).local(db)
}

pub fn crate_def_map(self, db: &dyn DefDatabase) -> Arc<DefMap> {
db.crate_def_map(self.krate)
pub fn crate_def_map(self, db: &dyn DefDatabase) -> &DefMap {
crate_def_map(db, self.krate)
}

pub fn krate(self) -> Crate {
Expand Down
10 changes: 5 additions & 5 deletions crates/hir-def/src/macro_expansion_tests/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,7 @@ use test_fixture::WithFixture;
use crate::{
AdtId, Lookup, ModuleDefId,
db::DefDatabase,
nameres::{DefMap, ModuleSource},
nameres::{DefMap, ModuleSource, crate_def_map},
src::HasSource,
test_db::TestDB,
tt::TopSubtree,
Expand All @@ -49,7 +49,7 @@ use crate::{
fn check_errors(#[rust_analyzer::rust_fixture] ra_fixture: &str, expect: Expect) {
let db = TestDB::with_files(ra_fixture);
let krate = db.fetch_test_crate();
let def_map = db.crate_def_map(krate);
let def_map = crate_def_map(&db, krate);
let errors = def_map
.modules()
.flat_map(|module| module.1.scope.all_macro_calls())
Expand Down Expand Up @@ -113,7 +113,7 @@ pub fn identity_when_valid(_attr: TokenStream, item: TokenStream) -> TokenStream

let (body, sm) = db.body_with_source_map(body);
if let Some(it) =
body.blocks(db).find_map(|block| resolve(db, &block.1, ast_id, ast_ptr))
body.blocks(db).find_map(|block| resolve(db, block.1, ast_id, ast_ptr))
{
return Some(it);
}
Expand All @@ -127,7 +127,7 @@ pub fn identity_when_valid(_attr: TokenStream, item: TokenStream) -> TokenStream

let db = TestDB::with_files_extra_proc_macros(ra_fixture, extra_proc_macros);
let krate = db.fetch_test_crate();
let def_map = db.crate_def_map(krate);
let def_map = crate_def_map(&db, krate);
let local_id = DefMap::ROOT;
let source = def_map[local_id].definition_source(&db);
let source_file = match source.value {
Expand All @@ -142,7 +142,7 @@ pub fn identity_when_valid(_attr: TokenStream, item: TokenStream) -> TokenStream
let ast_id = db.ast_id_map(source.file_id).ast_id(&macro_call_node);
let ast_id = InFile::new(source.file_id, ast_id);
let ptr = InFile::new(source.file_id, AstPtr::new(&macro_call_node));
let macro_call_id = resolve(&db, &def_map, ast_id, ptr)
let macro_call_id = resolve(&db, def_map, ast_id, ptr)
.unwrap_or_else(|| panic!("unable to find semantic macro call {macro_call_node}"));
let expansion_result = db.parse_macro_expansion(macro_call_id);
expansions.push((macro_call_node.clone(), expansion_result));
Expand Down
Loading