zpl_toolchain_core 0.1.5

Core parser, emitter, and validator for ZPL II label code
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
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
//! Validator tests for the ZPL toolchain.
//!
//! Tests validation diagnostics (ZPL1xxx, ZPL2xxx, ZPL3xxx), profile
//! constraints, printer gates, media modes, structural validation,
//! semantic validation, and cross-command constraints.
//!
//! Parser tests (tokenization, command recognition, AST structure) live in
//! `parser.rs`.

mod common;

use common::{extract_codes, find_args, find_diag};
use zpl_toolchain_core::grammar::parser::parse_with_tables;
use zpl_toolchain_core::validate::{self, validate_with_profile};
use zpl_toolchain_diagnostics::{Severity, codes};

// ─── Validator Basics ────────────────────────────────────────────────────────

#[test]
fn validator_ignores_trivia_and_field_data_nodes() {
    let tables = &*common::TABLES;
    let result = parse_with_tables("^XA;comment\n^FO10,10^FDdata^FS^XZ", Some(tables));
    let vr = validate::validate(&result.ast, tables);
    // Should not produce errors from Trivia or FieldData nodes themselves
    let unexpected: Vec<_> = vr
        .issues
        .iter()
        .filter(|d| d.message.contains("Trivia") || d.message.contains("FieldData"))
        .collect();
    assert!(
        unexpected.is_empty(),
        "validator should ignore Trivia/FieldData nodes: {:?}",
        unexpected
    );
}

#[test]
fn validator_diagnostics_have_spans() {
    let tables = &*common::TABLES;
    // Create a label with an out-of-range value to trigger a validator diagnostic
    let result = parse_with_tables("^XA^BY999^XZ", Some(tables));
    let vr = validate::validate(&result.ast, tables);
    // Find any diagnostic with a span
    let with_span: Vec<_> = vr.issues.iter().filter(|d| d.span.is_some()).collect();
    if !vr.issues.is_empty() {
        assert!(
            !with_span.is_empty(),
            "validator diagnostics should include spans: {:?}",
            vr.issues
        );
    }
}

#[test]
fn diag_no_false_positives_valid_label() {
    let tables = &*common::TABLES;
    // A well-formed label should produce NO error-level diagnostics
    let result = parse_with_tables("^XA^CF0,30^FO50,50^FDHello World^FS^XZ", Some(tables));
    let vr = validate::validate(&result.ast, tables);
    let errors: Vec<_> = vr
        .issues
        .iter()
        .filter(|d| matches!(d.severity, Severity::Error))
        .collect();
    assert!(
        errors.is_empty(),
        "well-formed label should have no errors: {:?}",
        errors,
    );
}

// ─── ZPL1101: Arity ─────────────────────────────────────────────────────────

#[test]
fn diag_zpl1101_too_many_args() {
    let tables = &*common::TABLES;
    // ^BY has arity 3; give it 5 args
    let result = parse_with_tables("^XA^BY1,2,10,extra,more^XZ", Some(tables));
    let vr = validate::validate(&result.ast, tables);
    assert!(
        vr.issues.iter().any(|d| d.id == codes::ARITY),
        "should flag too many args: {:?}",
        vr.issues,
    );
}

#[test]
fn diag_zpl1101_correct_arity_passes() {
    let tables = &*common::TABLES;
    // ^BY with exactly 3 args (correct arity) should NOT trigger ZPL1101
    let result = parse_with_tables("^XA^BY2,3.0,10^XZ", Some(tables));
    let vr = validate::validate(&result.ast, tables);
    assert!(
        !vr.issues.iter().any(|d| d.id == codes::ARITY),
        "correct arity should not emit ZPL1101: {:?}",
        vr.issues,
    );
}

// ─── ZPL1103: Invalid Enum ───────────────────────────────────────────────────

#[test]
fn diag_zpl1103_invalid_enum() {
    let tables = &*common::TABLES;
    // ^BC orientation (arg 0) must be N/R/I/B; give it X
    let result = parse_with_tables("^XA^BY2^BCX^FDtest^FS^XZ", Some(tables));
    let vr = validate::validate(&result.ast, tables);
    assert!(
        vr.issues.iter().any(|d| d.id == codes::INVALID_ENUM),
        "should flag invalid enum: {:?}",
        vr.issues,
    );
}

#[test]
fn diag_zpl1103_valid_enum_passes() {
    let tables = &*common::TABLES;
    // ^BC orientation (arg 0) with valid value "N" should NOT trigger ZPL1103
    let result = parse_with_tables("^XA^BY2^BCN,100,Y,N,N^FDtest^FS^XZ", Some(tables));
    let vr = validate::validate(&result.ast, tables);
    assert!(
        !vr.issues.iter().any(|d| d.id == codes::INVALID_ENUM),
        "valid enum should not emit ZPL1103: {:?}",
        vr.issues,
    );
}

// ─── ZPL1104: Empty Field Data ───────────────────────────────────────────────

#[test]
fn diag_zpl1104_empty_field_data() {
    let tables = &*common::TABLES;
    // ^FD with no data and no following FieldData node should trigger ZPL1104.
    // The ^FD/^FV spec has an emptyData constraint: { "kind": "emptyData", "severity": "warn" }.
    let result = parse_with_tables("^XA^FO50,50^FD^FS^XZ", Some(tables));
    let vr = validate::validate(&result.ast, tables);
    assert!(
        vr.issues.iter().any(|d| d.id == codes::EMPTY_FIELD_DATA),
        "empty field data should emit ZPL1104: {:?}",
        vr.issues,
    );
}

#[test]
fn diag_zpl1104_non_empty_field_data_passes() {
    let tables = &*common::TABLES;
    // ^FD with content should NOT trigger ZPL1104
    let result = parse_with_tables("^XA^FO50,50^FDHello^FS^XZ", Some(tables));
    let vr = validate::validate(&result.ast, tables);
    assert!(
        !vr.issues.iter().any(|d| d.id == codes::EMPTY_FIELD_DATA),
        "non-empty field data should not emit ZPL1104: {:?}",
        vr.issues,
    );
}

// ─── ZPL1107/1108/1109: Type Validation ──────────────────────────────────────

#[test]
fn diag_zpl1107_int_type_mismatch() {
    let tables = &*common::TABLES;
    // ^FO x (arg 0) should be int; give it "abc"
    let result = parse_with_tables("^XA^FOabc,200^FDtest^FS^XZ", Some(tables));
    let vr = validate::validate(&result.ast, tables);
    assert!(
        vr.issues.iter().any(|d| d.id == codes::EXPECTED_INTEGER),
        "should flag non-integer: {:?}",
        vr.issues,
    );
}

#[test]
fn diag_zpl1107_valid_integer_passes() {
    let tables = &*common::TABLES;
    // ^FO with valid integer args should NOT trigger ZPL1107
    let result = parse_with_tables("^XA^FO100,200^FDtest^FS^XZ", Some(tables));
    let vr = validate::validate(&result.ast, tables);
    assert!(
        !vr.issues.iter().any(|d| d.id == codes::EXPECTED_INTEGER),
        "valid integer should not emit ZPL1107: {:?}",
        vr.issues,
    );
}

#[test]
fn diag_zpl1108_float_type_mismatch() {
    let tables = &*common::TABLES;
    // ^BY ratio (arg 1) is float with range [2.0, 3.0]; give it "xyz"
    let result = parse_with_tables("^XA^BY2,xyz,10^XZ", Some(tables));
    let vr = validate::validate(&result.ast, tables);
    assert!(
        vr.issues.iter().any(|d| d.id == codes::EXPECTED_NUMERIC),
        "should flag non-float: {:?}",
        vr.issues,
    );
}

#[test]
fn diag_zpl1108_valid_float_passes() {
    let tables = &*common::TABLES;
    // ^BY ratio (arg 1) with valid float 3.0 should NOT trigger ZPL1108
    let result = parse_with_tables("^XA^BY2,3.0,10^XZ", Some(tables));
    let vr = validate::validate(&result.ast, tables);
    assert!(
        !vr.issues.iter().any(|d| d.id == codes::EXPECTED_NUMERIC),
        "valid float should not emit ZPL1108: {:?}",
        vr.issues,
    );
}

#[test]
fn diag_zpl1109_char_type_mismatch() {
    let tables = &*common::TABLES;
    // ^CW takes font letter (char) + font name; give "ABC" (3 chars) as font letter
    // ^CC is not suitable for this test because it consumes exactly one char as
    // the new prefix and re-tokenizes the rest.
    // Instead, test with a command that has a char-typed arg but normal parsing.
    // Use ^CD via the validator directly with a multi-char delimiter (which gets
    // consumed as one char by the early handler, so also not suitable).
    // ^FW orientation is enum, not char type.
    // Look for any command with type=char that uses normal arg parsing.
    // Since ^CC/^CD/^CT now use early single-char handling, we need to test
    // the char type validation path with a different command.
    // For now, verify ^CC correctly takes only one char (the first) from "ABC".
    let result = parse_with_tables("^XA^CCABC^XZ", Some(tables));
    let codes = extract_codes(&result);
    // ^CC takes 'A' as the new prefix; 'B' and 'C' become unknown-command candidates
    assert!(codes.contains(&"^CC".to_string()), "should parse ^CC");
    // With prefix changed to 'A', subsequent tokens are re-tokenized
    // The command should have arg value 'A' (single char)
    let cc_args = find_args(&result, "^CC");
    assert_eq!(
        cc_args[0].value.as_deref(),
        Some("A"),
        "^CC should take only first char"
    );
}

#[test]
fn diag_zpl1109_single_char_passes() {
    let tables = &*common::TABLES;
    // ^CC with a single valid char should NOT trigger ZPL1109
    let result = parse_with_tables("^XA^CC+^XZ", Some(tables));
    let vr = validate::validate(&result.ast, tables);
    assert!(
        !vr.issues.iter().any(|d| d.id == codes::EXPECTED_CHAR),
        "single char should pass: {:?}",
        vr.issues,
    );
}

// ─── ZPL1201: Out of Range ───────────────────────────────────────────────────

#[test]
fn diag_zpl1201_out_of_range() {
    let tables = &*common::TABLES;
    // ^BY module width (arg 0) range is [1, 10]; give it 99
    let result = parse_with_tables("^XA^BY99^XZ", Some(tables));
    let vr = validate::validate(&result.ast, tables);
    assert!(
        vr.issues.iter().any(|d| d.id == codes::OUT_OF_RANGE),
        "should flag out of range: {:?}",
        vr.issues,
    );
}

#[test]
fn diag_zpl1201_in_range_passes() {
    let tables = &*common::TABLES;
    // ^BY module width (arg 0) range is [1, 10]; give it 5 (within range)
    let result = parse_with_tables("^XA^BY5^XZ", Some(tables));
    let vr = validate::validate(&result.ast, tables);
    assert!(
        !vr.issues.iter().any(|d| d.id == codes::OUT_OF_RANGE),
        "in-range value should not emit ZPL1201: {:?}",
        vr.issues,
    );
}

// ─── ZPL1401: Profile Constraint ─────────────────────────────────────────────

