datex-core 0.0.14

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
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
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
pub use crate::prelude::*;
use crate::{
    ast::{
        resolved_variable::{ResolvedVariable, VariableId},
        spanned::Spanned,
        type_expressions::TypeExpression,
    },
    global::{
        operators::{
            ArithmeticUnaryOperator, BinaryOperator, ComparisonOperator,
            UnaryOperator, modification::ModificationOperator,
        },
        stack_index::StackIndex,
    },
    libs::core::core_lib_id::CoreLibId,
    shared_values::{
        PointerAddress, ReferenceMutability, SelfOwnedPointerAddress,
        SharedContainerMutability,
    },
    types::{
        r#type::Type, type_definition::callable::CallableKind,
        type_definition_with_metadata::LocalReferenceMutability,
    },
    values::{
        core_value::CoreValue,
        core_value_with_classification::CoreValueWithClassification,
        core_values::{
            self,
            boolean::Boolean,
            decimal::{Decimal, typed_decimal::TypedDecimal},
            endpoint::Endpoint,
            instant::Instant,
            integer::{Integer, typed_integer::TypedInteger},
            text::Text,
        },
        value::Value,
        value_container::ValueContainer,
    },
};
use core::{
    fmt::Display,
    ops::{self, Neg},
};

#[derive(Clone, Debug)]
/// An expression in the AST
pub struct DatexExpression {
    pub data: Box<DatexExpressionData>,
    pub span: ops::Range<usize>,
    pub ty: Option<Type>,
}
impl Default for DatexExpression {
    fn default() -> Self {
        DatexExpression {
            data: Box::new(DatexExpressionData::Statements(Statements {
                statements: Vec::new(),
                is_terminated: false,
                unbounded: None,
            })),
            span: 0..0,
            ty: None,
        }
    }
}
impl DatexExpression {
    pub fn new(data: DatexExpressionData, span: ops::Range<usize>) -> Self {
        DatexExpression {
            data: Box::new(data),
            span,
            ty: None,
        }
    }

    pub fn data(&self) -> &DatexExpressionData {
        &self.data
    }

    pub fn data_mut(&mut self) -> &mut DatexExpressionData {
        &mut self.data
    }

    pub fn span(&self) -> &ops::Range<usize> {
        &self.span
    }

    pub fn ty(&self) -> Option<&Type> {
        self.ty.as_ref()
    }
}

// PartialEquality for DatexExpression ignores the span (allows for easier testing)
impl PartialEq for DatexExpression {
    fn eq(&self, other: &Self) -> bool {
        self.data == other.data
    }
}
impl Eq for DatexExpression {}

#[derive(Clone, Debug, PartialEq)]
/// The different kinds of type expressions in the AST
#[derive(Default)]
pub enum DatexExpressionData {
    /// This is a marker for recovery from parse errors.
    /// We should never use this manually.
    #[default]
    Noop,

    Recover,
    NativeImplementationIndicator,

    /// null
    Null,

    /// (...)
    OmitRecursive,

    /// Boolean (true or false)
    Boolean(Boolean),
    /// Text, e.g "Hello, world!"
    Text(Text),
    /// Decimal, e.g 123.456789123456
    Decimal(Decimal),

    /// Typed Decimal, e.g. 123.456i8
    TypedDecimal(TypedDecimal),

    /// Integer, e.g 123456789123456789
    Integer(Integer),

    /// DateTime, e.g. 2026-04-13T18:28:09.415Z (stored as Instant)
    Instant(Instant),

    Range(RangeDeclaration),

    /// Typed Integer, e.g. 123i8
    TypedInteger(TypedInteger),

    /// Identifier (variable / core type usage)
    Identifier(String),

    /// Endpoint, e.g. @test_a or @test_b
    Endpoint(Endpoint),
    /// List, e.g  `[1, 2, 3, "text"]`
    List(List),
    /// Map, e.g {"xy": 2, (3): 4, xy: "xy"}
    Map(Map),

    Sender,
    Receiver,

    /// One or more statements, e.g (1; 2; 3)
    Statements(Statements),
    /// reference access to shared value, e.g. '$ABC / 'mut $ABC
    RequestSharedRef(RequestSharedRef),

