relon-parser 0.1.0-rc2

The core parser for the Relon language
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
use ordered_float::OrderedFloat;
use std::fmt::{Display, Formatter};
use std::sync::atomic::{AtomicU32, Ordering};
use std::sync::Arc;

/// Internal TypeNode head used by the lowered representation of `#enum`.
/// User source cannot write this name directly as public enum syntax.
pub const INTERNAL_ENUM_TYPE_NAME: &str = "__RelonEnum";

/// Stable identifier assigned to every `Node` at parse time.
///
/// Used as the key in side-tables maintained by `relon-analyzer` (resolved
/// references, desugar caches, diagnostics) so analyzer passes can attach
/// information without mutating the AST itself.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
pub struct NodeId(pub u32);

impl NodeId {
    /// Sentinel id for synthetic nodes built outside the parser (e.g. by
    /// the evaluator when fabricating a `Type` node mid-flight). Analyzer
    /// side-tables must not key on this value.
    pub const SYNTHETIC: NodeId = NodeId(0);

    /// Allocate a fresh, process-wide-unique id.
    ///
    /// Public so AST rewriters outside the parser (analyzer, evaluator
    /// fabricated nodes, host transforms) can mint ids that won't collide
    /// with parser-emitted ones.
    pub fn alloc() -> NodeId {
        // Start at 1 so `SYNTHETIC` (0) stays distinct from any real node.
        static COUNTER: AtomicU32 = AtomicU32::new(1);
        NodeId(COUNTER.fetch_add(1, Ordering::Relaxed))
    }
}

#[derive(Debug, PartialEq, Clone, Eq, Copy, Default, Hash)]
pub struct TokenPosition {
    pub line: u32,
    pub column: usize,
    pub offset: usize,
}

#[derive(Debug, PartialEq, Clone, Eq, Copy, Default, Hash)]
pub struct TokenRange {
    pub start: TokenPosition,
    pub end: TokenPosition,
}

impl From<TokenRange> for miette::SourceSpan {
    fn from(range: TokenRange) -> Self {
        let len = range.end.offset.saturating_sub(range.start.offset);
        (range.start.offset, len).into()
    }
}

#[derive(Debug, PartialEq, Clone)]
// `Dynamic` carries a full `Node` so this variant is significantly
// larger than the others. The values are parser/AST-internal and
// always wrapped in tuples or larger AST types in practice; the size
// disparity isn't worth boxing every key access for.
#[allow(clippy::large_enum_variant)]
pub enum TokenKey {
    Dummy,
    Index(usize, bool),               // index, is_optional
    String(String, TokenRange, bool), // name, range, is_optional
    Dynamic(Node, bool),              // expr, is_optional
    Spread(TokenRange),
}

impl TokenKey {
    pub fn name(&self) -> String {
        match self {
            TokenKey::Dummy => "_".to_string(),
            TokenKey::Index(i, _) => i.to_string(),
            TokenKey::String(s, _, _) => s.clone(),
            TokenKey::Dynamic(_, _) => "<dynamic>".to_string(),
            TokenKey::Spread(_) => "...".to_string(),
        }
    }

    pub fn to_string_key(&self) -> String {
        self.name()
    }

    pub fn is_optional(&self) -> bool {
        match self {
            TokenKey::Index(_, opt) => *opt,
            TokenKey::String(_, _, opt) => *opt,
            TokenKey::Dynamic(_, opt) => *opt,
            _ => false,
        }
    }
}

#[derive(Debug, PartialEq, Clone, Hash, Eq)]
pub struct TokenId(pub String, pub TokenRange);

impl TokenId {
    pub fn name(&self) -> &str {
        &self.0
    }
}

/// Represents a single argument in a function call or decorator.
/// Can be positional or named (keyword).
#[derive(Debug, PartialEq, Clone)]
pub struct CallArg {
    pub name: Option<String>,
    pub value: Node,
}

#[derive(Debug, PartialEq, Clone)]
pub struct Decorator {
    pub path: Vec<TokenKey>,
    pub args: Vec<CallArg>,
    pub range: TokenRange,
}