#[test]
fn diag_zpl1401_profile_constraint() {
    let tables = &*common::TABLES;
    // ^PW (print width) has profileConstraint { field: "page.width_dots", op: "lte" }
    // Create a profile with width_dots = 100, then set ^PW9999 → violates lte
    let profile = common::profile_from_json(
        r#"{"id":"test","schema_version":"1.0.0","dpi":203,"page":{"width_dots":100,"height_dots":100}}"#,
    );
    let result = parse_with_tables("^XA^PW9999^XZ", Some(tables));
    let vr = validate_with_profile(&result.ast, tables, Some(&profile));
    assert!(
        vr.issues.iter().any(|d| d.id == codes::PROFILE_CONSTRAINT),
        "should flag profile violation: {:?}",
        vr.issues,
    );
}

#[test]
fn diag_profile_constraint_ll_exceeds_height() {
    let tables = &*common::TABLES;
    let profile = common::profile_800x1200();
    // ^LL1500 exceeds profile height 1200 — now caught by generic profileConstraint (ZPL1401)
    let result = parse_with_tables("^XA^LL1500^XZ", Some(tables));
    let vr = validate_with_profile(&result.ast, tables, Some(&profile));
    assert!(
        vr.issues.iter().any(|d| d.id == codes::PROFILE_CONSTRAINT),
        "should flag ^LL exceeding profile height via generic constraint: {:?}",
        vr.issues,
    );
}

#[test]
fn diag_profile_constraint_ll_within_height() {
    let tables = &*common::TABLES;
    let profile = common::profile_800x1200();
    // ^LL800 is within profile height 1200 — generic profileConstraint should not fire
    let result = parse_with_tables("^XA^LL800^XZ", Some(tables));
    let vr = validate_with_profile(&result.ast, tables, Some(&profile));
    assert!(
        !vr.issues.iter().any(|d| d.id == codes::PROFILE_CONSTRAINT),
        "should not flag ^LL within profile height: {:?}",
        vr.issues,
    );
}

// ─── ZPL1501/1502: Required Missing/Empty ────────────────────────────────────

#[test]
fn diag_zpl1501_required_missing() {
    let tables = &*common::TABLES;
    // ^GF has 5 args: enum(optional), int(required), int(required),
    // int(required), string(required). Giving no args should flag the
    // required ones. With allowEmptyTrailing=true, absent trailing args
    // are treated as "empty" (ZPL1502) rather than "missing" (ZPL1501).
    let result = parse_with_tables("^XA^GF^XZ", Some(tables));
    let vr = validate::validate(&result.ast, tables);
    assert!(
        vr.issues
            .iter()
            .any(|d| d.id == codes::REQUIRED_MISSING || d.id == codes::REQUIRED_EMPTY),
        "should flag required missing/empty: {:?}",
        vr.issues,
    );
}

#[test]
fn diag_zpl1502_required_empty() {
    let tables = &*common::TABLES;
    // ^GFA,,100,10,data — arg 1 (binary_byte_count) is required (optional=false)
    // but given as empty (the ",," leaves it blank).
    let result = parse_with_tables("^XA^GFA,,100,10,data^XZ", Some(tables));
    let vr = validate::validate(&result.ast, tables);
    let has_presence = vr
        .issues
        .iter()
        .any(|d| d.id == codes::REQUIRED_MISSING || d.id == codes::REQUIRED_EMPTY);
    assert!(
        has_presence,
        "should flag empty required arg: {:?}",
        vr.issues,
    );
}

// ─── ZPL2101: Required Command ───────────────────────────────────────────────

#[test]
fn diag_zpl2101_requires_missing() {
    let tables = &*common::TABLES;
    // ^BC requires ^BY in the label; omit ^BY entirely
    let result = parse_with_tables("^XA^BCN,100,Y,N,N^FDtest^FS^XZ", Some(tables));
    let vr = validate::validate(&result.ast, tables);
    assert!(
        vr.issues.iter().any(|d| d.id == codes::REQUIRED_COMMAND),
        "should flag missing required command: {:?}",
        vr.issues,
    );
}

#[test]
fn diag_zpl2101_required_command_present_passes() {
    let tables = &*common::TABLES;
    // ^BC requires ^BY; include ^BY before ^BC — should NOT trigger ZPL2101
    let result = parse_with_tables("^XA^BY2^BCN,100,Y,N,N^FDtest^FS^XZ", Some(tables));
    let vr = validate::validate(&result.ast, tables);
    assert!(
        !vr.issues.iter().any(|d| d.id == codes::REQUIRED_COMMAND),
        "required command present should not emit ZPL2101: {:?}",
        vr.issues,
    );
}

// ─── ZPL2103: Order Violation ────────────────────────────────────────────────

#[test]
fn diag_zpl2103_order_violation() {
    let tables = &*common::TABLES;
    // ^BC has constraint "before:^FD|^FV": ^FD or ^FV must NOT appear before
    // ^BC in the node list. Put ^FD BEFORE ^BC to trigger this.
    let result = parse_with_tables(
        "^XA^BY2^FO10,10^FDtest^FS^BCN,100,Y,N,N^FDmore^FS^XZ",
        Some(tables),
    );
    let vr = validate::validate(&result.ast, tables);
    assert!(
        vr.issues.iter().any(|d| d.id == codes::ORDER_BEFORE),
        "should flag order violation: {:?}",
        vr.issues,
    );
}

#[test]
fn diag_zpl2103_correct_order_passes() {
    let tables = &*common::TABLES;
    // ^BC placed before ^FD (correct order) — should NOT trigger ZPL2103
    let result = parse_with_tables("^XA^BY2^FO10,10^BCN,100,Y,N,N^FDtest^FS^XZ", Some(tables));
    let vr = validate::validate(&result.ast, tables);
    assert!(
        !vr.issues.iter().any(|d| d.id == codes::ORDER_BEFORE),
        "correct order should not emit ZPL2103: {:?}",
        vr.issues,
    );
}

// ─── ZPL2201: Field Data Without Origin ──────────────────────────────────────

#[test]
fn diag_zpl2201_missing_field_origin() {
    let tables = &*common::TABLES;
    // ^FD without ^FO or ^FT preceding it
    let result = parse_with_tables("^XA^FDno origin^FS^XZ", Some(tables));
    let vr = validate::validate(&result.ast, tables);
    assert!(
        vr.issues
            .iter()
            .any(|d| d.id == codes::FIELD_DATA_WITHOUT_ORIGIN),
        "should flag missing field origin: {:?}",
        vr.issues,
    );
}

#[test]
fn diag_zpl2201_field_origin_present_passes() {
    let tables = &*common::TABLES;
    // ^FO before ^FD provides field origin — should NOT trigger ZPL2201
    let result = parse_with_tables("^XA^FO50,50^FDHello^FS^XZ", Some(tables));
    let vr = validate::validate(&result.ast, tables);
    assert!(
        !vr.issues
            .iter()
            .any(|d| d.id == codes::FIELD_DATA_WITHOUT_ORIGIN),
        "field origin present should not emit ZPL2201: {:?}",
        vr.issues,
    );
}

// ─── ZPL2202: Empty Label ────────────────────────────────────────────────────

#[test]
fn diag_zpl2202_empty_label() {
    let tables = &*common::TABLES;
    let result = parse_with_tables("^XA^XZ", Some(tables));
    let vr = validate::validate(&result.ast, tables);
    assert!(
        vr.issues.iter().any(|d| d.id == codes::EMPTY_LABEL),
        "empty label should emit ZPL2202: {:?}",
        vr.issues,
    );
}

#[test]
fn diag_zpl2202_non_empty_label_passes() {
    let tables = &*common::TABLES;
    // A label with content should NOT trigger ZPL2202
    let result = parse_with_tables("^XA^FO50,50^FDHello^FS^XZ", Some(tables));
    let vr = validate::validate(&result.ast, tables);
    assert!(
        !vr.issues.iter().any(|d| d.id == codes::EMPTY_LABEL),
        "non-empty label should not emit ZPL2202: {:?}",
        vr.issues,
    );
}

// ─── ZPL2203: Overlapping Fields ─────────────────────────────────────────────

#[test]
fn diag_zpl2203_overlapping_fields() {
    let tables = &*common::TABLES;
    // Two ^FO without ^FS between them
    let result = parse_with_tables("^XA^FO10,10^FO20,20^FDHello^FS^XZ", Some(tables));
    let vr = validate::validate(&result.ast, tables);
    assert!(
        vr.issues.iter().any(|d| d.id == codes::FIELD_NOT_CLOSED),
        "overlapping fields should emit ZPL2203: {:?}",
        vr.issues,
    );
}

#[test]
fn diag_zpl2203_non_overlapping_fields_passes() {
    let tables = &*common::TABLES;
    // Properly separated fields: ^FO -> ^FD -> ^FS, then ^FO -> ^FD -> ^FS
    let result = parse_with_tables(
        "^XA^FO10,10^FDFirst^FS^FO10,50^FDSecond^FS^XZ",
        Some(tables),
    );
    let vr = validate::validate(&result.ast, tables);
    assert!(
        !vr.issues.iter().any(|d| d.id == codes::FIELD_NOT_CLOSED),
        "non-overlapping fields should not emit ZPL2203: {:?}",
        vr.issues,
    );
}

// ─── ZPL2204: Orphaned Field Separator ───────────────────────────────────────

#[test]
fn diag_zpl2204_orphaned_fs() {
    let tables = &*common::TABLES;
    // ^FS without a preceding ^FO
    let result = parse_with_tables("^XA^FS^XZ", Some(tables));
    let vr = validate::validate(&result.ast, tables);
    assert!(
        vr.issues
            .iter()
            .any(|d| d.id == codes::ORPHANED_FIELD_SEPARATOR),
        "orphaned ^FS should emit ZPL2204: {:?}",
        vr.issues,
    );
}

#[test]
fn diag_zpl2204_paired_fs_passes() {
    let tables = &*common::TABLES;
    // ^FS properly paired with ^FO — should NOT trigger ZPL2204
    let result = parse_with_tables("^XA^FO10,10^FDHello^FS^XZ", Some(tables));
    let vr = validate::validate(&result.ast, tables);
    assert!(
        !vr.issues
            .iter()
            .any(|d| d.id == codes::ORPHANED_FIELD_SEPARATOR),
        "paired ^FS should not emit ZPL2204: {:?}",
        vr.issues,
    );
}

// ─── ZPL2205: Host Command in Label ──────────────────────────────────────────

#[test]
fn diag_zpl2205_scope_violation_host_in_label() {
    let tables = &*common::TABLES;
    // ~HS is a host command (plane: "host") — should not be inside ^XA/^XZ
    let result = parse_with_tables("^XA~HS^XZ", Some(tables));
    let vr = validate::validate(&result.ast, tables);
    assert!(
        vr.issues
            .iter()
            .any(|d| d.id == codes::HOST_COMMAND_IN_LABEL),
        "host command inside label should emit ZPL2205: {:?}",
        vr.issues,
    );
}

#[test]
fn diag_zpl2205_label_command_in_label_passes() {
    let tables = &*common::TABLES;
    // ^FO is a label-scoped command — should NOT trigger ZPL2205 inside ^XA/^XZ
    let result = parse_with_tables("^XA^FO10,10^FDHello^FS^XZ", Some(tables));
    let vr = validate::validate(&result.ast, tables);
    assert!(
        !vr.issues
            .iter()
            .any(|d| d.id == codes::HOST_COMMAND_IN_LABEL),
        "label command in label should not emit ZPL2205: {:?}",
        vr.issues,
    );
}

