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