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