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