oxdock-core 0.16.0-alpha

Core engine for OxDock's Dockerfile-inspired compile-time DSL, orchestrating workspace snapshots and asset embedding.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
use std::collections::{BTreeMap, HashMap, HashSet};
use std::sync::Arc;

use anyhow::Result;
use oxdock_func_macro::oxdock_func;
use oxdock_parser::{
    KEYWORD_INSPECT, SCRIPT_MODULE_NAME, STD_MODULE_NAME, Step, Value, base_name, qualify,
    split_qualified,
};
use oxdock_process::{DefaultProcessManager, ProcessManager};

use super::state::ExecState;
use super::steps::StepCtx;
use super::typing::TypeDescriptor;

/// Origin of a callable in the unified function registry. `Script` is an
/// interpreted `FUNC` body; `HostCtx` and `HostPure` are compiled Rust
/// functions (the `#[oxdock_func]` host export macro). Builtins and
/// runtime-registered hosts share the host kinds; only `DESCRIBE` output
/// shows the label, and both host kinds keep rendering as `host`.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum FuncKind {
    Script,
    HostCtx,
    HostPure,
}

impl FuncKind {
    pub fn label(&self) -> &'static str {
        match self {
            FuncKind::Script => "script",
            FuncKind::HostCtx | FuncKind::HostPure => "host",
        }
    }
}

/// One declared parameter of a registered function. `param_type` is `None`
/// for unconstrained `Value` parameters (the macro accepts any value).
#[derive(Debug, Clone)]
pub struct FuncParam {
    pub name: String,
    pub param_type: Option<String>,
}

/// Introspectable metadata for one function. Single source for
/// `DESCRIBE(name)` output and the static function reference. `rpn` names
/// whether the function also runs on the compiled math path (`true` for
/// pure functions and opted-in stateful ones); everything runs on the AST
/// path.
#[derive(Debug, Clone)]
pub struct FuncMeta {
    pub name: String,
    /// Owning module (`STD` for builtins, `SCRIPT` for DSL definitions,
    /// the host module name otherwise). `name` is always the qualified
    /// `MODULE::BASE` form, so listings and `DESCRIBE` never lose origin.
    pub module: String,
    pub kind: FuncKind,
    pub params: Option<Vec<FuncParam>>,
    pub returns: Option<String>,
    pub rpn: bool,
    pub summary: &'static str,
    pub docs: &'static str,
}

/// Pure scalar function: no filesystem, no scope, no process access.
/// Usable from both AST evaluation and compiled RPN math.
pub type PureFn = Arc<dyn Fn(Vec<Value>) -> Result<Value> + Send + Sync>;

/// Stateful/IO function with full step context (fs, cwd, envs, vars, pipes).
pub type NativeFn<P> = Arc<dyn Fn(&mut StepCtx<P>, Vec<Value>) -> Result<Value> + Send + Sync>;

/// Export hook for a DSL function, implemented by `#[oxdock_func]` on a
/// registration marker. The engine calls `registration()` and never names
/// a generated symbol.
pub trait OxDockFn<P: ProcessManager> {
    /// The registry entry deriving from the Rust signature plus doc
    /// comments: name, metadata, and entry point, composed.
    fn registration() -> HostRegistration<P>;
}

/// One host-registered function, grouped into a [`HostModule`] and passed
/// to `Engine::register_module`. Build the entry with the `#[oxdock_func]`-
/// generated registration marker, or by hand. `Pure` entries run
/// on both the AST and the compiled RPN math paths; `Stateful` entries run
/// on the AST path with full step context.
pub enum HostRegistration<P: ProcessManager> {
    Stateful {
        name: String,
        meta: FuncMeta,
        func: NativeFn<P>,
    },
    Pure {
        name: String,
        meta: FuncMeta,
        func: PureFn,
    },
}

// Manual `Clone` (a derive would demand `P: Clone`): entries share their
// function pointers through the `Arc`s and deep-copy the metadata.
impl<P: ProcessManager> Clone for HostRegistration<P> {
    fn clone(&self) -> Self {
        match self {
            HostRegistration::Stateful { name, meta, func } => HostRegistration::Stateful {
                name: name.clone(),
                meta: meta.clone(),
                func: Arc::clone(func),
            },
            HostRegistration::Pure { name, meta, func } => HostRegistration::Pure {
                name: name.clone(),
                meta: meta.clone(),
                func: Arc::clone(func),
            },
        }
    }
}

