perl-ast 0.13.3

AST node definitions for Perl parsing, providing typed representations of Perl syntax constructs
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
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
//! Abstract Syntax Tree definitions for Perl within the parsing and LSP workflow.
//!
//! This module defines the comprehensive AST node types that represent parsed Perl code
//! during the Parse → Index → Navigate → Complete → Analyze stages. The design is optimized
//! for both direct use in Rust analysis and for generating tree-sitter compatible
//! S-expressions during large workspace processing operations.
//!
//! # LSP Workflow Integration
//!
//! The AST structures support Perl tooling workflows by:
//! - **Parse**: Produced by the parser as the canonical syntax tree
//! - **Index**: Traversed to build symbol and reference tables
//! - **Navigate**: Provides locations for definition and reference lookups
//! - **Complete**: Supplies context for completion, hover, and signature help
//! - **Analyze**: Feeds semantic analysis, diagnostics, and refactoring
//!
//! # Performance Characteristics
//!
//! AST structures are optimized for large codebases with:
//! - Memory-efficient node representation using `Box<Node>` for recursive structures
//! - Fast pattern matching via enum variants for common Perl constructs
//! - Location tracking for precise error reporting in large files
//! - Cheap cloning for parallel analysis tasks
//!
//! # Usage Examples
//!
//! ## Basic AST Construction
//!
//! ```rust
//! use perl_ast::{Node, NodeKind, SourceLocation};
//!
//! // Create a simple variable declaration node
//! let location = SourceLocation { start: 0, end: 10 };
//! let node = Node::new(
//!     NodeKind::VariableDeclaration {
//!         declarator: "my".to_string(),
//!         variable: Box::new(Node::new(
//!             NodeKind::Variable { sigil: "$".to_string(), name: "x".to_string() },
//!             location,
//!         )),
//!         attributes: vec![],
//!         initializer: None,
//!     },
//!     location,
//! );
//! assert_eq!(node.kind.kind_name(), "VariableDeclaration");
//! ```
//!
//! ## Tree-sitter S-expression Generation
//!
//! ```rust
//! use perl_ast::{Node, NodeKind, SourceLocation};
//!
//! let loc = SourceLocation { start: 0, end: 2 };
//! let num = Node::new(NodeKind::Number { value: "42".to_string() }, loc);
//! let program = Node::new(NodeKind::Program { statements: vec![num] }, loc);
//!
//! let sexp = program.to_sexp();
//! assert!(sexp.starts_with("(source_file"));
//! ```
//!
//! ## AST Traversal and Analysis
//!
//! ```rust
//! use perl_ast::{Node, NodeKind, SourceLocation};
//!
//! fn count_variables(node: &Node) -> usize {
//!     let mut count = 0;
//!     match &node.kind {
//!         NodeKind::Variable { .. } => count += 1,
//!         NodeKind::Program { statements } => {
//!             for stmt in statements {
//!                 count += count_variables(stmt);
//!             }
//!         }
//!         _ => {} // Handle other node types as needed
//!     }
//!     count
//! }
//!
//! let loc = SourceLocation { start: 0, end: 5 };
//! let var = Node::new(
//!     NodeKind::Variable { sigil: "$".to_string(), name: "x".to_string() },
//!     loc,
//! );
//! let program = Node::new(NodeKind::Program { statements: vec![var] }, loc);
//! assert_eq!(count_variables(&program), 1);
//! ```
//!
//! ## Parsing Integration
//!
//! In practice the AST is produced by the parser rather than built by hand
//! (requires `perl-parser-core`):
//!
//! ```rust,ignore
//! use perl_parser_core::Parser;
//! use perl_ast::NodeKind;
//!
//! let mut parser = Parser::new("my $x = 42;");
//! let ast = parser.parse().expect("should parse");
//! assert!(matches!(ast.kind, NodeKind::Program { .. }));
//! ```

// Re-export SourceLocation from perl-position-tracking for unified span handling
pub use perl_position_tracking::SourceLocation;
// Re-export Token and TokenKind from perl-token for AST error nodes
pub use perl_token::{Token, TokenKind};
use std::fmt;

/// Core AST node representing any Perl language construct within parsing workflows.
///
/// This is the fundamental building block for representing parsed Perl code. Each node
/// contains both the semantic information (kind) and positional information (location)
/// necessary for comprehensive script analysis.
///
/// # LSP Workflow Role
///
/// Nodes flow through tooling stages:
/// - **Parse**: Created by the parser as it builds the syntax tree
/// - **Index**: Visited to build symbol and reference tables
/// - **Navigate**: Used to resolve definitions, references, and call hierarchy
/// - **Complete**: Provides contextual information for completion and hover
/// - **Analyze**: Drives semantic analysis and diagnostics
///
/// # Memory Optimization
///
/// The structure is designed for efficient memory usage during large-scale parsing:
/// - `SourceLocation` uses compact position encoding for large files
/// - `NodeKind` enum variants minimize memory overhead for common constructs
/// - Clone operations are optimized for shared analysis workflows
///
/// # Examples
///
/// Construct a variable declaration node manually:
///
/// ```
/// use perl_ast::{Node, NodeKind, SourceLocation};
///
/// let loc = SourceLocation { start: 0, end: 11 };
/// let var = Node::new(
///     NodeKind::Variable { sigil: "$".to_string(), name: "x".to_string() },
///     loc,
/// );
/// let decl = Node::new(
///     NodeKind::VariableDeclaration {
///         declarator: "my".to_string(),
///         variable: Box::new(var),
///         attributes: vec![],
///         initializer: None,
///     },
///     loc,
/// );
/// assert_eq!(decl.kind.kind_name(), "VariableDeclaration");
/// ```
///
/// Typically you obtain nodes from the parser rather than constructing them by hand:
///
/// ```ignore
/// use perl_parser::Parser;
///
/// let mut parser = Parser::new("my $x = 42;");
/// let ast = parser.parse()?;
/// println!("AST: {}", ast.to_sexp());
/// ```
#[derive(Debug, Clone, PartialEq)]
pub struct Node {
    /// The specific type and semantic content of this AST node
    pub kind: NodeKind,
    /// Source position information for error reporting and code navigation
    pub location: SourceLocation,
}

impl Node {
    /// Create a new AST node with the given kind and source location.
    ///
    /// # Examples
    ///
    /// ```
    /// use perl_ast::{Node, NodeKind, SourceLocation};
    ///
    /// let node = Node::new(
    ///     NodeKind::Number { value: "42".to_string() },
    ///     SourceLocation { start: 0, end: 2 },
    /// );
    /// assert_eq!(node.kind.kind_name(), "Number");
    /// assert_eq!(node.location.start, 0);
    /// ```
    pub fn new(kind: NodeKind, location: SourceLocation) -> Self {
        Node { kind, location }
    }

