lemma-engine 0.8.14

A language that means business.
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
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
use crate::error::Error;
use crate::limits::ResourceLimits;

pub mod ast;
pub mod lexer;
pub mod parser;
pub mod source;

pub use ast::{DepthTracker, Span};
pub use source::Source;

pub use ast::*;
pub use parser::ParseResult;

pub fn parse(
    content: &str,
    source_type: source::SourceType,
    limits: &ResourceLimits,
) -> Result<ParseResult, Error> {
    parser::parse(content, source_type, limits)
}

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

#[cfg(test)]
mod tests {
    use super::{parse, ArithmeticComputation, Expression, ExpressionKind};
    use crate::formatting::format_parse_result;
    use crate::Error;
    use crate::ResourceLimits;

    #[test]
    fn parse_empty_input_returns_no_specs() {
        let result = parse(
            "",
            crate::parsing::source::SourceType::Volatile,
            &ResourceLimits::default(),
        )
        .unwrap()
        .into_flattened_specs();
        assert_eq!(result.len(), 0);
    }

    #[test]
    fn parse_workspace_file_yields_expected_spec_datas_and_rules() {
        let input = r#"spec person
data name: "John Doe"
rule adult: true"#;
        let result = parse(
            input,
            crate::parsing::source::SourceType::Volatile,
            &ResourceLimits::default(),
        )
        .unwrap()
        .into_flattened_specs();
        assert_eq!(result.len(), 1);
        assert_eq!(result[0].name, "person");
        assert_eq!(result[0].data.len(), 1);
        assert_eq!(result[0].rules.len(), 1);
        assert_eq!(result[0].rules[0].name, "adult");
    }

    #[test]
    fn mixing_data_and_rules_is_collected_into_spec() {
        let input = r#"spec test
data name: "John"
rule is_adult: age >= 18
data age: 25
rule can_drink: age >= 21
data status: "active"
rule is_eligible: is_adult and status is "active""#;

        let result = parse(
            input,
            crate::parsing::source::SourceType::Volatile,
            &ResourceLimits::default(),
        )
        .unwrap()
        .into_flattened_specs();
        assert_eq!(result.len(), 1);
        assert_eq!(result[0].data.len(), 3);
        assert_eq!(result[0].rules.len(), 3);
    }

    #[test]
    fn parse_simple_spec_collects_data() {
        let input = r#"spec person
data name: "John"
data age: 25"#;
        let result = parse(
            input,
            crate::parsing::source::SourceType::Volatile,
            &ResourceLimits::default(),
        )
        .unwrap()
        .into_flattened_specs();
        assert_eq!(result.len(), 1);
        assert_eq!(result[0].name, "person");
        assert_eq!(result[0].data.len(), 2);
    }

    #[test]
    fn parse_dotted_spec_name() {
        let input = r#"spec contracts.employment.jack
data name: "Jack""#;
        let result = parse(
            input,
            crate::parsing::source::SourceType::Volatile,
            &ResourceLimits::default(),
        )
        .unwrap()
        .into_flattened_specs();
        assert_eq!(result.len(), 1);
        assert_eq!(result[0].name, "contracts.employment.jack");
    }

    #[test]
    fn parse_slashed_spec_name() {
        let input = "spec contracts/employment/jack\ndata x: 1";
        let result = parse(
            input,
            crate::parsing::source::SourceType::Volatile,
            &ResourceLimits::default(),
        )
        .unwrap()
        .into_flattened_specs();
        assert_eq!(result.len(), 1);
        assert_eq!(result[0].name, "contracts/employment/jack");
    }

    #[test]
    fn parse_spec_name_no_version_tag() {
        let input = "spec myspec\nrule x: 1";
        let result = parse(
            input,
            crate::parsing::source::SourceType::Volatile,
            &ResourceLimits::default(),
        )
        .unwrap()
        .into_flattened_specs();
        assert_eq!(result.len(), 1);
        assert_eq!(result[0].name, "myspec");
        assert_eq!(result[0].effective_from(), None);
    }

    #[test]
    fn parse_commentary_block_is_attached_to_spec() {
        let input = r#"spec person
"""
This is a markdown comment
uses **bold** text
"""
data name: "John""#;
        let result = parse(
            input,
            crate::parsing::source::SourceType::Volatile,
            &ResourceLimits::default(),
        )
        .unwrap()
        .into_flattened_specs();
        assert_eq!(result.len(), 1);
        assert!(result[0].commentary.is_some());
        assert!(result[0].commentary.as_ref().unwrap().contains("**bold**"));
    }

    #[test]
    fn parse_spec_with_rule_collects_rule() {
        let input = r#"spec person
rule is_adult: age >= 18"#;
        let result = parse(
            input,
            crate::parsing::source::SourceType::Volatile,
            &ResourceLimits::default(),
        )
        .unwrap()
        .into_flattened_specs();
        assert_eq!(result.len(), 1);
        assert_eq!(result[0].rules.len(), 1);
        assert_eq!(result[0].rules[0].name, "is_adult");
    }

    #[test]
    fn parse_multiple_specs_returns_all_specs() {
        let input = r#"spec person
data name: "John"

spec company
data name: "Acme Corp""#;
        let result = parse(
            input,
            crate::parsing::source::SourceType::Volatile,
            &ResourceLimits::default(),
        )
        .unwrap()
        .into_flattened_specs();
        assert_eq!(result.len(), 2);
        assert_eq!(result[0].name, "person");
        assert_eq!(result[1].name, "company");
    }

    #[test]
    fn parse_allows_duplicate_data_names() {
        let input = r#"spec person
data name: "John"
data name: "Jane""#;
        let result = parse(
            input,
            crate::parsing::source::SourceType::Volatile,
            &ResourceLimits::default(),
        );
        assert!(
            result.is_ok(),
            "Parser should succeed even with duplicate data"
        );
    }

