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, constants::VAR_SIGIL};
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. A default (`MAP<retries: INT = 2>`) fills when
51    /// absent: defaults satisfy every binding check, and readers
52    /// never observe the hole.
53    pub optional: bool,
54    /// Fill value for absent fields (`None` when the shape carries
55    /// none). Materialized where the alias resolves and checked
56    /// against the field type there, so ill-typed defaults fail
57    /// naming the declaration.
58    pub default: Option<Value>,
59    /// Alternate CLI spelling (`MAP<h: BOOL ALIAS help>`): accepted on
60    /// the command line, canonical key stays `name` in the parsed map.
61    /// `None` for ordinary fields and every hand-registered schema.
62    pub alias: Option<String>,
63}
64
65/// A declarative type for function params, returns, and bindings.
66///
67/// Builtins are variants, so exhaustiveness is compiler-checked wherever
68/// tags are matched. [`TypeTag::Custom`] carries a host descriptor for
69/// opaque handles. [`TypeTag::ListOf`], [`TypeTag::Record`],
70/// [`TypeTag::MapOf`], and [`TypeTag::Union`] share their payloads
71/// through [`Arc`]: cheap clones, no leaks, freed
72/// when the last owner drops. Bare `List` and `Map`
73/// are runtime words only, never declaration spellings. Unknown
74/// lists declare `LIST<ANY>`; unknown maps declare [`TypeTag::MapOf`]
75/// with [`TypeTag::Any`] values (`MAP<ANY>`).
76#[derive(Clone)]
77pub enum TypeTag {
78    String,
79    Int,
80    Float,
81    Bool,
82    List,
83    Map,
84    Pipe,
85    Handle,
86    HandleOf(Arc<TypeTag>),
87    Void,
88    Duration,
89    Path,
90    Semaphore,
91    Permit,
92    /// Every word: for parameters that accept anything by design
93    /// (coercion inputs, generic carriers). Boundary and coercion
94    /// both accept unconditionally, so the tag never lies.
95    Any,
96    Custom(&'static TypeDescriptor),
97    ListOf(Arc<TypeTag>),
98    Record(Arc<[Field]>),
99    MapOf(Arc<TypeTag>),
100    /// Admission set over existing words (`STRING|PIPE`): values stay
101    /// whatever words the members name, so no word reader changes.
102    /// The spelling is computed once at construction from the
103    /// members and shared; `name()` borrows it with no allocation.
104    /// Members are flat, deduplicated, and order-free by
105    /// construction, and every comparison is subset-based, so member
106    /// order never matters.
107    Union(Arc<str>, Arc<[TypeTag]>),
108}
109
110/// The `ANY` word for rendered tags: one shared instance so generic
111/// spellings like `MAP<ANY>` never mint competing statics.
112pub const ANY_TAG: TypeTag = TypeTag::Any;
113
114/// The MAP word for `TypeTag::ListOf` metadata: one shared instance
115/// so generated registrations never mint competing statics.
116pub const MAP_TAG: TypeTag = TypeTag::Map;
117
118/// The LIST word for `TypeTag` metadata, matching `MAP_TAG`.
119pub const LIST_TAG: TypeTag = TypeTag::List;
120
121/// The canonical source spelling of the handle word: declaration
122/// sites compare against this instead of a literal, so the spelling
123/// lives once beside the tag it names.
124pub const HANDLE_TYPE_NAME: &str = "HANDLE";
125
126/// The canonical source spelling of the list word, matching
127/// [`HANDLE_TYPE_NAME`]: generic heads compare against this.
128pub const LIST_TYPE_NAME: &str = "LIST";
129
130/// The canonical source spelling of the map word, matching
131/// [`HANDLE_TYPE_NAME`].
132pub const MAP_TYPE_NAME: &str = "MAP";
133
134/// The canonical source spelling of the any word, matching
135/// [`HANDLE_TYPE_NAME`].
136pub const ANY_TYPE_NAME: &str = "ANY";
137
138/// The canonical source spelling of the string word.
139pub const STRING_TYPE_NAME: &str = "STRING";
140
141/// The canonical source spelling of the int word.
142pub const INT_TYPE_NAME: &str = "INT";
143
144/// The canonical source spelling of the float word.
145pub const FLOAT_TYPE_NAME: &str = "FLOAT";
146
147/// The canonical source spelling of the bool word.
148pub const BOOL_TYPE_NAME: &str = "BOOL";
149
150/// The canonical source spelling of the pipe word.
151pub const PIPE_TYPE_NAME: &str = "PIPE";
152
153/// The canonical source spelling of the void word.
154pub const VOID_TYPE_NAME: &str = "VOID";
155
156/// The canonical source spelling of the duration word.
157pub const DURATION_TYPE_NAME: &str = "DURATION";
158
159/// The canonical source spelling of the path word.
160pub const PATH_TYPE_NAME: &str = "PATH";
161
162/// The canonical source spelling of the semaphore word.
163pub const SEMAPHORE_TYPE_NAME: &str = "SEMAPHORE";
164
165/// The canonical source spelling of the permit word.
166pub const PERMIT_TYPE_NAME: &str = "PERMIT";
167
168/// The canonical source spelling of the `ALIAS` field-alias keyword:
169/// spelling and shape matching compare against this instead of a
170/// literal, so the keyword lives once beside the tags it modifies.
171pub const ALIAS_KEYWORD: &str = "ALIAS";
172impl std::fmt::Debug for TypeTag {
173    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
174        match self {
175            TypeTag::Custom(descriptor) => {
176                write!(f, "Custom({})", descriptor.name)
177            }
178            TypeTag::ListOf(element) => write!(f, "ListOf({element:?})"),
179            TypeTag::HandleOf(inner) => write!(f, "HandleOf({inner:?})"),
180            TypeTag::MapOf(values) => write!(f, "MapOf({values:?})"),
181            TypeTag::Record(fields) => {
182                let names: Vec<&str> = fields.iter().map(|field| field.name.as_str()).collect();
183                write!(f, "Record({})", names.join(", "))
184            }
185            // Unions render their stored spelling, like shaped tags
186            // render their contents: the spelling names every member,
187            // so no member detail is lost. Bare words share the
188            // `name()` delegation below, which is itself exhaustive.
189            TypeTag::Union(spelling, _) => write!(f, "Union({spelling})"),
190            tag => write!(f, "{}", tag.name()),
191        }
192    }
193}
194
195impl std::fmt::Display for TypeTag {
196    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
197        f.write_str(self.name())
198    }
199}
200impl TypeTag {
201    /// Build a union tag from resolved members, computing the
202    /// canonical spelling from their structural renders. Single
203    /// source for the spelling: the macro and the resolve path
204    /// share it, so no hand-written string exists anywhere. Members
205    /// pass through as given (no normalization here): the resolve
206    /// path normalizes through its own pass before calling.
207    pub fn union(members: Vec<TypeTag>) -> TypeTag {
208        let spelling: Arc<str> = members
209            .iter()
210            .map(render_structural)
211            .collect::<Vec<_>>()
212            .join("|")
213            .into();
214        TypeTag::Union(spelling, Arc::from(members))
215    }
216
217    /// Display name: the builtin label, the custom descriptor name, or
218    /// the coarse word kind for shaped compounds. Field detail renders
219    /// structurally, never through this string. Borrowed in every
220    /// case: constants for words, the stored spelling for unions.
221    pub fn name(&self) -> &str {
222        match self {
223            TypeTag::String => STRING_TYPE_NAME,
224            TypeTag::Int => INT_TYPE_NAME,
225            TypeTag::Float => FLOAT_TYPE_NAME,
226            TypeTag::Bool => BOOL_TYPE_NAME,
227            TypeTag::List => LIST_TYPE_NAME,
228            TypeTag::Map => MAP_TYPE_NAME,
229            TypeTag::Pipe => PIPE_TYPE_NAME,
230            TypeTag::Handle => HANDLE_TYPE_NAME,
231            TypeTag::HandleOf(_) => HANDLE_TYPE_NAME,
232            TypeTag::Void => VOID_TYPE_NAME,
233            TypeTag::Duration => DURATION_TYPE_NAME,
234            TypeTag::Path => PATH_TYPE_NAME,
235            TypeTag::Semaphore => SEMAPHORE_TYPE_NAME,
236            TypeTag::Permit => PERMIT_TYPE_NAME,
237            TypeTag::Any => ANY_TYPE_NAME,
238            // Borrowed from the stored spelling: computed once at
239            // construction, shared by every clone.
240            TypeTag::Union(spelling, _) => spelling,
241            TypeTag::Custom(descriptor) => descriptor.name,
242            TypeTag::ListOf(_) => LIST_TYPE_NAME,
243            TypeTag::MapOf(_) => MAP_TYPE_NAME,
244            TypeTag::Record(_) => MAP_TYPE_NAME,
245        }
246    }
247
248    /// Resolve a builtin label to its tag. Custom, shaped, and unknown
249    /// names return `None`: customs resolve through the run's type
250    /// directory, shapes through the schema directory.
251    pub fn builtin(name: &str) -> Option<TypeTag> {
252        match name {
253            STRING_TYPE_NAME => Some(TypeTag::String),
254            INT_TYPE_NAME => Some(TypeTag::Int),
255            FLOAT_TYPE_NAME => Some(TypeTag::Float),
256            BOOL_TYPE_NAME => Some(TypeTag::Bool),
257            LIST_TYPE_NAME => Some(TypeTag::List),
258            MAP_TYPE_NAME => Some(TypeTag::Map),
259            PIPE_TYPE_NAME => Some(TypeTag::Pipe),
260            HANDLE_TYPE_NAME => Some(TypeTag::Handle),
261            VOID_TYPE_NAME => Some(TypeTag::Void),
262            DURATION_TYPE_NAME => Some(TypeTag::Duration),
263            PATH_TYPE_NAME => Some(TypeTag::Path),
264            SEMAPHORE_TYPE_NAME => Some(TypeTag::Semaphore),
265            PERMIT_TYPE_NAME => Some(TypeTag::Permit),
266            ANY_TYPE_NAME => Some(TypeTag::Any),
267            _ => None,
268        }
269    }
270
271    /// Field table for [`TypeTag::Record`], `None` otherwise.
272    /// Every non-record variant is listed: a new variant fails to
273    /// compile here until its fieldlessness is explicit, so record
274    /// structure can never silently leak into (or out of) another tag.
275    pub fn fields(&self) -> Option<&[Field]> {
276        match self {
277            TypeTag::Record(fields) => Some(fields),
278            TypeTag::String
279            | TypeTag::Int
280            | TypeTag::Float
281            | TypeTag::Bool
282            | TypeTag::List
283            | TypeTag::Map
284            | TypeTag::Pipe
285            | TypeTag::Handle
286            | TypeTag::HandleOf(_)
287            | TypeTag::Void
288            | TypeTag::Duration
289            | TypeTag::Path
290            | TypeTag::Semaphore
291            | TypeTag::Permit
292            | TypeTag::Any
293            | TypeTag::Custom(_)
294            | TypeTag::ListOf(_)
295            | TypeTag::MapOf(_)
296            | TypeTag::Union(..) => None,
297        }
298    }
299}
300
301/// Render one tag structurally: shaped tags name their contents
302/// (`LIST<MAP>`, `MAP<name: TYPE, ...>`), so signatures show the
303/// generics the extractor enforces instead of the coarse word
304/// kind. Single renderer for `DESCRIBE` and oxdock-render alike.
305pub fn render_structural(tag: &TypeTag) -> String {
306    match tag {
307        TypeTag::ListOf(inner) => format!("LIST<{}>", render_structural(inner)),
308        TypeTag::HandleOf(inner) => format!("HANDLE<{}>", render_structural(inner)),
309        TypeTag::MapOf(values) => format!("MAP<{}>", render_structural(values)),
310        TypeTag::Record(fields) => {
311            let field_list = fields
312                .iter()
313                .map(|field| {
314                    format!(
315                        "{}{}: {}{}{}",
316                        field.name,
317                        if field.optional { "?" } else { "" },
318                        render_structural(&field.ty),
319                        field
320                            .alias
321                            .as_ref()
322                            .map(|a| format!(" {ALIAS_KEYWORD} {a}"))
323                            .unwrap_or_default(),
324                        field
325                            .default
326                            .as_ref()
327                            .map(|d| format!(" = {}", render_default_value(d)))
328                            .unwrap_or_default(),
329                    )
330                })
331                .collect::<Vec<_>>()
332                .join(", ");
333            format!("MAP<{field_list}>")
334        }
335        tag => tag.name().to_string(),
336    }
337}
338
339/// One parsed type spelling: a bare name, a generic application
340/// with positional (`LIST<MAP>`) or named (`MAP<name: STRING>`)
341/// arguments, or a union (`STRING|PIPE`) of sibling shapes. A named
342/// field with a `?` suffix is optional
343/// (`MAP<permit?: PERMIT>`). Arity and shape enforce at resolution,
344/// never here: `LIST<A, B>` and `STRING<INT>` parse and fail later
345/// naming the rule each breaks.
346#[derive(Debug, Clone, PartialEq, Eq)]
347pub enum Spelled {
348    Named(String),
349    Generic {
350        name: String,
351        args: Vec<SpelledField>,
352    },
353    Union(Vec<Spelled>),
354}
355
356/// One generic argument: a bare type or a named (possibly optional)
357/// record field carrying its nested spelling, optional `ALIAS`
358/// alternate flag spelling, and optional `= literal` default.
359/// Defaults are plain data here and become Values where the
360/// alias resolves, so spellings stay total and comparable.
361#[derive(Debug, Clone, PartialEq, Eq)]
362pub struct SpelledField {
363    pub name: Option<String>,
364    pub optional: bool,
365    pub ty: Spelled,
366    pub alias: Option<String>,
367    pub default: Option<SpelledDefault>,
368}
369
370/// One field default literal (`= 2`, `= "hi"`): integers, floats
371/// (stored as bits, since floats are not `Eq`), booleans, and
372/// double-quoted strings with no escapes. Plain data by design:
373/// resolution materializes the Value and checks it against the
374/// field type, so an ill-typed default fails naming the alias.
375#[derive(Debug, Clone, PartialEq, Eq)]
376pub enum SpelledDefault {
377    Str(String),
378    Int(i64),
379    Float(u64),
380    Bool(bool),
381}
382
383impl SpelledDefault {
384    /// Materialize the literal as a runtime word. Infallible by
385    /// construction: parsing validates, resolution converts.
386    pub fn to_value(&self) -> Value {
387        match self {
388            SpelledDefault::Str(s) => Value::string(s.clone()),
389            SpelledDefault::Int(n) => Value::int(*n),
390            SpelledDefault::Float(bits) => Value::float(f64::from_bits(*bits)),
391            SpelledDefault::Bool(b) => Value::bool(*b),
392        }
393    }
394
395    /// Canonical literal text: integers and booleans verbatim,
396    /// floats through `Debug` (shortest round-trip, always a
397    /// decimal point), strings double-quoted.
398    pub fn render(&self) -> String {
399        match self {
400            SpelledDefault::Str(s) => format!("\"{s}\""),
401            SpelledDefault::Int(n) => format!("{n}"),
402            SpelledDefault::Float(bits) => format!("{:?}", f64::from_bits(*bits)),
403            SpelledDefault::Bool(b) => format!("{b}"),
404        }
405    }
406}
407
408/// Canonical default literal text from a materialized word:
409/// integers and booleans verbatim, floats through `Debug`
410/// (shortest round-trip, always a decimal point), strings
411/// double-quoted. Must agree with [`SpelledDefault::render`]
412/// on every spelling-produced value; the round-trip test pins
413/// the agreement. Non-literals cannot arise from spellings;
414/// they render Debug rather than failing totality.
415pub fn render_default_value(value: &Value) -> String {
416    if let Some(n) = value.as_i64() {
417        return format!("{n}");
418    }
419    if let Some(f) = value.as_f64() {
420        return format!("{f:?}");
421    }
422    if let Some(b) = value.as_bool() {
423        return format!("{b}");
424    }
425    if let Some(s) = value.as_str() {
426        return format!("\"{s}\"");
427    }
428    format!("{value:?}")
429}
430
431/// Canonical spelling: exactly the structural representation
432/// (`MAP<name: STRING, age: INT>`), so stored declarations, intern
433/// keys, alias targets, and rendered signatures are one form, never
434/// two. Any input spacing parses to the same shape and renders to
435/// this form, which keeps every parse pathway in agreement.
436/// Malformed input passes through trimmed for the resolver to
437/// reject by name.
438pub fn canonicalize_spelling(s: &str) -> String {
439    match parse_spelling(s) {
440        Ok(spelled) => render_spelled(&spelled),
441        Err(_) => s.trim().to_string(),
442    }
443}
444
445/// Render one parsed spelling in canonical form: `LIST<MAP>`,
446/// `MAP<name: STRING, age: INT>`, `STRING|PIPE`. Deterministic by
447/// construction, so equal shapes share intern entries.
448pub fn render_spelled(spelled: &Spelled) -> String {
449    match spelled {
450        Spelled::Named(name) => name.clone(),
451        Spelled::Union(members) => members
452            .iter()
453            .map(render_spelled)
454            .collect::<Vec<_>>()
455            .join("|"),
456        Spelled::Generic { name, args } => {
457            let rendered: Vec<String> = args
458                .iter()
459                .map(|field| match &field.name {
460                    Some(field_name) => format!(
461                        "{}{}: {}{}{}",
462                        field_name,
463                        if field.optional { "?" } else { "" },
464                        render_spelled(&field.ty),
465                        field
466                            .alias
467                            .as_ref()
468                            .map(|a| format!(" {ALIAS_KEYWORD} {a}"))
469                            .unwrap_or_default(),
470                        field
471                            .default
472                            .as_ref()
473                            .map(|d| format!(" = {}", d.render()))
474                            .unwrap_or_default(),
475                    ),
476                    None => render_spelled(&field.ty),
477                })
478                .collect();
479            format!("{name}<{}>", rendered.join(", "))
480        }
481    }
482}
483
484/// Parse a spelling into its shape. Hand-rolled descent: the
485/// grammar guarantees shape for parser strings, this keeps the
486/// public resolution API safe for direct callers. Whitespace strips
487/// quote-aware (double-quoted default strings keep their spaces);
488/// any other spaced form parses.
489pub fn parse_spelling(s: &str) -> Result<Spelled, String> {
490    let text: String = strip_spelling_whitespace(s);
491    let (spelled, rest) = parse_spelled_one(&text, 0)?;
492    if !rest.is_empty() {
493        return Err(format!(
494            "unexpected trailing text in type spelling: {rest:?}"
495        ));
496    }
497    Ok(spelled)
498}
499
500/// Boundary marker surviving whitespace stripping: records where
501/// whitespace separated two word characters, so keywords fused by
502/// stripping stay distinguishable (`BOOL ALIAS help` keeps its
503/// boundaries while `FLAG_ALIAS` never gains one). Never valid in
504/// spellings; matched transiently mid-parse only.
505const WS_SENTINEL: char = '\u{1f}';
506
507/// Word characters for boundary tracking: ASCII alphanumerics plus
508/// underscore, matching field, type, and alias name shapes.
509fn is_spelling_word_char(ch: char) -> bool {
510    ch.is_ascii_alphanumeric() || ch == '_'
511}
512
513/// Strip whitespace outside double-quoted default strings: quoted
514/// regions keep their bytes verbatim, everything else drops gaps,
515/// except a [`WS_SENTINEL`] is left where whitespace separated two
516/// word characters so later stages still see the boundary.
517/// No escapes: a quote always toggles, so a default string cannot
518/// contain one (parse fails loudly instead of misreading).
519fn strip_spelling_whitespace(s: &str) -> String {
520    let mut out = String::with_capacity(s.len());
521    let mut quoted = false;
522    let mut pending_space = false;
523    let mut prev_word = false;
524    for ch in s.chars() {
525        if ch == '"' {
526            pending_space = false;
527            out.push(ch);
528            quoted = !quoted;
529            prev_word = false;
530            continue;
531        }
532        if !quoted && ch.is_whitespace() {
533            pending_space = true;
534            continue;
535        }
536        if pending_space && prev_word && !quoted && is_spelling_word_char(ch) {
537            out.push(WS_SENTINEL);
538        }
539        pending_space = false;
540        out.push(ch);
541        prev_word = !quoted && is_spelling_word_char(ch);
542    }
543    out
544}
545
546fn parse_spelled_one(text: &str, depth: usize) -> Result<(Spelled, &str), String> {
547    let (first, mut rest) = parse_spelled_shape(text, depth)?;
548    if !rest.starts_with('|') {
549        return Ok((first, rest));
550    }
551    // Union tail: `A|B|C` accumulates sibling shapes at any level, so
552    // unions combine inside generic arguments as well as at top
553    // level. Members share the depth budget (siblings, not nesting);
554    // every piece consumes input, so the loop always terminates.
555    let mut members = vec![first];
556    while let Some(tail) = rest.strip_prefix('|') {
557        let (next, after) = parse_spelled_shape(tail, depth)?;
558        members.push(next);
559        rest = after;
560    }
561    Ok((Spelled::Union(members), rest))
562}
563
564fn parse_spelled_shape(text: &str, depth: usize) -> Result<(Spelled, &str), String> {
565    if depth > MAX_GENERIC_DEPTH {
566        return Err(format!(
567            "type spelling exceeds maximum generic depth of {MAX_GENERIC_DEPTH}: {text:?}"
568        ));
569    }
570    let mut chars = text.char_indices();
571    let Some((_, first)) = chars.next() else {
572        return Err("expected type name, found end of spelling".to_string());
573    };
574    if !first.is_ascii_uppercase() {
575        return Err(format!("expected uppercase type name, found {first:?}"));
576    }
577    let mut end = first.len_utf8();
578    for (idx, ch) in chars {
579        if ch.is_ascii_uppercase() || ch.is_ascii_digit() || ch == '_' {
580            end = idx + ch.len_utf8();
581        } else {
582            break;
583        }
584    }
585    let (name, mut rest) = text.split_at(end);
586    let name = name.to_string();
587    if !rest.starts_with('<') {
588        return Ok((Spelled::Named(name), rest));
589    }
590    rest = &rest[1..];
591    let mut args = Vec::new();
592    loop {
593        let (field_name, optional, after_name) = parse_spelled_field_name(rest);
594        let (arg, after_arg) = parse_spelled_one(after_name, depth + 1)?;
595        let (alias, after_alias) = parse_spelled_alias(after_arg)?;
596        // Aliases ride named MAP fields only: bare arguments never
597        // carry an alternate spelling.
598        if alias.is_some() && field_name.is_none() {
599            return Err(format!(
600                "{ALIAS_KEYWORD} needs a named field, found bare {rest:?}"
601            ));
602        }
603        let (default, after_default) = parse_spelled_default(after_alias)?;
604        args.push(SpelledField {
605            name: field_name,
606            optional,
607            ty: arg,
608            alias,
609            default,
610        });
611        rest = after_default;
612        if let Some(tail) = rest.strip_prefix(',') {
613            rest = tail;
614            continue;
615        }
616        if let Some(tail) = rest.strip_prefix('>') {
617            rest = tail;
618            break;
619        }
620        return Err(format!(
621            "expected ',' or '>' in type spelling, found {rest:?}"
622        ));
623    }
624    Ok((Spelled::Generic { name, args }, rest))
625}
626
627/// Optional `field:` or `field?:` prefix of one generic argument. A
628/// lowercase name followed by an optional `?` and `:` claims the
629/// prefix (recording optionality); anything else leaves the text
630/// untouched for the bare-argument path.
631fn parse_spelled_field_name(text: &str) -> (Option<String>, bool, &str) {
632    let mut chars = text.char_indices();
633    let Some((_, first)) = chars.next() else {
634        return (None, false, text);
635    };
636    if !first.is_ascii_lowercase() {
637        return (None, false, text);
638    };
639    let mut end = first.len_utf8();
640    for (idx, ch) in chars {
641        if ch.is_ascii_lowercase() || ch.is_ascii_digit() || ch == '_' {
642            end = idx + ch.len_utf8();
643        } else {
644            break;
645        }
646    }
647    let (candidate, rest) = text.split_at(end);
648    let (optional, rest) = match rest.strip_prefix('?') {
649        Some(after) => (true, after),
650        None => (false, rest),
651    };
652    match rest.strip_prefix(':') {
653        Some(after) => (Some(candidate.to_string()), optional, after),
654        None => (None, false, text),
655    }
656}
657
658/// Optional `ALIAS name` after a field type: one alternate CLI
659/// spelling for `TYPE FLAGS` fields. Whitespace stripping leaves a
660/// [`WS_SENTINEL`] boundary around a separately-written keyword, so
661/// `BOOL ALIAS help` arrives splittable while `FLAG_ALIAS` never
662/// does; lowercase alias names keep the same shape as field names.
663/// No `ALIAS` means no alternate spelling.
664fn parse_spelled_alias(text: &str) -> Result<(Option<String>, &str), String> {
665    let text = text.strip_prefix(WS_SENTINEL).unwrap_or(text);
666    let Some(after_keyword) = text.strip_prefix(ALIAS_KEYWORD) else {
667        return Ok((None, text));
668    };
669    let after_keyword = after_keyword
670        .strip_prefix(WS_SENTINEL)
671        .unwrap_or(after_keyword);
672    if after_keyword.is_empty() {
673        return Err(format!("{ALIAS_KEYWORD} needs a lowercase alias name"));
674    }
675    let mut chars = after_keyword.char_indices();
676    let Some((_, first)) = chars.next() else {
677        return Err(format!("{ALIAS_KEYWORD} needs a lowercase alias name"));
678    };
679    if !first.is_ascii_lowercase() {
680        if !first.is_ascii_alphabetic() {
681            return Err(format!("{ALIAS_KEYWORD} needs a lowercase alias name"));
682        }
683        return Err(format!(
684            "{ALIAS_KEYWORD} name must start lowercase, found {first:?} in {after_keyword:?}"
685        ));
686    }
687    let mut end = first.len_utf8();
688    for (idx, ch) in chars {
689        if ch.is_ascii_lowercase() || ch.is_ascii_digit() || ch == '_' {
690            end = idx + ch.len_utf8();
691        } else {
692            break;
693        }
694    }
695    let (alias, rest) = after_keyword.split_at(end);
696    if alias.is_empty() {
697        return Err(format!("{ALIAS_KEYWORD} needs a lowercase alias name"));
698    }
699    Ok((Some(alias.to_string()), rest))
700}
701
702/// Optional `= literal` default after a field type: integers
703/// (optional `-`), decimals, `true`/`false`, or a double-quoted
704/// string with no escapes. No `=` means no default. Anything else
705/// fails naming the position, so malformed defaults never parse as
706/// a longer type.
707fn parse_spelled_default(text: &str) -> Result<(Option<SpelledDefault>, &str), String> {
708    let Some(after_eq) = text.strip_prefix('=') else {
709        return Ok((None, text));
710    };
711    let (lit, rest) = parse_spelled_literal(after_eq)?;
712    Ok((Some(lit), rest))
713}
714
715/// One default literal: the single owner for default spellings, so
716/// resolution and rendering agree on what parses. Trailing boundary
717/// checks belong to the caller: anything but `,` or `>` after the
718/// literal fails there naming the remainder.
719fn parse_spelled_literal(text: &str) -> Result<(SpelledDefault, &str), String> {
720    if let Some(after) = text.strip_prefix('"') {
721        match after.find('"') {
722            Some(end) => {
723                let (body, rest) = after.split_at(end);
724                return Ok((SpelledDefault::Str(body.to_string()), &rest[1..]));
725            }
726            None => {
727                return Err(format!(
728                    "unterminated string default in type spelling: {text:?}"
729                ));
730            }
731        }
732    }
733    if let Some(rest) = text.strip_prefix("true") {
734        return Ok((SpelledDefault::Bool(true), rest));
735    }
736    if let Some(rest) = text.strip_prefix("false") {
737        return Ok((SpelledDefault::Bool(false), rest));
738    }
739    let bytes = text.as_bytes();
740    let mut i = 0;
741    if bytes.first() == Some(&b'-') {
742        i += 1;
743    }
744    let int_start = i;
745    while bytes.get(i).is_some_and(|b| b.is_ascii_digit()) {
746        i += 1;
747    }
748    if i == int_start {
749        return Err(format!(
750            "expected default literal (INT, FLOAT, BOOL, or quoted STRING) in type spelling, found {text:?}"
751        ));
752    }
753    let mut is_float = false;
754    if bytes.get(i) == Some(&b'.') && bytes.get(i + 1).is_some_and(|b| b.is_ascii_digit()) {
755        is_float = true;
756        i += 1;
757        while bytes.get(i).is_some_and(|b| b.is_ascii_digit()) {
758            i += 1;
759        }
760    }
761    let (num, rest) = text.split_at(i);
762    if is_float {
763        match num.parse::<f64>() {
764            Ok(f) if f.is_finite() => Ok((SpelledDefault::Float(f.to_bits()), rest)),
765            _ => Err(format!("bad float default in type spelling: {num:?}")),
766        }
767    } else {
768        match num.parse::<i64>() {
769            Ok(n) => Ok((SpelledDefault::Int(n), rest)),
770            Err(_) => Err(format!("bad integer default in type spelling: {num:?}")),
771        }
772    }
773}
774
775/// Process-global intern table for rendered tags: one shared
776/// `&'static TypeTag` per distinct canonical spelling. The lock is
777/// held only for lookup/insert; leaf resolution happens outside it
778/// in the caller.
779static RENDERD_TAGS: OnceLock<Mutex<HashMap<String, TypeTag>>> = OnceLock::new();
780
781fn rendered_table() -> &'static Mutex<HashMap<String, TypeTag>> {
782    RENDERD_TAGS.get_or_init(|| Mutex::new(HashMap::new()))
783}
784
785/// Look up an already-interned spelling. Resolution checks this
786/// before building, so identical spellings share one `Arc` payload
787/// family (pointer identity holds across clones).
788pub fn lookup_rendered(canonical: &str) -> Option<TypeTag> {
789    rendered_table()
790        .lock()
791        .unwrap_or_else(|poisoned| poisoned.into_inner())
792        .get(canonical)
793        .cloned()
794}
795
796/// Intern one rendered tag under its canonical spelling: a raced
797/// build stores once (the loser drops its duplicate, still bounded
798/// by distinct spellings per process). The table owns every entry
799/// (reachable, freed with the process like any cache): clones share
800/// payloads through `Arc`, so identity holds without leaks.
801pub fn intern_rendered(canonical: String, tag: TypeTag) -> TypeTag {
802    let mut table = rendered_table()
803        .lock()
804        .unwrap_or_else(|poisoned| poisoned.into_inner());
805    if let Some(hit) = table.get(&canonical) {
806        return hit.clone();
807    }
808    table.insert(canonical, tag.clone());
809    tag
810}
811
812/// Check a value against a tag, failing naming the expected shape and
813/// the offending path. Records reject missing AND extra fields: a
814/// schema is a lock, not a hint. Fields with defaults count as
815/// satisfied when absent (every binding site fills them before
816/// verifying), so the lock holds without restating it per call site.
817pub fn check_value(tag: &TypeTag, value: &Value) -> Result<()> {
818    check_value_at(tag, value, VAR_SIGIL)
819}
820
821/// Shape conformance with a caller-chosen path prefix: the single
822/// implementation behind generated parameter extractors, so boundary
823/// errors name the function, the parameter, and the nested position
824/// (`F() argument `$maps`[1]: expected MAP, got INT`) with no second
825/// copy of the shape logic anywhere.
826pub fn check_value_at(tag: &TypeTag, value: &Value, path: &str) -> Result<()> {
827    match tag {
828        TypeTag::Any => Ok(()),
829        TypeTag::String if value.as_str().is_some() => Ok(()),
830        TypeTag::Int if value.as_i64().is_some() => Ok(()),
831        TypeTag::Float if value.as_f64().is_some() => Ok(()),
832        TypeTag::Bool if value.as_bool().is_some() => Ok(()),
833        TypeTag::Pipe if value.as_pipe_handle().is_some() => Ok(()),
834        TypeTag::Handle if value.as_handle().is_some() => Ok(()),
835        TypeTag::HandleOf(_) if value.as_handle().is_some() => Ok(()),
836        TypeTag::Void => bail!("{path}: expected VOID, got {}", value.type_name()),
837        TypeTag::Duration if value.as_duration().is_some() => Ok(()),
838        TypeTag::Path if value.as_path().is_some() => Ok(()),
839        TypeTag::Semaphore if value.as_semaphore().is_some() => Ok(()),
840        TypeTag::Permit if value.as_permit().is_some() => Ok(()),
841        TypeTag::List => match value.as_list() {
842            Some(_) => Ok(()),
843            None => bail!("{path}: expected LIST, got {}", value.type_name()),
844        },
845        TypeTag::Map => match value.as_map() {
846            Some(_) => Ok(()),
847            None => bail!("{path}: expected MAP, got {}", value.type_name()),
848        },
849        TypeTag::ListOf(element) => match value.as_list() {
850            Some(items) => {
851                for (idx, item) in items.iter().enumerate() {
852                    check_value_at(element, item, &format!("{path}[{idx}]"))?;
853                }
854                Ok(())
855            }
856            None => bail!("{path}: expected LIST, got {}", value.type_name()),
857        },
858        TypeTag::MapOf(values) => match value.as_map() {
859            Some(map) => {
860                for (key, item) in map.iter() {
861                    check_value_at(values, item, &format!("{path}.{key}"))?;
862                }
863                Ok(())
864            }
865            None => bail!(
866                "{path}: expected {}, got {}",
867                render_structural(tag),
868                value.type_name()
869            ),
870        },
871        TypeTag::Record(fields) => match value.as_map() {
872            Some(map) => {
873                for field in fields.iter() {
874                    match map.get(field.name.as_str()) {
875                        Some(item) => {
876                            check_value_at(&field.ty, item, &format!("{path}.{}", field.name))?;
877                        }
878                        // Optional or defaulted fields may be absent:
879                        // every binding site fills defaults before
880                        // verifying, so absence here only fails for
881                        // required fields with no default.
882                        None if field.optional || field.default.is_some() => {}
883                        None => bail!(
884                            "{path}: missing field '{}'; expected fields: {}",
885                            field.name,
886                            field_list(fields),
887                        ),
888                    }
889                }
890                for key in map.keys() {
891                    if !fields.iter().any(|field| field.name == *key) {
892                        bail!(
893                            "{path}: unknown field '{key}'; expected fields: {}",
894                            field_list(fields),
895                        );
896                    }
897                }
898                Ok(())
899            }
900            None => bail!("{path}: expected MAP, got {}", value.type_name()),
901        },
902        TypeTag::Custom(descriptor) => {
903            if value.type_name() == descriptor.name {
904                Ok(())
905            } else {
906                bail!(
907                    "{path}: expected {}, got {}",
908                    descriptor.name,
909                    value.type_name(),
910                )
911            }
912        }
913        // Admission set: any member passing admits the value, so
914        // member order never matters. All members failing names the
915        // set, never a single member.
916        TypeTag::Union(_, members) => {
917            if members
918                .iter()
919                .any(|member| check_value(member, value).is_ok())
920            {
921                Ok(())
922            } else {
923                bail!(
924                    "{path}: expected {}, got {}",
925                    render_structural(tag),
926                    value.type_name()
927                )
928            }
929        }
930        // Scalar mismatches: every scalar is listed so a new word
931        // kind fails to compile here until its mismatch text is
932        // explicit. No future variant can silently inherit this bail.
933        TypeTag::String
934        | TypeTag::Int
935        | TypeTag::Float
936        | TypeTag::Bool
937        | TypeTag::Pipe
938        | TypeTag::Handle
939        | TypeTag::HandleOf(_)
940        | TypeTag::Duration
941        | TypeTag::Path
942        | TypeTag::Semaphore
943        | TypeTag::Permit => bail!("{path}: expected {}, got {}", tag.name(), value.type_name()),
944    }
945}
946
947fn field_list(fields: &[Field]) -> String {
948    fields
949        .iter()
950        .map(|field| field.name.as_str())
951        .collect::<Vec<_>>()
952        .join(", ")
953}
954
955#[cfg(test)]
956mod tests {
957    use super::*;
958    use std::collections::BTreeMap;
959    use std::sync::Arc;
960
961    fn map(entries: &[(&str, Value)]) -> Value {
962        Value::map(
963            entries
964                .iter()
965                .map(|(k, v)| ((*k).to_string(), v.clone()))
966                .collect::<BTreeMap<_, _>>(),
967        )
968    }
969
970    #[test]
971    fn builtin_round_trips_through_names() {
972        for name in [
973            "STRING",
974            "INT",
975            "FLOAT",
976            "BOOL",
977            "LIST",
978            "MAP",
979            "PIPE",
980            "HANDLE",
981            "DURATION",
982            "PATH",
983            "SEMAPHORE",
984            "PERMIT",
985        ] {
986            let tag = TypeTag::builtin(name).expect("builtin");
987            assert_eq!(tag.name(), name);
988        }
989        assert!(TypeTag::builtin("NOPE").is_none());
990        assert!(TypeTag::builtin("string").is_none());
991    }
992
993    #[test]
994    fn scalars_conform_by_discriminant() {
995        assert!(check_value(&TypeTag::String, &Value::string("x".to_string())).is_ok());
996        assert!(check_value(&TypeTag::Int, &Value::int(1)).is_ok());
997        assert!(check_value(&TypeTag::String, &Value::int(1)).is_err());
998        // No cross coercion here: 3.0 is FLOAT, not INT.
999        assert!(check_value(&TypeTag::Int, &Value::float(3.0)).is_err());
1000    }
1001
1002    #[test]
1003    fn record_rejects_missing_and_extra_fields() {
1004        let fields: Arc<[Field]> = Arc::from([
1005            Field {
1006                name: "a".to_string(),
1007                ty: TypeTag::String,
1008                docs: "",
1009                optional: false,
1010                default: None,
1011
1012                alias: None,
1013            },
1014            Field {
1015                name: "b".to_string(),
1016                ty: TypeTag::Int,
1017                docs: "",
1018                optional: false,
1019                default: None,
1020
1021                alias: None,
1022            },
1023        ]);
1024        let tag = TypeTag::Record(fields);
1025        let good = map(&[("a", Value::string("x".to_string())), ("b", Value::int(1))]);
1026        assert!(check_value(&tag, &good).is_ok());
1027        let missing = map(&[("a", Value::string("x".to_string()))]);
1028        let err = check_value(&tag, &missing).expect_err("missing must fail");
1029        assert!(format!("{err:#}").contains('b'), "names the field: {err:#}");
1030        let extra = map(&[
1031            ("a", Value::string("x".to_string())),
1032            ("b", Value::int(1)),
1033            ("c", Value::int(2)),
1034        ]);
1035        let err = check_value(&tag, &extra).expect_err("extra must fail");
1036        assert!(format!("{err:#}").contains('c'), "names the field: {err:#}");
1037        let mistyped = map(&[
1038            ("a", Value::string("x".to_string())),
1039            ("b", Value::string("nope".to_string())),
1040        ]);
1041        assert!(check_value(&tag, &mistyped).is_err());
1042    }
1043
1044    #[test]
1045    fn record_optional_fields_may_be_absent() {
1046        // Optional fields validate when present and pass when absent;
1047        // required fields and extra keys still fail exactly.
1048        let fields: Arc<[Field]> = Arc::from([
1049            Field {
1050                name: "held".to_string(),
1051                ty: TypeTag::Int,
1052                docs: "",
1053                optional: false,
1054                default: None,
1055
1056                alias: None,
1057            },
1058            Field {
1059                name: "permit".to_string(),
1060                ty: TypeTag::String,
1061                docs: "",
1062                optional: true,
1063                default: None,
1064
1065                alias: None,
1066            },
1067        ]);
1068        let tag = TypeTag::Record(fields);
1069        let full = map(&[
1070            ("held", Value::int(1)),
1071            ("permit", Value::string("p".to_string())),
1072        ]);
1073        assert!(check_value(&tag, &full).is_ok());
1074        let missing_optional = map(&[("held", Value::int(0))]);
1075        assert!(check_value(&tag, &missing_optional).is_ok());
1076        let missing_required = map(&[("permit", Value::string("p".to_string()))]);
1077        let err = check_value(&tag, &missing_required).expect_err("missing required must fail");
1078        assert!(
1079            format!("{err:#}").contains("held"),
1080            "names the field: {err:#}"
1081        );
1082        let mistyped_optional = map(&[("held", Value::int(1)), ("permit", Value::int(2))]);
1083        assert!(check_value(&tag, &mistyped_optional).is_err());
1084    }
1085
1086    #[test]
1087    fn list_of_checks_elements_with_index() {
1088        let tag = TypeTag::ListOf(Arc::new(TypeTag::Int));
1089        let good = Value::list(vec![Value::int(1), Value::int(2)]);
1090        assert!(check_value(&tag, &good).is_ok());
1091        let bad = Value::list(vec![Value::int(1), Value::string("x".to_string())]);
1092        let err = check_value(&tag, &bad).expect_err("bad element must fail");
1093        assert!(
1094            format!("{err:#}").contains("[1]"),
1095            "names the index: {err:#}"
1096        );
1097    }
1098
1099    #[test]
1100    fn canonicalization_unifies_input_spacing() {
1101        // Every spaced form lands on the structural representation:
1102        // the stored, keyed, and rendered form is one form.
1103        assert_eq!(canonicalize_spelling("LIST<MAP>"), "LIST<MAP>");
1104        assert_eq!(canonicalize_spelling("LIST< MAP >"), "LIST<MAP>");
1105        assert_eq!(
1106            canonicalize_spelling("MAP<name:STRING,age:INT>"),
1107            "MAP<name: STRING, age: INT>"
1108        );
1109        assert_eq!(
1110            canonicalize_spelling("MAP<name : STRING>"),
1111            "MAP<name: STRING>"
1112        );
1113    }
1114
1115    #[test]
1116    fn spellings_parse_to_shapes() {
1117        assert_eq!(
1118            parse_spelling("LIST<MAP>").expect("parses"),
1119            Spelled::Generic {
1120                name: "LIST".to_string(),
1121                args: vec![SpelledField {
1122                    name: None,
1123                    optional: false,
1124                    ty: Spelled::Named("MAP".to_string()),
1125                    default: None,
1126
1127                    alias: None,
1128                }],
1129            }
1130        );
1131        assert_eq!(
1132            parse_spelling("MAP<name: STRING>").expect("parses"),
1133            Spelled::Generic {
1134                name: "MAP".to_string(),
1135                args: vec![SpelledField {
1136                    name: Some("name".to_string()),
1137                    optional: false,
1138                    ty: Spelled::Named("STRING".to_string()),
1139                    default: None,
1140
1141                    alias: None,
1142                }],
1143            }
1144        );
1145        // Arity violations parse; resolution rejects them naming
1146        // the rule (`LIST` arity, `MAP` bare fields).
1147        assert!(parse_spelling("LIST<A, B>").is_ok());
1148        assert!(parse_spelling("MAP<STRING>").is_ok());
1149    }
1150
1151    #[test]
1152    fn optional_field_spelling_parses_and_renders() {
1153        // A `?` suffix marks one field optional: it parses into the
1154        // flag, canonicalizes with the mark, and renders back.
1155        assert_eq!(
1156            parse_spelling("MAP<permit?: PERMIT>").expect("parses"),
1157            Spelled::Generic {
1158                name: "MAP".to_string(),
1159                args: vec![SpelledField {
1160                    name: Some("permit".to_string()),
1161                    optional: true,
1162                    ty: Spelled::Named("PERMIT".to_string()),
1163                    default: None,
1164
1165                    alias: None,
1166                }],
1167            }
1168        );
1169        assert_eq!(
1170            canonicalize_spelling("MAP<permit ? : PERMIT>"),
1171            "MAP<permit?: PERMIT>"
1172        );
1173    }
1174
1175    #[test]
1176    fn default_spellings_parse_render_and_materialize() {
1177        // `= literal` rides one field: ints, negative ints, floats,
1178        // bools, and quoted strings (spaces kept). Each parses into
1179        // the literal, canonicalizes back, and materializes the word.
1180        for (spelling, canonical, value) in [
1181            (
1182                "MAP<retries: INT = 2>",
1183                "MAP<retries: INT = 2>",
1184                Value::int(2),
1185            ),
1186            (
1187                "MAP<retries: INT=-2>",
1188                "MAP<retries: INT = -2>",
1189                Value::int(-2),
1190            ),
1191            (
1192                "MAP<ratio: FLOAT = 2.5>",
1193                "MAP<ratio: FLOAT = 2.5>",
1194                Value::float(2.5),
1195            ),
1196            (
1197                "MAP<on: BOOL = true>",
1198                "MAP<on: BOOL = true>",
1199                Value::bool(true),
1200            ),
1201            (
1202                "MAP<model: STRING = \"gpt-4\">",
1203                "MAP<model: STRING = \"gpt-4\">",
1204                Value::string("gpt-4".to_string()),
1205            ),
1206            (
1207                "MAP<msg: STRING = \"hello world\">",
1208                "MAP<msg: STRING = \"hello world\">",
1209                Value::string("hello world".to_string()),
1210            ),
1211        ] {
1212            let spelled = parse_spelling(spelling).expect("parses");
1213            assert_eq!(render_spelled(&spelled), canonical, "canonical: {spelling}");
1214            assert_eq!(canonicalize_spelling(spelling), canonical);
1215            match spelled {
1216                Spelled::Generic { args, .. } => {
1217                    let found = args.iter().find(|f| f.default.is_some()).expect("default");
1218                    let lit = found.default.as_ref().expect("lit");
1219                    assert_eq!(lit.to_value(), value);
1220                    assert!(
1221                        canonical.contains(&format!("= {}", lit.render())),
1222                        "canonical carries the default: {canonical}"
1223                    );
1224                }
1225                other => panic!("expected generic, got {other:?}"),
1226            }
1227        }
1228        // Rendered tags agree with rendered spellings on defaults.
1229        let tag = TypeTag::Record(Arc::from([Field {
1230            name: "retries".to_string(),
1231            ty: TypeTag::Int,
1232            docs: "",
1233            optional: false,
1234            default: Some(Value::int(2)),
1235
1236            alias: None,
1237        }]));
1238        assert_eq!(
1239            render_structural(&tag),
1240            "MAP<retries: INT = 2>",
1241            "tag renders defaults canonically"
1242        );
1243        assert_eq!(
1244            render_default_value(&Value::float(2.5)),
1245            "2.5",
1246            "float keeps its point"
1247        );
1248        // Malformed defaults fail loudly: empty, non-literal,
1249        // unterminated strings, and bad numbers.
1250        for bad in [
1251            "MAP<a: INT = >",
1252            "MAP<a: INT = x>",
1253            "MAP<a: INT = 1.2.3>",
1254            "MAP<a: INT = \"x>",
1255            "MAP<a: INT = 9999999999999999999999>",
1256        ] {
1257            assert!(parse_spelling(bad).is_err(), "must fail: {bad}");
1258        }
1259    }
1260
1261    #[test]
1262    fn unknown_map_spelling_parses_and_renders() {
1263        // `MAP<ANY>` is the explicit unknown map: it parses like any
1264        // other generic spelling and renders back to itself.
1265        assert_eq!(
1266            parse_spelling("MAP<ANY>").expect("parses"),
1267            Spelled::Generic {
1268                name: "MAP".to_string(),
1269                args: vec![SpelledField {
1270                    name: None,
1271                    optional: false,
1272                    ty: Spelled::Named("ANY".to_string()),
1273                    default: None,
1274
1275                    alias: None,
1276                }],
1277            }
1278        );
1279        assert_eq!(canonicalize_spelling("MAP< ANY >"), "MAP<ANY>");
1280        assert_eq!(
1281            render_structural(&TypeTag::MapOf(Arc::new(TypeTag::Any))),
1282            "MAP<ANY>"
1283        );
1284    }
1285
1286    #[test]
1287    fn map_of_checks_values_with_paths() {
1288        // Value shapes walk every entry with key paths; non-maps fail
1289        // naming the structural shape, never the coarse word.
1290        let tag = TypeTag::MapOf(Arc::new(TypeTag::Int));
1291        let good = map(&[("a", Value::int(1))]);
1292        assert!(check_value(&tag, &good).is_ok());
1293        let bad = map(&[("a", Value::string("x".to_string()))]);
1294        let err = check_value(&tag, &bad).expect_err("bad value must fail");
1295        assert!(format!("{err:#}").contains(".a"), "names the key: {err:#}");
1296        let not_map = Value::list(vec![Value::int(1)]);
1297        let err = check_value(&tag, &not_map).expect_err("non-map must fail");
1298        assert!(format!("{err:#}").contains("MAP<INT>"), "{err:#}");
1299    }
1300
1301    #[test]
1302    fn spellings_reject_malformed_input() {
1303        for bad in [
1304            "",
1305            "LIST<>",
1306            "LIST<A,>",
1307            "MAP<name:>",
1308            "LIST<A",
1309            "list<MAP>",
1310            "LIST<A>>",
1311        ] {
1312            assert!(parse_spelling(bad).is_err(), "{bad:?} must fail");
1313        }
1314        // Depth cap counts syntactic nesting; deeper bails naming it.
1315        let mut deep = "INT".to_string();
1316        for _ in 0..MAX_GENERIC_DEPTH + 1 {
1317            deep = format!("LIST<{deep}>");
1318        }
1319        let err = parse_spelling(&deep).expect_err("over-deep spelling must fail");
1320        assert!(err.contains("maximum generic depth"), "{err}");
1321    }
1322
1323    #[test]
1324    fn identical_spellings_share_one_interned_payload() {
1325        let first = intern_rendered(
1326            "LIST<MAP>".to_string(),
1327            TypeTag::ListOf(Arc::new(TypeTag::Map)),
1328        );
1329        let second = intern_rendered(
1330            "LIST<MAP>".to_string(),
1331            TypeTag::ListOf(Arc::new(TypeTag::Map)),
1332        );
1333        let (TypeTag::ListOf(a), TypeTag::ListOf(b)) = (first, second) else {
1334            panic!("rendered tags keep their shape");
1335        };
1336        assert!(
1337            Arc::ptr_eq(&a, &b),
1338            "same canonical spelling shares one payload"
1339        );
1340    }
1341
1342    #[test]
1343    fn structural_rendering_names_contents() {
1344        let fields: Arc<[Field]> = Arc::from([Field {
1345            name: "name".to_string(),
1346            ty: TypeTag::String,
1347            docs: "",
1348            optional: false,
1349            default: None,
1350
1351            alias: None,
1352        }]);
1353        let record = TypeTag::Record(fields);
1354        let list = TypeTag::ListOf(Arc::new(record));
1355        assert_eq!(render_structural(&list), "LIST<MAP<name: STRING>>");
1356        assert_eq!(render_structural(&TypeTag::Int), "INT");
1357    }
1358}