/// One user-defined function body (`FUNC NAME($p: TYPE, ...) { ... }`).
#[derive(Debug, Clone)]
pub(super) struct FuncDefData {
    pub(super) params: Vec<(String, String)>,
    pub(super) body: Vec<Step>,
}

/// Executable body behind one registry entry: an interpreted script, a
/// pure scalar function, or a stateful function with step context.
pub(super) enum FuncBody<P: ProcessManager> {
    Script(FuncDefData),
    Pure(PureFn),
    Ctx(NativeFn<P>),
}

// Manual `Clone` (a derive would demand `P: Clone`).
impl<P: ProcessManager> Clone for FuncBody<P> {
    fn clone(&self) -> Self {
        match self {
            FuncBody::Script(def) => FuncBody::Script(def.clone()),
            FuncBody::Pure(func) => FuncBody::Pure(Arc::clone(func)),
            FuncBody::Ctx(func) => FuncBody::Ctx(Arc::clone(func)),
        }
    }
}

/// One entry in the unified function registry: introspectable metadata
/// (mandatory for every entry, backing the pre-evaluation arity gate)
/// plus the executable body.
pub(super) struct FuncEntry<P: ProcessManager> {
    pub(super) meta: FuncMeta,
    pub(super) body: FuncBody<P>,
}

// Manual `Clone` (a derive would demand `P: Clone`).
impl<P: ProcessManager> Clone for FuncEntry<P> {
    fn clone(&self) -> Self {
        Self {
            meta: self.meta.clone(),
            body: self.body.clone(),
        }
    }
}

/// Names defined in one lexical scope frame: `defined` rejects duplicates
/// in the same scope, `shadowed` restores outer definitions on exit.
struct ScopeFrame<P: ProcessManager> {
    defined: HashSet<String>,
    shadowed: Vec<(String, FuncEntry<P>)>,
}

// Manual `Clone` (a derive would demand `P: Clone`).
impl<P: ProcessManager> Clone for ScopeFrame<P> {
    fn clone(&self) -> Self {
        Self {
            defined: self.defined.clone(),
            shadowed: self.shadowed.clone(),
        }
    }
}

/// The single function registry: DSL `FUNC` definitions, builtins, and
/// host extensions share one lookup table, one metadata path, and one
/// dispatch order. Script entries scope lexically (defined names revert on
/// scope exit, shadowing an outer definition restores it); native entries
/// persist for the run. Shared across `fork()` via clone; the entry maps
/// clone while scope frames stay per state.
pub struct FunctionRegistry<P: ProcessManager> {
    entries: HashMap<String, FuncEntry<P>>,
    scopes: Vec<ScopeFrame<P>>,
}

impl<P: ProcessManager> FunctionRegistry<P> {
    pub(super) fn with_builtins() -> Self {
        let mut reg = Self {
            entries: HashMap::new(),
            scopes: vec![ScopeFrame {
                defined: HashSet::new(),
                shadowed: Vec::new(),
            }],
        };
        // Every builtin registers through the same `HostRegistration`
        // entries hosts use: no separate authoring path for engine natives.
        // Builtins land in the `STD` module, exactly like a host module.
        for host in Self::builtin_registrations() {
            match host {
                HostRegistration::Stateful { name, meta, func } => {
                    reg.insert_qualified(STD_MODULE_NAME, name, meta, FuncBody::Ctx(func));
                }
                HostRegistration::Pure { name, meta, func } => {
                    reg.insert_qualified(STD_MODULE_NAME, name, meta, FuncBody::Pure(func));
                }
            }
        }
        reg
    }

    /// All builtins as host-style registrations, built from the same
    /// `#[oxdock_func]`-generated markers hosts use. `with_builtins`
    /// consumes this list, so builtins and hosts share one registration
    /// pathway instead of two authoring models.
    pub(super) fn builtin_registrations() -> Vec<HostRegistration<P>> {
        vec![
            Int::registration(),
            Float::registration(),
            Types::registration(),
            TypeDescribe::registration(),
            Glob::registration(),
            LoadToml::registration(),
            LoadJson::registration(),
            PathType::registration(),
            Functions::registration(),
            Describe::registration(),
        ]
    }

    /// Every name the registry answers to. Backs parse-time shadow
    /// validation through `builtin_function_names`.
    pub(super) fn keys(&self) -> HashSet<String> {
        self.entries.keys().cloned().collect()
    }

