eure 0.1.9

Eure core library
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
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
use eure_document::value::Tuple;
use eure_document::{
    document::{EureDocument, source_constructor::SourceConstructor},
    identifier::Identifier,
    path::{ArrayIndexKind, PathSegment},
    source::Comment,
    text::{Language, SyntaxHint, Text, TextParseError},
    value::{ObjectKey, PartialObjectKey, PrimitiveValue},
};
use eure_tree::tree::{InputSpan, RecursiveView};
use eure_tree::{prelude::*, tree::TerminalHandle};
use num_bigint::BigInt;
use regex::Regex;
use std::sync::LazyLock;

use crate::document::{CodeBlockError, DocumentConstructionError, InlineCodeError, OriginMap};

#[derive(Debug, Clone, Default)]
struct TerminalTokens {
    terminals: Vec<TerminalToken>,
}

#[derive(Debug, Clone)] // Added derive
enum TerminalToken {
    Input(InputSpan),
    Dynamic(DynamicTokenId),
}

impl TerminalTokens {
    pub fn new() -> Self {
        Self {
            terminals: Vec::new(),
        }
    }

    pub fn push_terminal(&mut self, token: TerminalData) {
        let new_token = match (self.terminals.last_mut(), token) {
            (Some(TerminalToken::Input(span)), TerminalData::Input(input_span))
                if span.end == input_span.start =>
            {
                span.end = input_span.end;
                return;
            }
            (_, TerminalData::Dynamic(id)) => TerminalToken::Dynamic(id),
            (_, TerminalData::Input(input_span)) => TerminalToken::Input(input_span),
        };
        self.terminals.push(new_token);
    }

    pub fn into_string(
        self,
        input: &str,
        cst: &impl CstFacade,
    ) -> Result<String, DocumentConstructionError> {
        let mut string = String::new();
        for token in self.terminals {
            match token {
                TerminalToken::Input(span) => {
                    string.push_str(&input[span.start as usize..span.end as usize])
                }
                TerminalToken::Dynamic(id) => {
                    let str = cst
                        .dynamic_token(id)
                        .ok_or(DocumentConstructionError::DynamicTokenNotFound(id))?;
                    string.push_str(str);
                }
            }
        }
        Ok(string)
    }

    /// Collect terminal tokens from LitStr1 content list
    pub fn from_lit_str_1_list<F: CstFacade>(
        list: &LitStr1ListHandle,
        tree: &F,
    ) -> Result<Self, DocumentConstructionError> {
        let mut tokens = Self::new();
        if let Some(view) = list.get_view(tree)? {
            let groups = view.get_all(tree)?;
            for group in groups {
                match group.get_view(tree)? {
                    LitStr1ListGroupView::NoSQuote(h) => {
                        let view = h.get_view(tree)?;
                        tokens.push_terminal(view.no_s_quote.get_data(tree)?);
                    }
                    LitStr1ListGroupView::SQuote(h) => {
                        let view = h.get_view(tree)?;
                        tokens.push_terminal(view.s_quote.get_data(tree)?);
                    }
                }
            }
        }
        Ok(tokens)
    }

    /// Collect terminal tokens from LitStr2 content list
    pub fn from_lit_str_2_list<F: CstFacade>(
        list: &LitStr2ListHandle,
        tree: &F,
    ) -> Result<Self, DocumentConstructionError> {
        let mut tokens = Self::new();
        if let Some(view) = list.get_view(tree)? {
            let groups = view.get_all(tree)?;
            for group in groups {
                match group.get_view(tree)? {
                    LitStr2ListGroupView::NoSQuote(h) => {
                        let view = h.get_view(tree)?;
                        tokens.push_terminal(view.no_s_quote.get_data(tree)?);
                    }
                    LitStr2ListGroupView::SQuote(h) => {
                        let view = h.get_view(tree)?;
                        tokens.push_terminal(view.s_quote.get_data(tree)?);
                    }
                }
            }
        }
        Ok(tokens)
    }

    /// Collect terminal tokens from LitStr3 content list
    pub fn from_lit_str_3_list<F: CstFacade>(
        list: &LitStr3ListHandle,
        tree: &F,
    ) -> Result<Self, DocumentConstructionError> {
        let mut tokens = Self::new();
        if let Some(view) = list.get_view(tree)? {
            let groups = view.get_all(tree)?;
            for group in groups {
                match group.get_view(tree)? {
                    LitStr3ListGroupView::NoSQuote(h) => {
                        let view = h.get_view(tree)?;
                        tokens.push_terminal(view.no_s_quote.get_data(tree)?);
                    }
                    LitStr3ListGroupView::SQuote(h) => {
                        let view = h.get_view(tree)?;
                        tokens.push_terminal(view.s_quote.get_data(tree)?);
                    }
                }
            }
        }
        Ok(tokens)
    }
}

// Grammar: /[a-zA-Z0-9-_]*`[^`\r\n]*`/
static INLINE_CODE_1_REGEX: LazyLock<Regex> =
    LazyLock::new(|| Regex::new(r"^([a-zA-Z0-9_-]*)`([^`\r\n]*)`$").unwrap());

// Grammar: /[a-zA-Z0-9-_]*<`/ (DelimCodeStart1)
static DELIM_CODE_START_1_REGEX: LazyLock<Regex> =
    LazyLock::new(|| Regex::new(r"^([a-zA-Z0-9_-]*)<`$").unwrap());

// Grammar: /[a-zA-Z0-9-_]*<<`/ (DelimCodeStart2)
static DELIM_CODE_START_2_REGEX: LazyLock<Regex> =
    LazyLock::new(|| Regex::new(r"^([a-zA-Z0-9_-]*)<<`$").unwrap());

// Grammar: /[a-zA-Z0-9-_]*<<<`/ (DelimCodeStart3)
static DELIM_CODE_START_3_REGEX: LazyLock<Regex> =
    LazyLock::new(|| Regex::new(r"^([a-zA-Z0-9_-]*)<<<`$").unwrap());

// Grammar: /`{n}[a-zA-Z0-9-_]*[\s--\r\n]*(\r\n|\r|\n)/
// [\s--\r\n]* means whitespace except \r\n, i.e., [ \t]*
static CODE_BLOCK_START_REGEX: LazyLock<Regex> =
    LazyLock::new(|| Regex::new(r"^`+([a-zA-Z0-9_-]*)[ \t]*(?:\r\n|\r|\n)$").unwrap());

// Pattern to validate <int>.<int> for Float keys
// This matches integer.integer patterns without signs, exponents, or suffixes
static INT_DOT_INT_PATTERN: LazyLock<Regex> =
    LazyLock::new(|| Regex::new(r"^(\d[\d_]*)\.(\d[\d_]*)$").unwrap());

/// Stored origin for code blocks and delimited code
#[derive(Debug, Clone, Copy)]
enum CodeOrigin {
    DelimCode1(DelimCode1Handle),
    DelimCode2(DelimCode2Handle),
    DelimCode3(DelimCode3Handle),
    CodeBlock(CodeBlockHandle),
}

struct CodeStart {
    language: Language,
    syntax_hint: SyntaxHint,
    terminals: TerminalTokens,
    origin: Option<CodeOrigin>,
}

impl CodeStart {
    fn new(language: Language, syntax_hint: SyntaxHint) -> Self {
        Self {
            language,
            syntax_hint,
            terminals: TerminalTokens::new(),
            origin: None,
        }
    }

    fn with_origin(language: Language, syntax_hint: SyntaxHint, origin: CodeOrigin) -> Self {
        Self {
            language,
            syntax_hint,
            terminals: TerminalTokens::new(),
            origin: Some(origin),
        }
    }
}

pub struct CstInterpreter<'a> {
    input: &'a str,
    // Main document being built
    document: SourceConstructor,
    code_start: Option<CodeStart>,
    // Stack for collecting PartialObjectKeys when processing KeyTuple
    collecting_partial_keys: Vec<Vec<PartialObjectKey>>,
    // Origin tracking for error span resolution
    origins: OriginMap,
    // Pending code origin - set by parent visitor, used by start visitor
    pending_code_origin: Option<CodeOrigin>,
    // Count of consecutive newline terminals since the last non-trivia token/comment.
    pending_newlines: usize,
}

impl<'a> CstInterpreter<'a> {
    pub fn new(input: &'a str) -> Self {
        Self {
            input,
            document: SourceConstructor::new(),
            code_start: None,
            collecting_partial_keys: vec![],
            origins: OriginMap::new(),
            pending_code_origin: None,
            pending_newlines: 0,
        }
    }

    /// Parse language from InlineCode1 token: [lang]`content`
    /// Grammar: /[a-zA-Z0-9-_]*`[^`\r\n]*`/
    /// Language tag must be alphanumeric/hyphen/underscore only, no whitespace
    fn parse_inline_code_1(token: &str) -> Result<(Language, String), InlineCodeError> {
        let caps = INLINE_CODE_1_REGEX
            .captures(token)
            .ok_or(InlineCodeError::InvalidInlineCode1Pattern)?;

        let lang = caps.get(1).unwrap().as_str();
        let content = caps.get(2).unwrap().as_str();

        let language = if lang.is_empty() {
            Language::Implicit
        } else {
            Language::new(lang.to_string())
        };
        Ok((language, content.to_string()))
    }

    /// Parse language from DelimCodeStart1 token: [lang]<`
    /// Grammar: /[a-zA-Z0-9-_]*<`/
    fn parse_delim_code_start_1(token: &str) -> Result<Language, InlineCodeError> {
        let caps = DELIM_CODE_START_1_REGEX
            .captures(token)
            .ok_or(InlineCodeError::InvalidDelimCodeStartPattern)?;

        let lang = caps.get(1).unwrap().as_str();
        let language = if lang.is_empty() {
            Language::Implicit
        } else {
            Language::new(lang.to_string())
        };
        Ok(language)
    }

    /// Parse language from DelimCodeStart2 token: [lang]<<`
    /// Grammar: /[a-zA-Z0-9-_]*<<`/
    fn parse_delim_code_start_2(token: &str) -> Result<Language, InlineCodeError> {
        let caps = DELIM_CODE_START_2_REGEX
            .captures(token)
            .ok_or(InlineCodeError::InvalidDelimCodeStartPattern)?;

        let lang = caps.get(1).unwrap().as_str();
        let language = if lang.is_empty() {
            Language::Implicit
        } else {
            Language::new(lang.to_string())
        };
        Ok(language)
    }

