club-kdl-codegen 0.11.1

Generate Rust / TypeScript / Zod / SurrealQL code from KDL schema files
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
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
//! Parser — KDL schema file → [`crate::ir::Schema`].
//!
//! Parsing happens in two stages:
//!
//! 1. **deserialize** — `club-kdl`'s `KdlDeserialize` derive fills the
//!    KDL-shaped `raw` structs from the document.
//! 2. **lower** — `raw` structs are converted into the validated
//!    [`crate::ir`] representation: enum-like strings become real enums, the
//!    flat `type` string becomes a [`crate::ir::Ty`], and channel semantics
//!    (datagram `channel_id` requirements) are checked.
//!
//! Only the modern dialect is accepted — `protocol` / `channel` / `request` /
//! `returns` / `event` / `field`, standalone `struct` / `enum`, and the
//! entity dialect `record` / `relation` / `id`. Legacy `service` / `method` /
//! `send` / `recv` constructs are not parsed.

mod raw;

use std::collections::HashSet;
use std::path::Path;

use crate::ir;

/// An error produced while parsing a KDL schema.
///
/// Marked `#[non_exhaustive]` so future error sources (network fetches, new
/// dialect-specific validation passes, …) can be added without a major bump.
/// Downstream `match` blocks need a `_ => …` arm.
#[derive(Debug, thiserror::Error)]
#[non_exhaustive]
pub enum ParseError {
    /// The input was not well-formed KDL, or did not match the schema shape.
    #[error("KDL parse error: {0}")]
    Kdl(String),
    /// The input parsed as KDL but violated a schema rule.
    #[error("schema validation error: {0}")]
    Validation(String),
    /// A `(<)file` / `(<)glob` directive failed to resolve. Only produced by
    /// [`parse_path`] — the pure-text [`parse`] and [`parse_doc`] entries
    /// never read the filesystem and therefore cannot emit this variant.
    #[error("compose error: {0}")]
    Compose(#[from] kdl_compose::ComposeError),
}

/// Parse a KDL schema source string into a [`Schema`](ir::Schema). Pure text
/// in, pure value out — no filesystem access, no directive resolution.
///
/// # Errors
///
/// Returns [`ParseError::Kdl`] if the input is not well-formed KDL or does not
/// match the schema shape, and [`ParseError::Validation`] if it parses but
/// breaks a schema rule (e.g. a datagram channel without a `channel_id`).
pub fn parse(src: &str) -> Result<ir::Schema, ParseError> {
    let raw: raw::RawSchema =
        club_kdl::from_str(src).map_err(|e| ParseError::Kdl(e.to_string()))?;
    lower_schema(raw)
}

/// Parse an already-loaded [`kdl::KdlDocument`] into a [`Schema`](ir::Schema).
///
/// The intended caller is [`parse_path`], which composes a multi-file schema
/// via [`kdl_compose::compose`] and then hands the resolved document to
/// this entry; exposed publicly so library consumers who build a `KdlDocument`
/// some other way (custom IO, in-memory generation) can skip the string round
/// trip.
///
/// # Errors
///
/// Same shape as [`parse`] — [`ParseError::Kdl`] on a deserialization failure,
/// [`ParseError::Validation`] on a schema-rule violation.
pub fn parse_doc(doc: &kdl::KdlDocument) -> Result<ir::Schema, ParseError> {
    let raw: raw::RawSchema =
        club_kdl::from_doc(doc).map_err(|e| ParseError::Kdl(e.to_string()))?;
    lower_schema(raw)
}

/// Read a KDL schema file from disk, resolve every `(<)file` / `(<)glob`
/// directive in it via [`kdl_compose::compose`], then parse the composed
/// document into a [`Schema`](ir::Schema).
///
/// A schema that contains no directives is composed to a document
/// byte-equivalent to the on-disk file, so this entry is a drop-in upgrade
/// from "read file + [`parse`]"; the only observable difference is that
/// `(<)` directives now work.
///
/// # Errors
///
/// In addition to the variants from [`parse`], returns [`ParseError::Compose`]
/// when the composer cannot read a referenced file, detects an include cycle,
/// or rejects a malformed directive.
pub fn parse_path(path: impl AsRef<Path>) -> Result<ir::Schema, ParseError> {
    let doc = kdl_compose::compose(path)?;
    parse_doc(&doc)
}

// =============================================================================
// Lowering — raw structs → IR
// =============================================================================

fn lower_schema(raw: raw::RawSchema) -> Result<ir::Schema, ParseError> {
    let mut types = Vec::with_capacity(raw.structs.len() + raw.enums.len());
    for s in raw.structs {
        types.push(lower_struct(s)?);
    }
    for e in raw.enums {
        types.push(lower_enum(e));
    }
    let records = raw
        .records
        .into_iter()
        .map(lower_record)
        .collect::<Result<Vec<_>, _>>()?;
    let relations = raw
        .relations
        .into_iter()
        .map(lower_relation)
        .collect::<Result<Vec<_>, _>>()?;
    let protocol = raw.protocol.map(lower_protocol).transpose()?;
    let schema = ir::Schema {
        types,
        records,
        relations,
        protocol,
    };
    validate_type_refs(&schema)?;
    Ok(schema)
}

/// The set of type names a schema defines, split by reference kind.
///
/// A [`ir::Ty::Named`] (embedded value) must resolve into [`Self::values`];
/// a [`ir::Ty::Link`] (stored reference) must resolve into [`Self::records`].
struct DefinedNames<'a> {
    /// `struct` / `enum` names — valid [`ir::Ty::Named`] targets.
    values: HashSet<&'a str>,
    /// `record` names — valid [`ir::Ty::Link`] targets.
    records: HashSet<&'a str>,
}