// ─── ZPL2301: Duplicate Field Number ─────────────────────────────────────────

#[test]
fn diag_zpl2301_duplicate_fn() {
    let tables = &*common::TABLES;
    // Two fields with the same ^FN number
    let result = parse_with_tables(
        "^XA^FO10,10^FN1^FDFirst^FS^FO10,50^FN1^FDSecond^FS^XZ",
        Some(tables),
    );
    let vr = validate::validate(&result.ast, tables);
    assert!(
        vr.issues
            .iter()
            .any(|d| d.id == codes::DUPLICATE_FIELD_NUMBER),
        "duplicate ^FN should emit ZPL2301: {:?}",
        vr.issues,
    );
}

#[test]
fn diag_zpl2301_unique_fn_passes() {
    let tables = &*common::TABLES;
    // Two fields with different ^FN numbers — should NOT trigger
    let result = parse_with_tables(
        "^XA^FO10,10^FN1^FDFirst^FS^FO10,50^FN2^FDSecond^FS^XZ",
        Some(tables),
    );
    let vr = validate::validate(&result.ast, tables);
    assert!(
        !vr.issues
            .iter()
            .any(|d| d.id == codes::DUPLICATE_FIELD_NUMBER),
        "unique ^FN numbers should not emit ZPL2301: {:?}",
        vr.issues,
    );
}

// ─── ZPL2302: Position Out of Bounds ─────────────────────────────────────────

#[test]
fn diag_zpl2302_position_out_of_bounds() {
    let tables = &*common::TABLES;
    let profile = common::profile_800x1200();
    // ^FO with x=9999 exceeds profile width of 800
    let result = parse_with_tables("^XA^FO9999,100^FDtest^FS^XZ", Some(tables));
    let vr = validate_with_profile(&result.ast, tables, Some(&profile));
    assert!(
        vr.issues
            .iter()
            .any(|d| d.id == codes::POSITION_OUT_OF_BOUNDS),
        "position exceeding bounds should emit ZPL2302: {:?}",
        vr.issues,
    );
}

#[test]
fn diag_zpl2302_position_within_bounds() {
    let tables = &*common::TABLES;
    let profile = common::profile_800x1200();
    // ^FO with valid positions
    let result = parse_with_tables("^XA^FO100,200^FDtest^FS^XZ", Some(tables));
    let vr = validate_with_profile(&result.ast, tables, Some(&profile));
    assert!(
        !vr.issues
            .iter()
            .any(|d| d.id == codes::POSITION_OUT_OF_BOUNDS),
        "valid position should not emit ZPL2302: {:?}",
        vr.issues,
    );
}

#[test]
fn diag_zpl2302_pw_overrides_profile() {
    let tables = &*common::TABLES;
    let profile = common::profile_800x1200();
    // ^PW sets width to 400 (narrower than profile), ^FO x=500 exceeds it
    let result = parse_with_tables("^XA^PW400^FO500,100^FDtest^FS^XZ", Some(tables));
    let vr = validate_with_profile(&result.ast, tables, Some(&profile));
    assert!(
        vr.issues
            .iter()
            .any(|d| d.id == codes::POSITION_OUT_OF_BOUNDS),
        "^PW should override profile width for bounds check: {:?}",
        vr.issues,
    );
}

// ─── ZPL2303: Unknown Font ───────────────────────────────────────────────────

#[test]
fn diag_zpl2303_unknown_font() {
    let tables = &*common::TABLES;
    // ^A with font 'x' (lowercase, not built-in A-Z or 0-9)
    let result = parse_with_tables("^XA^FO10,10^Ax,30,30^FDtest^FS^XZ", Some(tables));
    let vr = validate::validate(&result.ast, tables);
    assert!(
        vr.issues.iter().any(|d| d.id == codes::UNKNOWN_FONT),
        "unknown font should emit ZPL2303: {:?}",
        vr.issues,
    );
}

#[test]
fn diag_zpl2303_builtin_font_passes() {
    let tables = &*common::TABLES;
    // ^A with font 'A' (built-in)
    let result = parse_with_tables("^XA^FO10,10^AA,30,30^FDtest^FS^XZ", Some(tables));
    let vr = validate::validate(&result.ast, tables);
    assert!(
        !vr.issues.iter().any(|d| d.id == codes::UNKNOWN_FONT),
        "built-in font should not emit ZPL2303: {:?}",
        vr.issues,
    );
}

#[test]
fn diag_zpl2303_cw_loaded_font_passes() {
    let tables = &*common::TABLES;
    // ^CW loads font 'x', then ^A uses it — should NOT trigger
    let result = parse_with_tables(
        "^XA^CWx,E:ARIAL.TTF^FO10,10^Ax,30,30^FDtest^FS^XZ",
        Some(tables),
    );
    let vr = validate::validate(&result.ast, tables);
    assert!(
        !vr.issues.iter().any(|d| d.id == codes::UNKNOWN_FONT),
        "^CW loaded font should not emit ZPL2303: {:?}",
        vr.issues,
    );
}

// ─── ZPL2304: Invalid Hex Escape ─────────────────────────────────────────────

#[test]
fn diag_zpl2304_invalid_hex_escape() {
    let tables = &*common::TABLES;
    // ^FH enables hex escapes in field data; _GZ has invalid hex chars
    // (G and Z are not in 0-9/A-F). Use newline after ^FD to ensure content
    // flows into a FieldData node (inline content is absorbed into ^FD args
    // and the ZPL2304 check runs on FieldData nodes).
    let result = parse_with_tables("^XA^FO50,50^FH^FD\nHello _GZ World\n^FS^XZ", Some(tables));
    let vr = validate::validate(&result.ast, tables);
    let diag_ids: Vec<&str> = vr.issues.iter().map(|d| &*d.id).collect();
    assert!(
        diag_ids.contains(&codes::INVALID_HEX_ESCAPE),
        "expected ZPL2304 for invalid hex escape _GZ, got {:?}",
        diag_ids
    );
}

#[test]
fn diag_zpl2304_valid_hex_escape_passes() {
    let tables = &*common::TABLES;
    // ^FH with valid hex escape _1A (both chars are valid hex digits) should not trigger
    let result = parse_with_tables("^XA^FO50,50^FH^FD\nHello _1A World\n^FS^XZ", Some(tables));
    let vr = validate::validate(&result.ast, tables);
    let diag_ids: Vec<&str> = vr.issues.iter().map(|d| &*d.id).collect();
    assert!(
        !diag_ids.contains(&codes::INVALID_HEX_ESCAPE),
        "expected no ZPL2304 for valid hex escape _1A, got {:?}",
        diag_ids
    );
}

#[test]
fn diag_zpl2304_custom_indicator() {
    let tables = &*common::TABLES;
    // ^FH# sets '#' as the indicator — #GZ should trigger ZPL2304, _GZ should be fine
    let result = parse_with_tables("^XA^FO50,50^FH#^FD\n#GZ and _GZ\n^FS^XZ", Some(tables));
    let vr = validate::validate(&result.ast, tables);
    let hex_diags: Vec<_> = vr
        .issues
        .iter()
        .filter(|d| d.id == codes::INVALID_HEX_ESCAPE)
        .collect();
    assert_eq!(
        hex_diags.len(),
        1,
        "custom indicator '#' should find 1 error (#GZ), got {:?}",
        hex_diags
    );
    // Verify the indicator key is in the context
    let ctx = hex_diags[0]
        .context
        .as_ref()
        .expect("ZPL2304 should have context");
    assert_eq!(
        ctx.get("indicator").unwrap(),
        "#",
        "context should report custom indicator"
    );
}

#[test]
fn diag_zpl2304_indicator_resets_between_fields() {
    let tables = &*common::TABLES;
    // Field 1 uses custom indicator '#', field 2 uses default '_'
    // Field 1: #41 is valid (hex), field 2: _GZ should trigger error
    let result = parse_with_tables(
        "^XA^FO10,10^FH#^FD\n#41\n^FS^FO10,50^FH^FD\n_GZ\n^FS^XZ",
        Some(tables),
    );
    let vr = validate::validate(&result.ast, tables);
    let hex_diags: Vec<_> = vr
        .issues
        .iter()
        .filter(|d| d.id == codes::INVALID_HEX_ESCAPE)
        .collect();
    assert_eq!(
        hex_diags.len(),
        1,
        "should have 1 error for _GZ in field 2: {:?}",
        hex_diags
    );
    let ctx = hex_diags[0]
        .context
        .as_ref()
        .expect("ZPL2304 should have context");
    assert_eq!(
        ctx.get("indicator").unwrap(),
        "_",
        "field 2 should use default indicator"
    );
}

// ─── ZPL2305: Redundant State ────────────────────────────────────────────────

#[test]
fn diag_zpl2305_redundant_state() {
    let tables = &*common::TABLES;
    // Two ^BY commands with no barcode between them
    let result = parse_with_tables("^XA^BY2^BY3^BCN,100^FDtest^FS^XZ", Some(tables));
    let vr = validate::validate(&result.ast, tables);
    assert!(
        vr.issues.iter().any(|d| d.id == codes::REDUNDANT_STATE),
        "redundant ^BY should emit ZPL2305: {:?}",
        vr.issues,
    );
}

#[test]
fn diag_zpl2305_consumed_state_passes() {
    let tables = &*common::TABLES;
    // ^BY then barcode then ^BY — second ^BY is NOT redundant because first was consumed
    let result = parse_with_tables(
        "^XA^BY2^BCN,100^FDtest1^FS^BY3^BCN,200^FDtest2^FS^XZ",
        Some(tables),
    );
    let vr = validate::validate(&result.ast, tables);
    assert!(
        !vr.issues.iter().any(|d| d.id == codes::REDUNDANT_STATE),
        "consumed state should not emit ZPL2305: {:?}",
        vr.issues,
    );
}

// ─── ZPL2306: Serialization Without Field Number ─────────────────────────────

#[test]
fn diag_zpl2306_serial_without_fn() {
    let tables = &*common::TABLES;
    // ^SN in a field without ^FN
    let result = parse_with_tables("^XA^FO10,10^SN001,1,Y^FD001^FS^XZ", Some(tables));
    let vr = validate::validate(&result.ast, tables);
    assert!(
        vr.issues
            .iter()
            .any(|d| d.id == codes::SERIALIZATION_WITHOUT_FIELD_NUMBER),
        "^SN without ^FN should emit ZPL2306: {:?}",
        vr.issues,
    );
}

#[test]
fn diag_zpl2306_serial_with_fn_passes() {
    let tables = &*common::TABLES;
    // ^SN in a field WITH ^FN — should NOT trigger
    let result = parse_with_tables("^XA^FO10,10^FN1^SN001,1,Y^FD001^FS^XZ", Some(tables));
    let vr = validate::validate(&result.ast, tables);
    assert!(
        !vr.issues
            .iter()
            .any(|d| d.id == codes::SERIALIZATION_WITHOUT_FIELD_NUMBER),
        "^SN with ^FN should not emit ZPL2306: {:?}",
        vr.issues,
    );
}

// ─── ZPL2307: ^GF Data Length Mismatch ───────────────────────────────────────