    /// Single lookup for every callable: script, pure, or stateful.
    pub(super) fn get(&self, name: &str) -> Option<FuncEntry<P>> {
        self.entries.get(name).cloned()
    }

    fn insert_native(&mut self, name: String, meta: FuncMeta, body: FuncBody<P>) {
        self.entries.insert(name, FuncEntry { meta, body });
    }

    /// Insert under `MODULE::BASE`, stamping provenance on the metadata.
    /// The single choke point for every registry entry: builtins pass
    /// `STD`, hosts pass their module, scripts pass `SCRIPT`.
    fn insert_qualified(
        &mut self,
        module: &str,
        base: String,
        mut meta: FuncMeta,
        body: FuncBody<P>,
    ) {
        meta.name = qualify(module, &base);
        meta.module = module.to_string();
        // Last-write-wins would silently reroute calls, so a repeated
        // qualified name is a programmer error, never a shadow: panic like
        // conflicting type registrations do. `SCRIPT` definitions bypass
        // this path (`define_script` owns their scoped shadowing).
        if self.entries.contains_key(&meta.name) {
            panic!("duplicate function registration `{}`", meta.name);
        }
        self.insert_native(meta.name.clone(), meta, body);
    }

    pub(super) fn register_host(
        &mut self,
        module: &str,
        name: String,
        mut meta: FuncMeta,
        func: NativeFn<P>,
    ) {
        meta.kind = FuncKind::HostCtx;
        self.insert_qualified(module, name, meta, FuncBody::Ctx(func));
    }

    pub(super) fn register_pure_host(
        &mut self,
        module: &str,
        name: String,
        mut meta: FuncMeta,
        func: PureFn,
    ) {
        meta.kind = FuncKind::HostPure;
        self.insert_qualified(module, name, meta, FuncBody::Pure(func));
    }

    /// Define a DSL `FUNC`: names colliding with any known base name cannot
    /// shadow, same-scope duplicates cannot redefine, and nested shadowing
    /// of an outer script definition restores on scope exit. Stored as
    /// `SCRIPT::NAME`, exactly like every other qualified entry.
    pub(super) fn define_script(
        &mut self,
        name: &str,
        params: &[(String, String)],
        body: &[Step],
    ) -> Result<()> {
        let qualified = qualify(SCRIPT_MODULE_NAME, name);
        let shadowable = matches!(
            self.entries.get(&qualified).map(|entry| &entry.body),
            Some(FuncBody::Script(_))
        );
        // Reserved spans every module: compare base names so the message
        // keeps naming the bare script identifier.
        let reserved = self
            .entries
            .keys()
            .any(|key| split_qualified(key).is_some_and(|(_, base)| base == name));
        if reserved && !shadowable {
            anyhow::bail!("cannot shadow reserved function `{name}`");
        }
        if self
            .scopes
            .last()
            .is_some_and(|frame| frame.defined.contains(&qualified))
        {
            anyhow::bail!("duplicate function `{name}` in same scope");
        }
        let old = self.entries.insert(
            qualified.clone(),
            FuncEntry {
                meta: FuncMeta {
                    name: qualified.clone(),
                    module: SCRIPT_MODULE_NAME.to_string(),
                    kind: FuncKind::Script,
                    params: Some(
                        params
                            .iter()
                            .map(|(name, param_type)| FuncParam {
                                name: name.clone(),
                                param_type: Some(param_type.clone()),
                            })
                            .collect(),
                    ),
                    returns: None,
                    rpn: false,
                    summary: "DSL-defined function.",
                    docs: "Defined via FUNC in script.",
                },
                body: FuncBody::Script(FuncDefData {
                    params: params.to_vec(),
                    body: body.to_vec(),
                }),
            },
        );
        if let Some(frame) = self.scopes.last_mut() {
            frame.defined.insert(qualified.clone());
            if let Some(old) = old {
                frame.shadowed.push((qualified, old));
            }
        }
        Ok(())
    }

    /// Open a lexical scope frame for script definitions. Native entries
    /// persist; only script names track here.
    pub(super) fn push_scope(&mut self) {
        self.scopes.push(ScopeFrame {
            defined: HashSet::new(),
            shadowed: Vec::new(),
        });
    }

    /// Close a lexical scope frame: names defined inside revert, and any
    /// outer definition they shadowed is restored.
    pub(super) fn pop_scope(&mut self) {
        let Some(frame) = self.scopes.pop() else {
            return;
        };
        for name in frame.defined {
            self.entries.remove(&name);
        }
        for (name, old) in frame.shadowed {
            self.entries.insert(name, old);
        }
    }