    #[test]
    fn parse_allows_duplicate_rule_names() {
        let input = r#"spec person
rule is_adult: age >= 18
rule is_adult: age >= 21"#;
        let result = parse(
            input,
            crate::parsing::source::SourceType::Volatile,
            &ResourceLimits::default(),
        );
        assert!(
            result.is_ok(),
            "Parser should succeed even with duplicate rules"
        );
    }

    #[test]
    fn parse_rejects_malformed_input() {
        let input = "invalid syntax here";
        let result = parse(
            input,
            crate::parsing::source::SourceType::Volatile,
            &ResourceLimits::default(),
        );
        assert!(result.is_err());
    }

    #[test]
    fn parse_handles_whitespace_variants_in_expressions() {
        let test_cases = vec![
            ("spec test\nrule test: 2+3", "no spaces in arithmetic"),
            ("spec test\nrule test: age>=18", "no spaces in comparison"),
            (
                "spec test\nrule test: age >= 18 and salary>50000",
                "spaces around and keyword",
            ),
            (
                "spec test\nrule test: age  >=  18  and  salary  >  50000",
                "extra spaces",
            ),
            (
                "spec test\nrule test: \n  age >= 18 \n  and \n  salary > 50000",
                "newlines in expression",
            ),
        ];

        for (input, description) in test_cases {
            let result = parse(
                input,
                crate::parsing::source::SourceType::Volatile,
                &ResourceLimits::default(),
            );
            assert!(
                result.is_ok(),
                "Failed to parse {} ({}): {:?}",
                input,
                description,
                result.err()
            );
        }
    }

    #[test]
    fn parse_error_cases_are_rejected() {
        let error_cases = vec![
            (
                "spec test\ndata name: \"unclosed string",
                "unclosed string literal",
            ),
            ("spec test\nrule test: (2 + 3", "unclosed parenthesis"),
            ("spec test\nrule test: 2 + 3)", "extra closing paren"),
            ("spec test\ndata spec: 123", "reserved keyword as data name"),
            (
                "spec test\nrule rule: true",
                "reserved keyword as rule name",
            ),
        ];

        for (input, description) in error_cases {
            let result = parse(
                input,
                crate::parsing::source::SourceType::Volatile,
                &ResourceLimits::default(),
            );
            assert!(
                result.is_err(),
                "Expected error for {} but got success",
                description
            );
        }
    }

    #[test]
    fn parse_duration_literals_in_rules() {
        let test_cases = vec![
            ("2 years", "years"),
            ("6 months", "months"),
            ("52 weeks", "weeks"),
            ("365 days", "days"),
            ("24 hours", "hours"),
            ("60 minutes", "minutes"),
            ("3600 seconds", "seconds"),
            ("1000 milliseconds", "milliseconds"),
            ("500000 microseconds", "microseconds"),
            ("50 percent", "percent"),
        ];

        for (expr, description) in test_cases {
            let input = format!("spec test\nrule test: {}", expr);
            let result = parse(
                &input,
                crate::parsing::source::SourceType::Volatile,
                &ResourceLimits::default(),
            );
            assert!(
                result.is_ok(),
                "Failed to parse literal {} ({}): {:?}",
                expr,
                description,
                result.err()
            );
        }
    }

    #[test]
    fn parse_comparisons_with_duration_unit_conversions() {
        let test_cases = vec![
            (
                "(duration as hours) > 2",
                "duration conversion in comparison with parens",
            ),
            (
                "(meeting_time as minutes) >= 30",
                "duration conversion with gte",
            ),
            (
                "(project_length as days) < 100",
                "duration conversion with lt",
            ),
            (
                "(delay as seconds) is 60",
                "duration conversion with equality",
            ),
            (
                "(1 hours) > (30 minutes)",
                "duration conversions on both sides",
            ),
            (
                "duration as hours > 2",
                "duration conversion without parens",
            ),
            (
                "meeting_time as seconds > 3600",
                "variable duration conversion in comparison",
            ),
            (
                "project_length as days > deadline_days",
                "two variables with duration conversion",
            ),
            (
                "duration as hours >= 1 and duration as hours <= 8",
                "multiple duration comparisons",
            ),
            (
                "(2024-06-01...2024-06-15) as days as number >= 7",
                "chained as conversion before comparison",
            ),
            ("duration as hours as number > 2", "chained as on duration"),
        ];

        for (expr, description) in test_cases {
            let input = format!("spec test\nrule test: {}", expr);
            let result = parse(
                &input,
                crate::parsing::source::SourceType::Volatile,
                &ResourceLimits::default(),
            );
            assert!(
                result.is_ok(),
                "Failed to parse {} ({}): {:?}",
                expr,
                description,
                result.err()
            );
        }
    }

    #[test]
    fn parse_rejects_token_after_unit_conversion() {
        let result = parse(
            "spec test\nuses lemma si\nrule ok: (2024-06-01...2024-06-15) as days foo",
            crate::parsing::source::SourceType::Volatile,
            &ResourceLimits::default(),
        );
        let err = result.expect_err("expected parse error");
        let msg = err.to_string();
        assert!(
            msg.contains("Unexpected token") && msg.contains("foo"),
            "expected error at 'foo', got: {}",
            msg
        );
        assert!(
            !msg.contains("Expected 'data'"),
            "should not defer to spec-level error, got: {}",
            msg
        );
    }

    #[test]
    fn parse_unit_conversion_before_next_spec() {
        let result = parse(
            r#"spec pricing
rule hourly_rate: 150 eur
  unless loyalty is "silver" then 140 eur
  unless loyalty is "gold" then 125 usd as eur

spec other
rule x: 1"#,
            crate::parsing::source::SourceType::Volatile,
            &ResourceLimits::default(),
        );
        assert!(
            result.is_ok(),
            "unless branch ending with 'as' must parse before next spec: {:?}",
            result.err()
        );
    }

    #[test]
    fn parse_unit_conversion_before_sibling_rule() {
        let result = parse(
            r#"spec s
rule a: 100 usd as eur
rule b: 1"#,
            crate::parsing::source::SourceType::Volatile,
            &ResourceLimits::default(),
        );
        assert!(
            result.is_ok(),
            "rule ending with 'as' must parse before sibling rule: {:?}",
            result.err()
        );
    }