/// One of the five fixed shapes a `#name` directive can take. The shape
/// is determined by the directive's name (looked up at parse time) and
/// drives parser dispatch + analyzer / evaluator interpretation.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum DirectiveShape {
    /// `#name` — no body. Example: `#internal`.
    Bare,
    /// `#name <expr>` — single value. Example: `#default 0`,
    /// `#expect "msg"`, `#brand Color`.
    Value,
    /// `#name <ident> <body-expr>` — one named declaration with a
    /// single body expression (no colon). Example:
    /// `#schema User { String name: * }`. Inside a dict literal,
    /// `#schema X: { ... }` retains the dict-field grammar — the `:`
    /// belongs to the field separator, not the directive.
    NameBody,
    /// `#enum Name { Variant, Variant { field: Type } }` — Rust-like enum
    /// declaration lowered to the internal tagged-enum schema shape.
    Enum,
    /// `#import <bindspec> from <string>`. Example:
    /// `#import string from "std/string"`,
    /// `#import * from "std/list"`,
    /// `#import { upper, lower as lo } from "std/string"`.
    Import,
    /// `#main(<type> <ident> [, ...]*) [-> <type>]`. Example:
    /// `#main(User u, Cart cart) -> Result<Order>`.
    Main,
}

/// The body of a parsed `#name ...` directive, dispatched per
/// [`DirectiveShape`].
#[derive(Debug, PartialEq, Clone)]
pub enum DirectiveBody {
    Bare,
    Value(Box<Node>),
    /// Single named declaration: `<ident>[<T, ...>] <body-expr>` (no colon).
    /// `generics` carries the optional type-parameter list declared after
    /// the name (e.g. `Result<T, E>` → `["T", "E"]`); empty when absent.
    ///
    /// `methods` and `schema_no_auto_derives` carry the optional
    /// `with { ... }` extension block (Phase A of the trait-bound /
    /// schema-method system; see `docs/internal/archive/type-constraints-spec.md`).
    /// Both are empty when no `with` block follows the body.
    NameBody {
        name: String,
        name_range: TokenRange,
        generics: Vec<String>,
        body: Box<Node>,
        /// Methods declared inside the trailing `with { ... }` block.
        /// Order preserves source order. Each method may carry method-level
        /// `#derive <Constraint>` pragmas and an `#native` flag.
        methods: Vec<SchemaMethod>,
        /// Schema-level `#no_auto_derive <Constraint>` directives that
        /// appear directly inside `with { ... }` (no method follows).
        /// Constraint names are stored as bare strings; the analyzer
        /// validates them.
        schema_no_auto_derives: Vec<String>,
    },
    Import {
        spec: DirectiveImportSpec,
        path: String,
        path_range: TokenRange,
        /// Optional integrity pin: `#import <spec> from "path" sha256:"..."`.
        /// When present, the workspace loader verifies the loaded source's
        /// digest against this value and refuses the import on mismatch.
        /// v3++ b-2 wires sha256 only; the [`HashAlgorithm`] enum reserves
        /// space for additional algorithms (sha512, blake3, ...) without
        /// churning the AST surface again.
        integrity: Option<IntegrityHash>,
    },
    Main {
        params: Vec<DirectiveMainParam>,
        /// Optional `-> Type` declared after the parameter list. When
        /// `None`, the entry's return value is left unchecked.
        return_type: Option<TypeNode>,
    },
}

/// Hash algorithm used by an [`IntegrityHash`] pin on `#import`. Only
/// `Sha256` is wired in v3++ b-2; the enum exists so future agents can
/// add `Sha512` / `Blake3` (or SRI multi-algo) without an AST shape
/// change.
#[derive(Debug, PartialEq, Eq, Clone, Copy, Hash)]
pub enum HashAlgorithm {
    Sha256,
}

impl HashAlgorithm {
    /// Canonical lowercase identifier as it appears in source
    /// (`sha256:"..."`). Lookups in the parser / analyzer compare
    /// against this so the casing is fixed in one place.
    pub fn as_str(&self) -> &'static str {
        match self {
            HashAlgorithm::Sha256 => "sha256",
        }
    }

    /// Reverse of [`HashAlgorithm::as_str`]. Returns `None` for unknown
    /// names so the caller can emit a position-aware parse / analyzer
    /// diagnostic.
    pub fn from_ident(name: &str) -> Option<Self> {
        match name {
            "sha256" => Some(HashAlgorithm::Sha256),
            _ => None,
        }
    }

    /// Expected hex-digest length (one byte = two hex chars) for the
    /// algorithm. Used by the analyzer to reject obvious typos before
    /// it tries to verify the import.
    pub fn hex_len(&self) -> usize {
        match self {
            HashAlgorithm::Sha256 => 64,
        }
    }
}