    /// True when `name` is an interpreted script definition (needing call
    /// scoping and depth budgeting through `call_func_value` rather than
    /// inline evaluation).
    pub(super) fn contains_script(&self, name: &str) -> bool {
        matches!(
            self.entries.get(name).map(|entry| &entry.body),
            Some(FuncBody::Script(_))
        )
    }

    /// Clone the pure fn for `name` (ending the registry borrow) so callers
    /// can invoke it without holding `&self` across a `&mut StepCtx` use.
    fn clone_pure_fn(&self, name: &str) -> Option<PureFn> {
        match self.entries.get(name)?.body {
            FuncBody::Pure(ref func) => Some(Arc::clone(func)),
            _ => None,
        }
    }

    /// Clone the ctx fn for `name` (ending the registry borrow) so callers
    /// can invoke it with `&mut StepCtx` without double-borrowing state.
    fn clone_ctx_fn(&self, name: &str) -> Option<NativeFn<P>> {
        match self.entries.get(name)?.body {
            FuncBody::Ctx(ref func) => Some(Arc::clone(func)),
            _ => None,
        }
    }

    fn meta(&self, name: &str) -> Option<FuncMeta> {
        self.entries.get(name).map(|entry| entry.meta.clone())
    }

    fn native_metas(&self) -> Vec<FuncMeta> {
        let mut out: Vec<FuncMeta> = Vec::new();
        for entry in self.entries.values() {
            if !matches!(entry.body, FuncBody::Script(_)) {
                out.push(entry.meta.clone());
            }
        }
        out.sort_by(|a, b| a.name.cmp(&b.name));
        out
    }

    /// Every entry's metadata, scripts included, sorted by name. Backs
    /// runtime `FUNCTIONS()` listings.
    fn entries_metas(&self) -> Vec<FuncMeta> {
        let mut out: Vec<FuncMeta> = self
            .entries
            .values()
            .map(|entry| entry.meta.clone())
            .collect();
        out.sort_by(|a, b| a.name.cmp(&b.name));
        out
    }
}

impl<P: ProcessManager> Clone for FunctionRegistry<P> {
    fn clone(&self) -> Self {
        Self {
            entries: self.entries.clone(),
            scopes: self.scopes.clone(),
        }
    }
}

/// Names of all compiled-in builtins plus `INSPECT` (a dedicated AST/RPN
/// node, not a registry entry). Read straight off a stock registry, so the
/// `#[oxdock_func]` annotations stay the single source of truth: adding a
/// builtin extends this set with no parallel list to update. Seeds
/// parse-time shadow validation, so the parser crate keeps zero
/// compile-time knowledge of builtin names.
pub fn builtin_function_names() -> HashSet<String> {
    let mut names = FunctionRegistry::<DefaultProcessManager>::with_builtins().keys();
    names.insert(KEYWORD_INSPECT.to_string());
    names
}

/// Metadata of every builtin function, sorted by name, for static
/// rendering (docs-gen). Same single source as `builtin_function_names`:
/// the `#[oxdock_func]` annotations, never a parallel list.
pub fn builtin_function_metas() -> Vec<FuncMeta> {
    FunctionRegistry::<DefaultProcessManager>::with_builtins().native_metas()
}

/// Stock `STD` module table derived from the `#[oxdock_func]` builtins:
/// the single source of truth for builtin membership and RPN eligibility.
/// Seeds parse-time module resolution, so the parser crate keeps zero
/// compile-time knowledge of builtin names.
pub fn std_module_table() -> oxdock_parser::ModuleTable {
    // Registry names are qualified (`STD::GLOB`); the table holds bases.
    let functions: HashSet<String> = builtin_function_metas()
        .into_iter()
        .map(|meta| base_name(&meta.name).to_string())
        .collect();
    oxdock_parser::ModuleTable {
        modules: HashMap::from([(
            STD_MODULE_NAME.to_string(),
            Some(oxdock_parser::ModuleFuncs { functions }),
        )]),
    }
}

// Builtins below use the `#[oxdock_func]` host export macro, the exact same authoring
// model as host-registered functions: metadata, arity checks, and argument
// unpacking derive from the signature plus doc comments, so adding a native
// means writing one small typed function plus one line each in
// `builtin_registrations` (consumed by `with_builtins`) and the
// `FUNCTIONS`/`DESCRIBE`/`TYPES` surface, which all read the same symbols.

