evtx 0.12.2

A Fast (and safe) parser for the Windows XML Event Log (EVTX) format
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
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
//! Compiled templates: the per-record fast path.
//!
//! Each cached template definition compiles once per (base indent, root?) key
//! into a flat program: pre-rendered output text plus a list of ops — copy
//! this text range, format value N here. Per-record rendering is then a
//! descriptor scan (no `BinXmlValue` materialization, no IR walk, no
//! render-time scans) plus a linear op loop that formats values straight
//! from chunk bytes into the output buffer.
//!
//! Coverage is deliberately partial: the compiler bails on shapes whose
//! output depends on values in ways the op set doesn't model (processing
//! instructions, multi-placeholder content, runtime-forked layouts), and the
//! per-record pre-flight bails on anything irregular (mis-sized scalars,
//! unknown types, non-EOF trailers). A bailed record materializes into an IR
//! tree, which the same walker that compiles templates renders directly —
//! both paths share one implementation, so they cannot produce different
//! bytes for the same record. The pre-flight runs before any output is
//! written, so the executor never unwinds a partial record.

use crate::ParserSettings;
use crate::binxml::ir::{
    IrTemplateCache, TEMPLATE_DEFINITION_HEADER_SIZE, build_tree_from_binxml_bytes_direct,
    read_template_definition_header_at,
};
use crate::binxml::tokens::{single_instance_offset, token};
use crate::binxml::value_render::{StringEscapeMode, ValueRenderer};
use crate::err::Result;
use crate::evtx_chunk::EvtxChunk;
use crate::model::ir::{Attr, Element, ElementId, IrTree, Node, Placeholder, Text};
use crate::utils::ByteCursor;
use ahash::AHashMap;
use std::sync::Arc;

const INDENT_WIDTH: u16 = 2;
const XML_DECL: &[u8] = b"<?xml version=\"1.0\" encoding=\"utf-8\"?>\n";

/// A `lits` byte range.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
struct LitRange(u32, u32);

impl LitRange {
    /// The literal bytes this range denotes.
    fn of(self, lits: &[u8]) -> &[u8] {
        &lits[self.0 as usize..self.1 as usize]
    }
}
/// A `Preflight::slots` index range (one instance's slots).
type SlotRange = (u32, u32);

/// Duplicate-key `_N` suffix counter: 0 the first time `name` is seen (no
/// suffix), then 1, 2, … for repeats. Shared by the JSON compiler (compile
/// time) and the materialized layer (per record) so the rule cannot drift.
fn next_name_suffix<K: PartialEq>(name: K, counts: &mut Vec<(K, u16)>) -> u16 {
    if let Some((_, c)) = counts.iter_mut().find(|(n, _)| *n == name) {
        let suffix = *c;
        *c += 1;
        suffix
    } else {
        counts.push((name, 1));
        0
    }
}

/// One compiled op. `slot` indexes the instance's substitution array.
#[derive(Debug, Clone)]
enum XOp {
    /// Emit `lits[range]`.
    Lit(LitRange),
    /// Escaped value text in an always-emitted context (attribute value with
    /// static non-empty parts). No emptiness branch.
    Val { slot: u16, in_attr: bool },
    /// ` name="` + escaped value + `"`, all omitted when the value is
    /// empty-ish (mirrors `attribute_value_is_empty`: optionality ignored).
    AttrVal { slot: u16, pre: LitRange },
    /// `<Tag ...attrs` has been emitted (sans `>`). Emit `>` and the single
    /// placeholder content, branching on the runtime slot class:
    /// Skip -> `tail_empty`; text-ish -> text + `tail_text`;
    /// element -> newline + nested/frag at `indent + 2` + `tail_elem`.
    Body {
        slot: u16,
        optional: bool,
        indent: u16,
        tail_text: LitRange,
        tail_empty: LitRange,
        tail_elem: LitRange,
    },
    /// Placeholder in element-child position under a statically line-formed
    /// parent. Skip -> nothing; element -> nested/frag at `indent`;
    /// text-ish -> `ind` + text + newline.
    ChildSlot {
        slot: u16,
        optional: bool,
        indent: u16,
        ind: LitRange,
    },
    /// An attribute-less `<Data>` element whose entire content is one hole
    /// (MS-EVEN6 array expansion site). Scalar values follow `Body`
    /// semantics with `open` spliced first; a string array repeats the
    /// element per item — single-item arrays render inline like a scalar,
    /// empty items in larger arrays take the two-line empty form. Mirrors
    /// `array_expand` over the materialized tree.
    Expand {
        slot: u16,
        optional: bool,
        indent: u16,
        open: LitRange,
        tail_text: LitRange,
        tail_empty: LitRange,
        tail_elem: LitRange,
    },
}

/// A compiled template program for one (def offset, base indent, root?) key.
pub(crate) struct XmlProgram {
    lits: Vec<u8>,
    ops: Vec<XOp>,
    indent_on: bool,
    /// `(slot, child_indent)` for every slot rendered in element position;
    /// the pre-flight uses this to resolve nested-instance programs up front.
    elem_slots: Vec<(u16, u16)>,
    /// Slots compiled as `XOp::Expand` (string arrays allowed).
    expand_slots: Vec<u16>,
}

/// Per-chunk program cache. `None` marks templates that failed to compile so
/// they are not retried for every record.
pub(crate) type ProgramCache<P> = AHashMap<(u32, u16, bool), Option<Arc<P>>>;

/// Cross-chunk program store: templates are identical across chunks (same
/// GUID + size + definition bytes), so programs compile once per file/parser
/// instead of once per chunk. Shared across worker threads.
#[derive(Default)]
pub(crate) struct ProgramStore {
    xml: std::sync::RwLock<AHashMap<StoreKey, Option<Arc<XmlProgram>>>>,
    json: std::sync::RwLock<AHashMap<StoreKey, Option<Arc<JsonProgram>>>>,
    hasher: ahash::RandomState,
}

/// Content identity of a compiled program: template identity (GUID, size,
/// definition-bytes hash) plus the compile parameters.
type StoreKey = ([u8; 16], u32, u64, u16, bool);

impl std::fmt::Debug for ProgramStore {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("ProgramStore").finish_non_exhaustive()
    }
}

/// Per-format shard access used by `get_or_compile`.
pub(crate) trait StoredProgram: TemplateProgram {
    fn shard(store: &ProgramStore) -> &std::sync::RwLock<AHashMap<StoreKey, Option<Arc<Self>>>>;
}

impl StoredProgram for XmlProgram {
    fn shard(store: &ProgramStore) -> &std::sync::RwLock<AHashMap<StoreKey, Option<Arc<Self>>>> {
        &store.xml
    }
}

impl StoredProgram for JsonProgram {
    fn shard(store: &ProgramStore) -> &std::sync::RwLock<AHashMap<StoreKey, Option<Arc<Self>>>> {
        &store.json
    }
}

/// Per-chunk render state for the per-record APIs (`EvtxRecord::into_*`).
/// Fully owned (programs carry their own bytes), so `EvtxChunk` can hold it
/// behind a `RefCell` without self-referential lifetimes.
#[derive(Default)]
pub(crate) struct RenderCaches {
    pub(crate) xml: XmlProgramCache,
    pub(crate) json: JsonProgramCache,
    pub(crate) pf_xml: Preflight<XmlProgram>,
    pub(crate) pf_json: Preflight<JsonProgram>,
}

impl std::fmt::Debug for RenderCaches {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("RenderCaches")
            .field("xml_programs", &self.xml.len())
            .field("json_programs", &self.json.len())
            .finish()
    }
}
pub(crate) type XmlProgramCache = ProgramCache<XmlProgram>;
pub(crate) type JsonProgramCache = ProgramCache<JsonProgram>;

/// Per-slot validity constraint checked by the pre-flight (record falls back
/// when violated), so executors stay infallible.
#[derive(Debug, Clone, Copy)]
pub(crate) enum SlotConstraint {
    /// Slot must not be a non-empty embedded BinXml value (0x21).
    ForbidElem(u16),
    /// Slot must be a (single-instance) embedded BinXml value or empty.
    ElemOrEmpty(u16),
}

/// What the generic pre-flight needs from a compiled program.
pub(crate) trait TemplateProgram: Sized {
    /// Whether the executor can render non-instance BinXml fragments in
    /// element position (via a materialized fallback).
    const ALLOW_GENERIC_FRAGS: bool;
    /// `(slot, child_indent)` pairs rendered in element position.
    fn elem_slots(&self) -> &[(u16, u16)];
    fn constraints(&self) -> &[SlotConstraint] {
        &[]
    }
    /// Slots whose ops handle string-array values (element repetition /
    /// positional-Data aggregation). Arrays anywhere else bail.
    fn expand_slots(&self) -> &[u16] {
        &[]
    }
    fn compile(
        tree: &IrTree<'_>,
        has_literal_array: bool,
        base_indent: u16,
        is_root: bool,
        settings: &ParserSettings,
    ) -> Option<Self>;
}

impl TemplateProgram for XmlProgram {
    const ALLOW_GENERIC_FRAGS: bool = true;
    fn elem_slots(&self) -> &[(u16, u16)] {
        &self.elem_slots
    }
    fn expand_slots(&self) -> &[u16] {
        &self.expand_slots
    }
    fn compile(
        tree: &IrTree<'_>,
        has_literal_array: bool,
        base_indent: u16,
        is_root: bool,
        settings: &ParserSettings,
    ) -> Option<Self> {
        compile_xml_template(tree, has_literal_array, base_indent, is_root, settings)
    }
}

// ---------------------------------------------------------------------------
// Compilation (template definition IR -> program)
// ---------------------------------------------------------------------------

struct Bail;

struct XmlCompiler<'t, 'a> {
    tree: &'t IrTree<'a>,
    lits: Vec<u8>,
    ops: Vec<XOp>,
    /// Start of the not-yet-flushed literal run (`lits[run_start..]`).
    run_start: usize,
    elem_slots: Vec<(u16, u16)>,
    expand_slots: Vec<u16>,
    indent_on: bool,
    vr: ValueRenderer,
    /// Walking a fully materialized tree (slow lane / fragments): placeholder
    /// sites are errors instead of ops, and any error is a real record error.
    /// When false (template compilation), any error just means "not cacheable".
    materialized: bool,
}

/// Compile-lane bail sentinel (mapped to `None` by `compile_xml_template`).
fn bail_err() -> crate::err::EvtxError {
    crate::err::EvtxError::FailedToCreateRecordModel("compiled-template bail")
}

fn unresolved_placeholder() -> crate::err::EvtxError {
    crate::err::EvtxError::FailedToCreateRecordModel("unresolved placeholder in tree")
}

/// Compile a cached template definition into an XML program. Returns `None`
/// for shapes the op set doesn't model.
fn compile_xml_template(
    tree: &IrTree<'_>,
    has_literal_array: bool,
    base_indent: u16,
    is_root: bool,
    settings: &ParserSettings,
) -> Option<XmlProgram> {
    if has_literal_array {
        return None;
    }
    let mut c = XmlCompiler {
        tree,
        lits: Vec::with_capacity(512),
        ops: Vec::with_capacity(32),
        run_start: 0,
        elem_slots: Vec::new(),
        expand_slots: Vec::new(),
        indent_on: settings.should_indent(),
        vr: ValueRenderer::new(),
        materialized: false,
    };
    if is_root {
        c.lits.extend_from_slice(XML_DECL);
    }
    match c.compile_element(tree.root(), base_indent) {
        Ok(()) => {
            c.flush_lit_run();
            Some(XmlProgram {
                lits: c.lits,
                ops: c.ops,
                indent_on: c.indent_on,
                elem_slots: c.elem_slots,
                expand_slots: c.expand_slots,
            })
        }
        Err(_) => None,
    }
}

/// Render a fully materialized record tree to XML: the single-walker slow
/// lane (irregular records, after materialization) writing straight into
/// `out`. Byte-compatible with the cached-program lane by construction —
/// it IS the same walk, with zero placeholder sites.
pub(crate) fn render_tree_xml(
    tree: &IrTree<'_>,
    settings: &ParserSettings,
    out: &mut Vec<u8>,
) -> Result<()> {
    let mut c = XmlCompiler {
        tree,
        lits: std::mem::take(out),
        ops: Vec::new(),
        run_start: 0,
        elem_slots: Vec::new(),
        expand_slots: Vec::new(),
        indent_on: settings.should_indent(),
        vr: ValueRenderer::new(),
        materialized: true,
    };
    c.lits.extend_from_slice(XML_DECL);
    let res = c.compile_element(tree.root(), 0);
    debug_assert!(c.ops.is_empty(), "materialized walk produced ops");
    *out = c.lits;
    res
}

/// Render a materialized fragment subtree at `indent` (executor cold path).
fn render_subtree_xml(
    tree: &IrTree<'_>,
    indent: u16,
    indent_on: bool,
    out: &mut Vec<u8>,
) -> Result<()> {
    let mut c = XmlCompiler {
        tree,
        lits: std::mem::take(out),
        ops: Vec::new(),
        run_start: 0,
        elem_slots: Vec::new(),
        expand_slots: Vec::new(),
        indent_on,
        vr: ValueRenderer::new(),
        materialized: true,
    };
    let res = c.compile_element(tree.root(), indent);
    debug_assert!(c.ops.is_empty(), "materialized walk produced ops");
    *out = c.lits;
    res
}

