Skip to main content

oxdock_core/exec/
typing.rs

1//! Type-system integration for the executor.
2//!
3//! Name directories (which descriptor answers for `"TAG"`) live per
4//! execution state: one `HashMap` seeded with the startup descriptors,
5//! extended by the run's host descriptors. Words carry their own vtable,
6//! so lifecycle never consults any table; only name resolution (declaration
7//! checking, `TYPES()`, `TYPE_DESCRIBE`) reads the state map.
8
9pub use oxdock_parser::{
10    ANY_TYPE_NAME, Field, HANDLE_TYPE_NAME, LIST_TAG, LIST_TYPE_NAME, MAP_TAG, MAP_TYPE_NAME,
11    OxDockType, TypeDescriptor, TypeTag, Value, ValuePayload, check_value, check_value_at,
12    clone_boxed, clone_copy, clone_shared, drop_boxed, drop_noop, drop_shared, eq_boxed, eq_inline,
13    eq_shared, fmt_boxed, fmt_inline, fmt_shared, load_inline, startup_descriptors, store_inline,
14    type_anchor, unshare_boxed, unshare_inline, unshare_shared,
15};
16
17use std::collections::{HashMap, HashSet};
18
19use anyhow::{Result, bail};
20use oxdock_parser::{
21    ANY_TAG, MAX_GENERIC_DEPTH, Spelled, SpelledField, Step, StepKind, canonicalize_spelling,
22    intern_rendered, lookup_rendered, parse_spelling, render_structural,
23};
24use oxdock_process::ProcessManager;
25
26use super::state::ExecState;
27
28/// Check an options map against its declared keys: unknown keys fail
29/// listing the known ones, so script typos fail fast instead of
30/// silently ignored. Shared by generated extractors and hand-built
31/// entries alike: both validate against the same `ParamOption`
32/// statics the metadata renders, so the documented keys and the
33/// enforced keys cannot drift apart. Present values check against
34/// the declared `ParamOption.value` through the single shape path,
35/// so a wrong-typed option fails here naming func, key, expected,
36/// and actual instead of deeper in the body. Absent keys pass here:
37/// defaults, coercion, and cross-key rules stay function logic.
38pub fn check_options(
39    map: &std::collections::BTreeMap<String, Value>,
40    options: &[crate::ParamOption],
41    func: &str,
42) -> Result<()> {
43    for key in map.keys() {
44        if !options.iter().any(|known| known.name == key) {
45            let known: Vec<&str> = options.iter().map(|known| known.name).collect();
46            bail!(
47                "{func}() unknown option '{key}' (expected: {})",
48                known.join(", ")
49            );
50        }
51    }
52    for (key, value) in map.iter() {
53        let option = options
54            .iter()
55            .find(|known| known.name == *key)
56            .expect("unknown keys rejected above");
57        crate::check_value_at(&option.value, value, &format!("{func}() option '{key}'"))?;
58    }
59    Ok(())
60}
61
62/// Pure entry hash for the environment digest: the namespace byte
63/// names the collection (`b'a'` aliases, `b's'` schemas, `b't'`
64/// custom types), never the action. Set and removal of the same
65/// entry hash identically, so removal backs the insertion out
66/// exactly and the digest always mirrors current content.
67fn hash_env_entry(namespace: u8, name: &str, value: &str) -> u64 {
68    use std::hash::{DefaultHasher, Hasher};
69    let mut hasher = DefaultHasher::new();
70    hasher.write_u8(namespace);
71    hasher.write(name.as_bytes());
72    hasher.write(value.as_bytes());
73    hasher.finish()
74}
75
76/// Fresh name directory seeded with the startup descriptors.
77pub(super) fn startup_type_map() -> HashMap<String, &'static TypeDescriptor> {
78    startup_descriptors()
79        .into_iter()
80        .map(|(name, descriptor)| (name.to_string(), descriptor))
81        .collect()
82}
83
84impl<P: ProcessManager> ExecState<P> {
85    /// Register a host-defined type descriptor (usually `T::descriptor()`
86    /// for a `#[oxdock_type]` payload). Makes the name visible to `TYPES()`
87    /// and valid for `LET $x: NAME` declarations carrying same-named
88    /// payloads. Re-registering a name returns silently when the descriptor
89    /// is identical; a different descriptor under a live name panics
90    /// instead of aliasing two layouts.
91    pub fn register_type(&mut self, descriptor: &'static TypeDescriptor) {
92        if let Some(live) = self.types.get(descriptor.name) {
93            if !std::ptr::eq(*live, descriptor) {
94                panic!(
95                    "type name `{}` already registered for a different descriptor",
96                    descriptor.name
97                );
98            }
99            return;
100        }
101        self.types.insert(descriptor.name.to_string(), descriptor);
102        self.type_env_digest ^= hash_env_entry(b't', descriptor.name, descriptor.name);
103    }
104
105    /// True when `name` names a registered type (startup or host).
106    pub fn is_known_type(&self, name: &str) -> bool {
107        self.types.contains_key(name)
108    }
109
110    /// Register a named record schema for shaped MAP bindings (usually
111    /// alongside the module that produces them). Makes the name valid
112    /// for `LET $x: NAME` declarations carrying conforming maps. A
113    /// different field table under a live name panics instead of
114    /// aliasing two shapes.
115    pub fn register_record_schema(&mut self, name: &'static str, fields: std::sync::Arc<[Field]>) {
116        if let Some(live) = self.record_schemas.get(name) {
117            if live.len() != fields.len()
118                || live
119                    .iter()
120                    .zip(fields.iter())
121                    .any(|(a, b)| a.name != b.name)
122            {
123                panic!("record schema `{name}` already registered with different fields");
124            }
125            return;
126        }
127        let rendered = render_structural(&TypeTag::Record(fields.clone()));
128        self.record_schemas.insert(name.to_string(), fields);
129        self.type_env_digest ^= hash_env_entry(b's', name, &rendered);
130    }
131
132    /// Every registered schema name, sorted. Backs discovery listings.
133    pub fn schema_names(&self) -> Vec<String> {
134        let mut names: Vec<String> = self.record_schemas.keys().cloned().collect();
135        names.sort();
136        names
137    }
138
139    /// Every script alias name, sorted. Backs discovery listings
140    /// and unknown-type errors alongside schemas.
141    pub fn alias_names(&self) -> Vec<String> {
142        let mut names: Vec<String> = self.type_aliases.keys().cloned().collect();
143        names.sort();
144        names
145    }
146
147    /// The canonical target spelling of one script alias, if defined.
148    /// Backs `TYPE_DESCRIBE` so aliases introspect like named types.
149    pub fn alias_target(&self, name: &str) -> Option<String> {
150        self.type_aliases.get(name).cloned()
151    }
152
153    /// Resolve a source-level type name to its tag: builtins by closed
154    /// match, customs through the type directory, named schemas through
155    /// the schema directory, script aliases through the alias directory,
156    /// generic spellings (`LIST<MAP>`, `MAP<name: STRING>`) rendered
157    /// structurally, and unions (`STRING|PIPE`, including inside
158    /// generics) with one interned entry per distinct spelling.
159    /// Anything else bails listing every known type, schema, and alias.
160    /// Single choke for every `LET`/`FUNC` declaration. Signature is
161    /// stable: alias cycles and shared depth accounting thread
162    /// internally, so all call sites gain generics with zero edits.
163    pub fn resolve_tag(&self, name: &str) -> Result<TypeTag> {
164        let canonical = canonicalize_spelling(name);
165        if canonical.contains('<') || canonical.contains('|') {
166            return self.resolve_spelling_text(&canonical, &mut Vec::new(), 0);
167        }
168        self.resolve_named(&canonical, &mut Vec::new(), 0)
169    }
170
171    /// Resolve one bare name through every directory. Alias targets
172    /// loop back through the spelling path, so `LIST<PERSON>`
173    /// combines; each alias hop costs 1 of the shared depth budget
174    /// and repeats bail naming the cycle.
175    fn resolve_named(
176        &self,
177        name: &str,
178        resolving: &mut Vec<String>,
179        depth: usize,
180    ) -> Result<TypeTag> {
181        if depth > MAX_GENERIC_DEPTH {
182            bail!("type spelling exceeds maximum generic depth of {MAX_GENERIC_DEPTH}: '{name}'");
183        }
184        if name == MAP_TYPE_NAME {
185            bail!(
186                "bare {MAP_TYPE_NAME} is not a declaration type: write a shape ({MAP_TYPE_NAME}<name: TYPE, ...>) or {MAP_TYPE_NAME}<{ANY_TYPE_NAME}> for maps with unknown keys"
187            );
188        }
189        if name == LIST_TYPE_NAME {
190            bail!(
191                "bare {LIST_TYPE_NAME} is not a declaration type: write a shape ({LIST_TYPE_NAME}<TYPE>) or {LIST_TYPE_NAME}<{ANY_TYPE_NAME}> for lists with unknown elements"
192            );
193        }
194        if name == HANDLE_TYPE_NAME {
195            bail!(
196                "bare {HANDLE_TYPE_NAME} is not a declaration type: write {HANDLE_TYPE_NAME}<T> for a known payload or {HANDLE_TYPE_NAME}<{ANY_TYPE_NAME}> for an unknown one"
197            );
198        }
199        if let Some(tag) = TypeTag::builtin(name) {
200            return Ok(tag);
201        }
202        if let Some(descriptor) = self.types.get(name) {
203            return Ok(TypeTag::Custom(descriptor));
204        }
205        if let Some(fields) = self.record_schemas.get(name) {
206            let tag = TypeTag::Record(fields.clone());
207            self.check_tag_known("declaration", &tag, false)?;
208            return Ok(tag);
209        }
210        if let Some(target) = self.type_aliases.get(name) {
211            if resolving.iter().any(|s| s.as_str() == name) {
212                resolving.push(name.to_string());
213                bail!("type alias cycle: {}", resolving.join(" -> "));
214            }
215            resolving.push(name.to_string());
216            let target = target.clone();
217            let result = self.resolve_spelling_text(&target, resolving, depth + 1);
218            resolving.pop();
219            return result;
220        }
221        bail!(
222            "unknown type '{name}'; known types: {} and schemas: {} and aliases: {}",
223            self.type_names().join(", "),
224            self.schema_names().join(", "),
225            self.alias_names().join(", "),
226        )
227    }
228
229    /// Resolve one canonical spelling that may carry `<...>` args:
230    /// interned hit returns shared, else parse, build, and intern.
231    /// The intern key carries the environment digest: one run's
232    /// `MAP<flags: FLAGS>` must never share a payload with another
233    /// run that spells it under different aliases.
234    fn resolve_spelling_text(
235        &self,
236        canonical: &str,
237        resolving: &mut Vec<String>,
238        depth: usize,
239    ) -> Result<TypeTag> {
240        let key = format!("{}\x1f{:016x}", canonical, self.type_env_digest);
241        if let Some(hit) = lookup_rendered(&key) {
242            return Ok(hit);
243        }
244        let spelled = parse_spelling(canonical)
245            .map_err(|err| anyhow::anyhow!("invalid type spelling: {err}"))?;
246        let tag = self.build_rendered(&spelled, resolving, depth)?;
247        Ok(intern_rendered(key, tag))
248    }
249
250    /// Record one alias binding, folding it into the digest. An
251    /// overwrite backs the old target out before mixing the new one
252    /// in, so the digest always mirrors current content; identical
253    /// re-registration folds nothing, so re-importing the same file
254    /// shares cache entries instead of forking them.
255    pub(super) fn register_alias(&mut self, name: String, target: String) {
256        if let Some(old) = self.type_aliases.insert(name.clone(), target.clone()) {
257            if old == target {
258                return;
259            }
260            self.type_env_digest ^= hash_env_entry(b'a', &name, &old);
261        }
262        self.type_env_digest ^= hash_env_entry(b'a', &name, &target);
263    }
264
265    /// Drop one alias binding, backing its hash out of the digest.
266    /// Absent names change nothing and fold nothing.
267    pub(super) fn remove_alias(&mut self, name: &str) {
268        if let Some(old) = self.type_aliases.remove(name) {
269            self.type_env_digest ^= hash_env_entry(b'a', name, &old);
270        }
271    }
272
273    /// Replace the whole alias directory (save/restore paths). Backs
274    /// the entire current directory out and mixes the entire next
275    /// one in: swaps are bounded and infrequent next to lookups, and
276    /// the digest stays an exact mirror of content either way.
277    pub(super) fn restore_aliases(&mut self, next: HashMap<String, String>) {
278        for (name, target) in &self.type_aliases {
279            self.type_env_digest ^= hash_env_entry(b'a', name, target);
280        }
281        for (name, target) in &next {
282            self.type_env_digest ^= hash_env_entry(b'a', name, target);
283        }
284        self.type_aliases = next;
285    }
286
287    /// Build a parsed spelling into its structural tag. `LIST`
288    /// takes exactly one bare argument, `MAP` takes named fields;
289    /// anything else with arguments (or `MAP` with bare ones)
290    /// bails naming the rule. Leaves resolve through the full
291    /// directory, so schema and alias names nest freely. Union
292    /// members resolve the same way, so unions nest inside aliases,
293    /// generics, and each other through one shared normalizer.
294    fn build_rendered(
295        &self,
296        spelled: &Spelled,
297        resolving: &mut Vec<String>,
298        depth: usize,
299    ) -> Result<TypeTag> {
300        if depth > MAX_GENERIC_DEPTH {
301            bail!(
302                "type spelling exceeds maximum generic depth of {MAX_GENERIC_DEPTH}: '{spelled:?}'"
303            );
304        }
305        match spelled {
306            Spelled::Named(name) => self.resolve_named(name, resolving, depth),
307            Spelled::Generic { name, args } => self.build_generic(name, args, resolving, depth),
308            Spelled::Union(members) => {
309                let mut resolved = Vec::with_capacity(members.len());
310                for member in members {
311                    resolved.push(self.build_rendered(member, resolving, depth)?);
312                }
313                finish_union(resolved)
314            }
315        }
316    }
317
318    /// Build one generic application. `LIST` takes exactly one
319    /// bare argument, `MAP` takes named fields; any other head
320    /// resolves bare first so the error names the real problem
321    /// (`unknown type` vs. arguments on a scalar, custom,
322    /// schema, or alias target). Leaf homes leak like the rendered
323    /// entry itself (one per distinct spelling; see
324    /// `intern_rendered`), localized here for the same reason.
325    #[allow(clippy::disallowed_methods)]
326    fn build_generic(
327        &self,
328        name: &str,
329        args: &[SpelledField],
330        resolving: &mut Vec<String>,
331        depth: usize,
332    ) -> Result<TypeTag> {
333        if name != LIST_TYPE_NAME && name != MAP_TYPE_NAME && name != HANDLE_TYPE_NAME {
334            self.resolve_named(name, resolving, depth)?;
335            bail!("'{name}' takes no type arguments");
336        }
337        if name == HANDLE_TYPE_NAME {
338            let [
339                SpelledField {
340                    name: None,
341                    ty: payload,
342                    ..
343                },
344            ] = args
345            else {
346                bail!("{HANDLE_TYPE_NAME} takes exactly one bare type argument");
347            };
348            let payload = self.build_rendered(payload, resolving, depth + 1)?;
349            return Ok(TypeTag::HandleOf(std::sync::Arc::new(payload)));
350        }
351        if name == LIST_TYPE_NAME {
352            let [
353                SpelledField {
354                    name: None,
355                    ty: element,
356                    ..
357                },
358            ] = args
359            else {
360                bail!("{LIST_TYPE_NAME} takes exactly one bare type argument");
361            };
362            let element = self.build_rendered(element, resolving, depth + 1)?;
363            return Ok(TypeTag::ListOf(std::sync::Arc::new(element)));
364        }
365        if name == MAP_TYPE_NAME
366            && let [
367                SpelledField {
368                    name: None,
369                    ty: Spelled::Named(any),
370                    ..
371                },
372            ] = args
373            && any.as_str() == ANY_TYPE_NAME
374        {
375            // Explicit unknown map: the only bare MAP spelling. Anything
376            // else bare still rejects below, and plain `MAP` never
377            // resolves (see `resolve_named`).
378            return Ok(TypeTag::MapOf(std::sync::Arc::new(ANY_TAG)));
379        }
380        let mut fields = Vec::with_capacity(args.len());
381        for arg in args {
382            let Some(field_name) = arg.name.as_ref() else {
383                bail!(
384                    "{MAP_TYPE_NAME} fields require 'name: TYPE'; '{name}' takes no bare arguments"
385                );
386            };
387            let ty = self.build_rendered(&arg.ty, resolving, depth + 1)?;
388            let default = match &arg.default {
389                None => None,
390                Some(lit) => {
391                    let value = lit.to_value();
392                    check_value(&ty, &value).map_err(|_| {
393                        anyhow::anyhow!(
394                            "default for field '{field_name}' does not match {}",
395                            oxdock_parser::render_structural(&ty)
396                        )
397                    })?;
398                    Some(value)
399                }
400            };
401            fields.push(Field {
402                name: field_name.clone(),
403                ty,
404                docs: "",
405                optional: arg.optional,
406                default,
407                alias: arg.alias.clone(),
408            });
409        }
410        // Alias uniqueness: one spelling maps to one field. Canonical
411        // names and aliases share one namespace, so a clash fails here
412        // naming both sides instead of shadowing at parse time.
413        {
414            use std::collections::HashMap;
415            let mut seen: HashMap<&str, &str> = HashMap::new();
416            for field in &fields {
417                if let Some(prev) = seen.insert(field.name.as_str(), field.name.as_str()) {
418                    let _ = prev;
419                    bail!("duplicate field '{}' in MAP spelling", field.name);
420                }
421                if let Some(alias) = field.alias.as_ref() {
422                    if alias == &field.name {
423                        bail!(
424                            "alias '{}' duplicates its own field '{}'",
425                            alias,
426                            field.name
427                        );
428                    }
429                    if let Some(owner) = seen.insert(alias.as_str(), field.name.as_str()) {
430                        bail!(
431                            "alias '{}' for field '{}' clashes with '{}'",
432                            alias,
433                            field.name,
434                            owner
435                        );
436                    }
437                }
438            }
439        }
440        Ok(TypeTag::Record(std::sync::Arc::from(fields)))
441    }
442}
443
444/// Normalize resolved union members into one tag: flatten nested
445/// unions, absorb on `ANY`, deduplicate, collapse lone survivors.
446/// Members keep written order while every comparison stays
447/// order-free, so all spellings behave identically. The tag owns
448/// everything through `Arc`: shared on clone, freed with the last
449/// owner, never leaked.
450fn finish_union(members: Vec<TypeTag>) -> Result<TypeTag> {
451    let mut flat: Vec<TypeTag> = Vec::with_capacity(members.len());
452    for member in members {
453        // Nested unions splice flat: members never nest, so every
454        // comparison stays one level deep by construction.
455        if let TypeTag::Union(_, nested) = member {
456            flat.extend(nested.iter().cloned());
457        } else {
458            flat.push(member);
459        }
460    }
461    if flat.is_empty() {
462        bail!("empty union: no member shapes to admit");
463    }
464    // `ANY` absorbs the set: admitting everything is `ANY`.
465    if flat.iter().any(|member| matches!(member, TypeTag::Any)) {
466        return Ok(TypeTag::Any);
467    }
468    // Full (not just consecutive) deduplication: order-free
469    // comparisons make every permutation behave identically.
470    let mut unique: Vec<TypeTag> = Vec::with_capacity(flat.len());
471    for member in flat {
472        if !unique
473            .iter()
474            .any(|seen| super::static_check::tags_equal(seen, &member))
475        {
476            unique.push(member);
477        }
478    }
479    if unique.len() == 1 {
480        return Ok(unique.pop().expect("single survivor checked above"));
481    }
482    Ok(TypeTag::union(unique))
483}
484
485/// Collect top-level `TYPE` alias definitions into the run's
486/// alias directory: name to canonical target spelling. Runs
487/// before the static pass so forward references resolve
488/// run-wide. Duplicates and collisions with builtin, host,
489/// schema, and top-level `FUNC` names are static errors
490/// naming the offender. Nested `TYPE` steps cannot occur
491/// (the parser rejects them); hand-built ones never resolve.
492pub fn collect_type_aliases<P: ProcessManager>(
493    steps: &[Step],
494    exec: &ExecState<P>,
495) -> Result<HashMap<String, String>> {
496    let mut func_names = HashSet::new();
497    for step in steps {
498        if let StepKind::FuncDef { name, .. } = &step.kind {
499            func_names.insert(name.clone());
500        }
501    }
502    let mut aliases = HashMap::new();
503    for step in steps {
504        let StepKind::TypeAlias { name, target } = &step.kind else {
505            continue;
506        };
507        if aliases.contains_key(name) {
508            bail!("type alias '{name}' is already defined");
509        }
510        if TypeTag::builtin(name).is_some() {
511            bail!("type alias '{name}' collides with a builtin type");
512        }
513        if exec.types.contains_key(name) {
514            bail!("type alias '{name}' collides with registered host type '{name}'");
515        }
516        if exec.record_schemas.contains_key(name) {
517            bail!("type alias '{name}' collides with registered record schema '{name}'");
518        }
519        if func_names.contains(name) {
520            bail!("type alias '{name}' collides with function '{name}'");
521        }
522        aliases.insert(name.clone(), canonicalize_spelling(target));
523    }
524    Ok(aliases)
525}
526
527impl<P: ProcessManager> ExecState<P> {
528    /// Check one tag against the directories: customs must name a
529    /// registered descriptor, shaped tags recurse into fields and
530    /// elements, builtins are variants and cannot be misspelled.
531    /// Unknown names bail naming the use site and every known type.
532    /// Single choke for declaration validity: known customs plus
533    /// the VOID position rule. VOID is legal only as a bare function
534    /// return (`top_void` covers exactly that call) or as the direct
535    /// payload of HANDLE (`HANDLE<VOID>`). Every other position is a
536    /// static error naming the site: variable, parameter, record
537    /// field, union member, container element, or anything nested
538    /// deeper. One recursion serves all declaration sites, so the
539    /// rule cannot drift between LET, params, returns, schemas, and
540    /// aliases: resolve first, then validate here.
541    fn check_tag_known(&self, what: &str, tag: &TypeTag, top_void: bool) -> Result<()> {
542        match tag {
543            TypeTag::Custom(descriptor) => {
544                if !self.types.contains_key(descriptor.name) {
545                    bail!(
546                        "{what} declares unregistered type '{}'; known types: {}",
547                        descriptor.name,
548                        self.type_names().join(", ")
549                    );
550                }
551            }
552            TypeTag::Void if !top_void => {
553                bail!(
554                    "{what} declares VOID outside a return annotation: VOID is only a return type (or HANDLE<VOID> payload)"
555                );
556            }
557            TypeTag::Void => {}
558            TypeTag::ListOf(element) => self.check_tag_known(what, element, false)?,
559            TypeTag::HandleOf(payload) => self.check_tag_known(what, payload, true)?,
560            TypeTag::MapOf(values) => self.check_tag_known(what, values, false)?,
561            TypeTag::Record(fields) => {
562                for field in fields.iter() {
563                    self.check_tag_known(what, &field.ty, false)?;
564                }
565            }
566            // Union members recurse like shaped tags: every member
567            // must name a known type, so no unknown hides in a set.
568            // A VOID member is never admitted: unions of handles stay
569            // inside the payload (HANDLE<INT|STRING>), never at the
570            // root or beside a value type.
571            TypeTag::Union(_, members) => {
572                for member in members.iter() {
573                    self.check_tag_known(what, member, false)?;
574                }
575            }
576            // Bare words are variants and cannot be misspelled: every
577            // builtin is listed so a new word kind fails here until
578            // its directory rule is explicit.
579            TypeTag::String
580            | TypeTag::Int
581            | TypeTag::Float
582            | TypeTag::Bool
583            | TypeTag::List
584            | TypeTag::Map
585            | TypeTag::Pipe
586            | TypeTag::Handle
587            | TypeTag::Duration
588            | TypeTag::Path
589            | TypeTag::Semaphore
590            | TypeTag::Permit
591            | TypeTag::Any => {}
592        }
593        Ok(())
594    }
595
596    /// Declaration-site gate for everything that is not a function
597    /// return: LET bindings, parameters, schemas, aliases at use.
598    /// Single choke so the VOID position rule cannot drift between
599    /// the static checker and runtime definition paths.
600    pub fn check_declaration_tag(&self, what: &str, tag: &TypeTag) -> Result<()> {
601        self.check_tag_known(what, tag, false)
602    }
603
604    /// Return-position gate: bare VOID is legal here (and only
605    /// here, besides HANDLE payloads). Same single recursion as
606    /// every other declaration site.
607    pub fn check_return_tag(&self, what: &str, tag: &TypeTag) -> Result<()> {
608        self.check_tag_known(what, tag, true)
609    }
610
611    /// Fail fast when any registered function declares param or return
612    /// type names outside the type directory. Runs once per run before
613    /// the first step executes: param arity and `LET` coercion already
614    /// check values at use time, but a typo'd `returns` label otherwise
615    /// lives forever as a lie in `DESCRIBE` output and generated
616    /// references. Unknown names bail listing every known type. A
617    /// closed `allowed` set without a type is rejected too: the set
618    /// only means something alongside the `STRING` check that enforces
619    /// it, so hand-built entries cannot render a set they never check.
620    pub fn validate_function_type_tags(&self) -> Result<()> {
621        for meta in self.functions.all_metas() {
622            if let Some(params) = meta.params.as_deref() {
623                for (position, param) in params.iter().enumerate() {
624                    if let Some(expected) = param.param_type.as_ref() {
625                        let what = format!("param '{}' of '{}'", param.name, meta.name);
626                        Self::check_tag_known(self, &what, expected, false)?;
627                    }
628                    if param.param_type.is_none() && param.allowed.is_some() {
629                        anyhow::bail!(
630                            "param '{}' of '{}' declares values without a type",
631                            param.name,
632                            meta.name,
633                        );
634                    }
635                    if param.optional {
636                        // Omission fills an empty MAP, so only trailing
637                        // MAP params qualify: anything else would fill a
638                        // value the caller never chose.
639                        let trails = params[position..].iter().all(|later| later.optional);
640                        if !trails {
641                            anyhow::bail!(
642                                "param '{}' of '{}' is optional before a required param",
643                                param.name,
644                                meta.name,
645                            );
646                        }
647                        // Omission fills an empty MAP, so the param type
648                        // must admit one: checked semantically (empty MAP
649                        // against the type) instead of naming admissible
650                        // constructors, so defaulted shapes and unions
651                        // qualify exactly when the fill verifies.
652                        let fills = param.param_type.as_ref().is_some_and(|expected| {
653                            check_value(expected, &Value::map(std::collections::BTreeMap::new()))
654                                .is_ok()
655                        });
656                        if !fills {
657                            anyhow::bail!(
658                                "param '{}' of '{}' is optional without a MAP type",
659                                param.name,
660                                meta.name,
661                            );
662                        }
663                    }
664                }
665            }
666            if let Some(returns) = meta.returns.as_ref() {
667                let what = format!("return of '{}'", meta.name);
668                Self::check_tag_known(self, &what, returns, true)?;
669            }
670        }
671        Ok(())
672    }
673
674    /// Resolve a descriptor by name, or `None` when unregistered.
675    pub fn describe_type(&self, name: &str) -> Option<&'static TypeDescriptor> {
676        self.types.get(name).copied()
677    }
678
679    /// Every registered type name: startup descriptors first, then hosts in
680    /// registration order, then script aliases.
681    pub fn type_names(&self) -> Vec<String> {
682        let mut names: Vec<String> = startup_descriptors()
683            .into_iter()
684            .map(|(name, _)| name.to_string())
685            .collect();
686        for name in self.types.keys() {
687            if !names.iter().any(|n| n == name) {
688                names.push(name.clone());
689            }
690        }
691        for name in self.alias_names() {
692            if !names.contains(&name) {
693                names.push(name);
694            }
695        }
696        names
697    }
698}