1use crate::{
4 prelude::*,
5 runtime::cache::shared_references_cache::SharedReferencesCache,
6 traits::convert_value::ConvertValue,
7 types::type_definition::{
8 TypeDefinition, callable::CallableTypeDefinition,
9 },
10 values::{
11 core_value::CoreValue,
12 core_value_with_classification::CoreValueWithClassification,
13 core_values::{
14 callable::{Callable, CallableBody},
15 native::DatexNative,
16 },
17 value_container::ValueContainer,
18 },
19};
20mod apply;
21pub mod borrowed_value;
22mod classification;
23mod convert_parts;
24mod convert_value;
25mod datex_hash;
26mod datex_native;
27mod equality;
28mod get_core_lib_type_id;
29mod get_datex_type;
30mod iter_parts;
31mod local_child_path_resolver;
32mod ops;
33mod serde_dif;
34#[cfg(feature = "ast")]
35mod to_datex_expression_data;
36mod to_instructions;
37mod update_handler;
38mod value_access;
39pub mod value_classification;
40
41use crate::{
42 shared_values::errors::AccessError,
43 traits::{
44 classification::Classification, convert_parts::FromParts,
45 value_access::ValueAccess,
46 },
47 utils::impl_display_for_datex_value::impl_display_for_datex_value,
48 value_updates::update_handler::InternalMutabilityUpdateHandler,
49 values::{
50 core_values::{
51 endpoint::Endpoint, native::NativeCoreValue, text::Text,
52 },
53 value::value_classification::{
54 ValueClassification,
55 unresolved_value_classification::UnresolvedValueClassification,
56 },
57 value_container::borrowed_value_container::{
58 BorrowedValueContainer, BorrowedValueContainerMut,
59 },
60 },
61};
62use core::{
63 fmt::{Debug, Formatter},
64 result::Result,
65};
66
67mod try_clone;
68
69#[derive(Debug, Clone)]
70pub enum Value {
74 Core(CoreValueWithClassification),
76 Native(NativeCoreValue),
78}
79
80impl<T: ConvertValue> From<T> for Value {
81 fn from(inner: T) -> Self {
82 inner.to_value()
83 }
84}
85
86impl From<&'static str> for Value {
87 fn from(value: &'static str) -> Self {
88 Value::core(CoreValue::Text(Text::StaticStr(value)))
89 }
90}
91
92impl Value {
93 pub fn native(value: impl DatexNative) -> Value {
95 Value::Native(NativeCoreValue::new(value))
96 }
97 pub fn native_boxed(value: Box<dyn DatexNative>) -> Value {
98 Value::Native(NativeCoreValue { value })
99 }
100
101 pub fn core(inner: impl Into<CoreValueWithClassification>) -> Self {
102 Value::Core(inner.into())
103 }
104
105 pub fn core_with_classification(
106 inner: impl Into<CoreValue>,
107 classification: ValueClassification,
108 ) -> Self {
109 Value::Core(CoreValueWithClassification {
110 inner: inner.into(),
111 classification,
112 })
113 }
114
115 pub fn is_collection_value(&self) -> bool {
116 match self {
117 Value::Core(core_value_with_classification) => {
118 core_value_with_classification.is_collection_value()
119 }
120 Value::Native(_) => false,
121 }
122 }
123
124 pub fn null() -> Self {
125 CoreValue::Null.into()
126 }
127
128 pub fn uninitialized() -> Self {
129 CoreValue::Uninitialized.into()
130 }
131
132 pub fn classification(
134 &self,
135 cache: &mut SharedReferencesCache,
136 ) -> ValueClassification {
137 match self {
138 Value::Core(core_value_with_classification) => {
139 core_value_with_classification.classification.clone()
140 }
141 Value::Native(native) => native.classification(cache),
142 }
143 }
144
145 pub fn unresolved_classification(&self) -> UnresolvedValueClassification {
149 match self {
150 Value::Core(core_value_with_classification) => {
151 core_value_with_classification.classification.clone().into()
152 }
153 Value::Native(native) => native.unresolved_classification(),
154 }
155 }
156
157 pub fn new(inner: impl ConvertValue) -> Self {
158 inner.to_value()
159 }
160
161 pub fn is_native(&self) -> bool {
163 matches!(&self, Value::Native(_))
164 }
165
166 pub fn is_uninitialized(&self) -> bool {
167 match self {
168 Value::Core(core_value_with_classification) => {
169 core_value_with_classification.is_uninitialized()
170 }
171 Value::Native(_) => false,
172 }
173 }
174
175 pub fn without_local_observers(mut self) -> Value {
178 self.set_update_callback_data(None);
179 self
180 }
181
182 pub fn boxed(value: impl Into<ValueContainer>) -> Self {
186 Value::from(CoreValue::Box(Box::new(value.into())))
187 }
188 pub fn unbox(self) -> Result<ValueContainer, Value> {
189 match self {
190 Value::Core(core_value_with_classification) => {
191 match core_value_with_classification.inner {
192 CoreValue::Box(boxed) => Ok(*boxed),
193 _ => Err(Value::Core(core_value_with_classification)),
194 }
195 }
196 _ => Err(self),
197 }
198 }
199
200 pub fn try_as<T>(&self) -> Option<&T>
203 where
204 T: ConvertValue + ?Sized,
205 {
206 T::try_borrow_from_value(self).ok()
207 }
208
209 pub fn try_as_mut<T>(&mut self) -> Option<&mut T>
210 where
211 T: ConvertValue,
212 {
213 T::try_borrow_mut_from_value(self).ok()
214 }
215
216 pub fn try_as_str(&self) -> Option<&str> {
220 if let Some(string) = self.try_as::<String>() {
221 Some(string.as_str())
222 }
223 else if let Some(text) = self.try_as::<Text>() {
225 Some(text.as_str())
226 } else {
227 None
228 }
229 }
230
231 pub fn try_into_value<T>(self) -> Result<T, Value>
234 where
235 T: ConvertValue,
236 {
237 T::try_from_value(self)
238 }
239
240 pub fn try_convert_into_value<T>(self) -> Result<T, ()>
243 where
244 T: ConvertValue + FromParts,
245 {
246 T::try_convert_from_value(self)
247 }
248
249 pub fn try_as_core_value(&self) -> Option<&CoreValue> {
251 match self {
252 Value::Core(core_value_with_classification) => {
253 Some(&core_value_with_classification.inner)
254 }
255 Value::Native(_native) => None,
256 }
257 }
258
259 pub fn try_as_core_value_mut(&mut self) -> Option<&mut CoreValue> {
261 match self {
262 Value::Core(core_value_with_classification) => {
263 Some(&mut core_value_with_classification.inner)
264 }
265 Value::Native(_native) => None,
266 }
267 }
268
269 pub fn try_into_core_value(self) -> Result<CoreValue, Value> {
271 match self {
272 Value::Core(core_value_with_classification) => {
273 Ok(core_value_with_classification.inner)
274 }
275 Value::Native(native) => Err(Value::Native(native)),
276 }
277 }
278}
279
280impl Value {
281 pub fn callable(
282 name: Option<String>,
283 signature: CallableTypeDefinition,
284 body: CallableBody,
285 creator: Endpoint,
286 ) -> Self {
287 Value::new(CoreValue::Callable(Callable {
288 name,
289 signature,
290 body,
291 creator,
292 docs: None,
293 }))
294 }
295
296 pub fn is_null(&self) -> bool {
297 match self {
298 Value::Core(core_value_with_classification) => {
299 core_value_with_classification.is_null()
300 }
301 Value::Native(_native_core_value) => false, }
303 }
304
305 pub fn downcast_native<T: DatexNative>(self) -> Option<Box<T>> {
308 if let Value::Native(native_value) = self {
309 native_value.into_any().downcast::<T>().ok()
310 } else {
311 None
312 }
313 }
314
315 pub fn downcast_native_ref<T: DatexNative>(&self) -> Option<&T> {
318 if let Value::Native(native_value) = self {
319 native_value.as_any().downcast_ref::<T>()
320 } else {
321 None
322 }
323 }
324
325 pub fn downcast_native_mut<T: DatexNative>(&mut self) -> Option<&mut T> {
328 if let Value::Native(native_value) = self {
329 native_value.as_any_mut().downcast_mut::<T>()
330 } else {
331 None
332 }
333 }
334
335 pub fn try_get_property(
337 &self,
338 key: &ValueContainer,
339 ) -> Result<BorrowedValueContainer<'_>, AccessError> {
340 <Self as ValueAccess>::try_get_property(self, key)
341 }
342
343 pub fn try_get_property_mut(
344 &mut self,
345 key: &ValueContainer,
346 ) -> Result<BorrowedValueContainerMut<'_>, AccessError> {
347 <Self as ValueAccess>::try_get_property_mut(self, key)
348 }
349
350 pub fn actual_type(&self) -> TypeDefinition {
352 match self {
353 Value::Core(core_value_with_classification) => {
354 core_value_with_classification.actual_type()
355 }
356 Value::Native(_native) => todo!(),
357 }
358 }
359}
360
361impl_display_for_datex_value!(
362 Value,
363 impl core::fmt::Display for Value {
364 fn fmt(&self, f: &mut Formatter) -> core::fmt::Result {
365 match self {
366 Value::Core(core_value_with_classification) => {
367 core::write!(f, "{}", core_value_with_classification)
368 }
369 Value::Native(native) => {
370 core::write!(f, "{}", native)
371 }
372 }
373 }
374 }
375);
376
377#[cfg(test)]
378mod tests {
382 use super::*;
383 use crate::{
384 traits::structural_eq::assert_structural_eq,
385 values::core_values::{
386 endpoint::Endpoint,
387 integer::{Integer, typed_integer::TypedInteger},
388 list::{List, datex_list},
389 },
390 };
391 use core::assert_matches;
392 use log::info;
393
394 #[test]
395 fn endpoint() {
396 let endpoint = Value::from(Endpoint::new("@test"));
397 assert!(!endpoint.is_native());
398
399 let endpoint_value = endpoint.try_into_value::<Endpoint>().unwrap();
400 assert_eq!(endpoint_value.to_string(), "@test");
401
402 let endpoint = Value::from(CoreValue::Endpoint(Endpoint::new("@test")));
403 assert!(!endpoint.is_native());
404 assert_eq!(
405 endpoint.try_into_value::<Endpoint>().unwrap().to_string(),
406 "@test"
407 );
408 }
409
410 #[test]
411 fn new_addition_assignments() {
412 let mut x = Value::from(42i8);
413 let y = Value::from(27i8);
414
415 x += y.clone();
416 assert_eq!(x, Value::from(69i8));
417 }
418
419 #[test]
420 fn new_additions() {
421 let x = Value::from(42i8);
422 let y = Value::from(27i8);
423
424 let z = (x.clone() + y.clone()).unwrap();
425 assert_eq!(z, Value::from(69i8));
426 }
427
428 #[test]
429 fn list() {
430 let mut a = List::from(vec![
431 Value::from("42".to_string()),
432 Value::from(42),
433 Value::from(true),
434 ]);
435
436 a.push(Value::from(42));
437 a.push(4);
438
439 assert_eq!(a.len(), 5);
440
441 let b = List::from(vec![0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]);
442 assert_eq!(b.len(), 11);
443
444 let c = datex_list![1, "test".to_string(), 3, true, false];
445 assert_eq!(c.len(), 5);
446 assert_eq!(c[0], 1.into());
447 assert_eq!(c[1], "test".to_string().into());
448 assert_eq!(c[2], 3.into());
449 }
450
451 #[test]
452 fn boolean() {
453 let a = Value::from(CoreValue::Boolean(true.into()));
454 let b = Value::from(CoreValue::Boolean(false.into()));
455 let c = Value::from(CoreValue::Boolean(false.into()));
456 assert_ne!(a, b);
457 assert_eq!(b, c);
458
459 let d = (!&b).unwrap();
460 assert_eq!(a, d);
461
462 let a_plus_b = &a + &b;
464 assert!(a_plus_b.is_err());
465 }
466
467 #[test]
468 fn equality_same_type() {
469 let a = Value::from(42i8);
470 let b = Value::from(42i8);
471 let c = Value::from(27i8);
472
473 assert_eq!(a, b);
474 assert_ne!(a, c);
475 assert_ne!(b, c);
476
477 info!("{} === {}", a.clone(), b.clone());
478 info!("{} !== {}", a.clone(), c.clone());
479 }
480
481 #[test]
482 fn decimal() {
483 let a = Value::from(42.1f32);
484 let b = Value::from(27f32);
485
486 let a_plus_b = (a.clone() + b.clone()).unwrap();
487 assert_eq!(a_plus_b, Value::from(69.1f32));
488 info!("{} + {} = {}", a.clone(), b.clone(), a_plus_b);
489 }
490
491 #[test]
492 fn null() {
493 let null_value = Value::null();
494 assert_eq!(null_value.to_string(), "null");
495
496 let maybe_value: Option<i8> = None;
497 let null_value = Value::from(maybe_value);
498 assert_eq!(
500 null_value.try_convert_into_value::<Option<i8>>().unwrap(),
501 None
502 );
503 }
504
505 #[test]
506 fn addition() {
507 let a = Value::from(42i8);
508 let b = Value::from(27i8);
509
510 let a_plus_b = (a.clone() + b.clone()).unwrap();
511 assert_eq!(a_plus_b, Value::from(69i8));
512 info!("{} + {} = {}", a.clone(), b.clone(), a_plus_b);
513 }
514
515 #[test]
516 fn string_concatenation() {
517 let a = Value::from("Hello ".to_string());
518 let b = Value::from(TypedInteger::I8(42i8));
519 assert!(matches!(a.try_as_core_value().unwrap(), CoreValue::Text(_)));
520 assert!(matches!(
521 b.try_as::<TypedInteger>().unwrap(),
522 TypedInteger::I8(_)
523 ));
524
525 let a_plus_b = (&a + &b).unwrap();
526 let b_plus_a = (&b + &a).unwrap();
527
528 assert!(matches!(
529 a_plus_b.try_as_core_value().unwrap(),
530 CoreValue::Text(_)
531 ));
532 assert!(matches!(
533 b_plus_a.try_as_core_value().unwrap(),
534 CoreValue::Text(_)
535 ));
536
537 assert_eq!(a_plus_b, Value::from("Hello 42".to_string()));
538 assert_eq!(b_plus_a, Value::from("42Hello ".to_string()));
539
540 info!("{} + {} = {}", a.clone(), b.clone(), a_plus_b);
541 info!("{} + {} = {}", b.clone(), a.clone(), b_plus_a);
542 }
543
544 #[test]
545 fn structural_equality() {
546 let a = Value::from(42_i8);
547 let b = Value::from(42_i32);
548 assert_matches!(
549 a.try_as_core_value().unwrap(),
550 CoreValue::TypedInteger(TypedInteger::I8(_))
551 );
552 assert_matches!(
553 b.try_as_core_value().unwrap(),
554 CoreValue::TypedInteger(TypedInteger::I32(_))
555 );
556 assert_ne!(a, b);
557
558 assert_structural_eq!(a, b);
559
560 assert_structural_eq!(
561 Value::from(TypedInteger::I8(42)),
562 Value::from(TypedInteger::U32(42)),
563 );
564
565 assert_structural_eq!(
566 Value::from(42_i8),
567 Value::from(Integer::from(42_i8))
568 );
569 }
570}