    /// move a shared value, e.g. $ABC
    MoveSharedValue(SelfOwnedPointerAddress),

    ResolveCoreLibId(CoreLibId),

    /// compile ( ... )
    Compile(CompileExpression),

    /// Conditional expression, e.g. if (true) { 1 } else { 2 }
    Conditional(Conditional),

    // TODO #611: Give information on type kind (nominal & structural)
    /// Variable declaration, e.g. const x = 1, const mut x = 1, or var y = 2. VariableId is always set to 0 by the ast parser.
    VariableDeclaration(VariableDeclaration),
    /// Variable assignment, e.g. x = 42 or y += 1
    VariableAssignment(VariableAssignment),
    /// Variable access - only generated by the precompiler, not by the parser
    VariableAccess(VariableAccess),

    // TODO #612: Shall we avoid hoisting for type aliases?
    // This would remove the ability to have recursive type
    // definitions.
    /// Type declaration, e.g. type MyType = { x: 42, y: "John" };
    TypeDeclaration(TypeDeclarationExpression),

    /// Entity declaration, e.g. entity MyEntity = { x: 42, y: "John" };
    EntityDeclaration(EntityDeclarationExpression),

    /// Type expression, e.g. type(1 | 2)
    TypeExpression(TypeExpression),

    /// callable (function/procedure) declaration, e.g. function my_function() -> type ( ... )
    CallableDeclaration(Box<CallableDeclaration>),

    /// Create a new shared container
    CreateShared(CreateShared),
    /// Create a new reference
    DeriveRef(DeriveRef),

    /// Derive a new shared reference
    DeriveSharedRef(DeriveSharedRef),

    /// Creates a new mutable value
    CreateMut(CreateMut),

    /// Unbox
    Unbox(Unbox),

    /// Clone
    Clone(CloneExpression),

    /// relative StackIndex, e.g. \0, \1, \2, ...
    StackIndex(StackIndex),

    /// Tag, e.g. #Variant1
    Tag(TagExpression),

    /// Property access on the root, e.g. $.print
    RootPropertyAccess(RootPropertyAccess),

    /// Stack assignment e.g. {0} = ...
    StackAssignment(StackAssignment),

    /// Push list to stack, e.g. {...} = ...
    StackListAssignment(StackListAssignment),

    /// Binary operation, e.g. x + y
    BinaryOperation(BinaryOperation),

    /// Comparison operation, e.g. x < y
    ComparisonOperation(ComparisonOperation),

    /// Unbox assignment, e.g. *(...) = y, **(...) += y
    UnboxAssignment(UnboxAssignment),
    UnboxSlotAssignment(UnboxSlotAssignment),

    /// Property assignment, e.g. obj.property = value
    PropertyAssignment(PropertyAssignment),

    /// Unary operation, e.g. -x, !x
    UnaryOperation(UnaryOperation),

    /// Apply a value to another value, e.g. function call or type cast
    Apply(Apply),

    /// Call an interface method, e.g. obj->method()
    InterfaceMethodCall(InterfaceMethodCall),

    /// Apply a property access to an argument
    PropertyAccess(PropertyAccess),

    /// Generic instantiation, e.g. MyType<u8>
    GenericInstantiation(GenericInstantiation),

    /// The '?' placeholder expression
    Placeholder(ValueAccessType),

    /// Remote execution, e.g. @example :: 41 + 1
    RemoteExecution(RemoteExecution),

    /// Variant access, e.g. integer/u8
    VariantAccess(VariantAccess),

    EntityValue(EntityValueExpression),
}

impl DatexExpressionData {
    pub fn callable_declaration(
        callable_declaration: CallableDeclaration,
    ) -> Self {
        DatexExpressionData::CallableDeclaration(Box::new(callable_declaration))
    }
}

impl Spanned for DatexExpressionData {
    type Output = DatexExpression;

    fn with_span<T: Into<ops::Range<usize>>>(self, span: T) -> Self::Output {
        DatexExpression {
            data: Box::new(self),
            span: span.into(),
            ty: None,
        }
    }

    fn with_default_span(self) -> Self::Output {
        DatexExpression {
            data: Box::new(self),
            span: (0..0),
            ty: None,
        }
    }
}

