Skip to content
Open
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
2 changes: 1 addition & 1 deletion crates/hir-def/src/builtin_derive.rs
Original file line number Diff line number Diff line change
Expand Up @@ -111,7 +111,7 @@ impl BuiltinDeriveImplMethod {
pub fn trait_method(
self,
db: &dyn SourceDatabase,
impl_: BuiltinDeriveImplId,
impl_: BuiltinDeriveImplId<'_>,
) -> Option<FunctionId> {
let loc = impl_.loc(db);
let lang_items = crate::lang_item::lang_items(db, loc.krate(db));
Expand Down
255 changes: 134 additions & 121 deletions crates/hir-def/src/dyn_map.rs
Original file line number Diff line number Diff line change
Expand Up @@ -9,8 +9,8 @@
//! # use hir_def::dyn_map::DynMap;
//! # use hir_def::dyn_map::Key;
//! // keys define submaps of a `DynMap`
//! const STRING_TO_U32: Key<String, u32> = Key::new();
//! const U32_TO_VEC: Key<u32, Vec<bool>> = Key::new();
//! const STRING_TO_U32: StaticKey<String, u32> = Key::new();
//! const U32_TO_VEC: StaticKey<u32, Vec<bool>> = Key::new();
//!
//! // Note: concrete type, no type params!
//! let mut map = DynMap::new();
Expand All @@ -25,175 +25,188 @@
//! a coincidence.

pub mod keys {
use std::marker::PhantomData;

use either::Either;
use hir_expand::{MacroCallId, attrs::AttrId};
use rustc_hash::FxHashMap;
use syntax::{AstNode, AstPtr, ast};
use syntax::ast;

use crate::{
BlockId, BuiltinDeriveImplId, ConstId, EnumId, EnumVariantId, ExternBlockId, ExternCrateId,
FieldId, FunctionId, ImplId, LifetimeParamId, Macro2Id, MacroRulesId, ProcMacroId,
StaticId, StructId, TraitId, TypeAliasId, TypeOrConstParamId, UnionId, UseId,
dyn_map::{DynMap, Policy},
dyn_map::{Key, ValueTrait},
};

pub type Key<K, V> = crate::dyn_map::Key<AstPtr<K>, V, AstPtrPolicy<K, V>>;

pub const BLOCK: Key<ast::BlockExpr, BlockId> = Key::new();
pub const FUNCTION: Key<ast::Fn, FunctionId> = Key::new();
pub const CONST: Key<ast::Const, ConstId> = Key::new();
pub const STATIC: Key<ast::Static, StaticId> = Key::new();
pub const TYPE_ALIAS: Key<ast::TypeAlias, TypeAliasId> = Key::new();
pub const IMPL: Key<ast::Impl, ImplId> = Key::new();
pub const EXTERN_BLOCK: Key<ast::ExternBlock, ExternBlockId> = Key::new();
pub const TRAIT: Key<ast::Trait, TraitId> = Key::new();
pub const STRUCT: Key<ast::Struct, StructId> = Key::new();
pub const UNION: Key<ast::Union, UnionId> = Key::new();
pub const ENUM: Key<ast::Enum, EnumId> = Key::new();
pub const EXTERN_CRATE: Key<ast::ExternCrate, ExternCrateId> = Key::new();
pub const USE: Key<ast::Use, UseId> = Key::new();

pub const ENUM_VARIANT: Key<ast::Variant, EnumVariantId> = Key::new();
pub const TUPLE_FIELD: Key<ast::TupleField, FieldId> = Key::new();
pub const RECORD_FIELD: Key<ast::RecordField, FieldId> = Key::new();
pub const TYPE_PARAM: Key<ast::TypeParam, TypeOrConstParamId> = Key::new();
pub const CONST_PARAM: Key<ast::ConstParam, TypeOrConstParamId> = Key::new();
pub const LIFETIME_PARAM: Key<ast::LifetimeParam, LifetimeParamId> = Key::new();

pub const MACRO_RULES: Key<ast::MacroRules, MacroRulesId> = Key::new();
pub const MACRO2: Key<ast::MacroDef, Macro2Id> = Key::new();
pub const PROC_MACRO: Key<ast::Fn, ProcMacroId> = Key::new();
pub const MACRO_CALL: Key<ast::MacroCall, MacroCallId> = Key::new();
pub const ATTR_MACRO_CALL: Key<ast::Item, MacroCallId> = Key::new();
pub const DERIVE_MACRO_CALL: Key<
ast::Meta,
(
AttrId,
/* derive() */ MacroCallId,
/* actual derive macros */
Box<[Option<Either<MacroCallId, BuiltinDeriveImplId>>]>,
),
> = 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<AST, ID> {
_phantom: PhantomData<(AST, ID)>,
macro_rules! declare_keys {
{
$vis:vis const $key_name:ident<$key:ty, for<$db_lt:lifetime> $value:ty $(,)?>;
$( $rest:tt )*
} => {
$vis const $key_name: Key<$key, dyn for<$db_lt> ValueTrait<$db_lt, Output = $value>> = Key::new();
declare_keys!( $($rest)* );
};
{
$vis:vis const $key_name:ident<$key:ty, $value:ty $(,)?>;
$( $rest:tt )*
} => {
declare_keys! {
$vis const $key_name<$key, for<'db> $value>;
$( $rest )*
}
};
// Recursion base case.
() => {};
}

impl<AST: AstNode + 'static, ID: 'static> Policy for AstPtrPolicy<AST, ID> {
type K = AstPtr<AST>;
type V = ID;
fn insert(map: &mut DynMap, key: AstPtr<AST>, value: ID) {
map.map
.entry::<FxHashMap<AstPtr<AST>, ID>>()
.or_insert_with(Default::default)
.insert(key, value);
}
fn get<'a>(map: &'a DynMap, key: &AstPtr<AST>) -> Option<&'a ID> {
map.map.get::<FxHashMap<AstPtr<AST>, ID>>()?.get(key)
}
fn is_empty(map: &DynMap) -> bool {
map.map.get::<FxHashMap<AstPtr<AST>, ID>>().is_none_or(|it| it.is_empty())
}
declare_keys! {
pub const BLOCK<ast::BlockExpr, BlockId>;
pub const FUNCTION<ast::Fn, FunctionId>;
pub const CONST<ast::Const, ConstId>;
pub const STATIC<ast::Static, StaticId>;
pub const TYPE_ALIAS<ast::TypeAlias, TypeAliasId>;
pub const IMPL<ast::Impl, ImplId>;
pub const EXTERN_BLOCK<ast::ExternBlock, ExternBlockId>;
pub const TRAIT<ast::Trait, TraitId>;
pub const STRUCT<ast::Struct, StructId>;
pub const UNION<ast::Union, UnionId>;
pub const ENUM<ast::Enum, EnumId>;
pub const EXTERN_CRATE<ast::ExternCrate, ExternCrateId>;
pub const USE<ast::Use, UseId>;

pub const ENUM_VARIANT<ast::Variant, EnumVariantId>;
pub const TUPLE_FIELD<ast::TupleField, FieldId>;
pub const RECORD_FIELD<ast::RecordField, FieldId>;
pub const TYPE_PARAM<ast::TypeParam, TypeOrConstParamId>;
pub const CONST_PARAM<ast::ConstParam, TypeOrConstParamId>;
pub const LIFETIME_PARAM<ast::LifetimeParam, LifetimeParamId>;

pub const MACRO_RULES<ast::MacroRules, MacroRulesId>;
pub const MACRO2<ast::MacroDef, Macro2Id>;
pub const PROC_MACRO<ast::Fn, ProcMacroId>;
pub const MACRO_CALL<ast::MacroCall, MacroCallId>;
pub const ATTR_MACRO_CALL<ast::Item, MacroCallId>;
pub const DERIVE_MACRO_CALL<
ast::Meta,
for<'db> (
AttrId,
/* derive() */ MacroCallId,
/* actual derive macros */
Box<[Option<Either<MacroCallId, BuiltinDeriveImplId<'db>>>]>,
),
>;
}
}

use std::{
hash::Hash,
marker::PhantomData,
ops::{Index, IndexMut},
};

use rustc_hash::FxHashMap;
use stdx::anymap::Map;

pub struct Key<K, V, P = (K, V)> {
_phantom: PhantomData<(K, V, P)>,
}

impl<K, V, P> Key<K, V, P> {
#[allow(
clippy::new_without_default,
reason = "this a const fn, so it can't be default yet. See <https://github.com/rust-lang/rust/issues/63065>"
)]
pub(crate) const fn new() -> Key<K, V, P> {
Key { _phantom: PhantomData }
}
pub trait ValueTrait<'db> {
type Output;
}

