Skip to main content

datex_core/runtime/execution/execution_loop/
state.rs

1use crate::{
2    global::{
3        protocol_structures::injected_values::{
4            InjectedValueDeclaration, InjectedValueType,
5            SharedInjectedValueType,
6        },
7        stack_index::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, runtime_value::RuntimeValue,
19            },
20        },
21    },
22    shared_values::{
23        PointerAddress, SharedContainer,
24        base_shared_value_container::observers::TransceiverId,
25    },
26    values::value_container::ValueContainer,
27};
28use core::{cell::RefCell, fmt::Debug};
29use itertools::{EitherOrBoth, Itertools};
30
31pub struct ExecutionLoopState {
32    pub iterator: Box<
33        dyn Iterator<Item = Result<ExternalExecutionInterrupt, ExecutionError>>,
34    >,
35    pub dxb_body: Rc<RefCell<Vec<u8>>>,
36    pub(crate) interrupt_provider: InterruptProvider,
37}
38
39impl PartialEq for ExecutionLoopState {
40    fn eq(&self, other: &Self) -> bool {
41        Rc::ptr_eq(&self.dxb_body, &other.dxb_body)
42            && self.interrupt_provider == other.interrupt_provider
43    }
44}
45
46impl Eq for ExecutionLoopState {}
47
48impl ExecutionLoopState {
49    pub fn new(
50        dxb_body: Vec<u8>,
51        shared_values: Vec<SharedContainer>,
52        runtime: Runtime,
53        stack: RuntimeExecutionStack,
54        caller_metadata: ExecutionCallerMetadata,
55    ) -> Self {
56        let state = RuntimeExecutionState {
57            runtime: runtime.clone(),
58            source_id: TransceiverId::from(
59                &caller_metadata
60                    .endpoint
61                    .as_local_if_endpoint(runtime.endpoint()),
62            ),
63            stack,
64            caller_metadata,
65            shared_value_cache: SharedValuesCache::new(shared_values),
66        };
67        // TODO #641: optimize, don't clone the whole DXB body every time here
68        let dxb_rc = Rc::new(RefCell::new(dxb_body.to_vec()));
69        let interrupt_provider = InterruptProvider::new();
70        ExecutionLoopState {
71            dxb_body: dxb_rc.clone(),
72            iterator: Box::new(execution_loop(
73                state,
74                dxb_rc,
75                interrupt_provider.clone(),
76            )),
77            interrupt_provider,
78        }
79    }
80}
81
82impl Debug for ExecutionLoopState {
83    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
84        f.debug_struct("ExecutionIterator")
85            .field("dxb_body_length", &self.dxb_body.borrow().len())
86            .finish()
87    }
88}
89
90#[derive(Debug)]
91pub struct RuntimeExecutionState {
92    /// Local memory stack for current execution context.
93    pub stack: RuntimeExecutionStack,
94    pub runtime: Runtime,
95    pub source_id: TransceiverId,
96    pub caller_metadata: ExecutionCallerMetadata,
97    pub shared_value_cache: SharedValuesCache,
98}
99
100impl RuntimeExecutionState {
101    pub(crate) fn source_id_cloned(&self) -> TransceiverId {
102        self.source_id.clone()
103    }
104
105    /// Normalizes a pointer address to ensure it is in the correct form for the current execution context.
106    /// For self-owned addresses, it converts them to remote addresses owned by the caller's endpoint.
107    /// For remote addresses, it ensures that if the address is local to the current runtime, it is normalized to a @@local address.
108    pub fn normalize_pointer_address(
109        &self,
110        address: &PointerAddress,
111    ) -> PointerAddress {
112        let local_endpoint = self.runtime.endpoint().clone();
113        let owner_endpoint = &self.caller_metadata.endpoint;
114
115        match address {
116            // convert self owned to caller owned
117            PointerAddress::SelfOwned(address) => PointerAddress::Remote(
118                address.remote_for_endpoint(owner_endpoint),
119            )
120            .normalize_for_local(&local_endpoint),
121            // make sure remote with local endpoint is normalized to @@local
122            PointerAddress::Remote(address) => {
123                address.normalize_for_local(&local_endpoint)
124            }
125        }
126    }
127}
128
129#[derive(Debug, Default)]
130pub struct RuntimeExecutionStack {
131    pub values: Vec<Option<ValueContainer>>,
132}
133
134impl RuntimeExecutionStack {
135    /// Creates a new stack with initial allocated stack values.
136    pub fn new(values: Vec<ValueContainer>) -> Self {
137        Self {
138            values: values.into_iter().map(Some).collect(),
139        }
140    }
141
142    /// Pushes a value to the stack
143    pub(crate) fn push(&mut self, value: ValueContainer) {
144        self.values.push(Some(value));
145    }
146
147    /// Returns the current index for the next value to be pushed to the stack, which is the length of the current stack values.
148    pub(crate) fn current_index(&self) -> StackIndex {
149        StackIndex(self.values.len() as u32)
150    }
151
152    /// Frees the stack to the given index, removing all values above that index. If the index is out of bounds, it panics.
153    pub(crate) fn truncate(&mut self, index: StackIndex) {
154        if index.0 as usize > self.values.len() {
155            panic!(
156                "Cannot free stack to index {:?} as it is out of bounds (current stack size: {})",
157                index,
158                self.values.len()
159            );
160        }
161        self.values.truncate(index.0 as usize);
162    }
163
164    /// Takes a stack value by its index and returns its value.
165    /// If the stack value is not allocated or the index is out of bounds, it returns an error.
166    pub(crate) fn take_stack_value(
167        &mut self,
168        index: StackIndex,
169    ) -> Result<ValueContainer, ExecutionError> {
170        if let Some(stack_value) = self.values.get_mut(index.0 as usize) {
171            stack_value
172                .take()
173                .ok_or_else(|| ExecutionError::StackValueNotAllocated(index))
174        } else {
175            Err(ExecutionError::StackOutOfBoundsAccess(index))
176        }
177    }
178
179    /// Sets the value of a stack index, returning the previous value if it existed.
180    /// If the stack value is not allocated, it returns an error.
181    pub(crate) fn set_stack_value(
182        &mut self,
183        index: StackIndex,
184        value: ValueContainer,
185    ) -> Result<Option<ValueContainer>, ExecutionError> {
186        if let Some(stack_value) = self.values.get_mut(index.0 as usize) {
187            Ok(stack_value.replace(value))
188        } else {
189            Err(ExecutionError::StackOutOfBoundsAccess(index))
190        }
191    }
192
193    /// Retrieves a reference to the value of a stack value by its address.
194    /// If the stack value is not allocated, it returns an error.
195    pub(crate) fn get_stack_value(
196        &self,
197        index: StackIndex,
198    ) -> Result<&ValueContainer, ExecutionError> {
199        if let Some(stack_value) = self.values.get(index.0 as usize) {
200            stack_value
201                .as_ref()
202                .ok_or_else(|| ExecutionError::StackValueNotAllocated(index))
203        } else {
204            Err(ExecutionError::StackOutOfBoundsAccess(index))
205        }
206    }
207
208    /// Retrieves a mutable reference to the stack value by its index.
209    /// If the stack value is not allocated, it returns an error.
210    pub(crate) fn get_stack_value_mut(
211        &mut self,
212        index: StackIndex,
213    ) -> Result<&mut ValueContainer, ExecutionError> {
214        if let Some(stack_value) = self.values.get_mut(index.0 as usize) {
215            stack_value
216                .as_mut()
217                .ok_or_else(|| ExecutionError::StackValueNotAllocated(index))
218        } else {
219            Err(ExecutionError::StackOutOfBoundsAccess(index))
220        }
221    }
222
223    /// Resolves a list of injected values to actual values on the stack
224    pub fn resolve_injected_values(
225        &mut self,
226        injected_values: &[InjectedValueDeclaration],
227    ) -> Result<Vec<ValueContainer>, ExecutionError> {
228        let mut moved: Vec<Option<_>> = vec![None; injected_values.len()];
229
230        // perform all mutable operations (removing moved shared values)
231        for (i, InjectedValueDeclaration { index, ty }) in
232            injected_values.iter().enumerate()
233        {
234            if matches!(
235                ty,
236                InjectedValueType::Shared(SharedInjectedValueType::Move)
237            ) {
238                moved[i] = Some(self.take_stack_value(*index)?);
239            }
240        }
241
242        // collect all values
243        let mut resolved_values = Vec::with_capacity(injected_values.len());
244        for (i, InjectedValueDeclaration { index, ty }) in
245            injected_values.iter().enumerate()
246        {
247            resolved_values.push(match ty {
248                InjectedValueType::Shared(SharedInjectedValueType::Move) => {
249                    match moved[i].take().unwrap() {
250                        shared @ ValueContainer::Shared(_) => shared,
251                        local @ ValueContainer::Local(_) => {
252                            local
253                            // FIXME: should return this error, but since compiler currently also marks local values as shared, this is disabled for now
254                            // return Err(ExecutionError::ExpectedSharedValue);
255                        }
256                    }
257                }
258                _ => self.get_stack_value(*index)?.clone(), // TODO: avoid clone?
259            });
260        }
261
262        Ok(resolved_values)
263    }
264
265    /// Resolves a list of runtime values to actual values on the stack,
266    /// returning both the resolved values and their corresponding stack indices (for values stored on the stack)
267    pub fn take_runtime_values_with_stack_indices(
268        &mut self,
269        values: Vec<RuntimeValue>,
270    ) -> Result<(Vec<ValueContainer>, Vec<Option<StackIndex>>), ExecutionError>
271    {
272        let mut stack_indices = Vec::new();
273        let mut resolved_values = Vec::new();
274
275        for value in values {
276            match value {
277                RuntimeValue::StackValue(index) => {
278                    stack_indices.push(Some(index));
279                    resolved_values.push(self.take_stack_value(index)?);
280                }
281                RuntimeValue::ValueContainer(value) => {
282                    stack_indices.push(None);
283                    resolved_values.push(value);
284                }
285            }
286        }
287
288        Ok((resolved_values, stack_indices))
289    }
290
291    /// Restores values to the stack at the given indices, if both the index and value are available.
292    pub fn restore_stack_values(
293        &mut self,
294        values: Vec<ValueContainer>,
295        stack_indices: Vec<Option<StackIndex>>,
296    ) -> Result<(), ExecutionError> {
297        for x in stack_indices.into_iter().flatten().zip_longest(values) {
298            match x {
299                EitherOrBoth::Both(previous, next) => {
300                    // If a stack index is available, and the value for the reserved stack index is available, restore the value to the stack at the given index.
301                    self.set_stack_value(previous, next)?;
302                }
303                _ => {
304                    // error if the number of stack indices does not match the number of values
305                    return Err(ExecutionError::StackRestoreMismatch);
306                }
307            }
308        }
309        Ok(())
310    }
311}