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. Per-key value checks stay with
33/// the function (defaults, coercion, and cross-key rules are logic,
34/// not shape).
35pub fn check_options(
36    map: &std::collections::BTreeMap<String, Value>,
37    options: &[crate::ParamOption],
38    func: &str,
39) -> Result<()> {
40    for key in map.keys() {
41        if !options.iter().any(|known| known.name == key) {
42            let known: Vec<&str> = options.iter().map(|known| known.name).collect();
43            bail!(
44                "{func}() unknown option '{key}' (expected: {})",
45                known.join(", ")
46            );
47        }
48    }
49    Ok(())
50}
51
52/// Fresh name directory seeded with the startup descriptors.
53pub(super) fn startup_type_map() -> HashMap<String, &'static TypeDescriptor> {
54    startup_descriptors()
55        .into_iter()
56        .map(|(name, descriptor)| (name.to_string(), descriptor))
57        .collect()
58}
59
60impl<P: ProcessManager> ExecState<P> {
61    /// Register a host-defined type descriptor (usually `T::descriptor()`
62    /// for a `#[oxdock_type]` payload). Makes the name visible to `TYPES()`
63    /// and valid for `LET $x: NAME` declarations carrying same-named
64    /// payloads. Re-registering a name returns silently when the descriptor
65    /// is identical; a different descriptor under a live name panics
66    /// instead of aliasing two layouts.
67    pub fn register_type(&mut self, descriptor: &'static TypeDescriptor) {
68        if let Some(live) = self.types.get(descriptor.name) {
69            if !std::ptr::eq(*live, descriptor) {
70                panic!(
71                    "type name `{}` already registered for a different descriptor",
72                    descriptor.name
73                );
74            }
75            return;
76        }
77        self.types.insert(descriptor.name.to_string(), descriptor);
78    }
79
80    /// True when `name` names a registered type (startup or host).
81    pub fn is_known_type(&self, name: &str) -> bool {
82        self.types.contains_key(name)
83    }
84
85    /// Register a named record schema for shaped MAP bindings (usually
86    /// alongside the module that produces them). Makes the name valid
87    /// for `LET $x: NAME` declarations carrying conforming maps. A
88    /// different field table under a live name panics instead of
89    /// aliasing two shapes.
90    pub fn register_record_schema(&mut self, name: &'static str, fields: &'static [Field]) {
91        if let Some(live) = self.record_schemas.get(name) {
92            if live.len() != fields.len()
93                || live
94                    .iter()
95                    .zip(fields.iter())
96                    .any(|(a, b)| a.name != b.name)
97            {
98                panic!("record schema `{name}` already registered with different fields");
99            }
100            return;
101        }
102        self.record_schemas.insert(name.to_string(), fields);
103    }
104
105    /// Every registered schema name, sorted. Backs discovery listings.
106    pub fn schema_names(&self) -> Vec<String> {
107        let mut names: Vec<String> = self.record_schemas.keys().cloned().collect();
108        names.sort();
109        names
110    }
111
112    /// Every script alias name, sorted. Backs discovery listings
113    /// and unknown-type errors alongside schemas.
114    pub fn alias_names(&self) -> Vec<String> {
115        let mut names: Vec<String> = self.type_aliases.keys().cloned().collect();
116        names.sort();
117        names
118    }
119
120    /// The canonical target spelling of one script alias, if defined.
121    /// Backs `TYPE_DESCRIBE` so aliases introspect like named types.
122    pub fn alias_target(&self, name: &str) -> Option<String> {
123        self.type_aliases.get(name).cloned()
124    }
125
126    /// Resolve a source-level type name to its tag: builtins by closed
127    /// match, customs through the type directory, named schemas through
128    /// the schema directory, script aliases through the alias directory,
129    /// and generic spellings (`LIST<MAP>`, `MAP<name: STRING>`) composed
130    /// structurally with one interned entry per distinct spelling.
131    /// Anything else bails listing every known type, schema, and alias.
132    /// Single choke for every `LET`/`FUNC` declaration. Signature is
133    /// stable: alias cycles and shared depth accounting thread
134    /// internally, so all call sites gain generics with zero edits.
135    pub fn resolve_tag(&self, name: &str) -> Result<TypeTag> {
136        let canonical = canonicalize_spelling(name);
137        if canonical.contains('<') {
138            return self.resolve_spelling_text(&canonical, &mut Vec::new(), 0);
139        }
140        self.resolve_named(&canonical, &mut Vec::new(), 0)
141    }
142
143    /// Resolve one bare name through every directory. Alias targets
144    /// loop back through the spelling path, so `LIST<PERSON>`
145    /// composes; each alias hop costs 1 of the shared depth budget
146    /// and repeats bail naming the cycle.
147    fn resolve_named(
148        &self,
149        name: &str,
150        resolving: &mut Vec<String>,
151        depth: usize,
152    ) -> Result<TypeTag> {
153        if depth > MAX_GENERIC_DEPTH {
154            bail!("type spelling exceeds maximum generic depth of {MAX_GENERIC_DEPTH}: '{name}'");
155        }
156        if name == "MAP" {
157            bail!(
158                "bare MAP is not a declaration type: write a shape (MAP<name: TYPE, ...>) or MAP<ANY> for maps with unknown keys"
159            );
160        }
161        if name == "LIST" {
162            bail!(
163                "bare LIST is not a declaration type: write a shape (LIST<TYPE>) or LIST<ANY> for lists with unknown elements"
164            );
165        }
166        if let Some(tag) = TypeTag::builtin(name) {
167            return Ok(tag);
168        }
169        if let Some(descriptor) = self.types.get(name) {
170            return Ok(TypeTag::Custom(descriptor));
171        }
172        if let Some(fields) = self.record_schemas.get(name) {
173            let tag = TypeTag::Record(fields);
174            self.check_tag_known("declaration", &tag)?;
175            return Ok(tag);
176        }
177        if let Some(target) = self.type_aliases.get(name) {
178            if resolving.contains(&name.to_string()) {
179                resolving.push(name.to_string());
180                bail!("type alias cycle: {}", resolving.join(" -> "));
181            }
182            resolving.push(name.to_string());
183            let target = target.clone();
184            let result = self.resolve_spelling_text(&target, resolving, depth + 1);
185            resolving.pop();
186            return result;
187        }
188        bail!(
189            "unknown type '{name}'; known types: {} and schemas: {} and aliases: {}",
190            self.type_names().join(", "),
191            self.schema_names().join(", "),
192            self.alias_names().join(", "),
193        )
194    }
195
196    /// Resolve one canonical spelling that may carry `<...>` args:
197    /// interned hit returns shared, else parse, build, and intern.
198    fn resolve_spelling_text(
199        &self,
200        canonical: &str,
201        resolving: &mut Vec<String>,
202        depth: usize,
203    ) -> Result<TypeTag> {
204        if let Some(hit) = lookup_composed(canonical) {
205            return Ok(*hit);
206        }
207        let spelled = parse_spelling(canonical)
208            .map_err(|err| anyhow::anyhow!("invalid type spelling: {err}"))?;
209        let tag = self.build_composed(&spelled, resolving, depth)?;
210        Ok(*intern_composed(canonical.to_string(), tag))
211    }
212
213    /// Compose a parsed spelling into its structural tag. `LIST`
214    /// takes exactly one bare argument, `MAP` takes named fields;
215    /// anything else with arguments (or `MAP` with bare ones)
216    /// bails naming the rule. Leaves resolve through the full
217    /// directory, so schema and alias names nest freely.
218    fn build_composed(
219        &self,
220        spelled: &Spelled,
221        resolving: &mut Vec<String>,
222        depth: usize,
223    ) -> Result<TypeTag> {
224        if depth > MAX_GENERIC_DEPTH {
225            bail!(
226                "type spelling exceeds maximum generic depth of {MAX_GENERIC_DEPTH}: '{spelled:?}'"
227            );
228        }
229        match spelled {
230            Spelled::Named(name) => self.resolve_named(name, resolving, depth),
231            Spelled::Generic { name, args } => self.build_generic(name, args, resolving, depth),
232        }
233    }
234
235    /// Compose one generic application. `LIST` takes exactly one
236    /// bare argument, `MAP` takes named fields; any other head
237    /// resolves bare first so the error names the real problem
238    /// (`unknown type` vs. arguments on a scalar, custom,
239    /// schema, or alias target). Leaf homes leak like the composed
240    /// entry itself (one per distinct spelling; see
241    /// `intern_composed`), localized here for the same reason.
242    #[allow(clippy::disallowed_methods)]
243    fn build_generic(
244        &self,
245        name: &str,
246        args: &[SpelledField],
247        resolving: &mut Vec<String>,
248        depth: usize,
249    ) -> Result<TypeTag> {
250        if name != "LIST" && name != "MAP" {
251            self.resolve_named(name, resolving, depth)?;
252            bail!("'{name}' takes no type arguments");
253        }
254        if name == "LIST" {
255            let [
256                SpelledField {
257                    name: None,
258                    ty: element,
259                    ..
260                },
261            ] = args
262            else {
263                bail!("LIST takes exactly one bare type argument");
264            };
265            let element = self.build_composed(element, resolving, depth + 1)?;
266            return Ok(TypeTag::ListOf(Box::leak(Box::new(element))));
267        }
268        if name == "MAP"
269            && let [
270                SpelledField {
271                    name: None,
272                    ty: Spelled::Named(any),
273                    ..
274                },
275            ] = args
276            && any.as_str() == "ANY"
277        {
278            // Explicit unknown map: the only bare MAP spelling. Anything
279            // else bare still rejects below, and plain `MAP` never
280            // resolves (see `resolve_named`).
281            return Ok(TypeTag::MapOf(&ANY_TAG));
282        }
283        let mut fields = Vec::with_capacity(args.len());
284        for arg in args {
285            let Some(field_name) = arg.name.as_ref() else {
286                bail!("MAP fields require 'name: TYPE'; '{name}' takes no bare arguments");
287            };
288            let ty = self.build_composed(&arg.ty, resolving, depth + 1)?;
289            let leaked: &'static str = Box::leak(field_name.clone().into_boxed_str());
290            fields.push(Field {
291                name: leaked,
292                ty,
293                docs: "",
294                optional: arg.optional,
295            });
296        }
297        Ok(TypeTag::Record(Box::leak(fields.into_boxed_slice())))
298    }
299}
300/// Collect top-level `TYPE` alias definitions into the run's
301/// alias directory: name to canonical target spelling. Runs
302/// before the static pass so forward references resolve
303/// run-wide. Duplicates and collisions with builtin, host,
304/// schema, and top-level `FUNC` names are static errors
305/// naming the offender. Nested `TYPE` steps cannot occur
306/// (the parser rejects them); hand-built ones never resolve.
307pub fn collect_type_aliases<P: ProcessManager>(
308    steps: &[Step],
309    exec: &ExecState<P>,
310) -> Result<HashMap<String, String>> {
311    let mut func_names = HashSet::new();
312    for step in steps {
313        if let StepKind::FuncDef { name, .. } = &step.kind {
314            func_names.insert(name.clone());
315        }
316    }
317    let mut aliases = HashMap::new();
318    for step in steps {
319        let StepKind::TypeAlias { name, target } = &step.kind else {
320            continue;
321        };
322        if aliases.contains_key(name) {
323            bail!("type alias '{name}' is already defined");
324        }
325        if TypeTag::builtin(name).is_some() {
326            bail!("type alias '{name}' collides with a builtin type");
327        }
328        if exec.types.contains_key(name) {
329            bail!("type alias '{name}' collides with registered host type '{name}'");
330        }
331        if exec.record_schemas.contains_key(name) {
332            bail!("type alias '{name}' collides with registered record schema '{name}'");
333        }
334        if func_names.contains(name) {
335            bail!("type alias '{name}' collides with function '{name}'");
336        }
337        aliases.insert(name.clone(), canonicalize_spelling(target));
338    }
339    Ok(aliases)
340}
341
342impl<P: ProcessManager> ExecState<P> {
343    /// Check one tag against the directories: customs must name a
344    /// registered descriptor, shaped tags recurse into fields and
345    /// elements, builtins are variants and cannot be misspelled.
346    /// Unknown names bail naming the use site and every known type.
347    fn check_tag_known(&self, what: &str, tag: &TypeTag) -> Result<()> {
348        match tag {
349            TypeTag::Custom(descriptor) => {
350                if !self.types.contains_key(descriptor.name) {
351                    bail!(
352                        "{what} declares unregistered type '{}'; known types: {}",
353                        descriptor.name,
354                        self.type_names().join(", ")
355                    );
356                }
357            }
358            TypeTag::ListOf(element) => self.check_tag_known(what, element)?,
359            TypeTag::MapOf(values) => self.check_tag_known(what, values)?,
360            TypeTag::Record(fields) => {
361                for field in *fields {
362                    self.check_tag_known(what, &field.ty)?;
363                }
364            }
365            _ => {}
366        }
367        Ok(())
368    }
369
370    /// Fail fast when any registered function declares param or return
371    /// type names outside the type directory. Runs once per run before
372    /// the first step executes: param arity and `LET` coercion already
373    /// check values at use time, but a typo'd `returns` label otherwise
374    /// lives forever as a lie in `DESCRIBE` output and generated
375    /// references. Unknown names bail listing every known type. A
376    /// closed `allowed` set without a type is rejected too: the set
377    /// only means something alongside the `STRING` check that enforces
378    /// it, so hand-built entries cannot render a set they never check.
379    pub fn validate_function_type_tags(&self) -> Result<()> {
380        for meta in self.functions.all_metas() {
381            if let Some(params) = meta.params.as_deref() {
382                for (position, param) in params.iter().enumerate() {
383                    if let Some(expected) = param.param_type.as_ref() {
384                        let what = format!("param '{}' of '{}'", param.name, meta.name);
385                        Self::check_tag_known(self, &what, expected)?;
386                    }
387                    if param.param_type.is_none() && param.allowed.is_some() {
388                        anyhow::bail!(
389                            "param '{}' of '{}' declares values without a type",
390                            param.name,
391                            meta.name,
392                        );
393                    }
394                    if param.optional {
395                        // Omission fills an empty MAP, so only trailing
396                        // MAP params qualify: anything else would fill a
397                        // value the caller never chose.
398                        let trails = params[position..].iter().all(|later| later.optional);
399                        if !trails {
400                            anyhow::bail!(
401                                "param '{}' of '{}' is optional before a required param",
402                                param.name,
403                                meta.name,
404                            );
405                        }
406                        if !matches!(param.param_type, Some(TypeTag::Map)) {
407                            anyhow::bail!(
408                                "param '{}' of '{}' is optional without a MAP type",
409                                param.name,
410                                meta.name,
411                            );
412                        }
413                    }
414                }
415            }
416            if let Some(returns) = meta.returns.as_ref() {
417                let what = format!("return of '{}'", meta.name);
418                Self::check_tag_known(self, &what, returns)?;
419            }
420        }
421        Ok(())
422    }
423
424    /// Resolve a descriptor by name, or `None` when unregistered.
425    pub fn describe_type(&self, name: &str) -> Option<&'static TypeDescriptor> {
426        self.types.get(name).copied()
427    }
428
429    /// Every registered type name: startup descriptors first, then hosts in
430    /// registration order, then script aliases.
431    pub fn type_names(&self) -> Vec<String> {
432        let mut names: Vec<String> = startup_descriptors()
433            .into_iter()
434            .map(|(name, _)| name.to_string())
435            .collect();
436        for name in self.types.keys() {
437            if !names.contains(&name.to_string()) {
438                names.push(name.clone());
439            }
440        }
441        for name in self.alias_names() {
442            if !names.contains(&name) {
443                names.push(name);
444            }
445        }
446        names
447    }
448}