ron-schema 0.8.0

Schema definition and validation for RON (Rusty Object Notation) 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
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
/*************************
 * Author: Bradley Hunter
 */

use std::collections::{HashMap, HashSet};

use crate::error::{ErrorKind, ValidationError, ValidationResult, Warning, WarningKind};

/// Validates a parsed RON value against a schema.
///
/// Returns all validation errors and warnings found — does not stop at the first error.
/// An empty `errors` vec means the data is valid. Warnings are informational only.
#[must_use]
pub fn validate(schema: &Schema, value: &Spanned<RonValue>) -> ValidationResult {
    let mut errors = Vec::new();
    let mut warnings = Vec::new();
    validate_struct(&schema.root, value, "", &mut errors, &mut warnings, &schema.enums, &schema.aliases);
    ValidationResult { errors, warnings }
}
use crate::ron::RonValue;
use crate::schema::{EnumDef, Schema, SchemaType, StructDef};
use crate::span::{Span, Spanned};

/// Produces a human-readable description of a RON value for error messages.
fn describe(value: &RonValue) -> String {
    match value {
        RonValue::String(s) => {
            if s.len() > 20 {
                format!("String(\"{}...\")", &s[..20])
            } else {
                format!("String(\"{s}\")")
            }
        }
        RonValue::Integer(n) => format!("Integer({n})"),
        RonValue::Float(f) => format!("Float({f})"),
        RonValue::Bool(b) => format!("Bool({b})"),
        RonValue::Option(_) => "Option".to_string(),
        RonValue::Identifier(s) => format!("Identifier({s})"),
        RonValue::EnumVariant(name, _) => format!("{name}(...)"),
        RonValue::List(_) => "List".to_string(),
        RonValue::Map(_) => "Map".to_string(),
        RonValue::Tuple(_) => "Tuple".to_string(),
        RonValue::Struct(_) => "Struct".to_string(),
    }
}

/// Builds a dot-separated field path for error messages.
///
/// An empty parent means we're at the root, so just return the field name.
/// Otherwise, join with a dot: `"cost"` + `"generic"` → `"cost.generic"`.
fn build_path(parent: &str, field: &str) -> String {
    if parent.is_empty() {
        field.to_string()
    } else {
        format!("{parent}.{field}")
    }
}

