datex-core 0.0.13

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
//! This module defines the [CoreValue] enum, which represents the fundamental value types in DATEX.
//! Each variant of CoreValue holds the underlying value of a specific type, such as [Integer], [Text], or [List].
//! CoreValues can be converted to and from native Rust types.

use crate::{
    libs::core::type_id::{
        CoreLibBaseTypeId, CoreLibTypeId, CoreLibVariantTypeId,
    },
    prelude::*,
    types::entities::entity_type_definition::EntityTypeDefinition,
    values::core_values::instant::Instant,
};
pub mod serde_dif;
use crate::{
    types::r#type::Type,
    values::{
        core_values::{
            boolean::Boolean,
            callable::Callable,
            decimal::{
                Decimal,
                typed_decimal::{DecimalTypeVariant, TypedDecimal},
            },
            endpoint::Endpoint,
            integer::{
                Integer,
                typed_integer::{IntegerTypeVariant, TypedInteger},
            },
            list::List,
            map::Map,
            range::Range,
            receiver::ValueContainerReceiver,
            sender::ValueContainerSender,
            text::Text,
        },
        value_container::ValueContainer,
    },
};
use core::fmt::{Debug, Display, Formatter};

pub mod borrowed_core_value;
pub mod convert_core_value;
mod convert_parts;
mod datex_hash;
mod equality;
mod iter_parts;
mod ops;
mod to_instructions;
mod try_clone;

#[derive(Default, Clone, Debug)]
pub enum CoreValue {
    #[default]
    Uninitialized,
    Null,
    Boolean(Boolean),
    Integer(Integer),
    TypedInteger(TypedInteger),
    Decimal(Decimal),
    TypedDecimal(TypedDecimal),
    Text(Text),
    Endpoint(Endpoint),
    List(List),
    Map(Map),
    Type(Type),
    EntityTypeDefinition(EntityTypeDefinition),
    Callable(Callable),
    Range(Range),
    Instant(Instant),
    Sender(ValueContainerSender),
    Receiver(ValueContainerReceiver),
    /// Used for nested values, e.g. #Tagged (shared 42)
    Box(Box<ValueContainer>),
}

impl<T> FromIterator<T> for CoreValue
where
    T: Into<ValueContainer>,
{
    fn from_iter<I: IntoIterator<Item = T>>(iter: I) -> Self {
        CoreValue::List(List::new(iter.into_iter().map(Into::into).collect()))
    }
}

impl From<&CoreValue> for CoreLibTypeId {
    fn from(value: &CoreValue) -> Self {
        match value {
            CoreValue::Map(_) => CoreLibTypeId::Base(CoreLibBaseTypeId::Map),
            CoreValue::List(_) => CoreLibTypeId::Base(CoreLibBaseTypeId::List),
            CoreValue::Text(_) => CoreLibTypeId::Base(CoreLibBaseTypeId::Text),
            CoreValue::Boolean(_) => {
                CoreLibTypeId::Base(CoreLibBaseTypeId::Boolean)
            }
            CoreValue::TypedInteger(i) => CoreLibTypeId::Variant(
                CoreLibVariantTypeId::Integer(i.variant()),
            ),
            CoreValue::TypedDecimal(d) => CoreLibTypeId::Variant(
                CoreLibVariantTypeId::Decimal(d.variant()),
            ),
            CoreValue::Integer(_) => {
                CoreLibTypeId::Base(CoreLibBaseTypeId::Integer)
            }
            CoreValue::Decimal(_) => {
                CoreLibTypeId::Base(CoreLibBaseTypeId::Decimal)
            }
            CoreValue::Endpoint(_) => {
                CoreLibTypeId::Base(CoreLibBaseTypeId::Endpoint)
            }
            CoreValue::Null => CoreLibTypeId::Base(CoreLibBaseTypeId::Null),
            CoreValue::Type(_) => CoreLibTypeId::Base(CoreLibBaseTypeId::Type),
            CoreValue::Callable(_) => {
                CoreLibTypeId::Base(CoreLibBaseTypeId::Callable)
            }
            CoreValue::Range(_) => {
                CoreLibTypeId::Base(CoreLibBaseTypeId::Range)
            }
            CoreValue::EntityTypeDefinition(_nominal_type) => {
                CoreLibTypeId::Base(CoreLibBaseTypeId::Never) // TODO: what is the type of nominal type? do we even need to handle this?
            }
            CoreValue::Instant(_) => {
                CoreLibTypeId::Base(CoreLibBaseTypeId::Instant)
            }
            CoreValue::Uninitialized => {
                CoreLibTypeId::Base(CoreLibBaseTypeId::Never)
            }
            CoreValue::Box(_) => CoreLibTypeId::Base(CoreLibBaseTypeId::Box),
            CoreValue::Sender(_) => {
                CoreLibTypeId::Base(CoreLibBaseTypeId::Sender)
            }
            CoreValue::Receiver(_) => {
                CoreLibTypeId::Base(CoreLibBaseTypeId::Receiver)
            }
        }
    }
}

