datex_core/runtime/cache/
shared_references_cache.rs1use 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 owned_values: HashMap<PointerAddress, ReferencedSharedContainer>,
40 remote_values: HashMap<PointerAddress, WeakSharedContainer>,
42 resolving_structural_types: HashSet<TypeId>,
44}
45
46impl SharedReferencesCache {
47 pub fn register_remote_shared_container(
53 &mut self,
54 container: &ReferencedSharedContainer,
55 ) {
56 let pointer_address = container.pointer_address();
57 self.remote_values
59 .entry(pointer_address)
60 .or_insert_with(|| container.downgrade());
61 }
62
63 pub fn register_owned_shared_container(
68 &mut self,
69 container: &ReferencedSharedContainer,
70 ) {
71 let pointer_address = container.pointer_address();
72 self.owned_values
74 .entry(pointer_address)
75 .or_insert_with(|| container.clone());
76 }
77
78 pub fn remove_remote_shared_container(
80 &mut self,
81 pointer_address: &PointerAddress,
82 ) {
83 self.remote_values.remove(pointer_address);
84 }
85
86 pub fn remove_owned_shared_container(
88 &mut self,
89 pointer_address: &PointerAddress,
90 ) {
91 self.owned_values.remove(pointer_address);
92 }
93
94 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 pub fn get_owned_reference(
106 &self,
107 pointer_address: &PointerAddress,
108 ) -> Option<&ReferencedSharedContainer> {
109 self.owned_values.get(pointer_address)
110 }
111
112 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 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 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 pub fn owned_values(
145 &self,
146 ) -> impl Iterator<Item = &ReferencedSharedContainer> {
147 self.owned_values.values()
148 }
149
150 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 pub fn remote_values_weak(
161 &self,
162 ) -> impl Iterator<Item = &WeakSharedContainer> {
163 self.remote_values.values()
164 }
165
166 pub fn try_get_shared_type(
169 &mut self,
170 address: SelfOwnedPointerAddress,
171 ) -> Option<EntityType> {
172 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 unsafe {
192 Some(EntityType::new_unchecked(SharedContainer::Referenced(
193 value.clone(),
194 )))
195 }
196 } else {
197 None
198 }
199 }
200
201 pub unsafe fn register_shared_type(
206 &mut self,
207 address: SelfOwnedPointerAddress,
208 entity_type_definition: EntityTypeDefinition,
209 ) -> EntityType {
210 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 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 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 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 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 PointerAddress::Remote(remote_address) => {
294 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 SharedTypeReservation::New(unsafe {
318 EntityType::new_unchecked(shared_container)
319 })
320 }
321
322 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 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 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 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 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 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}