    /// Parse language from DelimCodeStart3 token: [lang]<<<`
    /// Grammar: /[a-zA-Z0-9-_]*<<<`/
    fn parse_delim_code_start_3(token: &str) -> Result<Language, InlineCodeError> {
        let caps = DELIM_CODE_START_3_REGEX
            .captures(token)
            .ok_or(InlineCodeError::InvalidDelimCodeStartPattern)?;

        let lang = caps.get(1).unwrap().as_str();
        let language = if lang.is_empty() {
            Language::Implicit
        } else {
            Language::new(lang.to_string())
        };
        Ok(language)
    }

    /// Parse language from CodeBlockStart token: ```[lang]\n or ````[lang]\n etc.
    /// Grammar: /`{n}[a-zA-Z0-9-_]*[\s--\r\n]*(\r\n|\r|\n)/
    /// Language tag must be alphanumeric/hyphen/underscore only, followed by optional whitespace (space/tab, not newlines)
    fn parse_code_block_start(token: &str) -> Result<Language, CodeBlockError> {
        let caps = CODE_BLOCK_START_REGEX
            .captures(token)
            .ok_or(CodeBlockError::InvalidCodeBlockStartPattern)?;

        let lang = caps.get(1).unwrap().as_str();
        let language = if lang.is_empty() {
            Language::Implicit
        } else {
            Language::new(lang.to_string())
        };
        Ok(language)
    }

    pub fn into_document(self) -> EureDocument {
        self.document.finish().document
    }

    pub fn into_document_and_origin_map(self) -> (EureDocument, OriginMap) {
        (self.document.finish().document, self.origins)
    }

    pub fn into_source_document(self) -> eure_document::source::SourceDocument {
        self.document.finish()
    }

    /// Record a definition span for a node (typically the key).
    fn record_definition(
        &mut self,
        node_id: eure_document::document::NodeId,
        cst_node_id: CstNodeId,
    ) {
        self.origins.record_definition(node_id, cst_node_id);
    }

    /// Record a value span for a node (the full expression).
    fn record_value(&mut self, node_id: eure_document::document::NodeId, cst_node_id: CstNodeId) {
        self.origins.record_value(node_id, cst_node_id);
    }

    /// Record a map key origin for precise error spans.
    fn record_key_origin(
        &mut self,
        map_node_id: eure_document::document::NodeId,
        key: ObjectKey,
        cst_node_id: CstNodeId,
    ) {
        self.origins.record_key(map_node_id, key, cst_node_id);
    }

