datex_core/runtime/execution/execution_loop/mod.rs
1//! This module contains the implementation of the execution loop that drives the execution of the compiled DATEX bytecode (DXB).
2//! It handles the execution of instructions, manages the runtime state, and processes interrupts that can occur during execution.
3mod internal_slots;
4pub mod interrupts;
5mod operations;
6mod runtime_value;
7pub mod state;
8
9use crate::{
10 core_compiler::{
11 core_compilation_context::{CompileInput, DXBWithSharedValues},
12 injected_values::compile_injected_values,
13 },
14 dxb_parser::{
15 body::{DXBParserError, iterate_instructions},
16 instruction_collector::{
17 CollectedResults, CollectionResultsPopper, FullOrPartialResult,
18 InstructionCollector, LastUnboundedResultCollector,
19 ResultCollector, StatementResultCollectionStrategy,
20 },
21 },
22 global::{
23 operators::{BinaryOperator, ComparisonOperator, UnaryOperator},
24 protocol_structures::{
25 instruction_data::{
26 ApplyData, Float32Data, Float64Data, FloatAsInt16Data,
27 FloatAsInt32Data, ModifyStackValue, ShortStatementsData,
28 ShortTextData, StatementsData, TaggedValue, TextData,
29 UnboundedStatementsData,
30 },
31 instructions::{Instruction, NestedInstructionResolutionStrategy},
32 regular_instructions::RegularInstruction,
33 type_instructions::TypeInstruction,
34 },
35 },
36 libs::core::type_id::CoreLibBaseTypeId,
37 prelude::*,
38 runtime::execution::{
39 ExecutionError, InvalidProgramError,
40 execution_loop::{
41 internal_slots::{get_root_property, get_stack_value},
42 interrupts::{
43 ExecutionInterrupt, ExternalExecutionInterrupt,
44 InterruptProvider,
45 },
46 operations::{
47 handle_assignment_operation, handle_binary_operation,
48 handle_comparison_operation, handle_unary_operation,
49 set_property,
50 },
51 runtime_value::RuntimeValue,
52 state::RuntimeExecutionState,
53 },
54 macros::{
55 interrupt, interrupt_with_maybe_value, interrupt_with_value,
56 interrupt_with_values, yield_unwrap,
57 },
58 },
59 shared_values::{
60 OwnedSharedContainer, PointerAddress, ReferenceMutability,
61 ReferencedSharedContainer, RemotePointerAddress,
62 SelfOwnedSharedContainer, SharedContainer, SharedContainerMutability,
63 SharedContainerOwnership,
64 base_shared_value_container::{
65 BaseSharedValueContainer, observers::TransceiverId,
66 },
67 },
68 types::{
69 r#type::Type,
70 type_definition::{
71 TypeDefinition, impl_type::ImplTypeDefinition,
72 range::RangeTypeDefinition, tagged_type::TaggedTypeDefinition,
73 },
74 type_definition_with_metadata::TypeDefinitionWithMetadata,
75 },
76 value_updates::{
77 update_data::{DeleteEntryUpdateData, ReplaceUpdateData},
78 update_handler::UpdateHandler,
79 },
80 values::{
81 core_value::CoreValue,
82 core_values::{
83 callable::{Callable, CallableBody, CoreStub},
84 decimal::{Decimal, typed_decimal::TypedDecimal},
85 endpoint::Endpoint,
86 integer::typed_integer::TypedInteger,
87 list::List,
88 map::{Map, MapKey},
89 },
90 value::Value,
91 value_container::{
92 ValueContainer, error::ValueError, value_key::ValueKey,
93 },
94 },
95};
96use alloc::rc::Rc;
97use core::cell::RefCell;
98
99#[derive(Debug)]
100enum CollectedExecutionResult {
101 /// contains an optional runtime value that is intercepted by the consumer of a value or passed as the final result at the end of execution
102 Value(Option<RuntimeValue>),
103 /// contains a [Type] that is intercepted by a consumer of a type value
104 Type(Type),
105 TypeDefinition(TypeDefinition),
106 /// contains a key-value pair that is intercepted by a map construction operation
107 KeyValuePair((MapKey, ValueContainer)),
108}
109
110impl From<Option<RuntimeValue>> for CollectedExecutionResult {
111 fn from(value: Option<RuntimeValue>) -> Self {
112 CollectedExecutionResult::Value(value)
113 }
114}
115impl From<RuntimeValue> for CollectedExecutionResult {
116 fn from(value: RuntimeValue) -> Self {
117 CollectedExecutionResult::Value(Some(value))
118 }
119}
120impl From<Type> for CollectedExecutionResult {
121 fn from(value: Type) -> Self {
122 CollectedExecutionResult::Type(value)
123 }
124}
125
126impl From<TypeDefinition> for CollectedExecutionResult {
127 fn from(value: TypeDefinition) -> Self {
128 CollectedExecutionResult::TypeDefinition(value)
129 }
130}
131
132impl From<(MapKey, ValueContainer)> for CollectedExecutionResult {
133 fn from(value: (MapKey, ValueContainer)) -> Self {
134 CollectedExecutionResult::KeyValuePair(value)
135 }
136}
137
138impl
139 CollectionResultsPopper<
140 CollectedExecutionResult,
141 Option<RuntimeValue>,
142 MapKey,
143 ValueContainer,
144 Type,
145 TypeDefinition,
146 > for CollectedResults<CollectedExecutionResult>
147{
148 fn try_extract_type_definition_result(
149 result: CollectedExecutionResult,
150 ) -> Option<TypeDefinition> {
151 match result {
152 CollectedExecutionResult::TypeDefinition(ty) => Some(ty),
153 _ => None,
154 }
155 }
156 fn try_extract_value_result(
157 result: CollectedExecutionResult,
158 ) -> Option<Option<RuntimeValue>> {
159 match result {
160 CollectedExecutionResult::Value(val) => Some(val),
161 _ => None,
162 }
163 }
164
165 fn try_extract_type_result(
166 result: CollectedExecutionResult,
167 ) -> Option<Type> {
168 match result {
169 CollectedExecutionResult::Type(ty) => Some(ty),
170 _ => None,
171 }
172 }
173
174 fn try_extract_key_value_pair_result(
175 result: CollectedExecutionResult,
176 ) -> Option<(MapKey, ValueContainer)> {
177 match result {
178 CollectedExecutionResult::KeyValuePair((key, value)) => {
179 Some((key, value))
180 }
181 _ => None,
182 }
183 }
184}
185
186impl CollectedResults<CollectedExecutionResult> {
187 fn collect_value_container_results_assert_existing(
188 mut self,
189 state: &RuntimeExecutionState,
190 ) -> Result<Vec<ValueContainer>, ExecutionError> {
191 let count = self.len();
192 let mut expressions = Vec::with_capacity(count);
193 for _ in 0..count {
194 expressions.push(
195 self.pop_potentially_cloned_value_container_result_assert_existing(state)?,
196 );
197 }
198 expressions.reverse();
199 Ok(expressions)
200 }
201
202 /// Pops a runtime value result, returning an error if none exists
203 fn pop_runtime_value_result_assert_existing(
204 &mut self,
205 ) -> Result<RuntimeValue, ExecutionError> {
206 self.pop_value_result()
207 .ok_or(ExecutionError::InvalidProgram(
208 InvalidProgramError::ExpectedValue,
209 ))
210 }
211
212 /// Pops a value container result, returning an error if none exists.
213 /// If the value is a slot address, it is resolved to a cloned value container.
214 /// Do not use this method if you want to work on the actual value without cloning it.
215 fn pop_potentially_cloned_value_container_result_assert_existing(
216 &mut self,
217 state: &RuntimeExecutionState,
218 ) -> Result<ValueContainer, ExecutionError> {
219 self.pop_runtime_value_result_assert_existing()?
220 .into_potentially_cloned_value_container(state)
221 }
222
223 fn collect_key_value_pair_results_assert_existing(
224 mut self,
225 ) -> Result<Vec<(MapKey, ValueContainer)>, ExecutionError> {
226 let count = self.len();
227 let mut pairs = Vec::with_capacity(count);
228 for _ in 0..count {
229 let (key, value) = self.pop_key_value_pair_result();
230 pairs.push((key, value));
231 }
232 pairs.reverse();
233 Ok(pairs)
234 }
235}
236
237/// Main execution loop that drives the execution of the DXB body
238/// The interrupt_provider is used to provide results for synchronous or asynchronous I/O operations
239pub fn execution_loop(
240 state: RuntimeExecutionState,
241 dxb_body: Rc<RefCell<Vec<u8>>>,
242 interrupt_provider: InterruptProvider,
243) -> impl Iterator<Item = Result<ExternalExecutionInterrupt, ExecutionError>> {
244 gen move {
245 let mut active_value: Option<ValueContainer> = None;
246
247 for interrupt in
248 inner_execution_loop(dxb_body, interrupt_provider.clone(), state)
249 {
250 match interrupt {
251 Ok(interrupt) => match interrupt {
252 ExecutionInterrupt::External(external_interrupt) => {
253 yield Ok(external_interrupt);
254 }
255 ExecutionInterrupt::SetActiveValue(value) => {
256 active_value = value;
257 }
258 },
259 Err(err) => {
260 match err {
261 ExecutionError::DXBParserError(
262 DXBParserError::ExpectingMoreInstructions,
263 ) => {
264 yield Err(
265 ExecutionError::IntermediateResultWithState(
266 active_value.take(),
267 None,
268 ),
269 );
270 // assume that when continuing after this yield, more instructions will have been loaded
271 // so we run the loop again to try to get the next instruction
272 continue;
273 }
274 _ => {
275 yield Err(err);
276 }
277 }
278 }
279 }
280 }
281 }
282}
283
284pub fn inner_execution_loop(
285 dxb_body: Rc<RefCell<Vec<u8>>>,
286 interrupt_provider: InterruptProvider,
287 mut state: RuntimeExecutionState,
288) -> impl Iterator<Item = Result<ExecutionInterrupt, ExecutionError>> {
289 gen move {
290 let mut collector =
291 InstructionCollector::<CollectedExecutionResult>::default();
292
293 for instruction_result in iterate_instructions(
294 dxb_body,
295 NestedInstructionResolutionStrategy::None,
296 ) {
297 let instruction = match instruction_result {
298 Ok(instruction) => instruction,
299 Err(DXBParserError::ExpectingMoreInstructions) => {
300 yield Err(DXBParserError::ExpectingMoreInstructions.into());
301 // assume that when continuing after this yield, more instructions will have been loaded
302 // so we run the loop again to try to get the next instruction
303 continue;
304 }
305 Err(err) => {
306 return yield Err(err.into());
307 }
308 };
309
310 let result = match instruction {
311 // handle regular instructions
312 Instruction::Regular(regular_instruction) => {
313 let regular_instruction = collector
314 .default_regular_instruction_collection(
315 regular_instruction,
316 StatementResultCollectionStrategy::Last,
317 state.stack.current_index(),
318 );
319
320 let expr: Option<Option<RuntimeValue>> = if let Some(
321 regular_instruction,
322 ) =
323 regular_instruction
324 {
325 Some(match regular_instruction {
326 // boolean
327 RegularInstruction::True => Some(ValueContainer::from(true).into()),
328 RegularInstruction::False => Some(ValueContainer::from(false).into()),
329
330 // integers
331 RegularInstruction::Int8(integer) => {
332 Some(ValueContainer::from(TypedInteger::from(integer.0)).into())
333 }
334 RegularInstruction::Int16(integer) => {
335 Some(ValueContainer::from(TypedInteger::from(integer.0)).into())
336 }
337 RegularInstruction::Int32(integer) => {
338 Some(ValueContainer::from(TypedInteger::from(integer.0)).into())
339 }
340 RegularInstruction::Int64(integer) => {
341 Some(ValueContainer::from(TypedInteger::from(integer.0)).into())
342 }
343 RegularInstruction::Int128(integer) => {
344 Some(ValueContainer::from(TypedInteger::from(integer.0)).into())
345 }
346
347 // unsigned integers
348 RegularInstruction::UInt8(integer) => {
349 Some(ValueContainer::from(TypedInteger::from(integer.0)).into())
350 }
351 RegularInstruction::UInt16(integer) => {
352 Some(ValueContainer::from(TypedInteger::from(integer.0)).into())
353 }
354 RegularInstruction::UInt32(integer) => {
355 Some(ValueContainer::from(TypedInteger::from(integer.0)).into())
356 }
357 RegularInstruction::UInt64(integer) => {
358 Some(ValueContainer::from(TypedInteger::from(integer.0)).into())
359 }
360 RegularInstruction::UInt128(integer) => {
361 Some(ValueContainer::from(TypedInteger::from(integer.0)).into())
362 }
363
364 // big integers
365 RegularInstruction::BigInteger(integer) => {
366 Some(ValueContainer::from(TypedInteger::IBig(integer)).into())
367 }
368
369 // default integer
370 RegularInstruction::Integer(integer) => {
371 Some(ValueContainer::from(integer).into())
372 }
373
374 // specific floats
375 RegularInstruction::DecimalF32(Float32Data(f32)) => {
376 Some(ValueContainer::from(TypedDecimal::from(f32)).into())
377 }
378 RegularInstruction::DecimalF64(Float64Data(f64)) => {
379 Some(ValueContainer::from(TypedDecimal::from(f64)).into())
380 }
381 // big decimal
382 RegularInstruction::BigDecimal(big_decimal) => {
383 Some(ValueContainer::from(TypedDecimal::Decimal(big_decimal)).into())
384 }
385
386 // default decimals
387 RegularInstruction::DecimalAsInt16(FloatAsInt16Data(i16)) => {
388 Some(ValueContainer::from(Decimal::from(i16 as f32)).into())
389 }
390 RegularInstruction::DecimalAsInt32(FloatAsInt32Data(i32)) => {
391 Some(ValueContainer::from(Decimal::from(i32 as f32)).into())
392 }
393 RegularInstruction::Decimal(big_decimal) => {
394 Some(ValueContainer::from(big_decimal).into())
395 }
396
397 // endpoint
398 RegularInstruction::Endpoint(endpoint) => Some(ValueContainer::from(endpoint).into()),
399
400 // null
401 RegularInstruction::Null => Some(ValueContainer::from(Value::null()).into()),
402
403 // text
404 RegularInstruction::ShortText(ShortTextData(text)) => {
405 Some(ValueContainer::from(text).into())
406 }
407 RegularInstruction::Text(TextData(text)) => Some(ValueContainer::from(text).into()),
408
409 RegularInstruction::RequestRemoteSharedRef(address) => Some(interrupt_with_value!(
410 interrupt_provider,
411 ExecutionInterrupt::External(
412 ExternalExecutionInterrupt::GetReferenceToRemotePointer(address, ReferenceMutability::Immutable)
413 )
414 ).into()),
415
416
417 RegularInstruction::RequestRemoteSharedRefMut(address) => Some(interrupt_with_value!(
418 interrupt_provider,
419 ExecutionInterrupt::External(
420 ExternalExecutionInterrupt::GetReferenceToRemotePointer(address, ReferenceMutability::Mutable)
421 )
422 ).into()),
423
424 RegularInstruction::GetLocalSharedRef(address) => {
425 let val = interrupt_with_maybe_value!(
426 interrupt_provider,
427 ExecutionInterrupt::External(
428 ExternalExecutionInterrupt::GetReferenceToLocalPointer(
429 address
430 )
431 )
432 );
433 if let Some(val) = val {
434 Some(val.into())
435 }
436 else {
437 return yield Err(ExecutionError::ReferenceNotFound);
438 }
439 }
440
441
442 RegularInstruction::GetCoreLibValue(id) => {
443 Some(interrupt_with_value!(
444 interrupt_provider,
445 ExecutionInterrupt::External(
446 ExternalExecutionInterrupt::GetCoreLibValue(
447 yield_unwrap!(
448 id.try_into().map_err(|_| ExecutionError::InvalidProgram(InvalidProgramError::InvalidCoreLibId(id)))
449 )
450 )
451 )
452 ).into())
453 }
454
455 RegularInstruction::GetRootProperty(stack_index) => {
456 Some(RuntimeValue::ValueContainer(yield_unwrap!(
457 get_root_property(
458 &state,
459 stack_index,
460 )
461 )))
462 }
463
464 // TODO: still needed?
465 RegularInstruction::BorrowStackValue(index) => {
466 Some(RuntimeValue::StackValue(index))
467 }
468
469 RegularInstruction::GetStackValueSharedRef(index) => {
470 let value = yield_unwrap!(state.stack.get_stack_value(index));
471 match value {
472 ValueContainer::Shared(container) => Some(RuntimeValue::ValueContainer(
473 ValueContainer::Shared(SharedContainer::Referenced(container.derive_immutable_reference()))
474 )),
475 _ => return yield Err(ExecutionError::ExpectedSharedValue)
476 }
477 }
478 RegularInstruction::GetStackValueSharedRefMut(index) => {
479 let value = yield_unwrap!(state.stack.get_stack_value(index));
480 match value {
481 ValueContainer::Shared(container) => Some(RuntimeValue::ValueContainer(
482 ValueContainer::Shared(SharedContainer::Referenced(
483 yield_unwrap!(
484 container
485 .try_derive_mutable_reference()
486 .map_err(|_| ExecutionError::MutableReferenceToNonMutableValue)
487 )
488 ))
489 )),
490 _ => return yield Err(ExecutionError::ExpectedSharedValue)
491 }
492 }
493
494 RegularInstruction::CloneStackValue(index) => {
495 let value = yield_unwrap!(state.stack.get_stack_value(index));
496 Some(RuntimeValue::ValueContainer(
497 value.get_cloned()
498 ))
499 }
500
501 RegularInstruction::TakeStackValue(index) => {
502 let val = yield_unwrap!(state.stack.take_stack_value(index));
503 Some(RuntimeValue::ValueContainer(
504 val
505 ))
506 }
507
508 RegularInstruction::PerformMoves(perform_move) => {
509 // request move not required if pointers are already local addresses (= current caller is local)
510 if state.caller_metadata.endpoint.is_local_or_equals_endpoint(state.runtime.endpoint()) {
511 let mut moved_values = Vec::with_capacity(perform_move.pointers.len());
512
513 for (_mutable_flag, address) in perform_move.pointers {
514 let container = yield_unwrap!(resolve_cache_value(
515 &mut state,
516 PointerAddress::SelfOwned(address),
517 SharedContainerOwnership::Owned,
518 ));
519 moved_values.push(ValueContainer::Shared(container));
520 }
521 Some(RuntimeValue::ValueContainer(ValueContainer::from(moved_values)))
522 }
523 else {
524 let resolved_moved_values = interrupt_with_values!(
525 interrupt_provider,
526 ExecutionInterrupt::External(
527 ExternalExecutionInterrupt::RequestMove(
528 perform_move.pointers
529 .into_iter()
530 .map(|(mutable_flag, address)|
531 (if mutable_flag != 0 {SharedContainerMutability::Mutable} else {SharedContainerMutability::Immutable}, address)
532 )
533 .collect()
534 )
535 )
536 );
537 Some(RuntimeValue::ValueContainer(ValueContainer::from(resolved_moved_values)))
538 }
539 }
540
541 RegularInstruction::Move(move_data) => {
542 let moved_values = interrupt_with_values!(
543 interrupt_provider,
544 ExecutionInterrupt::External(
545 ExternalExecutionInterrupt::Move(move_data.address_mappings)
546 )
547 );
548 Some(RuntimeValue::ValueContainer(ValueContainer::from(moved_values)))
549 }
550
551 RegularInstruction::SharedRef(shared_ref) => {
552 let endpoint = state.runtime.endpoint().clone();
553 // shared ref without value, assumes value already known, otherwise request (todo)
554 let container = yield_unwrap!(resolve_cache_value(
555 &mut state,
556 shared_ref.address.normalize(&endpoint),
557 SharedContainerOwnership::Referenced(shared_ref.ref_mutability)
558 ));
559 Some(RuntimeValue::ValueContainer(ValueContainer::Shared(container)))
560 }
561
562 RegularInstruction::TaggedValue(TaggedValue {is_empty: true, tag: ShortTextData(tag)}) => {
563 Some(RuntimeValue::ValueContainer(ValueContainer::Local(Value {
564 inner: CoreValue::Null,
565 custom_type: Some(TypeDefinition::TaggedType(TaggedTypeDefinition {
566 tag,
567 ty: Some(Box::new(TypeDefinition::CoreType(CoreLibBaseTypeId::Unit.into()).into())),
568 }))
569 })))
570 }
571
572 // NOTE: make sure that get_next_expected_instructions does not return None for these instructions!
573 RegularInstruction::Statements(_) |
574 RegularInstruction::ShortStatements(_) |
575 RegularInstruction::UnboundedStatements |
576 RegularInstruction::UnboundedStatementsEnd(_) |
577 RegularInstruction::List(_) |
578 RegularInstruction::Range |
579 RegularInstruction::ShortList(_) |
580 RegularInstruction::Map(_) |
581 RegularInstruction::ShortMap(_) |
582 RegularInstruction::TaggedValue(TaggedValue {is_empty: false, ..}) |
583 RegularInstruction::KeyValueDynamic |
584 RegularInstruction::KeyValueShortText(_) |
585 RegularInstruction::Add |
586 RegularInstruction::Subtract |
587 RegularInstruction::Multiply |
588 RegularInstruction::Divide |
589 RegularInstruction::UnaryMinus |
590 RegularInstruction::UnaryPlus |
591 RegularInstruction::BitwiseNot |
592 RegularInstruction::Apply(_) |
593 RegularInstruction::GetPropertyText(_) |
594 RegularInstruction::GetPropertyIndex(_) |
595 RegularInstruction::GetPropertyDynamic |
596 RegularInstruction::TakePropertyText(_) |
597 RegularInstruction::TakePropertyIndex(_) |
598 RegularInstruction::TakePropertyDynamic |
599 RegularInstruction::SetPropertyText(_) |
600 RegularInstruction::SetPropertyIndex(_) |
601 RegularInstruction::SetPropertyDynamic |
602 RegularInstruction::Is |
603 RegularInstruction::Matches |
604 RegularInstruction::StructuralEqual |
605 RegularInstruction::Equal |
606 RegularInstruction::NotStructuralEqual |
607 RegularInstruction::NotEqual |
608 RegularInstruction::GetSharedReference |
609 RegularInstruction::GetSharedReferenceMut |
610 RegularInstruction::CreateShared |
611 RegularInstruction::CreateSharedMut |
612 RegularInstruction::PushToStack |
613 RegularInstruction::PushListToStack |
614 RegularInstruction::SetStackValue(_) |
615 RegularInstruction::ModifyStackValue(_) |
616 RegularInstruction::ModifySharedContainerValue(_) |
617 RegularInstruction::SetSharedContainerValue |
618 RegularInstruction::Unbox |
619 RegularInstruction::TypedValue |
620 RegularInstruction::RemoteExecution(_) |
621 RegularInstruction::SharedRefWithValue(_) |
622 RegularInstruction::TypeExpression => unreachable!(),
623 #[cfg(feature = "disassembler")]
624 RegularInstruction::_RemoteExecutionDebugFlat(_) | RegularInstruction::_RemoteExecutionDebugTree(_) => unreachable!(),
625 })
626 } else {
627 None
628 };
629
630 expr.map(CollectedExecutionResult::from)
631 }
632 Instruction::Type(type_instruction) => {
633 let type_instruction = collector
634 .default_type_instruction_collection(type_instruction);
635
636 if let Some(type_instruction) = type_instruction {
637 Some(match type_instruction {
638 TypeInstruction::TypeDefinitionCoreType(core_lib_type_id) => {
639 CollectedExecutionResult::TypeDefinition(TypeDefinition::CoreType(core_lib_type_id))
640 }
641 TypeInstruction::TypeDefinitionLiteral(literal) => {
642 CollectedExecutionResult::TypeDefinition(literal.into())
643 }
644
645 TypeInstruction::TypeDefinitionSharedTypeReference(type_ref) => {
646 let val = interrupt_with_maybe_value!(
647 interrupt_provider,
648 match type_ref.address {
649 PointerAddress::SelfOwned(
650 address,
651 ) => {
652 ExecutionInterrupt::External(
653 ExternalExecutionInterrupt::GetReferenceToLocalPointer(
654 address,
655 ),
656 )
657 }
658 PointerAddress::Remote(address) => {
659 ExecutionInterrupt::External(
660 ExternalExecutionInterrupt::GetReferenceToRemotePointer(
661 address,
662 ReferenceMutability::Immutable,
663 ),
664 )
665 }
666 }
667 );
668
669 match val {
670 // simple Type value
671 Some(ValueContainer::Local(Value {
672 inner: CoreValue::Type(_ty),
673 ..
674 })) => todo!(),
675 // FIXME:
676 // // Type Reference
677 // Some(ValueContainer::Shared(SharedContainer {
678 // value: SharedContainerInner::Type(type_ref),
679 // .. })) => Type::new(
680 // StructuralTypeDefinition::Shared(
681 // type_ref,
682 // ),
683 // metadata,
684 // ),
685 _ => {
686 return yield Err(
687 ExecutionError::ExpectedTypeValue,
688 );
689 }
690 }
691 }
692
693 // NOTE: make sure that get_next_expected_instructions does not return None for these instructions!
694 TypeInstruction::TypeDefinitionList(_)
695 | TypeInstruction::TypeDefinitionMap(_)
696 | TypeInstruction::TypeDefinitionWithMetadata(_)
697 | TypeInstruction::TypeDefinitionRange
698 | TypeInstruction::TypeDefinitionImplType(_) => {
699 unreachable!()
700 }
701 })
702 } else {
703 None
704 }
705 }
706 };
707
708 if let Some(result) = result {
709 collector.push_result(result);
710 }
711
712 // handle collecting nested expressions
713 while let Some(result) = collector.try_pop_collected() {
714 let expr: CollectedExecutionResult = match result {
715 FullOrPartialResult::Full {
716 instruction,
717 results: mut collected_results,
718 } => {
719 match instruction {
720 Instruction::Regular(
721 regular_instruction,
722 ) => match regular_instruction {
723 RegularInstruction::List(_)
724 | RegularInstruction::ShortList(_) => {
725 let elements = yield_unwrap!(collected_results.collect_value_container_results_assert_existing(&state));
726 RuntimeValue::ValueContainer(
727 ValueContainer::from(List::new(
728 elements,
729 )),
730 )
731 .into()
732 }
733 RegularInstruction::Map(_)
734 | RegularInstruction::ShortMap(_) => {
735 let entries = yield_unwrap!(collected_results.collect_key_value_pair_results_assert_existing());
736 RuntimeValue::ValueContainer(
737 ValueContainer::from(Map::from(
738 entries,
739 )),
740 )
741 .into()
742 }
743
744 RegularInstruction::KeyValueDynamic => {
745 let value = yield_unwrap!(
746 collected_results.pop_potentially_cloned_value_container_result_assert_existing(&state)
747 );
748 let key = yield_unwrap!(
749 collected_results
750 .pop_potentially_cloned_value_container_result_assert_existing(&state)
751 );
752 CollectedExecutionResult::KeyValuePair((
753 MapKey::Value(key),
754 value,
755 ))
756 }
757
758 RegularInstruction::KeyValueShortText(
759 short_text_data,
760 ) => {
761 let value = yield_unwrap!(
762 collected_results.pop_potentially_cloned_value_container_result_assert_existing(&state)
763 );
764 let key = MapKey::Text(short_text_data.0);
765 CollectedExecutionResult::KeyValuePair((
766 key, value,
767 ))
768 }
769
770 RegularInstruction::TaggedValue(TaggedValue {
771 tag: ShortTextData(tag),
772 is_empty
773 }) => {
774 assert!(!is_empty);
775
776 let value_container = yield_unwrap!(
777 collected_results.pop_potentially_cloned_value_container_result_assert_existing(&state)
778 );
779 // expected value container to be local value
780 match value_container {
781 ValueContainer::Local(mut value) => {
782 // add tag type to the value
783 value.custom_type = Some(TypeDefinition::TaggedType(TaggedTypeDefinition {
784 tag,
785 ty: value.custom_type.map(Type::from).map(Box::new),
786 }));
787 RuntimeValue::ValueContainer(ValueContainer::Local(value))
788 .into()
789 },
790 _ => {
791 return yield Err(
792 ExecutionError::ExpectedLocalValue,
793 );
794 }
795 }
796 }
797
798 RegularInstruction::Add
799 | RegularInstruction::Subtract
800 | RegularInstruction::Multiply
801 | RegularInstruction::Range
802 | RegularInstruction::Divide => {
803 let right = yield_unwrap!(
804 collected_results
805 .pop_potentially_cloned_value_container_result_assert_existing(&state)
806 );
807 let left = yield_unwrap!(
808 collected_results
809 .pop_potentially_cloned_value_container_result_assert_existing(&state)
810 );
811
812 let res = handle_binary_operation(
813 BinaryOperator::from(
814 regular_instruction,
815 ),
816 &left,
817 &right,
818 );
819 RuntimeValue::ValueContainer(yield_unwrap!(
820 res
821 ))
822 .into()
823 }
824
825 RegularInstruction::Is
826 | RegularInstruction::StructuralEqual
827 | RegularInstruction::Equal
828 | RegularInstruction::NotStructuralEqual
829 | RegularInstruction::NotEqual => {
830 let right = yield_unwrap!(
831 collected_results
832 .pop_potentially_cloned_value_container_result_assert_existing(&state)
833 );
834 let left = yield_unwrap!(
835 collected_results
836 .pop_potentially_cloned_value_container_result_assert_existing(&state)
837 );
838
839 let res = handle_comparison_operation(
840 ComparisonOperator::from(
841 regular_instruction,
842 ),
843 &left,
844 &right,
845 );
846 RuntimeValue::ValueContainer(yield_unwrap!(
847 res
848 ))
849 .into()
850 }
851
852 RegularInstruction::Matches => {
853 let _target = yield_unwrap!(
854 collected_results
855 .pop_runtime_value_result_assert_existing()
856 );
857 let _type_pattern =
858 collected_results.pop_type_result();
859
860 todo!("#645 Undescribed by author.")
861 }
862
863 instruction @ (
864 RegularInstruction::CreateShared |
865 RegularInstruction::CreateSharedMut
866 ) => {
867 let value = yield_unwrap!(
868 collected_results
869 .pop_potentially_cloned_value_container_result_assert_existing(&state)
870 );
871 let pointer = state.runtime.pointer_address_provider().borrow_mut().get_new_self_owned_address();
872 let mutability = match instruction {
873 RegularInstruction::CreateShared => SharedContainerMutability::Immutable,
874 RegularInstruction::CreateSharedMut => SharedContainerMutability::Mutable,
875 _ => unreachable!(),
876 };
877
878 let shared_container = SharedContainer::Owned(OwnedSharedContainer::new_from_self_owned_container(
879 SelfOwnedSharedContainer::new(
880 BaseSharedValueContainer::new_with_inferred_allowed_type(
881 value,
882 mutability,
883 ),
884 pointer,
885 ),
886 ));
887
888 RuntimeValue::ValueContainer(ValueContainer::Shared(shared_container))
889 .into()
890 }
891
892 RegularInstruction::GetSharedReference => {
893 let target = yield_unwrap!(
894 collected_results
895 .pop_potentially_cloned_value_container_result_assert_existing(&state)
896 );
897
898 // value_container must be a shared value, otherwise we cannot create a reference to it
899 if let ValueContainer::Shared(shared) = target {
900 RuntimeValue::ValueContainer(ValueContainer::Shared(
901 SharedContainer::Referenced(shared.derive_immutable_reference())
902 ))
903 .into()
904 } else {
905 return yield Err(ExecutionError::ExpectedSharedValue);
906 }
907 }
908
909 RegularInstruction::GetSharedReferenceMut => {
910 let target = yield_unwrap!(
911 collected_results
912 .pop_potentially_cloned_value_container_result_assert_existing(&state)
913 );
914
915 // value_container must be a shared value, otherwise we cannot create a reference to it
916 if let ValueContainer::Shared(shared) = target {
917 let mut_ref = yield_unwrap!(
918 shared.try_derive_mutable_reference().map_err(|_| ExecutionError::MutableReferenceToNonMutableValue)
919 );
920 RuntimeValue::ValueContainer(ValueContainer::Shared(SharedContainer::Referenced(mut_ref)))
921 .into()
922 } else {
923 return yield Err(ExecutionError::ExpectedSharedValue);
924 }
925 }
926
927 RegularInstruction::UnaryMinus
928 | RegularInstruction::UnaryPlus
929 | RegularInstruction::BitwiseNot
930 | RegularInstruction::Unbox => {
931 let mut target = yield_unwrap!(
932 collected_results
933 .pop_runtime_value_result_assert_existing()
934 );
935 let res = target.with_mut_value_container(
936 &mut state.stack,
937 |target| {
938 handle_unary_operation(
939 UnaryOperator::from(
940 regular_instruction,
941 ),
942 target.clone(), // TODO #646: is unary operation supposed to take ownership?
943 state.runtime.memory(),
944 )
945 },
946 );
947 RuntimeValue::ValueContainer(yield_unwrap!(
948 yield_unwrap!(res)
949 ))
950 .into()
951 }
952
953 RegularInstruction::TypedValue => {
954 let mut value_container = yield_unwrap!(
955 collected_results
956 .pop_potentially_cloned_value_container_result_assert_existing(&state)
957 );
958 let ty =
959 collected_results.pop_type_result();
960
961 match &mut value_container {
962 ValueContainer::Local(value) => {
963 value.custom_type = Some(ty.convert_to_definition());
964 }
965 _ => panic!(
966 "Expected ValueContainer::Value for type casting"
967 ),
968 }
969 RuntimeValue::ValueContainer(
970 value_container,
971 )
972 .into()
973 }
974
975 // type(...)
976 RegularInstruction::TypeExpression => {
977 let ty =
978 collected_results.pop_type_result();
979 RuntimeValue::ValueContainer(
980 ValueContainer::Local(Value {
981 inner: CoreValue::Type(ty),
982 custom_type: None, // TODO #648: type for type
983 }),
984 )
985 .into()
986 }
987
988 RegularInstruction::ModifyStackValue(ModifyStackValue {
989 index,
990 operator
991 }) => {
992 let slot_value = yield_unwrap!(
993 get_stack_value(&state, index)
994 );
995 let value = yield_unwrap!(
996 collected_results
997 .pop_potentially_cloned_value_container_result_assert_existing(&state)
998 );
999
1000 let new_val = yield_unwrap!(
1001 handle_assignment_operation(
1002 operator,
1003 slot_value,
1004 value,
1005 )
1006 );
1007 yield_unwrap!(
1008 state
1009 .stack
1010 .set_stack_value(index, new_val)
1011 );
1012 None.into()
1013 }
1014
1015 RegularInstruction::SetSharedContainerValue => {
1016 let value_container = yield_unwrap!(
1017 collected_results
1018 .pop_potentially_cloned_value_container_result_assert_existing(&state)
1019 );
1020 let mut ref_runtime_value = yield_unwrap!(
1021 collected_results
1022 .pop_runtime_value_result_assert_existing()
1023 );
1024
1025 let res = ref_runtime_value.with_mut_value_container(
1026 &mut state.stack,
1027 |ref_value_container| {
1028 // assignment value must be a reference
1029 if let Some(reference) = ref_value_container.maybe_shared() {
1030 let update_data = ReplaceUpdateData { value: value_container };
1031 // TODO: pass TransceiverId
1032 reference.base_shared_container_mut().try_replace(update_data, TransceiverId(0)).map_err(ExecutionError::UpdateError)?;
1033 Ok(())
1034 } else {
1035 Err(
1036 ExecutionError::ExpectedSharedValue,
1037 )
1038 }
1039 },
1040 ).flatten();
1041 yield_unwrap!(res);
1042 None.into()
1043 },
1044
1045 RegularInstruction::ModifySharedContainerValue(
1046 set_shared_container_value,
1047 ) => {
1048 let value_container = yield_unwrap!(
1049 collected_results
1050 .pop_potentially_cloned_value_container_result_assert_existing(&state)
1051 );
1052 let mut ref_runtime_value = yield_unwrap!(
1053 collected_results
1054 .pop_runtime_value_result_assert_existing()
1055 );
1056
1057 let res = ref_runtime_value.with_mut_value_container(
1058 &mut state.stack,
1059 |ref_value_container| {
1060 // assignment value must be a reference
1061 if let Some(reference) = ref_value_container.maybe_shared() {
1062 let update_data = {
1063 let lhs = reference.value_container();
1064 let val = handle_assignment_operation(
1065 set_shared_container_value.operator,
1066 &lhs,
1067 value_container,
1068 )?;
1069 ReplaceUpdateData { value: val }
1070 };
1071 // TODO: pass TransceiverId
1072 reference.base_shared_container_mut().try_replace(update_data, TransceiverId(0)).map_err(ExecutionError::UpdateError)?;
1073 Ok(())
1074 } else {
1075 Err(
1076 ExecutionError::ExpectedSharedValue,
1077 )
1078 }
1079 },
1080 ).flatten();
1081 yield_unwrap!(res);
1082 None.into()
1083 }
1084
1085 RegularInstruction::SetStackValue(index) => {
1086 let value = yield_unwrap!(
1087 collected_results
1088 .pop_potentially_cloned_value_container_result_assert_existing(&state)
1089 );
1090 yield_unwrap!(
1091 state
1092 .stack
1093 .set_stack_value(index, value)
1094 );
1095 None.into()
1096 }
1097
1098 RegularInstruction::PushToStack => {
1099 let value = yield_unwrap!(
1100 collected_results
1101 .pop_potentially_cloned_value_container_result_assert_existing(&state)
1102 );
1103
1104 state
1105 .stack
1106 .push(value);
1107
1108 None.into()
1109 }
1110
1111 RegularInstruction::PushListToStack => {
1112 let value = yield_unwrap!(
1113 collected_results
1114 .pop_potentially_cloned_value_container_result_assert_existing(&state)
1115 );
1116
1117 // value must be a list value
1118 // push all entries onto the stack
1119 match value {
1120 ValueContainer::Local(Value {inner: CoreValue::List(list), ..}) => {
1121 for value in list {
1122 state.stack
1123 .push(value);
1124 }
1125 }
1126 _ => {
1127 return yield Err(ExecutionError::InvalidProgram(InvalidProgramError::ExpectedList))
1128 }
1129 }
1130
1131 None.into()
1132 }
1133
1134 RegularInstruction::GetPropertyText(
1135 property_data,
1136 ) => {
1137 let mut target = yield_unwrap!(
1138 collected_results
1139 .pop_runtime_value_result_assert_existing()
1140 );
1141 let property_name = property_data.0;
1142
1143 let res = target.with_mut_value_container(
1144 &mut state.stack,
1145 |target| {
1146 target.try_get_property(
1147 &property_name,
1148 )
1149 },
1150 );
1151 RuntimeValue::ValueContainer(yield_unwrap!(
1152 yield_unwrap!(res)
1153 ))
1154 .into()
1155 }
1156
1157 RegularInstruction::GetPropertyIndex(
1158 property_data,
1159 ) => {
1160 let mut target = yield_unwrap!(
1161 collected_results
1162 .pop_runtime_value_result_assert_existing()
1163 );
1164 let property_index = property_data.0;
1165
1166 let res = target.with_mut_value_container(
1167 &mut state.stack,
1168 |target| {
1169 target.try_get_property(
1170 property_index,
1171 )
1172 },
1173 );
1174 RuntimeValue::ValueContainer(yield_unwrap!(
1175 yield_unwrap!(res)
1176 ))
1177 .into()
1178 }
1179
1180 RegularInstruction::GetPropertyDynamic => {
1181 let key = yield_unwrap!(
1182 collected_results
1183 .pop_potentially_cloned_value_container_result_assert_existing(&state)
1184 );
1185 let mut target = yield_unwrap!(
1186 collected_results
1187 .pop_runtime_value_result_assert_existing()
1188 );
1189
1190 let res = target.with_mut_value_container(
1191 &mut state.stack,
1192 |target| target.try_get_property(&key),
1193 );
1194 RuntimeValue::ValueContainer(yield_unwrap!(
1195 yield_unwrap!(res)
1196 ))
1197 .into()
1198 }
1199
1200 RegularInstruction::TakePropertyIndex(
1201 property_data,
1202 ) => {
1203 let mut target = yield_unwrap!(
1204 collected_results
1205 .pop_runtime_value_result_assert_existing()
1206 );
1207 let property_index = property_data.0;
1208
1209 let res = target.with_mut_value_container(
1210 &mut state.stack,
1211 |target| {
1212 target.try_delete_entry(
1213 DeleteEntryUpdateData { key: ValueKey::Index(property_index as i64) },
1214 TransceiverId(0), // TODO
1215 )
1216 },
1217 );
1218 RuntimeValue::ValueContainer(yield_unwrap!(
1219 yield_unwrap!(res)
1220 ))
1221 .into()
1222 }
1223
1224 RegularInstruction::SetPropertyText(
1225 property_data,
1226 ) => {
1227 let mut target = yield_unwrap!(
1228 collected_results
1229 .pop_runtime_value_result_assert_existing()
1230 );
1231 let value = yield_unwrap!(
1232 collected_results
1233 .pop_potentially_cloned_value_container_result_assert_existing(&state)
1234 );
1235 let res = target.with_mut_value_container(
1236 &mut state.stack,
1237 |target| {
1238 set_property(
1239 target,
1240 ValueKey::Text(
1241 property_data.0,
1242 ),
1243 value,
1244 )
1245 },
1246 );
1247 yield_unwrap!(yield_unwrap!(res));
1248 None.into()
1249 }
1250
1251 RegularInstruction::SetPropertyIndex(
1252 property_data,
1253 ) => {
1254 let mut target = yield_unwrap!(
1255 collected_results
1256 .pop_runtime_value_result_assert_existing()
1257 );
1258 let value = yield_unwrap!(
1259 collected_results
1260 .pop_potentially_cloned_value_container_result_assert_existing(&state)
1261 );
1262
1263 let res = target.with_mut_value_container(
1264 &mut state.stack,
1265 |target| {
1266 set_property(
1267 target,
1268 ValueKey::Index(
1269 property_data.0 as i64,
1270 ),
1271 value,
1272 )
1273 },
1274 );
1275 yield_unwrap!(yield_unwrap!(res));
1276 None.into()
1277 }
1278
1279 RegularInstruction::SetPropertyDynamic => {
1280 let mut target = yield_unwrap!(
1281 collected_results
1282 .pop_runtime_value_result_assert_existing()
1283 );
1284 let value = yield_unwrap!(
1285 collected_results
1286 .pop_potentially_cloned_value_container_result_assert_existing(&state)
1287 );
1288 let key = yield_unwrap!(
1289 collected_results
1290 .pop_potentially_cloned_value_container_result_assert_existing(&state)
1291 );
1292
1293 let res = target.with_mut_value_container(
1294 &mut state.stack,
1295 |target| {
1296 set_property(
1297 target,
1298 ValueKey::Value(key),
1299 value,
1300 )
1301 },
1302 );
1303 yield_unwrap!(yield_unwrap!(res));
1304 None.into()
1305 }
1306
1307 RegularInstruction::RemoteExecution(
1308 exec_block_data,
1309 ) => {
1310 let receivers = yield_unwrap!(
1311 collected_results
1312 .pop_potentially_cloned_value_container_result_assert_existing(&state)
1313 );
1314
1315 // ensure receiver is single endpoint
1316 let receivers_list: Vec<Endpoint> = match receivers {
1317 ValueContainer::Local(Value {inner: CoreValue::Endpoint(endpoint), ..}) => vec![endpoint],
1318 // TODO: support advanced receivers
1319 _ => return yield Err(ExecutionError::ValueError(ValueError::InvalidOperation))
1320 };
1321
1322 let injected_values = yield_unwrap!(state.stack.resolve_injected_values(&exec_block_data.injected_values));
1323
1324 // build dxb
1325 let DXBWithSharedValues {dxb: buffer, shared_values: shared_containers} = yield_unwrap!({
1326 let lookup = state.runtime.pointer_availability_lookup();
1327 let compile_input = CompileInput::new(
1328 &lookup,
1329 &receivers_list,
1330 );
1331 compile_injected_values(
1332 exec_block_data,
1333 injected_values,
1334 compile_input
1335 )
1336 });
1337
1338 let shared_references_cache = shared_containers.to_vec();
1339
1340 yield_unwrap!(
1341 // SAFETY: we guarantee that receivers is not empty.
1342 unsafe {
1343 state.runtime.internal.register_shared_containers_for_endpoints(
1344 &receivers_list.iter().collect::<Vec<_>>(),
1345 shared_containers
1346 )
1347 }.map_err(|_e| ExecutionError::MoveToMultipleEndpoints)
1348 );
1349
1350 interrupt_with_maybe_value!(
1351 interrupt_provider,
1352 ExecutionInterrupt::External(
1353 ExternalExecutionInterrupt::RemoteExecution {
1354 input: DXBWithSharedValues {
1355 dxb: buffer,
1356 shared_values: shared_references_cache,
1357 },
1358 receivers: receivers_list
1359 }
1360 )
1361 )
1362 .map(RuntimeValue::ValueContainer)
1363 .into()
1364 }
1365
1366 RegularInstruction::Apply(ApplyData {
1367 ..
1368 }) => {
1369 let mut args = yield_unwrap!(collected_results.collect_value_container_results_assert_existing(&state));
1370 // last argument is the callee
1371 let callee = args.remove(args.len() - 1);
1372
1373 // special handling for panic function - abort execution
1374 if let ValueContainer::Local(Value {inner: CoreValue::Callable(Callable {body: CallableBody::CoreStub(CoreStub::Panic), ..}), ..}) = callee
1375 {
1376 // assert for now that single string arg
1377 let error: String = args.remove(0).try_into_value().unwrap();
1378 return yield Err(ExecutionError::Unspecified(error));
1379 }
1380
1381 interrupt_with_maybe_value!(
1382 interrupt_provider,
1383 ExecutionInterrupt::External(
1384 ExternalExecutionInterrupt::Apply(
1385 callee, args
1386 )
1387 )
1388 )
1389 .map(|val| {
1390 RuntimeValue::ValueContainer(val)
1391 })
1392 .into()
1393 }
1394
1395 RegularInstruction::UnboundedStatementsEnd(
1396 UnboundedStatementsData { terminated },
1397 ) => {
1398 let result = yield_unwrap!(collector.try_pop_unbounded().ok_or(DXBParserError::NotInUnboundedRegularScopeError));
1399 if let FullOrPartialResult::Partial {
1400 result: collected_result,
1401 previous_stack_index,
1402 ..
1403 } = result
1404 {
1405 // reset stack index
1406 state.stack.truncate(previous_stack_index);
1407 if terminated {
1408 CollectedExecutionResult::Value(
1409 None,
1410 )
1411 } else {
1412 match collected_result {
1413 Some(CollectedExecutionResult::Value(val)) => val.into(),
1414 None => CollectedExecutionResult::Value(None),
1415 _ => unreachable!(),
1416 }
1417 }
1418 } else {
1419 unreachable!()
1420 }
1421 }
1422
1423 RegularInstruction::SharedRefWithValue(shared_ref) => {
1424 let value = yield_unwrap!(
1425 collected_results
1426 .pop_potentially_cloned_value_container_result_assert_existing(&state)
1427 );
1428
1429 // if caller endpoint is local endpoint, this is a local pointer
1430 let referenced_container = if state.caller_metadata.endpoint.is_local_or_equals_endpoint(state.runtime.endpoint()) {
1431 let container = yield_unwrap!(resolve_cache_value(
1432 &mut state,
1433 PointerAddress::SelfOwned(shared_ref.address),
1434 SharedContainerOwnership::Referenced(shared_ref.ref_mutability)
1435 ));
1436 match container {
1437 SharedContainer::Referenced(referenced_container) => referenced_container,
1438 SharedContainer::Owned(_) => {
1439 unreachable!()
1440 }
1441 }
1442 }
1443 // else, get remote pointer from address
1444 else {
1445 let pointer_address = RemotePointerAddress::for_endpoint(&state.caller_metadata.endpoint, &shared_ref.address);
1446
1447 if state.runtime.memory().borrow().has_reference(&PointerAddress::Remote(pointer_address.clone())) {
1448 return yield Err(ExecutionError::Unknown); // TODO: error
1449 }
1450
1451 let base = yield_unwrap!(BaseSharedValueContainer::try_new(
1452 value,
1453 TypeDefinition::CoreType(CoreLibBaseTypeId::Unknown.into()),
1454 shared_ref.container_mutability,
1455 ));
1456
1457 // Note: safe because we checked if the address already exists in memory before
1458 yield_unwrap!(unsafe {ReferencedSharedContainer::try_new_external_from_base_container(
1459 base,
1460 pointer_address,
1461 shared_ref.ref_mutability,
1462 &state.runtime.memory().borrow_mut(),
1463 )}.map_err(|_err| ExecutionError::InvalidSharedValueType))
1464 };
1465
1466 let container = SharedContainer::Referenced(referenced_container);
1467 CollectedExecutionResult::Value(Some(ValueContainer::Shared(container).into()))
1468 },
1469
1470 e => {
1471 todo!(
1472 "Unhandled collected regular instruction: {:?}",
1473 e
1474 );
1475 }
1476 },
1477
1478 Instruction::Type(type_instruction) => {
1479 match type_instruction {
1480 TypeInstruction::TypeDefinitionImplType(
1481 impl_type_data,
1482 ) => {
1483 let def =
1484 collected_results.pop_type_result();
1485
1486 TypeDefinition::ImplType(ImplTypeDefinition::new(
1487 def,
1488 impl_type_data
1489 .impls
1490 .into_iter().collect(),
1491 )).into()
1492 }
1493 TypeInstruction::TypeDefinitionRange => {
1494 // TODO: add metadata everywhere
1495 let type_start =
1496 collected_results.pop_type_result();
1497 let type_end =
1498 collected_results.pop_type_result();
1499 let x = Type::Alias(
1500 TypeDefinition::Range(RangeTypeDefinition {
1501 start: Box::new(type_start),
1502 end: Box::new(type_end),
1503 }).into(),
1504 );
1505 x.into()
1506 }
1507 TypeInstruction::TypeDefinitionWithMetadata(metadata) => {
1508 let definition = collected_results.pop_type_definition_result();
1509 Type::Alias(TypeDefinitionWithMetadata {
1510 metadata,
1511 definition,
1512 reference_name: None,
1513 }).into()
1514 }
1515 _ => todo!("#649 Undescribed by author."),
1516 }
1517 }
1518 }
1519 }
1520 FullOrPartialResult::Partial {
1521 instruction,
1522 result: collected_result,
1523 previous_stack_index,
1524 } => {
1525 // reset stack index
1526 state.stack.truncate(previous_stack_index);
1527
1528 match instruction {
1529 Instruction::Regular(regular_instruction) => {
1530 match regular_instruction {
1531 RegularInstruction::ShortStatements(
1532 ShortStatementsData {
1533 terminated, ..
1534 },
1535 )
1536 | RegularInstruction::Statements(
1537 StatementsData { terminated, .. },
1538 ) => {
1539 if terminated {
1540 CollectedExecutionResult::Value(
1541 None,
1542 )
1543 } else {
1544 match collected_result {
1545 Some(
1546 CollectedExecutionResult::Value(
1547 val,
1548 ),
1549 ) => val.into(),
1550 None => {
1551 CollectedExecutionResult::Value(
1552 None,
1553 )
1554 }
1555 _ => unreachable!(), // statements always resolve to values
1556 }
1557 }
1558 }
1559 _ => unreachable!(),
1560 }
1561 }
1562
1563 Instruction::Type(_data) => unreachable!(),
1564 }
1565 }
1566 };
1567
1568 // info!("{} | {} >>> {:#?}", state.runtime_internal.endpoint,instruction_copy, expr);
1569
1570 collector.push_result(expr);
1571 }
1572
1573 // if in unbounded statements, propagate active value via interrupt
1574 if let Some(ResultCollector::LastUnbounded(
1575 LastUnboundedResultCollector {
1576 last_result:
1577 Some(CollectedExecutionResult::Value(last_result)),
1578 ..
1579 },
1580 )) = collector.last()
1581 {
1582 let active_value = yield_unwrap!(
1583 last_result
1584 .clone()
1585 .map(|v| v
1586 .into_potentially_cloned_value_container(&state))
1587 .transpose()
1588 );
1589
1590 interrupt!(
1591 interrupt_provider,
1592 ExecutionInterrupt::SetActiveValue(active_value)
1593 );
1594 }
1595 }
1596
1597 if let Some(result) = collector.take_root_result() {
1598 yield Ok(ExecutionInterrupt::External(
1599 ExternalExecutionInterrupt::Result(match result {
1600 CollectedExecutionResult::Value(value) => {
1601 yield_unwrap!(
1602 value
1603 .map(|v| v.into_value_container(&mut state))
1604 .transpose()
1605 )
1606 }
1607 _ => unreachable!("Expected root result"),
1608 }),
1609 ));
1610 } else {
1611 panic!("Execution finished without root result");
1612 }
1613 }
1614}
1615
1616fn resolve_cache_value(
1617 state: &mut RuntimeExecutionState,
1618 pointer_address: PointerAddress,
1619 ownership: SharedContainerOwnership,
1620) -> Result<SharedContainer, ExecutionError> {
1621 // try to find in execution context cache
1622 state
1623 .shared_value_cache
1624 .try_get_shared_container_with_ownership(&pointer_address, ownership)
1625 .map_err(ExecutionError::CacheValueRetrievalError)
1626}