/// Validates a single RON value against an expected schema type.
///
/// Matches on the expected type and checks that the actual value conforms.
/// For composite types (Option, List, Struct), recurses into the inner values.
/// Errors are collected into the `errors` vec — validation does not stop at the first error.
#[allow(clippy::too_many_lines)]
fn validate_type(
    expected: &SchemaType,
    actual: &Spanned<RonValue>,
    path: &str,
    errors: &mut Vec<ValidationError>,
    warnings: &mut Vec<Warning>,
    enums: &HashMap<String, EnumDef>,
    aliases: &HashMap<String, Spanned<SchemaType>>,
) {
    match expected {
        // Primitives: check that the value variant matches the schema type.
        SchemaType::String => {
            if !matches!(actual.value, RonValue::String(_)) {
                errors.push(ValidationError {
                    path: path.to_string(),
                    span: actual.span,
                    kind: ErrorKind::TypeMismatch {
                        expected: "String".to_string(),
                        found: describe(&actual.value),
                    },
                });
            }
        }
        SchemaType::Integer => {
            if !matches!(actual.value, RonValue::Integer(_)) {
                errors.push(ValidationError {
                    path: path.to_string(),
                    span: actual.span,
                    kind: ErrorKind::TypeMismatch {
                        expected: "Integer".to_string(),
                        found: describe(&actual.value),
                    },
                });
            }
        }
        SchemaType::Float => {
            if !matches!(actual.value, RonValue::Float(_)) {
                errors.push(ValidationError {
                    path: path.to_string(),
                    span: actual.span,
                    kind: ErrorKind::TypeMismatch {
                        expected: "Float".to_string(),
                        found: describe(&actual.value),
                    },
                });
            }
        }
        SchemaType::Bool => {
            if !matches!(actual.value, RonValue::Bool(_)) {
                errors.push(ValidationError {
                    path: path.to_string(),
                    span: actual.span,
                    kind: ErrorKind::TypeMismatch {
                        expected: "Bool".to_string(),
                        found: describe(&actual.value),
                    },
                });
            }
        }

        // Option: None is always valid. Some(inner) recurses into the inner value.
        // Anything else (bare integer, string, etc.) is an error — must be Some(...) or None.
        SchemaType::Option(inner_type) => match &actual.value {
            RonValue::Option(None) => {}
            RonValue::Option(Some(inner_value)) => {
                validate_type(inner_type, inner_value, path, errors, warnings, enums, aliases);
            }
            _ => {
                errors.push(ValidationError {
                    path: path.to_string(),
                    span: actual.span,
                    kind: ErrorKind::ExpectedOption {
                        found: describe(&actual.value),
                    },
                });
            }
        },

        // List: check value is a list, then validate each element against the element type.
        // Path gets bracket notation: "card_types[0]", "card_types[1]", etc.
        SchemaType::List(element_type) => {
            if let RonValue::List(elements) = &actual.value {
                for (index, element) in elements.iter().enumerate() {
                    let element_path = format!("{path}[{index}]");
                    validate_type(element_type, element, &element_path, errors, warnings, enums, aliases);
                }
            } else {
                errors.push(ValidationError {
                    path: path.to_string(),
                    span: actual.span,
                    kind: ErrorKind::ExpectedList {
                        found: describe(&actual.value),
                    },
                });
            }
        }

        // EnumRef: value must be a known variant. Unit variants are bare identifiers,
        // data variants are EnumVariant(name, data). The schema defines which variants
        // exist and whether they carry data.
        SchemaType::EnumRef(enum_name) => {
            let enum_def = &enums[enum_name];
            let variant_names: Vec<String> = enum_def.variants.keys().cloned().collect();

            match &actual.value {
                // Bare identifier — must be a known unit variant
                RonValue::Identifier(variant) => {
                    match enum_def.variants.get(variant) {
                        None => {
                            errors.push(ValidationError {
                                path: path.to_string(),
                                span: actual.span,
                                kind: ErrorKind::InvalidEnumVariant {
                                    enum_name: enum_name.clone(),
                                    variant: variant.clone(),
                                    valid: variant_names,
                                },
                            });
                        }
                        Some(Some(_expected_data_type)) => {
                            // Variant exists but expects data — bare identifier is wrong
                            errors.push(ValidationError {
                                path: path.to_string(),
                                span: actual.span,
                                kind: ErrorKind::InvalidVariantData {
                                    enum_name: enum_name.clone(),
                                    variant: variant.clone(),
                                    expected: "data".to_string(),
                                    found: "unit variant".to_string(),
                                },
                            });
                        }
                        Some(None) => {} // Unit variant, matches
                    }
                }
                // Enum variant with data — must be a known data variant, and data must match
                RonValue::EnumVariant(variant, data) => {
                    match enum_def.variants.get(variant) {
                        None => {
                            errors.push(ValidationError {
                                path: path.to_string(),
                                span: actual.span,
                                kind: ErrorKind::InvalidEnumVariant {
                                    enum_name: enum_name.clone(),
                                    variant: variant.clone(),
                                    valid: variant_names,
                                },
                            });
                        }
                        Some(None) => {
                            // Variant exists but is a unit variant — data is unexpected
                            errors.push(ValidationError {
                                path: path.to_string(),
                                span: actual.span,
                                kind: ErrorKind::InvalidVariantData {
                                    enum_name: enum_name.clone(),
                                    variant: variant.clone(),
                                    expected: "unit variant".to_string(),
                                    found: describe(&data.value),
                                },
                            });
                        }
                        Some(Some(expected_data_type)) => {
                            // Validate the associated data
                            validate_type(expected_data_type, data, path, errors, warnings, enums, aliases);
                        }
                    }
                }
                // Wrong value type entirely
                _ => {
                    errors.push(ValidationError {
                        path: path.to_string(),
                        span: actual.span,
                        kind: ErrorKind::TypeMismatch {
                            expected: enum_name.clone(),
                            found: describe(&actual.value),
                        },
                    });
                }
            }
        }

        // Map: check value is a map, then validate each key and value.
        SchemaType::Map(key_type, value_type) => {
            if let RonValue::Map(entries) = &actual.value {
                for (key, value) in entries {
                    let key_desc = describe(&key.value);
                    validate_type(key_type, key, path, errors, warnings, enums, aliases);
                    let entry_path = format!("{path}[{key_desc}]");
                    validate_type(value_type, value, &entry_path, errors, warnings, enums, aliases);
                }
            } else {
                errors.push(ValidationError {
                    path: path.to_string(),
                    span: actual.span,
                    kind: ErrorKind::ExpectedMap {
                        found: describe(&actual.value),
                    },
                });
            }
        }

        // Tuple: check value is a tuple, check element count, validate each element.
        SchemaType::Tuple(element_types) => {
            if let RonValue::Tuple(elements) = &actual.value {
                if elements.len() == element_types.len() {
                    for (index, (expected_type, element)) in element_types.iter().zip(elements).enumerate() {
                        let element_path = format!("{path}.{index}");
                        validate_type(expected_type, element, &element_path, errors, warnings, enums, aliases);
                    }
                } else {
                    errors.push(ValidationError {
                        path: path.to_string(),
                        span: actual.span,
                        kind: ErrorKind::TupleLengthMismatch {
                            expected: element_types.len(),
                            found: elements.len(),
                        },
                    });
                }
            } else {
                errors.push(ValidationError {
                    path: path.to_string(),
                    span: actual.span,
                    kind: ErrorKind::ExpectedTuple {
                        found: describe(&actual.value),
                    },
                });
            }
        }

        // AliasRef: look up the alias and validate against the resolved type.
        // Error messages use the alias name (e.g., "expected Cost") not the expanded type.
        SchemaType::AliasRef(alias_name) => {
            if let Some(resolved) = aliases.get(alias_name) {
                validate_type(&resolved.value, actual, path, errors, warnings, enums, aliases);
            }
            // If alias doesn't exist, the parser already caught it — unreachable in practice.
        }

        // Nested struct: recurse into validate_struct.
        SchemaType::Struct(struct_def) => {
            validate_struct(struct_def, actual, path, errors, warnings, enums, aliases);
        }
    }
}

