datex-core 0.0.12

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
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
use crate::{
    core_compiler::value_compiler::append_instruction,
    global::{
        operators::AssignmentOperator,
        protocol_structures::{
            injected_values::InjectedValueDeclaration,
            instructions::Instruction,
        },
        type_instruction_codes::{
            TypeLocalOrShared, TypeMutabilityCode, TypeOwnershipCode,
        },
    },
    prelude::*,
    shared_values::{
        PointerAddress, ReferenceMutability, RemotePointerAddress,
        SelfOwnedPointerAddress, SharedContainerMutability,
    },
    types::type_definition_with_metadata::TypeMetadata,
};
use alloc::string::FromUtf8Error;
use binrw::{
    BinRead, BinResult, BinWrite, Endian,
    io::{Cursor, Read, Seek, Write},
    meta::{EndianKind, ReadEndian},
};
use cfg_if::cfg_if;
use core::{fmt::Display, ops::AddAssign};
use modular_bitfield::{bitfield, prelude::B4};

#[derive(BinRead, BinWrite, Clone, Debug, PartialEq)]
#[brw(little)]
pub struct Int8Data(pub i8);

#[derive(BinRead, BinWrite, Clone, Debug, PartialEq)]
#[brw(little)]
pub struct Int16Data(pub i16);

#[derive(BinRead, BinWrite, Clone, Debug, PartialEq)]
#[brw(little)]
pub struct Int32Data(pub i32);

#[derive(BinRead, BinWrite, Clone, Debug, PartialEq)]
#[brw(little)]
pub struct Int64Data(pub i64);

#[derive(BinRead, BinWrite, Clone, Debug, PartialEq)]
#[brw(little)]
pub struct Int128Data(pub i128);

#[derive(BinRead, BinWrite, Clone, Debug, PartialEq)]
#[brw(little)]
pub struct UInt8Data(pub u8);

#[derive(BinRead, BinWrite, Clone, Debug, PartialEq)]
#[brw(little)]
pub struct UInt16Data(pub u16);

#[derive(BinRead, BinWrite, Clone, Debug, PartialEq)]
#[brw(little)]
pub struct UInt32Data(pub u32);

#[derive(BinRead, BinWrite, Clone, Debug, PartialEq)]
#[brw(little)]
pub struct UInt64Data(pub u64);

#[derive(BinRead, BinWrite, Clone, Debug, PartialEq)]
#[brw(little)]
pub struct UInt128Data(pub u128);

#[derive(BinRead, BinWrite, Clone, Debug, PartialEq)]
#[brw(little)]
pub struct Float32Data(pub f32);

#[derive(BinRead, BinWrite, Clone, Debug, PartialEq)]
#[brw(little)]
pub struct Float64Data(pub f64);

#[derive(BinRead, BinWrite, Clone, Debug, PartialEq)]
#[brw(little)]
pub struct FloatAsInt16Data(pub i16);

#[derive(BinRead, BinWrite, Clone, Debug, PartialEq)]
#[brw(little)]
pub struct FloatAsInt32Data(pub i32);

#[derive(BinRead, BinWrite, Clone, Debug, PartialEq)]
#[brw(little)]
pub struct ShortTextDataRaw {
    pub length: u8,
    #[br(count = length)]
    pub text: Vec<u8>,
}
#[derive(Clone, Debug, PartialEq)]
pub struct ShortTextData(pub String);

impl From<&ShortTextData> for ShortTextDataRaw {
    fn from(value: &ShortTextData) -> Self {
        let bytes = value.0.as_bytes();

        Self {
            length: bytes.len() as u8,
            text: bytes.to_vec(),
        }
    }
}

impl TryFrom<ShortTextDataRaw> for ShortTextData {
    type Error = FromUtf8Error;
    fn try_from(raw: ShortTextDataRaw) -> Result<Self, Self::Error> {
        let string = String::from_utf8(raw.text)?;
        Ok(ShortTextData(string))
    }
}

impl BinWrite for ShortTextData {
    type Args<'a> = ();