    /// Convert the AST to a tree-sitter compatible S-expression.
    ///
    /// Produces a parenthesized representation compatible with tree-sitter's
    /// S-expression format, useful for debugging and snapshot testing.
    ///
    /// # Examples
    ///
    /// ```
    /// use perl_ast::{Node, NodeKind, SourceLocation};
    ///
    /// let loc = SourceLocation { start: 0, end: 2 };
    /// let num = Node::new(NodeKind::Number { value: "42".to_string() }, loc);
    /// let program = Node::new(
    ///     NodeKind::Program { statements: vec![num] },
    ///     loc,
    /// );
    /// let sexp = program.to_sexp();
    /// assert!(sexp.starts_with("(source_file"));
    /// ```
    pub fn to_sexp(&self) -> String {
        match &self.kind {
            NodeKind::Program { statements } => {
                let stmts =
                    statements.iter().map(|s| s.to_sexp_inner()).collect::<Vec<_>>().join(" ");
                format!("(source_file {})", stmts)
            }

            NodeKind::ExpressionStatement { expression } => {
                format!("(expression_statement {})", expression.to_sexp())
            }

            NodeKind::VariableDeclaration { declarator, variable, attributes, initializer } => {
                let attrs_str = if attributes.is_empty() {
                    String::new()
                } else {
                    format!(" (attributes {})", attributes.join(" "))
                };
                if let Some(init) = initializer {
                    format!(
                        "({}_declaration {}{}{})",
                        declarator,
                        variable.to_sexp(),
                        attrs_str,
                        init.to_sexp()
                    )
                } else {
                    format!("({}_declaration {}{})", declarator, variable.to_sexp(), attrs_str)
                }
            }

            NodeKind::VariableListDeclaration {
                declarator,
                variables,
                attributes,
                initializer,
            } => {
                let vars = variables.iter().map(|v| v.to_sexp()).collect::<Vec<_>>().join(" ");
                let attrs_str = if attributes.is_empty() {
                    String::new()
                } else {
                    format!(" (attributes {})", attributes.join(" "))
                };
                if let Some(init) = initializer {
                    format!(
                        "({}_declaration ({}){}{})",
                        declarator,
                        vars,
                        attrs_str,
                        init.to_sexp()
                    )
                } else {
                    format!("({}_declaration ({}){})", declarator, vars, attrs_str)
                }
            }

            NodeKind::Variable { sigil, name } => {
                // Format expected by bless parsing tests: (variable $ name)
                format!("(variable {} {})", sigil, name)
            }

            NodeKind::VariableWithAttributes { variable, attributes } => {
                let attrs = attributes.join(" ");
                format!("({} (attributes {}))", variable.to_sexp(), attrs)
            }

            NodeKind::Assignment { lhs, rhs, op } => {
                format!(
                    "(assignment_{} {} {})",
                    op.replace("=", "assign"),
                    lhs.to_sexp(),
                    rhs.to_sexp()
                )
            }

            NodeKind::Binary { op, left, right } => {
                // Tree-sitter format: (binary_op left right)
                let op_name = format_binary_operator(op);
                format!("({} {} {})", op_name, left.to_sexp(), right.to_sexp())
            }

            NodeKind::Ternary { condition, then_expr, else_expr } => {
                format!(
                    "(ternary {} {} {})",
                    condition.to_sexp(),
                    then_expr.to_sexp(),
                    else_expr.to_sexp()
                )
            }

            NodeKind::Unary { op, operand } => {
                // Tree-sitter format: (unary_op operand)
                let op_name = format_unary_operator(op);
                format!("({} {})", op_name, operand.to_sexp())
            }

            NodeKind::Diamond => "(diamond)".to_string(),

            NodeKind::Ellipsis => "(ellipsis)".to_string(),

            NodeKind::Undef => "(undef)".to_string(),

            NodeKind::Readline { filehandle } => {
                if let Some(fh) = filehandle {
                    format!("(readline {})", fh)
                } else {
                    "(readline)".to_string()
                }
            }

            NodeKind::Glob { pattern } => {
                format!("(glob {})", pattern)
            }
            NodeKind::Typeglob { name } => {
                format!("(typeglob {})", name)
            }

            NodeKind::Number { value } => {
                // Format expected by bless parsing tests: (number value)
                format!("(number {})", value)
            }

            NodeKind::String { value, interpolated } => {
                // Escape quotes in string value to prevent S-expression parsing issues
                let escaped_value = value.replace('\\', "\\\\").replace('"', "\\\"");

                // Format based on interpolation status
                if *interpolated {
                    format!("(string_interpolated \"{}\")", escaped_value)
                } else {
                    format!("(string \"{}\")", escaped_value)
                }
            }

            NodeKind::Heredoc { delimiter, content, interpolated, indented, command, .. } => {
                let type_str = if *command {
                    "heredoc_command"
                } else if *indented {
                    if *interpolated { "heredoc_indented_interpolated" } else { "heredoc_indented" }
                } else if *interpolated {
                    "heredoc_interpolated"
                } else {
                    "heredoc"
                };
                format!("({} {:?} {:?})", type_str, delimiter, content)
            }

            NodeKind::ArrayLiteral { elements } => {
                let elems = elements.iter().map(|e| e.to_sexp()).collect::<Vec<_>>().join(" ");
                format!("(array {})", elems)
            }

            NodeKind::HashLiteral { pairs } => {
                let kvs = pairs
                    .iter()
                    .map(|(k, v)| format!("({} {})", k.to_sexp(), v.to_sexp()))
                    .collect::<Vec<_>>()
                    .join(" ");
                format!("(hash {})", kvs)
            }

            NodeKind::Block { statements } => {
                let stmts = statements.iter().map(|s| s.to_sexp()).collect::<Vec<_>>().join(" ");
                format!("(block {})", stmts)
            }

            NodeKind::Eval { block } => {
                format!("(eval {})", block.to_sexp())
            }

            NodeKind::Do { block } => {
                format!("(do {})", block.to_sexp())
            }

            NodeKind::Defer { block } => {
                format!("(defer {})", block.to_sexp())
            }

            NodeKind::Try { body, catch_blocks, finally_block } => {
                let mut parts = vec![format!("(try {})", body.to_sexp())];

                for (var, block) in catch_blocks {
                    if let Some(v) = var {
                        parts.push(format!("(catch {} {})", v, block.to_sexp()));
                    } else {
                        parts.push(format!("(catch {})", block.to_sexp()));
                    }
                }

                if let Some(finally) = finally_block {
                    parts.push(format!("(finally {})", finally.to_sexp()));
                }

                parts.join(" ")
            }

            NodeKind::If { condition, then_branch, elsif_branches, else_branch } => {
                let mut parts =
                    vec![format!("(if {} {})", condition.to_sexp(), then_branch.to_sexp())];

                for (cond, block) in elsif_branches {
                    parts.push(format!("(elsif {} {})", cond.to_sexp(), block.to_sexp()));
                }

                if let Some(else_block) = else_branch {
                    parts.push(format!("(else {})", else_block.to_sexp()));
                }

                parts.join(" ")
            }

            NodeKind::LabeledStatement { label, statement } => {
                format!("(labeled_statement {} {})", label, statement.to_sexp())
            }

            NodeKind::While { condition, body, continue_block } => {
                let mut s = format!("(while {} {})", condition.to_sexp(), body.to_sexp());
                if let Some(cont) = continue_block {
                    s.push_str(&format!(" (continue {})", cont.to_sexp()));
                }
                s
            }
            NodeKind::Tie { variable, package, args } => {
                let mut s = format!("(tie {} {}", variable.to_sexp(), package.to_sexp());
                for arg in args {
                    s.push_str(&format!(" {}", arg.to_sexp()));
                }
                s.push(')');
                s
            }
            NodeKind::Untie { variable } => {
                format!("(untie {})", variable.to_sexp())
            }
            NodeKind::For { init, condition, update, body, continue_block } => {
                let init_str =
                    init.as_ref().map(|i| i.to_sexp()).unwrap_or_else(|| "()".to_string());
                let cond_str =
                    condition.as_ref().map(|c| c.to_sexp()).unwrap_or_else(|| "()".to_string());
                let update_str =
                    update.as_ref().map(|u| u.to_sexp()).unwrap_or_else(|| "()".to_string());
                let mut result =
                    format!("(for {} {} {} {})", init_str, cond_str, update_str, body.to_sexp());
                if let Some(cont) = continue_block {
                    result.push_str(&format!(" (continue {})", cont.to_sexp()));
                }
                result
            }

            NodeKind::Foreach { variable, list, body, continue_block } => {
                let cont = if let Some(cb) = continue_block {
                    format!(" {}", cb.to_sexp())
                } else {
                    String::new()
                };
                format!(
                    "(foreach {} {} {}{})",
                    variable.to_sexp(),
                    list.to_sexp(),
                    body.to_sexp(),
                    cont
                )
            }

            NodeKind::Given { expr, body } => {
                format!("(given {} {})", expr.to_sexp(), body.to_sexp())
            }

            NodeKind::When { condition, body } => {
                format!("(when {} {})", condition.to_sexp(), body.to_sexp())
            }

            NodeKind::Default { body } => {
                format!("(default {})", body.to_sexp())
            }

            NodeKind::StatementModifier { statement, modifier, condition } => {
                format!(
                    "(statement_modifier_{} {} {})",
                    modifier,
                    statement.to_sexp(),
                    condition.to_sexp()
                )
            }

            NodeKind::Subroutine { name, prototype, signature, attributes, body, name_span: _ } => {
                if let Some(sub_name) = name {
                    // Named subroutine - bless test expected format: (sub name () block)
                    let mut parts = vec![sub_name.clone()];

                    // Add attributes if present (before prototype/signature)
                    if !attributes.is_empty() {
                        for attr in attributes {
                            parts.push(format!(":{}", attr));
                        }
                    }

                    // Add prototype/signature - use () for empty prototype
                    if let Some(proto) = prototype {
                        parts.push(format!("({})", proto.to_sexp()));
                    } else if signature.is_some() {
                        // If there's a signature but no prototype, still show ()
                        parts.push("()".to_string());
                    } else {
                        parts.push("()".to_string());
                    }

                    // Add body
                    parts.push(body.to_sexp());

                    // Format: (sub name [attrs...] ()(block ...)) - space between name and (), no space between () and block
                    if parts.len() >= 3 && parts[parts.len() - 2] == "()" {
                        let name_and_attrs = parts[0..parts.len() - 2].join(" ");
                        let proto = &parts[parts.len() - 2];
                        let body = &parts[parts.len() - 1];
                        format!("(sub {} {}{})", name_and_attrs, proto, body)
                    } else {
                        format!("(sub {})", parts.join(" "))
                    }
                } else {
                    // Anonymous subroutine - tree-sitter format
                    let mut parts = Vec::new();

                    // Add attributes if present
                    if !attributes.is_empty() {
                        let attrs: Vec<String> = attributes
                            .iter()
                            .map(|_attr| "(attribute (attribute_name))".to_string())
                            .collect();
                        parts.push(format!("(attrlist {})", attrs.join("")));
                    }

                    // Add prototype if present
                    if let Some(proto) = prototype {
                        parts.push(proto.to_sexp());
                    }

                    // Add signature if present
                    if let Some(sig) = signature {
                        parts.push(sig.to_sexp());
                    }

                    // Add body
                    parts.push(body.to_sexp());

                    format!("(anonymous_subroutine_expression {})", parts.join(""))
                }
            }

            NodeKind::Prototype { content: _ } => "(prototype)".to_string(),

            NodeKind::Signature { parameters } => {
                let params = parameters.iter().map(|p| p.to_sexp()).collect::<Vec<_>>().join(" ");
                format!("(signature {})", params)
            }

            NodeKind::MandatoryParameter { variable } => {
                format!("(mandatory_parameter {})", variable.to_sexp())
            }

            NodeKind::OptionalParameter { variable, default_value } => {
                format!("(optional_parameter {} {})", variable.to_sexp(), default_value.to_sexp())
            }

            NodeKind::SlurpyParameter { variable } => {
                format!("(slurpy_parameter {})", variable.to_sexp())
            }

            NodeKind::NamedParameter { variable } => {
                format!("(named_parameter {})", variable.to_sexp())
            }

            NodeKind::Method { name: _, signature, attributes, body } => {
                let block_contents = match &body.kind {
                    NodeKind::Block { statements } => {
                        statements.iter().map(|s| s.to_sexp()).collect::<Vec<_>>().join(" ")
                    }
                    _ => body.to_sexp(),
                };

                let mut parts = vec!["(bareword)".to_string()];

                // Add signature if present
                if let Some(sig) = signature {
                    parts.push(sig.to_sexp());
                }

                // Add attributes if present
                if !attributes.is_empty() {
                    let attrs: Vec<String> = attributes
                        .iter()
                        .map(|_attr| "(attribute (attribute_name))".to_string())
                        .collect();
                    parts.push(format!("(attrlist {})", attrs.join("")));
                }

                parts.push(format!("(block {})", block_contents));
                format!("(method_declaration_statement {})", parts.join(" "))
            }

            NodeKind::Return { value } => {
                if let Some(val) = value {
                    format!("(return {})", val.to_sexp())
                } else {
                    "(return)".to_string()
                }
            }

            NodeKind::LoopControl { op, label } => {
                if let Some(l) = label {
                    format!("({} {})", op, l)
                } else {
                    format!("({})", op)
                }
            }

            NodeKind::Goto { target } => {
                format!("(goto {})", target.to_sexp())
            }

            NodeKind::MethodCall { object, method, args } => {
                let args_str = args.iter().map(|a| a.to_sexp()).collect::<Vec<_>>().join(" ");
                format!("(method_call {} {} ({}))", object.to_sexp(), method, args_str)
            }

            NodeKind::FunctionCall { name, args } => {
                // Special handling for functions that should use call format in tree-sitter tests
                if matches!(
                    name.as_str(),
                    "bless"
                        | "shift"
                        | "unshift"
                        | "open"
                        | "die"
                        | "warn"
                        | "print"
                        | "printf"
                        | "say"
                        | "push"
                        | "pop"
                        | "map"
                        | "sort"
                        | "grep"
                        | "keys"
                        | "values"
                        | "each"
                        | "defined"
                        | "scalar"
                        | "ref"
                ) {
                    let args_str = args.iter().map(|a| a.to_sexp()).collect::<Vec<_>>().join(" ");
                    if args.is_empty() {
                        format!("(call {} ())", name)
                    } else {
                        format!("(call {} ({}))", name, args_str)
                    }
                } else {
                    // Tree-sitter format varies by context
                    let args_str = args.iter().map(|a| a.to_sexp()).collect::<Vec<_>>().join(" ");
                    if args.is_empty() {
                        "(function_call_expression (function))".to_string()
                    } else {
                        format!("(ambiguous_function_call_expression (function) {})", args_str)
                    }
                }
            }

            NodeKind::IndirectCall { method, object, args } => {
                let args_str = args.iter().map(|a| a.to_sexp()).collect::<Vec<_>>().join(" ");
                format!("(indirect_call {} {} ({}))", method, object.to_sexp(), args_str)
            }

            NodeKind::Regex { pattern, replacement, modifiers, has_embedded_code } => {
                let risk_marker = if *has_embedded_code { " (risk:code)" } else { "" };
                format!("(regex {:?} {:?} {:?}{})", pattern, replacement, modifiers, risk_marker)
            }

            NodeKind::Match { expr, pattern, modifiers, has_embedded_code, negated } => {
                let risk_marker = if *has_embedded_code { " (risk:code)" } else { "" };
                let op = if *negated { "not_match" } else { "match" };
                format!(
                    "({} {} (regex {:?} {:?}{}))",
                    op,
                    expr.to_sexp(),
                    pattern,
                    modifiers,
                    risk_marker
                )
            }

            NodeKind::Substitution {
                expr,
                pattern,
                replacement,
                modifiers,
                has_embedded_code,
                negated,
            } => {
                let risk_marker = if *has_embedded_code { " (risk:code)" } else { "" };
                let neg_marker = if *negated { " (negated)" } else { "" };
                format!(
                    "(substitution {} {:?} {:?} {:?}{}{})",
                    expr.to_sexp(),
                    pattern,
                    replacement,
                    modifiers,
                    risk_marker,
                    neg_marker
                )
            }

            NodeKind::Transliteration { expr, search, replace, modifiers, negated } => {
                let neg_marker = if *negated { " (negated)" } else { "" };
                format!(
                    "(transliteration {} {:?} {:?} {:?}{})",
                    expr.to_sexp(),
                    search,
                    replace,
                    modifiers,
                    neg_marker
                )
            }

            NodeKind::Package { name, block, name_span: _ } => {
                if let Some(blk) = block {
                    format!("(package {} {})", name, blk.to_sexp())
                } else {
                    format!("(package {})", name)
                }
            }

            NodeKind::Use { module, args, has_filter_risk } => {
                let risk_marker = if *has_filter_risk { " (risk:filter)" } else { "" };
                if args.is_empty() {
                    format!("(use {}{})", module, risk_marker)
                } else {
                    let args_str = args.join(" ");
                    format!("(use {} ({}){})", module, args_str, risk_marker)
                }
            }

            NodeKind::No { module, args, has_filter_risk } => {
                let risk_marker = if *has_filter_risk { " (risk:filter)" } else { "" };
                if args.is_empty() {
                    format!("(no {}{})", module, risk_marker)
                } else {
                    let args_str = args.join(" ");
                    format!("(no {} ({}){})", module, args_str, risk_marker)
                }
            }

            NodeKind::PhaseBlock { phase, phase_span: _, block } => {
                format!("({} {})", phase, block.to_sexp())
            }

            NodeKind::DataSection { marker, body } => {
                if let Some(body_text) = body {
                    format!("(data_section {} \"{}\")", marker, body_text.escape_default())
                } else {
                    format!("(data_section {})", marker)
                }
            }

            NodeKind::Class { name, parents, body } => {
                if parents.is_empty() {
                    format!("(class {} {})", name, body.to_sexp())
                } else {
                    format!("(class {} :isa({}) {})", name, parents.join(","), body.to_sexp())
                }
            }

            NodeKind::Format { name, body } => {
                format!("(format {} {:?})", name, body)
            }

            NodeKind::Identifier { name } => {
                // Format expected by tests: (identifier name)
                format!("(identifier {})", name)
            }

            NodeKind::Error { message, partial, .. } => {
                if let Some(node) = partial {
                    format!("(ERROR \"{}\" {})", message.escape_default(), node.to_sexp())
                } else {
                    format!("(ERROR \"{}\")", message.escape_default())
                }
            }
            NodeKind::MissingExpression => "(missing_expression)".to_string(),
            NodeKind::MissingStatement => "(missing_statement)".to_string(),
            NodeKind::MissingIdentifier => "(missing_identifier)".to_string(),
            NodeKind::MissingBlock => "(missing_block)".to_string(),
            NodeKind::UnknownRest => "(UNKNOWN_REST)".to_string(),
        }
    }