impl<'t, 'a> XmlCompiler<'t, 'a> {
    fn element_ref(&self, id: ElementId) -> &'t Element<'a> {
        self.tree.arena().get(id).expect("invalid element id")
    }

    fn flush_lit_run(&mut self) {
        let end = self.lits.len();
        if end > self.run_start {
            self.ops
                .push(XOp::Lit(LitRange(self.run_start as u32, end as u32)));
        }
        self.run_start = end;
    }

    /// Emit bytes via `f` as a side range (not part of any literal run).
    /// The current run must be flushed first.
    fn side_range(&mut self, f: impl FnOnce(&mut Self)) -> LitRange {
        debug_assert_eq!(self.run_start, self.lits.len(), "unflushed lit run");
        let start = self.lits.len() as u32;
        f(self);
        self.run_start = self.lits.len();
        LitRange(start, self.lits.len() as u32)
    }

    fn indent_str(&mut self, level: u16) {
        if self.indent_on {
            self.lits.extend(std::iter::repeat_n(b' ', level as usize));
        }
    }

    fn newline(&mut self) {
        if self.indent_on {
            self.lits.push(b'\n');
        }
    }

    fn compile_element(&mut self, id: ElementId, indent: u16) -> Result<()> {
        let element = self.element_ref(id);

        // Attribute-less single-hole `<Data>` elements are the array
        // expansion sites: compile them as self-contained `Expand` ops (the
        // open tag must be able to repeat per array item).
        if !self.materialized
            && element.attrs.is_empty()
            && is_data_element_name(element.name.as_str())
            && let ChildrenKind::SinglePlaceholder(ph) = classify_children(element)
        {
            return self.compile_expand(element, ph, indent);
        }

        // Note: even placeholder-free subtrees are walked here (not delegated
        // to the materialized emitter): template-scope layout classification
        // (scan rule) differs from the materialized rule for present-but-empty
        // literal children, and this walk is the template-lane source of truth.
        self.indent_str(indent);
        self.lits.push(b'<');
        self.lits
            .extend_from_slice(element.name.as_str().as_bytes());

        for attr in &element.attrs {
            self.compile_attr(attr)?;
        }

        match classify_children(element) {
            ChildrenKind::SinglePlaceholder(ph) => {
                if self.materialized {
                    return Err(unresolved_placeholder());
                }
                let name = element.name.as_str().as_bytes();
                let is_binary = element.name.as_str() == "Binary";
                self.lits.push(b'>');
                self.flush_lit_run();
                let tail_text = self.side_range(|c| {
                    c.lits.extend_from_slice(b"</");
                    c.lits.extend_from_slice(name);
                    c.lits.push(b'>');
                    c.newline();
                });
                let tail_empty = self.side_range(|c| {
                    if !is_binary {
                        c.newline();
                        c.indent_str(indent);
                    }
                    c.lits.extend_from_slice(b"</");
                    c.lits.extend_from_slice(name);
                    c.lits.push(b'>');
                    c.newline();
                });
                let tail_elem = self.side_range(|c| {
                    c.indent_str(indent);
                    c.lits.extend_from_slice(b"</");
                    c.lits.extend_from_slice(name);
                    c.lits.push(b'>');
                    c.newline();
                });
                self.elem_slots.push((ph.id, indent + INDENT_WIDTH));
                self.ops.push(XOp::Body {
                    slot: ph.id,
                    optional: ph.optional,
                    indent,
                    tail_text,
                    tail_empty,
                    tail_elem,
                });
            }
            ChildrenKind::Empty => {
                self.lits.push(b'>');
                if element.name.as_str() != "Binary" {
                    self.newline();
                    self.indent_str(indent);
                }
                self.close_tag_inline(element);
            }
            ChildrenKind::StaticInline => {
                self.lits.push(b'>');
                let nodes = &element.children;
                let mut idx = 0;
                while idx < nodes.len() {
                    match &nodes[idx] {
                        // Mirror `render_nodes`' processing-instruction
                        // pairing: `<?target data?>` / `<?target?>`.
                        Node::PITarget(name) => {
                            self.lits.extend_from_slice(b"<?");
                            self.lits.extend_from_slice(name.as_str().as_bytes());
                            if let Some(Node::PIData(data)) = nodes.get(idx + 1) {
                                self.lits.push(b' ');
                                self.compile_raw_text(data);
                                self.lits.extend_from_slice(b"?>");
                                idx += 2;
                                continue;
                            }
                            self.lits.extend_from_slice(b"?>");
                        }
                        Node::PIData(_) => {
                            return Err(crate::err::EvtxError::FailedToCreateRecordModel(
                                "PIData without PITarget",
                            ));
                        }
                        node => self.compile_literal_content_node(node, false)?,
                    }
                    idx += 1;
                }
                self.close_tag_inline(element);
            }
            ChildrenKind::StaticLines => {
                self.lits.push(b'>');
                self.newline();
                for node in &element.children {
                    match node {
                        Node::Element(child) => {
                            self.compile_element(*child, indent + INDENT_WIDTH)?;
                        }
                        Node::Placeholder(ph) => {
                            if self.materialized {
                                return Err(unresolved_placeholder());
                            }
                            self.flush_lit_run();
                            let ind = self.side_range(|c| c.indent_str(indent + INDENT_WIDTH));
                            self.elem_slots.push((ph.id, indent + INDENT_WIDTH));
                            self.ops.push(XOp::ChildSlot {
                                slot: ph.id,
                                optional: ph.optional,
                                indent: indent + INDENT_WIDTH,
                                ind,
                            });
                        }
                        other => {
                            self.indent_str(indent + INDENT_WIDTH);
                            self.compile_literal_content_node(other, false)?;
                            self.newline();
                        }
                    }
                }
                self.indent_str(indent);
                self.close_tag_inline(element);
            }
            ChildrenKind::Bail => {
                // Only placeholder-bearing shapes classify as Bail; on a
                // materialized tree that means an unresolved placeholder.
                return Err(if self.materialized {
                    unresolved_placeholder()
                } else {
                    bail_err()
                });
            }
        }
        Ok(())
    }

    fn close_tag_inline(&mut self, element: &Element<'_>) {
        self.lits.extend_from_slice(b"</");
        self.lits
            .extend_from_slice(element.name.as_str().as_bytes());
        self.lits.push(b'>');
        self.newline();
    }

    fn compile_attr(&mut self, attr: &Attr<'a>) -> Result<()> {
        // Placeholders are dynamic; everything else is compile-time constant.
        // Mirrors `attribute_value_is_empty` + `render_nodes`.
        let mut has_nonempty_const = false;
        let mut n_placeholders = 0usize;
        for node in attr.value.iter() {
            match node {
                Node::Placeholder(_) => {
                    if self.materialized {
                        return Err(crate::err::EvtxError::FailedToCreateRecordModel(
                            "unresolved placeholder in attribute value",
                        ));
                    }
                    n_placeholders += 1;
                }
                Node::Element(_) => {
                    return Err(crate::err::EvtxError::FailedToCreateRecordModel(
                        "element node inside attribute value",
                    ));
                }
                Node::PITarget(_) | Node::PIData(_) => {
                    return Err(crate::err::EvtxError::Unimplemented {
                        name: "processing instruction in attribute value".to_string(),
                    });
                }
                Node::Text(t) => {
                    if !t.is_empty() {
                        has_nonempty_const = true;
                    }
                }
                // `attribute_value_is_empty` treats CData (even zero-length)
                // as non-empty.
                Node::CData(_) | Node::EntityRef(_) | Node::CharRef(_) => has_nonempty_const = true,
                Node::Value(v) => {
                    if !crate::model::ir::is_optional_empty(v) {
                        has_nonempty_const = true;
                    }
                }
            }
        }

        if n_placeholders == 0 {
            if !has_nonempty_const {
                return Ok(()); // statically empty attribute: omitted
            }
            self.lits.push(b' ');
            self.lits.extend_from_slice(attr.name.as_str().as_bytes());
            self.lits.extend_from_slice(b"=\"");
            for node in attr.value.iter() {
                self.compile_literal_content_node(node, true)?;
            }
            self.lits.push(b'"');
            return Ok(());
        }

        if has_nonempty_const {
            // Attribute is always emitted; placeholders write inline.
            self.lits.push(b' ');
            self.lits.extend_from_slice(attr.name.as_str().as_bytes());
            self.lits.extend_from_slice(b"=\"");
            for node in attr.value.iter() {
                match node {
                    Node::Placeholder(ph) => {
                        self.flush_lit_run();
                        self.ops.push(XOp::Val {
                            slot: ph.id,
                            in_attr: true,
                        });
                    }
                    other => self.compile_literal_content_node(other, true)?,
                }
            }
            self.lits.push(b'"');
            return Ok(());
        }

        if n_placeholders > 1 {
            // Joint emptiness across several placeholders: not modeled.
            return Err(bail_err());
        }

        // Exactly one placeholder, no non-empty constants: conditional attr.
        // (Constant empty nodes contribute nothing in either branch.)
        let ph = attr
            .value
            .iter()
            .find_map(|n| match n {
                Node::Placeholder(ph) => Some(ph),
                _ => None,
            })
            .expect("counted placeholder");
        let name = attr.name.as_str().as_bytes();
        self.flush_lit_run();
        let pre = self.side_range(|c| {
            c.lits.push(b' ');
            c.lits.extend_from_slice(name);
            c.lits.extend_from_slice(b"=\"");
        });
        self.ops.push(XOp::AttrVal { slot: ph.id, pre });
        Ok(())
    }

    /// Compile an array-expansion site (`<Data>%n</Data>`, no attributes)
    /// into a self-contained `XOp::Expand`: the open tag lives in the op so
    /// the executor can repeat the whole element per array item.
    fn compile_expand(
        &mut self,
        element: &'t Element<'a>,
        ph: &Placeholder,
        indent: u16,
    ) -> Result<()> {
        let name = element.name.as_str().as_bytes();
        self.flush_lit_run();
        let open = self.side_range(|c| {
            c.indent_str(indent);
            c.lits.push(b'<');
            c.lits.extend_from_slice(name);
            c.lits.push(b'>');
        });
        let tail_text = self.side_range(|c| {
            c.lits.extend_from_slice(b"</");
            c.lits.extend_from_slice(name);
            c.lits.push(b'>');
            c.newline();
        });
        let tail_empty = self.side_range(|c| {
            c.newline();
            c.indent_str(indent);
            c.lits.extend_from_slice(b"</");
            c.lits.extend_from_slice(name);
            c.lits.push(b'>');
            c.newline();
        });
        let tail_elem = self.side_range(|c| {
            c.indent_str(indent);
            c.lits.extend_from_slice(b"</");
            c.lits.extend_from_slice(name);
            c.lits.push(b'>');
            c.newline();
        });
        self.elem_slots.push((ph.id, indent + INDENT_WIDTH));
        self.expand_slots.push(ph.id);
        self.ops.push(XOp::Expand {
            slot: ph.id,
            optional: ph.optional,
            indent,
            open,
            tail_text,
            tail_empty,
            tail_elem,
        });
        Ok(())
    }

    /// Render one literal (placeholder-free) node into `lits`, mirroring
    /// `XmlEmitter::render_single_node`.
    fn compile_literal_content_node(&mut self, node: &Node<'a>, in_attribute: bool) -> Result<()> {
        match node {
            Node::Text(text) => self.compile_literal_text(text, in_attribute),
            Node::Value(value) => {
                let mut sink = std::mem::take(&mut self.lits);
                let res = self.vr.write_xml_value_text(&mut sink, value, in_attribute);
                self.lits = sink;
                res
            }
            Node::EntityRef(name) => {
                self.lits.push(b'&');
                self.lits.extend_from_slice(name.as_str().as_bytes());
                self.lits.push(b';');
                Ok(())
            }
            Node::CharRef(ch) => {
                self.lits.extend_from_slice(format!("&#{};", ch).as_bytes());
                Ok(())
            }
            Node::CData(text) => {
                if in_attribute {
                    self.compile_literal_text(text, true)
                } else {
                    self.lits.extend_from_slice(b"<![CDATA[");
                    self.compile_raw_text(text);
                    self.lits.extend_from_slice(b"]]>");
                    Ok(())
                }
            }
            // PIs contribute nothing in content position (`render_single_node`).
            Node::PITarget(_) | Node::PIData(_) => Ok(()),
            Node::Element(_) => Err(crate::err::EvtxError::FailedToCreateRecordModel(
                "unexpected element node in text context",
            )),
            Node::Placeholder(_) => Err(unresolved_placeholder()),
        }
    }

