Skip to main content

datex_core/runtime/cache/
shared_references_cache.rs

1use crate::{
2    collections::{HashMap, HashSet},
3    datex_registry::get_impls_for,
4    dif::deserialize_with_serde_context::DeserializeWithSerdeContext,
5    prelude::*,
6    shared_values::{
7        PointerAddress, ReferenceMutability, ReferencedSharedContainer,
8        SelfOwnedPointerAddress, SharedContainer, SharedContainerMutability,
9        base_shared_value_container::BaseSharedValueContainer,
10        traits::SharedContainerCommon,
11        weak_shared_container::WeakSharedContainer,
12    },
13    traits::convert_value::ConvertValue,
14    types::{
15        entities::entity_type_definition::{
16            EntityTypeDefinition,
17            dyn_deserialize::{DeFn, de_as},
18        },
19        entity_type::EntityType,
20        r#type::Type,
21        type_definition::TypeDefinition,
22    },
23    values::{
24        core_value::CoreValue,
25        core_value_with_classification::CoreValueWithClassification,
26        value::Value, value_container::ValueContainer,
27    },
28};
29use core::{any::TypeId, fmt::Display, ops::Deref};
30
31pub enum SharedTypeReservation {
32    Existing(EntityType),
33    New(EntityType),
34}
35
36#[derive(Debug, Default)]
37pub struct SharedReferencesCache {
38    /// References to owned values that are currently referenced and required by remote endpoints
39    owned_values: HashMap<PointerAddress, ReferencedSharedContainer>,
40    /// Weak references to remote values that this endpoint is currently subscribed to and receives updates for
41    remote_values: HashMap<PointerAddress, WeakSharedContainer>,
42    /// Set of TypeIds of structural types that are currently being resolved to prevent recursion
43    resolving_structural_types: HashSet<TypeId>,
44}
45
46impl SharedReferencesCache {
47    /// Registers a remote shared container in the cache.
48    /// This method should be called for shared containers that this endpoint is currently subscribed to and receives updates for.
49    /// If the reference is already registered (has a PointerAddress), the existing address is returned and no new registration is done.
50    /// The reference is stored as a weak reference, so it will be dropped when there are no more strong references to it.
51    /// TODO: call remove on Rc drop!
52    pub fn register_remote_shared_container(
53        &mut self,
54        container: &ReferencedSharedContainer,
55    ) {
56        let pointer_address = container.pointer_address();
57        // check if reference is already registered (if it has an address, we assume it is registered)
58        self.remote_values
59            .entry(pointer_address)
60            .or_insert_with(|| container.downgrade());
61    }
62
63    /// Registers an owned shared container in the cache.
64    /// This method should be called for shared containers that this endpoint owns and is responsible for.
65    /// If the reference is already registered (has a PointerAddress), the existing address is returned and no new registration is done.
66    /// The reference is stored as a strong reference, so it will not be dropped until it is explicitly removed from the cache.
67    pub fn register_owned_shared_container(
68        &mut self,
69        container: &ReferencedSharedContainer,
70    ) {
71        let pointer_address = container.pointer_address();
72        // check if reference is already registered (if it has an address, we assume it is registered)
73        self.owned_values
74            .entry(pointer_address)
75            .or_insert_with(|| container.clone());
76    }
77
78    /// Removes a remote shared container from the cache.
79    pub fn remove_remote_shared_container(
80        &mut self,
81        pointer_address: &PointerAddress,
82    ) {
83        self.remote_values.remove(pointer_address);
84    }
85
86    /// Removes an owned shared container from the cache.
87    pub fn remove_owned_shared_container(
88        &mut self,
89        pointer_address: &PointerAddress,
90    ) {
91        self.owned_values.remove(pointer_address);
92    }
93
94    /// Returns a reference stored at the given PointerAddress, if it exists.
95    pub fn get_reference(
96        &self,
97        pointer_address: &PointerAddress,
98    ) -> Option<ReferencedSharedContainer> {
99        self.get_owned_reference(pointer_address)
100            .cloned()
101            .or_else(|| self.get_remote_reference(pointer_address))
102    }
103
104    /// Returns a reference to an owned shared container stored at the given PointerAddress, if it exists.
105    pub fn get_owned_reference(
106        &self,
107        pointer_address: &PointerAddress,
108    ) -> Option<&ReferencedSharedContainer> {
109        self.owned_values.get(pointer_address)
110    }
111
112    /// Returns a reference to a remote shared container stored at the given PointerAddress, if it exists and is still alive.
113    pub fn get_remote_reference(
114        &self,
115        pointer_address: &PointerAddress,
116    ) -> Option<ReferencedSharedContainer> {
117        self.remote_values
118            .get(pointer_address)
119            .and_then(|weak_ref| weak_ref.upgrade())
120    }
121
122    /// Checks if a reference with the given PointerAddress exists in memory.
123    pub fn has_reference(&self, pointer_address: &PointerAddress) -> bool {
124        self.owned_values.contains_key(pointer_address)
125            || self
126                .remote_values
127                .get(pointer_address)
128                .is_some_and(|weak_ref| weak_ref.upgrade().is_some())
129    }
130
131    /// Returns an iterator over all currently stored references in the cache, both owned and remote.
132    pub fn values(&self) -> impl Iterator<Item = ReferencedSharedContainer> {
133        gen move {
134            for value in self.owned_values() {
135                yield value.clone();
136            }
137            for value in self.remote_values() {
138                yield value;
139            }
140        }
141    }
142
143    /// Returns an iterator over all currently stored owned references in the cache.
144    pub fn owned_values(
145        &self,
146    ) -> impl Iterator<Item = &ReferencedSharedContainer> {
147        self.owned_values.values()
148    }
149
150    /// Returns an iterator over all currently stored remote references in the cache.
151    pub fn remote_values(
152        &self,
153    ) -> impl Iterator<Item = ReferencedSharedContainer> {
154        self.remote_values
155            .values()
156            .filter_map(|weak_ref| weak_ref.upgrade())
157    }
158
159    /// Returns an iterator over all currently stored remote weak references in the cache.
160    pub fn remote_values_weak(
161        &self,
162    ) -> impl Iterator<Item = &WeakSharedContainer> {
163        self.remote_values.values()
164    }
165
166    /// Tries to get a shared container containing an EntityTypeDefinition from the cache for the given SelfOwnedPointerAddress.
167    /// Returns the [EntityType] if found, or None if not found
168    pub fn try_get_shared_type(
169        &mut self,
170        address: SelfOwnedPointerAddress,
171    ) -> Option<EntityType> {
172        // return existing type container stored in cache
173        if let Some(value) = self
174            .get_owned_reference(&PointerAddress::SelfOwned(address.clone()))
175        {
176            match value.value_container().deref() {
177                ValueContainer::Local(Value::Core(
178                    CoreValueWithClassification {
179                        inner: CoreValue::EntityTypeDefinition(_),
180                        ..
181                    },
182                )) => {}
183                _ => {
184                    panic!(
185                        "Expected a shared container containing an EntityTypeDefinition, but found a different type for address: {}",
186                        address
187                    );
188                }
189            }
190            // SAFETY: We have checked that the value is a SharedContainer containing an EntityTypeDefinition.
191            unsafe {
192                Some(EntityType::new_unchecked(SharedContainer::Referenced(
193                    value.clone(),
194                )))
195            }
196        } else {
197            None
198        }
199    }
200
201    /// Registers a new shared container type in the cache for the given address and returns the registered container as a [EntityType].
202    ///
203    /// # Safety
204    /// The caller must ensure that the address is not used anywhere else.
205    pub unsafe fn register_shared_type(
206        &mut self,
207        address: SelfOwnedPointerAddress,
208        entity_type_definition: EntityTypeDefinition,
209    ) -> EntityType {
210        // create new shared container
211        let shared_type_container = unsafe {
212            EntityType::new_unchecked(
213                SharedContainer::new_owned_with_inferred_allowed_type_unsafe(
214                    CoreValue::EntityTypeDefinition(entity_type_definition),
215                    SharedContainerMutability::Immutable,
216                    address,
217                ),
218            )
219        };
220
221        // register shared container in cache
222        self.register_owned_shared_container(
223            &shared_type_container
224                .clone()
225                .to_shared_container()
226                .derive_reference_with_max_mutability(),
227        );
228        shared_type_container
229    }
230
231    /// Generates or retrieves an [EntityType] for the given type T, using the provided address and generation function.
232    /// If the type is already registered in the cache, it returns the existing [EntityType].
233    /// If not, it generates a new [EntityTypeDefinition] using the provided closure and registers it in the cache.
234    /// # Safety
235    /// The caller must ensure that the address is unique.
236    pub unsafe fn init_entity_type<T>(
237        &mut self,
238        address: PointerAddress,
239        generate: impl FnOnce(&mut Self) -> (String, TypeDefinition),
240    ) -> EntityType
241    where
242        T: for<'de> DeserializeWithSerdeContext<'de> + ConvertValue + 'static,
243    {
244        match unsafe { self.reserve_shared_type(address.clone()) } {
245            SharedTypeReservation::Existing(ty) => ty,
246            // if not found, create new def and register in cache
247            SharedTypeReservation::New(ty) => {
248                self.with_entity_boundary(|cache| {
249                    let (name, type_definition) = generate(cache);
250
251                    let impls = get_impls_for::<T>(cache);
252
253                    let definition =
254                        EntityTypeDefinition::new_with_impls_and_deserialize(
255                            type_definition,
256                            name,
257                            impls,
258                            Some(de_as::<T> as DeFn),
259                        );
260
261                    cache.finish_shared_type(address.clone(), definition);
262
263                    ty
264                })
265            }
266        }
267    }
268
269    /// Reserves a shared container type in the cache for the given address and returns a [SharedTypeReservation].
270    ///
271    /// # Safety
272    /// The caller must ensure that the address is unique.
273    pub unsafe fn reserve_shared_type(
274        &mut self,
275        address: PointerAddress,
276    ) -> SharedTypeReservation {
277        if let Some(existing) = self.get_owned_reference(&address) {
278            return SharedTypeReservation::Existing(unsafe {
279                EntityType::new_unchecked(SharedContainer::Referenced(
280                    existing.clone(),
281                ))
282            });
283        }
284        let shared_container = match address {
285            PointerAddress::SelfOwned(self_owned_address) => unsafe {
286                SharedContainer::new_owned_with_inferred_allowed_type_unsafe(
287                    CoreValue::Uninitialized,
288                    SharedContainerMutability::Immutable,
289                    self_owned_address,
290                )
291            },
292            // used for builtin type references only
293            PointerAddress::Remote(remote_address) => {
294                // assert that this is actually a builtin address
295                assert!(
296                    remote_address.is_builtin(),
297                    "Only builtin addresses can be used for remote shared containers, but got: {}",
298                    remote_address
299                );
300                SharedContainer::Referenced(unsafe {
301                    ReferencedSharedContainer::try_new_remote_from_base_container(
302                        BaseSharedValueContainer::new_with_inferred_allowed_type(
303                            CoreValue::Uninitialized,
304                            SharedContainerMutability::Immutable,
305                        ),
306                        remote_address,
307                        ReferenceMutability::Immutable,
308                    )
309                }.unwrap())
310            }
311        };
312        self.register_owned_shared_container(
313            &shared_container.derive_immutable_reference(),
314        );
315        // NOTE: this treats shared_container as if it already contains a type value.
316        // So accessing it as a type before finish_shared_type is called will panic.
317        SharedTypeReservation::New(unsafe {
318            EntityType::new_unchecked(shared_container)
319        })
320    }
321
322    /// Finishes the registration of a shared container type in the cache for the given address and definition.
323    /// This method should be called after reserve_shared_type to set the actual EntityTypeDefinition for
324    /// the reserved shared container. It will panic if the type is not in the cache or if it is already initialized.
325    pub fn finish_shared_type(
326        &mut self,
327        address: PointerAddress,
328        definition: EntityTypeDefinition,
329    ) {
330        let ty = self
331            .get_owned_reference(&address)
332            .unwrap_or_else(|| panic!("Type is not in cache: {}", address));
333        if !ty.value_container().is_uninitialized() {
334            panic!("Type is already initialized: {}", address);
335        }
336        *ty.value_container_mut() = ValueContainer::Local(
337            CoreValue::EntityTypeDefinition(definition).into(),
338        );
339    }
340
341    /// Resolves a structural type for the given type T, ensuring that recursive types are not allowed.
342    pub fn resolve_structural_type<T, F>(&mut self, f: F) -> Type
343    where
344        T: 'static,
345        F: FnOnce(&mut Self) -> Type,
346    {
347        let id = TypeId::of::<T>();
348        if !self.resolving_structural_types.insert(id) {
349            // FIXME: allo recursive structural types
350            panic!(
351                "Can not use recursive structural DATEX types: {}",
352                core::any::type_name::<T>(),
353            );
354        }
355        let ty = f(self);
356        self.resolving_structural_types.remove(&id);
357        ty
358    }
359
360    /// Executes the given closure with a temporary entity boundary,
361    /// which allows resolving structural types within the closure without affecting the outer context.
362    pub fn with_entity_boundary<F, R>(&mut self, f: F) -> R
363    where
364        F: FnOnce(&mut Self) -> R,
365    {
366        let previous = core::mem::take(&mut self.resolving_structural_types);
367        let result = f(self);
368        self.resolving_structural_types = previous;
369        result
370    }
371}
372
373#[cfg(feature = "decompiler")]
374impl Display for SharedReferencesCache {
375    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
376        use crate::decompiler::{ast_to_source_code::value_to_source_code, *};
377
378        // print owned values
379        writeln!(f, "Owned Values:")?;
380        for (address, value) in &self.owned_values {
381            writeln!(
382                f,
383                "  {}: {}",
384                address,
385                value_to_source_code(
386                    &ValueContainer::Shared(SharedContainer::Referenced(
387                        value.clone()
388                    )),
389                    DecompileOptions::default()
390                )
391            )?;
392        }
393        // print remote values
394        writeln!(f, "Remote Values:")?;
395        for (address, weak_value) in &self.remote_values {
396            let value = weak_value.upgrade();
397            if let Some(value) = value {
398                writeln!(
399                    f,
400                    "  {}: {}",
401                    address,
402                    value_to_source_code(
403                        &ValueContainer::Shared(SharedContainer::Referenced(
404                            value
405                        )),
406                        DecompileOptions::default()
407                    )
408                )?;
409            } else {
410                writeln!(f, "  {}: <dropped>", address)?;
411            }
412        }
413        Ok(())
414    }
415}