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::{DiagnosticResult, 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() -> DiagnosticResult<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::{DiagnosticResult, 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) -> ::oxdock_core::DiagnosticResult<::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//! ) -> ::oxdock_core::DiagnosticResult<::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 oxdock_diagnostics::DiagnosticResult;
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 func_names = 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 func_names.insert(name.clone());
263 }
264 table.modules.insert(
265 module.name.clone(),
266 Some(oxdock_parser::ModuleFuncs { func_names }),
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 ) -> DiagnosticResult<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 ) -> DiagnosticResult<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 /// Parse and run the script file at `path` on a caller-built
306 /// filesystem, with the entry file set so nested imports resolve
307 /// against the file's directory (like the CLI running a script
308 /// file), not the workspace root. Without this, a script run from
309 /// its text resolves sibling imports against the root and fails
310 /// to find them.
311 pub fn run_script_file_on(
312 &self,
313 fs: Box<dyn WorkspaceFs>,
314 path: &GuardedPath,
315 script: &str,
316 process: P,
317 ) -> DiagnosticResult<EngineOutput> {
318 let steps = crate::parse_script_with_modules(script, self.module_table())?;
319 let (cwd, fs, bindings) = super::run_steps_with_manager_with_modules_and_entry(
320 fs,
321 &steps,
322 process,
323 self.io.clone(),
324 self.modules.clone(),
325 self.types.clone(),
326 Some(path.clone()),
327 )?;
328 Ok(EngineOutput { cwd, fs, bindings })
329 }
330}
331
332impl Engine<DefaultProcessManager> {
333 /// Empty engine with default IO and no host surface. Concrete by
334 /// construction, so `let mut engine = Engine::new()` needs no
335 /// annotation; custom managers use `Engine::<P>::new_custom()`.
336 pub fn new() -> Self {
337 Self {
338 modules: Vec::new(),
339 types: Vec::new(),
340 io: ExecIo::new(),
341 }
342 }
343
344 /// Parse and run `script` with `root` as the workspace, with the
345 /// registered host surface available. Uses the default process manager
346 /// and a resolver built from `root`.
347 pub fn run_script(&self, root: &GuardedPath, script: &str) -> DiagnosticResult<EngineOutput> {
348 let steps = crate::parse_script_with_modules(script, self.module_table())?;
349 self.run_steps_without_snapshot(root, &steps)
350 }
351
352 /// Run already parsed `steps` (for example from the `oxdock!` macro,
353 /// which builds the same DSL at compile time) directly against `root`
354 /// with the registered host surface available. Writes land exactly in
355 /// `root`; for the lazy snapshot default use [`Engine::run_steps`].
356 /// Uses the default process manager and a resolver built from `root`.
357 pub fn run_steps_without_snapshot(
358 &self,
359 root: &GuardedPath,
360 steps: &[Step],
361 ) -> DiagnosticResult<EngineOutput> {
362 let resolver = PathResolver::new_guarded(root.clone(), root.clone())?;
363 let fs: Box<dyn WorkspaceFs> = Box::new(resolver);
364 self.run_steps_on(fs, steps, default_process_manager())
365 }
366
367 /// Run already parsed `steps` with the CLI default: a lazily-created
368 /// snapshot. No temporary directory exists until the first
369 /// snapshot-targeted resolution; reads fall through to the build
370 /// context. Carries the engine's registered host surface, IO, and
371 /// types; for bindings and the snapshot handle see the output.
372 pub fn run_steps(
373 &self,
374 build_context: &GuardedPath,
375 steps: &[Step],
376 ) -> DiagnosticResult<super::LazyRunOutput> {
377 super::run_steps_with_lazy_snapshot_and_modules(
378 build_context,
379 steps,
380 self.io.clone(),
381 self.modules.clone(),
382 self.types.clone(),
383 )
384 }
385}
386
387impl<P: ProcessManager> Default for Engine<P> {
388 fn default() -> Self {
389 Self::new_custom()
390 }
391}