    fn compile_literal_text(&mut self, text: &Text<'a>, in_attribute: bool) -> Result<()> {
        match text {
            Text::Utf16(value) => {
                let bytes = value.as_bytes();
                let units = bytes.len() / 2;
                if units == 0 {
                    return Ok(());
                }
                let mut sink = std::mem::take(&mut self.lits);
                let res = utf16_simd::write_xml_utf16le(&mut sink, bytes, units, in_attribute);
                self.lits = sink;
                res.map_err(crate::err::EvtxError::from)?;
                Ok(())
            }
            Text::Utf8(value) => {
                xml_escape_str_into(&mut self.lits, value, in_attribute);
                Ok(())
            }
        }
    }

    fn compile_raw_text(&mut self, text: &Text<'a>) {
        match text {
            Text::Utf16(value) => {
                let bytes = value.as_bytes();
                let units = bytes.len() / 2;
                if units > 0 {
                    let mut sink = std::mem::take(&mut self.lits);
                    let _ = utf16_simd::write_utf16le_raw(&mut sink, bytes, units);
                    self.lits = sink;
                }
            }
            Text::Utf8(value) => self.lits.extend_from_slice(value.as_bytes()),
        }
    }
}

/// Mirrors `XmlEmitter::write_escaped_str` for compile-time UTF-8 literals.
fn xml_escape_str_into(out: &mut Vec<u8>, text: &str, in_attribute: bool) {
    for ch in text.chars() {
        match ch {
            '&' => out.extend_from_slice(b"&amp;"),
            '<' => out.extend_from_slice(b"&lt;"),
            '>' => out.extend_from_slice(b"&gt;"),
            '"' if in_attribute => out.extend_from_slice(b"&quot;"),
            '\'' if in_attribute => out.extend_from_slice(b"&apos;"),
            _ => {
                let mut buf = [0_u8; 4];
                out.extend_from_slice(ch.encode_utf8(&mut buf).as_bytes());
            }
        }
    }
}

enum ChildrenKind<'n> {
    /// No children (or only statically-empty literals): logically empty.
    Empty,
    /// Exactly one placeholder child (the `<Data>%1</Data>` shape).
    SinglePlaceholder(&'n Placeholder),
    /// All literal, no element children, at least one non-empty content node.
    StaticInline,
    /// Statically line-formed: literal elements (>=1 when placeholders are
    /// present), placeholders, and literal nodes each on their own line.
    StaticLines,
    Bail,
}

fn classify_children<'n>(element: &'n Element<'_>) -> ChildrenKind<'n> {
    if element.children.is_empty() {
        return ChildrenKind::Empty;
    }
    if element.children.len() == 1
        && let Node::Placeholder(ph) = &element.children[0]
    {
        return ChildrenKind::SinglePlaceholder(ph);
    }
    let mut has_placeholder = false;
    let mut has_literal_element = false;
    let mut has_literal_content = false;
    for node in &element.children {
        match node {
            Node::Placeholder(_) => has_placeholder = true,
            Node::Element(_) => has_literal_element = true,
            // PIs are neither content nor element (scan_class: Empty); they
            // render inline (paired) or as bare lines depending on layout.
            Node::PITarget(_) | Node::PIData(_) => {}
            Node::Text(t) | Node::CData(t) => {
                if !t.is_empty() {
                    has_literal_content = true;
                }
            }
            Node::EntityRef(_) | Node::CharRef(_) => has_literal_content = true,
            Node::Value(v) => {
                if !crate::model::ir::is_optional_empty(v) {
                    has_literal_content = true;
                }
            }
        }
    }
    if !has_placeholder {
        if has_literal_element {
            return ChildrenKind::StaticLines;
        }
        // Present-but-empty literal children are NOT logically empty
        // (`child_layout` counts Empty-class nodes as `any`): inline form.
        return ChildrenKind::StaticInline;
    }
    // Placeholders mixed with other children: the layout must be statically
    // line-formed, which requires a literal element child. Literal content
    // would render inline if no element materializes -> runtime layout fork.
    if has_literal_element && !has_literal_content {
        return ChildrenKind::StaticLines;
    }
    ChildrenKind::Bail
}

fn subtree_has_placeholder(tree: &IrTree<'_>, element: &Element<'_>) -> bool {
    for attr in &element.attrs {
        if attr.value.iter().any(|n| matches!(n, Node::Placeholder(_))) {
            return true;
        }
    }
    for node in &element.children {
        match node {
            Node::Placeholder(_) => return true,
            Node::Element(id)
                if subtree_has_placeholder(tree, tree.arena().get(*id).expect("element id")) =>
            {
                return true;
            }
            _ => {}
        }
    }
    false
}

// ---------------------------------------------------------------------------
// Per-record pre-flight (raw instance scan)
// ---------------------------------------------------------------------------

/// One raw substitution slot: a typed window into the chunk data.
#[derive(Clone, Copy)]
struct RawSlot {
    off: u32,
    len: u16,
    ty: u8,
    /// Index into `Preflight::nested` for single-instance BinXml slots;
    /// `u16::MAX` otherwise.
    nested: u16,
    /// Type-discriminated side-table index: `Preflight::ansi` for ANSI
    /// strings, `Preflight::arrays` for string arrays.
    aux: u32,
}

const NO_NESTED: u16 = u16::MAX;
const NO_AUX: u32 = u32::MAX;

impl RawSlot {
    /// The value's byte window in the chunk data.
    fn bytes<'d>(&self, data: &'d [u8]) -> &'d [u8] {
        &data[self.off as usize..self.off as usize + usize::from(self.len)]
    }

    /// Index into `Preflight::nested` for resolved nested instances.
    fn nested_idx(&self) -> Option<usize> {
        (self.nested != NO_NESTED).then_some(usize::from(self.nested))
    }

    /// Index into `Preflight::ansi` for pre-decoded ANSI payloads.
    fn ansi_idx(&self) -> Option<usize> {
        (self.ty == value_ty::ANSI_STRING && self.aux != NO_AUX).then_some(self.aux as usize)
    }

    /// A non-empty embedded BinXML value (renders as an element).
    fn is_binxml_payload(&self) -> bool {
        self.ty == value_ty::BIN_XML && self.len > 0
    }
}

struct NestedInst<P> {
    prog: Arc<P>,
    slots: SlotRange,
}

/// Reusable per-chunk pre-flight scratch.
pub(crate) struct Preflight<P> {
    slots: Vec<RawSlot>,
    nested: Vec<NestedInst<P>>,
    ansi: Vec<String>,
    /// Per string-array slot: `(start, count)` into `array_items`.
    arrays: Vec<(u32, u32)>,
    /// Flat `(offset, byte len)` spans of string-array items (NUL-free).
    array_items: Vec<(u32, u16)>,
}

impl<P> Default for Preflight<P> {
    fn default() -> Self {
        Preflight {
            slots: Vec::new(),
            nested: Vec::new(),
            ansi: Vec::new(),
            arrays: Vec::new(),
            array_items: Vec::new(),
        }
    }
}

/// Substitution value-type wire bytes (MS-EVEN6 §2.2.4.1) interpreted by the
/// fast path. Anything outside this vocabulary routes to the materialize lane.
pub(crate) mod value_ty {
    pub(crate) const NULL: u8 = 0x00;
    pub(crate) const UTF16_STRING: u8 = 0x01;
    pub(crate) const ANSI_STRING: u8 = 0x02;
    pub(crate) const INT8: u8 = 0x03;
    pub(crate) const UINT8: u8 = 0x04;
    pub(crate) const INT16: u8 = 0x05;
    pub(crate) const UINT16: u8 = 0x06;
    pub(crate) const INT32: u8 = 0x07;
    pub(crate) const UINT32: u8 = 0x08;
    pub(crate) const INT64: u8 = 0x09;
    pub(crate) const UINT64: u8 = 0x0a;
    pub(crate) const REAL32: u8 = 0x0b;
    pub(crate) const REAL64: u8 = 0x0c;
    pub(crate) const BOOL: u8 = 0x0d;
    pub(crate) const BINARY: u8 = 0x0e;
    pub(crate) const GUID: u8 = 0x0f;
    pub(crate) const SIZE_T: u8 = 0x10;
    pub(crate) const FILETIME: u8 = 0x11;
    pub(crate) const SYSTIME: u8 = 0x12;
    pub(crate) const SID: u8 = 0x13;
    pub(crate) const HEX_INT32: u8 = 0x14;
    pub(crate) const HEX_INT64: u8 = 0x15;
    pub(crate) const BIN_XML: u8 = 0x21;
    /// UTF-16 string array (`0x01 | 0x80`): NUL-terminated strings packed
    /// back to back. The only array type observed in real logs.
    pub(crate) const STR_ARRAY: u8 = 0x81;
}

/// How the pre-flight validates a descriptor of a given type.
#[derive(Clone, Copy, PartialEq, Eq)]
enum TyClass {
    /// Arrays, exotics, unknowns: materialize lane.
    Reject,
    /// Exact wire width.
    Fixed(u8),
    /// Even-length UTF-16LE payload.
    Utf16,
    /// Any-length payload (NULL skips it, BINARY/BIN_XML slice it).
    Sized,
    /// ANSI string: any length, pre-decoded at pre-flight.
    Ansi,
    /// Pointer-width integer: 4 (32-bit) or 8 (64-bit) bytes.
    SizeT,
    /// `8 + 4 * sub_authority_count` bytes.
    Sid,
    /// UTF-16 string array: even-length payload of NUL-terminated strings;
    /// admitted only on slots the program compiled as expandable.
    StrArray,
}

/// The declarative wire-facts table the descriptor scan runs on.
const TY_CLASS: [TyClass; 256] = {
    use TyClass::*;
    use value_ty::*;
    let mut t = [Reject; 256];
    t[NULL as usize] = Sized;
    t[UTF16_STRING as usize] = Utf16;
    t[ANSI_STRING as usize] = Ansi;
    t[INT8 as usize] = Fixed(1);
    t[UINT8 as usize] = Fixed(1);
    t[INT16 as usize] = Fixed(2);
    t[UINT16 as usize] = Fixed(2);
    t[INT32 as usize] = Fixed(4);
    t[UINT32 as usize] = Fixed(4);
    t[INT64 as usize] = Fixed(8);
    t[UINT64 as usize] = Fixed(8);
    t[REAL32 as usize] = Fixed(4);
    t[REAL64 as usize] = Fixed(8);
    t[BOOL as usize] = Fixed(4); // a 4-byte i32 on the wire
    t[BINARY as usize] = Sized;
    t[GUID as usize] = Fixed(16);
    t[SIZE_T as usize] = SizeT;
    t[FILETIME as usize] = Fixed(8);
    t[SYSTIME as usize] = Fixed(16);
    t[SID as usize] = Sid;
    t[HEX_INT32 as usize] = Fixed(4);
    t[HEX_INT64 as usize] = Fixed(8);
    t[BIN_XML as usize] = Sized;
    t[STR_ARRAY as usize] = StrArray;
    t
};

/// Fast-lane bail depth for nested instances (deeper chains use the slow
/// lane, which is itself capped — see `ir::MAX_BINXML_NESTING`).
const MAX_FAST_LANE_NESTING: usize = 8;

/// Sanity cap on a template instance's substitution count (the wire could
/// claim up to `u32::MAX`; nothing legitimate comes close).
const MAX_SUBSTITUTIONS: usize = 4096;

/// `consumed` bytes of `stream` were parsed as a nested/record instance: the
/// remainder must be empty or start with EOF (the legacy trailer rule).
fn ends_stream(stream: &[u8], consumed: usize) -> bool {
    matches!(stream.get(consumed..), Some([]) | Some([token::EOF, ..]))
}

struct PreflightBail;

impl From<crate::err::DeserializationError> for PreflightBail {
    fn from(_: crate::err::DeserializationError) -> Self {
        PreflightBail
    }
}

impl From<crate::err::EvtxError> for PreflightBail {
    fn from(_: crate::err::EvtxError) -> Self {
        PreflightBail
    }
}

impl<P: StoredProgram> Preflight<P> {
    fn clear(&mut self) {
        self.slots.clear();
        self.nested.clear();
        self.ansi.clear();
        self.arrays.clear();
        self.array_items.clear();
    }

    /// Item spans of a string-array slot (validated by the pre-flight).
    fn str_array_items(&self, s: &RawSlot) -> &[(u32, u16)] {
        debug_assert_eq!(s.ty, value_ty::STR_ARRAY);
        let (start, count) = self.arrays[s.aux as usize];
        &self.array_items[start as usize..(start + count) as usize]
    }

    /// Emptiness of a slot, mirroring `is_optional_empty` over the value the
    /// regular path would have decoded (string NUL-truncation included).
    fn slot_empty(&self, s: &RawSlot, data: &[u8]) -> bool {
        match s.ty {
            value_ty::NULL => true,
            // The decoded string is empty when sized 0 or NUL-led (mirrors
            // `utf16_by_char_count` truncation).
            value_ty::UTF16_STRING => s.len == 0 || s.bytes(data).starts_with(&[0, 0]),
            value_ty::ANSI_STRING => s.ansi_idx().is_none_or(|i| self.ansi[i].is_empty()),
            value_ty::BINARY | value_ty::BIN_XML => s.len == 0,
            _ => false,
        }
    }

