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)]
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.clone()),
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; Bool as 1/0.
644///
645#[oxdock_func(pure, returns = TypeTag::Int)]
646fn int(
647    /// Value to convert to `INT`.
648    #[union(Int, Float, String, Bool)]
649    val: Value,
650) -> Result<Value> {
651    super::args::int_from_value(val)
652}
653
654/// Convert a value to FLOAT.
655///
656/// Parses f64 (accepts int strings), bails on non-finite or non-numeric.
657///
658#[oxdock_func(pure, returns = TypeTag::Float)]
659fn float(
660    /// Value to convert to `FLOAT`.
661    #[union(Float, Int, String)]
662    val: Value,
663) -> Result<Value> {
664    super::args::float_from_value(val)
665}
666
667/// Format a byte count canonically (`500B`, `10KB`, `2MB`, `1GB`,
668/// binary `10KIB` and friends): the inverse of `PARSE_BYTE_COUNT`, so
669/// formatted values reparse exactly. Negative inputs fail.
670///
671/// ```oxdock
672/// # Byte counts render in the largest exact unit.
673/// IMPORT [STD]
674/// LET $pretty: STRING = FORMAT_BYTE_COUNT(1_048_576)
675/// ASSERT_EQ $pretty "1MiB"
676///
677/// # The pair round-trips through the parser.
678/// LET $back: INT = PARSE_BYTE_COUNT($pretty)
679/// ASSERT_EQ $back 1_048_576
680/// ```
681///
682#[oxdock_func(pure, returns = TypeTag::String)]
683fn format_byte_count(
684    /// Byte count to format; negatives fail.
685    bytes: i64,
686) -> Result<Value> {
687    if bytes < 0 {
688        return Err(anyhow::anyhow!(
689            "FORMAT_BYTE_COUNT needs a non-negative byte count, got {bytes}"
690        ));
691    }
692    Ok(Value::string(oxdock_parser::command::format_byte_count(
693        bytes as u64,
694    )))
695}
696
697/// Parse a byte-count token to `INT` bytes.
698///
699/// Bare digits are bytes; suffixes `B`/`KB`/`MB`/`GB`/`TB` scale
700/// decimal and `KIB`/`MIB`/`GIB`/`TIB` binary, in any case. Plain
701/// `INT` values pass through (already bytes); integral finite `FLOAT`
702/// values convert. Pairs with `FORMAT_BYTE_COUNT` for the round trip.
703///
704/// ```oxdock
705/// # Units parse case-insensitively; bare digits are bytes.
706/// IMPORT [STD]
707/// LET $bytes: INT = PARSE_BYTE_COUNT("1Gb")
708/// ASSERT_EQ $bytes 1_000_000_000
709///
710/// # Binary suffixes scale by powers of two.
711/// LET $mebi: INT = PARSE_BYTE_COUNT("2mib")
712/// ASSERT_EQ $mebi 2_097_152
713///
714/// # Digit runs group Rust-literal style.
715/// LET $grouped: INT = PARSE_BYTE_COUNT("1_000_000")
716/// ASSERT_EQ $grouped 1_000_000
717///
718/// # Plain numbers pass through as bytes already.
719/// LET $plain: INT = PARSE_BYTE_COUNT(1_048_576)
720/// ASSERT_EQ $plain 1_048_576
721///
722/// # Bare literals group too.
723/// LET $bare: INT = PARSE_BYTE_COUNT(1_000_000)
724/// ASSERT_EQ $bare 1_000_000
725///
726/// # One optional space separates number from unit.
727/// LET $spaced: INT = PARSE_BYTE_COUNT("1 GB")
728/// ASSERT_EQ $spaced 1_000_000_000
729/// ```
730///
731#[oxdock_func(pure, returns = TypeTag::Int)]
732fn parse_byte_count(
733    /// Byte-count token to parse, or bytes already.
734    #[union(Int, Float, String)]
735    text: Value,
736) -> Result<Value> {
737    if let Some(n) = text.as_i64() {
738        if n < 0 {
739            return Err(anyhow::anyhow!(
740                "PARSE_BYTE_COUNT needs a non-negative byte count, got {n}"
741            ));
742        }
743        return Ok(Value::int(n));
744    }
745    if let Some(f) = text.as_f64() {
746        if f.is_finite() && f.fract() == 0.0 && f >= 0.0 && f <= i64::MAX as f64 {
747            return Ok(Value::int(f as i64));
748        }
749        return Err(anyhow::anyhow!(
750            "PARSE_BYTE_COUNT needs an integral byte count, got {f:?}"
751        ));
752    }
753    let Some(s) = text.as_str() else {
754        return Err(anyhow::anyhow!(
755            "PARSE_BYTE_COUNT needs a token or number, found {text:?}"
756        ));
757    };
758    let n = oxdock_parser::command::parse_byte_count(s)?;
759    let n = i64::try_from(n)
760        .map_err(|_| anyhow::anyhow!("PARSE_BYTE_COUNT out of INT range: {s:?}"))?;
761    Ok(Value::int(n))
762}
763
764/// Format millisecond durations canonically (`500ms`, `10s`, `2m`,
765/// `1h`): the inverse of `PARSE_DURATION`, so formatted values
766/// reparse exactly. Negative inputs fail.
767///
768/// ```oxdock
769/// # Durations render in the largest exact unit.
770/// IMPORT [STD]
771/// LET $pretty: STRING = FORMAT_DURATION(90_000)
772/// ASSERT_EQ $pretty "90s"
773///
774/// # The pair round-trips through the parser.
775/// LET $back: INT = PARSE_DURATION($pretty)
776/// ASSERT_EQ $back 90_000
777/// ```
778///
779#[oxdock_func(pure, returns = TypeTag::String)]
780fn format_duration(
781    /// Milliseconds to format; negatives fail.
782    millis: i64,
783) -> Result<Value> {
784    if millis < 0 {
785        return Err(anyhow::anyhow!(
786            "FORMAT_DURATION needs non-negative milliseconds, got {millis}"
787        ));
788    }
789    Ok(Value::string(oxdock_parser::command::format_duration(
790        &std::time::Duration::from_millis(millis as u64),
791    )))
792}
793
794/// Parse a duration token to `INT` milliseconds.
795///
796/// Suffixes `ms`/`s`/`m`/`h`; a bare number means seconds. Pairs with
797/// `FORMAT_DURATION` for the round trip.
798///
799/// ```oxdock
800/// # A bare number means seconds, like TIMEOUT.
801/// IMPORT [STD]
802/// LET $ms: INT = PARSE_DURATION("2m")
803/// ASSERT_EQ $ms 120_000
804///
805/// # Milliseconds stay exact.
806/// LET $exact: INT = PARSE_DURATION("1500ms")
807/// ASSERT_EQ $exact 1_500
808///
809/// # One optional space separates number from unit.
810/// LET $spaced: INT = PARSE_DURATION("1 h")
811/// ASSERT_EQ $spaced 3_600_000
812/// ```
813///
814#[oxdock_func(pure, returns = TypeTag::Int)]
815fn parse_duration(
816    /// Duration token to parse.
817    text: String,
818) -> Result<Value> {
819    let duration = oxdock_parser::command::parse_duration(&text)?;
820    let millis = i64::try_from(duration.as_millis())
821        .map_err(|_| anyhow::anyhow!("PARSE_DURATION out of INT range: {text:?}"))?;
822    Ok(Value::int(millis))
823}
824
825/// List workspace paths matching a glob pattern.
826///
827/// Sorted, root-relative LIST; empty on no match or `..` escape.
828///
829#[oxdock_func(rpn, returns = TypeTag::ListOf(std::sync::Arc::new(TypeTag::String)))]
830fn glob<P: ProcessManager>(
831    cx: &mut StepCtx<P>,
832    /// Glob pattern matched against workspace paths.
833    #[union(String, Path)]
834    pattern: Value,
835) -> Result<Value> {
836    let text = super::args::string_or_path_text(&pattern)?;
837    super::args::glob_from_value(&[Value::string(text)], cx)
838}
839
840/// Load and parse a TOML file.
841///
842/// Reads a workspace file and parses TOML into a DSL value.
843///
844#[oxdock_func(rpn, returns = TypeTag::MapOf(std::sync::Arc::new(TypeTag::Any)))]
845fn load_toml<P: ProcessManager>(
846    cx: &mut StepCtx<P>,
847    /// Workspace file path to load and parse as TOML.
848    #[union(String, Path)]
849    path: Value,
850) -> Result<Value> {
851    let text = super::args::string_or_path_text(&path)?;
852    super::args::load_toml_from_value(&[Value::string(text)], cx)
853}
854
855/// Load and parse a JSON file.
856///
857/// Reads a workspace file and parses JSON into a DSL value. Returns
858/// `ANY` by design: a top-level array or scalar parses to `LIST` or a
859/// scalar word. `LET` coercion still checks the actual value at
860/// assignment.
861///
862#[oxdock_func(rpn, returns = TypeTag::Any)]
863fn load_json<P: ProcessManager>(
864    cx: &mut StepCtx<P>,
865    /// Workspace file path to load and parse as JSON.
866    #[union(String, Path)]
867    path: Value,
868) -> Result<Value> {
869    let text = super::args::string_or_path_text(&path)?;
870    super::args::load_json_from_value(&[Value::string(text)], cx)
871}
872
873/// Parse TOML text already held in memory.
874///
875/// Uses the same conversion as file loading, so fetch bodies, file
876/// contents, and captured text share one JSON/TOML shape.
877///
878#[oxdock_func(pure, returns = TypeTag::MapOf(std::sync::Arc::new(TypeTag::Any)))]
879fn parse_toml(
880    /// TOML text already held in memory.
881    text: String,
882) -> Result<Value> {
883    super::args::parse_toml_from_value(Value::string(text))
884}
885
886/// Parse JSON text already held in memory.
887///
888/// Uses the same conversion as file loading, so fetch bodies, file
889/// contents, and captured text share one JSON value shape. Returns
890/// `ANY` by design, matching `LOAD_JSON`: a top-level array or scalar
891/// parses to `LIST` or a scalar word. `LET` coercion still checks the
892/// actual value at assignment.
893///
894/// ```oxdock
895/// # Parse in-memory JSON text with the same conversion as file loading.
896/// IMPORT [STD]
897/// LET $body: STRING = "{\"a\": 1}"
898/// LET $doc: ANY = PARSE_JSON($body)
899/// ASSERT_EQ $doc.a 1
900///
901/// # Top-level arrays parse to LIST, which is why the return is ANY.
902/// LET $items: LIST<ANY> = PARSE_JSON("[1, 2]")
903/// ASSERT_EQ $items.0 1
904/// ASSERT_EQ $items.1 2
905/// ```
906///
907#[oxdock_func(pure, returns = TypeTag::Any)]
908fn parse_json(
909    /// JSON text already held in memory.
910    text: String,
911) -> Result<Value> {
912    super::args::parse_json_from_value(Value::string(text))
913}
914
915/// Describe a filesystem entry.
916///
917/// Reports file, dir, symlink (no-follow), or absent. AST-only by design;
918/// there is no RPN arm for filesystem IO.
919///
920#[oxdock_func(returns = TypeTag::String)]
921fn path_type<P: ProcessManager>(
922    cx: &mut StepCtx<P>,
923    /// Workspace path of the entry to describe.
924    #[union(String, Path)]
925    path: Value,
926) -> Result<Value> {
927    let text = super::args::string_or_path_text(&path)?;
928    super::args::path_type_from_value(&[Value::string(text)], cx)
929}
930
931/// Report whether an ordinary file can be created at a path.
932///
933/// Walks up to the nearest existing ancestor, requires it be a
934/// directory, and probes writability by creating and deleting a probe
935/// file, so retry loops never litter. The empty string is false.
936/// AST-only by design, like `PATH_TYPE`: there is no RPN arm for
937/// filesystem IO.
938///
939/// ```oxdock
940/// # An absent nested path is writable when its ancestor is.
941/// IMPORT [STD]
942/// LET $fresh: BOOL = PATH_WRITABLE("probe-check/nested/file.txt")
943/// ASSERT_EQ $fresh true
944///
945/// # The empty string never aliases the working directory.
946/// LET $empty: BOOL = PATH_WRITABLE("")
947/// ASSERT_EQ $empty false
948/// ```
949///
950#[oxdock_func(returns = TypeTag::Bool)]
951fn path_writable<P: ProcessManager>(
952    cx: &mut StepCtx<P>,
953    /// Workspace path to probe for file creation.
954    #[union(String, Path)]
955    path: Value,
956) -> Result<Value> {
957    let text = super::args::string_or_path_text(&path)?;
958    super::args::path_writable_from_value(&[Value::string(text)], cx)
959}
960
961/// Report whether a name resolves to an executable file (#100).
962///
963/// Bare command names search `env:PATH` (`IS_EXEC("tar")` finds the
964/// first executable `tar`, plus `tar.exe`, on `PATH`); spellings
965/// containing a separator check that file directly. True means a real
966/// file with an executable bit on Unix, or a `PATHEXT` extension on
967/// Windows: each `env:PATHEXT` entry is probed in order (default
968/// `.COM;.EXE;.BAT;.CMD`, an explicitly empty value probes nothing). Absolute `PATH` entries resolve through the workspace as
969/// usual, so host probing wants `WORKSPACE SYSTEM` and an inherited
970/// `PATH`; anything unresolvable reads false, never errors. AST-only
971/// by design, like `PATH_TYPE`: there is no RPN arm for filesystem IO.
972///
973/// ```oxdock
974/// # Missing tools read false instead of failing the run.
975/// IMPORT [STD]
976/// LET $missing: BOOL = IS_EXEC("no-such-tool-xyz")
977/// ASSERT_EQ $missing false
978///
979/// # Plain files are not executable on any platform.
980/// WRITE tool.txt payload
981/// LET $plain: BOOL = IS_EXEC("tool.txt")
982/// ASSERT_EQ $plain false
983/// ```
984///
985#[oxdock_func(returns = TypeTag::Bool)]
986fn is_exec<P: ProcessManager>(
987    cx: &mut StepCtx<P>,
988    /// Command name or file path to probe.
989    #[union(String, Path)]
990    name: Value,
991) -> Result<Value> {
992    let text = super::args::string_or_path_text(&name)?;
993    super::args::is_exec_from_value(&[Value::string(text)], cx)
994}
995
996/// Report whether a map holds a key.
997///
998/// Pure MAP probe so scripts can branch on optional fields without
999/// tripping the strict missing-key error.
1000///
1001#[oxdock_func(pure, returns = TypeTag::Bool)]
1002fn has_key(
1003    /// Map to probe.
1004    map: BTreeMap<String, Value>,
1005    /// Key to look up.
1006    key: String,
1007) -> Result<Value> {
1008    super::args::has_key_from_value(Value::map(map), &key)
1009}
1010
1011/// Insert one key into a map.
1012///
1013/// Fails on duplicates so two entries sharing a key fail the run
1014/// instead of silently shadowing each other.
1015///
1016#[oxdock_func(pure, returns = TypeTag::MapOf(std::sync::Arc::new(TypeTag::Any)))]
1017fn map_set(
1018    /// Map to insert into.
1019    map: BTreeMap<String, Value>,
1020    /// Key to insert; duplicates fail.
1021    key: String,
1022    /// Value to store.
1023    value: Value,
1024) -> Result<Value> {
1025    super::args::map_set_from_value(Value::map(map), key, value)
1026}
1027
1028/// `RAND` options, shared by the registration metadata and the
1029/// arity check. One params vector feeds both, so the two can never
1030/// disagree: add a parameter once, here.
1031static RAND_OPTIONS: &[ParamOption] = &[ParamOption {
1032    name: "seed",
1033    value: TypeTag::Int,
1034    required: false,
1035    default: None,
1036}];
1037
1038/// Draw a random FLOAT uniformly from [0, 1), optionally seeded.
1039///
1040/// Impure by design: unseeded calls return different values, so this
1041/// runs on the AST script path only, never as a `{{ }}` placeholder
1042/// call. A seed draws the same value on every run, for deterministic
1043/// fixtures. Scale and shift the draw for wider ranges. Hand-built
1044/// (not `#[oxdock_func]`): the macro marks every param required, and
1045/// only hand-built entries can leave a trailing options MAP omittable,
1046/// so bare `RAND()` fills `{}`.
1047///
1048/// ```oxdock
1049/// # Scale a unit draw into a backoff delay between 1 and 11 seconds.
1050/// IMPORT [STD]
1051/// LET $draw: FLOAT = RAND()
1052/// LET $delay: FLOAT = 1.0 + $draw * 10.0
1053/// IF $delay < 1.0 {
1054///     EXIT 1
1055/// }
1056/// IF $delay >= 11.0 {
1057///     EXIT 1
1058/// }
1059/// ECHO "retrying in {{ $delay }}s"
1060///
1061/// # A seed draws the same value on every run.
1062/// LET $one: FLOAT = RAND({seed: 7})
1063/// LET $two: FLOAT = RAND({seed: 7})
1064/// ASSERT_EQ $one $two
1065/// ```
1066///
1067/// Registration marker for `RAND`, hand-implementing [`OxDockFn`]:
1068/// the `#[oxdock_func]` macro marks every param required, and only a
1069/// hand-built entry can leave the trailing options MAP omittable, so
1070/// bare `RAND()` fills `{}`.
1071pub struct Rand;
1072impl<P: ProcessManager> OxDockFn<P> for Rand {
1073    fn registration() -> HostRegistration<P> {
1074        rand_registration()
1075    }
1076}
1077
1078fn rand_registration<P: ProcessManager>() -> HostRegistration<P> {
1079    // One params vector feeds both the metadata and the arity check,
1080    // so the two can never disagree: add a parameter once, here.
1081    let params = vec![FuncParam {
1082        name: "options".to_string(),
1083        param_type: Some(TypeTag::Map),
1084        allowed: None,
1085        docs: "Draw settings: `seed`. Omittable: a missing options MAP fills `{}`.",
1086        options: Some(RAND_OPTIONS),
1087        optional: true,
1088    }];
1089    let arity = params.len();
1090    let required = required_arity(&params);
1091    let fill_params = params.clone();
1092    let func: NativeFn<P> = Arc::new(move |cx, values| {
1093        let _ = cx;
1094        if values.len() < required || values.len() > arity {
1095            anyhow::bail!(
1096                "RAND() expects {required} to {arity} argument(s), got {}",
1097                values.len()
1098            );
1099        }
1100        let mut values = fill_optional_args(&fill_params, values).into_iter();
1101        let options_value = values.next().expect("arity checked above");
1102        let options_map = match options_value.as_map() {
1103            Some(map) => map.clone(),
1104            None => anyhow::bail!(
1105                "RAND() argument `$options` must be a MAP, got {}",
1106                options_value.type_name()
1107            ),
1108        };
1109        check_options(&options_map, RAND_OPTIONS, "RAND")?;
1110        // `check_options` verified the shape above; the read below
1111        // narrows infallibly after.
1112        let seed = options_map
1113            .get("seed")
1114            .map(|value| value.as_i64().expect("check_options verified INT"));
1115        super::args::rand_float_from_value(seed)
1116    });
1117    HostRegistration::Stateful {
1118        name: "RAND".to_string(),
1119        meta: FuncMeta {
1120            name: "RAND".to_string(),
1121            // Assigned at registration, like the macro's markers.
1122            module: String::new(),
1123            kind: FuncKind::HostCtx,
1124            params: Some(params),
1125            returns: Some(TypeTag::Float),
1126            rpn: false,
1127            summary: "Draw a random FLOAT uniformly from [0, 1), optionally seeded.",
1128            docs: indoc::indoc! {r#"
1129                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 `{}`.
1130
1131                ```oxdock
1132                # Scale a unit draw into a backoff delay between 1 and 11 seconds.
1133                IMPORT [STD]
1134                LET $draw: FLOAT = RAND()
1135                LET $delay: FLOAT = 1.0 + $draw * 10.0
1136                IF $delay < 1.0 {
1137                    EXIT 1
1138                }
1139                IF $delay >= 11.0 {
1140                    EXIT 1
1141                }
1142                ECHO "retrying in {{ $delay }}s"
1143
1144                # A seed draws the same value on every run.
1145                LET $one: FLOAT = RAND({seed: 7})
1146                LET $two: FLOAT = RAND({seed: 7})
1147                ASSERT_EQ $one $two
1148                ```
1149            "#},
1150        },
1151        func,
1152    }
1153}
1154
1155/// Encode a STRING as standard base64.
1156///
1157/// Padded RFC 4648 alphabet, so encoded output pastes into any
1158/// standard decoder. Pairs with `BASE64_DECODE` for the round trip.
1159///
1160/// ```oxdock
1161/// # Encode text to standard base64.
1162/// IMPORT [STD]
1163/// LET $encoded: STRING = BASE64_ENCODE("hello")
1164/// ASSERT_EQ $encoded "aGVsbG8="
1165/// ```
1166///
1167#[oxdock_func(pure, returns = TypeTag::String)]
1168fn base64_encode(
1169    /// Text to encode.
1170    text: String,
1171) -> Result<Value> {
1172    super::args::base64_encode_from_value(Value::string(text))
1173}
1174
1175/// Decode standard base64 to a STRING.
1176///
1177/// Fails naming the input on invalid alphabet characters or
1178/// non-UTF-8 payloads instead of rendering a silent empty. Pairs
1179/// with `BASE64_ENCODE` for the round trip.
1180///
1181/// ```oxdock
1182/// # Decode standard base64 back to text.
1183/// IMPORT [STD]
1184/// LET $decoded: STRING = BASE64_DECODE("aGVsbG8=")
1185/// ASSERT_EQ $decoded "hello"
1186/// ```
1187///
1188#[oxdock_func(pure, returns = TypeTag::String)]
1189fn base64_decode(
1190    /// Base64 text to decode.
1191    text: String,
1192) -> Result<Value> {
1193    super::args::base64_decode_from_value(Value::string(text))
1194}
1195
1196/// Encode a script value as JSON with one trailing newline.
1197///
1198/// Maps stay sorted; only template-safe shapes (STRING, INT, FLOAT,
1199/// BOOL, LIST, MAP) survive, anything else fails here instead of
1200/// rendering as a silent empty.
1201///
1202#[oxdock_func(pure, returns = TypeTag::String)]
1203fn to_json(
1204    /// Value to encode as JSON.
1205    #[union(String, Int, Float, Bool, List, Map)]
1206    value: Value,
1207) -> Result<Value> {
1208    super::args::to_json_from_value(value)
1209}
1210
1211/// Name the word a value holds, for data-driven branching.
1212///
1213/// Returns the registered type word (`STRING`, `INT`, `FLOAT`, `BOOL`,
1214/// `LIST`, `MAP`, plus handle words like `PIPE`): the same name the
1215/// value prints in arity and coercion errors, so scripts can branch
1216/// on config shapes (a path string or a path list) without failing.
1217///
1218#[oxdock_func(pure, returns = TypeTag::String)]
1219fn type_of(
1220    /// Value whose word to name.
1221    value: Value,
1222) -> Result<Value> {
1223    super::args::type_of_from_value(value)
1224}
1225
1226/// Merge a LIST of MAPs in order under one duplicate policy.
1227///
1228/// `fail_on_duplicate` fails naming the repeated key, so two files
1229/// claiming one placeholder fail the run instead of shadowing each
1230/// other. `overwrite` lets later files win, for environment overlays.
1231/// Non MAP elements fail naming their position.
1232///
1233#[oxdock_func(pure, returns = TypeTag::MapOf(std::sync::Arc::new(TypeTag::Any)))]
1234fn merge_maps(
1235    /// LIST of MAPs to merge in order.
1236    maps: Vec<BTreeMap<String, Value>>,
1237    /// Duplicate policy.
1238    #[values("fail_on_duplicate", "overwrite")]
1239    policy: String,
1240) -> Result<Value> {
1241    super::args::merge_maps_from_value(
1242        Value::list(maps.into_iter().map(Value::map).collect()),
1243        policy,
1244    )
1245}
1246
1247/// List all visible function names.
1248///
1249/// Sorted LIST of qualified `MODULE::NAME` entries: DSL-defined plus native
1250/// plus host-registered names.
1251#[oxdock_func(returns = TypeTag::ListOf(std::sync::Arc::new(TypeTag::String)))]
1252fn functions<P: ProcessManager>(cx: &mut StepCtx<P>) -> Result<Value> {
1253    let mut names: Vec<String> = cx
1254        .state
1255        .list_functions()
1256        .into_iter()
1257        .map(|meta| meta.name)
1258        .collect();
1259    names.sort();
1260    names.dedup();
1261    Ok(Value::list(names.into_iter().map(Value::string).collect()))
1262}
1263
1264/// Describe one function by qualified name.
1265///
1266/// Returns a MAP with name, module, kind, params, returns, rpn, and
1267/// summary. `params` is always a LIST (empty for parameterless
1268/// functions) of entries carrying name, param_type, allowed, docs,
1269/// options, and optional flags, so the shape holds for every entry. Bare names
1270/// fail closed: `DESCRIBE` requires the qualified form (except
1271/// `INSPECT`, which is syntax rather than a registry entry). Errors
1272/// on unknown function.
1273///
1274/// Field table for the `DESCRIBE` result bundle: one source for the
1275/// shape the host mints, so introspection, enforcement, and
1276/// documentation cannot drift apart.
1277
1278#[oxdock_func(
1279    returns = TypeTag::Record(std::sync::Arc::from([Field {
1280        name: "name".to_string(),
1281        ty: TypeTag::String,
1282        docs: "Qualified function name.",
1283        optional: false,
1284    }, Field {
1285        name: "module".to_string(),
1286        ty: TypeTag::String,
1287        docs: "Owning module.",
1288        optional: false,
1289    }, Field {
1290        name: "kind".to_string(),
1291        ty: TypeTag::String,
1292        docs: "Origin label (`host` or `script`).",
1293        optional: false,
1294    }, Field {
1295        name: "params".to_string(),
1296        ty: TypeTag::ListOf(std::sync::Arc::new(TypeTag::MapOf(std::sync::Arc::new(
1297            TypeTag::Any,
1298        )))),
1299        docs: "Parameter entries (empty for parameterless functions).",
1300        optional: false,
1301    }, Field {
1302        name: "returns".to_string(),
1303        ty: TypeTag::String,
1304        docs: "Structural return shape (empty when untagged).",
1305        optional: false,
1306    }, Field {
1307        name: "rpn".to_string(),
1308        ty: TypeTag::Bool,
1309        docs: "True when callable in RPN position.",
1310        optional: false,
1311    }, Field {
1312        name: "summary".to_string(),
1313        ty: TypeTag::String,
1314        docs: "One-line description.",
1315        optional: false,
1316    }]))
1317    summary = "Describe one function by qualified name."
1318)]
1319fn describe<P: ProcessManager>(
1320    cx: &mut StepCtx<P>,
1321    /// Qualified function name (`MODULE::NAME`).
1322    name: String,
1323) -> Result<Value> {
1324    if split_qualified(&name).is_none() && name != KEYWORD_INSPECT {
1325        anyhow::bail!(
1326            "unknown function `{name}`: DESCRIBE requires a qualified name (e.g. `STD::{name}`)"
1327        );
1328    }
1329    cx.state
1330        .describe_function(&name)
1331        .ok_or_else(|| anyhow::anyhow!("unknown function {name}"))
1332}
1333
1334/// List all known type names.
1335///
1336/// Sorted LIST of startup plus host-registered type descriptors. Reads the
1337/// run's name directory, so it runs on the AST path like the other
1338/// introspection functions.
1339#[oxdock_func(returns = TypeTag::ListOf(std::sync::Arc::new(TypeTag::String)))]
1340fn types<P: ProcessManager>(cx: &mut StepCtx<P>) -> Result<Value> {
1341    Ok(Value::list(
1342        cx.state
1343            .type_names()
1344            .into_iter()
1345            .map(Value::string)
1346            .collect(),
1347    ))
1348}
1349
1350/// Describe one type by name.
1351///
1352/// Returns a MAP with name, summary, and docs. Errors on unknown type.
1353/// Reads the run's name directory, so it runs on the AST path.
1354///
1355#[oxdock_func(returns = TypeTag::Record(std::sync::Arc::from([Field {
1356    name: "name".to_string(),
1357    ty: TypeTag::String,
1358    docs: "Queried type name.",
1359    optional: false,
1360}, Field {
1361    name: "summary".to_string(),
1362    ty: TypeTag::String,
1363    docs: "One-line description.",
1364    optional: false,
1365}, Field {
1366    name: "docs".to_string(),
1367    ty: TypeTag::String,
1368    docs: "Full documentation text.",
1369    optional: false,
1370}])))]
1371fn type_describe<P: ProcessManager>(
1372    cx: &mut StepCtx<P>,
1373    /// Type name to describe.
1374    name: String,
1375) -> Result<Value> {
1376    if let Some(descriptor) = cx.state.describe_type(&name) {
1377        let mut map = BTreeMap::new();
1378        map.insert(
1379            "name".to_string(),
1380            Value::string(descriptor.name.to_string()),
1381        );
1382        map.insert(
1383            "summary".to_string(),
1384            Value::string(descriptor.summary.to_string()),
1385        );
1386        map.insert(
1387            "docs".to_string(),
1388            Value::string(descriptor.docs.to_string()),
1389        );
1390        return Ok(Value::map(map));
1391    }
1392    // Script aliases have no descriptor but introspect the same way:
1393    // the entry names the alias and its canonical target spelling.
1394    if let Some(target) = cx.state.alias_target(&name) {
1395        let mut map = BTreeMap::new();
1396        map.insert("name".to_string(), Value::string(name.clone()));
1397        map.insert(
1398            "summary".to_string(),
1399            Value::string(format!("Script type alias for {target}.")),
1400        );
1401        map.insert(
1402            "docs".to_string(),
1403            Value::string(format!(
1404                "Declared with TYPE {name} = {target}. The alias expands structurally at every declaration."
1405            )),
1406        );
1407        return Ok(Value::map(map));
1408    }
1409    Err(anyhow::anyhow!("unknown type {name}"))
1410}
1411
1412/// Report whether a standard stream is a terminal.
1413///
1414/// `IS_TERMINAL("stdin")`, `IS_TERMINAL("stdout")`, or `IS_TERMINAL("stderr")`
1415/// answers for the step's stream as currently bound, so scripts can adapt
1416/// prompts, colors, and progress output. Anything diverted from the
1417/// terminal reports false without touching host handles: `WITH_IO` pipe
1418/// bindings (script backends and OS pairs), `LET`-capture sinks, staged
1419/// runner sinks, and any materialized stdin stream (only a directly
1420/// inherited fd falls back to the process check). A transparent root tee
1421/// still answers the session question via the process check. The name
1422/// matches exactly (no case folding): anything else bails. AST-only:
1423/// reads the step context like the other introspection functions.
1424///
1425#[oxdock_func(returns = TypeTag::Bool)]
1426fn is_terminal<P: ProcessManager>(
1427    cx: &mut StepCtx<P>,
1428    /// Stream name: `stdin`, `stdout`, or `stderr` (exact match).
1429    #[values("stdin", "stdout", "stderr")]
1430    stream_name: String,
1431) -> Result<Value> {
1432    use std::io::IsTerminal;
1433    let terminal = match stream_name.as_str() {
1434        "stdin" => {
1435            // A script-pipe backend is definitive; Null is /dev/null.
1436            // Only a directly inherited fd answers the process check: a
1437            // materialized Stream is always a binding (staged input,
1438            // WITH_IO pipe, or OS half), never the raw fd.
1439            if cx.stdin_pipe.is_some() {
1440                false
1441            } else {
1442                match &cx.stdin {
1443                    CommandStdin::Null => false,
1444                    #[cfg(not(miri))]
1445                    CommandStdin::OsPipe(_) => false,
1446                    CommandStdin::Stream(_) => false,
1447                    CommandStdin::Inherit => std::io::stdin().is_terminal(),
1448                }
1449            }
1450        }
1451        "stdout" => {
1452            if cx.out_pipe.is_some() {
1453                // WITH_IO script-pipe binding: never a terminal.
1454                false
1455            } else if cx.state.io.stdout().is_some() {
1456                // Staged runner sink: the root tee diverts bytes to the
1457                // sink only, never to real stdout.
1458                false
1459            } else {
1460                match &cx.out {
1461                    // Unbound: inherited straight through.
1462                    None => std::io::stdout().is_terminal(),
1463                    // OS kernel pipe: never a terminal.
1464                    #[cfg(not(miri))]
1465                    Some(StreamHandle::Os(_)) => false,
1466                    // Root tee (transparent: forwards to real stdout when
1467                    // unstaged, so terminal-ness survives) versus a genuine
1468                    // diversion. WITH_IO bindings never reach here (script
1469                    // pipes trip out_pipe, OS pipes trip Os, staged sinks
1470                    // trip above). LET-capture cannot reach here either:
1471                    // assign_capture installs no sink for a bare NAME(...)
1472                    // call, so a direct query always observes the ambient
1473                    // routing. The process check answers the session
1474                    // question.
1475                    Some(StreamHandle::Stream(_)) => std::io::stdout().is_terminal(),
1476                }
1477            }
1478        }
1479        "stderr" => {
1480            if cx.state.io.stderr().is_some() {
1481                // Staged runner sink: diverted, never a terminal.
1482                false
1483            } else {
1484                match &cx.err {
1485                    // Unbound: inherited straight through.
1486                    None => std::io::stderr().is_terminal(),
1487                    // OS kernel pipe: never a terminal.
1488                    #[cfg(not(miri))]
1489                    Some(StreamHandle::Os(_)) => false,
1490                    // Root never tees stderr and LET never captures it,
1491                    // so a bound handle here is always a WITH_IO binding.
1492                    Some(StreamHandle::Stream(_)) => false,
1493                }
1494            }
1495        }
1496        _ => anyhow::bail!(
1497            // Unreachable through the macro path: the generated
1498            // extractor rejects non-members before the body runs, and
1499            // the static pre-pass rejects bad literals earlier still.
1500            // Kept as a bail (never a panic) for hand-built callers.
1501            "IS_TERMINAL expects \"stdin\", \"stdout\", or \"stderr\", got {stream_name:?}"
1502        ),
1503    };
1504    Ok(Value::bool(terminal))
1505}
1506
1507/// Create a counting semaphore admitting at most `max` concurrent holders.
1508///
1509/// Non-positive maxima bail. The word names a shared backend: every clone
1510/// observes the same count, and admission runs through
1511/// `SEMAPHORE_TRY_ACQUIRE`, never through the `SEMAPHORE_AVAILABLE`
1512/// readout.
1513///
1514/// ```oxdock
1515/// # Mint a semaphore admitting at most two holders.
1516/// IMPORT [STD]
1517/// LET $sem: SEMAPHORE = SEMAPHORE_NEW(2)
1518///
1519/// # A fresh semaphore reports its full cap as available.
1520/// LET $free: INT = SEMAPHORE_AVAILABLE($sem)
1521/// ASSERT_EQ $free 2
1522/// ```
1523///
1524#[oxdock_func(returns = TypeTag::Semaphore)]
1525fn semaphore_new<P: ProcessManager>(
1526    cx: &mut StepCtx<P>,
1527    /// Maximum concurrent holders; must be positive.
1528    max: i64,
1529) -> Result<Value> {
1530    let _ = cx;
1531    if max <= 0 {
1532        return Err(anyhow::anyhow!(
1533            "SEMAPHORE_NEW() requires a positive max, got {max}"
1534        ));
1535    }
1536    Ok(Value::semaphore(max as usize))
1537}
1538
1539/// Attempt one non-blocking acquire, always answering a MAP.
1540///
1541/// `held` is `true` with the permit under the `permit` key, or `false`
1542/// with no `permit` key: branch on `$m.held` directly. The DSL has no
1543/// null, so the absent key is the miss shape. Do not read `$m.permit`
1544/// unless `held`: missing-key access bails strictly.
1545/// Never waits, so no wait can wedge.
1546///
1547/// ```oxdock
1548/// # First acquire holds with a permit to bind.
1549/// IMPORT [STD]
1550/// LET $sem: SEMAPHORE = SEMAPHORE_NEW(1)
1551/// LET $first: MAP<held: BOOL, permit?: PERMIT> = SEMAPHORE_TRY_ACQUIRE($sem)
1552/// ASSERT_EQ $first.held true
1553/// LET $permit: PERMIT = $first.permit
1554///
1555/// # A capped semaphore answers held false with no permit key.
1556/// LET $second: MAP<held: BOOL, permit?: PERMIT> = SEMAPHORE_TRY_ACQUIRE($sem)
1557/// ASSERT_EQ $second.held false
1558/// LET $has_permit: BOOL = HAS_KEY($second, "permit")
1559/// ASSERT_EQ $has_permit false
1560/// ```
1561///
1562#[oxdock_func(returns = TypeTag::Record(std::sync::Arc::from([Field {
1563    name: "held".to_string(),
1564    ty: TypeTag::Bool,
1565    docs: "`true` with the permit under `permit`, `false` with no `permit` key.",
1566    optional: false,
1567}, Field {
1568    name: "permit".to_string(),
1569    ty: TypeTag::Permit,
1570    docs: "Permit handle; read only when `held`.",
1571    optional: true,
1572}])))]
1573fn semaphore_try_acquire<P: ProcessManager>(
1574    cx: &mut StepCtx<P>,
1575    /// Semaphore handle from `SEMAPHORE_NEW`.
1576    sem: Arc<SemaphoreState>,
1577) -> Result<Value> {
1578    let _ = cx;
1579    let mut map = BTreeMap::new();
1580    if sem.try_acquire() {
1581        map.insert("held".to_string(), Value::bool(true));
1582        map.insert("permit".to_string(), Value::permit(&sem));
1583    } else {
1584        map.insert("held".to_string(), Value::bool(false));
1585    }
1586    Ok(Value::map(map))
1587}
1588
1589/// Read free permits under the lock, with no mutation.
1590///
1591/// Observability only (audit lines, healthchecks: `active = max - free`).
1592/// Exact at read time and stale the instant the caller acts on it, so it
1593/// must never drive admission: that is `SEMAPHORE_TRY_ACQUIRE`'s job.
1594///
1595/// ```oxdock
1596/// # Hold one permit on a cap of two.
1597/// IMPORT [STD]
1598/// LET $sem: SEMAPHORE = SEMAPHORE_NEW(2)
1599/// LET $acq: MAP<held: BOOL, permit?: PERMIT> = SEMAPHORE_TRY_ACQUIRE($sem)
1600/// ASSERT_EQ $acq.held true
1601///
1602/// # One held permit leaves exactly one free.
1603/// LET $free: INT = SEMAPHORE_AVAILABLE($sem)
1604/// ASSERT_EQ $free 1
1605/// ```
1606///
1607#[oxdock_func(pure, returns = TypeTag::Int)]
1608fn semaphore_available(
1609    /// Semaphore handle from `SEMAPHORE_NEW`.
1610    sem: Arc<SemaphoreState>,
1611) -> Result<Value> {
1612    Ok(Value::int(sem.available() as i64))
1613}
1614
1615/// True when a pipe sits at end of stream: closed with nothing buffered,
1616/// so the next `READ_LINE` would bind `""` via EOF rather than a line.
1617/// Live writers, pinned keepers, and buffered bytes all answer false.
1618/// Never blocks: a reader already blocked stays blocked, so branch on
1619/// `EOF` before reading, not after. OS pairs and unbound handles answer
1620/// best-effort (kernel bytes are invisible there; see `INSPECT`).
1621/// Non-pipe arguments bail at the boundary: the parameter declares
1622/// `PIPE`, so the extractor and the static pass reject them before
1623/// the body runs.
1624///
1625/// ```oxdock
1626/// # Capture two lines, then drain to end of stream with no sentinel line.
1627/// IMPORT [STD]
1628/// LET $cap: PIPE
1629/// WITH_IO [stdout=$cap] {
1630///     ECHO "one"
1631///     ECHO "two"
1632/// }
1633///
1634/// # The loop exits on close, and the count proves both lines drained.
1635/// LET $n: INT = 0
1636/// WHILE !EOF($cap) {
1637///     WITH_IO [stdin=$cap] READ_LINE $line
1638///     $n = $n + 1
1639/// }
1640/// ASSERT_EQ $n 2
1641/// ```
1642///
1643#[oxdock_func(returns = TypeTag::Bool)]
1644fn eof<P: ProcessManager>(
1645    cx: &mut StepCtx<P>,
1646    /// Pipe handle to query for end of stream.
1647    pipe: PipeHandle,
1648) -> Result<Value> {
1649    let info = cx.state.io.inspect_pipe(&pipe);
1650    Ok(Value::bool(info.closed && info.buffered == 0))
1651}
1652
1653fn meta_to_value(meta: &FuncMeta) -> Value {
1654    let mut map = BTreeMap::new();
1655    map.insert("name".to_string(), Value::string(meta.name.clone()));
1656    map.insert("module".to_string(), Value::string(meta.module.clone()));
1657    map.insert(
1658        "kind".to_string(),
1659        Value::string(meta.kind.label().to_string()),
1660    );
1661    let params = match &meta.params {
1662        Some(params) => Value::list(
1663            params
1664                .iter()
1665                .map(|p| {
1666                    let mut entry = BTreeMap::new();
1667                    entry.insert("name".to_string(), Value::string(p.name.clone()));
1668                    entry.insert(
1669                        "param_type".to_string(),
1670                        Value::string(
1671                            p.param_type
1672                                .as_ref()
1673                                .map(render_structural)
1674                                .unwrap_or_default(),
1675                        ),
1676                    );
1677                    entry.insert(
1678                        "allowed".to_string(),
1679                        Value::string(
1680                            p.allowed
1681                                .map(|values| values.join(", "))
1682                                .unwrap_or_default(),
1683                        ),
1684                    );
1685                    entry.insert("docs".to_string(), Value::string(String::new()));
1686                    entry.insert("optional".to_string(), Value::bool(p.optional));
1687                    entry.insert(
1688                        "options".to_string(),
1689                        match p.options {
1690                            Some(keys) => Value::list(
1691                                keys.iter()
1692                                    .map(|key| {
1693                                        let mut option = BTreeMap::new();
1694                                        option.insert(
1695                                            "name".to_string(),
1696                                            Value::string(key.name.to_string()),
1697                                        );
1698                                        option.insert(
1699                                            "value_type".to_string(),
1700                                            Value::string(render_structural(&key.value)),
1701                                        );
1702                                        option.insert(
1703                                            "required".to_string(),
1704                                            Value::bool(key.required),
1705                                        );
1706                                        option.insert(
1707                                            "default".to_string(),
1708                                            Value::string(
1709                                                key.default.unwrap_or_default().to_string(),
1710                                            ),
1711                                        );
1712                                        Value::map(option)
1713                                    })
1714                                    .collect(),
1715                            ),
1716                            None => Value::string(String::new()),
1717                        },
1718                    );
1719                    Value::map(entry)
1720                })
1721                .collect(),
1722        ),
1723        // Parameterless functions mint an empty LIST, never an empty
1724        // STRING: the `DESCRIBE` return tag promises `LIST<MAP<ANY>>`
1725        // for every entry, and the boundary enforces it.
1726        None => Value::list(Vec::new()),
1727    };
1728    map.insert("params".to_string(), params);
1729    map.insert(
1730        "returns".to_string(),
1731        Value::string(
1732            meta.returns
1733                .as_ref()
1734                .map(render_structural)
1735                .unwrap_or_default(),
1736        ),
1737    );
1738    map.insert("rpn".to_string(), Value::bool(meta.rpn));
1739    map.insert(
1740        "summary".to_string(),
1741        Value::string(meta.summary.to_string()),
1742    );
1743    Value::map(map)
1744}
1745
1746/// One named record schema: a shape host functions produce and scripts
1747/// bind by name (`LET $s: SSH_SESSION_INFO`). Travels with its module
1748/// so schemas register exactly when their producer does.
1749#[derive(Debug, Clone)]
1750pub struct RecordSchema {
1751    pub name: &'static str,
1752    pub fields: std::sync::Arc<[Field]>,
1753}
1754
1755/// One host library: functions and types registered under a single module
1756/// name. `Engine::register_module` stages these; runs expose them as
1757/// `MODULE::NAME` calls with `MODULE` provenance on every entry.
1758#[derive(Clone)]
1759pub struct HostModule<P: ProcessManager> {
1760    pub name: String,
1761    pub funcs: Vec<HostRegistration<P>>,
1762    pub types: Vec<&'static TypeDescriptor>,
1763    pub record_schemas: Vec<RecordSchema>,
1764}
1765
1766impl<P: ProcessManager> ExecState<P> {
1767    /// Register one [`HostModule`]: every function becomes callable as
1768    /// `MODULE::NAME`, every type joins the run's name directory.
1769    pub fn register_module(&mut self, module: HostModule<P>) {
1770        for registration in module.funcs {
1771            match registration {
1772                HostRegistration::Stateful { name, meta, func } => {
1773                    self.functions.register_host(&module.name, name, meta, func);
1774                }
1775                HostRegistration::Pure { name, meta, func } => {
1776                    self.functions
1777                        .register_pure_host(&module.name, name, meta, func);
1778                }
1779            }
1780        }
1781        for descriptor in module.types {
1782            self.register_type(descriptor);
1783        }
1784        for schema in module.record_schemas {
1785            self.register_record_schema(schema.name, schema.fields);
1786        }
1787    }
1788
1789    /// All visible functions: natives plus hosts plus current DSL definitions.
1790    pub fn list_functions(&self) -> Vec<FuncMeta> {
1791        let mut out: Vec<FuncMeta> = self.functions.entries_metas().into_iter().collect();
1792        // TODO: Make a "virtual function" and don't hardcode
1793        if !out.iter().any(|m| m.name == KEYWORD_INSPECT) {
1794            out.push(FuncMeta {
1795                name: KEYWORD_INSPECT.to_string(),
1796                module: STD_MODULE_NAME.to_string(),
1797                kind: FuncKind::HostCtx,
1798                params: None,
1799                returns: Some(TypeTag::Map),
1800                rpn: false,
1801                summary: "Inspect a variable binding.",
1802                docs: "INSPECT($var): dedicated AST node taking a variable, not a value.",
1803            });
1804        }
1805        out.sort_by(|a, b| a.name.cmp(&b.name));
1806        out
1807    }
1808
1809    /// Describe one function by name, or `None` when unknown.
1810    pub fn describe_function(&self, name: &str) -> Option<Value> {
1811        if let Some(meta) = self.functions.meta(name) {
1812            return Some(meta_to_value(&meta));
1813        }
1814        // TODO: Make a "virtual function" and don't hardcode
1815        if name == KEYWORD_INSPECT {
1816            return Some(meta_to_value(&FuncMeta {
1817                name: KEYWORD_INSPECT.to_string(),
1818                module: STD_MODULE_NAME.to_string(),
1819                kind: FuncKind::HostCtx,
1820                params: None,
1821                returns: Some(TypeTag::Map),
1822                rpn: false,
1823                summary: "Inspect a variable binding.",
1824                docs: "INSPECT($var): dedicated AST node taking a variable, not a value.",
1825            }));
1826        }
1827        None
1828    }
1829
1830    pub(super) fn clone_native_pure(&self, name: &str) -> Option<PureFn> {
1831        self.functions.clone_pure_fn(name)
1832    }
1833
1834    /// Shared snapshot of every registered pure function for
1835    /// placeholder and host driven expansion. Public so host crates
1836    /// resolve calls through the live registry instead of hardcoding
1837    /// module or function names. Cloning the `Arc` never copies the map.
1838    pub fn pure_function_table(&self) -> Arc<PureTable> {
1839        self.functions.pure_shared()
1840    }
1841
1842    pub(super) fn clone_native_ctx(&self, name: &str) -> Option<NativeFn<P>> {
1843        self.functions.clone_ctx_fn(name)
1844    }
1845
1846    pub(super) fn native_meta(&self, name: &str) -> Option<FuncMeta> {
1847        self.functions.meta(name)
1848    }
1849}
1850
1851#[cfg(test)]
1852mod tests {
1853    use super::*;
1854
1855    #[test]
1856    fn describe_entry_renders_union_spellings() {
1857        // Union params and returns render through the same structural
1858        // renderer every other tag uses: `DESCRIBE` (and the generated
1859        // reference built on it) names the admission set, never a
1860        // bare word or an empty string. Built by macro, so the
1861        // spelling cannot drift from the members.
1862        let union = oxdock_parser::union_tag!(String, Pipe);
1863        let meta = FuncMeta {
1864            name: "T::F".to_string(),
1865            module: "T".to_string(),
1866            kind: FuncKind::HostPure,
1867            params: Some(vec![FuncParam {
1868                name: "text".to_string(),
1869                param_type: Some(union.clone()),
1870                allowed: None,
1871                docs: "",
1872                options: None,
1873                optional: false,
1874            }]),
1875            returns: Some(union),
1876            rpn: false,
1877            summary: "test-only",
1878            docs: "test-only",
1879        };
1880        let value = meta_to_value(&meta);
1881        let map = value.as_map().expect("describe value is a map");
1882        let params = map
1883            .get("params")
1884            .expect("params key")
1885            .as_list()
1886            .expect("params is a list");
1887        let first = params[0].as_map().expect("entry is a map");
1888        assert_eq!(
1889            first.get("param_type").and_then(Value::as_str),
1890            Some("STRING|PIPE"),
1891            "param renders the set"
1892        );
1893        assert_eq!(
1894            map.get("returns").and_then(Value::as_str),
1895            Some("STRING|PIPE"),
1896            "returns render the set"
1897        );
1898    }
1899
1900    #[test]
1901    fn describe_entry_carries_optional_flag() {
1902        // The `optional` key on params entries is the machine-readable
1903        // half of the `?` rendering: pin both values through the same
1904        // builder the runtime serves, not through prose.
1905        let meta = FuncMeta {
1906            name: "T::F".to_string(),
1907            module: "T".to_string(),
1908            kind: FuncKind::HostPure,
1909            params: Some(vec![
1910                FuncParam {
1911                    name: "url".to_string(),
1912                    param_type: Some(TypeTag::String),
1913                    allowed: None,
1914                    docs: "",
1915                    options: None,
1916                    optional: false,
1917                },
1918                FuncParam {
1919                    name: "options".to_string(),
1920                    param_type: Some(TypeTag::Map),
1921                    allowed: None,
1922                    docs: "",
1923                    options: None,
1924                    optional: true,
1925                },
1926            ]),
1927            returns: Some(TypeTag::String),
1928            rpn: false,
1929            summary: "test-only",
1930            docs: "test-only",
1931        };
1932        let value = meta_to_value(&meta);
1933        let map = value.as_map().expect("describe value is a map");
1934        let params = map
1935            .get("params")
1936            .expect("params key")
1937            .as_list()
1938            .expect("params is a list");
1939        assert_eq!(params.len(), 2);
1940        let first = params[0].as_map().expect("entry is a map");
1941        let second = params[1].as_map().expect("entry is a map");
1942        assert_eq!(
1943            first.get("optional").and_then(Value::as_bool),
1944            Some(false),
1945            "required param must read false"
1946        );
1947        assert_eq!(
1948            second.get("optional").and_then(Value::as_bool),
1949            Some(true),
1950            "omittable param must read true"
1951        );
1952    }
1953}