/// Check that every type reference resolves: a [`ir::Ty::Named`] to a defined
/// `struct` / `enum`, and a [`ir::Ty::Link`] to a defined `record`. Without
/// this, an unknown type name silently flows through to an emitter and
/// produces source that fails to compile.
fn validate_type_refs(schema: &ir::Schema) -> Result<(), ParseError> {
    let values: HashSet<&str> = schema
        .types
        .iter()
        .map(|t| match t {
            ir::TypeDef::Struct { name, .. } | ir::TypeDef::Enum { name, .. } => name.as_str(),
        })
        .collect();
    let records: HashSet<&str> = schema.records.iter().map(|r| r.name.as_str()).collect();
    let defined = DefinedNames { values, records };

    for ty in &schema.types {
        if let ir::TypeDef::Struct { fields, .. } = ty {
            check_fields(fields, &defined)?;
        }
    }
    for record in &schema.records {
        check_fields(&record.fields, &defined)?;
    }
    for relation in &schema.relations {
        check_fields(&relation.fields, &defined)?;
        // A relation's endpoints must name defined records.
        for (role, endpoint) in [("from", &relation.from), ("to", &relation.to)] {
            if !defined.records.contains(endpoint.as_str()) {
                return Err(ParseError::Validation(format!(
                    "relation {:?} {role}={endpoint:?} references unknown record; \
                     define it as a `record`",
                    relation.name
                )));
            }
        }
    }
    if let Some(protocol) = &schema.protocol {
        for channel in &protocol.channels {
            for request in &channel.requests {
                check_fields(&request.fields, &defined)?;
                if let Some(returns) = &request.returns {
                    check_fields(&returns.fields, &defined)?;
                }
            }
            for event in &channel.events {
                check_fields(&event.fields, &defined)?;
            }
        }
    }
    Ok(())
}

fn check_fields(fields: &[ir::Field], defined: &DefinedNames) -> Result<(), ParseError> {
    for field in fields {
        check_ty(&field.ty, &field.name, defined)?;
    }
    Ok(())
}

fn check_ty(ty: &ir::Ty, field: &str, defined: &DefinedNames) -> Result<(), ParseError> {
    match ty {
        ir::Ty::Primitive(_) | ir::Ty::Literal(_) => Ok(()),
        ir::Ty::Array(inner) => check_ty(inner, field, defined),
        ir::Ty::Union(members) => members.iter().try_for_each(|m| check_ty(m, field, defined)),
        ir::Ty::Named(name) if defined.values.contains(name.as_str()) => Ok(()),
        ir::Ty::Named(name) => Err(ParseError::Validation(format!(
            "field {field:?} references unknown type {name:?}; \
             define it as a `struct` or `enum`, or use `link<{name}>` for a `record`"
        ))),
        ir::Ty::Link(name) if defined.records.contains(name.as_str()) => Ok(()),
        ir::Ty::Link(name) => Err(ParseError::Validation(format!(
            "field {field:?} links to unknown record {name:?}; \
             define it as a `record`"
        ))),
    }
}

