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            });
408        }
409        Ok(TypeTag::Record(std::sync::Arc::from(fields)))
410    }
411}
412
413/// Normalize resolved union members into one tag: flatten nested
414/// unions, absorb on `ANY`, deduplicate, collapse lone survivors.
415/// Members keep written order while every comparison stays
416/// order-free, so all spellings behave identically. The tag owns
417/// everything through `Arc`: shared on clone, freed with the last
418/// owner, never leaked.
419fn finish_union(members: Vec<TypeTag>) -> Result<TypeTag> {
420    let mut flat: Vec<TypeTag> = Vec::with_capacity(members.len());
421    for member in members {
422        // Nested unions splice flat: members never nest, so every
423        // comparison stays one level deep by construction.
424        if let TypeTag::Union(_, nested) = member {
425            flat.extend(nested.iter().cloned());
426        } else {
427            flat.push(member);
428        }
429    }
430    if flat.is_empty() {
431        bail!("empty union: no member shapes to admit");
432    }
433    // `ANY` absorbs the set: admitting everything is `ANY`.
434    if flat.iter().any(|member| matches!(member, TypeTag::Any)) {
435        return Ok(TypeTag::Any);
436    }
437    // Full (not just consecutive) deduplication: order-free
438    // comparisons make every permutation behave identically.
439    let mut unique: Vec<TypeTag> = Vec::with_capacity(flat.len());
440    for member in flat {
441        if !unique
442            .iter()
443            .any(|seen| super::static_check::tags_equal(seen, &member))
444        {
445            unique.push(member);
446        }
447    }
448    if unique.len() == 1 {
449        return Ok(unique.pop().expect("single survivor checked above"));
450    }
451    Ok(TypeTag::union(unique))
452}
453
454/// Collect top-level `TYPE` alias definitions into the run's
455/// alias directory: name to canonical target spelling. Runs
456/// before the static pass so forward references resolve
457/// run-wide. Duplicates and collisions with builtin, host,
458/// schema, and top-level `FUNC` names are static errors
459/// naming the offender. Nested `TYPE` steps cannot occur
460/// (the parser rejects them); hand-built ones never resolve.
461pub fn collect_type_aliases<P: ProcessManager>(
462    steps: &[Step],
463    exec: &ExecState<P>,
464) -> Result<HashMap<String, String>> {
465    let mut func_names = HashSet::new();
466    for step in steps {
467        if let StepKind::FuncDef { name, .. } = &step.kind {
468            func_names.insert(name.clone());
469        }
470    }
471    let mut aliases = HashMap::new();
472    for step in steps {
473        let StepKind::TypeAlias { name, target } = &step.kind else {
474            continue;
475        };
476        if aliases.contains_key(name) {
477            bail!("type alias '{name}' is already defined");
478        }
479        if TypeTag::builtin(name).is_some() {
480            bail!("type alias '{name}' collides with a builtin type");
481        }
482        if exec.types.contains_key(name) {
483            bail!("type alias '{name}' collides with registered host type '{name}'");
484        }
485        if exec.record_schemas.contains_key(name) {
486            bail!("type alias '{name}' collides with registered record schema '{name}'");
487        }
488        if func_names.contains(name) {
489            bail!("type alias '{name}' collides with function '{name}'");
490        }
491        aliases.insert(name.clone(), canonicalize_spelling(target));
492    }
493    Ok(aliases)
494}
495
496impl<P: ProcessManager> ExecState<P> {
497    /// Check one tag against the directories: customs must name a
498    /// registered descriptor, shaped tags recurse into fields and
499    /// elements, builtins are variants and cannot be misspelled.
500    /// Unknown names bail naming the use site and every known type.
501    /// Single choke for declaration validity: known customs plus
502    /// the VOID position rule. VOID is legal only as a bare function
503    /// return (`top_void` covers exactly that call) or as the direct
504    /// payload of HANDLE (`HANDLE<VOID>`). Every other position is a
505    /// static error naming the site: variable, parameter, record
506    /// field, union member, container element, or anything nested
507    /// deeper. One recursion serves all declaration sites, so the
508    /// rule cannot drift between LET, params, returns, schemas, and
509    /// aliases: resolve first, then validate here.
510    fn check_tag_known(&self, what: &str, tag: &TypeTag, top_void: bool) -> Result<()> {
511        match tag {
512            TypeTag::Custom(descriptor) => {
513                if !self.types.contains_key(descriptor.name) {
514                    bail!(
515                        "{what} declares unregistered type '{}'; known types: {}",
516                        descriptor.name,
517                        self.type_names().join(", ")
518                    );
519                }
520            }
521            TypeTag::Void if !top_void => {
522                bail!(
523                    "{what} declares VOID outside a return annotation: VOID is only a return type (or HANDLE<VOID> payload)"
524                );
525            }
526            TypeTag::Void => {}
527            TypeTag::ListOf(element) => self.check_tag_known(what, element, false)?,
528            TypeTag::HandleOf(payload) => self.check_tag_known(what, payload, true)?,
529            TypeTag::MapOf(values) => self.check_tag_known(what, values, false)?,
530            TypeTag::Record(fields) => {
531                for field in fields.iter() {
532                    self.check_tag_known(what, &field.ty, false)?;
533                }
534            }
535            // Union members recurse like shaped tags: every member
536            // must name a known type, so no unknown hides in a set.
537            // A VOID member is never admitted: unions of handles stay
538            // inside the payload (HANDLE<INT|STRING>), never at the
539            // root or beside a value type.
540            TypeTag::Union(_, members) => {
541                for member in members.iter() {
542                    self.check_tag_known(what, member, false)?;
543                }
544            }
545            // Bare words are variants and cannot be misspelled: every
546            // builtin is listed so a new word kind fails here until
547            // its directory rule is explicit.
548            TypeTag::String
549            | TypeTag::Int
550            | TypeTag::Float
551            | TypeTag::Bool
552            | TypeTag::List
553            | TypeTag::Map
554            | TypeTag::Pipe
555            | TypeTag::Handle
556            | TypeTag::Duration
557            | TypeTag::Path
558            | TypeTag::Semaphore
559            | TypeTag::Permit
560            | TypeTag::Any => {}
561        }
562        Ok(())
563    }
564
565    /// Declaration-site gate for everything that is not a function
566    /// return: LET bindings, parameters, schemas, aliases at use.
567    /// Single choke so the VOID position rule cannot drift between
568    /// the static checker and runtime definition paths.
569    pub fn check_declaration_tag(&self, what: &str, tag: &TypeTag) -> Result<()> {
570        self.check_tag_known(what, tag, false)
571    }
572
573    /// Return-position gate: bare VOID is legal here (and only
574    /// here, besides HANDLE payloads). Same single recursion as
575    /// every other declaration site.
576    pub fn check_return_tag(&self, what: &str, tag: &TypeTag) -> Result<()> {
577        self.check_tag_known(what, tag, true)
578    }
579
580    /// Fail fast when any registered function declares param or return
581    /// type names outside the type directory. Runs once per run before
582    /// the first step executes: param arity and `LET` coercion already
583    /// check values at use time, but a typo'd `returns` label otherwise
584    /// lives forever as a lie in `DESCRIBE` output and generated
585    /// references. Unknown names bail listing every known type. A
586    /// closed `allowed` set without a type is rejected too: the set
587    /// only means something alongside the `STRING` check that enforces
588    /// it, so hand-built entries cannot render a set they never check.
589    pub fn validate_function_type_tags(&self) -> Result<()> {
590        for meta in self.functions.all_metas() {
591            if let Some(params) = meta.params.as_deref() {
592                for (position, param) in params.iter().enumerate() {
593                    if let Some(expected) = param.param_type.as_ref() {
594                        let what = format!("param '{}' of '{}'", param.name, meta.name);
595                        Self::check_tag_known(self, &what, expected, false)?;
596                    }
597                    if param.param_type.is_none() && param.allowed.is_some() {
598                        anyhow::bail!(
599                            "param '{}' of '{}' declares values without a type",
600                            param.name,
601                            meta.name,
602                        );
603                    }
604                    if param.optional {
605                        // Omission fills an empty MAP, so only trailing
606                        // MAP params qualify: anything else would fill a
607                        // value the caller never chose.
608                        let trails = params[position..].iter().all(|later| later.optional);
609                        if !trails {
610                            anyhow::bail!(
611                                "param '{}' of '{}' is optional before a required param",
612                                param.name,
613                                meta.name,
614                            );
615                        }
616                        // Omission fills an empty MAP, so the param type
617                        // must admit one: checked semantically (empty MAP
618                        // against the type) instead of naming admissible
619                        // constructors, so defaulted shapes and unions
620                        // qualify exactly when the fill verifies.
621                        let fills = param.param_type.as_ref().is_some_and(|expected| {
622                            check_value(expected, &Value::map(std::collections::BTreeMap::new()))
623                                .is_ok()
624                        });
625                        if !fills {
626                            anyhow::bail!(
627                                "param '{}' of '{}' is optional without a MAP type",
628                                param.name,
629                                meta.name,
630                            );
631                        }
632                    }
633                }
634            }
635            if let Some(returns) = meta.returns.as_ref() {
636                let what = format!("return of '{}'", meta.name);
637                Self::check_tag_known(self, &what, returns, true)?;
638            }
639        }
640        Ok(())
641    }
642
643    /// Resolve a descriptor by name, or `None` when unregistered.
644    pub fn describe_type(&self, name: &str) -> Option<&'static TypeDescriptor> {
645        self.types.get(name).copied()
646    }
647
648    /// Every registered type name: startup descriptors first, then hosts in
649    /// registration order, then script aliases.
650    pub fn type_names(&self) -> Vec<String> {
651        let mut names: Vec<String> = startup_descriptors()
652            .into_iter()
653            .map(|(name, _)| name.to_string())
654            .collect();
655        for name in self.types.keys() {
656            if !names.iter().any(|n| n == name) {
657                names.push(name.clone());
658            }
659        }
660        for name in self.alias_names() {
661            if !names.contains(&name) {
662                names.push(name);
663            }
664        }
665        names
666    }
667}