    fn write_options<W: Write + Seek>(
        &self,
        writer: &mut W,
        endian: Endian,
        _: Self::Args<'_>,
    ) -> BinResult<()> {
        let raw = ShortTextDataRaw::from(self);
        raw.write_options(writer, endian, ())
    }
}

impl BinRead for ShortTextData {
    type Args<'a> = ();

    fn read_options<R: Read + Seek>(
        reader: &mut R,
        endian: Endian,
        _: Self::Args<'_>,
    ) -> BinResult<Self> {
        let raw = ShortTextDataRaw::read_options(reader, endian, ())?;
        raw.try_into().map_err(|_| binrw::Error::AssertFail {
            pos: reader.stream_position().unwrap_or(0),
            message: "Invalid UTF-8 string".to_string(),
        })
    }
}

impl ReadEndian for ShortTextData {
    const ENDIAN: EndianKind = EndianKind::Endian(Endian::Little);
}

#[derive(BinRead, BinWrite, Clone, Debug, PartialEq)]
#[brw(little)]
pub struct TaggedValue {
    pub(crate) tag: ShortTextData,
    #[br(map = |x: u8| x != 0)]
    #[bw(map = |b: &bool| if *b { 1u8 } else { 0u8 })]
    pub(crate) is_empty: bool,
}

#[derive(BinRead, BinWrite, Clone, Debug, PartialEq)]
#[brw(little)]
pub struct TextDataRaw {
    pub length: u32,
    #[br(count = length)]
    pub text: Vec<u8>,
}

#[derive(Clone, Debug, PartialEq)]
pub struct TextData(pub String);

impl From<String> for TextData {
    fn from(value: String) -> Self {
        TextData(value)
    }
}
impl From<&str> for TextData {
    fn from(value: &str) -> Self {
        TextData(value.to_string())
    }
}

impl From<&TextData> for TextDataRaw {
    fn from(value: &TextData) -> Self {
        let bytes = value.0.as_bytes();

        Self {
            length: bytes.len() as u32,
            text: bytes.to_vec(),
        }
    }
}

impl TryFrom<TextDataRaw> for TextData {
    type Error = FromUtf8Error;
    fn try_from(raw: TextDataRaw) -> Result<Self, Self::Error> {
        let string = String::from_utf8(raw.text)?;
        Ok(TextData(string))
    }
}

impl BinWrite for TextData {
    type Args<'a> = ();

    fn write_options<W: Write + Seek>(
        &self,
        writer: &mut W,
        endian: Endian,
        _: Self::Args<'_>,
    ) -> BinResult<()> {
        let raw = TextDataRaw::from(self);
        raw.write_options(writer, endian, ())
    }
}

impl BinRead for TextData {
    type Args<'a> = ();

    fn read_options<R: Read + Seek>(
        reader: &mut R,
        endian: Endian,
        _: Self::Args<'_>,
    ) -> BinResult<Self> {
        let raw = TextDataRaw::read_options(reader, endian, ())?;
        raw.try_into().map_err(|_| binrw::Error::AssertFail {
            pos: reader.stream_position().unwrap_or(0),
            message: "Invalid UTF-8 string".to_string(),
        })
    }
}

impl ReadEndian for TextData {
    const ENDIAN: EndianKind = EndianKind::Endian(Endian::Little);
}

#[derive(BinRead, BinWrite, Clone, Debug, PartialEq)]
#[brw(little)]
pub struct ShortListData {
    pub element_count: u8,
}

#[derive(BinRead, BinWrite, Clone, Debug, PartialEq)]
#[brw(little)]
pub struct StatementsData {
    pub statements_count: u32,
    #[br(map = |x: u8| x != 0)]
    #[bw(map = |b: &bool| if *b { 1u8 } else { 0u8 })]
    pub terminated: bool,
}

#[derive(BinRead, BinWrite, Clone, Debug, PartialEq)]
#[brw(little)]
pub struct UnboundedStatementsData {
    #[br(map = |x: u8| x != 0)]
    #[bw(map = |b: &bool| if *b { 1u8 } else { 0u8 })]
    pub terminated: bool,
}

