oxdock_core/exec/native.rs
1use std::collections::{BTreeMap, HashMap, HashSet};
2use std::sync::Arc;
3
4use anyhow::Result;
5use oxdock_func_macro::oxdock_func;
6use oxdock_parser::{
7 Field, KEYWORD_INSPECT, SCRIPT_MODULE_NAME, STD_MODULE_NAME, SemaphoreState, Step, TypeTag,
8 Value, base_name, qualify, render_structural, split_qualified,
9};
10use oxdock_pipe::PipeHandle;
11use oxdock_process::{CommandStdin, DefaultProcessManager, ProcessManager};
12
13use super::io::StreamHandle;
14use super::state::ExecState;
15use super::steps::StepCtx;
16use super::typing::TypeDescriptor;
17
18/// Origin of a callable in the unified function registry. `Script` is an
19/// interpreted `FUNC` body; `HostCtx` and `HostPure` are compiled Rust
20/// functions (the `#[oxdock_func]` host export macro). Builtins and
21/// runtime-registered hosts share the host kinds; only `DESCRIBE` output
22/// shows the label, and both host kinds keep rendering as `host`.
23#[derive(Debug, Clone, Copy, PartialEq, Eq)]
24pub enum FuncKind {
25 Script,
26 HostCtx,
27 HostPure,
28}
29
30impl FuncKind {
31 pub fn label(&self) -> &'static str {
32 match self {
33 FuncKind::Script => "script",
34 FuncKind::HostCtx | FuncKind::HostPure => "host",
35 }
36 }
37}
38
39/// One declared parameter of a registered function. `param_type` is `None`
40/// for unconstrained `Value` parameters (the macro accepts any value).
41/// `allowed` names the closed value set for constrained `STRING`
42/// parameters, declared once via `#[values(...)]`: the generated
43/// extractor enforces membership and the reference renders the set,
44/// so the list cannot rot apart from the check. `docs` carries the
45/// parameter's description (parsed from the `# Arguments` doc section
46/// for macro functions, written inline for hand-built entries) and
47/// renders into every reference surface. `options` declares the known
48/// keys of a `MAP` options parameter: same single-source rule as
49/// `allowed`, with per-key types, required flags, defaults, and docs.
50/// `optional` marks a trailing `MAP` parameter callers may omit: the
51/// runtime fills an empty MAP, and signatures render `= {}`. Only
52/// trailing `MAP` params may be optional (run-start validation
53/// rejects anything else), so omission always means "no options".
54/// The macro never emits optional params: only hand-built entries
55/// use them, and only for options MAPs.
56#[derive(Debug, Clone)]
57pub struct FuncParam {
58 pub name: String,
59 pub param_type: Option<TypeTag>,
60 pub allowed: Option<&'static [&'static str]>,
61 pub docs: &'static str,
62 pub options: Option<&'static [ParamOption]>,
63 pub optional: bool,
64}
65
66/// Required argument count: total params minus trailing optionals.
67/// Callers may pass any count in `required..=total`; omitted trailing
68/// MAPs fill with an empty MAP. Shared by the static arity gate and
69/// the runtime gate so the two can never disagree.
70pub fn required_arity(params: &[FuncParam]) -> usize {
71 params
72 .iter()
73 .rev()
74 .take_while(|param| param.optional)
75 .fold(params.len(), |count, _| count - 1)
76}
77
78/// Fill omitted trailing optional MAP params with empty MAPs. The
79/// caller guarantees `values.len()` is within
80/// `required_arity(params)..=params.len()`; anything else is a bug,
81/// not a user error, so over- and under-counts panic loudly.
82pub fn fill_optional_args(params: &[FuncParam], mut values: Vec<Value>) -> Vec<Value> {
83 assert!(
84 values.len() <= params.len(),
85 "arity gate must run before fill_optional_args"
86 );
87 assert!(
88 values.len() >= required_arity(params),
89 "arity gate must run before fill_optional_args"
90 );
91 while values.len() < params.len() {
92 values.push(Value::map(BTreeMap::new()));
93 }
94 values
95}
96
97/// One known key of a `MAP` options parameter: name, value type,
98/// whether callers must pass it, the rendered default for optional
99/// keys, and what it controls. Declared once per options parameter
100/// (macro `#[options(...)]` plus the `# Options` doc section, or
101/// inline for hand-built entries) and rendered into signatures,
102/// `DESCRIBE` output, and generated references alike.
103#[derive(Debug, Clone, Copy)]
104pub struct ParamOption {
105 pub name: &'static str,
106 pub value: TypeTag,
107 pub required: bool,
108 pub default: Option<&'static str>,
109}
110
111/// Introspectable metadata for one function. Single source for
112/// `DESCRIBE(name)` output and the static function reference. `rpn` names
113/// whether the function also runs on the compiled math path (`true` for
114/// pure functions and opted-in stateful ones); everything runs on the AST
115/// path.
116#[derive(Debug, Clone)]
117pub struct FuncMeta {
118 pub name: String,
119 /// Owning module (`STD` for builtins, `SCRIPT` for DSL definitions,
120 /// the host module name otherwise). `name` is always the qualified
121 /// `MODULE::BASE` form, so listings and `DESCRIBE` never lose origin.
122 pub module: String,
123 pub kind: FuncKind,
124 pub params: Option<Vec<FuncParam>>,
125 pub returns: Option<TypeTag>,
126 pub rpn: bool,
127 pub summary: &'static str,
128 pub docs: &'static str,
129}
130
131/// Pure scalar function: no filesystem, no scope, no process access.
132/// Usable from both AST evaluation and compiled RPN math.
133pub type PureFn = Arc<dyn Fn(Vec<Value>) -> Result<Value> + Send + Sync>;
134
135/// Stateful/IO function with full step context (fs, cwd, envs, vars, pipes).
136pub type NativeFn<P> = Arc<dyn Fn(&mut StepCtx<P>, Vec<Value>) -> Result<Value> + Send + Sync>;
137
138/// Export hook for a DSL function, implemented by `#[oxdock_func]` on a
139/// registration marker. The engine calls `registration()` and never names
140/// a generated symbol.
141pub trait OxDockFn<P: ProcessManager> {
142 /// The registry entry deriving from the Rust signature plus doc
143 /// comments: name, metadata, and entry point, composed.
144 fn registration() -> HostRegistration<P>;
145}
146
147/// One host-registered function, grouped into a [`HostModule`] and passed
148/// to `Engine::register_module`. Build the entry with the `#[oxdock_func]`-
149/// generated registration marker, or by hand. `Pure` entries run
150/// on both the AST and the compiled RPN math paths; `Stateful` entries run
151/// on the AST path with full step context.
152pub enum HostRegistration<P: ProcessManager> {
153 Stateful {
154 name: String,
155 meta: FuncMeta,
156 func: NativeFn<P>,
157 },
158 Pure {
159 name: String,
160 meta: FuncMeta,
161 func: PureFn,
162 },
163}
164
165// Manual `Clone` (a derive would demand `P: Clone`): entries share their
166// function pointers through the `Arc`s and deep-copy the metadata.
167impl<P: ProcessManager> Clone for HostRegistration<P> {
168 fn clone(&self) -> Self {
169 match self {
170 HostRegistration::Stateful { name, meta, func } => HostRegistration::Stateful {
171 name: name.clone(),
172 meta: meta.clone(),
173 func: Arc::clone(func),
174 },
175 HostRegistration::Pure { name, meta, func } => HostRegistration::Pure {
176 name: name.clone(),
177 meta: meta.clone(),
178 func: Arc::clone(func),
179 },
180 }
181 }
182}
183
184impl<P: ProcessManager> HostRegistration<P> {
185 /// Introspectable metadata for this entry, for documentation tooling
186 /// that reads modules without registering them.
187 pub fn meta(&self) -> &FuncMeta {
188 match self {
189 HostRegistration::Stateful { meta, .. } => meta,
190 HostRegistration::Pure { meta, .. } => meta,
191 }
192 }
193}
194
195/// One user-defined function body (`FUNC NAME($p: TYPE, ...) { ... }`).
196/// Param types resolve to tags at definition time, where the type
197/// directory is in scope; the registry never holds raw type strings.
198#[derive(Debug, Clone)]
199pub(super) struct FuncDefData {
200 pub(super) params: Vec<(String, TypeTag)>,
201 pub(super) body: Vec<Step>,
202}
203
204/// Executable body behind one registry entry: an interpreted script, a
205/// pure scalar function, or a stateful function with step context.
206pub(super) enum FuncBody<P: ProcessManager> {
207 Script(FuncDefData),
208 Pure(PureFn),
209 Ctx(NativeFn<P>),
210}
211
212// Manual `Clone` (a derive would demand `P: Clone`).
213impl<P: ProcessManager> Clone for FuncBody<P> {
214 fn clone(&self) -> Self {
215 match self {
216 FuncBody::Script(def) => FuncBody::Script(def.clone()),
217 FuncBody::Pure(func) => FuncBody::Pure(Arc::clone(func)),
218 FuncBody::Ctx(func) => FuncBody::Ctx(Arc::clone(func)),
219 }
220 }
221}
222
223/// One entry in the unified function registry: introspectable metadata
224/// (mandatory for every entry, backing the pre-evaluation arity gate)
225/// plus the executable body.
226pub(super) struct FuncEntry<P: ProcessManager> {
227 pub(super) meta: FuncMeta,
228 pub(super) body: FuncBody<P>,
229}
230
231// Manual `Clone` (a derive would demand `P: Clone`).
232impl<P: ProcessManager> Clone for FuncEntry<P> {
233 fn clone(&self) -> Self {
234 Self {
235 meta: self.meta.clone(),
236 body: self.body.clone(),
237 }
238 }
239}
240
241/// Names defined in one lexical scope frame: `defined` rejects duplicates
242/// in the same scope, `shadowed` restores outer definitions on exit.
243struct ScopeFrame<P: ProcessManager> {
244 defined: HashSet<String>,
245 shadowed: Vec<(String, FuncEntry<P>)>,
246}
247
248// Manual `Clone` (a derive would demand `P: Clone`).
249impl<P: ProcessManager> Clone for ScopeFrame<P> {
250 fn clone(&self) -> Self {
251 Self {
252 defined: self.defined.clone(),
253 shadowed: self.shadowed.clone(),
254 }
255 }
256}
257
258/// The single function registry: DSL `FUNC` definitions, builtins, and
259/// host extensions share one lookup table, one metadata path, and one
260/// dispatch order. Script entries scope lexically (defined names revert on
261/// scope exit, shadowing an outer definition restores it); native entries
262/// persist for the run. Shared across `fork()` via clone; the entry maps
263/// clone while scope frames stay per state.
264/// Module to function-name table of pure entries, shared by reference.
265/// Nested so placeholder dispatch looks up `table[module][func]` with
266/// zero allocation; rebuilt only when native entries register.
267pub type PureTable = HashMap<String, HashMap<String, PureFn>>;
268
269pub struct FunctionRegistry<P: ProcessManager> {
270 entries: HashMap<String, FuncEntry<P>>,
271 scopes: Vec<ScopeFrame<P>>,
272 pure_shared: Arc<PureTable>,
273}
274
275impl<P: ProcessManager> FunctionRegistry<P> {
276 pub(super) fn with_builtins() -> Self {
277 let mut reg = Self {
278 entries: HashMap::new(),
279 pure_shared: Arc::new(HashMap::new()),
280 scopes: vec![ScopeFrame {
281 defined: HashSet::new(),
282 shadowed: Vec::new(),
283 }],
284 };
285 // Every builtin registers through the same `HostRegistration`
286 // entries hosts use: no separate authoring path for engine natives.
287 // Builtins land in the `STD` module, exactly like a host module.
288 for host in Self::builtin_registrations() {
289 match host {
290 HostRegistration::Stateful { name, meta, func } => {
291 reg.insert_qualified(STD_MODULE_NAME, name, meta, FuncBody::Ctx(func));
292 }
293 HostRegistration::Pure { name, meta, func } => {
294 reg.insert_qualified(STD_MODULE_NAME, name, meta, FuncBody::Pure(func));
295 }
296 }
297 }
298 reg
299 }
300
301 /// All builtins as host-style registrations, built from the same
302 /// `#[oxdock_func]`-generated markers hosts use. `with_builtins`
303 /// consumes this list, so builtins and hosts share one registration
304 /// pathway instead of two authoring models.
305 pub(super) fn builtin_registrations() -> Vec<HostRegistration<P>> {
306 vec![
307 Int::registration(),
308 Float::registration(),
309 Types::registration(),
310 TypeDescribe::registration(),
311 Glob::registration(),
312 LoadToml::registration(),
313 LoadJson::registration(),
314 ParseToml::registration(),
315 ParseJson::registration(),
316 PathType::registration(),
317 HasKey::registration(),
318 MapSet::registration(),
319 MergeMaps::registration(),
320 ToJson::registration(),
321 TypeOf::registration(),
322 Functions::registration(),
323 Describe::registration(),
324 IsTerminal::registration(),
325 Eof::registration(),
326 SemaphoreNew::registration(),
327 SemaphoreTryAcquire::registration(),
328 SemaphoreAvailable::registration(),
329 ]
330 }
331
332 /// Every name the registry answers to. Backs parse-time shadow
333 /// validation through `builtin_function_names`.
334 pub(super) fn keys(&self) -> HashSet<String> {
335 self.entries.keys().cloned().collect()
336 }
337
338 /// Single lookup for every callable: script, pure, or stateful.
339 pub(super) fn get(&self, name: &str) -> Option<FuncEntry<P>> {
340 self.entries.get(name).cloned()
341 }
342
343 fn insert_native(&mut self, name: String, meta: FuncMeta, body: FuncBody<P>) {
344 self.entries.insert(name, FuncEntry { meta, body });
345 self.rebuild_pure_shared();
346 }
347
348 /// Rebuild the shared pure table. Runs only on native insertion:
349 /// script definitions insert `Script` bodies directly and never
350 /// affect the pure set, so this stays correct between rebuilds.
351 fn rebuild_pure_shared(&mut self) {
352 let mut table: PureTable = HashMap::new();
353 for (name, entry) in &self.entries {
354 let FuncBody::Pure(ref func) = entry.body else {
355 continue;
356 };
357 if let Some((module, base)) = split_qualified(name) {
358 table
359 .entry(module.to_string())
360 .or_default()
361 .insert(base.to_string(), Arc::clone(func));
362 }
363 }
364 self.pure_shared = Arc::new(table);
365 }
366
367 /// Insert under `MODULE::BASE`, stamping provenance on the metadata.
368 /// The single choke point for every registry entry: builtins pass
369 /// `STD`, hosts pass their module, scripts pass `SCRIPT`.
370 fn insert_qualified(
371 &mut self,
372 module: &str,
373 base: String,
374 mut meta: FuncMeta,
375 body: FuncBody<P>,
376 ) {
377 meta.name = qualify(module, &base);
378 meta.module = module.to_string();
379 // Last-write-wins would silently reroute calls, so a repeated
380 // qualified name is a programmer error, never a shadow: panic like
381 // conflicting type registrations do. `SCRIPT` definitions bypass
382 // this path (`define_script` owns their scoped shadowing).
383 if self.entries.contains_key(&meta.name) {
384 panic!("duplicate function registration `{}`", meta.name);
385 }
386 self.insert_native(meta.name.clone(), meta, body);
387 }
388
389 pub(super) fn register_host(
390 &mut self,
391 module: &str,
392 name: String,
393 mut meta: FuncMeta,
394 func: NativeFn<P>,
395 ) {
396 meta.kind = FuncKind::HostCtx;
397 self.insert_qualified(module, name, meta, FuncBody::Ctx(func));
398 }
399
400 pub(super) fn register_pure_host(
401 &mut self,
402 module: &str,
403 name: String,
404 mut meta: FuncMeta,
405 func: PureFn,
406 ) {
407 meta.kind = FuncKind::HostPure;
408 self.insert_qualified(module, name, meta, FuncBody::Pure(func));
409 }
410
411 /// Define a DSL `FUNC`: names colliding with any known base name cannot
412 /// shadow, same-scope duplicates cannot redefine, and nested shadowing
413 /// of an outer script definition restores on scope exit. Stored as
414 /// `SCRIPT::NAME`, exactly like every other qualified entry.
415 pub(super) fn define_script(
416 &mut self,
417 name: &str,
418 params: &[(String, TypeTag)],
419 body: &[Step],
420 ) -> Result<()> {
421 let qualified = qualify(SCRIPT_MODULE_NAME, name);
422 let shadowable = matches!(
423 self.entries.get(&qualified).map(|entry| &entry.body),
424 Some(FuncBody::Script(_))
425 );
426 // Reserved spans every module: compare base names so the message
427 // keeps naming the bare script identifier.
428 let reserved = self
429 .entries
430 .keys()
431 .any(|key| split_qualified(key).is_some_and(|(_, base)| base == name));
432 if reserved && !shadowable {
433 anyhow::bail!("cannot shadow reserved function `{name}`");
434 }
435 if self
436 .scopes
437 .last()
438 .is_some_and(|frame| frame.defined.contains(&qualified))
439 {
440 anyhow::bail!("duplicate function `{name}` in same scope");
441 }
442 let old = self.entries.insert(
443 qualified.clone(),
444 FuncEntry {
445 meta: FuncMeta {
446 name: qualified.clone(),
447 module: SCRIPT_MODULE_NAME.to_string(),
448 kind: FuncKind::Script,
449 params: Some(
450 params
451 .iter()
452 .map(|(name, param_type)| FuncParam {
453 name: name.clone(),
454 param_type: Some(*param_type),
455 allowed: None,
456 // Script `FUNC` params carry no prose:
457 // declarations have no doc syntax.
458 docs: "",
459 options: None,
460 optional: false,
461 })
462 .collect(),
463 ),
464 returns: None,
465 rpn: false,
466 summary: "DSL-defined function.",
467 docs: "Defined via FUNC in script.",
468 },
469 body: FuncBody::Script(FuncDefData {
470 params: params.to_vec(),
471 body: body.to_vec(),
472 }),
473 },
474 );
475 if let Some(frame) = self.scopes.last_mut() {
476 frame.defined.insert(qualified.clone());
477 if let Some(old) = old {
478 frame.shadowed.push((qualified, old));
479 }
480 }
481 Ok(())
482 }
483
484 /// Open a lexical scope frame for script definitions. Native entries
485 /// persist; only script names track here.
486 pub(super) fn push_scope(&mut self) {
487 self.scopes.push(ScopeFrame {
488 defined: HashSet::new(),
489 shadowed: Vec::new(),
490 });
491 }
492
493 /// Close a lexical scope frame: names defined inside revert, and any
494 /// outer definition they shadowed is restored.
495 pub(super) fn pop_scope(&mut self) {
496 let Some(frame) = self.scopes.pop() else {
497 return;
498 };
499 for name in frame.defined {
500 self.entries.remove(&name);
501 }
502 for (name, old) in frame.shadowed {
503 self.entries.insert(name, old);
504 }
505 }
506
507 /// True when `name` is an interpreted script definition (needing call
508 /// scoping and depth budgeting through `call_func_value` rather than
509 /// inline evaluation).
510 pub(super) fn contains_script(&self, name: &str) -> bool {
511 matches!(
512 self.entries.get(name).map(|entry| &entry.body),
513 Some(FuncBody::Script(_))
514 )
515 }
516
517 /// Clone the pure fn for `name` (ending the registry borrow) so callers
518 /// can invoke it without holding `&self` across a `&mut StepCtx` use.
519 fn clone_pure_fn(&self, name: &str) -> Option<PureFn> {
520 match self.entries.get(name)?.body {
521 FuncBody::Pure(ref func) => Some(Arc::clone(func)),
522 _ => None,
523 }
524 }
525
526 /// Shared snapshot of every pure entry, nested by module and base
527 /// name. Cloning the `Arc` is refcount-only: placeholder dispatch
528 /// borrows this per expansion with no map copies.
529 pub(super) fn pure_shared(&self) -> Arc<PureTable> {
530 Arc::clone(&self.pure_shared)
531 }
532
533 /// Every entry's metadata, scripts included, sorted by name. Backs
534 /// run-start type tag validation.
535 pub(super) fn all_metas(&self) -> Vec<FuncMeta> {
536 self.entries_metas()
537 }
538
539 /// Clone the ctx fn for `name` (ending the registry borrow) so callers
540 /// can invoke it with `&mut StepCtx` without double-borrowing state.
541 fn clone_ctx_fn(&self, name: &str) -> Option<NativeFn<P>> {
542 match self.entries.get(name)?.body {
543 FuncBody::Ctx(ref func) => Some(Arc::clone(func)),
544 _ => None,
545 }
546 }
547
548 fn meta(&self, name: &str) -> Option<FuncMeta> {
549 self.entries.get(name).map(|entry| entry.meta.clone())
550 }
551
552 fn native_metas(&self) -> Vec<FuncMeta> {
553 let mut out: Vec<FuncMeta> = Vec::new();
554 for entry in self.entries.values() {
555 if !matches!(entry.body, FuncBody::Script(_)) {
556 out.push(entry.meta.clone());
557 }
558 }
559 out.sort_by(|a, b| a.name.cmp(&b.name));
560 out
561 }
562
563 /// Every entry's metadata, scripts included, sorted by name. Backs
564 /// runtime `FUNCTIONS()` listings.
565 fn entries_metas(&self) -> Vec<FuncMeta> {
566 let mut out: Vec<FuncMeta> = self
567 .entries
568 .values()
569 .map(|entry| entry.meta.clone())
570 .collect();
571 out.sort_by(|a, b| a.name.cmp(&b.name));
572 out
573 }
574}
575
576impl<P: ProcessManager> Clone for FunctionRegistry<P> {
577 fn clone(&self) -> Self {
578 Self {
579 entries: self.entries.clone(),
580 scopes: self.scopes.clone(),
581 pure_shared: Arc::clone(&self.pure_shared),
582 }
583 }
584}
585
586/// Names of all compiled-in builtins plus `INSPECT` (a dedicated AST/RPN
587/// node, not a registry entry). Read straight off a stock registry, so the
588/// `#[oxdock_func]` annotations stay the single source of truth: adding a
589/// builtin extends this set with no parallel list to update. Seeds
590/// parse-time shadow validation, so the parser crate keeps zero
591/// compile-time knowledge of builtin names.
592pub fn builtin_function_names() -> HashSet<String> {
593 let mut names = FunctionRegistry::<DefaultProcessManager>::with_builtins().keys();
594 names.insert(KEYWORD_INSPECT.to_string());
595 names
596}
597
598/// Metadata of every builtin function, sorted by name, for static
599/// rendering (docs-gen). Same single source as `builtin_function_names`:
600/// the `#[oxdock_func]` annotations, never a parallel list.
601pub fn builtin_function_metas() -> Vec<FuncMeta> {
602 FunctionRegistry::<DefaultProcessManager>::with_builtins().native_metas()
603}
604
605/// Stock `STD` module table derived from the `#[oxdock_func]` builtins:
606/// the single source of truth for builtin membership and RPN eligibility.
607/// Seeds parse-time module resolution, so the parser crate keeps zero
608/// compile-time knowledge of builtin names.
609pub fn std_module_table() -> oxdock_parser::ModuleTable {
610 // Registry names are qualified (`STD::GLOB`); the table holds bases.
611 let functions: HashSet<String> = builtin_function_metas()
612 .into_iter()
613 .map(|meta| base_name(&meta.name).to_string())
614 .collect();
615 oxdock_parser::ModuleTable {
616 modules: HashMap::from([(
617 STD_MODULE_NAME.to_string(),
618 Some(oxdock_parser::ModuleFuncs { functions }),
619 )]),
620 }
621}
622
623// Builtins below use the `#[oxdock_func]` host export macro, the exact same authoring
624// model as host-registered functions: metadata, arity checks, and argument
625// unpacking derive from the signature plus doc comments, so adding a native
626// means writing one small typed function plus one line each in
627// `builtin_registrations` (consumed by `with_builtins`) and the
628// `FUNCTIONS`/`DESCRIBE`/`TYPES` surface, which all read the same symbols.
629
630/// Convert a value to INT.
631///
632/// Trims ASCII whitespace and parses i64. Passes Int through; Float only
633/// when integral and finite.
634///
635#[oxdock_func(pure, returns = TypeTag::Int)]
636fn int(
637 /// Value to convert to `INT`.
638 val: Value,
639) -> Result<Value> {
640 super::args::int_from_value(val)
641}
642
643/// Convert a value to FLOAT.
644///
645/// Parses f64 (accepts int strings), bails on non-finite or non-numeric.
646///
647#[oxdock_func(pure, returns = TypeTag::Float)]
648fn float(
649 /// Value to convert to `FLOAT`.
650 val: Value,
651) -> Result<Value> {
652 super::args::float_from_value(val)
653}
654
655/// List workspace paths matching a glob pattern.
656///
657/// Sorted, root-relative LIST; empty on no match or `..` escape.
658///
659#[oxdock_func(rpn, returns = TypeTag::ListOf(&TypeTag::String))]
660fn glob<P: ProcessManager>(
661 cx: &mut StepCtx<P>,
662 /// Glob pattern matched against workspace paths.
663 pattern: String,
664) -> Result<Value> {
665 super::args::glob_from_value(&[Value::string(pattern)], cx)
666}
667
668/// Load and parse a TOML file.
669///
670/// Reads a workspace file and parses TOML into a DSL value.
671///
672#[oxdock_func(rpn, returns = TypeTag::MapOf(&TypeTag::Any))]
673fn load_toml<P: ProcessManager>(
674 cx: &mut StepCtx<P>,
675 /// Workspace file path to load and parse as TOML.
676 path: String,
677) -> Result<Value> {
678 super::args::load_toml_from_value(&[Value::string(path)], cx)
679}
680
681/// Load and parse a JSON file.
682///
683/// Reads a workspace file and parses JSON into a DSL value. Returns
684/// `ANY` by design: a top-level array or scalar parses to `LIST` or a
685/// scalar word. `LET` coercion still checks the actual value at
686/// assignment.
687///
688#[oxdock_func(rpn, returns = TypeTag::Any)]
689fn load_json<P: ProcessManager>(
690 cx: &mut StepCtx<P>,
691 /// Workspace file path to load and parse as JSON.
692 path: String,
693) -> Result<Value> {
694 super::args::load_json_from_value(&[Value::string(path)], cx)
695}
696
697/// Parse TOML text already held in memory.
698///
699/// Uses the same conversion as file loading, so fetch bodies, file
700/// contents, and captured text share one JSON/TOML shape.
701///
702#[oxdock_func(pure, returns = TypeTag::MapOf(&TypeTag::Any))]
703fn parse_toml(
704 /// TOML text already held in memory.
705 text: String,
706) -> Result<Value> {
707 super::args::parse_toml_from_value(Value::string(text))
708}
709
710/// Parse JSON text already held in memory.
711///
712/// Uses the same conversion as file loading, so fetch bodies, file
713/// contents, and captured text share one JSON value shape. Returns
714/// `ANY` by design, matching `LOAD_JSON`: a top-level array or scalar
715/// parses to `LIST` or a scalar word. `LET` coercion still checks the
716/// actual value at assignment.
717///
718/// ```oxdock
719/// # Parse in-memory JSON text with the same conversion as file loading.
720/// IMPORT [STD]
721/// LET $body: STRING = "{\"a\": 1}"
722/// LET $doc: ANY = PARSE_JSON($body)
723/// ASSERT_EQ $doc.a 1
724///
725/// # Top-level arrays parse to LIST, which is why the return is ANY.
726/// LET $items: LIST<ANY> = PARSE_JSON("[1, 2]")
727/// ASSERT_EQ $items.0 1
728/// ASSERT_EQ $items.1 2
729/// ```
730///
731#[oxdock_func(pure, returns = TypeTag::Any)]
732fn parse_json(
733 /// JSON text already held in memory.
734 text: String,
735) -> Result<Value> {
736 super::args::parse_json_from_value(Value::string(text))
737}
738
739/// Describe a filesystem entry.
740///
741/// Reports file, dir, symlink (no-follow), or absent. AST-only by design;
742/// there is no RPN arm for filesystem IO.
743///
744#[oxdock_func(returns = TypeTag::String)]
745fn path_type<P: ProcessManager>(
746 cx: &mut StepCtx<P>,
747 /// Workspace path of the entry to describe.
748 path: String,
749) -> Result<Value> {
750 super::args::path_type_from_value(&[Value::string(path)], cx)
751}
752
753/// Report whether a map holds a key.
754///
755/// Pure MAP probe so scripts can branch on optional fields without
756/// tripping the strict missing-key error.
757///
758#[oxdock_func(pure, returns = TypeTag::Bool)]
759fn has_key(
760 /// Map to probe.
761 map: BTreeMap<String, Value>,
762 /// Key to look up.
763 key: String,
764) -> Result<Value> {
765 super::args::has_key_from_value(Value::map(map), &key)
766}
767
768/// Insert one key into a map.
769///
770/// Fails on duplicates so two entries sharing a key fail the run
771/// instead of silently shadowing each other.
772///
773#[oxdock_func(pure, returns = TypeTag::MapOf(&TypeTag::Any))]
774fn map_set(
775 /// Map to insert into.
776 map: BTreeMap<String, Value>,
777 /// Key to insert; duplicates fail.
778 key: String,
779 /// Value to store.
780 value: Value,
781) -> Result<Value> {
782 super::args::map_set_from_value(Value::map(map), key, value)
783}
784
785/// Encode a script value as JSON with one trailing newline.
786///
787/// Maps stay sorted; only template-safe shapes (STRING, INT, FLOAT,
788/// BOOL, LIST, MAP) survive, anything else fails here instead of
789/// rendering as a silent empty.
790///
791#[oxdock_func(pure, returns = TypeTag::String)]
792fn to_json(
793 /// Value to encode as JSON.
794 value: Value,
795) -> Result<Value> {
796 super::args::to_json_from_value(value)
797}
798
799/// Name the word a value holds, for data-driven branching.
800///
801/// Returns the registered type word (`STRING`, `INT`, `FLOAT`, `BOOL`,
802/// `LIST`, `MAP`, plus handle words like `PIPE`): the same name the
803/// value prints in arity and coercion errors, so scripts can branch
804/// on config shapes (a path string or a path list) without failing.
805///
806#[oxdock_func(pure, returns = TypeTag::String)]
807fn type_of(
808 /// Value whose word to name.
809 value: Value,
810) -> Result<Value> {
811 super::args::type_of_from_value(value)
812}
813
814/// Merge a LIST of MAPs in order under one duplicate policy.
815///
816/// `fail_on_duplicate` fails naming the repeated key, so two files
817/// claiming one placeholder fail the run instead of shadowing each
818/// other. `overwrite` lets later files win, for environment overlays.
819/// Non MAP elements fail naming their position.
820///
821#[oxdock_func(pure, returns = TypeTag::MapOf(&TypeTag::Any))]
822fn merge_maps(
823 /// LIST of MAPs to merge in order.
824 maps: Vec<BTreeMap<String, Value>>,
825 /// Duplicate policy.
826 #[values("fail_on_duplicate", "overwrite")]
827 policy: String,
828) -> Result<Value> {
829 super::args::merge_maps_from_value(
830 Value::list(maps.into_iter().map(Value::map).collect()),
831 policy,
832 )
833}
834
835/// List all visible function names.
836///
837/// Sorted LIST of qualified `MODULE::NAME` entries: DSL-defined plus native
838/// plus host-registered names.
839#[oxdock_func(returns = TypeTag::ListOf(&TypeTag::String))]
840fn functions<P: ProcessManager>(cx: &mut StepCtx<P>) -> Result<Value> {
841 let mut names: Vec<String> = cx
842 .state
843 .list_functions()
844 .into_iter()
845 .map(|meta| meta.name)
846 .collect();
847 names.sort();
848 names.dedup();
849 Ok(Value::list(names.into_iter().map(Value::string).collect()))
850}
851
852/// Describe one function by qualified name.
853///
854/// Returns a MAP with name, module, kind, params, returns, rpn, and
855/// summary. `params` is always a LIST (empty for parameterless
856/// functions) of entries carrying name, param_type, allowed, docs,
857/// options, and optional flags, so the shape holds for every entry. Bare names
858/// fail closed: `DESCRIBE` requires the qualified form (except
859/// `INSPECT`, which is syntax rather than a registry entry). Errors
860/// on unknown function.
861///
862/// Field table for the `DESCRIBE` result bundle: one source for the
863/// shape the host mints, so introspection, enforcement, and
864/// documentation cannot drift apart. `const` (not `static`) so the
865/// inline `Record` below const-promotes to `'static` like the
866/// `TYPE_DESCRIBE` table beside it.
867const DESCRIBE_PARAMS_MAP: TypeTag = TypeTag::MapOf(&TypeTag::Any);
868const DESCRIBE_PARAMS: TypeTag = TypeTag::ListOf(&DESCRIBE_PARAMS_MAP);
869
870#[oxdock_func(
871 returns = TypeTag::Record(&[Field {
872 name: "name",
873 ty: TypeTag::String,
874 docs: "Qualified function name.",
875 optional: false,
876 }, Field {
877 name: "module",
878 ty: TypeTag::String,
879 docs: "Owning module.",
880 optional: false,
881 }, Field {
882 name: "kind",
883 ty: TypeTag::String,
884 docs: "Origin label (`host` or `script`).",
885 optional: false,
886 }, Field {
887 name: "params",
888 ty: DESCRIBE_PARAMS,
889 docs: "Parameter entries (empty for parameterless functions).",
890 optional: false,
891 }, Field {
892 name: "returns",
893 ty: TypeTag::String,
894 docs: "Structural return shape (empty when untagged).",
895 optional: false,
896 }, Field {
897 name: "rpn",
898 ty: TypeTag::Bool,
899 docs: "True when callable in RPN position.",
900 optional: false,
901 }, Field {
902 name: "summary",
903 ty: TypeTag::String,
904 docs: "One-line description.",
905 optional: false,
906 }]),
907 summary = "Describe one function by qualified name."
908)]
909fn describe<P: ProcessManager>(
910 cx: &mut StepCtx<P>,
911 /// Qualified function name (`MODULE::NAME`).
912 name: String,
913) -> Result<Value> {
914 if split_qualified(&name).is_none() && name != KEYWORD_INSPECT {
915 anyhow::bail!(
916 "unknown function `{name}`: DESCRIBE requires a qualified name (e.g. `STD::{name}`)"
917 );
918 }
919 cx.state
920 .describe_function(&name)
921 .ok_or_else(|| anyhow::anyhow!("unknown function {name}"))
922}
923
924/// List all known type names.
925///
926/// Sorted LIST of startup plus host-registered type descriptors. Reads the
927/// run's name directory, so it runs on the AST path like the other
928/// introspection functions.
929#[oxdock_func(returns = TypeTag::ListOf(&TypeTag::String))]
930fn types<P: ProcessManager>(cx: &mut StepCtx<P>) -> Result<Value> {
931 Ok(Value::list(
932 cx.state
933 .type_names()
934 .into_iter()
935 .map(Value::string)
936 .collect(),
937 ))
938}
939
940/// Describe one type by name.
941///
942/// Returns a MAP with name, summary, and docs. Errors on unknown type.
943/// Reads the run's name directory, so it runs on the AST path.
944///
945#[oxdock_func(returns = TypeTag::Record(&[Field {
946 name: "name",
947 ty: TypeTag::String,
948 docs: "Queried type name.",
949 optional: false,
950}, Field {
951 name: "summary",
952 ty: TypeTag::String,
953 docs: "One-line description.",
954 optional: false,
955}, Field {
956 name: "docs",
957 ty: TypeTag::String,
958 docs: "Full documentation text.",
959 optional: false,
960}]))]
961fn type_describe<P: ProcessManager>(
962 cx: &mut StepCtx<P>,
963 /// Type name to describe.
964 name: String,
965) -> Result<Value> {
966 if let Some(descriptor) = cx.state.describe_type(&name) {
967 let mut map = BTreeMap::new();
968 map.insert(
969 "name".to_string(),
970 Value::string(descriptor.name.to_string()),
971 );
972 map.insert(
973 "summary".to_string(),
974 Value::string(descriptor.summary.to_string()),
975 );
976 map.insert(
977 "docs".to_string(),
978 Value::string(descriptor.docs.to_string()),
979 );
980 return Ok(Value::map(map));
981 }
982 // Script aliases have no descriptor but introspect the same way:
983 // the entry names the alias and its canonical target spelling.
984 if let Some(target) = cx.state.alias_target(&name) {
985 let mut map = BTreeMap::new();
986 map.insert("name".to_string(), Value::string(name.clone()));
987 map.insert(
988 "summary".to_string(),
989 Value::string(format!("Script type alias for {target}.")),
990 );
991 map.insert(
992 "docs".to_string(),
993 Value::string(format!(
994 "Declared with TYPE {name} = {target}. The alias expands structurally at every declaration."
995 )),
996 );
997 return Ok(Value::map(map));
998 }
999 Err(anyhow::anyhow!("unknown type {name}"))
1000}
1001
1002/// Report whether a standard stream is a terminal.
1003///
1004/// `IS_TERMINAL("stdin")`, `IS_TERMINAL("stdout")`, or `IS_TERMINAL("stderr")`
1005/// answers for the step's stream as currently bound, so scripts can adapt
1006/// prompts, colors, and progress output. Anything diverted from the
1007/// terminal reports false without touching host handles: `WITH_IO` pipe
1008/// bindings (script backends and OS pairs), `LET`-capture sinks, staged
1009/// runner sinks, and any materialized stdin stream (only a directly
1010/// inherited fd falls back to the process check). A transparent root tee
1011/// still answers the session question via the process check. The name
1012/// matches exactly (no case folding): anything else bails. AST-only:
1013/// reads the step context like the other introspection functions.
1014///
1015#[oxdock_func(returns = TypeTag::Bool)]
1016fn is_terminal<P: ProcessManager>(
1017 cx: &mut StepCtx<P>,
1018 /// Stream name: `stdin`, `stdout`, or `stderr` (exact match).
1019 #[values("stdin", "stdout", "stderr")]
1020 stream_name: String,
1021) -> Result<Value> {
1022 use std::io::IsTerminal;
1023 let terminal = match stream_name.as_str() {
1024 "stdin" => {
1025 // A script-pipe backend is definitive; Null is /dev/null.
1026 // Only a directly inherited fd answers the process check: a
1027 // materialized Stream is always a binding (staged input,
1028 // WITH_IO pipe, or OS half), never the raw fd.
1029 if cx.stdin_pipe.is_some() {
1030 false
1031 } else {
1032 match &cx.stdin {
1033 CommandStdin::Null => false,
1034 #[cfg(not(miri))]
1035 CommandStdin::OsPipe(_) => false,
1036 CommandStdin::Stream(_) => false,
1037 CommandStdin::Inherit => std::io::stdin().is_terminal(),
1038 }
1039 }
1040 }
1041 "stdout" => {
1042 if cx.out_pipe.is_some() {
1043 // WITH_IO script-pipe binding: never a terminal.
1044 false
1045 } else if cx.state.io.stdout().is_some() {
1046 // Staged runner sink: the root tee diverts bytes to the
1047 // sink only, never to real stdout.
1048 false
1049 } else {
1050 match &cx.out {
1051 // Unbound: inherited straight through.
1052 None => std::io::stdout().is_terminal(),
1053 // OS kernel pipe: never a terminal.
1054 #[cfg(not(miri))]
1055 Some(StreamHandle::Os(_)) => false,
1056 // Root tee (transparent: forwards to real stdout when
1057 // unstaged, so terminal-ness survives) versus a genuine
1058 // diversion. WITH_IO bindings never reach here (script
1059 // pipes trip out_pipe, OS pipes trip Os, staged sinks
1060 // trip above). LET-capture cannot reach here either:
1061 // assign_capture installs no sink for a bare NAME(...)
1062 // call, so a direct query always observes the ambient
1063 // routing. The process check answers the session
1064 // question.
1065 Some(StreamHandle::Stream(_)) => std::io::stdout().is_terminal(),
1066 }
1067 }
1068 }
1069 "stderr" => {
1070 if cx.state.io.stderr().is_some() {
1071 // Staged runner sink: diverted, never a terminal.
1072 false
1073 } else {
1074 match &cx.err {
1075 // Unbound: inherited straight through.
1076 None => std::io::stderr().is_terminal(),
1077 // OS kernel pipe: never a terminal.
1078 #[cfg(not(miri))]
1079 Some(StreamHandle::Os(_)) => false,
1080 // Root never tees stderr and LET never captures it,
1081 // so a bound handle here is always a WITH_IO binding.
1082 Some(StreamHandle::Stream(_)) => false,
1083 }
1084 }
1085 }
1086 _ => anyhow::bail!(
1087 // Unreachable through the macro path: the generated
1088 // extractor rejects non-members before the body runs, and
1089 // the static pre-pass rejects bad literals earlier still.
1090 // Kept as a bail (never a panic) for hand-built callers.
1091 "IS_TERMINAL expects \"stdin\", \"stdout\", or \"stderr\", got {stream_name:?}"
1092 ),
1093 };
1094 Ok(Value::bool(terminal))
1095}
1096
1097/// Create a counting semaphore admitting at most `max` concurrent holders.
1098///
1099/// Non-positive maxima bail. The word names a shared backend: every clone
1100/// observes the same count, and admission runs through
1101/// `SEMAPHORE_TRY_ACQUIRE`, never through the `SEMAPHORE_AVAILABLE`
1102/// readout.
1103///
1104/// ```oxdock
1105/// # Mint a semaphore admitting at most two holders.
1106/// IMPORT [STD]
1107/// LET $sem: SEMAPHORE = SEMAPHORE_NEW(2)
1108///
1109/// # A fresh semaphore reports its full cap as available.
1110/// LET $free: INT = SEMAPHORE_AVAILABLE($sem)
1111/// ASSERT_EQ $free 2
1112/// ```
1113///
1114#[oxdock_func(returns = TypeTag::Semaphore)]
1115fn semaphore_new<P: ProcessManager>(
1116 cx: &mut StepCtx<P>,
1117 /// Maximum concurrent holders; must be positive.
1118 max: i64,
1119) -> Result<Value> {
1120 let _ = cx;
1121 if max <= 0 {
1122 return Err(anyhow::anyhow!(
1123 "SEMAPHORE_NEW() requires a positive max, got {max}"
1124 ));
1125 }
1126 Ok(Value::semaphore(max as usize))
1127}
1128
1129/// Attempt one non-blocking acquire, always answering a MAP.
1130///
1131/// `held` is `true` with the permit under the `permit` key, or `false`
1132/// with no `permit` key: branch on `$m.held` directly. The DSL has no
1133/// null, so the absent key is the miss shape. Do not read `$m.permit`
1134/// unless `held`: missing-key access bails strictly.
1135/// Never waits, so no wait can wedge.
1136///
1137/// ```oxdock
1138/// # First acquire holds with a permit to bind.
1139/// IMPORT [STD]
1140/// LET $sem: SEMAPHORE = SEMAPHORE_NEW(1)
1141/// LET $first: MAP<held: BOOL, permit?: PERMIT> = SEMAPHORE_TRY_ACQUIRE($sem)
1142/// ASSERT_EQ $first.held true
1143/// LET $permit: PERMIT = $first.permit
1144///
1145/// # A capped semaphore answers held false with no permit key.
1146/// LET $second: MAP<held: BOOL, permit?: PERMIT> = SEMAPHORE_TRY_ACQUIRE($sem)
1147/// ASSERT_EQ $second.held false
1148/// LET $has_permit: BOOL = HAS_KEY($second, "permit")
1149/// ASSERT_EQ $has_permit false
1150/// ```
1151///
1152#[oxdock_func(returns = TypeTag::Record(&[Field {
1153 name: "held",
1154 ty: TypeTag::Bool,
1155 docs: "`true` with the permit under `permit`, `false` with no `permit` key.",
1156 optional: false,
1157}, Field {
1158 name: "permit",
1159 ty: TypeTag::Permit,
1160 docs: "Permit handle; read only when `held`.",
1161 optional: true,
1162}]))]
1163fn semaphore_try_acquire<P: ProcessManager>(
1164 cx: &mut StepCtx<P>,
1165 /// Semaphore handle from `SEMAPHORE_NEW`.
1166 sem: Arc<SemaphoreState>,
1167) -> Result<Value> {
1168 let _ = cx;
1169 let mut map = BTreeMap::new();
1170 if sem.try_acquire() {
1171 map.insert("held".to_string(), Value::bool(true));
1172 map.insert("permit".to_string(), Value::permit(&sem));
1173 } else {
1174 map.insert("held".to_string(), Value::bool(false));
1175 }
1176 Ok(Value::map(map))
1177}
1178
1179/// Read free permits under the lock, with no mutation.
1180///
1181/// Observability only (audit lines, healthchecks: `active = max - free`).
1182/// Exact at read time and stale the instant the caller acts on it, so it
1183/// must never drive admission: that is `SEMAPHORE_TRY_ACQUIRE`'s job.
1184///
1185/// ```oxdock
1186/// # Hold one permit on a cap of two.
1187/// IMPORT [STD]
1188/// LET $sem: SEMAPHORE = SEMAPHORE_NEW(2)
1189/// LET $acq: MAP<held: BOOL, permit?: PERMIT> = SEMAPHORE_TRY_ACQUIRE($sem)
1190/// ASSERT_EQ $acq.held true
1191///
1192/// # One held permit leaves exactly one free.
1193/// LET $free: INT = SEMAPHORE_AVAILABLE($sem)
1194/// ASSERT_EQ $free 1
1195/// ```
1196///
1197#[oxdock_func(pure, returns = TypeTag::Int)]
1198fn semaphore_available(
1199 /// Semaphore handle from `SEMAPHORE_NEW`.
1200 sem: Arc<SemaphoreState>,
1201) -> Result<Value> {
1202 Ok(Value::int(sem.available() as i64))
1203}
1204
1205/// True when a pipe sits at end of stream: closed with nothing buffered,
1206/// so the next `READ_LINE` would bind `""` via EOF rather than a line.
1207/// Live writers, pinned keepers, and buffered bytes all answer false.
1208/// Never blocks: a reader already blocked stays blocked, so branch on
1209/// `EOF` before reading, not after. OS pairs and unbound handles answer
1210/// best-effort (kernel bytes are invisible there; see `INSPECT`).
1211/// Non-pipe arguments bail at the boundary: the parameter declares
1212/// `PIPE`, so the extractor and the static pass reject them before
1213/// the body runs.
1214///
1215/// ```oxdock
1216/// # Capture two lines, then drain to end of stream with no sentinel line.
1217/// IMPORT [STD]
1218/// LET $cap: PIPE
1219/// WITH_IO [stdout=$cap] {
1220/// ECHO "one"
1221/// ECHO "two"
1222/// }
1223///
1224/// # The loop exits on close, and the count proves both lines drained.
1225/// LET $n: INT = 0
1226/// WHILE !EOF($cap) {
1227/// WITH_IO [stdin=$cap] READ_LINE $line
1228/// $n = $n + 1
1229/// }
1230/// ASSERT_EQ $n 2
1231/// ```
1232///
1233#[oxdock_func(returns = TypeTag::Bool)]
1234fn eof<P: ProcessManager>(
1235 cx: &mut StepCtx<P>,
1236 /// Pipe handle to query for end of stream.
1237 pipe: PipeHandle,
1238) -> Result<Value> {
1239 let info = cx.state.io.inspect_pipe(&pipe);
1240 Ok(Value::bool(info.closed && info.buffered == 0))
1241}
1242
1243fn meta_to_value(meta: &FuncMeta) -> Value {
1244 let mut map = BTreeMap::new();
1245 map.insert("name".to_string(), Value::string(meta.name.clone()));
1246 map.insert("module".to_string(), Value::string(meta.module.clone()));
1247 map.insert(
1248 "kind".to_string(),
1249 Value::string(meta.kind.label().to_string()),
1250 );
1251 let params = match &meta.params {
1252 Some(params) => Value::list(
1253 params
1254 .iter()
1255 .map(|p| {
1256 let mut entry = BTreeMap::new();
1257 entry.insert("name".to_string(), Value::string(p.name.clone()));
1258 entry.insert(
1259 "param_type".to_string(),
1260 Value::string(
1261 p.param_type
1262 .as_ref()
1263 .map(render_structural)
1264 .unwrap_or_default(),
1265 ),
1266 );
1267 entry.insert(
1268 "allowed".to_string(),
1269 Value::string(
1270 p.allowed
1271 .map(|values| values.join(", "))
1272 .unwrap_or_default(),
1273 ),
1274 );
1275 entry.insert("docs".to_string(), Value::string(String::new()));
1276 entry.insert("optional".to_string(), Value::bool(p.optional));
1277 entry.insert(
1278 "options".to_string(),
1279 match p.options {
1280 Some(keys) => Value::list(
1281 keys.iter()
1282 .map(|key| {
1283 let mut option = BTreeMap::new();
1284 option.insert(
1285 "name".to_string(),
1286 Value::string(key.name.to_string()),
1287 );
1288 option.insert(
1289 "value_type".to_string(),
1290 Value::string(render_structural(&key.value)),
1291 );
1292 option.insert(
1293 "required".to_string(),
1294 Value::bool(key.required),
1295 );
1296 option.insert(
1297 "default".to_string(),
1298 Value::string(
1299 key.default.unwrap_or_default().to_string(),
1300 ),
1301 );
1302 Value::map(option)
1303 })
1304 .collect(),
1305 ),
1306 None => Value::string(String::new()),
1307 },
1308 );
1309 Value::map(entry)
1310 })
1311 .collect(),
1312 ),
1313 // Parameterless functions mint an empty LIST, never an empty
1314 // STRING: the `DESCRIBE` return tag promises `LIST<MAP<ANY>>`
1315 // for every entry, and the boundary enforces it.
1316 None => Value::list(Vec::new()),
1317 };
1318 map.insert("params".to_string(), params);
1319 map.insert(
1320 "returns".to_string(),
1321 Value::string(
1322 meta.returns
1323 .as_ref()
1324 .map(render_structural)
1325 .unwrap_or_default(),
1326 ),
1327 );
1328 map.insert("rpn".to_string(), Value::bool(meta.rpn));
1329 map.insert(
1330 "summary".to_string(),
1331 Value::string(meta.summary.to_string()),
1332 );
1333 Value::map(map)
1334}
1335
1336/// One named record schema: a shape host functions produce and scripts
1337/// bind by name (`LET $s: SSH_SESSION_INFO`). Travels with its module
1338/// so schemas register exactly when their producer does.
1339#[derive(Debug, Clone, Copy)]
1340pub struct RecordSchema {
1341 pub name: &'static str,
1342 pub fields: &'static [Field],
1343}
1344
1345/// One host library: functions and types registered under a single module
1346/// name. `Engine::register_module` stages these; runs expose them as
1347/// `MODULE::NAME` calls with `MODULE` provenance on every entry.
1348#[derive(Clone)]
1349pub struct HostModule<P: ProcessManager> {
1350 pub name: String,
1351 pub funcs: Vec<HostRegistration<P>>,
1352 pub types: Vec<&'static TypeDescriptor>,
1353 pub record_schemas: Vec<RecordSchema>,
1354}
1355
1356impl<P: ProcessManager> ExecState<P> {
1357 /// Register one [`HostModule`]: every function becomes callable as
1358 /// `MODULE::NAME`, every type joins the run's name directory.
1359 pub fn register_module(&mut self, module: HostModule<P>) {
1360 for registration in module.funcs {
1361 match registration {
1362 HostRegistration::Stateful { name, meta, func } => {
1363 self.functions.register_host(&module.name, name, meta, func);
1364 }
1365 HostRegistration::Pure { name, meta, func } => {
1366 self.functions
1367 .register_pure_host(&module.name, name, meta, func);
1368 }
1369 }
1370 }
1371 for descriptor in module.types {
1372 self.register_type(descriptor);
1373 }
1374 for schema in module.record_schemas {
1375 self.register_record_schema(schema.name, schema.fields);
1376 }
1377 }
1378
1379 /// All visible functions: natives plus hosts plus current DSL definitions.
1380 pub fn list_functions(&self) -> Vec<FuncMeta> {
1381 let mut out: Vec<FuncMeta> = self.functions.entries_metas().into_iter().collect();
1382 // TODO: Make a "virtual function" and don't hardcode
1383 if !out.iter().any(|m| m.name == KEYWORD_INSPECT) {
1384 out.push(FuncMeta {
1385 name: KEYWORD_INSPECT.to_string(),
1386 module: STD_MODULE_NAME.to_string(),
1387 kind: FuncKind::HostCtx,
1388 params: None,
1389 returns: Some(TypeTag::Map),
1390 rpn: false,
1391 summary: "Inspect a variable binding.",
1392 docs: "INSPECT($var): dedicated AST node taking a variable, not a value.",
1393 });
1394 }
1395 out.sort_by(|a, b| a.name.cmp(&b.name));
1396 out
1397 }
1398
1399 /// Describe one function by name, or `None` when unknown.
1400 pub fn describe_function(&self, name: &str) -> Option<Value> {
1401 if let Some(meta) = self.functions.meta(name) {
1402 return Some(meta_to_value(&meta));
1403 }
1404 // TODO: Make a "virtual function" and don't hardcode
1405 if name == KEYWORD_INSPECT {
1406 return Some(meta_to_value(&FuncMeta {
1407 name: KEYWORD_INSPECT.to_string(),
1408 module: STD_MODULE_NAME.to_string(),
1409 kind: FuncKind::HostCtx,
1410 params: None,
1411 returns: Some(TypeTag::Map),
1412 rpn: false,
1413 summary: "Inspect a variable binding.",
1414 docs: "INSPECT($var): dedicated AST node taking a variable, not a value.",
1415 }));
1416 }
1417 None
1418 }
1419
1420 pub(super) fn clone_native_pure(&self, name: &str) -> Option<PureFn> {
1421 self.functions.clone_pure_fn(name)
1422 }
1423
1424 /// Shared snapshot of every registered pure function for
1425 /// placeholder and host driven expansion. Public so host crates
1426 /// resolve calls through the live registry instead of hardcoding
1427 /// module or function names. Cloning the `Arc` never copies the map.
1428 pub fn pure_function_table(&self) -> Arc<PureTable> {
1429 self.functions.pure_shared()
1430 }
1431
1432 pub(super) fn clone_native_ctx(&self, name: &str) -> Option<NativeFn<P>> {
1433 self.functions.clone_ctx_fn(name)
1434 }
1435
1436 pub(super) fn native_meta(&self, name: &str) -> Option<FuncMeta> {
1437 self.functions.meta(name)
1438 }
1439}
1440
1441#[cfg(test)]
1442mod tests {
1443 use super::*;
1444
1445 #[test]
1446 fn describe_entry_carries_optional_flag() {
1447 // The `optional` key on params entries is the machine-readable
1448 // half of the `?` rendering: pin both values through the same
1449 // builder the runtime serves, not through prose.
1450 let meta = FuncMeta {
1451 name: "T::F".to_string(),
1452 module: "T".to_string(),
1453 kind: FuncKind::HostPure,
1454 params: Some(vec![
1455 FuncParam {
1456 name: "url".to_string(),
1457 param_type: Some(TypeTag::String),
1458 allowed: None,
1459 docs: "",
1460 options: None,
1461 optional: false,
1462 },
1463 FuncParam {
1464 name: "options".to_string(),
1465 param_type: Some(TypeTag::Map),
1466 allowed: None,
1467 docs: "",
1468 options: None,
1469 optional: true,
1470 },
1471 ]),
1472 returns: Some(TypeTag::String),
1473 rpn: false,
1474 summary: "test-only",
1475 docs: "test-only",
1476 };
1477 let value = meta_to_value(&meta);
1478 let map = value.as_map().expect("describe value is a map");
1479 let params = map
1480 .get("params")
1481 .expect("params key")
1482 .as_list()
1483 .expect("params is a list");
1484 assert_eq!(params.len(), 2);
1485 let first = params[0].as_map().expect("entry is a map");
1486 let second = params[1].as_map().expect("entry is a map");
1487 assert_eq!(
1488 first.get("optional").and_then(Value::as_bool),
1489 Some(false),
1490 "required param must read false"
1491 );
1492 assert_eq!(
1493 second.get("optional").and_then(Value::as_bool),
1494 Some(true),
1495 "omittable param must read true"
1496 );
1497 }
1498}