toml-spanner 1.0.0

High Performance Toml parser and deserializer that preserves span information with fast compile times.
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
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
use crate::ErrorKind;
use crate::Span;
use crate::Table;

macro_rules! is_number_error {
    ($kind:expr) => {
        matches!(
            $kind,
            ErrorKind::InvalidInteger(_)
                | ErrorKind::InvalidFloat(_)
                | ErrorKind::InvalidDateTime(_)
        )
    };
}

struct TestCtx {
    arena: crate::arena::Arena,
}

impl TestCtx {
    fn new() -> Self {
        Self {
            arena: crate::arena::Arena::new(),
        }
    }

    fn parse_ok<'a>(&'a self, input: &'a str) -> Table<'a> {
        crate::parser::parse(input, &self.arena)
            .unwrap_or_else(|e| panic!("parse failed for {input:?}: {e}"))
            .into_table()
    }

    fn parse_err<'a>(&'a self, input: &'a str) -> crate::Error {
        match crate::parser::parse(input, &self.arena) {
            Ok(_) => panic!("For input `{input}` expected error but parsed successfully"),
            Err(err) => err,
        }
    }
}

#[test]
fn basic_scalar_values() {
    let ctx = TestCtx::new();

    // empty document
    let v = ctx.parse_ok("");
    assert!(v.is_empty());

    // string
    let v = ctx.parse_ok("a = \"hello\"");
    assert_eq!(v["a"].as_str(), Some("hello"));

    // integer
    let v = ctx.parse_ok("a = 42");
    assert_eq!(v["a"].as_i64(), Some(42));

    // negative integer
    let v = ctx.parse_ok("a = -100");
    assert_eq!(v["a"].as_i64(), Some(-100));

    // float
    let v = ctx.parse_ok("a = 3.15");
    let f = v["a"].as_f64().unwrap();
    assert!((f - 3.15).abs() < f64::EPSILON);

    // booleans
    let v = ctx.parse_ok("a = true");
    assert_eq!(v["a"].as_bool(), Some(true));
    let v = ctx.parse_ok("a = false");
    assert_eq!(v["a"].as_bool(), Some(false));

    // multiple keys
    let v = ctx.parse_ok("a = 1\nb = 2\nc = 3");
    assert_eq!(v.len(), 3);
    assert_eq!(v["a"].as_i64(), Some(1));
    assert_eq!(v["c"].as_i64(), Some(3));
}