#[test]
fn diag_zpl2307_gf_ascii_hex_mismatch() {
    let tables = &*common::TABLES;
    // ^GF with ASCII hex (A): 3 bytes = 6 hex chars expected, but only 4 provided
    let result = parse_with_tables("^XA^GFA,3,3,1,AABB^FS^XZ", Some(tables));
    let vr = validate::validate(&result.ast, tables);
    assert!(
        vr.issues
            .iter()
            .any(|d| d.id == codes::GF_DATA_LENGTH_MISMATCH),
        "^GF with mismatched ASCII hex data length should emit ZPL2307: {:?}",
        vr.issues,
    );
}

#[test]
fn diag_zpl2307_gf_ascii_hex_correct() {
    let tables = &*common::TABLES;
    // ^GF with ASCII hex (A): 3 bytes = 6 hex chars, data is exactly 6 chars
    let result = parse_with_tables("^XA^GFA,3,3,1,AABBCC^FS^XZ", Some(tables));
    let vr = validate::validate(&result.ast, tables);
    assert!(
        !vr.issues
            .iter()
            .any(|d| d.id == codes::GF_DATA_LENGTH_MISMATCH),
        "^GF with correct ASCII hex data length should not emit ZPL2307: {:?}",
        vr.issues,
    );
}

#[test]
fn diag_zpl2307_gf_binary_mismatch() {
    let tables = &*common::TABLES;
    // ^GF with binary (B): 4 bytes declared, but data is 2 bytes
    let result = parse_with_tables("^XA^GFB,4,4,1,AB^FS^XZ", Some(tables));
    let vr = validate::validate(&result.ast, tables);
    assert!(
        vr.issues
            .iter()
            .any(|d| d.id == codes::GF_DATA_LENGTH_MISMATCH),
        "^GF with mismatched binary data length should emit ZPL2307: {:?}",
        vr.issues,
    );
}

#[test]
fn diag_zpl2307_gf_compressed_skipped() {
    let tables = &*common::TABLES;
    // ^GF with compressed (C): should NOT emit ZPL2307 — compression makes length unpredictable
    let result = parse_with_tables("^XA^GFC,100,100,10,ABC^FS^XZ", Some(tables));
    let vr = validate::validate(&result.ast, tables);
    assert!(
        !vr.issues
            .iter()
            .any(|d| d.id == codes::GF_DATA_LENGTH_MISMATCH),
        "^GF with compressed format should not emit ZPL2307: {:?}",
        vr.issues,
    );
}

#[test]
fn diag_zpl2307_gf_multiline_correct() {
    let tables = &*common::TABLES;
    // ^GF with 8 bytes declared = 16 ASCII hex chars.
    // 8 chars inline (FFAA5500) + 8 chars continuation (FFAA5500) = 16 total.
    let input = "^XA^GFA,8,8,1,FFAA5500\nFFAA5500\n^FS^XZ";
    let result = parse_with_tables(input, Some(tables));
    let vr = validate::validate(&result.ast, tables);
    assert!(
        !vr.issues
            .iter()
            .any(|d| d.id == codes::GF_DATA_LENGTH_MISMATCH),
        "^GF with correct total data across continuation should not emit ZPL2307: {:?}",
        vr.issues,
    );
}

#[test]
fn diag_zpl2307_gf_multiline_mismatch() {
    let tables = &*common::TABLES;
    // ^GF with 8 bytes declared = 16 ASCII hex chars.
    // Only 4 chars inline (FFAA) + 4 chars continuation (5500) = 8 total, which is wrong.
    let input = "^XA^GFA,8,8,1,FFAA\n5500\n^FS^XZ";
    let result = parse_with_tables(input, Some(tables));
    let vr = validate::validate(&result.ast, tables);
    assert!(
        vr.issues
            .iter()
            .any(|d| d.id == codes::GF_DATA_LENGTH_MISMATCH),
        "^GF with mismatched total data across continuation should emit ZPL2307: {:?}",
        vr.issues,
    );
}

#[test]
fn diag_zpl2307_gf_inline_only_regression() {
    let tables = &*common::TABLES;
    // Single-line ^GF that was correct before — must still pass (regression guard)
    let input = "^XA^GFA,4,4,1,AABBCCDD^FS^XZ";
    let result = parse_with_tables(input, Some(tables));
    let vr = validate::validate(&result.ast, tables);
    assert!(
        !vr.issues
            .iter()
            .any(|d| d.id == codes::GF_DATA_LENGTH_MISMATCH),
        "single-line ^GF with correct length should not emit ZPL2307 (regression): {:?}",
        vr.issues,
    );
}

// ─── ZPL2308: Graphics Bounds Check ──────────────────────────────────────────

#[test]
fn diag_zpl2308_gf_overflows_width() {
    let tables = &*common::TABLES;
    let profile = common::profile_800x1200();
    // ^PW400 sets width to 400. ^FO300,0 sets position.
    // ^GF with bytes_per_row=20 → graphic_width = 20*8 = 160 dots.
    // 300 + 160 = 460 > 400 → should overflow.
    // Using ASCII hex (A): graphic_field_count=20, bytes_per_row=20 → 1 row.
    // data: 40 hex chars (20 bytes * 2 hex/byte)
    let data = "FF".repeat(20);
    let input = format!("^XA^PW400^FO300,0^GFA,20,20,20,{}^FS^XZ", data);
    let result = parse_with_tables(&input, Some(tables));
    let vr = validate_with_profile(&result.ast, tables, Some(&profile));
    assert!(
        vr.issues.iter().any(|d| d.id == codes::GF_BOUNDS_OVERFLOW),
        "^GF overflowing label width should emit ZPL2308: {:?}",
        vr.issues,
    );
}

#[test]
fn diag_zpl2308_gf_overflows_height() {
    let tables = &*common::TABLES;
    // ^FO0,50 sets position. ^GF with graphic_field_count=200, bytes_per_row=10.
    // graphic_height = 200/10 = 20 rows. graphic_width = 10*8 = 80 dots.
    // 50 + 20 = 70 > 60 → should overflow.
    let profile = common::profile_from_json(
        r#"{"id":"test","schema_version":"1.0.0","dpi":203,"page":{"width_dots":800,"height_dots":60}}"#,
    );
    let data = "FF".repeat(200);
    let input = format!("^XA^FO0,50^GFA,200,200,10,{}^FS^XZ", data);
    let result = parse_with_tables(&input, Some(tables));
    let vr = validate_with_profile(&result.ast, tables, Some(&profile));
    assert!(
        vr.issues.iter().any(|d| d.id == codes::GF_BOUNDS_OVERFLOW),
        "^GF overflowing label height should emit ZPL2308: {:?}",
        vr.issues,
    );
}

#[test]
fn diag_zpl2308_gf_fits_no_diagnostic() {
    let tables = &*common::TABLES;
    let profile = common::profile_800x1200();
    // ^FO0,0 + ^GF with bytes_per_row=10: graphic_width=80, graphic_height=10.
    // 0+80 ≤ 800, 0+10 ≤ 1200 → fits fine.
    let data = "FF".repeat(100);
    let input = format!("^XA^FO0,0^GFA,100,100,10,{}^FS^XZ", data);
    let result = parse_with_tables(&input, Some(tables));
    let vr = validate_with_profile(&result.ast, tables, Some(&profile));
    assert!(
        !vr.issues.iter().any(|d| d.id == codes::GF_BOUNDS_OVERFLOW),
        "^GF that fits should not emit ZPL2308: {:?}",
        vr.issues,
    );
}

// ─── ZPL2309: Graphics Memory Estimation ─────────────────────────────────────

#[test]
fn diag_zpl2309_gf_exceeds_memory() {
    let tables = &*common::TABLES;
    // Profile with 1 KB RAM (1024 bytes). Two ^GF with 600 bytes each = 1200 > 1024.
    let profile = common::profile_from_json(
        r#"{"id":"test","schema_version":"1.0.0","dpi":203,"page":{"width_dots":800,"height_dots":1200},"memory":{"ram_kb":1}}"#,
    );
    let data1 = "FF".repeat(600);
    let data2 = "FF".repeat(600);
    let input = format!(
        "^XA^FO0,0^GFA,600,600,10,{}^FS^FO0,100^GFA,600,600,10,{}^FS^XZ",
        data1, data2
    );
    let result = parse_with_tables(&input, Some(tables));
    let vr = validate_with_profile(&result.ast, tables, Some(&profile));
    assert!(
        vr.issues.iter().any(|d| d.id == codes::GF_MEMORY_EXCEEDED),
        "total ^GF bytes exceeding RAM should emit ZPL2309: {:?}",
        vr.issues,
    );
}

#[test]
fn diag_zpl2309_gf_no_warning_without_profile() {
    let tables = &*common::TABLES;
    // No profile → no memory check.
    let data = "FF".repeat(600);
    let input = format!("^XA^FO0,0^GFA,600,600,10,{}^FS^XZ", data);
    let result = parse_with_tables(&input, Some(tables));
    let vr = validate::validate(&result.ast, tables);
    assert!(
        !vr.issues.iter().any(|d| d.id == codes::GF_MEMORY_EXCEEDED),
        "^GF without profile should not emit ZPL2309: {:?}",
        vr.issues,
    );
}

#[test]
fn diag_zpl2309_gf_within_memory_no_warning() {
    let tables = &*common::TABLES;
    // Profile with 512 KB RAM. ^GF with 100 bytes — well within limits.
    let profile = common::profile_from_json(
        r#"{"id":"test","schema_version":"1.0.0","dpi":203,"memory":{"ram_kb":512}}"#,
    );
    let data = "FF".repeat(100);
    let input = format!("^XA^FO0,0^GFA,100,100,10,{}^FS^XZ", data);
    let result = parse_with_tables(&input, Some(tables));
    let vr = validate_with_profile(&result.ast, tables, Some(&profile));
    assert!(
        !vr.issues.iter().any(|d| d.id == codes::GF_MEMORY_EXCEEDED),
        "^GF within RAM should not emit ZPL2309: {:?}",
        vr.issues,
    );
}

// ─── ZPL2310: Missing Explicit Dimensions ────────────────────────────────────

#[test]
fn diag_zpl2310_missing_pw_ll_with_profile() {
    let tables = &*common::TABLES;
    let profile = common::profile_800x1200();
    // Profile provides dimensions but label has no ^PW or ^LL
    let result = parse_with_tables("^XA^FO50,50^FDHello^FS^XZ", Some(tables));
    let vr = validate_with_profile(&result.ast, tables, Some(&profile));
    assert!(
        vr.issues
            .iter()
            .any(|d| d.id == codes::MISSING_EXPLICIT_DIMENSIONS),
        "label without ^PW/^LL with profile should emit ZPL2310: {:?}",
        vr.issues,
    );
}

#[test]
fn diag_zpl2310_has_pw_ll_no_diagnostic() {
    let tables = &*common::TABLES;
    let profile = common::profile_800x1200();
    // Label has both ^PW and ^LL — should NOT trigger
    let result = parse_with_tables("^XA^PW800^LL1200^FO50,50^FDHello^FS^XZ", Some(tables));
    let vr = validate_with_profile(&result.ast, tables, Some(&profile));
    assert!(
        !vr.issues
            .iter()
            .any(|d| d.id == codes::MISSING_EXPLICIT_DIMENSIONS),
        "label with ^PW and ^LL should not emit ZPL2310: {:?}",
        vr.issues,
    );
}