/// Convert a value to INT.
///
/// Trims ASCII whitespace and parses i64. Passes Int through; Float only
/// when integral and finite.
#[oxdock_func(pure, returns = "INT")]
fn int(val: Value) -> Result<Value> {
    super::args::int_from_value(val)
}

/// Convert a value to FLOAT.
///
/// Parses f64 (accepts int strings), bails on non-finite or non-numeric.
#[oxdock_func(pure, returns = "FLOAT")]
fn float(val: Value) -> Result<Value> {
    super::args::float_from_value(val)
}

/// List workspace paths matching a glob pattern.
///
/// Sorted, root-relative LIST; empty on no match or `..` escape.
#[oxdock_func(rpn, returns = "LIST")]
fn glob<P: ProcessManager>(cx: &mut StepCtx<P>, pattern: String) -> Result<Value> {
    super::args::glob_from_value(&[Value::string(pattern)], cx)
}

/// Load and parse a TOML file.
///
/// Reads a workspace file and parses TOML into a DSL value.
#[oxdock_func(rpn, returns = "MAP")]
fn load_toml<P: ProcessManager>(cx: &mut StepCtx<P>, path: String) -> Result<Value> {
    super::args::load_toml_from_value(&[Value::string(path)], cx)
}

/// Load and parse a JSON file.
///
/// Reads a workspace file and parses JSON into a DSL value.
#[oxdock_func(rpn, returns = "MAP")]
fn load_json<P: ProcessManager>(cx: &mut StepCtx<P>, path: String) -> Result<Value> {
    super::args::load_json_from_value(&[Value::string(path)], cx)
}

/// Describe a filesystem entry.
///
/// Reports file, dir, symlink (no-follow), or absent. AST-only by design;
/// there is no RPN arm for filesystem IO.
#[oxdock_func(returns = "STRING")]
fn path_type<P: ProcessManager>(cx: &mut StepCtx<P>, path: String) -> Result<Value> {
    super::args::path_type_from_value(&[Value::string(path)], cx)
}

/// List all visible function names.
///
/// Sorted LIST of qualified `MODULE::NAME` entries: DSL-defined plus native
/// plus host-registered names.
#[oxdock_func(returns = "LIST")]
fn functions<P: ProcessManager>(cx: &mut StepCtx<P>) -> Result<Value> {
    let mut names: Vec<String> = cx
        .state
        .list_functions()
        .into_iter()
        .map(|meta| meta.name)
        .collect();
    names.sort();
    names.dedup();
    Ok(Value::list(names.into_iter().map(Value::string).collect()))
}

/// Describe one function by qualified name.
///
/// Returns a MAP with name, module, kind, params, returns, and summary.
/// Bare names fail closed: `DESCRIBE` requires the qualified form (except
/// `INSPECT`, which is syntax rather than a registry entry). Errors on
/// unknown function.
#[oxdock_func(returns = "MAP")]
fn describe<P: ProcessManager>(cx: &mut StepCtx<P>, name: String) -> Result<Value> {
    if split_qualified(&name).is_none() && name != KEYWORD_INSPECT {
        anyhow::bail!(
            "unknown function `{name}`: DESCRIBE requires a qualified name (e.g. `STD::{name}`)"
        );
    }
    cx.state
        .describe_function(&name)
        .ok_or_else(|| anyhow::anyhow!("unknown function {name}"))
}

/// List all known type names.
///
/// Sorted LIST of startup plus host-registered type descriptors. Reads the
/// run's name directory, so it runs on the AST path like the other
/// introspection functions.
#[oxdock_func(returns = "LIST")]
fn types<P: ProcessManager>(cx: &mut StepCtx<P>) -> Result<Value> {
    Ok(Value::list(
        cx.state
            .type_names()
            .into_iter()
            .map(Value::string)
            .collect(),
    ))
}

/// Describe one type by name.
///
/// Returns a MAP with name, summary, and docs. Errors on unknown type.
/// Reads the run's name directory, so it runs on the AST path.
#[oxdock_func(returns = "MAP")]
fn type_describe<P: ProcessManager>(cx: &mut StepCtx<P>, name: String) -> Result<Value> {
    cx.state
        .describe_type(&name)
        .map(|descriptor| {
            let mut map = BTreeMap::new();
            map.insert(
                "name".to_string(),
                Value::string(descriptor.name.to_string()),
            );
            map.insert(
                "summary".to_string(),
                Value::string(descriptor.summary.to_string()),
            );
            map.insert(
                "docs".to_string(),
                Value::string(descriptor.docs.to_string()),
            );
            Value::map(map)
        })
        .ok_or_else(|| anyhow::anyhow!("unknown type {name}"))
}

