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,
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/// Fresh name directory seeded with the startup descriptors.
63pub(super) fn startup_type_map() -> HashMap<String, &'static TypeDescriptor> {
64    startup_descriptors()
65        .into_iter()
66        .map(|(name, descriptor)| (name.to_string(), descriptor))
67        .collect()
68}
69
70impl<P: ProcessManager> ExecState<P> {
71    /// Register a host-defined type descriptor (usually `T::descriptor()`
72    /// for a `#[oxdock_type]` payload). Makes the name visible to `TYPES()`
73    /// and valid for `LET $x: NAME` declarations carrying same-named
74    /// payloads. Re-registering a name returns silently when the descriptor
75    /// is identical; a different descriptor under a live name panics
76    /// instead of aliasing two layouts.
77    pub fn register_type(&mut self, descriptor: &'static TypeDescriptor) {
78        if let Some(live) = self.types.get(descriptor.name) {
79            if !std::ptr::eq(*live, descriptor) {
80                panic!(
81                    "type name `{}` already registered for a different descriptor",
82                    descriptor.name
83                );
84            }
85            return;
86        }
87        self.types.insert(descriptor.name.to_string(), descriptor);
88    }
89
90    /// True when `name` names a registered type (startup or host).
91    pub fn is_known_type(&self, name: &str) -> bool {
92        self.types.contains_key(name)
93    }
94
95    /// Register a named record schema for shaped MAP bindings (usually
96    /// alongside the module that produces them). Makes the name valid
97    /// for `LET $x: NAME` declarations carrying conforming maps. A
98    /// different field table under a live name panics instead of
99    /// aliasing two shapes.
100    pub fn register_record_schema(&mut self, name: &'static str, fields: std::sync::Arc<[Field]>) {
101        if let Some(live) = self.record_schemas.get(name) {
102            if live.len() != fields.len()
103                || live
104                    .iter()
105                    .zip(fields.iter())
106                    .any(|(a, b)| a.name != b.name)
107            {
108                panic!("record schema `{name}` already registered with different fields");
109            }
110            return;
111        }
112        self.record_schemas.insert(name.to_string(), fields);
113    }
114
115    /// Every registered schema name, sorted. Backs discovery listings.
116    pub fn schema_names(&self) -> Vec<String> {
117        let mut names: Vec<String> = self.record_schemas.keys().cloned().collect();
118        names.sort();
119        names
120    }
121
122    /// Every script alias name, sorted. Backs discovery listings
123    /// and unknown-type errors alongside schemas.
124    pub fn alias_names(&self) -> Vec<String> {
125        let mut names: Vec<String> = self.type_aliases.keys().cloned().collect();
126        names.sort();
127        names
128    }
129
130    /// The canonical target spelling of one script alias, if defined.
131    /// Backs `TYPE_DESCRIBE` so aliases introspect like named types.
132    pub fn alias_target(&self, name: &str) -> Option<String> {
133        self.type_aliases.get(name).cloned()
134    }
135
136    /// Resolve a source-level type name to its tag: builtins by closed
137    /// match, customs through the type directory, named schemas through
138    /// the schema directory, script aliases through the alias directory,
139    /// generic spellings (`LIST<MAP>`, `MAP<name: STRING>`) rendered
140    /// structurally, and unions (`STRING|PIPE`, including inside
141    /// generics) with one interned entry per distinct spelling.
142    /// Anything else bails listing every known type, schema, and alias.
143    /// Single choke for every `LET`/`FUNC` declaration. Signature is
144    /// stable: alias cycles and shared depth accounting thread
145    /// internally, so all call sites gain generics with zero edits.
146    pub fn resolve_tag(&self, name: &str) -> Result<TypeTag> {
147        let canonical = canonicalize_spelling(name);
148        if canonical.contains('<') || canonical.contains('|') {
149            return self.resolve_spelling_text(&canonical, &mut Vec::new(), 0);
150        }
151        self.resolve_named(&canonical, &mut Vec::new(), 0)
152    }
153
154    /// Resolve one bare name through every directory. Alias targets
155    /// loop back through the spelling path, so `LIST<PERSON>`
156    /// combines; each alias hop costs 1 of the shared depth budget
157    /// and repeats bail naming the cycle.
158    fn resolve_named(
159        &self,
160        name: &str,
161        resolving: &mut Vec<String>,
162        depth: usize,
163    ) -> Result<TypeTag> {
164        if depth > MAX_GENERIC_DEPTH {
165            bail!("type spelling exceeds maximum generic depth of {MAX_GENERIC_DEPTH}: '{name}'");
166        }
167        if name == MAP_TYPE_NAME {
168            bail!(
169                "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"
170            );
171        }
172        if name == LIST_TYPE_NAME {
173            bail!(
174                "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"
175            );
176        }
177        if name == HANDLE_TYPE_NAME {
178            bail!(
179                "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"
180            );
181        }
182        if let Some(tag) = TypeTag::builtin(name) {
183            return Ok(tag);
184        }
185        if let Some(descriptor) = self.types.get(name) {
186            return Ok(TypeTag::Custom(descriptor));
187        }
188        if let Some(fields) = self.record_schemas.get(name) {
189            let tag = TypeTag::Record(fields.clone());
190            self.check_tag_known("declaration", &tag, false)?;
191            return Ok(tag);
192        }
193        if let Some(target) = self.type_aliases.get(name) {
194            if resolving.contains(&name.to_string()) {
195                resolving.push(name.to_string());
196                bail!("type alias cycle: {}", resolving.join(" -> "));
197            }
198            resolving.push(name.to_string());
199            let target = target.clone();
200            let result = self.resolve_spelling_text(&target, resolving, depth + 1);
201            resolving.pop();
202            return result;
203        }
204        bail!(
205            "unknown type '{name}'; known types: {} and schemas: {} and aliases: {}",
206            self.type_names().join(", "),
207            self.schema_names().join(", "),
208            self.alias_names().join(", "),
209        )
210    }
211
212    /// Resolve one canonical spelling that may carry `<...>` args:
213    /// interned hit returns shared, else parse, build, and intern.
214    fn resolve_spelling_text(
215        &self,
216        canonical: &str,
217        resolving: &mut Vec<String>,
218        depth: usize,
219    ) -> Result<TypeTag> {
220        if let Some(hit) = lookup_rendered(canonical) {
221            return Ok(hit);
222        }
223        let spelled = parse_spelling(canonical)
224            .map_err(|err| anyhow::anyhow!("invalid type spelling: {err}"))?;
225        let tag = self.build_rendered(&spelled, resolving, depth)?;
226        Ok(intern_rendered(canonical.to_string(), tag))
227    }
228
229    /// Build a parsed spelling into its structural tag. `LIST`
230    /// takes exactly one bare argument, `MAP` takes named fields;
231    /// anything else with arguments (or `MAP` with bare ones)
232    /// bails naming the rule. Leaves resolve through the full
233    /// directory, so schema and alias names nest freely. Union
234    /// members resolve the same way, so unions nest inside aliases,
235    /// generics, and each other through one shared normalizer.
236    fn build_rendered(
237        &self,
238        spelled: &Spelled,
239        resolving: &mut Vec<String>,
240        depth: usize,
241    ) -> Result<TypeTag> {
242        if depth > MAX_GENERIC_DEPTH {
243            bail!(
244                "type spelling exceeds maximum generic depth of {MAX_GENERIC_DEPTH}: '{spelled:?}'"
245            );
246        }
247        match spelled {
248            Spelled::Named(name) => self.resolve_named(name, resolving, depth),
249            Spelled::Generic { name, args } => self.build_generic(name, args, resolving, depth),
250            Spelled::Union(members) => {
251                let mut resolved = Vec::with_capacity(members.len());
252                for member in members {
253                    resolved.push(self.build_rendered(member, resolving, depth)?);
254                }
255                finish_union(resolved)
256            }
257        }
258    }
259
260    /// Build one generic application. `LIST` takes exactly one
261    /// bare argument, `MAP` takes named fields; any other head
262    /// resolves bare first so the error names the real problem
263    /// (`unknown type` vs. arguments on a scalar, custom,
264    /// schema, or alias target). Leaf homes leak like the rendered
265    /// entry itself (one per distinct spelling; see
266    /// `intern_rendered`), localized here for the same reason.
267    #[allow(clippy::disallowed_methods)]
268    fn build_generic(
269        &self,
270        name: &str,
271        args: &[SpelledField],
272        resolving: &mut Vec<String>,
273        depth: usize,
274    ) -> Result<TypeTag> {
275        if name != LIST_TYPE_NAME && name != MAP_TYPE_NAME && name != HANDLE_TYPE_NAME {
276            self.resolve_named(name, resolving, depth)?;
277            bail!("'{name}' takes no type arguments");
278        }
279        if name == HANDLE_TYPE_NAME {
280            let [
281                SpelledField {
282                    name: None,
283                    ty: payload,
284                    ..
285                },
286            ] = args
287            else {
288                bail!("{HANDLE_TYPE_NAME} takes exactly one bare type argument");
289            };
290            let payload = self.build_rendered(payload, resolving, depth + 1)?;
291            return Ok(TypeTag::HandleOf(std::sync::Arc::new(payload)));
292        }
293        if name == LIST_TYPE_NAME {
294            let [
295                SpelledField {
296                    name: None,
297                    ty: element,
298                    ..
299                },
300            ] = args
301            else {
302                bail!("{LIST_TYPE_NAME} takes exactly one bare type argument");
303            };
304            let element = self.build_rendered(element, resolving, depth + 1)?;
305            return Ok(TypeTag::ListOf(std::sync::Arc::new(element)));
306        }
307        if name == MAP_TYPE_NAME
308            && let [
309                SpelledField {
310                    name: None,
311                    ty: Spelled::Named(any),
312                    ..
313                },
314            ] = args
315            && any.as_str() == ANY_TYPE_NAME
316        {
317            // Explicit unknown map: the only bare MAP spelling. Anything
318            // else bare still rejects below, and plain `MAP` never
319            // resolves (see `resolve_named`).
320            return Ok(TypeTag::MapOf(std::sync::Arc::new(ANY_TAG)));
321        }
322        let mut fields = Vec::with_capacity(args.len());
323        for arg in args {
324            let Some(field_name) = arg.name.as_ref() else {
325                bail!(
326                    "{MAP_TYPE_NAME} fields require 'name: TYPE'; '{name}' takes no bare arguments"
327                );
328            };
329            let ty = self.build_rendered(&arg.ty, resolving, depth + 1)?;
330            fields.push(Field {
331                name: field_name.clone(),
332                ty,
333                docs: "",
334                optional: arg.optional,
335            });
336        }
337        Ok(TypeTag::Record(std::sync::Arc::from(fields)))
338    }
339}
340
341/// Normalize resolved union members into one tag: flatten nested
342/// unions, absorb on `ANY`, deduplicate, collapse lone survivors.
343/// Members keep written order while every comparison stays
344/// order-free, so all spellings behave identically. The tag owns
345/// everything through `Arc`: shared on clone, freed with the last
346/// owner, never leaked.
347fn finish_union(members: Vec<TypeTag>) -> Result<TypeTag> {
348    let mut flat: Vec<TypeTag> = Vec::with_capacity(members.len());
349    for member in members {
350        // Nested unions splice flat: members never nest, so every
351        // comparison stays one level deep by construction.
352        if let TypeTag::Union(_, nested) = member {
353            flat.extend(nested.iter().cloned());
354        } else {
355            flat.push(member);
356        }
357    }
358    if flat.is_empty() {
359        bail!("empty union: no member shapes to admit");
360    }
361    // `ANY` absorbs the set: admitting everything is `ANY`.
362    if flat.iter().any(|member| matches!(member, TypeTag::Any)) {
363        return Ok(TypeTag::Any);
364    }
365    // Full (not just consecutive) deduplication: order-free
366    // comparisons make every permutation behave identically.
367    let mut unique: Vec<TypeTag> = Vec::with_capacity(flat.len());
368    for member in flat {
369        if !unique
370            .iter()
371            .any(|seen| super::static_check::tags_equal(seen, &member))
372        {
373            unique.push(member);
374        }
375    }
376    if unique.len() == 1 {
377        return Ok(unique.pop().expect("single survivor checked above"));
378    }
379    Ok(TypeTag::union(unique))
380}
381
382/// Collect top-level `TYPE` alias definitions into the run's
383/// alias directory: name to canonical target spelling. Runs
384/// before the static pass so forward references resolve
385/// run-wide. Duplicates and collisions with builtin, host,
386/// schema, and top-level `FUNC` names are static errors
387/// naming the offender. Nested `TYPE` steps cannot occur
388/// (the parser rejects them); hand-built ones never resolve.
389pub fn collect_type_aliases<P: ProcessManager>(
390    steps: &[Step],
391    exec: &ExecState<P>,
392) -> Result<HashMap<String, String>> {
393    let mut func_names = HashSet::new();
394    for step in steps {
395        if let StepKind::FuncDef { name, .. } = &step.kind {
396            func_names.insert(name.clone());
397        }
398    }
399    let mut aliases = HashMap::new();
400    for step in steps {
401        let StepKind::TypeAlias { name, target } = &step.kind else {
402            continue;
403        };
404        if aliases.contains_key(name) {
405            bail!("type alias '{name}' is already defined");
406        }
407        if TypeTag::builtin(name).is_some() {
408            bail!("type alias '{name}' collides with a builtin type");
409        }
410        if exec.types.contains_key(name) {
411            bail!("type alias '{name}' collides with registered host type '{name}'");
412        }
413        if exec.record_schemas.contains_key(name) {
414            bail!("type alias '{name}' collides with registered record schema '{name}'");
415        }
416        if func_names.contains(name) {
417            bail!("type alias '{name}' collides with function '{name}'");
418        }
419        aliases.insert(name.clone(), canonicalize_spelling(target));
420    }
421    Ok(aliases)
422}
423
424impl<P: ProcessManager> ExecState<P> {
425    /// Check one tag against the directories: customs must name a
426    /// registered descriptor, shaped tags recurse into fields and
427    /// elements, builtins are variants and cannot be misspelled.
428    /// Unknown names bail naming the use site and every known type.
429    /// Single choke for declaration validity: known customs plus
430    /// the VOID position rule. VOID is legal only as a bare function
431    /// return (`top_void` covers exactly that call) or as the direct
432    /// payload of HANDLE (`HANDLE<VOID>`). Every other position is a
433    /// static error naming the site: variable, parameter, record
434    /// field, union member, container element, or anything nested
435    /// deeper. One recursion serves all declaration sites, so the
436    /// rule cannot drift between LET, params, returns, schemas, and
437    /// aliases: resolve first, then validate here.
438    fn check_tag_known(&self, what: &str, tag: &TypeTag, top_void: bool) -> Result<()> {
439        match tag {
440            TypeTag::Custom(descriptor) => {
441                if !self.types.contains_key(descriptor.name) {
442                    bail!(
443                        "{what} declares unregistered type '{}'; known types: {}",
444                        descriptor.name,
445                        self.type_names().join(", ")
446                    );
447                }
448            }
449            TypeTag::Void if !top_void => {
450                bail!(
451                    "{what} declares VOID outside a return annotation: VOID is only a return type (or HANDLE<VOID> payload)"
452                );
453            }
454            TypeTag::Void => {}
455            TypeTag::ListOf(element) => self.check_tag_known(what, element, false)?,
456            TypeTag::HandleOf(payload) => self.check_tag_known(what, payload, true)?,
457            TypeTag::MapOf(values) => self.check_tag_known(what, values, false)?,
458            TypeTag::Record(fields) => {
459                for field in fields.iter() {
460                    self.check_tag_known(what, &field.ty, false)?;
461                }
462            }
463            // Union members recurse like shaped tags: every member
464            // must name a known type, so no unknown hides in a set.
465            // A VOID member is never admitted: unions of handles stay
466            // inside the payload (HANDLE<INT|STRING>), never at the
467            // root or beside a value type.
468            TypeTag::Union(_, members) => {
469                for member in members.iter() {
470                    self.check_tag_known(what, member, false)?;
471                }
472            }
473            // Bare words are variants and cannot be misspelled: every
474            // builtin is listed so a new word kind fails here until
475            // its directory rule is explicit.
476            TypeTag::String
477            | TypeTag::Int
478            | TypeTag::Float
479            | TypeTag::Bool
480            | TypeTag::List
481            | TypeTag::Map
482            | TypeTag::Pipe
483            | TypeTag::Handle
484            | TypeTag::Duration
485            | TypeTag::Path
486            | TypeTag::Semaphore
487            | TypeTag::Permit
488            | TypeTag::Any => {}
489        }
490        Ok(())
491    }
492
493    /// Declaration-site gate for everything that is not a function
494    /// return: LET bindings, parameters, schemas, aliases at use.
495    /// Single choke so the VOID position rule cannot drift between
496    /// the static checker and runtime definition paths.
497    pub fn check_declaration_tag(&self, what: &str, tag: &TypeTag) -> Result<()> {
498        self.check_tag_known(what, tag, false)
499    }
500
501    /// Return-position gate: bare VOID is legal here (and only
502    /// here, besides HANDLE payloads). Same single recursion as
503    /// every other declaration site.
504    pub fn check_return_tag(&self, what: &str, tag: &TypeTag) -> Result<()> {
505        self.check_tag_known(what, tag, true)
506    }
507
508    /// Fail fast when any registered function declares param or return
509    /// type names outside the type directory. Runs once per run before
510    /// the first step executes: param arity and `LET` coercion already
511    /// check values at use time, but a typo'd `returns` label otherwise
512    /// lives forever as a lie in `DESCRIBE` output and generated
513    /// references. Unknown names bail listing every known type. A
514    /// closed `allowed` set without a type is rejected too: the set
515    /// only means something alongside the `STRING` check that enforces
516    /// it, so hand-built entries cannot render a set they never check.
517    pub fn validate_function_type_tags(&self) -> Result<()> {
518        for meta in self.functions.all_metas() {
519            if let Some(params) = meta.params.as_deref() {
520                for (position, param) in params.iter().enumerate() {
521                    if let Some(expected) = param.param_type.as_ref() {
522                        let what = format!("param '{}' of '{}'", param.name, meta.name);
523                        Self::check_tag_known(self, &what, expected, false)?;
524                    }
525                    if param.param_type.is_none() && param.allowed.is_some() {
526                        anyhow::bail!(
527                            "param '{}' of '{}' declares values without a type",
528                            param.name,
529                            meta.name,
530                        );
531                    }
532                    if param.optional {
533                        // Omission fills an empty MAP, so only trailing
534                        // MAP params qualify: anything else would fill a
535                        // value the caller never chose.
536                        let trails = params[position..].iter().all(|later| later.optional);
537                        if !trails {
538                            anyhow::bail!(
539                                "param '{}' of '{}' is optional before a required param",
540                                param.name,
541                                meta.name,
542                            );
543                        }
544                        if !matches!(param.param_type, Some(TypeTag::Map)) {
545                            anyhow::bail!(
546                                "param '{}' of '{}' is optional without a MAP type",
547                                param.name,
548                                meta.name,
549                            );
550                        }
551                    }
552                }
553            }
554            if let Some(returns) = meta.returns.as_ref() {
555                let what = format!("return of '{}'", meta.name);
556                Self::check_tag_known(self, &what, returns, true)?;
557            }
558        }
559        Ok(())
560    }
561
562    /// Resolve a descriptor by name, or `None` when unregistered.
563    pub fn describe_type(&self, name: &str) -> Option<&'static TypeDescriptor> {
564        self.types.get(name).copied()
565    }
566
567    /// Every registered type name: startup descriptors first, then hosts in
568    /// registration order, then script aliases.
569    pub fn type_names(&self) -> Vec<String> {
570        let mut names: Vec<String> = startup_descriptors()
571            .into_iter()
572            .map(|(name, _)| name.to_string())
573            .collect();
574        for name in self.types.keys() {
575            if !names.contains(&name.to_string()) {
576                names.push(name.clone());
577            }
578        }
579        for name in self.alias_names() {
580            if !names.contains(&name) {
581                names.push(name);
582            }
583        }
584        names
585    }
586}