fn lower_struct(raw: raw::RawStruct) -> Result<ir::TypeDef, ParseError> {
    Ok(ir::TypeDef::Struct {
        name: raw.name,
        description: raw.description,
        fields: lower_fields(raw.fields)?,
    })
}

fn lower_enum(raw: raw::RawEnum) -> ir::TypeDef {
    ir::TypeDef::Enum {
        name: raw.name,
        description: raw.description,
        variants: raw.variants.into_iter().map(|v| v.name).collect(),
    }
}

fn lower_record(raw: raw::RawRecord) -> Result<ir::Record, ParseError> {
    let id_strategy = lower_id_strategy(raw.id.and_then(|i| i.strategy).as_deref())?;
    Ok(ir::Record {
        name: raw.name,
        description: raw.description,
        id_strategy,
        fields: lower_fields(raw.fields)?,
    })
}

fn lower_relation(raw: raw::RawRelation) -> Result<ir::Relation, ParseError> {
    Ok(ir::Relation {
        name: raw.name,
        description: raw.description,
        from: raw.from,
        to: raw.to,
        unique: raw.unique,
        fields: lower_fields(raw.fields)?,
    })
}

fn lower_id_strategy(s: Option<&str>) -> Result<ir::IdStrategy, ParseError> {
    match s {
        None | Some("uuidv7") => Ok(ir::IdStrategy::Uuidv7),
        Some("ulid") => Ok(ir::IdStrategy::Ulid),
        Some("manual") => Ok(ir::IdStrategy::Manual),
        Some(other) => Err(ParseError::Validation(format!(
            "unknown id `strategy` value {other:?} (expected uuidv7/ulid/manual)"
        ))),
    }
}

fn lower_protocol(raw: raw::RawProtocol) -> Result<ir::Protocol, ParseError> {
    let channels = raw
        .channels
        .into_iter()
        .map(lower_channel)
        .collect::<Result<Vec<_>, _>>()?;
    Ok(ir::Protocol {
        name: raw.name,
        version: raw.version,
        namespace: raw.namespace,
        description: raw.description,
        channels,
    })
}

fn lower_channel(raw: raw::RawChannel) -> Result<ir::Channel, ParseError> {
    let from = lower_channel_from(&raw.from)?;
    let lifetime = lower_channel_lifetime(&raw.lifetime)?;
    let backend = lower_channel_backend(raw.backend.as_deref())?;
    let requests = raw
        .requests
        .into_iter()
        .map(lower_request)
        .collect::<Result<Vec<_>, _>>()?;
    let events = raw
        .events
        .into_iter()
        .map(lower_event)
        .collect::<Result<Vec<_>, _>>()?;

    // Semantic validation — mirrors club-unison's `Channel::validate`.
    if backend == ir::ChannelBackend::Datagram {
        match raw.channel_id {
            None => {
                return Err(ParseError::Validation(format!(
                    "channel {:?} has backend=\"datagram\" but no channel_id; \
                     channel_id=N (1..) is required",
                    raw.name
                )));
            }
            Some(0) => {
                return Err(ParseError::Validation(format!(
                    "channel {:?} has channel_id=0 which is reserved; use 1..",
                    raw.name
                )));
            }
            Some(_) => {}
        }
        if !requests.is_empty() {
            return Err(ParseError::Validation(format!(
                "channel {:?} has backend=\"datagram\" with request blocks; \
                 datagram channels support event only (no Request/Response)",
                raw.name
            )));
        }
    }

    Ok(ir::Channel {
        name: raw.name,
        from,
        lifetime,
        backend,
        channel_id: raw.channel_id,
        envelope: raw.envelope,
        requests,
        events,
    })
}

fn lower_request(raw: raw::RawRequest) -> Result<ir::Request, ParseError> {
    Ok(ir::Request {
        name: raw.name,
        fields: lower_fields(raw.fields)?,
        returns: raw.returns.map(lower_message).transpose()?,
    })
}

fn lower_event(raw: raw::RawEvent) -> Result<ir::Event, ParseError> {
    Ok(ir::Event {
        name: raw.name,
        fields: lower_fields(raw.fields)?,
    })
}