    /// Convert the AST to S-expression format that unwraps expression statements in programs
    pub fn to_sexp_inner(&self) -> String {
        match &self.kind {
            NodeKind::ExpressionStatement { expression } => {
                // Check if this is an anonymous subroutine - if so, keep it wrapped
                match &expression.kind {
                    NodeKind::Subroutine { name, .. } if name.is_none() => {
                        // Anonymous subroutine should remain wrapped in expression statement
                        self.to_sexp()
                    }
                    _ => {
                        // In the inner format, other expression statements are unwrapped
                        expression.to_sexp()
                    }
                }
            }
            _ => {
                // For all other node types, use regular to_sexp
                self.to_sexp()
            }
        }
    }

    /// Call a function on every direct child node of this node.
    ///
    /// This enables depth-first traversal for operations like heredoc content attachment.
    /// The closure receives a mutable reference to each child node.
    #[inline]
    pub fn for_each_child_mut<F: FnMut(&mut Node)>(&mut self, mut f: F) {
        match &mut self.kind {
            NodeKind::Tie { variable, package, args } => {
                f(variable);
                f(package);
                for arg in args {
                    f(arg);
                }
            }
            NodeKind::Untie { variable } => f(variable),

            // Root program node
            NodeKind::Program { statements } => {
                for stmt in statements {
                    f(stmt);
                }
            }

            // Statement wrappers
            NodeKind::ExpressionStatement { expression } => f(expression),

            // Variable declarations
            NodeKind::VariableDeclaration { variable, initializer, .. } => {
                f(variable);
                if let Some(init) = initializer {
                    f(init);
                }
            }
            NodeKind::VariableListDeclaration { variables, initializer, .. } => {
                for var in variables {
                    f(var);
                }
                if let Some(init) = initializer {
                    f(init);
                }
            }
            NodeKind::VariableWithAttributes { variable, .. } => f(variable),

            // Binary operations
            NodeKind::Binary { left, right, .. } => {
                f(left);
                f(right);
            }
            NodeKind::Ternary { condition, then_expr, else_expr } => {
                f(condition);
                f(then_expr);
                f(else_expr);
            }
            NodeKind::Unary { operand, .. } => f(operand),
            NodeKind::Assignment { lhs, rhs, .. } => {
                f(lhs);
                f(rhs);
            }

            // Control flow
            NodeKind::Block { statements } => {
                for stmt in statements {
                    f(stmt);
                }
            }
            NodeKind::If { condition, then_branch, elsif_branches, else_branch, .. } => {
                f(condition);
                f(then_branch);
                for (elsif_cond, elsif_body) in elsif_branches {
                    f(elsif_cond);
                    f(elsif_body);
                }
                if let Some(else_body) = else_branch {
                    f(else_body);
                }
            }
            NodeKind::While { condition, body, continue_block, .. } => {
                f(condition);
                f(body);
                if let Some(cont) = continue_block {
                    f(cont);
                }
            }
            NodeKind::For { init, condition, update, body, continue_block, .. } => {
                if let Some(i) = init {
                    f(i);
                }
                if let Some(c) = condition {
                    f(c);
                }
                if let Some(u) = update {
                    f(u);
                }
                f(body);
                if let Some(cont) = continue_block {
                    f(cont);
                }
            }
            NodeKind::Foreach { variable, list, body, continue_block } => {
                f(variable);
                f(list);
                f(body);
                if let Some(cb) = continue_block {
                    f(cb);
                }
            }
            NodeKind::Given { expr, body } => {
                f(expr);
                f(body);
            }
            NodeKind::When { condition, body } => {
                f(condition);
                f(body);
            }
            NodeKind::Default { body } => f(body),
            NodeKind::StatementModifier { statement, condition, .. } => {
                f(statement);
                f(condition);
            }
            NodeKind::LabeledStatement { statement, .. } => f(statement),

            // Eval and Do blocks
            NodeKind::Eval { block } => f(block),
            NodeKind::Do { block } => f(block),
            NodeKind::Defer { block } => f(block),
            NodeKind::Try { body, catch_blocks, finally_block } => {
                f(body);
                for (_, catch_body) in catch_blocks {
                    f(catch_body);
                }
                if let Some(finally) = finally_block {
                    f(finally);
                }
            }

            // Function calls
            NodeKind::FunctionCall { args, .. } => {
                for arg in args {
                    f(arg);
                }
            }
            NodeKind::MethodCall { object, args, .. } => {
                f(object);
                for arg in args {
                    f(arg);
                }
            }
            NodeKind::IndirectCall { object, args, .. } => {
                f(object);
                for arg in args {
                    f(arg);
                }
            }

            // Functions
            NodeKind::Subroutine { prototype, signature, body, .. } => {
                if let Some(proto) = prototype {
                    f(proto);
                }
                if let Some(sig) = signature {
                    f(sig);
                }
                f(body);
            }
            NodeKind::Method { signature, body, .. } => {
                if let Some(sig) = signature {
                    f(sig);
                }
                f(body);
            }
            NodeKind::Return { value } => {
                if let Some(v) = value {
                    f(v);
                }
            }
            NodeKind::Goto { target } => f(target),
            NodeKind::Signature { parameters } => {
                for param in parameters {
                    f(param);
                }
            }
            NodeKind::MandatoryParameter { variable } => f(variable),
            NodeKind::OptionalParameter { variable, default_value } => {
                f(variable);
                f(default_value);
            }
            NodeKind::SlurpyParameter { variable } => f(variable),
            NodeKind::NamedParameter { variable } => f(variable),

            // Pattern matching
            NodeKind::Match { expr, .. } => f(expr),
            NodeKind::Substitution { expr, .. } => f(expr),
            NodeKind::Transliteration { expr, .. } => f(expr),

            // Containers
            NodeKind::ArrayLiteral { elements } => {
                for elem in elements {
                    f(elem);
                }
            }
            NodeKind::HashLiteral { pairs } => {
                for (key, value) in pairs {
                    f(key);
                    f(value);
                }
            }

            // Package system
            NodeKind::Package { block, .. } => {
                if let Some(b) = block {
                    f(b);
                }
            }
            NodeKind::PhaseBlock { block, .. } => f(block),
            NodeKind::Class { body, .. } => f(body),

            // Error node might have a partial valid tree
            NodeKind::Error { partial, .. } => {
                if let Some(node) = partial {
                    f(node);
                }
            }

            // Leaf nodes (no children to traverse)
            NodeKind::Variable { .. }
            | NodeKind::Identifier { .. }
            | NodeKind::Number { .. }
            | NodeKind::String { .. }
            | NodeKind::Heredoc { .. }
            | NodeKind::Regex { .. }
            | NodeKind::Readline { .. }
            | NodeKind::Glob { .. }
            | NodeKind::Typeglob { .. }
            | NodeKind::Diamond
            | NodeKind::Ellipsis
            | NodeKind::Undef
            | NodeKind::Use { .. }
            | NodeKind::No { .. }
            | NodeKind::Prototype { .. }
            | NodeKind::DataSection { .. }
            | NodeKind::Format { .. }
            | NodeKind::LoopControl { .. }
            | NodeKind::MissingExpression
            | NodeKind::MissingStatement
            | NodeKind::MissingIdentifier
            | NodeKind::MissingBlock
            | NodeKind::UnknownRest => {}
        }
    }

