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