Skip to main content

oxdock_core/exec/
engine.rs

1//! Fluent host-extension facade: register functions and types, run scripts.
2//!
3//! Raw pipeline setup (filesystem resolver, process manager, IO, registry
4//! assembly) lives here, so downstream integrations never touch it:
5//!
6//! ```rust
7//! use oxdock_core::{Engine, OxDockFn, OxDockType, Value};
8//! use oxdock_func_macro::{oxdock_func, oxdock_type};
9//! use std::fmt;
10//!
11//! /// Opaque label type.
12//! #[oxdock_type(name = "ENGINE_DOCTEST_TAG")]
13//! #[derive(Debug, Clone, PartialEq)]
14//! struct EngineTag(String);
15//!
16//! impl fmt::Display for EngineTag {
17//!     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
18//!         write!(f, "tag:{}", self.0)
19//!     }
20//! }
21//!
22//! /// Mint one opaque label.
23//! #[oxdock_func(pure)]
24//! fn engine_make_tag() -> anyhow::Result<Value> {
25//!     Ok(Value::mint_heap(EngineTag::descriptor(), EngineTag("demo".into())))
26//! }
27//!
28//! fn main() {
29//!     let temp = oxdock_fs::GuardedPath::tempdir().unwrap();
30//!     let root = temp.as_guarded_path().clone();
31//!     let mut engine = Engine::new();
32//!     engine.register_type::<EngineTag>();
33//!     engine.register_module(oxdock_core::HostModule {
34//!         name: "DEMO".to_string(),
35//!         funcs: vec![EngineMakeTag::registration()],
36//!         types: vec![],
37//!         record_schemas: vec![],
38//!         states: vec![],
39//!     });
40//!     let run = engine
41//!         .run_script(
42//!             &root,
43//!             "IMPORT [DEMO]\nLET $t: ENGINE_DOCTEST_TAG = ENGINE_MAKE_TAG()\n",
44//!         )
45//!         .expect("script runs");
46//!     assert!(run.bindings.contains_key("t"));
47//! }
48//! ```
49//!
50//! Hosts that need more than the defaults (a sandboxed process manager, a
51//! caller-built filesystem, custom IO) stay on the same facade: pick the
52//! manager as the type parameter, stage IO with [`Engine::with_io`], and run
53//! with [`Engine::run_steps_on`] or [`Engine::run_script_on`]. The free
54//! [`run_steps_with_manager_with_modules`](super::run_steps_with_manager_with_modules)
55//! function remains for callers that never stage host surface at all.
56//!
57//! Registration shapes behind the macros (pure vs stateful functions,
58//! heap vs inline types):
59//!
60//! ```rust
61//! use oxdock_func_macro::{oxdock_func, oxdock_type};
62//! use ::oxdock_core::{OxDockFn, OxDockType};
63//! use ::oxdock_process::DefaultProcessManager;
64//!
65//! /// Echo one value back.
66//! #[oxdock_func(pure, name = "ECHO_VAL")]
67//! fn echo_val(val: ::oxdock_core::Value) -> ::anyhow::Result<::oxdock_core::Value> {
68//!     Ok(val)
69//! }
70//!
71//! /// Read an environment variable, defaulting to empty.
72//! #[oxdock_func(name = "ENV_OR", returns = ::oxdock_core::TypeTag::String)]
73//! fn env_or<P: ::oxdock_core::ProcessManager>(
74//!     cx: &mut ::oxdock_core::StepCtx<P>,
75//!     key: String,
76//! ) -> ::anyhow::Result<::oxdock_core::Value> {
77//!     Ok(::oxdock_core::Value::string(cx.get_env(&key).unwrap_or_default()))
78//! }
79//!
80//! /// Dense vector embedding.
81//! ///
82//! /// Heap type: one box allocation per word.
83//! #[oxdock_type(name = "EMBEDDING")]
84//! #[derive(Debug, Clone, PartialEq)]
85//! struct Embedding(Vec<f32>);
86//!
87//! impl ::std::fmt::Display for Embedding {
88//!     fn fmt(&self, f: &mut ::std::fmt::Formatter) -> ::std::fmt::Result {
89//!         write!(f, "embedding[{}]", self.0.len())
90//!     }
91//! }
92//!
93//! /// Entity handle.
94//! ///
95//! /// Inline type: zero allocation, rides in the payload.
96//! #[oxdock_type(name = "ENTITY", inline)]
97//! #[derive(Clone, Copy, PartialEq)]
98//! struct EntityId(u64);
99//!
100//! impl ::std::fmt::Display for EntityId {
101//!     fn fmt(&self, f: &mut ::std::fmt::Formatter) -> ::std::fmt::Result {
102//!         write!(f, "entity#{}", self.0)
103//!     }
104//! }
105//! impl ::std::fmt::Debug for EntityId {
106//!     fn fmt(&self, f: &mut ::std::fmt::Formatter) -> ::std::fmt::Result {
107//!         write!(f, "EntityId({})", self.0)
108//!     }
109//! }
110//!
111//! fn main() {
112//!     let entry: ::oxdock_core::HostRegistration<::oxdock_process::DefaultProcessManager> =
113//!         EchoVal::registration();
114//!     let ::oxdock_core::HostRegistration::Pure { meta, .. } = entry else {
115//!         panic!("pure functions register Pure entries");
116//!     };
117//!     assert_eq!(meta.name, "ECHO_VAL");
118//!     assert_eq!(meta.summary, "Echo one value back.");
119//!     assert_eq!(meta.params.expect("one param").len(), 1);
120//!
121//!     let stateful =
122//!         <EnvOr as OxDockFn<DefaultProcessManager>>::registration();
123//!     let ::oxdock_core::HostRegistration::Stateful { meta, .. } = stateful else {
124//!         panic!("context functions register Stateful entries");
125//!     };
126//!     assert_eq!(meta.name, "ENV_OR");
127//!
128//!     let descriptor = Embedding::descriptor();
129//!     assert_eq!(descriptor.name, "EMBEDDING");
130//!     assert_eq!(descriptor.summary, "Dense vector embedding.");
131//! }
132//! ```
133
134use std::collections::BTreeMap;
135use std::fmt;
136use std::sync::Arc;
137
138use anyhow::Result;
139use oxdock_fs::{GuardedPath, PathResolver, WorkspaceFs};
140use oxdock_parser::{Step, Value};
141use oxdock_process::{DefaultProcessManager, ProcessManager, default_process_manager};
142
143use super::io::ExecIo;
144use super::native::{HostModule, HostRegistration, std_module_table};
145use super::typing::{OxDockType, TypeDescriptor};
146
147/// Output of one [`Engine`] run: the final working directory, the filesystem
148/// handle the run executed against, and the top-level script variable
149/// bindings captured at completion.
150pub struct EngineOutput {
151    /// Working directory when the last step finished.
152    pub cwd: GuardedPath,
153    /// Filesystem handle the run executed against.
154    pub fs: Box<dyn WorkspaceFs>,
155    /// Top-level script variables (`FUNC` bodies and loop scopes excluded).
156    pub bindings: BTreeMap<String, Value>,
157}
158
159impl fmt::Debug for EngineOutput {
160    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
161        f.debug_struct("EngineOutput")
162            .field("cwd", &self.cwd.as_path().display().to_string())
163            .field("bindings", &self.bindings)
164            .finish_non_exhaustive()
165    }
166}
167
168/// Host-extension engine: the single front door for registering Rust
169/// functions and types and running scripts against them.
170///
171/// The type parameter selects the process manager: the default
172/// [`DefaultProcessManager`] runs real subprocesses, while test harnesses
173/// pass their mock (`Engine::<MockProcessManager>::new_custom()` in
174/// `crates/oxdock-core/tests/integration/custom_types.rs` shows the shape).
175/// Staged IO applies to every run; the process manager and the filesystem
176/// are chosen per run, so one engine serves many roots.
177pub struct Engine<P: ProcessManager = DefaultProcessManager> {
178    modules: Vec<HostModule<P>>,
179    types: Vec<&'static TypeDescriptor>,
180    io: ExecIo,
181}
182
183impl<P: ProcessManager> Engine<P> {
184    /// Empty engine for a custom process manager, with default IO and no
185    /// host surface. Prefer [`Engine::new`] for the default manager: a
186    /// bare `Engine::new()` pins the manager type for inference, while
187    /// this constructor needs the turbofish (`Engine::<Mock>::new_custom()`).
188    /// `Engine::<P>::default()` works the same way.
189    pub fn new_custom() -> Self {
190        Self {
191            modules: Vec::new(),
192            types: Vec::new(),
193            io: ExecIo::new(),
194        }
195    }
196
197    /// Stage custom IO (for example inherited environment overrides) for
198    /// every run. Chainable.
199    pub fn with_io(mut self, io: ExecIo) -> Self {
200        self.io = io;
201        self
202    }
203
204    /// Stage the transport behind `REMOTE` blocks for every run.
205    /// Chainable. Without this every `REMOTE` step bails naming the NET
206    /// plugin; the CLI registers its SSH session here at startup.
207    pub fn set_remote_runner(&mut self, runner: Arc<dyn super::remote::RemoteRunner>) -> &mut Self {
208        self.io.set_remote_runner(runner);
209        self
210    }
211
212    /// Register a host library module: its functions become callable as
213    /// `MODULE::NAME`, its types join the run's name directory. Chainable.
214    /// Group `#[oxdock_func]` markers (for example `MakeTag` for
215    /// `make_tag`) with their `#[oxdock_type]` payloads here. Panics on a
216    /// duplicate qualified name, including collisions with `STD` builtins;
217    /// the registry re-checks at run time for direct state users.
218    pub fn register_module(&mut self, module: HostModule<P>) -> &mut Self {
219        let mut seen: std::collections::HashSet<String> = super::builtin_function_names();
220        for staged in self.modules.iter().chain(std::iter::once(&module)) {
221            for registration in &staged.funcs {
222                let base = match registration {
223                    HostRegistration::Stateful { name, .. }
224                    | HostRegistration::Pure { name, .. }
225                    | HostRegistration::Both { name, .. } => name,
226                };
227                let qualified = format!("{}::{base}", staged.name);
228                if !seen.insert(qualified.clone()) {
229                    panic!("duplicate function registration `{qualified}`");
230                }
231            }
232        }
233        self.modules.push(module);
234        self
235    }
236
237    /// Register a `#[oxdock_type]` payload struct. Chainable. Staged for
238    /// the run: values mint straight from the payload type's own
239    /// descriptor, which needs no registration to exist.
240    pub fn register_type<T>(&mut self) -> &mut Self
241    where
242        T: OxDockType,
243    {
244        self.types.push(T::descriptor());
245        self
246    }
247
248    /// Parse-time module table for this engine: stock `STD` builtins plus
249    /// every staged host module (function names and RPN eligibility).
250    /// Unknown modules stay unknown: the `oxdock!` macro declares its own
251    /// opaque modules via the `modules:` prefix instead.
252    pub fn module_table(&self) -> oxdock_parser::ModuleTable {
253        let mut table = std_module_table();
254        for module in &self.modules {
255            let mut functions = std::collections::HashSet::new();
256            for registration in &module.funcs {
257                let name = match registration {
258                    HostRegistration::Stateful { name, .. } => name,
259                    HostRegistration::Pure { name, .. } => name,
260                    HostRegistration::Both { name, .. } => name,
261                };
262                functions.insert(name.clone());
263            }
264            table.modules.insert(
265                module.name.clone(),
266                Some(oxdock_parser::ModuleFuncs { functions }),
267            );
268        }
269        table
270    }
271
272    /// Parse and run `script` on a caller-built filesystem with `process`
273    /// as the manager and the registered host surface available.
274    pub fn run_script_on(
275        &self,
276        fs: Box<dyn WorkspaceFs>,
277        script: &str,
278        process: P,
279    ) -> Result<EngineOutput> {
280        let steps = crate::parse_script_with_modules(script, self.module_table())?;
281        self.run_steps_on(fs, &steps, process)
282    }
283
284    /// Run already parsed `steps` (for example from the `oxdock!` macro,
285    /// which builds the same DSL at compile time) on a caller-built
286    /// filesystem with `process` as the manager and the registered host
287    /// surface available.
288    pub fn run_steps_on(
289        &self,
290        fs: Box<dyn WorkspaceFs>,
291        steps: &[Step],
292        process: P,
293    ) -> Result<EngineOutput> {
294        let (cwd, fs, bindings) = super::run_steps_with_manager_with_modules(
295            fs,
296            steps,
297            process,
298            self.io.clone(),
299            self.modules.clone(),
300            self.types.clone(),
301        )?;
302        Ok(EngineOutput { cwd, fs, bindings })
303    }
304}
305
306impl Engine<DefaultProcessManager> {
307    /// Empty engine with default IO and no host surface. Concrete by
308    /// construction, so `let mut engine = Engine::new()` needs no
309    /// annotation; custom managers use `Engine::<P>::new_custom()`.
310    pub fn new() -> Self {
311        Self {
312            modules: Vec::new(),
313            types: Vec::new(),
314            io: ExecIo::new(),
315        }
316    }
317
318    /// Parse and run `script` with `root` as the workspace, with the
319    /// registered host surface available. Uses the default process manager
320    /// and a resolver built from `root`.
321    pub fn run_script(&self, root: &GuardedPath, script: &str) -> Result<EngineOutput> {
322        let steps = crate::parse_script_with_modules(script, self.module_table())?;
323        self.run_steps(root, &steps)
324    }
325
326    /// Run already parsed `steps` (for example from the `oxdock!` macro,
327    /// which builds the same DSL at compile time) with `root` as the
328    /// workspace and the registered host surface available. Uses the
329    /// default process manager and a resolver built from `root`.
330    pub fn run_steps(&self, root: &GuardedPath, steps: &[Step]) -> Result<EngineOutput> {
331        let resolver = PathResolver::new_guarded(root.clone(), root.clone())?;
332        let fs: Box<dyn WorkspaceFs> = Box::new(resolver);
333        self.run_steps_on(fs, steps, default_process_manager())
334    }
335}
336
337impl<P: ProcessManager> Default for Engine<P> {
338    fn default() -> Self {
339        Self::new_custom()
340    }
341}