    /// Call a function on every direct child node of this node (immutable version).
    ///
    /// This enables depth-first traversal for read-only operations like AST analysis.
    /// The closure receives an immutable reference to each child node.
    #[inline]
    pub fn for_each_child<'a, F: FnMut(&'a Node)>(&'a self, mut f: F) {
        match &self.kind {
            NodeKind::Tie { variable, package, args } => {
                f(variable);
                f(package);
                for arg in args {
                    f(arg);
                }
            }
            NodeKind::Untie { variable } => f(variable),

            // Root program node
            NodeKind::Program { statements } => {
                for stmt in statements {
                    f(stmt);
                }
            }

            // Statement wrappers
            NodeKind::ExpressionStatement { expression } => f(expression),

            // Variable declarations
            NodeKind::VariableDeclaration { variable, initializer, .. } => {
                f(variable);
                if let Some(init) = initializer {
                    f(init);
                }
            }
            NodeKind::VariableListDeclaration { variables, initializer, .. } => {
                for var in variables {
                    f(var);
                }
                if let Some(init) = initializer {
                    f(init);
                }
            }
            NodeKind::VariableWithAttributes { variable, .. } => f(variable),

            // Binary operations
            NodeKind::Binary { left, right, .. } => {
                f(left);
                f(right);
            }
            NodeKind::Ternary { condition, then_expr, else_expr } => {
                f(condition);
                f(then_expr);
                f(else_expr);
            }
            NodeKind::Unary { operand, .. } => f(operand),
            NodeKind::Assignment { lhs, rhs, .. } => {
                f(lhs);
                f(rhs);
            }

            // Control flow
            NodeKind::Block { statements } => {
                for stmt in statements {
                    f(stmt);
                }
            }
            NodeKind::If { condition, then_branch, elsif_branches, else_branch, .. } => {
                f(condition);
                f(then_branch);
                for (elsif_cond, elsif_body) in elsif_branches {
                    f(elsif_cond);
                    f(elsif_body);
                }
                if let Some(else_body) = else_branch {
                    f(else_body);
                }
            }
            NodeKind::While { condition, body, continue_block, .. } => {
                f(condition);
                f(body);
                if let Some(cont) = continue_block {
                    f(cont);
                }
            }
            NodeKind::For { init, condition, update, body, continue_block, .. } => {
                if let Some(i) = init {
                    f(i);
                }
                if let Some(c) = condition {
                    f(c);
                }
                if let Some(u) = update {
                    f(u);
                }
                f(body);
                if let Some(cont) = continue_block {
                    f(cont);
                }
            }
            NodeKind::Foreach { variable, list, body, continue_block } => {
                f(variable);
                f(list);
                f(body);
                if let Some(cb) = continue_block {
                    f(cb);
                }
            }
            NodeKind::Given { expr, body } => {
                f(expr);
                f(body);
            }
            NodeKind::When { condition, body } => {
                f(condition);
                f(body);
            }
            NodeKind::Default { body } => f(body),
            NodeKind::StatementModifier { statement, condition, .. } => {
                f(statement);
                f(condition);
            }
            NodeKind::LabeledStatement { statement, .. } => f(statement),

            // Eval and Do blocks
            NodeKind::Eval { block } => f(block),
            NodeKind::Do { block } => f(block),
            NodeKind::Defer { block } => f(block),
            NodeKind::Try { body, catch_blocks, finally_block } => {
                f(body);
                for (_, catch_body) in catch_blocks {
                    f(catch_body);
                }
                if let Some(finally) = finally_block {
                    f(finally);
                }
            }

            // Function calls
            NodeKind::FunctionCall { args, .. } => {
                for arg in args {
                    f(arg);
                }
            }
            NodeKind::MethodCall { object, args, .. } => {
                f(object);
                for arg in args {
                    f(arg);
                }
            }
            NodeKind::IndirectCall { object, args, .. } => {
                f(object);
                for arg in args {
                    f(arg);
                }
            }

            // Functions
            NodeKind::Subroutine { prototype, signature, body, .. } => {
                if let Some(proto) = prototype {
                    f(proto);
                }
                if let Some(sig) = signature {
                    f(sig);
                }
                f(body);
            }
            NodeKind::Method { signature, body, .. } => {
                if let Some(sig) = signature {
                    f(sig);
                }
                f(body);
            }
            NodeKind::Return { value } => {
                if let Some(v) = value {
                    f(v);
                }
            }
            NodeKind::Goto { target } => f(target),
            NodeKind::Signature { parameters } => {
                for param in parameters {
                    f(param);
                }
            }
            NodeKind::MandatoryParameter { variable } => f(variable),
            NodeKind::OptionalParameter { variable, default_value } => {
                f(variable);
                f(default_value);
            }
            NodeKind::SlurpyParameter { variable } => f(variable),
            NodeKind::NamedParameter { variable } => f(variable),

            // Pattern matching
            NodeKind::Match { expr, .. } => f(expr),
            NodeKind::Substitution { expr, .. } => f(expr),
            NodeKind::Transliteration { expr, .. } => f(expr),

            // Containers
            NodeKind::ArrayLiteral { elements } => {
                for elem in elements {
                    f(elem);
                }
            }
            NodeKind::HashLiteral { pairs } => {
                for (key, value) in pairs {
                    f(key);
                    f(value);
                }
            }

            // Package system
            NodeKind::Package { block, .. } => {
                if let Some(b) = block {
                    f(b);
                }
            }
            NodeKind::PhaseBlock { block, .. } => f(block),
            NodeKind::Class { body, .. } => f(body),

            // Error node might have a partial valid tree
            NodeKind::Error { partial, .. } => {
                if let Some(node) = partial {
                    f(node);
                }
            }

            // Leaf nodes (no children to traverse)
            NodeKind::Variable { .. }
            | NodeKind::Identifier { .. }
            | NodeKind::Number { .. }
            | NodeKind::String { .. }
            | NodeKind::Heredoc { .. }
            | NodeKind::Regex { .. }
            | NodeKind::Readline { .. }
            | NodeKind::Glob { .. }
            | NodeKind::Typeglob { .. }
            | NodeKind::Diamond
            | NodeKind::Ellipsis
            | NodeKind::Undef
            | NodeKind::Use { .. }
            | NodeKind::No { .. }
            | NodeKind::Prototype { .. }
            | NodeKind::DataSection { .. }
            | NodeKind::Format { .. }
            | NodeKind::LoopControl { .. }
            | NodeKind::MissingExpression
            | NodeKind::MissingStatement
            | NodeKind::MissingIdentifier
            | NodeKind::MissingBlock
            | NodeKind::UnknownRest => {}
        }
    }

    /// Count the total number of nodes in this subtree (inclusive).
    ///
    /// # Examples
    ///
    /// ```
    /// use perl_ast::{Node, NodeKind, SourceLocation};
    ///
    /// let loc = SourceLocation { start: 0, end: 1 };
    /// let leaf = Node::new(NodeKind::Number { value: "1".to_string() }, loc);
    /// assert_eq!(leaf.count_nodes(), 1);
    ///
    /// let program = Node::new(
    ///     NodeKind::Program { statements: vec![leaf] },
    ///     loc,
    /// );
    /// assert_eq!(program.count_nodes(), 2);
    /// ```
    pub fn count_nodes(&self) -> usize {
        let mut count = 1;
        self.for_each_child(|child| {
            count += child.count_nodes();
        });
        count
    }

    /// Collect direct child nodes into a vector for convenience APIs.
    ///
    /// # Examples
    ///
    /// ```
    /// use perl_ast::{Node, NodeKind, SourceLocation};
    ///
    /// let loc = SourceLocation { start: 0, end: 1 };
    /// let stmt = Node::new(NodeKind::Number { value: "1".to_string() }, loc);
    /// let program = Node::new(
    ///     NodeKind::Program { statements: vec![stmt] },
    ///     loc,
    /// );
    /// assert_eq!(program.children().len(), 1);
    /// ```
    #[inline]
    pub fn children(&self) -> Vec<&Node> {
        let mut children = Vec::new();
        self.for_each_child(|child| children.push(child));
        children
    }

    /// Count direct child nodes without allocating an intermediate vector.
    ///
    /// This is more efficient than `children().len()` when callers only need
    /// cardinality.
    #[inline]
    pub fn child_count(&self) -> usize {
        let mut count = 0;
        self.for_each_child(|_| count += 1);
        count
    }

    /// Get the first direct child node, if any.
    ///
    /// Optimized to avoid allocating the children vector.
    #[inline]
    pub fn first_child(&self) -> Option<&Node> {
        let mut result = None;
        self.for_each_child(|child| {
            if result.is_none() {
                result = Some(child);
            }
        });
        result
    }

    /// Returns `true` when this node's source span contains `offset`.
    ///
    /// The start position is inclusive and the end position is exclusive.
    #[inline]
    pub fn contains_offset(&self, offset: usize) -> bool {
        self.location.start <= offset && offset < self.location.end
    }

    /// Returns the byte length of this node's source span.
    ///
    /// Uses saturating subtraction so malformed spans never underflow.
    #[inline]
    pub fn span_len(&self) -> usize {
        self.location.end.saturating_sub(self.location.start)
    }

    /// Get the last direct child node, if any.
    ///
    /// Optimized to avoid allocating the children vector.
    ///
    /// # Examples
    ///
    /// ```
    /// use perl_ast::{Node, NodeKind, SourceLocation};
    ///
    /// let loc = SourceLocation { start: 0, end: 1 };
    /// let first = Node::new(NodeKind::Number { value: "1".to_string() }, loc);
    /// let second = Node::new(NodeKind::Number { value: "2".to_string() }, loc);
    /// let program = Node::new(
    ///     NodeKind::Program { statements: vec![first, second] },
    ///     loc,
    /// );
    ///
    /// assert_eq!(program.last_child().map(|n| n.kind.kind_name()), Some("Number"));
    /// assert_eq!(Node::new(NodeKind::Block { statements: vec![] }, loc).last_child(), None);
    /// ```
    #[inline]
    pub fn last_child(&self) -> Option<&Node> {
        let mut result = None;
        self.for_each_child(|child| {
            result = Some(child);
        });
        result
    }
}

