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
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
pub use crate::prelude::*;
use crate::{
    ast::{
        resolved_variable::{ResolvedVariable, VariableId},
        spanned::Spanned,
        type_expressions::TypeExpression,
    },
    global::{
        operators::{
            ArithmeticUnaryOperator, BinaryOperator, ComparisonOperator,
            UnaryOperator, assignment::AssignmentOperator,
        },
        protocol_structures::instruction_data::StackIndex,
    },
    libs::core::core_lib_id::CoreLibId,
    shared_values::{
        PointerAddress, ReferenceMutability, SharedContainerMutability,
    },
    types::{
        r#type::Type, type_definition::callable::CallableKind,
        type_definition_with_metadata::LocalReferenceMutability,
    },
    values::{
        core_value::CoreValue,
        core_values::{
            self,
            boolean::Boolean,
            decimal::{Decimal, typed_decimal::TypedDecimal},
            endpoint::Endpoint,
            integer::{Integer, typed_integer::TypedInteger},
            text::Text,
        },
        value::Value,
        value_container::ValueContainer,
    },
};
use core::{fmt::Display, ops, ops::Neg};

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

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

#[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,
    /// 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),

    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),
    /// One or more statements, e.g (1; 2; 3)
    Statements(Statements),
    /// reference access to shared value, e.g. '$ABC / 'mut $ABC
    RequestSharedRef(RequestSharedRef),

    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(TypeDeclaration),

    /// 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
    GetRef(GetRef),

    /// Get a new shared reference
    GetSharedRef(GetSharedRef),

    /// 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),

    /// Slot assignment
    SlotAssignment(StackAssignment),

    /// 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),

    /// 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),
}

impl Spanned for DatexExpressionData {
    type Output = DatexExpression;

    fn with_span<T: Into<core::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 {
                        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: Box<DatexExpression>,
    pub right: Box<DatexExpression>,
    pub ty: Option<Type>,
}

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

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

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

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

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

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

#[derive(Clone, Debug, PartialEq)]
pub enum TypeDeclarationKind {
    Nominal,
    Alias,
}
impl Display for TypeDeclarationKind {
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        match self {
            TypeDeclarationKind::Nominal => core::write!(f, "type"),
            TypeDeclarationKind::Alias => core::write!(f, "typealias"),
        }
    }
}
impl TypeDeclarationKind {
    pub fn is_nominal(&self) -> bool {
        matches!(self, TypeDeclarationKind::Nominal)
    }
    pub fn is_alias(&self) -> bool {
        matches!(self, TypeDeclarationKind::Alias)
    }
}

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

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

#[derive(Clone, Debug, PartialEq, Default)]
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: Box<DatexExpression>,
    pub arguments: Vec<DatexExpression>,
}

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

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

#[derive(Clone, Debug, PartialEq)]
pub struct RemoteExecution {
    pub left: Box<DatexExpression>,
    pub right: Box<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: Box<DatexExpression>,
}

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

#[derive(Clone, Debug, PartialEq)]
pub struct CompileExpression {
    pub expression: Box<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 name: Option<String>,
    pub kind: CallableKind,
    pub parameters: Vec<(String, TypeExpression)>,
    pub rest_parameter: Option<(String, TypeExpression)>,
    pub return_type: Option<TypeExpression>,
    pub yeet_type: Option<TypeExpression>,
    pub body: Box<DatexExpression>,
    pub injected_variable_count: Option<u32>,
}

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

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

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

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<Box<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: Box<DatexExpression>,
    // TODO: operator for stack assignment, e.g. \\1 += 2
    // pub operator: Option<AssignmentOperator>,
}

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

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

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

#[derive(Clone, Debug, PartialEq)]
pub struct GetRef {
    pub mutability: LocalReferenceMutability,
    pub expression: Box<DatexExpression>,
}

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

#[derive(Clone, Debug, PartialEq)]
pub struct GetSharedRef {
    pub mutability: ReferenceMutability,
    pub expression: Box<DatexExpression>,
}

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