    /// Scan a `TemplateInstance` whose header starts at absolute `pos` (the
    /// byte after the 0x0c token). Appends slots/nested entries and returns
    /// `(program, slot_range, end_pos)`.
    #[allow(clippy::too_many_arguments)]
    fn scan_instance<'a>(
        &mut self,
        chunk: &'a EvtxChunk<'a>,
        pos: usize,
        depth: usize,
        cache: &mut IrTemplateCache<'a>,
        progs: &mut ProgramCache<P>,
        settings: &ParserSettings,
        base_indent: u16,
        is_root: bool,
    ) -> std::result::Result<(Arc<P>, SlotRange, usize), PreflightBail> {
        if depth > MAX_FAST_LANE_NESTING {
            return Err(PreflightBail);
        }
        let data = chunk.data;

        // Instance header (mirrors `read_template_values_cursor`).
        let mut cur = ByteCursor::with_pos(data, pos)?;
        cur.u8()?; // unknown byte
        let _template_id = cur.u32()?;
        let def_offset = cur.u32()?;
        if cur.position() as u32 == def_offset {
            // Inline definition: skip its header + payload.
            let header = read_template_definition_header_at(data, def_offset)?;
            cur.set_pos_u64(
                cur.position()
                    + (TEMPLATE_DEFINITION_HEADER_SIZE as u64)
                    + u64::from(header.data_size),
                "skip inline template definition",
            )?;
        }
        let n = cur.u32()? as usize;
        if n > MAX_SUBSTITUTIONS {
            return Err(PreflightBail);
        }

        let prog = get_or_compile(
            chunk,
            def_offset,
            base_indent,
            is_root,
            cache,
            progs,
            settings,
        )
        .ok_or(PreflightBail)?;

        // Descriptor table: n x (u16 size, u8 type, u8 pad), then the values.
        let descriptors = cur.take_bytes(n * 4, "descriptor table")?;
        let mut off = cur.pos();
        let slot_start = self.slots.len() as u32;
        for (i, desc) in descriptors.chunks_exact(4).enumerate() {
            let &[len_lo, len_hi, ty, _pad] = desc else {
                unreachable!("chunks_exact(4)");
            };
            let len = u16::from_le_bytes([len_lo, len_hi]);
            let end = off + usize::from(len);
            if end > data.len() {
                return Err(PreflightBail);
            }
            match TY_CLASS[usize::from(ty)] {
                TyClass::Reject => return Err(PreflightBail),
                TyClass::Fixed(width) => {
                    if len != u16::from(width) {
                        return Err(PreflightBail);
                    }
                }
                TyClass::Utf16 => {
                    if len % 2 != 0 {
                        return Err(PreflightBail);
                    }
                }
                TyClass::SizeT => {
                    if !(len == 4 || len == 8) {
                        return Err(PreflightBail);
                    }
                }
                TyClass::Sid => {
                    // SID payload: revision, sub-authority count, 48-bit
                    // authority, then 4-byte sub-authorities.
                    let &[_revision, sub_count, ..] = &data[off..end] else {
                        return Err(PreflightBail);
                    };
                    if usize::from(len) != 8 + 4 * usize::from(sub_count) {
                        return Err(PreflightBail);
                    }
                }
                TyClass::StrArray => {
                    // Admitted only on slots the program compiled as
                    // expandable; everything else keeps the slow lane.
                    if len % 2 != 0 || !prog.expand_slots().contains(&(i as u16)) {
                        return Err(PreflightBail);
                    }
                }
                TyClass::Sized | TyClass::Ansi => {}
            }
            let mut slot = RawSlot {
                off: off as u32,
                len,
                ty,
                nested: NO_NESTED,
                aux: NO_AUX,
            };
            if ty == value_ty::ANSI_STRING && len > 0 {
                // Decode ANSI now so the executor stays infallible. Mirrors
                // `deserialize_value_type_cursor_in` (NUL filter + strict).
                let raw = &data[off..end];
                let filtered: Vec<u8> = raw.iter().copied().filter(|&b| b != 0).collect();
                let decoded = settings
                    .get_ansi_codec()
                    .decode(&filtered, encoding::DecoderTrap::Strict)
                    .map_err(|_| PreflightBail)?;
                slot.aux = self.ansi.len() as u32;
                self.ansi.push(decoded);
            } else if ty == value_ty::STR_ARRAY {
                // Split the payload into NUL-terminated item spans now so the
                // executor stays infallible. Mirrors the deserializer: every
                // NUL ends an item; the payload must end exactly on one (an
                // unterminated tail keeps the legacy lane's read-past quirk).
                let items_start = self.array_items.len() as u32;
                let mut item_off = off;
                for (pi, pair) in data[off..end].chunks_exact(2).enumerate() {
                    if let &[0, 0] = pair {
                        let nul_at = off + pi * 2;
                        self.array_items
                            .push((item_off as u32, (nul_at - item_off) as u16));
                        item_off = nul_at + 2;
                    }
                }
                let count = self.array_items.len() as u32 - items_start;
                if item_off != end || count == 0 {
                    return Err(PreflightBail);
                }
                slot.aux = self.arrays.len() as u32;
                self.arrays.push((items_start, count));
            }
            self.slots.push(slot);
            off = end;
        }
        let slot_range = (slot_start, self.slots.len() as u32);

        // Resolve nested instances for slots this program renders as elements.
        for &(slot_id, child_indent) in prog.elem_slots() {
            if u32::from(slot_id) >= slot_range.1 - slot_range.0 {
                continue; // out-of-range -> Skip at exec
            }
            let idx = slot_start as usize + slot_id as usize;
            let s = self.slots[idx];
            if !s.is_binxml_payload() {
                continue;
            }
            let frag = s.bytes(data);
            let Some(inst_off) = single_instance_offset(frag) else {
                // Generic fragment: rendered via the materialized fallback
                // where the executor supports it; otherwise fall back.
                if P::ALLOW_GENERIC_FRAGS {
                    continue;
                }
                return Err(PreflightBail);
            };
            let (nprog, nslots, nend) = self.scan_instance(
                chunk,
                s.off as usize + inst_off,
                depth + 1,
                cache,
                progs,
                settings,
                child_indent,
                false,
            )?;
            // The nested instance must span its whole payload (allow EOF pad).
            if !ends_stream(frag, nend - s.off as usize) {
                return Err(PreflightBail);
            }
            if self.nested.len() >= usize::from(u16::MAX) {
                return Err(PreflightBail);
            }
            self.slots[idx].nested = self.nested.len() as u16;
            self.nested.push(NestedInst {
                prog: nprog,
                slots: nslots,
            });
        }

        // Per-slot constraints (kept rare; violations route to the fallback).
        for &c in prog.constraints() {
            let (slot_id, forbid_elem) = match c {
                SlotConstraint::ForbidElem(s) => (s, true),
                SlotConstraint::ElemOrEmpty(s) => (s, false),
            };
            if u32::from(slot_id) >= slot_range.1 - slot_range.0 {
                continue; // out-of-range resolves to Skip everywhere
            }
            let s = self.slots[slot_start as usize + slot_id as usize];
            let is_elem = s.is_binxml_payload();
            let empty = self.slot_empty(&s, data);
            if (forbid_elem && is_elem) || (!forbid_elem && !is_elem && !empty) {
                return Err(PreflightBail);
            }
        }

        Ok((prog, slot_range, off))
    }
}

fn get_or_compile<'a, P: StoredProgram>(
    chunk: &'a EvtxChunk<'a>,
    def_offset: u32,
    base_indent: u16,
    is_root: bool,
    cache: &mut IrTemplateCache<'a>,
    progs: &mut ProgramCache<P>,
    settings: &ParserSettings,
) -> Option<Arc<P>> {
    let key = (def_offset, base_indent, is_root);
    if let Some(entry) = progs.get(&key) {
        return entry.clone();
    }

    // Cross-chunk store, keyed by template content identity.
    let store = &*chunk.program_store;
    let store_key = template_content_key(chunk, def_offset, &store.hasher)
        .map(|(guid, size, hash)| (guid, size, hash, base_indent, is_root));
    // Lock sections are bare map reads/inserts (compilation happens outside),
    // so a poisoned lock cannot hold inconsistent data: recover and continue.
    if let Some(sk) = store_key.as_ref()
        && let Some(entry) = P::shard(store)
            .read()
            .unwrap_or_else(std::sync::PoisonError::into_inner)
            .get(sk)
    {
        progs.insert(key, entry.clone());
        return entry.clone();
    }

    let compiled =
        cache
            .template_for_compile(chunk, def_offset)
            .ok()
            .and_then(|(tree, has_literal_array)| {
                P::compile(&tree, has_literal_array, base_indent, is_root, settings).map(Arc::new)
            });
    if let Some(sk) = store_key {
        P::shard(store)
            .write()
            .unwrap_or_else(std::sync::PoisonError::into_inner)
            .insert(sk, compiled.clone());
    }
    progs.insert(key, compiled.clone());
    compiled
}

/// Template content identity at `def_offset`: (GUID, data size, bytes hash).
fn template_content_key(
    chunk: &EvtxChunk<'_>,
    def_offset: u32,
    hasher: &ahash::RandomState,
) -> Option<([u8; 16], u32, u64)> {
    let header = read_template_definition_header_at(chunk.data, def_offset).ok()?;
    let body_start = (def_offset as usize).checked_add(TEMPLATE_DEFINITION_HEADER_SIZE)?;
    let body = chunk
        .data
        .get(body_start..body_start.checked_add(header.data_size as usize)?)?;
    Some((header.guid, header.data_size, hasher.hash_one(body)))
}

// ---------------------------------------------------------------------------
// Per-record entry + executor
// ---------------------------------------------------------------------------

/// Try to render one record's BinXML via the compiled-template path.
///
/// Returns `false` with `out` untouched when the record isn't covered (the
/// caller then uses the regular path). On `true` the record was rendered
/// byte-identically to `render_xml_record_content`.
#[allow(clippy::too_many_arguments)]
pub(crate) fn try_render_xml_compiled<'a>(
    bytes: &[u8],
    chunk: &'a EvtxChunk<'a>,
    cache: &mut IrTemplateCache<'a>,
    progs: &mut XmlProgramCache,
    pf: &mut Preflight<XmlProgram>,
    settings: &ParserSettings,
    vr: &mut ValueRenderer,
    out: &mut Vec<u8>,
) -> bool {
    // Single-instance stream shape (mirrors `read_single_instance_stream`).
    let Some(inst_off) = single_instance_offset(bytes) else {
        return false;
    };
    let data_start = chunk.data.as_ptr() as usize;
    let slice_start = bytes.as_ptr() as usize;
    if slice_start < data_start || slice_start + bytes.len() > data_start + chunk.data.len() {
        return false;
    }
    let stream_offset = slice_start - data_start;

    pf.clear();
    let (prog, slot_range, end) = match pf.scan_instance(
        chunk,
        stream_offset + inst_off,
        0,
        cache,
        progs,
        settings,
        0,
        true,
    ) {
        Ok(v) => v,
        Err(PreflightBail) => return false,
    };

    // Anything after the instance other than EOF (0x00) is unhandled here.
    if !ends_stream(bytes, end - stream_offset) {
        return false;
    }

    let start = out.len();
    match exec(&prog, slot_range, pf, chunk, cache, vr, out) {
        Ok(()) => true,
        Err(_) => {
            // Unreachable post-preflight except for attribute-position BinXml
            // elements, which the regular path also rejects per record.
            out.truncate(start);
            false
        }
    }
}

/// Runtime slot class for `Body`/`ChildSlot` branching.
enum SlotClass {
    Skip,
    TextLike,
    Element,
}