/// Comprehensive enumeration of all Perl language constructs supported by the parser.
///
/// This enum represents every possible AST node type that can be parsed from Perl code
/// during the Parse → Index → Navigate → Complete → Analyze workflow. Each variant captures
/// the semantic meaning and structural relationships needed for complete script analysis
/// and transformation.
///
/// # LSP Workflow Integration
///
/// Node kinds are processed differently across workflow stages:
/// - **Parse**: All variants are produced by the parser
/// - **Index**: Symbol-bearing variants feed workspace indexing
/// - **Navigate**: Call and reference variants support navigation features
/// - **Complete**: Expression variants provide completion context
/// - **Analyze**: Semantic variants drive diagnostics and refactoring
///
/// # Examples
///
/// Pattern-match on node kinds to extract semantic information:
///
/// ```
/// use perl_ast::{Node, NodeKind, SourceLocation};
///
/// let loc = SourceLocation { start: 0, end: 5 };
/// let node = Node::new(
///     NodeKind::Variable { sigil: "$".to_string(), name: "foo".to_string() },
///     loc,
/// );
///
/// assert!(matches!(
///     &node.kind,
///     NodeKind::Variable { sigil, name } if sigil == "$" && name == "foo"
/// ));
/// ```
///
/// Use [`kind_name()`](NodeKind::kind_name) for debugging and diagnostics:
///
/// ```
/// use perl_ast::NodeKind;
///
/// let kind = NodeKind::Number { value: "99".to_string() };
/// assert_eq!(kind.kind_name(), "Number");
///
/// let kind = NodeKind::Variable { sigil: "@".to_string(), name: "list".to_string() };
/// assert_eq!(kind.kind_name(), "Variable");
/// ```
///
/// # Performance Considerations
///
/// The enum design optimizes for large codebases:
/// - Box pointers minimize stack usage for recursive structures
/// - Vector storage enables efficient bulk operations on child nodes
/// - Clone operations optimized for concurrent analysis workflows
/// - Pattern matching performance tuned for common Perl constructs
#[derive(Debug, Clone, PartialEq)]
pub enum NodeKind {
    /// Top-level program containing all statements in an Perl script
    ///
    /// This is the root node for any parsed Perl script content, containing all
    /// top-level statements found during the Parse stage of LSP workflow.
    Program {
        /// All top-level statements in the Perl script
        statements: Vec<Node>,
    },

    /// Statement wrapper for expressions that appear at statement level
    ///
    /// Used during Analyze stage to distinguish between expressions used as
    /// statements versus expressions within other contexts during Perl parsing.
    ExpressionStatement {
        /// The expression being used as a statement
        expression: Box<Node>,
    },

    /// Variable declaration with scope declarator in Perl script processing
    ///
    /// Represents declarations like `my $var`, `our $global`, `local $dynamic`, etc.
    /// Critical for Analyze stage symbol table construction during Perl parsing.
    VariableDeclaration {
        /// Scope declarator: "my", "our", "local", "state"
        declarator: String,
        /// The variable being declared
        variable: Box<Node>,
        /// Variable attributes (e.g., ":shared", ":locked")
        attributes: Vec<String>,
        /// Optional initializer expression
        initializer: Option<Box<Node>>,
    },

    /// Multiple variable declaration in a single statement
    ///
    /// Handles constructs like `my ($x, $y) = @values` common in Perl script processing.
    /// Supports efficient bulk variable analysis during Navigate stage operations.
    VariableListDeclaration {
        /// Scope declarator for all variables in the list
        declarator: String,
        /// All variables being declared in the list
        variables: Vec<Node>,
        /// Attributes applied to the variable list
        attributes: Vec<String>,
        /// Optional initializer for the entire variable list
        initializer: Option<Box<Node>>,
    },

    /// Perl variable reference (scalar, array, hash, etc.) in Perl parsing workflow
    Variable {
        /// Variable sigil indicating type: $, @, %, &, *
        sigil: String, // $, @, %, &, *
        /// Variable name without sigil
        name: String,
    },

    /// Variable with additional attributes for enhanced LSP workflow
    VariableWithAttributes {
        /// The base variable node
        variable: Box<Node>,
        /// List of attribute names applied to the variable
        attributes: Vec<String>,
    },

    /// Assignment operation for LSP data processing workflows
    Assignment {
        /// Left-hand side of assignment
        lhs: Box<Node>,
        /// Right-hand side of assignment
        rhs: Box<Node>,
        /// Assignment operator: =, +=, -=, etc.
        op: String, // =, +=, -=, etc.
    },

    // Expressions
    /// Binary operation for Perl parsing workflow calculations
    Binary {
        /// Binary operator
        op: String,
        /// Left operand
        left: Box<Node>,
        /// Right operand
        right: Box<Node>,
    },

    /// Ternary conditional expression for Perl parsing workflow logic
    Ternary {
        /// Condition to evaluate
        condition: Box<Node>,
        /// Expression when condition is true
        then_expr: Box<Node>,
        /// Expression when condition is false
        else_expr: Box<Node>,
    },

    /// Unary operation for Perl parsing workflow
    Unary {
        /// Unary operator
        op: String,
        /// Operand to apply operator to
        operand: Box<Node>,
    },

    // I/O operations
    /// Diamond operator for file input in Perl parsing workflow
    Diamond, // <>

    /// Ellipsis operator for Perl parsing workflow
    Ellipsis, // ...

    /// Undef value for Perl parsing workflow
    Undef, // undef

    /// Readline operation for LSP file processing
    Readline {
        /// Optional filehandle: `<STDIN>`, `<$fh>`, etc.
        filehandle: Option<String>, // <STDIN>, <$fh>, etc.
    },

    /// Glob pattern for LSP workspace file matching
    Glob {
        /// Pattern string for file matching
        pattern: String, // <*.txt>
    },

    /// Typeglob expression: `*foo` or `*main::bar`
    ///
    /// Provides access to all symbol table entries for a given name.
    Typeglob {
        /// Name of the symbol (including package qualification)
        name: String,
    },

    /// Numeric literal in Perl code (integer, float, hex, octal, binary)
    ///
    /// Represents all numeric literal forms: `42`, `3.14`, `0x1A`, `0o755`, `0b1010`.
    Number {
        /// String representation preserving original format
        value: String,
    },

    /// String literal with optional interpolation
    ///
    /// Handles both single-quoted (`'literal'`) and double-quoted (`"$interpolated"`) strings.
    String {
        /// String content (after quote processing)
        value: String,
        /// Whether the string supports variable interpolation
        interpolated: bool,
    },

    /// Heredoc string literal for multi-line content
    ///
    /// Supports all heredoc forms: `<<EOF`, `<<'EOF'`, `<<"EOF"`, `<<~EOF` (indented).
    Heredoc {
        /// Delimiter marking heredoc boundaries
        delimiter: String,
        /// Content between delimiters
        content: String,
        /// Whether content supports variable interpolation
        interpolated: bool,
        /// Whether leading whitespace is stripped (<<~ form)
        indented: bool,
        /// Whether this is a command execution heredoc (<<`EOF`)
        command: bool,
        /// Body span for breakpoint detection (populated by drain_pending_heredocs)
        body_span: Option<SourceLocation>,
    },

    /// Array literal expression: `(1, 2, 3)` or `[1, 2, 3]`
    ArrayLiteral {
        /// Elements in the array
        elements: Vec<Node>,
    },

    /// Hash literal expression: `(key => 'value')` or `{key => 'value'}`
    HashLiteral {
        /// Key-value pairs in the hash
        pairs: Vec<(Node, Node)>,
    },

    /// Block of statements: `{ ... }`
    ///
    /// Used for control structures, subroutine bodies, and bare blocks.
    Block {
        /// Statements within the block
        statements: Vec<Node>,
    },

    /// Eval block for exception handling: `eval { ... }`
    Eval {
        /// Block to evaluate with exception trapping
        block: Box<Node>,
    },

    /// Do block for file inclusion or expression evaluation: `do { ... }` or `do "file"`
    Do {
        /// Block to execute or file expression
        block: Box<Node>,
    },

    /// Defer block for deferred cleanup on scope exit (Perl 5.36+ experimental, stable in 5.40)
    Defer {
        /// Block to execute on scope exit
        block: Box<Node>,
    },

    /// Try-catch-finally for modern exception handling (Syntax::Keyword::Try style)
    Try {
        /// Try block body
        body: Box<Node>,
        /// Catch blocks: (optional exception variable, handler block)
        catch_blocks: Vec<(Option<String>, Box<Node>)>,
        /// Optional finally block
        finally_block: Option<Box<Node>>,
    },

    /// If-elsif-else conditional statement
    If {
        /// Condition expression
        condition: Box<Node>,
        /// Then branch block
        then_branch: Box<Node>,
        /// Elsif branches: (condition, block) pairs
        elsif_branches: Vec<(Box<Node>, Box<Node>)>,
        /// Optional else branch
        else_branch: Option<Box<Node>>,
    },

    /// Statement with a label for loop control: `LABEL: while (...)`
    LabeledStatement {
        /// Label name (e.g., "OUTER", "LINE")
        label: String,
        /// Labeled statement (typically a loop)
        statement: Box<Node>,
    },

    /// While loop: `while (condition) { ... }`
    While {
        /// Loop condition
        condition: Box<Node>,
        /// Loop body
        body: Box<Node>,
        /// Optional continue block
        continue_block: Option<Box<Node>>,
    },

    /// Tie operation for binding variables to objects: `tie %hash, 'Package', @args`
    Tie {
        /// Variable being tied
        variable: Box<Node>,
        /// Class/package name to tie to
        package: Box<Node>,
        /// Arguments passed to TIE* method
        args: Vec<Node>,
    },

