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