fn lower_message(raw: raw::RawMessage) -> Result<ir::Message, ParseError> {
    Ok(ir::Message {
        name: raw.name,
        fields: lower_fields(raw.fields)?,
    })
}

fn lower_fields(raw: Vec<raw::RawField>) -> Result<Vec<ir::Field>, ParseError> {
    raw.into_iter().map(lower_field).collect()
}

fn lower_field(raw: raw::RawField) -> Result<ir::Field, ParseError> {
    Ok(ir::Field {
        ty: parse_ty(&raw.type_str)?,
        name: raw.name,
        required: !raw.optional,
        flexible: raw.flexible,
        default: raw.default,
        description: raw.description,
        constraints: ir::Constraints {
            min: raw.min,
            max: raw.max,
            min_length: raw.min_length,
            max_length: raw.max_length,
            pattern: raw.pattern,
        },
    })
}

// =============================================================================
// Scalar lowering helpers
// =============================================================================

fn lower_channel_from(s: &str) -> Result<ir::ChannelFrom, ParseError> {
    match s {
        "client" => Ok(ir::ChannelFrom::Client),
        "server" => Ok(ir::ChannelFrom::Server),
        "either" => Ok(ir::ChannelFrom::Either),
        other => Err(ParseError::Validation(format!(
            "unknown channel `from` value {other:?} (expected client/server/either)"
        ))),
    }
}

fn lower_channel_lifetime(s: &str) -> Result<ir::ChannelLifetime, ParseError> {
    match s {
        "transient" => Ok(ir::ChannelLifetime::Transient),
        "persistent" => Ok(ir::ChannelLifetime::Persistent),
        other => Err(ParseError::Validation(format!(
            "unknown channel `lifetime` value {other:?} (expected transient/persistent)"
        ))),
    }
}

fn lower_channel_backend(s: Option<&str>) -> Result<ir::ChannelBackend, ParseError> {
    match s {
        None | Some("stream") => Ok(ir::ChannelBackend::Stream),
        Some("datagram") => Ok(ir::ChannelBackend::Datagram),
        Some(other) => Err(ParseError::Validation(format!(
            "unknown channel `backend` value {other:?} (expected stream/datagram)"
        ))),
    }
}

/// Parse a field-type string into a [`Ty`](ir::Ty).
///
/// Grammar (lowest precedence first):
///
/// - `A | B | ...` — a [`Ty::Union`](ir::Ty::Union). `|` is split only at
///   the top level (not inside `array<...>` / `link<...>`).
/// - `array<T>` — a [`Ty::Array`](ir::Ty::Array).
/// - `link<Name>` — a [`Ty::Link`](ir::Ty::Link), a stored record reference.
/// - `'literal'` — a [`Ty::Literal`](ir::Ty::Literal) (single-quoted).
/// - the primitive set — `string` / `int` / `float` / `bool` / `datetime` /
///   `json`. `object` aliases `json`, `number` aliases `float`, `timestamp`
///   aliases `datetime`.
/// - any other identifier — a [`Ty::Named`](ir::Ty::Named) reference to a
///   `struct` / `enum`.
fn parse_ty(s: &str) -> Result<ir::Ty, ParseError> {
    let s = s.trim();
    if s.is_empty() {
        return Err(ParseError::Validation("empty field type".to_string()));
    }

    // Union has the lowest precedence — split on top-level `|`.
    let members = split_top_level_union(s);
    if members.len() > 1 {
        let parsed = members
            .iter()
            .map(|m| parse_ty(m))
            .collect::<Result<Vec<_>, _>>()?;
        return Ok(ir::Ty::Union(parsed));
    }

    parse_atom(s)
}