impl CoreValue {
    pub fn new<T>(value: T) -> CoreValue
    where
        CoreValue: From<T>,
    {
        value.into()
    }

    /// Check if the CoreValue is a combined value type (List, Map)
    /// that contains inner ValueContainers.
    pub fn is_collection_value(&self) -> bool {
        core::matches!(self, CoreValue::List(_) | CoreValue::Map(_))
    }

    /// Get the default type of the CoreValue type definition.
    /// This method uses the CoreLibPointerId to retrieve the corresponding
    /// type reference from the core library.
    /// For example, a CoreValue::TypedInteger(i32) will return the type ref integer/i32
    pub fn core_lib_type_id(&self) -> CoreLibTypeId {
        CoreLibTypeId::from(self)
    }

    /// Casts the value to a [Text] value
    /// Note: [Text] values are kept as is an not wrapped in quotes
    pub fn cast_to_text(&self) -> Text {
        match self {
            CoreValue::Text(text) => text.clone(),
            _ => Text::String(self.to_string()),
        }
    }

    pub fn cast_to_bool(&self) -> Option<Boolean> {
        match self {
            CoreValue::Text(text) => Some(Boolean(!text.as_str().is_empty())),
            CoreValue::Boolean(bool) => Some(bool.clone()),
            CoreValue::TypedInteger(int) => Some(Boolean(int.as_i128()? != 0)),
            CoreValue::Null => Some(Boolean(false)),
            _ => None,
        }
    }

    pub fn cast_to_decimal(&self) -> Option<Decimal> {
        match self {
            CoreValue::Text(text) => {
                text.as_string().parse::<f64>().ok().map(Decimal::from)
            }
            CoreValue::TypedInteger(int) => {
                Some(Decimal::from(int.as_i128()? as f64))
            }
            CoreValue::TypedDecimal(decimal) => {
                Some(Decimal::from(decimal.clone()))
            }
            CoreValue::Integer(int) => {
                Some(Decimal::from(int.as_i128()? as f64))
            }
            CoreValue::Decimal(decimal) => Some(decimal.clone()),
            _ => None,
        }
    }

    pub fn cast_to_typed_decimal(
        &self,
        variant: DecimalTypeVariant,
    ) -> Option<TypedDecimal> {
        match self {
            CoreValue::Text(text) => TypedDecimal::try_from_string_and_variant(
                text.as_str(),
                variant,
            )
            .ok(),
            CoreValue::TypedInteger(int) => Some(
                TypedDecimal::try_from_string_and_variant(
                    &int.to_string(),
                    variant,
                )
                .ok()?,
            ),
            CoreValue::TypedDecimal(decimal) => Some(
                TypedDecimal::try_from_string_and_variant(
                    &decimal.to_string(),
                    variant,
                )
                .ok()?,
            ),
            CoreValue::Integer(int) => Some(
                TypedDecimal::try_from_string_and_variant(
                    &int.to_string(),
                    variant,
                )
                .ok()?,
            ),
            CoreValue::Decimal(decimal) => Some(
                TypedDecimal::try_from_string_and_variant(
                    &decimal.to_string(),
                    variant,
                )
                .ok()?,
            ),
            _ => None,
        }
    }