    fn get_terminal_str<T: TerminalHandle>(
        &'a self,
        tree: &'a impl CstFacade,
        handle: T,
    ) -> Result<&'a str, DocumentConstructionError> {
        match tree.get_terminal_str(self.input, handle)? {
            Ok(str) => Ok(str),
            Err(id) => Err(DocumentConstructionError::DynamicTokenNotFound(id)),
        }
    }

    fn flush_blank_lines(&mut self) {
        for _ in 1..self.pending_newlines {
            self.document.blank_line();
        }
        self.pending_newlines = 0;
    }

    /// Parse a Str terminal (with surrounding quotes) into a String
    fn parse_str_terminal(
        &self,
        str_handle: StrHandle,
        tree: &impl CstFacade,
    ) -> Result<String, DocumentConstructionError> {
        let str_view = str_handle.get_view(tree)?;
        let str_with_quotes = self.get_terminal_str(tree, str_view.str)?;

        // Remove surrounding quotes
        let str_content = str_with_quotes
            .strip_prefix('"')
            .and_then(|s| s.strip_suffix('"'))
            .ok_or_else(|| DocumentConstructionError::InvalidStringKey {
                node_id: str_handle.node_id(),
                error: TextParseError::InvalidEndOfStringAfterEscape,
            })?;

        // Parse the string content
        let text = Text::parse_quoted_string(str_content).map_err(|error| {
            DocumentConstructionError::InvalidStringKey {
                node_id: str_handle.node_id(),
                error,
            }
        })?;

        Ok(text.content)
    }

    fn get_key_ident_str(
        &'a self,
        tree: &'a impl CstFacade,
        ident_handle: KeyIdentHandle,
    ) -> Result<&'a str, DocumentConstructionError> {
        let ident_view = ident_handle.get_view(tree)?;
        let ident_str = match ident_view {
            KeyIdentView::Ident(ident_handle) => {
                self.get_terminal_str(tree, ident_handle.get_view(tree)?.ident)?
            }
            KeyIdentView::True(true_handle) => {
                self.get_terminal_str(tree, true_handle.get_view(tree)?.r#true)?
            }
            KeyIdentView::False(false_handle) => {
                self.get_terminal_str(tree, false_handle.get_view(tree)?.r#false)?
            }
            KeyIdentView::Null(null_handle) => {
                self.get_terminal_str(tree, null_handle.get_view(tree)?.r#null)?
            }
        };
        Ok(ident_str)
    }

    /// Handle Float token in key position by splitting <int>.<int> into two integer keys
    fn handle_float_as_integer_keys<F: CstFacade>(
        &mut self,
        float_handle: FloatHandle,
        tree: &F,
    ) -> Result<(), DocumentConstructionError> {
        let float_view = float_handle.get_view(tree)?;
        let str = self.get_terminal_str(tree, float_view.float)?;

        // Get the Float token's InputSpan for calculating sub-spans
        let float_span = tree.span(float_handle.node_id()).ok_or_else(|| {
            DocumentConstructionError::InvalidFloatKey {
                node_id: float_handle.node_id(),
                value: str.to_string(),
            }
        })?;

        // Validate <int>.<int> pattern (no exponent, no suffix, no sign)
        let captures = INT_DOT_INT_PATTERN.captures(str).ok_or_else(|| {
            DocumentConstructionError::InvalidFloatKey {
                node_id: float_handle.node_id(),
                value: str.to_string(),
            }
        })?;

        // Parse first integer
        let first_int_str = &captures[1];
        let first_big_int: BigInt = first_int_str
            .replace('_', "")
            .parse()
            .map_err(|_| DocumentConstructionError::InvalidBigInt(first_int_str.to_string()))?;
        let first_key = ObjectKey::Number(first_big_int);

        // Parse second integer
        let second_int_str = &captures[2];
        let second_big_int: BigInt = second_int_str
            .replace('_', "")
            .parse()
            .map_err(|_| DocumentConstructionError::InvalidBigInt(second_int_str.to_string()))?;
        let second_key = ObjectKey::Number(second_big_int);

        // Calculate precise sub-spans
        // For "3.1": float_span covers all 3 bytes
        // First int "3": from start to start + len(first_int_str)
        // Second int "1": from (start + len(first_int_str) + 1) to end (skip the dot)
        let first_span = InputSpan::new(
            float_span.start,
            float_span.start + first_int_str.len() as u32,
        );
        let second_span = InputSpan::new(
            float_span.start + first_int_str.len() as u32 + 1, // +1 for the dot
            float_span.end,
        );

        // Record origin for FIRST key with precise span
        let first_container_id = self.document.current_node_id();
        self.origins
            .record_key_span(first_container_id, first_key.clone(), first_span);
        // Also record by CST node ID for error reporting
        self.origins
            .record_key_span_by_cst(float_handle.node_id(), first_key.clone(), first_span);

        // Navigate to FIRST integer key
        let float_node_id = float_handle.node_id(); // Capture before move
        self.document
            .navigate(PathSegment::Value(first_key))
            .map_err(|e| DocumentConstructionError::DocumentInsert {
                error: e,
                node_id: float_node_id, // Use Float token's CST node ID
                parent_node_id: Some(first_container_id),
            })?;

        let first_child_id = self.document.current_node_id();
        self.record_definition(first_child_id, float_handle.node_id());

        // Record origin for SECOND key with precise span
        let second_container_id = self.document.current_node_id();
        self.origins
            .record_key_span(second_container_id, second_key.clone(), second_span);
        // Also record by CST node ID for error reporting
        self.origins.record_key_span_by_cst(
            float_handle.node_id(),
            second_key.clone(),
            second_span,
        );

        // Navigate to SECOND integer key
        let float_node_id = float_handle.node_id(); // Capture before closure
        self.document
            .navigate(PathSegment::Value(second_key.clone()))
            .map_err(|e| DocumentConstructionError::DocumentInsert {
                error: e,
                node_id: float_node_id, // Use Float token's CST node ID
                parent_node_id: Some(second_container_id),
            })?;

        let second_child_id = self.document.current_node_id();
        self.record_definition(second_child_id, float_handle.node_id());

        Ok(())
    }
}

impl<F: CstFacade> CstVisitor<F> for CstInterpreter<'_> {
    type Error = DocumentConstructionError;

    fn visit_eure(
        &mut self,
        handle: EureHandle,
        view: EureView,
        tree: &F,
    ) -> Result<(), Self::Error> {
        let root_id = self.document.current_node_id();

        // Only record value span for the true document root (not for section bodies).
        // Section bodies get their value span from visit_section.
        if root_id == self.document.document().get_root_id() {
            self.record_value(root_id, handle.node_id());
        }

        // Visit children using the default super implementation
        self.visit_eure_super(handle, view, tree)?;
        // Check if Eure is truly empty (no ValueBinding, no Bindings, no Sections)
        let has_value_binding = view.eure_opt.get_view(tree)?.is_some();
        if self.document.current_node().content.is_hole() && !has_value_binding {
            self.document.bind_empty_map().map_err(|e| {
                DocumentConstructionError::DocumentInsert {
                    error: e,
                    node_id: handle.node_id(),
                    parent_node_id: None,
                }
            })?;
        }
        Ok(())
    }

    fn visit_object(
        &mut self,
        handle: ObjectHandle,
        view: ObjectView,
        tree: &F,
    ) -> Result<(), Self::Error> {
        // Record the object container value span
        let container_id = self.document.current_node_id();
        self.record_value(container_id, handle.node_id());

        self.document.suspend_path_tracking();
        let result = (|| {
            // Check if there's a value binding (new syntax: { = value, ... })
            let has_value_binding = if let Some(object_opt_view) = view.object_opt.get_view(tree)? {
                // Visit the value binding - this binds the main value
                self.visit_value_binding_handle(object_opt_view.value_binding, tree)?;
                true
            } else {
                false
            };

            // Process each entry in the ObjectList
            // Each entry has: keys => value
            // The keys can be nested (e.g., a.b => 1 becomes { a => { b => 1 } })
            if let Some(object_list_view) = view.object_list.get_view(tree)? {
                for item in object_list_view.get_all(tree)? {
                    let scope = self.document.begin_scope();

                    // Navigate through the keys
                    self.visit_keys_handle(item.keys, tree)?;

                    // Validate binding target is a Hole
                    let node_id = self.document.current_node_id();
                    self.document.require_hole().map_err(|e| {
                        DocumentConstructionError::DocumentInsert {
                            error: e,
                            node_id: handle.node_id(),
                            parent_node_id: None,
                        }
                    })?;

                    // Record value span for this object entry
                    self.record_value(node_id, item.keys.node_id());

                    // Visit the value
                    self.visit_value_handle(item.value, tree)?;

                    // Restore to the Object level
                    self.document.end_scope(scope).map_err(|e| {
                        DocumentConstructionError::DocumentInsert {
                            error: e,
                            node_id: handle.node_id(),
                            parent_node_id: None,
                        }
                    })?;
                }
            }

            if self.document.current_node().content.is_hole() && !has_value_binding {
                // Empty object (no value binding, no entries)
                self.document.bind_empty_map().map_err(|e| {
                    DocumentConstructionError::DocumentInsert {
                        error: e,
                        node_id: handle.node_id(),
                        parent_node_id: None,
                    }
                })?;
            }

            self.document.set_last_bound_node(container_id);

            Ok(())
        })();
        self.document.resume_path_tracking();
        result
    }

    fn visit_array(
        &mut self,
        handle: ArrayHandle,
        view: ArrayView,
        tree: &F,
    ) -> Result<(), Self::Error> {
        // Record the array container value span
        let container_id = self.document.current_node_id();
        self.record_value(container_id, handle.node_id());

        self.document.suspend_path_tracking();
        let result = (|| {
            // Process array elements
            if let Some(elements_handle) = view.array_opt.get_view(tree)? {
                // Iterate through array elements
                let mut current = Some(elements_handle);
                let mut index = 0usize;

                while let Some(elem_handle) = current {
                    let elem_view = elem_handle.get_view(tree)?;

                    // Begin scope and navigate to array index
                    let scope = self.document.begin_scope();
                    let node_id = self
                        .document
                        .navigate(PathSegment::ArrayIndex(ArrayIndexKind::Specific(index)))
                        .map_err(|e| DocumentConstructionError::DocumentInsert {
                            error: e,
                            node_id: handle.node_id(),
                            parent_node_id: None,
                        })?;

                    // Record value span for this array element
                    self.record_value(node_id, handle.node_id());

                    // Visit the value at this index
                    self.visit_value_handle(elem_view.value, tree)?;

                    // End scope to return to array level
                    self.document.end_scope(scope).map_err(|e| {
                        DocumentConstructionError::DocumentInsert {
                            error: e,
                            node_id: handle.node_id(),
                            parent_node_id: None,
                        }
                    })?;

                    // Move to next element if any
                    current =
                        if let Some(tail_handle) = elem_view.array_elements_opt.get_view(tree)? {
                            let tail_view = tail_handle.get_view(tree)?;
                            tail_view.array_elements_tail_opt.get_view(tree)?
                        } else {
                            None
                        };

                    index += 1;
                }
            } else {
                self.document.bind_empty_array().map_err(|e| {
                    DocumentConstructionError::DocumentInsert {
                        error: e,
                        node_id: handle.node_id(),
                        parent_node_id: None,
                    }
                })?;
            }

            self.document.set_last_bound_node(container_id);

            Ok(())
        })();
        self.document.resume_path_tracking();
        result
    }

    fn visit_tuple(
        &mut self,
        handle: TupleHandle,
        view: TupleView,
        tree: &F,
    ) -> Result<(), Self::Error> {
        // Record the tuple container value span
        let container_id = self.document.current_node_id();
        self.record_value(container_id, handle.node_id());

        self.document.suspend_path_tracking();
        let result = (|| {
            // Process tuple elements (similar to array but with TupleIndex path segment)
            if let Some(elements_handle) = view.tuple_opt.get_view(tree)? {
                // Iterate through tuple elements
                let mut current = Some(elements_handle);
                let mut index = 0u8;

                while let Some(elem_handle) = current {
                    let elem_view = elem_handle.get_view(tree)?;

                    // Begin scope and navigate to tuple index
                    let scope = self.document.begin_scope();
                    let node_id = self
                        .document
                        .navigate(PathSegment::TupleIndex(index))
                        .map_err(|e| DocumentConstructionError::DocumentInsert {
                            error: e,
                            node_id: handle.node_id(),
                            parent_node_id: None,
                        })?;

                    // Record value span for this tuple element
                    self.record_value(node_id, handle.node_id());

                    // Visit the value at this index
                    self.visit_value_handle(elem_view.value, tree)?;

                    // End scope to return to tuple level
                    self.document.end_scope(scope).map_err(|e| {
                        DocumentConstructionError::DocumentInsert {
                            error: e,
                            node_id: handle.node_id(),
                            parent_node_id: None,
                        }
                    })?;

                    // Move to next element if any
                    current =
                        if let Some(tail_handle) = elem_view.tuple_elements_opt.get_view(tree)? {
                            let tail_view = tail_handle.get_view(tree)?;
                            tail_view.tuple_elements_tail_opt.get_view(tree)?
                        } else {
                            None
                        };

                    index = index.saturating_add(1);
                }
            } else {
                self.document.bind_empty_tuple().map_err(|e| {
                    DocumentConstructionError::DocumentInsert {
                        error: e,
                        node_id: handle.node_id(),
                        parent_node_id: None,
                    }
                })?;
            }

            self.document.set_last_bound_node(container_id);

            Ok(())
        })();
        self.document.resume_path_tracking();
        result
    }

    fn visit_key(&mut self, handle: KeyHandle, view: KeyView, tree: &F) -> Result<(), Self::Error> {
        // Special handling for Float -> two integer keys
        if let KeyView::Float(float_handle) = view {
            return self.handle_float_as_integer_keys(float_handle, tree);
        }

        // Capture container node ID before navigation (for key origin tracking)
        let container_id = self.document.current_node_id();

        if let KeyView::Hole(hole_handle) = view {
            let hole_view = hole_handle.get_view(tree)?;
            let token_str = self.get_terminal_str(tree, hole_view.hole)?;
            let label = if token_str == "!" {
                None
            } else {
                Some(token_str[1..].parse::<Identifier>()?)
            };
            let key_cst_node = hole_handle.node_id();
            self.document
                .navigate_partial_map_entry(PartialObjectKey::Hole(label))
                .map_err(|e| DocumentConstructionError::DocumentInsert {
                    error: e,
                    node_id: handle.node_id(),
                    parent_node_id: Some(container_id),
                })?;
            let child_id = self.document.current_node_id();
            self.record_definition(child_id, key_cst_node);
            return Ok(());
        }

        // Build segment and optionally capture key origin info for ObjectKey-based keys
        let (segment, key_origin_info) = match view {
            KeyView::KeyIdent(ident_handle) => {
                let ident_str = self.get_key_ident_str(tree, ident_handle)?;
                let identifier: Identifier = ident_str.parse()?;
                // Record key origin as string key (identifiers become string keys in maps)
                let object_key = ObjectKey::String(ident_str.to_string());
                (
                    PathSegment::Ident(identifier),
                    Some((object_key, ident_handle.node_id())),
                )
            }
            KeyView::ExtensionNameSpace(ext_handle) => {
                let ext_view = ext_handle.get_view(tree)?;
                let ident_str = self.get_key_ident_str(tree, ext_view.key_ident)?;
                let identifier: Identifier = ident_str.parse()?;
                (PathSegment::Extension(identifier), None)
            }
            KeyView::String(string_handle) => {
                let content = self.parse_string(string_handle, tree)?;
                let object_key = ObjectKey::String(content);
                (
                    PathSegment::Value(object_key.clone()),
                    Some((object_key, string_handle.node_id())),
                )
            }
            KeyView::Integer(int_handle) => {
                let int_view = int_handle.get_view(tree)?;
                let str = self.get_terminal_str(tree, int_view.integer)?;
                let big_int: BigInt = str
                    .parse()
                    .map_err(|_| DocumentConstructionError::InvalidBigInt(str.to_string()))?;
                let object_key = ObjectKey::Number(big_int);
                (
                    PathSegment::Value(object_key.clone()),
                    Some((object_key, int_handle.node_id())),
                )
            }
            KeyView::KeyTuple(tuple_handle) => {
                self.collecting_partial_keys.push(vec![]);
                self.visit_key_tuple_handle(tuple_handle, tree)?;
                let keys = self.collecting_partial_keys.pop().expect(
                    "collecting_partial_keys stack should not be empty after visiting KeyTuple",
                );
                let object_keys: Result<Vec<_>, _> =
                    keys.iter().cloned().map(ObjectKey::try_from).collect();
                if object_keys.is_err() {
                    let partial_key = PartialObjectKey::Tuple(Tuple(keys));
                    self.document
                        .navigate_partial_map_entry(partial_key)
                        .map_err(|e| DocumentConstructionError::DocumentInsert {
                            error: e,
                            node_id: handle.node_id(),
                            parent_node_id: Some(container_id),
                        })?;
                    let child_id = self.document.current_node_id();
                    self.record_definition(child_id, tuple_handle.node_id());
                    return Ok(());
                }

                let object_key = ObjectKey::Tuple(Tuple(
                    object_keys.expect("tuple key without holes must convert"),
                ));
                (
                    PathSegment::Value(object_key.clone()),
                    Some((object_key, tuple_handle.node_id())),
                )
            }
            KeyView::TupleIndex(tuple_index_handle) => {
                let tuple_index_view = tuple_index_handle.get_view(tree)?;
                let int_view = tuple_index_view.integer.get_view(tree)?;
                let str = self.get_terminal_str(tree, int_view.integer)?;
                let length: u8 =
                    str.parse()
                        .map_err(|_| DocumentConstructionError::InvalidTupleIndex {
                            node_id: tuple_index_handle.node_id(),
                            value: str.to_string(),
                        })?;
                (PathSegment::TupleIndex(length), None)
            }
            KeyView::Float(_) => unreachable!("handled above"),
            KeyView::Hole(_) => unreachable!("handled above"),
        };

        // Capture CST node ID before consuming key_origin_info
        let key_cst_node = key_origin_info.as_ref().map(|(_, id)| *id);

        // Record key origin for ObjectKey-based segments (for precise error spans)
        if let Some((object_key, key_cst_node_id)) = key_origin_info {
            self.record_key_origin(container_id, object_key, key_cst_node_id);
        }

        // Navigate to this segment
        self.document
            .navigate(segment)
            .map_err(|e| DocumentConstructionError::DocumentInsert {
                error: e,
                node_id: handle.node_id(),
                parent_node_id: None,
            })?;

        // Record definition span for the navigated node using the key's CST span
        // This ensures MissingRequiredField errors point to the defining key
        if let Some(cst_node_id) = key_cst_node {
            let child_id = self.document.current_node_id();
            self.record_definition(child_id, cst_node_id);
        }

        Ok(())
    }

    fn visit_array_marker(
        &mut self,
        handle: ArrayMarkerHandle,
        view: ArrayMarkerView,
        tree: &F,
    ) -> Result<(), Self::Error> {
        let kind = if let Some(group_handle) = view.array_marker_opt.get_view(tree)? {
            match group_handle.get_view(tree)? {
                ArrayMarkerOptGroupView::Integer(int_handle) => {
                    let int_view = int_handle.get_view(tree)?;
                    let str = self.get_terminal_str(tree, int_view.integer)?;
                    let index: usize = str
                        .parse()
                        .map_err(|_| DocumentConstructionError::InvalidInteger(str.to_string()))?;
                    ArrayIndexKind::Specific(index)
                }
                ArrayMarkerOptGroupView::Caret(_) => ArrayIndexKind::Current,
            }
        } else {
            ArrayIndexKind::Push
        };
        self.document
            .navigate(PathSegment::ArrayIndex(kind))
            .map_err(|e| DocumentConstructionError::DocumentInsert {
                error: e,
                node_id: handle.node_id(),
                parent_node_id: None,
            })?;
        Ok(())
    }

    fn visit_key_value(
        &mut self,
        _handle: KeyValueHandle,
        view: KeyValueView,
        tree: &F,
    ) -> Result<(), Self::Error> {
        let partial_key = match view {
            KeyValueView::Integer(int_handle) => {
                let int_view = int_handle.get_view(tree)?;
                let str = self.get_terminal_str(tree, int_view.integer)?;
                let big_int: BigInt = str
                    .parse()
                    .map_err(|_| DocumentConstructionError::InvalidBigInt(str.to_string()))?;
                PartialObjectKey::Number(big_int)
            }
            KeyValueView::Boolean(bool_handle) => {
                let bool_view = bool_handle.get_view(tree)?;
                match bool_view {
                    BooleanView::True(_) => PartialObjectKey::String("true".to_string()),
                    BooleanView::False(_) => PartialObjectKey::String("false".to_string()),
                }
            }
            KeyValueView::Str(str_handle) => {
                let result = self.parse_str_terminal(str_handle, tree)?;
                PartialObjectKey::String(result)
            }
            KeyValueView::KeyTuple(tuple_handle) => {
                // Recursively handle nested tuple
                self.collecting_partial_keys.push(vec![]);
                self.visit_key_tuple_handle(tuple_handle, tree)?;
                let keys = self.collecting_partial_keys.pop().expect(
                    "collecting_partial_keys stack should not be empty after visiting KeyTuple",
                );
                PartialObjectKey::Tuple(Tuple(keys))
            }
            KeyValueView::Hole(hole_handle) => {
                let hole_view = hole_handle.get_view(tree)?;
                let token_str = self.get_terminal_str(tree, hole_view.hole)?;
                let label = if token_str == "!" {
                    None
                } else {
                    Some(token_str[1..].parse::<Identifier>()?)
                };
                PartialObjectKey::Hole(label)
            }
        };

        // Add to current collection
        self.collecting_partial_keys
            .last_mut()
            .expect("collecting_partial_keys stack should not be empty when visiting KeyValue")
            .push(partial_key);

        Ok(())
    }

    fn visit_binding(
        &mut self,
        handle: BindingHandle,
        view: BindingView,
        tree: &F,
    ) -> Result<(), Self::Error> {
        self.document.begin_binding();
        let scope = self.document.begin_scope();

        // Navigate through the keys
        self.visit_keys_handle(view.keys, tree)?;

        // Validate binding target is a Hole
        let node_id = self.document.current_node_id();
        self.document
            .require_hole()
            .map_err(|e| DocumentConstructionError::DocumentInsert {
                error: e,
                node_id: handle.node_id(),
                parent_node_id: None,
            })?;

        self.record_value(node_id, handle.node_id());

        // Determine if this is a block binding (SectionBinding) or value binding
        let binding_rhs_view = view.binding_rhs.get_view(tree)?;
        let is_block = matches!(binding_rhs_view, BindingRhsView::SectionBinding(_));

        if is_block {
            self.document.begin_eure_block();
        }

        self.visit_binding_rhs_handle(view.binding_rhs, tree)?;

        if is_block {
            self.document.end_eure_block().map_err(|e| {
                DocumentConstructionError::DocumentInsert {
                    error: e,
                    node_id: handle.node_id(),
                    parent_node_id: None,
                }
            })?;
        }

        self.document
            .end_scope(scope)
            .map_err(|e| DocumentConstructionError::DocumentInsert {
                error: e,
                node_id: handle.node_id(),
                parent_node_id: None,
            })?;

        if is_block {
            self.document.end_binding_block().map_err(|e| {
                DocumentConstructionError::DocumentInsert {
                    error: e,
                    node_id: handle.node_id(),
                    parent_node_id: None,
                }
            })?;
        } else {
            self.document.end_binding_value().map_err(|e| {
                DocumentConstructionError::DocumentInsert {
                    error: e,
                    node_id: handle.node_id(),
                    parent_node_id: None,
                }
            })?;
        }
        Ok(())
    }

    fn visit_section(
        &mut self,
        handle: SectionHandle,
        view: SectionView,
        tree: &F,
    ) -> Result<(), Self::Error> {
        let SectionView {
            at: _,
            keys,
            section_body,
        } = view;

        self.document.begin_section();
        let scope = self.document.begin_scope();

        // Navigate through the keys
        self.visit_keys_handle(keys, tree)?;

        // Validate section target is unbound
        let node_id = self.document.current_node_id();
        self.document
            .require_hole()
            .map_err(|e| DocumentConstructionError::DocumentInsert {
                error: e,
                node_id: handle.node_id(),
                parent_node_id: None,
            })?;

        self.record_value(node_id, handle.node_id());

        // Determine if this is a block section (@ path { }) or item section (@ path)
        let section_body_view = section_body.get_view(tree)?;
        let is_block = matches!(section_body_view, SectionBodyView::BlockBody(_));

        if is_block {
            self.document.begin_eure_block();
        } else {
            self.document.begin_section_items();
        }

        self.visit_section_body_handle(section_body, tree)?;

        if is_block {
            self.document.end_eure_block().map_err(|e| {
                DocumentConstructionError::DocumentInsert {
                    error: e,
                    node_id: handle.node_id(),
                    parent_node_id: None,
                }
            })?;
        }

        self.document
            .end_scope(scope)
            .map_err(|e| DocumentConstructionError::DocumentInsert {
                error: e,
                node_id: handle.node_id(),
                parent_node_id: None,
            })?;

        if is_block {
            self.document.end_section_block().map_err(|e| {
                DocumentConstructionError::DocumentInsert {
                    error: e,
                    node_id: handle.node_id(),
                    parent_node_id: None,
                }
            })?;
        } else {
            self.document.end_section_items().map_err(|e| {
                DocumentConstructionError::DocumentInsert {
                    error: e,
                    node_id: handle.node_id(),
                    parent_node_id: None,
                }
            })?;
        }
        Ok(())
    }

    fn visit_section_body(
        &mut self,
        handle: SectionBodyHandle,
        view: SectionBodyView,
        tree: &F,
    ) -> Result<(), Self::Error> {
        match view {
            SectionBodyView::SectionBodyOpt(section_body_opt) => {
                if let Some(flat_body_handle) = section_body_opt.get_view(tree)? {
                    self.visit_flat_body_handle(flat_body_handle, tree)?;
                } else {
                    // Empty section body (no newline, no bindings): bind as empty map
                    self.document.bind_empty_map().map_err(|e| {
                        DocumentConstructionError::DocumentInsert {
                            error: e,
                            node_id: handle.node_id(),
                            parent_node_id: None,
                        }
                    })?;
                }
            }
            SectionBodyView::BlockBody(_) => {
                self.visit_section_body_super(handle, view, tree)?;
            }
        }
        Ok(())
    }

    fn visit_flat_body(
        &mut self,
        handle: FlatBodyHandle,
        view: FlatBodyView,
        tree: &F,
    ) -> Result<(), Self::Error> {
        let section_head_view = view.section_head.get_view(tree)?;
        let has_bindings = view.flat_body_list.get_view(tree)?.is_some();
        let has_root_binding = match &section_head_view {
            SectionHeadView::RootBinding(_) => true,
            SectionHeadView::NewlineHead(newline_head_handle) => {
                let newline_head_view = newline_head_handle.get_view(tree)?;
                newline_head_view.newline_head_opt.get_view(tree)?.is_some()
            }
        };
        let is_empty = !has_root_binding && !has_bindings;

        if is_empty {
            // Empty section body (just a newline, no bindings): bind as empty map
            self.document.bind_empty_map().map_err(|e| {
                DocumentConstructionError::DocumentInsert {
                    error: e,
                    node_id: handle.node_id(),
                    parent_node_id: None,
                }
            })?;
        } else {
            self.visit_flat_body_super(handle, view, tree)?;
        }
        Ok(())
    }

    fn visit_root_text_binding(
        &mut self,
        handle: RootTextBindingHandle,
        view: RootTextBindingView,
        tree: &F,
    ) -> Result<(), Self::Error> {
        let text_view = view.root_text_binding_opt_0.get_view(tree)?;
        let text = if let Some(text_handle) = text_view {
            let text_view = text_handle.get_view(tree)?;
            let text_str = self.get_terminal_str(tree, text_view.text)?;
            Text::parse_text_binding(text_str).map_err(|error| {
                DocumentConstructionError::InvalidStringKey {
                    node_id: text_handle.node_id(),
                    error,
                }
            })?
        } else {
            Text::new(String::new(), Language::Plaintext)
        };
        let node_id = self.document.current_node_id();
        self.document
            .bind_primitive(PrimitiveValue::Text(text))
            .map_err(|e| DocumentConstructionError::DocumentInsert {
                error: e,
                node_id: handle.node_id(),
                parent_node_id: None,
            })?;
        self.record_value(node_id, handle.node_id());
        Ok(())
    }

    fn visit_null(
        &mut self,
        handle: NullHandle,
        _view: NullView,
        _tree: &F,
    ) -> Result<(), Self::Error> {
        let node_id = self.document.current_node_id();
        self.document
            .bind_primitive(PrimitiveValue::Null)
            .map_err(|e| DocumentConstructionError::DocumentInsert {
                error: e,
                node_id: handle.node_id(),
                parent_node_id: None,
            })?;
        self.record_value(node_id, handle.node_id());
        Ok(())
    }

    fn visit_true(
        &mut self,
        handle: TrueHandle,
        _view: TrueView,
        _tree: &F,
    ) -> Result<(), Self::Error> {
        let node_id = self.document.current_node_id();
        self.document
            .bind_primitive(PrimitiveValue::Bool(true))
            .map_err(|e| DocumentConstructionError::DocumentInsert {
                error: e,
                node_id: handle.node_id(),
                parent_node_id: None,
            })?;
        self.record_value(node_id, handle.node_id());
        Ok(())
    }

    fn visit_false(
        &mut self,
        handle: FalseHandle,
        _view: FalseView,
        _tree: &F,
    ) -> Result<(), Self::Error> {
        let node_id = self.document.current_node_id();
        self.document
            .bind_primitive(PrimitiveValue::Bool(false))
            .map_err(|e| DocumentConstructionError::DocumentInsert {
                error: e,
                node_id: handle.node_id(),
                parent_node_id: None,
            })?;
        self.record_value(node_id, handle.node_id());
        Ok(())
    }

    fn visit_integer(
        &mut self,
        handle: IntegerHandle,
        view: IntegerView,
        tree: &F,
    ) -> Result<(), Self::Error> {
        let str = self.get_terminal_str(tree, view.integer)?;

        // Remove underscores for parsing
        let clean_str = str.replace('_', "");

        let big_int: BigInt = clean_str
            .parse()
            .map_err(|_| DocumentConstructionError::InvalidBigInt(str.to_string()))?;

        let node_id = self.document.current_node_id();
        self.document
            .bind_primitive(PrimitiveValue::Integer(big_int))
            .map_err(|e| DocumentConstructionError::DocumentInsert {
                error: e,
                node_id: handle.node_id(),
                parent_node_id: None,
            })?;
        self.record_value(node_id, handle.node_id());
        Ok(())
    }

    fn visit_inf(&mut self, handle: InfHandle, view: InfView, tree: &F) -> Result<(), Self::Error> {
        let str = self.get_terminal_str(tree, view.inf)?;

        let float = if str.starts_with('-') {
            f64::NEG_INFINITY
        } else {
            f64::INFINITY
        };

        let node_id = self.document.current_node_id();
        self.document
            .bind_primitive(PrimitiveValue::F64(float))
            .map_err(|e| DocumentConstructionError::DocumentInsert {
                error: e,
                node_id: handle.node_id(),
                parent_node_id: None,
            })?;
        self.record_value(node_id, handle.node_id());
        Ok(())
    }

    fn visit_na_n(
        &mut self,
        handle: NaNHandle,
        _view: NaNView,
        _tree: &F,
    ) -> Result<(), Self::Error> {
        let node_id = self.document.current_node_id();
        self.document
            .bind_primitive(PrimitiveValue::F64(f64::NAN))
            .map_err(|e| DocumentConstructionError::DocumentInsert {
                error: e,
                node_id: handle.node_id(),
                parent_node_id: None,
            })?;
        self.record_value(node_id, handle.node_id());
        Ok(())
    }

    fn visit_float(
        &mut self,
        handle: FloatHandle,
        view: FloatView,
        tree: &F,
    ) -> Result<(), Self::Error> {
        let str = self.get_terminal_str(tree, view.float)?;

        // Check for f32/f64 suffix
        let (num_str, is_f32) = if let Some(stripped) = str.strip_suffix("f32") {
            (stripped, true)
        } else if let Some(stripped) = str.strip_suffix("f64") {
            (stripped, false)
        } else {
            (str, false)
        };

        // Remove underscores for parsing
        let clean_str = num_str.replace('_', "");

        let node_id = self.document.current_node_id();
        let primitive = if is_f32 {
            let float: f32 = clean_str
                .parse()
                .map_err(|_| DocumentConstructionError::InvalidFloat(str.to_string()))?;
            PrimitiveValue::F32(float)
        } else {
            let float: f64 = clean_str
                .parse()
                .map_err(|_| DocumentConstructionError::InvalidFloat(str.to_string()))?;
            PrimitiveValue::F64(float)
        };

        self.document.bind_primitive(primitive).map_err(|e| {
            DocumentConstructionError::DocumentInsert {
                error: e,
                node_id: handle.node_id(),
                parent_node_id: None,
            }
        })?;
        self.record_value(node_id, handle.node_id());
        Ok(())
    }

    fn visit_hole(
        &mut self,
        handle: HoleHandle,
        view: HoleView,
        tree: &F,
    ) -> Result<(), Self::Error> {
        // Extract label from the hole token
        let token_str = self.get_terminal_str(tree, view.hole)?;
        let label = if token_str.len() > 1 {
            // Named hole: `!label` - skip '!' prefix and parse as Identifier
            Some(token_str[1..].parse::<Identifier>()?)
        } else {
            // Anonymous hole: just `!`
            None
        };

        let node_id = self.document.current_node_id();
        self.document
            .bind_hole(label)
            .map_err(|e| DocumentConstructionError::DocumentInsert {
                error: e,
                node_id: handle.node_id(),
                parent_node_id: None,
            })?;
        self.record_value(node_id, handle.node_id());
        Ok(())
    }

    fn visit_inline_code_1(
        &mut self,
        handle: InlineCode1Handle,
        view: InlineCode1View,
        tree: &F,
    ) -> Result<(), Self::Error> {
        let token_str = self.get_terminal_str(tree, view.inline_code_1)?;
        let (language, content) = Self::parse_inline_code_1(token_str).map_err(|error| {
            DocumentConstructionError::InvalidInlineCode {
                node_id: view.inline_code_1.node_id(),
                error,
            }
        })?;
        let text = Text::with_syntax_hint(content, language, SyntaxHint::Inline1);
        let node_id = self.document.current_node_id();
        self.document
            .bind_primitive(PrimitiveValue::Text(text))
            .map_err(|e| DocumentConstructionError::DocumentInsert {
                error: e,
                node_id: handle.node_id(),
                parent_node_id: None,
            })?;
        self.record_value(node_id, handle.node_id());
        Ok(())
    }

    // === DelimCode1 handlers ===
    fn visit_delim_code_1(
        &mut self,
        handle: DelimCode1Handle,
        view: DelimCode1View,
        tree: &F,
    ) -> Result<(), Self::Error> {
        self.pending_code_origin = Some(CodeOrigin::DelimCode1(handle));
        self.visit_delim_code_1_super(handle, view, tree)?;
        self.pending_code_origin = None;
        Ok(())
    }

    fn visit_delim_code_start_1(
        &mut self,
        _handle: DelimCodeStart1Handle,
        view: DelimCodeStart1View,
        tree: &F,
    ) -> Result<(), Self::Error> {
        let token_str = self.get_terminal_str(tree, view.delim_code_start_1)?;
        let language = Self::parse_delim_code_start_1(token_str).map_err(|error| {
            DocumentConstructionError::InvalidInlineCode {
                node_id: view.delim_code_start_1.node_id(),
                error,
            }
        })?;
        self.code_start = if let Some(origin) = self.pending_code_origin {
            Some(CodeStart::with_origin(language, SyntaxHint::Delim1, origin))
        } else {
            Some(CodeStart::new(language, SyntaxHint::Delim1))
        };
        Ok(())
    }

    fn visit_delim_code_end_1(
        &mut self,
        handle: DelimCodeEnd1Handle,
        _view: DelimCodeEnd1View,
        tree: &F,
    ) -> Result<(), Self::Error> {
        if let Some(code_start) = self.code_start.take() {
            let content = code_start.terminals.into_string(self.input, tree)?;
            let text = Text::with_syntax_hint(content, code_start.language, code_start.syntax_hint);
            let node_id = self.document.current_node_id();
            self.document
                .bind_primitive(PrimitiveValue::Text(text))
                .map_err(|e| DocumentConstructionError::DocumentInsert {
                    error: e,
                    node_id: handle.node_id(),
                    parent_node_id: None,
                })?;
            if let Some(CodeOrigin::DelimCode1(delim_handle)) = code_start.origin {
                self.record_value(node_id, delim_handle.node_id());
            }
        }
        Ok(())
    }

    // === DelimCode2 handlers ===
    fn visit_delim_code_2(
        &mut self,
        handle: DelimCode2Handle,
        view: DelimCode2View,
        tree: &F,
    ) -> Result<(), Self::Error> {
        self.pending_code_origin = Some(CodeOrigin::DelimCode2(handle));
        self.visit_delim_code_2_super(handle, view, tree)?;
        self.pending_code_origin = None;
        Ok(())
    }

    fn visit_delim_code_start_2(
        &mut self,
        _handle: DelimCodeStart2Handle,
        view: DelimCodeStart2View,
        tree: &F,
    ) -> Result<(), Self::Error> {
        let token_str = self.get_terminal_str(tree, view.delim_code_start_2)?;
        let language = Self::parse_delim_code_start_2(token_str).map_err(|error| {
            DocumentConstructionError::InvalidInlineCode {
                node_id: view.delim_code_start_2.node_id(),
                error,
            }
        })?;
        self.code_start = if let Some(origin) = self.pending_code_origin {
            Some(CodeStart::with_origin(language, SyntaxHint::Delim2, origin))
        } else {
            Some(CodeStart::new(language, SyntaxHint::Delim2))
        };
        Ok(())
    }

    fn visit_delim_code_end_2(
        &mut self,
        handle: DelimCodeEnd2Handle,
        _view: DelimCodeEnd2View,
        tree: &F,
    ) -> Result<(), Self::Error> {
        if let Some(code_start) = self.code_start.take() {
            let content = code_start.terminals.into_string(self.input, tree)?;
            let text = Text::with_syntax_hint(content, code_start.language, code_start.syntax_hint);
            let node_id = self.document.current_node_id();
            self.document
                .bind_primitive(PrimitiveValue::Text(text))
                .map_err(|e| DocumentConstructionError::DocumentInsert {
                    error: e,
                    node_id: handle.node_id(),
                    parent_node_id: None,
                })?;
            if let Some(CodeOrigin::DelimCode2(delim_handle)) = code_start.origin {
                self.record_value(node_id, delim_handle.node_id());
            }
        }
        Ok(())
    }

    // === DelimCode3 handlers ===
    fn visit_delim_code_3(
        &mut self,
        handle: DelimCode3Handle,
        view: DelimCode3View,
        tree: &F,
    ) -> Result<(), Self::Error> {
        self.pending_code_origin = Some(CodeOrigin::DelimCode3(handle));
        self.visit_delim_code_3_super(handle, view, tree)?;
        self.pending_code_origin = None;
        Ok(())
    }

    fn visit_delim_code_start_3(
        &mut self,
        _handle: DelimCodeStart3Handle,
        view: DelimCodeStart3View,
        tree: &F,
    ) -> Result<(), Self::Error> {
        let token_str = self.get_terminal_str(tree, view.delim_code_start_3)?;
        let language = Self::parse_delim_code_start_3(token_str).map_err(|error| {
            DocumentConstructionError::InvalidInlineCode {
                node_id: view.delim_code_start_3.node_id(),
                error,
            }
        })?;
        self.code_start = if let Some(origin) = self.pending_code_origin {
            Some(CodeStart::with_origin(language, SyntaxHint::Delim3, origin))
        } else {
            Some(CodeStart::new(language, SyntaxHint::Delim3))
        };
        Ok(())
    }

    fn visit_delim_code_end_3(
        &mut self,
        handle: DelimCodeEnd3Handle,
        _view: DelimCodeEnd3View,
        tree: &F,
    ) -> Result<(), Self::Error> {
        if let Some(code_start) = self.code_start.take() {
            let content = code_start.terminals.into_string(self.input, tree)?;
            let text = Text::with_syntax_hint(content, code_start.language, code_start.syntax_hint);
            let node_id = self.document.current_node_id();
            self.document
                .bind_primitive(PrimitiveValue::Text(text))
                .map_err(|e| DocumentConstructionError::DocumentInsert {
                    error: e,
                    node_id: handle.node_id(),
                    parent_node_id: None,
                })?;
            if let Some(CodeOrigin::DelimCode3(delim_handle)) = code_start.origin {
                self.record_value(node_id, delim_handle.node_id());
            }
        }
        Ok(())
    }

    fn visit_code_block(
        &mut self,
        handle: CodeBlockHandle,
        view: CodeBlockView,
        tree: &F,
    ) -> Result<(), Self::Error> {
        // Store the origin before visiting children
        self.pending_code_origin = Some(CodeOrigin::CodeBlock(handle));
        // Visit children
        self.visit_code_block_super(handle, view, tree)?;
        self.pending_code_origin = None;
        Ok(())
    }

    fn visit_code_block_start_3(
        &mut self,
        _handle: CodeBlockStart3Handle,
        view: CodeBlockStart3View,
        tree: &F,
    ) -> Result<(), Self::Error> {
        let token_str = self.get_terminal_str(tree, view.code_block_start_3)?;
        let language = Self::parse_code_block_start(token_str).map_err(|error| {
            DocumentConstructionError::InvalidCodeBlock {
                node_id: view.code_block_start_3.node_id(),
                error,
            }
        })?;
        // Use pending origin if available
        self.code_start = if let Some(origin) = self.pending_code_origin {
            Some(CodeStart::with_origin(language, SyntaxHint::Block3, origin))
        } else {
            Some(CodeStart::new(language, SyntaxHint::Block3))
        };
        Ok(())
    }

    fn visit_code_block_end_3(
        &mut self,
        handle: CodeBlockEnd3Handle,
        _view: CodeBlockEnd3View,
        tree: &F,
    ) -> Result<(), Self::Error> {
        if let Some(code_start) = self.code_start.take() {
            let content = code_start.terminals.into_string(self.input, tree)?;
            let text =
                Text::parse_indented_block(code_start.language, content, code_start.syntax_hint)
                    .map_err(|e| DocumentConstructionError::InvalidCodeBlock {
                        node_id: handle.node_id(),
                        error: CodeBlockError::from(e),
                    })?;
            let node_id = self.document.current_node_id();
            self.document
                .bind_primitive(PrimitiveValue::Text(text))
                .map_err(|e| DocumentConstructionError::DocumentInsert {
                    error: e,
                    node_id: handle.node_id(),
                    parent_node_id: None,
                })?;
            // Record origin if available
            if let Some(CodeOrigin::CodeBlock(block_handle)) = code_start.origin {
                self.record_value(node_id, block_handle.node_id());
            }
        }
        Ok(())
    }

    fn visit_code_block_start_4(
        &mut self,
        _handle: CodeBlockStart4Handle,
        view: CodeBlockStart4View,
        tree: &F,
    ) -> Result<(), Self::Error> {
        let token_str = self.get_terminal_str(tree, view.code_block_start_4)?;
        let language = Self::parse_code_block_start(token_str).map_err(|error| {
            DocumentConstructionError::InvalidCodeBlock {
                node_id: view.code_block_start_4.node_id(),
                error,
            }
        })?;
        // Use pending origin if available
        self.code_start = if let Some(origin) = self.pending_code_origin {
            Some(CodeStart::with_origin(language, SyntaxHint::Block4, origin))
        } else {
            Some(CodeStart::new(language, SyntaxHint::Block4))
        };
        Ok(())
    }

    fn visit_code_block_end_4(
        &mut self,
        handle: CodeBlockEnd4Handle,
        _view: CodeBlockEnd4View,
        tree: &F,
    ) -> Result<(), Self::Error> {
        if let Some(code_start) = self.code_start.take() {
            let content = code_start.terminals.into_string(self.input, tree)?;
            let text =
                Text::parse_indented_block(code_start.language, content, code_start.syntax_hint)
                    .map_err(|e| DocumentConstructionError::InvalidCodeBlock {
                        node_id: handle.node_id(),
                        error: CodeBlockError::from(e),
                    })?;
            let node_id = self.document.current_node_id();
            self.document
                .bind_primitive(PrimitiveValue::Text(text))
                .map_err(|e| DocumentConstructionError::DocumentInsert {
                    error: e,
                    node_id: handle.node_id(),
                    parent_node_id: None,
                })?;
            // Record origin if available
            if let Some(CodeOrigin::CodeBlock(block_handle)) = code_start.origin {
                self.record_value(node_id, block_handle.node_id());
            }
        }
        Ok(())
    }

    fn visit_code_block_start_5(
        &mut self,
        _handle: CodeBlockStart5Handle,
        view: CodeBlockStart5View,
        tree: &F,
    ) -> Result<(), Self::Error> {
        let token_str = self.get_terminal_str(tree, view.code_block_start_5)?;
        let language = Self::parse_code_block_start(token_str).map_err(|error| {
            DocumentConstructionError::InvalidCodeBlock {
                node_id: view.code_block_start_5.node_id(),
                error,
            }
        })?;
        // Use pending origin if available
        self.code_start = if let Some(origin) = self.pending_code_origin {
            Some(CodeStart::with_origin(language, SyntaxHint::Block5, origin))
        } else {
            Some(CodeStart::new(language, SyntaxHint::Block5))
        };
        Ok(())
    }

    fn visit_code_block_end_5(
        &mut self,
        handle: CodeBlockEnd5Handle,
        _view: CodeBlockEnd5View,
        tree: &F,
    ) -> Result<(), Self::Error> {
        if let Some(code_start) = self.code_start.take() {
            let content = code_start.terminals.into_string(self.input, tree)?;
            let text =
                Text::parse_indented_block(code_start.language, content, code_start.syntax_hint)
                    .map_err(|e| DocumentConstructionError::InvalidCodeBlock {
                        node_id: handle.node_id(),
                        error: CodeBlockError::from(e),
                    })?;
            let node_id = self.document.current_node_id();
            self.document
                .bind_primitive(PrimitiveValue::Text(text))
                .map_err(|e| DocumentConstructionError::DocumentInsert {
                    error: e,
                    node_id: handle.node_id(),
                    parent_node_id: None,
                })?;
            // Record origin if available
            if let Some(CodeOrigin::CodeBlock(block_handle)) = code_start.origin {
                self.record_value(node_id, block_handle.node_id());
            }
        }
        Ok(())
    }

    fn visit_code_block_start_6(
        &mut self,
        _handle: CodeBlockStart6Handle,
        view: CodeBlockStart6View,
        tree: &F,
    ) -> Result<(), Self::Error> {
        let token_str = self.get_terminal_str(tree, view.code_block_start_6)?;
        let language = Self::parse_code_block_start(token_str).map_err(|error| {
            DocumentConstructionError::InvalidCodeBlock {
                node_id: view.code_block_start_6.node_id(),
                error,
            }
        })?;
        // Use pending origin if available
        self.code_start = if let Some(origin) = self.pending_code_origin {
            Some(CodeStart::with_origin(language, SyntaxHint::Block6, origin))
        } else {
            Some(CodeStart::new(language, SyntaxHint::Block6))
        };
        Ok(())
    }

    fn visit_code_block_end_6(
        &mut self,
        handle: CodeBlockEnd6Handle,
        _view: CodeBlockEnd6View,
        tree: &F,
    ) -> Result<(), Self::Error> {
        if let Some(code_start) = self.code_start.take() {
            let content = code_start.terminals.into_string(self.input, tree)?;
            let text =
                Text::parse_indented_block(code_start.language, content, code_start.syntax_hint)
                    .map_err(|e| DocumentConstructionError::InvalidCodeBlock {
                        node_id: handle.node_id(),
                        error: CodeBlockError::from(e),
                    })?;
            let node_id = self.document.current_node_id();
            self.document
                .bind_primitive(PrimitiveValue::Text(text))
                .map_err(|e| DocumentConstructionError::DocumentInsert {
                    error: e,
                    node_id: handle.node_id(),
                    parent_node_id: None,
                })?;
            // Record origin if available
            if let Some(CodeOrigin::CodeBlock(block_handle)) = code_start.origin {
                self.record_value(node_id, block_handle.node_id());
            }
        }
        Ok(())
    }

    fn visit_text_binding(
        &mut self,
        handle: TextBindingHandle,
        view: TextBindingView,
        tree: &F,
    ) -> Result<(), Self::Error> {
        let text_view = view.text_binding_opt_0.get_view(tree)?;
        let text = if let Some(text_handle) = text_view {
            let text_view = text_handle.get_view(tree)?;
            let text_str = self.get_terminal_str(tree, text_view.text)?;
            Text::parse_text_binding(text_str).map_err(|error| {
                DocumentConstructionError::InvalidStringKey {
                    node_id: text_handle.node_id(),
                    error,
                }
            })?
        } else {
            Text::new(String::new(), Language::Plaintext)
        };
        let node_id = self.document.current_node_id();
        self.document
            .bind_primitive(PrimitiveValue::Text(text))
            .map_err(|e| DocumentConstructionError::DocumentInsert {
                error: e,
                node_id: handle.node_id(),
                parent_node_id: None,
            })?;
        self.record_value(node_id, handle.node_id());
        Ok(())
    }

    fn visit_strings(
        &mut self,
        handle: StringsHandle,
        view: StringsView,
        tree: &F,
    ) -> Result<(), Self::Error> {
        // Parse the first string (can be any of the 8 string types)
        let (first_str, first_hint) = self.parse_string_with_hint(view.string, tree)?;

        // Check for continuations
        let (result, syntax_hint) = if let Some(list_view) = view.strings_list.get_view(tree)? {
            // There are continuation strings - collect and join them
            // Use first string's hint (can't represent mixed syntax in a single hint)
            let mut parts = vec![first_str];
            for item in list_view.get_all(tree)? {
                let (part, _) = self.parse_string_with_hint(item.string, tree)?;
                parts.push(part);
            }
            (parts.join(""), first_hint)
        } else {
            (first_str, first_hint)
        };

        let text = Text::with_syntax_hint(result, Language::Plaintext, syntax_hint);
        let node_id = self.document.current_node_id();
        self.document
            .bind_primitive(PrimitiveValue::Text(text))
            .map_err(|e| DocumentConstructionError::DocumentInsert {
                error: e,
                node_id: handle.node_id(),
                parent_node_id: None,
            })?;
        self.record_value(node_id, handle.node_id());
        Ok(())
    }

    fn visit_new_line_terminal(
        &mut self,
        terminal: NewLine,
        data: TerminalData,
        tree: &F,
    ) -> Result<(), Self::Error> {
        self.pending_newlines += 1;
        self.visit_new_line_terminal_super(terminal, data, tree)
    }

    fn visit_line_comment_terminal(
        &mut self,
        terminal: LineComment,
        data: TerminalData,
        tree: &F,
    ) -> Result<(), Self::Error> {
        self.flush_blank_lines();
        let text = self.get_terminal_str(tree, terminal)?;
        let text = text.strip_prefix("//").unwrap_or(text);
        let text = text
            .strip_prefix(' ')
            .unwrap_or(text)
            .trim_end_matches(['\r', '\n'])
            .to_string();
        self.document.comment(Comment::Line(text));
        self.visit_line_comment_terminal_super(terminal, data, tree)
    }

    fn visit_block_comment_terminal(
        &mut self,
        terminal: BlockComment,
        data: TerminalData,
        tree: &F,
    ) -> Result<(), Self::Error> {
        self.flush_blank_lines();
        let text = self.get_terminal_str(tree, terminal)?;
        let text = text
            .strip_prefix("/*")
            .and_then(|s| s.strip_suffix("*/"))
            .unwrap_or(text)
            .to_string();
        self.document.comment(Comment::Block(text));
        self.visit_block_comment_terminal_super(terminal, data, tree)
    }

    fn visit_terminal(
        &mut self,
        _id: CstNodeId,
        kind: TerminalKind,
        data: TerminalData,
        _tree: &F,
    ) -> Result<(), Self::Error> {
        if !matches!(
            kind,
            TerminalKind::NewLine
                | TerminalKind::Whitespace
                | TerminalKind::LineComment
                | TerminalKind::BlockComment
        ) {
            self.flush_blank_lines();
        }
        // If we're inside a code block or inline code, collect the terminals
        if let Some(code_start) = &mut self.code_start {
            code_start.terminals.push_terminal(data);
        }
        Ok(())
    }

    fn then_construct_error(
        &mut self,
        _node_data: Option<CstNode>,
        _parent: CstNodeId,
        _kind: NodeKind,
        error: CstConstructError,
        _tree: &F,
    ) -> Result<(), Self::Error> {
        Err(DocumentConstructionError::CstError(error))
    }
}

