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