1mod implementation;
4use implementation::*;
5mod execution_result_popper;
6pub mod internal_slots;
7pub mod interrupts;
8mod runtime_value;
9pub mod state;
10use crate::{
11 core_compiler::{
12 core_compilation_context::{CompileInput, DXBWithSharedValues},
13 injected_values::compile_injected_values,
14 },
15 dxb_parser::{
16 body::{DXBParserError, SeekRequest, iterate_instructions_with_seek},
17 instruction_collector::{
18 CollectionResultsPopper, FullOrPartialResult, InstructionCollector,
19 LastUnboundedResultCollector, ResultCollector,
20 StatementResultCollectionStrategy,
21 },
22 },
23 global::operators::{BinaryOperator, ComparisonOperator, UnaryOperator},
24 instruction::{
25 Instruction, NestedInstructionResolutionStrategy,
26 instruction_data::{
27 ApplyData, ClassifiedValueData, Float32Data, Float64Data,
28 FloatAsInt16Data, FloatAsInt32Data, InstantData, IntersectionData,
29 JumpData, ListSliceCollectionData, MapData, ShortStatementsData,
30 ShortTextData, StatementsData, TaggedTypeData, TextData,
31 UnboundedStatementsData, UnionData,
32 },
33 regular_instruction::RegularInstruction,
34 type_instruction::TypeInstruction,
35 },
36 libs::core::type_id::CoreLibBaseTypeId,
37 prelude::*,
38 runtime::{
39 Runtime,
40 cache::shared_values_cache::{
41 CacheValueRetrievalError, ValueNotFoundInCacheError,
42 },
43 execution::{
44 ExecutionError, InvalidProgramError,
45 execution_loop::{
46 internal_slots::get_root_property,
47 interrupts::{
48 ExecutionInterrupt, ExternalExecutionInterrupt,
49 InterruptProvider, InterruptResult,
50 },
51 runtime_value::RuntimeValue,
52 state::RuntimeExecutionState,
53 },
54 macros::{
55 interrupt, interrupt_with_maybe_value, interrupt_with_value,
56 },
57 },
58 },
59 shared_values::{
60 PointerAddress, ReferenceMutability, ReferencedSharedContainer,
61 RemotePointerAddress, SharedContainer, SharedContainerMutability,
62 SharedContainerOwnership,
63 base_shared_value_container::BaseSharedValueContainer,
64 },
65 types::{
66 r#type::Type,
67 type_definition::{
68 TypeDefinition,
69 collection::{
70 CollectionTypeDefinition,
71 type_definition::{
72 ListCollectionTypeDefinition,
73 ListSliceCollectionTypeDefinition,
74 MapCollectionTypeDefinition,
75 },
76 },
77 impl_type::ImplMarkers,
78 intersection::IntersectionTypeDefinition,
79 map::MapTypeDefinition,
80 range::RangeTypeDefinition,
81 tagged_type::TaggedTypeDefinition,
82 union::UnionTypeDefinition,
83 },
84 type_definition_with_metadata::TypeDefinitionWithMetadata,
85 },
86 value_updates::{
87 update_data::{AppendEntryUpdateData, DeleteEntryUpdateData},
88 update_handler::UpdateHandler,
89 },
90 values::{
91 core_value::CoreValue,
92 core_value_with_classification::CoreValueWithClassification,
93 core_values::{
94 boolean::Boolean,
95 callable::{Callable, CallableBody, CoreStub},
96 decimal::{Decimal, typed_decimal::TypedDecimal},
97 endpoint::Endpoint,
98 integer::{Integer, typed_integer::TypedInteger},
99 list::List,
100 map::Map,
101 },
102 value::Value,
103 value_container::{ValueContainer, error::ValueError},
104 },
105};
106use alloc::rc::Rc;
107use core::{cell::RefCell, ops::DerefMut};
108
109mod collected_execution_result;
110use crate::{
111 instruction::instruction_data::{
112 CallMethodData, CallableSignatureData, ImplMarkersData, ShortMapData,
113 },
114 libs::core::{core_lib_id::CoreLibIdIndex, type_id::CoreLibVariantTypeId},
115 runtime::execution::macros::interrupt_with_borrowed_args_and_maybe_result,
116 traits::apply::{ApplyArgument, into_apply_arguments_with_stack_indices},
117 types::{
118 entities::entity_type_definition::EntityTypeDefinition,
119 entity_type::EntityType,
120 type_definition::{
121 callable::CallableTypeDefinition,
122 collection::type_definition::{
123 ReceiverTypeDefinition, SenderTypeDefinition,
124 },
125 },
126 },
127 value_updates::update_data::{
128 DecrementUpdateData, IncrementUpdateData, ListSpliceUpdateData,
129 },
130 values::{
131 core_values::{
132 callable::DatexBytecodeCallable,
133 integer::typed_integer::IntegerTypeVariant,
134 receiver::ValueContainerReceiver, sender::Sender,
135 },
136 value::value_classification::{ValueClassification, ValueTag},
137 value_container::borrowed_value_container::BorrowedValueContainer,
138 },
139};
140use collected_execution_result::CollectedExecutionResult;
141
142pub fn execution_loop(
145 state: RuntimeExecutionState,
146 dxb_body: Rc<RefCell<Vec<u8>>>,
147 interrupt_provider: InterruptProvider,
148) -> impl Iterator<Item = Result<ExternalExecutionInterrupt, ExecutionError>> {
149 gen move {
150 let mut active_value: Option<ValueContainer> = None;
151
152 for interrupt in
153 inner_execution_loop(dxb_body, interrupt_provider.clone(), state)
154 {
155 match interrupt {
156 Ok(interrupt) => match interrupt {
157 ExecutionInterrupt::External(external_interrupt) => {
158 yield Ok(external_interrupt);
159 }
160 ExecutionInterrupt::SetActiveValue(value) => {
161 active_value = value;
162 }
163 ExecutionInterrupt::TakeActiveValue => {
164 interrupt_provider.provide_result(
165 InterruptResult::ResolvedValue(active_value.take()),
166 );
167 }
168 },
169 Err(err) => {
170 match err {
171 ExecutionError::DXBParserError(
172 DXBParserError::ExpectingMoreInstructions(_),
173 ) => {
174 yield Err(
175 ExecutionError::IntermediateResultWithState(
176 Box::new(active_value.take()),
177 Box::new(None),
178 ),
179 );
180 continue;
183 }
184 _ => {
185 yield Err(err);
186 }
187 }
188 }
189 }
190 }
191 }
192}
193
194pub gen fn inner_execution_loop(
195 dxb_body: Rc<RefCell<Vec<u8>>>,
196 interrupt_provider: InterruptProvider,
197 mut state: RuntimeExecutionState,
198) -> Result<ExecutionInterrupt, ExecutionError> {
199 let mut collector =
200 InstructionCollector::<CollectedExecutionResult>::default();
201
202 let seek_request: SeekRequest = Rc::new(RefCell::new(None));
203
204 for instruction_result in iterate_instructions_with_seek(
205 dxb_body,
206 NestedInstructionResolutionStrategy::None,
207 Some(seek_request.clone()),
208 ) {
209 let instruction = match instruction_result {
210 Ok(instruction) => instruction,
211 Err(DXBParserError::ExpectingMoreInstructions(stack)) => {
212 yield Err(
213 DXBParserError::ExpectingMoreInstructions(stack).into()
214 );
215 continue;
218 }
219 Err(err) => {
220 return yield Err(err.into());
221 }
222 };
223
224 let result: Option<CollectedExecutionResult> = match instruction
225 .instruction
226 {
227 Instruction::Regular(regular_instruction) => {
229 let regular_instruction = collector
230 .default_instruction_collection(
231 Instruction::Regular(regular_instruction),
232 StatementResultCollectionStrategy::Last,
233 state.stack.current_index(),
234 )
235 .map(|instruction| match instruction {
236 Instruction::Regular(regular) => regular,
237 _ => unreachable!(),
238 });
239
240 let expr: Option<Option<RuntimeValue>> = if let Some(
241 regular_instruction,
242 ) =
243 regular_instruction
244 {
245 if let RegularInstruction::Jump(data) = regular_instruction
246 {
247 seek_request.borrow_mut().replace(data.offset);
249 None
250 } else {
251 let regular_result: Result<
252 Option<RuntimeValue>,
253 ExecutionError,
254 > = try {
255 match regular_instruction {
256 RegularInstruction::Jump(_) => unreachable!(),
258 RegularInstruction::True => Some(ValueContainer::from(true).into()),
260 RegularInstruction::False => Some(ValueContainer::from(false).into()),
261
262 RegularInstruction::Receiver => Some(ValueContainer::from(ValueContainerReceiver::new_with_remote_sender()).into()),
263
264 RegularInstruction::Int8(integer) => {
266 Some(ValueContainer::from(TypedInteger::from(integer.0)).into())
267 }
268 RegularInstruction::Int16(integer) => {
269 Some(ValueContainer::from(TypedInteger::from(integer.0)).into())
270 }
271 RegularInstruction::Int32(integer) => {
272 Some(ValueContainer::from(TypedInteger::from(integer.0)).into())
273 }
274 RegularInstruction::Int64(integer) => {
275 Some(ValueContainer::from(TypedInteger::from(integer.0)).into())
276 }
277 RegularInstruction::Int128(integer) => {
278 Some(ValueContainer::from(TypedInteger::from(integer.0)).into())
279 }
280
281 RegularInstruction::UInt8(integer) => {
283 Some(ValueContainer::from(TypedInteger::from(integer.0)).into())
284 }
285 RegularInstruction::UInt16(integer) => {
286 Some(ValueContainer::from(TypedInteger::from(integer.0)).into())
287 }
288 RegularInstruction::UInt32(integer) => {
289 Some(ValueContainer::from(TypedInteger::from(integer.0)).into())
290 }
291 RegularInstruction::UInt64(integer) => {
292 Some(ValueContainer::from(TypedInteger::from(integer.0)).into())
293 }
294 RegularInstruction::UInt128(integer) => {
295 Some(ValueContainer::from(TypedInteger::from(integer.0)).into())
296 }
297
298 RegularInstruction::BigInteger(integer) => {
300 Some(ValueContainer::from(TypedInteger::IBig(integer)).into())
301 }
302
303 RegularInstruction::Integer(integer) => {
305 Some(ValueContainer::from(integer).into())
306 }
307
308 RegularInstruction::DecimalF32(Float32Data(f32)) => {
310 Some(ValueContainer::from(TypedDecimal::from(f32)).into())
311 }
312 RegularInstruction::DecimalF64(Float64Data(f64)) => {
313 Some(ValueContainer::from(TypedDecimal::from(f64)).into())
314 }
315 RegularInstruction::BigDecimal(big_decimal) => {
317 Some(ValueContainer::from(TypedDecimal::Decimal(big_decimal)).into())
318 }
319
320 RegularInstruction::DecimalAsInt16(FloatAsInt16Data(i16)) => {
322 Some(ValueContainer::from(Decimal::from(i16 as f32)).into())
323 }
324 RegularInstruction::DecimalAsInt32(FloatAsInt32Data(i32)) => {
325 Some(ValueContainer::from(Decimal::from(i32 as f32)).into())
326 }
327 RegularInstruction::Decimal(big_decimal) => {
328 Some(ValueContainer::from(big_decimal).into())
329 }
330
331 RegularInstruction::CompactList(list_data) => {
333 if list_data.core_lib_type == CoreLibIdIndex::from(CoreLibVariantTypeId::Integer(IntegerTypeVariant::U8)) {
335 Some(ValueContainer::from(list_data.elements).into())
336 }
337 else {
338 todo!()
339 }
340 }
341
342 RegularInstruction::Endpoint(endpoint) => Some(ValueContainer::from(endpoint).into()),
344
345 RegularInstruction::Instant(InstantData(timestamp)) => {
347 Some(ValueContainer::from(Integer::new(timestamp)).into())
348 }
349
350 RegularInstruction::Null => Some(ValueContainer::from(Value::null()).into()),
352
353 RegularInstruction::Uninitialized => Some(ValueContainer::from(Value::uninitialized()).into()),
354
355 RegularInstruction::ShortText(ShortTextData(text)) => {
357 Some(ValueContainer::from(text).into())
358 }
359 RegularInstruction::Text(TextData(text)) => Some(ValueContainer::from(text).into()),
360
361 RegularInstruction::RequestRemoteSharedRef(address) => Some(interrupt_with_value!(
362 interrupt_provider,
363 ExecutionInterrupt::External(
364 ExternalExecutionInterrupt::GetReferenceToRemotePointer(address, ReferenceMutability::Immutable)
365 )
366 ).into()),
367
368 RegularInstruction::RequestRemoteSharedRefMut(address) => Some(interrupt_with_value!(
369 interrupt_provider,
370 ExecutionInterrupt::External(
371 ExternalExecutionInterrupt::GetReferenceToRemotePointer(address, ReferenceMutability::Mutable)
372 )
373 ).into()),
374
375 RegularInstruction::GetLocalSharedRef(address) => {
376 let val = interrupt_with_maybe_value!(
377 interrupt_provider,
378 ExecutionInterrupt::External(
379 ExternalExecutionInterrupt::GetReferenceToLocalPointer(
380 address
381 )
382 )
383 );
384 if let Some(val) = val {
385 Some(val.into())
386 } else {
387 return yield Err(ExecutionError::ReferenceNotFound);
388 }
389 }
390
391 RegularInstruction::GetCoreLibValue(id) => {
392 Some(interrupt_with_value!(
393 interrupt_provider,
394 ExecutionInterrupt::External(
395 ExternalExecutionInterrupt::GetCoreLibValue(
396 id.try_into().map_err(|_| ExecutionError::invalid_program(InvalidProgramError::InvalidCoreLibId(id)))?
397 )
398 )
399 ).into())
400 }
401
402 RegularInstruction::GetRootProperty(stack_index) => {
403 Some(RuntimeValue::ValueContainer(get_root_property(
404 &state.runtime,
405 &state.caller_metadata,
406 stack_index,
407 )?))
408 }
409
410 RegularInstruction::BorrowStackValue(index) => {
411 Some(RuntimeValue::StackValue(index))
412 }
413
414 RegularInstruction::GetStackValueSharedRef(index) => {
415 let value = state.stack.get_stack_value(index)?;
416 match value {
417 ValueContainer::Shared(container) => Some(RuntimeValue::ValueContainer(
418 ValueContainer::Shared(SharedContainer::Referenced(container.derive_immutable_reference()))
419 )),
420 _ => return yield Err(ExecutionError::ExpectedSharedValue)
421 }
422 }
423 RegularInstruction::GetStackValueSharedRefMut(index) => {
424 let value = state.stack.get_stack_value(index)?;
425 match value {
426 ValueContainer::Shared(container) => Some(RuntimeValue::ValueContainer(
427 ValueContainer::Shared(SharedContainer::Referenced(
428 container
429 .try_derive_mutable_reference()
430 .map_err(|_| ExecutionError::MutableReferenceToNonMutableValue)?
431 ))
432 )),
433 _ => return yield Err(ExecutionError::ExpectedSharedValue)
434 }
435 }
436
437 RegularInstruction::CloneStackValue(index) => {
438 let value = state.stack.get_stack_value(index)?;
439 Some(RuntimeValue::ValueContainer(
440 value.get_cloned()
441 ))
442 }
443
444 RegularInstruction::TakeStackValue(index) => {
445 Some(RuntimeValue::ValueContainer(
446 state.stack.take_stack_value(index)?
447 ))
448 }
449
450 RegularInstruction::SharedRef(shared_ref) => {
451 let address = state.normalize_pointer_address(&shared_ref.address);
452 let container = resolve_cache_value(
454 &mut state,
455 &address,
456 SharedContainerOwnership::Referenced(shared_ref.ref_mutability),
457 )?;
458 Some(RuntimeValue::ValueContainer(ValueContainer::Shared(container)))
459 }
460
461 RegularInstruction::ClassifiedValue(ClassifiedValueData {
462 tag_value_is_empty: true,
463 tag: Some(tag),
464 is_entity: false,
465 impls,
466 ..
467 }) => {
468
469 Some(RuntimeValue::ValueContainer(
470 ValueContainer::Local(Value::core_with_classification(CoreValue::Null, ValueClassification {
471 tag: Some(ValueTag {
472 name: tag.0,
473 is_empty: true,
474 }),
475 impls,
476 entity_type: None
477 }))))
478 }
479
480 RegularInstruction::Statements(_) |
482 RegularInstruction::ShortStatements(_) |
483 RegularInstruction::UnboundedStatements |
484 RegularInstruction::UnboundedStatementsEnd(_) |
485 RegularInstruction::List(_) |
486 RegularInstruction::Range |
487 RegularInstruction::ShortList(_) |
488 RegularInstruction::Map(_) |
489 RegularInstruction::ShortMap(_) |
490 RegularInstruction::ClassifiedValue(_) |
491 RegularInstruction::KeyValueDynamic |
492 RegularInstruction::KeyValueShortText(_) |
493 RegularInstruction::Add |
494 RegularInstruction::Subtract |
495 RegularInstruction::Multiply |
496 RegularInstruction::Divide |
497 RegularInstruction::UnaryMinus |
498 RegularInstruction::UnaryPlus |
499 RegularInstruction::BitwiseNot |
500 RegularInstruction::Apply(_) |
501 RegularInstruction::CallMethod(_) |
502 RegularInstruction::GetEntryText(_) |
503 RegularInstruction::GetEntryIndex(_) |
504 RegularInstruction::GetEntryDynamic |
505 RegularInstruction::TakeEntryText(_) |
506 RegularInstruction::TakeEntryIndex(_) |
507 RegularInstruction::TakeEntryDynamic |
508 RegularInstruction::SetEntryText(_) |
509 RegularInstruction::SetEntryIndex(_) |
510 RegularInstruction::SetEntryDynamic |
511 RegularInstruction::Is |
512 RegularInstruction::Sender |
513 RegularInstruction::JumpIfFalse(_) |
514 RegularInstruction::JumpWithValue(_) |
515 RegularInstruction::Matches |
516 RegularInstruction::StructuralEqual |
517 RegularInstruction::Equal |
518 RegularInstruction::NotStructuralEqual |
519 RegularInstruction::NotEqual |
520 RegularInstruction::DeriveSharedReference |
521 RegularInstruction::DeriveSharedReferenceMut |
522 RegularInstruction::CreateShared |
523 RegularInstruction::CreateSharedMut |
524 RegularInstruction::PushToStack |
525 RegularInstruction::PushListToStack |
526 RegularInstruction::SetStackValue(_) |
527 RegularInstruction::Splice(_) |
528 RegularInstruction::SpliceDynamic |
529 RegularInstruction::AppendEntry |
530 RegularInstruction::Clear |
531 RegularInstruction::Increment |
532 RegularInstruction::Decrement |
533 RegularInstruction::SetSharedContainerValue |
534 RegularInstruction::Unbox |
535 RegularInstruction::RemoteExecution(_) |
536 RegularInstruction::MoveWithValue(_) |
537 RegularInstruction::SharedRefWithValue(_) |
538 RegularInstruction::CallableDeclaration(_) |
539 RegularInstruction::Callable(_) |
540 RegularInstruction::EntityTypeDefinition(_) |
541 RegularInstruction::BoxedValue |
542 RegularInstruction::TypeExpression => {
543 unreachable!()
546 },
547 #[cfg(feature = "disassembler")]
548 RegularInstruction::_RemoteExecutionDebugFlat(_) |
549 RegularInstruction::_RemoteExecutionDebugTree(_) |
550 RegularInstruction::_CallableDeclarationDebugFlat(_) |
551 RegularInstruction::_CallableDeclarationDebugTree(_) |
552 RegularInstruction::_CallableDebugFlat(_) |
553 RegularInstruction::_CallableDebugTree(_)
554 => unreachable!(),
555 }
556 };
557 Some(match regular_result {
558 Ok(value) => value,
559 Err(error) => return yield Err(error),
560 })
561 }
562 } else {
563 None
564 };
565
566 expr.map(CollectedExecutionResult::from)
567 }
568 Instruction::Type(type_instruction) => {
569 let type_instruction = collector
570 .default_instruction_collection(
571 Instruction::Type(type_instruction),
572 StatementResultCollectionStrategy::Last,
573 state.stack.current_index(),
574 )
575 .map(|instruction| match instruction {
576 Instruction::Type(ty) => ty,
577 _ => unreachable!(),
578 });
579
580 if let Some(type_instruction) = type_instruction {
581 Some(match type_instruction {
582 TypeInstruction::CoreType(core_lib_type_id) => {
583 CollectedExecutionResult::type_definition(
584 TypeDefinition::CoreType(core_lib_type_id),
585 )
586 }
587 TypeInstruction::Literal(literal) => {
588 CollectedExecutionResult::type_definition(
589 literal.into(),
590 )
591 }
592 TypeInstruction::TaggedType(TaggedTypeData {
593 tag,
594 has_type: false,
595 }) => CollectedExecutionResult::type_definition(
596 TypeDefinition::TaggedType(
597 TaggedTypeDefinition::new_without_type(tag.0),
599 ),
600 ),
601
602 TypeInstruction::SharedTypeReference(type_ref) => {
603 let val = interrupt_with_maybe_value!(
604 interrupt_provider,
605 match type_ref.address {
606 PointerAddress::SelfOwned(address) => {
607 ExecutionInterrupt::External(
608 ExternalExecutionInterrupt::GetReferenceToLocalPointer(
609 address,
610 ),
611 )
612 }
613 PointerAddress::Remote(address) => {
614 ExecutionInterrupt::External(
615 ExternalExecutionInterrupt::GetReferenceToRemotePointer(
616 address,
617 ReferenceMutability::Immutable,
618 ),
619 )
620 }
621 }
622 );
623
624 match val {
625 Some(ValueContainer::Local(Value::Core(
627 CoreValueWithClassification {
628 inner: CoreValue::Type(_ty),
629 ..
630 },
631 ))) => todo!(),
632 _ => {
643 return yield Err(
644 ExecutionError::ExpectedTypeValue,
645 );
646 }
647 }
648 }
649
650 TypeInstruction::ImplMarkers(ImplMarkersData {
651 impls,
652 ..
653 }) => CollectedExecutionResult::type_definition(
654 TypeDefinition::ImplMarkers(ImplMarkers::new(
655 impls,
656 )),
657 ),
658
659 TypeInstruction::List(_)
661 | TypeInstruction::Intersection(_)
662 | TypeInstruction::ListSliceCollection(_)
663 | TypeInstruction::MapCollection
664 | TypeInstruction::ListCollection
665 | TypeInstruction::Boxed
666 | TypeInstruction::Union(_)
667 | TypeInstruction::Callable(_)
668 | TypeInstruction::EntityType
669 | TypeInstruction::Sender
670 | TypeInstruction::Receiver
671 | TypeInstruction::Map(_)
672 | TypeInstruction::DefinitionWithMetadata(_)
673 | TypeInstruction::Range
674 | TypeInstruction::TaggedType(TaggedTypeData {
675 has_type: true,
676 ..
677 }) => {
678 panic!(
679 "Unexpected type instruction: {:?}",
680 type_instruction
681 );
682 }
683 })
684 } else {
685 None
686 }
687 }
688 };
689
690 if let Some(result) = result {
691 collector.push_result(result);
692 }
693
694 while let Some(result) = collector.try_pop_collected() {
696 let expr_result: Result<CollectedExecutionResult, ExecutionError> = try {
697 match result {
698 FullOrPartialResult::Full {
699 instruction,
700 results: mut collected_results,
701 } => {
702 match instruction {
703 Instruction::Regular(
704 regular_instruction,
705 ) => match regular_instruction {
706
707 RegularInstruction::Sender => {
708 let receiver_shared_container = collected_results.try_pop_value_container(&mut state)?;
709 let receiver_shared_container = match receiver_shared_container {
710 ValueContainer::Shared(shared) => shared,
711 _ => return yield Err(ExecutionError::ExpectedSharedValue),
712 };
713
714 RuntimeValue::ValueContainer(
715 ValueContainer::from(Sender::<ValueContainer>::try_from(&receiver_shared_container.derive_reference_with_max_mutability()).map_err(|_| ExecutionError::InvalidSharedValueType)?)
716 ).into()
717 }
718
719
720 RegularInstruction::List(_)
721 | RegularInstruction::ShortList(_) => {
722 let elements = collected_results.try_collect_value_containers(&mut state)?;
723 RuntimeValue::ValueContainer(
724 ValueContainer::from(List::new(
725 elements,
726 )),
727 )
728 .into()
729 }
730 RegularInstruction::Map(MapData {allow_only_text_keys, ..})
731 | RegularInstruction::ShortMap(ShortMapData {allow_only_text_keys, ..}) => {
732 let entries = collected_results.try_collect_key_value_pair()?;
733 RuntimeValue::ValueContainer(
734 ValueContainer::from(Map::try_new(
735 entries,
736 allow_only_text_keys,
737 ).map_err(|_e| ExecutionError::InvalidTypeCast)?),
738 )
739 .into()
740 }
741
742 RegularInstruction::KeyValueDynamic => {
743 let value = collected_results.try_pop_value_container(&mut state)?;
744 let key = collected_results
745 .try_pop_value_container(&mut state)?;
746 CollectedExecutionResult::key_value_pair(
747 key,
748 value,
749 )
750 }
751
752 RegularInstruction::KeyValueShortText(
753 short_text_data,
754 ) => {
755 let value = collected_results.try_pop_value_container(&mut state)?;
756 let key = ValueContainer::from(short_text_data.0);
757 CollectedExecutionResult::key_value_pair(
758 key, value,
759 )
760 }
761
762 RegularInstruction::ClassifiedValue(ClassifiedValueData {
763 tag,
764 tag_value_is_empty,
765 impls,
766 is_entity,
767 ..
768 }) => {
769 let mut value_container = if tag_value_is_empty {
770 if tag.is_none() {
771 return yield Err(ExecutionError::InvalidProgram(Box::new(InvalidProgramError::InvalidInstructionFormat)));
773 }
774 ValueContainer::Local(Value::null())
775 } else {
776 collected_results.try_pop_value_container(&mut state)?
777 };
778
779 let entity_type = if is_entity {
780 let entity_container: ValueContainer = collected_results
781 .try_pop_value_container(&mut state)?;
782 let entity_container = match entity_container {
783 ValueContainer::Shared(shared) => shared,
784 _ => return yield Err(ExecutionError::ExpectedSharedValue)
785 };
786
787 Some(EntityType::try_from(entity_container)
789 .map_err(|_| ExecutionError::invalid_program(InvalidProgramError::InvalidType))?)
790 } else {
791 None
792 };
793 let classification = ValueClassification {
794 entity_type,
795 impls,
796 tag:tag.map(|t| ValueTag::from(t.0)),
797 };
798
799 match &mut value_container {
800 ValueContainer::Local(Value::Core(value)) => {
801 value.classification = classification;
802 }
803 _ => return yield Err(ExecutionError::invalid_program(InvalidProgramError::InvalidType)),
804 }
805 RuntimeValue::ValueContainer(
806 value_container,
807 ).into()
808 }
809
810 RegularInstruction::Add
811 | RegularInstruction::Subtract
812 | RegularInstruction::Multiply
813 | RegularInstruction::Range
814 | RegularInstruction::Divide => {
815 let right = collected_results
816 .try_pop_runtime_value()?;
817 let left = collected_results
818 .try_pop_runtime_value()?;
819
820 let res = handle_binary_operation(
821 BinaryOperator::from(
822 regular_instruction,
823 ),
824 left.as_value_container(&state.stack)?,
825 right.as_value_container(&state.stack)?,
826 )?;
827 res.into()
828 }
829
830 RegularInstruction::Is
831 | RegularInstruction::StructuralEqual
832 | RegularInstruction::Equal
833 | RegularInstruction::NotStructuralEqual
834 | RegularInstruction::NotEqual => {
835 let right = collected_results
836 .try_pop_runtime_value()?;
837 let left = collected_results
838 .try_pop_runtime_value()?;
839
840 let res = handle_comparison_operation(
841 ComparisonOperator::from(
842 regular_instruction,
843 ),
844 left.as_value_container(&state.stack)?,
845 right.as_value_container(&state.stack)?,
846 )?;
847 res.into()
848 }
849
850 RegularInstruction::CallableDeclaration(callable_declaration) => {
851 let types = collected_results.pop_types(callable_declaration.signature.total_type_count());
852 let signature = resolve_callable_type_definition(types, &callable_declaration.signature);
853 let injected_values = state.stack.resolve_injected_values(&callable_declaration.body.injected_values)?;
854
855 ValueContainer::from(Callable {
856 name: if callable_declaration.signature.name.0.is_empty() {
857 None
858 } else {
859 Some(callable_declaration.signature.name.0)
860 },
861 signature,
862 body: CallableBody::DatexBytecode(DatexBytecodeCallable {
863 requires_async: callable_declaration.signature.requires_async,
864 injected_values,
865 body: callable_declaration.body.body,
866 }),
867 creator: state.caller_metadata.endpoint.clone(),
868 docs: None,
869 })
870 .into()
871 }
872 RegularInstruction::Callable(callable_data) => {
873
874 let has_native_impl = callable_data.body.length == 0;
876
877 let injected_values = collected_results
878 .pop_values(callable_data.body.injected_value_count)
879 .into_iter()
880 .flatten()
881 .map(|runtime_value| runtime_value.into_value_container(&mut state))
882 .collect::<Result<Vec<_>, ExecutionError>>()?;
883
884 let types = collected_results.pop_types(callable_data.signature.total_type_count());
885 let mut signature = resolve_callable_type_definition(types, &callable_data.signature);
886
887 if has_native_impl {
889 signature.requires_async = true;
890 }
891
892 ValueContainer::from(Callable {
893 name: if callable_data.signature.name.0.is_empty() {
894 None
895 } else {
896 Some(callable_data.signature.name.0)
897 },
898 signature,
899 body: if has_native_impl {
900 CallableBody::Hidden
901 }
902 else {
903 CallableBody::DatexBytecode(DatexBytecodeCallable {
904 requires_async: callable_data.signature.requires_async,
905 injected_values,
906 body: callable_data.body.body,
907 })
908 },
909 creator: state.caller_metadata.endpoint.clone(),
910 docs: None,
911 })
912 .into()
913 }
914
915 RegularInstruction::EntityTypeDefinition(data) => {
916 let definition = collected_results.pop_type_definition();
917 ValueContainer::from(CoreValue::EntityTypeDefinition(EntityTypeDefinition {
919 definition,
920 name: data.name.0,
921 allowed_variants: vec![],
922 impls: vec![],
923 deserialize_from_dif: None,
924 })).into()
925 }
926
927 RegularInstruction::Matches => {
928 let _target = collected_results
929 .try_pop_runtime_value()?;
930 let _type_pattern =
931 collected_results.pop_type();
932
933 todo!("#645 Undescribed by author.")
934 }
935
936 instruction @ (
937 RegularInstruction::CreateShared |
938 RegularInstruction::CreateSharedMut
939 ) => {
940 let value = collected_results
941 .try_pop_value_container(&mut state)?;
942 let mutability = match instruction {
943 RegularInstruction::CreateShared => SharedContainerMutability::Immutable,
944 RegularInstruction::CreateSharedMut => SharedContainerMutability::Mutable,
945 _ => unreachable!(),
946 };
947
948 create_owned_shared_container(
949 value,
950 mutability,
951 state.runtime.pointer_address_provider_mut().deref_mut(),
952 ).into()
953 }
954
955 RegularInstruction::DeriveSharedReference => {
956 let target = collected_results
957 .try_pop_value_container(&mut state)?;
958
959 derive_shared_reference(
960 &target,
961 ReferenceMutability::Immutable,
962 )?.into()
963 }
964
965 RegularInstruction::DeriveSharedReferenceMut => {
966 let target = collected_results
967 .try_pop_value_container(&mut state)?;
968 derive_shared_reference(
969 &target,
970 ReferenceMutability::Mutable,
971 )?.into()
972 }
973
974 RegularInstruction::UnaryMinus
975 | RegularInstruction::UnaryPlus
976 | RegularInstruction::BitwiseNot
977 | RegularInstruction::Unbox => {
978 let target = collected_results
979 .try_pop_runtime_value()?;
980 let value_container = target.as_value_container(
981 &state.stack
982 )?.clone();
983 let res = handle_unary_operation(
984 UnaryOperator::from(
985 regular_instruction,
986 ),
987 value_container, state.runtime.shared_references_cache_refcell(),
989 )?;
990 RuntimeValue::ValueContainer(
991 res
992 ).into()
993 }
994 RegularInstruction::BoxedValue => {
995 let expression = collected_results.try_pop_runtime_value()?;
996 let value_container = expression.into_value_container(&mut state)?;
997 ValueContainer::from(Value::boxed(value_container)).into()
998 }
999
1000 RegularInstruction::TypeExpression => {
1002 let ty =
1003 collected_results.pop_type();
1004 RuntimeValue::ValueContainer(
1005 ValueContainer::Local(Value::new(CoreValue::Type(ty))),
1006 )
1007 .into()
1008 }
1009
1010 RegularInstruction::SetSharedContainerValue => {
1011 let mut target = collected_results
1012 .try_pop_runtime_value()?;
1013 let new_value: ValueContainer = collected_results
1014 .try_pop_runtime_value()?
1015 .into_value_container(&mut state)?;
1016 let source_id = state.source_id_cloned();
1017 let target = target.as_value_container_mut(&mut state.stack)?;
1018 try_set_shared_container_value(
1019 target,
1020 new_value,
1021 source_id,
1022 state.runtime.shared_references_cache_refcell()
1023 )?;
1024 None.into()
1025 }
1026
1027 RegularInstruction::Splice(
1028 splice,
1029 ) => {
1030 let source_id = state.source_id_cloned();
1031 let mut target = collected_results.try_pop_runtime_value()?;
1032 let values = collected_results.try_collect_value_containers(&mut state)?;
1033 let target_value = target.as_value_container_mut(&mut state.stack)?;
1034
1035 let res_values = target_value
1036 .try_list_splice(vec![], source_id, ListSpliceUpdateData::new(
1037 splice.start_index,
1038 splice.delete_count,
1039 values,
1040 ), state.runtime.shared_references_cache_refcell()).map_err(|e| e.into())?;
1041
1042 ValueContainer::from(List::new(res_values)).into()
1044 }
1045
1046 RegularInstruction::SpliceDynamic => {
1047 let source_id = state.source_id_cloned();
1048 let mut target = collected_results.try_pop_runtime_value()?;
1049 let values = collected_results.try_pop_value_container(&mut state)?;
1050 let delete_count = collected_results.try_pop_value_container(&mut state)?;
1051 let start_index = collected_results.try_pop_value_container(&mut state)?;
1052
1053 let values: List = match values.try_into_value() {
1055 Ok(list) => list,
1056 Err(_) => return yield Err(ExecutionError::invalid_program(InvalidProgramError::ExpectedList))
1057 };
1058 let delete_count: u32 = match delete_count.clone().try_into_value::<Integer>() {
1060 Ok(int) => int.as_wrapped_u32(),
1061 Err(_) => match delete_count.try_into_value::<TypedInteger>() {
1062 Ok(int) => int.as_usize().unwrap() as u32,
1063 Err(_) => return yield Err(ExecutionError::invalid_program(InvalidProgramError::ExpectedList)),
1064 }
1065 };
1066
1067 let start_index: u32 = match start_index.clone().try_into_value::<Integer>() {
1069 Ok(int) => int.as_wrapped_u32(),
1070 Err(_) => match start_index.try_into_value::<TypedInteger>() {
1071 Ok(int) => int.as_usize().unwrap() as u32,
1072 Err(_) => return yield Err(ExecutionError::invalid_program(InvalidProgramError::ExpectedList)),
1073 }
1074 };
1075
1076 let target_value = target.as_value_container_mut(&mut state.stack)?;
1077
1078 let res_values = target_value
1079 .try_list_splice(vec![], source_id, ListSpliceUpdateData::new(
1080 start_index,
1081 delete_count,
1082 values.into_vec(),
1083 ), state.runtime.shared_references_cache_refcell()).map_err(|e| e.into())?;
1084
1085 ValueContainer::from(List::new(res_values)).into()
1087 }
1088
1089 RegularInstruction::Clear => {
1090 let source_id = state.source_id_cloned();
1091 let mut target = collected_results.try_pop_runtime_value()?;
1092 let target_value = target.as_value_container_mut(&mut state.stack)?;
1093
1094 let _res = target_value
1096 .try_clear(vec![], source_id, state.runtime.shared_references_cache_refcell())
1097 .map_err(|e| e.into())?;
1098
1099 None.into()
1100 }
1101 RegularInstruction::AppendEntry => {
1102 let source_id = state.source_id_cloned();
1103 let mut target = collected_results.try_pop_runtime_value()?;
1104 let value = collected_results.try_pop_value_container(&mut state)?;
1105 let target_value = target.as_value_container_mut(&mut state.stack)?;
1106
1107 target_value
1108 .try_append_entry(vec![], source_id, AppendEntryUpdateData::new(value), state.runtime.shared_references_cache_refcell())
1109 .map_err(|e| e.into())?;
1110
1111 None.into()
1112 }
1113
1114 RegularInstruction::Increment => {
1115 let source_id = state.source_id_cloned();
1116 let mut target = collected_results.try_pop_runtime_value()?;
1117 let value = collected_results.try_pop_value_container(&mut state)?;
1118 let target_value = target.as_value_container_mut(&mut state.stack)?;
1119
1120
1121 target_value
1122 .try_increment(vec![], source_id, IncrementUpdateData::new(value), state.runtime.shared_references_cache_refcell())
1123 .map_err(|e| e.into())?;
1124
1125 None.into()
1126 }
1127
1128 RegularInstruction::Decrement => {
1129 let source_id = state.source_id_cloned();
1130 let mut target = collected_results.try_pop_runtime_value()?;
1131 let value = collected_results.try_pop_value_container(&mut state)?;
1132 let target_value = target.as_value_container_mut(&mut state.stack)?;
1133
1134 target_value
1135 .try_decrement(vec![], source_id, DecrementUpdateData::new(value), state.runtime.shared_references_cache_refcell())
1136 .map_err(|e| e.into())?;
1137
1138 None.into()
1139 }
1140
1141 RegularInstruction::SetStackValue(index) => {
1142 let value = collected_results
1143 .try_pop_value_container(&mut state)?;
1144 state
1145 .stack
1146 .set_stack_value(index, value)?;
1147 None.into()
1148 }
1149
1150 RegularInstruction::PushToStack => {
1151 let value = collected_results
1152 .try_pop_value_container(&mut state)?;
1153
1154 state
1155 .stack
1156 .push(value);
1157
1158 None.into()
1159 }
1160
1161 RegularInstruction::PushListToStack => {
1162 let value = collected_results
1163 .try_pop_value_container(&mut state)?;
1164
1165 match value {
1168 ValueContainer::Local(Value::Core(CoreValueWithClassification{ inner: CoreValue::List(list), .. })) => {
1169 for value in list {
1170 state.stack
1171 .push(value);
1172 }
1173 }
1174 _ => {
1175 return yield Err(ExecutionError::invalid_program(InvalidProgramError::ExpectedList))
1176 }
1177 }
1178
1179 None.into()
1180 }
1181
1182 RegularInstruction::GetEntryText(
1183 property_data,
1184 ) => {
1185 let mut target = collected_results
1186 .try_pop_runtime_value()?;
1187 let property_name = property_data.0;
1188 let target = target.as_value_container_mut(
1189 &mut state.stack
1190 )?;
1191
1192 let res = if let Some(endpoint) = target.try_as::<Endpoint>() {
1193 interrupt_with_value!(
1194 interrupt_provider,
1195 ExecutionInterrupt::External(
1196 ExternalExecutionInterrupt::GetEndpointProperty{
1197 endpoint: endpoint.clone(),
1198 property_name,
1199 }
1200 )
1201 )
1202 } else {
1203 let collapsed_value = target.collapsed_value();
1204 collapsed_value.borrow().try_get_property(
1205 &ValueContainer::from(property_name),
1206 )
1207 .map(BorrowedValueContainer::try_clone_to_value_container) .map_err(ExecutionError::access_error)?
1209 .map_err(|_| ExecutionError::UnclonableValue)?
1210 };
1211
1212 res.into()
1213 }
1214
1215 RegularInstruction::GetEntryIndex(
1216 property_data,
1217 ) => {
1218 let target = collected_results
1219 .try_pop_runtime_value()?;
1220 let property_index = property_data.0;
1221
1222 let value_container = target.as_value_container(&state.stack)?;
1223 let collapsed_value = value_container.collapsed_value();
1224 let res = collapsed_value.borrow()
1225 .try_get_property(
1226 &ValueContainer::from(property_index)
1227 )
1228 .map(BorrowedValueContainer::try_clone_to_value_container) .map_err(ExecutionError::access_error)?
1230 .map_err(|_| ExecutionError::UnclonableValue)?;
1231 res.into()
1232 }
1233
1234 RegularInstruction::GetEntryDynamic => {
1235 let key = collected_results
1236 .try_pop_value_container(&mut state)?;
1237 let target = collected_results
1238 .try_pop_runtime_value()?;
1239
1240 let value_container = target.as_value_container(&state.stack)?;
1241 let collapsed_value = value_container.collapsed_value();
1242 let res = collapsed_value.borrow()
1243 .try_get_property(&key)
1244 .map(BorrowedValueContainer::try_clone_to_value_container) .map_err(ExecutionError::access_error)?
1246 .map_err(|_| ExecutionError::UnclonableValue)?;
1247
1248 res.into()
1249 }
1250
1251 RegularInstruction::TakeEntryIndex(
1252 property_data,
1253 ) => {
1254 let mut target = collected_results
1255 .try_pop_runtime_value()?;
1256 let property_index = property_data.0;
1257
1258 let source_id = state.source_id_cloned();
1259 let value_container = target.as_value_container_mut(&mut state.stack)?;
1260 let res = value_container.try_delete_entry(
1261 vec![], source_id,
1263 DeleteEntryUpdateData { key: ValueContainer::local(property_index as i64) },
1264 state.runtime.shared_references_cache_refcell()
1265 ).map_err(ExecutionError::update_error)?;
1266 ValueContainer::new_from_option(res)
1267 .into()
1268 }
1269
1270 RegularInstruction::SetEntryText(
1271 property_data,
1272 ) => {
1273 let mut target_runtime_value = collected_results
1274 .try_pop_runtime_value()?;
1275 let value_runtime_value = collected_results
1276 .try_pop_runtime_value()?;
1277 let source_id = state.source_id_cloned();
1278 let value = value_runtime_value.into_value_container(&mut state)?;
1279 let target = target_runtime_value.as_value_container_mut(&mut state.stack)?;
1280
1281 let res = if let Some(endpoint) = target.try_as::<Endpoint>() {
1282 interrupt_with_maybe_value!(
1283 interrupt_provider,
1284 ExecutionInterrupt::External(
1285 ExternalExecutionInterrupt::SetEndpointProperty
1286 {
1287 endpoint: endpoint.clone(),
1288 property_name: property_data.0,
1289 value,
1290 }
1291 )
1292 )
1293 } else {
1294 try_set_property(
1295 target,
1296 ValueContainer::local(
1297 property_data.0,
1298 ),
1299 value,
1300 vec![], source_id,
1302 state.runtime.shared_references_cache_refcell(),
1303 )?
1304 };
1305 ValueContainer::new_from_option(res).into()
1306 }
1307
1308 RegularInstruction::SetEntryIndex(
1309 property_data,
1310 ) => {
1311 let mut target = collected_results
1312 .try_pop_runtime_value()?;
1313 let value = collected_results
1314 .try_pop_value_container(&mut state)?;
1315 let source_id = state.source_id_cloned();
1316 let value_container = target.as_value_container_mut(&mut state.stack)?;
1317
1318 let _res = try_set_property(
1319 value_container,
1320 ValueContainer::local(
1321 property_data.0 as i64,
1322 ),
1323 value,
1324 vec![], source_id,
1326 state.runtime.shared_references_cache_refcell())?;
1327 None.into()
1328 }
1329
1330 RegularInstruction::SetEntryDynamic => {
1331 let mut target = collected_results
1332 .try_pop_runtime_value()?;
1333 let value = collected_results
1334 .try_pop_value_container(&mut state)?;
1335 let key = collected_results
1336 .try_pop_value_container(&mut state)?;
1337
1338 let source_id = state.source_id_cloned();
1339
1340 let value_container = target.as_value_container_mut(&mut state.stack)?;
1341
1342 let _res = try_set_property(
1343 value_container,
1344 key,
1345 value,
1346 vec![], source_id,
1348 state.runtime.shared_references_cache_refcell()
1349 )?;
1350 None.into()
1351 }
1352
1353 RegularInstruction::MoveWithValue(move_with_value) => {
1354 let address = state.normalize_pointer_address(&PointerAddress::SelfOwned(move_with_value.previous_address));
1355
1356 if state.caller_metadata.endpoint.is_local_or_equals_endpoint(state.runtime.endpoint()) &&
1358 state
1359 .shared_value_cache
1360 .has_address_with_ownership(&address, SharedContainerOwnership::Owned) {
1361 let container = resolve_cache_value(
1362 &mut state,
1363 &address,
1364 SharedContainerOwnership::Owned,
1365 )?;
1366 Some(RuntimeValue::ValueContainer(ValueContainer::Shared(container))).into()
1367 }
1368 else {
1370 let value = collected_results.try_pop_runtime_value()?.into_value_container(&mut state)?;
1371 let container = SharedContainer::new_owned_with_inferred_allowed_type(
1372 value,
1373 move_with_value.mutability,
1374 state.runtime.pointer_address_provider_mut().deref_mut(),
1375 );
1376 Some(RuntimeValue::ValueContainer(ValueContainer::Shared(container))).into()
1380 }
1381 }
1382
1383 RegularInstruction::RemoteExecution(
1384 exec_block_data,
1385 ) => {
1386 let receivers = collected_results
1387 .try_pop_value_container(&mut state)?;
1388
1389 let receivers_list: Vec<Endpoint> = match receivers {
1391 ValueContainer::Local(Value::Core(CoreValueWithClassification { inner: CoreValue::Endpoint(endpoint), .. })) => vec![endpoint],
1392 _ => return yield Err(ExecutionError::value_error(ValueError::InvalidOperation))
1394 };
1395
1396 let injected_values = state.stack.resolve_injected_values(&exec_block_data.injected_values)?;
1397
1398 let DXBWithSharedValues {
1400 dxb: buffer,
1401 shared_values: shared_containers,
1402 } = {
1403 let lookup = state.runtime.pointer_availability_lookup();
1404 let compile_input = CompileInput::new(
1405 &lookup,
1406 &receivers_list,
1407 );
1408
1409 let mut cache = state.runtime.shared_references_cache_mut();
1410
1411 compile_injected_values(
1412 exec_block_data,
1413 injected_values,
1414 compile_input,
1415 cache.deref_mut(),
1416 ).map_err(|_e| ExecutionError::invalid_program(InvalidProgramError::ExpectedValue))?
1417 };
1418
1419 interrupt_with_maybe_value!(
1420 interrupt_provider,
1421 ExecutionInterrupt::External(
1422 ExternalExecutionInterrupt::RemoteExecution {
1423 input: DXBWithSharedValues {
1424 dxb: buffer,
1425 shared_values: shared_containers,
1426 },
1427 receivers: receivers_list,
1428 }
1429 )
1430 )
1431 .map(RuntimeValue::ValueContainer)
1432 .into()
1433 }
1434
1435 RegularInstruction::Apply(ApplyData { .. }) => {
1436 let mut args = collected_results.try_collect_runtime_values()?;
1437 let callee = args.remove(args.len() - 1);
1439
1440 if let RuntimeValue::ValueContainer(ValueContainer::Local(Value::Core(CoreValueWithClassification { inner: CoreValue::Callable(Callable { body: CallableBody::CoreStub(CoreStub::Panic), .. }), .. }))) = &callee
1442 {
1443 let error = args
1445 .remove(0)
1446 .into_value_container(&mut state)?
1447 .try_into_value::<String>()
1448 .map_err(|_| ExecutionError::InvalidProgram(Box::new(InvalidProgramError::InvalidType)))?;
1449 return yield Err(ExecutionError::Unspecified(error));
1450 }
1451
1452 let (callee, _callee_stack_index) = callee.into_value_container_with_previous_stack_index(&mut state)?;
1453 let (args, borrowed_args_stack_indices) = state.stack.take_runtime_values_with_stack_indices(args)?;
1454
1455 let (result, borrowed_args) = interrupt_with_borrowed_args_and_maybe_result!(
1456 interrupt_provider,
1457 ExecutionInterrupt::External(
1458 ExternalExecutionInterrupt::Apply(
1459 callee,
1460 into_apply_arguments_with_stack_indices(
1461 args,
1462 &borrowed_args_stack_indices,
1463 )
1464 )
1465 )
1466 );
1467
1468 state.stack.restore_stack_values(borrowed_args, borrowed_args_stack_indices)?;
1470
1471
1472 result.map(|val| {
1473 RuntimeValue::ValueContainer(val)
1474 })
1475 .into()
1476 }
1477 RegularInstruction::JumpIfFalse(JumpData { offset }) => {
1478 let condition_value = collected_results.try_pop_runtime_value()?;
1479 let condition_value = condition_value.as_value_container(&state.stack)?;
1480 if condition_value.try_as::<Boolean>().ok_or_else(|| ExecutionError::InvalidTypeCast)?.is_false() {
1482 seek_request.borrow_mut().replace(offset);
1483 }
1484 CollectedExecutionResult::value(None)
1485 }
1486
1487 RegularInstruction::CallMethod(CallMethodData {method_name, ..}) => {
1488 let method_name = method_name.0;
1489
1490 let callee = collected_results.try_pop_runtime_value()?;
1491 let args = collected_results.try_collect_runtime_values()?;
1492
1493 let (callee, callee_stack_index) = callee.into_value_container_with_previous_stack_index(&mut state)?;
1494 let (args, borrowed_args_stack_indices) = state.stack.take_runtime_values_with_stack_indices(args)?;
1495
1496 let (val, borrowed_args) = interrupt_with_borrowed_args_and_maybe_result!(
1497 interrupt_provider,
1498 ExecutionInterrupt::External(
1499 ExternalExecutionInterrupt::CallMethod(
1500 ApplyArgument {
1501 value: callee,
1502 passed_as_ref: callee_stack_index.is_some(),
1503 },
1504 method_name,
1505 into_apply_arguments_with_stack_indices(
1506 args,
1507 &borrowed_args_stack_indices,
1508 )
1509 )
1510 )
1511 );
1512
1513 let mut borrowed_args_iter = borrowed_args.into_iter();
1514
1515 if let Some(callee_stack_index) = callee_stack_index {
1517 let borrowed_callee = borrowed_args_iter.next().unwrap();
1518 state.stack.set_stack_value(callee_stack_index, borrowed_callee)?;
1519 }
1520
1521 let borrowed_args = borrowed_args_iter.collect::<Vec<_>>();
1522
1523 state.stack.restore_stack_values(borrowed_args, borrowed_args_stack_indices)?;
1525
1526
1527 val.map(|val| {
1528 RuntimeValue::ValueContainer(val)
1529 })
1530 .into()
1531 }
1532
1533 RegularInstruction::UnboundedStatementsEnd(
1534 UnboundedStatementsData { terminated },
1535 ) => {
1536 let result = collector.try_pop_unbounded()
1537 .ok_or(ExecutionError::dxb_parser_error(DXBParserError::NotInUnboundedRegularScopeError))?;
1538 if let FullOrPartialResult::Partial {
1539 result: collected_result,
1540 previous_stack_index,
1541 ..
1542 } = result
1543 {
1544 state.stack.truncate(previous_stack_index);
1546 if terminated {
1547 CollectedExecutionResult::value(
1548 None,
1549 )
1550 } else {
1551 match collected_result {
1552 Some(CollectedExecutionResult::Value(val)) => (*val).into(),
1553 None => {
1554 let active_value = interrupt_with_maybe_value!(interrupt_provider, ExecutionInterrupt::TakeActiveValue);
1556 CollectedExecutionResult::value(active_value.map(RuntimeValue::ValueContainer))
1557 }
1558 _ => unreachable!(),
1559 }
1560 }
1561 } else {
1562 unreachable!()
1563 }
1564 }
1565
1566 RegularInstruction::SharedRefWithValue(shared_ref) => {
1567 let address = state.normalize_pointer_address(&PointerAddress::SelfOwned(shared_ref.address.clone()));
1568
1569 let value = collected_results
1570 .try_pop_runtime_value()?
1571 .into_value_container(&mut state)?;
1572
1573 let referenced_container = if state.caller_metadata.endpoint.is_local_or_equals_endpoint(state.runtime.endpoint()) {
1575 let cache_result = resolve_cache_value(
1576 &mut state,
1577 &address,
1578 SharedContainerOwnership::Referenced(shared_ref.ref_mutability),
1579 );
1580 match cache_result {
1581 Ok(container) => match container {
1583 SharedContainer::Referenced(referenced_container) => referenced_container,
1584 SharedContainer::Owned(_) => {
1585 unreachable!()
1586 }
1587 },
1588 Err(_) => {
1589 create_new_reference_from_value(
1590 &address,
1591 &state.runtime,
1592 value,
1593 shared_ref.container_mutability,
1594 shared_ref.ref_mutability,
1595 shared_ref.is_debug,
1596 )?
1597 }
1598 }
1599 }
1600 else {
1602 let pointer_address = PointerAddress::Remote(RemotePointerAddress::for_endpoint(&state.caller_metadata.endpoint, &shared_ref.address));
1603 create_new_reference_from_value(
1604 &pointer_address,
1605 &state.runtime,
1606 value,
1607 shared_ref.container_mutability,
1608 shared_ref.ref_mutability,
1609 shared_ref.is_debug,
1610 )?
1611 };
1612
1613 let container = SharedContainer::Referenced(referenced_container);
1614 CollectedExecutionResult::value(Some(ValueContainer::Shared(container).into()))
1615 }
1616
1617 e => {
1618 todo!(
1619 "Unhandled collected regular instruction: {:?}",
1620 e
1621 );
1622 }
1623 },
1624
1625 Instruction::Type(type_instruction) => {
1626 match type_instruction {
1627 TypeInstruction::TaggedType(tagged_type_data) => {
1628 if tagged_type_data.has_type {
1629 let def = collected_results.pop_type();
1630 TypeDefinition::TaggedType(TaggedTypeDefinition::new(
1631 def,
1632 tagged_type_data.tag.0
1633 )).into()
1634 } else {
1635 TypeDefinition::TaggedType(TaggedTypeDefinition::new_without_type(
1636 tagged_type_data.tag.0
1637 )).into()
1638 }
1639 }
1640 TypeInstruction::Range => {
1641 let type_end =
1642 collected_results.pop_type();
1643 let type_start =
1644 collected_results.pop_type();
1645 let x = Type::Definition(
1646 TypeDefinition::Range(RangeTypeDefinition {
1647 start: Box::new(type_start),
1648 end: Box::new(type_end),
1649 }).into(),
1650 );
1651 x.into()
1652 }
1653 TypeInstruction::DefinitionWithMetadata(metadata) => {
1654 let definition = collected_results.pop_type_definition();
1655 Type::Definition(TypeDefinitionWithMetadata::new(definition, metadata)).into()
1656 }
1657 TypeInstruction::Map(MapData { element_count, ..}) => {
1658 let mut map_entries = Vec::with_capacity(element_count as usize);
1659 for _ in 0..element_count {
1660 let value_type = collected_results.pop_type();
1661 let key_type = collected_results.pop_type();
1662 map_entries.push((key_type, value_type));
1663 }
1664 TypeDefinition::Map(MapTypeDefinition(map_entries.into_iter().rev().collect())).into()
1665 }
1666 TypeInstruction::Union(UnionData {element_count}) => {
1667 let mut union_entries = Vec::with_capacity(element_count as usize);
1668 for _ in 0..element_count {
1669 let ty = collected_results.pop_type();
1670 union_entries.push(ty);
1671 }
1672 TypeDefinition::Union(UnionTypeDefinition(union_entries.into_iter().rev().collect())).into()
1673 }
1674 TypeInstruction::Intersection(IntersectionData {element_count}) => {
1675 let mut intersection_entries = Vec::with_capacity(element_count as usize);
1676 for _ in 0..element_count {
1677 let ty = collected_results.pop_type();
1678 intersection_entries.push(ty);
1679 }
1680 TypeDefinition::Intersection(IntersectionTypeDefinition(intersection_entries.into_iter().rev().collect())).into()
1681 }
1682 TypeInstruction::ListSliceCollection(ListSliceCollectionData { element_count }) => {
1683 let ty = collected_results.pop_type();
1684 TypeDefinition::Collection(CollectionTypeDefinition::ListSlice(
1685 ListSliceCollectionTypeDefinition::new(ty, element_count as usize)
1686 )).into()
1687 }
1688 TypeInstruction::MapCollection => {
1689 let value_type = collected_results.pop_type();
1690 let key_type = collected_results.pop_type();
1691 TypeDefinition::Collection(CollectionTypeDefinition::Map(
1692 MapCollectionTypeDefinition::new(key_type, value_type)
1693 )).into()
1694 }
1695 TypeInstruction::ListCollection => {
1696 let ty = collected_results.pop_type();
1697 TypeDefinition::Collection(CollectionTypeDefinition::List(
1698 ListCollectionTypeDefinition::new(ty)
1699 )).into()
1700 }
1701 TypeInstruction::Sender => {
1702 let ty = collected_results.pop_type();
1703 TypeDefinition::Collection(CollectionTypeDefinition::Sender(
1704 SenderTypeDefinition::new(ty)
1705 )).into()
1706 }
1707 TypeInstruction::Receiver => {
1708 let ty = collected_results.pop_type();
1709 TypeDefinition::Collection(CollectionTypeDefinition::Receiver(
1710 ReceiverTypeDefinition::new(ty)
1711 )).into()
1712 }
1713 TypeInstruction::Boxed => {
1714 let ty = collected_results.pop_type();
1715 TypeDefinition::Box(Box::new(ty)).into()
1716 }
1717 TypeInstruction::Callable(signature_data) => {
1718 let callable_type = resolve_callable_type_definition(
1719 collected_results.pop_types(signature_data.total_type_count()),
1720 &signature_data,
1721 );
1722 TypeDefinition::Callable(callable_type).into()
1723 }
1724 TypeInstruction::EntityType => {
1725 let shared_container = collected_results.try_pop_value_container(&mut state)?;
1726 let shared_container = match shared_container {
1727 ValueContainer::Shared(shared) => shared,
1728 _ => return yield Err(ExecutionError::ExpectedSharedValue),
1729 };
1730 let entity_type = EntityType::try_from(shared_container).map_err(|_| ExecutionError::InvalidSharedValueType)?;
1731 Type::Entity(entity_type).into()
1732 },
1733 e => todo!(
1734 "Unhandled collected type instruction: {:?}",
1735 e
1736 ),
1737 }
1738 }
1739 }
1740 }
1741 FullOrPartialResult::Partial {
1742 instruction,
1743 result: collected_result,
1744 previous_stack_index,
1745 } => {
1746 state.stack.truncate(previous_stack_index);
1748
1749 match instruction {
1750 Instruction::Regular(regular_instruction) => {
1751 match regular_instruction {
1752 RegularInstruction::ShortStatements(
1753 ShortStatementsData {
1754 terminated, ..
1755 },
1756 )
1757 | RegularInstruction::Statements(
1758 StatementsData { terminated, .. },
1759 ) => {
1760 if terminated {
1761 CollectedExecutionResult::value(
1762 None,
1763 )
1764 } else {
1765 match collected_result {
1766 Some(
1767 CollectedExecutionResult::Value(
1768 val,
1769 ),
1770 ) => (*val).into(),
1771 None => {
1772 CollectedExecutionResult::value(
1773 None,
1774 )
1775 }
1776 _ => unreachable!(), }
1778 }
1779 }
1780 _ => unreachable!(),
1781 }
1782 }
1783
1784 Instruction::Type(_data) => unreachable!(),
1785 }
1786 }
1787 }
1788 };
1789
1790 let expr: CollectedExecutionResult = match expr_result {
1791 Ok(expr) => expr,
1792 Err(error) => return yield Err(error),
1793 };
1794
1795 collector.push_result(expr);
1798 }
1799
1800 if let Some(ResultCollector::LastUnbounded(
1802 LastUnboundedResultCollector { last_result, .. },
1803 )) = collector.last_mut()
1804 && let Some(CollectedExecutionResult::Value(mut last_result)) =
1805 last_result.take()
1806 {
1807 let active_value_result: Result<_, ExecutionError> = try {
1808 last_result
1809 .take()
1810 .map(|v| v.into_value_container(&mut state))
1811 .transpose()?
1812 };
1813
1814 let active_value = match active_value_result {
1815 Ok(value) => value,
1816 Err(error) => return yield Err(error),
1817 };
1818
1819 interrupt!(
1820 interrupt_provider,
1821 ExecutionInterrupt::SetActiveValue(active_value)
1822 );
1823
1824 }
1826 }
1827
1828 if let Some(result) = collector.take_root_result() {
1829 let root_result: Result<_, ExecutionError> = try {
1830 match result {
1831 CollectedExecutionResult::Value(value) => value
1832 .map(|v| v.into_value_container(&mut state))
1833 .transpose()?,
1834 _ => unreachable!("Expected root result"),
1835 }
1836 };
1837
1838 let root_result = match root_result {
1839 Ok(value) => value,
1840 Err(error) => return yield Err(error),
1841 };
1842
1843 yield Ok(ExecutionInterrupt::External(
1844 ExternalExecutionInterrupt::Result(root_result),
1845 ));
1846 } else {
1847 panic!("Execution finished without root result");
1848 }
1849}
1850
1851fn resolve_callable_type_definition(
1852 mut types: Vec<Type>,
1853 signature_data: &CallableSignatureData,
1854) -> CallableTypeDefinition {
1855 let yeet_type = if signature_data.has_yeet_type {
1856 Some(Box::new(types.pop().expect("Expected yeet type")))
1857 } else {
1858 None
1859 };
1860 let return_type = if signature_data.has_return_type {
1861 Some(Box::new(types.pop().expect("Expected return type")))
1862 } else {
1863 None
1864 };
1865
1866 let rest_parameter = if signature_data.has_rest_parameter {
1867 Some((
1868 signature_data
1869 .rest_parameter_name
1870 .as_ref()
1871 .map(|name| name.0.clone()),
1872 Box::new(types.pop().expect("Expected rest parameter type")),
1873 ))
1874 } else {
1875 None
1876 };
1877
1878 let parameters = signature_data
1879 .parameter_names
1880 .iter()
1881 .zip(types)
1882 .map(|(name, param_type)| (Some(name.0.clone()), param_type))
1883 .collect::<Vec<_>>();
1884
1885 CallableTypeDefinition {
1886 kind: signature_data.kind,
1887 requires_async: signature_data.requires_async,
1888 parameters,
1889 rest_parameter,
1890 return_type,
1891 yeet_type,
1892 }
1893}
1894
1895fn create_new_reference_from_value(
1898 pointer_address: &PointerAddress,
1899 runtime: &Runtime,
1900 value: ValueContainer,
1901 container_mutability: SharedContainerMutability,
1902 ref_mutability: ReferenceMutability,
1903 is_debug: bool,
1904) -> Result<ReferencedSharedContainer, ExecutionError> {
1905 let memory = &mut runtime.shared_references_cache_refcell().borrow_mut();
1906
1907 if let Some(reference) = memory.get_reference(pointer_address) {
1908 reference.mark_debug(is_debug);
1909 return Ok(reference.clone());
1910 }
1911 match pointer_address {
1912 PointerAddress::SelfOwned(_) => {
1914 Err(CacheValueRetrievalError::ValueNotFoundInCache(
1915 ValueNotFoundInCacheError(pointer_address.clone()),
1916 )
1917 .into())
1918 }
1919 PointerAddress::Remote(remote_address) => {
1920 let base = BaseSharedValueContainer::try_new(
1921 value,
1922 TypeDefinition::CoreType(CoreLibBaseTypeId::Any.into()),
1923 container_mutability,
1924 )?;
1925
1926 let reference = unsafe {
1928 ReferencedSharedContainer::try_new_remote_from_base_container(
1929 base,
1930 remote_address.clone(),
1931 ref_mutability,
1932 )
1933 }
1934 .map_err(|_err| ExecutionError::InvalidSharedValueType)?;
1935
1936 memory.register_remote_shared_container(&reference);
1939 runtime.internal().sync_value_with_owner(
1941 &SharedContainer::Referenced(reference.clone()),
1942 )?;
1943
1944 reference.mark_debug(is_debug);
1945
1946 Ok(reference)
1947 }
1948 }
1949}
1950
1951fn resolve_cache_value(
1953 state: &mut RuntimeExecutionState,
1954 pointer_address: &PointerAddress,
1955 ownership: SharedContainerOwnership,
1956) -> Result<SharedContainer, ExecutionError> {
1957 if let Ok(val) =
1959 resolve_execution_cache_value(state, pointer_address, ownership)
1960 {
1961 Ok(val)
1962 }
1963 else {
1965 if let Some(reference) = state
1966 .runtime
1967 .shared_references_cache_refcell()
1968 .borrow()
1969 .get_reference(pointer_address)
1970 {
1971 Ok(SharedContainer::Referenced(reference))
1972 } else {
1973 Err(ExecutionError::cache_value_retrieval_error(
1974 CacheValueRetrievalError::ValueNotFoundInCache(
1975 ValueNotFoundInCacheError(pointer_address.clone()),
1976 ),
1977 ))
1978 }
1979 }
1980}
1981
1982fn resolve_execution_cache_value(
1983 state: &mut RuntimeExecutionState,
1984 pointer_address: &PointerAddress,
1985 ownership: SharedContainerOwnership,
1986) -> Result<SharedContainer, ExecutionError> {
1987 state
1989 .shared_value_cache
1990 .try_get_shared_container_with_ownership(pointer_address, ownership)
1991 .map_err(ExecutionError::cache_value_retrieval_error)
1992}