/// Inline integrity pin on a `#import` directive. The source form is
/// `<algorithm>:"<hex>"` (e.g. `sha256:"abc..."`); the parser does not
/// validate the hex string itself — that work happens in the analyzer
/// so the diagnostic carries a real source span. The algorithm name
/// is preserved verbatim alongside the parsed [`HashAlgorithm`] enum
/// so the analyzer can render the offending identifier when it does
/// not match any known algorithm.
#[derive(Debug, PartialEq, Eq, Clone)]
pub struct IntegrityHash {
    /// Parsed algorithm. `None` when the source identifier did not
    /// match any known algorithm — the analyzer surfaces the typo /
    /// unsupported-algo diagnostic before the loader is consulted.
    pub algorithm: Option<HashAlgorithm>,
    /// Verbatim source identifier (`sha256`, `sha512`, ...). Kept
    /// alongside [`Self::algorithm`] so error messages can echo the
    /// exact spelling the author used.
    pub algorithm_text: String,
    pub hex: String,
    /// Full source range covering `<algorithm>:"<hex>"` so analyzer
    /// diagnostics (`unknown algorithm`, `hex length mismatch`, …) can
    /// point at the right span.
    pub range: TokenRange,
}

/// Bindspec for `#import <spec> from "path"`.
#[derive(Debug, PartialEq, Clone)]
pub enum DirectiveImportSpec {
    /// `#import name from "path"` — bind module under `name`.
    Alias(String),
    /// `#import * from "path"` — spread module's exported bindings.
    Spread,
    /// `#import { a, b as c } from "path"` — bind each entry; `Some(_)`
    /// is the rebinding alias.
    Destructure(Vec<(String, Option<String>)>),
}

/// One `<type> <ident>` parameter of a `#main(...)` signature.
#[derive(Debug, PartialEq, Clone)]
pub struct DirectiveMainParam {
    pub name: String,
    pub name_range: TokenRange,
    pub type_node: TypeNode,
}

/// One typed parameter of a schema method declared inside `with { ... }`.
/// Form: `<ident>: <TypeNode>`. The `self` receiver is implicit and is not
/// represented here; analyzer-side lowering injects it as a leading
/// parameter of type `Self`.
#[derive(Debug, PartialEq, Clone)]
pub struct SchemaMethodParam {
    pub name: String,
    pub name_range: TokenRange,
    pub type_node: TypeNode,
}

/// A method declaration inside a schema's `with { ... }` block.
///
/// Source form: `[#derive C ...]* [#native] name(p1: T1, ...) -> R [: body]`
/// — the body is required when `is_native` is false and forbidden when it
/// is true (parser enforces this).
#[derive(Debug, PartialEq, Clone)]
pub struct SchemaMethod {
    /// Method name (the `name` in `name(...) -> R`).
    pub name: String,
    pub name_range: TokenRange,
    /// Method-level generic type parameter names (e.g. `["U"]` for
    /// `map<U>(...)`). Empty for monomorphic methods. Each occurrence
    /// inside `params[i].type_node` or `return_type` is a placeholder
    /// instantiated at the call site, on top of any schema-level
    /// placeholders already in scope.
    pub generics: Vec<String>,
    /// Typed parameters as written; `self` is implicit and is added by
    /// the analyzer when lowering.
    pub params: Vec<SchemaMethodParam>,
    /// Return type (the `R` in `-> R`). Required for every method —
    /// methods are not type-inferred at the signature level.
    pub return_type: TypeNode,
    /// Body expression (`: body`). `None` when the method is marked
    /// `#native` — the host registers the implementation.
    pub body: Option<Box<Node>>,
    /// Constraint names from method-level `#derive <Constraint>` pragmas,
    /// in source order.
    pub derives: Vec<String>,
    /// True when an `#native` pragma precedes this method, indicating
    /// the body lives in host Rust (registered via the schema-method
    /// host API). The parser leaves `body` `None` in this case.
    pub is_native: bool,
    /// True when a `#internal` pragma precedes this method. Internal
    /// methods are visible only from other method bodies on the same
    /// schema; script-level `value.method()` calls fail with
    /// `MethodNotFound` at the analyzer stage.
    pub is_private: bool,
    pub range: TokenRange,
    pub doc_comment: Option<String>,
}