    #[test]
    fn parse_unit_conversion_before_uses() {
        let result = parse(
            r#"spec s
rule rate: 10 usd as eur
uses lemma si
rule hours: 1 hour"#,
            crate::parsing::source::SourceType::Volatile,
            &ResourceLimits::default(),
        );
        assert!(
            result.is_ok(),
            "rule ending with 'as' must parse before uses: {:?}",
            result.err()
        );
    }

    /// Every token that may follow a completed rule / unless expression ending in `as`.
    #[test]
    fn parse_unit_conversion_before_expression_boundaries() {
        let cases: &[(&str, &str)] = &[
            (
                "sibling data",
                r#"spec s
rule rate: 10 usd as eur
data price: 100 eur"#,
            ),
            (
                "sibling fill",
                r#"spec s
rule rate: 10 usd as eur
fill price: rate"#,
            ),
            (
                "sibling meta",
                r#"spec s
rule rate: 10 usd as eur
meta version: 1"#,
            ),
            (
                "another unless",
                r#"spec s
rule rate: 10 usd
  unless active then 5 usd as eur
  unless premium then 3 usd as eur"#,
            ),
            (
                "eof",
                r#"spec s
rule rate: 10 usd as eur"#,
            ),
            (
                "next repo",
                r#"spec s
rule rate: 10 usd as eur

repo other
spec t
rule x: 1"#,
            ),
            (
                "unless then before next unless",
                r#"spec s
rule rate: 10 usd
  unless a then 1 usd as eur
  unless b then 2"#,
            ),
            (
                "chained as before sibling rule",
                r#"spec s
rule rate: (2024-01-01...2024-01-02) as days as number
rule other: 1"#,
            ),
        ];

        for (label, source) in cases {
            let result = parse(
                source,
                crate::parsing::source::SourceType::Volatile,
                &ResourceLimits::default(),
            );
            assert!(
                result.is_ok(),
                "unit conversion before {label} must parse: {:?}",
                result.err()
            );
        }
    }

    #[test]
    fn parse_rejects_plain_number_plus_converted_operand() {
        let result = parse(
            r#"spec test
data c: quantity
  -> unit eur 1
  -> unit usd 0.84
rule z: 5 + c as usd"#,
            crate::parsing::source::SourceType::Volatile,
            &ResourceLimits::default(),
        );
        let err = result.expect_err("expected parse error for 5 + c as usd");
        let msg = err.to_string();
        assert!(
            msg.contains("plain number") || msg.contains("each operand"),
            "expected conversion-before-+ error, got: {msg}"
        );
    }

    #[test]
    fn parse_accepts_conversion_on_each_additive_operand() {
        let cases: &[(&str, &str)] = &[
            (
                "money",
                r#"spec test
data c: quantity
  -> unit eur 1
  -> unit usd 0.84
rule z: 5 as usd + c as usd"#,
            ),
            (
                "duration + literal",
                r#"spec test
uses lemma si
rule z: duration as hours + 1"#,
            ),
            (
                "duration + comparison",
                r#"spec test
uses lemma si
data duration: si.duration
  -> default 1 hour
rule z: duration as hours + 1 > 0"#,
            ),
            (
                "date range + ref",
                r#"spec test
uses lemma si
data age: date range
data c: quantity
  -> unit eur 1
rule z: age as days + c"#,
            ),
        ];
        for (label, source) in cases {
            let result = parse(
                source,
                crate::parsing::source::SourceType::Volatile,
                &ResourceLimits::default(),
            );
            assert!(
                result.is_ok(),
                "expected {label} to parse, got: {:?}",
                result.err()
            );
        }
    }

    fn rule_expression(source: &str, rule_name: &str) -> Expression {
        let parsed = parse(
            source,
            crate::parsing::source::SourceType::Volatile,
            &ResourceLimits::default(),
        )
        .expect("expected parse");
        let spec = parsed
            .flatten_specs()
            .into_iter()
            .next()
            .expect("expected one spec");
        spec.rules
            .iter()
            .find(|rule| rule.name == rule_name)
            .unwrap_or_else(|| panic!("rule '{rule_name}' not found"))
            .expression
            .clone()
    }

    fn assert_multiply_range_side(expression: &Expression, range_on_left: bool, label: &str) {
        let ExpressionKind::Arithmetic(left, ArithmeticComputation::Multiply, right) =
            &expression.kind
        else {
            panic!("{label}: expected Multiply, got {:?}", expression.kind);
        };
        let (range, other) = if range_on_left {
            (left.as_ref(), right.as_ref())
        } else {
            (right.as_ref(), left.as_ref())
        };
        assert!(
            matches!(range.kind, ExpressionKind::RangeLiteral(..)),
            "{label}: expected RangeLiteral on {} of *, got {:?}",
            if range_on_left { "left" } else { "right" },
            range.kind
        );
        assert!(
            !matches!(other.kind, ExpressionKind::RangeLiteral(..)),
            "{label}: expected non-range on other side of *"
        );
    }

    #[test]
    fn parse_range_binds_tighter_than_multiply() {
        let base = r#"spec test
uses lemma si
data rate: quantity -> unit eur 1
data period_start: 2026-01-01
data period_end: 2026-01-02
"#;
        assert_multiply_range_side(
            &rule_expression(
                &format!("{base}rule rhs: rate * period_start...period_end"),
                "rhs",
            ),
            false,
            "rate * period_start...period_end",
        );
        assert_multiply_range_side(
            &rule_expression(
                &format!("{base}rule lhs: period_start...period_end * rate"),
                "lhs",
            ),
            true,
            "period_start...period_end * rate",
        );
    }