fn exec<'a>(
    prog: &XmlProgram,
    slot_range: SlotRange,
    pf: &Preflight<XmlProgram>,
    chunk: &'a EvtxChunk<'a>,
    cache: &mut IrTemplateCache<'a>,
    vr: &mut ValueRenderer,
    out: &mut Vec<u8>,
) -> Result<()> {
    let lits = &prog.lits;
    let slot_at = |slot: u16| -> Option<RawSlot> {
        if u32::from(slot) < slot_range.1 - slot_range.0 {
            Some(pf.slots[slot_range.0 as usize + slot as usize])
        } else {
            None
        }
    };
    let classify = |slot: u16, optional: bool| -> SlotClass {
        match slot_at(slot) {
            None => SlotClass::Skip,
            Some(s) => {
                if pf.slot_empty(&s, chunk.data) {
                    if optional {
                        SlotClass::Skip
                    } else {
                        SlotClass::TextLike
                    }
                } else if s.is_binxml_payload() {
                    SlotClass::Element
                } else {
                    SlotClass::TextLike
                }
            }
        }
    };

    macro_rules! write_lit {
        ($r:expr) => {
            out.extend_from_slice($r.of(lits))
        };
    }
    macro_rules! write_val {
        ($s:expr, $in_attr:expr) => {{
            let s = $s;
            let vb = s.bytes(chunk.data);
            let ansi = s.ansi_idx().map(|i| pf.ansi[i].as_str());
            vr.write_raw_value_text(
                out,
                s.ty,
                vb,
                ansi,
                StringEscapeMode::Xml {
                    in_attribute: $in_attr,
                },
            )?;
        }};
    }

    for op in &prog.ops {
        match op {
            XOp::Lit(r) => write_lit!(*r),
            XOp::Val { slot, in_attr } => {
                if let Some(s) = slot_at(*slot) {
                    if s.is_binxml_payload() {
                        return Err(crate::err::EvtxError::FailedToCreateRecordModel(
                            "element node inside attribute value",
                        ));
                    }
                    write_val!(s, *in_attr);
                }
            }
            XOp::AttrVal { slot, pre } => {
                if let Some(s) = slot_at(*slot)
                    && !pf.slot_empty(&s, chunk.data)
                {
                    if s.is_binxml_payload() {
                        return Err(crate::err::EvtxError::FailedToCreateRecordModel(
                            "element node inside attribute value",
                        ));
                    }
                    write_lit!(*pre);
                    write_val!(s, true);
                    out.push(b'"');
                }
            }
            XOp::Body {
                slot,
                optional,
                indent,
                tail_text,
                tail_empty,
                tail_elem,
            } => {
                // The opening `<Tag ...>` (including `>`) came from the
                // preceding Lit run; only the content + close remain here.
                match classify(*slot, *optional) {
                    SlotClass::Skip => write_lit!(*tail_empty),
                    SlotClass::TextLike => {
                        if let Some(s) = slot_at(*slot) {
                            write_val!(s, false);
                        }
                        write_lit!(*tail_text);
                    }
                    SlotClass::Element => {
                        let s = slot_at(*slot).expect("element class implies present");
                        if prog.indent_on {
                            out.push(b'\n');
                        }
                        render_element_slot(
                            &s,
                            pf,
                            chunk,
                            cache,
                            vr,
                            *indent + INDENT_WIDTH,
                            prog.indent_on,
                            out,
                        )?;
                        write_lit!(*tail_elem);
                    }
                }
            }
            XOp::ChildSlot {
                slot,
                optional,
                indent,
                ind,
            } => match classify(*slot, *optional) {
                SlotClass::Skip => {}
                SlotClass::TextLike => {
                    write_lit!(*ind);
                    if let Some(s) = slot_at(*slot) {
                        write_val!(s, false);
                    }
                    if prog.indent_on {
                        out.push(b'\n');
                    }
                }
                SlotClass::Element => {
                    let s = slot_at(*slot).expect("element class implies present");
                    render_element_slot(&s, pf, chunk, cache, vr, *indent, prog.indent_on, out)?;
                }
            },
            XOp::Expand {
                slot,
                optional,
                indent,
                open,
                tail_text,
                tail_empty,
                tail_elem,
            } => {
                if let Some(s) = slot_at(*slot).filter(|s| s.ty == value_ty::STR_ARRAY) {
                    // Array: the element repeats per item. Single-item arrays
                    // are not expanded by the materialize lane (the value node
                    // stays inline, empty or not); empty items in larger
                    // arrays drop their text node (two-line empty form).
                    let items = pf.str_array_items(&s);
                    let multi = items.len() > 1;
                    for &(ioff, ilen) in items {
                        write_lit!(*open);
                        if multi && ilen == 0 {
                            write_lit!(*tail_empty);
                        } else {
                            vr.write_raw_value_text(
                                out,
                                value_ty::UTF16_STRING,
                                &chunk.data[ioff as usize..ioff as usize + usize::from(ilen)],
                                None,
                                StringEscapeMode::Xml {
                                    in_attribute: false,
                                },
                            )?;
                            write_lit!(*tail_text);
                        }
                    }
                } else {
                    // Scalar: `Body` semantics with the open tag spliced in.
                    write_lit!(*open);
                    match classify(*slot, *optional) {
                        SlotClass::Skip => write_lit!(*tail_empty),
                        SlotClass::TextLike => {
                            if let Some(s) = slot_at(*slot) {
                                write_val!(s, false);
                            }
                            write_lit!(*tail_text);
                        }
                        SlotClass::Element => {
                            let s = slot_at(*slot).expect("element class implies present");
                            if prog.indent_on {
                                out.push(b'\n');
                            }
                            render_element_slot(
                                &s,
                                pf,
                                chunk,
                                cache,
                                vr,
                                *indent + INDENT_WIDTH,
                                prog.indent_on,
                                out,
                            )?;
                            write_lit!(*tail_elem);
                        }
                    }
                }
            }
        }
    }
    Ok(())
}

/// Render an element-class slot: a nested compiled instance, or a generic
/// BinXml fragment via the materialized fallback renderer.
#[allow(clippy::too_many_arguments)]
fn render_element_slot<'a>(
    s: &RawSlot,
    pf: &Preflight<XmlProgram>,
    chunk: &'a EvtxChunk<'a>,
    cache: &mut IrTemplateCache<'a>,
    vr: &mut ValueRenderer,
    indent: u16,
    indent_on: bool,
    out: &mut Vec<u8>,
) -> Result<()> {
    if let Some(idx) = s.nested_idx() {
        let inst = &pf.nested[idx];
        return exec(&inst.prog, inst.slots, pf, chunk, cache, vr, out);
    }
    // Generic (non-instance) fragment: materialize and render. Cold path.
    let frag = s.bytes(chunk.data);
    let tree = build_tree_from_binxml_bytes_direct(frag, chunk, cache)?;
    render_subtree_xml(&tree, indent, indent_on, out)
}

// ---------------------------------------------------------------------------
// JSON programs
// ---------------------------------------------------------------------------

/// One attribute member inside a `JOp::Elem` `#attributes` object.
#[derive(Debug, Clone)]
enum JAttrPart {
    /// Pre-rendered `"name":value` member; always emitted.
    Literal(LitRange),
    /// Conditional member: `"name":` key bytes plus the value from `slot`,
    /// omitted when the slot is empty.
    Placeholder { key: LitRange, slot: u16 },
}

#[derive(Debug, Clone)]
enum JOp {
    /// Emit `lits[range]`.
    Lit(LitRange),
    /// A leaf element value: `null`/`""` when empty, bare number for
    /// int/bool-typed slots, nested-instance object for BinXml slots,
    /// quoted escaped string otherwise.
    LeafVal { slot: u16, empty: LitRange },
    /// `write_element_value` for an element with placeholder attributes and
    /// at most one placeholder content child (no element children possible).
    Elem {
        attrs: Box<[JAttrPart]>,
        content: Option<u16>,
        /// `null` / `""` for the all-empty case.
        empty: LitRange,
    },
    /// A placeholder in element-child position inside an object: emits
    /// `,"<NestedRootName>[_N]": { ... }` when the slot is a nested instance,
    /// nothing when empty. Pre-flight guarantees elem-or-empty.
    SlotChild {
        slot: u16,
        /// `(name bytes in lits, static emission count)` of preceding static
        /// members, for `_N` suffix seeding.
        static_names: Box<[(LitRange, u16)]>,
        /// Whether any object member unconditionally precedes this op.
        lead_comma: bool,
    },
}

/// A compiled JSON template program.
pub(crate) struct JsonProgram {
    lits: Vec<u8>,
    ops: Vec<JOp>,
    elem_slots: Vec<(u16, u16)>,
    constraints: Vec<SlotConstraint>,
    /// Slots whose `LeafVal` sits at a positional-`Data` aggregation site
    /// (string arrays allowed: they render as a JSON array `#text`).
    expand_slots: Vec<u16>,
    /// Raw root element name bytes (member key for nested-instance values).
    root_name: Vec<u8>,
}

impl TemplateProgram for JsonProgram {
    const ALLOW_GENERIC_FRAGS: bool = false;
    fn elem_slots(&self) -> &[(u16, u16)] {
        &self.elem_slots
    }
    fn constraints(&self) -> &[SlotConstraint] {
        &self.constraints
    }
    fn expand_slots(&self) -> &[u16] {
        &self.expand_slots
    }
    fn compile(
        tree: &IrTree<'_>,
        has_literal_array: bool,
        _base_indent: u16,
        is_root: bool,
        settings: &ParserSettings,
    ) -> Option<Self> {
        compile_json_template(tree, has_literal_array, is_root, settings)
    }
}

struct JsonCompiler<'t, 'a> {
    tree: Option<&'t IrTree<'a>>,
    lits: Vec<u8>,
    ops: Vec<JOp>,
    run_start: usize,
    elem_slots: Vec<(u16, u16)>,
    constraints: Vec<SlotConstraint>,
    expand_slots: Vec<u16>,
    vr: ValueRenderer,
    formatter: sonic_rs::format::CompactFormatter,
    /// `--separate-json-attributes` (slow lane only; such templates bail).
    separate: bool,
}

fn compile_json_template(
    tree: &IrTree<'_>,
    has_literal_array: bool,
    is_root: bool,
    settings: &ParserSettings,
) -> Option<JsonProgram> {
    if has_literal_array || settings.should_separate_json_attributes() {
        return None;
    }
    let root = tree.root_element();
    let root_container = is_data_container_name(root.name.as_str());
    let mut c = JsonCompiler {
        tree: Some(tree),
        lits: Vec::with_capacity(512),
        ops: Vec::with_capacity(32),
        run_start: 0,
        elem_slots: Vec::new(),
        constraints: Vec::new(),
        expand_slots: Vec::new(),
        vr: ValueRenderer::new(),
        formatter: sonic_rs::format::CompactFormatter,
        separate: false,
    };
    if is_root {
        c.lits.push(b'{');
        c.lits.push(b'"');
        c.lits.extend_from_slice(root.name.as_str().as_bytes());
        c.lits.extend_from_slice(b"\":");
    }
    match c.compile_element_value(tree.root(), root_container) {
        Ok(()) => {
            if is_root {
                c.lits.push(b'}');
            }
            c.flush_lit_run();
            Some(JsonProgram {
                lits: c.lits,
                ops: c.ops,
                elem_slots: c.elem_slots,
                constraints: c.constraints,
                expand_slots: c.expand_slots,
                root_name: root.name.as_str().as_bytes().to_vec(),
            })
        }
        Err(Bail) => None,
    }
}

fn is_data_container_name(name: &str) -> bool {
    name == "EventData" || name == "UserData"
}

fn is_data_element_name(name: &str) -> bool {
    name == "Data"
}

/// Compile-time emptiness of a literal (placeholder-free) node, mirroring
/// `scan_class` Content-detection for literals.
fn literal_nonempty(node: &Node<'_>) -> bool {
    match node {
        Node::Text(t) | Node::CData(t) => !t.is_empty(),
        Node::EntityRef(_) | Node::CharRef(_) => true,
        Node::Value(v) => !crate::model::ir::is_optional_empty(v),
        Node::Element(_) | Node::Placeholder(_) | Node::PITarget(_) | Node::PIData(_) => false,
    }
}

impl<'t, 'a> JsonCompiler<'t, 'a> {
    fn tree(&self) -> &'t IrTree<'a> {
        self.tree.expect("tree-bound walk")
    }

    fn flush_lit_run(&mut self) {
        let end = self.lits.len();
        if end > self.run_start {
            self.ops
                .push(JOp::Lit(LitRange(self.run_start as u32, end as u32)));
        }
        self.run_start = end;
    }

    fn side_range(&mut self, f: impl FnOnce(&mut Self)) -> LitRange {
        debug_assert_eq!(self.run_start, self.lits.len(), "unflushed lit run");
        let start = self.lits.len() as u32;
        f(self);
        self.run_start = self.lits.len();
        LitRange(start, self.lits.len() as u32)
    }

    /// `write_element_value` equivalent: emits the VALUE of `element` (the
    /// member key is the caller's responsibility).
    fn compile_element_value(
        &mut self,
        id: ElementId,
        container: bool,
    ) -> std::result::Result<(), Bail> {
        let element = self.element_ref(id);

        // Placeholder-free subtree: render via the materialized layer (the
        // same implementation the slow lane uses).
        if !subtree_has_placeholder(self.tree(), element) {
            return self
                .write_element_value_plain(element, container)
                .map_err(|_| Bail);
        }

        let ph_attrs = element
            .attrs
            .iter()
            .any(|a| a.value.iter().any(|n| matches!(n, Node::Placeholder(_))));
        let static_attr_text = element.attrs.iter().any(|a| {
            !a.value.iter().any(|n| matches!(n, Node::Placeholder(_)))
                && a.value.iter().any(literal_nonempty)
        });

        match classify_children(element) {
            ChildrenKind::SinglePlaceholder(ph) => {
                if !ph_attrs && !static_attr_text {
                    // Leaf shape: `null` when empty, primitive otherwise.
                    self.compile_leaf_val(ph.id, b"null", container)
                } else {
                    self.compile_elem_op(element, Some(ph.id))
                }
            }
            ChildrenKind::Empty => {
                if !ph_attrs {
                    // Statically resolvable: `null` or attrs-only object.
                    // (subtree_has_placeholder was true, so this can't happen.)
                    Err(Bail)
                } else {
                    self.compile_elem_op(element, None)
                }
            }
            ChildrenKind::StaticInline => Err(Bail), // literal text + ph attrs: rare
            ChildrenKind::StaticLines => self.compile_object_body(element, container, ph_attrs),
            ChildrenKind::Bail => Err(Bail),
        }
    }

