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, .. } => name,
225 };
226 let qualified = format!("{}::{base}", staged.name);
227 if !seen.insert(qualified.clone()) {
228 panic!("duplicate function registration `{qualified}`");
229 }
230 }
231 }
232 self.modules.push(module);
233 self
234 }
235
236 /// Register a `#[oxdock_type]` payload struct. Chainable. Staged for
237 /// the run: values mint straight from the payload type's own
238 /// descriptor, which needs no registration to exist.
239 pub fn register_type<T>(&mut self) -> &mut Self
240 where
241 T: OxDockType,
242 {
243 self.types.push(T::descriptor());
244 self
245 }
246
247 /// Parse-time module table for this engine: stock `STD` builtins plus
248 /// every staged host module (function names and RPN eligibility).
249 /// Unknown modules stay unknown: the `oxdock!` macro declares its own
250 /// opaque modules via the `modules:` prefix instead.
251 pub fn module_table(&self) -> oxdock_parser::ModuleTable {
252 let mut table = std_module_table();
253 for module in &self.modules {
254 let mut functions = std::collections::HashSet::new();
255 for registration in &module.funcs {
256 let name = match registration {
257 HostRegistration::Stateful { name, .. } => name,
258 HostRegistration::Pure { name, .. } => name,
259 };
260 functions.insert(name.clone());
261 }
262 table.modules.insert(
263 module.name.clone(),
264 Some(oxdock_parser::ModuleFuncs { functions }),
265 );
266 }
267 table
268 }
269
270 /// Parse and run `script` on a caller-built filesystem with `process`
271 /// as the manager and the registered host surface available.
272 pub fn run_script_on(
273 &self,
274 fs: Box<dyn WorkspaceFs>,
275 script: &str,
276 process: P,
277 ) -> Result<EngineOutput> {
278 let steps = crate::parse_script_with_modules(script, self.module_table())?;
279 self.run_steps_on(fs, &steps, process)
280 }
281
282 /// Run already parsed `steps` (for example from the `oxdock!` macro,
283 /// which builds the same DSL at compile time) on a caller-built
284 /// filesystem with `process` as the manager and the registered host
285 /// surface available.
286 pub fn run_steps_on(
287 &self,
288 fs: Box<dyn WorkspaceFs>,
289 steps: &[Step],
290 process: P,
291 ) -> Result<EngineOutput> {
292 let (cwd, fs, bindings) = super::run_steps_with_manager_with_modules(
293 fs,
294 steps,
295 process,
296 self.io.clone(),
297 self.modules.clone(),
298 self.types.clone(),
299 )?;
300 Ok(EngineOutput { cwd, fs, bindings })
301 }
302}
303
304impl Engine<DefaultProcessManager> {
305 /// Empty engine with default IO and no host surface. Concrete by
306 /// construction, so `let mut engine = Engine::new()` needs no
307 /// annotation; custom managers use `Engine::<P>::new_custom()`.
308 pub fn new() -> Self {
309 Self {
310 modules: Vec::new(),
311 types: Vec::new(),
312 io: ExecIo::new(),
313 }
314 }
315
316 /// Parse and run `script` with `root` as the workspace, with the
317 /// registered host surface available. Uses the default process manager
318 /// and a resolver built from `root`.
319 pub fn run_script(&self, root: &GuardedPath, script: &str) -> Result<EngineOutput> {
320 let steps = crate::parse_script_with_modules(script, self.module_table())?;
321 self.run_steps(root, &steps)
322 }
323
324 /// Run already parsed `steps` (for example from the `oxdock!` macro,
325 /// which builds the same DSL at compile time) with `root` as the
326 /// workspace and the registered host surface available. Uses the
327 /// default process manager and a resolver built from `root`.
328 pub fn run_steps(&self, root: &GuardedPath, steps: &[Step]) -> Result<EngineOutput> {
329 let resolver = PathResolver::new_guarded(root.clone(), root.clone())?;
330 let fs: Box<dyn WorkspaceFs> = Box::new(resolver);
331 self.run_steps_on(fs, steps, default_process_manager())
332 }
333}
334
335impl<P: ProcessManager> Default for Engine<P> {
336 fn default() -> Self {
337 Self::new_custom()
338 }
339}