From 8c86963d47953045f2f33ee6620d305a6589641e Mon Sep 17 00:00:00 2001 From: Aleksey Kladov Date: Thu, 5 Dec 2019 23:34:12 +0100 Subject: DynMap This might, or might not help us to reduce boilerplate associated with plumbing values from analysis to the IDE layer --- crates/ra_hir_def/src/child_by_source.rs | 139 +++++++++++++++ crates/ra_hir_def/src/child_from_source.rs | 276 ----------------------------- crates/ra_hir_def/src/dyn_map.rs | 108 +++++++++++ crates/ra_hir_def/src/keys.rs | 48 +++++ crates/ra_hir_def/src/lib.rs | 5 +- 5 files changed, 299 insertions(+), 277 deletions(-) create mode 100644 crates/ra_hir_def/src/child_by_source.rs delete mode 100644 crates/ra_hir_def/src/child_from_source.rs create mode 100644 crates/ra_hir_def/src/dyn_map.rs create mode 100644 crates/ra_hir_def/src/keys.rs (limited to 'crates/ra_hir_def/src') diff --git a/crates/ra_hir_def/src/child_by_source.rs b/crates/ra_hir_def/src/child_by_source.rs new file mode 100644 index 000000000..a3574a9db --- /dev/null +++ b/crates/ra_hir_def/src/child_by_source.rs @@ -0,0 +1,139 @@ +//! When *constructing* `hir`, we start at some parent syntax node and recursively +//! lower the children. +//! +//! This modules allows one to go in the opposite direction: start with a syntax +//! node for a *child*, and get its hir. + +use either::Either; + +use crate::{ + db::DefDatabase, + dyn_map::DynMap, + keys, + src::{HasChildSource, HasSource}, + AssocItemId, EnumId, EnumVariantId, ImplId, Lookup, ModuleDefId, ModuleId, StructFieldId, + TraitId, VariantId, +}; + +pub trait ChildBySource { + fn child_by_source(&self, db: &impl DefDatabase) -> DynMap; +} + +impl ChildBySource for TraitId { + fn child_by_source(&self, db: &impl DefDatabase) -> DynMap { + let mut res = DynMap::default(); + + let data = db.trait_data(*self); + for (_name, item) in data.items.iter() { + match *item { + AssocItemId::FunctionId(func) => { + let src = func.lookup(db).source(db); + res[keys::FUNCTION].insert(src, func) + } + AssocItemId::ConstId(konst) => { + let src = konst.lookup(db).source(db); + res[keys::CONST].insert(src, konst) + } + AssocItemId::TypeAliasId(ty) => { + let src = ty.lookup(db).source(db); + res[keys::TYPE_ALIAS].insert(src, ty) + } + } + } + + res + } +} + +impl ChildBySource for ImplId { + fn child_by_source(&self, db: &impl DefDatabase) -> DynMap { + let mut res = DynMap::default(); + + let data = db.impl_data(*self); + for &item in data.items.iter() { + match item { + AssocItemId::FunctionId(func) => { + let src = func.lookup(db).source(db); + res[keys::FUNCTION].insert(src, func) + } + AssocItemId::ConstId(konst) => { + let src = konst.lookup(db).source(db); + res[keys::CONST].insert(src, konst) + } + AssocItemId::TypeAliasId(ty) => { + let src = ty.lookup(db).source(db); + res[keys::TYPE_ALIAS].insert(src, ty) + } + } + } + + res + } +} + +impl ChildBySource for ModuleId { + fn child_by_source(&self, db: &impl DefDatabase) -> DynMap { + let mut res = DynMap::default(); + + let crate_def_map = db.crate_def_map(self.krate); + for item in crate_def_map[self.local_id].scope.declarations() { + match item { + ModuleDefId::FunctionId(func) => { + let src = func.lookup(db).source(db); + res[keys::FUNCTION].insert(src, func) + } + ModuleDefId::ConstId(konst) => { + let src = konst.lookup(db).source(db); + res[keys::CONST].insert(src, konst) + } + ModuleDefId::StaticId(statik) => { + let src = statik.lookup(db).source(db); + res[keys::STATIC].insert(src, statik) + } + ModuleDefId::TypeAliasId(ty) => { + let src = ty.lookup(db).source(db); + res[keys::TYPE_ALIAS].insert(src, ty) + } + _ => (), + } + } + + res + } +} + +impl ChildBySource for VariantId { + fn child_by_source(&self, db: &impl DefDatabase) -> DynMap { + let mut res = DynMap::default(); + + let arena_map = self.child_source(db); + let arena_map = arena_map.as_ref(); + for (local_id, source) in arena_map.value.iter() { + let id = StructFieldId { parent: *self, local_id }; + match source { + Either::Left(source) => { + res[keys::TUPLE_FIELD].insert(arena_map.with_value(source.clone()), id) + } + Either::Right(source) => { + res[keys::RECORD_FIELD].insert(arena_map.with_value(source.clone()), id) + } + } + } + res + } +} + +impl ChildBySource for EnumId { + fn child_by_source(&self, db: &impl DefDatabase) -> DynMap { + let mut res = DynMap::default(); + + let arena_map = self.child_source(db); + let arena_map = arena_map.as_ref(); + for (local_id, source) in arena_map.value.iter() { + let id = EnumVariantId { parent: *self, local_id }; + res[keys::ENUM_VARIANT].insert(arena_map.with_value(source.clone()), id) + } + + res + } +} diff --git a/crates/ra_hir_def/src/child_from_source.rs b/crates/ra_hir_def/src/child_from_source.rs deleted file mode 100644 index 37d4b7870..000000000 --- a/crates/ra_hir_def/src/child_from_source.rs +++ /dev/null @@ -1,276 +0,0 @@ -//! When *constructing* `hir`, we start at some parent syntax node and recursively -//! lower the children. -//! -//! This modules allows one to go in the opposite direction: start with a syntax -//! node for a *child*, and get its hir. - -use either::Either; -use hir_expand::InFile; -use ra_syntax::{ast, AstNode, AstPtr}; - -use crate::{ - db::DefDatabase, - src::{HasChildSource, HasSource}, - AssocItemId, ConstId, EnumId, EnumVariantId, FunctionId, ImplId, Lookup, ModuleDefId, ModuleId, - StaticId, StructFieldId, TraitId, TypeAliasId, VariantId, -}; - -pub trait ChildFromSource { - fn child_from_source( - &self, - db: &impl DefDatabase, - child_source: InFile, - ) -> Option; -} - -impl ChildFromSource for TraitId { - fn child_from_source( - &self, - db: &impl DefDatabase, - child_source: InFile, - ) -> Option { - let data = db.trait_data(*self); - data.items - .iter() - .filter_map(|(_, item)| match item { - AssocItemId::FunctionId(it) => Some(*it), - _ => None, - }) - .find(|func| { - let source = func.lookup(db).source(db); - same_source(&source, &child_source) - }) - } -} - -impl ChildFromSource for ImplId { - fn child_from_source( - &self, - db: &impl DefDatabase, - child_source: InFile, - ) -> Option { - let data = db.impl_data(*self); - data.items - .iter() - .filter_map(|item| match item { - AssocItemId::FunctionId(it) => Some(*it), - _ => None, - }) - .find(|func| { - let source = func.lookup(db).source(db); - same_source(&source, &child_source) - }) - } -} - -impl ChildFromSource for ModuleId { - fn child_from_source( - &self, - db: &impl DefDatabase, - child_source: InFile, - ) -> Option { - let crate_def_map = db.crate_def_map(self.krate); - let res = crate_def_map[self.local_id] - .scope - .declarations() - .filter_map(|item| match item { - ModuleDefId::FunctionId(it) => Some(it), - _ => None, - }) - .find(|func| { - let source = func.lookup(db).source(db); - same_source(&source, &child_source) - }); - res - } -} - -impl ChildFromSource for TraitId { - fn child_from_source( - &self, - db: &impl DefDatabase, - child_source: InFile, - ) -> Option { - let data = db.trait_data(*self); - data.items - .iter() - .filter_map(|(_, item)| match item { - AssocItemId::ConstId(it) => Some(*it), - _ => None, - }) - .find(|func| { - let source = func.lookup(db).source(db); - same_source(&source, &child_source) - }) - } -} - -impl ChildFromSource for ImplId { - fn child_from_source( - &self, - db: &impl DefDatabase, - child_source: InFile, - ) -> Option { - let data = db.impl_data(*self); - data.items - .iter() - .filter_map(|item| match item { - AssocItemId::ConstId(it) => Some(*it), - _ => None, - }) - .find(|func| { - let source = func.lookup(db).source(db); - same_source(&source, &child_source) - }) - } -} - -impl ChildFromSource for ModuleId { - fn child_from_source( - &self, - db: &impl DefDatabase, - child_source: InFile, - ) -> Option { - let crate_def_map = db.crate_def_map(self.krate); - let res = crate_def_map[self.local_id] - .scope - .declarations() - .filter_map(|item| match item { - ModuleDefId::ConstId(it) => Some(it), - _ => None, - }) - .find(|func| { - let source = func.lookup(db).source(db); - same_source(&source, &child_source) - }); - res - } -} - -impl ChildFromSource for TraitId { - fn child_from_source( - &self, - db: &impl DefDatabase, - child_source: InFile, - ) -> Option { - let data = db.trait_data(*self); - data.items - .iter() - .filter_map(|(_, item)| match item { - AssocItemId::TypeAliasId(it) => Some(*it), - _ => None, - }) - .find(|func| { - let source = func.lookup(db).source(db); - same_source(&source, &child_source) - }) - } -} - -impl ChildFromSource for ImplId { - fn child_from_source( - &self, - db: &impl DefDatabase, - child_source: InFile, - ) -> Option { - let data = db.impl_data(*self); - data.items - .iter() - .filter_map(|item| match item { - AssocItemId::TypeAliasId(it) => Some(*it), - _ => None, - }) - .find(|func| { - let source = func.lookup(db).source(db); - same_source(&source, &child_source) - }) - } -} - -impl ChildFromSource for ModuleId { - fn child_from_source( - &self, - db: &impl DefDatabase, - child_source: InFile, - ) -> Option { - let crate_def_map = db.crate_def_map(self.krate); - let res = crate_def_map[self.local_id] - .scope - .declarations() - .filter_map(|item| match item { - ModuleDefId::TypeAliasId(it) => Some(it), - _ => None, - }) - .find(|func| { - let source = func.lookup(db).source(db); - same_source(&source, &child_source) - }); - res - } -} - -impl ChildFromSource for ModuleId { - fn child_from_source( - &self, - db: &impl DefDatabase, - child_source: InFile, - ) -> Option { - let crate_def_map = db.crate_def_map(self.krate); - let res = crate_def_map[self.local_id] - .scope - .declarations() - .filter_map(|item| match item { - ModuleDefId::StaticId(it) => Some(it), - _ => None, - }) - .find(|func| { - let source = func.lookup(db).source(db); - same_source(&source, &child_source) - }); - res - } -} - -impl ChildFromSource> for VariantId { - fn child_from_source( - &self, - db: &impl DefDatabase, - child_source: InFile>, - ) -> Option { - let arena_map = self.child_source(db); - let (local_id, _) = arena_map.as_ref().value.iter().find(|(_local_id, source)| { - child_source.file_id == arena_map.file_id - && match (source, &child_source.value) { - (Either::Left(a), Either::Left(b)) => AstPtr::new(a) == AstPtr::new(b), - (Either::Right(a), Either::Right(b)) => AstPtr::new(a) == AstPtr::new(b), - _ => false, - } - })?; - Some(StructFieldId { parent: *self, local_id }) - } -} - -impl ChildFromSource for EnumId { - fn child_from_source( - &self, - db: &impl DefDatabase, - child_source: InFile, - ) -> Option { - let arena_map = self.child_source(db); - let (local_id, _) = arena_map.as_ref().value.iter().find(|(_local_id, source)| { - child_source.file_id == arena_map.file_id - && AstPtr::new(*source) == AstPtr::new(&child_source.value) - })?; - Some(EnumVariantId { parent: *self, local_id }) - } -} - -/// XXX: AST Nodes and SyntaxNodes have identity equality semantics: nodes are -/// equal if they point to exactly the same object. -/// -/// In general, we do not guarantee that we have exactly one instance of a -/// syntax tree for each file. We probably should add such guarantee, but, for -/// the time being, we will use identity-less AstPtr comparison. -fn same_source(s1: &InFile, s2: &InFile) -> bool { - s1.as_ref().map(AstPtr::new) == s2.as_ref().map(AstPtr::new) -} diff --git a/crates/ra_hir_def/src/dyn_map.rs b/crates/ra_hir_def/src/dyn_map.rs new file mode 100644 index 000000000..6f269d7b0 --- /dev/null +++ b/crates/ra_hir_def/src/dyn_map.rs @@ -0,0 +1,108 @@ +//! This module defines a `DynMap` -- a container for heterogeneous maps. +//! +//! This means that `DynMap` stores a bunch of hash maps inside, and those maps +//! can be of different types. +//! +//! It is used like this: +//! +//! ``` +//! // keys define submaps of a `DynMap` +//! const STRING_TO_U32: Key = Key::new(); +//! const U32_TO_VEC: Key> = Key::new(); +//! +//! // Note: concrete type, no type params! +//! let mut map = DynMap::new(); +//! +//! // To access a specific map, index the `DynMap` by `Key`: +//! map[STRING_TO_U32].insert("hello".to_string(), 92); +//! let value = map[U32_TO_VEC].get(92); +//! assert!(value.is_none()); +//! ``` +//! +//! This is a work of fiction. Any similarities to Kotlin's `BindingContext` are +//! a coincidence. +use std::{ + hash::Hash, + marker::PhantomData, + ops::{Index, IndexMut}, +}; + +use anymap::Map; +use rustc_hash::FxHashMap; + +pub struct Key { + _phantom: PhantomData<(K, V, P)>, +} + +impl Key { + pub(crate) const fn new() -> Key { + Key { _phantom: PhantomData } + } +} + +impl Copy for Key {} + +impl Clone for Key { + fn clone(&self) -> Key { + *self + } +} + +pub trait Policy { + type K; + type V; + + fn insert(map: &mut DynMap, key: Self::K, value: Self::V); + fn get<'a>(map: &'a DynMap, key: &Self::K) -> Option<&'a Self::V>; +} + +impl Policy for (K, V) { + type K = K; + type V = V; + fn insert(map: &mut DynMap, key: K, value: V) { + map.map.entry::>().or_insert_with(Default::default).insert(key, value); + } + fn get<'a>(map: &'a DynMap, key: &K) -> Option<&'a V> { + map.map.get::>()?.get(key) + } +} + +pub struct DynMap { + pub(crate) map: Map, +} + +impl Default for DynMap { + fn default() -> Self { + DynMap { map: Map::new() } + } +} + +#[repr(transparent)] +pub struct KeyMap { + map: DynMap, + _phantom: PhantomData, +} + +impl KeyMap> { + pub fn insert(&mut self, key: P::K, value: P::V) { + P::insert(&mut self.map, key, value) + } + pub fn get(&self, key: &P::K) -> Option<&P::V> { + P::get(&self.map, key) + } +} + +impl Index> for DynMap { + type Output = KeyMap>; + fn index(&self, _key: Key) -> &Self::Output { + // Safe due to `#[repr(transparent)]`. + unsafe { std::mem::transmute::<&DynMap, &KeyMap>>(self) } + } +} + +impl IndexMut> for DynMap { + fn index_mut(&mut self, _key: Key) -> &mut Self::Output { + // Safe due to `#[repr(transparent)]`. + unsafe { std::mem::transmute::<&mut DynMap, &mut KeyMap>>(self) } + } +} diff --git a/crates/ra_hir_def/src/keys.rs b/crates/ra_hir_def/src/keys.rs new file mode 100644 index 000000000..447b7e3ba --- /dev/null +++ b/crates/ra_hir_def/src/keys.rs @@ -0,0 +1,48 @@ +//! keys to be used with `DynMap` + +use std::marker::PhantomData; + +use hir_expand::InFile; +use ra_syntax::{ast, AstNode, AstPtr}; +use rustc_hash::FxHashMap; + +use crate::{ + dyn_map::{DynMap, Policy}, + ConstId, EnumVariantId, FunctionId, StaticId, StructFieldId, TypeAliasId, +}; + +type Key = crate::dyn_map::Key, V, AstPtrPolicy>; + +pub const FUNCTION: Key = Key::new(); +pub const CONST: Key = Key::new(); +pub const STATIC: Key = Key::new(); +pub const ENUM_VARIANT: Key = Key::new(); +pub const TYPE_ALIAS: Key = Key::new(); +pub const TUPLE_FIELD: Key = Key::new(); +pub const RECORD_FIELD: Key = Key::new(); + +/// XXX: AST Nodes and SyntaxNodes have identity equality semantics: nodes are +/// equal if they point to exactly the same object. +/// +/// In general, we do not guarantee that we have exactly one instance of a +/// syntax tree for each file. We probably should add such guarantee, but, for +/// the time being, we will use identity-less AstPtr comparison. +pub struct AstPtrPolicy { + _phantom: PhantomData<(AST, ID)>, +} + +impl Policy for AstPtrPolicy { + type K = InFile; + type V = ID; + fn insert(map: &mut DynMap, key: InFile, value: ID) { + let key = key.as_ref().map(AstPtr::new); + map.map + .entry::>, ID>>() + .or_insert_with(Default::default) + .insert(key, value); + } + fn get<'a>(map: &'a DynMap, key: &InFile) -> Option<&'a ID> { + let key = key.as_ref().map(AstPtr::new); + map.map.get::>, ID>>()?.get(&key) + } +} diff --git a/crates/ra_hir_def/src/lib.rs b/crates/ra_hir_def/src/lib.rs index e02622f62..68e66d276 100644 --- a/crates/ra_hir_def/src/lib.rs +++ b/crates/ra_hir_def/src/lib.rs @@ -16,6 +16,9 @@ pub mod builtin_type; pub mod diagnostics; pub mod per_ns; +pub mod dyn_map; +pub mod keys; + pub mod adt; pub mod data; pub mod generics; @@ -30,7 +33,7 @@ mod trace; pub mod nameres; pub mod src; -pub mod child_from_source; +pub mod child_by_source; #[cfg(test)] mod test_db; -- cgit v1.2.3