/// Parsed `#name ...` directive — a structural / declarative attribute
/// stacked above a node. Parallel to [`Decorator`] but with one of five
/// fixed [`DirectiveShape`]s rather than free-form `args`.
#[derive(Debug, PartialEq, Clone)]
pub struct Directive {
    /// Single-segment directive name (e.g. `"main"`, `"schema"`).
    pub name: String,
    /// Parsed body matching the shape registered for `name`.
    pub body: DirectiveBody,
    /// Source range of the entire `#name ...` form.
    pub range: TokenRange,
}

#[derive(Debug, PartialEq, Clone)]
pub struct TypeNode {
    pub path: Vec<String>,
    pub generics: Vec<TypeNode>,
    pub is_optional: bool,
    pub range: TokenRange,
    /// `Some(_)` only when this node is an alternative inside the lowered
    /// internal representation of `#enum`. `Some(vec![])` is a unit variant;
    /// `Some(non-empty)` carries the variant payload as `(field_name, field_type)`
    /// pairs. Stays `None` for every non-variant type expression.
    pub variant_fields: Option<Vec<(String, TypeNode)>>,
    /// Documentation extracted from leading comments.
    pub doc_comment: Option<String>,
}

#[derive(Debug, PartialEq, Clone)]
pub struct ClosureParam {
    pub name: String,
    pub type_hint: Option<TypeNode>,
    pub range: TokenRange,
}

#[derive(Debug, PartialEq, Clone)]
pub struct PatternBinding {
    /// `Some(field)` for struct payload patterns (`Email { address: a }`),
    /// `None` for tuple payload patterns (`Pair(a, b)`).
    pub field: Option<String>,
    /// Bound local name. `None` means the payload slot is ignored (`*`).
    pub binding: Option<String>,
}

#[derive(Debug, Clone)]
pub struct Node {
    /// Stable identity assigned at construction. Analyzer side-tables key
    /// off this; not part of structural equality.
    pub id: NodeId,
    /// `Arc` rather than `Box` so analyzer side-tables (`node_index`) and
    /// every walker that snapshots a `Node` share the body via reference
    /// counting instead of recursively deep-cloning the subtree. The AST
    /// is effectively immutable after parsing; the lone in-place rewrite
    /// (closure desugar in `lower.rs`) reassigns the field on a freshly
    /// built node before any shared clones exist.
    pub expr: Arc<Expr>,
    /// `@name(...)` decorators stacked above this node — value-transform
    /// hooks (host-registered + user-definable).
    pub decorators: Vec<Decorator>,
    /// `#name ...` directives stacked above this node — structural /
    /// declarative attributes (host-registered only). Parsed in source
    /// order; the analyzer interprets them by name + shape.
    pub directives: Vec<Directive>,
    pub type_hint: Option<TypeNode>,
    pub range: TokenRange,
    /// Documentation extracted from leading comments immediately preceding
    /// the node.
    pub doc_comment: Option<String>,
}

/// Structural equality only — `id` is intentionally excluded so two
/// independently-parsed-but-identical AST fragments still compare equal.
/// This matters for `Value::Closure` PartialEq (compares `body: Node`) and
/// for parser tests that round-trip syntactic shape.
impl PartialEq for Node {
    fn eq(&self, other: &Self) -> bool {
        self.expr == other.expr
            && self.decorators == other.decorators
            && self.directives == other.directives
            && self.type_hint == other.type_hint
            && self.range == other.range
            && self.doc_comment == other.doc_comment
    }
}

impl Node {
    pub fn new(expr: Expr, range: TokenRange) -> Self {
        Self {
            id: NodeId::alloc(),
            expr: Arc::new(expr),
            decorators: Vec::new(),
            directives: Vec::new(),
            type_hint: None,
            range,
            doc_comment: None,
        }
    }

    /// Construct a `Node` with a caller-supplied `NodeId`. Used by tests
    /// and (rarely) by AST rewriters that want to preserve the original
    /// node's identity after a structural transform.
    pub fn with_id(id: NodeId, expr: Expr, range: TokenRange) -> Self {
        Self {
            id,
            expr: Arc::new(expr),
            decorators: Vec::new(),
            directives: Vec::new(),
            type_hint: None,
            range,
            doc_comment: None,
        }
    }

