datex-core 0.0.13

The DATEX Core Rust implementation
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
use crate::{
    collections::{HashMap, HashSet},
    datex_registry::get_impls_for,
    dif::deserialize_with_serde_context::DeserializeWithSerdeContext,
    prelude::*,
    shared_values::{
        PointerAddress, ReferenceMutability, ReferencedSharedContainer,
        SelfOwnedPointerAddress, SharedContainer, SharedContainerMutability,
        base_shared_value_container::BaseSharedValueContainer,
        traits::SharedContainerCommon,
        weak_shared_container::WeakSharedContainer,
    },
    traits::convert_value::ConvertValue,
    types::{
        entities::entity_type_definition::{
            EntityTypeDefinition,
            dyn_deserialize::{DeFn, de_as},
        },
        entity_type::EntityType,
        r#type::Type,
        type_definition::TypeDefinition,
    },
    values::{
        core_value::CoreValue,
        core_value_with_classification::CoreValueWithClassification,
        value::Value, value_container::ValueContainer,
    },
};
use core::{any::TypeId, fmt::Display, ops::Deref};

pub enum SharedTypeReservation {
    Existing(EntityType),
    New(EntityType),
}

#[derive(Debug, Default)]
pub struct SharedReferencesCache {
    /// References to owned values that are currently referenced and required by remote endpoints
    owned_values: HashMap<PointerAddress, ReferencedSharedContainer>,
    /// Weak references to remote values that this endpoint is currently subscribed to and receives updates for
    remote_values: HashMap<PointerAddress, WeakSharedContainer>,
    /// Set of TypeIds of structural types that are currently being resolved to prevent recursion
    resolving_structural_types: HashSet<TypeId>,
}

impl SharedReferencesCache {
    /// Registers a remote shared container in the cache.
    /// This method should be called for shared containers that this endpoint is currently subscribed to and receives updates for.
    /// If the reference is already registered (has a PointerAddress), the existing address is returned and no new registration is done.
    /// The reference is stored as a weak reference, so it will be dropped when there are no more strong references to it.
    /// TODO: call remove on Rc drop!
    pub fn register_remote_shared_container(
        &mut self,
        container: &ReferencedSharedContainer,
    ) {
        let pointer_address = container.pointer_address();
        // check if reference is already registered (if it has an address, we assume it is registered)
        self.remote_values
            .entry(pointer_address)
            .or_insert_with(|| container.downgrade());
    }

    /// Registers an owned shared container in the cache.
    /// This method should be called for shared containers that this endpoint owns and is responsible for.
    /// If the reference is already registered (has a PointerAddress), the existing address is returned and no new registration is done.
    /// The reference is stored as a strong reference, so it will not be dropped until it is explicitly removed from the cache.
    pub fn register_owned_shared_container(
        &mut self,
        container: &ReferencedSharedContainer,
    ) {
        let pointer_address = container.pointer_address();
        // check if reference is already registered (if it has an address, we assume it is registered)
        self.owned_values
            .entry(pointer_address)
            .or_insert_with(|| container.clone());
    }

    /// Removes a remote shared container from the cache.
    pub fn remove_remote_shared_container(
        &mut self,
        pointer_address: &PointerAddress,
    ) {
        self.remote_values.remove(pointer_address);
    }

    /// Removes an owned shared container from the cache.
    pub fn remove_owned_shared_container(
        &mut self,
        pointer_address: &PointerAddress,
    ) {
        self.owned_values.remove(pointer_address);
    }

    /// Returns a reference stored at the given PointerAddress, if it exists.
    pub fn get_reference(
        &self,
        pointer_address: &PointerAddress,
    ) -> Option<ReferencedSharedContainer> {
        self.get_owned_reference(pointer_address)
            .cloned()
            .or_else(|| self.get_remote_reference(pointer_address))
    }

    /// Returns a reference to an owned shared container stored at the given PointerAddress, if it exists.
    pub fn get_owned_reference(
        &self,
        pointer_address: &PointerAddress,
    ) -> Option<&ReferencedSharedContainer> {
        self.owned_values.get(pointer_address)
    }

    /// Returns a reference to a remote shared container stored at the given PointerAddress, if it exists and is still alive.
    pub fn get_remote_reference(
        &self,
        pointer_address: &PointerAddress,
    ) -> Option<ReferencedSharedContainer> {
        self.remote_values
            .get(pointer_address)
            .and_then(|weak_ref| weak_ref.upgrade())
    }

