intuicio_framework_dynamic/
lib.rs

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
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
use intuicio_core::{
    define_native_struct,
    function::{FunctionHandle, FunctionQuery},
    object::Object,
    registry::Registry,
    types::{struct_type::NativeStructBuilder, TypeHandle, TypeQuery},
};
use intuicio_data::{shared::Shared, type_hash::TypeHash};
use std::{
    cell::{Ref, RefMut},
    collections::HashMap,
};

pub type Boolean = bool;
pub type Integer = i64;
pub type Real = f64;
pub type Text = String;
pub type Array = Vec<Reference>;
pub type Map = HashMap<Text, Reference>;

thread_local! {
    static TRANSFERRED_STRUCT_HANDLE: TypeHandle = NativeStructBuilder::new::<Transferred>().build().into_type().into_handle();
}

#[derive(Default, Clone)]
pub struct Type {
    data: Option<TypeHandle>,
}

impl Type {
    pub fn by_name(name: &str, module_name: &str, registry: &Registry) -> Option<Self> {
        Some(Self::new(registry.find_type(TypeQuery {
            name: Some(name.into()),
            module_name: Some(module_name.into()),
            ..Default::default()
        })?))
    }

    pub fn of<T: 'static>(registry: &Registry) -> Option<Self> {
        Some(Self::new(registry.find_type(TypeQuery {
            type_hash: Some(TypeHash::of::<T>()),
            ..Default::default()
        })?))
    }

    pub fn new(handle: TypeHandle) -> Self {
        Self { data: Some(handle) }
    }

    pub fn handle(&self) -> Option<&TypeHandle> {
        self.data.as_ref()
    }

    pub fn is<T: 'static>(&self) -> bool {
        self.data
            .as_ref()
            .map(|data| data.type_hash() == TypeHash::of::<T>())
            .unwrap_or(false)
    }

    pub fn is_same_as(&self, other: &Self) -> bool {
        if let (Some(this), Some(other)) = (self.data.as_ref(), other.data.as_ref()) {
            this == other
        } else {
            false
        }
    }

    pub fn type_hash(&self) -> Option<TypeHash> {
        Some(self.data.as_ref()?.type_hash())
    }
}

#[derive(Default, Clone)]
pub struct Function {
    data: Option<FunctionHandle>,
}

impl Function {
    pub fn by_name(name: &str, module_name: &str, registry: &Registry) -> Option<Self> {
        Some(Self::new(registry.find_function(FunctionQuery {
            name: Some(name.into()),
            module_name: Some(module_name.into()),
            ..Default::default()
        })?))
    }

    pub fn new(handle: FunctionHandle) -> Self {
        Self { data: Some(handle) }
    }

    pub fn handle(&self) -> Option<&FunctionHandle> {
        self.data.as_ref()
    }

    pub fn is_same_as(&self, other: &Self) -> bool {
        if let (Some(this), Some(other)) = (self.data.as_ref(), other.data.as_ref()) {
            this.signature() == other.signature()
        } else {
            false
        }
    }
}

#[derive(Default, Clone)]
pub struct Reference {
    data: Option<Shared<Object>>,
}

impl Reference {
    pub fn null() -> Self {
        Self { data: None }
    }

    pub fn is_null(&self) -> bool {
        self.data.is_none()
    }

    pub fn is_transferred(&self) -> bool {
        self.data
            .as_ref()
            .and_then(|data| data.read())
            .map(|data| data.read::<Transferred>().is_some())
            .unwrap_or_default()
    }

    pub fn is_being_written(&mut self) -> bool {
        self.data
            .as_mut()
            .map(|data| data.write().is_none())
            .unwrap_or_default()
    }

    pub fn new_boolean(value: Boolean, registry: &Registry) -> Self {
        Self::new(value, registry)
    }

    pub fn new_integer(value: Integer, registry: &Registry) -> Self {
        Self::new(value, registry)
    }

    pub fn new_real(value: Real, registry: &Registry) -> Self {
        Self::new(value, registry)
    }

