Skip to main content

datex_core/runtime/execution/
mod.rs

1//! This module contains the implementation of the execution engine which is responsible for executing compiled DATEX bytecode (DXB) and handling interrupts that can occur during execution, such as calling functions, loading pointers, and performing pointer updates.
2use crate::{
3    runtime::{
4        Runtime,
5        execution::{
6            context::{ExecutionMode, RemoteExecutionContext},
7            execution_loop::interrupts::{
8                ExternalExecutionInterrupt, InterruptResult,
9            },
10        },
11    },
12    traits::apply::{Apply, ApplyError},
13    values::value_container::ValueContainer,
14};
15
16use crate::{
17    libs::core::core_lib_id::CoreLibId,
18    shared_values::{
19        PointerAddress, ReferenceMutability, ReferencedSharedContainer,
20        RemotePointerAddress, SelfOwnedPointerAddress, SharedContainer,
21    },
22};
23use core::{result::Result, unreachable};
24pub use errors::*;
25pub use execution_input::{ExecutionInput, ExecutionOptions};
26pub use stack_dump::*;
27
28pub mod context;
29mod errors;
30pub mod execution_input;
31pub mod execution_loop;
32pub mod macros;
33mod stack_dump;
34
35#[cfg(all(test, feature = "std"))]
36mod test_remote_execution;
37
38pub fn execute_dxb_sync(
39    input: ExecutionInput,
40) -> Result<Option<ValueContainer>, ExecutionError> {
41    let runtime = input.runtime.clone();
42    let (interrupt_provider, execution_loop) = input.execution_loop();
43
44    for output in execution_loop {
45        match output? {
46            ExternalExecutionInterrupt::Result(result) => return Ok(result),
47            ExternalExecutionInterrupt::GetReferenceToRemotePointer(
48                address,
49                mutability,
50            ) => interrupt_provider.provide_result(
51                InterruptResult::ResolvedValue(
52                    get_remote_shared_container_reference(
53                        &runtime, address, mutability,
54                    )?
55                    .map(|v| {
56                        ValueContainer::Shared(SharedContainer::Referenced(v))
57                    }),
58                ),
59            ),
60            ExternalExecutionInterrupt::GetReferenceToLocalPointer(address) => {
61                // TODO #401: in the future, local pointer addresses should be relative to the block sender, not the local runtime
62                interrupt_provider.provide_result(
63                    InterruptResult::ResolvedValue(
64                        get_local_pointer_value(&runtime, address).map(|v| {
65                            ValueContainer::Shared(SharedContainer::Referenced(
66                                v,
67                            ))
68                        }),
69                    ),
70                );
71            }
72            ExternalExecutionInterrupt::GetCoreLibValue(id) => {
73                interrupt_provider.provide_result(
74                    InterruptResult::ResolvedValue(Some(
75                        get_core_lib_value_container(&runtime, id)?,
76                    )),
77                );
78            }
79            ExternalExecutionInterrupt::Apply(callee, args) => {
80                let res = handle_apply(&callee, &args)?;
81                interrupt_provider
82                    .provide_result(InterruptResult::ResolvedValue(res));
83            }
84            _ => return Err(ExecutionError::RequiresAsyncExecution),
85        }
86    }
87
88    Err(ExecutionError::RequiresAsyncExecution)
89}
90
91pub async fn execute_dxb(
92    input: ExecutionInput,
93) -> Result<Option<ValueContainer>, ExecutionError> {
94    let runtime = input.runtime.clone();
95    let caller_metadata = input.caller_metadata.clone();
96    let (interrupt_provider, execution_loop) = input.execution_loop();
97
98    for output in execution_loop {
99        match output? {
100            ExternalExecutionInterrupt::Result(result) => return Ok(result),
101            ExternalExecutionInterrupt::GetReferenceToRemotePointer(
102                address,
103                mutability,
104            ) => {
105                interrupt_provider.provide_result(
106                    InterruptResult::ResolvedValue(
107                        get_remote_shared_container_reference(
108                            &runtime, address, mutability,
109                        )?
110                        .map(|v| {
111                            ValueContainer::Shared(SharedContainer::Referenced(
112                                v,
113                            ))
114                        }),
115                    ),
116                );
117            }
118            ExternalExecutionInterrupt::GetReferenceToLocalPointer(address) => {
119                // TODO #402: in the future, local pointer addresses should be relative to the block sender, not the local runtime
120                interrupt_provider.provide_result(
121                    InterruptResult::ResolvedValue(
122                        get_local_pointer_value(&runtime, address).map(|v| {
123                            ValueContainer::Shared(SharedContainer::Referenced(
124                                v,
125                            ))
126                        }),
127                    ),
128                );
129            }
130            ExternalExecutionInterrupt::GetCoreLibValue(id) => {
131                interrupt_provider.provide_result(
132                    InterruptResult::ResolvedValue(Some(
133                        get_core_lib_value_container(&runtime, id)?,
134                    )),
135                );
136            }
137            ExternalExecutionInterrupt::RemoteExecution {
138                input,
139                mut receivers,
140            } => {
141                // assert that receivers is a single endpoint
142                assert_eq!(receivers.len(), 1);
143
144                let mut remote_execution_context = RemoteExecutionContext::new(
145                    receivers.remove(0),
146                    ExecutionMode::Static,
147                    runtime.clone(),
148                );
149                let res = runtime
150                    .execute_remote(&mut remote_execution_context, input)
151                    .await?;
152                interrupt_provider
153                    .provide_result(InterruptResult::ResolvedValue(res));
154            }
155            ExternalExecutionInterrupt::Apply(callee, args) => {
156                let res = handle_apply(&callee, &args)?;
157                interrupt_provider
158                    .provide_result(InterruptResult::ResolvedValue(res));
159            }
160            ExternalExecutionInterrupt::RequestMove(pointers) => {
161                let moved_values = runtime
162                    .internal
163                    .clone()
164                    .request_pointer_move(&caller_metadata.endpoint, pointers)
165                    .await?
166                    .into_iter()
167                    .map(|v| ValueContainer::Shared(SharedContainer::Owned(v)))
168                    .collect();
169                interrupt_provider.provide_result(
170                    InterruptResult::ResolvedValues(moved_values),
171                );
172            }
173            ExternalExecutionInterrupt::Move(address_mapping) => {
174                let moved_values =
175                    runtime.internal.clone().handle_pointer_move_to_remote(
176                        &caller_metadata.endpoint,
177                        address_mapping,
178                        &runtime.memory().borrow(),
179                    )?;
180                interrupt_provider.provide_result(
181                    InterruptResult::ResolvedValues(moved_values),
182                );
183            }
184        }
185    }
186
187    unreachable!("Execution loop should always return a result");
188}
189
190fn handle_apply(
191    callee: &ValueContainer,
192    args: &[ValueContainer],
193) -> Result<Option<ValueContainer>, ApplyError> {
194    // callee is guaranteed to be Some here
195    // apply_single if one arg, apply otherwise
196    Ok(if args.len() == 1 {
197        callee.try_apply_single(&args[0])?
198    } else {
199        callee.try_apply(args)?
200    })
201}
202
203fn get_remote_shared_container_reference(
204    runtime: &Runtime,
205    address: RemotePointerAddress,
206    _mutability: ReferenceMutability,
207) -> Result<Option<ReferencedSharedContainer>, ExecutionError> {
208    let address_provider = runtime.pointer_address_provider().borrow();
209    let memory = runtime.memory().borrow();
210    let resolved_address = address_provider.normalize_address(address);
211    // convert slot to InternalSlot enum
212    // TODO #770: resolve from remote, handle mutability
213    Ok(memory.get_reference(&resolved_address).cloned())
214}
215
216fn get_core_lib_value_container(
217    runtime: &Runtime,
218    id: CoreLibId,
219) -> Result<ValueContainer, ExecutionError> {
220    let value = runtime.core_library().value_or_type_by_id(id);
221    Ok(ValueContainer::Local(value.clone()))
222}
223
224fn get_local_pointer_value(
225    runtime: &Runtime,
226    address: SelfOwnedPointerAddress,
227) -> Option<ReferencedSharedContainer> {
228    // convert slot to InternalSlot enum
229    runtime
230        .memory()
231        .borrow()
232        .get_reference(&PointerAddress::SelfOwned(address))
233        .cloned()
234}
235
236#[cfg(test)]
237#[cfg(feature = "compiler")]
238mod tests {
239    use super::*;
240    use crate::{
241        assert_structural_eq, assert_value_eq,
242        collections::HashMap,
243        compiler::{CompileOptions, compile_script, scope::CompilationScope},
244        core_compiler::core_compilation_context::DXBWithSharedValues,
245        datex_list,
246        libs::core::type_id::CoreLibBaseTypeId,
247        prelude::*,
248        runtime::{
249            Runtime, RuntimeConfig, RuntimeRunner,
250            execution::{
251                context::{ExecutionContext, LocalExecutionContext},
252                execution_input::{ExecutionCallerMetadata, ExecutionOptions},
253            },
254        },
255        shared_values::{
256            OwnedSharedContainer, ReferencedSharedContainer, SharedContainer,
257            SharedContainerInner, SharedContainerMutability,
258            base_shared_value_container::BaseSharedValueContainer,
259        },
260        traits::{structural_eq::StructuralEq, value_eq::ValueEq},
261        types::{
262            r#type::Type,
263            type_definition::{
264                TypeDefinition, tagged_type::TaggedTypeDefinition,
265            },
266        },
267        values::{
268            core_value::CoreValue,
269            core_values::{
270                decimal::Decimal,
271                endpoint::Endpoint,
272                integer::{Integer, typed_integer::TypedInteger},
273                list::List,
274                map::Map,
275            },
276            value::Value,
277        },
278    };
279    use core::assert_matches;
280    use log::{debug, info};
281
282    fn execute_datex_script_debug(
283        datex_script: &str,
284    ) -> Option<ValueContainer> {
285        let runtime = Runtime::stub();
286        let (dxb, _) = compile_script(
287            datex_script,
288            CompileOptions::default(),
289            runtime.clone(),
290        )
291        .unwrap();
292        let context = ExecutionInput::new(
293            DXBWithSharedValues::new(dxb, vec![]),
294            ExecutionCallerMetadata::local_default(),
295            ExecutionOptions { verbose: true },
296            runtime,
297        );
298        execute_dxb_sync(context).unwrap()
299    }
300
301    fn execute_datex_script_debug_unbounded(
302        datex_script_parts: impl Iterator<Item = &'static str>,
303        runtime: Runtime,
304    ) -> impl Iterator<Item = Result<Option<ValueContainer>, ExecutionError>>
305    {
306        gen move {
307            let datex_script_parts = datex_script_parts.collect::<Vec<_>>();
308            let mut execution_context =
309                ExecutionContext::Local(LocalExecutionContext::new(
310                    ExecutionMode::unbounded(),
311                    runtime.clone(),
312                    ExecutionCallerMetadata::local_default(),
313                ));
314            let mut compilation_scope =
315                CompilationScope::new(ExecutionMode::unbounded());
316
317            let len = datex_script_parts.len();
318            for (index, script_part) in
319                datex_script_parts.into_iter().enumerate()
320            {
321                // if last part, compile and return static value if possible
322                if index == len - 1 {
323                    compilation_scope.mark_as_last_execution();
324                }
325
326                let (dxb, new_compilation_scope) = compile_script(
327                    script_part,
328                    CompileOptions::new(
329                        compilation_scope,
330                        vec![Endpoint::LOCAL],
331                    ),
332                    runtime.clone(),
333                )
334                .unwrap();
335                compilation_scope = new_compilation_scope;
336                yield execution_context
337                    .execute_dxb_sync(DXBWithSharedValues::new(dxb, vec![]));
338            }
339        }
340    }
341
342    fn assert_unbounded_input_matches_output(
343        input: Vec<&'static str>,
344        expected_output: Vec<Option<ValueContainer>>,
345        runtime: Runtime,
346    ) {
347        let input = input.into_iter();
348        let expected_output = expected_output.into_iter();
349        for (result, expected) in execute_datex_script_debug_unbounded(
350            input.into_iter(),
351            runtime.clone(),
352        )
353        .zip(expected_output.into_iter())
354        {
355            let result = result.unwrap();
356            assert_eq!(result, expected);
357        }
358    }
359
360    fn execute_datex_script_debug_with_error(
361        datex_script: &str,
362    ) -> Result<Option<ValueContainer>, ExecutionError> {
363        let runtime = Runtime::stub();
364        let (dxb, _) = compile_script(
365            datex_script,
366            CompileOptions::default(),
367            runtime.clone(),
368        )
369        .unwrap();
370        let context = ExecutionInput::new(
371            DXBWithSharedValues::new(dxb, vec![]),
372            ExecutionCallerMetadata::local_default(),
373            ExecutionOptions { verbose: true },
374            runtime,
375        );
376        execute_dxb_sync(context)
377    }
378
379    fn execute_datex_script_debug_with_result(
380        datex_script: &str,
381    ) -> ValueContainer {
382        execute_datex_script_debug(datex_script).unwrap()
383    }
384
385    async fn execute_datex_script_with_runtime(
386        config: RuntimeConfig,
387        datex_script: &str,
388    ) -> Result<Option<ValueContainer>, ExecutionError> {
389        RuntimeRunner::new(config)
390            .run(async |runtime| {
391                let (dxb, _) = compile_script(
392                    datex_script,
393                    CompileOptions::default(),
394                    runtime.clone(),
395                )
396                .unwrap();
397                let context = ExecutionInput::new(
398                    DXBWithSharedValues::new(dxb, vec![]),
399                    ExecutionCallerMetadata::local_default(),
400                    ExecutionOptions { verbose: true },
401                    runtime,
402                );
403                execute_dxb(context).await
404            })
405            .await
406    }
407
408    #[test]
409    fn empty_script() {
410        assert_eq!(execute_datex_script_debug(""), None);
411    }
412
413    #[test]
414    fn empty_script_semicolon() {
415        assert_eq!(execute_datex_script_debug(";;;"), None);
416    }
417
418    #[test]
419    fn single_value() {
420        assert_eq!(
421            execute_datex_script_debug_with_result("42"),
422            Integer::from(42i8).into()
423        );
424    }
425
426    #[test]
427    fn single_value_semicolon() {
428        assert_eq!(execute_datex_script_debug("42;"), None)
429    }
430
431    #[test]
432    fn is() {
433        let result = execute_datex_script_debug_with_result("1 is 1");
434        assert_eq!(result, false.into());
435        assert_structural_eq!(result, ValueContainer::from(false));
436    }
437
438    #[test]
439    fn equality() {
440        let result = execute_datex_script_debug_with_result("1 == 1");
441        assert_eq!(result, true.into());
442        assert_structural_eq!(result, ValueContainer::from(true));
443
444        let result = execute_datex_script_debug_with_result("1 == 2");
445        assert_eq!(result, false.into());
446        assert_structural_eq!(result, ValueContainer::from(false));
447
448        let result = execute_datex_script_debug_with_result("1 != 2");
449        assert_eq!(result, true.into());
450        assert_structural_eq!(result, ValueContainer::from(true));
451
452        let result = execute_datex_script_debug_with_result("1 != 1");
453        assert_eq!(result, false.into());
454        assert_structural_eq!(result, ValueContainer::from(false));
455        let result = execute_datex_script_debug_with_result("1 === 1");
456        assert_eq!(result, true.into());
457
458        assert_structural_eq!(result, ValueContainer::from(true));
459        let result = execute_datex_script_debug_with_result("1 !== 2");
460        assert_eq!(result, true.into());
461        assert_structural_eq!(result, ValueContainer::from(true));
462
463        let result = execute_datex_script_debug_with_result("1 !== 1");
464        assert_eq!(result, false.into());
465        assert_structural_eq!(result, ValueContainer::from(false));
466    }
467
468    #[test]
469    fn single_value_scope() {
470        let result = execute_datex_script_debug_with_result("(42)");
471        assert_eq!(result, Integer::from(42i8).into());
472        assert_structural_eq!(result, ValueContainer::from(42_u128));
473    }
474
475    #[test]
476    fn add() {
477        let result = execute_datex_script_debug_with_result("1 + 2");
478        assert_eq!(result, Integer::from(3i8).into());
479        assert_structural_eq!(result, ValueContainer::from(3i8));
480    }
481
482    #[test]
483    fn nested_scope() {
484        let result = execute_datex_script_debug_with_result("1 + (2 + 3)");
485        assert_eq!(result, Integer::from(6i8).into());
486    }
487
488    #[test]
489    fn empty_list() {
490        let result = execute_datex_script_debug_with_result("[]");
491        let list: &List = result.try_as().unwrap();
492        assert_eq!(list.len(), 0);
493        assert_eq!(result, Vec::<ValueContainer>::new().into());
494        assert_eq!(result, ValueContainer::from(Vec::<ValueContainer>::new()));
495    }
496
497    #[test]
498    fn empty_tag() {
499        let result = execute_datex_script_debug_with_result("#Example");
500        if let ValueContainer::Local(value) = result {
501            assert_eq!(&value.inner, &CoreValue::Null);
502            assert_eq!(
503                &value.custom_type,
504                &Some(TypeDefinition::TaggedType(TaggedTypeDefinition {
505                    tag: "Example".to_string(),
506                    ty: Some(Box::new(Type::Alias(
507                        TypeDefinition::CoreType(
508                            CoreLibBaseTypeId::Unit.into()
509                        )
510                        .into()
511                    ))),
512                }))
513            )
514        } else {
515            panic!("Result should be Local value");
516        }
517    }
518
519    #[test]
520    fn empty_with_map() {
521        let result =
522            execute_datex_script_debug_with_result("#Example {a: true}");
523        if let ValueContainer::Local(value) = result {
524            assert_eq!(
525                &value.inner,
526                &CoreValue::Map(Map::StructuralWithStringKeys(vec![(
527                    "a".to_string(),
528                    ValueContainer::from(true)
529                )]))
530            );
531            assert_eq!(
532                &value.custom_type,
533                &Some(
534                    TypeDefinition::TaggedType(TaggedTypeDefinition {
535                        tag: "Example".to_string(),
536                        ty: None,
537                    })
538                    .into()
539                )
540            )
541        } else {
542            panic!("Result should be Local value");
543        }
544    }
545
546    #[test]
547    fn list() {
548        let result = execute_datex_script_debug_with_result("[1, 2, 3]");
549        let list: &List = result.try_as().unwrap();
550        let expected = datex_list![
551            Integer::from(1i8),
552            Integer::from(2i8),
553            Integer::from(3i8)
554        ];
555        assert_eq!(list.len(), 3);
556        assert_eq!(result, expected.into());
557        assert_ne!(result, ValueContainer::from(vec![1, 2, 3]));
558        assert_structural_eq!(result, ValueContainer::from(vec![1, 2, 3]));
559    }
560
561    #[test]
562    fn list_with_nested_scope() {
563        let result = execute_datex_script_debug_with_result("[1, (2 + 3), 4]");
564        let expected = datex_list![
565            Integer::from(1i8),
566            Integer::from(5i8),
567            Integer::from(4i8)
568        ];
569
570        assert_eq!(result, expected.into());
571        assert_ne!(result, ValueContainer::from(vec![1_u8, 5_u8, 4_u8]));
572        assert_structural_eq!(
573            result,
574            ValueContainer::from(vec![1_u8, 5_u8, 4_u8])
575        );
576    }
577
578    #[test]
579    fn boolean() {
580        let result = execute_datex_script_debug_with_result("true");
581        assert_eq!(result, true.into());
582        assert_structural_eq!(result, ValueContainer::from(true));
583
584        let result = execute_datex_script_debug_with_result("false");
585        assert_eq!(result, false.into());
586        assert_structural_eq!(result, ValueContainer::from(false));
587    }
588
589    #[test]
590    fn decimal() {
591        let result = execute_datex_script_debug_with_result("1.5");
592        assert_eq!(result, Decimal::try_from_string("1.5").unwrap().into());
593        assert_structural_eq!(result, ValueContainer::from(1.5));
594    }
595
596    #[test]
597    fn decimal_and_integer() {
598        let result = execute_datex_script_debug_with_result("-2341324.0");
599        assert_eq!(
600            result,
601            Decimal::try_from_string("-2341324").unwrap().into()
602        );
603        assert!(!result.structural_eq(&ValueContainer::from(-2341324)));
604    }
605
606    #[test]
607    fn integer() {
608        let result = execute_datex_script_debug_with_result("2");
609        assert_eq!(result, Integer::from(2).into());
610        assert_ne!(result, 2_u8.into());
611        assert_structural_eq!(result, ValueContainer::from(2_i8));
612    }
613
614    #[test]
615    fn typed_integer() {
616        let result = execute_datex_script_debug_with_result("-2i16");
617        assert_eq!(result, TypedInteger::from(-2i16).into());
618        assert_structural_eq!(result, ValueContainer::from(-2_i16));
619
620        let result = execute_datex_script_debug_with_result("2i32");
621        assert_eq!(result, TypedInteger::from(2i32).into());
622        assert_structural_eq!(result, ValueContainer::from(2_i32));
623
624        let result = execute_datex_script_debug_with_result("-2i64");
625        assert_eq!(result, TypedInteger::from(-2i64).into());
626        assert_structural_eq!(result, ValueContainer::from(-2_i64));
627
628        let result = execute_datex_script_debug_with_result("2i128");
629        assert_eq!(result, TypedInteger::from(2i128).into());
630        assert_structural_eq!(result, ValueContainer::from(2_i128));
631
632        let result = execute_datex_script_debug_with_result("2u8");
633        assert_eq!(result, TypedInteger::from(2_u8).into());
634        assert_structural_eq!(result, ValueContainer::from(2_u8));
635
636        let result = execute_datex_script_debug_with_result("2u16");
637        assert_eq!(result, TypedInteger::from(2_u16).into());
638        assert_structural_eq!(result, ValueContainer::from(2_u16));
639
640        let result = execute_datex_script_debug_with_result("2u32");
641        assert_eq!(result, TypedInteger::from(2_u32).into());
642        assert_structural_eq!(result, ValueContainer::from(2_u32));
643
644        let result = execute_datex_script_debug_with_result("2u64");
645        assert_eq!(result, TypedInteger::from(2_u64).into());
646        assert_structural_eq!(result, ValueContainer::from(2_u64));
647
648        let result = execute_datex_script_debug_with_result("2u128");
649        assert_eq!(result, TypedInteger::from(2_u128).into());
650        assert_structural_eq!(result, ValueContainer::from(2_u128));
651
652        let result = execute_datex_script_debug_with_result("2ibig");
653        assert_eq!(result, TypedInteger::IBig(Integer::from(2)).into());
654        assert_structural_eq!(result, ValueContainer::from(2));
655    }
656
657    #[test]
658    fn null() {
659        let result = execute_datex_script_debug_with_result("null");
660        assert_eq!(result, ValueContainer::from(CoreValue::Null));
661        assert_eq!(result, CoreValue::Null.into());
662        assert_structural_eq!(result, ValueContainer::from(CoreValue::Null));
663    }
664
665    #[test]
666    fn map() {
667        let result =
668            execute_datex_script_debug_with_result("{x: 1, y: 2, z: 42}");
669        let map: CoreValue = result.get_cloned_value().inner;
670        let map: Map = map.try_into().unwrap();
671
672        // form and size
673        assert_eq!(map.to_string(), "{\"x\": 1, \"y\": 2, \"z\": 42}");
674        assert_eq!(map.size(), 3);
675
676        info!("Map: {:?}", map);
677
678        // access by key
679        assert_eq!(map.get("x"), Ok(&Integer::from(1).into()));
680        assert_eq!(map.get("y"), Ok(&Integer::from(2).into()));
681        assert_eq!(map.get("z"), Ok(&Integer::from(42).into()));
682
683        // structural equality checks
684        let expected_se: Map = Map::from(vec![
685            ("x".to_string(), 1.into()),
686            ("y".to_string(), 2.into()),
687            ("z".to_string(), 42.into()),
688        ]);
689        assert_structural_eq!(map, expected_se);
690
691        // strict equality checks
692        let expected_strict: Map = Map::from(vec![
693            ("x".to_string(), Integer::from(1).into()),
694            ("y".to_string(), Integer::from(2).into()),
695            ("z".to_string(), Integer::from(42).into()),
696        ]);
697        debug!("Expected map: {expected_strict}");
698        debug!("Map result: {map}");
699        // FIXME #104 type information gets lost on compile
700        // assert_eq!(result, expected.into());
701    }
702
703    #[test]
704    fn empty_map() {
705        let result = execute_datex_script_debug_with_result("{}");
706        let map: CoreValue = result.clone().get_cloned_value().inner;
707        let map: Map = map.try_into().unwrap();
708
709        // form and size
710        assert_eq!(map.to_string(), "{}");
711        assert_eq!(map.size(), 0);
712
713        info!("Map: {:?}", map);
714    }
715
716    #[test]
717    fn statements() {
718        let result = execute_datex_script_debug_with_result("1; 2; 3");
719        assert_eq!(result, Integer::from(3).into());
720    }
721
722    #[test]
723    fn single_terminated_statement() {
724        let result = execute_datex_script_debug("1;");
725        assert_eq!(result, None);
726    }
727
728    #[test]
729    fn const_declaration() {
730        let result = execute_datex_script_debug_with_result("const x = 42; x");
731        assert_eq!(result, Integer::from(42).into());
732    }
733
734    #[test]
735    fn const_declaration_with_addition() {
736        let result =
737            execute_datex_script_debug_with_result("const x = 1 + 2; x");
738        assert_eq!(result, Integer::from(3).into());
739    }
740
741    #[test]
742    fn unbox_shared() {
743        let result =
744            execute_datex_script_debug_with_result("const x = shared 42; *x");
745        assert_eq!(result, ValueContainer::from(Integer::from(42)));
746    }
747
748    #[test]
749    fn shared_creation_mut_ref_to_mut() {
750        let result = execute_datex_script_debug_with_result(
751            "const x = 'mut shared mut 42; x",
752        );
753        assert_matches!(result, ValueContainer::Shared(SharedContainer::Referenced(ref container)) if
754            container.container_mutability().clone() == SharedContainerMutability::Mutable &&
755            container.reference_mutability() == ReferenceMutability::Mutable
756        );
757        assert_value_eq!(result, ValueContainer::from(Integer::from(42)));
758    }
759
760    #[test]
761    fn shared_creation_immut_ref_to_mut() {
762        let result = execute_datex_script_debug_with_result(
763            "const x = 'shared mut 42; x",
764        );
765        assert_matches!(result, ValueContainer::Shared(SharedContainer::Referenced(ref container)) if
766            container.container_mutability().clone() == SharedContainerMutability::Mutable &&
767            container.reference_mutability() == ReferenceMutability::Immutable
768        );
769
770        assert_value_eq!(result, ValueContainer::from(Integer::from(42)));
771    }
772
773    #[test]
774    fn shared_creation_immut_ref() {
775        let result =
776            execute_datex_script_debug_with_result("const x = 'shared 42; x");
777        assert_matches!(result, ValueContainer::Shared(SharedContainer::Referenced(ref container)) if
778            container.container_mutability().clone() == SharedContainerMutability::Immutable &&
779            container.reference_mutability() == ReferenceMutability::Immutable
780        );
781
782        assert_value_eq!(result, ValueContainer::from(Integer::from(42)));
783    }
784
785    #[test]
786    fn shared_creation_immut() {
787        let result =
788            execute_datex_script_debug_with_result("const x = shared 42; x");
789        assert_matches!(result, ValueContainer::Shared(SharedContainer::Owned(ref container)) if
790            container.container_mutability().clone() == SharedContainerMutability::Immutable
791        );
792
793        assert_value_eq!(result, ValueContainer::from(Integer::from(42)));
794    }
795
796    #[test]
797    fn shared_creation_mut() {
798        let result = execute_datex_script_debug_with_result(
799            "const x = shared mut 42; x",
800        );
801        assert_matches!(result, ValueContainer::Shared(SharedContainer::Owned(
802            ref container @ OwnedSharedContainer { .. }
803        )) if container.container_mutability().clone() == SharedContainerMutability::Mutable);
804        assert_value_eq!(result, ValueContainer::from(Integer::from(42)));
805    }
806
807    #[test]
808    fn shared_creation_mut_ref_to_immut() {
809        let result = execute_datex_script_debug_with_error(
810            "const x = 'mut shared 42; x",
811        );
812        assert_matches!(
813            result,
814            Err(ExecutionError::MutableReferenceToNonMutableValue)
815        );
816    }
817
818    #[test]
819    fn shared_value_add_assignment() {
820        let result = execute_datex_script_debug_with_result(
821            "var x = shared mut 42; *x += 1; x",
822        );
823
824        assert_value_eq!(result, ValueContainer::from(Integer::from(43)));
825        assert_matches!(result, ValueContainer::Shared(..));
826        if let ValueContainer::Shared(shared) = &result {
827            assert_eq!(
828                *shared.inner().base_shared_container().mutability(),
829                SharedContainerMutability::Mutable
830            );
831        } else {
832            panic!("Expected shared value");
833        }
834    }
835
836    #[test]
837    fn shared_value_sub_assignment() {
838        let result = execute_datex_script_debug_with_result(
839            "const x = 'mut shared mut 42; *x -= 1; x",
840        );
841
842        assert_matches!(result, ValueContainer::Shared(..));
843        assert_value_eq!(result, ValueContainer::from(Integer::from(41)));
844    }
845
846    #[test]
847    fn shared_value_assignment() {
848        let result = execute_datex_script_debug_with_result(
849            "const x = 'mut shared mut 42; *x = 100; x",
850        );
851
852        assert_matches!(result, ValueContainer::Shared(..));
853        assert_value_eq!(result, ValueContainer::from(Integer::from(100)));
854    }
855
856    #[tokio::test]
857    async fn env_slot() {
858        let res = execute_datex_script_with_runtime(
859            RuntimeConfig {
860                env: Some(HashMap::from([(
861                    "TEST_ENV_VAR".to_string(),
862                    "test_value".to_string(),
863                )])),
864                ..Default::default()
865            },
866            "$.env",
867        )
868        .await
869        .unwrap();
870        assert!(res.is_some());
871        let env = res.unwrap().try_into_value::<Map>().unwrap();
872        assert_eq!(env.get("TEST_ENV_VAR"), Ok(&"test_value".into()));
873    }
874
875    #[test]
876    fn shebang() {
877        let result = execute_datex_script_debug_with_result("#!datex\n42");
878        assert_eq!(result, Integer::from(42).into());
879    }
880
881    #[test]
882    fn single_line_comment() {
883        let result =
884            execute_datex_script_debug_with_result("// this is a comment\n42");
885        assert_eq!(result, Integer::from(42).into());
886
887        let result = execute_datex_script_debug_with_result(
888            "// this is a comment\n// another comment\n42",
889        );
890        assert_eq!(result, Integer::from(42).into());
891    }
892
893    #[test]
894    fn multi_line_comment() {
895        let result = execute_datex_script_debug_with_result(
896            "/* this is a comment */\n42",
897        );
898        assert_eq!(result, Integer::from(42).into());
899
900        let result = execute_datex_script_debug_with_result(
901            "/* this is a comment\n   with multiple lines */\n42",
902        );
903        assert_eq!(result, Integer::from(42).into());
904
905        let result = execute_datex_script_debug_with_result("[1, /* 2, */ 3]");
906        let expected = datex_list![Integer::from(1), Integer::from(3)];
907        assert_eq!(result, expected.into());
908    }
909
910    #[test]
911    fn continuous_execution() {
912        assert_unbounded_input_matches_output(
913            vec!["1", "2"],
914            vec![Some(Integer::from(1).into()), Some(Integer::from(2).into())],
915            Runtime::stub(),
916        )
917    }
918
919    #[test]
920    fn resolve_core_lib_type_reference() {
921        let result = execute_datex_script_debug_with_result("integer");
922        assert_eq!(
923            result,
924            ValueContainer::Local(Value::from(Type::core(
925                CoreLibBaseTypeId::Integer,
926            )))
927        );
928    }
929
930    #[test]
931    fn continuous_execution_multiple_external_interrupts() {
932        let runtime = Runtime::stub();
933
934        assert_unbounded_input_matches_output(
935            vec!["1", "integer", "boolean"],
936            vec![
937                Some(Integer::from(1).into()),
938                Some(ValueContainer::Local(Value::from(Type::core(
939                    CoreLibBaseTypeId::Integer,
940                )))),
941                Some(ValueContainer::Local(Value::from(Type::core(
942                    CoreLibBaseTypeId::Boolean,
943                )))),
944            ],
945            runtime,
946        )
947    }
948
949    #[test]
950    fn property_text_access() {
951        let result =
952            execute_datex_script_debug_with_result("var x = {a: 42}; x.a");
953        assert_eq!(result, Integer::from(42).into());
954    }
955
956    #[test]
957    fn property_index_access() {
958        let result =
959            execute_datex_script_debug_with_result("var x = [1,2,3]; x.1");
960        assert_eq!(result, Integer::from(2).into());
961    }
962
963    #[test]
964    fn property_text_update() {
965        let result = execute_datex_script_debug_with_result(
966            "var x = {a: 42}; x.a = 100; x.a",
967        );
968        assert_eq!(result, Integer::from(100).into());
969    }
970
971    #[test]
972    fn nested_stack() {
973        let result = execute_datex_script_debug_with_result(
974            "var x = 1; var y = (var x = 2; x); [x, y]",
975        );
976        assert_eq!(
977            result,
978            List::from(vec![Integer::from(1), Integer::from(2)]).into()
979        );
980    }
981}