Skip to main content

datex_core/values/value/
mod.rs

1//! This module contains the implementation of the [Value] struct, which represents a value in the DATEX type system.
2//! A [Value] consists of a [CoreValue] representation and an optional custom type.
3use crate::{
4    prelude::*,
5    types::type_definition::{
6        TypeDefinition, callable::CallableTypeDefinition,
7    },
8    values::{
9        core_value::CoreValue,
10        core_values::{
11            callable::{Callable, CallableBody},
12            integer::typed_integer::TypedInteger,
13        },
14        value_container::{ValueContainer, value_key::BorrowedValueKey},
15    },
16};
17pub mod apply;
18mod child_iterator;
19pub mod datex_proxy;
20pub mod equality;
21pub mod ops;
22pub mod serde_dif;
23pub mod update_handler;
24
25use crate::shared_values::errors::AccessError;
26use core::{
27    fmt::{Display, Formatter},
28    result::Result,
29};
30
31#[derive(Clone, Debug, Eq, PartialEq, Hash)]
32pub struct Value {
33    pub inner: CoreValue,
34    // actual type of the value - if [None], use default type for given value
35    pub custom_type: Option<TypeDefinition>,
36}
37
38impl<T: Into<CoreValue>> From<T> for Value {
39    fn from(inner: T) -> Self {
40        let inner = inner.into();
41        Value {
42            inner,
43            custom_type: None,
44        }
45    }
46}
47
48impl Value {
49    pub fn null() -> Self {
50        CoreValue::Null.into()
51    }
52}
53
54impl Value {
55    pub fn callable(
56        name: Option<String>,
57        signature: CallableTypeDefinition,
58        body: CallableBody,
59    ) -> Self {
60        Value {
61            inner: CoreValue::Callable(Callable {
62                name,
63                signature: signature.clone(),
64                body,
65            }),
66            custom_type: Some(TypeDefinition::callable(signature)),
67        }
68    }
69
70    #[deprecated]
71    pub fn is_null(&self) -> bool {
72        core::matches!(self.inner, CoreValue::Null)
73    }
74    #[deprecated]
75    pub fn is_text(&self) -> bool {
76        core::matches!(self.inner, CoreValue::Text(_))
77    }
78    #[deprecated]
79    pub fn is_integer_i8(&self) -> bool {
80        core::matches!(
81            &self.inner,
82            CoreValue::TypedInteger(TypedInteger::I8(_))
83        )
84    }
85    #[deprecated]
86    pub fn is_map(&self) -> bool {
87        core::matches!(self.inner, CoreValue::Map(_))
88    }
89
90    /// Tries to get a borrow of the current value as the specified type.
91    /// Does not perform any type conversion.
92    pub fn try_as<'a, T: 'a>(&'a self) -> Option<&'a T>
93    where
94        &'a T: TryFrom<&'a CoreValue>,
95    {
96        <&T>::try_from(&self.inner).ok()
97    }
98
99    pub fn try_as_mut<'a, T: 'a>(&'a mut self) -> Option<&'a mut T>
100    where
101        &'a mut T: TryFrom<&'a mut CoreValue>,
102    {
103        <&mut T>::try_from(&mut self.inner).ok()
104    }
105
106    /// Tries to convert the current value into the specific specified type.
107    /// Does not perform any type conversion.
108    pub fn try_into_value<T>(self) -> Option<T>
109    where
110        T: TryFrom<CoreValue>,
111    {
112        T::try_from(self.inner).ok()
113    }
114
115    /// Returns true if the current Value's actual type is the same as its default type
116    /// E.g. if the type is integer for an Integer value, or integer/u8 for a typed integer value
117    /// This will return false for an integer value if the actual type is one of the following:
118    /// * an ImplType<integer, x>
119    /// * a new nominal type containing an integer
120    /// TODO #604: this does not match all cases of default types from the point of view of the compiler -
121    /// integer variants (despite bigint) can be distinguished based on the instruction code, but for text variants,
122    /// the variant must be included in the compiler output - so we need to handle theses cases as well.
123    /// Generally speaking, all variants except the few integer variants should never be considered default types.
124    pub fn has_default_type(&self) -> bool {
125        match &self.custom_type {
126            None => true,
127            Some(TypeDefinition::CoreType(core_type)) => {
128                core_type == &self.default_core_type()
129            }
130            Some(_) => false,
131        }
132    }
133
134    /// Returns the actual type, generating the default type from the provided memory if no custom typoe is set
135    pub fn actual_type(&self) -> TypeDefinition {
136        match &self.custom_type {
137            Some(actual_type) => actual_type.clone(),
138            None => TypeDefinition::CoreType(self.default_core_type()),
139        }
140    }
141
142    /// Gets a property on the value if applicable (e.g. for map and structs)
143    pub fn try_get_property<'a>(
144        &self,
145        key: impl Into<BorrowedValueKey<'a>>,
146    ) -> Result<ValueContainer, AccessError> {
147        match self.inner {
148            CoreValue::Map(ref map) => {
149                // If the value is a map, get the property
150                Ok(map.get(key)?.clone())
151            }
152            CoreValue::List(ref list) => {
153                if let Some(index) = key.into().try_as_index() {
154                    Ok(list.try_get(index)?.clone())
155                } else {
156                    Err(AccessError::InvalidIndexKey)
157                }
158            }
159            CoreValue::Text(ref text) => {
160                if let Some(index) = key.into().try_as_index() {
161                    let char = text.char_at(index)?;
162                    Ok(ValueContainer::from(char.to_string()))
163                } else {
164                    Err(AccessError::InvalidIndexKey)
165                }
166            }
167            _ => {
168                // If the value is not an map, we cannot get a property
169                Err(AccessError::InvalidOperation(
170                    "Cannot get property".to_string(),
171                ))
172            }
173        }
174    }
175
176    /// Takes (removes) a property from the value if applicable (e.g. for map and structs)
177    pub fn try_take_property<'a>(
178        &mut self,
179        key: impl Into<BorrowedValueKey<'a>>,
180    ) -> Result<ValueContainer, AccessError> {
181        match self.inner {
182            CoreValue::Map(ref mut map) => {
183                // If the value is a map, get the property
184                Ok(map.try_delete(key)?)
185            }
186            CoreValue::List(ref mut list) => {
187                if let Some(index) = key.into().try_as_index() {
188                    Ok(list.delete(index)?)
189                } else {
190                    Err(AccessError::InvalidIndexKey)
191                }
192            }
193            CoreValue::Text(ref text) => {
194                if let Some(index) = key.into().try_as_index() {
195                    let char = text.char_at(index)?;
196                    Ok(ValueContainer::from(char.to_string()))
197                } else {
198                    Err(AccessError::InvalidIndexKey)
199                }
200            }
201            _ => {
202                // If the value is not an map, we cannot get a property
203                Err(AccessError::InvalidOperation(
204                    "Cannot get property".to_string(),
205                ))
206            }
207        }
208    }
209
210    pub fn try_delete_property<'a>(
211        &mut self,
212        key: impl Into<BorrowedValueKey<'a>>,
213    ) -> Result<(), AccessError> {
214        match self.inner {
215            CoreValue::Map(ref mut map) => {
216                // If the value is a map, delete the property
217                map.try_delete(key)?;
218                Ok(())
219            }
220            CoreValue::List(ref mut list) => {
221                if let Some(index) = key.into().try_as_index() {
222                    list.delete(index)?;
223                    Ok(())
224                } else {
225                    Err(AccessError::InvalidIndexKey)
226                }
227            }
228            CoreValue::Text(_) => Err(AccessError::InvalidOperation(
229                "Cannot delete property on text".to_string(),
230            )),
231            _ => {
232                // If the value is not a map, we cannot delete a property
233                Err(AccessError::InvalidOperation(
234                    "Cannot delete property".to_string(),
235                ))
236            }
237        }
238    }
239
240    /// Sets a property on the value if applicable (e.g. for maps)
241    pub fn try_set_property<'a>(
242        &mut self,
243        key: impl Into<BorrowedValueKey<'a>>,
244        val: ValueContainer,
245    ) -> Result<(), AccessError> {
246        let key = key.into();
247
248        match self.inner {
249            CoreValue::Map(ref mut map) => {
250                // If the value is an map, set the property
251                map.try_set(key, val)?;
252            }
253            CoreValue::List(ref mut list) => {
254                if let Some(index) = key.try_as_index() {
255                    list.try_set(index, val)
256                        .map_err(AccessError::IndexOutOfBounds)?;
257                } else {
258                    return Err(AccessError::InvalidIndexKey);
259                }
260            }
261            CoreValue::Text(ref mut text) => {
262                if let Some(index) = key.try_as_index() {
263                    if let ValueContainer::Local(v) = &val
264                        && let CoreValue::Text(new_char) = &v.inner
265                        && new_char.0.len() == 1
266                    {
267                        let char = new_char.0.chars().next().unwrap_or('\0');
268                        text.set_char_at(index, char).map_err(|err| {
269                            AccessError::IndexOutOfBounds(err)
270                        })?;
271                    } else {
272                        return Err(AccessError::InvalidOperation(
273                            "Can only set char character in text".to_string(),
274                        ));
275                    }
276                } else {
277                    return Err(AccessError::InvalidIndexKey);
278                }
279            }
280            _ => {
281                // If the value is not a map, we cannot set a property
282                return Err(AccessError::InvalidOperation(format!(
283                    "Cannot set property '{}' on non-map value: {:?}",
284                    key, self
285                )));
286            }
287        }
288
289        Ok(())
290    }
291}
292
293impl Display for Value {
294    fn fmt(&self, f: &mut Formatter) -> core::fmt::Result {
295        core::write!(f, "{}", self.inner)
296    }
297}
298
299impl<T> From<Option<T>> for Value
300where
301    T: Into<Value>,
302{
303    fn from(opt: Option<T>) -> Self {
304        match opt {
305            Some(v) => v.into(),
306            None => Value::null(),
307        }
308    }
309}
310
311#[cfg(test)]
312/// Tests for the Value struct and its methods.
313/// This module contains unit tests for the Value struct, including its methods and operations.
314/// The value is a holder for a combination of a CoreValue representation and its actual type.
315mod tests {
316    use super::*;
317    use crate::{
318        assert_structural_eq, datex_list,
319        libs::core::type_id::{CoreLibBaseTypeId, CoreLibTypeId},
320        prelude::*,
321        types::{r#type::Type, type_definition::impl_type::ImplTypeDefinition},
322        values::core_values::{
323            endpoint::Endpoint,
324            integer::{Integer, typed_integer::TypedInteger},
325            list::List,
326        },
327    };
328    use core::str::FromStr;
329    use log::info;
330
331    #[test]
332    fn endpoint() {
333        let endpoint = Value::from(Endpoint::from_str("@test").unwrap());
334        assert_eq!(endpoint.to_string(), "@test");
335    }
336
337    #[test]
338    fn new_addition_assignments() {
339        let mut x = Value::from(42i8);
340        let y = Value::from(27i8);
341
342        x += y.clone();
343        assert_eq!(x, Value::from(69i8));
344    }
345
346    #[test]
347    fn new_additions() {
348        let x = Value::from(42i8);
349        let y = Value::from(27i8);
350
351        let z = (x.clone() + y.clone()).unwrap();
352        assert_eq!(z, Value::from(69i8));
353    }
354
355    #[test]
356    fn list() {
357        let mut a = List::from(vec![
358            Value::from("42"),
359            Value::from(42),
360            Value::from(true),
361        ]);
362
363        a.push(Value::from(42));
364        a.push(4);
365
366        assert_eq!(a.len(), 5);
367
368        let b = List::from(vec![0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]);
369        assert_eq!(b.len(), 11);
370
371        let c = datex_list![1, "test", 3, true, false];
372        assert_eq!(c.len(), 5);
373        assert_eq!(c[0], 1.into());
374        assert_eq!(c[1], "test".into());
375        assert_eq!(c[2], 3.into());
376    }
377
378    #[test]
379    fn boolean() {
380        let a = Value::from(true);
381        let b = Value::from(false);
382        let c = Value::from(false);
383        assert_ne!(a, b);
384        assert_eq!(b, c);
385
386        let d = (!b.clone()).unwrap();
387        assert_eq!(a, d);
388
389        // We can't add two booleans together, so this should return None
390        let a_plus_b = a.clone() + b.clone();
391        assert!(a_plus_b.is_err());
392    }
393
394    #[test]
395    fn equality_same_type() {
396        let a = Value::from(42i8);
397        let b = Value::from(42i8);
398        let c = Value::from(27i8);
399
400        assert_eq!(a, b);
401        assert_ne!(a, c);
402        assert_ne!(b, c);
403
404        info!("{} === {}", a.clone(), b.clone());
405        info!("{} !== {}", a.clone(), c.clone());
406    }
407
408    #[test]
409    fn decimal() {
410        let a = Value::from(42.1f32);
411        let b = Value::from(27f32);
412
413        let a_plus_b = (a.clone() + b.clone()).unwrap();
414        assert_eq!(a_plus_b, Value::from(69.1f32));
415        info!("{} + {} = {}", a.clone(), b.clone(), a_plus_b);
416    }
417
418    #[test]
419    fn null() {
420        let null_value = Value::null();
421        assert_eq!(null_value.to_string(), "null");
422
423        let maybe_value: Option<i8> = None;
424        let null_value = Value::from(maybe_value);
425        assert_eq!(null_value.to_string(), "null");
426        assert!(null_value.is_null());
427    }
428
429    #[test]
430    fn addition() {
431        let a = Value::from(42i8);
432        let b = Value::from(27i8);
433
434        let a_plus_b = (a.clone() + b.clone()).unwrap();
435        assert_eq!(a_plus_b, Value::from(69i8));
436        info!("{} + {} = {}", a.clone(), b.clone(), a_plus_b);
437    }
438
439    #[test]
440    fn string_concatenation() {
441        let a = Value::from("Hello ");
442        let b = Value::from(42i8);
443
444        assert!(a.is_text());
445        assert!(b.is_integer_i8());
446
447        let a_plus_b = (a.clone() + b.clone()).unwrap();
448        let b_plus_a = (b.clone() + a.clone()).unwrap();
449
450        assert!(a_plus_b.is_text());
451        assert!(b_plus_a.is_text());
452
453        assert_eq!(a_plus_b, Value::from("Hello 42"));
454        assert_eq!(b_plus_a, Value::from("42Hello "));
455
456        info!("{} + {} = {}", a.clone(), b.clone(), a_plus_b);
457        info!("{} + {} = {}", b.clone(), a.clone(), b_plus_a);
458    }
459
460    #[test]
461    fn structural_equality() {
462        let a = Value::from(42_i8);
463        let b = Value::from(42_i32);
464        assert!(a.is_integer_i8());
465
466        assert_structural_eq!(a, b);
467
468        assert_structural_eq!(
469            Value::from(TypedInteger::I8(42)),
470            Value::from(TypedInteger::U32(42)),
471        );
472
473        assert_structural_eq!(
474            Value::from(42_i8),
475            Value::from(Integer::from(42_i8))
476        );
477    }
478
479    #[test]
480    fn default_types() {
481        let val = Value::from(Integer::from(42));
482        assert!(val.has_default_type());
483
484        let val = Value::from(42i8);
485        assert!(val.has_default_type());
486
487        let val = Value {
488            inner: CoreValue::Integer(Integer::from(42)),
489            custom_type: Some(TypeDefinition::CoreType(
490                CoreLibBaseTypeId::Integer.into(),
491            )),
492        };
493
494        assert!(val.has_default_type());
495
496        let val = Value {
497            inner: CoreValue::Integer(Integer::from(42)),
498            custom_type: Some(TypeDefinition::ImplType(
499                ImplTypeDefinition::new(
500                    Type::core(CoreLibBaseTypeId::Integer),
501                    vec![],
502                ),
503            )),
504        };
505
506        assert!(!val.has_default_type());
507    }
508}