Skip to main content

datex_core/values/core_value/
mod.rs

1//! This module defines the [CoreValue] enum, which represents the fundamental value types in DATEX.
2//! Each variant of CoreValue holds the underlying value of a specific type, such as [Integer], [Text], or [List].
3//! CoreValues can be converted to and from native Rust types.
4
5use crate::{
6    libs::core::type_id::{
7        CoreLibBaseTypeId, CoreLibTypeId, CoreLibVariantTypeId,
8    },
9    prelude::*,
10    types::nominal_type_definition::NominalTypeDefinition,
11};
12use datex_macros_internal::FromCoreValue;
13pub mod serde_dif;
14use crate::{
15    types::r#type::Type,
16    values::{
17        core_values::{
18            boolean::Boolean,
19            callable::Callable,
20            decimal::{
21                Decimal,
22                typed_decimal::{DecimalTypeVariant, TypedDecimal},
23            },
24            endpoint::Endpoint,
25            integer::{
26                Integer,
27                typed_integer::{IntegerTypeVariant, TypedInteger},
28            },
29            list::List,
30            map::Map,
31            range::Range,
32            text::Text,
33        },
34        value_container::ValueContainer,
35    },
36};
37use core::fmt::{Display, Formatter};
38pub mod ops;
39
40#[derive(Clone, Debug, PartialEq, Eq, Hash, FromCoreValue)]
41pub enum CoreValue {
42    Null,
43    Boolean(Boolean),
44    Integer(Integer),
45    TypedInteger(TypedInteger),
46    Decimal(Decimal),
47    TypedDecimal(TypedDecimal),
48    Text(Text),
49    Endpoint(Endpoint),
50    List(List),
51    Map(Map),
52    Type(Type),
53    NominalTypeDefinition(NominalTypeDefinition),
54    Callable(Callable),
55    Range(Range),
56}
57mod child_iterator;
58pub mod datex_proxy;
59pub mod equality;
60
61impl From<&str> for CoreValue {
62    fn from(value: &str) -> Self {
63        CoreValue::Text(value.into())
64    }
65}
66impl From<String> for CoreValue {
67    fn from(value: String) -> Self {
68        CoreValue::Text(Text(value))
69    }
70}
71
72impl<T> From<Vec<T>> for CoreValue
73where
74    T: Into<ValueContainer>,
75{
76    fn from(vec: Vec<T>) -> Self {
77        CoreValue::List(vec.into())
78    }
79}
80
81impl<T> FromIterator<T> for CoreValue
82where
83    T: Into<ValueContainer>,
84{
85    fn from_iter<I: IntoIterator<Item = T>>(iter: I) -> Self {
86        CoreValue::List(List::new(iter.into_iter().map(Into::into).collect()))
87    }
88}
89
90impl From<bool> for CoreValue {
91    fn from(value: bool) -> Self {
92        CoreValue::Boolean(value.into())
93    }
94}
95
96impl From<i8> for CoreValue {
97    fn from(value: i8) -> Self {
98        CoreValue::TypedInteger(value.into())
99    }
100}
101impl From<i16> for CoreValue {
102    fn from(value: i16) -> Self {
103        CoreValue::TypedInteger(value.into())
104    }
105}
106impl From<i32> for CoreValue {
107    fn from(value: i32) -> Self {
108        CoreValue::TypedInteger(value.into())
109    }
110}
111impl From<i64> for CoreValue {
112    fn from(value: i64) -> Self {
113        CoreValue::TypedInteger(value.into())
114    }
115}
116impl From<i128> for CoreValue {
117    fn from(value: i128) -> Self {
118        CoreValue::TypedInteger(value.into())
119    }
120}
121
122impl From<u8> for CoreValue {
123    fn from(value: u8) -> Self {
124        CoreValue::TypedInteger(value.into())
125    }
126}
127impl From<u16> for CoreValue {
128    fn from(value: u16) -> Self {
129        CoreValue::TypedInteger(value.into())
130    }
131}
132impl From<u32> for CoreValue {
133    fn from(value: u32) -> Self {
134        CoreValue::TypedInteger(value.into())
135    }
136}
137impl From<u64> for CoreValue {
138    fn from(value: u64) -> Self {
139        CoreValue::TypedInteger(value.into())
140    }
141}
142impl From<u128> for CoreValue {
143    fn from(value: u128) -> Self {
144        CoreValue::TypedInteger(value.into())
145    }
146}
147
148impl From<f32> for CoreValue {
149    fn from(value: f32) -> Self {
150        CoreValue::TypedDecimal(value.into())
151    }
152}
153impl From<f64> for CoreValue {
154    fn from(value: f64) -> Self {
155        CoreValue::TypedDecimal(value.into())
156    }
157}
158
159impl From<usize> for CoreValue {
160    fn from(value: usize) -> Self {
161        #[cfg(target_pointer_width = "64")]
162        {
163            CoreValue::TypedInteger((value as u64).into())
164        }
165        #[cfg(target_pointer_width = "32")]
166        {
167            CoreValue::TypedInteger((value as u32).into())
168        }
169    }
170}
171
172impl From<isize> for CoreValue {
173    fn from(value: isize) -> Self {
174        #[cfg(target_pointer_width = "64")]
175        {
176            CoreValue::TypedInteger((value as i64).into())
177        }
178        #[cfg(target_pointer_width = "32")]
179        {
180            CoreValue::TypedInteger((value as i32).into())
181        }
182    }
183}
184
185impl From<&CoreValue> for CoreLibTypeId {
186    fn from(value: &CoreValue) -> Self {
187        match value {
188            CoreValue::Map(_) => CoreLibTypeId::Base(CoreLibBaseTypeId::Map),
189            CoreValue::List(_) => CoreLibTypeId::Base(CoreLibBaseTypeId::List),
190            CoreValue::Text(_) => CoreLibTypeId::Base(CoreLibBaseTypeId::Text),
191            CoreValue::Boolean(_) => {
192                CoreLibTypeId::Base(CoreLibBaseTypeId::Boolean)
193            }
194            CoreValue::TypedInteger(i) => CoreLibTypeId::Variant(
195                CoreLibVariantTypeId::Integer(i.variant()),
196            ),
197            CoreValue::TypedDecimal(d) => CoreLibTypeId::Variant(
198                CoreLibVariantTypeId::Decimal(d.variant()),
199            ),
200            CoreValue::Integer(_) => {
201                CoreLibTypeId::Base(CoreLibBaseTypeId::Integer)
202            }
203            CoreValue::Decimal(_) => {
204                CoreLibTypeId::Base(CoreLibBaseTypeId::Decimal)
205            }
206            CoreValue::Endpoint(_) => {
207                CoreLibTypeId::Base(CoreLibBaseTypeId::Endpoint)
208            }
209            CoreValue::Null => CoreLibTypeId::Base(CoreLibBaseTypeId::Null),
210            CoreValue::Type(_) => CoreLibTypeId::Base(CoreLibBaseTypeId::Type),
211            CoreValue::Callable(_) => {
212                CoreLibTypeId::Base(CoreLibBaseTypeId::Callable)
213            }
214            CoreValue::Range(_) => {
215                CoreLibTypeId::Base(CoreLibBaseTypeId::Range)
216            }
217            CoreValue::NominalTypeDefinition(_nominal_type) => {
218                CoreLibTypeId::Base(CoreLibBaseTypeId::Never) // TODO: what is the type of nominal type? do we even need to handle this?
219            }
220        }
221    }
222}
223
224impl CoreValue {
225    pub fn new<T>(value: T) -> CoreValue
226    where
227        CoreValue: From<T>,
228    {
229        value.into()
230    }
231
232    /// Check if the CoreValue is a combined value type (List, Map)
233    /// that contains inner ValueContainers.
234    pub fn is_collection_value(&self) -> bool {
235        core::matches!(self, CoreValue::List(_) | CoreValue::Map(_))
236    }
237
238    /// Get the default type of the CoreValue type definition.
239    /// This method uses the CoreLibPointerId to retrieve the corresponding
240    /// type reference from the core library.
241    /// For example, a CoreValue::TypedInteger(i32) will return the type ref integer/i32
242    pub fn default_core_type(&self) -> CoreLibTypeId {
243        CoreLibTypeId::from(self)
244    }
245
246    /// Tries to get a borrow of the current value as the specified type.
247    /// Does not perform any type conversion.
248    pub fn try_as<'a, T: 'a>(&'a self) -> Option<&'a T>
249    where
250        &'a T: TryFrom<&'a CoreValue>,
251    {
252        <&T>::try_from(self).ok()
253    }
254
255    pub fn try_as_mut<'a, T: 'a>(&'a mut self) -> Option<&'a mut T>
256    where
257        &'a mut T: TryFrom<&'a mut CoreValue>,
258    {
259        <&mut T>::try_from(self).ok()
260    }
261
262    /// Tries to convert the current value into the specific specified type.
263    /// Does not perform any type conversion.
264    pub fn try_into_value<T>(self) -> Option<T>
265    where
266        T: TryFrom<CoreValue>,
267    {
268        T::try_from(self).ok()
269    }
270
271    /// Casts the value to a [Text] value
272    /// Note: in contrast to [try_cast_to], [Text] values are not wrapped in quotation marks.
273    pub fn cast_to_text(&self) -> Text {
274        match self {
275            CoreValue::Text(text) => text.clone(),
276            _ => Text(self.to_string()),
277        }
278    }
279
280    pub fn cast_to_bool(&self) -> Option<Boolean> {
281        match self {
282            CoreValue::Text(text) => Some(Boolean(!text.0.is_empty())),
283            CoreValue::Boolean(bool) => Some(bool.clone()),
284            CoreValue::TypedInteger(int) => Some(Boolean(int.as_i128()? != 0)),
285            CoreValue::Null => Some(Boolean(false)),
286            _ => None,
287        }
288    }
289
290    pub fn cast_to_decimal(&self) -> Option<Decimal> {
291        match self {
292            CoreValue::Text(text) => {
293                text.to_string().parse::<f64>().ok().map(Decimal::from)
294            }
295            CoreValue::TypedInteger(int) => {
296                Some(Decimal::from(int.as_i128()? as f64))
297            }
298            CoreValue::TypedDecimal(decimal) => {
299                Some(Decimal::from(decimal.clone()))
300            }
301            CoreValue::Integer(int) => {
302                Some(Decimal::from(int.as_i128()? as f64))
303            }
304            CoreValue::Decimal(decimal) => Some(decimal.clone()),
305            _ => None,
306        }
307    }
308
309    pub fn cast_to_typed_decimal(
310        &self,
311        variant: DecimalTypeVariant,
312    ) -> Option<TypedDecimal> {
313        match self {
314            CoreValue::Text(text) => TypedDecimal::try_from_string_and_variant(
315                text.as_str(),
316                variant,
317            )
318            .ok(),
319            CoreValue::TypedInteger(int) => Some(
320                TypedDecimal::try_from_string_and_variant(
321                    &int.to_string(),
322                    variant,
323                )
324                .ok()?,
325            ),
326            CoreValue::TypedDecimal(decimal) => Some(
327                TypedDecimal::try_from_string_and_variant(
328                    &decimal.to_string(),
329                    variant,
330                )
331                .ok()?,
332            ),
333            CoreValue::Integer(int) => Some(
334                TypedDecimal::try_from_string_and_variant(
335                    &int.to_string(),
336                    variant,
337                )
338                .ok()?,
339            ),
340            CoreValue::Decimal(decimal) => Some(
341                TypedDecimal::try_from_string_and_variant(
342                    &decimal.to_string(),
343                    variant,
344                )
345                .ok()?,
346            ),
347            _ => None,
348        }
349    }
350
351    // FIXME #314 discuss here - shall we fit the integer in the minimum viable type?
352    pub fn _cast_to_integer_internal(&self) -> Option<TypedInteger> {
353        match self {
354            CoreValue::Text(text) => {
355                Integer::try_from_string(&text.to_string())
356                    .map(|x| Some(x.to_smallest_fitting()))
357                    .unwrap_or(None)
358            }
359            CoreValue::TypedInteger(int) => {
360                Some(int.to_smallest_fitting().clone())
361            }
362            CoreValue::Integer(int) => {
363                Some(TypedInteger::IBig(int.clone()).to_smallest_fitting())
364            }
365            CoreValue::Decimal(decimal) => Some(
366                TypedInteger::from(decimal.into_f64() as i128)
367                    .to_smallest_fitting(),
368            ),
369            CoreValue::TypedDecimal(decimal) => Some(
370                TypedInteger::from(decimal.as_f64() as i64)
371                    .to_smallest_fitting(),
372            ),
373            _ => None,
374        }
375    }
376
377    // TODO #315 improve conversion logic
378    pub fn cast_to_integer(&self) -> Option<Integer> {
379        match self {
380            CoreValue::Text(text) => {
381                Integer::try_from_string(&text.to_string()).ok()
382            }
383            CoreValue::TypedInteger(int) => Some(int.as_integer()),
384            CoreValue::Integer(int) => Some(int.clone()),
385            CoreValue::Decimal(decimal) => {
386                // FIXME #316 currently bad as f64 can be infinity or nan
387                // convert decimal directly to integer into_f64 is wrong here
388                Some(Integer::from(decimal.into_f64() as i128))
389            }
390            CoreValue::TypedDecimal(decimal) => {
391                decimal.as_integer().map(Integer::from)
392            }
393            _ => None,
394        }
395    }
396
397    pub fn cast_to_typed_integer(
398        &self,
399        variant: IntegerTypeVariant,
400    ) -> Option<TypedInteger> {
401        match self {
402            CoreValue::Text(text) => TypedInteger::try_from_string_and_variant(
403                text.as_str(),
404                variant,
405            )
406            .ok(),
407            CoreValue::TypedInteger(int) => {
408                TypedInteger::try_from_string_and_variant(
409                    &int.to_string(),
410                    variant,
411                )
412                .ok()
413            }
414            CoreValue::Integer(int) => {
415                TypedInteger::try_from_string_and_variant(
416                    int.to_string().as_str(),
417                    variant,
418                )
419                .ok()
420            }
421            CoreValue::Decimal(decimal) => {
422                Some(TypedInteger::from(decimal.into_f64() as i128))
423            }
424            CoreValue::TypedDecimal(decimal) => {
425                decimal.as_integer().map(TypedInteger::from)
426            }
427            _ => None,
428        }
429    }
430
431    pub fn cast_to_endpoint(&self) -> Option<Endpoint> {
432        match self {
433            CoreValue::Text(text) => Endpoint::try_from(text.as_str()).ok(),
434            CoreValue::Endpoint(endpoint) => Some(endpoint.clone()),
435            _ => None,
436        }
437    }
438}
439
440impl Display for CoreValue {
441    fn fmt(&self, f: &mut Formatter) -> core::fmt::Result {
442        match self {
443            CoreValue::Type(ty) => write!(f, "{ty}"),
444            CoreValue::Boolean(bool) => write!(f, "{bool}"),
445            CoreValue::TypedInteger(int) => write!(f, "{int}"),
446            CoreValue::TypedDecimal(decimal) => write!(f, "{decimal}"),
447            CoreValue::Text(text) => write!(f, "{text}"),
448            CoreValue::Null => write!(f, "null"),
449            CoreValue::Endpoint(endpoint) => write!(f, "{endpoint}"),
450            CoreValue::Map(map) => write!(f, "{map}"),
451            CoreValue::Range(range) => {
452                write!(f, "{}..{}", range.start, range.end)
453            }
454            CoreValue::Integer(integer) => write!(f, "{integer}"),
455            CoreValue::Decimal(decimal) => write!(f, "{decimal}"),
456            CoreValue::List(list) => write!(f, "{list}"),
457            CoreValue::Callable(_callable) => write!(f, "[[ callable ]]"),
458            CoreValue::NominalTypeDefinition(container) => {
459                write!(f, "{container}")
460            }
461        }
462    }
463}
464
465#[cfg(test)]
466/// This module contains tests for the CoreValue struct.
467/// Each CoreValue is a representation of an underlying native value.
468/// The tests cover addition, casting, and type conversions.
469mod tests {
470    use log::{debug, info};
471
472    use super::*;
473
474    #[test]
475    fn type_construct() {
476        let a = CoreValue::from(42i32);
477        assert_eq!(a.default_core_type().to_string(), "integer/i32");
478    }
479
480    #[test]
481    fn addition() {
482        let a = CoreValue::from(42i32);
483        let b = CoreValue::from(11i32);
484        let c = CoreValue::from("11");
485
486        let a_plus_b = (a.clone() + b.clone()).unwrap();
487        assert_eq!(a_plus_b.clone(), CoreValue::from(53));
488        info!("{} + {} = {}", a.clone(), b.clone(), a_plus_b.clone());
489    }
490
491    #[test]
492    fn endpoint() {
493        let endpoint: Endpoint =
494            CoreValue::from("@test").cast_to_endpoint().unwrap();
495        debug!("Endpoint: {endpoint}");
496        assert_eq!(endpoint.to_string(), "@test");
497    }
498
499    #[test]
500    pub fn range_from_core() {
501        assert_eq!(
502            CoreValue::from(Range {
503                start: Box::new(Integer::from(11).into()),
504                end: Box::new(Integer::from(13).into())
505            })
506            .to_string(),
507            "11..13"
508        );
509    }
510}