#[test]
fn string_escapes() {
    let ctx = TestCtx::new();

    let cases = [
        (r#"a = "line1\nline2""#, "line1\nline2"),
        (r#"a = "col1\tcol2""#, "col1\tcol2"),
        (r#"a = "path\\to""#, "path\\to"),
        (r#"a = "say \"hi\"""#, "say \"hi\""),
        (r#"a = "\u0041""#, "A"),
        (r#"a = "\U00000041""#, "A"),
    ];

    for (input, expected) in cases {
        let v = ctx.parse_ok(input);
        assert_eq!(v["a"].as_str(), Some(expected), "input: {input}");
    }
}

#[test]
fn string_types() {
    let ctx = TestCtx::new();

    let cases = [
        ("a = \"\"\"\nhello\nworld\"\"\"", "hello\nworld"),
        ("a = '''\nhello\nworld'''", "hello\nworld"),
        (r#"a = 'no\escape'"#, "no\\escape"),
        (r#"a = """#, ""),
    ];

    for (input, expected) in cases {
        let v = ctx.parse_ok(input);
        assert_eq!(v["a"].as_str(), Some(expected), "input: {input}");
    }
}

#[test]
fn number_formats() {
    let ctx = TestCtx::new();

    let int_cases = [
        ("a = 0xDEAD", 0xDEAD),
        ("a = 0o777", 0o777),
        ("a = 0b1010", 0b1010),
        ("a = 1_000_000", 1_000_000),
    ];

    for (input, expected) in int_cases {
        let v = ctx.parse_ok(input);
        assert_eq!(v["a"].as_i64(), Some(expected), "input: {input}");
    }

    let float_cases = [
        ("a = inf", f64::INFINITY, false),
        ("a = -inf", f64::NEG_INFINITY, false),
        ("a = nan", f64::NAN, true),
        ("a = -nan", f64::NAN, true),
    ];

    for (input, expected, is_nan) in float_cases {
        let v = ctx.parse_ok(input);
        let f = v["a"].as_f64().unwrap();
        if is_nan {
            assert!(f.is_nan(), "input: {input}");
        } else {
            assert_eq!(f, expected, "input: {input}");
        }
    }

    let float_approx_cases = [
        ("a = 1e10", 1e10, 1.0),
        ("a = 1.5E-3", 1.5e-3, 1e-10),
        ("a = 1_000.5", 1000.5, f64::EPSILON),
    ];

    for (input, expected, epsilon) in float_approx_cases {
        let v = ctx.parse_ok(input);
        let f = v["a"].as_f64().unwrap();
        assert!((f - expected).abs() < epsilon, "input: {input}");
    }
}

#[test]
fn arrays() {
    let ctx = TestCtx::new();

    let v = ctx.parse_ok("a = [1, 2, 3]");
    assert_eq!(v["a"].as_array().unwrap().len(), 3);
    assert_eq!(v["a"][0].as_i64(), Some(1));
    assert_eq!(v["a"][2].as_i64(), Some(3));

    // empty
    let v = ctx.parse_ok("a = []");
    assert!(v["a"].as_array().unwrap().is_empty());

    // nested
    let v = ctx.parse_ok("a = [[1, 2], [3, 4]]");
    assert_eq!(v["a"].as_array().unwrap().len(), 2);
    assert_eq!(v["a"][0].as_array().unwrap().len(), 2);
}

#[test]
fn split_keys_error() {
    let ctx = TestCtx::new();

    ctx.parse_err("a.\nb = 1");
    ctx.parse_err("a\n.b = 1");
    ctx.parse_err("a\n.\nb = 1");
    ctx.parse_err("[a\n.\nb]\nc = 1");
    ctx.parse_err("[a\n.b]\nc = 1");
    ctx.parse_err("[a.\nb]\nc = 1");
    ctx.parse_err("a={a\n.b=1}");
    ctx.parse_err("a={a.\nb=1}");
    ctx.parse_err("a={a\n.\nb=1}");
}

#[test]
fn inline_tables() {
    let ctx = TestCtx::new();

    let v = ctx.parse_ok("a = {x = 1, y = 2}");
    assert_eq!(v["a"].as_table().unwrap().len(), 2);
    assert_eq!(v["a"]["x"].as_i64(), Some(1));
    assert_eq!(v["a"]["y"].as_i64(), Some(2));

    // empty
    let v = ctx.parse_ok("a = {}");
    assert!(v["a"].as_table().unwrap().is_empty());

    // nested
    let v = ctx.parse_ok("a = {b = {c = 1}}");
    assert_eq!(v["a"]["b"]["c"].as_i64(), Some(1));

    // array of inline tables
    let v = ctx.parse_ok("a = [{x = 1}, {x = 2}]");
    assert_eq!(v["a"].as_array().unwrap().len(), 2);
    assert_eq!(v["a"][0]["x"].as_i64(), Some(1));
}

#[test]
fn table_headers_and_structure() {
    let ctx = TestCtx::new();

    // simple header
    let v = ctx.parse_ok("[table]\nkey = 1");
    assert_eq!(v["table"]["key"].as_i64(), Some(1));

    // multiple headers
    let v = ctx.parse_ok("[a]\nx = 1\n[b]\ny = 2");
    assert_eq!(v["a"]["x"].as_i64(), Some(1));
    assert_eq!(v["b"]["y"].as_i64(), Some(2));

    // dotted header
    let v = ctx.parse_ok("[a.b.c]\nkey = 1");
    assert_eq!(v["a"]["b"]["c"]["key"].as_i64(), Some(1));

    // dotted key-value
    let v = ctx.parse_ok("a.b.c = 1");
    assert_eq!(v["a"]["b"]["c"].as_i64(), Some(1));

    // dotted key multiple
    let v = ctx.parse_ok("a.x = 1\na.y = 2");
    assert_eq!(v["a"]["x"].as_i64(), Some(1));
    assert_eq!(v["a"]["y"].as_i64(), Some(2));

    // array of tables
    let v = ctx.parse_ok("[[items]]\nname = \"a\"\n[[items]]\nname = \"b\"");
    assert_eq!(v["items"].as_array().unwrap().len(), 2);
    assert_eq!(v["items"][0]["name"].as_str(), Some("a"));
    assert_eq!(v["items"][1]["name"].as_str(), Some("b"));

    // array of tables with subtable
    let v = ctx.parse_ok("[[fruit]]\nname = \"apple\"\n[fruit.physical]\ncolor = \"red\"");
    assert_eq!(v["fruit"][0]["name"].as_str(), Some("apple"));
    assert_eq!(v["fruit"][0]["physical"]["color"].as_str(), Some("red"));

    // implicit table via header
    let v = ctx.parse_ok("[a.b]\nx = 1\n[a]\ny = 2");
    assert_eq!(v["a"]["y"].as_i64(), Some(2));
    assert_eq!(v["a"]["b"]["x"].as_i64(), Some(1));
}

#[test]
fn table_indexing_thresholds() {
    let ctx = TestCtx::new();

    // 5 keys — linear scan
    let v = ctx.parse_ok("a = 1\nb = 2\nc = 3\nd = 4\ne = 5");
    assert_eq!(v.len(), 5);
    assert_eq!(v["e"].as_i64(), Some(5));

    // 6 keys — bulk index
    let v = ctx.parse_ok("a = 1\nb = 2\nc = 3\nd = 4\ne = 5\nf = 6");
    assert_eq!(v.len(), 6);
    assert_eq!(v["a"].as_i64(), Some(1));
    assert_eq!(v["f"].as_i64(), Some(6));

    // 7 keys — incremental index
    let v = ctx.parse_ok("a = 1\nb = 2\nc = 3\nd = 4\ne = 5\nf = 6\ng = 7");
    assert_eq!(v.len(), 7);
    assert_eq!(v["g"].as_i64(), Some(7));

    // 20 keys
    let mut lines = Vec::new();
    for i in 0..20 {
        lines.push(format!("key{i} = {i}"));
    }
    let input = lines.join("\n");
    let v = ctx.parse_ok(&input);
    assert_eq!(v.len(), 20);
    assert_eq!(v["key0"].as_i64(), Some(0));
    assert_eq!(v["key19"].as_i64(), Some(19));

    // subtable crossing threshold
    let mut lines = vec!["[sub]".to_string()];
    for i in 0..6 {
        lines.push(format!("k{i} = {i}"));
    }
    let input = lines.join("\n");
    let v = ctx.parse_ok(&input);
    assert_eq!(v["sub"].as_table().unwrap().len(), 6);
    assert_eq!(v["sub"]["k5"].as_i64(), Some(5));
}

#[test]
fn parse_errors() {
    let ctx = TestCtx::new();

    let e = ctx.parse_err("a = 1\na = 2");
    assert!(matches!(e.kind(), ErrorKind::DuplicateKey { .. }));

    let e = ctx.parse_err("a = \"unterminated");
    assert!(matches!(e.kind(), ErrorKind::UnterminatedString('"')));

    let e = ctx.parse_err(r#"a = "\z""#);
    assert!(matches!(e.kind(), ErrorKind::InvalidEscape('z')));

    let e = ctx.parse_err("[t]\na = 1\n[t]\nb = 2");
    assert!(matches!(e.kind(), ErrorKind::DuplicateTable { .. }));

    let e = ctx.parse_err("a = ");
    assert!(matches!(e.kind(), ErrorKind::UnexpectedEof));

    let e = ctx.parse_err("a = 0x");
    assert!(is_number_error!(e.kind()));

    let e = ctx.parse_err("a = 1\n[a]\nb = 2");
    assert!(matches!(
        e.kind(),
        ErrorKind::DuplicateTable { .. } | ErrorKind::DuplicateKey { .. }
    ));

    let e = ctx.parse_err("a = {x = 1}\n[a]\ny = 2");
    assert!(matches!(
        e.kind(),
        ErrorKind::DuplicateTable { .. } | ErrorKind::DuplicateKey { .. }
    ));
}

#[test]
fn error_span_in_range() {
    let ctx = TestCtx::new();

    let cases = [
        "a = 0.",
        "a = 0.e",
        "a = 0.E",
        "a = 0.0E",
        "a = 0.0e",
        "a = 0.0e-",
        "a = 0.0e+",
        "a = ",
        "key =",
    ];

    for input in cases {
        let e = ctx.parse_err(input);
        let span = e.span();
        assert!(
            (span.start as usize) <= input.len() && (span.end as usize) <= input.len(),
            "span {span:?} out of range for {input:?} (len {})",
            input.len()
        );
        assert!(
            span.start <= span.end,
            "inverted span {span:?} for {input:?}"
        );
    }
}

#[test]
fn quoted_keys_and_spans() {
    let ctx = TestCtx::new();

    // basic quoted key
    let v = ctx.parse_ok(r#""quoted key" = 1"#);
    assert_eq!(v["quoted key"].as_i64(), Some(1));

    // quoted key with escape
    let v = ctx.parse_ok(r#""key\nwith\nnewlines" = 1"#);
    assert_eq!(v["key\nwith\nnewlines"].as_i64(), Some(1));

    // literal quoted key
    let v = ctx.parse_ok("'literal key' = 1");
    assert_eq!(v["literal key"].as_i64(), Some(1));

    // span for integer value
    let input = "key = 42";
    let v = ctx.parse_ok(input);
    let span = v.get("key").unwrap().span_unchecked();
    assert_eq!(&input[span.start as usize..span.end as usize], "42");

    // span for string value (includes quotes)
    let input = "key = \"hello\"";
    let v = ctx.parse_ok(input);
    let span = v.get("key").unwrap().span_unchecked();
    assert_eq!(&input[span.start as usize..span.end as usize], "\"hello\"");
}

#[test]
fn comments_and_whitespace() {
    let ctx = TestCtx::new();

    let v = ctx.parse_ok("# comment\na = 1 # inline comment\n# another");
    assert_eq!(v["a"].as_i64(), Some(1));

    let v = ctx.parse_ok("\n\n\na = 1\n\n\n");
    assert_eq!(v["a"].as_i64(), Some(1));
}

#[test]
fn value_into_kind() {
    let ctx = TestCtx::new();
    let mut v = ctx.parse_ok("a = \"hello\"\nb = 42\nc = [1, 2]\nd = {x = 1}");

    let (_, a) = v.remove_entry("a").unwrap();
    assert_eq!(a.as_str().unwrap(), "hello");

    let (_, b) = v.remove_entry("b").unwrap();
    assert_eq!(b.as_i64().unwrap(), 42);

    let (_, c) = v.remove_entry("c").unwrap();
    assert_eq!(c.as_array().unwrap().len(), 2);

    let (_, d) = v.remove_entry("d").unwrap();
    assert_eq!(d.as_table().unwrap().len(), 1);
}

#[test]
fn recursion_depth_at_limit() {
    let depth = super::MAX_RECURSION_DEPTH as usize;
    let ctx = TestCtx::new();

    // Nested arrays: [[[...1...]]]
    let mut input = String::from("a = ");
    for _ in 0..depth {
        input.push('[');
    }
    input.push('1');
    for _ in 0..depth {
        input.push(']');
    }
    ctx.parse_ok(&input);

    // Nested inline tables: {b= {b= {b= ...1...}}}
    let mut input = String::from("a = ");
    for _ in 0..depth {
        input.push_str("{b= ");
    }
    input.push('1');
    for _ in 0..depth {
        input.push('}');
    }
    ctx.parse_ok(&input);

    // Mixed: [{b= [{b= ...1...}]}]
    let mut input = String::from("a = ");
    for _ in 0..depth / 2 {
        input.push_str("[{b= ");
    }
    input.push('1');
    for _ in 0..depth / 2 {
        input.push_str("}]");
    }
    ctx.parse_ok(&input);
}

#[test]
fn recursion_depth_over_limit() {
    let depth = super::MAX_RECURSION_DEPTH as usize;
    let ctx = TestCtx::new();

    // Nested arrays one past the limit
    let mut input = String::from("a = ");
    for _ in 0..=depth {
        input.push('[');
    }
    input.push('1');
    for _ in 0..=depth {
        input.push(']');
    }
    let e = ctx.parse_err(&input);
    assert!(matches!(
        e.kind(),
        ErrorKind::OutOfRange {
            ty: &"Max recursion depth exceeded",
            ..
        }
    ));

    // Nested inline tables one past the limit
    let mut input = String::from("a = ");
    for _ in 0..=depth {
        input.push_str("{b= ");
    }
    input.push('1');
    for _ in 0..=depth {
        input.push('}');
    }
    let e = ctx.parse_err(&input);
    assert!(matches!(
        e.kind(),
        ErrorKind::OutOfRange {
            ty: &"Max recursion depth exceeded",
            ..
        }
    ));

    // Mixed nesting one past the limit
    let mut input = String::from("a = ");
    for _ in 0..=depth / 2 {
        input.push_str("[{b= ");
    }
    input.push('1');
    for _ in 0..=depth / 2 {
        input.push_str("}]");
    }
    let e = ctx.parse_err(&input);
    assert!(matches!(
        e.kind(),
        ErrorKind::OutOfRange {
            ty: &"Max recursion depth exceeded",
            ..
        }
    ));
}

#[test]
fn mixed_content() {
    let ctx = TestCtx::new();
    let input = r#"
title = "TOML Example"
enabled = true
count = 100
ratio = 0.5

[database]
server = "192.168.1.1"
ports = [8001, 8001, 8002]
enabled = true

[servers.alpha]
ip = "10.0.0.1"

[servers.beta]
ip = "10.0.0.2"

[[products]]
name = "Hammer"
sku = 738594937

[[products]]
name = "Nail"
sku = 284758393
"#;
    let v = ctx.parse_ok(input);
    assert_eq!(v["title"].as_str(), Some("TOML Example"));
    assert_eq!(v["count"].as_i64(), Some(100));
    assert_eq!(v["database"]["ports"].as_array().unwrap().len(), 3);
    assert_eq!(v["servers"]["alpha"]["ip"].as_str(), Some("10.0.0.1"));
    assert_eq!(v["products"].as_array().unwrap().len(), 2);
    assert_eq!(v["products"][0]["name"].as_str(), Some("Hammer"));
}

#[test]
fn utf8_bom_is_skipped() {
    let ctx = TestCtx::new();

    // BOM-only input -> empty table
    let v = ctx.parse_ok("\u{FEFF}");
    assert!(v.is_empty());

    // BOM followed by key-value
    let v = ctx.parse_ok("\u{FEFF}a = 1");
    assert_eq!(v["a"].as_i64(), Some(1));

    // BOM followed by table header
    let v = ctx.parse_ok("\u{FEFF}[section]\nkey = \"val\"");
    assert_eq!(v["section"]["key"].as_str(), Some("val"));
}

#[test]
fn crlf_handling() {
    let ctx = TestCtx::new();

    let v = ctx.parse_ok("a = 1\r\nb = 2\r\n");
    assert_eq!(v["a"].as_i64(), Some(1), "input: a = 1\\r\\nb = 2\\r\\n");
    assert_eq!(v["b"].as_i64(), Some(2), "input: a = 1\\r\\nb = 2\\r\\n");

    let valid_str_cases = [
        ("a = \"\"\"\r\nhello\r\nworld\"\"\"", "hello\r\nworld"),
        ("a = \"\"\"\\\r\n   trimmed\"\"\"", "trimmed"),
        ("a = \"\"\"\\\n\r\n   trimmed\"\"\"", "trimmed"),
        ("a = \"\"\"\r\ncontent\"\"\"", "content"),
        ("a = \"\"\"\r\nline1\r\nline2\"\"\"", "line1\r\nline2"),
    ];

    for (input, expected) in valid_str_cases {
        let v = ctx.parse_ok(input);
        assert_eq!(v["a"].as_str(), Some(expected), "input: {input}");
    }

    let v = ctx.parse_ok("[table]\r\nkey = 1\r\n");
    assert_eq!(
        v["table"]["key"].as_i64(),
        Some(1),
        "input: [table]\\r\\nkey = 1\\r\\n"
    );

    let e = ctx.parse_err("a = \"hello\rworld\"");
    assert!(
        matches!(e.kind(), ErrorKind::InvalidCharInString('\r')),
        "input: a = \"hello\\rworld\""
    );

    let e = ctx.parse_err("a = \"hello\r\nworld\"");
    assert!(
        matches!(e.kind(), ErrorKind::UnterminatedString('"')),
        "input: a = \"hello\\r\\nworld\""
    );

    // Bare CR in array
    let e = ctx.parse_err("a = [ \r ]");
    assert!(
        matches!(e.kind(), ErrorKind::Unexpected('\r')),
        "bare CR in array: {:?}",
        e.kind(),
    );

    // Bare CR in inline table (hits read_table_key, reported as "a carriage return")
    let e = ctx.parse_err("a = { \r }");
    assert!(
        matches!(
            e.kind(),
            ErrorKind::Wanted {
                expected: &"a table key",
                found: &"a carriage return",
            }
        ),
        "bare CR in inline table: {:?}",
        e.kind(),
    );

    // Bare CR after key-value (via eat_newline_or_eof)
    let e = ctx.parse_err("a = 1\r");
    assert!(
        matches!(
            e.kind(),
            ErrorKind::Wanted {
                expected: &"newline",
                found: &"a carriage return",
            }
        ),
        "bare CR after key-value: {:?}",
        e.kind(),
    );

    // Bare CR after table header (via eat_newline_or_eof)
    let e = ctx.parse_err("[a]\r");
    assert!(
        matches!(
            e.kind(),
            ErrorKind::Wanted {
                expected: &"newline",
                found: &"a carriage return",
            }
        ),
        "bare CR after table header: {:?}",
        e.kind(),
    );
}

#[test]
fn escape_sequences() {
    let ctx = TestCtx::new();

    let valid_cases = [
        (r#"a = "\b\f""#, "\x08\x0C"),
        (r#"a = "\e""#, "\x1B"),
        (r#"a = "\x41""#, "A"),
        (r#"a = "\r""#, "\r"),
    ];

    for (input, expected) in valid_cases {
        let v = ctx.parse_ok(input);
        assert_eq!(v["a"].as_str(), Some(expected), "input: {input}");
    }

    let e = ctx.parse_err(r#"a = "\uGGGG""#);
    assert!(
        matches!(e.kind(), ErrorKind::InvalidHexEscape('G')),
        "input: a = \"\\uGGGG\""
    );

    let e = ctx.parse_err(r#"a = "\UFFFFFFFF""#);
    assert!(
        matches!(e.kind(), ErrorKind::InvalidEscapeValue(_)),
        "input: a = \"\\UFFFFFFFF\""
    );

    let e = ctx.parse_err("a = \"\\u00");
    assert!(
        matches!(e.kind(), ErrorKind::UnterminatedString('"')),
        "input: a = \"\\u00"
    );

    let e = ctx.parse_err(r#"a = "\xGG""#);
    assert!(
        matches!(e.kind(), ErrorKind::InvalidHexEscape('G')),
        "input: a = \"\\xGG\""
    );
}

#[test]
fn multiline_string_edge_cases() {
    let ctx = TestCtx::new();

    let valid_cases = [
        ("a = \"\"\"\\\n   trimmed\"\"\"", "trimmed"),
        ("a = \"\"\"\\  \n   trimmed\"\"\"", "trimmed"),
        ("a = \"\"\"\\\t\n   trimmed\"\"\"", "trimmed"),
        ("a = \"\"\"\\\r\n   trimmed\"\"\"", "trimmed"),
        ("a = \"\"\"\\\n\n\n   trimmed\"\"\"", "trimmed"),
        ("a = \"\"\"content\"\"\"\"\"", "content\"\""),
        ("a = \"\"\"content\"\"\"\"", "content\""),
        ("a = \"\"\"he said \"hi\" ok\"\"\"", "he said \"hi\" ok"),
        ("a = \"\"\"two \"\" here\"\"\"", "two \"\" here"),
    ];

    for (input, expected) in valid_cases {
        let v = ctx.parse_ok(input);
        assert_eq!(v["a"].as_str(), Some(expected), "input: {input}");
    }

    let e = ctx.parse_err("a = \"\"\"\\  x\"\"\"");
    assert!(
        matches!(e.kind(), ErrorKind::InvalidEscape(' ')),
        "input: a = \"\"\"\\  x\"\"\""
    );

    // Bare CR after line-ending backslash is invalid (only space/tab are
    // valid whitespace before the newline per the TOML ABNF: mlb-escaped-nl
    // = escape ws newline, where ws = *wschar and wschar = SP / HTAB).
    let e = ctx.parse_err("a = \"\"\"\\\r\r\n\"\"\"");
    assert!(
        matches!(e.kind(), ErrorKind::InvalidCharInString('\r')),
        "bare CR after line-ending backslash: {:?}",
        e.kind(),
    );
}

#[test]
fn number_valid_edge_cases() {
    let ctx = TestCtx::new();

    let int_cases = [
        ("a = 0xDEAD_BEEF", 0xDEAD_BEEF),
        ("a = 0o755", 0o755),
        ("a = 0b1111_0000", 0b1111_0000),
        ("a = +42", 42),
    ];

    for (input, expected) in int_cases {
        let v = ctx.parse_ok(input);
        assert_eq!(v["a"].as_i64(), Some(expected), "input: {input}");
    }

    let v = ctx.parse_ok("a = +3.15");
    let f = v["a"].as_f64().unwrap();
    assert!((f - 3.15).abs() < f64::EPSILON, "input: a = +3.15");

    let v = ctx.parse_ok("a = +inf");
    assert_eq!(v["a"].as_f64(), Some(f64::INFINITY), "input: a = +inf");

    let v = ctx.parse_ok("a = +nan");
    assert!(v["a"].as_f64().unwrap().is_nan(), "input: a = +nan");
}

#[test]
fn number_format_errors() {
    let ctx = TestCtx::new();

    let error_cases = [
        "a = +0xFF",
        "a = +",
        "a = 0o89",
        "a = 0b102",
        "a = 0x",
        "a = 0o",
        "a = 0b",
        "a = 0x_FF",
        "a = 0xFF_",
        "a = 0o77_",
        "a = 0b11_",
        "a = 0xF__F",
        "a = 0o7__7",
        "a = 0b1__0",
        "a = 01",
        "a = 123_",
        "a = 1__2",
    ];

    for input in error_cases {
        let e = ctx.parse_err(input);
        assert!(is_number_error!(e.kind()), "input: {input}");
    }
}

#[test]
fn float_valid_edge_cases() {
    let ctx = TestCtx::new();

    let cases = [
        ("a = 5e2", 500.0, 0.01),
        ("a = -1.5e-3", -1.5e-3, 1e-10),
        ("a = 1_000.5_00", 1000.5, f64::EPSILON),
        ("a = 1e+5", 1e5, 0.01),
        ("a = 1.5E+3", 1.5e3, 0.01),
    ];

    for (input, expected, epsilon) in cases {
        let v = ctx.parse_ok(input);
        let f = v["a"].as_f64().unwrap();
        assert!((f - expected).abs() < epsilon, "input: {input}");
    }
}

#[test]
fn float_format_errors() {
    let ctx = TestCtx::new();

    let error_cases = [
        "a = 00.5",
        "a = 1.",
        // "a = .1" is now Unexpected('.'), not a number error
        "a = 1.5_",
        "a = --1.0",
        "a = --1",
        "a = -+1",
        "a = +-1",
        "a = +-1.0",
        "a = +-1E",
        "a = --1E",
        "a = ++1E",
        "a = -00.5",
        "a = 50E+-1",
        "a = 50E-+1",
        "a = 1._5",
        "a = 1e\nb = 2",
    ];

    for input in error_cases {
        let e = ctx.parse_err(input);
        assert!(is_number_error!(e.kind()), "input: {input}");
    }
}

#[test]
fn structural_errors() {
    let ctx = TestCtx::new();

    // dotted key on non-table value
    let e = ctx.parse_err("a = 1\na.b = 2");
    assert!(matches!(e.kind(), ErrorKind::DottedKeyInvalidType { .. }));

    // dotted key on frozen inline table
    let e = ctx.parse_err("a = {b = 1}\na.c = 2");
    assert!(matches!(
        e.kind(),
        ErrorKind::DuplicateTable { .. }
            | ErrorKind::DuplicateKey { .. }
            | ErrorKind::DottedKeyInvalidType { .. }
    ));

    // table then array of tables
    let e = ctx.parse_err("[a]\nb = 1\n[[a]]");
    assert!(matches!(e.kind(), ErrorKind::RedefineAsArray { .. }));

    // duplicate table header
    let e = ctx.parse_err("[a]\nb = 1\n[a]\nc = 2");
    assert!(matches!(e.kind(), ErrorKind::DuplicateTable { .. }));

    // multiline basic string as key
    let e = ctx.parse_err("\"\"\"key\"\"\" = 1");
    assert!(matches!(e.kind(), ErrorKind::MultilineStringKey));

    // multiline literal string as key
    let e = ctx.parse_err("'''key''' = 1");
    assert!(matches!(e.kind(), ErrorKind::MultilineStringKey));

    // unquoted string value
    let e = ctx.parse_err("a = not_a_keyword");
    assert!(matches!(e.kind(), ErrorKind::UnquotedString));

    // missing value at EOF
    let e = ctx.parse_err("a = ");
    assert!(matches!(e.kind(), ErrorKind::UnexpectedEof));

    // missing equals sign
    let e = ctx.parse_err("key 1");
    assert!(matches!(e.kind(), ErrorKind::Wanted { .. }));

    // newline in basic string
    let e = ctx.parse_err("a = \"line1\nline2\"");
    assert!(matches!(e.kind(), ErrorKind::UnterminatedString('"')));

    // newline in literal string
    let e = ctx.parse_err("a = 'line1\nline2'");
    assert!(matches!(e.kind(), ErrorKind::UnterminatedString('\'')));

    // DEL character in string
    let e = ctx.parse_err("a = \"hello\x7Fworld\"");
    assert!(matches!(e.kind(), ErrorKind::InvalidCharInString(_)));
}

#[test]
fn inline_table_edge_cases() {
    let ctx = TestCtx::new();

    let v = ctx.parse_ok("a = {b.c = 1}");
    assert_eq!(v["a"]["b"]["c"].as_i64(), Some(1), "input: a = {{b.c = 1}}");

    let table_len_cases = [
        ("a = {x = 1, y = 2,}", 2),
        ("a = {\n  x = 1,\n  y = 2\n}", 2),
        ("a = {\n  x = 1, # comment\n  y = 2\n}", 2),
    ];

    for (input, expected_len) in table_len_cases {
        let v = ctx.parse_ok(input);
        assert_eq!(
            v["a"].as_table().unwrap().len(),
            expected_len,
            "input: {input}"
        );
    }
}

#[test]
fn array_edge_cases() {
    let ctx = TestCtx::new();

    let cases = [
        ("a = [\n  1, # first\n  2, # second\n  3\n]", 3),
        ("a = [1, 2, 3,]", 3),
    ];

    for (input, expected_len) in cases {
        let v = ctx.parse_ok(input);
        assert_eq!(
            v["a"].as_array().unwrap().len(),
            expected_len,
            "input: {input}"
        );
    }
}

#[test]
fn dotted_key_features() {
    let ctx = TestCtx::new();

    // deep dotted key
    let v = ctx.parse_ok("a.b.c.d = 1");
    assert_eq!(v["a"]["b"]["c"]["d"].as_i64(), Some(1));

    // extend existing table via dotted key
    let v = ctx.parse_ok("a.b = 1\na.c = 2");
    assert_eq!(v["a"]["b"].as_i64(), Some(1));
    assert_eq!(v["a"]["c"].as_i64(), Some(2));

    // table header then dotted key
    let v = ctx.parse_ok("[a]\nb.c = 1\nb.d = 2");
    assert_eq!(v["a"]["b"]["c"].as_i64(), Some(1));
    assert_eq!(v["a"]["b"]["d"].as_i64(), Some(2));
}

#[test]
fn aot_and_implicit_tables() {
    let ctx = TestCtx::new();

    // array of tables with subtable
    let v = ctx.parse_ok("[[a]]\nb = 1\n[a.c]\nd = 2\n[[a]]\nb = 3");
    assert_eq!(v["a"].as_array().unwrap().len(), 2);
    assert_eq!(v["a"][0]["b"].as_i64(), Some(1));
    assert_eq!(v["a"][0]["c"]["d"].as_i64(), Some(2));

    // navigate header intermediate on array of tables
    let v = ctx.parse_ok("[[a]]\nb = 1\n[a.c]\nd = 2");
    assert_eq!(v["a"][0]["b"].as_i64(), Some(1));
    assert_eq!(v["a"][0]["c"]["d"].as_i64(), Some(2));

    // implicit table then explicit define
    let v = ctx.parse_ok("[a.b]\nc = 1\n[a]\nd = 2");
    assert_eq!(v["a"]["d"].as_i64(), Some(2));
    assert_eq!(v["a"]["b"]["c"].as_i64(), Some(1));
}

#[test]
fn integer_boundary_values() {
    let ctx = TestCtx::new();

    let cases = [
        ("a = -9223372036854775808", i64::MIN),
        ("a = 9223372036854775807", i64::MAX),
    ];

    for (input, expected) in cases {
        let v = ctx.parse_ok(input);
        assert_eq!(v["a"].as_i64(), Some(expected), "input: {input}");
    }
}

#[test]
fn integer_overflow_errors() {
    let ctx = TestCtx::new();

    let error_cases = [
        "a = 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF",
        "a = 99999999999999999999999999999999999999999",
    ];

    for input in error_cases {
        let e = ctx.parse_err(input);
        assert!(is_number_error!(e.kind()), "input: {input}");
    }

    // Former i64 overflow values now fit in i128
    let ok_cases = [
        ("a = 0xFFFFFFFFFFFFFFFF", 0xFFFFFFFFFFFFFFFFi128),
        ("a = 99999999999999999999", 99999999999999999999i128),
    ];
    for (input, expected) in ok_cases {
        let v = ctx.parse_ok(input);
        assert_eq!(v["a"].as_i128(), Some(expected), "input: {input}");
    }
}

#[test]
fn more_parse_errors() {
    let ctx = TestCtx::new();

    // inline table duplicate key
    let e = ctx.parse_err("a = {x = 1, x = 2}");
    assert!(matches!(e.kind(), ErrorKind::DuplicateKey { .. }));

    // dotted key duplicate in table
    let e = ctx.parse_err("[a]\nb = 1\nb = 2");
    assert!(matches!(e.kind(), ErrorKind::DuplicateKey { .. }));

    // expected value found ]
    let e = ctx.parse_err("a = ]");
    assert!(matches!(e.kind(), ErrorKind::Unexpected(']')));

    // expected value found }
    let e = ctx.parse_err("a = }");
    assert!(matches!(e.kind(), ErrorKind::Unexpected('}')));

    // dash-leading invalid number
    let e = ctx.parse_err("a = -_bad");
    assert!(is_number_error!(e.kind()));

    // EOF in key position
    let e = ctx.parse_err("[");
    assert!(matches!(e.kind(), ErrorKind::Wanted { .. }));

    // invalid key character (= with no key)
    let e = ctx.parse_err("= 1");
    assert!(matches!(e.kind(), ErrorKind::Wanted { .. }));

    // bare CR at document level
    let e = ctx.parse_err("a = 1\r");
    assert!(matches!(
        e.kind(),
        ErrorKind::Wanted { .. } | ErrorKind::Unexpected('\r')
    ));

    // missing closing bracket in table header
    let e = ctx.parse_err("[table\na = 1");
    assert!(matches!(e.kind(), ErrorKind::Wanted { .. }));

    // missing closing brace in inline table
    let e = ctx.parse_err("a = {x = 1");
    assert!(matches!(e.kind(), ErrorKind::UnclosedInlineTable));

    // missing closing bracket in array
    let e = ctx.parse_err("a = [1, 2");
    assert!(matches!(e.kind(), ErrorKind::UnclosedArray));

    // junk after value on same line
    let e = ctx.parse_err("a = 1 b = 2");
    assert!(matches!(e.kind(), ErrorKind::Wanted { .. }));

    // dotted key in inline table on frozen table
    let e = ctx.parse_err("a = {b = 1}\na.b.c = 2");
    assert!(matches!(
        e.kind(),
        ErrorKind::DuplicateKey { .. } | ErrorKind::DottedKeyInvalidType { .. }
    ));

    // header intermediate on scalar
    let e = ctx.parse_err("a = 1\n[a.b]");
    assert!(matches!(e.kind(), ErrorKind::DuplicateKey { .. }));

    // dotted key conflicts with header
    let e = ctx.parse_err("[a]\nb = 1\n[a.b]\nc = 2");
    assert!(matches!(
        e.kind(),
        ErrorKind::DottedKeyInvalidType { .. } | ErrorKind::DuplicateKey { .. }
    ));

    // redefine dotted as header
    let e = ctx.parse_err("a.b = 1\n[a.b]\nc = 2");
    assert!(matches!(
        e.kind(),
        ErrorKind::DuplicateKey { .. } | ErrorKind::DuplicateTable { .. }
    ));

    // header on frozen inline table
    let e = ctx.parse_err("a = {b = 1}\n[a.c]");
    assert!(matches!(e.kind(), ErrorKind::DuplicateKey { .. }));

    // array-of-tables on existing non-table
    let e = ctx.parse_err("a = 1\n[[a]]");
    assert!(matches!(e.kind(), ErrorKind::DuplicateKey { .. }));

    // dotted header on dotted table
    let e = ctx.parse_err("a.b = 1\n[a]\nc = 2");
    assert!(matches!(
        e.kind(),
        ErrorKind::DuplicateTable { .. } | ErrorKind::DuplicateKey { .. }
    ));

    // unterminated quoted key
    let e = ctx.parse_err(r#""unterminated = 1"#);
    assert!(matches!(e.kind(), ErrorKind::UnterminatedString('"')));

    // unterminated literal key
    let e = ctx.parse_err("'unterminated = 1");
    assert!(matches!(e.kind(), ErrorKind::UnterminatedString('\'')));

    // expected key found equals
    let e = ctx.parse_err("= 1");
    assert!(matches!(
        e.kind(),
        ErrorKind::Wanted {
            expected: &"a table key",
            ..
        }
    ));

    // expected key found comma
    let e = ctx.parse_err("[a]\n, = 1");
    assert!(matches!(e.kind(), ErrorKind::Wanted { .. }));

    // CRLF in basic string (not multiline) is an error
    let e = ctx.parse_err("a = \"hello\r\nworld\"");
    assert!(matches!(e.kind(), ErrorKind::UnterminatedString('"')));
}

#[test]
fn crlf_in_intermediate_contexts() {
    let ctx = TestCtx::new();

    // CRLF as newline inside array (eat_newline in eat_intermediate)
    let array_cases = [
        ("a = [\r\n1\r\n]", 1),
        ("a = [\r\n1,\r\n2\r\n]", 2),
        ("a = [\r\n  1, # comment\r\n  2\r\n]", 2),
    ];
    for (input, expected_len) in array_cases {
        let v = ctx.parse_ok(input);
        assert_eq!(
            v["a"].as_array().unwrap().len(),
            expected_len,
            "input: {input}"
        );
    }

    // CRLF in inline table whitespace (eat_newline in eat_inline_table_whitespace)
    let v = ctx.parse_ok("a = {\r\nx = 1\r\n}");
    assert_eq!(v["a"]["x"].as_i64(), Some(1));

    // Multiline string: backslash followed by space then CRLF
    let ml_cases = [
        ("a = \"\"\"\\ \r\n   trimmed\"\"\"", "trimmed"),
        ("a = \"\"\"\\\t\r\n   trimmed\"\"\"", "trimmed"),
        ("a = \"\"\"\\\r\n\r\n   trimmed\"\"\"", "trimmed"),
    ];
    for (input, expected) in ml_cases {
        let v = ctx.parse_ok(input);
        assert_eq!(v["a"].as_str(), Some(expected), "input: {input}");
    }
}

#[test]
fn scan_token_desc_branches() {
    let ctx = TestCtx::new();

    // Non-key characters at table-header key position trigger
    // read_table_key -> scan_token_desc_and_end with different found descriptions.
    let header_key_cases: [(&str, &str); 4] = [
        ("[#]", "a comment"),
        ("[.]", "a period"),
        ("[:]", "a colon"),
        ("[+]", "a plus"),
    ];
    for (input, expected_found) in header_key_cases {
        let e = ctx.parse_err(input);
        assert!(
            matches!(
                e.kind(),
                ErrorKind::Wanted { found, .. } if *found == expected_found
            ),
            "input: {input}, got: {:?}",
            e.kind()
        );
    }

    // Identifier branch: missing comma, cursor at next identifier
    let e = ctx.parse_err("a = {x = 1 y = 2}");
    assert!(
        matches!(e.kind(), ErrorKind::MissingInlineTableComma),
        "input: a = {{x = 1 y = 2}}, got: {:?}",
        e.kind()
    );

    // Generic character branch: non-special byte
    let e = ctx.parse_err("a = {x = 1 @}");
    assert!(
        matches!(e.kind(), ErrorKind::MissingInlineTableComma),
        "input: a = {{x = 1 @}}, got: {:?}",
        e.kind()
    );
}

#[test]
fn string_eof_edge_cases() {
    let ctx = TestCtx::new();

    let eof_cases = ["a = \"", "a = \"\\", "a = \"\"\"", "a = \"\"\"\\"];
    for input in eof_cases {
        let e = ctx.parse_err(input);
        assert!(
            matches!(e.kind(), ErrorKind::UnterminatedString('"')),
            "input: {input}"
        );
    }
}

#[test]
fn number_identifier_not_inf_nan() {
    let ctx = TestCtx::new();

    // Keylike with - prefix followed by i/n but not -inf/-nan.
    let cases = ["a = -infix", "a = -nah", "a = -infinity", "a = -nano"];
    for input in cases {
        let e = ctx.parse_err(input);
        assert!(is_number_error!(e.kind()), "input: {input}");
    }
}

#[test]
fn error_messages_and_spans() {
    let ctx = TestCtx::new();

    // Signed prefixed integers
    let e = ctx.parse_err("a = +0xFF");
    assert!(matches!(
        e.kind(),
        ErrorKind::InvalidInteger("signs are not allowed on prefixed integers")
    ));

    let e = ctx.parse_err("a = -0b1");
    assert!(matches!(
        e.kind(),
        ErrorKind::InvalidInteger("signs are not allowed on prefixed integers")
    ));

    let e = ctx.parse_err("a = -0o7");
    assert!(matches!(
        e.kind(),
        ErrorKind::InvalidInteger("signs are not allowed on prefixed integers")
    ));

    // Expected digit after sign
    let e = ctx.parse_err("a = -.7");
    assert!(matches!(
        e.kind(),
        ErrorKind::InvalidInteger("expected digit after sign")
    ));

    let e = ctx.parse_err("a = +_2");
    assert!(matches!(
        e.kind(),
        ErrorKind::InvalidInteger("expected digit after sign")
    ));

    let e = ctx.parse_err("a = -_bad");
    assert!(matches!(
        e.kind(),
        ErrorKind::InvalidInteger("expected digit after sign")
    ));

    // Stray plus at EOF
    let e = ctx.parse_err("key = +");
    assert!(matches!(
        e.kind(),
        ErrorKind::InvalidInteger("expected digit after sign")
    ));

    // Unexpected characters in value position
    let e = ctx.parse_err("a = .1");
    assert!(matches!(e.kind(), ErrorKind::Unexpected('.')));

    let e = ctx.parse_err("a = ]");
    assert!(matches!(e.kind(), ErrorKind::Unexpected(']')));

    let e = ctx.parse_err("a = }");
    assert!(matches!(e.kind(), ErrorKind::Unexpected('}')));

    // Unquoted strings
    let e = ctx.parse_err("a = hello");
    assert!(matches!(e.kind(), ErrorKind::UnquotedString));

    let e = ctx.parse_err("a = not_a_keyword");
    assert!(matches!(e.kind(), ErrorKind::UnquotedString));

    let e = ctx.parse_err("a = True");
    assert!(matches!(e.kind(), ErrorKind::UnquotedString));

    // Pointed span for invalid hex digit: "a = 0xABGD" → G at position 8
    let e = ctx.parse_err("a = 0xABGD");
    assert!(matches!(
        e.kind(),
        ErrorKind::InvalidInteger("invalid digit for hexadecimal")
    ));
    assert_eq!(e.span(), Span::new(8, 9), "should point at 'G'");

    // Pointed span for invalid octal digit: "a = 0o89" → 8 at position 6
    let e = ctx.parse_err("a = 0o89");
    assert!(matches!(
        e.kind(),
        ErrorKind::InvalidInteger("invalid digit for octal")
    ));
    assert_eq!(e.span(), Span::new(6, 7), "should point at '8'");

    // Pointed span for invalid binary digit: "a = 0b102" → 2 at position 8
    let e = ctx.parse_err("a = 0b102");
    assert!(matches!(
        e.kind(),
        ErrorKind::InvalidInteger("invalid digit for binary")
    ));
    assert_eq!(e.span(), Span::new(8, 9), "should point at '2'");

    // Pointed span for underscore errors: "a = 1__2" → second _ at position 6
    let e = ctx.parse_err("a = 1__2");
    assert!(matches!(
        e.kind(),
        ErrorKind::InvalidInteger("underscores must be between two digits")
    ));
    assert_eq!(
        e.span(),
        Span::new(6, 7),
        "should point at second underscore"
    );

    // Trailing underscore: "a = 123_" → _ at position 7
    let e = ctx.parse_err("a = 123_");
    assert!(matches!(
        e.kind(),
        ErrorKind::InvalidInteger("underscores must be between two digits")
    ));
    assert_eq!(
        e.span(),
        Span::new(7, 8),
        "should point at trailing underscore"
    );

    // Hex trailing underscore: "a = 0xFF_" → _ at position 8
    let e = ctx.parse_err("a = 0xFF_");
    assert!(matches!(
        e.kind(),
        ErrorKind::InvalidInteger("underscores must be between two digits")
    ));
    assert_eq!(
        e.span(),
        Span::new(8, 9),
        "should point at trailing underscore in hex"
    );

    // Non-digit in decimal: "a = 1a2" → a at position 5
    let e = ctx.parse_err("a = 1a2");
    assert!(matches!(
        e.kind(),
        ErrorKind::InvalidInteger("contains non-digit character")
    ));
    assert_eq!(e.span(), Span::new(5, 6), "should point at 'a'");

    // Leading zeros
    let e = ctx.parse_err("a = 01");
    assert!(matches!(
        e.kind(),
        ErrorKind::InvalidInteger("leading zeros are not allowed")
    ));

    // Malformed datetimes produce datetime errors, not integer errors
    let e = ctx.parse_err("a = 2016-9-09T09:09:09Z");
    assert!(matches!(
        e.kind(),
        ErrorKind::InvalidDateTime("expected 2-digit month")
    ));

    let e = ctx.parse_err("a = 25-01-01T00:00:00Z");
    assert!(matches!(
        e.kind(),
        ErrorKind::InvalidDateTime("expected 4-digit year")
    ));

    let e = ctx.parse_err("a = 2016-13-01");
    assert!(matches!(
        e.kind(),
        ErrorKind::InvalidDateTime("month is out of range")
    ));

    let e = ctx.parse_err("a = 2016-02-30");
    assert!(matches!(
        e.kind(),
        ErrorKind::InvalidDateTime("day is out of range")
    ));

    let e = ctx.parse_err("a = 2016-09-09T25:00:00");
    assert!(matches!(
        e.kind(),
        ErrorKind::InvalidDateTime("hour is out of range")
    ));

    let e = ctx.parse_err("a = 2016-09-09T09:60:00");
    assert!(matches!(
        e.kind(),
        ErrorKind::InvalidDateTime("minute is out of range")
    ));
}

#[test]
fn integer_overflow_specific_paths() {
    let ctx = TestCtx::new();

    // Decimal: i128::MAX + 1 overflows positive max
    let e = ctx.parse_err("a = 170141183460469231731687303715884105728");
    assert!(is_number_error!(e.kind()), "input: i128::MAX + 1");

    // Decimal: negative overflow past i128::MIN
    let e = ctx.parse_err("a = -170141183460469231731687303715884105729");
    assert!(is_number_error!(e.kind()), "input: -(i128::MIN) - 1");

    // Former i64 overflow values now succeed
    let v = ctx.parse_ok("a = 9223372036854775808");
    assert_eq!(v["a"].as_i128(), Some(9223372036854775808i128));

    let v = ctx.parse_ok("a = -9223372036854775809");
    assert_eq!(v["a"].as_i128(), Some(-9223372036854775809i128));

    // Hex: invalid hex digit
    let hex_invalid = ["a = 0xGG", "a = 0xZZ"];
    for input in hex_invalid {
        let e = ctx.parse_err(input);
        assert!(is_number_error!(e.kind()), "input: {input}");
    }

    // Hex: overflow via acc >> 124 != 0 (33 hex digits)
    let e = ctx.parse_err("a = 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF");
    assert!(is_number_error!(e.kind()), "input: 0x 33 F's");

    // Former i64 overflow hex values now succeed
    let v = ctx.parse_ok("a = 0xFFFFFFFFFFFFFFFFF");
    assert_eq!(v["a"].as_i128(), Some(0xFFFFFFFFFFFFFFFFFi128));

    let v = ctx.parse_ok("a = 0x10000000000000000");
    assert_eq!(v["a"].as_i128(), Some(0x10000000000000000i128));

    // Octal: overflow past i128::MAX
    let e = ctx.parse_err("a = 0o4000000000000000000000000000000000000000000");
    assert!(is_number_error!(e.kind()), "input: 0o > i128::MAX");

    // Binary: overflow via acc >> 127 != 0 (129 binary digits)
    let e = ctx.parse_err(&format!("a = 0b1{}", "1".repeat(128)));
    assert!(is_number_error!(e.kind()), "input: 0b 129 ones");
}

#[test]
fn float_validation_edge_cases() {
    let ctx = TestCtx::new();

    // push_strip_underscores fails on integer part (trailing underscore before dot)
    let integer_part_cases = ["a = 1_.5", "a = 1__.5"];
    for input in integer_part_cases {
        let e = ctx.parse_err(input);
        assert!(is_number_error!(e.kind()), "input: {input}");
    }

    // push_strip_underscores fails on exponent part (leading/trailing underscore)
    let exponent_cases = ["a = 1e+_5", "a = 1E+_5", "a = 1e+5_"];
    for input in exponent_cases {
        let e = ctx.parse_err(input);
        assert!(is_number_error!(e.kind()), "input: {input}");
    }

    // Result overflows to infinity, rejected as non-finite
    let non_finite_cases = ["a = 1e999", "a = 1e9999", "a = 1.0e999", "a = -1e999"];
    for input in non_finite_cases {
        let e = ctx.parse_err(input);
        assert!(is_number_error!(e.kind()), "input: {input}");
    }
}

#[test]
fn inline_table_error_paths() {
    let ctx = TestCtx::new();

    // eat_inline_table_whitespace error at start (bare CR after comment)
    let e = ctx.parse_err("a = {#bad\r}");
    assert!(
        matches!(e.kind(), ErrorKind::Wanted { .. }),
        "input: bare CR after comment in inline table start"
    );

    // read_table_key error in loop (non-key character)
    let e = ctx.parse_err("a = {!}");
    assert!(
        matches!(
            e.kind(),
            ErrorKind::Wanted {
                expected: &"a table key",
                ..
            }
        ),
        "input: a = {{!}}"
    );

    // eat_inline_table_whitespace error after key (bare CR)
    let e = ctx.parse_err("a = {x #bad\r= 1}");
    assert!(
        matches!(e.kind(), ErrorKind::Wanted { .. }),
        "input: bare CR after key in inline table"
    );

    // navigate_dotted_key error (dotted key on non-table value)
    let e = ctx.parse_err("a = {x = 1, x.y = 2}");
    assert!(
        matches!(e.kind(), ErrorKind::DottedKeyInvalidType { .. }),
        "input: dotted key on integer in inline table"
    );

    // read_table_key error after dot in dotted key
    let e = ctx.parse_err("a = {x.! = 1}");
    assert!(
        matches!(
            e.kind(),
            ErrorKind::Wanted {
                expected: &"a table key",
                ..
            }
        ),
        "input: invalid key after dot in inline table"
    );

    // expect_byte(b'=') error (missing equals)
    let e = ctx.parse_err("a = {x}");
    assert!(
        matches!(
            e.kind(),
            ErrorKind::Wanted {
                expected: &"an equals",
                ..
            }
        ),
        "input: a = {{x}}"
    );

    // eat_inline_table_whitespace error after value (bare CR)
    let e = ctx.parse_err("a = {x = 1 #bad\r}");
    assert!(
        matches!(e.kind(), ErrorKind::Wanted { .. }),
        "input: bare CR after value in inline table"
    );

    // eat_inline_table_whitespace error after comma (bare CR)
    let e = ctx.parse_err("a = {x = 1, #bad\r}");
    assert!(
        matches!(e.kind(), ErrorKind::Wanted { .. }),
        "input: bare CR after comma in inline table"
    );
}

#[test]
fn array_error_paths() {
    let ctx = TestCtx::new();

    // eat_intermediate error at start of array (bare CR after comment)
    let e = ctx.parse_err("a = [#bad\r]");
    assert!(
        matches!(e.kind(), ErrorKind::Wanted { .. }),
        "input: bare CR after comment at array start"
    );

    // eat_intermediate error after value (bare CR after comment)
    let e = ctx.parse_err("a = [1 #bad\r]");
    assert!(
        matches!(e.kind(), ErrorKind::Wanted { .. }),
        "input: bare CR after comment after array value"
    );

    // eat_intermediate error after comma
    let e = ctx.parse_err("a = [1, #bad\r]");
    assert!(
        matches!(e.kind(), ErrorKind::Wanted { .. }),
        "input: bare CR after comment after comma in array"
    );
}

#[test]
fn parse_document_error_paths() {
    let ctx = TestCtx::new();

    // eat_comment error at top level (bare CR after comment)
    let e = ctx.parse_err("#bad\r");
    assert!(
        matches!(e.kind(), ErrorKind::Wanted { .. }),
        "input: bare CR after top-level comment"
    );

    let e = ctx.parse_err("a = 1\n#bad\r");
    assert!(
        matches!(e.kind(), ErrorKind::Wanted { .. }),
        "input: bare CR after comment following key-value"
    );

    // Bare CR at top level (not in comment or string)
    let e = ctx.parse_err("\r");
    assert!(
        matches!(e.kind(), ErrorKind::Unexpected('\r')),
        "input: bare CR at document top level"
    );

    let e = ctx.parse_err("a = 1\n\r");
    assert!(
        matches!(e.kind(), ErrorKind::Unexpected('\r')),
        "input: bare CR after newline at document top level"
    );
}

#[test]
fn table_header_error_paths() {
    let ctx = TestCtx::new();

    // read_table_key error after dot in header (trailing dot)
    let e = ctx.parse_err("[a.]\nk = 1");
    assert!(
        matches!(
            e.kind(),
            ErrorKind::Wanted {
                expected: &"a table key",
                ..
            }
        ),
        "input: [a.]"
    );

    // Missing second ] for array-of-tables
    let e = ctx.parse_err("[[a]\nk = 1");
    assert!(
        matches!(
            e.kind(),
            ErrorKind::Wanted {
                expected: &"a right bracket",
                ..
            }
        ),
        "input: [[a] missing second bracket"
    );

    // Comment on same line as header (success path)
    let v = ctx.parse_ok("[a] # comment\nk = 1");
    assert_eq!(v["a"]["k"].as_i64(), Some(1), "input: [a] # comment");

    // Junk after header (no newline, not EOF)
    let e = ctx.parse_err("[a]x");
    assert!(
        matches!(
            e.kind(),
            ErrorKind::Wanted {
                expected: &"newline",
                ..
            }
        ),
        "input: [a]x"
    );

    // eat_comment error after header (bare CR)
    let e = ctx.parse_err("[a]#bad\r");
    assert!(
        matches!(e.kind(), ErrorKind::Wanted { .. }),
        "input: [a]#bad\\r"
    );
}

#[test]
fn key_value_error_paths() {
    let ctx = TestCtx::new();

    // read_table_key error in dotted key loop
    let e = ctx.parse_err("x.! = 1");
    assert!(
        matches!(
            e.kind(),
            ErrorKind::Wanted {
                expected: &"a table key",
                ..
            }
        ),
        "input: x.! = 1"
    );

    let e = ctx.parse_err("[t]\nx.= = 1");
    assert!(
        matches!(
            e.kind(),
            ErrorKind::Wanted {
                expected: &"a table key",
                ..
            }
        ),
        "input: x.= = 1"
    );

    // eat_comment error after key-value (bare CR)
    let e = ctx.parse_err("a = 1 #bad\r");
    assert!(
        matches!(e.kind(), ErrorKind::Wanted { .. }),
        "input: a = 1 #bad\\r"
    );
}

#[test]
fn hex_numbers_with_zero_digits() {
    let ctx = TestCtx::new();

    // Hex digits that include '0' after the prefix, exercising the
    // HEX lookup table for the 0-9 range as well as lowercase a-f.
    let cases: [(&str, i64); 6] = [
        ("a = 0x10", 0x10),
        ("a = 0x0F", 0x0F),
        ("a = 0x00", 0x00),
        ("a = 0x0a", 0x0a),
        ("a = 0xab", 0xab),
        ("a = 0xAbCd", 0xABCD),
    ];
    for (input, expected) in cases {
        let v = ctx.parse_ok(input);
        assert_eq!(v["a"].as_i64(), Some(expected), "input: {input}");
    }
}

#[test]
fn integer_base_max_boundary() {
    let ctx = TestCtx::new();

    // Hex: i64::MAX = 0x7FFFFFFFFFFFFFFF
    let v = ctx.parse_ok("a = 0x7FFFFFFFFFFFFFFF");
    assert_eq!(v["a"].as_i64(), Some(i64::MAX));

    // Hex: i64::MAX + 1 now parses as i128
    let v = ctx.parse_ok("a = 0x8000000000000000");
    assert_eq!(v["a"].as_i128(), Some(0x8000000000000000i128));
    assert_eq!(v["a"].as_i64(), None);

    // Hex: i128::MAX
    let v = ctx.parse_ok("a = 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF");
    assert_eq!(v["a"].as_i128(), Some(i128::MAX));

    // Hex: i128::MAX + 1 should overflow
    let e = ctx.parse_err("a = 0x80000000000000000000000000000000");
    assert!(is_number_error!(e.kind()), "hex i128::MAX+1");

    // Octal: i64::MAX = 0o777777777777777777777
    let v = ctx.parse_ok("a = 0o777777777777777777777");
    assert_eq!(v["a"].as_i64(), Some(i64::MAX));

    // Octal: i64::MAX + 1 now parses as i128
    let v = ctx.parse_ok("a = 0o1000000000000000000000");
    assert_eq!(v["a"].as_i128(), Some(0o1000000000000000000000i128));

    // Binary: i64::MAX = 0b followed by 0 then 62 ones
    let v = ctx.parse_ok("a = 0b0111111111111111111111111111111111111111111111111111111111111111");
    assert_eq!(v["a"].as_i64(), Some(i64::MAX));

    // Binary: i64::MAX + 1 now parses as i128
    let v = ctx.parse_ok("a = 0b1000000000000000000000000000000000000000000000000000000000000000");
    assert_eq!(v["a"].as_i128(), Some(1i128 << 63));
}

#[test]
fn literal_string_span() {
    let ctx = TestCtx::new();

    // Span of a single-quoted (literal) string value includes the quotes.
    let input = "key = 'hello'";
    let v = ctx.parse_ok(input);
    let span = v.get("key").unwrap().span_unchecked();
    assert_eq!(
        &input[span.start as usize..span.end as usize],
        "'hello'",
        "literal string span"
    );

    // Empty literal string: span covers both quotes
    let input = "key = ''";
    let v = ctx.parse_ok(input);
    let span = v.get("key").unwrap().span_unchecked();
    assert_eq!(span.start, 6, "empty literal string span start");
    assert_eq!(span.end, 8, "empty literal string span end");
}

#[test]
fn multiline_string_spans() {
    let ctx = TestCtx::new();

    // Multiline basic string span includes the triple-quote delimiters.
    let input = "key = \"\"\"\nhello\nworld\"\"\"";
    let v = ctx.parse_ok(input);
    let span = v.get("key").unwrap().span_unchecked();
    assert_eq!(
        &input[span.start as usize..span.end as usize],
        "\"\"\"\nhello\nworld\"\"\"",
        "multiline basic string span"
    );

    // Multiline basic string with CRLF opening
    let input = "key = \"\"\"\r\nhello\"\"\"";
    let v = ctx.parse_ok(input);
    let span = v.get("key").unwrap().span_unchecked();
    assert_eq!(
        &input[span.start as usize..span.end as usize],
        "\"\"\"\r\nhello\"\"\"",
        "multiline basic string span with CRLF opening"
    );

    // Multiline basic string without leading newline
    let input = "key = \"\"\"hello\"\"\"";
    let v = ctx.parse_ok(input);
    let span = v.get("key").unwrap().span_unchecked();
    assert_eq!(
        &input[span.start as usize..span.end as usize],
        "\"\"\"hello\"\"\"",
        "multiline basic string span without leading newline"
    );

    // Multiline literal string span
    let input = "key = '''\nhello\nworld'''";
    let v = ctx.parse_ok(input);
    let span = v.get("key").unwrap().span_unchecked();
    assert_eq!(
        &input[span.start as usize..span.end as usize],
        "'''\nhello\nworld'''",
        "multiline literal string span"
    );

    // Empty string: span covers both quotes
    let input = "key = \"\"";
    let v = ctx.parse_ok(input);
    let span = v.get("key").unwrap().span_unchecked();
    assert_eq!(span.start, 6, "empty basic string span start");
    assert_eq!(span.end, 8, "empty basic string span end");
}

#[test]
fn backslash_whitespace_in_nonmultiline_string() {
    let ctx = TestCtx::new();

    // Backslash followed by space in a non-multiline basic string is an error.
    let e = ctx.parse_err("a = \"hello\\ world\"");
    assert!(
        matches!(e.kind(), ErrorKind::InvalidEscape(' ')),
        "backslash-space in basic string: {:?}",
        e.kind()
    );

    // Backslash followed by tab in a non-multiline basic string is an error.
    let e = ctx.parse_err("a = \"hello\\\tworld\"");
    assert!(
        matches!(e.kind(), ErrorKind::InvalidEscape('\t')),
        "backslash-tab in basic string: {:?}",
        e.kind()
    );
}

#[test]
fn lowercase_hex_escapes() {
    let ctx = TestCtx::new();

    // Lowercase hex digits in \u and \U escapes
    let cases = [
        (r#"a = "\u0061""#, "a"),             // lowercase a-f digits
        (r#"a = "\u00ff""#, "\u{ff}"),        // all lowercase hex
        (r#"a = "\U0001f600""#, "\u{1f600}"), // emoji via lowercase hex
        (r#"a = "\x61""#, "a"),               // \x with lowercase
    ];
    for (input, expected) in cases {
        let v = ctx.parse_ok(input);
        assert_eq!(
            v.get("a").unwrap().as_str(),
            Some(expected),
            "input: {input}"
        );
    }
}

#[test]
fn nan_sign_preservation() {
    let ctx = TestCtx::new();

    let v = ctx.parse_ok("a = nan");
    let f = v["a"].as_f64().unwrap();
    assert!(f.is_nan());
    assert!(f.is_sign_positive(), "nan should be positive");

    let v = ctx.parse_ok("a = -nan");
    let f = v["a"].as_f64().unwrap();
    assert!(f.is_nan());
    assert!(f.is_sign_negative(), "-nan should be negative");

    let v = ctx.parse_ok("a = +nan");
    let f = v["a"].as_f64().unwrap();
    assert!(f.is_nan());
    assert!(f.is_sign_positive(), "+nan should be positive");
}

#[test]
fn indexed_table_nonexistent_key() {
    let ctx = TestCtx::new();

    // Table with 6+ entries uses hash index for lookups.
    // Verify that a nonexistent key returns None.
    let v = ctx.parse_ok("a = 1\nb = 2\nc = 3\nd = 4\ne = 5\nf = 6");
    assert!(
        v.get("nonexistent").is_none(),
        "nonexistent key in 6-entry table"
    );

    // Also verify all 6 keys are correctly found (not just first/last).
    assert_eq!(v["a"].as_i64(), Some(1));
    assert_eq!(v["b"].as_i64(), Some(2));
    assert_eq!(v["c"].as_i64(), Some(3));
    assert_eq!(v["d"].as_i64(), Some(4));
    assert_eq!(v["e"].as_i64(), Some(5));
    assert_eq!(v["f"].as_i64(), Some(6));

    // 7+ entries: incremental indexing after initial bulk
    let v = ctx.parse_ok("a = 1\nb = 2\nc = 3\nd = 4\ne = 5\nf = 6\ng = 7");
    assert!(
        v.get("nonexistent").is_none(),
        "nonexistent key in 7-entry table"
    );
    assert_eq!(v["a"].as_i64(), Some(1));
    assert_eq!(v["g"].as_i64(), Some(7));
}

#[test]
fn long_string_exercises_swar_path() {
    let ctx = TestCtx::new();

    // Strings longer than 8 bytes exercise the SWAR fast path in skip_string_plain.
    // Include special characters at various positions to test boundary detection.
    let cases = [
        // Plain ASCII > 8 bytes
        (r#"a = "abcdefghijklmnop""#, "abcdefghijklmnop"),
        // Special char at position 9 (after one SWAR chunk)
        ("a = \"abcdefgh\\nrest\"", "abcdefgh\nrest"),
        // Delimiter at position 10
        (r#"a = "abcdefghij""#, "abcdefghij"),
        // Tab (benign for SWAR, should pass through)
        ("a = \"abc\tdefghijklmno\"", "abc\tdefghijklmno"),
    ];
    for (input, expected) in cases {
        let v = ctx.parse_ok(input);
        assert_eq!(v["a"].as_str(), Some(expected), "input: {input}");
    }

    // Literal string > 8 bytes (skip_string_plain with delim=')
    let v = ctx.parse_ok("a = 'abcdefghijklmnop'");
    assert_eq!(v["a"].as_str(), Some("abcdefghijklmnop"));
}

#[test]
fn integer_plus_sign_in_decimal() {
    let ctx = TestCtx::new();

    // Explicit + sign on decimal integers
    let cases: [(&str, i64); 3] = [
        ("a = +0", 0),
        ("a = +1", 1),
        ("a = +9223372036854775807", i64::MAX),
    ];
    for (input, expected) in cases {
        let v = ctx.parse_ok(input);
        assert_eq!(v["a"].as_i64(), Some(expected), "input: {input}");
    }
}

#[test]
fn octal_digit_validation() {
    let ctx = TestCtx::new();

    // Valid octal
    let cases: [(&str, i64); 3] = [("a = 0o0", 0), ("a = 0o7", 7), ("a = 0o10", 8)];
    for (input, expected) in cases {
        let v = ctx.parse_ok(input);
        assert_eq!(v["a"].as_i64(), Some(expected), "input: {input}");
    }

    // Invalid octal digits (8, 9)
    let e = ctx.parse_err("a = 0o8");
    assert!(is_number_error!(e.kind()), "octal digit 8");

    let e = ctx.parse_err("a = 0o9");
    assert!(is_number_error!(e.kind()), "octal digit 9");
}

// #[test]
// #[ignore] // requires 512+ MiB allocation
// fn file_too_large() {
//     let ctx = TestCtx::new();
//     let size = (1u32 << 29) as usize + 1;
//     let big = " ".repeat(size);
//     let e = ctx.parse_err(&big);
//     assert!(matches!(e.kind(), ErrorKind::FileTooLarge));
// }

#[test]
fn invalid_true_false_literals() {
    let ctx = TestCtx::new();

    for input in [
        "a = tru",
        "a = toast",
        "a = true2",
        "a = fals",
        "a = foobar",
        "a = false2",
        "a = t2",
        "a = f2",
    ] {
        let e = ctx.parse_err(input);
        assert!(
            matches!(e.kind(), ErrorKind::UnquotedString),
            "input: {input}, got: {:?}",
            e.kind()
        );
    }
}

#[test]
fn datetime_values() {
    let ctx = TestCtx::new();

    // Datetime as value (exercises the DateTime::munch path in number())
    let v = ctx.parse_ok("a = 2023-06-15T12:30:45Z");
    assert!(v["a"].as_datetime().is_some());
    assert_eq!(v["a"].as_datetime().unwrap().date().unwrap().year, 2023);

    let v = ctx.parse_ok("a = 2023-06-15");
    assert!(v["a"].as_datetime().is_some());

    let v = ctx.parse_ok("a = 2023-06-15T12:30:45+05:30");
    assert!(v["a"].as_datetime().is_some());
}

#[test]
fn scan_token_whitespace_and_string() {
    let ctx = TestCtx::new();

    // Whitespace at position where a comma/brace is expected triggers
    // scan_token_desc_and_end with whitespace (space/tab run)
    let e = ctx.parse_err("a = {x = 1   ");
    assert!(
        matches!(e.kind(), ErrorKind::UnclosedInlineTable),
        "input: truncated inline table with trailing whitespace"
    );

    // String delimiter at unexpected position
    let e = ctx.parse_err("[\"key\"\n]");
    assert!(
        matches!(e.kind(), ErrorKind::Wanted { .. }),
        "input: string where bracket expected"
    );
}

#[test]
fn duplicate_key_in_indexed_table() {
    let ctx = TestCtx::new();

    // Duplicate key in a table with 6+ entries (hash-indexed).
    // This exercises the insert_value Occupied path with an existing index.
    let mut lines = Vec::new();
    for i in 0..7 {
        lines.push(format!("k{i} = {i}"));
    }
    lines.push("k0 = 99".to_string()); // duplicate of k0
    let input = lines.join("\n");
    let e = ctx.parse_err(&input);
    assert!(
        matches!(e.kind(), ErrorKind::DuplicateKey { .. }),
        "duplicate in indexed table: {:?}",
        e.kind()
    );

    // Duplicate key in inline table with 6+ entries (exercises
    // insert_value_known_to_be_unique bulk indexing and then
    // an immediate duplicate on the 7th entry).
    let mut pairs = Vec::new();
    for i in 0..6 {
        pairs.push(format!("k{i} = {i}"));
    }
    let input = format!("a = {{{}, k0 = 99}}", pairs.join(", "));
    let e = ctx.parse_err(&input);
    assert!(
        matches!(e.kind(), ErrorKind::DuplicateKey { .. }),
        "duplicate in inline table: {:?}",
        e.kind()
    );
}

#[test]
fn crlf_line_endings() {
    let ctx = TestCtx::new();

    // Basic CRLF document
    let v = ctx.parse_ok("a = 1\r\nb = 2\r\n");
    assert_eq!(v["a"].as_i64(), Some(1));
    assert_eq!(v["b"].as_i64(), Some(2));

    // CRLF blank lines between entries (exercises eat_newline CRLF path)
    let v = ctx.parse_ok("a = 1\r\n\r\n\r\nb = 2\r\n");
    assert_eq!(v["a"].as_i64(), Some(1));
    assert_eq!(v["b"].as_i64(), Some(2));

    // CRLF blank lines between table headers
    let v = ctx.parse_ok("[t]\r\nx = 'hello'\r\n\r\n[u]\r\ny = 42\r\n");
    assert_eq!(v["t"]["x"].as_str(), Some("hello"));
    assert_eq!(v["u"]["y"].as_i64(), Some(42));

    // CRLF in array of tables with blank lines
    let v = ctx.parse_ok("[[items]]\r\nval = 1\r\n\r\n[[items]]\r\nval = 2\r\n");
    assert_eq!(v["items"][0]["val"].as_i64(), Some(1));
    assert_eq!(v["items"][1]["val"].as_i64(), Some(2));

    // CRLF with comments
    let v = ctx.parse_ok("# comment\r\n\r\na = 1\r\n");
    assert_eq!(v["a"].as_i64(), Some(1));

    // CRLF after inline table entries
    let v = ctx.parse_ok("t = {\r\n  a = 1,\r\n  b = 2\r\n}\r\n");
    assert_eq!(v["t"]["a"].as_i64(), Some(1));
    assert_eq!(v["t"]["b"].as_i64(), Some(2));

    // CRLF after array entries
    let v = ctx.parse_ok("a = [\r\n  1,\r\n  2,\r\n  3\r\n]\r\n");
    let arr = v["a"].as_array().unwrap();
    assert_eq!(arr.len(), 3);
}

#[test]
fn parse_error_token_descriptions() {
    let ctx = TestCtx::new();

    // Whitespace-only input after key (exercises scan_token_desc_and_end whitespace path)
    let e = ctx.parse_err("key   ");
    assert!(matches!(e.kind(), ErrorKind::Wanted { .. }));

    // Stray colon (exercises scan_token_desc_and_end colon path)
    let e = ctx.parse_err("key : value");
    assert!(matches!(e.kind(), ErrorKind::Wanted { .. }));

    // Stray plus (exercises scan_token_desc_and_end plus path)
    let e = ctx.parse_err("key = +");
    assert!(is_number_error!(e.kind()));

    // Incomplete inline table with whitespace error
    let e = ctx.parse_err("t = { a = 1  ");
    assert!(matches!(e.kind(), ErrorKind::UnclosedInlineTable));

    // Array with trailing error
    let e = ctx.parse_err("a = [1, 2  ");
    assert!(matches!(e.kind(), ErrorKind::UnclosedArray));
}

#[test]
fn error_paths() {
    let ctx = TestCtx::new();

    let path = |e: crate::Error| -> String {
        let components = e.path().expect("expected non-empty path");
        use std::fmt::Write;
        let mut out = String::new();
        for (i, c) in components.iter().enumerate() {
            match c {
                crate::error::PathComponent::Key(k) => {
                    if i > 0 {
                        out.push('.');
                    }
                    out.push_str(k.name);
                }
                crate::error::PathComponent::Index(idx) => {
                    write!(out, "[{idx}]").unwrap();
                }
            }
        }
        out
    };

    // Simple top-level duplicate key
    let e = ctx.parse_err("a = 1\na = 2");
    assert_eq!(path(e), "a");

    // Dotted key error shows full path
    let e = ctx.parse_err("[fruit.apple.taste]\n[fruit]\napple.taste.sweet = true");
    assert_eq!(path(e), "fruit.apple.taste");

    // Table header intermediate error
    let e = ctx.parse_err("[a]\nb = 1\n[a]\nc = 2");
    assert_eq!(path(e), "a");

    // Duplicate key inside a section
    let e = ctx.parse_err("[section]\na = 1\na = 2");
    assert_eq!(path(e), "section.a");

    // AOT shows index
    let e = ctx.parse_err(
        "[[servers]]\nname = 'a'\n[[servers]]\nname = 'b'\n[[servers]]\nname = 'c'\nname = 'd'",
    );
    assert_eq!(path(e), "servers[2].name");

    // Nested AOT intermediate
    let e = ctx.parse_err("[[a]]\n[[a.b]]\nx = 1\n[[a.b]]\nx = 2\nx = 3");
    assert_eq!(path(e), "a[0].b[1].x");

    // Header key error (trailing period)
    let e = ctx.parse_err("[a.]");
    assert_eq!(path(e), "a");
}

// --- parse_recoverable tests ---

#[cfg(feature = "from-toml")]
mod recovering {
    use crate::arena::Arena;

    #[test]
    fn valid_input_no_errors() {
        let arena = Arena::new();
        let doc = crate::parser::parse_recoverable("key = 'value'\nnum = 42\n", &arena);
        assert!(doc.errors().is_empty());
        assert_eq!(doc["key"].as_str(), Some("value"));
        assert_eq!(doc["num"].as_i64(), Some(42));
    }

    #[test]
    fn multiple_value_errors() {
        let input = "good = 1\nbad =\nalso_good = 2\nworse = [}\n";
        let arena = Arena::new();
        let doc = crate::parser::parse_recoverable(input, &arena);
        assert!(doc.errors().len() >= 2);
        assert_eq!(doc["good"].as_i64(), Some(1));
        assert_eq!(doc["also_good"].as_i64(), Some(2));
    }

    #[test]
    fn bad_table_header_recovery() {
        let input = "[valid]\na = 1\n[bad.]\n[another]\nb = 2\n";
        let arena = Arena::new();
        let doc = crate::parser::parse_recoverable(input, &arena);
        assert!(!doc.errors().is_empty());
        assert_eq!(doc["valid"].as_table().unwrap()["a"].as_i64(), Some(1));
        assert_eq!(doc["another"].as_table().unwrap()["b"].as_i64(), Some(2));
    }

    #[test]
    fn error_limit() {
        let mut input = String::new();
        for _ in 0..50 {
            input.push_str("bad =\n");
        }
        let arena = Arena::new();
        let doc = crate::parser::parse_recoverable(&input, &arena);
        assert_eq!(
            doc.errors().len(),
            crate::parser::Parser::MAX_RECOVER_ERRORS
        );
    }

    #[test]
    fn eof_mid_error() {
        let arena = Arena::new();
        let doc = crate::parser::parse_recoverable("[incomplete", &arena);
        assert!(!doc.errors().is_empty());
    }

    #[test]
    fn bare_cr_recovery() {
        let input = "a = 1\n\rb = 2\nc = 3\n";
        let arena = Arena::new();
        let doc = crate::parser::parse_recoverable(input, &arena);
        assert!(!doc.errors().is_empty());
        assert_eq!(doc["a"].as_i64(), Some(1));
        assert_eq!(doc["c"].as_i64(), Some(3));
    }

    #[test]
    fn multiline_inline_table_error() {
        let input = "a = {\n  b = 1,\n  c = \n}\nd = 2\n";
        let arena = Arena::new();
        let doc = crate::parser::parse_recoverable(input, &arena);
        assert!(!doc.errors().is_empty());
        assert_eq!(doc["d"].as_i64(), Some(2));
    }

    #[test]
    fn multiline_array_error() {
        let input = "a = [\n  1,\n  bad,\n  3\n]\nb = 2\n";
        let arena = Arena::new();
        let doc = crate::parser::parse_recoverable(input, &arena);
        assert!(!doc.errors().is_empty());
        assert_eq!(doc["b"].as_i64(), Some(2));
    }

    #[test]
    fn nested_inline_structure_error() {
        let input = "a = {b = [1, {c = }, 3]}\nd = 2\n";
        let arena = Arena::new();
        let doc = crate::parser::parse_recoverable(input, &arena);
        assert!(!doc.errors().is_empty());
        assert_eq!(doc["d"].as_i64(), Some(2));
    }

    #[test]
    fn string_with_brackets_not_confused() {
        let input = "a = \"hello [\"\nb = \"world }\"\nc = 3\n";
        let arena = Arena::new();
        let doc = crate::parser::parse_recoverable(input, &arena);
        assert!(doc.errors().is_empty());
        assert_eq!(doc["a"].as_str(), Some("hello ["));
        assert_eq!(doc["b"].as_str(), Some("world }"));
        assert_eq!(doc["c"].as_i64(), Some(3));
    }

    #[test]
    fn unclosed_inline_table_at_eof() {
        let input = "a = 1\nb = {c = \n";
        let arena = Arena::new();
        let doc = crate::parser::parse_recoverable(input, &arena);
        assert!(!doc.errors().is_empty());
        assert_eq!(doc["a"].as_i64(), Some(1));
    }

    #[test]
    fn unclosed_array_at_eof() {
        let input = "a = 1\nb = [1, 2\n";
        let arena = Arena::new();
        let doc = crate::parser::parse_recoverable(input, &arena);
        assert!(!doc.errors().is_empty());
        assert_eq!(doc["a"].as_i64(), Some(1));
    }

    #[test]
    fn multiline_array_single_bad_element() {
        let input = "before = true\narr = [\n  1,\n  ,\n  3,\n]\nafter = true\n";
        let arena = Arena::new();
        let doc = crate::parser::parse_recoverable(input, &arena);
        assert!(!doc.errors().is_empty());
        assert_eq!(doc["before"].as_bool(), Some(true));
        assert_eq!(doc["after"].as_bool(), Some(true));
    }

    #[test]
    fn error_inside_multiline_string_does_not_cascade() {
        let input = "a = 1\nb = \"unterminated\nc = 2\nd = 3\n";
        let arena = Arena::new();
        let doc = crate::parser::parse_recoverable(input, &arena);
        assert!(!doc.errors().is_empty());
        assert_eq!(doc["a"].as_i64(), Some(1));
        assert_eq!(doc["d"].as_i64(), Some(3));
    }

    #[test]
    fn multiple_sections_with_errors() {
        let input = "\
[s1]
a = 1
b = {bad
[s2]
c = 2
d = [broken
[s3]
e = 3
";
        let arena = Arena::new();
        let doc = crate::parser::parse_recoverable(input, &arena);
        assert!(doc.errors().len() >= 2);
        assert_eq!(doc["s1"].as_table().unwrap()["a"].as_i64(), Some(1));
        assert_eq!(doc["s2"].as_table().unwrap()["c"].as_i64(), Some(2));
        assert_eq!(doc["s3"].as_table().unwrap()["e"].as_i64(), Some(3));
    }
}