    /// Leaf value op (single placeholder content, no attribute text).
    fn compile_leaf_val(
        &mut self,
        slot: u16,
        empty_form: &[u8],
        container: bool,
    ) -> std::result::Result<(), Bail> {
        // A Data-container leaf (`<UserData>%n</UserData>`) re-enters the
        // flattening rules through its nested root; keep it on the fallback.
        if container {
            return Err(Bail);
        }
        self.flush_lit_run();
        let empty = self.side_range(|c| c.lits.extend_from_slice(empty_form));
        self.elem_slots.push((slot, 0));
        self.ops.push(JOp::LeafVal { slot, empty });
        Ok(())
    }

    /// `JOp::Elem` for `<Tag attr=%a ...>%c?</Tag>` shapes.
    ///
    /// The caller decides leaf-vs-object form; literal attribute members are
    /// emitted unconditionally here, which is what makes static attribute
    /// text force the object form at run time.
    fn compile_elem_op(
        &mut self,
        element: &'t Element<'a>,
        content: Option<u16>,
    ) -> std::result::Result<(), Bail> {
        let mut parts: Vec<JAttrPart> = Vec::with_capacity(element.attrs.len());
        self.flush_lit_run();
        for attr in &element.attrs {
            let n_ph = attr
                .value
                .iter()
                .filter(|n| matches!(n, Node::Placeholder(_)))
                .count();
            match n_ph {
                0 => {
                    if !attr.value.iter().any(literal_nonempty) {
                        continue; // statically empty: never a member
                    }
                    // Pre-render `"name":value` via the materialized layer.
                    let start = self.lits.len() as u32;
                    self.lits.push(b'"');
                    self.lits.extend_from_slice(attr.name.as_str().as_bytes());
                    self.lits.extend_from_slice(b"\":");
                    let number = self
                        .try_as_number_plain(&attr.value, false)
                        .map_err(|_| Bail)?;
                    if !number {
                        self.lits.push(b'"');
                        self.text_content_plain(&attr.value, false)
                            .map_err(|_| Bail)?;
                        self.lits.push(b'"');
                    }
                    let lit_member = LitRange(start, self.lits.len() as u32);
                    self.run_start = self.lits.len();
                    parts.push(JAttrPart::Literal(lit_member));
                }
                1 if attr.value.len() == 1 => {
                    let Node::Placeholder(ph) = &attr.value[0] else {
                        return Err(Bail);
                    };
                    let name = attr.name.as_str().as_bytes();
                    let key = self.side_range(|c| {
                        c.lits.push(b'"');
                        c.lits.extend_from_slice(name);
                        c.lits.extend_from_slice(b"\":");
                    });
                    self.constraints.push(SlotConstraint::ForbidElem(ph.id));
                    parts.push(JAttrPart::Placeholder { key, slot: ph.id });
                }
                _ => return Err(Bail),
            }
        }
        if let Some(slot) = content {
            self.constraints.push(SlotConstraint::ForbidElem(slot));
        }
        let empty = self.side_range(|c| c.lits.extend_from_slice(b"null"));
        self.ops.push(JOp::Elem {
            attrs: parts.into_boxed_slice(),
            content,
            empty,
        });
        Ok(())
    }

    /// Static-layout object: literal element children (each a member), plus
    /// optional trailing placeholder children (`SlotChild`).
    fn compile_object_body(
        &mut self,
        element: &'t Element<'a>,
        container: bool,
        ph_attrs: bool,
    ) -> std::result::Result<(), Bail> {
        if ph_attrs {
            return Err(Bail); // object with placeholder attrs: fallback
        }
        self.lits.push(b'{');
        let mut wrote_any = false;

        // `#attributes` for literal attrs (static decision + static bytes).
        if !element.attrs.is_empty() && self.attrs_object_plain(&element.attrs).map_err(|_| Bail)? {
            wrote_any = true;
        }

        // Flattening / positional decisions are compile-time: literal `Data`
        // children only (placeholder `Data` shapes bail via classify above).
        let mut flatten_named = false;
        if container {
            for node in &element.children {
                if let Node::Element(id) = node {
                    let child = self.element_ref(*id);
                    if is_data_element_name(child.name.as_str())
                        && let Some(attr) = child.attrs.iter().find(|a| a.name.as_str() == "Name")
                    {
                        if attr.value.iter().any(|n| matches!(n, Node::Placeholder(_))) {
                            return Err(Bail); // dynamic Data names: fallback
                        }
                        if attr.value.iter().any(literal_nonempty) {
                            flatten_named = true;
                            break;
                        }
                    }
                }
            }
        }
        let positional_data: Vec<ElementId> = if container && !flatten_named {
            element
                .children
                .iter()
                .filter_map(|n| match n {
                    Node::Element(id)
                        if is_data_element_name(self.element_ref(*id).name.as_str()) =>
                    {
                        Some(*id)
                    }
                    _ => None,
                })
                .collect()
        } else {
            Vec::new()
        };
        let mut positional_emitted = false;

        // Compile-time `_N` suffix counting for static members.
        let mut static_names: Vec<(&[u8], u16)> = Vec::new();

        let mut seen_slot_child = false;
        for node in &element.children {
            match node {
                Node::Element(id) => {
                    if seen_slot_child {
                        return Err(Bail); // static member after dynamic: comma hazard
                    }
                    let child = self.element_ref(*id);
                    let cname = child.name.as_str();
                    if container && is_data_element_name(cname) {
                        if flatten_named {
                            let Some(attr) = child.attrs.iter().find(|a| a.name.as_str() == "Name")
                            else {
                                continue; // unnamed Data skipped in named form
                            };
                            if !attr.value.iter().any(literal_nonempty) {
                                continue; // empty literal name: skipped
                            }
                            if wrote_any {
                                self.lits.push(b',');
                            }
                            wrote_any = true;
                            // Key: JSON-escaped literal name text.
                            self.lits.push(b'"');
                            self.text_content_plain(&attr.value, false)
                                .map_err(|_| Bail)?;
                            self.lits.extend_from_slice(b"\":");
                            self.compile_data_value(*id, false)?;
                        } else if !positional_emitted && !positional_data.is_empty() {
                            positional_emitted = true;
                            if wrote_any {
                                self.lits.push(b',');
                            }
                            wrote_any = true;
                            self.lits.extend_from_slice(b"\"Data\":{\"#text\":");
                            if positional_data.len() == 1 {
                                // Sole positional Data: a string array here
                                // aggregates into a JSON array value, so the
                                // slot is expandable.
                                self.compile_data_value(positional_data[0], true)?;
                            } else {
                                self.lits.push(b'[');
                                for (i, did) in positional_data.iter().enumerate() {
                                    if i > 0 {
                                        self.lits.push(b',');
                                    }
                                    self.compile_data_value(*did, false)?;
                                }
                                self.lits.push(b']');
                            }
                            self.lits.push(b'}');
                        }
                        continue;
                    }
                    // Normal member.
                    if wrote_any {
                        self.lits.push(b',');
                    }
                    wrote_any = true;
                    let suffix = next_name_suffix(cname.as_bytes(), &mut static_names);
                    self.lits.push(b'"');
                    self.lits.extend_from_slice(cname.as_bytes());
                    if suffix > 0 {
                        self.lits.push(b'_');
                        self.lits.extend_from_slice(suffix.to_string().as_bytes());
                    }
                    self.lits.extend_from_slice(b"\":");
                    self.compile_element_value(*id, is_data_container_name(cname))?;
                }
                Node::Placeholder(ph) => {
                    // Dynamic member: nested-instance value (or absent).
                    self.flush_lit_run();
                    let name_ranges: Vec<(LitRange, u16)> = static_names
                        .iter()
                        .map(|(n, c)| {
                            let r = self.side_range(|cc| cc.lits.extend_from_slice(n));
                            (r, *c)
                        })
                        .collect();
                    self.constraints.push(SlotConstraint::ElemOrEmpty(ph.id));
                    self.elem_slots.push((ph.id, 0));
                    self.ops.push(JOp::SlotChild {
                        slot: ph.id,
                        static_names: name_ranges.into_boxed_slice(),
                        lead_comma: wrote_any,
                    });
                    seen_slot_child = true;
                }
                other => {
                    if literal_nonempty(other) {
                        return Err(Bail); // would force #text: fallback
                    }
                }
            }
        }
        self.lits.push(b'}');
        Ok(())
    }

    /// `render_data_element_value` for a literal `<Data ...>` child: leaf
    /// placeholder -> LeafVal with `""` empty form; literal-only -> rendered
    /// at compile time; anything else bails.
    fn compile_data_value(
        &mut self,
        id: ElementId,
        expandable: bool,
    ) -> std::result::Result<(), Bail> {
        let element = self.element_ref(id);
        if !subtree_has_placeholder(self.tree(), element) {
            return self.data_element_value_plain(element).map_err(|_| Bail);
        }
        if element.children.len() == 1
            && let Node::Placeholder(ph) = &element.children[0]
        {
            self.flush_lit_run();
            let empty = self.side_range(|c| c.lits.extend_from_slice(b"\"\""));
            self.elem_slots.push((ph.id, 0));
            if expandable {
                self.expand_slots.push(ph.id);
            }
            self.ops.push(JOp::LeafVal { slot: ph.id, empty });
            return Ok(());
        }
        Err(Bail)
    }
}

// ---------------------------------------------------------------------------
// JSON executor
// ---------------------------------------------------------------------------

/// Try to render one record's BinXML as JSON via the compiled-template path.
#[allow(clippy::too_many_arguments)]
pub(crate) fn try_render_json_compiled<'a>(
    bytes: &[u8],
    chunk: &'a EvtxChunk<'a>,
    cache: &mut IrTemplateCache<'a>,
    progs: &mut JsonProgramCache,
    pf: &mut Preflight<JsonProgram>,
    settings: &ParserSettings,
    vr: &mut ValueRenderer,
    out: &mut Vec<u8>,
) -> bool {
    // Single-instance stream shape (mirrors `read_single_instance_stream`).
    let Some(inst_off) = single_instance_offset(bytes) else {
        return false;
    };
    let data_start = chunk.data.as_ptr() as usize;
    let slice_start = bytes.as_ptr() as usize;
    if slice_start < data_start || slice_start + bytes.len() > data_start + chunk.data.len() {
        return false;
    }
    let stream_offset = slice_start - data_start;

    pf.clear();
    let (prog, slot_range, end) = match pf.scan_instance(
        chunk,
        stream_offset + inst_off,
        0,
        cache,
        progs,
        settings,
        0,
        true,
    ) {
        Ok(v) => v,
        Err(PreflightBail) => return false,
    };
    if !ends_stream(bytes, end - stream_offset) {
        return false;
    }

    let start = out.len();
    match exec_json(&prog, slot_range, pf, chunk, vr, out) {
        Ok(()) => true,
        Err(_) => {
            out.truncate(start);
            false
        }
    }
}

/// Whether `ty` renders as a bare JSON number/bool (`write_value_as_number`).
fn json_bare_type(ty: u8) -> bool {
    matches!(ty, value_ty::INT8..=value_ty::UINT64 | value_ty::BOOL)
}