/// Helper methods for parsing strings (outside of CstVisitor trait)
impl<'a> CstInterpreter<'a> {
    /// Parse a String (any of the string types) and return the content with syntax hint
    fn parse_string_with_hint<F: CstFacade>(
        &self,
        handle: StringHandle,
        tree: &F,
    ) -> Result<(String, SyntaxHint), DocumentConstructionError> {
        match handle.get_view(tree)? {
            StringView::Str(h) => self
                .parse_str_terminal(h, tree)
                .map(|s| (s, SyntaxHint::Str)),
            StringView::LitStr(h) => self.parse_lit_str(h, tree).map(|s| (s, SyntaxHint::LitStr)),
            StringView::LitStr1(h) => self
                .parse_lit_str_1(h, tree)
                .map(|s| (s, SyntaxHint::LitStr1)),
            StringView::LitStr2(h) => self
                .parse_lit_str_2(h, tree)
                .map(|s| (s, SyntaxHint::LitStr2)),
            StringView::LitStr3(h) => self
                .parse_lit_str_3(h, tree)
                .map(|s| (s, SyntaxHint::LitStr3)),
        }
    }

    /// Parse a String (any of the string types) and return just the content
    fn parse_string<F: CstFacade>(
        &self,
        handle: StringHandle,
        tree: &F,
    ) -> Result<String, DocumentConstructionError> {
        self.parse_string_with_hint(handle, tree).map(|(s, _)| s)
    }