fn meta_to_value(meta: &FuncMeta) -> Value {
    let mut map = BTreeMap::new();
    map.insert("name".to_string(), Value::string(meta.name.clone()));
    map.insert("module".to_string(), Value::string(meta.module.clone()));
    map.insert(
        "kind".to_string(),
        Value::string(meta.kind.label().to_string()),
    );
    let params = match &meta.params {
        Some(params) => Value::list(
            params
                .iter()
                .map(|p| {
                    let mut entry = BTreeMap::new();
                    entry.insert("name".to_string(), Value::string(p.name.clone()));
                    entry.insert(
                        "param_type".to_string(),
                        Value::string(p.param_type.clone().unwrap_or_default()),
                    );
                    Value::map(entry)
                })
                .collect(),
        ),
        None => Value::string(String::new()),
    };
    map.insert("params".to_string(), params);
    map.insert(
        "returns".to_string(),
        Value::string(meta.returns.clone().unwrap_or_default()),
    );
    map.insert("rpn".to_string(), Value::bool(meta.rpn));
    map.insert(
        "summary".to_string(),
        Value::string(meta.summary.to_string()),
    );
    Value::map(map)
}

/// One host library: functions and types registered under a single module
/// name. `Engine::register_module` stages these; runs expose them as
/// `MODULE::NAME` calls with `MODULE` provenance on every entry.
#[derive(Clone)]
pub struct HostModule<P: ProcessManager> {
    pub name: String,
    pub funcs: Vec<HostRegistration<P>>,
    pub types: Vec<&'static TypeDescriptor>,
}

impl<P: ProcessManager> ExecState<P> {
    /// Register one [`HostModule`]: every function becomes callable as
    /// `MODULE::NAME`, every type joins the run's name directory.
    pub fn register_module(&mut self, module: HostModule<P>) {
        for registration in module.funcs {
            match registration {
                HostRegistration::Stateful { name, meta, func } => {
                    self.functions.register_host(&module.name, name, meta, func);
                }
                HostRegistration::Pure { name, meta, func } => {
                    self.functions
                        .register_pure_host(&module.name, name, meta, func);
                }
            }
        }
        for descriptor in module.types {
            self.register_type(descriptor);
        }
    }

    /// All visible functions: natives plus hosts plus current DSL definitions.
    pub fn list_functions(&self) -> Vec<FuncMeta> {
        let mut out: Vec<FuncMeta> = self.functions.entries_metas().into_iter().collect();
        // TODO: Make a "virtual function" and don't hardcode
        if !out.iter().any(|m| m.name == KEYWORD_INSPECT) {
            out.push(FuncMeta {
                name: KEYWORD_INSPECT.to_string(),
                module: STD_MODULE_NAME.to_string(),
                kind: FuncKind::HostCtx,
                params: None,
                returns: Some("MAP".to_string()),
                rpn: false,
                summary: "Inspect a variable binding.",
                docs: "INSPECT($var): dedicated AST node taking a variable, not a value.",
            });
        }
        out.sort_by(|a, b| a.name.cmp(&b.name));
        out
    }

    /// Describe one function by name, or `None` when unknown.
    pub fn describe_function(&self, name: &str) -> Option<Value> {
        if let Some(meta) = self.functions.meta(name) {
            return Some(meta_to_value(&meta));
        }
        // TODO: Make a "virtual function" and don't hardcode
        if name == KEYWORD_INSPECT {
            return Some(meta_to_value(&FuncMeta {
                name: KEYWORD_INSPECT.to_string(),
                module: STD_MODULE_NAME.to_string(),
                kind: FuncKind::HostCtx,
                params: None,
                returns: Some("MAP".to_string()),
                rpn: false,
                summary: "Inspect a variable binding.",
                docs: "INSPECT($var): dedicated AST node taking a variable, not a value.",
            }));
        }
        None
    }

    pub(super) fn clone_native_pure(&self, name: &str) -> Option<PureFn> {
        self.functions.clone_pure_fn(name)
    }

    pub(super) fn clone_native_ctx(&self, name: &str) -> Option<NativeFn<P>> {
        self.functions.clone_ctx_fn(name)
    }

    pub(super) fn native_meta(&self, name: &str) -> Option<FuncMeta> {
        self.functions.meta(name)
    }
}