    pub fn new_text(value: Text, registry: &Registry) -> Self {
        Self::new(value, registry)
    }

    pub fn new_array(value: Array, registry: &Registry) -> Self {
        Self::new(value, registry)
    }

    pub fn new_map(value: Map, registry: &Registry) -> Self {
        Self::new(value, registry)
    }

    pub fn new_type(value: Type, registry: &Registry) -> Self {
        Self::new(value, registry)
    }

    pub fn new_function(value: Function, registry: &Registry) -> Self {
        Self::new(value, registry)
    }

    pub fn new<T: 'static>(data: T, registry: &Registry) -> Self {
        let type_ = registry.find_type(TypeQuery::of::<T>()).unwrap_or_else(|| {
            panic!(
                "Could not make a reference of type: {}",
                std::any::type_name::<T>()
            )
        });
        let mut value = unsafe { Object::new_uninitialized(type_).unwrap() };
        unsafe { value.as_mut_ptr().cast::<T>().write(data) };
        Self::new_raw(value)
    }

    pub fn new_custom<T: 'static>(data: T, ty: &Type) -> Self {
        let mut value =
            unsafe { Object::new_uninitialized(ty.data.as_ref().unwrap().clone()).unwrap() };
        unsafe { value.as_mut_ptr().cast::<T>().write(data) };
        Self::new_raw(value)
    }

    pub fn new_raw(data: Object) -> Self {
        Self {
            data: Some(Shared::new(data)),
        }
    }

    pub fn new_shared(data: Shared<Object>) -> Self {
        Self { data: Some(data) }
    }

    pub fn initialized(ty: &Type) -> Self {
        Self::new_raw(Object::new(ty.data.as_ref().unwrap().clone()))
    }

    /// # Safety
    pub unsafe fn uninitialized(ty: &Type) -> Self {
        Self::new_raw(Object::new_uninitialized(ty.data.as_ref().unwrap().clone()).unwrap())
    }

    pub fn type_of(&self) -> Option<Type> {
        Some(Type::new(self.data.as_ref()?.read()?.type_handle().clone()))
    }

    pub fn read<T: 'static>(&self) -> Option<Ref<T>> {
        let result = self.data.as_ref()?.read()?;
        if result.type_handle().type_hash() == TypeHash::of::<T>() {
            Some(Ref::map(result, |data| data.read::<T>().unwrap()))
        } else {
            None
        }
    }

    pub fn write<T: 'static>(&mut self) -> Option<RefMut<T>> {
        let result = self.data.as_mut()?.write()?;
        if result.type_handle().type_hash() == TypeHash::of::<T>() {
            Some(RefMut::map(result, |data| data.write::<T>().unwrap()))
        } else {
            None
        }
    }

    pub fn read_object(&self) -> Option<Ref<Object>> {
        self.data.as_ref()?.read()
    }

    pub fn write_object(&mut self) -> Option<RefMut<Object>> {
        self.data.as_mut()?.write()
    }

    pub fn swap<T: 'static>(&mut self, data: T) -> Option<T> {
        Some(std::mem::replace(
            self.data.as_mut()?.write()?.write::<T>()?,
            data,
        ))
    }

    pub fn try_consume(self) -> Result<Object, Self> {
        match self.data {
            Some(data) => match data.try_consume() {
                Ok(data) => Ok(data),
                Err(data) => Err(Self { data: Some(data) }),
            },
            None => Err(Self::null()),
        }
    }

    pub fn references_count(&self) -> usize {
        self.data
            .as_ref()
            .map(|data| data.references_count())
            .unwrap_or(0)
    }

    pub fn does_share_reference(&self, other: &Self, consider_null: bool) -> bool {
        match (self.data.as_ref(), other.data.as_ref()) {
            (Some(this), Some(other)) => this.does_share_reference(other),
            (None, None) => consider_null,
            _ => false,
        }
    }

    /// # Safety
    pub unsafe fn transfer(&self) -> Option<Result<Object, usize>> {
        let mut data = self.data.as_ref()?.write()?;
        if let Some(data) = data.read::<Transferred>() {
            return Some(Err(data.0));
        }
        if !data.type_handle().is_send() {
            return None;
        }
        let mut object =
            Object::new_uninitialized(TRANSFERRED_STRUCT_HANDLE.with(|handle| handle.clone()))
                .unwrap();
        object
            .as_mut_ptr()
            .cast::<Transferred>()
            .write(Transferred(data.as_ptr() as usize));
        Some(Ok(std::mem::replace(&mut *data, object)))
    }
}