    #[test]
    fn parse_range_in_additive_term_before_plus() {
        let expression = rule_expression(
            r#"spec test
uses lemma si
data period_start: 2026-01-01
data period_end: 2026-01-02
rule span: period_start...period_end + 1 day"#,
            "span",
        );
        let ExpressionKind::Arithmetic(left, ArithmeticComputation::Add, right) = &expression.kind
        else {
            panic!("expected Add, got {:?}", expression.kind);
        };
        assert!(matches!(left.kind, ExpressionKind::RangeLiteral(..)));
        assert!(!matches!(right.kind, ExpressionKind::RangeLiteral(..)));
    }

    #[test]
    fn parse_range_multiply_with_conversion_without_inner_parens() {
        let expression = rule_expression(
            r#"spec test
uses lemma si
data money: quantity -> unit eur 1
data rate: quantity -> unit eur_per_hour eur/hour
data hourly_rate: 50 eur_per_hour
data period_start: 2026-01-01
data period_end: 2026-01-02
rule pay: (hourly_rate * period_start...period_end) as eur"#,
            "pay",
        );
        let ExpressionKind::UnitConversion(inner, _) = &expression.kind else {
            panic!("expected UnitConversion, got {:?}", expression.kind);
        };
        assert_multiply_range_side(inner, false, "pay");
    }

    #[test]
    fn parse_error_includes_attribute_and_parse_error_spec_name() {
        let result = parse(
            r#"
spec test
data name: "Unclosed string
data age: 25
"#,
            crate::parsing::source::SourceType::Volatile,
            &ResourceLimits::default(),
        );

        match result {
            Err(Error::Parsing(details)) => {
                let src = details
                    .source
                    .as_ref()
                    .expect("BUG: parsing errors always have source");
                assert_eq!(
                    src.source_type,
                    crate::parsing::source::SourceType::Volatile
                );
            }
            Err(e) => panic!("Expected Parse error, got: {e:?}"),
            Ok(_) => panic!("Expected parse error for unclosed string"),
        }
    }

    #[test]
    fn parse_single_spec_file() {
        let input = r#"spec somespec
data name: "Alice""#;
        let parsed = parse(
            input,
            crate::parsing::source::SourceType::Volatile,
            &ResourceLimits::default(),
        )
        .unwrap();
        let specs = parsed.flatten_specs();
        assert_eq!(specs.len(), 1);
        assert_eq!(specs[0].name, "somespec");
    }

    #[test]
    fn parse_uses_registry_spec_explicit_alias() {
        let input = r#"spec example
uses external: @user/workspace somespec"#;
        let specs = parse(
            input,
            crate::parsing::source::SourceType::Volatile,
            &ResourceLimits::default(),
        )
        .unwrap()
        .into_flattened_specs();
        assert_eq!(specs.len(), 1);
        assert_eq!(specs[0].data.len(), 1);
        match &specs[0].data[0].value {
            crate::parsing::ast::DataValue::Import(spec_ref) => {
                assert_eq!(spec_ref.name, "somespec");
                let repository_hdr = spec_ref
                    .repository
                    .as_ref()
                    .expect("expected repository qualifier");
                assert_eq!(repository_hdr.name, "@user/workspace");
            }
            other => panic!("Expected Import, got: {:?}", other),
        }
    }

    #[test]
    fn parse_multiple_specs_cross_reference_in_file() {
        let input = r#"spec spec_a
data x: 10

spec spec_b
data y: 20
uses a: spec_a"#;
        let parsed = parse(
            input,
            crate::parsing::source::SourceType::Volatile,
            &ResourceLimits::default(),
        )
        .unwrap();
        let specs = parsed.flatten_specs();
        assert_eq!(specs.len(), 2);
        assert_eq!(specs[0].name, "spec_a");
        assert_eq!(specs[1].name, "spec_b");
    }

    #[test]
    fn parse_uses_registry_spec_default_alias() {
        let input = "spec example\nuses @owner/repo somespec";
        let specs = parse(
            input,
            crate::parsing::source::SourceType::Volatile,
            &ResourceLimits::default(),
        )
        .unwrap()
        .into_flattened_specs();
        match &specs[0].data[0].value {
            crate::parsing::ast::DataValue::Import(spec_ref) => {
                assert_eq!(spec_ref.name, "somespec");
                let repository_hdr = spec_ref
                    .repository
                    .as_ref()
                    .expect("expected repository qualifier");
                assert_eq!(repository_hdr.name, "@owner/repo");
            }
            other => panic!("Expected Import, got: {:?}", other),
        }
    }

    #[test]
    fn parse_uses_local_spec_default_alias() {
        let input = "spec example\nuses myspec";
        let specs = parse(
            input,
            crate::parsing::source::SourceType::Volatile,
            &ResourceLimits::default(),
        )
        .unwrap()
        .into_flattened_specs();
        match &specs[0].data[0].value {
            crate::parsing::ast::DataValue::Import(spec_ref) => {
                assert_eq!(spec_ref.name, "myspec");
                assert!(
                    spec_ref.repository.is_none(),
                    "same-repository reference must omit repository qualifier"
                );
            }
            other => panic!("Expected Import, got: {:?}", other),
        }
    }

    #[test]
    fn parse_spec_name_with_trailing_dot_is_error() {
        let input = "spec myspec.\ndata x: 1";
        let result = parse(
            input,
            crate::parsing::source::SourceType::Volatile,
            &ResourceLimits::default(),
        );
        assert!(
            result.is_err(),
            "Trailing dot after spec name should be a parse error"
        );
    }

    #[test]
    fn parse_multiple_specs_in_same_file() {
        let input = "spec myspec_a\nrule x: 1\n\nspec myspec_b\nrule x: 2";
        let result = parse(
            input,
            crate::parsing::source::SourceType::Volatile,
            &ResourceLimits::default(),
        )
        .unwrap()
        .into_flattened_specs();
        assert_eq!(result.len(), 2);
        assert_eq!(result[0].name, "myspec_a");
        assert_eq!(result[1].name, "myspec_b");
    }