impl Spanned for Box<DatexExpressionData> {
    type Output = DatexExpression;

    fn with_span<T: Into<ops::Range<usize>>>(self, span: T) -> Self::Output {
        DatexExpression {
            data: self,
            span: span.into(),
            ty: None,
        }
    }

    fn with_default_span(self) -> Self::Output {
        DatexExpression {
            data: self,
            span: (0..0),
            ty: None,
        }
    }
}

// directly convert DatexExpression to a ValueContainer
impl TryFrom<&DatexExpressionData> for ValueContainer {
    type Error = ();

    fn try_from(expr: &DatexExpressionData) -> Result<Self, Self::Error> {
        Ok(match expr {
            DatexExpressionData::UnaryOperation(UnaryOperation {
                operator,
                expression,
            }) => {
                let value = ValueContainer::try_from(expression.data())?;
                match value {
                    ValueContainer::Local(Value::Core(
                        CoreValueWithClassification {
                            inner: CoreValue::Integer(_) | CoreValue::Decimal(_),
                            ..
                        },
                    )) => match operator {
                        UnaryOperator::Arithmetic(
                            ArithmeticUnaryOperator::Plus,
                        ) => value,
                        UnaryOperator::Arithmetic(
                            ArithmeticUnaryOperator::Minus,
                        ) => value.neg().map_err(|_| ())?,
                        _ => Err(())?,
                    },
                    _ => Err(())?,
                }
            }
            DatexExpressionData::Null => ValueContainer::Local(Value::null()),
            DatexExpressionData::Boolean(b) => ValueContainer::from(b.clone()),
            DatexExpressionData::Text(s) => ValueContainer::from(s.clone()),
            DatexExpressionData::Decimal(d) => ValueContainer::from(d.clone()),
            DatexExpressionData::Integer(i) => ValueContainer::from(i.clone()),
            DatexExpressionData::TypedInteger(i) => {
                ValueContainer::from(i.clone())
            }
            DatexExpressionData::TypedDecimal(d) => {
                ValueContainer::from(d.clone())
            }
            DatexExpressionData::Endpoint(e) => ValueContainer::from(e.clone()),
            DatexExpressionData::List(list) => {
                let entries = list
                    .items
                    .iter()
                    .map(|e| ValueContainer::try_from(e.data()))
                    .collect::<Result<Vec<ValueContainer>, ()>>()?;
                ValueContainer::from(core_values::list::List::from(entries))
            }
            DatexExpressionData::Map(pairs) => {
                let entries = pairs
                    .entries
                    .iter()
                    .map(|(k, v)| {
                        let key = ValueContainer::try_from(k.data())?;
                        let value = ValueContainer::try_from(v.data())?;
                        Ok((key, value))
                    })
                    .collect::<Result<Vec<(ValueContainer, ValueContainer)>, ()>>()?;
                ValueContainer::from(core_values::map::Map::from(entries))
            }
            _ => Err(())?,
        })
    }
}

#[derive(Clone, Debug, PartialEq)]
pub struct BinaryOperation {
    pub operator: BinaryOperator,
    pub left: DatexExpression,
    pub right: DatexExpression,
    pub ty: Option<Type>,
}

#[derive(Clone, Debug, PartialEq)]
pub struct RangeDeclaration {
    pub start: DatexExpression,
    pub end: DatexExpression,
}

#[derive(Clone, Debug, PartialEq)]
pub struct ComparisonOperation {
    pub operator: ComparisonOperator,
    pub left: DatexExpression,
    pub right: DatexExpression,
}

#[derive(Clone, Debug, PartialEq)]
pub struct UnboxAssignment {
    pub operator: Option<ModificationOperator>,
    pub unbox_expression: DatexExpression,
    pub assigned_expression: DatexExpression,
}

#[derive(Clone, Debug, PartialEq)]
pub struct UnboxSlotAssignment {
    pub operator: Option<ModificationOperator>,
    pub stack_index: StackIndex,
    pub assigned_expression: DatexExpression,
}

#[derive(Clone, Debug, PartialEq)]
pub struct PropertyAssignment {
    pub operator: Option<ModificationOperator>,
    pub base: DatexExpression,
    pub property: DatexExpression,
    pub assigned_expression: DatexExpression,
}

