Skip to main content

oxdock_parser/
tag.rs

1//! Static type tags for function metadata and variable bindings.
2//!
3//! The DSL surface stays text (`LET $x: MAP`, `DESCRIBE`), but everything
4//! the engine reasons about is a [`TypeTag`]: builtins are enum variants
5//! a typo cannot spell, host handles carry their descriptor, and shaped
6//! maps carry their field table. Strings survive only at display and
7//! parse boundaries through [`TypeTag::name`] and [`TypeTag::builtin`].
8
9use anyhow::{Result, bail};
10
11use std::collections::HashMap;
12use std::sync::{Arc, Mutex, OnceLock};
13
14use crate::{TypeDescriptor, Value};
15
16/// Maximum generic nesting for one spelling: syntactic `<` levels
17/// and alias hops share this budget at resolution, so neither deep
18/// nesting nor long alias chains can wedge the pass. Parser-bounded
19/// scripts never approach it; exceeding it bails naming the shape.
20pub const MAX_GENERIC_DEPTH: usize = 8;
21
22/// Build a union tag from member variant idents: the spelling
23/// derives from the members' own names at construction, so no
24/// hand-written string can drift from the set it names. Unknown
25/// idents fail at the `TypeTag::` path, so misspelled members never
26/// compile. Empty sets are unrepresentable (one or more idents).
27/// Runtime-built (shared `Arc` payloads, freed with the last
28/// owner): not for `const` or `static` initializers.
29#[macro_export]
30macro_rules! union_tag {
31    ($($member:ident),+ $(,)?) => {
32        $crate::TypeTag::union(vec![$($crate::TypeTag::$member),+])
33    };
34}
35
36/// One named field of a [`TypeTag::Record`] schema.
37#[derive(Debug, Clone)]
38pub struct Field {
39    /// Field key as it appears in the value map. Owned: schema names
40    /// arrive from runtime spellings, so interning them would leak
41    /// per distinct spelling.
42    pub name: String,
43    /// Expected type of the field value. Nests freely.
44    pub ty: TypeTag,
45    /// What the field carries. Hand-registered schemas document every
46    /// field; fields synthesized from inline spellings carry none.
47    pub docs: &'static str,
48    /// Optional fields (`MAP<permit?: PERMIT>`) may be absent: missing
49    /// optional keys pass, missing required keys fail, extra keys
50    /// always fail.
51    pub optional: bool,
52}
53
54/// A declarative type for function params, returns, and bindings.
55///
56/// Builtins are variants, so exhaustiveness is compiler-checked wherever
57/// tags are matched. [`TypeTag::Custom`] carries a host descriptor for
58/// opaque handles. [`TypeTag::ListOf`], [`TypeTag::Record`],
59/// [`TypeTag::MapOf`], and [`TypeTag::Union`] share their payloads
60/// through [`Arc`]: cheap clones, no leaks, freed
61/// when the last owner drops. Bare `List` and `Map`
62/// are runtime words only, never declaration spellings. Unknown
63/// lists declare `LIST<ANY>`; unknown maps declare [`TypeTag::MapOf`]
64/// with [`TypeTag::Any`] values (`MAP<ANY>`).
65#[derive(Clone)]
66pub enum TypeTag {
67    String,
68    Int,
69    Float,
70    Bool,
71    List,
72    Map,
73    Pipe,
74    Handle,
75    HandleOf(Arc<TypeTag>),
76    Void,
77    Duration,
78    Path,
79    Semaphore,
80    Permit,
81    /// Every word: for parameters that accept anything by design
82    /// (coercion inputs, generic carriers). Boundary and coercion
83    /// both accept unconditionally, so the tag never lies.
84    Any,
85    Custom(&'static TypeDescriptor),
86    ListOf(Arc<TypeTag>),
87    Record(Arc<[Field]>),
88    MapOf(Arc<TypeTag>),
89    /// Admission set over existing words (`STRING|PIPE`): values stay
90    /// whatever words the members name, so no word reader changes.
91    /// The spelling is computed once at construction from the
92    /// members and shared; `name()` borrows it with no allocation.
93    /// Members are flat, deduplicated, and order-free by
94    /// construction, and every comparison is subset-based, so member
95    /// order never matters.
96    Union(Arc<str>, Arc<[TypeTag]>),
97}
98
99/// The `ANY` word for rendered tags: one shared instance so generic
100/// spellings like `MAP<ANY>` never mint competing statics.
101pub const ANY_TAG: TypeTag = TypeTag::Any;
102
103/// The MAP word for `TypeTag::ListOf` metadata: one shared instance
104/// so generated registrations never mint competing statics.
105pub const MAP_TAG: TypeTag = TypeTag::Map;
106
107/// The LIST word for `TypeTag` metadata, matching `MAP_TAG`.
108pub const LIST_TAG: TypeTag = TypeTag::List;
109
110/// The canonical source spelling of the handle word: declaration
111/// sites compare against this instead of a literal, so the spelling
112/// lives once beside the tag it names.
113pub const HANDLE_TYPE_NAME: &str = "HANDLE";
114
115/// The canonical source spelling of the list word, matching
116/// [`HANDLE_TYPE_NAME`]: generic heads compare against this.
117pub const LIST_TYPE_NAME: &str = "LIST";
118
119/// The canonical source spelling of the map word, matching
120/// [`HANDLE_TYPE_NAME`].
121pub const MAP_TYPE_NAME: &str = "MAP";
122
123/// The canonical source spelling of the any word, matching
124/// [`HANDLE_TYPE_NAME`].
125pub const ANY_TYPE_NAME: &str = "ANY";
126
127/// The canonical source spelling of the string word.
128pub const STRING_TYPE_NAME: &str = "STRING";
129
130/// The canonical source spelling of the int word.
131pub const INT_TYPE_NAME: &str = "INT";
132
133/// The canonical source spelling of the float word.
134pub const FLOAT_TYPE_NAME: &str = "FLOAT";
135
136/// The canonical source spelling of the bool word.
137pub const BOOL_TYPE_NAME: &str = "BOOL";
138
139/// The canonical source spelling of the pipe word.
140pub const PIPE_TYPE_NAME: &str = "PIPE";
141
142/// The canonical source spelling of the void word.
143pub const VOID_TYPE_NAME: &str = "VOID";
144
145/// The canonical source spelling of the duration word.
146pub const DURATION_TYPE_NAME: &str = "DURATION";
147
148/// The canonical source spelling of the path word.
149pub const PATH_TYPE_NAME: &str = "PATH";
150
151/// The canonical source spelling of the semaphore word.
152pub const SEMAPHORE_TYPE_NAME: &str = "SEMAPHORE";
153
154/// The canonical source spelling of the permit word.
155pub const PERMIT_TYPE_NAME: &str = "PERMIT";
156impl std::fmt::Debug for TypeTag {
157    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
158        match self {
159            TypeTag::Custom(descriptor) => {
160                write!(f, "Custom({})", descriptor.name)
161            }
162            TypeTag::ListOf(element) => write!(f, "ListOf({element:?})"),
163            TypeTag::HandleOf(inner) => write!(f, "HandleOf({inner:?})"),
164            TypeTag::MapOf(values) => write!(f, "MapOf({values:?})"),
165            TypeTag::Record(fields) => {
166                let names: Vec<&str> = fields.iter().map(|field| field.name.as_str()).collect();
167                write!(f, "Record({})", names.join(", "))
168            }
169            // Unions render their stored spelling, like shaped tags
170            // render their contents: the spelling names every member,
171            // so no member detail is lost. Bare words share the
172            // `name()` delegation below, which is itself exhaustive.
173            TypeTag::Union(spelling, _) => write!(f, "Union({spelling})"),
174            tag => write!(f, "{}", tag.name()),
175        }
176    }
177}
178
179impl std::fmt::Display for TypeTag {
180    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
181        f.write_str(self.name())
182    }
183}
184impl TypeTag {
185    /// Build a union tag from resolved members, computing the
186    /// canonical spelling from their structural renders. Single
187    /// source for the spelling: the macro and the resolve path
188    /// share it, so no hand-written string exists anywhere. Members
189    /// pass through as given (no normalization here): the resolve
190    /// path normalizes through its own pass before calling.
191    pub fn union(members: Vec<TypeTag>) -> TypeTag {
192        let spelling: Arc<str> = members
193            .iter()
194            .map(render_structural)
195            .collect::<Vec<_>>()
196            .join("|")
197            .into();
198        TypeTag::Union(spelling, Arc::from(members))
199    }
200
201    /// Display name: the builtin label, the custom descriptor name, or
202    /// the coarse word kind for shaped compounds. Field detail renders
203    /// structurally, never through this string. Borrowed in every
204    /// case: constants for words, the stored spelling for unions.
205    pub fn name(&self) -> &str {
206        match self {
207            TypeTag::String => STRING_TYPE_NAME,
208            TypeTag::Int => INT_TYPE_NAME,
209            TypeTag::Float => FLOAT_TYPE_NAME,
210            TypeTag::Bool => BOOL_TYPE_NAME,
211            TypeTag::List => LIST_TYPE_NAME,
212            TypeTag::Map => MAP_TYPE_NAME,
213            TypeTag::Pipe => PIPE_TYPE_NAME,
214            TypeTag::Handle => HANDLE_TYPE_NAME,
215            TypeTag::HandleOf(_) => HANDLE_TYPE_NAME,
216            TypeTag::Void => VOID_TYPE_NAME,
217            TypeTag::Duration => DURATION_TYPE_NAME,
218            TypeTag::Path => PATH_TYPE_NAME,
219            TypeTag::Semaphore => SEMAPHORE_TYPE_NAME,
220            TypeTag::Permit => PERMIT_TYPE_NAME,
221            TypeTag::Any => ANY_TYPE_NAME,
222            // Borrowed from the stored spelling: computed once at
223            // construction, shared by every clone.
224            TypeTag::Union(spelling, _) => spelling,
225            TypeTag::Custom(descriptor) => descriptor.name,
226            TypeTag::ListOf(_) => LIST_TYPE_NAME,
227            TypeTag::MapOf(_) => MAP_TYPE_NAME,
228            TypeTag::Record(_) => MAP_TYPE_NAME,
229        }
230    }
231
232    /// Resolve a builtin label to its tag. Custom, shaped, and unknown
233    /// names return `None`: customs resolve through the run's type
234    /// directory, shapes through the schema directory.
235    pub fn builtin(name: &str) -> Option<TypeTag> {
236        match name {
237            STRING_TYPE_NAME => Some(TypeTag::String),
238            INT_TYPE_NAME => Some(TypeTag::Int),
239            FLOAT_TYPE_NAME => Some(TypeTag::Float),
240            BOOL_TYPE_NAME => Some(TypeTag::Bool),
241            LIST_TYPE_NAME => Some(TypeTag::List),
242            MAP_TYPE_NAME => Some(TypeTag::Map),
243            PIPE_TYPE_NAME => Some(TypeTag::Pipe),
244            HANDLE_TYPE_NAME => Some(TypeTag::Handle),
245            VOID_TYPE_NAME => Some(TypeTag::Void),
246            DURATION_TYPE_NAME => Some(TypeTag::Duration),
247            PATH_TYPE_NAME => Some(TypeTag::Path),
248            SEMAPHORE_TYPE_NAME => Some(TypeTag::Semaphore),
249            PERMIT_TYPE_NAME => Some(TypeTag::Permit),
250            ANY_TYPE_NAME => Some(TypeTag::Any),
251            _ => None,
252        }
253    }
254
255    /// Field table for [`TypeTag::Record`], `None` otherwise.
256    /// Every non-record variant is listed: a new variant fails to
257    /// compile here until its fieldlessness is explicit, so record
258    /// structure can never silently leak into (or out of) another tag.
259    pub fn fields(&self) -> Option<&[Field]> {
260        match self {
261            TypeTag::Record(fields) => Some(fields),
262            TypeTag::String
263            | TypeTag::Int
264            | TypeTag::Float
265            | TypeTag::Bool
266            | TypeTag::List
267            | TypeTag::Map
268            | TypeTag::Pipe
269            | TypeTag::Handle
270            | TypeTag::HandleOf(_)
271            | TypeTag::Void
272            | TypeTag::Duration
273            | TypeTag::Path
274            | TypeTag::Semaphore
275            | TypeTag::Permit
276            | TypeTag::Any
277            | TypeTag::Custom(_)
278            | TypeTag::ListOf(_)
279            | TypeTag::MapOf(_)
280            | TypeTag::Union(..) => None,
281        }
282    }
283}
284
285/// Render one tag structurally: shaped tags name their contents
286/// (`LIST<MAP>`, `MAP<name: TYPE, ...>`), so signatures show the
287/// generics the extractor enforces instead of the coarse word
288/// kind. Single renderer for `DESCRIBE` and oxdock-render alike.
289pub fn render_structural(tag: &TypeTag) -> String {
290    match tag {
291        TypeTag::ListOf(inner) => format!("LIST<{}>", render_structural(inner)),
292        TypeTag::HandleOf(inner) => format!("HANDLE<{}>", render_structural(inner)),
293        TypeTag::MapOf(values) => format!("MAP<{}>", render_structural(values)),
294        TypeTag::Record(fields) => {
295            let field_list = fields
296                .iter()
297                .map(|field| {
298                    format!(
299                        "{}{}: {}",
300                        field.name,
301                        if field.optional { "?" } else { "" },
302                        render_structural(&field.ty)
303                    )
304                })
305                .collect::<Vec<_>>()
306                .join(", ");
307            format!("MAP<{field_list}>")
308        }
309        tag => tag.name().to_string(),
310    }
311}
312
313/// One parsed type spelling: a bare name, a generic application
314/// with positional (`LIST<MAP>`) or named (`MAP<name: STRING>`)
315/// arguments, or a union (`STRING|PIPE`) of sibling shapes. A named
316/// field with a `?` suffix is optional
317/// (`MAP<permit?: PERMIT>`). Arity and shape enforce at resolution,
318/// never here: `LIST<A, B>` and `STRING<INT>` parse and fail later
319/// naming the rule each breaks.
320#[derive(Debug, Clone, PartialEq, Eq)]
321pub enum Spelled {
322    Named(String),
323    Generic {
324        name: String,
325        args: Vec<SpelledField>,
326    },
327    Union(Vec<Spelled>),
328}
329
330/// One generic argument: a bare type or a named (possibly optional)
331/// record field carrying its nested spelling.
332#[derive(Debug, Clone, PartialEq, Eq)]
333pub struct SpelledField {
334    pub name: Option<String>,
335    pub optional: bool,
336    pub ty: Spelled,
337}
338
339/// Canonical spelling: exactly the structural representation
340/// (`MAP<name: STRING, age: INT>`), so stored declarations, intern
341/// keys, alias targets, and rendered signatures are one form, never
342/// two. Any input spacing parses to the same shape and renders to
343/// this form, which keeps every parse pathway in agreement.
344/// Malformed input passes through trimmed for the resolver to
345/// reject by name.
346pub fn canonicalize_spelling(s: &str) -> String {
347    let stripped: String = s.chars().filter(|c| !c.is_whitespace()).collect();
348    match parse_spelling(&stripped) {
349        Ok(spelled) => render_spelled(&spelled),
350        Err(_) => s.trim().to_string(),
351    }
352}
353
354/// Render one parsed spelling in canonical form: `LIST<MAP>`,
355/// `MAP<name: STRING, age: INT>`, `STRING|PIPE`. Deterministic by
356/// construction, so equal shapes share intern entries.
357pub fn render_spelled(spelled: &Spelled) -> String {
358    match spelled {
359        Spelled::Named(name) => name.clone(),
360        Spelled::Union(members) => members
361            .iter()
362            .map(render_spelled)
363            .collect::<Vec<_>>()
364            .join("|"),
365        Spelled::Generic { name, args } => {
366            let rendered: Vec<String> = args
367                .iter()
368                .map(|field| match &field.name {
369                    Some(field_name) => format!(
370                        "{}{}: {}",
371                        field_name,
372                        if field.optional { "?" } else { "" },
373                        render_spelled(&field.ty)
374                    ),
375                    None => render_spelled(&field.ty),
376                })
377                .collect();
378            format!("{name}<{}>", rendered.join(", "))
379        }
380    }
381}
382
383/// Parse a spelling into its shape. Hand-rolled descent: the
384/// grammar guarantees shape for parser strings, this keeps the
385/// public resolution API safe for direct callers. All whitespace
386/// is stripped before parsing, so any spaced form parses.
387pub fn parse_spelling(s: &str) -> Result<Spelled, String> {
388    let text: String = s.chars().filter(|c| !c.is_whitespace()).collect();
389    let (spelled, rest) = parse_spelled_one(&text, 0)?;
390    if !rest.is_empty() {
391        return Err(format!(
392            "unexpected trailing text in type spelling: {rest:?}"
393        ));
394    }
395    Ok(spelled)
396}
397
398fn parse_spelled_one(text: &str, depth: usize) -> Result<(Spelled, &str), String> {
399    let (first, mut rest) = parse_spelled_shape(text, depth)?;
400    if !rest.starts_with('|') {
401        return Ok((first, rest));
402    }
403    // Union tail: `A|B|C` accumulates sibling shapes at any level, so
404    // unions combine inside generic arguments as well as at top
405    // level. Members share the depth budget (siblings, not nesting);
406    // every piece consumes input, so the loop always terminates.
407    let mut members = vec![first];
408    while let Some(tail) = rest.strip_prefix('|') {
409        let (next, after) = parse_spelled_shape(tail, depth)?;
410        members.push(next);
411        rest = after;
412    }
413    Ok((Spelled::Union(members), rest))
414}
415
416fn parse_spelled_shape(text: &str, depth: usize) -> Result<(Spelled, &str), String> {
417    if depth > MAX_GENERIC_DEPTH {
418        return Err(format!(
419            "type spelling exceeds maximum generic depth of {MAX_GENERIC_DEPTH}: {text:?}"
420        ));
421    }
422    let mut chars = text.char_indices();
423    let Some((_, first)) = chars.next() else {
424        return Err("expected type name, found end of spelling".to_string());
425    };
426    if !first.is_ascii_uppercase() {
427        return Err(format!("expected uppercase type name, found {first:?}"));
428    }
429    let mut end = first.len_utf8();
430    for (idx, ch) in chars {
431        if ch.is_ascii_uppercase() || ch.is_ascii_digit() || ch == '_' {
432            end = idx + ch.len_utf8();
433        } else {
434            break;
435        }
436    }
437    let (name, mut rest) = text.split_at(end);
438    let name = name.to_string();
439    if !rest.starts_with('<') {
440        return Ok((Spelled::Named(name), rest));
441    }
442    rest = &rest[1..];
443    let mut args = Vec::new();
444    loop {
445        let (field_name, optional, after_name) = parse_spelled_field_name(rest);
446        let (arg, after_arg) = parse_spelled_one(after_name, depth + 1)?;
447        args.push(SpelledField {
448            name: field_name,
449            optional,
450            ty: arg,
451        });
452        rest = after_arg;
453        if let Some(tail) = rest.strip_prefix(',') {
454            rest = tail;
455            continue;
456        }
457        if let Some(tail) = rest.strip_prefix('>') {
458            rest = tail;
459            break;
460        }
461        return Err(format!(
462            "expected ',' or '>' in type spelling, found {rest:?}"
463        ));
464    }
465    Ok((Spelled::Generic { name, args }, rest))
466}
467
468/// Optional `field:` or `field?:` prefix of one generic argument. A
469/// lowercase name followed by an optional `?` and `:` claims the
470/// prefix (recording optionality); anything else leaves the text
471/// untouched for the bare-argument path.
472fn parse_spelled_field_name(text: &str) -> (Option<String>, bool, &str) {
473    let mut chars = text.char_indices();
474    let Some((_, first)) = chars.next() else {
475        return (None, false, text);
476    };
477    if !first.is_ascii_lowercase() {
478        return (None, false, text);
479    };
480    let mut end = first.len_utf8();
481    for (idx, ch) in chars {
482        if ch.is_ascii_lowercase() || ch.is_ascii_digit() || ch == '_' {
483            end = idx + ch.len_utf8();
484        } else {
485            break;
486        }
487    }
488    let (candidate, rest) = text.split_at(end);
489    let (optional, rest) = match rest.strip_prefix('?') {
490        Some(after) => (true, after),
491        None => (false, rest),
492    };
493    match rest.strip_prefix(':') {
494        Some(after) => (Some(candidate.to_string()), optional, after),
495        None => (None, false, text),
496    }
497}
498
499/// Process-global intern table for rendered tags: one shared
500/// `&'static TypeTag` per distinct canonical spelling. The lock is
501/// held only for lookup/insert; leaf resolution happens outside it
502/// in the caller.
503static RENDERD_TAGS: OnceLock<Mutex<HashMap<String, TypeTag>>> = OnceLock::new();
504
505fn rendered_table() -> &'static Mutex<HashMap<String, TypeTag>> {
506    RENDERD_TAGS.get_or_init(|| Mutex::new(HashMap::new()))
507}
508
509/// Look up an already-interned spelling. Resolution checks this
510/// before building, so identical spellings share one `Arc` payload
511/// family (pointer identity holds across clones).
512pub fn lookup_rendered(canonical: &str) -> Option<TypeTag> {
513    rendered_table()
514        .lock()
515        .unwrap_or_else(|poisoned| poisoned.into_inner())
516        .get(canonical)
517        .cloned()
518}
519
520/// Intern one rendered tag under its canonical spelling: a raced
521/// build stores once (the loser drops its duplicate, still bounded
522/// by distinct spellings per process). The table owns every entry
523/// (reachable, freed with the process like any cache): clones share
524/// payloads through `Arc`, so identity holds without leaks.
525pub fn intern_rendered(canonical: String, tag: TypeTag) -> TypeTag {
526    let mut table = rendered_table()
527        .lock()
528        .unwrap_or_else(|poisoned| poisoned.into_inner());
529    if let Some(hit) = table.get(&canonical) {
530        return hit.clone();
531    }
532    table.insert(canonical, tag.clone());
533    tag
534}
535
536/// Check a value against a tag, failing naming the expected shape and
537/// the offending path. Records reject missing AND extra fields: a
538/// schema is a lock, not a hint.
539pub fn check_value(tag: &TypeTag, value: &Value) -> Result<()> {
540    check_value_at(tag, value, "$")
541}
542
543/// Shape conformance with a caller-chosen path prefix: the single
544/// implementation behind generated parameter extractors, so boundary
545/// errors name the function, the parameter, and the nested position
546/// (`F() argument `$maps`[1]: expected MAP, got INT`) with no second
547/// copy of the shape logic anywhere.
548pub fn check_value_at(tag: &TypeTag, value: &Value, path: &str) -> Result<()> {
549    match tag {
550        TypeTag::Any => Ok(()),
551        TypeTag::String if value.as_str().is_some() => Ok(()),
552        TypeTag::Int if value.as_i64().is_some() => Ok(()),
553        TypeTag::Float if value.as_f64().is_some() => Ok(()),
554        TypeTag::Bool if value.as_bool().is_some() => Ok(()),
555        TypeTag::Pipe if value.as_pipe_handle().is_some() => Ok(()),
556        TypeTag::Handle if value.as_handle().is_some() => Ok(()),
557        TypeTag::HandleOf(_) if value.as_handle().is_some() => Ok(()),
558        TypeTag::Void => bail!("{path}: expected VOID, got {}", value.type_name()),
559        TypeTag::Duration if value.as_duration().is_some() => Ok(()),
560        TypeTag::Path if value.as_path().is_some() => Ok(()),
561        TypeTag::Semaphore if value.as_semaphore().is_some() => Ok(()),
562        TypeTag::Permit if value.as_permit().is_some() => Ok(()),
563        TypeTag::List => match value.as_list() {
564            Some(_) => Ok(()),
565            None => bail!("{path}: expected LIST, got {}", value.type_name()),
566        },
567        TypeTag::Map => match value.as_map() {
568            Some(_) => Ok(()),
569            None => bail!("{path}: expected MAP, got {}", value.type_name()),
570        },
571        TypeTag::ListOf(element) => match value.as_list() {
572            Some(items) => {
573                for (idx, item) in items.iter().enumerate() {
574                    check_value_at(element, item, &format!("{path}[{idx}]"))?;
575                }
576                Ok(())
577            }
578            None => bail!("{path}: expected LIST, got {}", value.type_name()),
579        },
580        TypeTag::MapOf(values) => match value.as_map() {
581            Some(map) => {
582                for (key, item) in map.iter() {
583                    check_value_at(values, item, &format!("{path}.{key}"))?;
584                }
585                Ok(())
586            }
587            None => bail!(
588                "{path}: expected {}, got {}",
589                render_structural(tag),
590                value.type_name()
591            ),
592        },
593        TypeTag::Record(fields) => match value.as_map() {
594            Some(map) => {
595                for field in fields.iter() {
596                    match map.get(field.name.as_str()) {
597                        Some(item) => {
598                            check_value_at(&field.ty, item, &format!("{path}.{}", field.name))?;
599                        }
600                        None if field.optional => {}
601                        None => bail!(
602                            "{path}: missing field '{}'; expected fields: {}",
603                            field.name,
604                            field_list(fields),
605                        ),
606                    }
607                }
608                for key in map.keys() {
609                    if !fields.iter().any(|field| field.name == *key) {
610                        bail!(
611                            "{path}: unknown field '{key}'; expected fields: {}",
612                            field_list(fields),
613                        );
614                    }
615                }
616                Ok(())
617            }
618            None => bail!("{path}: expected MAP, got {}", value.type_name()),
619        },
620        TypeTag::Custom(descriptor) => {
621            if value.type_name() == descriptor.name {
622                Ok(())
623            } else {
624                bail!(
625                    "{path}: expected {}, got {}",
626                    descriptor.name,
627                    value.type_name(),
628                )
629            }
630        }
631        // Admission set: any member passing admits the value, so
632        // member order never matters. All members failing names the
633        // set, never a single member.
634        TypeTag::Union(_, members) => {
635            if members
636                .iter()
637                .any(|member| check_value(member, value).is_ok())
638            {
639                Ok(())
640            } else {
641                bail!(
642                    "{path}: expected {}, got {}",
643                    render_structural(tag),
644                    value.type_name()
645                )
646            }
647        }
648        // Scalar mismatches: every scalar is listed so a new word
649        // kind fails to compile here until its mismatch text is
650        // explicit. No future variant can silently inherit this bail.
651        TypeTag::String
652        | TypeTag::Int
653        | TypeTag::Float
654        | TypeTag::Bool
655        | TypeTag::Pipe
656        | TypeTag::Handle
657        | TypeTag::HandleOf(_)
658        | TypeTag::Duration
659        | TypeTag::Path
660        | TypeTag::Semaphore
661        | TypeTag::Permit => bail!("{path}: expected {}, got {}", tag.name(), value.type_name()),
662    }
663}
664
665fn field_list(fields: &[Field]) -> String {
666    fields
667        .iter()
668        .map(|field| field.name.as_str())
669        .collect::<Vec<_>>()
670        .join(", ")
671}
672
673#[cfg(test)]
674mod tests {
675    use super::*;
676    use std::collections::BTreeMap;
677    use std::sync::Arc;
678
679    fn map(entries: &[(&str, Value)]) -> Value {
680        Value::map(
681            entries
682                .iter()
683                .map(|(k, v)| ((*k).to_string(), v.clone()))
684                .collect::<BTreeMap<_, _>>(),
685        )
686    }
687
688    #[test]
689    fn builtin_round_trips_through_names() {
690        for name in [
691            "STRING",
692            "INT",
693            "FLOAT",
694            "BOOL",
695            "LIST",
696            "MAP",
697            "PIPE",
698            "HANDLE",
699            "DURATION",
700            "PATH",
701            "SEMAPHORE",
702            "PERMIT",
703        ] {
704            let tag = TypeTag::builtin(name).expect("builtin");
705            assert_eq!(tag.name(), name);
706        }
707        assert!(TypeTag::builtin("NOPE").is_none());
708        assert!(TypeTag::builtin("string").is_none());
709    }
710
711    #[test]
712    fn scalars_conform_by_discriminant() {
713        assert!(check_value(&TypeTag::String, &Value::string("x".to_string())).is_ok());
714        assert!(check_value(&TypeTag::Int, &Value::int(1)).is_ok());
715        assert!(check_value(&TypeTag::String, &Value::int(1)).is_err());
716        // No cross coercion here: 3.0 is FLOAT, not INT.
717        assert!(check_value(&TypeTag::Int, &Value::float(3.0)).is_err());
718    }
719
720    #[test]
721    fn record_rejects_missing_and_extra_fields() {
722        let fields: Arc<[Field]> = Arc::from([
723            Field {
724                name: "a".to_string(),
725                ty: TypeTag::String,
726                docs: "",
727                optional: false,
728            },
729            Field {
730                name: "b".to_string(),
731                ty: TypeTag::Int,
732                docs: "",
733                optional: false,
734            },
735        ]);
736        let tag = TypeTag::Record(fields);
737        let good = map(&[("a", Value::string("x".to_string())), ("b", Value::int(1))]);
738        assert!(check_value(&tag, &good).is_ok());
739        let missing = map(&[("a", Value::string("x".to_string()))]);
740        let err = check_value(&tag, &missing).expect_err("missing must fail");
741        assert!(format!("{err:#}").contains('b'), "names the field: {err:#}");
742        let extra = map(&[
743            ("a", Value::string("x".to_string())),
744            ("b", Value::int(1)),
745            ("c", Value::int(2)),
746        ]);
747        let err = check_value(&tag, &extra).expect_err("extra must fail");
748        assert!(format!("{err:#}").contains('c'), "names the field: {err:#}");
749        let mistyped = map(&[
750            ("a", Value::string("x".to_string())),
751            ("b", Value::string("nope".to_string())),
752        ]);
753        assert!(check_value(&tag, &mistyped).is_err());
754    }
755
756    #[test]
757    fn record_optional_fields_may_be_absent() {
758        // Optional fields validate when present and pass when absent;
759        // required fields and extra keys still fail exactly.
760        let fields: Arc<[Field]> = Arc::from([
761            Field {
762                name: "held".to_string(),
763                ty: TypeTag::Int,
764                docs: "",
765                optional: false,
766            },
767            Field {
768                name: "permit".to_string(),
769                ty: TypeTag::String,
770                docs: "",
771                optional: true,
772            },
773        ]);
774        let tag = TypeTag::Record(fields);
775        let full = map(&[
776            ("held", Value::int(1)),
777            ("permit", Value::string("p".to_string())),
778        ]);
779        assert!(check_value(&tag, &full).is_ok());
780        let missing_optional = map(&[("held", Value::int(0))]);
781        assert!(check_value(&tag, &missing_optional).is_ok());
782        let missing_required = map(&[("permit", Value::string("p".to_string()))]);
783        let err = check_value(&tag, &missing_required).expect_err("missing required must fail");
784        assert!(
785            format!("{err:#}").contains("held"),
786            "names the field: {err:#}"
787        );
788        let mistyped_optional = map(&[("held", Value::int(1)), ("permit", Value::int(2))]);
789        assert!(check_value(&tag, &mistyped_optional).is_err());
790    }
791
792    #[test]
793    fn list_of_checks_elements_with_index() {
794        let tag = TypeTag::ListOf(Arc::new(TypeTag::Int));
795        let good = Value::list(vec![Value::int(1), Value::int(2)]);
796        assert!(check_value(&tag, &good).is_ok());
797        let bad = Value::list(vec![Value::int(1), Value::string("x".to_string())]);
798        let err = check_value(&tag, &bad).expect_err("bad element must fail");
799        assert!(
800            format!("{err:#}").contains("[1]"),
801            "names the index: {err:#}"
802        );
803    }
804
805    #[test]
806    fn canonicalization_unifies_input_spacing() {
807        // Every spaced form lands on the structural representation:
808        // the stored, keyed, and rendered form is one form.
809        assert_eq!(canonicalize_spelling("LIST<MAP>"), "LIST<MAP>");
810        assert_eq!(canonicalize_spelling("LIST< MAP >"), "LIST<MAP>");
811        assert_eq!(
812            canonicalize_spelling("MAP<name:STRING,age:INT>"),
813            "MAP<name: STRING, age: INT>"
814        );
815        assert_eq!(
816            canonicalize_spelling("MAP<name : STRING>"),
817            "MAP<name: STRING>"
818        );
819    }
820
821    #[test]
822    fn spellings_parse_to_shapes() {
823        assert_eq!(
824            parse_spelling("LIST<MAP>").expect("parses"),
825            Spelled::Generic {
826                name: "LIST".to_string(),
827                args: vec![SpelledField {
828                    name: None,
829                    optional: false,
830                    ty: Spelled::Named("MAP".to_string()),
831                }],
832            }
833        );
834        assert_eq!(
835            parse_spelling("MAP<name: STRING>").expect("parses"),
836            Spelled::Generic {
837                name: "MAP".to_string(),
838                args: vec![SpelledField {
839                    name: Some("name".to_string()),
840                    optional: false,
841                    ty: Spelled::Named("STRING".to_string()),
842                }],
843            }
844        );
845        // Arity violations parse; resolution rejects them naming
846        // the rule (`LIST` arity, `MAP` bare fields).
847        assert!(parse_spelling("LIST<A, B>").is_ok());
848        assert!(parse_spelling("MAP<STRING>").is_ok());
849    }
850
851    #[test]
852    fn optional_field_spelling_parses_and_renders() {
853        // A `?` suffix marks one field optional: it parses into the
854        // flag, canonicalizes with the mark, and renders back.
855        assert_eq!(
856            parse_spelling("MAP<permit?: PERMIT>").expect("parses"),
857            Spelled::Generic {
858                name: "MAP".to_string(),
859                args: vec![SpelledField {
860                    name: Some("permit".to_string()),
861                    optional: true,
862                    ty: Spelled::Named("PERMIT".to_string()),
863                }],
864            }
865        );
866        assert_eq!(
867            canonicalize_spelling("MAP<permit ? : PERMIT>"),
868            "MAP<permit?: PERMIT>"
869        );
870    }
871
872    #[test]
873    fn unknown_map_spelling_parses_and_renders() {
874        // `MAP<ANY>` is the explicit unknown map: it parses like any
875        // other generic spelling and renders back to itself.
876        assert_eq!(
877            parse_spelling("MAP<ANY>").expect("parses"),
878            Spelled::Generic {
879                name: "MAP".to_string(),
880                args: vec![SpelledField {
881                    name: None,
882                    optional: false,
883                    ty: Spelled::Named("ANY".to_string()),
884                }],
885            }
886        );
887        assert_eq!(canonicalize_spelling("MAP< ANY >"), "MAP<ANY>");
888        assert_eq!(
889            render_structural(&TypeTag::MapOf(Arc::new(TypeTag::Any))),
890            "MAP<ANY>"
891        );
892    }
893
894    #[test]
895    fn map_of_checks_values_with_paths() {
896        // Value shapes walk every entry with key paths; non-maps fail
897        // naming the structural shape, never the coarse word.
898        let tag = TypeTag::MapOf(Arc::new(TypeTag::Int));
899        let good = map(&[("a", Value::int(1))]);
900        assert!(check_value(&tag, &good).is_ok());
901        let bad = map(&[("a", Value::string("x".to_string()))]);
902        let err = check_value(&tag, &bad).expect_err("bad value must fail");
903        assert!(format!("{err:#}").contains(".a"), "names the key: {err:#}");
904        let not_map = Value::list(vec![Value::int(1)]);
905        let err = check_value(&tag, &not_map).expect_err("non-map must fail");
906        assert!(format!("{err:#}").contains("MAP<INT>"), "{err:#}");
907    }
908
909    #[test]
910    fn spellings_reject_malformed_input() {
911        for bad in [
912            "",
913            "LIST<>",
914            "LIST<A,>",
915            "MAP<name:>",
916            "LIST<A",
917            "list<MAP>",
918            "LIST<A>>",
919        ] {
920            assert!(parse_spelling(bad).is_err(), "{bad:?} must fail");
921        }
922        // Depth cap counts syntactic nesting; deeper bails naming it.
923        let mut deep = "INT".to_string();
924        for _ in 0..MAX_GENERIC_DEPTH + 1 {
925            deep = format!("LIST<{deep}>");
926        }
927        let err = parse_spelling(&deep).expect_err("over-deep spelling must fail");
928        assert!(err.contains("maximum generic depth"), "{err}");
929    }
930
931    #[test]
932    fn identical_spellings_share_one_interned_payload() {
933        let first = intern_rendered(
934            "LIST<MAP>".to_string(),
935            TypeTag::ListOf(Arc::new(TypeTag::Map)),
936        );
937        let second = intern_rendered(
938            "LIST<MAP>".to_string(),
939            TypeTag::ListOf(Arc::new(TypeTag::Map)),
940        );
941        let (TypeTag::ListOf(a), TypeTag::ListOf(b)) = (first, second) else {
942            panic!("rendered tags keep their shape");
943        };
944        assert!(
945            Arc::ptr_eq(&a, &b),
946            "same canonical spelling shares one payload"
947        );
948    }
949
950    #[test]
951    fn structural_rendering_names_contents() {
952        let fields: Arc<[Field]> = Arc::from([Field {
953            name: "name".to_string(),
954            ty: TypeTag::String,
955            docs: "",
956            optional: false,
957        }]);
958        let record = TypeTag::Record(fields);
959        let list = TypeTag::ListOf(Arc::new(record));
960        assert_eq!(render_structural(&list), "LIST<MAP<name: STRING>>");
961        assert_eq!(render_structural(&TypeTag::Int), "INT");
962    }
963}