#[test]
fn diag_zpl2310_no_profile_no_diagnostic() {
    let tables = &*common::TABLES;
    // No profile → no ZPL2310
    let result = parse_with_tables("^XA^FO50,50^FDHello^FS^XZ", Some(tables));
    let vr = validate::validate(&result.ast, tables);
    assert!(
        !vr.issues
            .iter()
            .any(|d| d.id == codes::MISSING_EXPLICIT_DIMENSIONS),
        "label without profile should not emit ZPL2310: {:?}",
        vr.issues,
    );
}

#[test]
fn diag_zpl2310_partial_pw_only() {
    let tables = &*common::TABLES;
    let profile = common::profile_800x1200();
    // Label has ^PW but not ^LL — should emit ZPL2310 for missing ^LL
    let result = parse_with_tables("^XA^PW800^FO50,50^FDHello^FS^XZ", Some(tables));
    let vr = validate_with_profile(&result.ast, tables, Some(&profile));
    let diag = vr
        .issues
        .iter()
        .find(|d| d.id == codes::MISSING_EXPLICIT_DIMENSIONS);
    assert!(
        diag.is_some(),
        "label with only ^PW should emit ZPL2310: {:?}",
        vr.issues,
    );
    let ctx = diag.unwrap().context.as_ref().expect("should have context");
    assert!(
        ctx.get("missing_commands").unwrap().contains("^LL"),
        "missing_commands should include ^LL: {:?}",
        ctx,
    );
    assert!(
        !ctx.get("missing_commands").unwrap().contains("^PW"),
        "missing_commands should not include ^PW: {:?}",
        ctx,
    );
}