/// Parse a single (non-union) type atom.
fn parse_atom(s: &str) -> Result<ir::Ty, ParseError> {
    let s = s.trim();
    if let Some(inner) = s.strip_prefix("array<").and_then(|r| r.strip_suffix('>')) {
        return Ok(ir::Ty::Array(Box::new(parse_ty(inner)?)));
    }
    if let Some(inner) = s.strip_prefix("link<").and_then(|r| r.strip_suffix('>')) {
        let name = inner.trim();
        if name.is_empty() {
            return Err(ParseError::Validation(
                "empty record name in `link<>`".to_string(),
            ));
        }
        return Ok(ir::Ty::Link(name.to_string()));
    }
    // String literal: `'value'`.
    if let Some(inner) = s.strip_prefix('\'').and_then(|r| r.strip_suffix('\'')) {
        return Ok(ir::Ty::Literal(inner.to_string()));
    }
    let prim = match s {
        "string" => Some(ir::Prim::String),
        "int" => Some(ir::Prim::Int),
        "float" | "number" => Some(ir::Prim::Float),
        "bool" => Some(ir::Prim::Bool),
        "datetime" | "timestamp" => Some(ir::Prim::Datetime),
        "json" | "object" => Some(ir::Prim::Json),
        _ => None,
    };
    match prim {
        Some(p) => Ok(ir::Ty::Primitive(p)),
        None if s.is_empty() => Err(ParseError::Validation("empty field type".to_string())),
        None => Ok(ir::Ty::Named(s.to_string())),
    }
}

/// Split a type string on top-level `|`, ignoring `|` nested inside `<...>`
/// brackets or `'...'` string literals. Returns the trimmed segments.
fn split_top_level_union(s: &str) -> Vec<String> {
    let mut parts: Vec<String> = Vec::new();
    let mut cur = String::new();
    let mut depth: usize = 0;
    let mut in_literal = false;
    for c in s.chars() {
        match c {
            '\'' => {
                in_literal = !in_literal;
                cur.push(c);
            }
            '<' if !in_literal => {
                depth += 1;
                cur.push(c);
            }
            '>' if !in_literal => {
                depth = depth.saturating_sub(1);
                cur.push(c);
            }
            '|' if depth == 0 && !in_literal => {
                parts.push(cur.trim().to_string());
                cur.clear();
            }
            _ => cur.push(c),
        }
    }
    parts.push(cur.trim().to_string());
    parts
}

