Skip to main content

datex_core/runtime/execution/execution_loop/
state.rs

1use crate::{
2    global::protocol_structures::{
3        injected_values::{
4            InjectedValueDeclaration, InjectedValueType,
5            SharedInjectedValueType,
6        },
7        instruction_data::StackIndex,
8    },
9    prelude::*,
10    runtime::{
11        Runtime,
12        cache::shared_values_cache::SharedValuesCache,
13        execution::{
14            ExecutionError,
15            execution_input::ExecutionCallerMetadata,
16            execution_loop::{
17                ExternalExecutionInterrupt, execution_loop,
18                interrupts::InterruptProvider,
19            },
20        },
21    },
22    shared_values::{
23        SharedContainer, base_shared_value_container::observers::TransceiverId,
24    },
25    values::value_container::ValueContainer,
26};
27use core::{cell::RefCell, fmt::Debug};
28
29pub struct ExecutionLoopState {
30    pub iterator: Box<
31        dyn Iterator<Item = Result<ExternalExecutionInterrupt, ExecutionError>>,
32    >,
33    pub dxb_body: Rc<RefCell<Vec<u8>>>,
34    pub(crate) interrupt_provider: InterruptProvider,
35}
36impl ExecutionLoopState {
37    pub fn new(
38        dxb_body: Vec<u8>,
39        shared_values: Vec<SharedContainer>,
40        runtime: Runtime,
41        stack: RuntimeExecutionStack,
42        caller_metadata: ExecutionCallerMetadata,
43    ) -> Self {
44        let state = RuntimeExecutionState {
45            runtime: runtime.clone(),
46            source_id: TransceiverId(0), // TODO #640: set proper source ID
47            stack,
48            caller_metadata,
49            shared_value_cache: SharedValuesCache::new(shared_values),
50        };
51        // TODO #641: optimize, don't clone the whole DXB body every time here
52        let dxb_rc = Rc::new(RefCell::new(dxb_body.to_vec()));
53        let interrupt_provider = InterruptProvider::new();
54        ExecutionLoopState {
55            dxb_body: dxb_rc.clone(),
56            iterator: Box::new(execution_loop(
57                state,
58                dxb_rc,
59                interrupt_provider.clone(),
60            )),
61            interrupt_provider,
62        }
63    }
64}
65
66impl Debug for ExecutionLoopState {
67    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
68        f.debug_struct("ExecutionIterator")
69            .field("dxb_body_length", &self.dxb_body.borrow().len())
70            .finish()
71    }
72}
73
74#[derive(Debug)]
75pub struct RuntimeExecutionState {
76    /// Local memory stack for current execution context.
77    pub stack: RuntimeExecutionStack,
78    pub runtime: Runtime,
79    pub source_id: TransceiverId,
80    pub caller_metadata: ExecutionCallerMetadata,
81    pub shared_value_cache: SharedValuesCache,
82}
83
84#[derive(Debug, Default)]
85pub struct RuntimeExecutionStack {
86    pub values: Vec<Option<ValueContainer>>,
87}
88
89impl RuntimeExecutionStack {
90    /// Pushes a value to the stack
91    pub(crate) fn push(&mut self, value: ValueContainer) {
92        self.values.push(Some(value));
93    }
94
95    /// Pushes multiple values to the stack
96    pub(crate) fn push_multiple(&mut self, values: Vec<ValueContainer>) {
97        self.values.extend(values.into_iter().map(Some));
98    }
99
100    /// Returns the current index for the next value to be pushed to the stack, which is the length of the current stack values.
101    pub(crate) fn current_index(&self) -> StackIndex {
102        StackIndex(self.values.len() as u32)
103    }
104
105    /// Frees the stack to the given index, removing all values above that index. If the index is out of bounds, it panics.
106    pub(crate) fn truncate(&mut self, index: StackIndex) {
107        if index.0 as usize > self.values.len() {
108            panic!(
109                "Cannot free stack to index {:?} as it is out of bounds (current stack size: {})",
110                index,
111                self.values.len()
112            );
113        }
114        self.values.truncate(index.0 as usize);
115    }
116
117    /// Takes a stack value by its index and returns its value.
118    /// If the stack value is not allocated or the index is out of bounds, it returns an error.
119    pub(crate) fn take_stack_value(
120        &mut self,
121        index: StackIndex,
122    ) -> Result<ValueContainer, ExecutionError> {
123        if let Some(stack_value) = self.values.get_mut(index.0 as usize) {
124            stack_value
125                .take()
126                .ok_or_else(|| ExecutionError::StackValueNotAllocated(index))
127        } else {
128            Err(ExecutionError::StackOutOfBoundsAccess(index))
129        }
130    }
131
132    /// Sets the value of a stack index, returning the previous value if it existed.
133    /// If the stack value is not allocated, it returns an error.
134    pub(crate) fn set_stack_value(
135        &mut self,
136        index: StackIndex,
137        value: ValueContainer,
138    ) -> Result<Option<ValueContainer>, ExecutionError> {
139        if let Some(stack_value) = self.values.get_mut(index.0 as usize) {
140            Ok(stack_value.replace(value))
141        } else {
142            Err(ExecutionError::StackOutOfBoundsAccess(index))
143        }
144    }
145
146    /// Retrieves a reference to the value of a stack value by its address.
147    /// If the stack value is not allocated, it returns an error.
148    pub(crate) fn get_stack_value(
149        &self,
150        index: StackIndex,
151    ) -> Result<&ValueContainer, ExecutionError> {
152        if let Some(stack_value) = self.values.get(index.0 as usize) {
153            stack_value
154                .as_ref()
155                .ok_or_else(|| ExecutionError::StackValueNotAllocated(index))
156        } else {
157            Err(ExecutionError::StackOutOfBoundsAccess(index))
158        }
159    }
160
161    /// Retrieves a mutable reference to the stack value by its index.
162    /// If the stack value is not allocated, it returns an error.
163    pub(crate) fn get_stack_value_mut(
164        &mut self,
165        index: StackIndex,
166    ) -> Result<&mut ValueContainer, ExecutionError> {
167        if let Some(stack_value) = self.values.get_mut(index.0 as usize) {
168            stack_value
169                .as_mut()
170                .ok_or_else(|| ExecutionError::StackValueNotAllocated(index))
171        } else {
172            Err(ExecutionError::StackOutOfBoundsAccess(index))
173        }
174    }
175
176    /// Resolves a list of injected values to actual values on the stack
177    pub fn resolve_injected_values(
178        &mut self,
179        injected_values: &[InjectedValueDeclaration],
180    ) -> Result<Vec<ValueContainer>, ExecutionError> {
181        let mut moved: Vec<Option<_>> = vec![None; injected_values.len()];
182
183        // perform all mutable operations (removing moved shared values)
184        for (i, InjectedValueDeclaration { index, ty }) in
185            injected_values.iter().enumerate()
186        {
187            if matches!(
188                ty,
189                InjectedValueType::Shared(SharedInjectedValueType::Move)
190            ) {
191                moved[i] = Some(self.take_stack_value(*index)?);
192            }
193        }
194
195        // collect all values
196        let mut resolved_values = Vec::with_capacity(injected_values.len());
197        for (i, InjectedValueDeclaration { index, ty }) in
198            injected_values.iter().enumerate()
199        {
200            resolved_values.push(match ty {
201                InjectedValueType::Shared(SharedInjectedValueType::Move) => {
202                    match moved[i].take().unwrap() {
203                        shared @ ValueContainer::Shared(_) => shared,
204                        ValueContainer::Local(_) => {
205                            return Err(ExecutionError::ExpectedSharedValue);
206                        }
207                    }
208                }
209                _ => self.get_stack_value(*index)?.clone(), // TODO: avoid clone?
210            });
211        }
212
213        Ok(resolved_values)
214    }
215}