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    KEYWORD_INSPECT, SCRIPT_MODULE_NAME, STD_MODULE_NAME, Step, Value, base_name, qualify,
8    split_qualified,
9};
10use oxdock_process::{CommandStdin, DefaultProcessManager, ProcessManager};
11
12use super::io::StreamHandle;
13use super::state::ExecState;
14use super::steps::StepCtx;
15use super::typing::TypeDescriptor;
16
17/// Origin of a callable in the unified function registry. `Script` is an
18/// interpreted `FUNC` body; `HostCtx` and `HostPure` are compiled Rust
19/// functions (the `#[oxdock_func]` host export macro). Builtins and
20/// runtime-registered hosts share the host kinds; only `DESCRIBE` output
21/// shows the label, and both host kinds keep rendering as `host`.
22#[derive(Debug, Clone, Copy, PartialEq, Eq)]
23pub enum FuncKind {
24    Script,
25    HostCtx,
26    HostPure,
27}
28
29impl FuncKind {
30    pub fn label(&self) -> &'static str {
31        match self {
32            FuncKind::Script => "script",
33            FuncKind::HostCtx | FuncKind::HostPure => "host",
34        }
35    }
36}
37
38/// One declared parameter of a registered function. `param_type` is `None`
39/// for unconstrained `Value` parameters (the macro accepts any value).
40#[derive(Debug, Clone)]
41pub struct FuncParam {
42    pub name: String,
43    pub param_type: Option<String>,
44}
45
46/// Introspectable metadata for one function. Single source for
47/// `DESCRIBE(name)` output and the static function reference. `rpn` names
48/// whether the function also runs on the compiled math path (`true` for
49/// pure functions and opted-in stateful ones); everything runs on the AST
50/// path.
51#[derive(Debug, Clone)]
52pub struct FuncMeta {
53    pub name: String,
54    /// Owning module (`STD` for builtins, `SCRIPT` for DSL definitions,
55    /// the host module name otherwise). `name` is always the qualified
56    /// `MODULE::BASE` form, so listings and `DESCRIBE` never lose origin.
57    pub module: String,
58    pub kind: FuncKind,
59    pub params: Option<Vec<FuncParam>>,
60    pub returns: Option<String>,
61    pub rpn: bool,
62    pub summary: &'static str,
63    pub docs: &'static str,
64}
65
66/// Pure scalar function: no filesystem, no scope, no process access.
67/// Usable from both AST evaluation and compiled RPN math.
68pub type PureFn = Arc<dyn Fn(Vec<Value>) -> Result<Value> + Send + Sync>;
69
70/// Stateful/IO function with full step context (fs, cwd, envs, vars, pipes).
71pub type NativeFn<P> = Arc<dyn Fn(&mut StepCtx<P>, Vec<Value>) -> Result<Value> + Send + Sync>;
72
73/// Export hook for a DSL function, implemented by `#[oxdock_func]` on a
74/// registration marker. The engine calls `registration()` and never names
75/// a generated symbol.
76pub trait OxDockFn<P: ProcessManager> {
77    /// The registry entry deriving from the Rust signature plus doc
78    /// comments: name, metadata, and entry point, composed.
79    fn registration() -> HostRegistration<P>;
80}
81
82/// One host-registered function, grouped into a [`HostModule`] and passed
83/// to `Engine::register_module`. Build the entry with the `#[oxdock_func]`-
84/// generated registration marker, or by hand. `Pure` entries run
85/// on both the AST and the compiled RPN math paths; `Stateful` entries run
86/// on the AST path with full step context.
87pub enum HostRegistration<P: ProcessManager> {
88    Stateful {
89        name: String,
90        meta: FuncMeta,
91        func: NativeFn<P>,
92    },
93    Pure {
94        name: String,
95        meta: FuncMeta,
96        func: PureFn,
97    },
98}
99
100// Manual `Clone` (a derive would demand `P: Clone`): entries share their
101// function pointers through the `Arc`s and deep-copy the metadata.
102impl<P: ProcessManager> Clone for HostRegistration<P> {
103    fn clone(&self) -> Self {
104        match self {
105            HostRegistration::Stateful { name, meta, func } => HostRegistration::Stateful {
106                name: name.clone(),
107                meta: meta.clone(),
108                func: Arc::clone(func),
109            },
110            HostRegistration::Pure { name, meta, func } => HostRegistration::Pure {
111                name: name.clone(),
112                meta: meta.clone(),
113                func: Arc::clone(func),
114            },
115        }
116    }
117}
118
119impl<P: ProcessManager> HostRegistration<P> {
120    /// Introspectable metadata for this entry, for documentation tooling
121    /// that reads modules without registering them.
122    pub fn meta(&self) -> &FuncMeta {
123        match self {
124            HostRegistration::Stateful { meta, .. } => meta,
125            HostRegistration::Pure { meta, .. } => meta,
126        }
127    }
128}
129
130/// One user-defined function body (`FUNC NAME($p: TYPE, ...) { ... }`).
131#[derive(Debug, Clone)]
132pub(super) struct FuncDefData {
133    pub(super) params: Vec<(String, String)>,
134    pub(super) body: Vec<Step>,
135}
136
137/// Executable body behind one registry entry: an interpreted script, a
138/// pure scalar function, or a stateful function with step context.
139pub(super) enum FuncBody<P: ProcessManager> {
140    Script(FuncDefData),
141    Pure(PureFn),
142    Ctx(NativeFn<P>),
143}
144
145// Manual `Clone` (a derive would demand `P: Clone`).
146impl<P: ProcessManager> Clone for FuncBody<P> {
147    fn clone(&self) -> Self {
148        match self {
149            FuncBody::Script(def) => FuncBody::Script(def.clone()),
150            FuncBody::Pure(func) => FuncBody::Pure(Arc::clone(func)),
151            FuncBody::Ctx(func) => FuncBody::Ctx(Arc::clone(func)),
152        }
153    }
154}
155
156/// One entry in the unified function registry: introspectable metadata
157/// (mandatory for every entry, backing the pre-evaluation arity gate)
158/// plus the executable body.
159pub(super) struct FuncEntry<P: ProcessManager> {
160    pub(super) meta: FuncMeta,
161    pub(super) body: FuncBody<P>,
162}
163
164// Manual `Clone` (a derive would demand `P: Clone`).
165impl<P: ProcessManager> Clone for FuncEntry<P> {
166    fn clone(&self) -> Self {
167        Self {
168            meta: self.meta.clone(),
169            body: self.body.clone(),
170        }
171    }
172}
173
174/// Names defined in one lexical scope frame: `defined` rejects duplicates
175/// in the same scope, `shadowed` restores outer definitions on exit.
176struct ScopeFrame<P: ProcessManager> {
177    defined: HashSet<String>,
178    shadowed: Vec<(String, FuncEntry<P>)>,
179}
180
181// Manual `Clone` (a derive would demand `P: Clone`).
182impl<P: ProcessManager> Clone for ScopeFrame<P> {
183    fn clone(&self) -> Self {
184        Self {
185            defined: self.defined.clone(),
186            shadowed: self.shadowed.clone(),
187        }
188    }
189}
190
191/// The single function registry: DSL `FUNC` definitions, builtins, and
192/// host extensions share one lookup table, one metadata path, and one
193/// dispatch order. Script entries scope lexically (defined names revert on
194/// scope exit, shadowing an outer definition restores it); native entries
195/// persist for the run. Shared across `fork()` via clone; the entry maps
196/// clone while scope frames stay per state.
197pub struct FunctionRegistry<P: ProcessManager> {
198    entries: HashMap<String, FuncEntry<P>>,
199    scopes: Vec<ScopeFrame<P>>,
200}
201
202impl<P: ProcessManager> FunctionRegistry<P> {
203    pub(super) fn with_builtins() -> Self {
204        let mut reg = Self {
205            entries: HashMap::new(),
206            scopes: vec![ScopeFrame {
207                defined: HashSet::new(),
208                shadowed: Vec::new(),
209            }],
210        };
211        // Every builtin registers through the same `HostRegistration`
212        // entries hosts use: no separate authoring path for engine natives.
213        // Builtins land in the `STD` module, exactly like a host module.
214        for host in Self::builtin_registrations() {
215            match host {
216                HostRegistration::Stateful { name, meta, func } => {
217                    reg.insert_qualified(STD_MODULE_NAME, name, meta, FuncBody::Ctx(func));
218                }
219                HostRegistration::Pure { name, meta, func } => {
220                    reg.insert_qualified(STD_MODULE_NAME, name, meta, FuncBody::Pure(func));
221                }
222            }
223        }
224        reg
225    }
226
227    /// All builtins as host-style registrations, built from the same
228    /// `#[oxdock_func]`-generated markers hosts use. `with_builtins`
229    /// consumes this list, so builtins and hosts share one registration
230    /// pathway instead of two authoring models.
231    pub(super) fn builtin_registrations() -> Vec<HostRegistration<P>> {
232        vec![
233            Int::registration(),
234            Float::registration(),
235            Types::registration(),
236            TypeDescribe::registration(),
237            Glob::registration(),
238            LoadToml::registration(),
239            LoadJson::registration(),
240            PathType::registration(),
241            Functions::registration(),
242            Describe::registration(),
243            IsTerminal::registration(),
244            Eof::registration(),
245            SemaphoreNew::registration(),
246            SemaphoreTryAcquire::registration(),
247            SemaphoreAvailable::registration(),
248        ]
249    }
250
251    /// Every name the registry answers to. Backs parse-time shadow
252    /// validation through `builtin_function_names`.
253    pub(super) fn keys(&self) -> HashSet<String> {
254        self.entries.keys().cloned().collect()
255    }
256
257    /// Single lookup for every callable: script, pure, or stateful.
258    pub(super) fn get(&self, name: &str) -> Option<FuncEntry<P>> {
259        self.entries.get(name).cloned()
260    }
261
262    fn insert_native(&mut self, name: String, meta: FuncMeta, body: FuncBody<P>) {
263        self.entries.insert(name, FuncEntry { meta, body });
264    }
265
266    /// Insert under `MODULE::BASE`, stamping provenance on the metadata.
267    /// The single choke point for every registry entry: builtins pass
268    /// `STD`, hosts pass their module, scripts pass `SCRIPT`.
269    fn insert_qualified(
270        &mut self,
271        module: &str,
272        base: String,
273        mut meta: FuncMeta,
274        body: FuncBody<P>,
275    ) {
276        meta.name = qualify(module, &base);
277        meta.module = module.to_string();
278        // Last-write-wins would silently reroute calls, so a repeated
279        // qualified name is a programmer error, never a shadow: panic like
280        // conflicting type registrations do. `SCRIPT` definitions bypass
281        // this path (`define_script` owns their scoped shadowing).
282        if self.entries.contains_key(&meta.name) {
283            panic!("duplicate function registration `{}`", meta.name);
284        }
285        self.insert_native(meta.name.clone(), meta, body);
286    }
287
288    pub(super) fn register_host(
289        &mut self,
290        module: &str,
291        name: String,
292        mut meta: FuncMeta,
293        func: NativeFn<P>,
294    ) {
295        meta.kind = FuncKind::HostCtx;
296        self.insert_qualified(module, name, meta, FuncBody::Ctx(func));
297    }
298
299    pub(super) fn register_pure_host(
300        &mut self,
301        module: &str,
302        name: String,
303        mut meta: FuncMeta,
304        func: PureFn,
305    ) {
306        meta.kind = FuncKind::HostPure;
307        self.insert_qualified(module, name, meta, FuncBody::Pure(func));
308    }
309
310    /// Define a DSL `FUNC`: names colliding with any known base name cannot
311    /// shadow, same-scope duplicates cannot redefine, and nested shadowing
312    /// of an outer script definition restores on scope exit. Stored as
313    /// `SCRIPT::NAME`, exactly like every other qualified entry.
314    pub(super) fn define_script(
315        &mut self,
316        name: &str,
317        params: &[(String, String)],
318        body: &[Step],
319    ) -> Result<()> {
320        let qualified = qualify(SCRIPT_MODULE_NAME, name);
321        let shadowable = matches!(
322            self.entries.get(&qualified).map(|entry| &entry.body),
323            Some(FuncBody::Script(_))
324        );
325        // Reserved spans every module: compare base names so the message
326        // keeps naming the bare script identifier.
327        let reserved = self
328            .entries
329            .keys()
330            .any(|key| split_qualified(key).is_some_and(|(_, base)| base == name));
331        if reserved && !shadowable {
332            anyhow::bail!("cannot shadow reserved function `{name}`");
333        }
334        if self
335            .scopes
336            .last()
337            .is_some_and(|frame| frame.defined.contains(&qualified))
338        {
339            anyhow::bail!("duplicate function `{name}` in same scope");
340        }
341        let old = self.entries.insert(
342            qualified.clone(),
343            FuncEntry {
344                meta: FuncMeta {
345                    name: qualified.clone(),
346                    module: SCRIPT_MODULE_NAME.to_string(),
347                    kind: FuncKind::Script,
348                    params: Some(
349                        params
350                            .iter()
351                            .map(|(name, param_type)| FuncParam {
352                                name: name.clone(),
353                                param_type: Some(param_type.clone()),
354                            })
355                            .collect(),
356                    ),
357                    returns: None,
358                    rpn: false,
359                    summary: "DSL-defined function.",
360                    docs: "Defined via FUNC in script.",
361                },
362                body: FuncBody::Script(FuncDefData {
363                    params: params.to_vec(),
364                    body: body.to_vec(),
365                }),
366            },
367        );
368        if let Some(frame) = self.scopes.last_mut() {
369            frame.defined.insert(qualified.clone());
370            if let Some(old) = old {
371                frame.shadowed.push((qualified, old));
372            }
373        }
374        Ok(())
375    }
376
377    /// Open a lexical scope frame for script definitions. Native entries
378    /// persist; only script names track here.
379    pub(super) fn push_scope(&mut self) {
380        self.scopes.push(ScopeFrame {
381            defined: HashSet::new(),
382            shadowed: Vec::new(),
383        });
384    }
385
386    /// Close a lexical scope frame: names defined inside revert, and any
387    /// outer definition they shadowed is restored.
388    pub(super) fn pop_scope(&mut self) {
389        let Some(frame) = self.scopes.pop() else {
390            return;
391        };
392        for name in frame.defined {
393            self.entries.remove(&name);
394        }
395        for (name, old) in frame.shadowed {
396            self.entries.insert(name, old);
397        }
398    }
399
400    /// True when `name` is an interpreted script definition (needing call
401    /// scoping and depth budgeting through `call_func_value` rather than
402    /// inline evaluation).
403    pub(super) fn contains_script(&self, name: &str) -> bool {
404        matches!(
405            self.entries.get(name).map(|entry| &entry.body),
406            Some(FuncBody::Script(_))
407        )
408    }
409
410    /// Clone the pure fn for `name` (ending the registry borrow) so callers
411    /// can invoke it without holding `&self` across a `&mut StepCtx` use.
412    fn clone_pure_fn(&self, name: &str) -> Option<PureFn> {
413        match self.entries.get(name)?.body {
414            FuncBody::Pure(ref func) => Some(Arc::clone(func)),
415            _ => None,
416        }
417    }
418
419    /// Clone the ctx fn for `name` (ending the registry borrow) so callers
420    /// can invoke it with `&mut StepCtx` without double-borrowing state.
421    fn clone_ctx_fn(&self, name: &str) -> Option<NativeFn<P>> {
422        match self.entries.get(name)?.body {
423            FuncBody::Ctx(ref func) => Some(Arc::clone(func)),
424            _ => None,
425        }
426    }
427
428    fn meta(&self, name: &str) -> Option<FuncMeta> {
429        self.entries.get(name).map(|entry| entry.meta.clone())
430    }
431
432    fn native_metas(&self) -> Vec<FuncMeta> {
433        let mut out: Vec<FuncMeta> = Vec::new();
434        for entry in self.entries.values() {
435            if !matches!(entry.body, FuncBody::Script(_)) {
436                out.push(entry.meta.clone());
437            }
438        }
439        out.sort_by(|a, b| a.name.cmp(&b.name));
440        out
441    }
442
443    /// Every entry's metadata, scripts included, sorted by name. Backs
444    /// runtime `FUNCTIONS()` listings.
445    fn entries_metas(&self) -> Vec<FuncMeta> {
446        let mut out: Vec<FuncMeta> = self
447            .entries
448            .values()
449            .map(|entry| entry.meta.clone())
450            .collect();
451        out.sort_by(|a, b| a.name.cmp(&b.name));
452        out
453    }
454}
455
456impl<P: ProcessManager> Clone for FunctionRegistry<P> {
457    fn clone(&self) -> Self {
458        Self {
459            entries: self.entries.clone(),
460            scopes: self.scopes.clone(),
461        }
462    }
463}
464
465/// Names of all compiled-in builtins plus `INSPECT` (a dedicated AST/RPN
466/// node, not a registry entry). Read straight off a stock registry, so the
467/// `#[oxdock_func]` annotations stay the single source of truth: adding a
468/// builtin extends this set with no parallel list to update. Seeds
469/// parse-time shadow validation, so the parser crate keeps zero
470/// compile-time knowledge of builtin names.
471pub fn builtin_function_names() -> HashSet<String> {
472    let mut names = FunctionRegistry::<DefaultProcessManager>::with_builtins().keys();
473    names.insert(KEYWORD_INSPECT.to_string());
474    names
475}
476
477/// Metadata of every builtin function, sorted by name, for static
478/// rendering (docs-gen). Same single source as `builtin_function_names`:
479/// the `#[oxdock_func]` annotations, never a parallel list.
480pub fn builtin_function_metas() -> Vec<FuncMeta> {
481    FunctionRegistry::<DefaultProcessManager>::with_builtins().native_metas()
482}
483
484/// Stock `STD` module table derived from the `#[oxdock_func]` builtins:
485/// the single source of truth for builtin membership and RPN eligibility.
486/// Seeds parse-time module resolution, so the parser crate keeps zero
487/// compile-time knowledge of builtin names.
488pub fn std_module_table() -> oxdock_parser::ModuleTable {
489    // Registry names are qualified (`STD::GLOB`); the table holds bases.
490    let functions: HashSet<String> = builtin_function_metas()
491        .into_iter()
492        .map(|meta| base_name(&meta.name).to_string())
493        .collect();
494    oxdock_parser::ModuleTable {
495        modules: HashMap::from([(
496            STD_MODULE_NAME.to_string(),
497            Some(oxdock_parser::ModuleFuncs { functions }),
498        )]),
499    }
500}
501
502// Builtins below use the `#[oxdock_func]` host export macro, the exact same authoring
503// model as host-registered functions: metadata, arity checks, and argument
504// unpacking derive from the signature plus doc comments, so adding a native
505// means writing one small typed function plus one line each in
506// `builtin_registrations` (consumed by `with_builtins`) and the
507// `FUNCTIONS`/`DESCRIBE`/`TYPES` surface, which all read the same symbols.
508
509/// Convert a value to INT.
510///
511/// Trims ASCII whitespace and parses i64. Passes Int through; Float only
512/// when integral and finite.
513#[oxdock_func(pure, returns = "INT")]
514fn int(val: Value) -> Result<Value> {
515    super::args::int_from_value(val)
516}
517
518/// Convert a value to FLOAT.
519///
520/// Parses f64 (accepts int strings), bails on non-finite or non-numeric.
521#[oxdock_func(pure, returns = "FLOAT")]
522fn float(val: Value) -> Result<Value> {
523    super::args::float_from_value(val)
524}
525
526/// List workspace paths matching a glob pattern.
527///
528/// Sorted, root-relative LIST; empty on no match or `..` escape.
529#[oxdock_func(rpn, returns = "LIST")]
530fn glob<P: ProcessManager>(cx: &mut StepCtx<P>, pattern: String) -> Result<Value> {
531    super::args::glob_from_value(&[Value::string(pattern)], cx)
532}
533
534/// Load and parse a TOML file.
535///
536/// Reads a workspace file and parses TOML into a DSL value.
537#[oxdock_func(rpn, returns = "MAP")]
538fn load_toml<P: ProcessManager>(cx: &mut StepCtx<P>, path: String) -> Result<Value> {
539    super::args::load_toml_from_value(&[Value::string(path)], cx)
540}
541
542/// Load and parse a JSON file.
543///
544/// Reads a workspace file and parses JSON into a DSL value.
545#[oxdock_func(rpn, returns = "MAP")]
546fn load_json<P: ProcessManager>(cx: &mut StepCtx<P>, path: String) -> Result<Value> {
547    super::args::load_json_from_value(&[Value::string(path)], cx)
548}
549
550/// Describe a filesystem entry.
551///
552/// Reports file, dir, symlink (no-follow), or absent. AST-only by design;
553/// there is no RPN arm for filesystem IO.
554#[oxdock_func(returns = "STRING")]
555fn path_type<P: ProcessManager>(cx: &mut StepCtx<P>, path: String) -> Result<Value> {
556    super::args::path_type_from_value(&[Value::string(path)], cx)
557}
558
559/// List all visible function names.
560///
561/// Sorted LIST of qualified `MODULE::NAME` entries: DSL-defined plus native
562/// plus host-registered names.
563#[oxdock_func(returns = "LIST")]
564fn functions<P: ProcessManager>(cx: &mut StepCtx<P>) -> Result<Value> {
565    let mut names: Vec<String> = cx
566        .state
567        .list_functions()
568        .into_iter()
569        .map(|meta| meta.name)
570        .collect();
571    names.sort();
572    names.dedup();
573    Ok(Value::list(names.into_iter().map(Value::string).collect()))
574}
575
576/// Describe one function by qualified name.
577///
578/// Returns a MAP with name, module, kind, params, returns, and summary.
579/// Bare names fail closed: `DESCRIBE` requires the qualified form (except
580/// `INSPECT`, which is syntax rather than a registry entry). Errors on
581/// unknown function.
582#[oxdock_func(returns = "MAP")]
583fn describe<P: ProcessManager>(cx: &mut StepCtx<P>, name: String) -> Result<Value> {
584    if split_qualified(&name).is_none() && name != KEYWORD_INSPECT {
585        anyhow::bail!(
586            "unknown function `{name}`: DESCRIBE requires a qualified name (e.g. `STD::{name}`)"
587        );
588    }
589    cx.state
590        .describe_function(&name)
591        .ok_or_else(|| anyhow::anyhow!("unknown function {name}"))
592}
593
594/// List all known type names.
595///
596/// Sorted LIST of startup plus host-registered type descriptors. Reads the
597/// run's name directory, so it runs on the AST path like the other
598/// introspection functions.
599#[oxdock_func(returns = "LIST")]
600fn types<P: ProcessManager>(cx: &mut StepCtx<P>) -> Result<Value> {
601    Ok(Value::list(
602        cx.state
603            .type_names()
604            .into_iter()
605            .map(Value::string)
606            .collect(),
607    ))
608}
609
610/// Describe one type by name.
611///
612/// Returns a MAP with name, summary, and docs. Errors on unknown type.
613/// Reads the run's name directory, so it runs on the AST path.
614#[oxdock_func(returns = "MAP")]
615fn type_describe<P: ProcessManager>(cx: &mut StepCtx<P>, name: String) -> Result<Value> {
616    cx.state
617        .describe_type(&name)
618        .map(|descriptor| {
619            let mut map = BTreeMap::new();
620            map.insert(
621                "name".to_string(),
622                Value::string(descriptor.name.to_string()),
623            );
624            map.insert(
625                "summary".to_string(),
626                Value::string(descriptor.summary.to_string()),
627            );
628            map.insert(
629                "docs".to_string(),
630                Value::string(descriptor.docs.to_string()),
631            );
632            Value::map(map)
633        })
634        .ok_or_else(|| anyhow::anyhow!("unknown type {name}"))
635}
636
637/// Report whether a standard stream is a terminal.
638///
639/// `IS_TERMINAL("stdin")`, `IS_TERMINAL("stdout")`, or `IS_TERMINAL("stderr")`
640/// answers for the step's stream as currently bound, so scripts can adapt
641/// prompts, colors, and progress output. Anything diverted from the
642/// terminal reports false without touching host handles: `WITH_IO` pipe
643/// bindings (script backends and OS pairs), `LET`-capture sinks, staged
644/// runner sinks, and any materialized stdin stream (only a directly
645/// inherited fd falls back to the process check). A transparent root tee
646/// still answers the session question via the process check. The name
647/// matches exactly (no case folding): anything else bails. AST-only:
648/// reads the step context like the other introspection functions.
649#[oxdock_func(returns = "BOOL")]
650fn is_terminal<P: ProcessManager>(cx: &mut StepCtx<P>, stream: String) -> Result<Value> {
651    use std::io::IsTerminal;
652    let terminal = match stream.as_str() {
653        "stdin" => {
654            // A script-pipe backend is definitive; Null is /dev/null.
655            // Only a directly inherited fd answers the process check: a
656            // materialized Stream is always a binding (staged input,
657            // WITH_IO pipe, or OS half), never the raw fd.
658            if cx.stdin_pipe.is_some() {
659                false
660            } else {
661                match &cx.stdin {
662                    CommandStdin::Null => false,
663                    #[cfg(not(miri))]
664                    CommandStdin::OsPipe(_) => false,
665                    CommandStdin::Stream(_) => false,
666                    CommandStdin::Inherit => std::io::stdin().is_terminal(),
667                }
668            }
669        }
670        "stdout" => {
671            if cx.out_pipe.is_some() {
672                // WITH_IO script-pipe binding: never a terminal.
673                false
674            } else if cx.state.io.stdout().is_some() {
675                // Staged runner sink: the root tee diverts bytes to the
676                // sink only, never to real stdout.
677                false
678            } else {
679                match &cx.out {
680                    // Unbound: inherited straight through.
681                    None => std::io::stdout().is_terminal(),
682                    // OS kernel pipe: never a terminal.
683                    #[cfg(not(miri))]
684                    Some(StreamHandle::Os(_)) => false,
685                    // Root tee (transparent: forwards to real stdout when
686                    // unstaged, so terminal-ness survives) versus a genuine
687                    // diversion. WITH_IO bindings never reach here (script
688                    // pipes trip out_pipe, OS pipes trip Os, staged sinks
689                    // trip above). LET-capture cannot reach here either:
690                    // assign_capture installs no sink for a bare NAME(...)
691                    // call, so a direct query always observes the ambient
692                    // routing. The process check answers the session
693                    // question.
694                    Some(StreamHandle::Stream(_)) => std::io::stdout().is_terminal(),
695                }
696            }
697        }
698        "stderr" => {
699            if cx.state.io.stderr().is_some() {
700                // Staged runner sink: diverted, never a terminal.
701                false
702            } else {
703                match &cx.err {
704                    // Unbound: inherited straight through.
705                    None => std::io::stderr().is_terminal(),
706                    // OS kernel pipe: never a terminal.
707                    #[cfg(not(miri))]
708                    Some(StreamHandle::Os(_)) => false,
709                    // Root never tees stderr and LET never captures it,
710                    // so a bound handle here is always a WITH_IO binding.
711                    Some(StreamHandle::Stream(_)) => false,
712                }
713            }
714        }
715        _ => anyhow::bail!(
716            "IS_TERMINAL expects \"stdin\", \"stdout\", or \"stderr\", got {stream:?}"
717        ),
718    };
719    Ok(Value::bool(terminal))
720}
721
722/// Create a counting semaphore admitting at most `max` concurrent holders.
723///
724/// Non-positive maxima bail. The word names a shared backend: every clone
725/// observes the same count, and admission runs through
726/// `SEMAPHORE_TRY_ACQUIRE`, never through the `SEMAPHORE_AVAILABLE`
727/// readout.
728///
729/// ```text
730/// LET $sem: SEMAPHORE = SEMAPHORE_NEW(10)
731/// ```
732#[oxdock_func(returns = "SEMAPHORE")]
733fn semaphore_new<P: ProcessManager>(cx: &mut StepCtx<P>, max: i64) -> Result<Value> {
734    let _ = cx;
735    if max <= 0 {
736        return Err(anyhow::anyhow!(
737            "SEMAPHORE_NEW() requires a positive max, got {max}"
738        ));
739    }
740    Ok(Value::semaphore(max as usize))
741}
742
743/// Attempt one non-blocking acquire, always answering a MAP.
744///
745/// `held` is `1` with the permit under the `permit` key, or `0` with no
746/// `permit` key: branch on `$m.held == 1` (an INT compare; bare `IF $m.held`
747/// is a Type Error). The DSL has no null, so the absent key is the miss
748/// shape. Do not read `$m.permit` unless `held == 1`: missing-key access
749/// bails strictly.
750/// Never waits, so no wait can wedge.
751///
752/// ```text
753/// LET $acq: MAP = SEMAPHORE_TRY_ACQUIRE($sem)
754/// IF $acq.held == 0 {
755///   ECHO "at cap, rejecting"
756/// } ELSE {
757///   LET $permit: PERMIT = $acq.permit
758///   ASYNC { session work }
759/// }
760/// ```
761#[oxdock_func(returns = "MAP")]
762fn semaphore_try_acquire<P: ProcessManager>(cx: &mut StepCtx<P>, sem: Value) -> Result<Value> {
763    let _ = cx;
764    let Some(sem) = sem.as_semaphore() else {
765        return Err(anyhow::anyhow!(
766            "SEMAPHORE_TRY_ACQUIRE() argument `$sem` must be a SEMAPHORE, got {}",
767            sem.type_name(),
768        ));
769    };
770    let mut map = BTreeMap::new();
771    if sem.try_acquire() {
772        map.insert("held".to_string(), Value::int(1));
773        map.insert("permit".to_string(), Value::permit(&sem));
774    } else {
775        map.insert("held".to_string(), Value::int(0));
776    }
777    Ok(Value::map(map))
778}
779
780/// Read free permits under the lock, with no mutation.
781///
782/// Observability only (audit lines, healthchecks: `active = max - free`).
783/// Exact at read time and stale the instant the caller acts on it, so it
784/// must never drive admission: that is `SEMAPHORE_TRY_ACQUIRE`'s job.
785///
786/// ```text
787/// LET $free: INT = SEMAPHORE_AVAILABLE($sem)
788/// ```
789#[oxdock_func(pure, returns = "INT")]
790fn semaphore_available(sem: Value) -> Result<Value> {
791    let Some(sem) = sem.as_semaphore() else {
792        return Err(anyhow::anyhow!(
793            "SEMAPHORE_AVAILABLE() argument `$sem` must be a SEMAPHORE, got {}",
794            sem.type_name(),
795        ));
796    };
797    Ok(Value::int(sem.available() as i64))
798}
799
800/// True when a pipe sits at end of stream: closed with nothing buffered,
801/// so the next `READ_LINE` would bind `""` via EOF rather than a line.
802/// Live writers, pinned keepers, and buffered bytes all answer false.
803/// Never blocks: a reader already blocked stays blocked, so branch on
804/// `EOF` before reading, not after. OS pairs and unbound handles answer
805/// best-effort (kernel bytes are invisible there; see `INSPECT`).
806/// Non-pipe arguments bail.
807///
808/// ```oxdock
809/// # Capture two lines, then drain to end of stream with no sentinel line.
810/// IMPORT [STD]
811/// LET $cap: PIPE
812/// WITH_IO [stdout=$cap] {
813///     ECHO "one"
814///     ECHO "two"
815/// }
816///
817/// # The loop exits on close, and the count proves both lines drained.
818/// LET $n: INT = 0
819/// WHILE !EOF($cap) {
820///     WITH_IO [stdin=$cap] READ_LINE $line
821///     $n = $n + 1
822/// }
823/// ASSERT_EQ $n 2
824/// ```
825#[oxdock_func(returns = "BOOL")]
826fn eof<P: ProcessManager>(cx: &mut StepCtx<P>, pipe: Value) -> Result<Value> {
827    let Some(handle) = pipe.as_pipe_handle() else {
828        return Err(anyhow::anyhow!(
829            "EOF() argument `$pipe` must be a PIPE, got {}",
830            pipe.type_name(),
831        ));
832    };
833    let info = cx.state.io.inspect_pipe(&handle);
834    Ok(Value::bool(info.closed && info.buffered == 0))
835}
836
837fn meta_to_value(meta: &FuncMeta) -> Value {
838    let mut map = BTreeMap::new();
839    map.insert("name".to_string(), Value::string(meta.name.clone()));
840    map.insert("module".to_string(), Value::string(meta.module.clone()));
841    map.insert(
842        "kind".to_string(),
843        Value::string(meta.kind.label().to_string()),
844    );
845    let params = match &meta.params {
846        Some(params) => Value::list(
847            params
848                .iter()
849                .map(|p| {
850                    let mut entry = BTreeMap::new();
851                    entry.insert("name".to_string(), Value::string(p.name.clone()));
852                    entry.insert(
853                        "param_type".to_string(),
854                        Value::string(p.param_type.clone().unwrap_or_default()),
855                    );
856                    Value::map(entry)
857                })
858                .collect(),
859        ),
860        None => Value::string(String::new()),
861    };
862    map.insert("params".to_string(), params);
863    map.insert(
864        "returns".to_string(),
865        Value::string(meta.returns.clone().unwrap_or_default()),
866    );
867    map.insert("rpn".to_string(), Value::bool(meta.rpn));
868    map.insert(
869        "summary".to_string(),
870        Value::string(meta.summary.to_string()),
871    );
872    Value::map(map)
873}
874
875/// One host library: functions and types registered under a single module
876/// name. `Engine::register_module` stages these; runs expose them as
877/// `MODULE::NAME` calls with `MODULE` provenance on every entry.
878#[derive(Clone)]
879pub struct HostModule<P: ProcessManager> {
880    pub name: String,
881    pub funcs: Vec<HostRegistration<P>>,
882    pub types: Vec<&'static TypeDescriptor>,
883}
884
885impl<P: ProcessManager> ExecState<P> {
886    /// Register one [`HostModule`]: every function becomes callable as
887    /// `MODULE::NAME`, every type joins the run's name directory.
888    pub fn register_module(&mut self, module: HostModule<P>) {
889        for registration in module.funcs {
890            match registration {
891                HostRegistration::Stateful { name, meta, func } => {
892                    self.functions.register_host(&module.name, name, meta, func);
893                }
894                HostRegistration::Pure { name, meta, func } => {
895                    self.functions
896                        .register_pure_host(&module.name, name, meta, func);
897                }
898            }
899        }
900        for descriptor in module.types {
901            self.register_type(descriptor);
902        }
903    }
904
905    /// All visible functions: natives plus hosts plus current DSL definitions.
906    pub fn list_functions(&self) -> Vec<FuncMeta> {
907        let mut out: Vec<FuncMeta> = self.functions.entries_metas().into_iter().collect();
908        // TODO: Make a "virtual function" and don't hardcode
909        if !out.iter().any(|m| m.name == KEYWORD_INSPECT) {
910            out.push(FuncMeta {
911                name: KEYWORD_INSPECT.to_string(),
912                module: STD_MODULE_NAME.to_string(),
913                kind: FuncKind::HostCtx,
914                params: None,
915                returns: Some("MAP".to_string()),
916                rpn: false,
917                summary: "Inspect a variable binding.",
918                docs: "INSPECT($var): dedicated AST node taking a variable, not a value.",
919            });
920        }
921        out.sort_by(|a, b| a.name.cmp(&b.name));
922        out
923    }
924
925    /// Describe one function by name, or `None` when unknown.
926    pub fn describe_function(&self, name: &str) -> Option<Value> {
927        if let Some(meta) = self.functions.meta(name) {
928            return Some(meta_to_value(&meta));
929        }
930        // TODO: Make a "virtual function" and don't hardcode
931        if name == KEYWORD_INSPECT {
932            return Some(meta_to_value(&FuncMeta {
933                name: KEYWORD_INSPECT.to_string(),
934                module: STD_MODULE_NAME.to_string(),
935                kind: FuncKind::HostCtx,
936                params: None,
937                returns: Some("MAP".to_string()),
938                rpn: false,
939                summary: "Inspect a variable binding.",
940                docs: "INSPECT($var): dedicated AST node taking a variable, not a value.",
941            }));
942        }
943        None
944    }
945
946    pub(super) fn clone_native_pure(&self, name: &str) -> Option<PureFn> {
947        self.functions.clone_pure_fn(name)
948    }
949
950    pub(super) fn clone_native_ctx(&self, name: &str) -> Option<NativeFn<P>> {
951        self.functions.clone_ctx_fn(name)
952    }
953
954    pub(super) fn native_meta(&self, name: &str) -> Option<FuncMeta> {
955        self.functions.meta(name)
956    }
957}