#[derive(Clone, Debug, PartialEq)]
pub struct Conditional {
    pub condition: DatexExpression,
    pub then_branch: DatexExpression,
    pub else_branch: Option<DatexExpression>,
}

#[derive(Clone, Debug, PartialEq)]
pub struct TypeDeclarationExpression {
    pub id: Option<VariableId>,
    pub name: String, // TODO #614: separate variant from name
    pub definition: TypeExpression,
    pub hoisted: bool,
}

#[derive(Clone, Debug, PartialEq)]
pub struct UnaryOperation {
    pub operator: UnaryOperator,
    pub expression: DatexExpression,
}

#[derive(Clone, Debug, PartialEq, Default, Hash, Eq)]
pub enum ValueAccessType {
    /// 'mut x
    SharedRefMut,
    /// 'x
    SharedRef,
    /// clone x
    Clone, // TODO: allow clone only for non-shared values, for shared values, do clone *x
    /// temp borrow for x (used before Unbox)
    Borrow,
    #[default]
    MoveOrCopy,
}

impl From<&ReferenceMutability> for ValueAccessType {
    fn from(mutability: &ReferenceMutability) -> Self {
        match mutability {
            ReferenceMutability::Mutable => ValueAccessType::SharedRefMut,
            ReferenceMutability::Immutable => ValueAccessType::SharedRef,
        }
    }
}

#[derive(Clone, Debug, PartialEq)]
pub struct Apply {
    pub base: DatexExpression,
    pub arguments: Vec<DatexExpression>,
}

#[derive(Clone, Debug, PartialEq)]
pub struct InterfaceMethodCall {
    pub target: DatexExpression,
    pub method_name: String,
    pub arguments: Vec<DatexExpression>,
}

impl InterfaceMethodCall {
    pub fn new(
        target: DatexExpression,
        method_name: String,
        arguments: Vec<DatexExpression>,
    ) -> Self {
        InterfaceMethodCall {
            target,
            method_name,
            arguments,
        }
    }
}

#[derive(Clone, Debug, PartialEq)]
pub struct PropertyAccess {
    pub base: DatexExpression,
    pub property: DatexExpression,
}

#[derive(Clone, Debug, PartialEq)]
pub struct GenericInstantiation {
    pub base: DatexExpression,
    pub generic_arguments: Vec<TypeExpression>,
}

#[derive(Clone, Debug, PartialEq)]
pub struct RemoteExecution {
    pub left: DatexExpression,
    pub right: DatexExpression,
    /// internal metadata set by precompiler, indicates how many variables from parent scope are accessed inside the remote execution
    pub injected_variable_count: Option<u32>,
}

#[derive(Clone, Debug, PartialEq)]
pub struct UnboundedStatement {
    pub is_first: bool,
    pub is_last: bool,
}

#[derive(Clone, Debug, PartialEq)]
pub struct Statements {
    pub statements: Vec<DatexExpression>,
    pub is_terminated: bool,
    pub unbounded: Option<UnboundedStatement>,
}

impl Statements {
    pub fn empty() -> Self {
        Statements {
            statements: Vec::new(),
            is_terminated: true,
            unbounded: None,
        }
    }
    pub fn new_terminated(statements: Vec<DatexExpression>) -> Self {
        Statements {
            statements,
            is_terminated: true,
            unbounded: None,
        }
    }
    pub fn new_unterminated(statements: Vec<DatexExpression>) -> Self {
        Statements {
            statements,
            is_terminated: false,
            unbounded: None,
        }
    }
}

#[derive(Clone, Debug, PartialEq)]
pub struct VariableDeclaration {
    pub id: Option<VariableId>,
    pub kind: VariableKind,
    pub name: String,
    pub type_annotation: Option<TypeExpression>,
    pub init_expression: DatexExpression,
}

#[derive(Clone, Debug, PartialEq)]
pub struct VariableAssignment {
    pub id: Option<VariableId>,
    pub name: String,
    pub operator: Option<ModificationOperator>,
    pub expression: DatexExpression,
}

#[derive(Clone, Debug, PartialEq)]
pub struct EntityDeclarationExpression {
    pub id: Option<VariableId>,
    pub name: String,
    pub definition: TypeExpression,
    pub hoisted: bool,
}

