rapidproto-build 0.1.0-alpha.2

Generates RapidProto's Rust decoders for Protobuf schemas in a build script, without protoc.
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
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
// SPDX-License-Identifier: Apache-2.0
// Copyright 2026 Christian Vetter

#include "rapidproto/rustgen/generator.hpp"

#include <algorithm>
#include <cstddef>
#include <cstdint>
#include <map>
#include <string>
#include <string_view>
#include <unordered_map>
#include <unordered_set>
#include <utility>
#include <vector>

#include "rapidproto/arenagen/layout.hpp"  // LayoutSet / MessageLayout / MemberPlan / FieldKind
#include "rapidproto/arenagen/modes.hpp"  // FieldMode / FieldModes (the shared field-modes resolver)
#include "rapidproto/ast.hpp"
#include "rapidproto/codegen/emit.hpp"  // holds_enum
#include "rapidproto/codegen/printer.hpp"
#include "rapidproto/rustgen/names.hpp"

namespace rapidproto::rustgen {
namespace {

using codegen::Printer;

// Split a dotted proto name ("a.b.c") into its components ("" -> none).
std::vector<std::string> dotted_components(std::string_view name) {
    std::vector<std::string> out;
    std::size_t start = 0;
    while (start <= name.size()) {
        const std::size_t dot = name.find('.', start);
        const std::size_t end = dot == std::string_view::npos ? name.size() : dot;
        if (end > start) {
            out.emplace_back(name.substr(start, end - start));
        }
        if (dot == std::string_view::npos) {
            break;
        }
        start = dot + 1;
    }
    return out;
}

// Pointers to a vector's elements, so one module scope can gather members from several files (same-
// package imports) without copying. Nested recursion addrs() a single node's child vector.
template <class T>
std::vector<const T*> addrs(const std::vector<T>& items) {
    std::vector<const T*> out;
    out.reserve(items.size());
    for (const T& item : items) {
        out.push_back(&item);
    }
    return out;
}

// The package tree for a whole generation (the import closure merged into ONE module tree, Option A).
// Each node is a package-path prefix; `files` are the files whose package is EXACTLY this node's path
// (several when same-package files are imported together), `children` the next path components. The
// node's `emitted` Rust module name is assigned by its PARENT (escaped + deduped among siblings), so
// two sibling packages whose escapes collide (`self`/`self_`) still get distinct `pub mod`s, and the
// name table and emission share the exact same module path.
struct PkgTrie {
    std::vector<const FileNode*> files;
    std::map<std::string, PkgTrie> children;  // RAW component -> child (sorted => deterministic)
    std::string emitted;  // this node's deduped Rust module name (empty at root)
    std::string package;  // this node's dotted package path, for its module doc (empty at root)
};

PkgTrie build_pkg_trie(const std::vector<const FileNode*>& files) {
    PkgTrie root;
    for (const FileNode* file : files) {
        PkgTrie* node = &root;
        std::string package;
        for (const std::string& component : dotted_components(file->package)) {
            package += package.empty() ? component : "." + component;
            node = &node->children[component];
            node->package = package;
        }
        node->files.push_back(file);
    }
    return root;
}

// Assign each child node its deduped Rust module name (escaped raw component, made unique among its
// siblings). A sub-package module is a path segment, so it keeps its name; a colliding message
// submodule/struct is bumped against it later (see build_scope's reserved set).
void assign_emitted_names(PkgTrie& node) {
    std::unordered_set<std::string> taken;
    for (auto& [component, child] : node.children) {
        child.emitted = dedup_ident(taken, escape_rust_ident(component));
        assign_emitted_names(child);
    }
}

// The deduped module names of a node's direct sub-packages (as identities, like every dedup set) --
// reserved in that node's scope so a message submodule, struct or visitor trait cannot collide with a
// sub-package `pub mod`.
std::unordered_set<std::string> child_module_names(const PkgTrie& node) {
    std::unordered_set<std::string> names;
    for (const auto& [component, child] : node.children) {
        names.emplace(ident_identity(child.emitted));
    }
    return names;
}

// --- Name table -------------------------------------------------------------------------------
// Every message/enum's placement in its model tree, with all Rust identifier dedup applied, computed
// ONCE per file. Emission and cross-reference path computation both read it, so an emitted `pub mod`
// / `pub struct` / newtype name and the path that refers to it can never disagree -- the reason this
// is a table and not recomputed at each use.
//
// Dedup is per scope (one proto package level or message = one Rust module). Within a scope these
// share the Rust TYPE namespace and so must be mutually unique:
//   - arena tree: each message's struct, and the `pub mod <snake>` holding its nested types;
//   - common tree: each enum's newtype and its `<Name>Class`, and the `pub mod <snake>` holding a
//     nested message's enums.
//   - stream tree: each message's handle (the arena struct's name) and its `<Name>Visitor` trait,
//     and the same `pub mod <snake>`s.
// A message's submodule name (snake of the message) is deduped among sibling messages ALONE, so it
// is the SAME string in both trees: the module PATH is shared (an enclosing message nests both its
// messages in arena and its enums in common), so renaming a module in one tree would desync the other
// and the stored paths. A leaf type (struct / newtype / Class / visitor) that collides with a module
// name is bumped instead -- a leaf name is never used as a path component, so bumping it stays local.
// Every set holds identities and every derived name is built from one (see dedup_ident).
struct MsgNames {
    std::vector<std::string> module;  // enclosing module segments, from the model root
    std::string type_name;            // the arena struct / stream handle identifier
    std::string visitor_name;         // the stream tree's `<Name>Visitor` trait identifier
    std::string submodule;  // the `pub mod` that holds nested types (snake); shared by both trees
};
struct EnumNames {
    std::vector<std::string> module;
    std::string type_name;   // the newtype identifier
    std::string class_name;  // the `<Name>Class` classify-enum identifier
};
struct NameTable {
    std::string root;  // the module the file is included at: `crate` or `crate::<path>`
    std::string tree;  // the model tree being emitted: `arena` or `stream`
    std::unordered_map<std::string, MsgNames> messages;  // message FQN -> names
    std::unordered_map<std::string, EnumNames> enums;    // enum FQN -> names
    // A oneof's enum type name (e.g. `Payload`), keyed by the OneofNode (oneofs carry no FQN). The
    // enum lives in the owning MESSAGE's arena submodule, deduped against that submodule's other
    // arena items (nested structs + their modules); see build_scope. The pointer keys index into the
    // FileNode passed to build_name_table; generate_arena/_common build the table and emit from that
    // one un-mutated FileNode, so the keys stay live -- do not copy or rebuild the AST between them.
    std::unordered_map<const OneofNode*, std::string> oneofs;
};

// Assign deduped names for ONE scope -- the child messages/enums declared directly at `module`, plus
// `scope_oneofs` (the oneofs of the MESSAGE whose submodule this scope is; empty at the package root,
// since oneofs always live in their owning message's submodule) -- then recurse into each message's
// own scope. `module` is the enclosing module path (mutated in place across the recursion).
void build_scope(const std::vector<const MessageNode*>& msgs,
                 const std::vector<const EnumNode*>& enums,
                 const std::vector<const OneofNode*>& scope_oneofs,
                 const std::unordered_set<std::string>& reserved_modules,
                 std::vector<std::string>& module, NameTable& table) {
    // Submodule names first: `reserved_modules` (sub-package `pub mod`s at this scope, fixed path
    // segments) are claimed up front, then each message's snake name, deduped among siblings. Both
    // trees and the paths agree on them. A message claims a name iff it emits a `pub mod` SOMEWHERE
    // -- arena when it has nested messages OR oneofs, common when it holds enums; a message that emits
    // none leaves `submodule` empty (never read). The reserved names are ONE shared set that both
    // trees' leaf dedup starts from, so a struct/enum name is bumped off a submodule (or a sub-package
    // module) even in the tree where that module does not exist. That over-dedup is cosmetic -- the
    // bumped name is stored and used uniformly, never a wrong path -- and keeps the set single.
    std::unordered_set<std::string> submods = reserved_modules;
    std::vector<std::string> submodule(msgs.size());
    for (std::size_t i = 0; i < msgs.size(); ++i) {
        if (!msgs[i]->nested_messages.empty() || !msgs[i]->oneofs.empty() ||
            codegen::holds_enum(*msgs[i])) {
            submodule[i] = dedup_ident(submods, escape_rust_ident(to_snake_case(msgs[i]->name)));
        }
    }
    // Arena submodule items: submodule + sub-package names reserved first (shared type namespace),
    // then each nested struct, then this message's oneof enums -- all deduped against the reserved
    // modules and each other. A module keeps its name (path segment); a colliding leaf is bumped.
    // The stream tree's visitor traits sit beside the same structs (as handles) and modules, but not
    // the oneof enums (arena only): they are deduped after every struct, so a trait is bumped and a
    // struct -- which arena-only users see too -- never is.
    {
        std::unordered_set<std::string> taken = submods;
        std::vector<MsgNames> names(msgs.size());
        for (std::size_t i = 0; i < msgs.size(); ++i) {
            names[i].module = module;
            names[i].type_name = dedup_ident(taken, type_ident(msgs[i]->name));
            names[i].submodule = submodule[i];
        }
        std::unordered_set<std::string> stream_taken = taken;
        for (std::size_t i = 0; i < msgs.size(); ++i) {
            names[i].visitor_name = dedup_ident(
                stream_taken, std::string(ident_identity(names[i].type_name)) + "Visitor");
            table.messages.emplace(msgs[i]->fqn, std::move(names[i]));
        }
        for (const OneofNode* oneof : scope_oneofs) {
            table.oneofs.emplace(oneof, dedup_ident(taken, pascal_ident(oneof->name)));
        }
    }
    // Common enum names: the SAME reserved set first (so a nested message's/sub-package's `pub mod`
    // and an enum newtype in this common scope cannot collide), then each newtype and its Class.
    {
        std::unordered_set<std::string> taken = submods;
        for (const EnumNode* node : enums) {
            EnumNames names;
            names.module = module;
            names.type_name = dedup_ident(taken, reserve_rp_prefix(type_ident(node->name)));
            names.class_name =
                dedup_ident(taken, std::string(ident_identity(names.type_name)) + "Class");
            table.enums.emplace(node->fqn, std::move(names));
        }
    }
    // Recurse into each message that has its own scope to record (nested messages, enums and/or
    // oneofs), descending through its (non-empty) submodule name. Nested scopes have no sub-packages,
    // so they reserve nothing.
    for (std::size_t i = 0; i < msgs.size(); ++i) {
        if (submodule[i].empty()) {
            continue;  // no nested messages, enums or oneofs: nothing to record
        }
        module.push_back(submodule[i]);
        build_scope(addrs(msgs[i]->nested_messages), addrs(msgs[i]->enums), addrs(msgs[i]->oneofs),
                    {}, module, table);
        module.pop_back();
    }
}

// Record one package node's own types (the top-level messages/enums of every file at this exact
// package, gathered together so same-package imports share one scope and dedup against each other),
// then recurse into its sub-packages. `module` is the node's emitted package path.
void build_names_for_node(const PkgTrie& node, std::vector<std::string>& module, NameTable& table) {
    std::vector<const MessageNode*> msgs;
    std::vector<const EnumNode*> enums;
    for (const FileNode* file : node.files) {
        for (const MessageNode& msg : file->messages) {
            msgs.push_back(&msg);
        }
        for (const EnumNode& node_enum : file->enums) {
            enums.push_back(&node_enum);
        }
    }
    // The package root declares no oneofs; sub-package module names are reserved so a message here
    // cannot collide with a `pub mod <subpackage>`.
    build_scope(msgs, enums, /*scope_oneofs=*/{}, child_module_names(node), module, table);
    for (const auto& [component, child] : node.children) {
        module.push_back(child.emitted);
        build_names_for_node(child, module, table);
        module.pop_back();
    }
}

// Build the name table over the whole generation (the import closure). Every type's module path +
// name is recorded, so a reference across files or packages is written like an intra-file one.
NameTable build_name_table(const PkgTrie& root) {
    NameTable table;
    std::vector<std::string> module;
    build_names_for_node(root, module, table);
    return table;
}

// The signature line every generated `Debug` impl opens its `fmt` with.
constexpr std::string_view kDebugFmt =
    "fn fmt(&self, rp_f: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result {\n";

// A proto full name as the docs show it, without the leading dot (`.weather.Station` ->
// `weather.Station`).
std::string proto_name(std::string_view fqn) {
    if (!fqn.empty() && fqn.front() == '.') {
        fqn.remove_prefix(1);
    }
    return std::string(fqn);
}

// Emit the newtype + classify enum for one proto enum.
//
//   #[derive(Clone, Copy, PartialEq, Eq, Hash, Default)]
//   #[repr(transparent)]
//   pub struct Color(pub i32);
//   impl Debug for Color { /* prints self.classify() */ }
//   impl Color {
//       pub const RED: Color = Color(1);
//       ...
//       #[inline] pub fn classify(self) -> ColorClass { match self.0 { 1 => ColorClass::Red, ..,
//                                                rp_other => ColorClass::Unknown(rp_other) } }
//   }
//   #[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)]
//   pub enum ColorClass { Red, .., Unknown(i32) }
//
// Storage is the raw `i32` (open enum, full range); the classify enum is the ergonomic match
// surface and `classify()` fuses to a branchless switch at the call site. The newtype and Class names
// come from the name table (deduped against everything else in the enum's common scope).
void emit_enum(Printer& printer, const NameTable& table, const EnumNode& node, bool serde) {
    const EnumNames& names = table.enums.at(node.fqn);
    const std::vector<std::string> consts = enum_const_names(node);
    const std::vector<std::string> variants = enum_variant_names(node);

    printer.set("T", names.type_name);
    printer.set("K", names.class_name);
    printer.set("proto", proto_name(node.fqn));

    printer.print(
        "/// The `$proto$` enum.\n"
        "///\n"
        "/// A field can hold a number the schema does not name, so this wraps any `i32`.\n"
        "/// Each named value is a constant, which also works as a `match` pattern. For an\n"
        "/// exhaustive `match`, use [`classify`](Self::classify).\n");
    // `Default` yields the all-zero enum value (`$T$(0)`), protobuf's default for an enum field.
    printer.print("#[derive(Clone, Copy, PartialEq, Eq, Hash, Default)]\n");
    // `repr(transparent)`: a zero-cost wrapper, layout-identical to its `i32`. (It does NOT let a
    // wire enum array be aliased -- enum values are varint-encoded, so variable-width and decoded
    // one at a time; the guarantee only matters for reinterpreting an in-memory `i32` buffer.)
    printer.print("#[repr(transparent)]\n");
    printer.print("pub struct $T$(pub i32);\n\n");

    // `Debug` prints the value's name, or `Unknown(7)` for a number the schema does not name.
    printer.print("impl ::core::fmt::Debug for $T$ {\n");
    printer.indent();
    printer.print(kDebugFmt);
    printer.indent();
    printer.print("::core::fmt::Debug::fmt(&self.classify(), rp_f)\n");
    printer.outdent();
    printer.print("}\n");
    printer.outdent();
    printer.print("}\n\n");

    if (serde) {
        // An open enum serializes as its raw `i32`, preserving any value the schema does not name --
        // the lossless choice for a forward-compatible enum.
        printer.print("impl ::rapidproto::serde::Serialize for $T$ {\n");
        printer.indent();
        printer.print(
            "fn serialize<RpS>(&self, rp_ser: RpS) -> ::core::result::Result<RpS::Ok, "
            "RpS::Error>\n");
        printer.print("where\n");
        printer.indent();
        printer.print("RpS: ::rapidproto::serde::Serializer,\n");
        printer.outdent();
        printer.print("{\n");
        printer.indent();
        printer.print("rp_ser.serialize_i32(self.0)\n");
        printer.outdent();
        printer.print("}\n");
        printer.outdent();
        printer.print("}\n\n");
    }

    printer.print("impl $T$ {\n");
    printer.indent();
    for (std::size_t i = 0; i < node.values.size(); ++i) {
        printer.print("pub const $name$: $T$ = $T$($n$);\n",
                      {{"name", consts[i]}, {"n", std::to_string(node.values[i].number)}});
    }
    printer.print("\n");
    printer.print(
        "/// Returns the value as an enum you can `match`.\n"
        "///\n"
        "/// A number the schema does not name is `Unknown`.\n");
    printer.print("#[inline]\n");
    printer.print("#[must_use]\n");
    printer.print("pub fn classify(self) -> $K$ {\n");
    printer.indent();
    printer.print("match self.0 {\n");
    printer.indent();
    // One arm per DISTINCT number (aliases share a number; duplicate match arms would not compile).
    std::unordered_set<std::int32_t> seen;
    for (std::size_t i = 0; i < node.values.size(); ++i) {
        if (!seen.insert(node.values[i].number).second) {
            continue;
        }
        printer.print("$n$ => $K$::$v$,\n",
                      {{"n", std::to_string(node.values[i].number)}, {"v", variants[i]}});
    }
    // An `rp_` binding: a plain `other` would be a pattern naming the newtype of an `enum other`.
    printer.print("rp_other => $K$::Unknown(rp_other),\n");
    printer.outdent();
    printer.print("}\n");
    printer.outdent();
    printer.print("}\n");
    printer.outdent();
    printer.print("}\n\n");

    printer.print("/// The values of the `$proto$` enum, for `match`.\n");
    printer.print("#[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)]\n");
    printer.print("pub enum $K$ {\n");
    printer.indent();
    for (const std::string& variant : variants) {
        printer.print("$v$,\n", {{"v", variant}});
    }
    printer.print("/// A number the schema does not name.\n");
    printer.print("Unknown(i32),\n");
    printer.outdent();
    printer.print("}\n");
}

// The Rust type for a proto scalar keyword. `string`/`bytes` are `ProtoStr<'a>` / `ProtoBytes<'a>`,
// 12-byte values borrowing the input for `'a`, which both models hand out as they are.
std::string rust_scalar_type(std::string_view t) {
    if (t == "int32" || t == "sint32" || t == "sfixed32") {
        return "i32";
    }
    if (t == "int64" || t == "sint64" || t == "sfixed64") {
        return "i64";
    }
    if (t == "uint32" || t == "fixed32") {
        return "u32";
    }
    if (t == "uint64" || t == "fixed64") {
        return "u64";
    }
    if (t == "bool") {
        return "bool";
    }
    if (t == "float") {
        return "f32";
    }
    if (t == "double") {
        return "f64";
    }
    if (t == "string") {
        return "::rapidproto::ProtoStr<'a>";
    }
    if (t == "bytes") {
        return "::rapidproto::ProtoBytes<'a>";
    }
    return "()";  // defensive: not reached for a resolved scalar field
}

// Every reference to a generated type is an absolute path from the module the file is included at, so
// it reads the same from anywhere in the tree, and no schema name in between can capture it.
//
// The two path helpers look the target up in the name table. `.at`: every referenced type is in the
// table, so a miss is a generator invariant breach (e.g. a cross-file reference before the table is
// built over the import closure) and aborts rather than silently emitting a wrong path.

// The path to a module of model tree `tree`.
std::string tree_module_path(const NameTable& table, const std::string& tree,
                             const std::vector<std::string>& module) {
    std::string out = table.root + "::" + tree;
    for (const std::string& seg : module) {
        out += "::";
        out += seg;
    }
    return out;
}

// The path to an ENUM, which lives in the `common` tree. Enum newtypes carry no lifetime.
std::string common_type_path(const NameTable& table, const std::string& fqn) {
    const EnumNames& loc = table.enums.at(fqn);
    return tree_module_path(table, "common", loc.module) + "::" + loc.type_name;
}

// The path to a message in the tree being emitted, without its lifetime.
std::string message_path(const NameTable& table, const std::string& fqn) {
    const MsgNames& loc = table.messages.at(fqn);
    return tree_module_path(table, table.tree, loc.module) + "::" + loc.type_name;
}

// The path to a oneof's enum, which lives in its message's arena submodule, without its lifetime.
std::string oneof_path(const NameTable& table, const MessageNode& msg, const OneofNode& oneof) {
    const MsgNames& loc = table.messages.at(msg.fqn);
    return tree_module_path(table, "arena", loc.module) + "::" + loc.submodule +
           "::" + table.oneofs.at(&oneof);
}

// The Rust type of a field's singular VALUE as a decoded message stores it, ignoring repeated/presence
// wrapping: scalar -> a Rust primitive, enum -> the common-tree path, string -> ProtoStr<'a>, bytes ->
// ProtoBytes<'a>, message -> the arena-tree path with its lifetime (`Inner<'a>`).
std::string field_value_type(const NameTable& table, const FieldNode& field) {
    if (field.is_message_type) {
        return message_path(table, field.resolved_type_fqn) + "<'a>";
    }
    if (field.is_enum_type) {
        return common_type_path(table, field.resolved_type_fqn);
    }
    return rust_scalar_type(field.type_name);
}

// Whether `field` is a `string` or `bytes` scalar (not a message or enum, whose `type_name` is the
// referenced type's name).
bool is_string_or_bytes(const FieldNode& field) {
    return !field.is_message_type && !field.is_enum_type &&
           (field.type_name == "string" || field.type_name == "bytes");
}

// The type carried by a oneof variant for `field`: a singular message is borrowed (`&'a T<'a>`, like
// a singular message FIELD); everything else is the stored value type (ProtoStr<'a>, ProtoBytes<'a>,
// the enum newtype, or a scalar primitive). Oneof fields are never repeated or maps.
std::string variant_payload_type(const NameTable& table, const FieldNode& field) {
    if (field.is_message_type) {
        return "&'a " + field_value_type(table, field);
    }
    return field_value_type(table, field);
}

// Does any variant of `oneof` borrow the input, so the enum needs a `<'a>`? Message, string and bytes
// variants borrow; scalar and enum (Copy newtype) variants do not.
bool oneof_borrows(const OneofNode& oneof) {
    return std::any_of(oneof.fields.begin(), oneof.fields.end(), [](const FieldNode& field) {
        return field.is_message_type || is_string_or_bytes(field);
    });
}

// Emit `pub enum <Name>['a] { Variant(T), .. }` for one oneof, in the owning message's arena submodule.
// The enum is closed: a oneof has a fixed variant set, and an off-list wire field is just an unknown
// field, not a new case. The `<'a>` is present only when a variant borrows -- an enum cannot carry an
// unused lifetime without a bogus phantom variant, unlike a struct's PhantomData field. No `Copy`
// derive: the oneof getter hands back a borrow (`Option<&Payload>`), matching C++ (a reference into the
// union, no copy) and keeping `Copy` off the public API -- deriving it would be a hard-to-revert
// commitment, and `Copy` is for cheap integer-like values, not a sum type.
void emit_oneof_enum(Printer& printer, const NameTable& table, const MessageNode& msg,
                     const OneofNode& oneof) {
    const std::vector<std::string> variants = oneof_variant_names(oneof);
    printer.print("/// The `$o$` oneof of `$m$`.\n",
                  {{"o", oneof.name}, {"m", proto_name(msg.fqn)}});
    printer.print("#[derive(Debug)]\n");
    printer.print("pub enum $n$$lt$ {\n",
                  {{"n", table.oneofs.at(&oneof)}, {"lt", oneof_borrows(oneof) ? "<'a>" : ""}});
    printer.indent();
    for (std::size_t i = 0; i < oneof.fields.size(); ++i) {
        printer.print("$v$($t$),\n",
                      {{"v", variants[i]}, {"t", variant_payload_type(table, oneof.fields[i])}});
    }
    printer.outdent();
    printer.print("}\n");
}

// Deduped accessor method names for a message's regular fields, map fields and oneofs, in that order.
// Each name also names the member's struct storage field. Each proto name is escaped and `rp_`-reserved
// (reserve_rp_prefix), then deduped against the others AND the non-`rp_` names the same type defines,
// with a trailing `_` on collision. Without this, a field named `decode`, or two members escaping to
// one identifier (`self` -> `self_` beside a field `self_`, or a field and a oneof with the same name),
// would emit duplicate items -- non-compiling Rust for a protoc-valid schema. Mirrors the enum dedup.
// Every other name in the type's method and field namespaces (`rp_decode_into`, `rp_default`, the
// `rp_presence` / `rp_unknown` storage) is `rp_`-prefixed, and the decode body's locals are too, so the
// reservation alone keeps an accessor off them.
struct AccessorNames {
    std::vector<std::string> fields;
    std::vector<std::string> maps;
    std::vector<std::string> oneofs;
};
AccessorNames message_accessor_names(const MessageNode& msg) {
    std::unordered_set<std::string> taken = {
        "decode",              // the generated decode() method
        "decode_owned",        // the alloc-gated owning-handle constructor (impl_decode_owned!)
        "has_unknown_fields",  // the field-modes unknown-fields accessor (when enabled)
        "_marker",             // the PhantomData storage field of a message with no `'a` field
    };
    AccessorNames names;
    const auto assign = [&taken](const std::string& raw) {
        return dedup_ident(taken, reserve_rp_prefix(escape_rust_ident(raw)));
    };
    names.fields.reserve(msg.fields.size());
    for (const FieldNode& field : msg.fields) {
        names.fields.push_back(assign(field.name));
    }
    names.maps.reserve(msg.map_fields.size());
    for (const MapFieldNode& map : msg.map_fields) {
        names.maps.push_back(assign(map.name));
    }
    names.oneofs.reserve(msg.oneofs.size());
    for (const OneofNode& oneof : msg.oneofs) {
        names.oneofs.push_back(assign(oneof.name));
    }
    return names;
}

// The resolved field mode for a field / map field (Materialize when the profile is silent on it).
arenagen::FieldMode field_mode(const FieldModes& modes, const FieldNode& field) {
    const auto it = modes.fields.find(&field);
    return it == modes.fields.end() ? arenagen::FieldMode::Materialize : it->second;
}
arenagen::FieldMode map_mode(const FieldModes& modes, const MapFieldNode& map) {
    const auto it = modes.maps.find(&map);
    return it == modes.maps.end() ? arenagen::FieldMode::Materialize : it->second;
}

// Does the message's struct use the `'a` lifetime through a field (string/bytes borrow the input; a
// message field is a borrowed pointer; any repeated field is a borrowed slice; a `MapView<'a, ..>`
// always carries it; a oneof does when a variant borrows)? If not (only singular numeric / enum / bool
// fields), the struct carries a `PhantomData<&'a ()>` to use `'a`.
bool message_uses_lifetime(const MessageNode& msg, const FieldModes& modes) {
    if (std::any_of(msg.map_fields.begin(), msg.map_fields.end(), [&](const MapFieldNode& map) {
            return map_mode(modes, map) != arenagen::FieldMode::Drop;  // a MapView<'a, ..>
        })) {
        return true;
    }
    if (std::any_of(msg.fields.begin(), msg.fields.end(), [&](const FieldNode& field) {
            // A dropped field has no storage; a raw message field borrows its payload.
            return field_mode(modes, field) != arenagen::FieldMode::Drop &&
                   (field.is_repeated || field.is_message_type || is_string_or_bytes(field));
        })) {
        return true;
    }
    return std::any_of(msg.oneofs.begin(), msg.oneofs.end(), oneof_borrows);
}

// Does the decode body allocate from the arena (so its `rp_decode_into` uses the `arena` param)? Repeated
// fields and maps accumulate into an arena `DecodeVec`; a MATERIALIZED singular message field and a
// oneof message variant are arena-allocated. A singular `raw` message field stores borrowed payload
// bytes (no alloc); a `drop` field stores nothing.
bool body_uses_arena(const MessageNode& msg, const FieldModes& modes) {
    if (std::any_of(msg.map_fields.begin(), msg.map_fields.end(), [&](const MapFieldNode& map) {
            return map_mode(modes, map) != arenagen::FieldMode::Drop;  // DecodeVec of entries
        })) {
        return true;
    }
    if (std::any_of(msg.fields.begin(), msg.fields.end(), [&](const FieldNode& field) {
            const arenagen::FieldMode mode = field_mode(modes, field);
            if (mode == arenagen::FieldMode::Drop) {
                return false;
            }
            return field.is_repeated ||  // a DecodeVec (even repeated raw payloads)
                   (field.is_message_type && mode == arenagen::FieldMode::Materialize);  // alloc'd
        })) {
        return true;
    }
    return std::any_of(msg.oneofs.begin(), msg.oneofs.end(), [](const OneofNode& oneof) {
        return std::any_of(oneof.fields.begin(), oneof.fields.end(),
                           [](const FieldNode& field) { return field.is_message_type; });
    });
}

// ---------------------------------------------------------------------------------------------------
// Shared storage-layout planner (arenagen::plan_layouts) consumption. The Rust decoder reuses the C++
// planner's DECISIONS -- which singular sub-messages inline by value vs behind a pointer, and the
// bit-packed presence/bool mask -- so both decoders inline and track presence for the same fields. The
// planner's C++ byte offsets/sizes are ignored (Rust lays out its own structs).

// The planner's MemberPlan for `field` in `layout`, or null (a message may lack a layout plan, and a
// map-entry synthetic field is not a member of its parent message). Matched by FieldNode identity.
const arenagen::MemberPlan* member_for(const arenagen::MessageLayout* layout,
                                       const FieldNode& field) {
    if (layout == nullptr) {
        return nullptr;
    }
    for (const arenagen::MemberPlan& m : layout->members) {
        if (m.field == &field) {
            return &m;
        }
    }
    return nullptr;
}

// How a non-repeated, non-dropped field is stored in the Rust struct, derived from its MemberPlan.
enum class RustStore : std::uint8_t {
    Bare,         // bare value, no presence bit (Implicit/Required scalar/enum/string/bytes)
    MaskedValue,  // bare value + a mask presence bit (Explicit scalar/enum/string/bytes)
    MaskedBool,   // NO struct field; a mask value bit (+ a presence bit iff Explicit)
    InlineMsg,    // bare `T<'a>` + a mask presence bit; `T::default()` when absent
    PointerMsg,   // `Option<&'a T<'a>>`, no bit (null = absent)
};

// Classify a singular (non-repeated), materialized field. `member` may be null (no layout plan, or a
// fallback); then the pre-planner behavior (Explicit -> Option, message -> pointer) is reproduced.
RustStore rust_store(const arenagen::MemberPlan* member, const FieldNode& field) {
    if (member == nullptr) {
        if (field.is_message_type) {
            return RustStore::PointerMsg;
        }
        if (field.type_name == "bool" && field.presence != FieldPresence::Required) {
            return RustStore::Bare;  // no planner: keep a plain bool byte
        }
        return field.presence == FieldPresence::Explicit ? RustStore::MaskedValue : RustStore::Bare;
    }
    switch (member->kind) {
        case arenagen::FieldKind::InlineFixedSubMsg:
            return RustStore::InlineMsg;
        case arenagen::FieldKind::PointerSubMsg:
            return RustStore::PointerMsg;
        case arenagen::FieldKind::InlineScalar:
            if (member->is_bool) {
                return RustStore::MaskedBool;
            }
            return member->presence_bit >= 0 ? RustStore::MaskedValue : RustStore::Bare;
        case arenagen::FieldKind::InlineEnum:
        case arenagen::FieldKind::BorrowString:
            return member->presence_bit >= 0 ? RustStore::MaskedValue : RustStore::Bare;
        case arenagen::FieldKind::Repeated:
        case arenagen::FieldKind::Map:
        case arenagen::FieldKind::Raw:
            break;  // handled on their own emission paths, never through rust_store
    }
    return RustStore::Bare;
}

// Bits the Rust mask word carries: the planner's presence + value bits (NOT the unknown bit -- Rust
// keeps `rp_unknown: bool` as a separate field). Presence/value bits are assigned before the unknown
// bit, so they occupy [0, unknown_bit) when an unknown bit exists, else [0, mask_bits). 0 = no mask.
int rust_mask_bits(const arenagen::MessageLayout& layout) {
    return layout.unknown_bit >= 0 ? layout.unknown_bit : layout.mask_bits;
}

// A `[u64; N]` array mask is used past this many bits; at or below it a single uint word holds the mask.
constexpr int kMaskWordBits = 64;

// The Rust mask word type for `bits` (> 0): the smallest uint covering them, or a `[u64; N]` array.
std::string mask_word_type(int bits) {
    constexpr int kU8 = 8;
    constexpr int kU16 = 16;
    constexpr int kU32 = 32;
    if (bits <= kU8) {
        return "u8";
    }
    if (bits <= kU16) {
        return "u16";
    }
    if (bits <= kU32) {
        return "u32";
    }
    if (bits <= kMaskWordBits) {
        return "u64";
    }
    return "[u64; " + std::to_string((bits + kMaskWordBits - 1) / kMaskWordBits) + "]";
}

// The all-clear value of a `mask_word_type(bits)`: `0`, or `[0; N]` for an array.
std::string mask_zero(int bits) {
    return bits > kMaskWordBits
               ? "[0; " + std::to_string((bits + kMaskWordBits - 1) / kMaskWordBits) + "]"
               : std::string("0");
}

// The lvalue holding `bit` for a mask of `total` bits: the word itself, or `word[bit/64]` when the mask
// is a `[u64; N]` array (> 64 bits).
std::string mask_word_at(const std::string& base, int bit, int total) {
    return total > kMaskWordBits ? base + "[" + std::to_string(bit / kMaskWordBits) + "]" : base;
}
int mask_bit_pos(int bit, int total) {
    return total > kMaskWordBits ? bit % kMaskWordBits : bit;
}

// `(<base>[word] & (1 << pos)) != 0` -- a bit-set test over the mask word, or `== 0` with
// `set = false`.
std::string mask_test(const std::string& base, int bit, int total, bool set = true) {
    return "(" + mask_word_at(base, bit, total) + " & (1 << " +
           std::to_string(mask_bit_pos(bit, total)) + (set ? ")) != 0" : ")) == 0");
}

// Whether a singular field's decode local holds the plain `&'a [u8]` it read: a `string` or `bytes`
// field. The struct packs it into its 12-byte cell only at construction: a decode keeps many such
// locals live at once, and the pointer/length pair stays in registers where a packed 12-byte value
// is copied through memory.
bool slice_local(const FieldNode& field) {
    return !field.is_repeated && is_string_or_bytes(field);
}

// The struct storage type for a field: a repeated field is a `PackedSlice` of its elements (12 bytes,
// like the C++ decoder's views); a singular message is `Option<&'a T<'a>>`; everything else is the
// bare value type, a string or `bytes` being its 12-byte cell (an explicit-presence scalar keeps its
// presence in the mask). A proto2 `[default = ...]` is NOT materialized (matching the C++ decoder,
// which reads an absent defaulted field as `None` and leaves the default to the consumer), so a
// defaulted field is stored exactly like any other field of its presence. A `raw` message field keeps
// its undecoded LEN payload instead of the decoded tree, as `bytes`: `Option<ProtoBytes<'a>>` singular
// (still 12 bytes, `None` being the null pointer), a `PackedSlice` of them repeated (the consumer feeds
// a payload to the field type's `decode` itself).
std::string field_storage_type(const NameTable& table, const FieldNode& field,
                               const FieldModes& modes, const arenagen::MemberPlan* member) {
    const bool raw = field_mode(modes, field) == arenagen::FieldMode::Raw;
    std::string value = raw ? rust_scalar_type("bytes") : field_value_type(table, field);
    if (field.is_repeated) {
        return "::rapidproto::PackedSlice<'a, " + value + ">";
    }
    if (raw) {
        return "::core::option::Option<" + value + ">";
    }
    if (rust_store(member, field) == RustStore::PointerMsg) {
        return "::core::option::Option<&'a " + value + ">";
    }
    // Everything else is stored bare: Bare / MaskedValue (presence in the mask) / InlineMsg (by value,
    // presence in the mask). A MaskedBool has no struct field at all, so this is never emitted for it.
    return value;
}

// The getter's return type -- the SEMANTIC presence-wrapped type, which (unlike the storage type) still
// wraps explicit presence in `Option`: masked scalar/enum/string -> `Option<T>`; inline/pointer message
// -> `Option<&T>`; bool -> `bool` / `Option<bool>`; bare -> the plain value; repeated -> the plain
// slice its `PackedSlice` holds; raw -> `Option<ProtoBytes<'a>>` singular, a slice of them repeated.
std::string field_getter_type(const NameTable& table, const FieldNode& field,
                              const FieldModes& modes, const arenagen::MemberPlan* member) {
    if (field_mode(modes, field) == arenagen::FieldMode::Raw) {
        const std::string bytes = rust_scalar_type("bytes");
        return field.is_repeated ? "&'a [" + bytes + "]" : "::core::option::Option<" + bytes + ">";
    }
    if (field.is_repeated) {
        return "&'a [" + field_value_type(table, field) + "]";
    }
    std::string value = field_value_type(table, field);
    switch (rust_store(member, field)) {
        case RustStore::PointerMsg:
            // A Copy arena borrow, outlives `&self`.
            return "::core::option::Option<&'a " + value + ">";
        case RustStore::InlineMsg:
            // Borrows `&self` (the value lives in the struct).
            return "::core::option::Option<&" + value + ">";
        case RustStore::MaskedValue:
            return "::core::option::Option<" + value + ">";
        case RustStore::MaskedBool:
            return field.presence == FieldPresence::Explicit ? "::core::option::Option<bool>"
                                                             : "bool";
        case RustStore::Bare:
            return value;
    }
    return value;
}

// The default initializer for a NON-repeated field's or a map entry key/value's decode local (a
// string/bytes or raw field's local is a plain slice instead, see `emit_decode_locals`): `None` for a
// pointer message; its `rp_default()` for an inlined-by-value message; else the proto3 zero value
// (shared by Bare and masked-with-a-presence-bit fields -- the presence bit, not the value, records
// absence). A proto2 `[default = ...]` is not materialized (matching the C++ decoder). A bool has no
// local (it lives in the mask). Repeated fields use a `DecodeVec`, not this.
std::string field_default_expr(const NameTable& table, const FieldNode& field,
                               const arenagen::MemberPlan* member) {
    switch (rust_store(member, field)) {
        case RustStore::PointerMsg:
            return "::core::option::Option::None";
        case RustStore::InlineMsg:
            return "<" + field_value_type(table, field) + ">::rp_default()";
        case RustStore::MaskedBool:  // no local emitted; defensive
        case RustStore::Bare:
        case RustStore::MaskedValue:
            break;
    }
    if (field.is_enum_type) {
        return field_value_type(table, field) + "(0)";
    }
    const std::string& t = field.type_name;
    if (t == "string" || t == "bytes") {
        return "::core::default::Default::default()";
    }
    if (t == "bool") {
        return "false";
    }
    if (t == "float" || t == "double") {
        return "0.0";
    }
    return "0";
}

// The `wire::WireType` variant a scalar field's tag must carry.
std::string scalar_wire_variant(const FieldNode& field) {
    const std::string& t = field.type_name;
    if (t == "fixed32" || t == "sfixed32" || t == "float") {
        return "I32";
    }
    if (t == "fixed64" || t == "sfixed64" || t == "double") {
        return "I64";
    }
    if (t == "string" || t == "bytes") {
        return "Len";
    }
    return "Varint";  // int*/uint*/sint*/bool/enum
}

// Whether a field also arrives as a packed LEN run: a repeated numeric (not a message, string or
// bytes).
bool is_packable_repeated(const FieldNode& field) {
    return field.is_repeated && !field.is_message_type && scalar_wire_variant(field) != "Len";
}

// The low-3-bit wire code of each wire type (its on-wire value, matching `wire::WireType as u8`).
enum WireCode : std::uint8_t {
    kWireVarint = 0,
    kWireI64 = 1,
    kWireLen = 2,
    kWireSGroup = 3,  // proto2 group start (a materialized group message field dispatches on this)
    kWireI32 = 5,
};

// The raw tag key `field << 3 | wire_code` a decode arm matches on -- the value the loop's one-byte
// peek hub dispatches with (the tag byte itself for a one-byte tag, else `(field << 3) | wire` rebuilt
// after a full read). `wire` is a `scalar_wire_variant` result or the literal "Len". Field numbers go
// up to 2^29 - 1, so the key stays within u32 (the loop's dispatch type).
std::int64_t raw_tag_value(std::int64_t number, const std::string& wire) {
    std::int64_t code = kWireI32;
    if (wire == "Varint") {
        code = kWireVarint;
    } else if (wire == "I64") {
        code = kWireI64;
    } else if (wire == "Len") {
        code = kWireLen;
    } else if (wire == "SGroup") {
        code = kWireSGroup;
    }
    return (number << 3) | code;
}

std::string raw_tag_key(std::int64_t number, const std::string& wire) {
    return std::to_string(raw_tag_value(number, wire)) + "u32";
}

// The expression converting the just-read raw wire value (`rp_v`: u64 for Varint, u32 for I32, u64 for
// I64; `rp_p`: &[u8] for Len) into the field's Rust value type. A string or `bytes` value skips the
// length check of `new`: both decoders reject an input over `u32::MAX` bytes, so `rp_p` fits.
std::string scalar_convert_expr(const NameTable& table, const FieldNode& field) {
    if (field.is_enum_type) {
        return field_value_type(table, field) + "(rp_v as i32)";
    }
    const std::string& t = field.type_name;
    // `rp_v` is u64 for a Varint field, u32 for an I32 (fixed32) field, u64 for an I64 (fixed64)
    // field -- so a fixed32/fixed64 value needs no cast, while the varint-coded types do.
    if (t == "int32" || t == "sfixed32") {
        return "rp_v as i32";
    }
    if (t == "int64" || t == "sfixed64") {
        return "rp_v as i64";
    }
    if (t == "uint32") {
        return "rp_v as u32";
    }
    if (t == "uint64" || t == "fixed32" || t == "fixed64") {
        return "rp_v";
    }
    if (t == "sint32") {
        return "::rapidproto::wire::zigzag32(rp_v as u32)";
    }
    if (t == "sint64") {
        return "::rapidproto::wire::zigzag64(rp_v)";
    }
    if (t == "bool") {
        return "rp_v != 0";
    }
    if (t == "float") {
        return "f32::from_bits(rp_v)";
    }
    if (t == "double") {
        return "f64::from_bits(rp_v)";
    }
    if (t == "string") {
        return "::rapidproto::ProtoStr::new_truncating(rp_p)";
    }
    if (t == "bytes") {
        return "::rapidproto::ProtoBytes::new_truncating(rp_p)";
    }
    return "rp_v";  // defensive
}

// Emit a `pub fn <field>(&self) -> ...` accessor. The return type is the SEMANTIC presence-wrapped
// type; the body reads the bare storage and -- for presence/bool-packed fields -- tests the
// `rp_presence` mask (set-index == test-index, both from the shared planner's bit assignment).
// `mask_bits` is the message's Rust mask width.
void emit_field_accessor(Printer& printer, const NameTable& table, const FieldNode& field,
                         const std::string& accessor, const FieldModes& modes,
                         const arenagen::MemberPlan* member, int mask_bits) {
    const std::string ret = field_getter_type(table, field, modes, member);
    printer.print("pub fn $a$(&self) -> $t$ {\n", {{"a", accessor}, {"t", ret}});
    printer.indent();
    const RustStore store = rust_store(member, field);
    const bool masked = field_mode(modes, field) != arenagen::FieldMode::Raw &&
                        !field.is_repeated && member != nullptr;
    // A field with no plan has neither bit.
    const int presence_bit = member != nullptr ? member->presence_bit : -1;
    const int value_bit = member != nullptr ? member->value_bit : -1;
    // Only an Explicit field carries a resting presence bit (planner `needs_presence`); an Implicit
    // bool (value bit only) or a Required inlined message has `presence_bit == -1`, so computing the
    // test would emit `1 << -1`. Leave it empty there -- the branches that lack a presence bit never
    // read `pbit`.
    // A present-iff-bit getter is `(<bit test>).then_some(<value>)`, or the `Some`-then-`None` form
    // below for a string or bytes: the value is a field read or a bit test, so evaluating it eagerly
    // costs nothing.
    const std::string pbit =
        (masked && presence_bit >= 0) ? mask_test("self.rp_presence", presence_bit, mask_bits) : "";
    // The stored value as the getter returns it: a `PackedSlice` hands back its plain slice, for the
    // full `'a`.
    std::string value = "self." + accessor;
    if (field.is_repeated) {
        value += ".as_slice()";
    }
    switch (store) {
        case RustStore::MaskedBool: {
            const std::string vtest = mask_test("self.rp_presence", value_bit, mask_bits);
            if (field.presence == FieldPresence::Explicit) {
                printer.print("($p$).then_some($v$)\n", {{"p", pbit}, {"v", vtest}});
            } else {
                printer.print("$v$\n", {{"v", vtest}});
            }
            break;
        }
        case RustStore::MaskedValue:
            if (is_string_or_bytes(field)) {
                // Rebuilt from its fields, not copied whole. Rust copies the packed 12 bytes as raw
                // memory, and the copy loses LLVM's knowledge that the pointer is non-null. `None` is
                // the null pointer, so every test of the returned `Option` would then load and test it.
                const std::string cell =
                    field.type_name == "string"
                        ? "::rapidproto::ProtoStr::new_truncating(" + value + ".as_bytes())"
                        : "::rapidproto::ProtoBytes::new_truncating(" + value + ".as_slice())";
                // `Some`, then overwritten with `None`, so the length is written on both paths. An
                // `Option` of a packed cell is an aggregate, not a scalar pair, so it lives in a stack
                // slot, and in a caller's loop that slot is reused on every pass. `then_some` writes
                // the length only on `Some`, so on `None` the slot keeps the previous pass's length,
                // and LLVM keeps the length load behind a branch with a second test of the bit.
                printer.print(
                    "let mut rp_v = ::core::option::Option::Some($v$);\n"
                    "if $c$ {\n  rp_v = ::core::option::Option::None;\n}\nrp_v\n",
                    {{"v", cell},
                     {"c", mask_test("self.rp_presence", presence_bit, mask_bits, false)}});
            } else {
                printer.print("($p$).then_some($v$)\n", {{"p", pbit}, {"v", value}});
            }
            break;
        case RustStore::InlineMsg:
            if (presence_bit >= 0) {
                printer.print("($p$).then_some(&self.$a$)\n", {{"p", pbit}, {"a", accessor}});
            } else {
                // A Required inlined message has no resting presence bit (validated via
                // MissingRequired), so on a successful decode it is always present.
                printer.print("::core::option::Option::Some(&self.$a$)\n", {{"a", accessor}});
            }
            break;
        case RustStore::PointerMsg:
        case RustStore::Bare:
            printer.print("$v$\n", {{"v", value}});
            break;
    }
    printer.outdent();
    printer.print("}\n");
}

// The struct storage (= getter return) type for one map field: a borrowed `MapView<'a, K, V>`. Keys
// are scalar; a message value is stored inline by value (`Inner<'a>`), like a repeated-message element.
std::string map_view_type(const NameTable& table, const MapFieldNode& map) {
    const std::string key = rust_scalar_type(map.key_type);
    std::string value;
    if (map.value_is_message) {
        value = message_path(table, map.resolved_value_type_fqn) + "<'a>";
    } else if (map.value_is_enum) {
        value = common_type_path(table, map.resolved_value_type_fqn);
    } else {
        value = rust_scalar_type(map.value_type);
    }
    return "::rapidproto::MapView<'a, " + key + ", " + value + ">";
}

// The struct storage (= getter return) type for one oneof: `Option<<Enum>['a]>` (None = unset). The
// `<'a>` is present only when a variant borrows (matching the enum definition).
std::string oneof_storage_type(const NameTable& table, const MessageNode& msg,
                               const OneofNode& oneof) {
    return "::core::option::Option<" + oneof_path(table, msg, oneof) +
           (oneof_borrows(oneof) ? "<'a>" : "") + ">";
}

// Emit a `pub fn <map>(&self) -> MapView<'a, K, V>` accessor reading the stored view. `accessor` is
// the pre-deduped name.
void emit_map_accessor(Printer& printer, const NameTable& table, const MapFieldNode& map,
                       const std::string& accessor) {
    printer.print("pub fn $a$(&self) -> $t$ {\n",
                  {{"a", accessor}, {"t", map_view_type(table, map)}});
    printer.indent();
    printer.print("self.$a$\n", {{"a", accessor}});
    printer.outdent();
    printer.print("}\n");
}

// Emit a `pub fn <oneof>(&self) -> Option<&Payload['a]>` accessor (None = unset), borrowing the stored
// enum (`as_ref`). The getter hands back a reference -- the oneof is not `Copy` (see `emit_oneof_enum`)
// -- so matching binds the variant payloads by reference. `accessor` is the pre-deduped method name.
void emit_oneof_accessor(Printer& printer, const NameTable& table, const MessageNode& msg,
                         const OneofNode& oneof, const std::string& accessor) {
    const std::string ret = "::core::option::Option<&" + oneof_path(table, msg, oneof) +
                            (oneof_borrows(oneof) ? "<'a>" : "") + ">";
    printer.print("pub fn $a$(&self) -> $t$ {\n", {{"a", accessor}, {"t", ret}});
    printer.indent();
    printer.print("self.$a$.as_ref()\n", {{"a", accessor}});
    printer.outdent();
    printer.print("}\n");
}

// A wire read in a decode frame: `src` is the `rest` slice variable to read from and advance, and `off`
// is the body-relative offset expression to report on error -- both resolved to the current frame. The
// readers leave `src` unadvanced on `Err`, so `src`'s position is where the failing item began.
struct ReadAt {
    std::string src;
    std::string off;
};

// The main message loop's body-relative offset: the readers leave `rp_rest` at the failing item.
constexpr const char* kLoopOff = "rp_body.len() - rp_rest.len()";

// The read context for the main message loop: read from `rp_rest`, error at its position in `rp_body`.
ReadAt loop_read() {
    return {"rp_rest", kLoopOff};
}

// The read context for one element inside a packed run: read from the payload suffix `rp_p`. `rp_rest`
// is already fixed past the whole payload and `rp_p` shrinks as elements are read, so this points at
// the element being read -- not at the end of the field, as `loop_read`'s offset would here.
ReadAt packed_read() {
    return {"rp_p", "rp_body.len() - rp_rest.len() - rp_p.len()"};
}

// Close a `<slice> = match <wire read> {` the caller opened: the advanced slice on success, else an
// early return of the error at `off`.
void emit_read_arms(Printer& printer, const std::string& off) {
    printer.indent();
    printer.print("::core::result::Result::Ok(r) => r,\n");
    printer.print(
        "::core::result::Result::Err(k) => return "
        "::core::result::Result::Err(::rapidproto::DecodeError::new(k, $off$)),\n",
        {{"off", off}});
    printer.outdent();
    printer.print("};\n");
}

// How a varint value is read: `Split` (`read_varint`) inlines only the one-byte case and calls out of
// line for the rest, which keeps a decoder that reads every field compact (the arena's); `Inline`
// (`read_varint_inline`) inlines the multibyte decode too, for the stream decoders, where only the
// selected fields' reads remain.
enum class VarintRead : std::uint8_t { Split, Inline };

// Emit a scalar (Varint/I32/I64) value read from `at.src` into `rp_v`, erroring at `at.off`. After it
// `scalar_convert_expr` yields the typed value.
void emit_scalar_value_read(Printer& printer, const FieldNode& field, const ReadAt& at,
                            VarintRead varint = VarintRead::Split) {
    const std::string wire = scalar_wire_variant(field);
    if (wire == "I32") {
        printer.print("let mut rp_v = 0u32;\n");
        printer.print("$s$ = match ::rapidproto::wire::read_fixed32($s$, &mut rp_v) {\n",
                      {{"s", at.src}});
    } else if (wire == "I64") {
        printer.print("let mut rp_v = 0u64;\n");
        printer.print("$s$ = match ::rapidproto::wire::read_fixed64($s$, &mut rp_v) {\n",
                      {{"s", at.src}});
    } else {
        printer.print("let mut rp_v = 0u64;\n");
        printer.print("$s$ = match ::rapidproto::wire::$r$($s$, &mut rp_v) {\n",
                      {{"s", at.src},
                       {"r", varint == VarintRead::Inline ? "read_varint_inline" : "read_varint"}});
    }
    emit_read_arms(printer, at.off);
}

// Emit a length-delimited payload read from `at.src` into `rp_p`, erroring at `at.off`.
void emit_len_read(Printer& printer, const ReadAt& at) {
    printer.print("let mut rp_p: &[u8] = &[];\n");
    printer.print("$s$ = match ::rapidproto::wire::read_length_delimited($s$, &mut rp_p) {\n",
                  {{"s", at.src}});
    emit_read_arms(printer, at.off);
}

// The wire form a message field arrives in: a proto2 group (delimited) is `SGroup` (start-group tag,
// scanned to its matching end), every other message field is length-prefixed (`Len`). Drives both the
// dispatch key and which payload reader runs.
std::string message_field_wire(const FieldNode& field) {
    return field.message_encoding == MessageEncoding::Delimited ? "SGroup" : "Len";
}

// Read a message field's payload from `at.src` into `rp_p`: a length-delimited body for a normal
// message, or a group body (start-tag already consumed, scanned to the matching end-group) via
// `read_group` for a proto2 group field. Either way `rp_p` is the bytes to decode as the message body.
void emit_msg_payload_read(Printer& printer, const FieldNode& field, const ReadAt& at) {
    if (field.message_encoding != MessageEncoding::Delimited) {
        emit_len_read(printer, at);
        return;
    }
    printer.print("let mut rp_p: &[u8] = &[];\n");
    printer.print("$s$ = match ::rapidproto::wire::read_group($s$, $n$, &mut rp_p) {\n",
                  {{"s", at.src}, {"n", std::to_string(field.number)}});
    emit_read_arms(printer, at.off);
}

// A `DecodeVec::push`, mapping arena exhaustion to a DecodeError.
void emit_push(Printer& printer, const std::string& acc, const std::string& value) {
    printer.print(
        "$acc$.push($v$).map_err(|_| "
        "::rapidproto::DecodeError::new(::rapidproto::ErrorKind::ArenaExhausted, 0))?;\n",
        {{"acc", acc}, {"v", value}});
}

// A `DecodeVec::reserve`, mapping arena exhaustion to a DecodeError. Packed decode calls it once
// before the fill loop to pre-size the array (mirrors the C++ decoder's up-front `allocate_array`).
void emit_reserve(Printer& printer, const std::string& acc, const std::string& count) {
    printer.print(
        "$acc$.reserve($c$).map_err(|_| "
        "::rapidproto::DecodeError::new(::rapidproto::ErrorKind::ArenaExhausted, 0))?;\n",
        {{"acc", acc}, {"c", count}});
}

// Advance the slice `at.src` past the current field via `skip_field`, given its raw tag key `key`,
// erroring at `at.off`. The loop's `_` catch-all passes `rp_tagkey`: the peek hub dispatches on the raw
// key, so an unknown or wrong-wire field reaches here with only the key (no rebuilt Tag), and
// `skip_field` reconstructs the wire type -- rejecting a malformed one-byte tag (field 0 / reserved
// wire code) as InvalidTag, the kind a full tag read would have raised. A threading probe (a stream
// decoder's unselected field, an arena decoder's dropped field) passes its field's constant key, for
// which `skip_field` folds to that wire type's skip.
void emit_skip_field_body(Printer& printer, const ReadAt& at,
                          const std::string& key = "rp_tagkey") {
    printer.print("$s$ = match ::rapidproto::wire::skip_field($s$, $k$) {\n",
                  {{"s", at.src}, {"k", key}});
    emit_read_arms(printer, at.off);
}

// Emit the field loop's one-byte peek hub: read the next tag's raw key into `rp_tagkey` (u32), or
// `break` at end of the slice `at.src`. A one-byte tag (high bit clear) becomes the key directly after
// bumping the slice past it -- no Tag built and no field/wire validation (a malformed one-byte tag
// flows to the `_` arm's `skip_field`, which rejects it); a multi-byte tag goes through the fused
// `read_tag` and is rebuilt as `(field << 3) | wire`. The caller then `match`es `rp_tagkey` against
// each field's raw key (see `raw_tag_key`). `tag` is the scratch Tag local (`rp_tag` / `rp_etag`);
// `at.off` is the body-relative error offset for a malformed multi-byte tag.
void emit_peek_hub(Printer& printer, const ReadAt& at, const std::string& tag) {
    printer.print("let rp_b = match $s$.first() {\n", {{"s", at.src}});
    printer.indent();
    printer.print("::core::option::Option::Some(&rp_b) => rp_b,\n");
    printer.print("::core::option::Option::None => break,\n");
    printer.outdent();
    printer.print("};\n");
    printer.print("let rp_tagkey: u32 = if rp_b < 0x80 {\n");
    printer.indent();
    printer.print("$s$ = &$s$[1..];\n", {{"s", at.src}});
    printer.print("rp_b as u32\n");  // a lossless widening; `u32::from` needs the prelude's `From`
    printer.outdent();
    printer.print("} else {\n");
    printer.indent();
    printer.print(
        "let mut $t$ = ::rapidproto::wire::Tag { field: 0, wire: "
        "::rapidproto::wire::WireType::Varint };\n",
        {{"t", tag}});
    printer.print("$s$ = match ::rapidproto::wire::read_tag($s$, &mut $t$) {\n",
                  {{"s", at.src}, {"t", tag}});
    emit_read_arms(printer, at.off);
    printer.print("($t$.field << 3) | $t$.wire as u32\n", {{"t", tag}});
    printer.outdent();
    printer.print("};\n");
}

// Emit the packed (length-delimited run) arm for a repeated numeric field, pre-sizing the
// accumulator from the span before the fill -- the Rust mirror of the C++ decoder's standalone
// `emit_packed_fill` (src/arenagen/generator.cpp). Varint elements reserve the span's byte length as
// an element upper bound (each varint is >= 1 byte), fill, then trim the over-estimate back to the
// exact count (`shrink_to_fit`). Fixed-width elements reserve the exact count (span / width); on a
// little-endian host a whole-multiple span fills in one bulk copy (`extend_from_le_bytes`, the span
// IS the native byte image), else a per-element read reports an exact truncation error.
// Body of the packed (length-delimited run) decode for a repeated numeric field (no arm wrapper),
// shared by the hub `(n,Len)` arm and the threaded prologue's packed probe.
void emit_packed_body(Printer& printer, const NameTable& table, const FieldNode& field) {
    const std::string acc = "rp_acc_" + std::to_string(field.number);
    const std::string wire = scalar_wire_variant(field);
    const std::string conv = scalar_convert_expr(table, field);
    emit_len_read(printer, loop_read());
    if (wire == "Varint") {
        // Packed varint: the width-classified SWAR kernel (large spans) / scalar loop (small) reserves
        // the element upper bound, fills, and trims -- the Rust mirror of the C++ decoder's
        // `decode_packed_varints`. `$off$` is the span's byte offset in the body; the kernel adds the
        // offset of a malformed varint within the span. `conv` reads the raw value named `rp_v`.
        printer.print("$acc$.fill_packed_varints(rp_p, $off$, |rp_v| $conv$)?;\n",
                      {{"acc", acc}, {"off", packed_read().off}, {"conv", conv}});
    } else {
        const std::string width = wire == "I32" ? "4" : "8";
        printer.print("if ::core::cfg!(target_endian = \"little\") && rp_p.len() % $w$ == 0 {\n",
                      {{"w", width}});
        printer.indent();
        printer.print(
            "$acc$.extend_from_le_bytes(rp_p).map_err(|_| "
            "::rapidproto::DecodeError::new(::rapidproto::ErrorKind::ArenaExhausted, 0))?;\n",
            {{"acc", acc}});
        printer.outdent();
        printer.print("} else {\n");
        printer.indent();
        emit_reserve(printer, acc, "rp_p.len() / " + width);
        printer.print("while !rp_p.is_empty() {\n");
        printer.indent();
        emit_scalar_value_read(printer, field, packed_read());
        emit_push(printer, acc, conv);
        printer.outdent();
        printer.print("}\n");
        printer.outdent();
        printer.print("}\n");
    }
}

// Emit the packed arm for a repeated numeric field (body shared with the threaded prologue). Pre-sizes
// the accumulator from the span before the fill -- the Rust mirror of the C++ decoder's standalone
// `emit_packed_fill`.
void emit_packed_arm(Printer& printer, const NameTable& table, const FieldNode& field) {
    printer.print("$k$ => {\n", {{"k", raw_tag_key(field.number, "Len")}});
    printer.indent();
    emit_packed_body(printer, table, field);
    printer.outdent();
    printer.print("}\n");
}

// Body of one repeated-field element decode (no arm wrapper): read ONE native element and push it into
// the accumulator -- a numeric value, a string/bytes payload, or a sub-message decoded into the growable
// slot. Shared by the hub arm and the threaded prologue's element self-loop (both read `rp_rest` via
// `loop_read()`), so the element decode cannot drift.
void emit_repeated_native_body(Printer& printer, const NameTable& table, const FieldNode& field) {
    const std::string acc = "rp_acc_" + std::to_string(field.number);
    if (field.is_message_type) {
        const std::string path = message_path(table, field.resolved_type_fqn);
        emit_msg_payload_read(printer, field, loop_read());
        printer.print(
            "$acc$.emplace(|rp_out| $p$::rp_decode_into(rp_out, rp_p, rp_arena, rp_depth + 1))?;\n",
            {{"acc", acc}, {"p", path}});
        return;
    }
    const std::string wire = scalar_wire_variant(field);
    const std::string conv = scalar_convert_expr(table, field);
    if (wire == "Len") {
        emit_len_read(printer, loop_read());
    } else {
        emit_scalar_value_read(printer, field, loop_read());
    }
    emit_push(printer, acc, conv);
}

// The decode-body local holding a singular field's value until the construct stores it under the
// field's accessor name. `rp_`-named like every decode-body name, so no field name -- `Some`, which as
// a binding would be the prelude variant's pattern, or a decode parameter's -- can clash with one.
std::string field_local(const FieldNode& field) {
    return "rp_field_" + std::to_string(field.number);
}

// The decode-body accumulator of a map field's entries.
std::string map_local(const MapFieldNode& map) {
    return "rp_map_" + std::to_string(map.number);
}

// Body of a singular (non-repeated) MATERIALIZED message decode (no arm wrapper): reject a second
// occurrence, read the LEN payload, decode it in place -- by value into inline storage
// (`decode_value`, no alloc, presence = a mask bit) if the planner inlined it, else into an arena slot
// behind a pointer (`emplace`, presence = `Option` is `Some`) -- and record presence/required. Shared
// by the hub `(n,Len)` arm and the threaded prologue; both operate on `rp_rest` (`loop_read()`), so the
// body is identical either way.
void emit_singular_message_body(Printer& printer, const NameTable& table, const FieldNode& field,
                                bool required, const arenagen::MemberPlan* member, int mask_bits) {
    const std::string local = field_local(field);
    const std::string nstr = std::to_string(field.number);
    const std::string path = message_path(table, field.resolved_type_fqn);
    const bool inlined = rust_store(member, field) == RustStore::InlineMsg;
    const bool inlined_masked =
        inlined && member->presence_bit >= 0;  // Explicit: mask-bit presence
    // Duplicate-singular-message rejection tests "already seen": an Explicit inlined message by its
    // mask presence bit, a Required inlined message by its transient `rp_req_<n>` flag (it has no
    // resting bit), and a pointer message by its `Option` being `Some`.
    std::string seen;
    if (inlined_masked) {
        seen = mask_test("rp_presence", member->presence_bit, mask_bits);
    } else if (inlined) {
        seen = "rp_req_" + nstr;
    } else {
        seen = local + ".is_some()";
    }
    printer.print("if $s$ {\n", {{"s", seen}});
    printer.indent();
    printer.print(
        "return ::core::result::Result::Err(::rapidproto::DecodeError::new("
        "::rapidproto::ErrorKind::RepeatedSingularMessage, $off$).with_field($n$));\n",
        {{"off", kLoopOff}, {"n", nstr}});
    printer.outdent();
    printer.print("}\n");
    emit_msg_payload_read(printer, field, loop_read());
    if (inlined) {
        // Decode by value directly into the inline storage slot (no arena alloc, no pointer).
        printer.print(
            "$l$ = ::rapidproto::decode_value(|rp_out| $p$::rp_decode_into(rp_out, rp_p, rp_arena, "
            "rp_depth + 1))?;\n",
            {{"l", local}, {"p", path}});
        if (inlined_masked) {
            // Explicit: record presence in the mask. (Required has no resting bit -- `rp_req_<n>`
            // below both rejects a duplicate and drives the post-loop MissingRequired check.)
            printer.print("$w$ |= 1 << $b$;\n",
                          {{"w", mask_word_at("rp_presence", member->presence_bit, mask_bits)},
                           {"b", std::to_string(mask_bit_pos(member->presence_bit, mask_bits))}});
        }
    } else {
        // Decode directly into its arena slot (no by-value copy).
        printer.print(
            "$l$ = ::core::option::Option::Some(rp_arena.emplace(|rp_out| "
            "$p$::rp_decode_into(rp_out, rp_p, rp_arena, rp_depth + 1))?);\n",
            {{"l", local}, {"p", path}});
    }
    if (required) {
        printer.print("rp_req_$n$ = true;\n", {{"n", nstr}});
    }
}

// Emit the `(n, Len) => { .. }` arm for a singular materialized message field (body shared with the
// threaded prologue). A second occurrence is rejected (matching C++).
void emit_singular_message_arm(Printer& printer, const NameTable& table, const FieldNode& field,
                               bool required, const arenagen::MemberPlan* member, int mask_bits) {
    printer.print("$k$ => {\n", {{"k", raw_tag_key(field.number, message_field_wire(field))}});
    printer.indent();
    emit_singular_message_body(printer, table, field, required, member, mask_bits);
    printer.outdent();
    printer.print("}\n");
}

// Read a singular scalar/enum/string/bytes/bool VALUE at `at` and store it into the field's local per
// the field's layout: a bare value, a masked value + presence bit, or a bool packed into value (and,
// if explicit, presence) mask bits. Then set the proto2 `required` seen-flag. Shared by the general
// match arm and the threaded prologue so the two cannot drift on storage semantics;
// `member`/`mask_bits` drive the presence/bool mask.
void emit_singular_scalar_store(Printer& printer, const NameTable& table, const FieldNode& field,
                                bool required, const arenagen::MemberPlan* member, int mask_bits,
                                const ReadAt& at) {
    const std::string local = field_local(field);
    // A string/bytes local holds the slice it read (see `slice_local`).
    const std::string conv = slice_local(field) ? "rp_p" : scalar_convert_expr(table, field);
    const auto set_bit = [&](int bit) {
        return mask_word_at("rp_presence", bit, mask_bits) + " |= 1 << " +
               std::to_string(mask_bit_pos(bit, mask_bits)) + ";\n";
    };
    const auto clear_bit = [&](int bit) {
        return mask_word_at("rp_presence", bit, mask_bits) + " &= !(1 << " +
               std::to_string(mask_bit_pos(bit, mask_bits)) + ");\n";
    };
    if (scalar_wire_variant(field) == "Len") {
        emit_len_read(printer, at);
    } else {
        emit_scalar_value_read(printer, field, at);
    }
    switch (rust_store(member, field)) {
        case RustStore::MaskedBool:
            // The bool value is a mask bit (no byte field): set it from the varint (clear on false, so
            // a later `false` overrides an earlier `true`); Explicit also records the presence bit.
            printer.print("if rp_v != 0 {\n");
            printer.indent();
            printer.print(set_bit(member->value_bit));
            printer.outdent();
            printer.print("} else {\n");
            printer.indent();
            printer.print(clear_bit(member->value_bit));
            printer.outdent();
            printer.print("}\n");
            if (member->presence_bit >= 0) {
                printer.print(set_bit(member->presence_bit));
            }
            break;
        case RustStore::MaskedValue:
            printer.print("$l$ = $c$;\n", {{"l", local}, {"c", conv}});
            printer.print(set_bit(member->presence_bit));
            break;
        case RustStore::Bare:
        case RustStore::InlineMsg:
        case RustStore::PointerMsg:
            printer.print("$l$ = $c$;\n", {{"l", local}, {"c", conv}});
            break;
    }
    if (required) {
        printer.print("rp_req_$n$ = true;\n", {{"n", std::to_string(field.number)}});
    }
}

// Emit the `match rp_tagkey` arm(s) for one field, keyed by its raw tag `field << 3 | wire`: one arm
// for a singular value, two for a repeated numeric (unpacked + packed), reading via the value-threaded
// wire primitives and storing
// into the field's local (field_local) or pushing into its accumulator (`rp_acc_<n>`). A singular
// message is decoded in place (see emit_singular_message_arm); a repeated message's element is decoded
// into the growable array slot. A singular message seen twice is rejected (matching C++).
void emit_field_arms(Printer& printer, const NameTable& table, const FieldNode& field,
                     bool required, const FieldModes& modes, const arenagen::MemberPlan* member,
                     int mask_bits) {
    const std::string nstr = std::to_string(field.number);
    const std::string acc = "rp_acc_" + nstr;

    const arenagen::FieldMode mode = field_mode(modes, field);
    if (mode == arenagen::FieldMode::Drop) {
        // A dropped field gets no arm: it falls to the loop's `_` catch-all, which skips it. Its
        // number is still in the catch-all's known-number set, so (in an unknown-tracked message) it
        // never trips the unknown-fields bit -- matching the old explicit `(n, _)` known-skip arm.
        return;
    }
    if (mode == arenagen::FieldMode::Raw) {
        // A message field kept as its undecoded payload bytes (no recursion): the LEN payload, or -- for
        // a proto2 group field -- the scanned group body via `read_group` (dispatched on the SGroup
        // key). Singular rejects a second occurrence like a materialized singular message; repeated
        // pushes each payload.
        printer.print("$k$ => {\n", {{"k", raw_tag_key(field.number, message_field_wire(field))}});
        printer.indent();
        if (field.is_repeated) {
            emit_msg_payload_read(printer, field, loop_read());
            emit_push(printer, acc, "::rapidproto::ProtoBytes::new_truncating(rp_p)");
        } else {
            const std::string local = field_local(field);
            printer.print("if $l$.is_some() {\n", {{"l", local}});
            printer.indent();
            printer.print(
                "return ::core::result::Result::Err(::rapidproto::DecodeError::new("
                "::rapidproto::ErrorKind::RepeatedSingularMessage, $off$).with_field($n$));\n",
                {{"off", kLoopOff}, {"n", nstr}});
            printer.outdent();
            printer.print("}\n");
            emit_msg_payload_read(printer, field, loop_read());
            printer.print("$l$ = ::core::option::Option::Some(rp_p);\n", {{"l", local}});
            if (required) {
                printer.print("rp_req_$n$ = true;\n", {{"n", nstr}});
            }
        }
        printer.outdent();
        printer.print("}\n");
        return;
    }

    if (field.is_message_type && !field.is_repeated) {
        emit_singular_message_arm(printer, table, field, required, member, mask_bits);
        return;
    }
    if (field.is_message_type && field.is_repeated) {
        printer.print("$k$ => {\n", {{"k", raw_tag_key(field.number, message_field_wire(field))}});
        printer.indent();
        emit_repeated_native_body(printer, table, field);  // one element -> array slot
        printer.outdent();
        printer.print("}\n");
        return;
    }

    const std::string wire = scalar_wire_variant(field);
    if (is_packable_repeated(field)) {
        // Repeated numeric: an unpacked arm (one value per occurrence) and a packed arm (a
        // length-delimited run of values). proto permits mixing both on the wire.
        printer.print("$k$ => {\n", {{"k", raw_tag_key(field.number, wire)}});
        printer.indent();
        emit_repeated_native_body(printer, table, field);
        printer.outdent();
        printer.print("}\n");
        emit_packed_arm(printer, table, field);
        return;
    }
    if (field.is_repeated) {  // repeated string/bytes (wire == Len, not packable)
        printer.print("$k$ => {\n", {{"k", raw_tag_key(field.number, "Len")}});
        printer.indent();
        emit_repeated_native_body(printer, table, field);
        printer.outdent();
        printer.print("}\n");
        return;
    }
    // Singular scalar / enum / string / bytes.
    printer.print("$k$ => {\n", {{"k", raw_tag_key(field.number, wire)}});
    printer.indent();
    emit_singular_scalar_store(printer, table, field, required, member, mask_bits, loop_read());
    printer.outdent();
    printer.print("}\n");
}

// A map entry is a sub-message with field 1 = key, field 2 = value; synthesize the two `FieldNode`s so
// the scalar/message read + convert + storage-type helpers apply unchanged. Keys are always scalar.
FieldNode map_key_field(const MapFieldNode& map) {
    FieldNode f;
    f.name = "key";
    f.type_name = map.key_type;
    f.number = 1;
    f.presence = FieldPresence::Implicit;
    return f;
}
FieldNode map_value_field(const MapFieldNode& map) {
    FieldNode f;
    f.name = "value";
    f.type_name = map.value_type;
    f.number = 2;
    f.presence = FieldPresence::Implicit;
    f.resolved_type_fqn = map.resolved_value_type_fqn;
    f.is_message_type = map.value_is_message;
    f.is_enum_type = map.value_is_enum;
    return f;
}

// Emit the match arm for one oneof member field: read its value and set the oneof's local to
// `Some(<Enum>::<Variant>(value))`. The last tag wins -- the slot simply overwrites -- EXCEPT a message
// member seen while the oneof already holds THAT member is rejected (`RepeatedSingularMessage`): two
// occurrences of the same sub-message would be merged by protobuf, which a read-only tree cannot do, so
// last-wins there would hand back a value differing from protobuf (matching the C++ decoder and the
// singular-message-field / map-value rules). An intervening different member clears the slot, so that
// later occurrence starts fresh and keeps the plain last-wins. `enum_path` is the path to the oneof's
// enum; a message variant carries a borrowed `&'a T` (arena-allocated).
// Body of one oneof member decode (no arm wrapper), shared by the hub arm and the threaded prologue
// (both read from `rp_rest` via `loop_read()`).
void emit_oneof_body(Printer& printer, const NameTable& table, const FieldNode& field,
                     const std::string& oneof_local, const std::string& enum_path,
                     const std::string& variant) {
    const std::string nstr = std::to_string(field.number);
    if (field.is_message_type) {
        const std::string path = message_path(table, field.resolved_type_fqn);
        printer.print("if ::core::matches!($l$, ::core::option::Option::Some($e$::$v$(_))) {\n",
                      {{"l", oneof_local}, {"e", enum_path}, {"v", variant}});
        printer.indent();
        printer.print(
            "return ::core::result::Result::Err(::rapidproto::DecodeError::new("
            "::rapidproto::ErrorKind::RepeatedSingularMessage, $off$).with_field($n$));\n",
            {{"off", kLoopOff}, {"n", nstr}});
        printer.outdent();
        printer.print("}\n");
        emit_msg_payload_read(printer, field, loop_read());
        // Decode the oneof's message member directly into its arena slot (no by-value copy).
        printer.print(
            "let rp_ptr = rp_arena.emplace(|rp_out| $p$::rp_decode_into(rp_out, rp_p, rp_arena, "
            "rp_depth "
            "+ 1))?;\n",
            {{"p", path}});
        printer.print("$l$ = ::core::option::Option::Some($e$::$v$(rp_ptr));\n",
                      {{"l", oneof_local}, {"e", enum_path}, {"v", variant}});
        return;
    }
    const std::string wire = scalar_wire_variant(field);
    const std::string conv = scalar_convert_expr(table, field);
    if (wire == "Len") {
        emit_len_read(printer, loop_read());
    } else {
        emit_scalar_value_read(printer, field, loop_read());
    }
    printer.print("$l$ = ::core::option::Option::Some($e$::$v$($c$));\n",
                  {{"l", oneof_local}, {"e", enum_path}, {"v", variant}, {"c", conv}});
}

// Emit the match arm for one oneof member field: read its value and set the oneof's local to
// `Some(<Enum>::<Variant>(value))`. The last tag wins -- the slot simply overwrites -- EXCEPT a message
// member seen while the oneof already holds THAT member is rejected (`RepeatedSingularMessage`): two
// occurrences of the same sub-message would be merged by protobuf, which a read-only tree cannot do, so
// last-wins there would hand back a value differing from protobuf (matching the C++ decoder and the
// singular-message-field / map-value rules). An intervening different member clears the slot, so that
// later occurrence starts fresh and keeps the plain last-wins. `enum_path` is the path to the oneof's
// enum; a message variant carries a borrowed `&'a T` (arena-allocated).
void emit_oneof_arm(Printer& printer, const NameTable& table, const FieldNode& field,
                    const std::string& oneof_local, const std::string& enum_path,
                    const std::string& variant) {
    const std::string wire =
        field.is_message_type ? message_field_wire(field) : scalar_wire_variant(field);
    printer.print("$k$ => {\n", {{"k", raw_tag_key(field.number, wire)}});
    printer.indent();
    emit_oneof_body(printer, table, field, oneof_local, enum_path, variant);
    printer.outdent();
    printer.print("}\n");
}

// Emit the key (field 1) or value (field 2) arm inside a map entry loop, reading into `local` (`rp_key`
// / `rp_val`) at `at` (entry-relative offsets). A message value is decoded by value and, seen twice in
// one entry, rejected (`RepeatedSingularMessage`, keyed to the map field `map_number`) -- matching C++;
// a scalar key/value silently last-wins.
void emit_map_component(Printer& printer, const NameTable& table, const FieldNode& field,
                        const std::string& local, const ReadAt& at, std::int32_t map_number) {
    if (field.is_message_type) {  // the value field; held in an `Option` (None = not yet seen)
        const std::string path = message_path(table, field.resolved_type_fqn);
        printer.print("$k$ => {\n", {{"k", raw_tag_key(field.number, "Len")}});
        printer.indent();
        printer.print("if $l$.is_some() {\n", {{"l", local}});
        printer.indent();
        printer.print(
            "return ::core::result::Result::Err(::rapidproto::DecodeError::new("
            "::rapidproto::ErrorKind::RepeatedSingularMessage, $o$).with_field($m$));\n",
            {{"o", at.off}, {"m", std::to_string(map_number)}});
        printer.outdent();
        printer.print("}\n");
        emit_len_read(printer, at);
        // Map value message is stored by value in the entry's `Option`; `decode_value` runs the
        // destination-slot decode and moves the result out (its `unsafe` stays in the runtime).
        printer.print(
            "$l$ = ::core::option::Option::Some(::rapidproto::decode_value(|rp_out| "
            "$p$::rp_decode_into(rp_out, rp_p, rp_arena, rp_depth + 1))?);\n",
            {{"l", local}, {"p", path}});
        printer.outdent();
        printer.print("}\n");
        return;
    }
    const std::string wire = scalar_wire_variant(field);
    const std::string conv = scalar_convert_expr(table, field);
    printer.print("$k$ => {\n", {{"k", raw_tag_key(field.number, wire)}});
    printer.indent();
    if (wire == "Len") {
        emit_len_read(printer, at);
    } else {
        emit_scalar_value_read(printer, field, at);
    }
    printer.print("$l$ = $c$;\n", {{"l", local}, {"c", conv}});
    printer.outdent();
    printer.print("}\n");
}

// Body of one map ENTRY decode (no arm wrapper): read the length-delimited entry, decode its key/value
// in an inner loop (unknown entry fields skipped), and push `(key, value)` into the map's `DecodeVec`.
// The entry is its own decode frame -- offsets inside it are entry-relative (matching C++'s map
// re-anchor). Shared by the hub `(n,Len)` arm and the threaded prologue's map self-loop; both read the
// entry from `rp_rest` (`loop_read()`), so one call decodes exactly one entry.
void emit_map_body(Printer& printer, const NameTable& table, const MapFieldNode& map) {
    const FieldNode key = map_key_field(map);
    const FieldNode val = map_value_field(map);
    const ReadAt entry_at{"rp_ent", "rp_ent_body.len() - rp_ent.len()"};
    emit_len_read(printer, loop_read());  // the entry payload -> rp_p
    printer.print("let rp_ent_body: &'a [u8] = rp_p;\n");
    printer.print("let mut rp_key: $t$ = $d$;\n", {{"t", field_value_type(table, key)},
                                                   {"d", field_default_expr(table, key, nullptr)}});
    // A message value is stored by value (no `Option`), so it is accumulated in an `Option` here --
    // `None` until seen -- and filled with the default (empty) message if the entry omits field 2.
    if (val.is_message_type) {
        printer.print(
            "let mut rp_val: ::core::option::Option<$t$> = ::core::option::Option::None;\n",
            {{"t", field_value_type(table, val)}});
    } else {
        printer.print(
            "let mut rp_val: $t$ = $d$;\n",
            {{"t", field_value_type(table, val)}, {"d", field_default_expr(table, val, nullptr)}});
    }
    printer.print("let mut rp_ent: &'a [u8] = rp_ent_body;\n");
    printer.print("loop {\n");
    printer.indent();
    emit_peek_hub(printer, entry_at, "rp_etag");
    printer.print("match rp_tagkey {\n");
    printer.indent();
    emit_map_component(printer, table, key, "rp_key", entry_at, map.number);
    emit_map_component(printer, table, val, "rp_val", entry_at, map.number);
    printer.print("_ => {\n");
    printer.indent();
    emit_skip_field_body(printer, entry_at);
    printer.outdent();
    printer.print("}\n");
    printer.outdent();
    printer.print("}\n");  // match
    printer.outdent();
    printer.print("}\n");  // loop
    if (val.is_message_type) {
        // An entry that omitted field 2 gets the default (empty) message. (On non-protoc input where
        // the value message has `required` fields, this empty decode surfaces MissingRequired rather
        // than C++'s zero-init; protoc always serializes field 2, so protoc-valid input is unaffected.)
        const std::string path = message_path(table, val.resolved_type_fqn);
        printer.print("let rp_val = match rp_val {\n");
        printer.indent();
        printer.print("::core::option::Option::Some(rp_sub) => rp_sub,\n");
        printer.print(
            "::core::option::Option::None => ::rapidproto::decode_value(|rp_out| "
            "$p$::rp_decode_into(rp_out, &[], rp_arena, rp_depth + 1))?,\n",
            {{"p", path}});
        printer.outdent();
        printer.print("};\n");
    }
    emit_push(printer, map_local(map), "(rp_key, rp_val)");
}

// Emit the match arm for one map field (body shared with the threaded prologue's map self-loop).
void emit_map_arm(Printer& printer, const NameTable& table, const MapFieldNode& map) {
    printer.print("$k$ => {\n", {{"k", raw_tag_key(map.number, "Len")}});
    printer.indent();
    emit_map_body(printer, table, map);
    printer.outdent();
    printer.print("}\n");
}

// Emit `decode()` + the `rp_decode_into()` worker for a decodable message: a field loop over `rp_body`
// driven by a one-byte peek hub (`emit_peek_hub`) that reads each tag's raw key into `rp_tagkey`, then
// `match rp_tagkey` to read each known regular / oneof-member / map field by its `field << 3 | wire`
// key (a wrong wire type for a known field falls to `skip_field`, like an unknown field), accumulating
// repeated fields and maps in `DecodeVec`s and recursing into sub-messages, then constructing the
// message (checking proto2 `required` fields were all seen). `rp_decode_into` is visible to the whole
// arena tree, so sub-messages in other modules can recurse into it.
// The decode locals: a repeated field / map accumulates into a `DecodeVec`; a oneof holds its enum
// (None until a member is seen); a proto2 `required` field a transient seen-flag; `unknown-fields` a
// bool; the rest plain values at their proto3 zero / None default. A dropped field/map has no local
// (it is skip-validated and discarded).
void emit_decode_locals(Printer& printer, const NameTable& table, const MessageNode& msg,
                        const FieldModes& modes, const arenagen::MessageLayout* layout) {
    const int mask_bits = layout != nullptr ? rust_mask_bits(*layout) : 0;
    if (mask_bits > 0) {
        // The presence/bool mask, built up as fields decode and stored in the construct.
        printer.print("let mut rp_presence: $t$ = $z$;\n",
                      {{"t", mask_word_type(mask_bits)}, {"z", mask_zero(mask_bits)}});
    }
    for (const FieldNode& field : msg.fields) {
        if (field_mode(modes, field) == arenagen::FieldMode::Drop) {
            continue;
        }
        const arenagen::MemberPlan* member = member_for(layout, field);
        if (field.is_repeated) {
            printer.print("let mut rp_acc_$n$ = ::rapidproto::DecodeVec::new(rp_arena);\n",
                          {{"n", std::to_string(field.number)}});
        } else if (rust_store(member, field) != RustStore::MaskedBool) {
            // A packed bool has no local -- its value and presence live entirely in the mask. A
            // string/bytes local holds the plain slice (see `slice_local`) and a raw field's local
            // the payload slice, `None` while absent; the construct packs either into its cell.
            std::string type;
            std::string init;
            if (slice_local(field)) {
                type = "&'a [u8]";
                init = "&[]";
            } else if (field_mode(modes, field) == arenagen::FieldMode::Raw) {
                type = "::core::option::Option<&'a [u8]>";
                init = "::core::option::Option::None";
            } else {
                type = field_storage_type(table, field, modes, member);
                init = field_default_expr(table, field, member);
            }
            printer.print("let mut $l$: $t$ = $d$;\n",
                          {{"l", field_local(field)}, {"t", type}, {"d", init}});
        }
        if (field.presence == FieldPresence::Required) {
            printer.print("let mut rp_req_$n$ = false;\n", {{"n", std::to_string(field.number)}});
        }
    }
    if (modes.wants_unknown(&msg)) {
        printer.print("let mut rp_unknown = false;\n");  // set by the unknown-field catch-all
    }
    for (const MapFieldNode& map : msg.map_fields) {
        if (map_mode(modes, map) != arenagen::FieldMode::Drop) {
            printer.print("let mut $l$ = ::rapidproto::DecodeVec::new(rp_arena);\n",
                          {{"l", map_local(map)}});
        }
    }
    for (std::size_t i = 0; i < msg.oneofs.size(); ++i) {
        printer.print(
            "let mut rp_oneof_$i$: $t$ = ::core::option::Option::None;\n",
            {{"i", std::to_string(i)}, {"t", oneof_storage_type(table, msg, msg.oneofs[i])}});
    }
}

// The `match rp_tagkey` arm for every regular / map / oneof-member field (keyed by its raw tag
// `field << 3 | wire`), then a `_` catch-all that skips anything else. A dropped field/map gets no
// arm -- it falls to the catch-all and is skipped like an unknown field. The catch-all reconstructs
// and skips via `skip_field` (the peek hub handed it only the raw key). In an unknown-tracked message
// the catch-all first routes on the field NUMBER (`rp_tagkey >> 3`): a declared number (a kept or
// dropped field/map/oneof member arriving with the wrong wire type) is skipped silently, an undeclared
// one trips the unknown-fields bit -- matching C++ (which flags only unrecognized field numbers, never
// a known number with a wrong wire type).
void emit_decode_arms(Printer& printer, const NameTable& table, const MessageNode& msg,
                      const FieldModes& modes, const arenagen::MessageLayout* layout) {
    const bool wants_unknown = modes.wants_unknown(&msg);
    const int mask_bits = layout != nullptr ? rust_mask_bits(*layout) : 0;
    // Every declared field number (regular -- kept OR dropped -- plus map and oneof-member numbers)
    // as an or-pattern: the set the catch-all treats as "known" so a wrong-wire occurrence never trips
    // the unknown bit. Built only for an unknown-tracked message (unused otherwise).
    std::string known_numbers;
    const auto note_known = [&](std::int64_t number) {
        if (!known_numbers.empty()) {
            known_numbers += " | ";
        }
        known_numbers += std::to_string(number) + "u32";
    };
    for (const FieldNode& field : msg.fields) {
        emit_field_arms(printer, table, field, field.presence == FieldPresence::Required, modes,
                        member_for(layout, field), mask_bits);
        note_known(field.number);
    }
    for (const MapFieldNode& map : msg.map_fields) {
        if (map_mode(modes, map) != arenagen::FieldMode::Drop) {
            emit_map_arm(printer, table, map);
        }
        note_known(map.number);
    }
    for (std::size_t i = 0; i < msg.oneofs.size(); ++i) {
        const OneofNode& oneof = msg.oneofs[i];
        const std::string enum_path = oneof_path(table, msg, oneof);
        const std::vector<std::string> variants = oneof_variant_names(oneof);
        const std::string local = "rp_oneof_" + std::to_string(i);
        for (std::size_t j = 0; j < oneof.fields.size(); ++j) {
            emit_oneof_arm(printer, table, oneof.fields[j], local, enum_path, variants[j]);
            note_known(oneof.fields[j].number);
        }
    }
    printer.print("_ => {\n");
    printer.indent();
    if (wants_unknown) {
        // A declared field number with a wrong wire type is still "known" (skip, no bit); only an
        // undeclared number trips the unknown bit. The `_` arm cannot pattern out the field bits of a
        // single key, so route on `rp_tagkey >> 3` in the cold catch-all. A fieldless message has no
        // known numbers, so every field on the wire is unknown -- set the bit unconditionally (an empty
        // `matches!(.., )` pattern is a Rust syntax error).
        if (known_numbers.empty()) {
            printer.print("rp_unknown = true;\n");
        } else {
            printer.print("if !::core::matches!(rp_tagkey >> 3, $k$) {\n", {{"k", known_numbers}});
            printer.indent();
            printer.print("rp_unknown = true;\n");  // a genuinely unknown field number was seen
            printer.outdent();
            printer.print("}\n");
        }
    }
    emit_skip_field_body(printer, loop_read());
    printer.outdent();
    printer.print("}\n");
}

// The `Ok(Msg { .. })` construct from the decode locals; a dropped field/map contributes no storage,
// `unknown-fields` the bit, and a message with no `'a`-using field the `PhantomData` marker.
void emit_decode_construct(Printer& printer, const MessageNode& msg, const FieldModes& modes,
                           const AccessorNames& accessors, const arenagen::MessageLayout* layout) {
    // Construct the message directly into the caller's slot (`Slot::write` is safe -- no `unsafe` in
    // generated code) and return the `Init` proof it yields, so LLVM builds the struct in place and
    // the caller's `emplace`/`decode_value` needs no init-on-trust. Mirrors the C++ decoder writing
    // fields straight into `out`.
    printer.print("::core::result::Result::Ok(rp_out.write($M$ {\n");
    printer.indent();
    for (std::size_t i = 0; i < msg.fields.size(); ++i) {
        const FieldNode& field = msg.fields[i];
        if (field_mode(modes, field) == arenagen::FieldMode::Drop) {
            continue;
        }
        if (field.is_repeated) {
            printer.print("$a$: ::rapidproto::PackedSlice::new(rp_acc_$n$.into_slice()),\n",
                          {{"a", accessors.fields[i]}, {"n", std::to_string(field.number)}});
        } else if (rust_store(member_for(layout, field), field) != RustStore::MaskedBool) {
            // A packed bool contributes no struct field (its value/presence are in `rp_presence`). A
            // string/bytes/raw local is packed here (see `slice_local`).
            const char* fmt = "$a$: $l$,\n";
            if (slice_local(field)) {
                fmt = field.type_name == "string"
                          ? "$a$: ::rapidproto::ProtoStr::new_truncating($l$),\n"
                          : "$a$: ::rapidproto::ProtoBytes::new_truncating($l$),\n";
            } else if (field_mode(modes, field) == arenagen::FieldMode::Raw) {
                fmt = "$a$: $l$.map(::rapidproto::ProtoBytes::new_truncating),\n";
            }
            printer.print(fmt, {{"a", accessors.fields[i]}, {"l", field_local(field)}});
        }
    }
    if (layout != nullptr && rust_mask_bits(*layout) > 0) {
        printer.print("rp_presence,\n");  // the packed presence/bool mask
    }
    for (std::size_t i = 0; i < msg.map_fields.size(); ++i) {
        if (map_mode(modes, msg.map_fields[i]) != arenagen::FieldMode::Drop) {
            printer.print("$a$: ::rapidproto::MapView::new($l$.into_slice()),\n",
                          {{"a", accessors.maps[i]}, {"l", map_local(msg.map_fields[i])}});
        }
    }
    for (std::size_t i = 0; i < msg.oneofs.size(); ++i) {
        printer.print("$l$: rp_oneof_$i$,\n",
                      {{"l", accessors.oneofs[i]}, {"i", std::to_string(i)}});
    }
    if (modes.wants_unknown(&msg)) {
        printer.print("rp_unknown,\n");  // the has_unknown_fields() storage
    }
    if (!message_uses_lifetime(msg, modes)) {
        printer.print("_marker: ::core::marker::PhantomData,\n");
    }
    printer.outdent();
    printer.print("}))\n");
}

// A field the threaded prologue will probe, with everything its body emitter needs. Collected across a
// message's regular fields and oneof members by `collect_threaded_items`, then emitted in ascending
// field-number order. A `Skip` item is a dropped field or map: its probe only skips the value.
enum class ThreadKind : std::uint8_t { Scalar, Message, Oneof, Repeated, Map, Skip };
struct ThreadItem {
    int number;
    ThreadKind kind;
    bool packable;     // repeated numeric: also probe its packed LEN form
    std::string wire;  // the native/singular tag's wire variant (what the probe matches)
    const FieldNode* field;
    bool required;
    const arenagen::MemberPlan* member;
    std::string oneof_local, enum_path, variant;  // oneof members only
    const MapFieldNode* map = nullptr;  // non-null for a map, kept (Map) or dropped (Skip)
};

// Whether the Rust prologues (arena and stream) can thread a repeated field, which self-loops on its
// own element tag: up to a two-byte tag (see `emit_threaded_prologue` for why that is broader than the
// C++ reference), and never a group. A group element (SGROUP/EGROUP-delimited) must NOT thread as a
// bare LEN self-loop -- it dispatches on the SGroup hub arm and reads via `read_group` -- so a repeated
// group field is excluded (mirroring arenagen's `is_threaded` "delimited never thread"); its elements
// decode through the hub.
bool is_threadable_repeated(const FieldNode& field) {
    const bool group =
        field.is_message_type && field.message_encoding == MessageEncoding::Delimited;
    return field.number >= 1 && field.number <= codegen::kMaxTwoByteTagField && !group;
}

// Whether the Rust prologues can thread a map: a repeated series of LEN entries, so it self-loops like
// a repeated field, up to a two-byte tag (<= 2047).
bool is_threadable_map(const MapFieldNode& map) {
    return map.number >= 1 && map.number <= codegen::kMaxTwoByteTagField;
}

// Append the threadable maps of `msg` to `items`; a dropped map's probe skips its entries.
void append_map_threaded_items(const MessageNode& msg, const FieldModes& modes,
                               std::vector<ThreadItem>& items) {
    for (const MapFieldNode& map : msg.map_fields) {
        if (!is_threadable_map(map)) {
            continue;
        }
        const ThreadKind kind =
            map_mode(modes, map) == arenagen::FieldMode::Drop ? ThreadKind::Skip : ThreadKind::Map;
        items.push_back(
            {map.number, kind, false, "Len", nullptr, false, nullptr, "", "", "", &map});
    }
}

// Append the threadable oneof members of `msg` to `items` (each oneof member shares the field-number
// space, so they interleave with regular fields once the caller sorts).
void append_oneof_threaded_items(const NameTable& table, const MessageNode& msg,
                                 std::vector<ThreadItem>& items) {
    for (std::size_t oi = 0; oi < msg.oneofs.size(); ++oi) {
        const OneofNode& oneof = msg.oneofs[oi];
        const std::string enum_path = oneof_path(table, msg, oneof);
        const std::vector<std::string> variants = oneof_variant_names(oneof);
        const std::string local = "rp_oneof_" + std::to_string(oi);
        for (std::size_t j = 0; j < oneof.fields.size(); ++j) {
            const FieldNode& mf = oneof.fields[j];
            if (!codegen::is_threadable_singular(mf)) {
                continue;
            }
            const std::string wire = mf.is_message_type ? "Len" : scalar_wire_variant(mf);
            items.push_back({mf.number, ThreadKind::Oneof, false, wire, &mf, false, nullptr, local,
                             enum_path, variants[j]});
        }
    }
}

// Collect the fields this message threads (see `emit_threaded_prologue` for the scope). Regular fields
// and oneof members are gathered together; the caller sorts by field number before emitting.
std::vector<ThreadItem> collect_threaded_items(const NameTable& table, const MessageNode& msg,
                                               const FieldModes& modes,
                                               const arenagen::MessageLayout* layout) {
    std::vector<ThreadItem> items;
    for (const FieldNode& f : msg.fields) {
        const arenagen::FieldMode mode = field_mode(modes, f);
        if (mode == arenagen::FieldMode::Raw) {
            continue;  // a raw field is never threaded (handled by its hub arm)
        }
        // Number out of 1..2047, or a delimited (group) message: not threadable.
        if (f.is_repeated ? !is_threadable_repeated(f) : !codegen::is_threadable_singular(f)) {
            continue;
        }
        const std::string wire = f.is_message_type ? "Len" : scalar_wire_variant(f);
        const bool packable = is_packable_repeated(f);
        if (mode == arenagen::FieldMode::Drop) {
            items.push_back(
                {f.number, ThreadKind::Skip, packable, wire, &f, false, nullptr, "", "", ""});
        } else if (f.is_repeated) {
            items.push_back(
                {f.number, ThreadKind::Repeated, packable, wire, &f, false, nullptr, "", "", ""});
        } else {
            const bool required = f.presence == FieldPresence::Required;
            const ThreadKind kind = f.is_message_type ? ThreadKind::Message : ThreadKind::Scalar;
            items.push_back(
                {f.number, kind, false, wire, &f, required, member_for(layout, f), "", "", ""});
        }
    }
    append_map_threaded_items(msg, modes, items);
    append_oneof_threaded_items(table, msg, items);
    return items;
}

// Open a threading probe: an `if`/`while` that matches the field's whole constant tag against the next
// input byte(s) and, on a match, consumes exactly that tag. `wire` is the tag's wire variant; one byte
// for field <= 15, two for 16..2047 (`b0` = low 7 bits + continuation, `b1` = next 7). The caller emits
// the body, then `emit_probe_close`.
void emit_probe_open(Printer& printer, int number, const std::string& wire, bool self_loop) {
    const std::int64_t v = raw_tag_value(number, wire);
    const char* kw = self_loop ? "while" : "if";
    if (number <= codegen::kMaxOneByteTagField) {
        printer.print("$kw$ rp_rest.first() == ::core::option::Option::Some(&$t$u8) {\n",
                      {{"kw", kw}, {"t", std::to_string(v)}});
        printer.indent();
        printer.print("rp_rest = &rp_rest[1..];\n");
    } else {
        const std::int64_t b0 = (v & codegen::kVarintPayload) | codegen::kVarintContinue;
        const std::int64_t b1 = v >> codegen::kVarintShift;
        printer.print(
            "$kw$ rp_rest.first_chunk::<2>() == ::core::option::Option::Some(&[$b0$u8, $b1$u8]) "
            "{\n",
            {{"kw", kw}, {"b0", std::to_string(b0)}, {"b1", std::to_string(b1)}});
        printer.indent();
        printer.print("rp_rest = &rp_rest[2..];\n");
    }
}

void emit_probe_close(Printer& printer) {
    printer.outdent();
    printer.print("}\n");
}

// Field-order threading: before the general peek-hub loop, probe each threadable field in field-number
// order with a cheap constant-tag compare; on a match, consume the tag and decode+store the value
// inline (via the SAME body emitters the hub arms use), then fall through to the next probe. Encoders
// write fields in ascending order, so the common case runs this straight-line chain with no tag-varint
// parse and no `match` dispatch -- the hub loop then handles only what the prologue did not consume
// (out-of-order, repeats, unknown/wrong-wire, or non-threaded fields), so correctness and last-wins
// semantics are unchanged (the prologue is a pure fast path over the SAME validated reads and stores).
// Rust has no goto, so each threaded field's body is duplicated here and in its hub arm (decode code
// grows for threaded fields); the tail-call form that would share one body relies on opportunistic TCO
// (an unbounded-stack risk on adversarial input), so the robust straight-line form is used -- the same
// choice the C++ reference makes.
//
// Scope: every singular field admitted by codegen::is_threadable_singular (scalar/enum/bool/string/
// bytes/message, one- or two-byte tag, non-group) AND oneof members likewise; plus repeated non-group
// fields and maps (one- or two-byte tag <= 2047), which self-loop on their own tag (a repeated numeric
// also probes its packed LEN form). This is BROADER than the C++ reference's is_threaded (repeated
// one-byte only; maps never): C++ re-enters threading from its hub via goto, so an unthreaded field
// mid-message costs it nothing, but Rust's straight-line prologue can't re-enter -- once it falls to
// the hub it stays there -- so leaving a map or a two-byte repeated field unthreaded would end
// threading for every later field of a well-ordered message. For the same reason a dropped field or
// map is probed by the same rules, its probe skipping the value through `skip_field` with the
// constant tag (as the stream prologue skips an unselected field); C++ leaves dropped fields to its
// hub. A well-ordered message (fields <= 2047) thus stays on the fast path end to end, except past a
// group or a raw field, which still end threading. Decoded output is unchanged either way (threading
// is a pure fast path; the hub decodes whatever the prologue did not).
void emit_threaded_prologue(Printer& printer, const NameTable& table, const MessageNode& msg,
                            const FieldModes& modes, const arenagen::MessageLayout* layout) {
    const int mask_bits = layout != nullptr ? rust_mask_bits(*layout) : 0;
    std::vector<ThreadItem> items = collect_threaded_items(table, msg, modes, layout);
    // Probe in ascending field-number order to match the typical ascending wire order.
    std::sort(items.begin(), items.end(),
              [](const ThreadItem& a, const ThreadItem& b) { return a.number < b.number; });
    for (const ThreadItem& it : items) {
        // Repeated fields and maps are a series of same-tag entries, so they self-loop (`while`);
        // singular fields and oneof members occur once (`if`).
        const bool self_loop = it.map != nullptr || it.field->is_repeated;
        emit_probe_open(printer, it.number, it.wire, self_loop);
        switch (it.kind) {
            case ThreadKind::Scalar:
                emit_singular_scalar_store(printer, table, *it.field, it.required, it.member,
                                           mask_bits, loop_read());
                break;
            case ThreadKind::Message:
                emit_singular_message_body(printer, table, *it.field, it.required, it.member,
                                           mask_bits);
                break;
            case ThreadKind::Oneof:
                emit_oneof_body(printer, table, *it.field, it.oneof_local, it.enum_path,
                                it.variant);
                break;
            case ThreadKind::Repeated:
                emit_repeated_native_body(printer, table, *it.field);
                break;
            case ThreadKind::Map:
                emit_map_body(printer, table, *it.map);
                break;
            case ThreadKind::Skip:
                emit_skip_field_body(printer, loop_read(), raw_tag_key(it.number, it.wire));
                break;
        }
        emit_probe_close(printer);
        if (it.packable) {
            // A packed run of the same field: one LEN payload. Probed once (a second run falls to the
            // hub loop).
            emit_probe_open(printer, it.number, "Len", /*self_loop=*/false);
            if (it.kind == ThreadKind::Skip) {
                emit_skip_field_body(printer, loop_read(), raw_tag_key(it.number, "Len"));
            } else {
                emit_packed_body(printer, table, *it.field);
            }
            emit_probe_close(printer);
        }
    }
}

// Reject an `input` over `u32::MAX` bytes, the most a `ProtoStr`, `ProtoBytes` or `PackedSlice` holds.
// It runs once per root, in the arena `decode` and the stream `new`. Every nested message and value is
// a part of that input, so they need no check of their own and are built unchecked.
void emit_input_size_check(Printer& printer, const std::string& input) {
    printer.print("if $i$.len() > u32::MAX as usize {\n", {{"i", input}});
    printer.indent();
    printer.print(
        "return ::core::result::Result::Err(::rapidproto::DecodeError::new("
        "::rapidproto::ErrorKind::InputTooLarge, 0));\n");
    printer.outdent();
    printer.print("}\n");
}

void emit_decode(Printer& printer, const NameTable& table, const MessageNode& msg,
                 const AccessorNames& accessors, const FieldModes& modes,
                 const arenagen::MessageLayout* layout) {
    printer.print("/// Decodes `input` into `arena` and returns the message.\n");
    printer.print(
        "pub fn decode(input: &'a [u8], arena: &'a ::rapidproto::Arena<'a>) "
        "-> ::core::result::Result<&'a $M$<'a>, ::rapidproto::DecodeError> {\n");
    printer.indent();
    emit_input_size_check(printer, "input");
    // Decode the root message directly into its final arena slot (no by-value copy), mirroring the
    // caller side of every sub-message decode below.
    printer.print(
        "let rp_root = arena.emplace(|rp_out| Self::rp_decode_into(rp_out, input, arena, 0))?;\n");
    printer.print("::core::result::Result::Ok(&*rp_root)\n");
    printer.outdent();
    printer.print("}\n\n");

    // Emulate the C++ decoder's RP_FLATTEN / RP_NOINLINE, driven by the SAME flatten-budget decision
    // (`plan_layouts` sets `noinline_decode`, so the two generators flatten identically). A message
    // under budget is `#[inline(always)]`, so a parent's decode absorbs it -- and, since its own
    // sub-message decoders are likewise `#[inline(always)]` until the next marked message, the whole
    // closure collapses into one function (the Rust analog of flatten). A budget-marked message is
    // `#[inline(never)]`: the out-of-line boundary that stops a parent from absorbing it, which bounds
    // whole-closure (and compile-time) growth on a large or recursive schema. A message with no layout
    // (defensive; decodable messages always have one) keeps the compiler's default.
    if (layout != nullptr) {
        printer.print(layout->noinline_decode ? "#[inline(never)]\n" : "#[inline(always)]\n");
    }
    // `rp_arena` is unused when the body neither accumulates a repeated field nor allocates a
    // sub-message (a message of only singular scalar/enum/string/bytes fields); name it `_rp_arena`
    // then to avoid an unused-variable warning.
    printer.print("#[doc(hidden)]\n");
    // Takes a branded write-once `Slot` and returns the `Init<'id>` proof that `Slot::write` yields --
    // an unforgeable witness that the slot was initialized. The in-place helpers
    // (`Arena::emplace`/`DecodeVec::emplace`/`decode_value`) publish the slot only against that proof,
    // so they stay sound for ANY safe caller (no init-on-trust), not just this generated one.
    // Visible to the whole arena tree, which decodes sub-messages through it, and to nothing else.
    printer.print(
        "pub(in $root$::arena) fn rp_decode_into<'id>(rp_out: ::rapidproto::Slot<'id, $M$<'a>>, "
        "rp_body: "
        "&'a [u8], $ap$: &'a ::rapidproto::Arena<'a>, rp_depth: u32) -> "
        "::core::result::Result<::rapidproto::Init<'id>, ::rapidproto::DecodeError> {\n",
        {{"root", table.root}, {"ap", body_uses_arena(msg, modes) ? "rp_arena" : "_rp_arena"}});
    printer.indent();
    printer.print("if rp_depth > ::rapidproto::MAX_DECODE_DEPTH {\n");
    printer.indent();
    printer.print(
        "return ::core::result::Result::Err(::rapidproto::DecodeError::new("
        "::rapidproto::ErrorKind::DepthLimitExceeded, 0));\n");
    printer.outdent();
    printer.print("}\n");
    emit_decode_locals(printer, table, msg, modes, layout);
    printer.print("let mut rp_rest: &'a [u8] = rp_body;\n");
    emit_threaded_prologue(printer, table, msg, modes, layout);
    printer.print("loop {\n");
    printer.indent();
    emit_peek_hub(printer, loop_read(), "rp_tag");
    printer.print("match rp_tagkey {\n");
    printer.indent();
    emit_decode_arms(printer, table, msg, modes, layout);
    printer.outdent();
    printer.print("}\n");  // match
    printer.outdent();
    printer.print("}\n");  // loop
    // proto2 `required`: every required field must have appeared on the wire (checked after the loop,
    // matching C++), else the message is incomplete.
    for (const FieldNode& field : msg.fields) {
        if (field.presence == FieldPresence::Required) {
            const std::string nstr = std::to_string(field.number);
            printer.print("if !rp_req_$n$ {\n", {{"n", nstr}});
            printer.indent();
            printer.print(
                "return ::core::result::Result::Err(::rapidproto::DecodeError::new("
                "::rapidproto::ErrorKind::MissingRequired, 0).with_field($n$));\n",
                {{"n", nstr}});
            printer.outdent();
            printer.print("}\n");
        }
    }
    emit_decode_construct(printer, msg, modes, accessors, layout);
    printer.outdent();
    printer.print("}\n");
}

// Emit `pub struct Msg<'a> { .. }` -- the storage fields (= getters' return types). A dropped field/map
// has no storage; a `raw` message field stores its payload bytes; `unknown-fields` adds the bit.
void emit_message_struct(Printer& printer, const NameTable& table, const MessageNode& msg,
                         const FieldModes& modes, const AccessorNames& accessors,
                         const arenagen::MessageLayout* layout) {
    printer.print("pub struct $M$<'a> {\n");
    printer.indent();
    for (std::size_t i = 0; i < msg.fields.size(); ++i) {
        const FieldNode& field = msg.fields[i];
        if (field_mode(modes, field) == arenagen::FieldMode::Drop) {
            continue;
        }
        const arenagen::MemberPlan* member = member_for(layout, field);
        if (!field.is_repeated && rust_store(member, field) == RustStore::MaskedBool) {
            continue;  // a packed bool has no struct field (it lives in `rp_presence`)
        }
        printer.print("$l$: $t$,\n", {{"l", accessors.fields[i]},
                                      {"t", field_storage_type(table, field, modes, member)}});
    }
    if (layout != nullptr && rust_mask_bits(*layout) > 0) {
        printer.print("rp_presence: $t$,\n", {{"t", mask_word_type(rust_mask_bits(*layout))}});
    }
    for (std::size_t i = 0; i < msg.map_fields.size(); ++i) {
        if (map_mode(modes, msg.map_fields[i]) != arenagen::FieldMode::Drop) {
            printer.print("$l$: $t$,\n", {{"l", accessors.maps[i]},
                                          {"t", map_view_type(table, msg.map_fields[i])}});
        }
    }
    for (std::size_t i = 0; i < msg.oneofs.size(); ++i) {
        printer.print("$l$: $t$,\n", {{"l", accessors.oneofs[i]},
                                      {"t", oneof_storage_type(table, msg, msg.oneofs[i])}});
    }
    if (modes.wants_unknown(&msg)) {
        printer.print("rp_unknown: bool,\n");  // has_unknown_fields() storage
    }
    if (!message_uses_lifetime(msg, modes)) {
        printer.print("_marker: ::core::marker::PhantomData<&'a ()>,\n");
    }
    printer.outdent();
    printer.print("}\n\n");
}

// Whether a message exposes any getter (so `emit_message_accessors` emits an `impl` block at all).
bool message_has_accessors(const MessageNode& msg, const FieldModes& modes) {
    if (modes.wants_unknown(&msg) || !msg.oneofs.empty()) {
        return true;
    }
    if (std::any_of(msg.fields.begin(), msg.fields.end(), [&](const FieldNode& field) {
            return field_mode(modes, field) != arenagen::FieldMode::Drop;
        })) {
        return true;
    }
    return std::any_of(msg.map_fields.begin(), msg.map_fields.end(), [&](const MapFieldNode& map) {
        return map_mode(modes, map) != arenagen::FieldMode::Drop;
    });
}

// Emit `impl<'a> Msg<'a> { <getters> }` (skipped when nothing is exposed). A dropped field/map has no
// getter; `unknown-fields` adds `has_unknown_fields()`. The decode impl is emitted separately, later.
void emit_message_accessors(Printer& printer, const NameTable& table, const MessageNode& msg,
                            const FieldModes& modes, const AccessorNames& accessors,
                            const arenagen::MessageLayout* layout) {
    if (!message_has_accessors(msg, modes)) {
        return;
    }
    const int mask_bits = layout != nullptr ? rust_mask_bits(*layout) : 0;
    printer.print("impl<'a> $M$<'a> {\n");
    printer.indent();
    for (std::size_t i = 0; i < msg.fields.size(); ++i) {
        if (field_mode(modes, msg.fields[i]) != arenagen::FieldMode::Drop) {
            emit_field_accessor(printer, table, msg.fields[i], accessors.fields[i], modes,
                                member_for(layout, msg.fields[i]), mask_bits);
        }
    }
    for (std::size_t i = 0; i < msg.map_fields.size(); ++i) {
        if (map_mode(modes, msg.map_fields[i]) != arenagen::FieldMode::Drop) {
            emit_map_accessor(printer, table, msg.map_fields[i], accessors.maps[i]);
        }
    }
    for (std::size_t i = 0; i < msg.oneofs.size(); ++i) {
        emit_oneof_accessor(printer, table, msg, msg.oneofs[i], accessors.oneofs[i]);
    }
    if (modes.wants_unknown(&msg)) {
        printer.print(
            "/// Returns `true` if the encoded message had a field the schema does not declare.\n"
            "///\n"
            "/// Unknown fields inside a sub-message do not count.\n");
        printer.print("pub fn has_unknown_fields(&self) -> bool {\n");
        printer.indent();
        printer.print("self.rp_unknown\n");
        printer.outdent();
        printer.print("}\n");
    }
    printer.outdent();
    printer.print("}\n\n");
}

// --- Debug and serde Serialize --------------------------------------------------------------------
// Both walk a message's fields the same way and carry exactly the fields the debug dumper prints, keyed
// by PROTO field names: explicit => when set; proto3 implicit => when non-default; required => always;
// repeated/map => when non-empty; a oneof => its active member as a direct entry. A dropped field is
// left out. Values go through their own impls: `bytes` as one opaque value (not a sequence of u8), an
// enum by its own impl, strings, sub-messages and maps through theirs. The walk reads the SAME public
// getters as a user, so a wrong decoded value shows up here too.

// How the walk records one field: `entry` for a value bound as `rp_v`, `member` for a oneof match arm
// whose member is bound by reference. `$n$` is the proto name.
struct FieldWalk {
    const char* entry;
    const char* member;
};

// `Debug`: a field of the `debug_struct` `rp_s`.
constexpr FieldWalk kDebugWalk = {
    "rp_s.field($n$, &rp_v);\n",
    "$e$::$v$(rp_v) => {\n  rp_s.field($n$, rp_v);\n}\n",
};

// `Serialize` (the `serde` option): an entry of the map `rp_map`.
constexpr FieldWalk kSerializeWalk = {
    "rp_map.serialize_entry($n$, &rp_v)?;\n",
    "$e$::$v$(rp_v) => rp_map.serialize_entry($n$, rp_v)?,\n",
};

// A Rust string literal for a proto field name (names are `[A-Za-z0-9_]`, so no escaping needed).
std::string rust_str_lit(std::string_view name) {
    return "\"" + std::string(name) + "\"";
}

// The name a message's `Debug` impl prints, as a string literal: the identifier, as `derive(Debug)`
// prints it, so `r#type` prints as `type`.
std::string debug_name(const NameTable& table, const MessageNode& msg) {
    return rust_str_lit(ident_identity(table.messages.at(msg.fqn).type_name));
}

void emit_field_walk(Printer& printer, const FieldNode& field, const std::string& accessor,
                     const FieldWalk& walk) {
    const std::string key = rust_str_lit(field.name);
    printer.print("{\n");
    printer.indent();
    if (field.is_repeated) {
        printer.print("let rp_v = self.$a$();\n", {{"a", accessor}});
        printer.print("if !rp_v.is_empty() {\n");
        printer.indent();
        printer.print(walk.entry, {{"n", key}});
        printer.outdent();
        printer.print("}\n");
    } else if (field.is_message_type || field.presence == FieldPresence::Explicit) {
        // The getter returns an `Option`: a singular message for every presence (required => Some), a
        // raw one as its payload's `ProtoBytes`, and any explicit-presence field.
        printer.print("if let ::core::option::Option::Some(rp_v) = self.$a$() {\n",
                      {{"a", accessor}});
        printer.indent();
        printer.print(walk.entry, {{"n", key}});
        printer.outdent();
        printer.print("}\n");
    } else if (field.presence == FieldPresence::Required) {
        printer.print("let rp_v = self.$a$();\n", {{"a", accessor}});
        printer.print(walk.entry, {{"n", key}});
    } else {  // Implicit (proto3 singular): emit only a non-default value, as protobuf JSON does.
        std::string cond;
        if (field.is_enum_type) {
            cond = "rp_v.0 != 0";
        } else if (field.type_name == "bool") {
            cond = "rp_v";
        } else if (field.type_name == "float" || field.type_name == "double") {
            // Only +0.0 is the omittable default; -0.0 (and NaN) are present -- matching the dumper's
            // is_positive_zero rule and protobuf. `!= 0.0` would wrongly drop -0.0.
            cond = "rp_v.to_bits() != 0";
        } else if (field.type_name == "string" || field.type_name == "bytes") {
            cond = "!rp_v.is_empty()";
        } else {
            cond = "rp_v != 0";
        }
        printer.print("let rp_v = self.$a$();\n", {{"a", accessor}});
        printer.print("if $c$ {\n", {{"c", cond}});
        printer.indent();
        printer.print(walk.entry, {{"n", key}});
        printer.outdent();
        printer.print("}\n");
    }
    printer.outdent();
    printer.print("}\n");
}

void emit_oneof_walk(Printer& printer, const NameTable& table, const MessageNode& msg,
                     const OneofNode& oneof, const std::string& accessor, const FieldWalk& walk) {
    const std::vector<std::string> variants = oneof_variant_names(oneof);
    const std::string enum_path = oneof_path(table, msg, oneof);
    printer.print("if let ::core::option::Option::Some(rp_o) = self.$a$() {\n", {{"a", accessor}});
    printer.indent();
    printer.print("match rp_o {\n");
    printer.indent();
    for (std::size_t i = 0; i < oneof.fields.size(); ++i) {
        printer.print(
            walk.member,
            {{"e", enum_path}, {"v", variants[i]}, {"n", rust_str_lit(oneof.fields[i].name)}});
    }
    printer.outdent();
    printer.print("}\n");
    printer.outdent();
    printer.print("}\n");
}

void emit_map_walk(Printer& printer, const MapFieldNode& map, const std::string& accessor,
                   const FieldWalk& walk) {
    printer.print("{\n");
    printer.indent();
    printer.print("let rp_v = self.$a$();\n", {{"a", accessor}});
    printer.print("if !rp_v.is_empty() {\n");
    printer.indent();
    printer.print(walk.entry, {{"n", rust_str_lit(map.name)}});
    printer.outdent();
    printer.print("}\n");
    printer.outdent();
    printer.print("}\n");
}

void emit_message_walk(Printer& printer, const NameTable& table, const MessageNode& msg,
                       const FieldModes& modes, const AccessorNames& accessors,
                       const FieldWalk& walk) {
    for (std::size_t i = 0; i < msg.fields.size(); ++i) {
        if (field_mode(modes, msg.fields[i]) != arenagen::FieldMode::Drop) {
            emit_field_walk(printer, msg.fields[i], accessors.fields[i], walk);
        }
    }
    for (std::size_t i = 0; i < msg.map_fields.size(); ++i) {
        if (map_mode(modes, msg.map_fields[i]) != arenagen::FieldMode::Drop) {
            emit_map_walk(printer, msg.map_fields[i], accessors.maps[i], walk);
        }
    }
    for (std::size_t i = 0; i < msg.oneofs.size(); ++i) {
        emit_oneof_walk(printer, table, msg, msg.oneofs[i], accessors.oneofs[i], walk);
    }
}

// `Name { field: value, .. }`, like `derive(Debug)`, with only the walk's fields.
void emit_message_debug(Printer& printer, const NameTable& table, const MessageNode& msg,
                        const FieldModes& modes, const AccessorNames& accessors) {
    printer.print("impl<'a> ::core::fmt::Debug for $M$<'a> {\n");
    printer.indent();
    printer.print(kDebugFmt);
    printer.indent();
    printer.print("let mut rp_s = rp_f.debug_struct($n$);\n", {{"n", debug_name(table, msg)}});
    emit_message_walk(printer, table, msg, modes, accessors, kDebugWalk);
    printer.print("rp_s.finish()\n");
    printer.outdent();
    printer.print("}\n");
    printer.outdent();
    printer.print("}\n\n");
}

void emit_message_serialize(Printer& printer, const NameTable& table, const MessageNode& msg,
                            const FieldModes& modes, const AccessorNames& accessors) {
    printer.print("impl<'a> ::rapidproto::serde::Serialize for $M$<'a> {\n");
    printer.indent();
    printer.print(
        "fn serialize<RpS>(&self, rp_ser: RpS) -> ::core::result::Result<RpS::Ok, RpS::Error>\n");
    printer.print("where\n");
    printer.indent();
    printer.print("RpS: ::rapidproto::serde::Serializer,\n");
    printer.outdent();
    printer.print("{\n");
    printer.indent();
    printer.print("use ::rapidproto::serde::ser::SerializeMap as _;\n");
    printer.print("let mut rp_map = rp_ser.serialize_map(::core::option::Option::None)?;\n");
    emit_message_walk(printer, table, msg, modes, accessors, kSerializeWalk);
    printer.print("rp_map.end()\n");
    printer.outdent();
    printer.print("}\n");
    printer.outdent();
    printer.print("}\n\n");
}

// The owning-handle API: one runtime macro expands to the `ArenaDecode` tag impl on `$M$<'static>` (no
// separate marker type) + the `$M$::decode_owned` convenience over the runtime
// `::rapidproto::decode_owned` -- the Rust pendant of C++'s `decode_owned`. Emitting the macro call,
// not the boilerplate, keeps each message to one line and the SAFETY rationale in one place (the
// macro definition). Without the runtime's `alloc` feature the macro expands to nothing. Ends with a
// single newline (no trailing blank): the caller separates items with its own blank lines. `$M$` is
// set by the caller.
void emit_message_owned(Printer& printer) {
    printer.print("::rapidproto::impl_decode_owned!($M$);\n");
}

void emit_message(Printer& printer, const NameTable& table, const MessageNode& msg,
                  const FieldModes& modes, const LayoutSet& layouts, bool serde) {
    printer.set("M", table.messages.at(msg.fqn).type_name);
    const arenagen::MessageLayout* layout = layouts.find(msg.fqn);
    const AccessorNames accessors = message_accessor_names(msg);
    emit_message_struct(printer, table, msg, modes, accessors, layout);
    // The `decode`/`rp_decode_into` impl is emitted at the end of the arena module
    // ([`emit_message_decode`]) so a reader skims the whole getter API without the wire-loop bodies in
    // between.
    emit_message_accessors(printer, table, msg, modes, accessors, layout);
    // The `Debug` and `serde::Serialize` impls read those same getters.
    emit_message_debug(printer, table, msg, modes, accessors);
    if (serde) {
        emit_message_serialize(printer, table, msg, modes, accessors);
    }
    // The owning-handle API (`decode_owned`).
    emit_message_owned(printer);
}

// Emit `rp_default`, the value a parent's decode starts from for a fixed-size message it stores inline:
// every field at its zero value. A `Default` impl would do the same, but users could reach it.
void emit_message_default(Printer& printer, const NameTable& table, const MessageNode& msg,
                          const FieldModes& modes, const AccessorNames& accessors,
                          const arenagen::MessageLayout& layout) {
    printer.print("\n#[inline(always)]\n");
    printer.print("pub(in $root$::arena) fn rp_default() -> Self {\n", {{"root", table.root}});
    printer.indent();
    printer.print("$M$ {\n");
    printer.indent();
    for (std::size_t i = 0; i < msg.fields.size(); ++i) {
        const FieldNode& field = msg.fields[i];
        const arenagen::MemberPlan* member = member_for(&layout, field);
        if (field_mode(modes, field) != arenagen::FieldMode::Drop &&
            rust_store(member, field) != RustStore::MaskedBool) {
            printer.print("$a$: $d$,\n", {{"a", accessors.fields[i]},
                                          {"d", field_default_expr(table, field, member)}});
        }
    }
    if (rust_mask_bits(layout) > 0) {
        printer.print("rp_presence: $z$,\n", {{"z", mask_zero(rust_mask_bits(layout))}});
    }
    if (modes.wants_unknown(&msg)) {
        printer.print("rp_unknown: false,\n");
    }
    if (!message_uses_lifetime(msg, modes)) {
        printer.print("_marker: ::core::marker::PhantomData,\n");
    }
    printer.outdent();
    printer.print("}\n");
    printer.outdent();
    printer.print("}\n");
}

// Emit the `decode` + `rp_decode_into` impl for one message, in its OWN module but
// after that module's structs/getters and submodules, so a reader skims the getters first and the
// wire-loop bodies sit at the bottom of each module. It must stay in the message's module:
// `rp_decode_into` constructs the struct from its PRIVATE storage fields, which only the defining
// module may do.
void emit_message_decode(Printer& printer, const NameTable& table, const MessageNode& msg,
                         const FieldModes& modes, const LayoutSet& layouts) {
    printer.set("M", table.messages.at(msg.fqn).type_name);
    printer.print("impl<'a> $M$<'a> {\n");
    printer.indent();
    const AccessorNames accessors = message_accessor_names(msg);
    const arenagen::MessageLayout* layout = layouts.find(msg.fqn);
    emit_decode(printer, table, msg, accessors, modes, layout);
    if (layout != nullptr && layout->fixed_size) {
        emit_message_default(printer, table, msg, modes, accessors, *layout);
    }
    printer.outdent();
    printer.print("}\n");
}

// Open `pub mod <name> {` for the types declared in `msg`, with its doc, and indent. Each tree opens one
// for a message whose nested types it emits.
void emit_nested_module_open(Printer& printer, const std::string& name, const MessageNode& msg) {
    printer.print("/// Types declared in `$m$`.\n", {{"m", proto_name(msg.fqn)}});
    printer.print("pub mod $n$ {\n", {{"n", name}});
    printer.indent();
}

// Open `pub mod <name> {` for a package, with its doc, and indent. A node with no files of its own is
// only a prefix of the packages below it.
void emit_package_module_open(Printer& printer, const PkgTrie& node) {
    printer.print(node.files.empty() ? "/// Packages under `$p$`.\n" : "/// The `$p$` package.\n",
                  {{"p", node.package}});
    printer.print("pub mod $n$ {\n", {{"n", node.emitted}});
    printer.indent();
}

// Recursively emit arena message structs: each message as a struct+impl, then -- in a
// `pub mod <snake>` one level deeper -- its oneof enums followed by its nested messages. The submodule
// name comes from the name table (deduped against sibling messages and struct/oneof-enum names), so it
// matches the paths referring in. The submodule is emitted when the message has nested messages OR
// oneofs (both live there).
void emit_arena_messages(Printer& printer, const NameTable& table,
                         const std::vector<const MessageNode*>& msgs, const FieldModes& modes,
                         const LayoutSet& layouts, bool serde) {
    for (std::size_t i = 0; i < msgs.size(); ++i) {
        if (i != 0) {
            printer.print("\n");
        }
        emit_message(printer, table, *msgs[i], modes, layouts, serde);
        const bool has_submodule = !msgs[i]->nested_messages.empty() || !msgs[i]->oneofs.empty();
        if (has_submodule) {
            const std::string& sub = table.messages.at(msgs[i]->fqn).submodule;
            printer.print("\n");
            emit_nested_module_open(printer, sub, *msgs[i]);
            for (std::size_t k = 0; k < msgs[i]->oneofs.size(); ++k) {
                if (k != 0) {
                    printer.print("\n");
                }
                emit_oneof_enum(printer, table, *msgs[i], msgs[i]->oneofs[k]);
            }
            if (!msgs[i]->oneofs.empty() && !msgs[i]->nested_messages.empty()) {
                printer.print("\n");  // separate the oneof enums from the nested messages
            }
            emit_arena_messages(printer, table, addrs(msgs[i]->nested_messages), modes, layouts,
                                serde);
            printer.outdent();
            printer.print("}\n");
        }
    }
    // The decode impls for this module's messages, grouped at the bottom (after the structs/getters and
    // submodules above), so the getters read uninterrupted. Each stays in its message's own module.
    for (const MessageNode* msg : msgs) {
        printer.print("\n");
        emit_message_decode(printer, table, *msg, modes, layouts);
    }
}

// Recursively emit nested enums into the common tree: a message holding enums gets a `pub mod <snake>`
// (the same table-assigned submodule name as the arena tree) with its own enums plus the recursion.
void emit_common_message_enums(Printer& printer, const NameTable& table,
                               const std::vector<const MessageNode*>& msgs, bool serde) {
    for (const MessageNode* msg : msgs) {
        if (!codegen::holds_enum(*msg)) {
            continue;
        }
        emit_nested_module_open(printer, table.messages.at(msg->fqn).submodule, *msg);
        for (std::size_t i = 0; i < msg->enums.size(); ++i) {
            if (i != 0) {
                printer.print("\n");
            }
            emit_enum(printer, table, msg->enums[i], serde);
        }
        emit_common_message_enums(printer, table, addrs(msg->nested_messages), serde);
        printer.outdent();
        printer.print("}\n");
    }
}

// The top-level messages / enums of every file at one package node, gathered into one scope.
std::vector<const MessageNode*> node_messages(const PkgTrie& node) {
    std::vector<const MessageNode*> msgs;
    for (const FileNode* file : node.files) {
        for (const MessageNode& msg : file->messages) {
            msgs.push_back(&msg);
        }
    }
    return msgs;
}
std::vector<const EnumNode*> node_enums(const PkgTrie& node) {
    std::vector<const EnumNode*> enums;
    for (const FileNode* file : node.files) {
        for (const EnumNode& node_enum : file->enums) {
            enums.push_back(&node_enum);
        }
    }
    return enums;
}

// Whether a package or one below it declares an enum, at the top level or in a message: what the
// `common` tree emits. A package without one gets no module there.
bool subtree_has_enums(const PkgTrie& node) {
    const bool here = std::any_of(node.files.begin(), node.files.end(), [](const FileNode* file) {
        return !file->enums.empty() ||
               std::any_of(file->messages.begin(), file->messages.end(),
                           [](const MessageNode& msg) { return codegen::holds_enum(msg); });
    });
    return here || std::any_of(node.children.begin(), node.children.end(),
                               [](const auto& child) { return subtree_has_enums(child.second); });
}

// Whether a package or one below it declares a message: what the `arena` and `stream` trees emit. A
// package without one gets no module there.
bool subtree_has_messages(const PkgTrie& node) {
    const bool here = std::any_of(node.files.begin(), node.files.end(),
                                  [](const FileNode* file) { return !file->messages.empty(); });
    return here || std::any_of(node.children.begin(), node.children.end(), [](const auto& child) {
               return subtree_has_messages(child.second);
           });
}

// Emit the `common` subtree for one package node: this package's enums (its files', plus the per-
// message nested-enum mirror), then a `pub mod <component>` per sub-package that has any.
void emit_common_node(Printer& printer, const NameTable& table, const PkgTrie& node, bool serde) {
    const std::vector<const EnumNode*> enums = node_enums(node);
    for (std::size_t i = 0; i < enums.size(); ++i) {
        if (i != 0) {
            printer.print("\n");
        }
        emit_enum(printer, table, *enums[i], serde);
    }
    emit_common_message_enums(printer, table, node_messages(node), serde);
    for (const auto& [component, child] : node.children) {
        if (!subtree_has_enums(child)) {
            continue;
        }
        emit_package_module_open(printer, child);
        emit_common_node(printer, table, child, serde);
        printer.outdent();
        printer.print("}\n");
    }
}

// Emit the `arena` subtree for one package node: this package's message structs, then a
// `pub mod <component>` per sub-package that has any.
void emit_arena_node(Printer& printer, const NameTable& table, const PkgTrie& node,
                     const FieldModes& modes, const LayoutSet& layouts, bool serde) {
    emit_arena_messages(printer, table, node_messages(node), modes, layouts, serde);
    for (const auto& [component, child] : node.children) {
        if (!subtree_has_messages(child)) {
            continue;
        }
        printer.print("\n");
        emit_package_module_open(printer, child);
        emit_arena_node(printer, table, child, modes, layouts, serde);
        printer.outdent();
        printer.print("}\n");
    }
}

// ===== streaming decoder =====
//
// The `stream` tree is the counterpart to `arena`: a consumer that only wants a few fields visits them
// as they appear on the wire and never materializes the message. Per message it emits a reader handle
// `Msg<'a>` (`Msg::new(bytes).decode(visitor)`), a `MsgVisitor<'a>` trait (one
// `const WANT_<field>: bool = false` + a defaulted `on_<field>(&mut self, V) -> Result<Flow, _>` per
// field, plus an `unknown` handler), and a per-message `<msg>_stream! { field => closure, .. }` macro
// building an anonymous visitor whose closures capture local state. The macro also takes a shared-state
// form, `<msg>_stream!(&mut state; { field => |state, value| .. })`: the driver lends one `&mut state`
// to every handler instead of each closure capturing it, so a walk can aggregate many fields into one
// accumulator (or parse into one struct) -- which exclusive-`&mut` captures cannot. The decode driver
// gates each field on `V::WANT_<field>` (const-folded: unselected => a wire-skip), and a handler's
// `Err` or `Flow::Stop` ends `decode`, which returns the `Flow` so that a handler returning a child's
// `decode` passes a stop on. The loop, peek hub, wire reads and skip are shared with the arena emitter
// above; streaming replaces storage+construct with a gate + a direct visitor call.
//
// The generated code is O(N): the trait, the driver and the macro are each one unit per field -- no
// quadratic setter reconstruction (there is no builder). A map field is a selectable slot too: its
// handler receives `(key, value)` per entry (`emit_stream_map_body`), mirroring C++ streamgen. Field
// modes (drop/raw/unknown-fields) are arena-STORAGE options and do not apply to a streaming visitor,
// which materializes nothing, so streaming ignores the modes. Groups ride the message path
// (`message_field_wire` / `emit_msg_payload_read`).
//
// Enum- and message-typed fields deliver their generated type (the enum newtype, the child's reader
// handle). The `*_stream!` macro expands at the CONSUMER'S call site, so it names everything through
// `$crate` and the module the file is included at (`emit_stream_macro`).

// One selectable field on a message's stream visitor: the escaped proto field name (names `WANT_<name>`,
// `on_<name>` -- which the built visitor also uses as its field and type parameter -- and the macro
// key) plus the field. Exactly one of `field` / `map` is set: `field` for a regular or oneof-member field, `map` for
// a map field (delivered as a `(key, value)` entry).
struct StreamSlot {
    std::string name;
    const FieldNode* field = nullptr;
    const MapFieldNode* map = nullptr;
};

// A proto field name as a PLAIN, non-keyword Rust identifier safe both to prefix (`on_`/`WANT_`) and
// to capture as a macro `:ident`: a keyword (or a raw-ineligible `self`/`crate`/..) gets a
// trailing `_`, NEVER an `r#` raw-escape (which cannot be prefixed, and which a macro key/`:ident`
// cannot always carry). The consumer types this escaped name as the macro key. For a keyword this is
// the same as the arena accessor (`self` -> `self_`). A name the arena accessor changes only to keep
// clear of the message type's own items -- `decode` (-> `decode_`) and the other reserved methods, or
// an `rp_` name (-> `rp__x`) -- stays bare here: the stream's own names are `on_`/`WANT_`-prefixed or
// `unknown`, so it cannot collide.
std::string stream_ident(const std::string& name) {
    if (name == "_") {
        return "_x";
    }
    if (is_raw_ineligible(name) || is_rust_keyword(name)) {
        return name + "_";
    }
    return name;
}

// The visitor slots for a message: one per regular field, then one per map field (delivered as a
// `(key, value)` entry), then one per oneof MEMBER (each member is individually selectable) -- the
// arena accessor order. Escaped via `stream_ident`, deduped against each other AND the reserved
// `unknown` handler names (a field literally named `unknown`/`UNKNOWN` is bumped, so it cannot collide
// with the per-message unknown-field handler's `WANT_UNKNOWN`/`on_unknown`/`unknown` macro key).
std::vector<StreamSlot> collect_stream_slots(const MessageNode& msg) {
    std::unordered_set<std::string> taken = {"unknown", "UNKNOWN"};
    std::vector<StreamSlot> slots;
    std::size_t slot_count = msg.fields.size() + msg.map_fields.size();
    for (const OneofNode& oneof : msg.oneofs) {
        slot_count += oneof.fields.size();
    }
    slots.reserve(slot_count);
    for (const FieldNode& field : msg.fields) {
        slots.push_back({dedup_ident(taken, stream_ident(field.name)), &field, nullptr});
    }
    for (const MapFieldNode& map : msg.map_fields) {
        slots.push_back({dedup_ident(taken, stream_ident(map.name)), nullptr, &map});
    }
    for (const OneofNode& oneof : msg.oneofs) {
        for (const FieldNode& field : oneof.fields) {
            slots.push_back({dedup_ident(taken, stream_ident(field.name)), &field, nullptr});
        }
    }
    return slots;
}

// Append `seg` as its length then its text. A sequence of identifiers encoded this way is injective
// (an identifier never starts with a digit, so each length ends where the name begins).
void append_length_prefixed(std::string& out, std::string_view seg) {
    out += std::to_string(seg.size());
    out += seg;
}

// A message's identity in the macro names below: its proto FQN, length-prefixed segment by segment
// (`.p3.Msg` -> `2p33Msg`). Unique per message, and stable across schema edits elsewhere.
std::string encoded_fqn(const MessageNode& msg) {
    const std::string_view fqn = msg.fqn;
    std::string out;
    std::size_t pos = 0;
    while (pos <= fqn.size()) {
        const std::size_t dot = std::min(fqn.find('.', pos), fqn.size());
        if (dot > pos) {
            append_length_prefixed(out, fqn.substr(pos, dot - pos));
        }
        pos = dot + 1;
    }
    return out;
}

// The crate-root name of `msg`'s macro: `__rp_<path>_<fqn>`, with the segments of the module path after
// `crate` length-prefixed, raw prefixes dropped. Two generated files in one crate can share a message,
// so the path keeps their names apart. A schema-derived name cannot clash: the only other macro names
// the file defines are friendly ones, inside the `stream` tree.
std::string stream_export_name(std::string_view root, const MessageNode& msg) {
    std::string name = "__rp_";
    std::size_t pos = std::min(root.find("::"), root.size());
    while (pos < root.size()) {
        pos += 2;
        const std::size_t sep = std::min(root.find("::", pos), root.size());
        std::string_view seg = root.substr(pos, sep - pos);
        if (seg.rfind("r#", 0) == 0) {
            seg.remove_prefix(2);
        }
        append_length_prefixed(name, seg);
        pos = sep;
    }
    name += '_';
    name += encoded_fqn(msg);
    return name;
}

// How a macro expansion names the runtime (see generate_stream).
std::string stream_runtime_path(const NameTable& table) {
    return "$" + table.root + "::rp_rt";
}

// The handler value type for a field, with its borrow written as lifetime `lt`: message/group -> the
// child reader handle `Child<lt>`; enum -> the newtype (no lifetime); string -> `ProtoStr<lt>`;
// bytes -> `ProtoBytes<lt>`; scalar -> a primitive. `in_macro` is for the macro, which expands at the
// caller's call site: a generated type's path starts at `$crate`, the runtime is reached through the
// `rp_rt` re-export (see generate_stream), since the caller's crate may not depend on it directly, and
// a primitive is `::core::primitive::*`, since the caller's scope can hold an item of that name.
std::string stream_value_type(const NameTable& table, const FieldNode& field, const std::string& lt,
                              bool in_macro) {
    const std::string dollar = in_macro ? "$" : "";
    if (field.is_message_type) {
        return dollar + message_path(table, field.resolved_type_fqn) + "<" + lt + ">";
    }
    if (field.is_enum_type) {
        return dollar + common_type_path(table, field.resolved_type_fqn);
    }
    const std::string& t = field.type_name;
    if (t == "string" || t == "bytes") {
        return (in_macro ? stream_runtime_path(table) : "::rapidproto") +
               (t == "string" ? "::ProtoStr<" : "::ProtoBytes<") + lt + ">";
    }
    const std::string prim = in_macro ? "::core::primitive::" : "";
    return prim + rust_scalar_type(t);  // numeric: no lifetime
}

// The handler value type for a whole slot: a regular/oneof field's value type, or -- for a map slot --
// the `(key, value)` tuple a map entry delivers (key always scalar; value scalar/enum/child handle).
std::string stream_slot_value_type(const NameTable& table, const StreamSlot& slot,
                                   const std::string& lt, bool in_macro) {
    if (slot.map != nullptr) {
        const FieldNode key = map_key_field(*slot.map);
        const FieldNode val = map_value_field(*slot.map);
        return "(" + stream_value_type(table, key, lt, in_macro) + ", " +
               stream_value_type(table, val, lt, in_macro) + ")";
    }
    return stream_value_type(table, *slot.field, lt, in_macro);
}

// The doc of a slot's `on_<field>` handler, which names the proto field.
std::string handler_doc(const StreamSlot& slot) {
    if (slot.map != nullptr) {
        return "/// Handles one entry of the `" + slot.map->name + "` map.\n";
    }
    const FieldNode& field = *slot.field;
    const std::string kind = field.is_message_type ? "sub-message" : "field";
    std::string doc = field.is_repeated ? "/// Handles one element of `" + field.name + "`.\n"
                                        : "/// Handles the `" + field.name + "` " + kind + ".\n";
    if (field.is_message_type) {
        doc += "///\n/// Read its fields with `value.decode`.\n";
    }
    return doc;
}

// `pub trait <Msg>Visitor<'a> { const WANT_<f>: bool = false; fn on_<f>(&mut self, V) -> Result<Flow>
// { Ok(Continue) } .. const WANT_UNKNOWN; fn on_unknown(..) .. }` -- the handler surface a consumer
// overrides. Every const defaults false and every method to a no-op continue, so an un-overridden field
// is genuinely unselected (its read compiles away, leaving only its skip). The `<'a>` is always present.
void emit_stream_visitor_trait(Printer& printer, const NameTable& table,
                               const std::vector<StreamSlot>& slots) {
    // The doc steers the reader to the macro and pins the one hand-impl footgun: a field is selected by
    // overriding BOTH `WANT_<field>` and `on_<field>` -- the macro always emits the pair, but a
    // hand-impl that sets only `on_<field>` leaves `WANT_<field>` false, so the field is silently never
    // decoded. It names the macro without a link: docs that include private items leave out the
    // macro's re-export, and the link would show as literal brackets there.
    printer.print(
        "/// Receives the selected fields of `$proto$`.\n"
        "///\n"
        "/// Usually you build one with `$mac_hint$!`. To write one by hand, select a field\n"
        "/// by setting its `WANT_<field>` constant to `true` and overriding `on_<field>`. If\n"
        "/// `WANT_<field>` stays `false`, the decoder never calls `on_<field>`. To receive the\n"
        "/// fields the schema does not declare, set `WANT_UNKNOWN` and override `on_unknown`.\n");
    printer.print("pub trait $Vis$<'a> {\n");
    printer.indent();
    for (const StreamSlot& slot : slots) {
        printer.print("/// Whether the decoder calls [`on_$n$`](Self::on_$n$).\n",
                      {{"n", slot.name}});
        printer.print("const WANT_$n$: bool = false;\n", {{"n", slot.name}});
        printer.print(handler_doc(slot));
        printer.print("#[inline(always)]\n");
        printer.print(
            "fn on_$n$(&mut self, value: $t$) -> "
            "::core::result::Result<::rapidproto::stream::Flow, "
            "::rapidproto::DecodeError> { ::core::result::Result::Ok(::rapidproto::stream::Flow::"
            "Continue) }\n",
            {{"n", slot.name}, {"t", stream_slot_value_type(table, slot, "'a", false)}});
    }
    // The unknown-field handler: fires for a field number the schema does not declare (a declared
    // number with a wrong wire type is skipped, not delivered), when selected.
    printer.print("/// Whether the decoder calls [`on_unknown`](Self::on_unknown).\n");
    printer.print("const WANT_UNKNOWN: bool = false;\n");
    printer.print("/// Handles a field the schema does not declare.\n");
    printer.print("#[inline(always)]\n");
    printer.print(
        "fn on_unknown(&mut self, value: ::rapidproto::stream::UnknownField<'a>) -> "
        "::core::result::Result<::rapidproto::stream::Flow, ::rapidproto::DecodeError> "
        "{ ::core::result::Result::Ok(::rapidproto::stream::Flow::Continue) }\n");
    printer.outdent();
    printer.print("}\n");
}

// `match visitor.on_<name>(<value>)? { Flow::Stop => return Ok(Flow::Stop), Flow::Continue => {} }` --
// deliver one occurrence to the handler, propagating an `Err` out of `decode` and honoring an early
// stop.
void emit_stream_dispatch(Printer& printer, const std::string& name, const std::string& value) {
    printer.print("match visitor.on_$n$($v$)? {\n", {{"n", name}, {"v", value}});
    printer.indent();
    printer.print(
        "::rapidproto::stream::Flow::Stop => "
        "return ::core::result::Result::Ok(::rapidproto::stream::Flow::Stop),\n");
    printer.print("::rapidproto::stream::Flow::Continue => {}\n");
    printer.outdent();
    printer.print("}\n");
}

// Deliver each varint of the packed payload `rp_p` to `on_<name>`, as `conv` of the raw value `rp_v`,
// read with `wire::PackedVarints`. A malformed varint errors at its own offset (`remaining` starts at
// it after the error).
void emit_packed_varints_loop(Printer& printer, const std::string& name, const std::string& conv) {
    printer.print("let mut rp_pv = ::rapidproto::wire::PackedVarints::new(rp_p);\n");
    printer.print("loop {\n");
    printer.indent();
    printer.print("let rp_v = match rp_pv.read() {\n");
    printer.indent();
    printer.print("::core::result::Result::Ok(::core::option::Option::Some(v)) => v,\n");
    printer.print("::core::result::Result::Ok(::core::option::Option::None) => break,\n");
    printer.print(
        "::core::result::Result::Err(k) => return ::core::result::Result::Err("
        "::rapidproto::DecodeError::new(k, rp_body.len() - rp_rest.len() - "
        "rp_pv.remaining().len())),\n");
    printer.outdent();
    printer.print("};\n");
    emit_stream_dispatch(printer, name, conv);
    printer.outdent();
    printer.print("}\n");
}

// Read one map-entry component (field 1 = key, field 2 = value) from `rp_ent` into `local`: a
// length-delimited key/value (string/bytes) or a scalar/enum, last-wins on a repeat. A message value is
// NOT read here (it is captured as payload bytes by the caller's own arm).
void emit_stream_map_component(Printer& printer, const NameTable& table, const FieldNode& field,
                               const std::string& local, const ReadAt& at) {
    printer.print("$k$ => {\n", {{"k", raw_tag_key(field.number, scalar_wire_variant(field))}});
    printer.indent();
    if (scalar_wire_variant(field) == "Len") {
        emit_len_read(printer, at);
    } else {
        emit_scalar_value_read(printer, field, at, VarintRead::Inline);
    }
    printer.print("$l$ = $c$;\n", {{"l", local}, {"c", scalar_convert_expr(table, field)}});
    printer.outdent();
    printer.print("}\n");
}

// Open the `match rp_tagkey` arm for raw key `key`, guarded by the slot's `V::WANT_<name>`. The guard
// is a constant, so an arm the visitor does not select compiles away and its field falls to the `_`
// catch-all, which skips it: one skip site in the loop for every unselected field.
void emit_stream_arm_open(Printer& printer, const std::string& key, const std::string& name) {
    printer.print("$k$ if V::WANT_$n$ => {\n", {{"k", key}, {"n", name}});
    printer.indent();
}

void emit_stream_arm_close(Printer& printer) {
    printer.outdent();
    printer.print("}\n");
}

// One MAP entry, its tag consumed: decode the length-delimited entry's `{ key=1, value=2 }` in an inner
// loop (absent key/value default to zero, unknown entry fields skipped) and deliver `(key, value)` to
// the handler -- the Rust mirror of C++ streamgen's per-entry map callback. A scalar/enum value is
// delivered by value; a message value as the child's reader handle over the (possibly empty) value
// payload. Shared by the map's `match` arm and its threaded probe.
void emit_stream_map_body(Printer& printer, const NameTable& table, const StreamSlot& slot) {
    const MapFieldNode& map = *slot.map;
    const FieldNode key = map_key_field(map);
    const FieldNode val = map_value_field(map);
    const ReadAt entry_at{"rp_ent", "rp_ent_body.len() - rp_ent.len()"};

    emit_len_read(printer, loop_read());  // the entry payload -> rp_p
    printer.print("let rp_ent_body: &'a [u8] = rp_p;\n");
    // An entry that omits its key or value delivers the zero value, as protobuf specifies.
    printer.print("let mut rp_key: $t$ = $d$;\n",
                  {{"t", stream_value_type(table, key, "'a", false)},
                   {"d", field_default_expr(table, key, nullptr)}});
    if (val.is_message_type) {
        // A message value is handed over as a child reader handle; capture its payload bytes (empty
        // when the entry omits field 2 -> an empty child).
        printer.print("let mut rp_val: &'a [u8] = &[];\n");
    } else {
        printer.print("let mut rp_val: $t$ = $d$;\n",
                      {{"t", stream_value_type(table, val, "'a", false)},
                       {"d", field_default_expr(table, val, nullptr)}});
    }
    printer.print("let mut rp_ent: &'a [u8] = rp_ent_body;\n");
    printer.print("loop {\n");
    printer.indent();
    emit_peek_hub(printer, entry_at, "rp_etag");
    printer.print("match rp_tagkey {\n");
    printer.indent();
    emit_stream_map_component(printer, table, key, "rp_key", entry_at);
    if (val.is_message_type) {
        printer.print("$k$ => {\n", {{"k", raw_tag_key(val.number, message_field_wire(val))}});
        printer.indent();
        emit_msg_payload_read(printer, val, entry_at);  // -> rp_p
        printer.print("rp_val = rp_p;\n");
        printer.outdent();
        printer.print("}\n");
    } else {
        emit_stream_map_component(printer, table, val, "rp_val", entry_at);
    }
    printer.print("_ => {\n");
    printer.indent();
    emit_skip_field_body(printer, entry_at);
    printer.outdent();
    printer.print("}\n");
    printer.outdent();
    printer.print("}\n");  // match
    printer.outdent();
    printer.print("}\n");  // loop
    const std::string value_expr =
        val.is_message_type ? message_path(table, val.resolved_type_fqn) + "::rp_new(rp_val)"
                            : "rp_val";
    emit_stream_dispatch(printer, slot.name, "(rp_key, " + value_expr + ")");
}

// One occurrence of a non-map field, its tag consumed: read the value and deliver it (a message/group
// field as the child's reader handle `<Child>::rp_new(payload)`). Shared by the `match` arm and the
// threaded probe.
void emit_stream_value_body(Printer& printer, const NameTable& table, const StreamSlot& slot) {
    const FieldNode& field = *slot.field;
    if (field.is_message_type) {
        const std::string path = message_path(table, field.resolved_type_fqn);
        emit_msg_payload_read(printer, field, loop_read());
        emit_stream_dispatch(printer, slot.name, path + "::rp_new(rp_p)");
        return;
    }
    if (scalar_wire_variant(field) == "Len") {
        emit_len_read(printer, loop_read());
    } else {
        emit_scalar_value_read(printer, field, loop_read(), VarintRead::Inline);
    }
    emit_stream_dispatch(printer, slot.name, scalar_convert_expr(table, field));
}

// A packed run of a repeated numeric field, its tag consumed: deliver each element. Shared by the
// `match` arm and the threaded probe.
void emit_stream_packed_body(Printer& printer, const NameTable& table, const StreamSlot& slot) {
    const FieldNode& field = *slot.field;
    const std::string conv = scalar_convert_expr(table, field);
    emit_len_read(printer, loop_read());
    if (scalar_wire_variant(field) == "Varint") {
        emit_packed_varints_loop(printer, slot.name, conv);
        return;
    }
    printer.print("while !rp_p.is_empty() {\n");
    printer.indent();
    emit_scalar_value_read(printer, field, packed_read());
    emit_stream_dispatch(printer, slot.name, conv);
    printer.outdent();
    printer.print("}\n");
}

// The wire form one occurrence of a slot's field arrives in: LEN for a map entry, the message wire for
// a message/group field, else the scalar's (for a repeated numeric, its unpacked element).
std::string stream_slot_wire(const StreamSlot& slot) {
    if (slot.map != nullptr) {
        return "Len";
    }
    return slot.field->is_message_type ? message_field_wire(*slot.field)
                                       : scalar_wire_variant(*slot.field);
}

// Whether the slot is a repeated numeric field, which also arrives as a packed LEN run.
bool stream_slot_packable(const StreamSlot& slot) {
    return slot.field != nullptr && is_packable_repeated(*slot.field);
}

// The field number of the slot's field or map.
int stream_slot_number(const StreamSlot& slot) {
    return slot.map != nullptr ? slot.map->number : slot.field->number;
}

// The `match rp_tagkey` arm(s) for one slot in the decode driver, each read + deliver (unselected
// fields are skipped by the catch-all, see `emit_stream_arm_open`). A repeated numeric field emits an
// unpacked arm + a packed arm (per element).
void emit_stream_arm(Printer& printer, const NameTable& table, const StreamSlot& slot) {
    const int number = stream_slot_number(slot);
    emit_stream_arm_open(printer, raw_tag_key(number, stream_slot_wire(slot)), slot.name);
    if (slot.map != nullptr) {
        emit_stream_map_body(printer, table, slot);
    } else {
        emit_stream_value_body(printer, table, slot);
    }
    emit_stream_arm_close(printer);
    if (stream_slot_packable(slot)) {
        emit_stream_arm_open(printer, raw_tag_key(number, "Len"), slot.name);
        emit_stream_packed_body(printer, table, slot);
        emit_stream_arm_close(printer);
    }
}

// Field-order threading for the stream driver: the arena prologue's straight-line probe chain (see
// `emit_threaded_prologue` for why it is straight-line and why its scope is broader than the C++
// reference's), with the same scope: singular fields and oneof members admitted by
// codegen::is_threadable_singular, plus the repeated fields and maps admitted by
// `is_threadable_repeated` / `is_threadable_map`, which self-loop (a repeated numeric also probes its
// packed run). A probed field is delivered when the visitor selects it and skipped otherwise, through
// `skip_field` with its constant tag, which folds to that wire type's skip -- as C++ streamgen skips an
// unselected threaded field. So a well-ordered message with few selected fields costs one tag compare
// per field, with no `match` and no runtime wire-type switch. The hub loop after it decodes whatever
// the chain did not consume.
void emit_stream_prologue(Printer& printer, const NameTable& table,
                          const std::vector<StreamSlot>& slots) {
    std::vector<const StreamSlot*> items;
    for (const StreamSlot& slot : slots) {
        bool threadable = false;
        if (slot.map != nullptr) {
            threadable = is_threadable_map(*slot.map);
        } else if (slot.field->is_repeated) {
            threadable = is_threadable_repeated(*slot.field);
        } else {
            threadable = codegen::is_threadable_singular(*slot.field);
        }
        if (threadable) {
            items.push_back(&slot);
        }
    }
    std::sort(items.begin(), items.end(), [](const StreamSlot* a, const StreamSlot* b) {
        return stream_slot_number(*a) < stream_slot_number(*b);
    });
    const auto probe = [&](const StreamSlot& slot, const std::string& wire, bool self_loop,
                           auto&& body) {
        const int number = stream_slot_number(slot);
        emit_probe_open(printer, number, wire, self_loop);
        printer.print("if V::WANT_$n$ {\n", {{"n", slot.name}});
        printer.indent();
        body();
        printer.outdent();
        printer.print("} else {\n");
        printer.indent();
        emit_skip_field_body(printer, loop_read(), raw_tag_key(number, wire));
        printer.outdent();
        printer.print("}\n");
        emit_probe_close(printer);
    };
    for (const StreamSlot* slot : items) {
        const bool self_loop = slot->map != nullptr || slot->field->is_repeated;
        probe(*slot, stream_slot_wire(*slot), self_loop, [&] {
            if (slot->map != nullptr) {
                emit_stream_map_body(printer, table, *slot);
            } else {
                emit_stream_value_body(printer, table, *slot);
            }
        });
        if (stream_slot_packable(*slot)) {
            // One packed run (a second falls to the hub loop).
            probe(*slot, "Len", /*self_loop=*/false,
                  [&] { emit_stream_packed_body(printer, table, *slot); });
        }
    }
}

// The `_ =>` catch-all: a field number the schema declares (regular / oneof member / map) is skipped
// silently -- an unselected field, whose guarded arm compiled away, or one with a wrong wire type; a
// number the schema does NOT declare is delivered to the `unknown` handler (when selected) as an
// `UnknownField` carrying its value bytes, else skipped.
void emit_stream_unknown_arm(Printer& printer, const MessageNode& msg) {
    std::string known;
    const auto note = [&](std::int64_t number) {
        if (!known.empty()) {
            known += " | ";
        }
        known += std::to_string(number);
    };
    for (const FieldNode& field : msg.fields) {
        note(field.number);
    }
    for (const OneofNode& oneof : msg.oneofs) {
        for (const FieldNode& field : oneof.fields) {
            note(field.number);
        }
    }
    for (const MapFieldNode& map : msg.map_fields) {
        note(map.number);
    }
    printer.print("_ => {\n");
    printer.indent();
    // A fieldless message has no declared numbers, so every field on the wire is unknown (an empty
    // `matches!(.., )` pattern is a syntax error, so gate on the flag alone there).
    if (known.empty()) {
        printer.print("if V::WANT_UNKNOWN {\n");
    } else {
        printer.print("if V::WANT_UNKNOWN && !::core::matches!(rp_tagkey >> 3, $k$) {\n",
                      {{"k", known}});
    }
    printer.indent();
    printer.print("let rp_before = rp_rest;\n");
    emit_skip_field_body(printer, loop_read());
    printer.print(
        "let rp_u = ::rapidproto::stream::UnknownField::new(rp_tagkey, "
        "&rp_before[..rp_before.len() - rp_rest.len()]);\n");
    emit_stream_dispatch(printer, "unknown", "rp_u");
    printer.outdent();
    printer.print("} else {\n");
    printer.indent();
    emit_skip_field_body(printer, loop_read());
    printer.outdent();
    printer.print("}\n");
    printer.outdent();
    printer.print("}\n");
}

// `pub struct Msg<'a> { .. }` reader handle (`Msg::new(bytes)?.decode(visitor)`) + the decode driver:
// the field-order probes, then the shared peek-hub field loop, each arm gated on its field's `WANT_`
// const.
void emit_stream_decode(Printer& printer, const NameTable& table, const MessageNode& msg,
                        const std::vector<StreamSlot>& slots) {
    // Generated docs link only within the user's crate. Their `cargo doc --no-deps` cannot reach the
    // runtime's pages, and rustdoc then writes a link into it as its raw path.
    printer.print(
        "/// An encoded `$proto$` message, read field by field with [`decode`](Self::decode).\n");
    printer.print("#[derive(Clone, Copy)]\n");
    printer.print("pub struct $M$<'a> {\n");
    printer.indent();
    printer.print("rp_input: &'a [u8],\n");
    printer.outdent();
    printer.print("}\n\n");
    // A handle has not decoded anything, so `Debug` prints only how many bytes it holds.
    printer.print("impl ::core::fmt::Debug for $M$<'_> {\n");
    printer.indent();
    printer.print(kDebugFmt);
    printer.indent();
    printer.print("rp_f.debug_struct($n$).field(\"len\", &self.rp_input.len()).finish()\n",
                  {{"n", debug_name(table, msg)}});
    printer.outdent();
    printer.print("}\n");
    printer.outdent();
    printer.print("}\n\n");
    printer.print("impl<'a> $M$<'a> {\n");
    printer.indent();
    // The size check sits here, not in `decode`: a handler decodes a nested message through the same
    // `decode`, so a check there would run at every level. Inline in `decode`, it also grew every decode
    // enough that LLVM stopped inlining the wire reads into some of them.
    printer.print(
        "/// Wraps an encoded message.\n"
        "///\n"
        "/// Fails with `ErrorKind::InputTooLarge` if `input` is longer than `u32::MAX` bytes.\n");
    printer.print("#[inline(always)]\n");
    printer.print(
        "pub fn new(input: &'a [u8]) -> ::core::result::Result<$M$<'a>, "
        "::rapidproto::DecodeError> {\n");
    printer.indent();
    emit_input_size_check(printer, "input");
    printer.print("::core::result::Result::Ok($M$ { rp_input: input })\n");
    printer.outdent();
    printer.print("}\n\n");
    // The handle a parent hands its handler for a nested message, a part of an input `new` checked.
    // Visible to the whole stream tree, so parents in other modules can build it, and to nothing else.
    printer.print("#[inline(always)]\n");
    printer.print(
        "pub(in $root$::stream) fn rp_new(rp_input: &'a [u8]) -> $M$<'a> { $M$ { rp_input } }\n\n",
        {{"root", table.root}});
    // The handle wraps the message BODY (post-length-prefix) -- the same bytes the arena model's
    // `decode(bytes, &arena)` expects -- so exposing them lets a consumer stream the outer message and
    // materialize a chosen sub-message mid-stream (the stream->arena hybrid), composing the two models
    // without any coupling in the generated code.
    // `$bytes_arena$` (see generate_stream) points to the arena decoder when the file has one.
    printer.print("/// Returns the encoded message.\n$bytes_arena$");
    printer.print("#[inline(always)]\n");
    printer.print("pub fn bytes(&self) -> &'a [u8] { self.rp_input }\n\n");
    printer.print(
        "/// Decodes the message and passes each selected field to `visitor`.\n"
        "///\n"
        "/// Returns `Flow::Stop` if a handler stopped the decode. Fails if a handler returns an\n"
        "/// error or the message is malformed. A sub-message is checked only when a handler\n"
        "/// decodes it.\n");
    printer.print(
        "pub fn decode<V: $Vis$<'a>>(self, mut visitor: V) "
        "-> ::core::result::Result<::rapidproto::stream::Flow, ::rapidproto::DecodeError> {\n");
    printer.indent();
    printer.print("let rp_body: &'a [u8] = self.rp_input;\n");
    printer.print("let mut rp_rest: &'a [u8] = rp_body;\n");
    emit_stream_prologue(printer, table, slots);
    printer.print("loop {\n");
    printer.indent();
    emit_peek_hub(printer, loop_read(), "rp_tag");
    printer.print("match rp_tagkey {\n");
    printer.indent();
    for (const StreamSlot& slot : slots) {
        emit_stream_arm(printer, table, slot);
    }
    emit_stream_unknown_arm(printer, msg);
    printer.outdent();
    printer.print("}\n");  // match
    printer.outdent();
    printer.print("}\n");  // loop
    printer.print("::core::result::Result::Ok(::rapidproto::stream::Flow::Continue)\n");
    printer.outdent();
    printer.print("}\n");  // decode
    printer.outdent();
    printer.print("}\n");  // impl
}

// The per-message `<name>_stream!` macro. The expansion runs at the caller's call site, so everything
// it names (the trait, the value types, its own recursion, the runtime) is a path from `$crate` through
// the module the file is included at. So the caller needs nothing in scope but the macro's own name, and
// every module on that path must be visible to the caller.
//
// The macro is a token muncher. Its two public arms (`{ field => |value| .. }` and `(&mut state;
// { field => |state, value| .. })`) start one `@f` accumulator whose head records the form (`[]` /
// `[state]`); one arm per field (plus `unknown`) appends a row `WANT_<f> on_<f>: V = closure;`; a
// fallback turns a mistyped field into a `compile_error!` listing the selectable ones; and the
// terminal arm hands the rows to the runtime's `stream_visitor!`, which builds the visitor -- so the
// per-field boilerplate lives once, in the runtime. Expands to O(k) for k selected fields; the
// definition is O(N).
//
// A macro reachable from another crate must be `#[macro_export]`, which defines it at the crate root,
// hence the crate-root-unique `__rp_<path>_<fqn>`. It is re-exported at the module path under its
// friendly name (`#[doc(inline)]`, so rustdoc shows it there). The `pub use` binds ONLY the macro
// namespace, since the hidden name exists only there: a same-named submodule (`message FooStream {
// message In {} }` holds its nested types in `foo_stream`) does not clash with it (E0255). The recursion
// goes through that friendly path, unlike `$crate::<hidden>!`, which the deny-by-default
// `macro_expanded_macro_exports_accessed_by_absolute_paths` rejects for `include!`d code.
void emit_stream_macro(Printer& printer, const NameTable& table, const MessageNode& msg,
                       const std::vector<StreamSlot>& slots, const std::string& macro_name) {
    const std::string module =
        "$" + tree_module_path(table, "stream", table.messages.at(msg.fqn).module);
    printer.set("mac", macro_name);
    printer.set("def", stream_export_name(table.root, msg));
    printer.set("self", module + "::" + macro_name);
    printer.set("rt", stream_runtime_path(table));
    printer.set("trait", module + "::" + table.messages.at(msg.fqn).visitor_name);
    std::string valid_keys;  // for the unknown-field compile_error
    for (const StreamSlot& slot : slots) {
        valid_keys += slot.name + ", ";
    }
    valid_keys += "unknown";
    printer.set("valid", valid_keys);

    printer.print(
        "/// Builds an implementation of [`$Vis$`] from handlers, one per selected field.\n"
        "///\n"
        "/// With `$mac$! { field => |value| .. }`, each handler captures its own state.\n"
        "/// With `$mac$!(&mut state; { field => |state, value| .. })`, the handlers share\n"
        "/// `state`. The key `unknown` selects the fields the schema does not declare.\n");

    printer.print("#[doc(hidden)]\n#[macro_export]\n");
    printer.print("macro_rules! $def$ {\n");
    printer.indent();
    printer.print(
        "($$($$f:ident => $$c:expr),* $$(,)?) => { $self$!(@f [[]] $$($$f => $$c,)*) };\n");
    printer.print(
        "($$s:expr; {$$($$f:ident => $$c:expr),* $$(,)?}) => { $self$!(@f [[$$s]] "
        "$$($$f => $$c,)*) };\n");
    // One row per selectable field: its key, the trait const and method it overrides, and its value
    // type at the visitor impl's lifetime `'rp_a`.
    const auto row = [&](const std::string& key, const std::string& want, const std::string& type) {
        printer.print(
            "(@f [$$($$a:tt)*] $k$ => $$c:expr, $$($$r:tt)*) => { $self$!(@f [$$($$a)* $w$ "
            "on_$k$: $t$ = $$c;] $$($$r)*) };\n",
            {{"k", key}, {"w", want}, {"t", type}});
    };
    for (const StreamSlot& slot : slots) {
        row(slot.name, "WANT_" + slot.name, stream_slot_value_type(table, slot, "'rp_a", true));
    }
    row("unknown", "WANT_UNKNOWN", stream_runtime_path(table) + "::stream::UnknownField<'rp_a>");
    // Fallback: an `ident =>` that matched none of the field arms above is a mistyped or unsupported
    // field. Name it and list the selectable fields, instead of the bare "no rules expected this
    // token" a muncher would otherwise give. Must come after every field arm.
    printer.print(
        "(@f $$a:tt $$bad:ident => $$c:expr, $$($$r:tt)*) => { "
        "::core::compile_error!(::core::concat!(\"unknown field `\", ::core::stringify!($$bad), "
        "\"` for this message; selectable fields: $valid$\")) };\n");
    printer.print("(@f $$a:tt) => { $rt$::stream_visitor!($trait$<'rp_a> $$a) };\n");
    printer.outdent();
    printer.print("}\n");
    printer.print("#[doc(inline)]\npub use $def$ as $mac$;\n");
}

// Emit one message's streaming decoder: the visitor trait, the reader handle + decode driver, and the
// builder macro. `macro_name` is pre-deduped against siblings.
void emit_stream_message(Printer& printer, const NameTable& table, const MessageNode& msg,
                         const std::string& macro_name) {
    const std::vector<StreamSlot> slots = collect_stream_slots(msg);
    printer.set("M", table.messages.at(msg.fqn).type_name);
    printer.set("Vis", table.messages.at(msg.fqn).visitor_name);
    printer.set("mac_hint", macro_name);
    printer.set("proto", proto_name(msg.fqn));
    emit_stream_visitor_trait(printer, table, slots);
    printer.print("\n");
    emit_stream_decode(printer, table, msg, slots);
    printer.print("\n");
    emit_stream_macro(printer, table, msg, slots, macro_name);
}

// Recursively emit the stream decoders for a list of sibling messages: each message, followed -- when
// it has nested messages -- by a `pub mod <submodule>` (the same table-assigned name as the arena tree)
// holding the nested decoders. Builder-macro names (`<snake>_stream`) are deduped among siblings (macros
// share one namespace).
void emit_stream_messages(Printer& printer, const NameTable& table,
                          const std::vector<const MessageNode*>& msgs) {
    std::unordered_set<std::string> macro_names;
    for (std::size_t i = 0; i < msgs.size(); ++i) {
        if (i != 0) {
            printer.print("\n");
        }
        const std::string macro_name = dedup_ident(
            macro_names,
            to_snake_case(ident_identity(table.messages.at(msgs[i]->fqn).type_name)) + "_stream");
        emit_stream_message(printer, table, *msgs[i], macro_name);
        if (!msgs[i]->nested_messages.empty()) {
            printer.print("\n");
            emit_nested_module_open(printer, table.messages.at(msgs[i]->fqn).submodule, *msgs[i]);
            emit_stream_messages(printer, table, addrs(msgs[i]->nested_messages));
            printer.outdent();
            printer.print("}\n");
        }
    }
}

// Emit the `stream` subtree for one package node: this package's message decoders, then a
// `pub mod <component>` per sub-package that has any (mirroring `emit_arena_node`).
void emit_stream_node(Printer& printer, const NameTable& table, const PkgTrie& node) {
    emit_stream_messages(printer, table, node_messages(node));
    for (const auto& [component, child] : node.children) {
        if (!subtree_has_messages(child)) {
            continue;
        }
        printer.print("\n");
        emit_package_module_open(printer, child);
        emit_stream_node(printer, table, child);
        printer.outdent();
        printer.print("}\n");
    }
}

// Goes on every top-level generated item, so that including a generated file adds no diagnostics to
// the consumer's crate. `warnings` covers every lint the crate has at warning level. The other names
// cover a crate that raises a lint to `deny`: the lints a private include trips, including clippy's
// restriction lints, two of which (`allow_attributes`, `allow_attributes_without_reason`) this
// attribute itself trips. Naming a lint the crate forbids is a hard error (E0453) even if the lint
// would not fire, so a crate that forbids one of these, such as `unused_variables` or any restriction
// lint, cannot include generated code. Nothing else is named for that reason. A crate that denies an
// unnamed lint, such as `missing_docs` on a public include, can add its own allow around the include.
constexpr const char* kModuleLints =
    "#[allow(warnings, dead_code, unused_imports, unused_macros, unused_mut, unused_variables, "
    "nonstandard_style, unreachable_pub, single_use_lifetimes, unused_qualifications, clippy::all, "
    "clippy::pedantic, clippy::nursery, clippy::restriction)]\n";

// The version of the contract between generated code and the runtime. The runtime's `rp_abi!` macro
// accepts only this number, and its comment in rust/rapidproto/src/lib.rs says when to bump both.
constexpr int kGeneratedAbi = 1;

// A module of compile-time checks on the file.
// The first fails unless the runtime accepts this code's version number. rustc reports macro errors
// before name and type errors, so mismatched versions of rapidproto and rapidproto-build report this
// error first instead of dozens about the runtime's internals. A runtime older than the check has no
// `rp_abi!`, and the comment on the line is then the only hint, so it must fit an 80-column error.
// The second fails unless the file is included at `module_path`, by reaching its own private constant
// through that path. Nothing else checks the path of a file whose types never refer to each other,
// whose macros would then fail at their first call, possibly in another crate. The comment shares the
// path's line because rustc shows that line in the error.
std::string file_checks(const std::string& module_path) {
    Printer printer;
    printer.print(kModuleLints);
    printer.print("#[doc(hidden)]\nmod rp_check {\n");
    printer.indent();
    printer.print("::rapidproto::rp_abi!($abi$); // rapidproto must match rapidproto-build.\n",
                  {{"abi", std::to_string(kGeneratedAbi)}});
    printer.print("const C: () = ();\n");
    printer.print(
        "const _: () = $p$::rp_check::C; // This path must be where this file is included.\n",
        {{"p", module_path}});
    printer.outdent();
    printer.print("}\n");
    return printer.str();
}

}  // namespace

std::string generate_common(const std::vector<const FileNode*>& files, bool serde) {
    const PkgTrie root = [&] {
        PkgTrie trie = build_pkg_trie(files);
        assign_emitted_names(trie);
        return trie;
    }();
    if (!subtree_has_enums(root)) {
        return {};
    }
    const NameTable table = build_name_table(root);
    Printer printer;
    printer.print("/// The schema's enums.\n");
    printer.print(kModuleLints);
    printer.print("pub mod common {\n");
    printer.indent();
    emit_common_node(printer, table, root, serde);
    printer.outdent();
    printer.print("}\n");
    return printer.str();
}

std::vector<std::pair<std::string, std::string>> arena_type_paths(
    const std::vector<const FileNode*>& files, const std::string& module_path) {
    // Rebuilds the name table independently of generate_rust (a caller may want the paths alone, and
    // naming is modes-independent, so this stays a standalone entry point). The rebuild is
    // generation-time and O(small).
    PkgTrie root = build_pkg_trie(files);
    assign_emitted_names(root);
    NameTable table = build_name_table(root);
    table.root = module_path;
    table.tree = "arena";
    std::vector<std::pair<std::string, std::string>> out;
    out.reserve(table.messages.size());
    for (const auto& [fqn, names] : table.messages) {
        out.emplace_back(fqn, message_path(table, fqn));
    }
    return out;
}

std::string generate_arena(const std::vector<const FileNode*>& files, const LayoutSet& layouts,
                           const FieldModes& modes, bool serde, const std::string& module_path) {
    PkgTrie root = build_pkg_trie(files);
    if (!subtree_has_messages(root)) {
        return {};
    }
    assign_emitted_names(root);
    NameTable table = build_name_table(root);
    table.root = module_path;
    table.tree = "arena";
    Printer printer;
    printer.print("/// Arena decoders, which decode a whole message into an arena.\n");
    printer.print(kModuleLints);
    printer.print("pub mod arena {\n");
    printer.indent();
    emit_arena_node(printer, table, root, modes, layouts, serde);
    printer.outdent();
    printer.print("}\n");
    return printer.str();
}

std::string generate_stream(const std::vector<const FileNode*>& files,
                            const std::string& module_path, bool arena) {
    PkgTrie root = build_pkg_trie(files);
    if (!subtree_has_messages(root)) {
        return {};
    }
    assign_emitted_names(root);
    NameTable table = build_name_table(root);
    table.root = module_path;
    table.tree = "stream";
    Printer printer;
    // The rest of a stream struct's `bytes()` doc (emit_stream_decode).
    printer.set(
        "bytes_arena",
        arena ? "///\n/// To decode a sub-message whole, pass these bytes to the arena decoder's "
                "`decode`.\n"
              : "");
    // The runtime's module of this name, for the macros (stream_runtime_path), which can expand in a
    // crate with no direct `rapidproto` dependency. Beside the trees, so no schema name can meet it.
    printer.print(kModuleLints);
    printer.print("#[doc(hidden)]\npub use ::rapidproto::rp_rt;\n\n");
    printer.print("/// Stream decoders, which pass the fields you select to your handlers.\n");
    printer.print(kModuleLints);
    printer.print("pub mod stream {\n");
    printer.indent();
    emit_stream_node(printer, table, root);
    printer.outdent();
    printer.print("}\n");
    return printer.str();
}

std::string generate_file(const std::vector<const FileNode*>& files, const LayoutSet& layouts,
                          const FieldModes& modes, const RustOptions& options) {
    // A header comment records the active field-modes profile (its id + canonical drop/raw/unknown
    // lines) for traceability. Rust needs no ODR-style identity guard: a generated file is included
    // once as a self-contained module tree, so two differently-profiled generations cannot silently
    // merge (including both into one scope is a duplicate-module compile error).
    std::string banner = "// @generated by rapidproto-build -- do not edit.\n";
    if (modes.active()) {
        banner += "// field-modes profile " + modes.profile_id + ":\n";
        for (const std::string& line : modes.normalized) {
            banner += "//   " + line + "\n";
        }
    }
    // `common` (shared enum/newtype defs) is emitted whenever any decoder model is, since both the
    // arena and stream trees reference it. At least one model is always selected (the caller enforces
    // it); default is arena only. A tree with nothing in it is left out.
    std::string out = banner + "\n" + file_checks(options.module_path);
    const auto append = [&out](const std::string& tree) {
        if (!tree.empty()) {
            out += "\n" + tree;
        }
    };
    append(generate_common(files, options.serde));
    if (options.arena) {
        append(generate_arena(files, layouts, modes, options.serde, options.module_path));
    }
    if (options.stream) {
        append(generate_stream(files, options.module_path, options.arena));
    }
    return out;
}

}  // namespace rapidproto::rustgen