Skip to main content

datex_core/runtime/execution/context/
mod.rs

1//! This module contains the implementation of the execution context, which holds the state of an active execution.
2#[cfg(feature = "compiler")]
3use crate::compiler::{
4    CompileOptions, compile_template, error::SpannedCompilerError,
5    scope::CompilationScope,
6};
7use crate::{
8    core_compiler::core_compilation_context::DXBWithSharedValues,
9    runtime::execution::{
10        ExecutionError, ExecutionInput, MemoryDump, execute_dxb,
11        execute_dxb_sync,
12    },
13    values::{
14        core_values::endpoint::Endpoint, value_container::ValueContainer,
15    },
16};
17
18use crate::{
19    prelude::*,
20    runtime::{
21        Runtime, execution::execution_loop::state::RuntimeExecutionStack,
22    },
23};
24pub use local::*;
25use log::info;
26pub use remote::*;
27pub use script::*;
28
29mod local;
30mod remote;
31mod script;
32
33/// Represents an execution context that can be either final (dropped after execution) or persisted (kept for future executions).
34/// Depending on this, the [is_end_of_context] flag is set to true or false on the DXB block
35pub enum FinalOrPersistedExecutionContext<'a> {
36    /// The execution is no longer used afterwards and will be dropped after the execution is finished
37    Final(ExecutionContext),
38    /// The execution context is only given as a reference and will be persisted after the execution is finished.
39    /// This allows reusing the same execution context for multiple executions.
40    Ongoing(&'a mut ExecutionContext),
41}
42
43impl FinalOrPersistedExecutionContext<'_> {
44    /// Returns true if the execution context is final and will be dropped after the execution is finished.
45    pub fn is_end_of_context(&self) -> bool {
46        matches!(self, FinalOrPersistedExecutionContext::Final(_))
47    }
48}
49
50impl AsRef<ExecutionContext> for FinalOrPersistedExecutionContext<'_> {
51    fn as_ref(&self) -> &ExecutionContext {
52        match self {
53            FinalOrPersistedExecutionContext::Final(context) => context,
54            FinalOrPersistedExecutionContext::Ongoing(context) => context,
55        }
56    }
57}
58
59impl AsMut<ExecutionContext> for FinalOrPersistedExecutionContext<'_> {
60    fn as_mut(&mut self) -> &mut ExecutionContext {
61        match self {
62            FinalOrPersistedExecutionContext::Final(context) => context,
63            FinalOrPersistedExecutionContext::Ongoing(context) => context,
64        }
65    }
66}
67
68impl From<ExecutionContext> for FinalOrPersistedExecutionContext<'_> {
69    fn from(context: ExecutionContext) -> Self {
70        FinalOrPersistedExecutionContext::Final(context)
71    }
72}
73
74impl<'a> From<&'a mut ExecutionContext>
75    for FinalOrPersistedExecutionContext<'a>
76{
77    fn from(context: &'a mut ExecutionContext) -> Self {
78        FinalOrPersistedExecutionContext::Ongoing(context)
79    }
80}
81
82/// An execution context holds the persistent state for executing multiple scripts sequentially within the same context.
83/// This can be either a local context, which is used for executing scripts in the same process, or a remote context,
84/// which is used for executing scripts on a remote endpoint.
85#[derive(Debug)]
86pub enum ExecutionContext {
87    Local(LocalExecutionContext),
88    Remote(RemoteExecutionContext),
89}
90impl ExecutionContext {
91    pub fn receivers(&self) -> Vec<Endpoint> {
92        match self {
93            ExecutionContext::Local(_) => {
94                vec![Endpoint::LOCAL]
95            }
96            ExecutionContext::Remote(remote_context) => {
97                remote_context.endpoints().to_vec()
98            }
99        }
100    }
101}
102
103impl ExecutionContext {
104    #[cfg(feature = "compiler")]
105    fn compile_scope(&self) -> &CompilationScope {
106        match self {
107            ExecutionContext::Local(LocalExecutionContext {
108                compile_scope,
109                ..
110            }) => compile_scope,
111            ExecutionContext::Remote(RemoteExecutionContext {
112                compile_scope,
113                ..
114            }) => compile_scope,
115        }
116    }
117
118    #[cfg(feature = "compiler")]
119    fn set_compile_scope(&mut self, new_compile_scope: CompilationScope) {
120        match self {
121            ExecutionContext::Local(LocalExecutionContext {
122                compile_scope,
123                ..
124            }) => *compile_scope = new_compile_scope,
125            ExecutionContext::Remote(RemoteExecutionContext {
126                compile_scope,
127                ..
128            }) => *compile_scope = new_compile_scope,
129        }
130    }
131
132    fn runtime(&self) -> &Runtime {
133        match self {
134            ExecutionContext::Local(LocalExecutionContext {
135                runtime, ..
136            }) => runtime,
137            ExecutionContext::Remote(RemoteExecutionContext {
138                runtime,
139                ..
140            }) => runtime,
141        }
142    }
143
144    /// Compiles a script using the compile scope of the execution context
145    #[cfg(feature = "compiler")]
146    pub fn compile(
147        &mut self,
148        script: &str,
149        inserted_values: &[ValueContainer],
150        receivers: Vec<Endpoint>,
151    ) -> Result<DXBWithSharedValues, SpannedCompilerError> {
152        use crate::compiler::compilation_result::CompilationResult;
153        let compile_scope = self.compile_scope();
154        // TODO #107: don't clone compile_scope if possible
155        let res = compile_template(
156            script,
157            inserted_values
158                .iter()
159                .cloned()
160                .map(Some)
161                .collect::<Vec<_>>(),
162            CompileOptions::new(compile_scope.clone(), receivers),
163            self.runtime().clone(),
164        );
165        match res {
166            Ok(CompilationResult {
167                dxb_with_shared_values,
168                scope,
169                ..
170            }) => {
171                self.set_compile_scope(scope);
172                Ok(dxb_with_shared_values)
173            }
174            Err(err) => Err(err),
175        }
176    }
177
178    fn print_dxb_debug(&self, dxb: &[u8]) -> Result<(), ExecutionError> {
179        info!(
180            "\x1b[32m[Compiled Bytecode] {}",
181            dxb.iter()
182                .map(|b| format!("{b:02x}"))
183                .collect::<Vec<_>>()
184                .join(" ")
185        );
186
187        #[cfg(feature = "decompiler")]
188        {
189            let decompiled =
190                crate::decompiler::dxb_to_source_code::dxb_to_source_code(
191                    dxb,
192                    crate::decompiler::DecompileOptions::colorized(),
193                );
194            if let Err(e) = decompiled {
195                info!("\x1b[31m[Decompiler Error] {e}\x1b[0m");
196            } else {
197                let decompiled = decompiled?;
198                info!("[Decompiled]: {decompiled}");
199            }
200        }
201
202        Ok(())
203    }
204
205    fn get_local_execution_input(
206        &mut self,
207        input: DXBWithSharedValues,
208        initial_stack_values: Option<Vec<ValueContainer>>,
209    ) -> Result<ExecutionInput, ExecutionError> {
210        // show DXB and decompiled code if verbose is enabled
211        if let ExecutionContext::Local(LocalExecutionContext {
212            verbose: true,
213            ..
214        }) = &self
215        {
216            self.print_dxb_debug(&input.dxb)?;
217        };
218
219        match self {
220            ExecutionContext::Remote(_) => {
221                panic!("Remote execution requires a Runtime");
222            }
223            ExecutionContext::Local(LocalExecutionContext {
224                runtime,
225                loop_state,
226                execution_options,
227                verbose: _,
228                caller_metadata,
229                ..
230            }) => {
231                let input =
232                    if let Some(initial_stack_values) = initial_stack_values {
233                        // if we already have a loop state but also provided new initial stack values, this is an invalid state
234                        if loop_state.is_some() {
235                            return Err(ExecutionError::InvalidExecutionState);
236                        }
237                        ExecutionInput::new_with_stack(
238                            input,
239                            caller_metadata.clone(),
240                            (*execution_options).clone(),
241                            runtime.clone(),
242                            RuntimeExecutionStack::new(initial_stack_values),
243                        )
244                    } else {
245                        ExecutionInput::new_with_loop_state(
246                            input,
247                            caller_metadata.clone(),
248                            (*execution_options).clone(),
249                            runtime.clone(),
250                            loop_state.take(),
251                        )
252                    };
253
254                Ok(input)
255            }
256        }
257    }
258
259    /// Executes DXB in a local execution context.
260    pub fn execute_dxb_sync(
261        &mut self,
262        dxb: DXBWithSharedValues,
263        initial_stack_values: Option<Vec<ValueContainer>>,
264    ) -> Result<Option<ValueContainer>, ExecutionError> {
265        let execution_input =
266            self.get_local_execution_input(dxb, initial_stack_values)?;
267        let res = execute_dxb_sync(execution_input);
268        self.intercept_intermediate_result(res)
269    }
270
271    /// Executes a script in a local execution context.
272    #[cfg(feature = "compiler")]
273    pub fn execute_sync(
274        &mut self,
275        script: &str,
276        inserted_values: &[ValueContainer],
277    ) -> Result<Option<ValueContainer>, ScriptExecutionError> {
278        // TODO: insert values as stack values, don't compile?
279        let dxb =
280            self.compile(script, inserted_values, vec![Endpoint::LOCAL])?;
281        self.execute_dxb_sync(dxb, None)
282            .map_err(ScriptExecutionError::from)
283    }
284
285    pub async fn execute_dxb(
286        &mut self,
287        input: DXBWithSharedValues,
288        initial_stack_values: Option<Vec<ValueContainer>>,
289    ) -> Result<Option<ValueContainer>, ExecutionError> {
290        match self {
291            ExecutionContext::Local(..) => {
292                let res = {
293                    let execution_input = self.get_local_execution_input(
294                        input,
295                        initial_stack_values,
296                    )?;
297                    execute_dxb(execution_input).await
298                };
299                self.intercept_intermediate_result(res)
300            }
301            // remote execution is not supported directly in execution context
302            ExecutionContext::Remote(..) => {
303                panic!("Remote execution requires a Runtime");
304            }
305        }
306    }
307
308    /// Intercepts an intermediate execution result,
309    /// storing the loop state if present in the execution context and returning the intermediate result as an Ok value.
310    /// Note: this function assumes that self is a Local execution context
311    fn intercept_intermediate_result(
312        &mut self,
313        execution_result: Result<Option<ValueContainer>, ExecutionError>,
314    ) -> Result<Option<ValueContainer>, ExecutionError> {
315        match execution_result {
316            Err(ExecutionError::IntermediateResultWithState(
317                intermediate_result,
318                Some(state),
319            )) => {
320                match self {
321                    ExecutionContext::Local(LocalExecutionContext {
322                        loop_state,
323                        ..
324                    }) => {
325                        loop_state.replace(state);
326                        Ok(*intermediate_result)
327                    }
328                    _ => unreachable!(), // note: this must be ensured by the caller
329                }
330            }
331            _ => execution_result,
332        }
333    }
334
335    #[cfg(feature = "compiler")]
336    pub async fn execute(
337        &mut self,
338        script: &str,
339        inserted_values: &[ValueContainer],
340    ) -> Result<Option<ValueContainer>, ScriptExecutionError> {
341        // TODO: insert values as stack values, don't compile?
342        let dxb =
343            self.compile(script, inserted_values, vec![Endpoint::LOCAL])?;
344        self.execute_dxb(dxb, None)
345            .await
346            .map_err(ScriptExecutionError::from)
347    }
348
349    /// Returns a memory dump of the current state of the execution context if available.
350    pub fn memory_dump(&self) -> Option<MemoryDump> {
351        match self {
352            ExecutionContext::Local(_local_context) => {
353                todo!("#650 Undescribed by author.")
354                // Some(local_context.memory_dump())
355            }
356            // TODO #397: also support remote memory dump if possible
357            ExecutionContext::Remote(_) => None,
358        }
359    }
360}