    // FIXME #314 discuss here - shall we fit the integer in the minimum viable type?
    pub fn _cast_to_integer_internal(&self) -> Option<TypedInteger> {
        match self {
            CoreValue::Text(text) => {
                Integer::try_from_string(&text.as_string())
                    .map(|x| Some(x.to_smallest_fitting()))
                    .unwrap_or(None)
            }
            CoreValue::TypedInteger(int) => {
                Some(int.to_smallest_fitting().clone())
            }
            CoreValue::Integer(int) => {
                Some(TypedInteger::IBig(int.clone()).to_smallest_fitting())
            }
            CoreValue::Decimal(decimal) => Some(
                TypedInteger::from(decimal.into_f64() as i128)
                    .to_smallest_fitting(),
            ),
            CoreValue::TypedDecimal(decimal) => Some(
                TypedInteger::from(decimal.as_f64() as i64)
                    .to_smallest_fitting(),
            ),
            _ => None,
        }
    }

    // TODO #315 improve conversion logic
    pub fn cast_to_integer(&self) -> Option<Integer> {
        match self {
            CoreValue::Text(text) => {
                Integer::try_from_string(&text.as_string()).ok()
            }
            CoreValue::TypedInteger(int) => Some(int.as_integer()),
            CoreValue::Integer(int) => Some(int.clone()),
            CoreValue::Decimal(decimal) => {
                // FIXME #316 currently bad as f64 can be infinity or nan
                // convert decimal directly to integer into_f64 is wrong here
                Some(Integer::from(decimal.into_f64() as i128))
            }
            CoreValue::TypedDecimal(decimal) => {
                decimal.as_integer().map(Integer::from)
            }
            _ => None,
        }
    }

    pub fn cast_to_typed_integer(
        &self,
        variant: IntegerTypeVariant,
    ) -> Option<TypedInteger> {
        match self {
            CoreValue::Text(text) => TypedInteger::try_from_string_and_variant(
                text.as_str(),
                variant,
            )
            .ok(),
            CoreValue::TypedInteger(int) => {
                TypedInteger::try_from_string_and_variant(
                    &int.to_string(),
                    variant,
                )
                .ok()
            }
            CoreValue::Integer(int) => {
                TypedInteger::try_from_string_and_variant(
                    int.to_string().as_str(),
                    variant,
                )
                .ok()
            }
            CoreValue::Decimal(decimal) => {
                Some(TypedInteger::from(decimal.into_f64() as i128))
            }
            CoreValue::TypedDecimal(decimal) => {
                decimal.as_integer().map(TypedInteger::from)
            }
            _ => None,
        }
    }

    pub fn cast_to_endpoint(&self) -> Option<Endpoint> {
        match self {
            CoreValue::Text(text) => Endpoint::try_from(text.as_str()).ok(),
            CoreValue::Endpoint(endpoint) => Some(endpoint.clone()),
            _ => None,
        }
    }
}

impl Display for CoreValue {
    fn fmt(&self, f: &mut Formatter) -> core::fmt::Result {
        match self {
            CoreValue::Instant(instant) => write!(f, "{instant}"),
            CoreValue::Type(ty) => write!(f, "{ty}"),
            CoreValue::Boolean(bool) => write!(f, "{bool}"),
            CoreValue::TypedInteger(int) => write!(f, "{int}"),
            CoreValue::TypedDecimal(decimal) => write!(f, "{decimal}"),
            CoreValue::Text(text) => write!(f, "{text}"),
            CoreValue::Null => write!(f, "null"),
            CoreValue::Endpoint(endpoint) => write!(f, "{endpoint}"),
            CoreValue::Map(map) => write!(f, "{map}"),
            CoreValue::Range(range) => {
                write!(f, "{}..{}", range.start, range.end)
            }
            CoreValue::Integer(integer) => write!(f, "{integer}"),
            CoreValue::Decimal(decimal) => write!(f, "{decimal}"),
            CoreValue::List(list) => write!(f, "{list}"),
            CoreValue::Callable(_callable) => write!(f, "[[ callable ]]"),
            CoreValue::EntityTypeDefinition(container) => {
                write!(f, "{container}")
            }
            CoreValue::Uninitialized => write!(f, "[[ uninitialized ]]"),
            CoreValue::Box(inner) => write!(f, "({})", inner),
            CoreValue::Sender(_sender) => write!(f, "[[ sender ]]"),
            CoreValue::Receiver(_receiver) => write!(f, "[[ receiver ]]"),
        }
    }
}

