1use crate::{
3 core_compiler::instruction_input::InstructionInput,
4 global::root_properties::RootProperty,
5 instruction::regular_instruction::RegularInstruction,
6 libs::core::core_lib_id::CoreLibId,
7 prelude::*,
8 runtime::{
9 Runtime,
10 execution::{
11 context::{ExecutionMode, RemoteExecutionContext},
12 execution_input::ExecutionCallerMetadata,
13 execution_loop::{
14 internal_slots::get_root_property,
15 interrupts::{ExternalExecutionInterrupt, InterruptResult},
16 },
17 remote_execution_options::RemoteExecutionOptions,
18 },
19 },
20 shared_values::{
21 PointerAddress, ReferenceMutability, ReferencedSharedContainer,
22 RemotePointerAddress, SelfOwnedPointerAddress, SharedContainer,
23 },
24 traits::apply::Apply,
25 values::{
26 core_values::endpoint::Endpoint, value_container::ValueContainer,
27 },
28};
29use core::{result::Result, str::FromStr, unreachable};
30pub use errors::*;
31pub use execution_input::{ExecutionInput, ExecutionOptions};
32pub use stack_dump::*;
33
34pub mod context;
35mod errors;
36pub mod execution_input;
37pub mod execution_loop;
38pub mod macros;
39mod stack_dump;
40
41pub mod remote_execution_options;
42#[cfg(all(test, feature = "std"))]
43mod test_remote_execution;
44
45pub fn execute_dxb_sync(
46 input: ExecutionInput,
47) -> Result<Option<ValueContainer>, ExecutionError> {
48 let runtime = input.runtime.clone();
49 let execution_options = input.options.clone();
50 let caller_metadata = input.caller_metadata.clone();
51
52 let (interrupt_provider, execution_loop) = input.execution_loop();
53 for output in execution_loop {
54 match output? {
55 ExternalExecutionInterrupt::SetEndpointProperty {
56 endpoint,
57 property_name,
58 value,
59 } => {
60 if endpoint.is_local_or_equals_endpoint(runtime.endpoint()) {
61 interrupt_provider.provide_result(
62 InterruptResult::ResolvedValue(
63 runtime
64 .endpoint_properties_mut()
65 .insert(property_name, value),
66 ),
67 );
68 } else {
69 return Err(ExecutionError::RequiresAsyncExecution);
70 }
71 }
72 ExternalExecutionInterrupt::GetEndpointProperty {
73 endpoint,
74 property_name,
75 } => {
76 if endpoint.is_local_or_equals_endpoint(runtime.endpoint()) {
77 interrupt_provider.provide_result(
78 InterruptResult::ResolvedValue(Some(
79 ValueContainer::new_from_option(
80 get_local_endpoint_property(
81 &runtime,
82 &caller_metadata,
83 property_name,
84 )?,
85 ),
86 )),
87 );
88 } else {
89 return Err(ExecutionError::RequiresAsyncExecution);
90 }
91 }
92 ExternalExecutionInterrupt::Result(result) => return Ok(result),
93 ExternalExecutionInterrupt::GetReferenceToRemotePointer(
94 address,
95 mutability,
96 ) => interrupt_provider.provide_result(
97 InterruptResult::ResolvedValue(
98 get_remote_shared_container_reference(
99 &runtime, address, mutability,
100 )?
101 .map(|v| {
102 ValueContainer::Shared(SharedContainer::Referenced(v))
103 }),
104 ),
105 ),
106 ExternalExecutionInterrupt::GetReferenceToLocalPointer(address) => {
107 interrupt_provider.provide_result(
109 InterruptResult::ResolvedValue(
110 get_local_pointer_value(&runtime, address).map(|v| {
111 ValueContainer::Shared(SharedContainer::Referenced(
112 v,
113 ))
114 }),
115 ),
116 );
117 }
118 ExternalExecutionInterrupt::GetCoreLibValue(id) => {
119 interrupt_provider.provide_result(
120 InterruptResult::ResolvedValue(Some(
121 get_core_lib_value_container(&runtime, id)?,
122 )),
123 );
124 }
125 ExternalExecutionInterrupt::Apply(callee, args) => {
126 let res = callee.try_apply_sync_checked(&runtime, args)?;
127 interrupt_provider.provide_result(
128 InterruptResult::ResolvedValueAndBorrowedArgs(res),
129 );
130 }
131 ExternalExecutionInterrupt::CallMethod(
132 callee,
133 method_name,
134 args,
135 ) => {
136 let res = callee.try_call_method_sync(
137 &method_name,
138 args,
139 &runtime,
140 )?;
141
142 interrupt_provider.provide_result(
143 InterruptResult::ResolvedValueAndBorrowedArgs(res),
144 )
145 }
146 ExternalExecutionInterrupt::RemoteExecution {
147 input: dxb_with_shared_values,
148 receivers,
149 } if receivers.iter().all(|r: &Endpoint| {
150 r.is_local_or_equals_endpoint(runtime.endpoint())
151 }) =>
152 {
153 let local_input = ExecutionInput::new(
154 dxb_with_shared_values,
155 caller_metadata.clone(),
156 execution_options.clone(),
157 runtime.clone(),
158 );
159 let result = execute_dxb_sync(local_input)?;
160 interrupt_provider
161 .provide_result(InterruptResult::ResolvedValue(result));
162 }
163 _ => return Err(ExecutionError::RequiresAsyncExecution),
164 }
165 }
166
167 Err(ExecutionError::RequiresAsyncExecution)
168}
169
170pub async fn execute_dxb(
171 input: ExecutionInput,
172) -> Result<Option<ValueContainer>, ExecutionError> {
173 let runtime = input.runtime.clone();
174 let caller_metadata = input.caller_metadata.clone();
175 let execution_options = input.options.clone();
176 let (interrupt_provider, execution_loop) = input.execution_loop();
177
178 for output in execution_loop {
179 match output? {
180 ExternalExecutionInterrupt::SetEndpointProperty {
181 endpoint,
182 property_name,
183 value,
184 } => {
185 if endpoint.is_local_or_equals_endpoint(runtime.endpoint()) {
186 interrupt_provider.provide_result(
187 InterruptResult::ResolvedValue(
188 runtime
189 .endpoint_properties_mut()
190 .insert(property_name, value),
191 ),
192 );
193 } else {
194 interrupt_provider.provide_result(
195 InterruptResult::ResolvedValue(
196 set_remote_endpoint_property(
197 &runtime,
198 endpoint,
199 property_name,
200 value,
201 )
202 .await?,
203 ),
204 );
205 }
206 }
207 ExternalExecutionInterrupt::GetEndpointProperty {
208 endpoint,
209 property_name,
210 } => {
211 if endpoint.is_local_or_equals_endpoint(runtime.endpoint()) {
212 interrupt_provider.provide_result(
213 InterruptResult::ResolvedValue(Some(
214 ValueContainer::new_from_option(
215 get_local_endpoint_property(
216 &runtime,
217 &caller_metadata,
218 property_name,
219 )?,
220 ),
221 )),
222 );
223 } else {
224 interrupt_provider.provide_result(
225 InterruptResult::ResolvedValue(
226 get_remote_endpoint_property(
227 &runtime,
228 endpoint,
229 property_name,
230 )
231 .await?,
232 ),
233 );
234 }
235 }
236 ExternalExecutionInterrupt::Result(result) => return Ok(result),
237 ExternalExecutionInterrupt::GetReferenceToRemotePointer(
238 address,
239 mutability,
240 ) => {
241 interrupt_provider.provide_result(
242 InterruptResult::ResolvedValue(
243 get_remote_shared_container_reference(
244 &runtime, address, mutability,
245 )?
246 .map(|v| {
247 ValueContainer::Shared(SharedContainer::Referenced(
248 v,
249 ))
250 }),
251 ),
252 );
253 }
254 ExternalExecutionInterrupt::GetReferenceToLocalPointer(address) => {
255 interrupt_provider.provide_result(
257 InterruptResult::ResolvedValue(
258 get_local_pointer_value(&runtime, address).map(|v| {
259 ValueContainer::Shared(SharedContainer::Referenced(
260 v,
261 ))
262 }),
263 ),
264 );
265 }
266 ExternalExecutionInterrupt::GetCoreLibValue(id) => {
267 interrupt_provider.provide_result(
268 InterruptResult::ResolvedValue(Some(
269 get_core_lib_value_container(&runtime, id)?,
270 )),
271 );
272 }
273 ExternalExecutionInterrupt::RemoteExecution {
274 input: dxb_with_shared_values,
275 receivers,
276 } => {
277 assert_eq!(receivers.len(), 1);
279
280 if receivers[0].is_local_or_equals_endpoint(runtime.endpoint())
282 {
283 let local_input = ExecutionInput::new(
284 dxb_with_shared_values,
285 caller_metadata.clone(),
286 execution_options.clone(),
287 runtime.clone(),
288 );
289 let result = execute_dxb_sync(local_input)?;
290 interrupt_provider
291 .provide_result(InterruptResult::ResolvedValue(result));
292 } else {
293 let remote_execution_context = RemoteExecutionContext::new(
294 receivers,
295 ExecutionMode::Static,
296 runtime.clone(),
297 );
298 let res = runtime
299 .execute_remote_single_receiver(
300 &remote_execution_context.target,
301 dxb_with_shared_values,
302 RemoteExecutionOptions::new_with_end_of_context(
303 true,
304 ),
305 )
306 .await?;
307 interrupt_provider
308 .provide_result(InterruptResult::ResolvedValue(res));
309 }
310 }
311 ExternalExecutionInterrupt::Apply(callee, args) => {
312 let res =
313 callee.try_apply_async_checked(&runtime, args).await?;
314 interrupt_provider.provide_result(
315 InterruptResult::ResolvedValueAndBorrowedArgs(res),
316 );
317 }
318 ExternalExecutionInterrupt::CallMethod(
319 callee,
320 method_name,
321 args,
322 ) => {
323 let res = callee
324 .try_call_method_async(&method_name, args, &runtime)
325 .await?;
326
327 interrupt_provider.provide_result(
328 InterruptResult::ResolvedValueAndBorrowedArgs(res),
329 )
330 }
331 }
332 }
333
334 unreachable!("Execution loop should always return a result");
335}
336
337async fn set_remote_endpoint_property(
338 runtime: &Runtime,
339 endpoint: Endpoint,
340 property_name: String,
341 value: ValueContainer,
342) -> Result<Option<ValueContainer>, ExecutionError> {
343 runtime
344 .execute_instructions_remote_single_receiver(
345 endpoint,
346 vec![
347 RegularInstruction::set_entry_text(property_name).into(),
348 InstructionInput::ValueContainer(value),
349 RegularInstruction::Endpoint(Endpoint::LOCAL).into(),
350 ],
351 false,
352 )
353 .await
354}
355
356async fn get_remote_endpoint_property(
357 runtime: &Runtime,
358 endpoint: Endpoint,
359 property_name: String,
360) -> Result<Option<ValueContainer>, ExecutionError> {
361 runtime
362 .execute_instructions_remote_single_receiver(
363 endpoint,
364 vec![
365 RegularInstruction::get_entry_text(property_name).into(),
366 RegularInstruction::Endpoint(Endpoint::LOCAL).into(),
367 ],
368 false,
369 )
370 .await
371}
372
373fn get_local_endpoint_property(
375 runtime: &Runtime,
376 caller_metadata: &ExecutionCallerMetadata,
377 property_name: String,
378) -> Result<Option<ValueContainer>, ExecutionError> {
379 let value = runtime.endpoint_properties().get(&property_name).cloned();
380
381 if let Some(value) = value {
382 return Ok(Some(value));
383 } else if let Ok(root_property) = RootProperty::from_str(&property_name) {
384 return Ok(Some(get_root_property(
385 runtime,
386 caller_metadata,
387 root_property,
388 )?));
389 }
390
391 Ok(None)
392}
393
394fn get_remote_shared_container_reference(
395 runtime: &Runtime,
396 address: RemotePointerAddress,
397 _mutability: ReferenceMutability,
398) -> Result<Option<ReferencedSharedContainer>, ExecutionError> {
399 let address_provider = runtime.pointer_address_provider_mut();
400 let memory = runtime.shared_references_cache_refcell().borrow();
401 let resolved_address = address_provider.normalize_address(address);
402 Ok(memory.get_reference(&resolved_address))
405}
406
407fn get_core_lib_value_container(
408 runtime: &Runtime,
409 id: CoreLibId,
410) -> Result<ValueContainer, ExecutionError> {
411 let value = runtime.core_library().value_or_type_by_id(id);
412 Ok(ValueContainer::Local(value.clone()))
413}
414
415fn get_local_pointer_value(
416 runtime: &Runtime,
417 address: SelfOwnedPointerAddress,
418) -> Option<ReferencedSharedContainer> {
419 runtime
421 .shared_references_cache_refcell()
422 .borrow()
423 .get_reference(&PointerAddress::SelfOwned(address))
424}
425
426#[cfg(test)]
427#[cfg(feature = "compiler")]
428mod tests {
429 use super::*;
430 use crate::{
431 compiler::{CompileOptions, compile_script, scope::CompilationScope},
432 core_compiler::core_compilation_context::DXBWithSharedValues,
433 disassembler::print_disassembled,
434 global::protocol_structures::serializable::Serializable,
435 libs::core::type_id::CoreLibBaseTypeId,
436 runtime::{
437 CustomRuntimeInfo, Runtime, RuntimeConfig, RuntimeRunner,
438 execution::{
439 context::{ExecutionContext, LocalExecutionContext},
440 execution_input::{ExecutionCallerMetadata, ExecutionOptions},
441 },
442 },
443 shared_values::{
444 OwnedSharedContainer, SharedContainer, SharedContainerMutability,
445 traits::SharedContainerCommon,
446 },
447 traits::{
448 convert_value_container::ConvertValueContainer,
449 structural_eq::{StructuralEq, assert_structural_eq},
450 value_eq::assert_value_eq,
451 },
452 types::{
453 r#type::Type,
454 type_definition::callable::{CallableKind, CallableTypeDefinition},
455 },
456 values::{
457 core_value::CoreValue,
458 core_values::{
459 callable::{Callable, CallableBody, DatexBytecodeCallable},
460 decimal::Decimal,
461 endpoint::Endpoint,
462 integer::{Integer, typed_integer::TypedInteger},
463 list::{List, datex_list},
464 map::Map,
465 },
466 value::{
467 Value,
468 value_classification::{ValueClassification, ValueTag},
469 },
470 },
471 };
472 use core::assert_matches;
473 use log::{debug, info};
474
475 fn execute_datex_script_debug(
476 datex_script: &str,
477 ) -> Option<ValueContainer> {
478 let runtime = Runtime::stub();
479 let (dxb, _) = compile_script(
480 datex_script,
481 CompileOptions::default(),
482 runtime.clone(),
483 )
484 .unwrap();
485
486 flexi_logger::init();
487 print_disassembled(&dxb);
488
489 let context = ExecutionInput::new(
490 DXBWithSharedValues::new(dxb, vec![]),
491 ExecutionCallerMetadata::local_default(),
492 ExecutionOptions { verbose: true },
493 runtime,
494 );
495 execute_dxb_sync(context).unwrap()
496 }
497
498 fn execute_datex_script_debug_unbounded(
499 datex_script_parts: impl Iterator<Item = &'static str>,
500 runtime: Runtime,
501 ) -> impl Iterator<Item = Result<Option<ValueContainer>, ExecutionError>>
502 {
503 gen move {
504 let datex_script_parts = datex_script_parts.collect::<Vec<_>>();
505 let mut execution_context =
506 ExecutionContext::Local(LocalExecutionContext::new(
507 ExecutionMode::unbounded(),
508 runtime.clone(),
509 ExecutionCallerMetadata::local_default(),
510 ));
511 let mut compilation_scope =
512 CompilationScope::new(ExecutionMode::unbounded());
513
514 let len = datex_script_parts.len();
515 for (index, script_part) in
516 datex_script_parts.into_iter().enumerate()
517 {
518 if index == len - 1 {
520 compilation_scope.mark_as_last_execution();
521 }
522
523 let (dxb, new_compilation_scope) = compile_script(
524 script_part,
525 CompileOptions::new(
526 compilation_scope,
527 vec![Endpoint::LOCAL],
528 ),
529 runtime.clone(),
530 )
531 .unwrap();
532 compilation_scope = new_compilation_scope;
533 yield execution_context.execute_dxb_sync(
534 DXBWithSharedValues::new(dxb, vec![]),
535 None,
536 );
537 }
538 }
539 }
540
541 fn assert_unbounded_input_matches_output(
542 input: Vec<&'static str>,
543 expected_output: Vec<Option<ValueContainer>>,
544 runtime: Runtime,
545 ) {
546 let input = input.into_iter();
547 let expected_output = expected_output.into_iter();
548 for (result, expected) in execute_datex_script_debug_unbounded(
549 input.into_iter(),
550 runtime.clone(),
551 )
552 .zip(expected_output)
553 {
554 let result = result.unwrap();
555 assert_eq!(result, expected);
556 }
557 }
558
559 fn execute_datex_script_debug_with_error(
560 datex_script: &str,
561 ) -> Result<Option<ValueContainer>, ExecutionError> {
562 let runtime = Runtime::stub();
563 let (dxb, _) = compile_script(
564 datex_script,
565 CompileOptions::default(),
566 runtime.clone(),
567 )
568 .unwrap();
569 let context = ExecutionInput::new(
570 DXBWithSharedValues::new(dxb, vec![]),
571 ExecutionCallerMetadata::local_default(),
572 ExecutionOptions { verbose: true },
573 runtime,
574 );
575 execute_dxb_sync(context)
576 }
577
578 fn execute_datex_script_debug_with_result(
579 datex_script: &str,
580 ) -> ValueContainer {
581 execute_datex_script_debug(datex_script).unwrap()
582 }
583
584 async fn execute_datex_script_with_runtime(
585 config: RuntimeConfig,
586 datex_script: &str,
587 ) -> Result<Option<ValueContainer>, ExecutionError> {
588 RuntimeRunner::new(config, CustomRuntimeInfo::default())
589 .run(async |runtime| {
590 let (dxb, _) = compile_script(
591 datex_script,
592 CompileOptions::default(),
593 runtime.clone(),
594 )
595 .unwrap();
596 let context = ExecutionInput::new(
597 DXBWithSharedValues::new(dxb, vec![]),
598 ExecutionCallerMetadata::local_default(),
599 ExecutionOptions { verbose: true },
600 runtime,
601 );
602 execute_dxb(context).await
603 })
604 .await
605 }
606
607 #[test]
608 fn empty_script() {
609 assert_eq!(execute_datex_script_debug(""), None);
610 }
611
612 #[test]
613 fn empty_script_semicolon() {
614 assert_eq!(execute_datex_script_debug(";;;"), None);
615 }
616
617 #[test]
618 fn single_value() {
619 assert_eq!(
620 execute_datex_script_debug_with_result("42"),
621 Integer::from(42i8).into()
622 );
623 }
624
625 #[test]
626 fn single_value_semicolon() {
627 assert_eq!(execute_datex_script_debug("42;"), None)
628 }
629
630 #[test]
631 fn is() {
632 let result = execute_datex_script_debug_with_result("1 is 1");
633 assert_eq!(result, false.into());
634 assert_structural_eq!(result, ValueContainer::from(false));
635 }
636
637 #[test]
638 fn equality() {
639 let result = execute_datex_script_debug_with_result("1 == 1");
640 assert_eq!(result, true.into());
641 assert_structural_eq!(result, ValueContainer::from(true));
642
643 let result = execute_datex_script_debug_with_result("1 == 2");
644 assert_eq!(result, false.into());
645 assert_structural_eq!(result, ValueContainer::from(false));
646
647 let result = execute_datex_script_debug_with_result("1 != 2");
648 assert_eq!(result, true.into());
649 assert_structural_eq!(result, ValueContainer::from(true));
650
651 let result = execute_datex_script_debug_with_result("1 != 1");
652 assert_eq!(result, false.into());
653 assert_structural_eq!(result, ValueContainer::from(false));
654 let result = execute_datex_script_debug_with_result("1 === 1");
655 assert_eq!(result, true.into());
656
657 assert_structural_eq!(result, ValueContainer::from(true));
658 let result = execute_datex_script_debug_with_result("1 !== 2");
659 assert_eq!(result, true.into());
660 assert_structural_eq!(result, ValueContainer::from(true));
661
662 let result = execute_datex_script_debug_with_result("1 !== 1");
663 assert_eq!(result, false.into());
664 assert_structural_eq!(result, ValueContainer::from(false));
665 }
666
667 #[test]
668 fn single_value_scope() {
669 let result = execute_datex_script_debug_with_result("(42)");
670 assert_eq!(result, Integer::from(42i8).into());
671 assert_structural_eq!(result, ValueContainer::from(42_u128));
672 }
673
674 #[test]
675 fn add() {
676 let result = execute_datex_script_debug_with_result("1 + 2");
677 assert_eq!(result, Integer::from(3i8).into());
678 assert_structural_eq!(result, ValueContainer::from(3i8));
679 }
680
681 #[test]
682 fn nested_scope() {
683 let result = execute_datex_script_debug_with_result("1 + (2 + 3)");
684 assert_eq!(result, Integer::from(6i8).into());
685 }
686
687 #[test]
688 fn empty_list() {
689 let result = execute_datex_script_debug_with_result("[]");
690 let list: &List = result.try_as().unwrap();
691 assert_eq!(list.len(), 0);
692 assert_eq!(
693 result,
694 List::new(Vec::<ValueContainer>::new()).to_value_container()
695 );
696 }
697
698 #[test]
699 fn empty_tag() {
700 let result = execute_datex_script_debug_with_result("#Example");
701 if let ValueContainer::Local(Value::Core(value)) = result {
702 assert_eq!(&value.inner, &CoreValue::Null);
703 assert_eq!(
704 value.classification,
705 ValueClassification::new_with_tag(ValueTag {
706 name: "Example".to_string(),
707 is_empty: true
708 })
709 )
710 } else {
711 panic!("Result should be Local value");
712 }
713 }
714
715 #[test]
716 fn empty_with_map() {
717 let result =
718 execute_datex_script_debug_with_result("#Example {a: true}");
719 if let ValueContainer::Local(Value::Core(value)) = result {
720 assert_eq!(
721 &value.inner,
722 &CoreValue::Map(Map::new_structural(vec![(
723 "a".into(),
724 ValueContainer::from(true)
725 )]))
726 );
727 assert_eq!(
728 value.classification,
729 ValueClassification::new_with_tag(ValueTag {
730 name: "Example".to_string(),
731 is_empty: false
732 })
733 )
734 } else {
735 panic!("Result should be Local value");
736 }
737 }
738
739 #[test]
740 fn list() {
741 let result = execute_datex_script_debug_with_result("[1i8, 2i8, 3i8]");
742 let list: &List = result.try_as().unwrap();
743 let expected = datex_list![
744 TypedInteger::from(1i8),
745 TypedInteger::from(2i8),
746 TypedInteger::from(3i8)
747 ];
748 assert_eq!(list.len(), 3);
749 assert_eq!(result, expected.into());
750 assert_eq!(result, List::new(vec![1i8, 2i8, 3i8]).to_value_container());
751 assert_structural_eq!(
752 result,
753 List::new(vec![1i8, 2i8, 3i8]).to_value_container()
754 );
755 }
756
757 #[test]
758 fn list_with_nested_scope() {
759 let result = execute_datex_script_debug_with_result("[1, (2 + 3), 4]");
760 let expected =
761 datex_list![Integer::from(1), Integer::from(5), Integer::from(4)];
762
763 assert_eq!(result, expected.into());
764 assert_ne!(
765 result,
766 datex_list![
767 TypedInteger::from(1u8),
768 TypedInteger::from(5u8),
769 TypedInteger::from(4u8)
770 ]
771 .into()
772 );
773 assert_structural_eq!(
774 result,
775 List::new(vec![1_u8, 5_u8, 4_u8]).to_value_container()
776 );
777 }
778
779 #[test]
780 fn boolean() {
781 let result = execute_datex_script_debug_with_result("true");
782 assert_eq!(result, true.into());
783 assert_structural_eq!(result, ValueContainer::from(true));
784
785 let result = execute_datex_script_debug_with_result("false");
786 assert_eq!(result, false.into());
787 assert_structural_eq!(result, ValueContainer::from(false));
788 }
789
790 #[test]
791 fn decimal() {
792 let result = execute_datex_script_debug_with_result("1.5");
793 assert_eq!(result, Decimal::try_from_string("1.5").unwrap().into());
794 assert_structural_eq!(result, ValueContainer::from(1.5));
795 }
796
797 #[test]
798 fn decimal_and_integer() {
799 let result = execute_datex_script_debug_with_result("-2341324.0");
800 assert_eq!(
801 result,
802 Decimal::try_from_string("-2341324").unwrap().into()
803 );
804 assert!(!result.structural_eq(&ValueContainer::from(-2341324)));
805 }
806
807 #[test]
808 fn integer() {
809 let result = execute_datex_script_debug_with_result("2");
810 assert_eq!(result, Integer::from(2).into());
811 assert_ne!(result, 2_u8.into());
812 assert_structural_eq!(result, ValueContainer::from(2_i8));
813 }
814
815 #[test]
816 fn typed_integer() {
817 let result = execute_datex_script_debug_with_result("-2i16");
818 assert_eq!(result, TypedInteger::from(-2i16).into());
819 assert_structural_eq!(result, ValueContainer::from(-2_i16));
820
821 let result = execute_datex_script_debug_with_result("2i32");
822 assert_eq!(result, TypedInteger::from(2i32).into());
823 assert_structural_eq!(result, ValueContainer::from(2_i32));
824
825 let result = execute_datex_script_debug_with_result("-2i64");
826 assert_eq!(result, TypedInteger::from(-2i64).into());
827 assert_structural_eq!(result, ValueContainer::from(-2_i64));
828
829 let result = execute_datex_script_debug_with_result("2i128");
830 assert_eq!(result, TypedInteger::from(2i128).into());
831 assert_structural_eq!(result, ValueContainer::from(2_i128));
832
833 let result = execute_datex_script_debug_with_result("2u8");
834 assert_eq!(result, TypedInteger::from(2_u8).into());
835 assert_structural_eq!(result, ValueContainer::from(2_u8));
836
837 let result = execute_datex_script_debug_with_result("2u16");
838 assert_eq!(result, TypedInteger::from(2_u16).into());
839 assert_structural_eq!(result, ValueContainer::from(2_u16));
840
841 let result = execute_datex_script_debug_with_result("2u32");
842 assert_eq!(result, TypedInteger::from(2_u32).into());
843 assert_structural_eq!(result, ValueContainer::from(2_u32));
844
845 let result = execute_datex_script_debug_with_result("2u64");
846 assert_eq!(result, TypedInteger::from(2_u64).into());
847 assert_structural_eq!(result, ValueContainer::from(2_u64));
848
849 let result = execute_datex_script_debug_with_result("2u128");
850 assert_eq!(result, TypedInteger::from(2_u128).into());
851 assert_structural_eq!(result, ValueContainer::from(2_u128));
852
853 let result = execute_datex_script_debug_with_result("2ibig");
854 assert_eq!(result, TypedInteger::IBig(Integer::from(2)).into());
855 assert_structural_eq!(result, ValueContainer::from(2));
856 }
857
858 #[test]
859 fn null() {
860 let result = execute_datex_script_debug_with_result("null");
861 assert_eq!(result, ValueContainer::from(CoreValue::Null));
862 assert_eq!(result, CoreValue::Null.into());
863 assert_structural_eq!(result, ValueContainer::from(CoreValue::Null));
864 }
865
866 #[test]
867 fn map() {
868 let result =
869 execute_datex_script_debug_with_result("{x: 1, y: 2, z: 42}");
870 let map = result.get_cloned_value();
871 let map = map.try_into_value::<Map>().unwrap();
872
873 assert_eq!(map.to_string(), "{\"x\": 1, \"y\": 2, \"z\": 42}");
875 assert_eq!(map.size(), 3);
876
877 info!("Map: {:?}", map);
878
879 assert_eq!(
881 map.try_get(&ValueContainer::from("x")),
882 Ok(&Integer::from(1).into())
883 );
884 assert_eq!(
885 map.try_get(&ValueContainer::from("y")),
886 Ok(&Integer::from(2).into())
887 );
888 assert_eq!(
889 map.try_get(&ValueContainer::from("z")),
890 Ok(&Integer::from(42).into())
891 );
892
893 let expected_se: Map = Map::from(vec![
895 ("x".to_string(), 1.into()),
896 ("y".to_string(), 2.into()),
897 ("z".to_string(), 42.into()),
898 ]);
899 assert_structural_eq!(map, expected_se);
900
901 let expected_strict: Map = Map::from(vec![
903 ("x".to_string(), Integer::from(1).into()),
904 ("y".to_string(), Integer::from(2).into()),
905 ("z".to_string(), Integer::from(42).into()),
906 ]);
907 debug!("Expected map: {expected_strict}");
908 debug!("Map result: {map}");
909 }
912
913 #[test]
914 fn empty_map() {
915 let result = execute_datex_script_debug_with_result("{}");
916 let map = result.clone().get_cloned_value();
917 let map = map.try_into_value::<Map>().unwrap();
918
919 assert_eq!(map.to_string(), "{}");
921 assert_eq!(map.size(), 0);
922
923 info!("Map: {:?}", map);
924 }
925
926 #[test]
927 fn statements() {
928 let result = execute_datex_script_debug_with_result("1; 2; 3");
929 assert_eq!(result, Integer::from(3).into());
930 }
931
932 #[test]
933 fn empty_function() {
934 let result =
935 execute_datex_script_debug_with_result("function test() ()");
936 let callable: Callable = result.try_into_value().unwrap();
937
938 assert_eq!(
939 callable,
940 Callable {
941 name: Some("test".to_string()),
942 signature: CallableTypeDefinition {
943 kind: CallableKind::Function,
944 requires_async: false,
945 parameters: vec![],
946 rest_parameter: None,
947 return_type: None,
948 yeet_type: None,
949 },
950 body: CallableBody::DatexBytecode(DatexBytecodeCallable {
951 requires_async: false,
952 injected_values: vec![],
953 body: RegularInstruction::statements(0, false).to_bytes(),
954 }),
955 creator: Endpoint::LOCAL,
956 docs: None,
957 }
958 )
959 }
960
961 #[test]
962 fn function_no_params() {
963 let result =
964 execute_datex_script_debug_with_result("function test() (null)");
965 let callable: Callable = result.try_into_value().unwrap();
966
967 assert_eq!(
968 callable,
969 Callable {
970 name: Some("test".to_string()),
971 signature: CallableTypeDefinition {
972 kind: CallableKind::Function,
973 requires_async: false,
974 parameters: vec![],
975 rest_parameter: None,
976 return_type: None,
977 yeet_type: None,
978 },
979 body: CallableBody::DatexBytecode(DatexBytecodeCallable {
980 requires_async: false,
981 injected_values: vec![],
982 body: RegularInstruction::Null.to_bytes(),
983 }),
984 creator: Endpoint::LOCAL,
985 docs: None,
986 }
987 );
988 }
989
990 #[test]
991 fn function() {
992 let result = execute_datex_script_debug_with_result(
993 "function test(a: integer) -> null (null)",
994 );
995 let callable: Callable = result.try_into_value().unwrap();
996
997 assert_eq!(
998 callable,
999 Callable {
1000 name: Some("test".to_string()),
1001 signature: CallableTypeDefinition {
1002 kind: CallableKind::Function,
1003 requires_async: false,
1004 parameters: vec![(
1005 Some("a".to_string()),
1006 Type::core(CoreLibBaseTypeId::Integer)
1007 )],
1008 rest_parameter: None,
1009 return_type: Some(Box::new(Type::core(
1010 CoreLibBaseTypeId::Null
1011 ))),
1012 yeet_type: None,
1013 },
1014 body: CallableBody::DatexBytecode(DatexBytecodeCallable {
1015 requires_async: false,
1016 injected_values: vec![],
1017 body: RegularInstruction::Null.to_bytes(),
1018 }),
1019 creator: Endpoint::LOCAL,
1020 docs: None,
1021 }
1022 );
1023 }
1024
1025 #[test]
1026 fn function_call_no_args() {
1027 let result = execute_datex_script_debug_with_result(
1028 "function test() -> integer (1 + 2)()",
1029 );
1030 let integer: Integer = result.try_into_value().unwrap();
1031 assert_eq!(integer, Integer::from(3));
1032 }
1033
1034 #[test]
1035 fn function_call_with_arg() {
1036 let result = execute_datex_script_debug_with_result(
1037 "function test(x: integer) -> integer (x + 2)(1)",
1038 );
1039 let integer: Integer = result.try_into_value().unwrap();
1040 assert_eq!(integer, Integer::from(3));
1041 }
1042
1043 #[test]
1044 fn function_call_with_arg_and_injected_value() {
1045 let result = execute_datex_script_debug_with_result(
1046 "const y = 42; function test(x: integer) -> integer (y + x + 2)(1)",
1047 );
1048 let integer: Integer = result.try_into_value().unwrap();
1049 assert_eq!(integer, Integer::from(45));
1050 }
1051
1052 #[test]
1053 fn single_terminated_statement() {
1054 let result = execute_datex_script_debug("1;");
1055 assert_eq!(result, None);
1056 }
1057
1058 #[test]
1059 fn const_declaration() {
1060 let result = execute_datex_script_debug_with_result("const x = 42; x");
1061 assert_eq!(result, Integer::from(42).into());
1062 }
1063
1064 #[test]
1065 fn const_declaration_with_addition() {
1066 let result =
1067 execute_datex_script_debug_with_result("const x = 1 + 2; x");
1068 assert_eq!(result, Integer::from(3).into());
1069 }
1070
1071 #[test]
1072 fn unbox_shared() {
1073 let result =
1074 execute_datex_script_debug_with_result("const x = shared 42; *x");
1075 assert_eq!(result, ValueContainer::from(Integer::from(42)));
1076 }
1077
1078 #[test]
1079 fn shared_creation_mut_ref_to_mut() {
1080 let result = execute_datex_script_debug_with_result(
1081 "const x = 'mut shared mut 42; x",
1082 );
1083 assert_matches!(result, ValueContainer::Shared(SharedContainer::Referenced(ref container)) if
1084 container.container_mutability() == SharedContainerMutability::Mutable &&
1085 container.reference_mutability() == ReferenceMutability::Mutable
1086 );
1087 assert_value_eq!(result, ValueContainer::from(Integer::from(42)));
1088 }
1089
1090 #[test]
1091 fn shared_creation_immut_ref_to_mut() {
1092 let result = execute_datex_script_debug_with_result(
1093 "const x = 'shared mut 42; x",
1094 );
1095 assert_matches!(result, ValueContainer::Shared(SharedContainer::Referenced(ref container)) if
1096 container.container_mutability() == SharedContainerMutability::Mutable &&
1097 container.reference_mutability() == ReferenceMutability::Immutable
1098 );
1099
1100 assert_value_eq!(result, ValueContainer::from(Integer::from(42)));
1101 }
1102
1103 #[test]
1104 fn shared_creation_immut_ref() {
1105 let result =
1106 execute_datex_script_debug_with_result("const x = 'shared 42; x");
1107 assert_matches!(result, ValueContainer::Shared(SharedContainer::Referenced(ref container)) if
1108 container.container_mutability() == SharedContainerMutability::Immutable &&
1109 container.reference_mutability() == ReferenceMutability::Immutable
1110 );
1111
1112 assert_value_eq!(result, ValueContainer::from(Integer::from(42)));
1113 }
1114
1115 #[test]
1116 fn shared_creation_immut() {
1117 let result =
1118 execute_datex_script_debug_with_result("const x = shared 42; x");
1119 assert_matches!(result, ValueContainer::Shared(SharedContainer::Owned(ref container)) if
1120 container.container_mutability() == SharedContainerMutability::Immutable
1121 );
1122
1123 assert_value_eq!(result, ValueContainer::from(Integer::from(42)));
1124 }
1125
1126 #[test]
1127 fn shared_creation_mut() {
1128 let result = execute_datex_script_debug_with_result(
1129 "const x = shared mut 42; x",
1130 );
1131 assert_matches!(result, ValueContainer::Shared(SharedContainer::Owned(
1132 ref container @ OwnedSharedContainer { .. }
1133 )) if container.container_mutability() == SharedContainerMutability::Mutable);
1134 assert_value_eq!(result, ValueContainer::from(Integer::from(42)));
1135 }
1136
1137 #[test]
1138 fn shared_creation_mut_ref_to_immut() {
1139 let result = execute_datex_script_debug_with_error(
1140 "const x = 'mut shared 42; x",
1141 );
1142 assert_matches!(
1143 result,
1144 Err(ExecutionError::MutableReferenceToNonMutableValue)
1145 );
1146 }
1147
1148 #[test]
1149 fn shared_value_add_assignment() {
1150 let result = execute_datex_script_debug_with_result(
1151 "var x = shared mut 42; *x += 1; x",
1152 );
1153
1154 assert_value_eq!(result, ValueContainer::from(Integer::from(43)));
1155 assert_matches!(result, ValueContainer::Shared(..));
1156 if let ValueContainer::Shared(shared) = &result {
1157 assert_eq!(
1158 *shared.inner().base_shared_container().mutability(),
1159 SharedContainerMutability::Mutable
1160 );
1161 } else {
1162 panic!("Expected shared value");
1163 }
1164 }
1165
1166 #[test]
1167 fn shared_value_sub_assignment() {
1168 let result = execute_datex_script_debug_with_result(
1169 "const x = 'mut shared mut 42; *x -= 1; x",
1170 );
1171
1172 assert_matches!(result, ValueContainer::Shared(..));
1173 assert_value_eq!(result, ValueContainer::from(Integer::from(41)));
1174 }
1175
1176 #[test]
1177 fn shared_value_assignment() {
1178 let result = execute_datex_script_debug_with_result(
1179 "const x = 'mut shared mut 42; *x = 100; x",
1180 );
1181
1182 assert_matches!(result, ValueContainer::Shared(..));
1183 assert_value_eq!(result, ValueContainer::from(Integer::from(100)));
1184 }
1185
1186 #[tokio::test]
1187 async fn env_slot() {
1188 use indexmap::IndexMap;
1189 let res = execute_datex_script_with_runtime(
1190 RuntimeConfig {
1191 env: Some(
1192 [("TEST_ENV_VAR".to_string(), "test_value".to_string())]
1193 .into_iter()
1194 .collect(),
1195 ),
1196 ..Default::default()
1197 },
1198 "$.env",
1199 )
1200 .await
1201 .unwrap();
1202 assert!(res.is_some());
1203 let env = res
1204 .unwrap()
1205 .try_into_value::<IndexMap<String, String, _>>()
1206 .unwrap();
1207 assert_eq!(env.get("TEST_ENV_VAR"), Some(&"test_value".into()));
1208 }
1209
1210 #[test]
1211 fn shebang() {
1212 let result = execute_datex_script_debug_with_result("#!datex\n42");
1213 assert_eq!(result, Integer::from(42).into());
1214 }
1215
1216 #[test]
1217 fn single_line_comment() {
1218 let result =
1219 execute_datex_script_debug_with_result("// this is a comment\n42");
1220 assert_eq!(result, Integer::from(42).into());
1221
1222 let result = execute_datex_script_debug_with_result(
1223 "// this is a comment\n// another comment\n42",
1224 );
1225 assert_eq!(result, Integer::from(42).into());
1226 }
1227
1228 #[test]
1229 fn multi_line_comment() {
1230 let result = execute_datex_script_debug_with_result(
1231 "/* this is a comment */\n42",
1232 );
1233 assert_eq!(result, Integer::from(42).into());
1234
1235 let result = execute_datex_script_debug_with_result(
1236 "/* this is a comment\n with multiple lines */\n42",
1237 );
1238 assert_eq!(result, Integer::from(42).into());
1239
1240 let result = execute_datex_script_debug_with_result("[1, /* 2, */ 3]");
1241 let expected = datex_list![Integer::from(1), Integer::from(3)];
1242 assert_eq!(result, expected.into());
1243 }
1244
1245 #[test]
1246 fn continuous_execution() {
1247 assert_unbounded_input_matches_output(
1248 vec!["1", "2"],
1249 vec![Some(Integer::from(1).into()), Some(Integer::from(2).into())],
1250 Runtime::stub(),
1251 )
1252 }
1253
1254 #[test]
1255 fn resolve_core_lib_type_reference() {
1256 let result = execute_datex_script_debug_with_result("integer");
1257 assert_eq!(
1258 result,
1259 ValueContainer::Local(Value::from(Type::core(
1260 CoreLibBaseTypeId::Integer,
1261 )))
1262 );
1263 }
1264
1265 #[test]
1266 fn continuous_execution_multiple_external_interrupts() {
1267 let runtime = Runtime::stub();
1268
1269 assert_unbounded_input_matches_output(
1270 vec!["1", "integer", "boolean"],
1271 vec![
1272 Some(Integer::from(1).into()),
1273 Some(ValueContainer::Local(Value::from(Type::core(
1274 CoreLibBaseTypeId::Integer,
1275 )))),
1276 Some(ValueContainer::Local(Value::from(Type::core(
1277 CoreLibBaseTypeId::Boolean,
1278 )))),
1279 ],
1280 runtime,
1281 )
1282 }
1283
1284 #[test]
1285 fn property_text_access() {
1286 let result =
1287 execute_datex_script_debug_with_result("var x = {a: 42}; x.a");
1288 assert_eq!(result, Integer::from(42).into());
1289 }
1290
1291 #[test]
1292 fn property_index_access() {
1293 let result =
1294 execute_datex_script_debug_with_result("var x = [1,2,3]; x.1");
1295 assert_eq!(result, Integer::from(2).into());
1296 }
1297
1298 #[test]
1299 fn property_text_update() {
1300 let result = execute_datex_script_debug_with_result(
1301 "var x = {a: 42}; x.a = 100; x.a",
1302 );
1303 assert_eq!(result, Integer::from(100).into());
1304 }
1305
1306 #[test]
1307 fn nested_stack() {
1308 let result = execute_datex_script_debug_with_result(
1309 "var x = 1; var y = (var x = 2; x); [x, y]",
1310 );
1311 assert_eq!(
1312 result,
1313 List::from(vec![Integer::from(1), Integer::from(2)]).into()
1314 );
1315 }
1316 #[test]
1317 fn conditional_true_branch() {
1318 let result =
1319 execute_datex_script_debug_with_result("if (true) (42) else (43)");
1320 assert_eq!(result, Integer::from(42).into());
1321 }
1322
1323 #[test]
1324 fn conditional_false_branch() {
1325 let result =
1326 execute_datex_script_debug_with_result("if (false) (42) else (43)");
1327 assert_eq!(result, Integer::from(43).into());
1328 }
1329
1330 #[test]
1331 fn conditional_no_else() {
1332 let result = execute_datex_script_debug("if (false) (42)");
1333 assert_eq!(result, None);
1334 }
1335
1336 #[test]
1337 fn conditional_nested_if_else() {
1338 let result = execute_datex_script_debug_with_result(
1339 "if (true) (1) else if (false) (2) else (3)",
1340 );
1341 assert_eq!(result, Integer::from(1).into());
1342 }
1343
1344 #[test]
1345 fn conditional_nested_else_if() {
1346 let result = execute_datex_script_debug_with_result(
1347 "if (false) (1) else if (true) (2) else (3)",
1348 );
1349 assert_eq!(result, Integer::from(2).into());
1350 }
1351
1352 #[test]
1353 fn conditional_nested_else_fallback() {
1354 let result = execute_datex_script_debug_with_result(
1355 "if (false) (1) else if (false) (2) else (3)",
1356 );
1357 assert_eq!(result, Integer::from(3).into());
1358 }
1359
1360 #[test]
1361 fn conditional_with_variable() {
1362 let result = execute_datex_script_debug_with_result(
1363 "const x = 42; if (true) (x) else (0)",
1364 );
1365 assert_eq!(result, Integer::from(42).into());
1366 }
1367
1368 #[test]
1369 fn conditional_with_variable_else_branch() {
1370 let result = execute_datex_script_debug_with_result(
1371 "const x = 99; if (false) (0) else (x)",
1372 );
1373 assert_eq!(result, Integer::from(99).into());
1374 }
1375
1376 #[test]
1377 fn conditional_complex_condition() {
1378 let result = execute_datex_script_debug_with_result(
1379 "if (1 + 1 == 2) (100) else (200)",
1380 );
1381 assert_eq!(result, Integer::from(100).into());
1382 }
1383
1384 #[test]
1385 fn conditional_mutation_in_branch() {
1386 let script = "
1387 var x = 1;
1388 if (true) (x = 2);
1389 x
1390 ";
1391 let result = execute_datex_script_debug_with_result(script);
1392 assert_eq!(result, Integer::from(2).into());
1393 }
1394
1395 #[test]
1396 fn conditional_mutation_in_false_branch() {
1397 let script = "
1398 var x = 1;
1399 if (false) (x = 2) else (x = 3);
1400 x
1401 ";
1402 let result = execute_datex_script_debug_with_result(script);
1403 assert_eq!(result, Integer::from(3).into());
1404 }
1405
1406 #[test]
1407 fn conditional_results_return() {
1408 let script = "
1409 var a = 1;
1410 var b = 2;
1411 if (false) (
1412 a = 2
1413 ) else (
1414 a = 3;
1415 b = 2;
1416 );
1417 b
1418 ";
1419 let result = execute_datex_script_debug_with_result(script);
1420 assert_eq!(result, Integer::from(2).into());
1421 }
1422
1423 #[test]
1424 fn conditional_complex_result() {
1425 let script = "
1426 var c = 0;
1427 const b = 5;
1428 const x = if (b==3) (
1429 250u8
1430 ) else (
1431 130u8
1432 );
1433 if (x==250) (
1434 c = 0u8;
1435 ) else if (x==130) (
1436 c = 1u8;
1437 ) else (
1438 c = 2u8;
1439 );
1440 c
1441 ";
1442 let result = execute_datex_script_debug_with_result(script);
1443 assert_eq!(result, TypedInteger::from(1u8).into());
1444 }
1445}