#[test]
fn diag_zpl2310_profile_no_page_no_diagnostic() {
    let tables = &*common::TABLES;
    // Profile without page dimensions — should NOT trigger ZPL2310
    let profile = common::profile_from_json(r#"{"id":"test","schema_version":"1.0.0","dpi":203}"#);
    let result = parse_with_tables("^XA^FO50,50^FDHello^FS^XZ", Some(tables));
    let vr = validate_with_profile(&result.ast, tables, Some(&profile));
    assert!(
        !vr.issues
            .iter()
            .any(|d| d.id == codes::MISSING_EXPLICIT_DIMENSIONS),
        "profile without page dimensions should not emit ZPL2310: {:?}",
        vr.issues,
    );
}

// ─── ZPL2401/2402: Barcode Validation ────────────────────────────────────────

#[test]
fn barcode_fd_ean13_valid() {
    let tables = &*common::TABLES;
    // ^BE (EAN-13) with exactly 12 digits — should pass
    let input = "^XA^FO10,10^BE,50,N,N^FD123456789012^FS^XZ";
    let result = parse_with_tables(input, Some(tables));
    let vr = validate::validate(&result.ast, tables);
    assert!(
        !vr.issues
            .iter()
            .any(|d| d.id == codes::BARCODE_INVALID_CHAR || d.id == codes::BARCODE_DATA_LENGTH),
        "valid EAN-13 data should not trigger barcode diagnostics: {:?}",
        vr.issues,
    );
}

#[test]
fn barcode_fd_ean13_invalid_chars() {
    let tables = &*common::TABLES;
    // ^BE (EAN-13) with non-numeric characters — should flag ZPL2401
    let input = "^XA^FO10,10^BE,50,N,N^FDABCDEF123456^FS^XZ";
    let result = parse_with_tables(input, Some(tables));
    let vr = validate::validate(&result.ast, tables);
    assert!(
        vr.issues
            .iter()
            .any(|d| d.id == codes::BARCODE_INVALID_CHAR),
        "non-numeric EAN-13 data should trigger ZPL2401: {:?}",
        vr.issues,
    );
}

#[test]
fn barcode_fd_ean13_wrong_length() {
    let tables = &*common::TABLES;
    // ^BE (EAN-13) with wrong length — should flag ZPL2402
    let input = "^XA^FO10,10^BE,50,N,N^FD12345^FS^XZ";
    let result = parse_with_tables(input, Some(tables));
    let vr = validate::validate(&result.ast, tables);
    assert!(
        vr.issues.iter().any(|d| d.id == codes::BARCODE_DATA_LENGTH),
        "wrong-length EAN-13 data should trigger ZPL2402: {:?}",
        vr.issues,
    );
}

#[test]
fn barcode_fd_code39_valid() {
    let tables = &*common::TABLES;
    // ^B3 (Code 39) with valid alphanumeric — should pass
    let input = "^XA^FO10,10^B3,N,50,N,N^FDTEST 123^FS^XZ";
    let result = parse_with_tables(input, Some(tables));
    let vr = validate::validate(&result.ast, tables);
    assert!(
        !vr.issues
            .iter()
            .any(|d| d.id == codes::BARCODE_INVALID_CHAR),
        "valid Code 39 data should not trigger ZPL2401: {:?}",
        vr.issues,
    );
}

#[test]
fn barcode_fd_code39_invalid_chars() {
    let tables = &*common::TABLES;
    // ^B3 (Code 39) with lowercase (not in standard charset) — should flag ZPL2401
    let input = "^XA^FO10,10^B3,N,50,N,N^FDhello^FS^XZ";
    let result = parse_with_tables(input, Some(tables));
    let vr = validate::validate(&result.ast, tables);
    assert!(
        vr.issues
            .iter()
            .any(|d| d.id == codes::BARCODE_INVALID_CHAR),
        "lowercase in Code 39 data should trigger ZPL2401: {:?}",
        vr.issues,
    );
}

#[test]
fn barcode_fd_interleaved2of5_even_parity() {
    let tables = &*common::TABLES;
    // ^B2 (Interleaved 2 of 5) with even digit count — should pass
    let input = "^XA^FO10,10^B2,50^FD1234^FS^XZ";
    let result = parse_with_tables(input, Some(tables));
    let vr = validate::validate(&result.ast, tables);
    assert!(
        !vr.issues.iter().any(|d| d.id == codes::BARCODE_DATA_LENGTH),
        "even digit count for I2of5 should pass: {:?}",
        vr.issues,
    );
}

#[test]
fn barcode_fd_interleaved2of5_odd_parity() {
    let tables = &*common::TABLES;
    // ^B2 (Interleaved 2 of 5) with odd digit count — should flag ZPL2402
    let input = "^XA^FO10,10^B2,50^FD123^FS^XZ";
    let result = parse_with_tables(input, Some(tables));
    let vr = validate::validate(&result.ast, tables);
    assert!(
        vr.issues.iter().any(|d| d.id == codes::BARCODE_DATA_LENGTH),
        "odd digit count for I2of5 should trigger ZPL2402: {:?}",
        vr.issues,
    );
}

#[test]
fn barcode_fd_no_barcode_no_validation() {
    let tables = &*common::TABLES;
    // No barcode command — ^FD with any content should not trigger barcode diagnostics
    let input = "^XA^FO10,10^FDanything goes here!@#$^FS^XZ";
    let result = parse_with_tables(input, Some(tables));
    let vr = validate::validate(&result.ast, tables);
    assert!(
        !vr.issues
            .iter()
            .any(|d| d.id == codes::BARCODE_INVALID_CHAR || d.id == codes::BARCODE_DATA_LENGTH),
        "no barcode command should not trigger barcode diagnostics: {:?}",
        vr.issues,
    );
}

// ─── ZPL3001: Note ───────────────────────────────────────────────────────────

#[test]
fn diag_zpl3001_note_emitted() {
    let tables = &*common::TABLES;
    // ^BY has note constraints about firmware behavior
    let result = parse_with_tables("^XA^BY2,3.0,10^XZ", Some(tables));
    let vr = validate::validate(&result.ast, tables);
    let notes: Vec<_> = vr.issues.iter().filter(|d| d.id == codes::NOTE).collect();
    assert!(
        !notes.is_empty(),
        "commands with note constraints should emit ZPL3001: {:?}",
        vr.issues,
    );
}

// ─── Structural Validation ───────────────────────────────────────────────────

#[test]
fn structural_valid_field_block_no_warnings() {
    let tables = &*common::TABLES;
    // Properly structured: ^FO -> ^FD -> ^FS
    let result = parse_with_tables("^XA^FO50,50^FDHello^FS^XZ", Some(tables));
    let vr = validate::validate(&result.ast, tables);
    let structural: Vec<_> = vr
        .issues
        .iter()
        .filter(|d| d.id.starts_with("ZPL22"))
        .collect();
    assert!(
        structural.is_empty(),
        "well-formed field block should have no structural warnings: {:?}",
        structural,
    );
}

#[test]
fn structural_multiple_fields_valid() {
    let tables = &*common::TABLES;
    // Multiple properly structured fields
    let result = parse_with_tables(
        "^XA^FO10,10^FDFirst^FS^FO10,50^FDSecond^FS^XZ",
        Some(tables),
    );
    let vr = validate::validate(&result.ast, tables);
    let structural: Vec<_> = vr
        .issues
        .iter()
        .filter(|d| d.id.starts_with("ZPL22"))
        .collect();
    assert!(
        structural.is_empty(),
        "multiple well-formed field blocks should have no structural warnings: {:?}",
        structural,
    );
}

// ─── Profile Edge Cases ─────────────────────────────────────────────────────

#[test]
fn profile_none_page_skips_constraints() {
    let tables = &*common::TABLES;
    let profile = common::profile_from_json(r#"{"id":"test","schema_version":"1.0.0","dpi":203}"#);
    let result = parse_with_tables("^XA^PW9999^XZ", Some(tables));
    let vr = validate_with_profile(&result.ast, tables, Some(&profile));
    // No profile constraint should fire since page is None
    assert!(
        !vr.issues.iter().any(|d| d.id == codes::PROFILE_CONSTRAINT),
        "profile with no page should not trigger constraints: {:?}",
        vr.issues,
    );
}

#[test]
fn profile_missing_height_skips_ll_constraint() {
    let tables = &*common::TABLES;
    let profile = common::profile_from_json(
        r#"{"id":"test","schema_version":"1.0.0","dpi":203,"page":{"width_dots":800}}"#,
    );
    let result = parse_with_tables("^XA^LL9999^XZ", Some(tables));
    let vr = validate_with_profile(&result.ast, tables, Some(&profile));
    // No height constraint should fire since height_dots is not in profile
    assert!(
        !vr.issues
            .iter()
            .any(|d| d.id == codes::PROFILE_CONSTRAINT && d.message.contains("height")),
        "profile without height_dots should not trigger ^LL constraint: {:?}",
        vr.issues,
    );
}

#[test]
fn profile_height_used_for_position_bounds() {
    let tables = &*common::TABLES;
    let profile = common::profile_from_json(
        r#"{"id":"test","schema_version":"1.0.0","dpi":203,"page":{"width_dots":800,"height_dots":600}}"#,
    );
    let result = parse_with_tables("^XA^FO100,700^XZ", Some(tables));
    let vr = validate_with_profile(&result.ast, tables, Some(&profile));
    assert!(
        vr.issues
            .iter()
            .any(|d| d.id == codes::POSITION_OUT_OF_BOUNDS),
        "y position 700 should exceed profile height 600: {:?}",
        vr.issues,
    );
}

#[test]
fn profile_300dpi_width_constraint() {
    let tables = &*common::TABLES;
    // 300 dpi profile has width_dots: 1218
    let profile = common::profile_from_json(
        r#"{"id":"zebra-generic-300","schema_version":"1.0.0","dpi":300,"page":{"width_dots":1218,"height_dots":1800}}"#,
    );

    // ^PW1300 exceeds the 300 dpi profile width (1218 dots)
    let ast = parse_with_tables("^XA^PW1300^XZ", Some(tables));
    let vr = validate_with_profile(&ast.ast, tables, Some(&profile));
    assert!(
        vr.issues.iter().any(|d| d.id == codes::PROFILE_CONSTRAINT),
        "^PW1300 should exceed 300 dpi profile width 1218: {:?}",
        vr.issues,
    );

    // ^PW1200 is within the 300 dpi profile width (1218 dots)
    let ast2 = parse_with_tables("^XA^PW1200^XZ", Some(tables));
    let vr2 = validate_with_profile(&ast2.ast, tables, Some(&profile));
    assert!(
        !vr2.issues.iter().any(|d| d.id == codes::PROFILE_CONSTRAINT),
        "^PW1200 should be within 300 dpi profile width 1218: {:?}",
        vr2.issues,
    );
}

#[test]
fn all_profile_constraint_fields_are_resolvable() {
    let tables = &*common::TABLES;

    // Build a fully-populated test profile so every field resolves to Some.
    let profile = common::profile_from_json(
        r#"{
        "id": "test",
        "schema_version": "1.1.0",
        "dpi": 203,
        "page": { "width_dots": 812, "height_dots": 1218 },
        "speed_range": { "min": 2, "max": 8 },
        "darkness_range": { "min": 0, "max": 30 },
        "features": {
            "cutter": true, "peel": true, "rewinder": true,
            "applicator": true, "rfid": true, "rtc": true,
            "battery": true, "zbi": true, "lcd": true, "kiosk": true
        },
        "media": {
            "print_method": "both",
            "supported_modes": ["T", "P", "C"],
            "supported_tracking": ["N", "Y", "M"]
        },
        "memory": { "ram_kb": 512, "flash_kb": 65536, "firmware_version": "V60.19.15Z" }
    }"#,
    );

    // Collect all unique profileConstraint.field values from all commands.
    let mut profile_fields: std::collections::HashSet<String> = std::collections::HashSet::new();
    for cmd in &tables.commands {
        if let Some(args) = &cmd.args {
            for arg_union in args {
                let args_to_check: Vec<&zpl_toolchain_spec_tables::Arg> = match arg_union {
                    zpl_toolchain_spec_tables::ArgUnion::Single(a) => vec![a.as_ref()],
                    zpl_toolchain_spec_tables::ArgUnion::OneOf { one_of } => {
                        one_of.iter().collect()
                    }
                };
                for arg in args_to_check {
                    if let Some(pc) = &arg.profile_constraint {
                        profile_fields.insert(pc.field.clone());
                    }
                }
            }
        }
    }

    assert!(
        !profile_fields.is_empty(),
        "Expected at least one profileConstraint.field in the spec tables — \
         is the test data missing?"
    );

    // Verify each field is resolvable.
    for field in &profile_fields {
        let resolved = zpl_toolchain_core::validate::resolve_profile_field(&profile, field);
        assert!(
            resolved.is_some(),
            "profileConstraint references field '{}' but resolve_profile_field returns None for it. \
             Add a match arm in resolve_profile_field() for this field path.",
            field
        );
    }
}

#[test]
fn diag_profile_constraint_sd_exceeds_darkness() {
    let tables = &*common::TABLES;
    let profile = common::profile_from_json(
        r#"{"id":"test","schema_version":"1.0.0","dpi":203,"darkness_range":{"min":0,"max":30}}"#,
    );

    // ~SD31 exceeds darkness_range.max (30)
    let ast = parse_with_tables("^XA~SD31^XZ", Some(tables));
    let vr = validate_with_profile(&ast.ast, tables, Some(&profile));
    assert!(
        vr.issues
            .iter()
            .any(|d| d.id == codes::PROFILE_CONSTRAINT && d.message.contains("darkness")),
        "~SD31 should exceed darkness_range.max 30: {:?}",
        vr.issues,
    );

    // ~SD25 is within darkness_range.max (30)
    let ast2 = parse_with_tables("^XA~SD25^XZ", Some(tables));
    let vr2 = validate_with_profile(&ast2.ast, tables, Some(&profile));
    assert!(
        !vr2.issues
            .iter()
            .any(|d| d.id == codes::PROFILE_CONSTRAINT && d.message.contains("darkness")),
        "~SD25 should be within darkness_range.max 30: {:?}",
        vr2.issues,
    );
}

#[test]
fn profile_all_none_skips_all_constraints() {
    let tables = &*common::TABLES;
    let profile = common::profile_from_json(r#"{"id":"test","schema_version":"1.0.0","dpi":203}"#);

    // All optional profile fields are None — no profileConstraint should fire
    let ast = parse_with_tables("^XA^PW9999^LL9999~SD99^XZ", Some(tables));
    let vr = validate_with_profile(&ast.ast, tables, Some(&profile));
    assert!(
        !vr.issues.iter().any(|d| d.id == codes::PROFILE_CONSTRAINT),
        "all-None profile should skip all profile constraints: {:?}",
        vr.issues,
    );
}

// ─── Printer Gate Enforcement ────────────────────────────────────────────────

#[test]
fn printer_gate_command_level_violation() {
    let tables = &*common::TABLES;
    // This test verifies that commands WITHOUT printerGates don't trigger ZPL1402
    // even when the profile has features set to false.
    let profile = common::profile_from_json(
        r#"{"id":"test","schema_version":"1.0.0","dpi":203,"features":{"cutter":false}}"#,
    );
    // ^PW has no printerGates, so it should NOT trigger ZPL1402
    let ast = parse_with_tables("^XA^PW100^XZ", Some(tables));
    let vr = validate_with_profile(&ast.ast, tables, Some(&profile));
    assert!(
        !vr.issues.iter().any(|d| d.id == codes::PRINTER_GATE),
        "commands without printerGates should not trigger ZPL1402: {:?}",
        vr.issues,
    );
}

#[test]
fn printer_gate_no_features_skips() {
    let tables = &*common::TABLES;
    // Profile without features should skip all gate checks
    let profile = common::profile_from_json(r#"{"id":"test","schema_version":"1.0.0","dpi":203}"#);
    let ast = parse_with_tables("^XA^PW100^XZ", Some(tables));
    let vr = validate_with_profile(&ast.ast, tables, Some(&profile));
    assert!(
        !vr.issues.iter().any(|d| d.id == codes::PRINTER_GATE),
        "profile without features should skip gate checks: {:?}",
        vr.issues,
    );
}

#[test]
fn printer_gate_command_fires_when_feature_false() {
    let tables = &*common::TABLES;
    // ^RF has printerGates: ["rfid"] in spec. Profile has rfid=false.
    let profile = common::profile_from_json(
        r#"{"id":"test","schema_version":"1.0.0","dpi":203,"features":{"rfid":false}}"#,
    );
    let ast = parse_with_tables("^XA^RFW,H,0,1,E^XZ", Some(tables));
    let vr = validate_with_profile(&ast.ast, tables, Some(&profile));
    assert!(
        vr.issues.iter().any(|d| d.id == codes::PRINTER_GATE),
        "^RF with rfid=false should trigger ZPL1402: {:?}",
        vr.issues,
    );
}

#[test]
fn printer_gate_command_skips_when_feature_true() {
    let tables = &*common::TABLES;
    let profile = common::profile_from_json(
        r#"{"id":"test","schema_version":"1.0.0","dpi":203,"features":{"rfid":true}}"#,
    );
    let ast = parse_with_tables("^XA^RFW,H,0,1,E^XZ", Some(tables));
    let vr = validate_with_profile(&ast.ast, tables, Some(&profile));
    assert!(
        !vr.issues.iter().any(|d| d.id == codes::PRINTER_GATE),
        "^RF with rfid=true should NOT trigger ZPL1402: {:?}",
        vr.issues,
    );
}

// ─── Enum Value-Level Gate Tests ─────────────────────────────────────────────

#[test]
fn printer_gate_enum_value_fires_when_feature_false() {
    let tables = &*common::TABLES;
    let profile = common::profile_from_json(
        r#"{"id":"test","schema_version":"1.0.0","dpi":203,"features":{"cutter":false}}"#,
    );
    let ast = parse_with_tables("^XA^MMC^XZ", Some(tables));
    let vr = validate_with_profile(&ast.ast, tables, Some(&profile));
    assert!(
        vr.issues.iter().any(|d| d.id == codes::PRINTER_GATE),
        "^MMC with cutter=false should trigger ZPL1402: {:?}",
        vr.issues,
    );
}

#[test]
fn printer_gate_enum_value_skips_ungated_value() {
    let tables = &*common::TABLES;
    let profile = common::profile_from_json(
        r#"{"id":"test","schema_version":"1.0.0","dpi":203,"features":{"cutter":false}}"#,
    );
    let ast = parse_with_tables("^XA^MMT^XZ", Some(tables));
    let vr = validate_with_profile(&ast.ast, tables, Some(&profile));
    assert!(
        !vr.issues.iter().any(|d| d.id == codes::PRINTER_GATE),
        "^MMT should not trigger ZPL1402 even with cutter=false: {:?}",
        vr.issues,
    );
}

#[test]
fn printer_gate_enum_value_skips_unknown_feature() {
    let tables = &*common::TABLES;
    // cutter is None (unknown) — should skip gate check
    let profile = common::profile_from_json(
        r#"{"id":"test","schema_version":"1.0.0","dpi":203,"features":{}}"#,
    );
    let ast = parse_with_tables("^XA^MMC^XZ", Some(tables));
    let vr = validate_with_profile(&ast.ast, tables, Some(&profile));
    assert!(
        !vr.issues.iter().any(|d| d.id == codes::PRINTER_GATE),
        "^MMC with cutter=None should NOT trigger ZPL1402: {:?}",
        vr.issues,
    );
}

// ─── Media Mode Validation (ZPL1403) ─────────────────────────────────────────

#[test]
fn media_mode_unsupported_mm() {
    let tables = &*common::TABLES;
    let profile = common::profile_from_json(
        r#"{"id":"test","schema_version":"1.0.0","dpi":203,"media":{"supported_modes":["T"]}}"#,
    );
    // "C" (cutter) not in supported_modes ["T"]
    let ast = parse_with_tables("^XA^MMC^XZ", Some(tables));
    let vr = validate_with_profile(&ast.ast, tables, Some(&profile));
    assert!(
        vr.issues
            .iter()
            .any(|d| d.id == codes::MEDIA_MODE_UNSUPPORTED),
        "^MMC should trigger ZPL1403 when C not in supported_modes: {:?}",
        vr.issues,
    );
}

#[test]
fn media_mode_supported_mm() {
    let tables = &*common::TABLES;
    let profile = common::profile_from_json(
        r#"{"id":"test","schema_version":"1.0.0","dpi":203,"media":{"supported_modes":["T"]}}"#,
    );
    let ast = parse_with_tables("^XA^MMT^XZ", Some(tables));
    let vr = validate_with_profile(&ast.ast, tables, Some(&profile));
    assert!(
        !vr.issues
            .iter()
            .any(|d| d.id == codes::MEDIA_MODE_UNSUPPORTED),
        "^MMT should not trigger ZPL1403 when T in supported_modes: {:?}",
        vr.issues,
    );
}

#[test]
fn media_tracking_unsupported_mn() {
    let tables = &*common::TABLES;
    let profile = common::profile_from_json(
        r#"{"id":"test","schema_version":"1.0.0","dpi":203,"media":{"supported_tracking":["N","Y"]}}"#,
    );
    let ast = parse_with_tables("^XA^MNM^XZ", Some(tables));
    let vr = validate_with_profile(&ast.ast, tables, Some(&profile));
    assert!(
        vr.issues
            .iter()
            .any(|d| d.id == codes::MEDIA_MODE_UNSUPPORTED),
        "^MNM should trigger ZPL1403 when M not in supported_tracking: {:?}",
        vr.issues,
    );
}

#[test]
fn media_print_method_conflict_mt() {
    let tables = &*common::TABLES;
    let profile = common::profile_from_json(
        r#"{"id":"test","schema_version":"1.0.0","dpi":203,"media":{"print_method":"direct_thermal"}}"#,
    );
    // T = thermal transfer, but profile is direct_thermal only
    let ast = parse_with_tables("^XA^MTT^XZ", Some(tables));
    let vr = validate_with_profile(&ast.ast, tables, Some(&profile));
    assert!(
        vr.issues
            .iter()
            .any(|d| d.id == codes::MEDIA_MODE_UNSUPPORTED),
        "^MTT should trigger ZPL1403 when profile is direct_thermal: {:?}",
        vr.issues,
    );
}

#[test]
fn media_print_method_both_allows_all() {
    let tables = &*common::TABLES;
    let profile = common::profile_from_json(
        r#"{"id":"test","schema_version":"1.0.0","dpi":203,"media":{"print_method":"both"}}"#,
    );
    let ast = parse_with_tables("^XA^MTT^XZ", Some(tables));
    let vr = validate_with_profile(&ast.ast, tables, Some(&profile));
    assert!(
        !vr.issues
            .iter()
            .any(|d| d.id == codes::MEDIA_MODE_UNSUPPORTED),
        "^MTT should not trigger ZPL1403 when print_method is Both: {:?}",
        vr.issues,
    );
}

#[test]
fn media_no_profile_media_skips() {
    let tables = &*common::TABLES;
    let profile = common::profile_from_json(r#"{"id":"test","schema_version":"1.0.0","dpi":203}"#);
    let ast = parse_with_tables("^XA^MMC^XZ", Some(tables));
    let vr = validate_with_profile(&ast.ast, tables, Some(&profile));
    assert!(
        !vr.issues
            .iter()
            .any(|d| d.id == codes::MEDIA_MODE_UNSUPPORTED),
        "no profile media should skip ZPL1403: {:?}",
        vr.issues,
    );
}

// ─── defaultByDpi Loading ────────────────────────────────────────────────────

#[test]
fn default_by_dpi_loaded_in_spec_tables() {
    let tables = &*common::TABLES;
    // ^BQ should have defaultByDpi on its magnification arg
    let bq = tables
        .cmd_by_code("^BQ")
        .expect("^BQ should exist in tables");
    let args = bq.args.as_ref().expect("^BQ should have args");
    let mag_arg = args
        .iter()
        .filter_map(|au| match au {
            zpl_toolchain_spec_tables::ArgUnion::Single(a) => Some(a.as_ref()),
            zpl_toolchain_spec_tables::ArgUnion::OneOf { one_of } => one_of
                .iter()
                .find(|a| a.name.as_deref() == Some("magnification_factor")),
        })
        .find(|a| a.name.as_deref() == Some("magnification_factor"))
        .expect("^BQ should have magnification_factor arg");
    assert!(
        mag_arg.default_by_dpi.is_some(),
        "^BQ.magnification_factor should have defaultByDpi"
    );
    let dpi_map = mag_arg.default_by_dpi.as_ref().unwrap();
    assert_eq!(dpi_map.get("203").and_then(|v| v.as_i64()), Some(2));
    assert_eq!(dpi_map.get("300").and_then(|v| v.as_i64()), Some(3));
    assert_eq!(dpi_map.get("600").and_then(|v| v.as_i64()), Some(6));
}

// ─── Diagnostic Structured Context ───────────────────────────────────────────

#[test]
fn context_arity() {
    let tables = &*common::TABLES;
    // ^PW has arity 1 — give it 3 args
    let ast = parse_with_tables("^XA^PW100,200,300^XZ", Some(tables));
    let vr = validate_with_profile(&ast.ast, tables, None);
    let d = find_diag(&vr.issues, codes::ARITY);
    let ctx = d
        .context
        .as_ref()
        .expect("arity diagnostic should have context");
    assert_eq!(ctx.get("command").unwrap(), "^PW");
    assert_eq!(ctx.get("arity").unwrap(), "1");
    assert_eq!(ctx.get("actual").unwrap(), "3");
}

#[test]
fn context_out_of_range() {
    let tables = &*common::TABLES;
    // ^PW range is typically [1, 32000] — give it 0
    let ast = parse_with_tables("^XA^PW0^XZ", Some(tables));
    let vr = validate_with_profile(&ast.ast, tables, None);
    let d = find_diag(&vr.issues, codes::OUT_OF_RANGE);
    let ctx = d
        .context
        .as_ref()
        .expect("out_of_range diagnostic should have context");
    assert_eq!(ctx.get("command").unwrap(), "^PW");
    assert!(ctx.contains_key("min"), "should have min key");
    assert!(ctx.contains_key("max"), "should have max key");
    assert_eq!(ctx.get("value").unwrap(), "0");
}

#[test]
fn context_invalid_enum() {
    let tables = &*common::TABLES;
    // ^BC orientation (arg 0) must be N/R/I/B; give it X
    let ast = parse_with_tables("^XA^BY2^BCX^FDtest^FS^XZ", Some(tables));
    let vr = validate_with_profile(&ast.ast, tables, None);
    let d = find_diag(&vr.issues, codes::INVALID_ENUM);
    let ctx = d
        .context
        .as_ref()
        .expect("invalid_enum diagnostic should have context");
    assert_eq!(ctx.get("command").unwrap(), "^BC");
    assert_eq!(ctx.get("value").unwrap(), "X");
    assert!(ctx.contains_key("arg"), "should have arg key");
}

#[test]
fn context_profile_constraint() {
    let tables = &*common::TABLES;
    let profile = common::profile_from_json(
        r#"{"id":"test","schema_version":"1.0.0","dpi":203,"page":{"width_dots":100}}"#,
    );
    let ast = parse_with_tables("^XA^PW200^XZ", Some(tables));
    let vr = validate_with_profile(&ast.ast, tables, Some(&profile));
    let d = find_diag(&vr.issues, codes::PROFILE_CONSTRAINT);
    let ctx = d
        .context
        .as_ref()
        .expect("profile_constraint diagnostic should have context");
    assert_eq!(ctx.get("command").unwrap(), "^PW");
    assert!(ctx.contains_key("field"), "should have field key");
    assert!(ctx.contains_key("op"), "should have op key");
    assert!(ctx.contains_key("limit"), "should have limit key");
    assert!(ctx.contains_key("actual"), "should have actual key");
}

#[test]
fn context_printer_gate_command_level() {
    let tables = &*common::TABLES;
    let profile = common::profile_from_json(
        r#"{"id":"test","schema_version":"1.0.0","dpi":203,"features":{"rfid":false}}"#,
    );
    // ^RF requires rfid gate
    let ast = parse_with_tables("^XA^RF^XZ", Some(tables));
    let vr = validate_with_profile(&ast.ast, tables, Some(&profile));
    let d = find_diag(&vr.issues, codes::PRINTER_GATE);
    let ctx = d
        .context
        .as_ref()
        .expect("printer_gate diagnostic should have context");
    assert_eq!(ctx.get("command").unwrap(), "^RF");
    assert_eq!(ctx.get("gate").unwrap(), "rfid");
    assert_eq!(ctx.get("level").unwrap(), "command");
    assert!(ctx.contains_key("profile"), "should have profile key");
}

#[test]
fn context_media_mode_unsupported() {
    let tables = &*common::TABLES;
    let profile = common::profile_from_json(
        r#"{"id":"test","schema_version":"1.0.0","dpi":203,"media":{"supported_modes":["T"]}}"#,
    );
    let ast = parse_with_tables("^XA^MMC^XZ", Some(tables));
    let vr = validate_with_profile(&ast.ast, tables, Some(&profile));
    let d = find_diag(&vr.issues, codes::MEDIA_MODE_UNSUPPORTED);
    let ctx = d
        .context
        .as_ref()
        .expect("media_mode diagnostic should have context");
    assert_eq!(ctx.get("command").unwrap(), "^MM");
    assert_eq!(ctx.get("kind").unwrap(), "mode");
    assert_eq!(ctx.get("value").unwrap(), "C");
    assert!(ctx.contains_key("supported"), "should have supported key");
    assert!(ctx.contains_key("profile"), "should have profile key");
}

#[test]
fn context_structural_field_data_without_origin() {
    let tables = &*common::TABLES;
    let ast = parse_with_tables("^XA^FDHello^FS^XZ", Some(tables));
    let vr = validate_with_profile(&ast.ast, tables, None);
    let d = find_diag(&vr.issues, codes::FIELD_DATA_WITHOUT_ORIGIN);
    let ctx = d
        .context
        .as_ref()
        .expect("structural diagnostic should have context");
    assert_eq!(ctx.get("command").unwrap(), "^FD");
}

#[test]
fn context_empty_label_has_no_context() {
    let tables = &*common::TABLES;
    let ast = parse_with_tables("^XA^XZ", Some(tables));
    let vr = validate_with_profile(&ast.ast, tables, None);
    let d = find_diag(&vr.issues, codes::EMPTY_LABEL);
    assert!(
        d.context.is_none(),
        "empty label diagnostic should have no context (self-explanatory)"
    );
}

#[test]
fn context_host_command_in_label() {
    let tables = &*common::TABLES;
    let ast = parse_with_tables("^XA~TA000^XZ", Some(tables));
    let vr = validate_with_profile(&ast.ast, tables, None);
    let d = find_diag(&vr.issues, codes::HOST_COMMAND_IN_LABEL);
    let ctx = d
        .context
        .as_ref()
        .expect("host_command_in_label diagnostic should have context");
    assert_eq!(ctx.get("command").unwrap(), "~TA");
    assert!(ctx.contains_key("plane"), "should have plane key");
}

// ─── requires_field enforcement ──────────────────────────────────────────────

#[test]
fn requires_field_fh_outside_field_emits_warning() {
    let tables = &*common::TABLES;
    // ^FH outside a field (no preceding ^FO) should trigger ZPL2201
    let result = parse_with_tables("^XA^FH^FDHello^FS^XZ", Some(tables));
    let vr = validate::validate(&result.ast, tables);
    assert!(
        vr.issues
            .iter()
            .any(|d| d.id == codes::FIELD_DATA_WITHOUT_ORIGIN && d.message.contains("^FH")),
        "^FH outside field should emit ZPL2201: {:?}",
        vr.issues,
    );
}

#[test]
fn requires_field_fh_inside_field_passes() {
    let tables = &*common::TABLES;
    // ^FH inside a field (after ^FO) should NOT trigger ZPL2201
    let result = parse_with_tables("^XA^FO10,10^FH^FDHello^FS^XZ", Some(tables));
    let vr = validate::validate(&result.ast, tables);
    assert!(
        !vr.issues
            .iter()
            .any(|d| d.id == codes::FIELD_DATA_WITHOUT_ORIGIN && d.message.contains("^FH")),
        "^FH inside field should not emit ZPL2201: {:?}",
        vr.issues,
    );
}

#[test]
fn requires_field_fr_outside_field_emits_warning() {
    let tables = &*common::TABLES;
    // ^FR outside a field should trigger ZPL2201
    let result = parse_with_tables("^XA^FR^FO10,10^FDHello^FS^XZ", Some(tables));
    let vr = validate::validate(&result.ast, tables);
    assert!(
        vr.issues
            .iter()
            .any(|d| d.id == codes::FIELD_DATA_WITHOUT_ORIGIN && d.message.contains("^FR")),
        "^FR outside field should emit ZPL2201: {:?}",
        vr.issues,
    );
}

#[test]
fn requires_field_fr_inside_field_passes() {
    let tables = &*common::TABLES;
    // ^FR inside a field (after ^FO) should NOT trigger ZPL2201
    let result = parse_with_tables("^XA^FO10,10^FR^FDHello^FS^XZ", Some(tables));
    let vr = validate::validate(&result.ast, tables);
    assert!(
        !vr.issues
            .iter()
            .any(|d| d.id == codes::FIELD_DATA_WITHOUT_ORIGIN && d.message.contains("^FR")),
        "^FR inside field should not emit ZPL2201: {:?}",
        vr.issues,
    );
}

#[test]
fn requires_field_sn_outside_field_emits_warning() {
    let tables = &*common::TABLES;
    // ^SN outside a field should trigger ZPL2201
    let result = parse_with_tables("^XA^SN001^XZ", Some(tables));
    let vr = validate::validate(&result.ast, tables);
    assert!(
        vr.issues
            .iter()
            .any(|d| d.id == codes::FIELD_DATA_WITHOUT_ORIGIN && d.message.contains("^SN")),
        "^SN outside field should emit ZPL2201: {:?}",
        vr.issues,
    );
}

#[test]
fn requires_field_sf_outside_field_emits_warning() {
    let tables = &*common::TABLES;
    // ^SF outside a field should trigger ZPL2201
    let result = parse_with_tables("^XA^SFD^XZ", Some(tables));
    let vr = validate::validate(&result.ast, tables);
    assert!(
        vr.issues
            .iter()
            .any(|d| d.id == codes::FIELD_DATA_WITHOUT_ORIGIN && d.message.contains("^SF")),
        "^SF outside field should emit ZPL2201: {:?}",
        vr.issues,
    );
}

#[test]
fn requires_field_sn_sf_inside_field_passes() {
    let tables = &*common::TABLES;
    // ^SN/^SF inside a field should NOT trigger ZPL2201
    let result = parse_with_tables("^XA^FO10,10^FN1^SN001^SF%d^FDStart^FS^XZ", Some(tables));
    let vr = validate::validate(&result.ast, tables);
    assert!(
        !vr.issues
            .iter()
            .any(|d| d.id == codes::FIELD_DATA_WITHOUT_ORIGIN
                && (d.message.contains("^SN") || d.message.contains("^SF"))),
        "^SN/^SF inside field should not emit ZPL2201: {:?}",
        vr.issues,
    );
}

// ─── ^MU Unit Conversion ────────────────────────────────────────────────────

#[test]
fn mu_units_inches_conversion() {
    let tables = &*common::TABLES;
    // Profile with DPI 203. ^MUI sets inches.
    // ^A height=5 in inches → 5*203=1015 dots, within [10,32000] — should pass.
    let profile = common::profile_from_json(r#"{"id":"test","schema_version":"1.0.0","dpi":203}"#);
    let ast = parse_with_tables("^XA^MUI^FO10,10^AA,N,5^FDtest^FS^XZ", Some(tables));
    let vr = validate_with_profile(&ast.ast, tables, Some(&profile));
    assert!(
        !vr.issues
            .iter()
            .any(|d| d.id == codes::OUT_OF_RANGE && d.message.contains("^A")),
        "^A height=5 inches (1015 dots) should be in range with ^MUI: {:?}",
        vr.issues,
    );
}

#[test]
fn mu_units_mm_conversion() {
    let tables = &*common::TABLES;
    // Profile with DPI 203. ^MUM sets millimeters.
    // ^A height=2 in mm → 2*203/25.4 ≈ 15.98 dots, within [10,32000] — should pass.
    // ^A height=1 in mm → 1*203/25.4 ≈ 7.99 dots, below 10 — should fail.
    let profile = common::profile_from_json(r#"{"id":"test","schema_version":"1.0.0","dpi":203}"#);

    // 2mm should pass
    let ast = parse_with_tables("^XA^MUM^FO10,10^AA,N,2^FDtest^FS^XZ", Some(tables));
    let vr = validate_with_profile(&ast.ast, tables, Some(&profile));
    assert!(
        !vr.issues
            .iter()
            .any(|d| d.id == codes::OUT_OF_RANGE && d.message.contains("^A")),
        "^A height=2 mm (~16 dots) should be in range with ^MUM: {:?}",
        vr.issues,
    );

    // 1mm should fail (≈8 dots, below min 10)
    let ast2 = parse_with_tables("^XA^MUM^FO10,10^AA,N,1^FDtest^FS^XZ", Some(tables));
    let vr2 = validate_with_profile(&ast2.ast, tables, Some(&profile));
    assert!(
        vr2.issues
            .iter()
            .any(|d| d.id == codes::OUT_OF_RANGE && d.message.contains("^A")),
        "^A height=1 mm (~8 dots) should be out of range with ^MUM: {:?}",
        vr2.issues,
    );
}

#[test]
fn mu_units_dots_default() {
    let tables = &*common::TABLES;
    // No ^MU — default is dots. ^A height=5 is below [10,32000] — should flag.
    let ast = parse_with_tables("^XA^FO10,10^AA,N,5^FDtest^FS^XZ", Some(tables));
    let vr = validate_with_profile(&ast.ast, tables, None);
    assert!(
        vr.issues
            .iter()
            .any(|d| d.id == codes::OUT_OF_RANGE && d.message.contains("^A")),
        "^A height=5 dots should be out of range without ^MU: {:?}",
        vr.issues,
    );

    // ^A height=100 should be within range
    let ast2 = parse_with_tables("^XA^FO10,10^AA,N,100^FDtest^FS^XZ", Some(tables));
    let vr2 = validate_with_profile(&ast2.ast, tables, None);
    assert!(
        !vr2.issues
            .iter()
            .any(|d| d.id == codes::OUT_OF_RANGE && d.message.contains("^A")),
        "^A height=100 dots should be in range without ^MU: {:?}",
        vr2.issues,
    );
}

// ─── Diagnostic ID Compile-Time Safety ───────────────────────────────────────

/// Verify that all diagnostic codes used in the validator have corresponding
/// explain() entries in the diagnostics crate. This catches typos in diagnostic IDs.
#[test]
fn all_diagnostic_ids_have_explanations() {
    use zpl_toolchain_diagnostics::explain;

    // All diagnostic codes used in the validator and parser.
    // Keep this list in sync when adding new codes.
    let validator_codes = [
        codes::ARITY,
        codes::INVALID_ENUM,
        codes::EMPTY_FIELD_DATA,
        codes::STRING_TOO_SHORT,
        codes::STRING_TOO_LONG,
        codes::EXPECTED_INTEGER,
        codes::EXPECTED_NUMERIC,
        codes::EXPECTED_CHAR,
        codes::OUT_OF_RANGE,
        codes::ROUNDING_VIOLATION,
        codes::PROFILE_CONSTRAINT,
        codes::PRINTER_GATE,
        codes::MEDIA_MODE_UNSUPPORTED,
        codes::REQUIRED_MISSING,
        codes::REQUIRED_EMPTY,
        codes::REQUIRED_COMMAND,
        codes::INCOMPATIBLE_COMMAND,
        codes::ORDER_BEFORE,
        codes::ORDER_AFTER,
        codes::FIELD_DATA_WITHOUT_ORIGIN,
        codes::EMPTY_LABEL,
        codes::FIELD_NOT_CLOSED,
        codes::ORPHANED_FIELD_SEPARATOR,
        codes::HOST_COMMAND_IN_LABEL,
        codes::DUPLICATE_FIELD_NUMBER,
        codes::POSITION_OUT_OF_BOUNDS,
        codes::UNKNOWN_FONT,
        codes::INVALID_HEX_ESCAPE,
        codes::REDUNDANT_STATE,
        codes::SERIALIZATION_WITHOUT_FIELD_NUMBER,
        codes::GF_DATA_LENGTH_MISMATCH,
        codes::GF_BOUNDS_OVERFLOW,
        codes::GF_MEMORY_EXCEEDED,
        codes::MISSING_EXPLICIT_DIMENSIONS,
        codes::BARCODE_INVALID_CHAR,
        codes::BARCODE_DATA_LENGTH,
        codes::NOTE,
    ];

    let parser_codes = [
        codes::PARSER_NO_LABELS,
        codes::PARSER_INVALID_COMMAND,
        codes::PARSER_UNKNOWN_COMMAND,
        codes::PARSER_MISSING_TERMINATOR,
        codes::PARSER_MISSING_FIELD_SEPARATOR,
        codes::PARSER_FIELD_DATA_INTERRUPTED,
        codes::PARSER_STRAY_CONTENT,
        codes::PARSER_NON_ASCII_ARG,
    ];

    let mut missing = Vec::new();
    for code in validator_codes.iter().chain(parser_codes.iter()) {
        if explain(code).is_none() {
            missing.push(*code);
        }
    }

    assert!(
        missing.is_empty(),
        "Diagnostic codes without explain() entries: {:?}",
        missing
    );
}

// ─── Untested Diagnostic Code Comments ───────────────────────────────────────
//
// ZPL1105 (string too short): No spec commands currently define a `minLength`
// constraint on any argument, so this diagnostic code path cannot be triggered
// with real ZPL. The validator code exists in validate/mod.rs and checks
// spec_arg.min_length. Test deferred until a spec command adds a minLength
// constraint.
//
// ZPL1106 (string too long): No spec commands currently define a `maxLength`
// constraint on any argument, so this diagnostic code path cannot be triggered
// with real ZPL. The validator code exists in validate/mod.rs and checks
// spec_arg.max_length. Test deferred until a spec command adds a maxLength
// constraint.
//
// ZPL2102 (incompatible commands): No spec commands currently use the
// "incompatible" constraint kind, so this diagnostic cannot be triggered.
// The validator code exists in validate/mod.rs (ConstraintKind::Incompatible).
// Test deferred until a spec command adds an incompatible constraint.
//
// ZPL2104 (ordering after:): All order constraints in spec files use "before:"
// prefix exclusively; none use "after:". The validator code handles "after:"
// expressions in validate/mod.rs, but no spec command triggers it today.
// Test deferred until a spec command adds an "after:" order constraint.
//
// NOTE: ComparisonOp coverage gap — only `lte` is used in current specs (^PW, ^LL).
// Tests for Gte, Lt, Gt, Eq operators cannot be exercised without spec commands that
// use those operators. This will be addressed when new specs use other operators.