fn exec_json(
    prog: &JsonProgram,
    slot_range: SlotRange,
    pf: &Preflight<JsonProgram>,
    chunk: &EvtxChunk<'_>,
    vr: &mut ValueRenderer,
    out: &mut Vec<u8>,
) -> Result<()> {
    let lits = &prog.lits;
    let slot_at = |slot: u16| -> Option<RawSlot> {
        if u32::from(slot) < slot_range.1 - slot_range.0 {
            Some(pf.slots[slot_range.0 as usize + slot as usize])
        } else {
            None
        }
    };

    macro_rules! write_lit {
        ($r:expr) => {
            out.extend_from_slice($r.of(lits))
        };
    }
    macro_rules! write_scalar {
        ($s:expr) => {{
            let s = $s;
            let vb = s.bytes(chunk.data);
            let ansi = s.ansi_idx().map(|i| pf.ansi[i].as_str());
            if json_bare_type(s.ty) {
                vr.write_raw_value_text(out, s.ty, vb, ansi, StringEscapeMode::Json)?;
            } else {
                out.push(b'"');
                vr.write_raw_value_text(out, s.ty, vb, ansi, StringEscapeMode::Json)?;
                out.push(b'"');
            }
        }};
    }

    for op in &prog.ops {
        match op {
            JOp::Lit(r) => write_lit!(*r),
            JOp::LeafVal { slot, empty } => match slot_at(*slot) {
                None => write_lit!(*empty),
                Some(s) if s.ty == value_ty::STR_ARRAY => {
                    // Positional-Data aggregation: one item renders bare
                    // (like an unexpanded scalar), more become a JSON array.
                    // Items are strings, so they are always quoted.
                    let items = pf.str_array_items(&s);
                    let multi = items.len() > 1;
                    if multi {
                        out.push(b'[');
                    }
                    for (i, &(ioff, ilen)) in items.iter().enumerate() {
                        if i > 0 {
                            out.push(b',');
                        }
                        out.push(b'"');
                        vr.write_raw_value_text(
                            out,
                            value_ty::UTF16_STRING,
                            &chunk.data[ioff as usize..ioff as usize + usize::from(ilen)],
                            None,
                            StringEscapeMode::Json,
                        )?;
                        out.push(b'"');
                    }
                    if multi {
                        out.push(b']');
                    }
                }
                Some(s) => {
                    if pf.slot_empty(&s, chunk.data) {
                        write_lit!(*empty);
                    } else if s.is_binxml_payload() {
                        let Some(idx) = s.nested_idx() else {
                            return Err(crate::err::EvtxError::FailedToCreateRecordModel(
                                "unresolved nested instance in compiled JSON",
                            ));
                        };
                        let inst = &pf.nested[idx];
                        out.push(b'{');
                        out.push(b'"');
                        out.extend_from_slice(&inst.prog.root_name);
                        out.extend_from_slice(b"\":");
                        exec_json(&inst.prog, inst.slots, pf, chunk, vr, out)?;
                        out.push(b'}');
                    } else {
                        write_scalar!(s);
                    }
                }
            },
            JOp::Elem {
                attrs,
                content,
                empty,
            } => {
                // Evaluate attribute member presence.
                let attr_present = attrs.iter().any(|part| match *part {
                    JAttrPart::Literal(_) => true,
                    JAttrPart::Placeholder { slot, .. } => {
                        slot_at(slot).is_some_and(|s| !pf.slot_empty(&s, chunk.data))
                    }
                });
                let content_slot =
                    content.and_then(|c| slot_at(c).filter(|s| !pf.slot_empty(s, chunk.data)));
                match (attr_present, content_slot) {
                    (false, None) => write_lit!(*empty),
                    (false, Some(s)) => write_scalar!(s),
                    (true, content_slot) => {
                        out.extend_from_slice(b"{\"#attributes\":{");
                        let mut first = true;
                        for part in attrs.iter() {
                            match *part {
                                JAttrPart::Literal(member) => {
                                    if !first {
                                        out.push(b',');
                                    }
                                    first = false;
                                    write_lit!(member);
                                }
                                JAttrPart::Placeholder { key, slot } => {
                                    if let Some(s) = slot_at(slot)
                                        && !pf.slot_empty(&s, chunk.data)
                                    {
                                        if !first {
                                            out.push(b',');
                                        }
                                        first = false;
                                        write_lit!(key);
                                        write_scalar!(s);
                                    }
                                }
                            }
                        }
                        out.push(b'}');
                        if let Some(s) = content_slot {
                            out.extend_from_slice(b",\"#text\":");
                            write_scalar!(s);
                        }
                        out.push(b'}');
                    }
                }
            }
            JOp::SlotChild {
                slot,
                static_names,
                lead_comma,
            } => {
                let Some(s) = slot_at(*slot) else { continue };
                if pf.slot_empty(&s, chunk.data) || !s.is_binxml_payload() {
                    continue; // constraint guarantees elem-or-empty
                }
                let Some(idx) = s.nested_idx() else {
                    return Err(crate::err::EvtxError::FailedToCreateRecordModel(
                        "unresolved nested instance in compiled JSON",
                    ));
                };
                let inst = &pf.nested[idx];
                let name = inst.prog.root_name.as_slice();
                // `_N` suffix: static members first, then prior dynamics.
                let mut count: u16 = 0;
                for (r, c) in static_names.iter() {
                    if &lits[r.0 as usize..r.1 as usize] == name {
                        count = *c;
                        break;
                    }
                }
                // (Prior dynamic same-name members would need scratch state;
                // a second dynamic member with a colliding name is not
                // expressible in compiled shapes today: one SlotChild per
                // object is enforced at compile time via `seen_slot_child`.)
                if *lead_comma {
                    out.push(b',');
                }
                out.push(b'"');
                out.extend_from_slice(name);
                if count > 0 {
                    out.push(b'_');
                    out.extend_from_slice(count.to_string().as_bytes());
                }
                out.extend_from_slice(b"\":");
                exec_json(&inst.prog, inst.slots, pf, chunk, vr, out)?;
            }
        }
    }
    Ok(())
}