impl<K, V, P> Copy for Key<K, V, P> {}
type Value<'db, V> = <V as ValueTrait<'db>>::Output;

impl<K, V, P> Clone for Key<K, V, P> {
fn clone(&self) -> Key<K, V, P> {
*self
}
}
use syntax::{AstNode, AstPtr};

pub trait Policy {
type K;
type V;
pub type StaticKey<K, V> = Key<K, dyn for<'db> ValueTrait<'db, Output = 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>;
fn is_empty(map: &DynMap) -> bool;
pub struct Key<K, V: ?Sized> {
_phantom: PhantomData<(K, V)>,
}

impl<K: Hash + Eq + 'static, V: 'static> Policy for (K, V) {
type K = K;
type V = V;
fn insert(map: &mut DynMap, key: K, value: V) {
map.map.entry::<FxHashMap<K, V>>().or_insert_with(Default::default).insert(key, value);
}
fn get<'a>(map: &'a DynMap, key: &K) -> Option<&'a V> {
map.map.get::<FxHashMap<K, V>>()?.get(key)
impl<K: 'static, V: ?Sized> Key<K, V> {
pub(crate) const fn new() -> Key<K, V>
where
V: for<'db> ValueTrait<'db>,
Value<'static, V>: 'static,
{
Key { _phantom: PhantomData }
}
fn is_empty(map: &DynMap) -> bool {
map.map.get::<FxHashMap<K, V>>().is_none_or(|it| it.is_empty())
}

impl<K, V: ?Sized> Copy for Key<K, V> {}

impl<K, V: ?Sized> Clone for Key<K, V> {
fn clone(&self) -> Key<K, V> {
*self
}
}

#[derive(Default)]
pub struct DynMap {
pub struct DynMap<'db> {
pub(crate) map: Map,
_marker: PhantomData<&'db ()>,
}

#[repr(transparent)]
pub struct KeyMap<KEY> {
map: DynMap,
pub struct KeyMap<'db, KEY> {
map: DynMap<'db>,
_phantom: PhantomData<KEY>,
}

impl<P: Policy> KeyMap<Key<P::K, P::V, P>> {
pub fn insert(&mut self, key: P::K, value: P::V) {
P::insert(&mut self.map, key, value)
// 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.
impl<'db, K, V: ?Sized> KeyMap<'db, Key<K, V>>
where
K: AstNode + 'static,
V: for<'db_> ValueTrait<'db_>,
Value<'static, V>: 'static,
{
#[inline]
pub fn insert(&mut self, key: AstPtr<K>, value: Value<'db, V>) {
// SAFETY: We only retrieve it with lifetime `'db`.
let value = unsafe { std::mem::transmute::<Value<'db, V>, Value<'static, V>>(value) };
self.map
.map
.entry::<FxHashMap<AstPtr<K>, Value<'static, V>>>()
.or_insert_with(Default::default)
.insert(key, value);
}
pub fn get(&self, key: &P::K) -> Option<&P::V> {
P::get(&self.map, key)

#[inline]
pub fn get(&self, key: &AstPtr<K>) -> Option<&Value<'db, V>> {
let result = self.map.map.get::<FxHashMap<AstPtr<K>, Value<'static, V>>>()?.get(key);
// SAFETY: We only store with lifetime `'db`.
unsafe { std::mem::transmute::<Option<&Value<'static, V>>, Option<&Value<'db, V>>>(result) }
}

#[inline]
pub fn is_empty(&self) -> bool {
P::is_empty(&self.map)
self.map.map.get::<FxHashMap<AstPtr<K>, Value<'static, V>>>().is_none_or(|it| it.is_empty())
}
}

impl<P: Policy> Index<Key<P::K, P::V, P>> for DynMap {
type Output = KeyMap<Key<P::K, P::V, P>>;
fn index(&self, _key: Key<P::K, P::V, P>) -> &Self::Output {
// Safe due to `#[repr(transparent)]`.
unsafe { std::mem::transmute::<&DynMap, &KeyMap<Key<P::K, P::V, P>>>(self) }
impl<'db, K, V: ?Sized> Index<Key<K, V>> for DynMap<'db>
where
K: AstNode + 'static,
V: for<'db_> ValueTrait<'db_>,
Value<'static, V>: 'static,
{
type Output = KeyMap<'db, Key<K, V>>;
#[inline]
fn index(&self, _key: Key<K, V>) -> &Self::Output {
// SAFETY: Safe due to `#[repr(transparent)]`.
unsafe { std::mem::transmute::<&DynMap<'db>, &KeyMap<'db, Key<K, V>>>(self) }
}
}

impl<P: Policy> IndexMut<Key<P::K, P::V, P>> for DynMap {
fn index_mut(&mut self, _key: Key<P::K, P::V, P>) -> &mut Self::Output {
// Safe due to `#[repr(transparent)]`.
unsafe { std::mem::transmute::<&mut DynMap, &mut KeyMap<Key<P::K, P::V, P>>>(self) }
impl<'db, K, V: ?Sized> IndexMut<Key<K, V>> for DynMap<'db>
where
K: AstNode + 'static,
V: for<'db_> ValueTrait<'db_>,
Value<'static, V>: 'static,
{
#[inline]
fn index_mut(&mut self, _key: Key<K, V>) -> &mut Self::Output {
// SAFETY: Safe due to `#[repr(transparent)]`.
unsafe { std::mem::transmute::<&mut DynMap<'db>, &mut KeyMap<'db, Key<K, V>>>(self) }
}
}
2 changes: 1 addition & 1 deletion crates/hir-def/src/expr_store.rs
Original file line number Diff line number Diff line change
Expand Up @@ -587,7 +587,7 @@ impl ExpressionStore {
pub fn blocks<'a>(
&'a self,
db: &'a dyn SourceDatabase,
) -> impl Iterator<Item = (BlockId, &'a DefMap)> + 'a {
) -> impl Iterator<Item = (BlockId, &'a DefMap<'a>)> {
self.expr_only
.as_ref()
.map(|it| &*it.block_scopes)
Expand Down
2 changes: 1 addition & 1 deletion crates/hir-def/src/expr_store/expander.rs
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,7 @@ impl<'db> Expander<'db> {
pub(super) fn new(
db: &'db dyn SourceDatabase,
current_file_id: HirFileId,
def_map: &'db DefMap,
def_map: &DefMap<'_>,
) -> Expander<'db> {
let recursion_limit = def_map.recursion_limit();
let recursion_limit = if cfg!(test) {
Expand Down
2 changes: 1 addition & 1 deletion crates/hir-def/src/expr_store/lower.rs
Original file line number Diff line number Diff line change
Expand Up @@ -450,7 +450,7 @@ pub struct ExprCollector<'db> {
db: &'db dyn SourceDatabase,
cfg_options: &'db CfgOptions,
expander: Expander<'db>,
def_map: &'db DefMap,
def_map: &'db DefMap<'db>,
local_def_map: &'db LocalDefMap,
module: ModuleId,
lowering_mode: LoweringMode,
Expand Down
Loading