    /// Checks if a reference with the given PointerAddress exists in memory.
    pub fn has_reference(&self, pointer_address: &PointerAddress) -> bool {
        self.owned_values.contains_key(pointer_address)
            || self
                .remote_values
                .get(pointer_address)
                .is_some_and(|weak_ref| weak_ref.upgrade().is_some())
    }

    /// Returns an iterator over all currently stored references in the cache, both owned and remote.
    pub fn values(&self) -> impl Iterator<Item = ReferencedSharedContainer> {
        gen move {
            for value in self.owned_values() {
                yield value.clone();
            }
            for value in self.remote_values() {
                yield value;
            }
        }
    }

    /// Returns an iterator over all currently stored owned references in the cache.
    pub fn owned_values(
        &self,
    ) -> impl Iterator<Item = &ReferencedSharedContainer> {
        self.owned_values.values()
    }

    /// Returns an iterator over all currently stored remote references in the cache.
    pub fn remote_values(
        &self,
    ) -> impl Iterator<Item = ReferencedSharedContainer> {
        self.remote_values
            .values()
            .filter_map(|weak_ref| weak_ref.upgrade())
    }

    /// Returns an iterator over all currently stored remote weak references in the cache.
    pub fn remote_values_weak(
        &self,
    ) -> impl Iterator<Item = &WeakSharedContainer> {
        self.remote_values.values()
    }

    /// Tries to get a shared container containing an EntityTypeDefinition from the cache for the given SelfOwnedPointerAddress.
    /// Returns the [EntityType] if found, or None if not found
    pub fn try_get_shared_type(
        &mut self,
        address: SelfOwnedPointerAddress,
    ) -> Option<EntityType> {
        // return existing type container stored in cache
        if let Some(value) = self
            .get_owned_reference(&PointerAddress::SelfOwned(address.clone()))
        {
            match value.value_container().deref() {
                ValueContainer::Local(Value::Core(
                    CoreValueWithClassification {
                        inner: CoreValue::EntityTypeDefinition(_),
                        ..
                    },
                )) => {}
                _ => {
                    panic!(
                        "Expected a shared container containing an EntityTypeDefinition, but found a different type for address: {}",
                        address
                    );
                }
            }
            // SAFETY: We have checked that the value is a SharedContainer containing an EntityTypeDefinition.
            unsafe {
                Some(EntityType::new_unchecked(SharedContainer::Referenced(
                    value.clone(),
                )))
            }
        } else {
            None
        }
    }

    /// Registers a new shared container type in the cache for the given address and returns the registered container as a [EntityType].
    ///
    /// # Safety
    /// The caller must ensure that the address is not used anywhere else.
    pub unsafe fn register_shared_type(
        &mut self,
        address: SelfOwnedPointerAddress,
        entity_type_definition: EntityTypeDefinition,
    ) -> EntityType {
        // create new shared container
        let shared_type_container = unsafe {
            EntityType::new_unchecked(
                SharedContainer::new_owned_with_inferred_allowed_type_unsafe(
                    CoreValue::EntityTypeDefinition(entity_type_definition),
                    SharedContainerMutability::Immutable,
                    address,
                ),
            )
        };

        // register shared container in cache
        self.register_owned_shared_container(
            &shared_type_container
                .clone()
                .to_shared_container()
                .derive_reference_with_max_mutability(),
        );
        shared_type_container
    }

    /// Generates or retrieves an [EntityType] for the given type T, using the provided address and generation function.
    /// If the type is already registered in the cache, it returns the existing [EntityType].
    /// If not, it generates a new [EntityTypeDefinition] using the provided closure and registers it in the cache.
    /// # Safety
    /// The caller must ensure that the address is unique.
    pub unsafe fn init_entity_type<T>(
        &mut self,
        address: PointerAddress,
        generate: impl FnOnce(&mut Self) -> (String, TypeDefinition),
    ) -> EntityType
    where
        T: for<'de> DeserializeWithSerdeContext<'de> + ConvertValue + 'static,
    {
        match unsafe { self.reserve_shared_type(address.clone()) } {
            SharedTypeReservation::Existing(ty) => ty,
            // if not found, create new def and register in cache
            SharedTypeReservation::New(ty) => {
                self.with_entity_boundary(|cache| {
                    let (name, type_definition) = generate(cache);

                    let impls = get_impls_for::<T>(cache);

                    let definition =
                        EntityTypeDefinition::new_with_impls_and_deserialize(
                            type_definition,
                            name,
                            impls,
                            Some(de_as::<T> as DeFn),
                        );

                    cache.finish_shared_type(address.clone(), definition);

                    ty
                })
            }
        }
    }

