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::{prelude::*, runtime::Runtime};
19pub use local::*;
20use log::info;
21pub use remote::*;
22pub use script::*;
23
24mod local;
25mod remote;
26mod script;
27
28/// An execution context holds the persistent state for executing multiple scripts sequentially within the same context.
29/// This can be either a local context, which is used for executing scripts in the same process, or a remote context,
30/// which is used for executing scripts on a remote endpoint.
31#[derive(Debug)]
32pub enum ExecutionContext {
33    Local(LocalExecutionContext),
34    Remote(RemoteExecutionContext),
35}
36impl ExecutionContext {
37    pub fn receivers(&self) -> Vec<Endpoint> {
38        match self {
39            ExecutionContext::Local(_) => {
40                vec![Endpoint::LOCAL]
41            }
42            ExecutionContext::Remote(remote_context) => {
43                vec![remote_context.endpoint.clone()]
44            }
45        }
46    }
47}
48
49impl ExecutionContext {
50    #[cfg(feature = "compiler")]
51    fn compile_scope(&self) -> &CompilationScope {
52        match self {
53            ExecutionContext::Local(LocalExecutionContext {
54                compile_scope,
55                ..
56            }) => compile_scope,
57            ExecutionContext::Remote(RemoteExecutionContext {
58                compile_scope,
59                ..
60            }) => compile_scope,
61        }
62    }
63
64    #[cfg(feature = "compiler")]
65    fn set_compile_scope(&mut self, new_compile_scope: CompilationScope) {
66        match self {
67            ExecutionContext::Local(LocalExecutionContext {
68                compile_scope,
69                ..
70            }) => *compile_scope = new_compile_scope,
71            ExecutionContext::Remote(RemoteExecutionContext {
72                compile_scope,
73                ..
74            }) => *compile_scope = new_compile_scope,
75        }
76    }
77
78    fn runtime(&self) -> &Runtime {
79        match self {
80            ExecutionContext::Local(LocalExecutionContext {
81                runtime, ..
82            }) => runtime,
83            ExecutionContext::Remote(RemoteExecutionContext {
84                runtime,
85                ..
86            }) => runtime,
87        }
88    }
89
90    /// Compiles a script using the compile scope of the execution context
91    #[cfg(feature = "compiler")]
92    pub fn compile(
93        &mut self,
94        script: &str,
95        inserted_values: &[ValueContainer],
96        receivers: Vec<Endpoint>,
97    ) -> Result<DXBWithSharedValues, SpannedCompilerError> {
98        let compile_scope = self.compile_scope();
99        // TODO #107: don't clone compile_scope if possible
100        let res = compile_template(
101            script,
102            inserted_values
103                .iter()
104                .cloned()
105                .map(Some)
106                .collect::<Vec<_>>(),
107            CompileOptions::new(compile_scope.clone(), receivers),
108            self.runtime().clone(),
109        );
110        match res {
111            Ok((result, compile_scope)) => {
112                self.set_compile_scope(compile_scope);
113                Ok(result)
114            }
115            Err(err) => Err(err),
116        }
117    }
118
119    fn print_dxb_debug(&self, dxb: &[u8]) -> Result<(), ExecutionError> {
120        info!(
121            "\x1b[32m[Compiled Bytecode] {}",
122            dxb.iter()
123                .map(|b| format!("{b:02x}"))
124                .collect::<Vec<_>>()
125                .join(" ")
126        );
127
128        #[cfg(feature = "decompiler")]
129        {
130            let decompiled = crate::decompiler::decompile_body(
131                dxb,
132                crate::decompiler::DecompileOptions::colorized(),
133            );
134            if let Err(e) = decompiled {
135                info!("\x1b[31m[Decompiler Error] {e}\x1b[0m");
136            } else {
137                let decompiled = decompiled?;
138                info!("[Decompiled]: {decompiled}");
139            }
140        }
141
142        Ok(())
143    }
144
145    fn get_local_execution_input(
146        &mut self,
147        input: DXBWithSharedValues,
148    ) -> Result<ExecutionInput, ExecutionError> {
149        // show DXB and decompiled code if verbose is enabled
150        if let ExecutionContext::Local(LocalExecutionContext {
151            verbose: true,
152            ..
153        }) = &self
154        {
155            self.print_dxb_debug(&input.dxb)?;
156        };
157
158        match self {
159            ExecutionContext::Remote(_) => {
160                core::panic!("Remote execution requires a Runtime");
161            }
162            ExecutionContext::Local(LocalExecutionContext {
163                runtime,
164                loop_state,
165                execution_options,
166                verbose: _,
167                caller_metadata,
168                ..
169            }) => {
170                let input = ExecutionInput::new_with_loop_state(
171                    input,
172                    caller_metadata.clone(),
173                    (*execution_options).clone(),
174                    runtime.clone(),
175                    loop_state.take(),
176                );
177
178                Ok(input)
179            }
180        }
181    }
182
183    /// Executes DXB in a local execution context.
184    pub fn execute_dxb_sync(
185        &mut self,
186        dxb: DXBWithSharedValues,
187    ) -> Result<Option<ValueContainer>, ExecutionError> {
188        let execution_input = self.get_local_execution_input(dxb)?;
189        let res = execute_dxb_sync(execution_input);
190        self.intercept_intermediate_result(res)
191    }
192
193    /// Executes a script in a local execution context.
194    #[cfg(feature = "compiler")]
195    pub fn execute_sync(
196        &mut self,
197        script: &str,
198        inserted_values: &[ValueContainer],
199    ) -> Result<Option<ValueContainer>, ScriptExecutionError> {
200        let dxb =
201            self.compile(script, inserted_values, vec![Endpoint::LOCAL])?;
202        self.execute_dxb_sync(dxb)
203            .map_err(ScriptExecutionError::from)
204    }
205
206    pub async fn execute_dxb(
207        &mut self,
208        input: DXBWithSharedValues,
209    ) -> Result<Option<ValueContainer>, ExecutionError> {
210        match self {
211            ExecutionContext::Local(..) => {
212                let res = {
213                    let execution_input =
214                        self.get_local_execution_input(input)?;
215                    execute_dxb(execution_input).await
216                };
217                self.intercept_intermediate_result(res)
218            }
219            // remote execution is not supported directly in execution context
220            ExecutionContext::Remote(..) => {
221                core::panic!("Remote execution requires a Runtime");
222            }
223        }
224    }
225
226    /// Intercepts an intermediate execution result,
227    /// storing the loop state if present in the execution context and returning the intermediate result as an Ok value.
228    /// Note: this function assumes that self is a Local execution context
229    fn intercept_intermediate_result(
230        &mut self,
231        execution_result: Result<Option<ValueContainer>, ExecutionError>,
232    ) -> Result<Option<ValueContainer>, ExecutionError> {
233        match execution_result {
234            Err(ExecutionError::IntermediateResultWithState(
235                intermediate_result,
236                Some(state),
237            )) => {
238                match self {
239                    ExecutionContext::Local(LocalExecutionContext {
240                        loop_state,
241                        ..
242                    }) => {
243                        loop_state.replace(state);
244                        Ok(intermediate_result)
245                    }
246                    _ => unreachable!(), // note: this must be ensured by the caller
247                }
248            }
249            _ => execution_result,
250        }
251    }
252
253    #[cfg(feature = "compiler")]
254    pub async fn execute(
255        &mut self,
256        script: &str,
257        inserted_values: &[ValueContainer],
258    ) -> Result<Option<ValueContainer>, ScriptExecutionError> {
259        let dxb =
260            self.compile(script, inserted_values, vec![Endpoint::LOCAL])?;
261        self.execute_dxb(dxb)
262            .await
263            .map_err(ScriptExecutionError::from)
264    }
265
266    /// Returns a memory dump of the current state of the execution context if available.
267    pub fn memory_dump(&self) -> Option<MemoryDump> {
268        match self {
269            ExecutionContext::Local(_local_context) => {
270                todo!("#650 Undescribed by author.")
271                // Some(local_context.memory_dump())
272            }
273            // TODO #397: also support remote memory dump if possible
274            ExecutionContext::Remote(_) => None,
275        }
276    }
277}