Skip to main content

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