Skip to main content

oxdock_parser/
tag.rs

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