impl std::fmt::Debug for Reference {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self.data.as_ref() {
            Some(object) => {
                if let Some(object) = object.read() {
                    f.debug_struct("Reference").field("data", &*object).finish()
                } else {
                    f.debug_struct("Reference").field("data", &()).finish()
                }
            }
            None => f.debug_struct("Reference").finish(),
        }
    }
}

impl From<Transferable> for Reference {
    fn from(value: Transferable) -> Self {
        value.reproduce()
    }
}

#[derive(Debug)]
enum TransferableObject {
    Array {
        object: Object,
        items: Vec<Option<usize>>,
    },
    Map {
        object: Object,
        pairs: HashMap<String, Option<usize>>,
    },
    Object {
        object: Object,
        fields: HashMap<String, Option<usize>>,
    },
}

#[derive(Debug)]
enum TransferableReference {
    Array {
        reference: Reference,
        items: Vec<Option<usize>>,
    },
    Map {
        reference: Reference,
        pairs: HashMap<String, Option<usize>>,
    },
    Object {
        reference: Reference,
        fields: HashMap<String, Option<usize>>,
    },
}

impl From<TransferableObject> for TransferableReference {
    fn from(value: TransferableObject) -> Self {
        match value {
            TransferableObject::Array { object, items } => TransferableReference::Array {
                reference: Reference::new_raw(object),
                items,
            },
            TransferableObject::Map { object, pairs } => TransferableReference::Map {
                reference: Reference::new_raw(object),
                pairs,
            },
            TransferableObject::Object { object, fields } => TransferableReference::Object {
                reference: Reference::new_raw(object),
                fields,
            },
        }
    }
}

impl TransferableReference {
    fn reference(&self) -> Reference {
        match self {
            TransferableReference::Array { reference, .. }
            | TransferableReference::Map { reference, .. }
            | TransferableReference::Object { reference, .. } => reference.clone(),
        }
    }
}

/// Normally references are single-threaded, but they can be sent between threads
/// only by means of transfer mechanism. Transfer mechanism works like this:
/// For transferred reference, we construct graph of connected unpacked objects,
/// replacing their original content objects with special Transferred type, so they
/// cannot be accessed later in original thread. We send that graph and on the other
/// thread we reconstruct objects and references from that graph and return main one.
#[derive(Debug)]
pub struct Transferable {
    /// { reference's object address as its unique ID: object behind reference}
    objects: HashMap<usize, TransferableObject>,
    root: Option<usize>,
}

unsafe impl Send for Transferable {}
unsafe impl Sync for Transferable {}