    /// Untie operation for unbinding variables: `untie %hash`
    Untie {
        /// Variable being untied
        variable: Box<Node>,
    },

    /// C-style for loop: `for (init; cond; update) { ... }`
    For {
        /// Initialization expression
        init: Option<Box<Node>>,
        /// Loop condition
        condition: Option<Box<Node>>,
        /// Update expression
        update: Option<Box<Node>>,
        /// Loop body
        body: Box<Node>,
        /// Optional continue block
        continue_block: Option<Box<Node>>,
    },

    /// Foreach loop: `foreach my $item (@list) { ... }`
    Foreach {
        /// Iterator variable
        variable: Box<Node>,
        /// List to iterate
        list: Box<Node>,
        /// Loop body
        body: Box<Node>,
        /// Optional continue block
        continue_block: Option<Box<Node>>,
    },

    /// Given statement for switch-like matching (Perl 5.10+)
    Given {
        /// Expression to match against
        expr: Box<Node>,
        /// Body containing when/default blocks
        body: Box<Node>,
    },

    /// When clause in given/switch: `when ($pattern) { ... }`
    When {
        /// Pattern to match
        condition: Box<Node>,
        /// Handler block
        body: Box<Node>,
    },

    /// Default clause in given/switch: `default { ... }`
    Default {
        /// Handler block for unmatched cases
        body: Box<Node>,
    },

    /// Statement modifier syntax: `print "ok" if $condition`
    StatementModifier {
        /// Statement to conditionally execute
        statement: Box<Node>,
        /// Modifier keyword: if, unless, while, until, for, foreach
        modifier: String,
        /// Modifier condition
        condition: Box<Node>,
    },

    // Functions
    /// Subroutine declaration (function) including name, prototype, signature and body.
    Subroutine {
        /// Name of the subroutine
        ///
        /// # Precise Navigation Support
        /// - Added name_span for exact LSP navigation
        /// - Enables precise go-to-definition and hover behavior
        /// - O(1) span lookup in workspace symbols
        ///
        /// ## Integration Points
        /// - Semantic token providers
        /// - Cross-reference generation
        /// - Symbol renaming
        name: Option<String>,

        /// Source location span of the subroutine name
        ///
        /// ## Usage Notes
        /// - Always corresponds to the name field
        /// - Provides constant-time position information
        /// - Essential for precise editor interactions
        name_span: Option<SourceLocation>,

        /// Optional prototype node (e.g. `($;@)`).
        prototype: Option<Box<Node>>,
        /// Optional signature node (Perl 5.20+ feature).
        signature: Option<Box<Node>>,
        /// Attributes attached to the subroutine (`:lvalue`, etc.).
        attributes: Vec<String>,
        /// The body block of the subroutine.
        body: Box<Node>,
    },

    /// Subroutine prototype specification: `sub foo ($;@) { ... }`
    Prototype {
        /// Prototype string defining argument behavior
        content: String,
    },

    /// Subroutine signature (Perl 5.20+): `sub foo ($x, $y = 0) { ... }`
    Signature {
        /// List of signature parameters
        parameters: Vec<Node>,
    },

    /// Mandatory signature parameter: `$x` in `sub foo ($x) { }`
    MandatoryParameter {
        /// Variable being bound
        variable: Box<Node>,
    },

    /// Optional signature parameter with default: `$y = 0` in `sub foo ($y = 0) { }`
    OptionalParameter {
        /// Variable being bound
        variable: Box<Node>,
        /// Default value expression
        default_value: Box<Node>,
    },

    /// Slurpy parameter collecting remaining args: `@rest` or `%opts` in signature
    SlurpyParameter {
        /// Array or hash variable to receive remaining arguments
        variable: Box<Node>,
    },

    /// Named parameter placeholder in signature (future Perl feature)
    NamedParameter {
        /// Variable for named parameter binding
        variable: Box<Node>,
    },

    /// Method declaration (Perl 5.38+ with `use feature 'class'`)
    Method {
        /// Method name
        name: String,
        /// Optional signature
        signature: Option<Box<Node>>,
        /// Method attributes (e.g., `:lvalue`)
        attributes: Vec<String>,
        /// Method body
        body: Box<Node>,
    },

    /// Return statement: `return;` or `return $value;`
    Return {
        /// Optional return value
        value: Option<Box<Node>>,
    },

    /// Loop control statement: `next`, `last`, or `redo`
    LoopControl {
        /// Control keyword: "next", "last", or "redo"
        op: String,
        /// Optional label: `next LABEL`
        label: Option<String>,
    },

    /// Goto statement: `goto LABEL`, `goto &sub`, or `goto $expr`
    Goto {
        /// The target of the goto (label identifier, sub reference, or expression)
        target: Box<Node>,
    },

    /// Method call: `$obj->method(@args)` or `$obj->method`
    MethodCall {
        /// Object or class expression
        object: Box<Node>,
        /// Method name being called
        method: String,
        /// Method arguments
        args: Vec<Node>,
    },

    /// Function call: `foo(@args)` or `foo()`
    FunctionCall {
        /// Function name (may be qualified: `Package::func`)
        name: String,
        /// Function arguments
        args: Vec<Node>,
    },

    /// Indirect object call (legacy syntax): `new Class @args`
    IndirectCall {
        /// Method name
        method: String,
        /// Object or class
        object: Box<Node>,
        /// Arguments
        args: Vec<Node>,
    },

    /// Regex literal: `/pattern/modifiers` or `qr/pattern/modifiers`
    Regex {
        /// Regular expression pattern
        pattern: String,
        /// Replacement string (for s/// when parsed as regex)
        replacement: Option<String>,
        /// Regex modifiers (i, m, s, x, g, etc.)
        modifiers: String,
        /// Whether the regex contains embedded code `(?{...})`
        has_embedded_code: bool,
    },

    /// Match operation: `$str =~ /pattern/modifiers` or `$str !~ /pattern/modifiers`
    Match {
        /// Expression to match against
        expr: Box<Node>,
        /// Pattern to match
        pattern: String,
        /// Match modifiers
        modifiers: String,
        /// Whether the regex contains embedded code `(?{...})`
        has_embedded_code: bool,
        /// Whether the binding operator was `!~` (negated match)
        negated: bool,
    },

    /// Substitution operation: `$str =~ s/pattern/replacement/modifiers`
    Substitution {
        /// Expression to substitute in
        expr: Box<Node>,
        /// Pattern to find
        pattern: String,
        /// Replacement string
        replacement: String,
        /// Substitution modifiers (g, e, r, etc.)
        modifiers: String,
        /// Whether the regex contains embedded code `(?{...})`
        has_embedded_code: bool,
        /// Whether the binding operator was `!~` (negated match)
        negated: bool,
    },

    /// Transliteration operation: `$str =~ tr/search/replace/` or `y///`
    Transliteration {
        /// Expression to transliterate
        expr: Box<Node>,
        /// Characters to search for
        search: String,
        /// Replacement characters
        replace: String,
        /// Transliteration modifiers (c, d, s, r)
        modifiers: String,
        /// Whether the binding operator was `!~` (negated match)
        negated: bool,
    },

    // Package system
    /// Package declaration (e.g. `package Foo;`) and optional inline block form.
    Package {
        /// Name of the package
        ///
        /// # Precise Navigation Support
        /// - Added name_span for exact LSP navigation
        /// - Enables precise go-to-definition and hover behavior
        /// - O(1) span lookup in workspace symbols
        ///
        /// ## Integration Points
        /// - Workspace indexing
        /// - Cross-module symbol resolution
        /// - Code action providers
        name: String,

        /// Source location span of the package name
        ///
        /// ## Usage Notes
        /// - Always corresponds to the name field
        /// - Provides constant-time position information
        /// - Essential for precise editor interactions
        name_span: SourceLocation,

        /// Optional inline block for `package Foo { ... }` declarations.
        block: Option<Box<Node>>,
    },

    /// Use statement for module loading: `use Module qw(imports);`
    Use {
        /// Module name to load
        module: String,
        /// Import arguments (symbols to import)
        args: Vec<String>,
        /// Whether this module is a known source filter (security risk)
        has_filter_risk: bool,
    },

    /// No statement for disabling features: `no strict;`
    No {
        /// Module/pragma name to disable
        module: String,
        /// Arguments for the no statement
        args: Vec<String>,
        /// Whether this module is a known source filter (security risk)
        has_filter_risk: bool,
    },

    /// Phase block for compile/runtime hooks: `BEGIN`, `END`, `CHECK`, `INIT`, `UNITCHECK`
    PhaseBlock {
        /// Phase name: BEGIN, END, CHECK, INIT, UNITCHECK
        phase: String,
        /// Source location span of the phase block name for precise navigation
        phase_span: Option<SourceLocation>,
        /// Block to execute during the specified phase
        block: Box<Node>,
    },

    /// Data section marker: `__DATA__` or `__END__`
    DataSection {
        /// Section marker (__DATA__ or __END__)
        marker: String,
        /// Content following the marker (if any)
        body: Option<String>,
    },

    /// Class declaration (Perl 5.38+ with `use feature 'class'`)
    Class {
        /// Class name
        name: String,
        /// Parent class names from `:isa(Parent)` attributes
        parents: Vec<String>,
        /// Class body containing methods and attributes
        body: Box<Node>,
    },

    /// Format declaration for legacy report generation
    Format {
        /// Format name (defaults to filehandle name)
        name: String,
        /// Format specification body
        body: String,
    },

    /// Bare identifier (bareword or package-qualified name)
    Identifier {
        /// Identifier string
        name: String,
    },

    /// Parse error placeholder with error message and recovery context
    Error {
        /// Error description
        message: String,
        /// Expected token types (if any)
        expected: Vec<TokenKind>,
        /// The token actually found (if any)
        found: Option<Token>,
        /// Partial AST node parsed before error (if any)
        partial: Option<Box<Node>>,
    },

    /// Missing expression where one was expected
    MissingExpression,
    /// Missing statement where one was expected
    MissingStatement,
    /// Missing identifier where one was expected
    MissingIdentifier,
    /// Missing block where one was expected
    MissingBlock,

    /// Lexer budget exceeded marker preserving partial parse results
    ///
    /// Used when recursion or token limits are hit to preserve already-parsed content.
    UnknownRest,
}