    pub fn with_decorators(mut self, decorators: Vec<Decorator>) -> Self {
        self.decorators = decorators;
        self
    }

    pub fn with_directives(mut self, directives: Vec<Directive>) -> Self {
        self.directives = directives;
        self
    }

    pub fn with_type_hint(mut self, type_hint: Option<TypeNode>) -> Self {
        self.type_hint = type_hint;
        self
    }

    pub fn with_doc_comment(mut self, doc_comment: Option<String>) -> Self {
        self.doc_comment = doc_comment;
        self
    }
}

#[derive(Debug, PartialEq, Clone)]
pub enum Expr {
    /// Internal placeholder for parse recovery or removed literals.
    Missing,
    Bool(bool),
    Int(i64),
    Float(OrderedFloat<f64>),
    String(String),

    List(Vec<Node>),
    /// Fixed-arity, heterogeneous, positional tuple value `(e1, e2, ...)`.
    /// Distinct from `List` so the analyzer can type it position-by-position
    /// (heterogeneous elements allowed, unlike a list literal) and the
    /// evaluator can preserve that distinction as `Value::Tuple`. JSON
    /// output still projects it as a positional array.
    /// `Tuple(vec![])` is the unit / zero-tuple `()`.
    Tuple(Vec<Node>),
    Dict(Vec<(TokenKey, Node)>),

    Spread(Node),

    Comprehension {
        element: Node,
        id: String,
        iterable: Node,
        condition: Option<Node>,
    },

    Variable(Vec<TokenKey>),
    Reference {
        base: RefBase,
        path: Vec<TokenKey>,
    },

    Binary(Operator, Node, Node),
    Unary(Operator, Node),
    Ternary {
        cond: Node,
        then: Node,
        els: Node,
    },

    FnCall {
        path: Vec<TokenKey>,
        args: Vec<CallArg>,
    },

    FString(Vec<FStringPart>),

    Type(TypeNode),

    Wildcard,

    Where {
        expr: Node,
        bindings: Node,
    },

    Match {
        expr: Node,
        arms: Vec<(Node, Node)>,
    },

    VariantPattern {
        enum_path: Vec<String>,
        variant: String,
        bindings: Vec<PatternBinding>,
    },

    Closure {
        params: Vec<ClosureParam>,
        return_type: Option<TypeNode>,
        body: Node,
    },

    /// Tagged-enum variant constructor: `EnumName.VariantName { field: value, ... }`.
    /// Unit variants share the bare-identifier-path form parsed as `Variable`
    /// — the evaluator promotes them to a variant when the head resolves to
    /// a sum-type schema.
    VariantCtor {
        enum_path: Vec<String>,
        variant: String,
        body: Node,
    },
}
#[derive(Debug, PartialEq, Clone, Copy, Eq, Hash)]
pub enum RefBase {
    Root,
    Sibling,
    Uncle,
    Prev,
    Next,
    Index,
    This,
}

#[derive(Debug, PartialEq, Clone)]
pub enum FStringPart {
    Literal(String),
    Interpolation(Box<Node>),
}

#[derive(Debug, PartialEq, Clone, Copy, Eq, Hash)]
pub enum Operator {
    Add,
    Sub,
    Mul,
    Div,
    Mod,
    Eq,
    Ne,
    Lt,
    Gt,
    Le,
    Ge,
    And,
    Or,
    Not,
    Pipe,
    Concat,
}