impl Transferable {
    fn produce(
        value: Reference,
        objects: &mut HashMap<usize, TransferableObject>,
    ) -> Option<usize> {
        let mut object = match unsafe { value.transfer() } {
            Some(object) => match object {
                Ok(object) => object,
                Err(address) => return Some(address),
            },
            None => return None,
        };
        let address = unsafe { object.as_ptr() as usize };
        if objects.iter().any(|object| *object.0 == address) {
            return Some(address);
        }
        if let Some(array) = object.write::<Array>() {
            let items = array
                .iter_mut()
                .map(|value| Self::produce(std::mem::replace(value, Reference::null()), objects))
                .collect();
            objects.insert(address, TransferableObject::Array { object, items });
        } else if let Some(map) = object.write::<Map>() {
            let pairs = map
                .iter_mut()
                .map(|(key, value)| {
                    (
                        key.to_owned(),
                        Self::produce(std::mem::replace(value, Reference::null()), objects),
                    )
                })
                .collect();
            objects.insert(address, TransferableObject::Map { object, pairs });
        } else {
            match &*object.type_handle().clone() {
                intuicio_core::types::Type::Struct(type_) => {
                    let fields = type_
                        .fields()
                        .iter()
                        .filter_map(|field| {
                            let value = object.write_field::<Reference>(&field.name)?;
                            Some((
                                field.name.to_owned(),
                                Self::produce(std::mem::replace(value, Reference::null()), objects),
                            ))
                        })
                        .collect();
                    objects.insert(address, TransferableObject::Object { object, fields });
                }
                intuicio_core::types::Type::Enum(type_) => {
                    let discriminant = unsafe { object.as_ptr().read() };
                    if let Some(variant) = type_.find_variant_by_discriminant(discriminant) {
                        let fields = variant
                            .fields
                            .iter()
                            .filter_map(|field| {
                                let value = object.write_field::<Reference>(&field.name)?;
                                Some((
                                    field.name.to_owned(),
                                    Self::produce(
                                        std::mem::replace(value, Reference::null()),
                                        objects,
                                    ),
                                ))
                            })
                            .collect();
                        objects.insert(address, TransferableObject::Object { object, fields });
                    }
                }
            }
        }
        Some(address)
    }