#[derive(Clone, Debug, PartialEq)]
pub struct CompileExpression {
    pub expression: DatexExpression,
}

#[derive(Clone, Debug, PartialEq)]
pub struct VariableAccess {
    pub id: VariableId,
    pub name: String,
    pub access_type: ValueAccessType,
}

#[derive(Clone, Debug, PartialEq)]
pub struct RequestSharedRef {
    pub mutability: ReferenceMutability,
    pub address: PointerAddress,
}

#[derive(Clone, Debug, PartialEq)]
pub struct CallableDeclaration {
    pub signature: CallableSignature,
    pub body: DatexExpression,
    pub injected_variable_count: Option<u32>,
}

#[derive(Clone, Debug, PartialEq)]
pub struct CallableSignature {
    pub name: Option<String>,
    pub kind: CallableKind,
    pub requires_async: bool,
    pub parameters: Vec<(String, TypeExpression)>,
    pub rest_parameter: Option<(String, TypeExpression)>,
    pub return_type: Option<TypeExpression>,
    pub yeet_type: Option<TypeExpression>,
}

#[derive(Clone, Debug, PartialEq)]
pub struct List {
    pub items: Vec<DatexExpression>,
}

impl List {
    pub fn new(items: Vec<DatexExpression>) -> Self {
        List { items }
    }
}

impl FromIterator<DatexExpression> for List {
    fn from_iter<T: IntoIterator<Item = DatexExpression>>(iter: T) -> Self {
        let items = iter.into_iter().collect();
        List { items }
    }
}

#[derive(Clone, Debug, PartialEq)]
pub struct Map {
    pub entries: Vec<(DatexExpression, DatexExpression)>,
}

impl FromIterator<(DatexExpression, DatexExpression)> for Map {
    fn from_iter<T: IntoIterator<Item = (DatexExpression, DatexExpression)>>(
        iter: T,
    ) -> Self {
        let entries = iter.into_iter().collect();
        Map { entries }
    }
}

impl Map {
    pub fn new(entries: Vec<(DatexExpression, DatexExpression)>) -> Self {
        Map { entries }
    }
}

#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum VariableKind {
    Const,
    Var,
}

impl Display for VariableKind {
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        match self {
            VariableKind::Const => core::write!(f, "const"),
            VariableKind::Var => core::write!(f, "var"),
        }
    }
}

#[derive(Clone, Debug, PartialEq)]
pub struct TagExpression {
    pub tag: String,
    pub expression: Option<DatexExpression>,
}

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

#[derive(Clone, Debug, PartialEq)]
pub struct RootPropertyAccess {
    pub property_name: String,
}

#[derive(Clone, Debug, PartialEq)]
pub struct StackAssignment {
    pub index: StackIndex,
    pub expression: DatexExpression,
}

#[derive(Clone, Debug, PartialEq)]
pub struct StackListAssignment {
    pub expression: DatexExpression,
}

#[derive(Clone, Debug, PartialEq)]
pub struct VariantAccess {
    pub name: String,
    pub variant: String,
    pub base: ResolvedVariable,
}

#[derive(Clone, Debug, PartialEq)]
pub struct EntityValueExpression {
    pub entity_name: String,
    pub entity_address: Option<PointerAddress>,
    pub value: DatexExpression,
}

#[derive(Clone, Debug, PartialEq)]
pub struct Unbox {
    pub expression: DatexExpression,
}

#[derive(Clone, Debug, PartialEq)]
pub struct CloneExpression {
    pub expression: DatexExpression,
}

#[derive(Clone, Debug, PartialEq)]
pub struct DeriveRef {
    pub mutability: LocalReferenceMutability,
    pub expression: DatexExpression,
}

#[derive(Clone, Debug, PartialEq)]
pub struct CreateShared {
    pub mutability: SharedContainerMutability,
    pub expression: DatexExpression,
}

#[derive(Clone, Debug, PartialEq)]
pub struct DeriveSharedRef {
    pub mutability: ReferenceMutability,
    pub expression: DatexExpression,
}

#[derive(Clone, Debug, PartialEq)]
pub struct CreateMut {
    pub expression: DatexExpression,
}