Skip to main content

datex_core/runtime/cache/
shared_values_cache.rs

1use crate::{
2    collections::HashMap,
3    prelude::*,
4    shared_values::{
5        OwnedSharedContainer, PointerAddress, ReferenceMutability,
6        ReferencedSharedContainer, SharedContainer, SharedContainerOwnership,
7        errors::{
8            UnexpectedImmutableReferenceError,
9            UnexpectedSharedContainerOwnershipError,
10        },
11        traits::SharedContainerCommon,
12    },
13    values::{
14        core_values::callable::Callable, value_container::ValueContainer,
15    },
16};
17use core::{
18    fmt::Display,
19    hash::{Hash, Hasher},
20};
21
22/// Cache layer that stores references or owned and referenced shared containers
23#[derive(Debug, Default)]
24pub struct SharedValuesCache {
25    values: HashMap<PointerAddress, SharedContainer>,
26    callables: HashMap<u64, Callable>,
27    vecs: HashMap<usize, Box<dyn core::any::Any>>,
28}
29
30#[derive(Debug, Clone, PartialEq, Eq)]
31pub struct ValueNotFoundInCacheError(pub PointerAddress);
32
33impl Display for ValueNotFoundInCacheError {
34    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
35        write!(f, "Value not found in cache: {}", self.0)
36    }
37}
38
39#[derive(Debug, Clone, PartialEq, Eq)]
40pub enum CacheValueRetrievalError {
41    UnexpectedImmutableReference(UnexpectedImmutableReferenceError),
42    UnexpectedSharedContainerOwnership(UnexpectedSharedContainerOwnershipError),
43    ValueNotFoundInCache(ValueNotFoundInCacheError),
44}
45
46impl Display for CacheValueRetrievalError {
47    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
48        match self {
49            CacheValueRetrievalError::UnexpectedImmutableReference(err) => {
50                write!(f, "Unexpected immutable reference: {}", err)
51            }
52            CacheValueRetrievalError::UnexpectedSharedContainerOwnership(
53                err,
54            ) => {
55                write!(f, "Unexpected shared container ownership: {}", err)
56            }
57            CacheValueRetrievalError::ValueNotFoundInCache(err) => {
58                write!(f, "{}", err)
59            }
60        }
61    }
62}
63
64impl From<UnexpectedImmutableReferenceError> for CacheValueRetrievalError {
65    fn from(error: UnexpectedImmutableReferenceError) -> Self {
66        CacheValueRetrievalError::UnexpectedImmutableReference(error)
67    }
68}
69
70impl From<ValueNotFoundInCacheError> for CacheValueRetrievalError {
71    fn from(error: ValueNotFoundInCacheError) -> Self {
72        CacheValueRetrievalError::ValueNotFoundInCache(error)
73    }
74}
75
76impl From<UnexpectedSharedContainerOwnershipError>
77    for CacheValueRetrievalError
78{
79    fn from(error: UnexpectedSharedContainerOwnershipError) -> Self {
80        CacheValueRetrievalError::UnexpectedSharedContainerOwnership(error)
81    }
82}
83
84impl SharedValuesCache {
85    /// Creates a new SharedValuesCache and populates it with the provided shared containers.
86    /// Assumes that all provided containers have unique pointer addresses.
87    pub fn new(values: Vec<SharedContainer>) -> Self {
88        SharedValuesCache {
89            values: values
90                .into_iter()
91                .map(|container| (container.pointer_address(), container))
92                .collect(),
93            callables: HashMap::new(),
94            vecs: HashMap::new(),
95        }
96    }
97
98    /// Stores a shared container in the cache, indexed by its pointer address.
99    /// If a container already exists at the address, the container with the maximum ownership is kept.
100    pub fn store_shared_container(&mut self, container: SharedContainer) {
101        if let Some(existing) = self.values.get(&container.pointer_address())
102            && existing.ownership() > container.ownership()
103        {
104            return;
105        }
106        self.values.insert(container.pointer_address(), container);
107    }
108
109    /// Stores a callable in the cache and returns its hash value.
110    /// TODO: use different hash and HashMap<hash, callable> to reduce collisions?
111    pub fn store_callable(&mut self, callable: Callable) -> u64 {
112        let mut hasher = default_hasher();
113        callable.hash(&mut hasher);
114        let hash = hasher.finish();
115        self.callables.insert(hash, callable);
116        hash
117    }
118
119    pub fn store_vec<T: 'static>(&mut self, vec: Vec<T>) -> usize {
120        let ptr = vec.as_ptr() as usize;
121        self.vecs.insert(ptr, Box::new(vec));
122
123        ptr
124    }
125
126    /// Removes a stored vector from the cache based on its handle.
127    pub fn remove_stored_vec(&mut self, handle: usize) {
128        self.vecs.remove(&handle);
129    }
130
131    /// Retrieves a callable from the cache based on its hash value.
132    pub fn get_callable(&self, hash: u64) -> Option<Callable> {
133        self.callables.get(&hash).cloned()
134    }
135
136    /// Removes a callable from the cache based on its hash value.
137    pub fn remove_callable_with_hash(&mut self, hash: u64) {
138        self.callables.remove(&hash);
139    }
140
141    /// Removes the shared container for the given pointer address from the cache, if it exists.
142    pub fn remove_shared_container(
143        &mut self,
144        pointer_address: &PointerAddress,
145    ) {
146        self.values.remove(pointer_address);
147    }
148
149    /// Tries to take an owned shared container from the cache for the given pointer address.
150    /// If the container for the address is not an owned shared container, or if there is no container for the address, None is returned and the cache is not modified.
151    /// If an owned shared container is found for the address, it is replaced with a reference in the cache and the owned container is returned
152    pub fn try_take_owned_shared_container(
153        &mut self,
154        pointer_address: &PointerAddress,
155    ) -> Result<OwnedSharedContainer, CacheValueRetrievalError> {
156        match self.values.get(pointer_address) {
157            Some(container) => {
158                match container {
159                    SharedContainer::Owned(container) => {
160                        // replace owned with reference in cache and return owned
161                        match self.values.insert(
162                            pointer_address.clone(),
163                            SharedContainer::Referenced(
164                                container.derive_with_max_mutability(),
165                            ),
166                        ) {
167                            Some(SharedContainer::Owned(owned_container)) => {
168                                Ok(owned_container)
169                            }
170                            _ => unreachable!(),
171                        }
172                    }
173                    SharedContainer::Referenced(reference) => {
174                        Err(UnexpectedSharedContainerOwnershipError {
175                            actual: SharedContainerOwnership::Referenced(
176                                reference.reference_mutability(),
177                            ),
178                            expected: SharedContainerOwnership::Owned,
179                        }
180                        .into())
181                    }
182                }
183            }
184            _ => Err(ValueNotFoundInCacheError(pointer_address.clone()).into()),
185        }
186    }
187
188    pub fn try_get_shared_container(
189        &self,
190        pointer_address: &PointerAddress,
191    ) -> Result<&SharedContainer, ValueNotFoundInCacheError> {
192        self.values
193            .get(pointer_address)
194            .ok_or(ValueNotFoundInCacheError(pointer_address.clone()))
195    }
196
197    /// Tries to get a mutable reference to a shared container from the cache at the given pointer address.
198    /// If the container for the address is not in the cache, a [ValueNotFoundInCacheError] is returned.
199    pub fn try_get_shared_container_reference(
200        &self,
201        pointer_address: &PointerAddress,
202        mutability: ReferenceMutability,
203    ) -> Result<ReferencedSharedContainer, CacheValueRetrievalError> {
204        match mutability {
205            ReferenceMutability::Mutable => {
206                self.try_get_shared_container_mutable_reference(pointer_address)
207            }
208            ReferenceMutability::Immutable => Ok(self
209                .try_get_shared_container_immutable_reference(
210                    pointer_address,
211                )?),
212        }
213    }
214
215    /// Tries to get a mutable reference to a shared container from the cache at the given pointer address.
216    /// If the container for the address is not in the cache, a [ValueNotFoundInCacheError] is returned.
217    /// If the container cannot be accessed as a mutable reference, an [UnexpectedImmutableReferenceError] error is returned.
218    pub fn try_get_shared_container_mutable_reference(
219        &self,
220        pointer_address: &PointerAddress,
221    ) -> Result<ReferencedSharedContainer, CacheValueRetrievalError> {
222        Ok(self
223            .values
224            .get(pointer_address)
225            .ok_or(ValueNotFoundInCacheError(pointer_address.clone()))?
226            .try_derive_mutable_reference()?)
227    }
228
229    /// Tries to get an immutable reference to a shared container from the cache at the given pointer address.
230    /// If the container for the address is not in the cache, a [ValueNotFoundInCacheError] is returned.
231    pub fn try_get_shared_container_immutable_reference(
232        &self,
233        pointer_address: &PointerAddress,
234    ) -> Result<ReferencedSharedContainer, ValueNotFoundInCacheError> {
235        Ok(self
236            .values
237            .get(pointer_address)
238            .ok_or(ValueNotFoundInCacheError(pointer_address.clone()))?
239            .derive_immutable_reference())
240    }
241
242    /// Tries to get a shared container from the cache at the given pointer address with the specified ownership.
243    /// If the container for the address is not in the cache, or if the container cannot be accessed with the specified ownership, a [CacheValueRetrievalError] is returned.
244    pub fn try_get_shared_container_with_ownership(
245        &mut self,
246        pointer_address: &PointerAddress,
247        ownership: SharedContainerOwnership,
248    ) -> Result<SharedContainer, CacheValueRetrievalError> {
249        match ownership {
250            SharedContainerOwnership::Owned => self
251                .try_take_owned_shared_container(pointer_address)
252                .map(SharedContainer::Owned),
253            SharedContainerOwnership::Referenced(
254                ReferenceMutability::Mutable,
255            ) => self
256                .try_get_shared_container_mutable_reference(pointer_address)
257                .map(SharedContainer::Referenced),
258            SharedContainerOwnership::Referenced(
259                ReferenceMutability::Immutable,
260            ) => Ok(self
261                .try_get_shared_container_immutable_reference(pointer_address)
262                .map(SharedContainer::Referenced)?),
263        }
264    }
265    pub fn has_address_with_ownership(
266        &self,
267        pointer_address: &PointerAddress,
268        ownership: SharedContainerOwnership,
269    ) -> bool {
270        self.values
271            .get(pointer_address)
272            .is_some_and(|container| container.ownership() >= ownership)
273    }
274}
275
276#[cfg(feature = "decompiler")]
277impl Display for SharedValuesCache {
278    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
279        use crate::decompiler::{ast_to_source_code::value_to_source_code, *};
280
281        writeln!(f, "Values:")?;
282        for (address, value) in &self.values {
283            writeln!(
284                f,
285                "  {}: {}",
286                address,
287                value_to_source_code(
288                    &ValueContainer::Shared(
289                        value.clone_with_move_indicator_if_owned()
290                    ),
291                    DecompileOptions::default()
292                )
293            )?;
294        }
295        Ok(())
296    }
297}