/// Validates a RON struct against a schema struct definition.
///
/// Three checks:
/// 1. Missing fields — in schema but not in data (points to closing paren)
/// 2. Unknown fields — in data but not in schema (points to field name)
/// 3. Matching fields — present in both, recurse into `validate_type`
fn validate_struct(
    struct_def: &StructDef,
    actual: &Spanned<RonValue>,
    path: &str,
    errors: &mut Vec<ValidationError>,
    warnings: &mut Vec<Warning>,
    enums: &HashMap<String, EnumDef>,
    aliases: &HashMap<String, Spanned<SchemaType>>,
) {
    // Value must be a struct — if not, report and bail (can't check fields of a non-struct)
    let RonValue::Struct(data_struct) = &actual.value else {
        errors.push(ValidationError {
            path: path.to_string(),
            span: actual.span,
            kind: ErrorKind::ExpectedStruct {
                found: describe(&actual.value),
            },
        });
        return;
    };

    // Build a lookup map from data fields for O(1) access by name
    let data_map: HashMap<&str, &Spanned<RonValue>> = data_struct
        .fields
        .iter()
        .map(|(name, value)| (name.value.as_str(), value))
        .collect();

    // Build a set of schema field names for unknown-field detection
    let schema_names: HashSet<&str> = struct_def
        .fields
        .iter()
        .map(|f| f.name.value.as_str())
        .collect();

    // 1. Missing fields: in schema but not in data (skip fields with defaults)
    for field_def in &struct_def.fields {
        if !data_map.contains_key(field_def.name.value.as_str()) && field_def.default.is_none() {
            errors.push(ValidationError {
                path: build_path(path, &field_def.name.value),
                span: data_struct.close_span,
                kind: ErrorKind::MissingField {
                    field_name: field_def.name.value.clone(),
                },
            });
        }
    }

    // 2. Unknown fields: in data but not in schema
    for (name, _value) in &data_struct.fields {
        if !schema_names.contains(name.value.as_str()) {
            errors.push(ValidationError {
                path: build_path(path, &name.value),
                span: name.span,
                kind: ErrorKind::UnknownField {
                    field_name: name.value.clone(),
                },
            });
        }
    }

    // 3. Matching fields: validate each against its expected type
    for field_def in &struct_def.fields {
        if let Some(data_value) = data_map.get(field_def.name.value.as_str()) {
            let field_path = build_path(path, &field_def.name.value);
            validate_type(&field_def.type_.value, data_value, &field_path, errors, warnings, enums, aliases);
        }
    }

    // 4. Field order: warn if data fields appear in a different order than the schema
    let schema_order: Vec<&str> = struct_def.fields.iter()
        .map(|f| f.name.value.as_str())
        .collect();
    let data_fields: Vec<(&str, Span)> = data_struct.fields.iter()
        .map(|(name, _)| (name.value.as_str(), name.span))
        .collect();
    let mut last_schema_index = 0;
    for (data_name, data_span) in &data_fields {
        if let Some(schema_index) = schema_order.iter().position(|&s| s == *data_name) {
            if schema_index < last_schema_index {
                // Find the field that should have come after this one
                let expected_after = schema_order[last_schema_index];
                warnings.push(Warning {
                    path: build_path(path, data_name),
                    span: *data_span,
                    kind: WarningKind::FieldOrderMismatch {
                        field_name: data_name.to_string(),
                        expected_after: expected_after.to_string(),
                    },
                });
            } else {
                last_schema_index = schema_index;
            }
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::schema::parser::parse_schema;
    use crate::ron::parser::parse_ron;

    /// Parses both a schema and data string, runs validation, returns errors.
    fn validate_str(schema_src: &str, data_src: &str) -> Vec<ValidationError> {
        validate_full(schema_src, data_src).errors
    }

    /// Parses both a schema and data string, runs validation, returns the full result.
    fn validate_full(schema_src: &str, data_src: &str) -> ValidationResult {
        let schema = parse_schema(schema_src).expect("test schema should parse");
        let data = parse_ron(data_src).expect("test data should parse");
        validate(&schema, &data)
    }

    // ========================================================
    // describe() tests
    // ========================================================

    // Describes a string value.
    #[test]
    fn describe_string() {
        assert_eq!(describe(&RonValue::String("hi".to_string())), "String(\"hi\")");
    }

    // Truncates long strings at 20 characters.
    #[test]
    fn describe_string_truncated() {
        let long = "a".repeat(30);
        let desc = describe(&RonValue::String(long));
        assert!(desc.contains("..."));
    }

    // Describes an integer.
    #[test]
    fn describe_integer() {
        assert_eq!(describe(&RonValue::Integer(42)), "Integer(42)");
    }

    // Describes a float.
    #[test]
    fn describe_float() {
        assert_eq!(describe(&RonValue::Float(3.14)), "Float(3.14)");
    }

    // Describes a bool.
    #[test]
    fn describe_bool() {
        assert_eq!(describe(&RonValue::Bool(true)), "Bool(true)");
    }

    // Describes an identifier.
    #[test]
    fn describe_identifier() {
        assert_eq!(describe(&RonValue::Identifier("Creature".to_string())), "Identifier(Creature)");
    }

    // ========================================================
    // build_path() tests
    // ========================================================

    // Root-level field has no dot prefix.
    #[test]
    fn build_path_root() {
        assert_eq!(build_path("", "name"), "name");
    }

    // Nested field gets dot notation.
    #[test]
    fn build_path_nested() {
        assert_eq!(build_path("cost", "generic"), "cost.generic");
    }

    // Deeply nested path.
    #[test]
    fn build_path_deep() {
        assert_eq!(build_path("a.b", "c"), "a.b.c");
    }

    // ========================================================
    // Valid data — no errors
    // ========================================================

    // Valid data with a single string field.
    #[test]
    fn valid_single_string_field() {
        let errs = validate_str("(\n  name: String,\n)", "(name: \"hello\")");
        assert!(errs.is_empty());
    }

    // Valid data with all primitive types.
    #[test]
    fn valid_all_primitives() {
        let schema = "(\n  s: String,\n  i: Integer,\n  f: Float,\n  b: Bool,\n)";
        let data = "(s: \"hi\", i: 42, f: 3.14, b: true)";
        let errs = validate_str(schema, data);
        assert!(errs.is_empty());
    }

    // Valid data with None option.
    #[test]
    fn valid_option_none() {
        let errs = validate_str("(\n  power: Option(Integer),\n)", "(power: None)");
        assert!(errs.is_empty());
    }

    // Valid data with Some option.
    #[test]
    fn valid_option_some() {
        let errs = validate_str("(\n  power: Option(Integer),\n)", "(power: Some(5))");
        assert!(errs.is_empty());
    }

    // Valid data with empty list.
    #[test]
    fn valid_list_empty() {
        let errs = validate_str("(\n  tags: [String],\n)", "(tags: [])");
        assert!(errs.is_empty());
    }

    // Valid data with populated list.
    #[test]
    fn valid_list_populated() {
        let errs = validate_str("(\n  tags: [String],\n)", "(tags: [\"a\", \"b\"])");
        assert!(errs.is_empty());
    }

    // Valid data with enum variant.
    #[test]
    fn valid_enum_variant() {
        let schema = "(\n  kind: Kind,\n)\nenum Kind { A, B, C }";
        let data = "(kind: B)";
        let errs = validate_str(schema, data);
        assert!(errs.is_empty());
    }

    // Valid data with list of enum variants.
    #[test]
    fn valid_enum_list() {
        let schema = "(\n  types: [CardType],\n)\nenum CardType { Creature, Trap }";
        let data = "(types: [Creature, Trap])";
        let errs = validate_str(schema, data);
        assert!(errs.is_empty());
    }

    // Valid data with nested struct.
    #[test]
    fn valid_nested_struct() {
        let schema = "(\n  cost: (\n    generic: Integer,\n    sigil: Integer,\n  ),\n)";
        let data = "(cost: (generic: 2, sigil: 1))";
        let errs = validate_str(schema, data);
        assert!(errs.is_empty());
    }

    // ========================================================
    // TypeMismatch errors
    // ========================================================

    // String field rejects integer value.
    #[test]
    fn type_mismatch_string_got_integer() {
        let errs = validate_str("(\n  name: String,\n)", "(name: 42)");
        assert_eq!(errs.len(), 1);
        assert!(matches!(&errs[0].kind, ErrorKind::TypeMismatch { expected, .. } if expected == "String"));
    }

    // Integer field rejects string value.
    #[test]
    fn type_mismatch_integer_got_string() {
        let errs = validate_str("(\n  age: Integer,\n)", "(age: \"five\")");
        assert_eq!(errs.len(), 1);
        assert!(matches!(&errs[0].kind, ErrorKind::TypeMismatch { expected, .. } if expected == "Integer"));
    }

    // Float field rejects integer value.
    #[test]
    fn type_mismatch_float_got_integer() {
        let errs = validate_str("(\n  rate: Float,\n)", "(rate: 5)");
        assert_eq!(errs.len(), 1);
        assert!(matches!(&errs[0].kind, ErrorKind::TypeMismatch { expected, .. } if expected == "Float"));
    }

    // Bool field rejects string value.
    #[test]
    fn type_mismatch_bool_got_string() {
        let errs = validate_str("(\n  flag: Bool,\n)", "(flag: \"yes\")");
        assert_eq!(errs.len(), 1);
        assert!(matches!(&errs[0].kind, ErrorKind::TypeMismatch { expected, .. } if expected == "Bool"));
    }

    // Error path is correct for type mismatch.
    #[test]
    fn type_mismatch_has_correct_path() {
        let errs = validate_str("(\n  name: String,\n)", "(name: 42)");
        assert_eq!(errs[0].path, "name");
    }

    // ========================================================
    // MissingField errors
    // ========================================================

    // Missing field is detected.
    #[test]
    fn missing_field_detected() {
        let errs = validate_str("(\n  name: String,\n  age: Integer,\n)", "(name: \"hi\")");
        assert_eq!(errs.len(), 1);
        assert!(matches!(&errs[0].kind, ErrorKind::MissingField { field_name } if field_name == "age"));
    }

    // Missing field path is correct.
    #[test]
    fn missing_field_has_correct_path() {
        let errs = validate_str("(\n  name: String,\n  age: Integer,\n)", "(name: \"hi\")");
        assert_eq!(errs[0].path, "age");
    }

    // Missing field span points to close paren.
    #[test]
    fn missing_field_span_points_to_close_paren() {
        let data = "(name: \"hi\")";
        let errs = validate_str("(\n  name: String,\n  age: Integer,\n)", data);
        // close paren is the last character
        assert_eq!(errs[0].span.start.offset, data.len() - 1);
    }

    // Multiple missing fields are all reported.
    #[test]
    fn missing_fields_all_reported() {
        let errs = validate_str("(\n  a: String,\n  b: Integer,\n  c: Bool,\n)", "()");
        assert_eq!(errs.len(), 3);
    }

    // ========================================================
    // FieldOrderMismatch warnings
    // ========================================================

    // No warning when fields are in schema order.
    #[test]
    fn field_order_correct_no_warning() {
        let result = validate_full("(\n  a: String,\n  b: Integer,\n)", "(a: \"hi\", b: 1)");
        assert!(result.warnings.is_empty());
    }

    // Warning when fields are swapped.
    #[test]
    fn field_order_swapped_produces_warning() {
        let result = validate_full("(\n  a: String,\n  b: Integer,\n)", "(b: 1, a: \"hi\")");
        assert_eq!(result.warnings.len(), 1);
    }

    // Warning has FieldOrderMismatch kind.
    #[test]
    fn field_order_warning_has_correct_kind() {
        let result = validate_full("(\n  a: String,\n  b: Integer,\n)", "(b: 1, a: \"hi\")");
        assert!(matches!(&result.warnings[0].kind, WarningKind::FieldOrderMismatch { .. }));
    }

    // Warning identifies the out-of-order field.
    #[test]
    fn field_order_warning_identifies_field() {
        let result = validate_full("(\n  a: String,\n  b: Integer,\n)", "(b: 1, a: \"hi\")");
        if let WarningKind::FieldOrderMismatch { field_name, .. } = &result.warnings[0].kind {
            assert_eq!(field_name, "a");
        } else {
            panic!("expected FieldOrderMismatch");
        }
    }

    // Warning identifies the field it should come after.
    #[test]
    fn field_order_warning_identifies_expected_after() {
        let result = validate_full("(\n  a: String,\n  b: Integer,\n)", "(b: 1, a: \"hi\")");
        if let WarningKind::FieldOrderMismatch { expected_after, .. } = &result.warnings[0].kind {
            assert_eq!(expected_after, "b");
        } else {
            panic!("expected FieldOrderMismatch");
        }
    }

    // Warning has correct path.
    #[test]
    fn field_order_warning_has_correct_path() {
        let result = validate_full("(\n  a: String,\n  b: Integer,\n)", "(b: 1, a: \"hi\")");
        assert_eq!(result.warnings[0].path, "a");
    }

    // Warning span points to the field name.
    #[test]
    fn field_order_warning_has_span() {
        let result = validate_full("(\n  a: String,\n  b: Integer,\n)", "(b: 1, a: \"hi\")");
        assert!(result.warnings[0].span.start.line > 0);
    }

    // Correct order with three fields produces no warning.
    #[test]
    fn field_order_three_fields_correct() {
        let result = validate_full(
            "(\n  a: String,\n  b: Integer,\n  c: Bool,\n)",
            "(a: \"hi\", b: 1, c: true)",
        );
        assert!(result.warnings.is_empty());
    }

    // Middle field out of order.
    #[test]
    fn field_order_middle_field_swapped() {
        let result = validate_full(
            "(\n  a: String,\n  b: Integer,\n  c: Bool,\n)",
            "(a: \"hi\", c: true, b: 1)",
        );
        assert_eq!(result.warnings.len(), 1);
        if let WarningKind::FieldOrderMismatch { field_name, .. } = &result.warnings[0].kind {
            assert_eq!(field_name, "b");
        } else {
            panic!("expected FieldOrderMismatch");
        }
    }

    // Field order warning does not produce errors.
    #[test]
    fn field_order_warning_no_errors() {
        let result = validate_full("(\n  a: String,\n  b: Integer,\n)", "(b: 1, a: \"hi\")");
        assert!(result.errors.is_empty());
    }

    // Unknown fields don't affect order checking.
    #[test]
    fn field_order_with_unknown_field() {
        let result = validate_full("(\n  a: String,\n  b: Integer,\n)", "(b: 1, x: true, a: \"hi\")");
        assert_eq!(result.warnings.len(), 1);
    }

    // ========================================================
    // Default values — fields with defaults are optional
    // ========================================================

    // Field with default does not produce MissingField when absent.
    #[test]
    fn default_field_not_required() {
        let errs = validate_str("(\n  name: String,\n  label: String = \"none\",\n)", "(name: \"hi\")");
        assert!(errs.is_empty());
    }

    // Field with default still validates type when present.
    #[test]
    fn default_field_still_validates_type() {
        let errs = validate_str("(\n  name: String,\n  label: String = \"none\",\n)", "(name: \"hi\", label: 42)");
        assert_eq!(errs.len(), 1);
        assert!(matches!(&errs[0].kind, ErrorKind::TypeMismatch { .. }));
    }

    // Field with default accepts correct type when present.
    #[test]
    fn default_field_accepts_correct_type() {
        let errs = validate_str("(\n  name: String,\n  label: String = \"none\",\n)", "(name: \"hi\", label: \"custom\")");
        assert!(errs.is_empty());
    }

    // Field without default still produces MissingField.
    #[test]
    fn non_default_field_still_required() {
        let errs = validate_str("(\n  name: String,\n  label: String = \"none\",\n)", "(label: \"hi\")");
        assert_eq!(errs.len(), 1);
        assert!(matches!(&errs[0].kind, ErrorKind::MissingField { field_name } if field_name == "name"));
    }

    // Multiple fields with defaults can all be absent.
    #[test]
    fn multiple_default_fields_all_absent() {
        let errs = validate_str(
            "(\n  name: String,\n  a: Integer = 0,\n  b: Bool = false,\n  c: String = \"x\",\n)",
            "(name: \"hi\")",
        );
        assert!(errs.is_empty());
    }

    // Default on Option field allows absence.
    #[test]
    fn default_option_field_not_required() {
        let errs = validate_str("(\n  name: String,\n  tag: Option(String) = None,\n)", "(name: \"hi\")");
        assert!(errs.is_empty());
    }

    // Default on list field allows absence.
    #[test]
    fn default_list_field_not_required() {
        let errs = validate_str("(\n  name: String,\n  tags: [String] = [],\n)", "(name: \"hi\")");
        assert!(errs.is_empty());
    }

    // ========================================================
    // UnknownField errors
    // ========================================================

    // Unknown field is detected.
    #[test]
    fn unknown_field_detected() {
        let errs = validate_str("(\n  name: String,\n)", "(name: \"hi\", colour: \"red\")");
        assert_eq!(errs.len(), 1);
        assert!(matches!(&errs[0].kind, ErrorKind::UnknownField { field_name } if field_name == "colour"));
    }

    // Unknown field path is correct.
    #[test]
    fn unknown_field_has_correct_path() {
        let errs = validate_str("(\n  name: String,\n)", "(name: \"hi\", extra: 5)");
        assert_eq!(errs[0].path, "extra");
    }

    // ========================================================
    // InvalidEnumVariant errors
    // ========================================================

    // Invalid enum variant is detected.
    #[test]
    fn invalid_enum_variant() {
        let schema = "(\n  kind: Kind,\n)\nenum Kind { A, B }";
        let errs = validate_str(schema, "(kind: C)");
        assert_eq!(errs.len(), 1);
        assert!(matches!(&errs[0].kind, ErrorKind::InvalidEnumVariant { variant, .. } if variant == "C"));
    }

    // Enum field rejects string value (should be bare identifier).
    #[test]
    fn enum_rejects_string() {
        let schema = "(\n  kind: Kind,\n)\nenum Kind { A, B }";
        let errs = validate_str(schema, "(kind: \"A\")");
        assert_eq!(errs.len(), 1);
        assert!(matches!(&errs[0].kind, ErrorKind::TypeMismatch { .. }));
    }

    // ========================================================
    // ExpectedOption errors
    // ========================================================

    // Option field rejects bare integer (not wrapped in Some).
    #[test]
    fn expected_option_got_bare_value() {
        let errs = validate_str("(\n  power: Option(Integer),\n)", "(power: 5)");
        assert_eq!(errs.len(), 1);
        assert!(matches!(&errs[0].kind, ErrorKind::ExpectedOption { .. }));
    }

    // Some wrapping wrong type is an error.
    #[test]
    fn option_some_wrong_inner_type() {
        let errs = validate_str("(\n  power: Option(Integer),\n)", "(power: Some(\"five\"))");
        assert_eq!(errs.len(), 1);
        assert!(matches!(&errs[0].kind, ErrorKind::TypeMismatch { expected, .. } if expected == "Integer"));
    }

    // ========================================================
    // ExpectedList errors
    // ========================================================

    // List field rejects non-list value.
    #[test]
    fn expected_list_got_string() {
        let errs = validate_str("(\n  tags: [String],\n)", "(tags: \"hi\")");
        assert_eq!(errs.len(), 1);
        assert!(matches!(&errs[0].kind, ErrorKind::ExpectedList { .. }));
    }

    // List element with wrong type is an error.
    #[test]
    fn list_element_wrong_type() {
        let errs = validate_str("(\n  tags: [String],\n)", "(tags: [\"ok\", 42])");
        assert_eq!(errs.len(), 1);
        assert!(matches!(&errs[0].kind, ErrorKind::TypeMismatch { expected, .. } if expected == "String"));
    }

    // List element error has bracket path.
    #[test]
    fn list_element_error_has_bracket_path() {
        let errs = validate_str("(\n  tags: [String],\n)", "(tags: [\"ok\", 42])");
        assert_eq!(errs[0].path, "tags[1]");
    }

    // ========================================================
    // ExpectedStruct errors
    // ========================================================

    // Struct field rejects non-struct value.
    #[test]
    fn expected_struct_got_integer() {
        let schema = "(\n  cost: (\n    generic: Integer,\n  ),\n)";
        let errs = validate_str(schema, "(cost: 5)");
        assert_eq!(errs.len(), 1);
        assert!(matches!(&errs[0].kind, ErrorKind::ExpectedStruct { .. }));
    }

    // ========================================================
    // Nested validation
    // ========================================================

    // Type mismatch in nested struct has correct path.
    #[test]
    fn nested_struct_type_mismatch_path() {
        let schema = "(\n  cost: (\n    generic: Integer,\n  ),\n)";
        let errs = validate_str(schema, "(cost: (generic: \"two\"))");
        assert_eq!(errs.len(), 1);
        assert_eq!(errs[0].path, "cost.generic");
    }

    // Missing field in nested struct has correct path.
    #[test]
    fn nested_struct_missing_field_path() {
        let schema = "(\n  cost: (\n    generic: Integer,\n    sigil: Integer,\n  ),\n)";
        let errs = validate_str(schema, "(cost: (generic: 1))");
        assert_eq!(errs.len(), 1);
        assert_eq!(errs[0].path, "cost.sigil");
    }

    // ========================================================
    // Multiple errors collected
    // ========================================================

    // Multiple errors in one struct are all reported.
    #[test]
    fn multiple_errors_collected() {
        let schema = "(\n  name: String,\n  age: Integer,\n  active: Bool,\n)";
        let data = "(name: 42, age: \"five\", active: \"yes\")";
        let errs = validate_str(schema, data);
        assert_eq!(errs.len(), 3);
    }

    // Mixed error types are all collected.
    #[test]
    fn mixed_error_types_collected() {
        let schema = "(\n  name: String,\n  age: Integer,\n)";
        let data = "(name: \"hi\", age: \"five\", extra: true)";
        let errs = validate_str(schema, data);
        // age is TypeMismatch, extra is UnknownField
        assert_eq!(errs.len(), 2);
    }

    // ========================================================
    // Integration: card-like schema
    // ========================================================

    // Valid card data produces no errors.
    #[test]
    fn valid_card_data() {
        let schema = r#"(
            name: String,
            card_types: [CardType],
            legendary: Bool,
            power: Option(Integer),
            toughness: Option(Integer),
            keywords: [String],
        )
        enum CardType { Creature, Trap, Artifact }"#;
        let data = r#"(
            name: "Ashborn Hound",
            card_types: [Creature],
            legendary: false,
            power: Some(1),
            toughness: Some(1),
            keywords: [],
        )"#;
        let errs = validate_str(schema, data);
        assert!(errs.is_empty());
    }

    // Card data with multiple errors reports all of them.
    #[test]
    fn card_data_multiple_errors() {
        let schema = r#"(
            name: String,
            card_types: [CardType],
            legendary: Bool,
            power: Option(Integer),
        )
        enum CardType { Creature, Trap }"#;
        let data = r#"(
            name: 42,
            card_types: [Pirates],
            legendary: false,
            power: Some("five"),
        )"#;
        let errs = validate_str(schema, data);
        // name: TypeMismatch, card_types[0]: InvalidEnumVariant, power: TypeMismatch
        assert_eq!(errs.len(), 3);
    }

    // ========================================================
    // Type alias validation
    // ========================================================

    // Alias to a struct type validates correctly.
    #[test]
    fn alias_struct_valid() {
        let schema = "(\n  cost: Cost,\n)\ntype Cost = (generic: Integer,)";
        let data = "(cost: (generic: 5))";
        let errs = validate_str(schema, data);
        assert!(errs.is_empty());
    }

    // Alias to a struct type catches type mismatch inside.
    #[test]
    fn alias_struct_type_mismatch() {
        let schema = "(\n  cost: Cost,\n)\ntype Cost = (generic: Integer,)";
        let data = "(cost: (generic: \"five\"))";
        let errs = validate_str(schema, data);
        assert_eq!(errs.len(), 1);
        assert!(matches!(&errs[0].kind, ErrorKind::TypeMismatch { expected, .. } if expected == "Integer"));
    }

    // Alias to a primitive type validates correctly.
    #[test]
    fn alias_primitive_valid() {
        let schema = "(\n  name: Name,\n)\ntype Name = String";
        let data = "(name: \"hello\")";
        let errs = validate_str(schema, data);
        assert!(errs.is_empty());
    }

    // Alias to a primitive type catches mismatch.
    #[test]
    fn alias_primitive_mismatch() {
        let schema = "(\n  name: Name,\n)\ntype Name = String";
        let data = "(name: 42)";
        let errs = validate_str(schema, data);
        assert_eq!(errs.len(), 1);
    }

    // Alias used inside a list validates each element.
    #[test]
    fn alias_in_list_valid() {
        let schema = "(\n  costs: [Cost],\n)\ntype Cost = (generic: Integer,)";
        let data = "(costs: [(generic: 1), (generic: 2)])";
        let errs = validate_str(schema, data);
        assert!(errs.is_empty());
    }

    // Alias used inside a list catches element errors.
    #[test]
    fn alias_in_list_element_error() {
        let schema = "(\n  costs: [Cost],\n)\ntype Cost = (generic: Integer,)";
        let data = "(costs: [(generic: 1), (generic: \"two\")])";
        let errs = validate_str(schema, data);
        assert_eq!(errs.len(), 1);
        assert_eq!(errs[0].path, "costs[1].generic");
    }

    // ========================================================
    // Map validation
    // ========================================================

    // Valid map with string keys and integer values.
    #[test]
    fn map_valid() {
        let schema = "(\n  attrs: {String: Integer},\n)";
        let data = "(attrs: {\"str\": 5, \"dex\": 3})";
        let errs = validate_str(schema, data);
        assert!(errs.is_empty());
    }

    // Empty map is always valid.
    #[test]
    fn map_empty_valid() {
        let schema = "(\n  attrs: {String: Integer},\n)";
        let data = "(attrs: {})";
        let errs = validate_str(schema, data);
        assert!(errs.is_empty());
    }

    // Non-map value where map expected.
    #[test]
    fn map_expected_got_string() {
        let schema = "(\n  attrs: {String: Integer},\n)";
        let data = "(attrs: \"not a map\")";
        let errs = validate_str(schema, data);
        assert_eq!(errs.len(), 1);
        assert!(matches!(&errs[0].kind, ErrorKind::ExpectedMap { .. }));
    }

    // Map value with wrong type.
    #[test]
    fn map_wrong_value_type() {
        let schema = "(\n  attrs: {String: Integer},\n)";
        let data = "(attrs: {\"str\": \"five\"})";
        let errs = validate_str(schema, data);
        assert_eq!(errs.len(), 1);
        assert!(matches!(&errs[0].kind, ErrorKind::TypeMismatch { expected, .. } if expected == "Integer"));
    }

    // Map key with wrong type.
    #[test]
    fn map_wrong_key_type() {
        let schema = "(\n  attrs: {String: Integer},\n)";
        let data = "(attrs: {42: 5})";
        let errs = validate_str(schema, data);
        assert_eq!(errs.len(), 1);
        assert!(matches!(&errs[0].kind, ErrorKind::TypeMismatch { expected, .. } if expected == "String"));
    }

    // ========================================================
    // Tuple validation
    // ========================================================

    // Valid tuple.
    #[test]
    fn tuple_valid() {
        let schema = "(\n  pos: (Float, Float),\n)";
        let data = "(pos: (1.0, 2.5))";
        let errs = validate_str(schema, data);
        assert!(errs.is_empty());
    }

    // Non-tuple value where tuple expected.
    #[test]
    fn tuple_expected_got_string() {
        let schema = "(\n  pos: (Float, Float),\n)";
        let data = "(pos: \"not a tuple\")";
        let errs = validate_str(schema, data);
        assert_eq!(errs.len(), 1);
        assert!(matches!(&errs[0].kind, ErrorKind::ExpectedTuple { .. }));
    }

    // Tuple with wrong element count.
    #[test]
    fn tuple_wrong_length() {
        let schema = "(\n  pos: (Float, Float),\n)";
        let data = "(pos: (1.0, 2.5, 3.0))";
        let errs = validate_str(schema, data);
        assert_eq!(errs.len(), 1);
        assert!(matches!(&errs[0].kind, ErrorKind::TupleLengthMismatch { expected: 2, found: 3 }));
    }

    // Tuple with wrong element type.
    #[test]
    fn tuple_wrong_element_type() {
        let schema = "(\n  pos: (Float, Float),\n)";
        let data = "(pos: (1.0, \"bad\"))";
        let errs = validate_str(schema, data);
        assert_eq!(errs.len(), 1);
        assert!(matches!(&errs[0].kind, ErrorKind::TypeMismatch { expected, .. } if expected == "Float"));
    }

    // Tuple element error has correct path.
    #[test]
    fn tuple_element_error_path() {
        let schema = "(\n  pos: (Float, Float),\n)";
        let data = "(pos: (1.0, \"bad\"))";
        let errs = validate_str(schema, data);
        assert_eq!(errs[0].path, "pos.1");
    }

    // ========================================================
    // Enum variant with data — validation
    // ========================================================

    // Valid data variant.
    #[test]
    fn enum_data_variant_valid() {
        let schema = "(\n  effect: Effect,\n)\nenum Effect { Damage(Integer), Draw }";
        let data = "(effect: Damage(5))";
        let errs = validate_str(schema, data);
        assert!(errs.is_empty());
    }

    // Valid unit variant alongside data variants.
    #[test]
    fn enum_unit_variant_valid() {
        let schema = "(\n  effect: Effect,\n)\nenum Effect { Damage(Integer), Draw }";
        let data = "(effect: Draw)";
        let errs = validate_str(schema, data);
        assert!(errs.is_empty());
    }

    // Data variant with wrong inner type.
    #[test]
    fn enum_data_variant_wrong_type() {
        let schema = "(\n  effect: Effect,\n)\nenum Effect { Damage(Integer), Draw }";
        let data = "(effect: Damage(\"five\"))";
        let errs = validate_str(schema, data);
        assert_eq!(errs.len(), 1);
        assert!(matches!(&errs[0].kind, ErrorKind::TypeMismatch { expected, .. } if expected == "Integer"));
    }

    // Unknown variant name with data.
    #[test]
    fn enum_data_variant_unknown() {
        let schema = "(\n  effect: Effect,\n)\nenum Effect { Damage(Integer), Draw }";
        let data = "(effect: Explode(10))";
        let errs = validate_str(schema, data);
        assert_eq!(errs.len(), 1);
        assert!(matches!(&errs[0].kind, ErrorKind::InvalidEnumVariant { .. }));
    }

    // Bare identifier for a variant that expects data.
    #[test]
    fn enum_missing_data() {
        let schema = "(\n  effect: Effect,\n)\nenum Effect { Damage(Integer), Draw }";
        let data = "(effect: Damage)";
        let errs = validate_str(schema, data);
        assert_eq!(errs.len(), 1);
        assert!(matches!(&errs[0].kind, ErrorKind::InvalidVariantData { .. }));
    }

    // Data provided for a unit variant.
    #[test]
    fn enum_unexpected_data() {
        let schema = "(\n  effect: Effect,\n)\nenum Effect { Damage(Integer), Draw }";
        let data = "(effect: Draw(5))";
        let errs = validate_str(schema, data);
        assert_eq!(errs.len(), 1);
        assert!(matches!(&errs[0].kind, ErrorKind::InvalidVariantData { .. }));
    }
}