impl NodeKind {
    /// Get the name of this `NodeKind` as a static string.
    ///
    /// Useful for diagnostics, logging, and human-readable AST dumps.
    ///
    /// # Examples
    ///
    /// ```
    /// use perl_ast::NodeKind;
    ///
    /// let kind = NodeKind::Variable { sigil: "$".to_string(), name: "x".to_string() };
    /// assert_eq!(kind.kind_name(), "Variable");
    ///
    /// let kind = NodeKind::Program { statements: vec![] };
    /// assert_eq!(kind.kind_name(), "Program");
    /// ```
    pub fn kind_name(&self) -> &'static str {
        match self {
            NodeKind::Program { .. } => "Program",
            NodeKind::ExpressionStatement { .. } => "ExpressionStatement",
            NodeKind::VariableDeclaration { .. } => "VariableDeclaration",
            NodeKind::VariableListDeclaration { .. } => "VariableListDeclaration",
            NodeKind::Variable { .. } => "Variable",
            NodeKind::VariableWithAttributes { .. } => "VariableWithAttributes",
            NodeKind::Assignment { .. } => "Assignment",
            NodeKind::Binary { .. } => "Binary",
            NodeKind::Ternary { .. } => "Ternary",
            NodeKind::Unary { .. } => "Unary",
            NodeKind::Diamond => "Diamond",
            NodeKind::Ellipsis => "Ellipsis",
            NodeKind::Undef => "Undef",
            NodeKind::Readline { .. } => "Readline",
            NodeKind::Glob { .. } => "Glob",
            NodeKind::Typeglob { .. } => "Typeglob",
            NodeKind::Number { .. } => "Number",
            NodeKind::String { .. } => "String",
            NodeKind::Heredoc { .. } => "Heredoc",
            NodeKind::ArrayLiteral { .. } => "ArrayLiteral",
            NodeKind::HashLiteral { .. } => "HashLiteral",
            NodeKind::Block { .. } => "Block",
            NodeKind::Eval { .. } => "Eval",
            NodeKind::Do { .. } => "Do",
            NodeKind::Defer { .. } => "Defer",
            NodeKind::Try { .. } => "Try",
            NodeKind::If { .. } => "If",
            NodeKind::LabeledStatement { .. } => "LabeledStatement",
            NodeKind::While { .. } => "While",
            NodeKind::Tie { .. } => "Tie",
            NodeKind::Untie { .. } => "Untie",
            NodeKind::For { .. } => "For",
            NodeKind::Foreach { .. } => "Foreach",
            NodeKind::Given { .. } => "Given",
            NodeKind::When { .. } => "When",
            NodeKind::Default { .. } => "Default",
            NodeKind::StatementModifier { .. } => "StatementModifier",
            NodeKind::Subroutine { .. } => "Subroutine",
            NodeKind::Prototype { .. } => "Prototype",
            NodeKind::Signature { .. } => "Signature",
            NodeKind::MandatoryParameter { .. } => "MandatoryParameter",
            NodeKind::OptionalParameter { .. } => "OptionalParameter",
            NodeKind::SlurpyParameter { .. } => "SlurpyParameter",
            NodeKind::NamedParameter { .. } => "NamedParameter",
            NodeKind::Method { .. } => "Method",
            NodeKind::Return { .. } => "Return",
            NodeKind::LoopControl { .. } => "LoopControl",
            NodeKind::Goto { .. } => "Goto",
            NodeKind::MethodCall { .. } => "MethodCall",
            NodeKind::FunctionCall { .. } => "FunctionCall",
            NodeKind::IndirectCall { .. } => "IndirectCall",
            NodeKind::Regex { .. } => "Regex",
            NodeKind::Match { .. } => "Match",
            NodeKind::Substitution { .. } => "Substitution",
            NodeKind::Transliteration { .. } => "Transliteration",
            NodeKind::Package { .. } => "Package",
            NodeKind::Use { .. } => "Use",
            NodeKind::No { .. } => "No",
            NodeKind::PhaseBlock { .. } => "PhaseBlock",
            NodeKind::DataSection { .. } => "DataSection",
            NodeKind::Class { .. } => "Class",
            NodeKind::Format { .. } => "Format",
            NodeKind::Identifier { .. } => "Identifier",
            NodeKind::Error { .. } => "Error",
            NodeKind::MissingExpression => "MissingExpression",
            NodeKind::MissingStatement => "MissingStatement",
            NodeKind::MissingIdentifier => "MissingIdentifier",
            NodeKind::MissingBlock => "MissingBlock",
            NodeKind::UnknownRest => "UnknownRest",
        }
    }

    /// Canonical list of **all** `kind_name()` strings, in alphabetical order.
    ///
    /// Every consumer that needs the full set of NodeKind names should reference
    /// this constant instead of maintaining a hand-written copy.
    pub const ALL_KIND_NAMES: &[&'static str] = &[
        "ArrayLiteral",
        "Assignment",
        "Binary",
        "Block",
        "Class",
        "DataSection",
        "Default",
        "Defer",
        "Diamond",
        "Do",
        "Ellipsis",
        "Error",
        "Eval",
        "ExpressionStatement",
        "For",
        "Foreach",
        "Format",
        "FunctionCall",
        "Given",
        "Glob",
        "Goto",
        "HashLiteral",
        "Heredoc",
        "Identifier",
        "If",
        "IndirectCall",
        "LabeledStatement",
        "LoopControl",
        "MandatoryParameter",
        "Match",
        "Method",
        "MethodCall",
        "MissingBlock",
        "MissingExpression",
        "MissingIdentifier",
        "MissingStatement",
        "NamedParameter",
        "No",
        "Number",
        "OptionalParameter",
        "Package",
        "PhaseBlock",
        "Program",
        "Prototype",
        "Readline",
        "Regex",
        "Return",
        "Signature",
        "SlurpyParameter",
        "StatementModifier",
        "String",
        "Subroutine",
        "Substitution",
        "Ternary",
        "Tie",
        "Transliteration",
        "Try",
        "Typeglob",
        "Unary",
        "Undef",
        "UnknownRest",
        "Untie",
        "Use",
        "Variable",
        "VariableDeclaration",
        "VariableListDeclaration",
        "VariableWithAttributes",
        "When",
        "While",
    ];

    /// Subset of `ALL_KIND_NAMES` that represent synthetic/recovery nodes.
    ///
    /// These kinds are only produced by `parse_with_recovery()` on malformed
    /// input and should not be expected in clean parses.
    pub const RECOVERY_KIND_NAMES: &[&'static str] = &[
        "Error",
        "MissingBlock",
        "MissingExpression",
        "MissingIdentifier",
        "MissingStatement",
        "UnknownRest",
    ];
}

impl fmt::Display for NodeKind {
    /// Formats as the canonical `kind_name()` string.
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str(self.kind_name())
    }
}

impl fmt::Display for Node {
    /// Formats as the tree-sitter compatible S-expression.
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str(&self.to_sexp())
    }
}

/// Format unary operator for S-expression output
fn format_unary_operator(op: &str) -> String {
    match op {
        // Arithmetic unary operators
        "+" => "unary_+".to_string(),
        "-" => "unary_-".to_string(),

        // Logical unary operators
        "!" => "unary_not".to_string(),
        "not" => "unary_not".to_string(),

        // Bitwise complement
        "~" => "unary_complement".to_string(),

        // Reference operator
        "\\" => "unary_ref".to_string(),

        // Postfix operators
        "++" => "unary_++".to_string(),
        "--" => "unary_--".to_string(),

        // File test operators
        "-f" => "unary_-f".to_string(),
        "-d" => "unary_-d".to_string(),
        "-e" => "unary_-e".to_string(),
        "-r" => "unary_-r".to_string(),
        "-w" => "unary_-w".to_string(),
        "-x" => "unary_-x".to_string(),
        "-o" => "unary_-o".to_string(),
        "-R" => "unary_-R".to_string(),
        "-W" => "unary_-W".to_string(),
        "-X" => "unary_-X".to_string(),
        "-O" => "unary_-O".to_string(),
        "-s" => "unary_-s".to_string(),
        "-p" => "unary_-p".to_string(),
        "-S" => "unary_-S".to_string(),
        "-b" => "unary_-b".to_string(),
        "-c" => "unary_-c".to_string(),
        "-t" => "unary_-t".to_string(),
        "-u" => "unary_-u".to_string(),
        "-g" => "unary_-g".to_string(),
        "-k" => "unary_-k".to_string(),
        "-T" => "unary_-T".to_string(),
        "-B" => "unary_-B".to_string(),
        "-M" => "unary_-M".to_string(),
        "-A" => "unary_-A".to_string(),
        "-C" => "unary_-C".to_string(),
        "-l" => "unary_-l".to_string(),
        "-z" => "unary_-z".to_string(),

        // Postfix dereferencing
        "->@*" => "unary_->@*".to_string(),
        "->%*" => "unary_->%*".to_string(),
        "->$*" => "unary_->$*".to_string(),
        "->&*" => "unary_->&*".to_string(),
        "->**" => "unary_->**".to_string(),

        // Defined operator
        "defined" => "unary_defined".to_string(),

        // Default case for unknown operators
        _ => format!("unary_{}", op.replace(' ', "_")),
    }
}

