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