    #[test]
    fn parse_uses_accepts_name_only() {
        let input = "spec consumer\nuses other";
        let result = parse(
            input,
            crate::parsing::source::SourceType::Volatile,
            &ResourceLimits::default(),
        );
        assert!(result.is_ok(), "uses name should parse");
        let specs = result.unwrap().into_flattened_specs();
        let spec_ref = match &specs[0].data[0].value {
            crate::parsing::ast::DataValue::Import(r) => r,
            _ => panic!("expected Import"),
        };
        assert_eq!(spec_ref.name, "other");
    }

    #[test]
    fn parse_uses_bare_year_effective() {
        let input = "spec consumer\nuses other 2026";
        let result = parse(
            input,
            crate::parsing::source::SourceType::Volatile,
            &ResourceLimits::default(),
        )
        .unwrap();
        let specs = result.into_flattened_specs();
        let spec_ref = match &specs[0].data[0].value {
            crate::parsing::ast::DataValue::Import(r) => r,
            _ => panic!("expected Import"),
        };
        assert_eq!(spec_ref.name, "other");
        let eff = spec_ref.effective.as_ref().expect("effective");
        assert_eq!(eff.year, 2026);
        assert_eq!(eff.month, 1);
        assert_eq!(eff.day, 1);
    }

    #[test]
    fn parse_uses_comma_separated_bare() {
        let input = "spec consumer\nuses a, b, c";
        let result = parse(
            input,
            crate::parsing::source::SourceType::Volatile,
            &ResourceLimits::default(),
        )
        .unwrap();
        let data = &result.flatten_specs()[0].data;
        assert_eq!(data.len(), 3);
        for (i, expected) in ["a", "b", "c"].iter().enumerate() {
            let sr = match &data[i].value {
                crate::parsing::ast::DataValue::Import(r) => r,
                _ => panic!("expected Import for item {i}"),
            };
            assert_eq!(sr.name, *expected);
            assert_eq!(data[i].reference.name, *expected);
            assert!(sr.effective.is_none());
        }
    }

    #[test]
    fn parse_uses_comma_separated_cross_repository() {
        let input = "spec consumer\nuses pricing retail, pricing wholesale";
        let result = parse(
            input,
            crate::parsing::source::SourceType::Volatile,
            &ResourceLimits::default(),
        )
        .unwrap();
        let data = &result.flatten_specs()[0].data;
        assert_eq!(data.len(), 2);
        let sr0 = match &data[0].value {
            crate::parsing::ast::DataValue::Import(r) => r,
            _ => panic!("expected Import"),
        };
        assert_eq!(sr0.name, "retail");
        let repository_hdr0 = sr0
            .repository
            .as_ref()
            .expect("expected repository qualifier");
        assert_eq!(repository_hdr0.name, "pricing");
        assert_eq!(data[0].reference.name, "retail");
        let sr1 = match &data[1].value {
            crate::parsing::ast::DataValue::Import(r) => r,
            _ => panic!("expected Import"),
        };
        assert_eq!(sr1.name, "wholesale");
        let repository_hdr1 = sr1
            .repository
            .as_ref()
            .expect("expected repository qualifier");
        assert_eq!(repository_hdr1.name, "pricing");
        assert_eq!(data[1].reference.name, "wholesale");
    }

    #[test]
    fn parse_uses_comma_separated_registry() {
        let input = "spec consumer\nuses @org/repo spec_a, @org/repo spec_b";
        let result = parse(
            input,
            crate::parsing::source::SourceType::Volatile,
            &ResourceLimits::default(),
        )
        .unwrap();
        let data = &result.flatten_specs()[0].data;
        assert_eq!(data.len(), 2);
        assert_eq!(data[0].reference.name, "spec_a");
        assert_eq!(data[1].reference.name, "spec_b");
        for sr in [&data[0].value, &data[1].value] {
            let r = match sr {
                crate::parsing::ast::DataValue::Import(r) => r,
                _ => panic!("expected Import"),
            };
            let repository_hdr = r
                .repository
                .as_ref()
                .expect("expected repository qualifier");
            assert_eq!(repository_hdr.name, "@org/repo");
        }
    }

    #[test]
    fn parse_uses_registry_spec_ref_records_repository_and_target_spans() {
        let input = "spec consumer\nuses @lemma/std finance 2026";
        let result = parse(
            input,
            crate::parsing::source::SourceType::Volatile,
            &ResourceLimits::default(),
        )
        .unwrap();
        let spec = &result.flatten_specs()[0];
        let sr = match &spec.data[0].value {
            crate::parsing::ast::DataValue::Import(r) => r,
            _ => panic!("expected Import"),
        };
        let rs = sr
            .repository_span
            .as_ref()
            .expect("repository_span should be set for @-qualified uses");
        let ts = sr
            .target_span
            .as_ref()
            .expect("target_span should cover spec name and effective");
        assert_eq!(&input[rs.start..rs.end], "@lemma/std");
        assert_eq!(&input[ts.start..ts.end], "finance 2026");
    }

    #[test]
    fn parse_uses_alias_no_comma_continuation() {
        let input = "spec consumer\nuses alias: pricing retail\ndata x: 1";
        let result = parse(
            input,
            crate::parsing::source::SourceType::Volatile,
            &ResourceLimits::default(),
        )
        .unwrap();
        let data = &result.flatten_specs()[0].data;
        assert_eq!(data.len(), 2);
        assert_eq!(data[0].reference.name, "alias");
        let sr = match &data[0].value {
            crate::parsing::ast::DataValue::Import(r) => r,
            _ => panic!("expected Import"),
        };
        assert_eq!(sr.name, "retail");
        let repository_hdr = sr
            .repository
            .as_ref()
            .expect("expected repository qualifier");
        assert_eq!(repository_hdr.name, "pricing");
    }