/// Format binary operator for S-expression output
fn format_binary_operator(op: &str) -> String {
    match op {
        // Arithmetic operators
        "+" => "binary_+".to_string(),
        "-" => "binary_-".to_string(),
        "*" => "binary_*".to_string(),
        "/" => "binary_/".to_string(),
        "%" => "binary_%".to_string(),
        "**" => "binary_**".to_string(),

        // Comparison operators
        "==" => "binary_==".to_string(),
        "!=" => "binary_!=".to_string(),
        "<" => "binary_<".to_string(),
        ">" => "binary_>".to_string(),
        "<=" => "binary_<=".to_string(),
        ">=" => "binary_>=".to_string(),
        "<=>" => "binary_<=>".to_string(),

        // String comparison
        "eq" => "binary_eq".to_string(),
        "ne" => "binary_ne".to_string(),
        "lt" => "binary_lt".to_string(),
        "le" => "binary_le".to_string(),
        "gt" => "binary_gt".to_string(),
        "ge" => "binary_ge".to_string(),
        "cmp" => "binary_cmp".to_string(),

        // Logical operators
        "&&" => "binary_&&".to_string(),
        "||" => "binary_||".to_string(),
        "and" => "binary_and".to_string(),
        "or" => "binary_or".to_string(),
        "xor" => "binary_xor".to_string(),

        // Bitwise operators
        "&" => "binary_&".to_string(),
        "|" => "binary_|".to_string(),
        "^" => "binary_^".to_string(),
        "<<" => "binary_<<".to_string(),
        ">>" => "binary_>>".to_string(),

        // Pattern matching
        "=~" => "binary_=~".to_string(),
        "!~" => "binary_!~".to_string(),

        // Smart match
        "~~" => "binary_~~".to_string(),

        // String repetition
        "x" => "binary_x".to_string(),

        // Concatenation
        "." => "binary_.".to_string(),

        // Range operators
        ".." => "binary_..".to_string(),
        "..." => "binary_...".to_string(),

        // Type checking
        "isa" => "binary_isa".to_string(),

        // Assignment operators
        "=" => "binary_=".to_string(),
        "+=" => "binary_+=".to_string(),
        "-=" => "binary_-=".to_string(),
        "*=" => "binary_*=".to_string(),
        "/=" => "binary_/=".to_string(),
        "%=" => "binary_%=".to_string(),
        "**=" => "binary_**=".to_string(),
        ".=" => "binary_.=".to_string(),
        "&=" => "binary_&=".to_string(),
        "|=" => "binary_|=".to_string(),
        "^=" => "binary_^=".to_string(),
        "<<=" => "binary_<<=".to_string(),
        ">>=" => "binary_>>=".to_string(),
        "&&=" => "binary_&&=".to_string(),
        "||=" => "binary_||=".to_string(),
        "//=" => "binary_//=".to_string(),

        // Defined-or operator
        "//" => "binary_//".to_string(),

        // Method calls and dereferencing
        "->" => "binary_->".to_string(),

        // Hash/array access
        "{}" => "binary_{}".to_string(),
        "[]" => "binary_[]".to_string(),

        // Arrow hash/array dereference
        "->{}" => "arrow_hash_deref".to_string(),
        "->[]" => "arrow_array_deref".to_string(),

        // Default case for unknown operators
        _ => format!("binary_{}", op.replace(' ', "_")),
    }
}

// SourceLocation is now provided by perl-position-tracking crate
// See the re-export at the top of this file

#[cfg(test)]
mod tests {
    use super::*;
    use std::collections::BTreeSet;

    /// Build a dummy instance for every `NodeKind` variant and return its
    /// `kind_name()`.  This ensures the compiler forces us to update here
    /// whenever a variant is added/removed.
    fn all_kind_names_from_variants() -> BTreeSet<&'static str> {
        let loc = SourceLocation { start: 0, end: 0 };
        let dummy_node = || Node::new(NodeKind::Undef, loc);

        let variants: Vec<NodeKind> = vec![
            NodeKind::Program { statements: vec![] },
            NodeKind::ExpressionStatement { expression: Box::new(dummy_node()) },
            NodeKind::VariableDeclaration {
                declarator: String::new(),
                variable: Box::new(dummy_node()),
                attributes: vec![],
                initializer: None,
            },
            NodeKind::VariableListDeclaration {
                declarator: String::new(),
                variables: vec![],
                attributes: vec![],
                initializer: None,
            },
            NodeKind::Variable { sigil: String::new(), name: String::new() },
            NodeKind::VariableWithAttributes {
                variable: Box::new(dummy_node()),
                attributes: vec![],
            },
            NodeKind::Assignment {
                lhs: Box::new(dummy_node()),
                rhs: Box::new(dummy_node()),
                op: String::new(),
            },
            NodeKind::Binary {
                op: String::new(),
                left: Box::new(dummy_node()),
                right: Box::new(dummy_node()),
            },
            NodeKind::Ternary {
                condition: Box::new(dummy_node()),
                then_expr: Box::new(dummy_node()),
                else_expr: Box::new(dummy_node()),
            },
            NodeKind::Unary { op: String::new(), operand: Box::new(dummy_node()) },
            NodeKind::Diamond,
            NodeKind::Ellipsis,
            NodeKind::Undef,
            NodeKind::Readline { filehandle: None },
            NodeKind::Glob { pattern: String::new() },
            NodeKind::Typeglob { name: String::new() },
            NodeKind::Number { value: String::new() },
            NodeKind::String { value: String::new(), interpolated: false },
            NodeKind::Heredoc {
                delimiter: String::new(),
                content: String::new(),
                interpolated: false,
                indented: false,
                command: false,
                body_span: None,
            },
            NodeKind::ArrayLiteral { elements: vec![] },
            NodeKind::HashLiteral { pairs: vec![] },
            NodeKind::Block { statements: vec![] },
            NodeKind::Eval { block: Box::new(dummy_node()) },
            NodeKind::Do { block: Box::new(dummy_node()) },
            NodeKind::Defer { block: Box::new(dummy_node()) },
            NodeKind::Try {
                body: Box::new(dummy_node()),
                catch_blocks: vec![],
                finally_block: None,
            },
            NodeKind::If {
                condition: Box::new(dummy_node()),
                then_branch: Box::new(dummy_node()),
                elsif_branches: vec![],
                else_branch: None,
            },
            NodeKind::LabeledStatement { label: String::new(), statement: Box::new(dummy_node()) },
            NodeKind::While {
                condition: Box::new(dummy_node()),
                body: Box::new(dummy_node()),
                continue_block: None,
            },
            NodeKind::Tie {
                variable: Box::new(dummy_node()),
                package: Box::new(dummy_node()),
                args: vec![],
            },
            NodeKind::Untie { variable: Box::new(dummy_node()) },
            NodeKind::For {
                init: None,
                condition: None,
                update: None,
                body: Box::new(dummy_node()),
                continue_block: None,
            },
            NodeKind::Foreach {
                variable: Box::new(dummy_node()),
                list: Box::new(dummy_node()),
                body: Box::new(dummy_node()),
                continue_block: None,
            },
            NodeKind::Given { expr: Box::new(dummy_node()), body: Box::new(dummy_node()) },
            NodeKind::When { condition: Box::new(dummy_node()), body: Box::new(dummy_node()) },
            NodeKind::Default { body: Box::new(dummy_node()) },
            NodeKind::StatementModifier {
                statement: Box::new(dummy_node()),
                modifier: String::new(),
                condition: Box::new(dummy_node()),
            },
            NodeKind::Subroutine {
                name: None,
                name_span: None,
                prototype: None,
                signature: None,
                attributes: vec![],
                body: Box::new(dummy_node()),
            },
            NodeKind::Prototype { content: String::new() },
            NodeKind::Signature { parameters: vec![] },
            NodeKind::MandatoryParameter { variable: Box::new(dummy_node()) },
            NodeKind::OptionalParameter {
                variable: Box::new(dummy_node()),
                default_value: Box::new(dummy_node()),
            },
            NodeKind::SlurpyParameter { variable: Box::new(dummy_node()) },
            NodeKind::NamedParameter { variable: Box::new(dummy_node()) },
            NodeKind::Method {
                name: String::new(),
                signature: None,
                attributes: vec![],
                body: Box::new(dummy_node()),
            },
            NodeKind::Return { value: None },
            NodeKind::LoopControl { op: String::new(), label: None },
            NodeKind::Goto { target: Box::new(dummy_node()) },
            NodeKind::MethodCall {
                object: Box::new(dummy_node()),
                method: String::new(),
                args: vec![],
            },
            NodeKind::FunctionCall { name: String::new(), args: vec![] },
            NodeKind::IndirectCall {
                method: String::new(),
                object: Box::new(dummy_node()),
                args: vec![],
            },
            NodeKind::Regex {
                pattern: String::new(),
                replacement: None,
                modifiers: String::new(),
                has_embedded_code: false,
            },
            NodeKind::Match {
                expr: Box::new(dummy_node()),
                pattern: String::new(),
                modifiers: String::new(),
                has_embedded_code: false,
                negated: false,
            },
            NodeKind::Substitution {
                expr: Box::new(dummy_node()),
                pattern: String::new(),
                replacement: String::new(),
                modifiers: String::new(),
                has_embedded_code: false,
                negated: false,
            },
            NodeKind::Transliteration {
                expr: Box::new(dummy_node()),
                search: String::new(),
                replace: String::new(),
                modifiers: String::new(),
                negated: false,
            },
            NodeKind::Package { name: String::new(), name_span: loc, block: None },
            NodeKind::Use { module: String::new(), args: vec![], has_filter_risk: false },
            NodeKind::No { module: String::new(), args: vec![], has_filter_risk: false },
            NodeKind::PhaseBlock {
                phase: String::new(),
                phase_span: None,
                block: Box::new(dummy_node()),
            },
            NodeKind::DataSection { marker: String::new(), body: None },
            NodeKind::Class { name: String::new(), parents: vec![], body: Box::new(dummy_node()) },
            NodeKind::Format { name: String::new(), body: String::new() },
            NodeKind::Identifier { name: String::new() },
            NodeKind::Error {
                message: String::new(),
                expected: vec![],
                found: None,
                partial: None,
            },
            NodeKind::MissingExpression,
            NodeKind::MissingStatement,
            NodeKind::MissingIdentifier,
            NodeKind::MissingBlock,
            NodeKind::UnknownRest,
        ];

        variants.iter().map(|v| v.kind_name()).collect()
    }

    #[test]
    fn all_kind_names_is_consistent_with_kind_name() {
        let from_enum = all_kind_names_from_variants();
        let from_const: BTreeSet<&str> = NodeKind::ALL_KIND_NAMES.iter().copied().collect();

        // Check for duplicates in the const array
        assert_eq!(
            NodeKind::ALL_KIND_NAMES.len(),
            from_const.len(),
            "ALL_KIND_NAMES contains duplicates"
        );

        let only_in_enum: Vec<_> = from_enum.difference(&from_const).collect();
        let only_in_const: Vec<_> = from_const.difference(&from_enum).collect();

        assert!(
            only_in_enum.is_empty() && only_in_const.is_empty(),
            "ALL_KIND_NAMES is out of sync with NodeKind variants:\n  \
             in enum but not in ALL_KIND_NAMES: {only_in_enum:?}\n  \
             in ALL_KIND_NAMES but not in enum: {only_in_const:?}"
        );
    }

    #[test]
    fn recovery_kind_names_is_subset_of_all() {
        let all: BTreeSet<&str> = NodeKind::ALL_KIND_NAMES.iter().copied().collect();
        let recovery: BTreeSet<&str> = NodeKind::RECOVERY_KIND_NAMES.iter().copied().collect();

        // No duplicates
        assert_eq!(
            NodeKind::RECOVERY_KIND_NAMES.len(),
            recovery.len(),
            "RECOVERY_KIND_NAMES contains duplicates"
        );

        let not_in_all: Vec<_> = recovery.difference(&all).collect();
        assert!(
            not_in_all.is_empty(),
            "RECOVERY_KIND_NAMES contains entries not in ALL_KIND_NAMES: {not_in_all:?}"
        );
    }
}