#[derive(BinRead, BinWrite, Clone, Debug, PartialEq)]
#[brw(little)]
pub struct ShortStatementsData {
    pub statements_count: u8,
    #[br(map = |x: u8| x != 0)]
    #[bw(map = |b: &bool| if *b { 1u8 } else { 0u8 })]
    pub terminated: bool,
}

#[derive(BinRead, BinWrite, Clone, Debug, PartialEq)]
#[brw(little)]
pub struct ListData {
    pub element_count: u32,
}

#[derive(BinRead, BinWrite, Clone, Debug, PartialEq)]
#[brw(little)]
pub struct ShortMapData {
    pub element_count: u8,
}

#[derive(BinRead, BinWrite, Clone, Debug, PartialEq)]
#[brw(little)]
pub struct MapData {
    pub element_count: u32,
}

#[derive(BinRead, BinWrite, Clone, Debug, PartialEq)]
#[brw(little)]
pub struct InstructionCloseAndStore {
    pub instruction: Int8Data,
}

#[derive(
    BinRead, BinWrite, Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord,
)]
#[brw(little)]
pub struct StackIndex(pub u32);

impl Display for StackIndex {
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        write!(f, "\\{}", self.0)
    }
}

impl AddAssign<u32> for StackIndex {
    fn add_assign(&mut self, rhs: u32) {
        self.0 += rhs;
    }
}

#[derive(BinRead, BinWrite, Clone, Debug, PartialEq)]
#[brw(little)]
pub struct GetOrCreateRemoteRefData {
    pub address: RemotePointerAddress,
    pub create_block_size: u64,
}

#[derive(BinRead, BinWrite, Clone, Debug, PartialEq)]
#[brw(little)]
pub struct PerformMoves {
    pub pointer_count: u32,
    #[br(count = pointer_count)]
    pub pointers: Vec<(u8, SelfOwnedPointerAddress)>, // FIXME: bool instead of u8
}

#[derive(BinRead, BinWrite, Clone, Debug, PartialEq)]
#[brw(little)]
pub struct SharedRef {
    pub address: PointerAddress,
    pub ref_mutability: ReferenceMutability,
    pub container_mutability: SharedContainerMutability,
}

#[derive(BinRead, BinWrite, Clone, Debug, PartialEq)]
#[brw(little)]
pub struct SharedRefWithValue {
    pub address: SelfOwnedPointerAddress, // address of the caller
    pub ref_mutability: ReferenceMutability,
    pub container_mutability: SharedContainerMutability,
}

#[derive(BinRead, BinWrite, Clone, Debug, PartialEq)]
#[brw(little)]
pub struct ModifySharedContainerValue {
    pub operator: AssignmentOperator,
}

#[derive(BinRead, BinWrite, Clone, Debug, PartialEq)]
#[brw(little)]
pub struct ModifyStackValue {
    pub index: StackIndex,
    pub operator: AssignmentOperator,
}

#[derive(BinRead, BinWrite, Clone, Debug, PartialEq)]
#[brw(little)]
pub struct Move {
    pub pointer_count: u32,
    #[br(count = pointer_count)]
    pub address_mappings:
        Vec<(SelfOwnedPointerAddress, SelfOwnedPointerAddress)>,
}

#[derive(BinRead, BinWrite, Clone, Debug, PartialEq)]
#[brw(little)]
pub struct InstructionBlockData {
    pub length: u32,
    pub injected_value_count: u32,
    #[br(count = injected_value_count)]
    pub injected_values: Vec<InjectedValueDeclaration>,
    #[br(count = length)]
    pub body: Vec<u8>,
}