    #[test]
    fn parse_data_qualified_type_with_effective_and_repository_on_uses() {
        let input = "spec consumer\nuses @lemma/std finance 2026-06-01\ndata price: finance.number -> minimum 0";
        let result = parse(
            input,
            crate::parsing::source::SourceType::Volatile,
            &ResourceLimits::default(),
        )
        .unwrap()
        .into_flattened_specs();
        let spec_ref = match &result[0].data[0].value {
            crate::parsing::ast::DataValue::Import(sr) => sr,
            other => panic!("expected Import on uses row, got: {:?}", other),
        };
        assert_eq!(spec_ref.name, "finance");

        let eff = spec_ref
            .effective
            .as_ref()
            .expect("expected effective datetime");
        assert_eq!(eff.year, 2026);
        assert_eq!(eff.month, 6);

        let qualifier = spec_ref
            .repository
            .as_ref()
            .expect("expected repository qualifier");
        assert_eq!(qualifier.name, "@lemma/std");

        match &result[0].data[1].value {
            crate::parsing::ast::DataValue::Definition {
                base,
                constraints,
                value,
            } => {
                assert!(value.is_none());
                assert_eq!(
                    base.as_ref().expect("expected base"),
                    &crate::parsing::ast::ParentType::Qualified {
                        spec_alias: "finance".into(),
                        inner: Box::new(crate::parsing::ast::ParentType::Primitive {
                            primitive: crate::parsing::ast::PrimitiveKind::Number,
                        }),
                    }
                );

                let cs = constraints
                    .as_ref()
                    .expect("expected trailing constraint chain");
                assert_eq!(cs.len(), 1);
            }
            other => panic!("expected Definition, got: {:?}", other),
        }
    }

    #[test]
    fn parse_error_is_returned_for_garbage_input() {
        let result = parse(
            r#"
spec test
this is not valid lemma syntax @#$%
"#,
            crate::parsing::source::SourceType::Volatile,
            &ResourceLimits::default(),
        );

        assert!(result.is_err(), "Should fail on malformed input");
        match result {
            Err(Error::Parsing { .. }) => {
                // Expected
            }
            Err(e) => panic!("Expected Parse error, got: {e:?}"),
            Ok(_) => panic!("Expected parse error"),
        }
    }

    // ─── Parser-level pins for DataValue variants ────────────────────

    /// `fill x: a.b` (local LHS, dotted RHS) must be parsed as [`DataValue::Fill`] with a reference payload.
    #[test]
    fn parse_fill_with_dotted_rhs_is_fill_reference() {
        let input = r#"spec s
data a: number -> default 1
fill x: a.something"#;
        let result = parse(
            input,
            crate::parsing::source::SourceType::Volatile,
            &ResourceLimits::default(),
        )
        .unwrap()
        .into_flattened_specs();
        let x_value = &result[0]
            .data
            .iter()
            .find(|d| d.reference.name == "x")
            .expect("fill x not found")
            .value;
        assert!(
            matches!(
                x_value,
                crate::parsing::ast::DataValue::Fill(
                    crate::parsing::ast::FillRhs::Reference { .. }
                )
            ),
            "dotted RHS must yield DataValue::Fill(Reference), got: {:?}",
            x_value
        );
    }

    /// `fill x: a.b.c.d` (3+ segment RHS) must parse and preserve segments.
    #[test]
    fn parse_fill_with_multi_segment_reference_rhs() {
        let input = r#"spec s
fill x: alpha.beta.gamma.delta"#;
        let result = parse(
            input,
            crate::parsing::source::SourceType::Volatile,
            &ResourceLimits::default(),
        )
        .unwrap()
        .into_flattened_specs();
        let value = &result[0].data[0].value;
        match value {
            crate::parsing::ast::DataValue::Fill(crate::parsing::ast::FillRhs::Reference {
                target,
                ..
            }) => {
                assert_eq!(target.segments, vec!["alpha", "beta", "gamma"]);
                assert_eq!(target.name, "delta");
            }
            other => panic!("expected Fill(Reference), got: {:?}", other),
        }
    }

    /// `fill x: a.b -> minimum 5` is rejected; constraint chains belong on `data`.
    #[test]
    fn parse_fill_reference_with_trailing_constraint_is_rejected() {
        let input = r#"spec s
fill x: foo.bar -> minimum 5"#;
        let err = parse(
            input,
            crate::parsing::source::SourceType::Volatile,
            &ResourceLimits::default(),
        )
        .unwrap_err();
        let msg = err.to_string();
        assert!(
            msg.contains("fill") && msg.contains("data"),
            "expected fill-vs-data constraint error, got: {msg}"
        );
    }

    /// `data x: notdotted` (local LHS, non-dotted RHS) MUST stay a
    /// Definition with an explicit custom parent — not silently reinterpreted as a Reference.
    #[test]
    fn parse_local_non_dotted_rhs_stays_definition_with_custom_base() {
        let input = r#"spec s
data x: myothertype"#;
        let result = parse(
            input,
            crate::parsing::source::SourceType::Volatile,
            &ResourceLimits::default(),
        )
        .unwrap()
        .into_flattened_specs();
        let value = &result[0].data[0].value;
        assert!(
            matches!(
                value,
                crate::parsing::ast::DataValue::Definition {
                    base: Some(crate::parsing::ast::ParentType::Custom { .. }),
                    ..
                }
            ),
            "non-dotted local RHS must stay Definition with custom base, got: {:?}",
            value
        );
    }

    /// `fill x.y: notdotted` (binding LHS, non-dotted RHS) is parsed as [`DataValue::Fill`] with a reference payload.
    #[test]
    fn parse_binding_non_dotted_rhs_is_fill_reference() {
        let input = r#"spec s
fill child.slot: somename"#;
        let result = parse(
            input,
            crate::parsing::source::SourceType::Volatile,
            &ResourceLimits::default(),
        )
        .unwrap()
        .into_flattened_specs();
        let value = &result[0].data[0].value;
        assert!(
            matches!(
                value,
                crate::parsing::ast::DataValue::Fill(
                    crate::parsing::ast::FillRhs::Reference { .. }
                )
            ),
            "non-dotted RHS in binding context must yield Fill(Reference); got: {:?}",
            value
        );
    }