    fn reproduce(self) -> Reference {
        let Some(root) = self.root else {
            return Reference::null();
        };
        let mut results = self
            .objects
            .into_iter()
            .map(|(address, object)| (address, TransferableReference::from(object)))
            .collect::<HashMap<_, _>>();
        let references = results
            .iter()
            .map(|(address, reference)| (*address, reference.reference()))
            .collect::<HashMap<_, _>>();
        for reference in results.values_mut() {
            match reference {
                TransferableReference::Array { reference, items } => {
                    if let Some(mut array) = reference.write::<Array>() {
                        for (index, value) in array.iter_mut().enumerate() {
                            if let Some(address) = items.get(index) {
                                *value = address
                                    .and_then(|address| references.get(&address).cloned())
                                    .unwrap_or_default();
                            } else {
                                *value = Reference::null();
                            }
                        }
                    }
                }
                TransferableReference::Map { reference, pairs } => {
                    if let Some(mut map) = reference.write::<Map>() {
                        for (key, value) in map.iter_mut() {
                            if let Some(address) = pairs.get(key) {
                                *value = address
                                    .and_then(|address| references.get(&address).cloned())
                                    .unwrap_or_default();
                            } else {
                                *value = Reference::null();
                            }
                        }
                    }
                }
                TransferableReference::Object { reference, fields } => {
                    if let Some(mut object) = reference.write_object() {
                        match &**object.type_handle() {
                            intuicio_core::types::Type::Struct(type_) => {
                                let names = type_
                                    .fields()
                                    .iter()
                                    .map(|field| field.name.to_owned())
                                    .collect::<Vec<_>>();
                                for name in names {
                                    if let Some(value) = object.write_field::<Reference>(&name) {
                                        if let Some(address) = fields.get(&name) {
                                            *value = address
                                                .and_then(|address| {
                                                    references.get(&address).cloned()
                                                })
                                                .unwrap_or_default();
                                        } else {
                                            *value = Reference::null();
                                        }
                                    }
                                }
                            }
                            intuicio_core::types::Type::Enum(type_) => {
                                let discriminant = unsafe { object.as_ptr().read() };
                                if let Some(variant) =
                                    type_.find_variant_by_discriminant(discriminant)
                                {
                                    let names = variant
                                        .fields
                                        .iter()
                                        .map(|field| field.name.to_owned())
                                        .collect::<Vec<_>>();
                                    for name in names {
                                        if let Some(value) = object.write_field::<Reference>(&name)
                                        {
                                            if let Some(address) = fields.get(&name) {
                                                *value = address
                                                    .and_then(|address| {
                                                        references.get(&address).cloned()
                                                    })
                                                    .unwrap_or_default();
                                            } else {
                                                *value = Reference::null();
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }
        references.get(&root).cloned().unwrap_or_default()
    }
}

impl From<Reference> for Transferable {
    fn from(value: Reference) -> Self {
        let mut objects = Default::default();
        let root = Transferable::produce(value, &mut objects);
        Self { objects, root }
    }
}

#[derive(Debug, Default)]
pub struct Transferred(usize);

pub fn install(registry: &mut Registry) {
    registry.add_type(define_native_struct! {
        registry => mod reflect struct Reference (Reference) {}
        [override_send = true]
    });
    registry.add_type(define_native_struct! {
        registry => mod reflect struct Type (Type) {}
    });
    registry.add_type(define_native_struct! {
        registry => mod reflect struct Function (Function) {}
    });
    registry.add_type(define_native_struct! {
        registry => mod math struct Boolean (Boolean) {}
    });
    registry.add_type(define_native_struct! {
        registry => mod math struct Integer (Integer) {}
    });
    registry.add_type(define_native_struct! {
        registry => mod math struct Real (Real) {}
    });
    registry.add_type(define_native_struct! {
        registry => mod math struct Text (Text) {}
    });
    registry.add_type(define_native_struct! {
        registry => mod math struct Array (Array) {}
    });
    registry.add_type(define_native_struct! {
        registry => mod math struct Map (Map) {}
    });
}

#[cfg(test)]
mod tests {
    use crate::{Integer, Reference, Transferable};
    use intuicio_core::prelude::*;
    use intuicio_derive::*;
    use std::thread::spawn;

    #[test]
    fn test_threading() {
        #[derive(IntuicioStruct, Default)]
        #[intuicio(name = "Foo", module_name = "test", override_send = true)]
        struct Foo {
            pub v: Reference,
            pub me: Reference,
        }

        #[derive(IntuicioEnum, Default)]
        #[intuicio(name = "Bar", module_name = "test", override_send = true)]
        #[repr(u8)]
        enum Bar {
            #[default]
            A,
            B(Reference),
        }

        let mut registry = Registry::default();
        crate::install(&mut registry);
        let foo_type = registry.add_type(Foo::define_struct(&registry));
        assert!(foo_type.is_send());
        let bar_type = registry.add_type(Bar::define_enum(&registry));
        assert!(bar_type.is_send());

        let mut value = Reference::new(
            Foo {
                v: Reference::new(Bar::B(Reference::new(0 as Integer, &registry)), &registry),
                me: Default::default(),
            },
            &registry,
        );
        let me = value.clone();
        value.write::<Foo>().unwrap().me = me;
        let transferable = Transferable::from(value.clone());
        assert!(value.is_transferred());

        let handle = spawn(|| {
            let mut registry = Registry::default();
            crate::install(&mut registry);
            let object = Reference::from(transferable);

            // we need to keep it in scope, because references being
            // actively written are not able to be transferred.
            {
                let mut value = object.clone();
                let mut value = value.write::<Foo>().unwrap();
                let mut value = value.v.write::<Bar>().unwrap();
                if let Bar::B(value) = &mut *value {
                    let mut value = value.write::<Integer>().unwrap();
                    while *value < 42 {
                        *value += 1;
                    }
                }
            }

            Transferable::from(object)
        });

        let object = Reference::from(handle.join().unwrap());
        assert!(!object.is_null());
        assert!(object.type_of().unwrap().is::<Foo>());
        let value = object.read::<Foo>().unwrap();
        assert!(!value.v.is_null());
        assert!(value.v.type_of().unwrap().is::<Bar>());
        if let Bar::B(value) = &*value.v.read::<Bar>().unwrap() {
            assert!(value.type_of().unwrap().is::<Integer>());
            assert_eq!(*value.read::<Integer>().unwrap(), 42);
        }
        assert!(!value.me.is_null());
        assert!(value.me.type_of().unwrap().is::<Foo>());
        assert!(value.me.does_share_reference(&object, true));
    }
}