    /// Parse LitStr ('...') and return the content (literal, no escape processing)
    fn parse_lit_str<F: CstFacade>(
        &self,
        handle: LitStrHandle,
        tree: &F,
    ) -> Result<String, DocumentConstructionError> {
        let view = handle.get_view(tree)?;
        let token = self.get_terminal_str(tree, view.lit_str)?;
        // Strip surrounding single quotes: 'content' -> content
        let content = token
            .strip_prefix('\'')
            .and_then(|s| s.strip_suffix('\''))
            .ok_or_else(|| DocumentConstructionError::InvalidLiteralStr {
                node_id: handle.node_id(),
            })?;
        Ok(content.to_string())
    }

    /// Parse LitStr1 (<'...'>) and return the content (literal, no escape processing)
    fn parse_lit_str_1<F: CstFacade>(
        &self,
        handle: LitStr1Handle,
        tree: &F,
    ) -> Result<String, DocumentConstructionError> {
        let view = handle.get_view(tree)?;
        let terminals = TerminalTokens::from_lit_str_1_list(&view.lit_str_1_list, tree)?;
        terminals.into_string(self.input, tree)
    }

    /// Parse LitStr2 (<<'...'>>) and return the content (literal, no escape processing)
    fn parse_lit_str_2<F: CstFacade>(
        &self,
        handle: LitStr2Handle,
        tree: &F,
    ) -> Result<String, DocumentConstructionError> {
        let view = handle.get_view(tree)?;
        let terminals = TerminalTokens::from_lit_str_2_list(&view.lit_str_2_list, tree)?;
        terminals.into_string(self.input, tree)
    }