    /// `data x: spec …` is invalid; spec imports use `uses`.
    #[test]
    fn parse_data_colon_spec_rhs_is_rejected() {
        let result = parse(
            r#"
spec s
data x: spec other
"#,
            crate::parsing::source::SourceType::Volatile,
            &ResourceLimits::default(),
        );
        match result {
            Ok(_) => panic!("`data x: spec other` must fail to parse"),
            Err(err) => {
                let msg = err.to_string();
                assert!(
                    msg.contains("uses") && msg.contains("spec"),
                    "error must direct to `uses` for spec import, got: {msg}"
                );
            }
        }
    }

    /// `fill x.y: z.w` (binding LHS, dotted RHS) → Reference with two LHS
    /// segments and two RHS segments.
    #[test]
    fn parse_binding_with_dotted_rhs_preserves_both_sides() {
        let input = r#"spec s
fill outer.inner: target.field"#;
        let result = parse(
            input,
            crate::parsing::source::SourceType::Volatile,
            &ResourceLimits::default(),
        )
        .unwrap()
        .into_flattened_specs();
        let datum = &result[0].data[0];
        assert_eq!(datum.reference.segments, vec!["outer"]);
        assert_eq!(datum.reference.name, "inner");
        match &datum.value {
            crate::parsing::ast::DataValue::Fill(crate::parsing::ast::FillRhs::Reference {
                target,
            }) => {
                assert_eq!(target.segments, vec!["target"]);
                assert_eq!(target.name, "field");
            }
            other => panic!("expected Fill(Reference), got: {:?}", other),
        }
    }

    #[test]
    fn parse_data_on_binding_path_is_rejected_with_fill_hint() {
        let result = parse(
            r#"spec s
data outer.inner: 1"#,
            crate::parsing::source::SourceType::Volatile,
            &ResourceLimits::default(),
        );
        match result {
            Ok(_) => panic!("data with binding path must not parse"),
            Err(err) => {
                let msg = err.to_string();
                assert!(
                    msg.contains("fill"),
                    "error should steer authors toward fill; got: {msg}"
                );
            }
        }
    }

    #[test]
    fn parse_bare_file_yields_single_anonymous_repository_group() {
        let input = "spec a\ndata x: 1\nspec b\ndata y: 2";
        let parsed = parse(
            input,
            crate::parsing::source::SourceType::Volatile,
            &ResourceLimits::default(),
        )
        .unwrap();
        assert_eq!(parsed.repositories.len(), 1);
        let (repo, specs) = parsed.repositories.iter().next().unwrap();
        assert!(repo.name.is_none());
        assert_eq!(specs.len(), 2);
        assert_eq!(specs[0].name, "a");
        assert_eq!(specs[1].name, "b");
    }

    #[test]
    fn parse_repo_sections_preserve_order_and_names() {
        let input = r#"repo r1

spec a
data x: 1

repo r2

spec b
data y: 2"#;
        let parsed = parse(
            input,
            crate::parsing::source::SourceType::Volatile,
            &ResourceLimits::default(),
        )
        .unwrap();
        assert_eq!(parsed.repositories.len(), 2);
        let keys: Vec<_> = parsed.repositories.keys().collect();
        assert_eq!(keys[0].name.as_deref(), Some("r1"));
        assert_eq!(keys[1].name.as_deref(), Some("r2"));
    }

    #[test]
    fn parse_duplicate_repo_name_merges_spec_lists() {
        let input = r#"repo dup

spec a
data x: 1

repo dup

spec b
data y: 2"#;
        let parsed = parse(
            input,
            crate::parsing::source::SourceType::Volatile,
            &ResourceLimits::default(),
        )
        .unwrap();
        assert_eq!(parsed.repositories.len(), 1);
        assert_eq!(parsed.flatten_specs().len(), 2);
    }

    #[test]
    fn parse_repo_with_no_specs_then_eof_yields_empty_spec_vec_for_that_repo() {
        let input = "repo empty";
        let parsed = parse(
            input,
            crate::parsing::source::SourceType::Volatile,
            &ResourceLimits::default(),
        )
        .unwrap();
        assert_eq!(parsed.repositories.len(), 1);
        let (_repo, specs) = parsed.repositories.iter().next().unwrap();
        assert_eq!(specs.len(), 0);
    }

    #[test]
    fn parse_repo_followed_by_repo_without_specs_first_repo_empty_second_has_spec() {
        let input = "repo a\n\nrepo b\n\nspec s\ndata x: 1";
        let parsed = parse(
            input,
            crate::parsing::source::SourceType::Volatile,
            &ResourceLimits::default(),
        )
        .unwrap();
        assert_eq!(parsed.repositories.len(), 2);
        let names: Vec<_> = parsed
            .repositories
            .keys()
            .map(|r| r.name.as_deref())
            .collect();
        assert_eq!(names, vec![Some("a"), Some("b")]);
        assert!(parsed.repositories.values().next().unwrap().is_empty());
        assert_eq!(parsed.repositories.values().nth(1).unwrap().len(), 1);
    }

    #[test]
    fn parse_spec_named_repo_keyword_should_be_rejected() {
        assert!(
            parse(
                "spec repo\ndata x: 1",
                crate::parsing::source::SourceType::Volatile,
                &ResourceLimits::default(),
            )
            .is_err(),
            "spec must not be allowed to use reserved keyword `repo` as its name"
        );
    }

    #[test]
    fn parse_repo_declaration_cannot_use_spec_keyword_as_repository_name() {
        assert!(
            parse(
                "repo spec\n\nspec z\ndata q: 1\nrule r: q",
                crate::parsing::source::SourceType::Volatile,
                &ResourceLimits::default(),
            )
            .is_err(),
            "repository name cannot be the token `spec`"
        );
    }

    #[test]
    fn parse_repo_declaration_cannot_use_data_keyword_as_repository_name() {
        assert!(
            parse(
                "repo data\n\nspec z\ndata q: 1\nrule r: q",
                crate::parsing::source::SourceType::Volatile,
                &ResourceLimits::default(),
            )
            .is_err(),
            "repository name cannot be the token `data`"
        );
    }

