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