    /// Parse LitStr3 (<<<'...'>>>) and return the content (literal, no escape processing)
    fn parse_lit_str_3<F: CstFacade>(
        &self,
        handle: LitStr3Handle,
        tree: &F,
    ) -> Result<String, DocumentConstructionError> {
        let view = handle.get_view(tree)?;
        let terminals = TerminalTokens::from_lit_str_3_list(&view.lit_str_3_list, tree)?;
        terminals.into_string(self.input, tree)
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use eure_tree::tree::{ConcreteSyntaxTree, CstNodeData, InputSpan, TerminalData};

    fn create_dummy_cst() -> ConcreteSyntaxTree<TerminalKind, NonTerminalKind> {
        let root_data = CstNodeData::new_non_terminal(
            NonTerminalKind::Root,
            NonTerminalData::Input(InputSpan::EMPTY),
        );
        ConcreteSyntaxTree::new(root_data)
    }

    // Tests for parse_inline_code_1
    mod parse_inline_code_1_tests {
        use super::*;

        #[test]
        fn test_simple_code_without_language() {
            let result = CstInterpreter::parse_inline_code_1("`hello`");
            assert!(result.is_ok());
            let (language, content) = result.unwrap();
            assert_eq!(language, Language::Implicit);
            assert_eq!(content, "hello");
        }

        #[test]
        fn test_code_with_language() {
            let result = CstInterpreter::parse_inline_code_1("rust`fn main() {}`");
            assert!(result.is_ok());
            let (language, content) = result.unwrap();
            assert_eq!(language, Language::Other("rust".into()));
            assert_eq!(content, "fn main() {}");
        }

        #[test]
        fn test_empty_code() {
            let result = CstInterpreter::parse_inline_code_1("``");
            assert!(result.is_ok());
            let (language, content) = result.unwrap();
            assert_eq!(language, Language::Implicit);
            assert_eq!(content, "");
        }

        #[test]
        fn test_code_with_special_chars() {
            let result = CstInterpreter::parse_inline_code_1("`hello world!@#$%`");
            assert!(result.is_ok());
            let (language, content) = result.unwrap();
            assert_eq!(language, Language::Implicit);
            assert_eq!(content, "hello world!@#$%");
        }

        #[test]
        fn test_language_with_hyphen_and_underscore() {
            let result = CstInterpreter::parse_inline_code_1("foo-bar_123`content`");
            assert!(result.is_ok());
            let (language, content) = result.unwrap();
            assert_eq!(language, Language::Other("foo-bar_123".into()));
            assert_eq!(content, "content");
        }

        #[test]
        fn test_no_backticks() {
            let result = CstInterpreter::parse_inline_code_1("no backticks");
            assert!(result.is_err());
            assert!(matches!(
                result.unwrap_err(),
                InlineCodeError::InvalidInlineCode1Pattern
            ));
        }

        #[test]
        fn test_single_backtick() {
            let result = CstInterpreter::parse_inline_code_1("`");
            assert!(result.is_err());
            assert!(matches!(
                result.unwrap_err(),
                InlineCodeError::InvalidInlineCode1Pattern
            ));
        }
    }

    // Tests for parse_delim_code_start_1
    mod parse_delim_code_start_1_tests {
        use super::*;

        #[test]
        fn test_no_language() {
            let result = CstInterpreter::parse_delim_code_start_1("<`");
            assert!(result.is_ok());
            assert_eq!(result.unwrap(), Language::Implicit);
        }

        #[test]
        fn test_with_language() {
            let result = CstInterpreter::parse_delim_code_start_1("rust<`");
            assert!(result.is_ok());
            assert_eq!(result.unwrap(), Language::Other("rust".into()));
        }

        #[test]
        fn test_with_complex_language() {
            let result = CstInterpreter::parse_delim_code_start_1("foo-bar_123<`");
            assert!(result.is_ok());
            assert_eq!(result.unwrap(), Language::Other("foo-bar_123".into()));
        }

        #[test]
        fn test_no_delim() {
            let result = CstInterpreter::parse_delim_code_start_1("rust");
            assert!(result.is_err());
            assert!(matches!(
                result.unwrap_err(),
                InlineCodeError::InvalidDelimCodeStartPattern
            ));
        }
    }

    // Tests for parse_delim_code_start_2
    mod parse_delim_code_start_2_tests {
        use super::*;

        #[test]
        fn test_no_language() {
            let result = CstInterpreter::parse_delim_code_start_2("<<`");
            assert!(result.is_ok());
            assert_eq!(result.unwrap(), Language::Implicit);
        }

        #[test]
        fn test_with_language() {
            let result = CstInterpreter::parse_delim_code_start_2("rust<<`");
            assert!(result.is_ok());
            assert_eq!(result.unwrap(), Language::Other("rust".into()));
        }
    }

    // Tests for parse_delim_code_start_3
    mod parse_delim_code_start_3_tests {
        use super::*;

        #[test]
        fn test_no_language() {
            let result = CstInterpreter::parse_delim_code_start_3("<<<`");
            assert!(result.is_ok());
            assert_eq!(result.unwrap(), Language::Implicit);
        }

        #[test]
        fn test_with_language() {
            let result = CstInterpreter::parse_delim_code_start_3("rust<<<`");
            assert!(result.is_ok());
            assert_eq!(result.unwrap(), Language::Other("rust".into()));
        }
    }

    // Tests for parse_code_block_start
    mod parse_code_block_start_tests {
        use crate::document::CodeBlockError;

        use super::*;

        #[test]
        fn test_no_language_3_backticks() {
            let result = CstInterpreter::parse_code_block_start("```\n");
            assert!(result.is_ok());
            assert_eq!(result.unwrap(), Language::Implicit);
        }

        #[test]
        fn test_with_language_3_backticks() {
            let result = CstInterpreter::parse_code_block_start("```rust\n");
            assert!(result.is_ok());
            assert_eq!(result.unwrap(), Language::Other("rust".into()));
        }

        #[test]
        fn test_with_language_4_backticks() {
            let result = CstInterpreter::parse_code_block_start("````python\n");
            assert!(result.is_ok());
            assert_eq!(result.unwrap(), Language::Other("python".into()));
        }

        #[test]
        fn test_with_language_5_backticks() {
            let result = CstInterpreter::parse_code_block_start("`````javascript\n");
            assert!(result.is_ok());
            assert_eq!(result.unwrap(), Language::Other("javascript".into()));
        }

        #[test]
        fn test_with_language_6_backticks() {
            let result = CstInterpreter::parse_code_block_start("``````typescript\n");
            assert!(result.is_ok());
            assert_eq!(result.unwrap(), Language::Other("typescript".into()));
        }

        #[test]
        fn test_language_with_trailing_whitespace() {
            let result = CstInterpreter::parse_code_block_start("```rust  \n");
            assert!(result.is_ok());
            assert_eq!(result.unwrap(), Language::Other("rust".into()));
        }

        #[test]
        fn test_language_with_leading_whitespace_is_invalid() {
            // Leading whitespace before language tag with non-whitespace after is grammar violation
            // Pattern: ```[a-zA-Z0-9_-]*[ \t]*\n but this has ``` [ \t]+ [a-z]+ which doesn't match
            let result = CstInterpreter::parse_code_block_start("```  rust\n");
            assert!(result.is_err());
            assert!(matches!(
                result.unwrap_err(),
                CodeBlockError::InvalidCodeBlockStartPattern
            ));
        }

        #[test]
        fn test_language_with_carriage_return() {
            let result = CstInterpreter::parse_code_block_start("```rust\r\n");
            assert!(result.is_ok());
            assert_eq!(result.unwrap(), Language::Other("rust".into()));
        }

        #[test]
        fn test_language_with_only_carriage_return() {
            let result = CstInterpreter::parse_code_block_start("```rust\r");
            assert!(result.is_ok());
            assert_eq!(result.unwrap(), Language::Other("rust".into()));
        }

        #[test]
        fn test_empty_language_with_spaces() {
            let result = CstInterpreter::parse_code_block_start("```   \n");
            assert!(result.is_ok());
            assert_eq!(result.unwrap(), Language::Implicit);
        }

        #[test]
        fn test_no_newline() {
            let result = CstInterpreter::parse_code_block_start("```rust");
            assert!(result.is_err());
            assert!(matches!(
                result.unwrap_err(),
                CodeBlockError::InvalidCodeBlockStartPattern
            ));
        }

        #[test]
        fn test_complex_language_tag() {
            let result = CstInterpreter::parse_code_block_start("```foo-bar_123\n");
            assert!(result.is_ok());
            assert_eq!(result.unwrap(), Language::Other("foo-bar_123".into()));
        }
    }

    #[test]
    fn test_push_input() {
        let mut tokens = TerminalTokens::new();
        let span = InputSpan::new(0, 5);
        tokens.push_terminal(TerminalData::Input(span));

        assert_eq!(tokens.terminals.len(), 1);
        match tokens.terminals[0] {
            TerminalToken::Input(s) => assert_eq!(s, span),
            _ => panic!("Expected Input token"),
        }
    }

    #[test]
    fn test_merge_adjacent_inputs() {
        let mut tokens = TerminalTokens::new();
        let span1 = InputSpan::new(0, 5);
        let span2 = InputSpan::new(5, 10);

        tokens.push_terminal(TerminalData::Input(span1));
        tokens.push_terminal(TerminalData::Input(span2));

        assert_eq!(tokens.terminals.len(), 1);
        match tokens.terminals[0] {
            TerminalToken::Input(s) => {
                assert_eq!(s.start, 0);
                assert_eq!(s.end, 10);
            }
            _ => panic!("Expected Input token"),
        }
    }

    #[test]
    fn test_dont_merge_non_adjacent() {
        let mut tokens = TerminalTokens::new();
        let span1 = InputSpan::new(0, 5);
        let span2 = InputSpan::new(6, 10); // Gap between 5 and 6

        tokens.push_terminal(TerminalData::Input(span1));
        tokens.push_terminal(TerminalData::Input(span2));

        assert_eq!(tokens.terminals.len(), 2);
        match tokens.terminals[0] {
            TerminalToken::Input(s) => assert_eq!(s, span1),
            _ => panic!("Expected Input token at 0"),
        }
        match tokens.terminals[1] {
            TerminalToken::Input(s) => assert_eq!(s, span2),
            _ => panic!("Expected Input token at 1"),
        }
    }

    #[test]
    fn test_dont_merge_dynamic() {
        let mut tokens = TerminalTokens::new();
        let span1 = InputSpan::new(0, 5);
        let id = DynamicTokenId(1);
        let span2 = InputSpan::new(5, 10);

        tokens.push_terminal(TerminalData::Input(span1));
        tokens.push_terminal(TerminalData::Dynamic(id));
        tokens.push_terminal(TerminalData::Input(span2));

        assert_eq!(tokens.terminals.len(), 3);
        match tokens.terminals[0] {
            TerminalToken::Input(s) => assert_eq!(s, span1),
            _ => panic!("Expected Input token at 0"),
        }
        match tokens.terminals[1] {
            TerminalToken::Dynamic(d) => assert_eq!(d, id),
            _ => panic!("Expected Dynamic token at 1"),
        }
        match tokens.terminals[2] {
            TerminalToken::Input(s) => assert_eq!(s, span2),
            _ => panic!("Expected Input token at 2"),
        }
    }

    #[test]
    fn test_into_string() {
        let mut cst = create_dummy_cst();
        let id = cst.insert_dynamic_terminal("world");

        let mut tokens = TerminalTokens::new();
        // "Hello "
        tokens.push_terminal(TerminalData::Input(InputSpan::new(0, 6)));
        // "world"
        tokens.push_terminal(TerminalData::Dynamic(id));
        // "!"
        tokens.push_terminal(TerminalData::Input(InputSpan::new(6, 7)));

        let input = "Hello !"; // Indices 0..6 is "Hello ", 6..7 is "!" (offset by dynamic token?)

        let result = tokens.into_string(input, &cst).expect("Should succeed");
        assert_eq!(result, "Hello world!");
    }

    #[test]
    fn test_into_string_missing_dynamic() {
        let cst = create_dummy_cst(); // Empty CST
        let id = DynamicTokenId(999); // Non-existent ID

        let mut tokens = TerminalTokens::new();
        tokens.push_terminal(TerminalData::Dynamic(id));

        let result = tokens.into_string("", &cst);
        assert!(matches!(
            result,
            Err(DocumentConstructionError::DynamicTokenNotFound(i)) if i == id
        ));
    }
}