// =============================================================================
// Tests
// =============================================================================

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn parses_a_protocol_with_request_and_returns() {
        let src = r#"
            protocol "ping-pong" version="2.0.0" {
                namespace "test.pp"
                channel "pp" from="client" lifetime="persistent" {
                    request "Ping" {
                        field "message" type="string"
                        returns "Pong" {
                            field "reply" type="string"
                        }
                    }
                }
            }
        "#;
        let schema = parse(src).expect("should parse");
        let protocol = schema.protocol.expect("has protocol");
        assert_eq!(protocol.name, "ping-pong");
        assert_eq!(protocol.version, "2.0.0");
        assert_eq!(protocol.namespace.as_deref(), Some("test.pp"));
        assert_eq!(protocol.channels.len(), 1);

        let channel = &protocol.channels[0];
        assert_eq!(channel.name, "pp");
        assert_eq!(channel.from, ir::ChannelFrom::Client);
        assert_eq!(channel.lifetime, ir::ChannelLifetime::Persistent);
        assert_eq!(channel.backend, ir::ChannelBackend::Stream);
        assert_eq!(channel.requests.len(), 1);

        let request = &channel.requests[0];
        assert_eq!(request.name, "Ping");
        assert_eq!(
            request.fields,
            vec![ir::Field {
                name: "message".to_string(),
                ty: ir::Ty::Primitive(ir::Prim::String),
                required: true,
                flexible: false,
                default: None,
                description: None,
                constraints: ir::Constraints::default(),
            }]
        );
        let returns = request.returns.as_ref().expect("has returns");
        assert_eq!(returns.name, "Pong");
        assert_eq!(returns.fields[0].name, "reply");
    }

    #[test]
    fn parses_events_and_optional_fields() {
        let src = r#"
            protocol "p" version="1.0.0" {
                channel "c" from="server" lifetime="persistent" {
                    event "Tick" {
                        field "seq" type="int"
                        field "note" type="string" optional=#true
                    }
                }
            }
        "#;
        let schema = parse(src).expect("should parse");
        let channel = &schema.protocol.unwrap().channels[0];
        let event = &channel.events[0];
        assert_eq!(event.name, "Tick");
        assert!(
            event.fields[0].required,
            "unmarked field defaults to required"
        );
        assert!(
            !event.fields[1].required,
            "explicit optional=#true → not required"
        );
    }

    #[test]
    fn datagram_channel_requires_channel_id() {
        let src = r#"
            protocol "p" version="1.0.0" {
                channel "metric" from="server" lifetime="persistent" backend="datagram" {
                    event "M" { field "v" type="int" }
                }
            }
        "#;
        let err = parse(src).expect_err("datagram without channel_id is invalid");
        assert!(matches!(err, ParseError::Validation(_)));
    }

    #[test]
    fn datagram_channel_rejects_requests() {
        let src = r#"
            protocol "p" version="1.0.0" {
                channel "c" from="client" lifetime="persistent" backend="datagram" channel_id=1 {
                    request "R" { field "x" type="int" }
                }
            }
        "#;
        let err = parse(src).expect_err("datagram with request is invalid");
        assert!(matches!(err, ParseError::Validation(_)));
    }

    #[test]
    fn parses_datagram_channel_with_id() {
        let src = r#"
            protocol "p" version="1.0.0" {
                channel "metric" from="server" lifetime="persistent" backend="datagram" channel_id=7 {
                    event "M" { field "v" type="int" }
                }
            }
        "#;
        let channel = &parse(src).unwrap().protocol.unwrap().channels[0];
        assert_eq!(channel.backend, ir::ChannelBackend::Datagram);
        assert_eq!(channel.channel_id, Some(7));
    }

    #[test]
    fn parses_data_dialect_struct_and_enum() {
        let src = r#"
            struct "User" {
                field "id" type="string"
                field "tags" type="array<string>"
                field "role" type="Role"
            }
            enum "Role" {
                variant "admin"
                variant "member"
            }
        "#;
        let schema = parse(src).expect("should parse");
        assert!(schema.protocol.is_none());
        assert_eq!(schema.types.len(), 2);

        match &schema.types[0] {
            ir::TypeDef::Struct { name, fields, .. } => {
                assert_eq!(name, "User");
                assert_eq!(
                    fields[1].ty,
                    ir::Ty::Array(Box::new(ir::Ty::Primitive(ir::Prim::String)))
                );
                assert_eq!(fields[2].ty, ir::Ty::Named("Role".to_string()));
            }
            other => panic!("expected struct, got {other:?}"),
        }
        match &schema.types[1] {
            ir::TypeDef::Enum { name, variants, .. } => {
                assert_eq!(name, "Role");
                assert_eq!(variants, &["admin", "member"]);
            }
            other => panic!("expected enum, got {other:?}"),
        }
    }

    #[test]
    fn rejects_unknown_channel_from() {
        let src = r#"
            protocol "p" version="1.0.0" {
                channel "c" from="nobody" lifetime="persistent" {
                    event "E" { field "x" type="int" }
                }
            }
        "#;
        let err = parse(src).expect_err("unknown from value is invalid");
        assert!(matches!(err, ParseError::Validation(_)));
    }

    #[test]
    fn primitive_type_aliases() {
        assert_eq!(
            parse_ty("object").unwrap(),
            ir::Ty::Primitive(ir::Prim::Json)
        );
        assert_eq!(
            parse_ty("number").unwrap(),
            ir::Ty::Primitive(ir::Prim::Float)
        );
        assert_eq!(
            parse_ty("timestamp").unwrap(),
            ir::Ty::Primitive(ir::Prim::Datetime)
        );
    }

    #[test]
    fn rejects_unknown_type_reference() {
        let src = r#"
            struct "User" {
                field "role" type="Role"
            }
        "#;
        // `Role` is never defined as a struct/enum.
        let err = parse(src).expect_err("unknown type reference is invalid");
        assert!(matches!(err, ParseError::Validation(_)));
    }

    #[test]
    fn accepts_array_of_defined_type() {
        let src = r#"
            struct "Team" {
                field "members" type="array<User>"
            }
            struct "User" {
                field "id" type="string"
            }
        "#;
        // `array<User>` resolves because `User` is defined; order-independent.
        parse(src).expect("array<User> with User defined should parse");
    }

    // -------------------------------------------------------------------------
    // Tier 1 — record / relation / link / union
    // -------------------------------------------------------------------------

    #[test]
    fn parses_record_with_id_strategy_and_fields() {
        let src = r#"
            record "Atlas" {
                id strategy="uuidv7"
                field "name"   type="string"
                field "parent" type="link<Atlas>"
            }
        "#;
        let schema = parse(src).expect("record should parse");
        assert_eq!(schema.records.len(), 1);
        let atlas = &schema.records[0];
        assert_eq!(atlas.name, "Atlas");
        assert_eq!(atlas.id_strategy, ir::IdStrategy::Uuidv7);
        assert_eq!(atlas.fields[0].name, "name");
        // self-link resolves because `Atlas` is itself a defined record.
        assert_eq!(atlas.fields[1].ty, ir::Ty::Link("Atlas".to_string()));
    }

    #[test]
    fn record_id_strategy_defaults_to_uuidv7_when_absent() {
        let src = r#"
            record "Note" {
                field "body" type="string"
            }
        "#;
        let schema = parse(src).expect("record without `id` node should parse");
        assert_eq!(schema.records[0].id_strategy, ir::IdStrategy::Uuidv7);
    }

    #[test]
    fn parses_all_id_strategies() {
        for (kw, expected) in [
            ("ulid", ir::IdStrategy::Ulid),
            ("manual", ir::IdStrategy::Manual),
            ("uuidv7", ir::IdStrategy::Uuidv7),
        ] {
            let src = format!(
                r#"record "R" {{ id strategy="{kw}"
                       field "x" type="string" }}"#
            );
            let schema = parse(&src).expect("record parses");
            assert_eq!(schema.records[0].id_strategy, expected);
        }
    }

    #[test]
    fn rejects_unknown_id_strategy() {
        let src = r#"record "R" { id strategy="snowflake"
                       field "x" type="string" }"#;
        let err = parse(src).expect_err("unknown id strategy is invalid");
        assert!(matches!(err, ParseError::Validation(_)));
    }

    #[test]
    fn parses_relation_with_endpoints_and_edge_fields() {
        let src = r#"
            record "Memory" {
                field "body" type="string"
            }
            relation "derivedFrom" from="Memory" to="Memory" unique=#true {
                field "confidence" type="float"
                field "reason"     type="string"
            }
        "#;
        let schema = parse(src).expect("relation should parse");
        assert_eq!(schema.relations.len(), 1);
        let rel = &schema.relations[0];
        assert_eq!(rel.name, "derivedFrom");
        assert_eq!(rel.from, "Memory");
        assert_eq!(rel.to, "Memory");
        assert!(rel.unique);
        assert_eq!(rel.fields.len(), 2);
        assert_eq!(rel.fields[0].name, "confidence");
    }

    #[test]
    fn relation_unique_defaults_to_false() {
        let src = r#"
            record "A" { field "x" type="string" }
            relation "rel" from="A" to="A"
        "#;
        let schema = parse(src).expect("relation parses");
        assert!(!schema.relations[0].unique);
    }

    #[test]
    fn rejects_relation_with_unknown_endpoint() {
        let src = r#"
            record "A" { field "x" type="string" }
            relation "rel" from="A" to="Ghost"
        "#;
        let err = parse(src).expect_err("unknown relation endpoint is invalid");
        assert!(matches!(err, ParseError::Validation(_)));
    }

    #[test]
    fn parse_ty_link_and_literal_and_union() {
        assert_eq!(
            parse_ty("link<Atlas>").unwrap(),
            ir::Ty::Link("Atlas".to_string())
        );
        assert_eq!(
            parse_ty("'public'").unwrap(),
            ir::Ty::Literal("public".to_string())
        );
        assert_eq!(
            parse_ty("'public' | 'private'").unwrap(),
            ir::Ty::Union(vec![
                ir::Ty::Literal("public".to_string()),
                ir::Ty::Literal("private".to_string()),
            ])
        );
        assert_eq!(
            parse_ty("string | int | bool").unwrap(),
            ir::Ty::Union(vec![
                ir::Ty::Primitive(ir::Prim::String),
                ir::Ty::Primitive(ir::Prim::Int),
                ir::Ty::Primitive(ir::Prim::Bool),
            ])
        );
    }

    #[test]
    fn union_does_not_split_inside_brackets() {
        // `|` inside `array<...>` must not be treated as a union separator.
        // (there is no nested union here, but the splitter must stay depth-aware)
        assert_eq!(
            parse_ty("array<string>").unwrap(),
            ir::Ty::Array(Box::new(ir::Ty::Primitive(ir::Prim::String)))
        );
    }

    #[test]
    fn link_to_unknown_record_is_rejected() {
        let src = r#"
            record "Atlas" {
                field "parent" type="link<Ghost>"
            }
        "#;
        let err = parse(src).expect_err("link to undefined record is invalid");
        assert!(matches!(err, ParseError::Validation(_)));
    }

    #[test]
    fn flexible_and_default_properties_are_lowered() {
        let src = r#"
            record "Atlas" {
                field "metadata"   type="object" flexible=#true
                field "visibility" type="'public' | 'private'" default="private"
            }
        "#;
        let schema = parse(src).expect("record should parse");
        let fields = &schema.records[0].fields;
        assert!(fields[0].flexible, "flexible=#true is lowered");
        assert!(!fields[1].flexible, "absent flexible defaults false");
        assert_eq!(fields[1].default.as_deref(), Some("private"));
    }

    #[test]
    fn bare_name_is_embedded_link_is_stored() {
        // A bare `Name` resolves to a struct/enum; `link<Name>` to a record.
        // The same identifier in both forms must keep its distinct meaning.
        let src = r#"
            struct "GeoPoint" {
                field "lat" type="float"
            }
            record "Place" {
                field "at"     type="GeoPoint"
                field "parent" type="link<Place>"
            }
        "#;
        let schema = parse(src).expect("schema parses");
        let fields = &schema.records[0].fields;
        assert_eq!(fields[0].ty, ir::Ty::Named("GeoPoint".to_string()));
        assert_eq!(fields[1].ty, ir::Ty::Link("Place".to_string()));
    }

    // -------------------------------------------------------------------------
    // Tier 2 — description / constraints
    // -------------------------------------------------------------------------

    #[test]
    fn record_and_field_descriptions_are_lowered() {
        let src = r#"
            record "Memory" description="User memory with content" {
                field "content" type="string" description="Memory content text"
            }
        "#;
        let schema = parse(src).expect("record with descriptions parses");
        let memory = &schema.records[0];
        assert_eq!(
            memory.description.as_deref(),
            Some("User memory with content")
        );
        assert_eq!(
            memory.fields[0].description.as_deref(),
            Some("Memory content text")
        );
    }

    #[test]
    fn struct_enum_relation_descriptions_are_lowered() {
        let src = r#"
            struct "Point" description="A 2D point" {
                field "x" type="float"
            }
            enum "Color" description="An RGB primary" {
                variant "red"
            }
            record "Node" { field "v" type="int" }
            relation "edge" from="Node" to="Node" description="A directed edge"
        "#;
        let schema = parse(src).expect("schema parses");
        match &schema.types[0] {
            ir::TypeDef::Struct { description, .. } => {
                assert_eq!(description.as_deref(), Some("A 2D point"));
            }
            other => panic!("expected struct, got {other:?}"),
        }
        match &schema.types[1] {
            ir::TypeDef::Enum { description, .. } => {
                assert_eq!(description.as_deref(), Some("An RGB primary"));
            }
            other => panic!("expected enum, got {other:?}"),
        }
        assert_eq!(
            schema.relations[0].description.as_deref(),
            Some("A directed edge")
        );
    }

    #[test]
    fn field_constraints_are_lowered() {
        let src = r#"
            struct "Profile" {
                field "confidence" type="float" min=0 max=1
                field "name"       type="string" min_length=1 max_length=32 pattern="^[a-z]+$"
            }
        "#;
        let schema = parse(src).expect("schema parses");
        let fields = match &schema.types[0] {
            ir::TypeDef::Struct { fields, .. } => fields,
            other => panic!("expected struct, got {other:?}"),
        };
        assert_eq!(fields[0].constraints.min, Some(0));
        assert_eq!(fields[0].constraints.max, Some(1));
        assert_eq!(fields[1].constraints.min_length, Some(1));
        assert_eq!(fields[1].constraints.max_length, Some(32));
        assert_eq!(fields[1].constraints.pattern.as_deref(), Some("^[a-z]+$"));
    }

    #[test]
    fn absent_constraints_and_description_default_to_none() {
        let src = r#"
            struct "Bare" {
                field "x" type="int"
            }
        "#;
        let schema = parse(src).expect("schema parses");
        let fields = match &schema.types[0] {
            ir::TypeDef::Struct { fields, .. } => fields,
            other => panic!("expected struct, got {other:?}"),
        };
        assert!(fields[0].description.is_none());
        assert!(
            fields[0].constraints.is_empty(),
            "a field with no constraint properties has empty Constraints"
        );
    }
}