    /// Reserves a shared container type in the cache for the given address and returns a [SharedTypeReservation].
    ///
    /// # Safety
    /// The caller must ensure that the address is unique.
    pub unsafe fn reserve_shared_type(
        &mut self,
        address: PointerAddress,
    ) -> SharedTypeReservation {
        if let Some(existing) = self.get_owned_reference(&address) {
            return SharedTypeReservation::Existing(unsafe {
                EntityType::new_unchecked(SharedContainer::Referenced(
                    existing.clone(),
                ))
            });
        }
        let shared_container = match address {
            PointerAddress::SelfOwned(self_owned_address) => unsafe {
                SharedContainer::new_owned_with_inferred_allowed_type_unsafe(
                    CoreValue::Uninitialized,
                    SharedContainerMutability::Immutable,
                    self_owned_address,
                )
            },
            // used for builtin type references only
            PointerAddress::Remote(remote_address) => {
                // assert that this is actually a builtin address
                assert!(
                    remote_address.is_builtin(),
                    "Only builtin addresses can be used for remote shared containers, but got: {}",
                    remote_address
                );
                SharedContainer::Referenced(unsafe {
                    ReferencedSharedContainer::try_new_remote_from_base_container(
                        BaseSharedValueContainer::new_with_inferred_allowed_type(
                            CoreValue::Uninitialized,
                            SharedContainerMutability::Immutable,
                        ),
                        remote_address,
                        ReferenceMutability::Immutable,
                    )
                }.unwrap())
            }
        };
        self.register_owned_shared_container(
            &shared_container.derive_immutable_reference(),
        );
        // NOTE: this treats shared_container as if it already contains a type value.
        // So accessing it as a type before finish_shared_type is called will panic.
        SharedTypeReservation::New(unsafe {
            EntityType::new_unchecked(shared_container)
        })
    }

    /// Finishes the registration of a shared container type in the cache for the given address and definition.
    /// This method should be called after reserve_shared_type to set the actual EntityTypeDefinition for
    /// the reserved shared container. It will panic if the type is not in the cache or if it is already initialized.
    pub fn finish_shared_type(
        &mut self,
        address: PointerAddress,
        definition: EntityTypeDefinition,
    ) {
        let ty = self
            .get_owned_reference(&address)
            .unwrap_or_else(|| panic!("Type is not in cache: {}", address));
        if !ty.value_container().is_uninitialized() {
            panic!("Type is already initialized: {}", address);
        }
        *ty.value_container_mut() = ValueContainer::Local(
            CoreValue::EntityTypeDefinition(definition).into(),
        );
    }

    /// Resolves a structural type for the given type T, ensuring that recursive types are not allowed.
    pub fn resolve_structural_type<T, F>(&mut self, f: F) -> Type
    where
        T: 'static,
        F: FnOnce(&mut Self) -> Type,
    {
        let id = TypeId::of::<T>();
        if !self.resolving_structural_types.insert(id) {
            // FIXME: allo recursive structural types
            panic!(
                "Can not use recursive structural DATEX types: {}",
                core::any::type_name::<T>(),
            );
        }
        let ty = f(self);
        self.resolving_structural_types.remove(&id);
        ty
    }

    /// Executes the given closure with a temporary entity boundary,
    /// which allows resolving structural types within the closure without affecting the outer context.
    pub fn with_entity_boundary<F, R>(&mut self, f: F) -> R
    where
        F: FnOnce(&mut Self) -> R,
    {
        let previous = core::mem::take(&mut self.resolving_structural_types);
        let result = f(self);
        self.resolving_structural_types = previous;
        result
    }
}

#[cfg(feature = "decompiler")]
impl Display for SharedReferencesCache {
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        use crate::decompiler::{ast_to_source_code::value_to_source_code, *};

        // print owned values
        writeln!(f, "Owned Values:")?;
        for (address, value) in &self.owned_values {
            writeln!(
                f,
                "  {}: {}",
                address,
                value_to_source_code(
                    &ValueContainer::Shared(SharedContainer::Referenced(
                        value.clone()
                    )),
                    DecompileOptions::default()
                )
            )?;
        }
        // print remote values
        writeln!(f, "Remote Values:")?;
        for (address, weak_value) in &self.remote_values {
            let value = weak_value.upgrade();
            if let Some(value) = value {
                writeln!(
                    f,
                    "  {}: {}",
                    address,
                    value_to_source_code(
                        &ValueContainer::Shared(SharedContainer::Referenced(
                            value
                        )),
                        DecompileOptions::default()
                    )
                )?;
            } else {
                writeln!(f, "  {}: <dropped>", address)?;
            }
        }
        Ok(())
    }
}