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