cfg_if! {
    if #[cfg(feature = "disassembler")]{
        use crate::disassembler::InstructionTree;

        #[derive(Clone, Debug, PartialEq)]
        pub struct InstructionBlockDataDebugTree {
            pub length: u32,
            pub injected_variable_count: u32,
            pub injected_values: Vec<InjectedValueDeclaration>,
            pub body: InstructionTree<Instruction>,
        }

        #[derive(Clone, Debug, PartialEq)]
        pub struct InstructionBlockDataDebugFlat {
            pub length: u32,
            pub injected_variable_count: u32,
            pub injected_values: Vec<InjectedValueDeclaration>,
            pub body: Vec<Instruction>,
        }

        impl From<&InstructionBlockDataDebugTree> for InstructionBlockDataDebugFlat {
            fn from(instruction_block_data: &InstructionBlockDataDebugTree) -> Self {
                InstructionBlockDataDebugFlat {
                    length: instruction_block_data.length,
                    injected_variable_count: instruction_block_data.injected_variable_count,
                    injected_values: instruction_block_data.injected_values.clone(),
                    body: instruction_block_data.body.flatten(),
                }
            }
        }

        impl From<&InstructionBlockDataDebugFlat> for InstructionBlockData {
            fn from(value: &InstructionBlockDataDebugFlat) -> Self {
                let mut cursor = Cursor::new(Vec::new());
                for instruction in &value.body {
                    append_instruction(&mut cursor, instruction.clone());
                }
                Self {
                    length: value.length,
                    injected_value_count: value.injected_variable_count,
                    injected_values: value.injected_values.clone(),
                    body: cursor.into_inner(),
                }
            }
        }

        impl BinWrite for InstructionBlockDataDebugFlat {
            type Args<'a> = ();

            fn write_options<W: Write + Seek>(
                &self,
                writer: &mut W,
                endian: Endian,
                _: Self::Args<'_>,
            ) -> BinResult<()> {
                let raw = InstructionBlockData::from(self);
                raw.write_options(writer, endian, ())
            }
        }

        impl BinWrite for InstructionBlockDataDebugTree {
            type Args<'a> = ();
            fn write_options<W: Write + Seek>(
                &self,
                writer: &mut W,
                endian: Endian,
                _: Self::Args<'_>,
            ) -> BinResult<()> {
                let raw = InstructionBlockData::from(&InstructionBlockDataDebugFlat::from(self));
                raw.write_options(writer, endian, ())
            }
        }

    }
}

#[derive(BinRead, BinWrite, Clone, Debug, PartialEq)]
#[brw(little)]
pub struct ApplyData {
    pub arg_count: u16,
}

#[derive(BinRead, BinWrite, Clone, Debug, PartialEq)]
#[brw(little)]
pub struct ImplTypeData {
    pub impl_count: u8,
    #[br(count = impl_count)]
    pub impls: Vec<PointerAddress>,
}

#[derive(BinRead, BinWrite, Clone, Debug, PartialEq)]
#[brw(little)]
pub struct TypeReferenceData {
    pub address: PointerAddress,
}

#[bitfield]
#[derive(BinWrite, BinRead, Clone, Copy, Debug, PartialEq)]
#[bw(map = |&x| Self::into_bytes(x))]
#[br(map = Self::from_bytes)]
#[brw(little)]
pub struct TypeMetadataBin {
    pub ownership: TypeOwnershipCode,
    pub mutability: TypeMutabilityCode,
    pub type_local_or_shared: TypeLocalOrShared,
    _unused: B4,
}

impl From<&TypeMetadataBin> for TypeMetadata {
    fn from(value: &TypeMetadataBin) -> Self {
        match value.type_local_or_shared() {
            TypeLocalOrShared::Local => TypeMetadata::Local {
                mutability: (&value.mutability()).into(),
                ownership: (&value.ownership()).into(),
            },
            TypeLocalOrShared::Shared => TypeMetadata::Shared {
                mutability: (&value.mutability()).into(),
                ownership: (&value.ownership()).into(),
            },
        }
    }
}

impl From<&TypeMetadata> for TypeMetadataBin {
    fn from(value: &TypeMetadata) -> Self {
        match value {
            TypeMetadata::Local {
                mutability,
                ownership: reference_mutability,
            } => Self::new()
                .with_type_local_or_shared(TypeLocalOrShared::Local)
                .with_mutability(mutability.into())
                .with_ownership(reference_mutability.into()),
            TypeMetadata::Shared {
                mutability,
                ownership,
            } => Self::new()
                .with_type_local_or_shared(TypeLocalOrShared::Shared)
                .with_mutability(mutability.into())
                .with_ownership(ownership.into()),
        }
    }
}