    #[test]
    fn parse_repo_declaration_cannot_use_rule_keyword_as_repository_name() {
        assert!(
            parse(
                "repo rule\n\nspec z\ndata q: 1\nrule r: q",
                crate::parsing::source::SourceType::Volatile,
                &ResourceLimits::default(),
            )
            .is_err(),
            "repository name cannot be the token `rule`"
        );
    }

    #[test]
    fn parse_data_named_repo_keyword_is_rejected() {
        let err = parse(
            "spec s\ndata repo: 1",
            crate::parsing::source::SourceType::Volatile,
            &ResourceLimits::default(),
        )
        .unwrap_err();
        assert!(
            err.to_string().contains("repo"),
            "data named repo should not parse: {}",
            err
        );
    }

    #[test]
    fn parse_rule_named_repo_keyword_is_rejected() {
        let err = parse(
            "spec s\ndata x: 1\nrule repo: x",
            crate::parsing::source::SourceType::Volatile,
            &ResourceLimits::default(),
        )
        .unwrap_err();
        let msg = err.to_string();
        assert!(
            msg.contains("repo") || msg.contains("reserved"),
            "rule named repo should not parse: {msg}"
        );
    }

    #[test]
    fn parse_repo_declaration_accepts_non_keyword_repository_identifier() {
        let parsed = parse(
            "repo warehouse\n\nspec z\ndata q: 1\nrule r: q",
            crate::parsing::source::SourceType::Volatile,
            &ResourceLimits::default(),
        )
        .unwrap();
        assert_eq!(parsed.repositories.len(), 1);
        assert_eq!(
            parsed.repositories.keys().next().unwrap().name.as_deref(),
            Some("warehouse")
        );
    }

    #[test]
    fn parse_repo_name_case_distinctness_two_repositories_not_merged() {
        let input = "repo Foo\n\nspec a\ndata x: 1\n\nrepo foo\n\nspec b\ndata y: 2";
        let parsed = parse(
            input,
            crate::parsing::source::SourceType::Volatile,
            &ResourceLimits::default(),
        )
        .unwrap();
        assert_eq!(
            parsed.repositories.len(),
            2,
            "Foo and foo must be distinct repository identities"
        );
    }

    #[test]
    fn parse_repo_empty_name_errors() {
        let err = parse(
            "repo \nspec a\ndata x: 1",
            crate::parsing::source::SourceType::Volatile,
            &ResourceLimits::default(),
        )
        .unwrap_err();
        assert!(
            !err.to_string().is_empty(),
            "empty repo name should not parse quietly: {err}"
        );
    }

    #[test]
    fn parse_repo_numeric_name_behavior() {
        let input = "repo 123\n\nspec a\ndata x: 1";
        let result = parse(
            input,
            crate::parsing::source::SourceType::Volatile,
            &ResourceLimits::default(),
        );
        match result {
            Ok(parsed) => {
                assert_eq!(
                    parsed.repositories.keys().next().unwrap().name.as_deref(),
                    Some("123"),
                    "if numeric repo names parse, identity must be stable"
                );
            }
            Err(e) => {
                assert!(
                    !e.to_string().is_empty(),
                    "rejecting numeric repo name is ok if explicit: {e}"
                );
            }
        }
    }

    #[test]
    fn parse_duplicate_repo_three_sections_preserves_spec_order_abc() {
        let input = r#"repo dup

spec a
data x: 1

repo dup

spec b
data y: 2

repo dup

spec c
data z: 3"#;
        let parsed = parse(
            input,
            crate::parsing::source::SourceType::Volatile,
            &ResourceLimits::default(),
        )
        .unwrap();
        assert_eq!(parsed.repositories.len(), 1);
        let specs = parsed.repositories.values().next().unwrap();
        assert_eq!(
            specs.iter().map(|s| s.name.as_str()).collect::<Vec<_>>(),
            vec!["a", "b", "c"]
        );
    }

    #[test]
    fn parse_repo_single_section_roundtrips_through_formatter() {
        let input = "repo r\n\nspec a\ndata x: 1";
        let parsed = parse(
            input,
            crate::parsing::source::SourceType::Volatile,
            &ResourceLimits::default(),
        )
        .unwrap();
        let formatted = format_parse_result(&parsed);
        let again = parse(
            &formatted,
            crate::parsing::source::SourceType::Volatile,
            &ResourceLimits::default(),
        )
        .unwrap();
        assert_eq!(again.repositories.len(), parsed.repositories.len());
        assert_eq!(again.flatten_specs().len(), parsed.flatten_specs().len());
        assert_eq!(
            again.flatten_specs()[0].name,
            parsed.flatten_specs()[0].name
        );
    }

    #[test]
    fn parse_repo_two_sections_roundtrips_through_formatter() {
        let input = "repo r1\n\nspec a\ndata x: 1\n\nrepo r2\n\nspec b\ndata y: 2";
        let parsed = parse(
            input,
            crate::parsing::source::SourceType::Volatile,
            &ResourceLimits::default(),
        )
        .unwrap();
        let formatted = format_parse_result(&parsed);
        let again = parse(
            &formatted,
            crate::parsing::source::SourceType::Volatile,
            &ResourceLimits::default(),
        )
        .unwrap();
        assert_eq!(again.repositories.len(), 2);
        assert_eq!(again.flatten_specs().len(), 2);
    }

    #[test]
    fn parse_repo_duplicate_merge_formatter_emits_single_repo_block_or_equivalent_parse() {
        let input = r#"repo dup

spec a
data x: 1

repo dup

spec b
data y: 2"#;
        let parsed = parse(
            input,
            crate::parsing::source::SourceType::Volatile,
            &ResourceLimits::default(),
        )
        .unwrap();
        let formatted = format_parse_result(&parsed);
        let again = parse(
            &formatted,
            crate::parsing::source::SourceType::Volatile,
            &ResourceLimits::default(),
        )
        .unwrap();
        assert_eq!(
            again.repositories.len(),
            1,
            "formatted duplicate-repo file must still merge to one logical repo"
        );
        assert_eq!(again.flatten_specs().len(), 2);
    }
}