impl Expr {
    /// Stable, allocation-free name for the variant — used by diagnostics
    /// (`SchemaBodyNotDict { found }`) and any walker that wants a cheap
    /// dispatch tag without matching the full enum.
    pub fn kind(&self) -> &'static str {
        match self {
            Expr::Missing => "Missing",
            Expr::Bool(_) => "Bool",
            Expr::Int(_) => "Int",
            Expr::Float(_) => "Float",
            Expr::String(_) => "String",
            Expr::List(_) => "List",
            Expr::Tuple(_) => "Tuple",
            Expr::Dict(_) => "Dict",
            Expr::Spread(_) => "Spread",
            Expr::Comprehension { .. } => "Comprehension",
            Expr::Variable(_) => "Variable",
            Expr::Reference { .. } => "Reference",
            Expr::Binary(_, _, _) => "Binary",
            Expr::Unary(_, _) => "Unary",
            Expr::Ternary { .. } => "Ternary",
            Expr::FnCall { .. } => "FnCall",
            Expr::FString(_) => "FString",
            Expr::Type(_) => "Type",
            Expr::Wildcard => "Wildcard",
            Expr::Where { .. } => "Where",
            Expr::Match { .. } => "Match",
            Expr::VariantPattern { .. } => "VariantPattern",
            Expr::Closure { .. } => "Closure",
            Expr::VariantCtor { .. } => "VariantCtor",
        }
    }
}

impl Display for Expr {
    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
        match self {
            Expr::Missing => write!(f, "<missing>"),
            Expr::Bool(v) => write!(f, "{}", v),
            Expr::Int(v) => write!(f, "{}", v),
            Expr::Float(v) => write!(f, "{}", v),
            Expr::String(v) => write!(f, "\"{}\"", v),
            _ => write!(f, "<expr>"),
        }
    }
}

/// Cheap predicate over primitive/container type identifiers such as `Int`,
/// `String`, `List`, `Dict`, and `Tuple`. Prelude enum schemas such as `Option`
/// and `Result` are resolved by the analyzer/evaluator schema paths, not by
/// this primitive set.
pub fn is_builtin_type_name(name: &str) -> bool {
    matches!(
        name,
        "Int"
            | "Float"
            | "Number"
            | "String"
            | "Bool"
            | "Any"
            | "List"
            | "Dict"
            | "Closure"
            | "Fn"
            // v1.7: tuple types `(T1, T2, ...)` are encoded internally
            // as a single-segment path `Tuple` whose `generics` carry
            // the element types in order. Reserved as a builtin name
            // so a user-declared `#schema Tuple { ... }` doesn't
            // shadow the encoding.
            | "Tuple"
    )
}

/// Lift a decorator-argument [`Expr`] back into a [`TypeNode`].
///
/// Used by every site that consumes a `@brand(Type)` argument — the
/// evaluator's `BrandDecorator::wrap_with_ast` runs this on the live
/// argument, and the analyzer's schema-field lowering runs it to lift
/// `@brand(X)` placed on a typeless schema field into an implicit type
/// prefix.
///
/// Accepted shapes:
///
/// * Full type expression (`Map<String, Int>`, `Foo<T>`, `Weather?`,
///   `Int`) — produced by `crate::expr::parse_type_expr`
///   and surfaced as `Expr::Type`. The contained `TypeNode` is returned
///   verbatim so generics and `is_optional` survive.
/// * Bareword / dotted path (`Weather`, `geo.Location`) — surfaced as
///   `Expr::Variable` because the parser only commits to `Expr::Type`
///   when it sees generics, `?`, or a known builtin head. Each path
///   segment must be a simple identifier (no `?.`, `[i]`, or spread).
/// * String literal (`"Weather"`, `"geo.Location"`) — split on `.` for
///   parity with the bareword form.
///
/// Returns `None` when `expr` is none of the above; callers turn that
/// into a user-facing "argument must be a type" error.
pub fn type_node_from_brand_arg(expr: &Expr, range: TokenRange) -> Option<TypeNode> {
    match expr {
        Expr::Type(t) => Some(t.clone()),
        Expr::Variable(path) => {
            let mut segs = Vec::with_capacity(path.len());
            for tk in path {
                match tk {
                    TokenKey::String(s, _, false) => segs.push(s.clone()),
                    _ => return None,
                }
            }
            if segs.is_empty() {
                return None;
            }
            Some(TypeNode {
                path: segs,
                generics: Vec::new(),
                is_optional: false,
                range,
                variant_fields: None,
                doc_comment: None,
            })
        }
        Expr::String(s) => {
            if s.is_empty() {
                return None;
            }
            let segs: Vec<String> = s.split('.').map(|p| p.to_string()).collect();
            if segs.iter().any(|p| p.is_empty()) {
                return None;
            }
            Some(TypeNode {
                path: segs,
                generics: Vec::new(),
                is_optional: false,
                range,
                variant_fields: None,
                doc_comment: None,
            })
        }
        _ => None,
    }
}