impl From<Text> for CoreValue {
    fn from(value: Text) -> Self {
        CoreValue::Text(value)
    }
}

impl From<Endpoint> for CoreValue {
    fn from(value: Endpoint) -> Self {
        CoreValue::Endpoint(value)
    }
}

impl From<Range> for CoreValue {
    fn from(value: Range) -> Self {
        CoreValue::Range(value)
    }
}

impl From<Callable> for CoreValue {
    fn from(value: Callable) -> Self {
        CoreValue::Callable(value)
    }
}

impl From<Type> for CoreValue {
    fn from(value: Type) -> Self {
        CoreValue::Type(value)
    }
}

impl From<EntityTypeDefinition> for CoreValue {
    fn from(value: EntityTypeDefinition) -> Self {
        CoreValue::EntityTypeDefinition(value)
    }
}

impl From<Map> for CoreValue {
    fn from(value: Map) -> Self {
        CoreValue::Map(value)
    }
}

impl From<List> for CoreValue {
    fn from(value: List) -> Self {
        CoreValue::List(value)
    }
}

impl From<Decimal> for CoreValue {
    fn from(value: Decimal) -> Self {
        CoreValue::Decimal(value)
    }
}

impl From<TypedDecimal> for CoreValue {
    fn from(value: TypedDecimal) -> Self {
        CoreValue::TypedDecimal(value)
    }
}

impl From<Integer> for CoreValue {
    fn from(value: Integer) -> Self {
        CoreValue::Integer(value)
    }
}

impl From<TypedInteger> for CoreValue {
    fn from(value: TypedInteger) -> Self {
        CoreValue::TypedInteger(value)
    }
}

impl From<Boolean> for CoreValue {
    fn from(value: Boolean) -> Self {
        CoreValue::Boolean(value)
    }
}

impl From<Instant> for CoreValue {
    fn from(value: Instant) -> Self {
        CoreValue::Instant(value)
    }
}

#[cfg(test)]
/// This module contains tests for the CoreValue struct.
/// Each CoreValue is a representation of an underlying native value.
/// The tests cover addition, casting, and type conversions.
mod tests {
    use log::{debug, info};

    use super::*;
    use crate::traits::{
        convert_value::ConvertValue, get_core_lib_type_id::GetCoreLibTypeId,
    };

    #[test]
    fn type_construct() {
        let a = 42i32.to_value();
        assert_eq!(a.core_lib_type_id().to_string(), "integer/i32");
    }

    #[test]
    fn addition() {
        let a = 42i32.to_value();
        let b = 11i32.to_value();

        let a_plus_b = (a.clone() + b.clone()).unwrap();
        assert_eq!(a_plus_b.clone(), 53i32.to_value());
        info!("{} + {} = {}", a.clone(), b.clone(), a_plus_b.clone());
    }

    #[test]
    fn endpoint() {
        let endpoint: Endpoint = "@test"
            .to_string()
            .to_value()
            .try_into_core_value()
            .unwrap()
            .cast_to_endpoint()
            .unwrap();
        debug!("Endpoint: {endpoint}");
        assert_eq!(endpoint.to_string(), "@test");
    }

    #[test]
    pub fn range_from_core() {
        assert_eq!(
            CoreValue::Range(Range::new(
                CoreValue::Integer(Integer::from(11)).into(),
                CoreValue::Integer(Integer::from(13)).into()
            ))
            .to_string(),
            "11..13"
        );
    }
}