/// Benchmark-only entry to the JSON text-content path.
#[cfg(feature = "bench")]
pub(crate) fn bench_json_text_content(out: &mut Vec<u8>, nodes: &[Node<'_>]) -> Result<()> {
    let mut c = JsonCompiler {
        tree: None,
        lits: std::mem::take(out),
        ops: Vec::new(),
        run_start: 0,
        elem_slots: Vec::new(),
        constraints: Vec::new(),
        expand_slots: Vec::new(),
        vr: ValueRenderer::new(),
        formatter: sonic_rs::format::CompactFormatter,
        separate: false,
    };
    let res = c.text_content_plain(nodes, false);
    *out = c.lits;
    res
}

// ---------------------------------------------------------------------------
// JSON materialized layer (the old JsonEmitter semantics over plain nodes).
//
// This layer is the sole behavioral source of truth for JSON text: both the
// slow lane (render_tree_json) and the compiler's pre-rendering of literal
// content go through these `*_plain` methods, so the two lanes cannot drift.
// ---------------------------------------------------------------------------
//
// These methods are the single implementation of JSON record rendering: the
// slow lane walks fully materialized trees through them, and the compiler
// calls them for placeholder-free pieces (subtrees, literal attributes,
// literal `Data` elements). Placeholder nodes are real errors here, mirroring
// the legacy emitter's behavior on materialized trees.

/// Render a fully materialized record tree to JSON (the single-walker slow
/// lane), honoring `--separate-json-attributes`.
pub(crate) fn render_tree_json(
    tree: &IrTree<'_>,
    settings: &ParserSettings,
    out: &mut Vec<u8>,
) -> Result<()> {
    let mut c = JsonCompiler {
        tree: Some(tree),
        lits: std::mem::take(out),
        ops: Vec::new(),
        run_start: 0,
        elem_slots: Vec::new(),
        constraints: Vec::new(),
        expand_slots: Vec::new(),
        vr: ValueRenderer::new(),
        formatter: sonic_rs::format::CompactFormatter,
        separate: settings.should_separate_json_attributes(),
    };
    let res = c.render_root_plain();
    debug_assert!(c.ops.is_empty(), "materialized walk produced ops");
    *out = c.lits;
    res
}

impl<'t, 'a> JsonCompiler<'t, 'a> {
    /// Mirrors `render_json_with_scope` for a materialized tree.
    fn render_root_plain(&mut self) -> Result<()> {
        let root = self.tree().root_element();
        self.lits.push(b'{');
        if self.separate {
            if !root.attrs.is_empty() && self.render_separate_attrs_plain(root, 0)? {
                self.lits.push(b',');
            }
            self.key_with_suffix_plain(root.name.as_str(), 0);
            self.write_element_value_no_attrs_plain(root, false)?;
        } else {
            self.lits.push(b'"');
            self.lits.extend_from_slice(root.name.as_str().as_bytes());
            self.lits.extend_from_slice(b"\":");
            self.write_element_value_plain(root, false)?;
        }
        self.lits.push(b'}');
        Ok(())
    }

    fn element_ref(&self, id: ElementId) -> &'t Element<'a> {
        self.tree().arena().get(id).expect("invalid element id")
    }

    // --- small writers ---

    fn key_with_suffix_plain(&mut self, name: &str, suffix: u16) {
        self.lits.push(b'"');
        self.lits.extend_from_slice(name.as_bytes());
        if suffix > 0 {
            self.lits.push(b'_');
            self.lits.extend_from_slice(suffix.to_string().as_bytes());
        }
        self.lits.extend_from_slice(b"\":");
    }

    fn json_escaped_str_plain(&mut self, s: &str) -> Result<()> {
        use sonic_rs::format::Formatter;
        self.formatter
            .write_string_fast(&mut self.lits, s, false)
            .map_err(crate::err::EvtxError::from)?;
        Ok(())
    }

    fn json_text_plain(&mut self, text: &Text<'_>) -> Result<()> {
        if text.is_empty() {
            return Ok(());
        }
        match text {
            Text::Utf16(value) => {
                let bytes = value.as_bytes();
                let units = bytes.len() / 2;
                if units > 0 {
                    utf16_simd::write_json_utf16le(&mut self.lits, bytes, units, false)
                        .map_err(crate::err::EvtxError::from)?;
                }
                Ok(())
            }
            Text::Utf8(value) => self.json_escaped_str_plain(value),
        }
    }

    fn write_u64_plain(&mut self, v: u64) -> Result<()> {
        use sonic_rs::format::Formatter;
        self.formatter
            .write_u64(&mut self.lits, v)
            .map_err(crate::err::EvtxError::from)?;
        Ok(())
    }

    fn write_i64_plain(&mut self, v: i64) -> Result<()> {
        use sonic_rs::format::Formatter;
        self.formatter
            .write_i64(&mut self.lits, v)
            .map_err(crate::err::EvtxError::from)?;
        Ok(())
    }

    /// Mirrors `write_value_as_number`.
    fn value_as_number_plain(
        &mut self,
        value: &crate::binxml::value_variant::BinXmlValue<'_>,
    ) -> Result<bool> {
        use crate::binxml::value_variant::BinXmlValue;
        match value {
            BinXmlValue::Int8Type(v) => self.write_i64_plain(i64::from(*v)).map(|_| true),
            BinXmlValue::Int16Type(v) => self.write_i64_plain(i64::from(*v)).map(|_| true),
            BinXmlValue::Int32Type(v) => self.write_i64_plain(i64::from(*v)).map(|_| true),
            BinXmlValue::Int64Type(v) => self.write_i64_plain(*v).map(|_| true),
            BinXmlValue::UInt8Type(v) => self.write_u64_plain(u64::from(*v)).map(|_| true),
            BinXmlValue::UInt16Type(v) => self.write_u64_plain(u64::from(*v)).map(|_| true),
            BinXmlValue::UInt32Type(v) => self.write_u64_plain(u64::from(*v)).map(|_| true),
            BinXmlValue::UInt64Type(v) => self.write_u64_plain(*v).map(|_| true),
            BinXmlValue::BoolType(v) => {
                self.lits
                    .extend_from_slice(if *v { b"true" } else { b"false" });
                Ok(true)
            }
            _ => Ok(false),
        }
    }

    // --- content scans (scan_class over plain nodes, ctx-None semantics) ---

    /// Mirrors `scan_class` with a materialized scope: is this node non-empty
    /// "text-like" content?
    fn node_is_content_plain(node: &Node<'_>) -> bool {
        match node {
            Node::Text(t) | Node::CData(t) => !t.is_empty(),
            Node::EntityRef(_) | Node::CharRef(_) => true,
            Node::Value(v) => !crate::model::ir::is_optional_empty(v),
            // Materialized trees should not contain placeholders; classify as
            // content so the emitting pass reports the error.
            Node::Placeholder(_) => true,
            Node::Element(_) | Node::PITarget(_) | Node::PIData(_) => false,
        }
    }

    fn has_text_content_plain(nodes: &[Node<'_>]) -> bool {
        nodes.iter().any(Self::node_is_content_plain)
    }

    /// Mirrors `content_layout`: `(has_text, has_element_child)`.
    fn content_layout_plain(element: &Element<'_>) -> (bool, bool) {
        let mut has_text = false;
        let mut has_element_child = element.has_element_child;
        for node in &element.children {
            if matches!(node, Node::Element(_)) {
                has_element_child = true;
            } else if Self::node_is_content_plain(node) {
                has_text = true;
            }
            if has_text && has_element_child {
                break;
            }
        }
        (has_text, has_element_child)
    }

    /// Mirrors `attr_flags`: `(has_any, has_any_non_empty_value)`.
    fn attr_flags_plain(attrs: &[Attr<'_>]) -> (bool, bool) {
        if attrs.is_empty() {
            return (false, false);
        }
        for attr in attrs {
            if Self::has_text_content_plain(&attr.value) {
                return (true, true);
            }
        }
        (true, false)
    }

    // --- text/value content rendering (mirrors write_json_text_content etc.) ---

    /// Mirrors `write_json_text_content` (no surrounding quotes).
    fn text_content_plain(&mut self, nodes: &[Node<'a>], skip_elements: bool) -> Result<()> {
        for node in nodes {
            match node {
                Node::Text(text) | Node::CData(text) => self.json_text_plain(text)?,
                Node::Value(value) => {
                    let mut sink = std::mem::take(&mut self.lits);
                    let res = self.vr.write_json_value_text(&mut sink, value);
                    self.lits = sink;
                    res?;
                }
                Node::CharRef(ch) => {
                    // In JSON, emit the resolved character (not `&#...;`).
                    if let Some(ch) = char::from_u32(u32::from(*ch)) {
                        let mut buf = [0_u8; 4];
                        let s = ch.encode_utf8(&mut buf);
                        self.json_escaped_str_plain(s)?;
                    } else {
                        self.lits.extend_from_slice(b"&#");
                        self.write_u64_plain(u64::from(*ch))?;
                        self.lits.push(b';');
                    }
                }
                Node::EntityRef(name) => {
                    let resolved = match name.as_str() {
                        "quot" => Some("\""),
                        "apos" => Some("'"),
                        "amp" => Some("&"),
                        "lt" => Some("<"),
                        "gt" => Some(">"),
                        _ => None,
                    };
                    match resolved {
                        Some(s) => self.json_escaped_str_plain(s)?,
                        None => {
                            self.lits.push(b'&');
                            self.lits.extend_from_slice(name.as_str().as_bytes());
                            self.lits.push(b';');
                        }
                    }
                }
                Node::PITarget(_) | Node::PIData(_) => {}
                Node::Placeholder(_) => return Err(unresolved_placeholder()),
                Node::Element(_) => {
                    if skip_elements {
                        continue;
                    }
                    return Err(crate::err::EvtxError::FailedToCreateRecordModel(
                        "unexpected element node in text context",
                    ));
                }
            }
        }
        Ok(())
    }

    /// Mirrors `try_write_as_number` / `try_write_as_number_skip_elements`.
    fn try_as_number_plain(&mut self, nodes: &[Node<'a>], skip_elements: bool) -> Result<bool> {
        let mut single: Option<&Node<'a>> = None;
        for node in nodes {
            match node {
                Node::Element(_) => {
                    if skip_elements {
                        continue;
                    }
                    return Ok(false);
                }
                Node::Text(t) | Node::CData(t) => {
                    if skip_elements {
                        if !t.is_empty() {
                            return Ok(false);
                        }
                    } else if single.is_some() || !t.is_empty() {
                        return Ok(false);
                    } else {
                        // Non-skip mode counts every node; an empty text node
                        // still occupies the single slot.
                        single = Some(node);
                    }
                }
                Node::Value(v) => {
                    if skip_elements && crate::model::ir::is_optional_empty(v) {
                        continue;
                    }
                    if single.is_some() {
                        return Ok(false);
                    }
                    single = Some(node);
                }
                Node::CharRef(_) | Node::EntityRef(_) => return Ok(false),
                Node::PITarget(_) | Node::PIData(_) => {
                    if !skip_elements && single.is_some() {
                        return Ok(false);
                    }
                    if !skip_elements {
                        single = Some(node);
                    }
                }
                Node::Placeholder(_) => {
                    if skip_elements {
                        return Err(unresolved_placeholder());
                    }
                    return Ok(false);
                }
            }
        }
        match single {
            Some(Node::Value(value)) => self.value_as_number_plain(value),
            _ => Ok(false),
        }
    }

    /// Mirrors `render_content_as_json_value`.
    fn content_as_json_value_plain(
        &mut self,
        nodes: &[Node<'a>],
        skip_elements: bool,
    ) -> Result<()> {
        if self.try_as_number_plain(nodes, skip_elements)? {
            return Ok(());
        }
        self.lits.push(b'"');
        self.text_content_plain(nodes, skip_elements)?;
        self.lits.push(b'"');
        Ok(())
    }

    // --- attributes ---

    /// Mirrors `render_attributes_object_body`.
    fn attrs_object_body_plain(&mut self, attrs: &[Attr<'a>]) -> Result<bool> {
        let mut wrote_any = false;
        let mut first = true;
        for attr in attrs {
            if !Self::has_text_content_plain(&attr.value) {
                continue;
            }
            if !first {
                self.lits.push(b',');
            }
            first = false;
            wrote_any = true;
            self.lits.push(b'"');
            self.lits.extend_from_slice(attr.name.as_str().as_bytes());
            self.lits.extend_from_slice(b"\":");
            if self.try_as_number_plain(&attr.value, false)? {
                continue;
            }
            self.lits.push(b'"');
            self.text_content_plain(&attr.value, false)?;
            self.lits.push(b'"');
        }
        Ok(wrote_any)
    }

    /// Mirrors `render_attributes_object`.
    fn attrs_object_plain(&mut self, attrs: &[Attr<'a>]) -> Result<bool> {
        let (_has_any, has_text) = Self::attr_flags_plain(attrs);
        if !has_text {
            return Ok(false);
        }
        self.lits.extend_from_slice(b"\"#attributes\":{");
        let wrote_any = self.attrs_object_body_plain(attrs)?;
        self.lits.push(b'}');
        Ok(wrote_any)
    }

    /// Mirrors `render_separate_attributes_for_element`.
    fn render_separate_attrs_plain(&mut self, element: &Element<'a>, suffix: u16) -> Result<bool> {
        if element.attrs.is_empty() {
            return Ok(false);
        }
        let (_has_any, has_text) = Self::attr_flags_plain(&element.attrs);
        if !has_text {
            return Ok(false);
        }
        self.lits.push(b'"');
        self.lits
            .extend_from_slice(element.name.as_str().as_bytes());
        if suffix > 0 {
            self.lits.push(b'_');
            self.write_u64_plain(u64::from(suffix))?;
        }
        self.lits.extend_from_slice(b"_attributes\":{");
        let wrote_any = self.attrs_object_body_plain(&element.attrs)?;
        self.lits.push(b'}');
        Ok(wrote_any)
    }

    // --- element values ---

    /// Mirrors `try_write_leaf_value`.
    fn try_leaf_value_plain(
        &mut self,
        element: &Element<'a>,
        empty_as_string: bool,
    ) -> Result<bool> {
        if element.has_element_child || element.children.len() != 1 {
            return Ok(false);
        }
        let empty: &[u8] = if empty_as_string { b"\"\"" } else { b"null" };
        match &element.children[0] {
            Node::Text(text) => {
                if text.is_empty() {
                    self.lits.extend_from_slice(empty);
                } else {
                    self.lits.push(b'"');
                    self.json_text_plain(text)?;
                    self.lits.push(b'"');
                }
                Ok(true)
            }
            Node::Value(value) => {
                if crate::model::ir::is_optional_empty(value) {
                    self.lits.extend_from_slice(empty);
                    return Ok(true);
                }
                if self.value_as_number_plain(value)? {
                    return Ok(true);
                }
                self.lits.push(b'"');
                let mut sink = std::mem::take(&mut self.lits);
                let res = self.vr.write_json_value_text(&mut sink, value);
                self.lits = sink;
                res?;
                self.lits.push(b'"');
                Ok(true)
            }
            _ => Ok(false),
        }
    }

    /// Mirrors `render_data_element_value` (`""` for the empty case).
    fn data_element_value_plain(&mut self, element: &Element<'a>) -> Result<()> {
        if self.try_leaf_value_plain(element, true)? {
            return Ok(());
        }
        let (has_text, has_element_child) = Self::content_layout_plain(element);
        if !has_text && !has_element_child {
            self.lits.extend_from_slice(b"\"\"");
            return Ok(());
        }
        if has_element_child {
            self.element_body_plain(element, false, true, has_text)
        } else {
            self.content_as_json_value_plain(&element.children, false)
        }
    }

    /// Mirrors `write_element_value_no_attrs` (separate-attrs mode).
    fn write_element_value_no_attrs_plain(
        &mut self,
        element: &Element<'a>,
        child_is_container: bool,
    ) -> Result<()> {
        if self.try_leaf_value_plain(element, false)? {
            return Ok(());
        }
        let (has_text, has_element_child) = Self::content_layout_plain(element);
        if !has_element_child && !has_text {
            self.lits.extend_from_slice(b"null");
            Ok(())
        } else if !has_element_child {
            self.content_as_json_value_plain(&element.children, false)
        } else {
            self.element_body_plain(element, child_is_container, true, has_text)
        }
    }

    /// Mirrors `write_element_value` (default mode).
    fn write_element_value_plain(
        &mut self,
        element: &Element<'a>,
        child_is_container: bool,
    ) -> Result<()> {
        if element.attrs.is_empty() && self.try_leaf_value_plain(element, false)? {
            return Ok(());
        }
        let (has_text, has_element_child) = Self::content_layout_plain(element);
        let (_has_attrs_any, has_attrs_text) = Self::attr_flags_plain(&element.attrs);

        if !has_element_child && !has_text && !has_attrs_text {
            self.lits.extend_from_slice(b"null");
            Ok(())
        } else if !has_element_child && !has_attrs_text {
            self.content_as_json_value_plain(&element.children, false)
        } else {
            self.element_body_plain(element, child_is_container, false, has_text)
        }
    }

    /// Mirrors `write_element_body_json` (materialized: no array expansion).
    fn element_body_plain(
        &mut self,
        element: &Element<'a>,
        in_data_container: bool,
        omit_attributes: bool,
        has_text: bool,
    ) -> Result<()> {
        // Flatten detection: one non-empty `Data[@Name]` selects named form.
        let mut should_flatten_named_data = false;
        if in_data_container {
            for node in &element.children {
                let Node::Element(id) = node else { continue };
                let child = self.element_ref(*id);
                if !is_data_element_name(child.name.as_str()) {
                    continue;
                }
                let Some(name_nodes) = child
                    .attrs
                    .iter()
                    .find(|a| a.name.as_str() == "Name")
                    .map(|a| &a.value)
                else {
                    continue;
                };
                if Self::has_text_content_plain(name_nodes) {
                    should_flatten_named_data = true;
                    break;
                }
            }
        }

        let mut name_counts: Vec<(&'t str, u16)> = Vec::new();

        self.lits.push(b'{');
        let mut wrote_any = false;

        if !omit_attributes
            && !element.attrs.is_empty()
            && self.attrs_object_plain(&element.attrs)?
        {
            wrote_any = true;
        }

        if has_text {
            if wrote_any {
                self.lits.push(b',');
            }
            wrote_any = true;
            self.lits.extend_from_slice(b"\"#text\":");
            self.content_as_json_value_plain(&element.children, true)?;
        }

        let positional_data_count = if in_data_container && !should_flatten_named_data {
            element
                .children
                .iter()
                .filter(|n| {
                    matches!(n, Node::Element(id)
                        if is_data_element_name(self.element_ref(*id).name.as_str()))
                })
                .count()
        } else {
            0
        };
        let mut positional_data_emitted = false;

        for node in &element.children {
            let Node::Element(id) = node else { continue };
            let child = self.element_ref(*id);

            if in_data_container && is_data_element_name(child.name.as_str()) {
                if should_flatten_named_data {
                    let Some(name_nodes) = child
                        .attrs
                        .iter()
                        .find(|a| a.name.as_str() == "Name")
                        .map(|a| &a.value)
                    else {
                        continue;
                    };
                    if !Self::has_text_content_plain(name_nodes) {
                        continue;
                    }
                    if wrote_any {
                        self.lits.push(b',');
                    }
                    wrote_any = true;
                    self.lits.push(b'"');
                    self.text_content_plain(name_nodes, false)?;
                    self.lits.extend_from_slice(b"\":");
                    self.data_element_value_plain(child)?;
                } else if !positional_data_emitted && positional_data_count > 0 {
                    if wrote_any {
                        self.lits.push(b',');
                    }
                    wrote_any = true;
                    positional_data_emitted = true;
                    self.lits.extend_from_slice(b"\"Data\":{\"#text\":");
                    if positional_data_count == 1 {
                        self.data_element_value_plain(child)?;
                    } else {
                        self.lits.push(b'[');
                        let mut first = true;
                        for node2 in &element.children {
                            let Node::Element(id2) = node2 else { continue };
                            let candidate = self.element_ref(*id2);
                            if !is_data_element_name(candidate.name.as_str()) {
                                continue;
                            }
                            if !first {
                                self.lits.push(b',');
                            }
                            first = false;
                            self.data_element_value_plain(candidate)?;
                        }
                        self.lits.push(b']');
                    }
                    self.lits.push(b'}');
                }
                continue;
            }

            // Normal child member with `_N` suffixing.
            let cname = child.name.as_str();
            let suffix = next_name_suffix(cname, &mut name_counts);

            if wrote_any {
                self.lits.push(b',');
            }
            wrote_any = true;

            let child_is_container = is_data_container_name(cname);
            if self.separate {
                let wrote_attrs = self.render_separate_attrs_plain(child, suffix)?;
                let (child_text, child_elem) = Self::content_layout_plain(child);
                let child_has_value = child_elem || child_text;
                let write_value = child_has_value || !wrote_attrs;
                if wrote_attrs && write_value {
                    self.lits.push(b',');
                }
                if write_value {
                    self.key_with_suffix_plain(cname, suffix);
                    self.write_element_value_no_attrs_plain(child, child_is_container)?;
                }
            } else {
                self.key_with_suffix_plain(cname, suffix);
                self.write_element_value_plain(child, child_is_container)?;
            }
        }

        self.lits.push(b'}');
        Ok(())
    }
}