reallyme-buffa-codegen 0.1.0

ReallyMe fork: Shared code generation logic for buffa (descriptor → Rust source)
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
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
5269
5270
5271
5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
5292
5293
5294
5295
5296
5297
5298
5299
5300
5301
5302
5303
5304
5305
5306
5307
5308
5309
5310
5311
5312
5313
5314
5315
5316
5317
5318
5319
5320
5321
5322
5323
5324
5325
5326
5327
5328
5329
5330
5331
5332
5333
5334
5335
5336
5337
5338
5339
5340
5341
5342
5343
5344
5345
5346
5347
5348
5349
5350
5351
5352
5353
5354
5355
5356
5357
5358
5359
5360
5361
5362
5363
5364
5365
5366
5367
5368
5369
5370
5371
5372
5373
5374
5375
5376
5377
5378
5379
5380
5381
5382
5383
5384
5385
5386
5387
5388
5389
5390
5391
5392
5393
5394
5395
5396
5397
5398
5399
5400
5401
5402
5403
5404
5405
5406
5407
5408
5409
5410
5411
5412
5413
5414
5415
5416
5417
5418
5419
5420
5421
5422
5423
5424
5425
5426
5427
5428
5429
5430
5431
5432
5433
5434
5435
5436
5437
5438
5439
5440
5441
5442
5443
5444
5445
5446
5447
5448
5449
5450
5451
5452
5453
5454
5455
5456
5457
5458
5459
5460
5461
5462
5463
5464
5465
5466
5467
5468
5469
5470
5471
5472
5473
5474
5475
5476
5477
5478
5479
5480
5481
5482
5483
5484
5485
5486
5487
5488
5489
5490
5491
5492
5493
5494
5495
5496
5497
5498
5499
5500
5501
5502
5503
5504
5505
5506
5507
5508
5509
5510
5511
5512
5513
5514
5515
5516
5517
5518
5519
5520
5521
5522
5523
5524
5525
5526
5527
5528
5529
5530
5531
5532
5533
5534
5535
5536
5537
5538
5539
5540
5541
5542
5543
5544
5545
5546
5547
5548
5549
5550
5551
5552
5553
5554
5555
5556
5557
5558
5559
5560
5561
5562
5563
5564
5565
5566
5567
5568
5569
5570
5571
5572
5573
5574
5575
5576
5577
5578
5579
5580
5581
5582
5583
5584
5585
5586
5587
5588
5589
5590
5591
5592
5593
5594
5595
5596
5597
5598
5599
5600
5601
5602
5603
5604
5605
5606
5607
5608
5609
5610
5611
5612
5613
5614
5615
5616
5617
5618
5619
5620
5621
5622
5623
5624
5625
5626
5627
5628
5629
5630
5631
5632
5633
5634
5635
5636
5637
5638
5639
5640
5641
5642
5643
5644
5645
5646
5647
5648
5649
5650
5651
5652
5653
5654
5655
5656
5657
5658
5659
5660
5661
5662
5663
5664
5665
5666
5667
5668
5669
5670
5671
5672
5673
5674
5675
5676
5677
5678
5679
5680
5681
5682
5683
5684
5685
5686
5687
5688
5689
5690
5691
5692
5693
5694
5695
5696
5697
5698
5699
5700
5701
5702
5703
5704
5705
5706
5707
5708
5709
5710
5711
5712
5713
5714
5715
5716
5717
5718
5719
5720
5721
5722
5723
5724
5725
5726
5727
5728
5729
5730
5731
5732
5733
5734
5735
5736
5737
5738
5739
5740
5741
5742
5743
5744
5745
5746
5747
5748
5749
5750
5751
5752
5753
5754
5755
5756
5757
5758
5759
5760
5761
5762
5763
5764
5765
5766
5767
5768
5769
5770
5771
5772
5773
5774
5775
5776
5777
5778
5779
5780
5781
5782
5783
5784
5785
5786
5787
5788
5789
5790
5791
5792
5793
5794
5795
5796
5797
5798
5799
5800
5801
5802
5803
5804
5805
5806
5807
5808
5809
5810
5811
5812
5813
5814
5815
5816
5817
5818
5819
5820
5821
5822
5823
5824
5825
5826
5827
5828
5829
5830
5831
5832
5833
5834
5835
5836
5837
5838
5839
5840
5841
5842
5843
5844
5845
5846
5847
5848
5849
5850
5851
5852
5853
5854
5855
5856
5857
5858
5859
5860
5861
5862
5863
5864
5865
5866
5867
5868
5869
5870
5871
5872
5873
5874
5875
5876
5877
5878
5879
5880
5881
5882
5883
5884
5885
5886
5887
5888
5889
5890
5891
5892
5893
5894
5895
5896
5897
5898
5899
5900
5901
5902
5903
5904
5905
5906
5907
5908
5909
5910
5911
5912
5913
5914
5915
5916
5917
5918
5919
5920
5921
5922
5923
5924
5925
5926
5927
5928
5929
5930
5931
5932
5933
5934
5935
5936
5937
5938
5939
5940
5941
5942
5943
5944
5945
5946
5947
5948
5949
5950
5951
5952
5953
5954
5955
5956
5957
5958
5959
5960
5961
5962
5963
5964
5965
5966
5967
5968
5969
5970
5971
5972
5973
5974
5975
5976
5977
5978
5979
5980
5981
5982
5983
5984
5985
5986
5987
5988
5989
5990
5991
5992
5993
5994
5995
5996
5997
5998
5999
6000
6001
6002
6003
6004
6005
6006
6007
6008
6009
6010
6011
6012
6013
6014
6015
6016
6017
6018
6019
6020
6021
6022
6023
6024
6025
6026
6027
6028
6029
6030
6031
6032
6033
6034
6035
6036
6037
6038
6039
6040
6041
6042
6043
6044
6045
6046
6047
6048
6049
6050
6051
6052
6053
6054
6055
6056
6057
6058
6059
6060
6061
6062
6063
6064
6065
6066
6067
6068
6069
6070
6071
6072
6073
6074
6075
6076
6077
6078
6079
6080
6081
6082
6083
6084
6085
6086
6087
6088
6089
6090
6091
6092
6093
6094
6095
6096
6097
6098
6099
6100
6101
6102
6103
6104
6105
6106
6107
6108
6109
// Modified by ReallyMe Technologies Limited.
//! Shared code generation logic for buffa.
//!
//! This crate takes protobuf descriptors (`google.protobuf.FileDescriptorProto`,
//! decoded from binary `FileDescriptorSet` data) and emits Rust source code
//! that uses the `buffa` runtime.
//!
//! It is used by:
//! - `protoc-gen-reallyme-buffa` (protoc plugin)
//! - `buffa-build` (build.rs integration)
//!
//! # Architecture
//!
//! The code generator is intentionally decoupled from how descriptors are
//! obtained. It receives fully-resolved `FileDescriptorProto`s and produces
//! Rust source strings. This means:
//!
//! - It doesn't parse `.proto` files.
//! - It doesn't invoke `protoc`.
//! - It doesn't do import resolution or name linking.
//!
//! All of that is handled upstream (by protoc, buf, or a future parser).

pub(crate) mod comments;
pub mod context;
pub(crate) mod defaults;
pub(crate) mod enumeration;
pub(crate) mod extension;
pub(crate) mod feature_gates;
pub use feature_gates::FeatureGateNames;
pub(crate) mod features;
pub(crate) mod field_names;
#[doc(hidden)]
pub use buffa_descriptor::generated;
pub(crate) mod feature_overrides;
pub mod idents;
pub(crate) mod impl_message;
pub(crate) mod impl_text;
pub(crate) mod imports;
pub(crate) mod json_policy;
pub(crate) mod lazy_view;
pub(crate) mod message;
pub(crate) mod oneof;
pub(crate) mod owned_view;
pub(crate) mod reflect;
pub(crate) mod reflect_owned;
pub(crate) mod reflect_view;
pub(crate) mod table_codec;
pub(crate) mod table_plan;
pub(crate) mod view;

use crate::generated::descriptor::{DescriptorProto, EnumDescriptorProto, FileDescriptorProto};
use proc_macro2::TokenStream;
use quote::{format_ident, quote};

const GENERATED_HEADER: &str = concat!(
    "// @generated by reallyme-buffa-codegen ",
    env!("CARGO_PKG_VERSION"),
    ". DO NOT EDIT.\n",
    "// Modified by ReallyMe Technologies Limited.\n",
);

/// Environment variable overriding the element-memory bound buffa's tooling
/// applies when decoding a descriptor set.
///
/// Accepts a byte count, or `unlimited` / `max` (both lowercase) for no bound.
/// A value that is not valid UTF-8 is treated as unset.
pub const ELEMENT_MEMORY_LIMIT_ENV: &str = "BUFFA_ELEMENT_MEMORY_LIMIT";

/// Element-memory bound buffa's build tooling applies to a descriptor set —
/// the `protoc` plugins to a `CodeGeneratorRequest`, `buffa-build` to a
/// `FileDescriptorSet`.
///
/// Much higher than [`buffa::DEFAULT_ELEMENT_MEMORY_LIMIT`], which is sized for
/// untrusted input: a build's descriptors come from a compiler the caller
/// invoked, or a file the caller named. It is deliberately not unbounded, so a
/// truncated or corrupt descriptor set still fails with an error rather than
/// exhausting memory.
///
/// 1 GiB is roughly twice what the largest schemas need. Descriptor types are
/// wide structs, so the element footprint runs several times the encoded size
/// — around 6x in practice, making this about 160 MB of descriptors.
pub const TOOLING_ELEMENT_MEMORY_LIMIT: usize = 1024 * 1024 * 1024;

/// Decode options for a descriptor set produced by the caller's own build,
/// honouring [`ELEMENT_MEMORY_LIMIT_ENV`].
///
/// The override is an environment variable rather than a `protoc` plugin
/// option because the options string travels *inside* the request: it cannot
/// be read until the request has already been decoded.
///
/// # Errors
///
/// Returns a message naming the variable if its value is not a byte count or
/// `unlimited` / `max`.
pub fn tooling_decode_options() -> Result<buffa::DecodeOptions, String> {
    let raw = std::env::var(ELEMENT_MEMORY_LIMIT_ENV).ok();
    let limit = parse_element_memory_limit(raw.as_deref())?;
    Ok(buffa::DecodeOptions::new().with_element_memory_limit(limit))
}

/// Describe a failure to decode a descriptor set, naming the override when the
/// element-memory bound is what rejected it.
///
/// `subject` is the message being decoded, e.g. `"CodeGeneratorRequest"`.
/// `limit` is the bound that was actually in force, which is not
/// [`TOOLING_ELEMENT_MEMORY_LIMIT`] once the environment overrides it — read it
/// back with `DecodeOptions::element_memory_limit`.
///
/// The bare error text names no remedy, and whoever hits the bound is exactly
/// who needs [`ELEMENT_MEMORY_LIMIT_ENV`] — so the hint belongs on the message
/// they see, not only in the guide.
#[must_use]
pub fn decode_failure(subject: &str, err: &buffa::DecodeError, limit: usize) -> String {
    let base = format!("failed to decode {subject}: {err}");
    match err {
        buffa::DecodeError::ElementMemoryLimitExceeded => format!(
            "{base}\n\
             These descriptors exceed the {budget} element-memory budget in force. \
             Raise it with the {opt}=<bytes> plugin option or the {env} environment \
             variable; either accepts 'unlimited'. See \"Very large schemas\" in the \
             buffa guide.",
            budget = describe_byte_budget(limit),
            opt = ELEMENT_MEMORY_LIMIT_OPT,
            env = ELEMENT_MEMORY_LIMIT_ENV,
        ),
        _ => base,
    }
}

/// Render a byte budget for a human: MiB once that is a whole number, bytes
/// below that. A sub-MiB limit is legitimate (the environment variable takes a
/// raw byte count), and truncating it to "0 MiB" would make the hint absurd.
fn describe_byte_budget(bytes: usize) -> String {
    const MIB: usize = 1024 * 1024;
    if bytes >= MIB && bytes % MIB == 0 {
        format!("{} MiB", bytes / MIB)
    } else {
        format!("{bytes}-byte")
    }
}

/// Plugin option, settable in the `protoc`/`buf` parameter string, that sets
/// the element-memory bound used to decode the request carrying it.
pub const ELEMENT_MEMORY_LIMIT_OPT: &str = "element_memory_limit";

/// Read `CodeGeneratorRequest.parameter` (field 2) straight off the wire,
/// without decoding the request.
///
/// An option that governs how the request itself is decoded cannot be read
/// from the decoded request. Scanning for the one field is what makes such
/// options possible: it skips every other field rather than materialising it,
/// so the cost is a wire walk, not a decode — microseconds against the tens of
/// milliseconds a full decode of a large request takes.
///
/// Returns `None` when the request carries no parameter.
///
/// # Errors
///
/// Returns a [`DecodeError`](buffa::DecodeError) if the bytes are not
/// well-formed protobuf, or if the parameter is not valid UTF-8.
pub fn peek_request_parameter(mut buf: &[u8]) -> Result<Option<&str>, buffa::DecodeError> {
    use buffa::encoding::{decode_varint, skip_field, Tag, WireType};

    /// `CodeGeneratorRequest.parameter`.
    const PARAMETER_FIELD: u32 = 2;

    let mut found = None;
    while !buf.is_empty() {
        let tag = Tag::decode(&mut buf)?;
        if tag.field_number() == PARAMETER_FIELD && tag.wire_type() == WireType::LengthDelimited {
            let len = usize::try_from(decode_varint(&mut buf)?)
                .map_err(|_| buffa::DecodeError::MessageTooLarge)?;
            if len > buf.len() {
                return Err(buffa::DecodeError::UnexpectedEof);
            }
            let (value, rest) = buf.split_at(len);
            // Last wins, matching how protobuf merges a repeated scalar field.
            found = Some(core::str::from_utf8(value).map_err(|_| buffa::DecodeError::InvalidUtf8)?);
            buf = rest;
            continue;
        }
        skip_field(tag, &mut buf)?;
    }
    Ok(found)
}

/// Find `element_memory_limit=<value>` in a `protoc` plugin parameter string.
///
/// Returns `None` when the option is absent, leaving
/// [`ELEMENT_MEMORY_LIMIT_ENV`] and then [`TOOLING_ELEMENT_MEMORY_LIMIT`] to
/// supply the value.
///
/// # Errors
///
/// Returns a message if the option is present with an unparseable value.
pub fn element_memory_limit_opt(parameter: &str) -> Result<Option<usize>, String> {
    let mut found = None;
    for entry in parameter.split(',').map(str::trim) {
        if let Some((key, value)) = entry.split_once('=') {
            if key.trim() == ELEMENT_MEMORY_LIMIT_OPT {
                found = Some(parse_element_memory_limit(Some(value))?);
            }
        }
    }
    Ok(found)
}

/// Decode a `CodeGeneratorRequest` from a `protoc` plugin's stdin.
///
/// The element-memory bound is taken from the `element_memory_limit` plugin
/// option if the request carries one, else [`ELEMENT_MEMORY_LIMIT_ENV`], else
/// [`TOOLING_ELEMENT_MEMORY_LIMIT`]. The option is read by scanning for it
/// ([`peek_request_parameter`]) rather than from the decoded request, since it
/// governs that decode.
///
/// Both plugins compose exactly this, so it lives here: a hint improved in one
/// binary should never disagree with the other.
///
/// # Errors
///
/// Returns a message describing the failure, naming the ways to raise the
/// bound when that is what rejected the request.
pub fn decode_request(input: &[u8]) -> Result<generated::compiler::CodeGeneratorRequest, String> {
    let parameter = peek_request_parameter(input)
        .map_err(|e| format!("failed to read the plugin parameter: {e}"))?
        .unwrap_or_default();
    let options = match element_memory_limit_opt(parameter)? {
        Some(limit) => buffa::DecodeOptions::new().with_element_memory_limit(limit),
        None => tooling_decode_options()?,
    };
    options
        .decode_from_slice::<generated::compiler::CodeGeneratorRequest>(input)
        .map_err(|e| decode_failure("CodeGeneratorRequest", &e, options.element_memory_limit()))
}

/// Resolve [`ELEMENT_MEMORY_LIMIT_ENV`]'s value to a byte count.
///
/// `None` and an all-whitespace value both mean "unset", yielding
/// [`TOOLING_ELEMENT_MEMORY_LIMIT`].
///
/// # Errors
///
/// Returns a message naming the variable if the value is neither a byte count
/// nor `unlimited` / `max`.
pub(crate) fn parse_element_memory_limit(raw: Option<&str>) -> Result<usize, String> {
    let Some(raw) = raw else {
        return Ok(TOOLING_ELEMENT_MEMORY_LIMIT);
    };
    match raw.trim() {
        "" => Ok(TOOLING_ELEMENT_MEMORY_LIMIT),
        "unlimited" | "max" => Ok(usize::MAX),
        n => n.parse::<usize>().map_err(|_| {
            format!("{ELEMENT_MEMORY_LIMIT_ENV}: expected a byte count or 'unlimited', got '{raw}'")
        }),
    }
}

/// Lints suppressed on generated code at module boundaries.
///
/// Consumed by [`generate_module_tree`], the per-package `.mod.rs`
/// stitcher, and `buffa-build`'s `_include.rs` writer. One list keeps
/// them in sync.
pub const ALLOW_LINTS: &[&str] = &[
    "non_camel_case_types",
    "dead_code",
    "unused_imports",
    // Cross-proto refs within the same package are emitted through the
    // canonical `super::super::__buffa::view::…` path even though the
    // target lives in the same generated module — using the bare name
    // would resolve, but the canonical path is stable when a sibling
    // proto defines a same-named natural-path re-export.
    "unused_qualifications",
    "clippy::derivable_impls",
    "clippy::match_single_binding",
    "clippy::uninlined_format_args",
    "clippy::doc_lazy_continuation",
    // A user `message View { message Inner }` produces
    // `__buffa::view::view::InnerView`; harmless but trips this lint.
    "clippy::module_inception",
];

/// Render [`ALLOW_LINTS`] as a `#[allow(…)]` attribute token stream.
pub fn allow_lints_attr() -> TokenStream {
    let lints: Vec<TokenStream> = ALLOW_LINTS
        .iter()
        .map(|l| syn::parse_str(l).expect("lint name parses as path"))
        .collect();
    quote! { #[allow( #(#lints),* )] }
}

/// One generated output file.
///
/// Each `.proto` produces up to five **content files** (`<stem>.rs`,
/// `<stem>.__view.rs`, `<stem>.__oneof.rs`, `<stem>.__view_oneof.rs`,
/// `<stem>.__ext.rs`) and each proto package produces one
/// `<dotted.pkg>.mod.rs` **stitcher** that `include!`s the content files
/// and authors the `pub mod __buffa { … }` ancillary tree.
/// Ancillary kinds with no content for that input file (e.g. a message
/// with no oneofs and no extensions) are omitted, and the stitcher's
/// `include!` set is filtered to match. The `__buffa` wrapper (and each
/// `view` / `oneof` / `ext` submodule inside it) is itself omitted when
/// it would be empty, so packages with only owned messages emit no
/// `__buffa` block at all.
/// See `DESIGN.md` → "Generated code layout".
///
/// Consumers normally only need to wire up the
/// [`GeneratedFileKind::PackageMod`] entries (one per package); the
/// per-proto content kinds are reached transitively via `include!` from
/// the stitcher. Write all files to disk; build a module tree from only
/// the `PackageMod` ones.
///
/// With [`CodeGenConfig::file_per_package`] set, the per-proto content
/// kinds are not emitted at all — the single `<dotted.pkg>.rs` (still
/// kind `PackageMod`) inlines what the stitcher would `include!`.
#[derive(Debug)]
pub struct GeneratedFile {
    /// The output file path (e.g., `"my.pkg.foo.rs"` or `"my.pkg.mod.rs"`).
    pub name: String,
    /// The proto package this file belongs to.
    pub package: String,
    /// What this file contains. Build integrations only need to wire up
    /// [`GeneratedFileKind::PackageMod`] files; everything else is reached
    /// via `include!` from there.
    pub kind: GeneratedFileKind,
    /// The generated Rust source code.
    pub content: String,
}

/// Kind of [`GeneratedFile`].
///
/// [`generate`] produces up to five per-proto content kinds — one each
/// of [`Owned`](Self::Owned), [`View`](Self::View), [`Oneof`](Self::Oneof),
/// [`ViewOneof`](Self::ViewOneof), and [`Ext`](Self::Ext) per input
/// `.proto` file — plus one [`PackageMod`](Self::PackageMod) stitcher per
/// package. Kinds with no content for the input (a proto with no oneofs
/// emits no [`Oneof`](Self::Oneof) / [`ViewOneof`](Self::ViewOneof);
/// no extensions, no [`Ext`](Self::Ext); etc.) are omitted. Build
/// integrations only need to wire up `PackageMod` entries; the per-proto
/// content kinds are reached via `include!` from the stitcher and need
/// only be written to disk alongside it. Under
/// [`CodeGenConfig::file_per_package`] only `PackageMod` is emitted.
///
/// [`Companion`](Self::Companion) is the one kind *not* produced by
/// [`generate`]: downstream code generators construct `Companion` files
/// themselves and merge them into buffa's output via
/// [`apply_companions`].
///
/// This enum is `#[non_exhaustive]` — match with a wildcard arm so new
/// kinds can be added without a major version bump.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub enum GeneratedFileKind {
    /// Owned message structs and enums (`<stem>.rs`).
    Owned,
    /// View structs (`<stem>.__view.rs`).
    View,
    /// Lazy view structs (`<stem>.__lazy_view.rs`).
    LazyView,
    /// Owned oneof enums (`<stem>.__oneof.rs`).
    Oneof,
    /// View oneof enums (`<stem>.__view_oneof.rs`).
    ViewOneof,
    /// File-level proto-extension consts (`<stem>.__ext.rs`) — the
    /// `pub const` `ExtensionDescriptor` items generated from `extend`
    /// blocks. Not to be confused with [`Companion`](Self::Companion),
    /// which is unrelated downstream-supplied content.
    Ext,
    /// Per-package stitcher (`<dotted.pkg>.mod.rs`). The only file build
    /// systems need to wire up directly.
    PackageMod,
    /// Extra per-proto content from a downstream code generator (service
    /// stubs, extra trait impls, etc.) that travels with buffa's output.
    ///
    /// Not produced by [`generate`]. Construct these in your own generator
    /// and pass them to [`apply_companions`], which appends an `include!`
    /// for each one at file scope in the matching package's
    /// [`PackageMod`](Self::PackageMod) — after buffa's own output, at
    /// package root alongside the owned message types (**not** under the
    /// `__buffa::` sentinel module). Items declared `pub` in a companion
    /// file are visible at `crate::<pkg>::*`.
    ///
    /// Not to be confused with [`Ext`](Self::Ext), which is the buffa-
    /// generated file holding protobuf `extend` consts.
    Companion,
}

/// Parse a custom owned-type path string (e.g. `"::smol_str::SmolStr"`) into a
/// token stream, validating it as a Rust type so a malformed path surfaces as a
/// codegen error rather than unparseable generated output.
pub(crate) fn parse_custom_type_path(path: &str) -> Result<proc_macro2::TokenStream, CodeGenError> {
    let ty: syn::Type =
        syn::parse_str(path).map_err(|_| CodeGenError::InvalidTypePath(path.to_string()))?;
    Ok(quote::quote! { #ty })
}

/// Parse a custom **map** container path, which is applied as `path<K, V>`.
///
/// The path must therefore be a bare type path with no `<...>` parameters of its
/// own (and, unlike the box/repeated knobs, no `*` placeholder — a map's key and
/// value are appended positionally). Reject anything else with a message that
/// names the convention, rather than letting `Foo<Bar><K, V>` surface as an
/// opaque whole-file parse error later.
pub(crate) fn parse_custom_map_path(path: &str) -> Result<proc_macro2::TokenStream, CodeGenError> {
    let ty: syn::Type = syn::parse_str(path).map_err(|_| {
        CodeGenError::InvalidTypePath(format!(
            "{path} (map custom path takes no `<K, V>` parameters and no `*` placeholder)"
        ))
    })?;
    let syn::Type::Path(tp) = &ty else {
        return Err(CodeGenError::InvalidTypePath(format!(
            "{path} (map custom path must be a plain type path)"
        )));
    };
    if tp
        .path
        .segments
        .iter()
        .any(|s| !matches!(s.arguments, syn::PathArguments::None))
    {
        return Err(CodeGenError::InvalidTypePath(format!(
            "{path} (map custom path must not include `<K, V>`; the key and value are appended automatically)"
        )));
    }
    Ok(quote::quote! { #ty })
}

/// Build a custom wrapper type from a `*`-templated path and a resolved inner
/// type, validating the result as a Rust type.
///
/// `*` cannot be a parsed placeholder (it is not valid in Rust type position),
/// so substitution is textual — every `*` in `template` is replaced by `inner`'s
/// token text before the whole string is parsed. Used by the pluggable pointer
/// knob, where the wrapped type sits inside extra generic parameters (e.g.
/// `"smallbox::SmallBox<*, S4>"`). The template must contain at least one `*`.
pub(crate) fn parse_wildcard_type_path(
    template: &str,
    inner: &proc_macro2::TokenStream,
) -> Result<proc_macro2::TokenStream, CodeGenError> {
    if !template.contains('*') {
        return Err(CodeGenError::MissingWildcard(template.to_string()));
    }
    let substituted = template.replace('*', &inner.to_string());
    let ty: syn::Type = syn::parse_str(&substituted)
        .map_err(|_| CodeGenError::InvalidTypePath(format!("{template} (as {substituted})")))?;
    Ok(quote::quote! { #ty })
}

/// Build a custom collection type from a `*`-templated path and the resolved
/// element type, validating the result as a Rust type.
///
/// `*` cannot be a parsed placeholder (it is not valid in Rust type position),
/// so substitution is textual — every `*` in `template` is replaced by the
/// element's token text before the whole string is parsed. The template must
/// contain at least one `*`, otherwise the element type would have nowhere to
/// go and the field would silently drop its element type.
pub(crate) fn parse_custom_list_path(
    template: &str,
    elem: &proc_macro2::TokenStream,
) -> Result<proc_macro2::TokenStream, CodeGenError> {
    if !template.contains('*') {
        return Err(CodeGenError::MissingListPlaceholder(template.to_string()));
    }
    let substituted = template.replace('*', &elem.to_string());
    let ty: syn::Type = syn::parse_str(&substituted)
        .map_err(|_| CodeGenError::InvalidTypePath(template.to_string()))?;
    Ok(quote::quote! { #ty })
}

/// The Rust type a proto `string` field maps to in generated owned structs.
///
/// The default is [`String`](StringRepr::String).
/// [`Custom`](StringRepr::Custom) substitutes any type named by its
/// fully-qualified Rust path — for example `::smol_str::SmolStr`,
/// `::ecow::EcoString`, or `::compact_str::CompactString` for read-mostly
/// schemas — that satisfies the `buffa::ProtoString` bound. The downstream crate
/// must itself depend on the crate providing that type (buffa does not re-export
/// it).
///
/// Select a representation through `buffa_build`'s `string_type` /
/// `string_type_custom` builder methods. The wire format is identical regardless
/// of representation — only the in-memory owned type changes, and view types
/// keep borrowing `&str`. A rule that matches a `map` field applies to its
/// `string` key and its `string` value.
#[derive(Debug, Clone, PartialEq, Eq, Default)]
#[non_exhaustive]
pub enum StringRepr {
    /// `::buffa::alloc::string::String` — growable and mutable (the default).
    #[default]
    String,
    /// A custom type named by its fully-qualified Rust path (e.g.
    /// `"::smol_str::SmolStr"`). Must satisfy `buffa::ProtoString` and be
    /// provided by a crate the downstream depends on.
    ///
    /// # Limitations
    ///
    /// - With `generate_reflection_vtable`, a *foreign* custom type used as a
    ///   `repeated` element or as a `map` key or value fails to compile (the
    ///   emitted `ReflectElement` / `ReflectMapKey` impl violates the orphan
    ///   rule). Wrap it in a crate-local newtype, or set
    ///   [`CodeGenConfig::emit_custom_type_impls`] to `false` when the defining
    ///   crate supplies those integrations. Singular / optional / oneof uses
    ///   work with a foreign type directly.
    /// - A custom type used as a `map` key must implement `Hash + Eq` for
    ///   [`MapRepr::HashMap`], or `Ord` for [`MapRepr::BTreeMap`].
    /// - With `generate_json`, a custom type on an `optional`, `repeated` or
    ///   oneof field, or used as a `map` key or value, must implement
    ///   `serde::Serialize` and `serde::Deserialize`. A singular field without
    ///   `optional` needs no `serde` impl.
    /// - A path that does not parse as a Rust type surfaces as
    ///   [`CodeGenError::InvalidTypePath`] at generation (`.compile()`) time.
    /// - The per-element impls are deduplicated within a single generation, but
    ///   the *same* crate-local type used as a `repeated` element across two
    ///   separate `compile()` invocations in one crate emits the impl twice (a
    ///   duplicate-impl `E0119`). Generate from a single `compile()`, use
    ///   distinct element types, or disable generated integrations and provide
    ///   them once in the defining crate.
    Custom(String),
}

impl StringRepr {
    /// The owned Rust type path emitted for a `string` field with this
    /// representation.
    ///
    /// `ctx` and `nesting` route the default `String` through the package-root
    /// import registry (`idiomatic_imports`); a custom path is parsed and
    /// emitted fully qualified.
    ///
    /// # Errors
    ///
    /// Returns [`CodeGenError::InvalidTypePath`] if a custom path does not parse
    /// as a Rust type.
    pub(crate) fn type_path(
        &self,
        resolver: &imports::ImportResolver,
        ctx: &context::CodeGenContext,
        nesting: usize,
    ) -> Result<proc_macro2::TokenStream, CodeGenError> {
        match self {
            StringRepr::String => Ok(resolver.string_at(ctx, nesting)),
            StringRepr::Custom(path) => parse_custom_type_path(path),
        }
    }

    /// Whether this is the default `String` representation, which keeps the
    /// `String`-specialized fast paths (in-place `merge_string`, `clear()`,
    /// native `Arbitrary`) instead of the generic `ProtoString` ones.
    pub(crate) fn is_default(&self) -> bool {
        matches!(self, StringRepr::String)
    }
}

/// The Rust type a proto `bytes` field maps to in generated owned structs.
///
/// The default is [`Vec`](BytesRepr::Vec) (`Vec<u8>`). [`Bytes`](BytesRepr::Bytes)
/// uses `bytes::Bytes`, which decodes zero-copy from a
/// `Bytes`-backed buffer. [`Custom`](BytesRepr::Custom) substitutes any type
/// named by its fully-qualified Rust path that satisfies the `buffa::ProtoBytes`
/// bound; the downstream crate must itself depend on the providing crate.
///
/// Select a representation through `buffa_build`'s `bytes_type` /
/// `bytes_type_custom` builder methods (or the legacy `use_bytes_type`, which
/// selects [`Bytes`](BytesRepr::Bytes)). The wire format is identical regardless
/// of representation, and view types keep borrowing `&[u8]`. A rule that
/// matches a `map` field applies to its `bytes` value. One map shape keeps
/// `Vec<u8>` values whatever rule matches: a map whose `string` key is mapped
/// to `bytes` by [`strict_utf8_mapping`](CodeGenConfig::strict_utf8_mapping)
/// (`utf8_validation = NONE` on the key) and whose value is `bytes`.
#[derive(Debug, Clone, PartialEq, Eq, Default)]
#[non_exhaustive]
pub enum BytesRepr {
    /// `::buffa::alloc::vec::Vec<u8>` — growable and mutable (the default).
    #[default]
    Vec,
    /// `::buffa::bytes::Bytes` — reference-counted, immutable, decodes zero-copy
    /// from a `Bytes`-backed buffer.
    Bytes,
    /// A custom type named by its fully-qualified Rust path. Must satisfy
    /// `buffa::ProtoBytes` and be provided by a crate the downstream depends on.
    ///
    /// # Limitations
    ///
    /// - A *foreign* custom type used as a `repeated` element fails to compile
    ///   (the emitted `ReflectElement` / `ProtoElemJson` impls violate the
    ///   orphan rule). Wrap it in a crate-local newtype, or set
    ///   [`CodeGenConfig::emit_custom_type_impls`] to `false` when the defining
    ///   crate supplies those integrations. Singular / optional / oneof uses
    ///   work with a foreign type directly.
    /// - A `Custom` rule applies to `map<K, bytes>` values, as
    ///   [`Bytes`](BytesRepr::Bytes) does. With `generate_json` or
    ///   `generate_reflection_vtable`, codegen emits `ProtoElemJson` /
    ///   `ReflectElement` impls for the value type, so it must be a
    ///   crate-local type unless generated integrations are disabled.
    /// - A path that does not parse as a Rust type surfaces as
    ///   [`CodeGenError::InvalidTypePath`] at generation (`.compile()`) time.
    /// - The per-element impls are deduplicated within a single generation, but
    ///   the *same* crate-local type used as a `repeated` element across two
    ///   separate `compile()` invocations in one crate emits the impl twice (a
    ///   duplicate-impl `E0119`). Generate from a single `compile()`, use
    ///   distinct element types, or disable generated integrations and provide
    ///   them once in the defining crate.
    Custom(String),
}

impl BytesRepr {
    /// The owned Rust type path emitted for a `bytes` field with this
    /// representation.
    ///
    /// `ctx` and `nesting` route the default `Vec<u8>` through the package-root
    /// import registry; `Bytes` and a custom path are emitted fully qualified.
    ///
    /// # Errors
    ///
    /// Returns [`CodeGenError::InvalidTypePath`] if a custom path does not parse
    /// as a Rust type.
    pub(crate) fn type_path(
        &self,
        resolver: &imports::ImportResolver,
        ctx: &context::CodeGenContext,
        nesting: usize,
    ) -> Result<proc_macro2::TokenStream, CodeGenError> {
        use quote::quote;
        match self {
            BytesRepr::Vec => {
                let vec = resolver.vec_at(ctx, nesting);
                Ok(quote! { #vec<u8> })
            }
            BytesRepr::Bytes => Ok(quote! { ::buffa::bytes::Bytes }),
            BytesRepr::Custom(path) => parse_custom_type_path(path),
        }
    }

    /// Whether this is the default `Vec<u8>` representation, which keeps the
    /// `Vec`-specialized fast paths (in-place `merge_bytes`, `clear()`, native
    /// `Arbitrary`) instead of the generic `ProtoBytes` ones.
    pub(crate) fn is_default(&self) -> bool {
        matches!(self, BytesRepr::Vec)
    }
}

/// The owned Rust collection a proto `map<K, V>` field maps to in generated
/// owned structs.
///
/// The default is [`HashMap`](MapRepr::HashMap) (`std::collections::HashMap`, or
/// `hashbrown::HashMap` under `no_std`). [`BTreeMap`](MapRepr::BTreeMap) selects
/// the buffa-provided `alloc::collections::BTreeMap` for deterministic iteration
/// order with no extra dependency or consumer code.
/// [`Custom`](MapRepr::Custom) substitutes any map that satisfies the
/// `buffa::map_codec::MapStorage` bound — for example a crate-local newtype
/// wrapping `indexmap::IndexMap`.
///
/// Unlike the `repeated` knob (which wraps the element type and needs a `*`
/// placeholder template), a map type is always `path<K, V>` with both
/// parameters positional and buffa-resolved, so a custom path is a plain type
/// path (e.g. `"::my_crate::OrderedMap"`) with no placeholder.
///
/// Select a representation through `buffa_build`'s `map_type` /
/// `map_type_custom` builder methods. The wire format is identical regardless of
/// the collection; only the in-memory owned type changes.
#[derive(Debug, Clone, PartialEq, Eq, Default)]
#[non_exhaustive]
pub enum MapRepr {
    /// `::buffa::__private::HashMap<K, V>` — the default. Generated output is
    /// byte-identical to a build without the knob.
    #[default]
    HashMap,
    /// `::buffa::alloc::collections::BTreeMap<K, V>` — buffa-provided, no extra
    /// dependency, deterministic key order (so encoded bytes are stable across
    /// runs). The key type must be `Ord`, which every proto map key type
    /// (integers, bool, string) satisfies.
    BTreeMap,
    /// A custom map named by a fully-qualified Rust type path (e.g.
    /// `"::my_crate::OrderedMap"`). The named type must satisfy
    /// `buffa::map_codec::MapStorage` and be a **crate-local newtype** (a foreign
    /// map cannot implement the buffa-owned reflection / serde traits).
    ///
    /// # Limitations
    ///
    /// - The path is a plain type path applied as `path<K, V>` — it must **not**
    ///   include the `<K, V>` parameters or a `*` placeholder. A path that does
    ///   not parse as a Rust type surfaces as [`CodeGenError::InvalidTypePath`]
    ///   at generation (`.compile()`) time.
    /// - The newtype must implement `buffa::map_codec::MapStorage` plus the
    ///   derive / `FromIterator` / `ReflectMap` / serde / `arbitrary` bounds
    ///   listed on that trait's docs (the canonical list). JSON and `arbitrary`
    ///   now work for every proto map key/value type regardless of the container.
    ///   The buffa-provided [`BTreeMap`](MapRepr::BTreeMap) already satisfies every
    ///   bound, so prefer it unless you need a specific foreign map.
    Custom(String),
}

impl MapRepr {
    /// The owned Rust map type emitted for a `map<K, V>` field with this
    /// representation, given the already-resolved key and value type tokens.
    ///
    /// `ctx` and `nesting` route the default `HashMap` through the package-root
    /// import registry; `BTreeMap` and a custom path are emitted fully
    /// qualified.
    ///
    /// # Errors
    ///
    /// Returns [`CodeGenError::InvalidTypePath`] if a custom path does not parse
    /// as a Rust type.
    pub(crate) fn type_path(
        &self,
        key: &proc_macro2::TokenStream,
        value: &proc_macro2::TokenStream,
        resolver: &imports::ImportResolver,
        ctx: &context::CodeGenContext,
        nesting: usize,
    ) -> Result<proc_macro2::TokenStream, CodeGenError> {
        use quote::quote;
        match self {
            MapRepr::HashMap => {
                let hm = resolver.hashmap_at(ctx, nesting);
                Ok(quote! { #hm<#key, #value> })
            }
            MapRepr::BTreeMap => Ok(quote! { ::buffa::alloc::collections::BTreeMap<#key, #value> }),
            MapRepr::Custom(path) => {
                let ty = parse_custom_map_path(path)?;
                Ok(quote! { #ty<#key, #value> })
            }
        }
    }

    /// Whether this is the default `HashMap` representation, whose generated
    /// output is byte-identical to a build without the knob.
    pub(crate) fn is_default(&self) -> bool {
        matches!(self, MapRepr::HashMap)
    }
}

/// The owned smart pointer a singular message field's `buffa::MessageField`
/// wraps in generated owned structs.
///
/// The default is [`Inline`](PointerRepr::Inline); it was `Box` before 0.9.
/// [`Custom`](PointerRepr::Custom)
/// substitutes any pointer that satisfies the `buffa::ProtoBox<T>` bound — for
/// example a `smallbox`-style pointer that stores small messages inline.
/// Because the pointer *wraps* the message type, its path is a **template**
/// containing a `*` placeholder for the message type (e.g.
/// `"::smallbox::SmallBox<*, ::smallbox::space::S4>"` or
/// `"::my_crate::SmallBox<*>"`).
///
/// Because `buffa::ProtoBox` is buffa-owned, a *foreign* pointer cannot
/// implement it directly (orphan rule) — the template must name a crate-local
/// newtype, mirroring the `ProtoString` newtype expectation.
///
/// Select a representation through `buffa_build`'s `box_type_custom` builder
/// method. The wire format is identical regardless of the pointer; view types
/// are unaffected. Applies to singular message fields and **boxed** oneof
/// message/group variants (a variant opted into inline storage via
/// `unboxed_oneof_fields` takes precedence and gets no pointer). Repeated
/// message fields use a collection, not a pointer.
#[derive(Debug, Clone, PartialEq, Eq, Default)]
#[non_exhaustive]
pub enum PointerRepr {
    /// `::buffa::alloc::boxed::Box<T>` (inside `MessageField<T>`). The opt-out
    /// from the `Inline` default for large or rarely-set submessages, via
    /// `box_type_in(PointerRepr::Box, paths)` (or `box_type(PointerRepr::Box)`
    /// to restore the pre-0.9 global default).
    Box,
    /// `::buffa::Inline<T>` — store the message directly in the parent struct,
    /// no heap allocation. `MessageField<T, Inline<T>>` is laid out as
    /// `Option<T>`. The default.
    ///
    /// Recursion-aware: a singular field that would form an infinite-size cycle
    /// (directly, mutually, or via an
    /// [`unbox_oneof`](CodeGenConfig::unboxed_oneof_fields)-inlined oneof
    /// variant) is silently kept on `Box`, so the default is always sized. An
    /// *exact-path* `Inline` rule that names a recursive field is rejected at
    /// codegen time.
    #[default]
    Inline,
    /// A custom pointer named by a Rust type-path **template** with a `*`
    /// placeholder for the message type. Must satisfy `buffa::ProtoBox<T>` and
    /// be a crate-local newtype.
    ///
    /// # Limitations
    ///
    /// - The template must contain at least one `*`; a template that omits it
    ///   surfaces as [`CodeGenError::MissingWildcard`], and one whose
    ///   substitution does not parse as [`CodeGenError::InvalidTypePath`], at
    ///   generation (`.compile()`) time.
    /// - `Rc` / `Arc` and other shared/COW pointers are unusable: the decoder
    ///   merges in place (needs `DerefMut`), so only an exclusively-owned
    ///   pointer (heap `Box`, inline `SmallBox`) can implement `ProtoBox`.
    /// - An inline pointer inflates the parent struct per field, so select it
    ///   per field/prefix, never as a blanket default.
    /// - On a **boxed oneof variant** under the `arbitrary` feature, the custom
    ///   pointer must implement `arbitrary::Arbitrary` (the oneof enum derives it
    ///   and stores the pointer directly in the variant). The singular-field path
    ///   needs no such impl — `MessageField` constructs the pointer itself.
    /// - With JSON generation enabled, custom pointers do not need
    ///   `serde::Serialize` or `serde::Deserialize`: singular message fields
    ///   and message-valued oneof variants serialize the pointee, while decode
    ///   paths construct the pointer through `ProtoBox`.
    Custom(String),
}

impl PointerRepr {
    /// The owned `MessageField<...>` type emitted for a singular message field
    /// with this representation, given the resolved inner message type tokens
    /// and the `MessageField` path from the resolver.
    ///
    /// # Errors
    ///
    /// Returns [`CodeGenError::MissingWildcard`] if a custom template omits `*`,
    /// or [`CodeGenError::InvalidTypePath`] if it does not parse once the message
    /// type is substituted.
    pub(crate) fn type_path(
        &self,
        message_field: &proc_macro2::TokenStream,
        inner: &proc_macro2::TokenStream,
    ) -> Result<proc_macro2::TokenStream, CodeGenError> {
        use quote::quote;
        match self {
            PointerRepr::Box => Ok(quote! { #message_field<#inner> }),
            PointerRepr::Inline => Ok(quote! { #message_field<#inner, ::buffa::Inline<#inner>> }),
            PointerRepr::Custom(template) => {
                let ptr = parse_wildcard_type_path(template, inner)?;
                Ok(quote! { #message_field<#inner, #ptr> })
            }
        }
    }

    /// The fully-qualified `::buffa::MessageField::<...>` path for a
    /// `::some(value)` construction of a singular message field with this
    /// representation: `<inner>` for `Box` (the pointer param defaults), or
    /// `<inner, ptr>` for a custom pointer. The view→owned conversion uses this
    /// so the constructed `MessageField` matches the field's declared type.
    ///
    /// # Errors
    ///
    /// As [`type_path`](Self::type_path) for a custom template.
    pub(crate) fn some_path(
        &self,
        inner: &proc_macro2::TokenStream,
    ) -> Result<proc_macro2::TokenStream, CodeGenError> {
        use quote::quote;
        match self {
            PointerRepr::Box => Ok(quote! { ::buffa::MessageField::<#inner> }),
            PointerRepr::Inline => {
                Ok(quote! { ::buffa::MessageField::<#inner, ::buffa::Inline<#inner>> })
            }
            PointerRepr::Custom(template) => {
                let ptr = parse_wildcard_type_path(template, inner)?;
                Ok(quote! { ::buffa::MessageField::<#inner, #ptr> })
            }
        }
    }

    /// The bare pointer type wrapping `inner` for a **boxed oneof variant**
    /// (`Box<inner>` by default, or the custom pointer). Unlike
    /// [`type_path`](Self::type_path) this is the pointer alone, not wrapped in
    /// `MessageField`, because a oneof enum stores the pointer directly in the
    /// variant.
    ///
    /// # Errors
    ///
    /// As [`type_path`](Self::type_path) for a custom template.
    pub(crate) fn pointer_type(
        &self,
        inner: &proc_macro2::TokenStream,
    ) -> Result<proc_macro2::TokenStream, CodeGenError> {
        use quote::quote;
        match self {
            PointerRepr::Box => Ok(quote! { ::buffa::alloc::boxed::Box<#inner> }),
            PointerRepr::Inline => Ok(quote! { ::buffa::Inline<#inner> }),
            PointerRepr::Custom(template) => parse_wildcard_type_path(template, inner),
        }
    }

    /// Construct the pointer from a value expression for a boxed oneof variant:
    /// `Box::new(value)` (byte-identical default) or the fully-qualified
    /// `<Ptr as ProtoBox<inner>>::new(value)` for a custom pointer (so an
    /// inherent `new` on the pointer can't shadow the trait method).
    ///
    /// # Errors
    ///
    /// As [`type_path`](Self::type_path) for a custom template.
    pub(crate) fn pointer_new(
        &self,
        inner: &proc_macro2::TokenStream,
        value: &proc_macro2::TokenStream,
    ) -> Result<proc_macro2::TokenStream, CodeGenError> {
        use quote::quote;
        match self {
            PointerRepr::Box => Ok(quote! { ::buffa::alloc::boxed::Box::new(#value) }),
            PointerRepr::Inline => Ok(quote! { ::buffa::Inline(#value) }),
            PointerRepr::Custom(template) => {
                let ptr = parse_wildcard_type_path(template, inner)?;
                Ok(quote! { <#ptr as ::buffa::ProtoBox<#inner>>::new(#value) })
            }
        }
    }
}

/// The owned Rust collection a proto `repeated` field maps to in generated
/// owned structs.
///
/// The default is [`Vec`](RepeatedRepr::Vec) (`Vec<T>`).
/// [`Custom`](RepeatedRepr::Custom) substitutes any collection that satisfies
/// the `buffa::ProtoList<T>` bound — for example a crate-local newtype wrapping
/// a `SmallVec`-backed inline collection. Unlike the scalar `string`/`bytes`
/// knobs the custom collection *wraps* the element type, so its path is a
/// **template** containing a `*` placeholder where the element type is
/// substituted (e.g. `"::my_crate::SmallList<*>"`).
///
/// Because `buffa::ProtoList` is buffa-owned, a *foreign* collection cannot
/// implement it directly (orphan rule) — the template must always name a
/// crate-local newtype, mirroring the `ProtoString` newtype expectation.
///
/// Select a representation through `buffa_build`'s `repeated_type_custom`
/// builder method. The wire format is identical regardless of the collection;
/// view types keep borrowing `&[T]`.
#[derive(Debug, Clone, PartialEq, Eq, Default)]
#[non_exhaustive]
pub enum RepeatedRepr {
    /// `::buffa::alloc::vec::Vec<T>` — the default. Keeps the `Vec`-specialized
    /// fast paths (in-place `push`/`reserve`/`clear`, native `Arbitrary`)
    /// instead of the generic `ProtoList` ones, so generated output for the
    /// default is byte-identical to a build without the knob.
    #[default]
    Vec,
    /// A custom collection named by a Rust type-path **template** with a `*`
    /// placeholder for the element type (e.g. `"::my_crate::SmallList<*>"`). The
    /// named type must satisfy `buffa::ProtoList<T>` and be a **crate-local
    /// newtype** (a foreign collection cannot implement the buffa-owned
    /// `ProtoList`).
    ///
    /// # Limitations
    ///
    /// - The template must contain at least one `*`; the element type is
    ///   substituted for every `*` before the result is parsed as a Rust type.
    ///   A template that omits `*` surfaces as
    ///   [`CodeGenError::MissingListPlaceholder`], and one whose substitution
    ///   does not parse as [`CodeGenError::InvalidTypePath`], at generation
    ///   (`.compile()`) time.
    /// - A custom collection always needs a crate-local newtype — this is not
    ///   limited to the reflection path. The generated decode and clear code
    ///   require `Field: ProtoList`, so even a binary-only build cannot use a
    ///   foreign collection directly.
    /// - Under reflection / vtable the newtype must implement
    ///   `buffa_descriptor`'s `ReflectList` (a `Vec`-backed newtype can delegate
    ///   to the inner `Vec<T>: ReflectList`). Under JSON it must implement
    ///   `serde::Serialize` / `Deserialize`; under the `arbitrary` feature,
    ///   `arbitrary::Arbitrary` (derivable on a newtype).
    /// - A `repeated <self-type>` field becomes `Collection<Self>`, so the
    ///   collection must be heap-backed; an inline collection (`SmallVec<[Self;
    ///   N]>`) would be infinitely sized and fail to compile.
    Custom(String),
}

impl RepeatedRepr {
    /// The owned Rust collection type emitted for a `repeated` field with this
    /// representation, given the already-resolved element type tokens.
    ///
    /// `ctx` and `nesting` route the default `Vec` through the package-root
    /// import registry; a custom template has its `*` placeholders replaced by
    /// `elem` and the result is parsed and emitted fully qualified.
    ///
    /// # Errors
    ///
    /// Returns [`CodeGenError::MissingListPlaceholder`] if a custom template
    /// omits `*`, or [`CodeGenError::InvalidTypePath`] if it does not parse as a
    /// Rust type once the element is substituted.
    pub(crate) fn type_path(
        &self,
        elem: &proc_macro2::TokenStream,
        resolver: &imports::ImportResolver,
        ctx: &context::CodeGenContext,
        nesting: usize,
    ) -> Result<proc_macro2::TokenStream, CodeGenError> {
        use quote::quote;
        match self {
            RepeatedRepr::Vec => {
                let vec = resolver.vec_at(ctx, nesting);
                Ok(quote! { #vec<#elem> })
            }
            RepeatedRepr::Custom(template) => parse_custom_list_path(template, elem),
        }
    }

    /// Whether this is the default `Vec` representation, which keeps the
    /// `Vec`-specialized fast paths instead of the generic `ProtoList` ones.
    pub(crate) fn is_default(&self) -> bool {
        matches!(self, RepeatedRepr::Vec)
    }
}

/// How much reflection support generated types get.
///
/// Selected through `buffa_build`'s `reflect_mode` builder method (or the
/// `protoc-gen-reallyme-buffa` `reflect_mode=` option). All modes need the consuming
/// crate to depend on `buffa-descriptor` with its `reflect` feature and on
/// `std`; the call site is `foo.reflect().get(fd)` regardless of mode.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
#[non_exhaustive]
pub enum ReflectMode {
    /// No reflection impls.
    #[default]
    Off,
    /// `Reflectable::reflect()` round-trips the message through a
    /// `DynamicMessage` (encode → decode → boxed handle). Smaller generated
    /// code; pays an allocation and a re-encode per `reflect()` call.
    Bridge,
    /// `impl ReflectMessage` directly on the owned and view types, and
    /// `Reflectable::reflect()` borrows `self` with no round-trip. Larger
    /// generated code; near-free reflective access. Does not require view
    /// generation — with views off, only the owned impls are emitted.
    VTable,
}

impl ReflectMode {
    /// Apply this mode to a [`CodeGenConfig`] (sets `generate_reflection` /
    /// `generate_reflection_vtable`). Used by the `buffa-build` and
    /// `protoc-gen-reallyme-buffa` front-ends.
    pub fn apply(self, config: &mut CodeGenConfig) {
        let (reflection, vtable) = match self {
            ReflectMode::Off => (false, false),
            ReflectMode::Bridge => (true, false),
            ReflectMode::VTable => (true, true),
        };
        config.generate_reflection = reflection;
        config.generate_reflection_vtable = vtable;
    }
}

/// A path-scoped protobuf editions feature override, applied by mutating the
/// parsed descriptors before generation (see
/// [`feature_overrides`](CodeGenConfig::feature_overrides)).
///
/// Editions unification models proto2 and proto3 as editions with fixed
/// feature defaults, so an override's semantics are "what this proto would
/// say had it been migrated to editions and this feature set at this path".
/// Each variant is admitted only once buffa's codegen, runtime, and
/// validation handle the descriptor states it can create — the enum is the
/// allowlist. Overrides never change the wire format.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub enum FeatureOverride {
    /// Override `features.enum_type` for matching enums or enum fields.
    ///
    /// An enum-type path mutates the enum's own descriptor (a spec-valid
    /// editions construct that also flows into the embedded reflection
    /// pool); a field path injects a field-level override that buffa
    /// resolves onto the field, in both generated code and the
    /// descriptor-driven codecs. `enum_type` is not a legal field target in
    /// the spec, so other runtimes reading the exported descriptors ignore a
    /// field path.
    EnumType(EnumTypeOverride),
}

impl FeatureOverride {
    /// The editions feature name this override sets, as spelled in
    /// `google.protobuf.FeatureSet` (e.g. for diagnostics).
    #[must_use]
    pub fn feature_name(&self) -> &'static str {
        match self {
            Self::EnumType(_) => "enum_type",
        }
    }

    /// The feature value this override sets, as spelled in the descriptor
    /// enum (e.g. for diagnostics).
    #[must_use]
    pub fn value_name(&self) -> &'static str {
        match self {
            Self::EnumType(EnumTypeOverride::Open) => "OPEN",
        }
    }
}

/// Supported values for [`FeatureOverride::EnumType`].
///
/// Only `OPEN` is currently supported — closing an open enum would
/// reintroduce closed-enum unknown-value routing on fields that never had
/// it, a combination buffa's codegen does not yet validate or test.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub enum EnumTypeOverride {
    /// `features.enum_type = OPEN`: matching closed enum fields generate as
    /// `EnumValue<E>`, making unknown wire values directly visible as
    /// `EnumValue::Unknown(n)`.
    Open,
}

/// How a message's binary [`Message`](https://docs.rs/reallyme-buffa/latest/buffa/trait.Message.html)
/// implementation is generated. Select it with
/// [`CodeGenConfig::codec_strategy`] and [`CodeGenConfig::codec_strategy_in`].
///
/// The strategy changes only the code that sizes, writes and decodes a message
/// in the binary wire format. It never changes the wire format, and JSON, text,
/// view and reflection code are generated the same way under either.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
#[non_exhaustive]
pub enum CodecStrategy {
    /// Emit code specialised to each message: the fastest code, and the
    /// largest. The default.
    #[default]
    Unrolled,
    /// Emit one static table per message and forward `Message` to interpreters
    /// shared by every message, in the `buffa` crate. On a large schema it
    /// makes the compiled code about 40% smaller at `opt-level = "z"`; a
    /// message that cannot use it keeps its size. It costs run time on messages
    /// made of many small fields. The guide's "Smaller generated code" section
    /// has the measurements.
    ///
    /// Not every message can use it. These stay [`Unrolled`](Self::Unrolled):
    ///
    /// - a message with a group field;
    /// - the message type of a group field;
    /// - a message that uses the `MessageSet` wire format;
    /// - a message with extension ranges, when JSON code is generated and
    ///   unknown fields are preserved;
    /// - a message with a `map` field, when `map_entries_omit_defaults` is
    ///   set: the table writes both fields of every entry;
    /// - a message with a field of a non-default string, bytes, or collection
    ///   type, such as `use_bytes_type`, `string_type`, `bytes_type`,
    ///   `repeated_type`, and a custom `map_type` select. `HashMap` and
    ///   `BTreeMap` maps are supported; a `map` whose keys or values are of a
    ///   non-default string or bytes type is not;
    /// - a message that holds, in a singular, repeated, `oneof`, or map value
    ///   field, a message of the same run that has a `bytes` field of a
    ///   non-default type, or that holds one. The table decodes from one
    ///   contiguous slice, so it would copy `bytes::Bytes` fields that
    ///   unrolled code decoding from a `Bytes` shares with the input.
    ///
    /// A table message may hold any other message, including as a member of a
    /// `oneof` and as a `map` value. It reaches a child that is a table
    /// message through the child's table, and any other child, whether it is
    /// [`Unrolled`](Self::Unrolled), generated by another crate, or a
    /// well-known type, through the child's `Message` impl, which costs a
    /// function call per child. Selecting a message does not select the
    /// messages it holds, and keeping a child [`Unrolled`](Self::Unrolled) does
    /// not keep the messages that hold it unrolled: to keep a whole path
    /// specialised, set its holders to `Unrolled` too.
    ///
    /// A table message differs from an unrolled one in these ways. A field that
    /// declares a length past the end of its enclosing message fails at once
    /// with `DecodeError::UnexpectedEof`, where unrolled code can report a
    /// different error for the same rejected input; a child reached through its
    /// `Message` impl is read from the slice of the nearest enclosing table
    /// message, so it is bounded there. `clear()` resets the message to its
    /// default, which releases the capacity of its strings, vectors and maps,
    /// where unrolled code keeps it.
    /// Decoding gathers a `Buf` that is not contiguous into one buffer first.
    /// Encoding into any sink other than the cursor that `Message::encode` and
    /// its siblings write a `BufMut` through, meaning a `Rope`, a sink defined
    /// outside `buffa`, or a `BufMut` passed straight to `Message::write_to`,
    /// stages each child reached through its `Message` impl in a scratch
    /// buffer, and a `Rope` copies it again and cannot share the `bytes`
    /// fields inside it by reference count. Codegen cannot see the fields of a
    /// message from another crate, so a table message that holds one with a
    /// `bytes` field of a non-default type copies it on decode. The well-known
    /// type `google.protobuf.Any` is one, because its `value` is
    /// `bytes::Bytes`. To keep the payload shared with a `Bytes` input, set the
    /// holder to [`Unrolled`](Self::Unrolled) with `codec_strategy_in`.
    ///
    /// A message that another crate or codegen run uses as the type of a group
    /// or editions `DELIMITED` field must not be selected, because
    /// `Message::merge_field` on a table message cannot gather a
    /// non-contiguous buffer, and the default group decoding calls it. Codegen
    /// sees only the group fields of its own run.
    ///
    /// Codegen reports the messages that fall back in one
    /// [`CodeGenWarning::TableCodecFallbackSummary`]. The table code needs Rust
    /// 1.77 or later, and contains `unsafe` code inside `buffa` macros, so it
    /// compiles under `#![forbid(unsafe_code)]`.
    Table,
}

/// Why some messages selected for [`CodecStrategy::Table`] fell back to
/// [`CodecStrategy::Unrolled`], for
/// [`CodeGenWarning::TableCodecFallbackSummary`].
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub struct TableCodecFallbackReason {
    /// The reason as a predicate, such as `has a group field`. The wording is for
    /// people and may change between releases.
    pub reason: String,
    /// The proto paths of all of them, with a leading dot, in declaration
    /// order.
    pub messages: Vec<String>,
}

/// Configuration for code generation.
#[derive(Debug, Clone)]
#[non_exhaustive]
pub struct CodeGenConfig {
    /// Generate recursive `Zeroize`, `ZeroizeOnDrop` and `Drop` for messages,
    /// oneofs and the owned storage of their views. Borrowed input is not wiped.
    /// Requires the runtime's `zeroize` feature, guarded custom bytes/string
    /// representations, and unknown-field storage disabled. Collections default
    /// to wipe-owning runtime collections; referenced messages must also support cleanup.
    /// Reflection uses borrowed `InspectMessage` access without snapshots.
    /// Arbitrary construction uses an early cleanup owner and a depth bound.
    pub generate_zeroize: bool,
    /// Proto path prefixes selecting messages for recursive cleanup.
    /// `.` selects every generated message, including nested messages.
    pub zeroize_messages: Vec<String>,
    /// Message prefixes whose views reject JSON serialization before writing output.
    /// The restriction propagates to containing messages, including through maps
    /// and imported descriptors. Owned-message JSON is unchanged. `.` selects all.
    /// Every rule must match a known message, including imported messages.
    pub deny_view_json: Vec<String>,
    /// Permit message selectors that belong to another directory-scoped plugin
    /// request. Such selectors still produce warnings. Keep this disabled when
    /// validating the complete project so misspelled security rules are errors.
    pub allow_unmatched_message_rules: bool,

    /// Whether to generate borrowed view types (`MyMessageView<'a>`) in
    /// addition to owned types.
    pub generate_views: bool,
    /// Whether to additionally generate the lazy view family
    /// (`MyMessageLazyView<'a>`) alongside the eager views (default: false).
    ///
    /// Lazy views implement `buffa::LazyMessageView`: `decode_lazy` performs
    /// a single non-recursive scan, recording singular/repeated message
    /// fields as undecoded byte ranges (`LazyMessageFieldView` /
    /// `LazyRepeatedView`) that decode on access — reading a few fields of
    /// many sub-messages no longer allocates or recurses into untouched
    /// sub-trees. The eager `MyMessageView` family is unchanged (output is
    /// byte-identical with or without this flag), so eager and lazy views
    /// coexist and generic `MessageView` consumers never silently inherit
    /// deferred validation.
    ///
    /// Semantics of the lazy family:
    ///
    /// - **Eager carve-outs**: groups / editions `DELIMITED` fields (no
    ///   length prefix to defer), oneof message variants, and map message
    ///   values use the eager view types.
    /// - **Merge preserved**: a singular message field split across wire
    ///   occurrences is recorded as fragments and merged on access.
    /// - **Budgets flow**: the recursion depth, unknown-field allowance, and
    ///   element-memory budget remaining at each deferred field are recorded
    ///   and replayed per access (a per-subtree approximation of the shared
    ///   budgets).
    /// - **Deferred validation**: malformed deferred bytes error on access,
    ///   from the fallible `to_owned_message`, and as a serde error from the
    ///   view `Serialize` impl. `ViewEncode` replays recorded fragments
    ///   **without validating them**.
    /// - No `ReflectMessage`, `OwnedView`, or text-format surface — use the
    ///   eager family for those.
    ///
    /// Requires [`generate_views`](Self::generate_views) (the lazy family
    /// reuses the eager view-oneof enums and eager sub-view types); with
    /// views disabled the flag is ignored with a warning.
    pub lazy_views: bool,
    /// Whether to preserve unknown fields (default: true).
    ///
    /// Path-scoped overrides go in
    /// [`preserve_unknown_fields_in`](Self::preserve_unknown_fields_in);
    /// the last matching rule wins over this global default.
    ///
    /// A message with preservation off has no `__buffa_unknown_fields` field,
    /// and with it loses everything built on that field: its `ExtensionSet`
    /// impl (typed extension access), `ReflectMessage::unknown_fields`,
    /// extension round-tripping through textproto, and `[ext]` keys in JSON.
    pub preserve_unknown_fields: bool,
    /// Path-scoped overrides for
    /// [`preserve_unknown_fields`](Self::preserve_unknown_fields). Each entry is
    /// `(proto_path_prefix, enabled)`, with a leading dot (`".pkg.Msg"`).
    ///
    /// Matching uses the same proto-segment-aware prefix rules as
    /// `bytes_fields` and `unboxed_oneof_fields`: a rule covers the message it
    /// names *and every message nested inside it*, and `"."` covers everything.
    /// A rule naming a nested message does not cover its enclosing message. The
    /// **last** matching rule wins, so a later, more specific entry can carve a
    /// nested message back out of an earlier, broader one. Granularity is
    /// per-message: the flag gates whether the struct carries
    /// `__buffa_unknown_fields`. Preservation is a property of each message
    /// type, not of a value graph, so a preserved message's sub-messages keep
    /// their own unknown fields only if their types are covered too.
    ///
    /// A rule that matches no generated message produces a
    /// [`CodeGenWarning::PreserveUnknownFieldsRuleMatchedNothing`].
    pub preserve_unknown_fields_in: Vec<(String, bool)>,
    /// Whether generated JSON deserializers reject unknown fields
    /// (default: `false`, lenient).
    ///
    /// Path-scoped overrides go in
    /// [`deny_unknown_json_fields_in`](Self::deny_unknown_json_fields_in);
    /// the last matching rule wins over this global default. With
    /// [`generate_json`](Self::generate_json) off the setting changes nothing
    /// and produces a [`CodeGenWarning::DenyUnknownJsonFieldsRequiresJson`].
    ///
    /// A strict message rejects every key that matches none of its fields,
    /// under either the JSON name or the proto name, with serde's
    /// `unknown_field` error. `"[pkg.ext]"` keys of a message that has
    /// extension ranges and preserves unknown fields still go through the
    /// extension registry, where `JsonParseOptions::strict_extension_keys`
    /// governs unregistered ones. A message with extension ranges and
    /// preservation off rejects them like any other unknown key.
    pub deny_unknown_json_fields: bool,
    /// Path-scoped overrides for
    /// [`deny_unknown_json_fields`](Self::deny_unknown_json_fields). Each
    /// entry is `(proto_path_prefix, enabled)`, with a leading dot
    /// (`".pkg.Msg"`).
    ///
    /// Matching uses the same proto-segment-aware prefix rules as
    /// [`preserve_unknown_fields_in`](Self::preserve_unknown_fields_in): a
    /// rule covers the message it names *and every message nested inside
    /// it*, `"."` covers everything, and the **last** matching rule wins, so
    /// a later, more specific entry can carve a nested message back out of an
    /// earlier, broader one.
    ///
    /// A rule that matches no generated message produces a
    /// [`CodeGenWarning::DenyUnknownJsonFieldsRuleMatchedNothing`].
    pub deny_unknown_json_fields_in: Vec<(String, bool)>,
    /// Whether to derive `serde::Serialize` / `serde::Deserialize` on
    /// generated message structs and enum types, and emit `#[serde(with = "...")]`
    /// attributes for proto3 JSON's special scalar encodings (int64 as quoted
    /// string, bytes as base64, etc.).
    ///
    /// When this is `true`, the downstream crate must depend on `serde` and
    /// must enable the `buffa/json` feature for the runtime helpers.
    ///
    /// Oneof fields use `#[serde(flatten)]` with custom `Serialize` /
    /// `Deserialize` impls so that each variant appears as a top-level
    /// JSON field (proto3 JSON inline oneof encoding).
    pub generate_json: bool,
    /// Whether to emit `#[cfg_attr(feature = "arbitrary", derive(arbitrary::Arbitrary))]`
    /// on generated message structs and enum types. An enum with a
    /// `[deprecated = true]` variant gets a generated impl under the same
    /// `cfg` instead, because the derive would warn on that variant.
    ///
    /// When this is `true`, the downstream crate must add `arbitrary` as an
    /// optional dependency and enable the `buffa/arbitrary` feature. The
    /// downstream crate's Cargo feature that gates `arbitrary` must be named
    /// exactly `"arbitrary"` — the generated `cfg_attr` uses that literal
    /// string and cannot be customized. This applies to both the struct-level
    /// `derive(Arbitrary)` and the per-field `#[arbitrary(with = ...)]`
    /// attributes described below.
    ///
    /// For a field whose `bytes_fields` or `string_fields` rule selects a
    /// non-default type, codegen emits `#[arbitrary(with = ...)]` using
    /// helpers in `::buffa::__private`, so the substituted type needs no
    /// `Arbitrary` impl. This covers singular, optional, repeated and oneof
    /// fields, and the key and value of a `map` field.
    pub generate_arbitrary: bool,
    /// Proto paths of the messages and enums whose generated `Debug`
    /// implementation is omitted, so that the consuming crate can write its
    /// own.
    ///
    /// For messages a rule is a proto-segment-aware prefix: `".pkg.Msg"`
    /// matches that message and the messages nested inside it, `".pkg"`
    /// matches every message in the package and its sub-packages, and `"."`
    /// matches every message. The oneof enums of a matched message lose
    /// their `Debug` with it. An enum loses its `Debug` only when a rule is
    /// its exact name, such as `".pkg.Level"`. View types keep theirs.
    ///
    /// A matched enum does not compile until the crate implements `Debug`
    /// for it, because `buffa::Enumeration` requires `Debug`. A matched
    /// message needs an impl when an unmatched message or oneof holds it,
    /// because their generated `Debug` formats it, and whenever reflection
    /// is generated, because `ReflectElement` requires `Debug`.
    ///
    /// A rule that matches no generated message and names no generated enum
    /// produces [`CodeGenWarning::SkipDebugRuleMatchedNothing`].
    pub skip_debug: Vec<String>,
    /// External type path mappings.
    ///
    /// Each entry maps either a fully-qualified protobuf package prefix
    /// (e.g., `".my.common"`) to a Rust module path (e.g.,
    /// `"::common_protos"`), or a single type FQN (e.g.,
    /// `".my.common.Shared"`) to a full Rust type path (e.g.,
    /// `"::shared_types::Shared"`). Matched types reference the extern Rust
    /// path instead of being generated, allowing shared proto packages to be
    /// compiled once in a dedicated crate and referenced from others. An
    /// exact type-FQN entry wins over a covering package prefix; otherwise
    /// the longest matching prefix wins.
    ///
    /// The proto side must be `"."` (every type) or a fully-qualified name:
    /// a leading dot, then protobuf identifiers separated by single dots,
    /// with no trailing dot. [`generate`] does not validate entries, and an
    /// entry in another form matches no type; a caller that fills this field
    /// directly should pass each name through
    /// [`normalize_extern_path_proto_name`], as `protoc-gen-reallyme-buffa` and
    /// `buffa-build` do.
    ///
    /// Well-known types (`google.protobuf.*`) are automatically mapped to
    /// `::buffa_types::google::protobuf::*` without needing an explicit
    /// entry here. To override with a custom implementation, add an
    /// `extern_path` for `.google.protobuf` pointing to your crate.
    ///
    /// When JSON generation is enabled, an external message routed through a
    /// ProtoJSON container helper must implement
    /// `buffa::json_helpers::ProtoElemJson` so generated containers can apply
    /// ProtoJSON encoding and reject null elements/values. This includes
    /// external wrapper types in repeated/map fields and external message
    /// values in bytes-keyed maps; ordinary message containers use serde
    /// directly.
    pub extern_paths: Vec<(String, String)>,
    /// Ordered (proto-path-prefix, [`BytesRepr`]) rules selecting the Rust type
    /// for `bytes` fields. Later rules win, so a broad rule (e.g. `"."` →
    /// `Bytes`) can be refined by a more specific one. Fields matching no rule
    /// use `Vec<u8>`.
    ///
    /// A rule is a prefix of a fully-qualified field path, matched on whole
    /// path segments, and starts with a dot: `".my.pkg.Msg.data"`,
    /// `".my.pkg.Msg"`, `".my.pkg"`, or `"."` for every field. Codegen does
    /// not add the dot (`buffa-build` does), and a path without it matches no
    /// field. A rule that does not match a field of a generated message
    /// produces [`CodeGenWarning::FieldTypeRuleMatchedNothing`].
    pub bytes_fields: Vec<(String, BytesRepr)>,
    /// Ordered (proto-path-prefix, [`StringRepr`]) rules selecting the Rust type
    /// for `string` fields. Later rules win, so a broad rule (e.g. `"."` →
    /// `SmolStr`) can be refined by a more specific one
    /// (`".my.pkg.Msg.field"` → `CompactString`). Fields matching no rule use
    /// `String`. The path is matched with the same proto-segment-aware prefix
    /// logic as [`bytes_fields`](Self::bytes_fields).
    ///
    /// Applies to singular, optional, and repeated `string` fields, oneof
    /// `string` variants, and the `string` keys and values of `map` fields
    /// (matched by the map field's path). A rule that does not match a field
    /// of a generated message produces
    /// [`CodeGenWarning::FieldTypeRuleMatchedNothing`].
    pub string_fields: Vec<(String, StringRepr)>,
    /// Custom `bytes` and `string` representations, named by Rust type path
    /// exactly as in their [`BytesRepr::Custom`] / [`StringRepr::Custom`]
    /// rules, whose protobuf JSON goes through `buffa::json_helpers::ProtoBytesJson`
    /// or `ProtoStringJson`.
    ///
    /// Every field of a listed type then serializes and deserializes through
    /// the type's policy: singular, optional, repeated and oneof fields, `map`
    /// values, and the corresponding fields of generated views and owned views.
    /// Paths are compared as parsed Rust types, so whitespace does not matter.
    /// A listed type that no unshadowed representation rule names produces
    /// [`CodeGenError::JsonPolicyTypeMatchedNothing`]; a listed `string` type
    /// used as a key of an enum-valued `map` is a
    /// [`CodeGenError::JsonPolicyMapKey`]. Unlisted
    /// custom types keep their existing JSON behavior.
    pub json_policy_types: Vec<String>,
    /// Emit element JSON/reflection impls for custom bytes/string types.
    ///
    /// Disable this when the representation's defining crate already supplies
    /// `ProtoElemJson`, `ReflectElement`, `ReflectMapKey` and `InspectElement` as needed. This
    /// permits shared foreign representations and separate generation calls
    /// without violating coherence or emitting duplicate implementations.
    /// Missing implementations remain compile errors in the generated code.
    pub emit_custom_type_impls: bool,
    /// Ordered (proto-path-prefix, [`MapRepr`]) rules selecting the owned Rust
    /// map collection for `map` fields. Later rules win, with the same
    /// proto-segment-aware prefix matching as [`bytes_fields`](Self::bytes_fields)
    /// (`"."` matches every field). Fields matching no rule use `HashMap<K, V>`.
    ///
    /// Independent of the element/value representation: a `map` field's key and
    /// value types are chosen by the usual scalar/string/bytes/message rules,
    /// and this option changes only the surrounding collection. A rule that
    /// does not match a field of a generated message produces
    /// [`CodeGenWarning::FieldTypeRuleMatchedNothing`].
    pub map_fields: Vec<(String, MapRepr)>,
    /// Ordered (proto-path-prefix, [`PointerRepr`]) rules selecting the owned
    /// smart pointer for singular message fields (the pointer inside
    /// `MessageField<T>`). Later rules win, same proto-segment-aware prefix
    /// matching as [`bytes_fields`](Self::bytes_fields). Fields matching no rule
    /// use `Box<T>`.
    ///
    /// Applies to singular (and proto2 optional/required) message fields only —
    /// not repeated message fields (a collection) or oneof message variants.
    pub pointer_fields: Vec<(String, PointerRepr)>,
    /// Ordered (proto-path-prefix, [`RepeatedRepr`]) rules selecting the owned
    /// Rust collection for `repeated` fields. Later rules win, with the same
    /// proto-segment-aware prefix matching as [`bytes_fields`](Self::bytes_fields)
    /// (`"."` matches every field). Fields matching no rule use `Vec<T>`.
    ///
    /// Applies only to `repeated` fields (not `map`, whose collection stays
    /// the configured map type). The element type is chosen by the usual
    /// scalar/string/bytes/message rules and substituted into the collection
    /// template. A rule that does not match a field of a generated message
    /// produces [`CodeGenWarning::FieldTypeRuleMatchedNothing`].
    pub repeated_fields: Vec<(String, RepeatedRepr)>,
    /// Path-scoped editions feature overrides, applied by mutating the parsed
    /// descriptors before generation.
    ///
    /// Each entry pairs a fully-qualified proto path prefix with a
    /// [`FeatureOverride`]. Paths are matched with the same
    /// proto-segment-aware logic as [`bytes_fields`](Self::bytes_fields): a
    /// rule may name a type (`".my.pkg.E"`), a field (`".my.pkg.Msg.e"`), a
    /// package/message prefix, or `"."` for everything the override targets.
    /// Leading dots are optional, trailing dots are ignored, and
    /// blank/all-dot entries match nothing. Map enum values match the outer
    /// map field path; oneof enum variants match the direct field path.
    ///
    /// The mutated descriptors are what codegen — and, under reflection, the
    /// embedded descriptor pool — see, so runtime reflection and
    /// descriptor-driven dynamic JSON stay consistent with the generated
    /// types for both enum-scoped and field-scoped rules; see each variant's
    /// docs for its semantics. A rule that matches nothing is reported as
    /// [`CodeGenWarning::FeatureOverrideMatchedNothing`] through
    /// [`generate_with_diagnostics`] (the plain [`generate`] entry point
    /// discards warnings). Overrides never change the wire format. The
    /// default is empty, so generated output and semantics are unchanged
    /// unless configured.
    pub feature_overrides: Vec<(String, FeatureOverride)>,
    /// Fully-qualified proto paths whose message-typed oneof variants should
    /// **not** be wrapped in `Box<T>`. By default every message/group oneof
    /// variant is boxed (so recursive types compile); entries here opt matching
    /// variants out, storing the message inline in the enum.
    ///
    /// Each entry is a proto path prefix matched with the same
    /// proto-segment-aware logic as [`bytes_fields`](Self::bytes_fields)
    /// (`"."` matches every variant). Recursive variants cannot be stored
    /// inline (the type would be unsized): an entry naming one *exactly* is
    /// rejected at codegen time, while a broader prefix entry silently keeps
    /// recursive variants boxed and inlines the rest.
    pub unboxed_oneof_fields: Vec<String>,
    /// Honor `features.utf8_validation = NONE` by emitting `Vec<u8>` / `&[u8]`
    /// for such string fields instead of `String` / `&str`.
    ///
    /// When `false` (the default), buffa emits `String` for all string fields
    /// and **validates UTF-8 on decode** — stricter than proto2 requires, but
    /// ergonomic and safe.
    ///
    /// When `true`, string fields with `utf8_validation = NONE` (all proto2
    /// strings by default, and editions fields that opt into `NONE`) become
    /// `Vec<u8>` / `&[u8]`. Decode skips validation; the caller decides at the
    /// call site whether to `std::str::from_utf8` (checked) or
    /// `from_utf8_unchecked` (trusted-input fast path). This is the only
    /// sound Rust mapping when strings may actually contain non-UTF-8 bytes.
    ///
    /// **This is a breaking change for proto2** — enable only for new code or
    /// when profiling identifies UTF-8 validation as a bottleneck.
    pub strict_utf8_mapping: bool,
    /// Permit `option message_set_wire_format = true` on input messages.
    ///
    /// MessageSet is a legacy Google-internal wire format that wraps each
    /// extension in a group structure instead of using regular field tags.
    /// When `false` (the default), encountering such a message is a codegen
    /// error — the flag exists to make MessageSet use explicit, since the
    /// format is obsolete outside of interop with very old Google protos.
    pub allow_message_set: bool,
    /// Whether to emit `impl buffa::text::TextFormat` on generated message
    /// structs for textproto (human-readable text format) encoding/decoding.
    ///
    /// When this is `true`, the downstream crate must enable the `buffa/text`
    /// feature for the runtime encoder/decoder.
    pub generate_text: bool,
    /// Whether the per-package `.mod.rs` stitcher emits
    /// `__buffa::register_types(&mut TypeRegistry)`.
    ///
    /// Default `true`. The fn aggregates `Any` type entries and extension
    /// entries for every message in the package. Set to `false` for
    /// crates that don't use extensions/`Any`, or that hand-roll
    /// registration (e.g. `buffa-types`' `register_wkt_types`, which
    /// knows the JSON-Any `is_wkt` special-casing the generic fn does
    /// not). The per-message `__*_JSON_ANY` / `__*_TEXT_ANY` consts are
    /// still emitted; only the aggregating fn is suppressed.
    pub emit_register_fn: bool,
    /// Emit one `<dotted.package>.rs` per proto package instead of the
    /// per-proto-file content set plus `<pkg>.mod.rs` stitcher.
    ///
    /// The single file inlines what the stitcher would otherwise `include!`,
    /// producing the same `__buffa::{view,oneof,ext,...}` module structure.
    /// Intended for Buf Schema Registry generated SDKs, whose `lib.rs`
    /// synthesis builds the module tree from `<dotted.package>.rs` filenames.
    ///
    /// Under `strategy: directory` this only sees one directory's files per
    /// invocation, so the input module must be `PACKAGE_DIRECTORY_MATCH`-clean
    /// (one package per directory) for the output to be complete. BSR-hosted
    /// modules satisfy this by lint default. If a package spans multiple
    /// directories, separate invocations each emit their own `<pkg>.rs` and
    /// the last write wins — silent partial output, not a codegen error.
    pub file_per_package: bool,
    /// Custom attributes to inject on generated types (messages, enums, and
    /// oneof enums — the latter matched on the oneof's own path,
    /// `.my.pkg.MyMessage.my_oneof`).
    ///
    /// Each entry is `(proto_path, attribute)`. The `proto_path` is matched
    /// as a prefix against the fully-qualified proto name: `"."` applies to
    /// all types, `".my.pkg"` to types in that package, `".my.pkg.MyMessage"`
    /// to a specific type. The `attribute` is one or more outer Rust
    /// attributes, each written with its `#[...]` (e.g.,
    /// `"#[derive(serde::Serialize)]"`). [`generate`] returns
    /// [`CodeGenError::InvalidCustomAttribute`] for any other string, an
    /// empty one included. The same rule holds for the five attribute lists
    /// below.
    ///
    /// When using a custom `serde::Serialize` derive, follow the requirements
    /// documented by `buffa_build::Config::type_attribute`: disable
    /// unknown-field preservation for generated messages and enable the
    /// `json` feature for buffa's `EnumValue` and `MessageField` serde
    /// implementations. Do not combine a custom derive with generated JSON
    /// implementations.
    pub type_attributes: Vec<(String, String)>,
    /// Custom attributes to inject on generated struct fields.
    ///
    /// Each entry is `(proto_path, attribute)`. The `proto_path` is matched
    /// as a prefix against the fully-qualified field path (e.g.,
    /// `".my.pkg.MyMessage.my_field"`). `"."` applies to all fields. Oneof
    /// variants are matched as `".my.pkg.MyMessage.my_oneof.variant"`; the
    /// struct field holding the oneof is not reached, see
    /// `oneof_struct_field_attributes`.
    pub field_attributes: Vec<(String, String)>,
    /// Custom attributes to inject on generated message structs only (not enums).
    ///
    /// Same path-matching semantics as `type_attributes`, but only applied to
    /// message structs, not enum types. Useful for struct-only attributes like
    /// `#[serde(default)]`.
    pub message_attributes: Vec<(String, String)>,
    /// Custom attributes to inject on generated enum types only (not messages).
    ///
    /// Same path-matching semantics as `type_attributes`, but only applied to
    /// enum types. Useful for enum-only attributes like
    /// `#[derive(strum::EnumIter)]` when the user does not want to apply the
    /// same attribute to every message in the matched scope.
    pub enum_attributes: Vec<(String, String)>,
    /// Custom attributes to inject on generated oneof enums only (not messages,
    /// not regular enums).
    ///
    /// Same path-matching semantics as `type_attributes`, matched against the
    /// oneof's fully-qualified path (`.pkg.Message.oneof_name`). Useful when a
    /// oneof needs a different attribute set than the surrounding types — e.g.
    /// applying `#[derive(serde::Serialize)]` to oneofs while a separate
    /// `enum_attributes` entry puts a different serde derive on the regular
    /// enums. When the surrounding messages use the same custom derive, follow
    /// the `buffa_build::Config::type_attribute` requirements for unknown
    /// fields and the `json` feature.
    pub oneof_attributes: Vec<(String, String)>,
    /// Custom attributes to inject on a message struct's field holding a
    /// oneof (the `Option<OneofEnum>` member), not on the oneof's variants or
    /// the oneof enum.
    ///
    /// Same path-matching semantics as `type_attributes`, matched against the
    /// oneof's fully-qualified path (`.pkg.Message.oneof_name`).
    /// `field_attributes` never reaches this field: on the oneof's path it
    /// matches only the variants (`.pkg.Message.oneof_name.variant`).
    ///
    /// Applies to the owned message struct only; the view structs do not get
    /// the attribute.
    pub oneof_struct_field_attributes: Vec<(String, String)>,
    /// Wrap generated `impl`s in `#[cfg(feature = "...")]` instead of
    /// emitting them unconditionally.
    ///
    /// When `true`, the impls controlled by [`generate_json`],
    /// [`generate_views`], and [`generate_text`] are emitted wrapped in
    /// `#[cfg(feature = "json" | "views" | "text")]` (or
    /// `#[cfg_attr(feature = ..., ...)]` for derives and field attributes)
    /// rather than unconditionally. The consuming crate must define matching
    /// Cargo features that enable the corresponding runtime support, e.g.:
    ///
    /// ```toml
    /// [features]
    /// json  = ["buffa/json", "dep:serde", "dep:serde_json"]
    /// views = []
    /// text  = ["buffa/text"]
    /// ```
    ///
    /// The [`generate_*`] flags still control *whether* an impl kind is
    /// emitted at all — this flag only controls whether it is `cfg`-gated.
    /// `generate_arbitrary` is always `cfg_attr`-gated on
    /// `feature = "arbitrary"` regardless of this flag, because `arbitrary`
    /// is an optional dependency by design.
    ///
    /// When [`generate_reflection`](Self::generate_reflection) is also on, the
    /// reflection impls are gated on `feature = "reflect"` alongside
    /// json/views/text. To gate *only* reflection without gating json/views/text,
    /// use [`gate_reflect_on_crate_feature`](Self::gate_reflect_on_crate_feature)
    /// instead.
    ///
    /// This is the mechanism that lets `buffa-descriptor` and `buffa-types`
    /// ship every impl while keeping the codegen toolchain
    /// (`buffa-codegen`/`buffa-build`/`protoc-gen-reallyme-buffa`) lean: those crates
    /// depend on `buffa-descriptor` with `default-features = false` and so
    /// don't pull `serde`/`serde_json`/`base64`. Most consumers don't need
    /// this — they decide at build-script time whether to generate JSON, and
    /// if they say yes, they want `impl Serialize` to just exist.
    ///
    /// [`generate_json`]: Self::generate_json
    /// [`generate_views`]: Self::generate_views
    /// [`generate_text`]: Self::generate_text
    /// [`generate_*`]: Self::generate_json
    pub gate_impls_on_crate_features: bool,
    /// Generate `with_*` builder-style setter methods for explicit-presence fields.
    ///
    /// Each explicit-presence scalar, bytes, or enum field gets a
    /// `pub fn with_<name>(mut self, value: T) -> Self` method that wraps the
    /// value in `Some` and returns `self`, enabling chained construction:
    ///
    /// ```ignore
    /// let req = MyRequest::default()
    ///     .with_name("alice")
    ///     .with_timeout_ms(30_000);
    /// ```
    ///
    /// **Fields that receive a setter:** proto3 `optional`, proto2 `optional`,
    /// and editions fields with `field_presence = EXPLICIT`.
    ///
    /// **Fields that do not receive a setter:** message fields
    /// (`MessageField<T>`), repeated fields, map fields, oneof variant fields,
    /// proto2 `required` fields, and any implicit-presence field.
    ///
    /// There is no `clear_<name>` companion — to clear a field, assign `None`
    /// directly: `msg.name = None;`.
    ///
    /// Defaults to `true`.
    pub generate_with_setters: bool,
    /// Encode map entries as prost does: leave an entry's key or value out
    /// when it holds what a missing field decodes to, and a message value when
    /// it encodes to nothing.
    ///
    /// Off, every entry carries both fields, as the C++ and Java runtimes
    /// write them. Decoding reads either; a `-0.0` float value is left out
    /// and so decodes as `0.0`. prost leaves out a message value equal to its
    /// default, so a value that still encodes a field, such as one with a
    /// `required` field at its default, is written here and not by prost.
    ///
    /// Applies to the owned, view and lazy view encoders of the messages
    /// generated in this run: types generated without it, the well-known
    /// types and `DynamicMessage` write both fields. With
    /// [`CodecStrategy::Table`], messages with a map field keep the unrolled
    /// codec, and a [`codec_strategy_in`](Self::codec_strategy_in) rule that
    /// selects the table for such a message by its exact path is a
    /// [`CodeGenError`]. `buffa_build::Config::map_entries_omit_defaults` has
    /// the details.
    ///
    /// Defaults to `false`.
    pub map_entries_omit_defaults: bool,
    /// Generate `impl Reflectable` for owned message types (bridge mode).
    ///
    /// When enabled, each generated message gets an
    /// `impl ::buffa_descriptor::reflect::Reflectable` whose `reflect()`
    /// round-trips through `DynamicMessage` (encode → decode → reflective
    /// handle), and the package's `__buffa::reflect` submodule embeds the
    /// `FileDescriptorSet` bytes plus a lazily-built `DescriptorPool`.
    ///
    /// **Runtime requirements** — the consuming crate must depend on:
    /// - `buffa-descriptor` with the `reflect` feature.
    /// - `std` (the lazy pool accessor uses `std::sync::OnceLock`).
    ///
    /// When [`gate_impls_on_crate_features`](Self::gate_impls_on_crate_features)
    /// is on, the impls are wrapped in `#[cfg(feature = "reflect")]` so the
    /// consuming crate can opt out per build.
    ///
    /// **Performance** — `reflect()` is one full encode/decode round-trip
    /// plus a heap allocation. The first call also pays a one-time pool
    /// build cost (linking the embedded `FileDescriptorSet`). For zero-copy
    /// reflective access over view types without the round-trip, additionally
    /// enable [`generate_reflection_vtable`](Self::generate_reflection_vtable).
    ///
    /// **Binary size** — by default each package embeds its own copy of the
    /// full `FileDescriptorSet` (transitive closure), so a multi-package run
    /// duplicates the FDS bytes per package. Enable
    /// [`shared_descriptor_pool`](Self::shared_descriptor_pool) to embed one
    /// shared copy at the module-tree root instead.
    ///
    /// Defaults to `false`.
    pub generate_reflection: bool,
    /// Emit vtable-mode reflection: `impl ReflectMessage` / `impl
    /// ReflectElement` on the owned message structs and (when views are
    /// generated) the view types, and switch the owned
    /// `Reflectable::reflect()` body to borrow `self`
    /// (`ReflectCow::Borrowed(self)`) instead of the bridge round-trip.
    ///
    /// Reflective access then reads struct fields in place — no encode/decode
    /// round-trip and no per-field allocation — for both a decoded view and an
    /// in-memory owned message.
    ///
    /// Requires [`generate_reflection`](Self::generate_reflection) (the impls
    /// resolve against the same embedded `DescriptorPool`) but not
    /// [`generate_views`](Self::generate_views) — with views off, only the
    /// owned impls are emitted. Set via [`ReflectMode::VTable`]
    /// — front-ends expose it as `buffa_build::Config::reflect_mode` /
    /// `protoc-gen-reallyme-buffa`'s `reflect_mode=vtable`.
    ///
    /// Defaults to `false`.
    pub generate_reflection_vtable: bool,
    /// Deduplicate the embedded reflection descriptor pool across packages.
    ///
    /// With [`generate_reflection`](Self::generate_reflection) on, each
    /// package normally embeds its own copy of the full-closure
    /// `FileDescriptorSet` (`FILE_DESCRIPTOR_SET_BYTES`). For a multi-package
    /// run those copies are byte-identical, so the crate carries the same
    /// bytes once per package — which dominates generated-crate size for large
    /// proto trees.
    ///
    /// When this is `true`, `generate` instead emits per-package
    /// `__buffa::reflect` modules that **delegate** to a single shared
    /// `__buffa_fds` module at the module-tree root. Every consumer path
    /// (`pkg::descriptor_pool()`, `pkg::FILE_DESCRIPTOR_SET_BYTES`,
    /// `pkg::__buffa::reflect::*`) keeps resolving; it just aliases the one
    /// shared copy, and all packages observe the same `DescriptorPool`
    /// instance.
    ///
    /// The shared root module itself is emitted by the module-tree builder
    /// (`buffa-build`, or `protoc-gen-reallyme-buffa-packaging` with its matching
    /// `shared_descriptor_pool=true`), not by `generate`, so this mode
    /// requires one of those front-ends to assemble the tree — unless
    /// [`shared_descriptor_pool_root`](Self::shared_descriptor_pool_root) is
    /// set, in which case the root can live anywhere the caller assembled it.
    /// Consumers that wire the per-package modules by hand should leave both
    /// `false`/`None` (the default), which keeps the self-contained
    /// per-package embedding.
    ///
    /// Use the same setting for every codegen run assembled into one module
    /// tree. Packages generated with this set to `false` keep their own pools
    /// even when sibling packages delegate to a shared pool; this mixed setup
    /// is not diagnosed.
    ///
    /// Defaults to `false`. [`generate`] errors when this is on without
    /// `generate_reflection`.
    pub shared_descriptor_pool: bool,
    /// When [`shared_descriptor_pool`](Self::shared_descriptor_pool) is on,
    /// use this path to the shared `__buffa_fds` module verbatim instead of
    /// computing a `super::`-relative one.
    ///
    /// The default `super::` path assumes one crate hosts the whole package
    /// tree as nested modules. A workspace with one crate per package has no
    /// such tree to climb; this field lets the caller point at wherever they
    /// assembled [`shared_descriptor_root_module`]'s output instead — a
    /// separate crate, a re-exported alias, anything.
    ///
    /// The target is a contract, not a free-form value: it must be
    /// [`shared_descriptor_root_module`]'s output, `pub` and nameable from
    /// every package this and every other codegen run in the tree emits,
    /// gated the same way as [`reflect_feature_gate`](Self::reflect_feature_gate)
    /// if that's set, built against a semver-compatible `buffa-descriptor`,
    /// and — like the plugin path's `shared_descriptor_pool` (see the guide's
    /// "spans both plugins" note) — contain every message this `generate()`
    /// run reflects on. A root missing a type fails at runtime with a
    /// `reflect()` lookup panic, not at `generate()` or `cargo build` time.
    ///
    /// Must be an absolute (`::`-prefixed) or `crate`-relative path of plain
    /// `::`-separated identifiers — no generic or parenthesized arguments —
    /// since the same string is spliced verbatim at every package depth.
    /// [`generate`] rejects a malformed value immediately, before splicing it
    /// into generated source. Example: `"::my_shared_fds_crate::__buffa_fds"`.
    ///
    /// `None` (the default) keeps the `super::`-relative behavior.
    pub shared_descriptor_pool_root: Option<String>,
    /// Reuse a [`SharedCorpusContext`] built once by
    /// [`SharedCorpusContext::new`] instead of re-deriving the corpus-wide
    /// oneof/pointer-repr resolution and comment collection on every
    /// `generate()` call — the win for a one-crate-per-package workspace that
    /// generates each package from one whole-corpus `FileDescriptorSet` with
    /// only `extern_paths` varying per call. The context must have been built
    /// from the same `files` and the same
    /// `unboxed_oneof_fields`/`pointer_fields` as the call using it;
    /// `generate` checks and returns
    /// [`CodeGenError::SharedCorpusContextMismatch`] otherwise.
    ///
    /// `None` (the default) recomputes on every call.
    pub shared_corpus_context: Option<SharedCorpusContext>,
    /// Gate the reflection impls behind a `reflect` crate feature, *without*
    /// gating json/views/text (unlike
    /// [`gate_impls_on_crate_features`](Self::gate_impls_on_crate_features),
    /// which gates them all together).
    ///
    /// Used by crates that ship view/text impls unconditionally but want the
    /// reflection surface — which pulls a `buffa-descriptor` dependency and
    /// `std` — to be opt-in. `buffa-types` is the motivating case: its WKT
    /// views are always available, but `impl ReflectMessage` for them is gated
    /// behind `buffa-types`'s `reflect` feature.
    ///
    /// When [`gate_impls_on_crate_features`](Self::gate_impls_on_crate_features)
    /// is already on, reflection is gated regardless and this flag is ignored.
    ///
    /// A low-level knob for crates whose generated code is a public interface
    /// (`buffa-types`, the conformance harness). Set directly by `gen_wkt_types`
    /// and exposed through `buffa_build::Config::gate_reflect_on_crate_feature`
    /// (currently `#[doc(hidden)]`).
    ///
    /// Defaults to `false`.
    pub gate_reflect_on_crate_feature: bool,
    /// Emit idiomatic `UpperCamelCase` constant aliases alongside each enum
    /// variant.
    ///
    /// Protobuf style names enum values in `SHOUTY_SNAKE_CASE`, conventionally
    /// prefixed with the enum name (`RULE_LEVEL_HIGH`). Those names remain the
    /// definitive Rust variants — they are guaranteed unique and valid by
    /// protobuf, and existing references (including `Debug` output) are
    /// unchanged. When this is enabled, codegen additionally emits associated
    /// `const`s with the prefix stripped and the name converted to
    /// `UpperCamelCase` (`RULE_LEVEL_HIGH` → `High`), so downstream code can
    /// write `RuleLevel::High`.
    ///
    /// The conversion is lossy, so two values can collide (`FOO_BAR` and
    /// `FOO__BAR` both map to `FooBar`). The rule is all-or-nothing per enum:
    /// if any two values would collide after conversion, or a value would yield
    /// an invalid identifier, **no** aliases are emitted for that enum (a
    /// [`CodeGenWarning`] and an enum doc note explain why). This keeps every
    /// match either fully `SHOUTY_SNAKE_CASE` or fully idiomatic, never a forced
    /// mix.
    ///
    /// The aliases are associated `const`s, which work in pattern position too:
    /// a `match` written entirely against aliases is still exhaustiveness-checked
    /// (the "non-exhaustive" error names the underlying `SHOUTY_SNAKE_CASE`
    /// variant, since that is the canonical name).
    ///
    /// Defaults to `true`: the aliases are purely additive (the proto names
    /// remain the variants, and `Debug` is unchanged), so enabling by default is
    /// backward-compatible, and the all-or-nothing rule guarantees correctness on
    /// any enum.
    pub idiomatic_enum_aliases: bool,
    /// Emit `use`-backed short type names at the package root instead of
    /// fully-qualified paths, so generated code reads like hand-written
    /// Rust (`pub at: MessageField<Timestamp>` instead of
    /// `pub at: ::buffa::MessageField<::buffa_types::google::protobuf::Timestamp>`).
    ///
    /// Requires [`file_per_package`](Self::file_per_package): only there is
    /// the package-root scope a single-writer file whose complete name set
    /// is known at generation time. In the multi-file layout the stitcher
    /// `include!`-merges every proto's content files into the shared root
    /// scope, where emitted `use` directives could collide across files —
    /// [`generate`] returns an error for that combination rather than
    /// silently ignoring the flag.
    ///
    /// Off by default; default output is byte-for-byte unchanged. Short
    /// names are always backed by an explicit `use` (never glob reliance),
    /// are refused when they would collide with the package's own items or
    /// names referenced bare by sibling emissions, and fall back to
    /// parent-module qualification and then the fully-qualified path. The
    /// short-name *assignment* (use block and per-path choices) is computed
    /// from a collection pre-pass and is stable under `.proto` file
    /// reordering; item order within the file still follows input order,
    /// so whole-file output is not reorder-invariant. The pre-pass
    /// generates the package twice, roughly doubling codegen time for it.
    ///
    /// Scope: only package-root *type declarations* (struct fields, oneof
    /// `Option` wrappers) are shortened. Impl bodies, nested-message
    /// modules, and `__buffa` internals keep fully-qualified paths — the
    /// readability payoff lands where consumers look (struct definitions
    /// and rustdoc), not in the codec internals.
    ///
    /// **Experimental** means: the generated-output shape may change
    /// between releases (requiring regeneration of checked-in code), and
    /// the option itself may be renamed or removed outside semver
    /// guarantees.
    pub idiomatic_imports: bool,
    /// Convert proto field and oneof names to idiomatic snake_case Rust
    /// identifiers (`webMessageInfo` → `web_message_info`), matching
    /// prost-build's behavior for protos that use camelCase field names.
    ///
    /// Only the generated *Rust source names* change — struct fields, view
    /// accessors, `has_*`/`with_*` methods. Every name-keyed protocol surface
    /// keeps the descriptor's names: the wire format keys on field numbers,
    /// JSON uses `json_name` (with the original proto name still accepted on
    /// parse, per the proto3 JSON spec), text format and reflection lookups
    /// use the original proto name. Enum values and message/module names are
    /// not affected (see
    /// [`idiomatic_enum_aliases`](Self::idiomatic_enum_aliases) for enums),
    /// and extension accessors are `SHOUTY_SNAKE_CASE` constants derived
    /// independently of this option.
    ///
    /// Word boundaries match heck's (and therefore prost-build's)
    /// segmentation, including acronym handling (`XMLHttpRequest` →
    /// `xml_http_request`) and digit-transparent case boundaries
    /// (`v2Field` → `v2_field`). The one deliberate divergence from prost:
    /// the conversion is insertion-only and never deletes underscores the
    /// proto author wrote, so it is the identity on every name that is
    /// already a valid snake_case identifier (`_foo` stays `_foo`, where
    /// prost emits `foo`).
    ///
    /// The conversion is lossy, so two members of one message can collide
    /// (`userName` and `user_name`). Unlike enum aliases — which are additive
    /// `const`s and can simply be suppressed — a field rename replaces the
    /// canonical name, so collisions are resolved deterministically instead:
    /// a member whose name is already snake_case keeps it, a converted field
    /// that collides gets an `_f<field_number>` suffix (`userName = 12` →
    /// `user_name_f12`), and a converted oneof that collides keeps its
    /// verbatim proto name. If an adjusted field name still collides, the
    /// changed members in that collision group fall back to their verbatim
    /// proto names. Each adjustment is reported as a
    /// [`CodeGenWarning::IdiomaticFieldNamesAdjusted`]. protoc rejects the
    /// underlying name collisions for proto3 and editions files (conflicting
    /// `json_name`s), so adjustments are only reachable from proto2 inputs.
    ///
    /// Defaults to `false`: a rename is not backward-compatible for existing
    /// consumers of generated camelCase fields, and verbatim emission keeps
    /// the `.proto` file the source of truth. Opt in for prost parity.
    pub idiomatic_field_names: bool,
    /// Crate feature names used by the `#[cfg(feature = "...")]` gates that
    /// [`gate_impls_on_crate_features`](Self::gate_impls_on_crate_features)
    /// and
    /// [`gate_reflect_on_crate_feature`](Self::gate_reflect_on_crate_feature)
    /// emit.
    ///
    /// Defaults to `"json"` / `"views"` / `"text"` / `"reflect"`. Override a
    /// name when the consuming crate gates the same concern behind a
    /// different feature name (e.g. its JSON support behind a `serde`
    /// feature). Inert unless one of the gating flags is on.
    pub feature_gate_names: FeatureGateNames,
    /// Prefix prepended to every locally-generated Rust type name.
    ///
    /// With prefix `"Rpc"`, `message User {}` generates `struct RpcUser`,
    /// its view becomes `RpcUserView` / `RpcUserOwnedView`, and every
    /// cross-reference (fields, oneof variants, maps, extensions) uses the
    /// prefixed name. Useful in multi-protocol systems where generated
    /// types from different domains would otherwise collide with each
    /// other or with a canonical hand-written model.
    ///
    /// The prefix applies to **message structs and enum types** (top-level
    /// and nested, plus their derived view/owned-view types). It does not
    /// apply to:
    ///
    /// - module names (`message Outer` still nests under `pub mod outer`).
    ///   A prefix can remove a module's trailing `_`: the nested types of
    ///   `message item` are in `item_` beside `struct item`, and in `item`
    ///   beside `struct Pbitem`,
    /// - oneof enums (structurally namespaced under `__buffa::oneof::`,
    ///   named after the oneof declaration, not the message),
    /// - types mapped away via [`extern_paths`](Self::extern_paths) or the
    ///   automatic well-known-type mapping (their names are owned by the
    ///   external crate),
    /// - wire-format and JSON output (proto names, `TYPE_URL`s, and JSON
    ///   field names are unaffected — this is a pure Rust-identifier
    ///   rename).
    ///
    /// When another codegen run references these prefixed types via its own
    /// [`extern_paths`](Self::extern_paths) mapping, the mapped Rust path
    /// must spell out the prefixed name (e.g. `::crate_a::RpcUser`) — the
    /// proto name carries no prefix, so the mapping is not derived
    /// automatically. Prefix-induced name collisions (e.g. `message RpcUser`
    /// alongside `message User` with prefix `Rpc`) are not detected here;
    /// they surface as ordinary duplicate-definition errors when the
    /// generated code is compiled.
    ///
    /// Must be PascalCase (`[A-Z][A-Za-z0-9]*`) — an ASCII uppercase letter
    /// followed by ASCII letters and digits — so the prefixed names stay
    /// conventionally cased; generation fails with
    /// [`CodeGenError::InvalidTypeNamePrefix`] otherwise. Defaults to `""`
    /// (no prefix).
    pub type_name_prefix: String,
    /// Proto packages to exclude from code generation (default: empty).
    ///
    /// Each entry is a normalized proto package name without a leading dot
    /// (e.g. `"buf.validate"`, `"gnostic.openapi.v3"`). A package matches
    /// if it equals an entry exactly or starts with `"<entry>."` — so
    /// `"buf.validate"` excludes both `buf.validate` and `buf.validate.priv`.
    ///
    /// Use this when `.proto` files from option-only packages (e.g.
    /// `buf/validate/validate.proto`, gnostic annotations) end up in the
    /// generate set via `include_imports` or directory globbing, but you do
    /// not want Rust types for those packages. Their descriptors remain in
    /// the compilation for type resolution; only code generation is skipped.
    ///
    /// **If you exclude a package that other kept files reference as a field
    /// type**, you must also add an [`extern_path`](Self::extern_paths) mapping
    /// for it, or the generated code will contain dangling `super::…::Type`
    /// paths that fail to compile ([`CodeGenWarning::ExcludedPackageFieldRef`]
    /// names the offending field first).
    ///
    /// Entries are proto package names with no empty segments (e.g.
    /// `"buf.validate"`, `"gnostic.openapi.v3"`); a leading dot is accepted
    /// and stripped at generation time. [`generate_with_diagnostics`] rejects
    /// anything else, and warns with
    /// [`CodeGenWarning::ExcludePackageMatchedNothing`] for an entry that
    /// matches no package in the input.
    pub exclude_packages: Vec<String>,
    /// The [`CodecStrategy`] of every message that no
    /// [`codec_strategy_in`](Self::codec_strategy_in) rule covers (default:
    /// [`CodecStrategy::Unrolled`]).
    ///
    /// Under [`CodecStrategy::Table`] a message that cannot use the table
    /// stays unrolled, and codegen reports one
    /// [`CodeGenWarning::TableCodecFallbackSummary`] for the run.
    pub codec_strategy: CodecStrategy,
    /// Path-scoped overrides for [`codec_strategy`](Self::codec_strategy).
    /// Each entry is `(proto_path_prefix, strategy)`, with a leading dot
    /// (`".pkg.Msg"`).
    ///
    /// Matching uses the same proto-segment-aware prefix rules as
    /// [`preserve_unknown_fields_in`](Self::preserve_unknown_fields_in): a rule
    /// covers the message it names *and every message nested inside it*, `"."`
    /// covers everything, and the **last** matching rule wins.
    ///
    /// A [`CodecStrategy::Table`] rule that covers a message that cannot use
    /// the table keeps it unrolled and counts it in the
    /// [`CodeGenWarning::TableCodecFallbackSummary`]. If the rule names the
    /// message by its exact path, that is an error instead, because the rule
    /// asked for something impossible. A rule that matches no generated message
    /// produces a [`CodeGenWarning::CodecStrategyRuleMatchedNothing`].
    ///
    /// A rule does not extend to the messages a message holds; see
    /// [`CodecStrategy::Table`].
    pub codec_strategy_in: Vec<(String, CodecStrategy)>,
}

impl Default for CodeGenConfig {
    fn default() -> Self {
        Self {
            generate_zeroize: false,
            zeroize_messages: Vec::new(),
            deny_view_json: Vec::new(),
            allow_unmatched_message_rules: false,
            generate_views: true,
            lazy_views: false,
            preserve_unknown_fields: true,
            preserve_unknown_fields_in: Vec::new(),
            deny_unknown_json_fields: false,
            deny_unknown_json_fields_in: Vec::new(),
            generate_json: false,
            generate_arbitrary: false,
            skip_debug: Vec::new(),
            extern_paths: Vec::new(),
            bytes_fields: Vec::new(),
            string_fields: Vec::new(),
            json_policy_types: Vec::new(),
            emit_custom_type_impls: true,
            map_fields: Vec::new(),
            pointer_fields: Vec::new(),
            repeated_fields: Vec::new(),
            feature_overrides: Vec::new(),
            unboxed_oneof_fields: Vec::new(),
            strict_utf8_mapping: false,
            allow_message_set: false,
            generate_text: false,
            emit_register_fn: true,
            file_per_package: false,
            type_attributes: Vec::new(),
            field_attributes: Vec::new(),
            message_attributes: Vec::new(),
            enum_attributes: Vec::new(),
            oneof_attributes: Vec::new(),
            oneof_struct_field_attributes: Vec::new(),
            gate_impls_on_crate_features: false,
            generate_with_setters: true,
            map_entries_omit_defaults: false,
            generate_reflection: false,
            generate_reflection_vtable: false,
            shared_descriptor_pool: false,
            shared_descriptor_pool_root: None,
            shared_corpus_context: None,
            gate_reflect_on_crate_feature: false,
            idiomatic_enum_aliases: true,
            idiomatic_imports: false,
            idiomatic_field_names: false,
            feature_gate_names: FeatureGateNames::default(),
            type_name_prefix: String::new(),
            exclude_packages: Vec::new(),
            codec_strategy: CodecStrategy::Unrolled,
            codec_strategy_in: Vec::new(),
        }
    }
}

impl CodeGenConfig {
    /// Whether any [`FeatureOverride::EnumType`] rule is configured — the
    /// gate for the open-enum declared-default machinery (which can only
    /// fire when a closed enum has been opened by such a rule).
    pub(crate) fn has_enum_type_overrides(&self) -> bool {
        self.feature_overrides
            .iter()
            .any(|(_, o)| matches!(o, FeatureOverride::EnumType(_)))
    }

    /// Active [`feature_gates::FeatureGates`] for this config.
    ///
    /// Recomputed on each call (cheap — three boolean ANDs); call once at
    /// the top of a generation function and thread through, or call inline
    /// at each use site, whichever reads better.
    pub(crate) fn feature_gates(&self) -> feature_gates::FeatureGates<'_> {
        feature_gates::FeatureGates::for_config(self)
    }

    /// The crate feature the reflection surface is gated behind, or `None`
    /// when reflection is unconditional.
    ///
    /// Front-ends emitting the shared descriptor root module (see
    /// [`shared_descriptor_root_module`] and
    /// [`shared_descriptor_pool`](Self::shared_descriptor_pool)) must gate it
    /// with this exact value, so the root module and the per-package
    /// delegations that reference it appear and disappear together.
    #[must_use]
    pub fn reflect_feature_gate(&self) -> Option<&str> {
        self.feature_gates().reflect
    }

    /// Returns the Rust name of a locally generated type:
    /// [`type_name_prefix`](Self::type_name_prefix), then the proto simple
    /// name, with [`idents::escape_type_name`] applied to the two joined.
    /// This is the name the type is declared with and the name in the type
    /// map.
    pub(crate) fn prefixed_type_name(&self, proto_name: &str) -> String {
        idents::local_type_name(&self.type_name_prefix, proto_name)
    }

    /// Validate [`type_name_prefix`](Self::type_name_prefix): empty (no
    /// prefix) or PascalCase (`[A-Z][A-Za-z0-9]*`), so `{prefix}{TypeName}`
    /// is always a valid, conventionally-cased identifier that does not
    /// trip `non_camel_case_types` in consumer crates.
    pub(crate) fn validate_type_name_prefix(&self) -> Result<(), CodeGenError> {
        let prefix = &self.type_name_prefix;
        let valid = prefix.is_empty()
            || (prefix.starts_with(|c: char| c.is_ascii_uppercase())
                && prefix.chars().all(|c| c.is_ascii_alphanumeric()));
        if valid {
            Ok(())
        } else {
            Err(CodeGenError::InvalidTypeNamePrefix {
                prefix: prefix.clone(),
            })
        }
    }
}

/// Compute the effective extern path list by starting with user-provided
/// mappings and adding the default WKT mapping if appropriate.
///
/// The default mapping `".google.protobuf" → "::buffa_types::google::protobuf"`
/// is added unless:
/// - The user already provided an extern_path covering `.google.protobuf`
/// - Any of the files being generated are in the `google.protobuf` package
///   (i.e., we're building `buffa-types` itself)
pub(crate) fn effective_extern_paths(
    file_descriptors: &[FileDescriptorProto],
    files_to_generate: &[String],
    config: &CodeGenConfig,
) -> Vec<(String, String)> {
    let mut paths = config.extern_paths.clone();

    // Only an EXACT .google.protobuf mapping suppresses auto-injection.
    // A sub-package mapping like .google.protobuf.compiler does NOT cover
    // WKTs like Timestamp — resolve_extern_prefix's longest-prefix matching
    // lets both coexist, so we still inject the parent mapping.
    let has_wkt_mapping = paths.iter().any(|(proto, _)| proto == ".google.protobuf");

    if !has_wkt_mapping {
        // Check if we're generating google.protobuf files ourselves
        // (e.g., building buffa-types). If so, don't auto-map.
        let generating_wkts = file_descriptors
            .iter()
            .filter(|fd| {
                fd.name
                    .as_deref()
                    .is_some_and(|n| files_to_generate.iter().any(|f| f == n))
            })
            .any(|fd| fd.package.as_deref() == Some("google.protobuf"));

        if !generating_wkts {
            paths.push((
                ".google.protobuf".to_string(),
                "::buffa_types::google::protobuf".to_string(),
            ));
        }
    }

    paths
}

/// Compute the effective file-level extern path list.
///
/// File-level mappings route a specific `.proto` file to a Rust module root,
/// taking priority over the package-level mappings from
/// [`effective_extern_paths`]. They exist to resolve a structural problem:
/// `descriptor.proto` is in the same `google.protobuf` package as the
/// well-known types (`Timestamp`, `Any`, …), but its types live in
/// `buffa-descriptor`, not `buffa-types`. A single package-keyed
/// `.google.protobuf` extern_path can route the package to one crate or the
/// other; it can't split it. The file-level mapping splits it.
///
/// Auto-injected mappings (when not suppressed):
///
/// | Proto file | Rust module |
/// |---|---|
/// | `google/protobuf/descriptor.proto` | `::buffa_descriptor::generated::descriptor` |
/// | `google/protobuf/compiler/plugin.proto` | `::buffa_descriptor::generated::compiler` |
///
/// Suppression conditions, evaluated **per file**:
///
/// - **A user-provided `extern_path` covers the file's package.** That
///   override has covered the file's types since the package mapping was
///   introduced; auto-injecting a higher-priority file-level mapping would
///   silently redirect them away from the user's crate. Matching is via
///   the same longest-prefix logic the package resolver uses, so both an
///   exact `.google.protobuf` mapping and a sub-package
///   `.google.protobuf.compiler` mapping suppress the entries they cover —
///   `.google.protobuf` suppresses both, `.google.protobuf.compiler`
///   suppresses only `plugin.proto`.
/// - **The proto file itself is in `files_to_generate`.** When building
///   `buffa-descriptor` (or any local copy of `descriptor.proto`), its types
///   must resolve to the local module, not externally.
///
/// Currently internal-only — there is no `CodeGenConfig` field for
/// user-provided *file-level* mappings. The user-facing `extern_path` API is
/// keyed by proto package *or* type FQN (per-type overrides, issue #111);
/// per-file overrides may be added later as a public feature if a concrete
/// need arises.
pub(crate) fn effective_file_extern_paths(
    files_to_generate: &[String],
    config: &CodeGenConfig,
) -> Vec<(String, String)> {
    // (proto file path, proto package, Rust module root). The package is
    // recorded alongside the file so the user-override suppression check
    // is per-file: a `.google.protobuf.compiler` extern_path covers only
    // `plugin.proto`, while `.google.protobuf` covers both.
    const DESCRIPTOR_FILES: [(&str, &str, &str); 2] = [
        (
            "google/protobuf/descriptor.proto",
            "google.protobuf",
            "::buffa_descriptor::generated::descriptor",
        ),
        (
            "google/protobuf/compiler/plugin.proto",
            "google.protobuf.compiler",
            "::buffa_descriptor::generated::compiler",
        ),
    ];

    DESCRIPTOR_FILES
        .into_iter()
        .filter(|(proto_file, package, _)| {
            // Yield to a user package-level extern_path that already covers
            // this file's package: anyone who wrote
            // `extern_path(".google.protobuf", "::my_crate")` (or a
            // sub-package mapping) today routes these types to their crate;
            // the auto-injected file-level mapping must not silently
            // outrank it.
            if context::resolve_extern_prefix(package, &config.extern_paths).is_some() {
                return false;
            }
            // Don't externalize a file we're generating locally.
            !files_to_generate.iter().any(|f| f == proto_file)
        })
        .map(|(proto_file, _, rust_module)| (proto_file.to_string(), rust_module.to_string()))
        .collect()
}

/// One CamelCase collision: a target identifier and the proto value names that
/// would all convert onto it.
///
/// Part of [`CodeGenWarning::IdiomaticAliasesSuppressed`].
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub struct AliasConflict {
    /// The `UpperCamelCase` identifier the colliding values map to.
    pub camel_target: String,
    /// The proto value names that convert onto `camel_target` (includes a
    /// literal variant name when an alias would shadow it).
    pub proto_values: Vec<String>,
}

/// A non-fatal diagnostic produced during code generation.
///
/// Returned by [`generate_with_diagnostics`]. Render the human-readable form via
/// the [`Display`](core::fmt::Display) impl (e.g. `cargo:warning={warning}`), or
/// match on the variant for programmatic handling. The enum and its variants are
/// `#[non_exhaustive]` so new diagnostic kinds and fields can be added without a
/// breaking change.
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub enum CodeGenWarning {
    /// An explicitly permitted selector was absent from this scoped request.
    #[non_exhaustive]
    ZeroizeRuleMatchedNothing { rule: String },
    /// An explicitly permitted view selector was absent from this scoped request.
    #[non_exhaustive]
    ViewJsonRuleMatchedNothing { rule: String },
    /// View JSON restrictions cannot apply without both JSON and view generation.
    #[non_exhaustive]
    ViewJsonRulesRequireJsonAndViews,
    /// Idiomatic CamelCase aliases were suppressed for an enum because two or
    /// more proto values collide after conversion, or a value would convert to
    /// an invalid identifier. The enum's `SHOUTY_SNAKE_CASE` variants are
    /// unaffected.
    #[non_exhaustive]
    IdiomaticAliasesSuppressed {
        /// The Rust name of the affected enum.
        enum_name: String,
        /// Each collision, by target identifier. Empty if the only problem was
        /// invalid identifiers.
        conflicts: Vec<AliasConflict>,
        /// Proto values that would convert to an invalid Rust identifier.
        invalid: Vec<String>,
    },
    /// A field or oneof accessor on a generated `FooOwnedView` wrapper was
    /// suppressed because the proto name collides with one of the wrapper's
    /// reserved method names (`decode`, `view`, `bytes`, …). The field stays
    /// fully accessible through `view()` on the wrapper (or
    /// `OwnedView::reborrow`).
    #[non_exhaustive]
    OwnedViewAccessorSuppressed {
        /// The Rust name of the wrapper type (e.g. `FooOwnedView`).
        wrapper_name: String,
        /// The proto field or oneof name whose accessor was suppressed.
        field_name: String,
    },
    /// `lazy_views` was requested with `generate_views` disabled; the lazy
    /// family reuses the eager view-oneof enums and eager sub-view types, so
    /// no lazy views were generated. Emitted once per generation run.
    #[non_exhaustive]
    LazyViewsRequireViews,
    /// [`deny_unknown_json_fields`](CodeGenConfig::deny_unknown_json_fields), or a
    /// [`deny_unknown_json_fields_in`](CodeGenConfig::deny_unknown_json_fields_in)
    /// rule, was set with [`generate_json`](CodeGenConfig::generate_json)
    /// disabled. There are no JSON deserializers to make strict, so the
    /// setting changed nothing — forgetting `generate_json` is the likelier
    /// mistake than a wrong path, and without this the option is silently
    /// inert. Emitted once per generation run.
    #[non_exhaustive]
    DenyUnknownJsonFieldsRequiresJson,
    /// [`json_policy_types`](CodeGenConfig::json_policy_types) is non-empty but
    /// JSON generation is off, so no field uses a policy.
    #[non_exhaustive]
    JsonPolicyTypesRequireJson,
    /// `idiomatic_field_names` found two or more members of one message whose
    /// snake_case conversions collide, and adjusted the affected Rust names
    /// deterministically (`_f<number>` suffix for fields, verbatim fallback
    /// for oneofs — see [`CodeGenConfig::idiomatic_field_names`]). Wire,
    /// JSON, and text-format names are unaffected.
    #[non_exhaustive]
    IdiomaticFieldNamesAdjusted {
        /// Fully-qualified proto name of the affected message.
        message_name: String,
        /// `(proto_name, final_rust_name)` for each adjusted member, sorted
        /// by proto name.
        assignments: Vec<(String, String)>,
    },
    /// A member's keyword-escaped Rust name is also the name of another
    /// member, and the keyword member was renamed.
    ///
    /// A field or oneof whose Rust name is `self`, `super`, `crate` or `Self`
    /// (after any `idiomatic_field_names` conversion) is generated as `self_`.
    /// Next to a member named `self_`, it is generated as `self__`, with more
    /// underscores while that name is taken too. Wire, JSON and text-format
    /// names are unaffected. Two oneofs named `self` and `self_` fail with
    /// [`CodeGenError::OneofEnumNameConflict`] instead.
    ///
    /// A field is identified by its name and number, and a oneof by its
    /// name, across the messages of every generated file. A message that
    /// declares the same member gets the same Rust name and this warning,
    /// even when it has no `self_` member of its own.
    #[non_exhaustive]
    KeywordEscapedNamesAdjusted {
        /// Fully-qualified proto name of the affected message.
        message_name: String,
        /// `(proto_name, final_rust_name)` for each adjusted member, sorted by
        /// proto name.
        assignments: Vec<(String, String)>,
    },
    /// A field in a kept file references a type from a package that is neither
    /// being generated nor covered by an [`extern_path`](CodeGenConfig::extern_paths)
    /// mapping. The generated code will emit a dangling type path that fails to
    /// compile in the consumer's build with no indication of where the
    /// configuration gap is.
    ///
    /// Fix by either:
    /// - Including the referenced package in the generation request (drop the
    ///   `exclude_package` plugin directive or the `.exclude_package(…)` call,
    ///   or add the missing `.proto` files to the generate set), or
    /// - Adding an `extern_path` mapping for the package pointing to the crate
    ///   that provides its generated types.
    ///
    /// Detection is type-granular: a kept file that generates *some* types from a
    /// package while another file in the same package is excluded will still
    /// produce a warning for references to the excluded file's types.
    ///
    /// One warning is emitted per unique `(file_name, type_fqn)` pair; other
    /// fields in the same file referencing the same type are not reported
    /// separately.
    #[non_exhaustive]
    ExcludedPackageFieldRef {
        /// The proto file that contains the referencing field,
        /// e.g. `"path/to/service.proto"`.
        file_name: String,
        /// The message that contains the referencing field, in dotted form
        /// (e.g. `"MyMessage"` or `"Outer.Inner"`). Empty when the reference
        /// is a file-level extension rather than a message field.
        message_name: String,
        /// The name of the field that holds the dangling reference.
        field_name: String,
        /// The proto package that owns the referenced type,
        /// e.g. `"buf.validate"`.
        ref_package: String,
        /// The fully-qualified type name in the descriptor (leading-dot form,
        /// matching the key format of [`CodeGenConfig::extern_paths`]),
        /// e.g. `".buf.validate.FieldConstraints"`.
        type_fqn: String,
    },
    /// An [`exclude_packages`](CodeGenConfig::exclude_packages) entry matched
    /// no proto package in the descriptor set. Usually a typo in the package
    /// name or a stale entry left after a proto reorganization — the entry is
    /// accepted but changes nothing.
    ///
    /// Check the spelling against the `package` declarations in your `.proto`
    /// files. The match is exact or prefix-on-component-boundary, so
    /// `"buf.validate"` covers `buf.validate` and `buf.validate.priv` but not
    /// `buf.validatex`.
    #[non_exhaustive]
    ExcludePackageMatchedNothing {
        /// The normalized package entry that matched nothing
        /// (leading dot already stripped).
        package: String,
    },
    /// A [`feature_overrides`](CodeGenConfig::feature_overrides) rule matched
    /// nothing the override targets in the compiled descriptor set, so it
    /// changed nothing. Usually a typo, a missing nested-message segment, or
    /// a stale path after a proto rename — the affected paths silently keep
    /// their default semantics.
    #[non_exhaustive]
    FeatureOverrideMatchedNothing {
        /// The rule's path as configured (post-normalization).
        rule: String,
        /// The overridden feature's name (e.g. `"enum_type"`).
        feature: &'static str,
        /// The override value (e.g. `"OPEN"`).
        value: &'static str,
    },
    /// A [`preserve_unknown_fields_in`](CodeGenConfig::preserve_unknown_fields_in)
    /// rule matched no message being generated, so it changed nothing. Usually
    /// a typo, a field path instead of a message path, or a rule for a package
    /// mapped through `extern_path` — the affected messages silently keep the
    /// global [`preserve_unknown_fields`](CodeGenConfig::preserve_unknown_fields)
    /// setting, which for a re-enable rule means losing round-trip fidelity.
    #[non_exhaustive]
    PreserveUnknownFieldsRuleMatchedNothing {
        /// The rule's path as configured.
        rule: String,
    },
    /// A [`deny_unknown_json_fields_in`](CodeGenConfig::deny_unknown_json_fields_in)
    /// rule matched no message being generated, so it changed nothing. Usually
    /// a typo, a field path instead of a message path, or a rule for a package
    /// mapped through `extern_path` — the affected messages silently keep the
    /// global [`deny_unknown_json_fields`](CodeGenConfig::deny_unknown_json_fields)
    /// setting, which for an enabling rule means unknown JSON keys stay silently
    /// ignored.
    #[non_exhaustive]
    DenyUnknownJsonFieldsRuleMatchedNothing {
        /// The rule's path as configured.
        rule: String,
    },
    /// A [`skip_debug`](CodeGenConfig::skip_debug) rule matched no generated
    /// message and named no generated enum, so it changed nothing. Usually a
    /// typo, a field or oneof path instead of a type path (a oneof is covered
    /// by its message's rule), or a rule for a package mapped through
    /// `extern_path`. Every generated `Debug` impl is still emitted, so a
    /// hand-written impl for the intended type fails to compile as a
    /// conflicting implementation.
    #[non_exhaustive]
    SkipDebugRuleMatchedNothing {
        /// The rule's path as configured.
        rule: String,
    },
    /// A [`bytes_fields`](CodeGenConfig::bytes_fields),
    /// [`string_fields`](CodeGenConfig::string_fields),
    /// [`map_fields`](CodeGenConfig::map_fields) or
    /// [`repeated_fields`](CodeGenConfig::repeated_fields) rule matched no
    /// field of a message generated by this call, so it changed nothing.
    ///
    /// Usually a typo, a path without its leading dot or its package, a
    /// prost-style suffix path such as `"items"`, or a path into a map-entry
    /// message (a rule reaches a map through the map field's own path). A
    /// package rule over messages that have no fields also warns.
    ///
    /// The check compares paths only: a rule whose path is a field of another
    /// type (a `string_fields` rule on an `int32` field) is also inert and
    /// does not warn. It runs once per `generate` call, so a config shared by
    /// several calls warns in each call whose files lack the field.
    #[non_exhaustive]
    FieldTypeRuleMatchedNothing {
        /// The rule's path as it is in the [`CodeGenConfig`] list
        /// (`buffa-build` has normalized it).
        rule: String,
        /// The [`CodeGenConfig`] list that contains the rule: `"bytes_fields"`,
        /// `"string_fields"`, `"map_fields"` or `"repeated_fields"`.
        option: &'static str,
        /// Whether the rule matches a field of a message that this call does
        /// not generate: one in an imported file, or in a package under
        /// `extern_path` or `exclude_packages`. The `Display` text then says
        /// so, in place of the path hint.
        matches_ungenerated: bool,
    },
    /// A [`codec_strategy_in`](CodeGenConfig::codec_strategy_in) rule matched no
    /// message being generated, so it changed nothing. Usually a typo, a field
    /// path instead of a message path, or a rule for a package mapped through
    /// `extern_path`.
    #[non_exhaustive]
    CodecStrategyRuleMatchedNothing {
        /// The rule's path as configured.
        rule: String,
    },
    /// Some messages selected for [`CodecStrategy::Table`], by the global
    /// [`codec_strategy`](CodeGenConfig::codec_strategy) or by a
    /// [`codec_strategy_in`](CodeGenConfig::codec_strategy_in) rule, cannot use
    /// the table and are generated [`CodecStrategy::Unrolled`]. One warning
    /// covers the whole run.
    #[non_exhaustive]
    TableCodecFallbackSummary {
        /// The number of messages that fell back.
        fallbacks: usize,
        /// The number of messages selected for the table.
        selected: usize,
        /// Why they fell back, most common reason first.
        reasons: Vec<TableCodecFallbackReason>,
    },
}

/// The `buffa-build` methods that add to the field-type rule list `option`,
/// for [`CodeGenWarning::FieldTypeRuleMatchedNothing`]'s text. A user of
/// `buffa-build` typed one of these, not the [`CodeGenConfig`] field's name.
fn field_type_rule_builders(option: &str) -> &'static str {
    match option {
        "bytes_fields" => "bytes_type_in / use_bytes_type_in / bytes_type_custom_in",
        "string_fields" => "string_type_in / string_type_custom_in",
        "map_fields" => "map_type_in / map_type_custom_in",
        "repeated_fields" => "repeated_type_in / repeated_type_custom_in",
        _ => "",
    }
}

impl core::fmt::Display for CodeGenWarning {
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        match self {
            Self::ViewJsonRulesRequireJsonAndViews => f.write_str(
                "deny_view_json requires both generate_json and generate_views; the configured restrictions are inactive"
            ),
            Self::ZeroizeRuleMatchedNothing { rule } => write!(
                f, "zeroize_in rule '{rule}' matches no message in this scoped request; validate the full project with allow_unmatched_message_rules=false"
            ),
            Self::ViewJsonRuleMatchedNothing { rule } => write!(
                f, "deny_view_json rule '{rule}' matches no message in this scoped request; validate the full project with allow_unmatched_message_rules=false"
            ),
            Self::IdiomaticAliasesSuppressed {
                enum_name,
                conflicts,
                invalid,
            } => {
                // Name the cause accurately: a collision, an invalid identifier,
                // or both.
                let cause = match (conflicts.is_empty(), invalid.is_empty()) {
                    (false, true) => "naming conflict",
                    (true, false) => "invalid identifier",
                    _ => "naming conflict / invalid identifier",
                };
                write!(
                    f,
                    "enum `{enum_name}`: idiomatic CamelCase aliases suppressed ({cause})"
                )?;
                let mut parts: Vec<String> = conflicts
                    .iter()
                    .map(|c| format!("{} → {}", c.proto_values.join(", "), c.camel_target))
                    .collect();
                parts.extend(invalid.iter().map(|n| format!("{n} → invalid identifier")));
                if !parts.is_empty() {
                    write!(f, ": {}", parts.join("; "))?;
                }
                Ok(())
            }
            Self::OwnedViewAccessorSuppressed {
                wrapper_name,
                field_name,
            } => {
                write!(
                    f,
                    "`{wrapper_name}`: accessor for field `{field_name}` suppressed \
                     (collides with a reserved wrapper method); use `.view().{field_name}` instead"
                )
            }
            Self::JsonPolicyTypesRequireJson => {
                write!(
                    f,
                    "json_policy_type requires generate_json (there is no generated \
                     JSON to route through a policy) — enable generate_json \
                     (buffa-build: `.generate_json(true)`; plugin: `json=true`)"
                )
            }
            Self::DenyUnknownJsonFieldsRequiresJson => {
                write!(
                    f,
                    "deny_unknown_json_fields requires generate_json (there are no \
                     generated JSON deserializers to make strict); unknown JSON keys \
                     are still ignored — enable generate_json (buffa-build: \
                     `.generate_json(true)`; plugin: `json=true`)"
                )
            }
            Self::LazyViewsRequireViews => {
                write!(
                    f,
                    "lazy_views requires generate_views (the lazy family reuses the \
                     eager view-oneof enums and sub-view types); no lazy views were \
                     generated — enable generate_views (buffa-build: \
                     `.generate_views(true)`, the default; plugin: `views=true`)"
                )
            }
            Self::IdiomaticFieldNamesAdjusted {
                message_name,
                assignments,
            } => {
                let parts: Vec<String> = assignments
                    .iter()
                    .map(|(proto, rust)| format!("`{proto}` → `{rust}`"))
                    .collect();
                write!(
                    f,
                    "message `{message_name}`: idiomatic snake_case field names collide; \
                     adjusted: {} (wire/JSON/text names are unaffected)",
                    parts.join(", ")
                )
            }
            Self::KeywordEscapedNamesAdjusted {
                message_name,
                assignments,
            } => {
                let parts: Vec<String> = assignments
                    .iter()
                    .map(|(proto, rust)| format!("`{proto}` → `{rust}`"))
                    .collect();
                write!(
                    f,
                    "message `{message_name}`: a member's keyword-escaped Rust name is the \
                     name of another member, in this message or in one that declares the \
                     same member; adjusted: {} (wire/JSON/text names are unaffected)",
                    parts.join(", ")
                )
            }
            Self::ExcludedPackageFieldRef {
                file_name,
                message_name,
                field_name,
                ref_package,
                type_fqn,
            } => {
                let location = if message_name.is_empty() {
                    format!("{file_name}: {field_name}")
                } else {
                    format!("{file_name}: {message_name}.{field_name}")
                };
                write!(
                    f,
                    "field `{location}` references `{type_fqn}`, which is not being \
                     generated and has no extern_path mapping; the generated code will \
                     contain a dangling type path — map the type or its package \
                     `{ref_package}` to the crate that defines it \
                     (buffa-build: `.extern_path(\"{type_fqn}\", \"::your_crate::Type\")` \
                     or `.extern_path(\".{ref_package}\", \"::your_crate\")`; \
                     plugin: `extern_path={type_fqn}=::your_crate::Type` or \
                     `extern_path=.{ref_package}=::your_crate`), or include the \
                     defining .proto file in the generate set \
                     (buffa-build: `.files(&[…])` or drop `.exclude_package(…)`; \
                     plugin: drop `exclude_package=`)"
                )
            }
            Self::ExcludePackageMatchedNothing { package } => {
                write!(
                    f,
                    "exclude_package entry \"{package}\" matched no proto package in the \
                     descriptor set — check for a typo or a stale entry \
                     (exact match or dotted-prefix: \"buf.validate\" covers \
                     buf.validate and buf.validate.priv, not buf.validatex)"
                )
            }
            Self::FeatureOverrideMatchedNothing {
                rule,
                feature,
                value,
            } => {
                write!(
                    f,
                    "feature override '{rule}' ({feature} = {value}) matched nothing in \
                     the compiled set; the affected paths keep their default semantics — \
                     check the path against the fully-qualified proto names"
                )
            }
            Self::PreserveUnknownFieldsRuleMatchedNothing { rule } => {
                write!(
                    f,
                    "preserve_unknown_fields_in rule '{rule}' matched no generated message; \
                     those messages keep the global preserve_unknown_fields setting — \
                     check the path against the fully-qualified proto message names"
                )
            }
            Self::CodecStrategyRuleMatchedNothing { rule } => {
                write!(
                    f,
                    "codec_strategy_in rule '{rule}' matched no generated message; those \
                     messages keep the global codec_strategy setting — check the path \
                     against the fully-qualified proto message names"
                )
            }
            Self::TableCodecFallbackSummary {
                fallbacks,
                selected,
                reasons,
            } => {
                write!(
                    f,
                    "{fallbacks} of {selected} messages selected for the table codec use the \
                     unrolled codec instead"
                )?;
                for (i, r) in reasons.iter().enumerate() {
                    let sep = if i == 0 { ": " } else { "; " };
                    let shown = r.messages.len().min(3);
                    let examples = r.messages[..shown].join(", ");
                    let more = match r.messages.len() - shown {
                        0 => String::new(),
                        n => format!(", and {n} more"),
                    };
                    write!(
                        f,
                        "{sep}{} ({}: {examples}{more})",
                        r.reason,
                        r.messages.len()
                    )?;
                }
                write!(
                    f,
                    ". To silence this warning, set the messages that fell back to the unrolled \
                     codec (buffa-build: `.codec_strategy_in(CodecStrategy::Unrolled, \
                     &[\"<path>\"])`; plugin: `codec_strategy_in=<path>=unrolled`)"
                )
            }
            Self::DenyUnknownJsonFieldsRuleMatchedNothing { rule } => {
                write!(
                    f,
                    "deny_unknown_json_fields_in rule '{rule}' matched no generated message; \
                     those messages keep the global deny_unknown_json_fields setting — \
                     check the path against the fully-qualified proto message names"
                )
            }
            Self::SkipDebugRuleMatchedNothing { rule } => {
                write!(
                    f,
                    "skip_debug rule '{rule}' matched no generated message or enum, \
                     so a hand-written Debug impl will conflict with the generated one — \
                     use the fully-qualified proto type name \
                     (a oneof is covered by its message's rule)"
                )
            }
            Self::FieldTypeRuleMatchedNothing {
                rule,
                option,
                matches_ungenerated,
            } => {
                let builders = field_type_rule_builders(option);
                write!(f, "{option} rule '{rule}' (buffa-build: {builders}) ")?;
                if *matches_ungenerated {
                    write!(
                        f,
                        "matches only fields of messages this run does not generate \
                         (an imported file, or a package under extern_path or \
                         exclude_package), so it changed nothing here"
                    )
                } else {
                    write!(
                        f,
                        "matched no field of a generated message, so it changed nothing — \
                         a rule is a fully-qualified proto path with its leading dot \
                         ('.my.pkg', '.my.pkg.Msg' or '.my.pkg.Msg.field'); a bare name \
                         such as 'field' or 'Msg.field' does not match"
                    )
                }
            }
        }
    }
}

/// The files named in `files_to_generate`, each with its package as a
/// leading-dot proto path (empty for a file without a package).
fn generated_files<'a>(
    file_descriptors: &'a [FileDescriptorProto],
    files_to_generate: &'a [String],
) -> impl Iterator<Item = (&'a FileDescriptorProto, String)> {
    file_descriptors
        .iter()
        .filter(move |fd| {
            fd.name
                .as_deref()
                .is_some_and(|n| files_to_generate.iter().any(|g| g == n))
        })
        .map(|fd| {
            let package = fd.package.as_deref().unwrap_or("");
            let package_fqn = if package.is_empty() {
                String::new()
            } else {
                format!(".{package}")
            };
            (fd, package_fqn)
        })
}

/// Whether `rule` (a leading-dot proto path prefix) matches at least one
/// message, nested messages included, declared in `files_to_generate`.
fn rule_matches_generated_message(
    rule: &str,
    file_descriptors: &[FileDescriptorProto],
    files_to_generate: &[String],
) -> bool {
    fn any_message_matches(rule: &str, parent_fqn: &str, messages: &[DescriptorProto]) -> bool {
        messages.iter().any(|m| {
            let fqn = format!("{parent_fqn}.{}", m.name.as_deref().unwrap_or(""));
            context::matches_proto_prefix(rule, &fqn)
                || any_message_matches(rule, &fqn, &m.nested_type)
        })
    }

    rule == "."
        || generated_files(file_descriptors, files_to_generate)
            .any(|(fd, package_fqn)| any_message_matches(rule, &package_fqn, &fd.message_type))
}

/// Whether `rule` (a leading-dot proto path) is the fully-qualified name of
/// an enum, top-level or nested in a message, declared in
/// `files_to_generate`.
fn rule_names_generated_enum(
    rule: &str,
    file_descriptors: &[FileDescriptorProto],
    files_to_generate: &[String],
) -> bool {
    fn names_enum(rule: &str, parent_fqn: &str, enums: &[EnumDescriptorProto]) -> bool {
        enums
            .iter()
            .any(|e| format!("{parent_fqn}.{}", e.name.as_deref().unwrap_or("")) == rule)
    }
    fn names_nested_enum(rule: &str, parent_fqn: &str, messages: &[DescriptorProto]) -> bool {
        messages.iter().any(|m| {
            let fqn = format!("{parent_fqn}.{}", m.name.as_deref().unwrap_or(""));
            names_enum(rule, &fqn, &m.enum_type) || names_nested_enum(rule, &fqn, &m.nested_type)
        })
    }

    generated_files(file_descriptors, files_to_generate).any(|(fd, package_fqn)| {
        names_enum(rule, &package_fqn, &fd.enum_type)
            || names_nested_enum(rule, &package_fqn, &fd.message_type)
    })
}

/// Whether `rule` (a leading-dot proto path prefix) matches at least one
/// field of a message, nested messages included, declared in the files named
/// by `file_names`. The fields of a map-entry message do not count: a rule
/// reaches a map through the map field's own path.
fn rule_matches_field_in(
    rule: &str,
    file_descriptors: &[FileDescriptorProto],
    file_names: &[String],
) -> bool {
    fn any_field_matches(rule: &str, parent_fqn: &str, messages: &[DescriptorProto]) -> bool {
        messages.iter().any(|m| {
            let is_map_entry = m
                .options
                .as_option()
                .and_then(|o| o.map_entry)
                .unwrap_or(false);
            if is_map_entry {
                return false;
            }
            let fqn = format!("{parent_fqn}.{}", m.name.as_deref().unwrap_or(""));
            m.field.iter().any(|f| {
                let field_fqn = format!("{fqn}.{}", f.name.as_deref().unwrap_or(""));
                context::matches_proto_prefix(rule, &field_fqn)
            }) || any_field_matches(rule, &fqn, &m.nested_type)
        })
    }

    rule == "."
        || generated_files(file_descriptors, file_names)
            .any(|(fd, package_fqn)| any_field_matches(rule, &package_fqn, &fd.message_type))
}

/// The paths of a field-type rule list such as
/// [`CodeGenConfig::string_fields`], in order.
fn rule_paths<R>(rules: &[(String, R)]) -> Vec<&String> {
    rules.iter().map(|(path, _)| path).collect()
}

/// A later ancestor rule replaces this rule everywhere, independently of which
/// directory a plugin request happens to contain. Narrow overrides do not make
/// an earlier package-wide rule inert outside their own prefixes.
fn unshadowed_rules<R>(rules: &[(String, R)]) -> impl Iterator<Item = &R> {
    rules
        .iter()
        .enumerate()
        .filter_map(|(index, (path, repr))| {
            let next = index.checked_add(1)?;
            (!rules
                .iter()
                .skip(next)
                .any(|(later, _)| context::matches_proto_prefix(later, path)))
            .then_some(repr)
        })
}

/// Generate Rust source files from a set of file descriptors.
///
/// `files_to_generate` is the set of file names that were explicitly requested
/// (matching `CodeGeneratorRequest.file_to_generate`). Descriptors for
/// dependencies may be present in `file_descriptors` but won't produce output
/// files unless they appear in `files_to_generate`. A name listed twice is
/// generated once.
///
/// Each `.proto` emits up to five content files (kinds with no content
/// are omitted); each distinct package emits one `<pkg>.mod.rs`
/// stitcher. Packages are processed in sorted order for deterministic
/// output.
///
/// # Diagnostics
///
/// Non-fatal diagnostics produced during generation (e.g. an enum whose
/// idiomatic CamelCase aliases were suppressed by a naming conflict) are
/// **discarded** here. Use [`generate_with_diagnostics`] to receive them and
/// surface them as build warnings.
///
/// # Errors
///
/// As [`generate_with_diagnostics`].
pub fn generate(
    file_descriptors: &[FileDescriptorProto],
    files_to_generate: &[String],
    config: &CodeGenConfig,
) -> Result<Vec<GeneratedFile>, CodeGenError> {
    Ok(generate_with_diagnostics(file_descriptors, files_to_generate, config)?.0)
}

/// Whether a custom `repeated` element type holds proto `string` or `bytes` —
/// selects `ValueRef::String`/`ValueRef::Bytes` and the JSON delegate module.
#[derive(Clone, Copy, PartialEq, Eq)]
enum CustomElemKind {
    String,
    Bytes,
}

/// The custom owned types collected generation-wide that need a codegen-emitted
/// reflection / JSON impl, split by the trait each needs.
#[derive(Default)]
struct CustomElements {
    /// Types needing `ReflectElement` (+ `ProtoElemJson` for bytes): custom
    /// `repeated` elements, custom `map` *values* (`string` or `bytes`).
    elements: std::collections::BTreeMap<String, CustomElemKind>,
    /// Custom `string` types used as a `map` *key*: need `ReflectMapKey` (vtable
    /// reflection only — the bridge path keys maps by the borrowed `&str` view).
    map_keys: std::collections::BTreeSet<String>,
}

/// Collect the distinct custom owned types that need a codegen-emitted element
/// impl (`ReflectElement` / `ProtoElemJson`), keyed by Rust type path, across
/// the whole request. These are custom `string`/`bytes` types used as the
/// element of a `repeated` field, and custom `bytes` types used as a
/// `map<K, bytes>` value — both reflect via the element trait and (for bytes)
/// serialize JSON via `proto_map`/`proto_seq`. Singular / optional / oneof
/// custom fields reach JSON and reflection without an element-trait impl, and
/// `string`/`Vec<u8>`/`Bytes` map values are covered by the built-in impls.
fn collect_custom_elements(
    ctx: &context::CodeGenContext,
    file_descriptors: &[FileDescriptorProto],
    files_to_generate: &[String],
    all_fields: bool,
) -> CustomElements {
    use crate::generated::descriptor::field_descriptor_proto::{Label, Type};

    fn walk(
        ctx: &context::CodeGenContext,
        messages: &[crate::generated::descriptor::DescriptorProto],
        scope: &str,
        parent_features: &crate::features::ResolvedFeatures,
        out: &mut CustomElements,
        all_fields: bool,
    ) {
        for msg in messages {
            if msg
                .options
                .as_option()
                .and_then(|options| options.map_entry)
                .unwrap_or(false)
            {
                continue;
            }
            let name = msg.name.as_deref().unwrap_or("");
            let fqn = if scope.is_empty() {
                name.to_string()
            } else {
                format!("{scope}.{name}")
            };
            let msg_features = crate::features::resolve_child(
                parent_features,
                crate::features::message_features(msg),
            );
            for field in &msg.field {
                if !all_fields && field.label.unwrap_or_default() != Label::LABEL_REPEATED {
                    continue;
                }
                let field_name = field.name.as_deref().unwrap_or("");
                let field_fqn = format!(".{fqn}.{field_name}");

                // `map` slots: a custom value type needs the element impls
                // (reflected via ReflectMap → ReflectElement, JSON via
                // proto_map → ProtoElemJson for bytes), and a custom `string`
                // key needs ReflectMapKey. All keyed on the outer map field
                // path (the same `string_type` rule covers both slots), with the
                // `map<bytes, bytes>` value carve-out.
                if let Some(entry) = crate::message::find_map_entry(msg, field) {
                    let key_ty = crate::message::map_entry_key_type(ctx, entry, &msg_features);
                    let val_ty = crate::message::map_entry_value_type(ctx, entry, &msg_features);
                    if let crate::BytesRepr::Custom(path) =
                        crate::impl_message::map_value_bytes_repr(
                            ctx, key_ty, val_ty, &fqn, field_name,
                        )
                    {
                        out.elements
                            .entry(context::rust_type_key(&path))
                            .or_insert(CustomElemKind::Bytes);
                    }
                    if let crate::StringRepr::Custom(path) = ctx.string_repr(&field_fqn) {
                        if key_ty == Some(Type::TYPE_STRING) {
                            out.map_keys.insert(context::rust_type_key(&path));
                        }
                        if val_ty == Some(Type::TYPE_STRING) {
                            out.elements
                                .entry(context::rust_type_key(&path))
                                .or_insert(CustomElemKind::String);
                        }
                    }
                    continue;
                }

                let field_features = crate::features::resolve_field(ctx, field, &msg_features);
                let ty = crate::impl_message::effective_type(ctx, field, &field_features);
                match ty {
                    Type::TYPE_STRING => {
                        if let crate::StringRepr::Custom(path) = ctx.string_repr(&field_fqn) {
                            out.elements
                                .entry(context::rust_type_key(&path))
                                .or_insert(CustomElemKind::String);
                        }
                    }
                    Type::TYPE_BYTES => {
                        if let crate::BytesRepr::Custom(path) = ctx.bytes_repr(&field_fqn) {
                            out.elements
                                .entry(context::rust_type_key(&path))
                                .or_insert(CustomElemKind::Bytes);
                        }
                    }
                    _ => {}
                }
            }
            walk(ctx, &msg.nested_type, &fqn, &msg_features, out, all_fields);
        }
    }

    let mut out = CustomElements::default();
    for file_name in files_to_generate {
        let Some(file) = file_descriptors
            .iter()
            .find(|f| f.name.as_deref() == Some(file_name.as_str()))
        else {
            continue;
        };
        let pkg = file.package.as_deref().unwrap_or("");
        let file_features = crate::features::for_file(file);
        walk(
            ctx,
            &file.message_type,
            pkg,
            &file_features,
            &mut out,
            all_fields,
        );
    }
    out
}

/// Render the deduped `ProtoElemJson` / `ReflectElement` impls for the collected
/// custom element types (repeated elements and `map<K, bytes>` values). Each
/// impl is feature-gated so a non-JSON /
/// non-reflect build never references an absent trait. These compile only when
/// the custom type is local to the generating crate (the orphan rule); that is
/// the documented limitation of a custom `repeated` element under JSON or vtable
/// reflection.
fn render_custom_elem_impls(
    ctx: &context::CodeGenContext,
    elems: &CustomElements,
) -> Result<TokenStream, CodeGenError> {
    if !ctx.config.emit_custom_type_impls {
        return Ok(TokenStream::new());
    }
    let json_gate = ctx.config.feature_gates().json;
    let reflect_gate = ctx.config.feature_gates().reflect;
    let mut out = TokenStream::new();
    for (path, kind) in &elems.elements {
        let ty = parse_custom_type_path(path)?;
        // A JSON policy type's elements always go through its policy trait,
        // whether it is a `bytes` or a `string` representation: codegen routes
        // its repeated fields and map values through `ProtoElemJson`.
        if ctx.is_json_policy_type(path) {
            let policy = match kind {
                CustomElemKind::Bytes => quote! { ::buffa::json_helpers::ProtoBytesJson },
                CustomElemKind::String => quote! { ::buffa::json_helpers::ProtoStringJson },
            };
            let borrowed = match kind {
                CustomElemKind::Bytes => quote! { [u8] },
                CustomElemKind::String => quote! { str },
            };
            out.extend(feature_gates::cfg_block(
                quote! {
                    impl ::buffa::json_helpers::ProtoElemJson for #ty {
                        fn serialize_proto_json<__S: ::serde::Serializer>(
                            v: &Self,
                            s: __S,
                        ) -> ::core::result::Result<__S::Ok, __S::Error> {
                            <Self as #policy>::serialize_json(
                                ::core::convert::AsRef::<#borrowed>::as_ref(v),
                                s,
                            )
                        }
                        fn deserialize_proto_json<'de, __D: ::serde::Deserializer<'de>>(
                            d: __D,
                        ) -> ::core::result::Result<Self, __D::Error> {
                            <Self as #policy>::deserialize_json(d)
                        }
                    }
                },
                json_gate,
            ));
        }
        // Otherwise `ProtoElemJson` is only needed for the `bytes` element
        // path (proto3 JSON base64). A repeated `string` element serializes
        // through the native `Vec<T>` serde derive, and custom `string` map
        // keys/values go through serde too (the derive / `string_key_map` /
        // `proto_str_key_map` paths), so a String-kind `ProtoElemJson` impl
        // would be dead code.
        else if ctx.config.generate_json && *kind == CustomElemKind::Bytes {
            out.extend(feature_gates::cfg_block(
                quote! {
                    impl ::buffa::json_helpers::ProtoElemJson for #ty {
                        fn serialize_proto_json<__S: ::serde::Serializer>(
                            v: &Self,
                            s: __S,
                        ) -> ::core::result::Result<__S::Ok, __S::Error> {
                            ::buffa::json_helpers::bytes::serialize(
                                ::core::convert::AsRef::<[u8]>::as_ref(v),
                                s,
                            )
                        }
                        fn deserialize_proto_json<'de, __D: ::serde::Deserializer<'de>>(
                            d: __D,
                        ) -> ::core::result::Result<Self, __D::Error> {
                            ::buffa::json_helpers::bytes::deserialize(d)
                        }
                    }
                },
                json_gate,
            ));
        }
        if ctx.config.generate_reflection_vtable {
            let value_ref = match kind {
                CustomElemKind::String => quote! {
                    ::buffa_descriptor::reflect::ValueRef::String(
                        ::core::convert::AsRef::<str>::as_ref(self),
                    )
                },
                CustomElemKind::Bytes => quote! {
                    ::buffa_descriptor::reflect::ValueRef::Bytes(
                        ::core::convert::AsRef::<[u8]>::as_ref(self),
                    )
                },
            };
            out.extend(feature_gates::cfg_block(
                quote! {
                    impl ::buffa_descriptor::reflect::ReflectElement for #ty {
                        fn as_value_ref(&self) -> ::buffa_descriptor::reflect::ValueRef<'_> {
                            #value_ref
                        }
                    }
                },
                reflect_gate,
            ));
        }
        if ctx.config.generate_reflection
            && (ctx.config.generate_zeroize || !ctx.config.zeroize_messages.is_empty())
        {
            let value = match kind {
                CustomElemKind::String => quote! {
                    ::buffa_descriptor::reflect::InspectValueRef::String(self.as_ref())
                },
                CustomElemKind::Bytes => quote! {
                    ::buffa_descriptor::reflect::InspectValueRef::Bytes(self.as_ref())
                },
            };
            out.extend(feature_gates::cfg_block(
                quote! {
                    impl ::buffa_descriptor::reflect::InspectElement for #ty {
                        fn as_inspect_value(&self) -> ::buffa_descriptor::reflect::InspectValueRef<'_> {
                            #value
                        }
                    }
                },
                reflect_gate,
            ));
        }
    }
    // A custom `string` type used as a `map` key needs `ReflectMapKey` for
    // vtable reflection (the bridge path keys maps by the borrowed `&str` view,
    // which already implements it). Like the element impls above, this compiles
    // only when the type is local to the generating crate (the orphan rule).
    if ctx.config.generate_reflection_vtable
        || (ctx.config.generate_reflection
            && (ctx.config.generate_zeroize || !ctx.config.zeroize_messages.is_empty()))
    {
        for path in &elems.map_keys {
            let ty = parse_custom_type_path(path)?;
            out.extend(feature_gates::cfg_block(
                quote! {
                    impl ::buffa_descriptor::reflect::ReflectMapKey for #ty {
                        fn as_map_key_ref(&self) -> ::buffa_descriptor::reflect::MapKeyRef<'_> {
                            ::buffa_descriptor::reflect::MapKeyRef::String(
                                ::core::convert::AsRef::<str>::as_ref(self),
                            )
                        }
                    }
                },
                reflect_gate,
            ));
        }
    }
    Ok(out)
}

// ── Excluded-package field-reference detection ───────────────────────────

/// Invariants shared across the recursive field-reference walk.
#[derive(Clone, Copy)]
struct ExcludedRefScan<'a> {
    ctx: &'a context::CodeGenContext<'a>,
    /// Effective package-level and per-type extern paths (from
    /// [`effective_extern_paths`], including the auto-injected WKT mapping).
    extern_paths: &'a [(String, String)],
    /// FQNs declared in the kept files — these are always safe to reference.
    declared_in_kept: &'a std::collections::HashSet<String>,
    /// FQNs covered by file-level extern paths (e.g. `descriptor.proto` →
    /// `::buffa_descriptor`). These resolve externally even when the
    /// package-level `extern_paths` don't cover them.
    file_extern_covered: &'a std::collections::HashSet<String>,
}

/// Populate `out` with all message/enum FQNs declared in `file` (in
/// leading-dot form, e.g. `.my.pkg.MyMessage`).
fn collect_fqns_in_file(file: &FileDescriptorProto, out: &mut std::collections::HashSet<String>) {
    let pkg = file.package.as_deref().unwrap_or("");
    for msg in &file.message_type {
        let Some(name) = &msg.name else { continue };
        let fqn = if pkg.is_empty() {
            format!(".{name}")
        } else {
            format!(".{pkg}.{name}")
        };
        collect_fqns_msg_recursive(&fqn, msg, out);
    }
    for en in &file.enum_type {
        let Some(name) = &en.name else { continue };
        let fqn = if pkg.is_empty() {
            format!(".{name}")
        } else {
            format!(".{pkg}.{name}")
        };
        out.insert(fqn);
    }
}

fn collect_fqns_msg_recursive(
    msg_fqn: &str,
    msg: &crate::generated::descriptor::DescriptorProto,
    out: &mut std::collections::HashSet<String>,
) {
    out.insert(msg_fqn.to_string());
    for nested in &msg.nested_type {
        let Some(name) = &nested.name else { continue };
        let nested_fqn = format!("{msg_fqn}.{name}");
        collect_fqns_msg_recursive(&nested_fqn, nested, out);
    }
    for en in &msg.enum_type {
        let Some(name) = &en.name else { continue };
        out.insert(format!("{msg_fqn}.{name}"));
    }
}

/// Check whether `type_fqn` is resolvable and, if not, emit an
/// `ExcludedPackageFieldRef` warning.
///
/// `field_name` is the *attribution* name used in the warning — normally the
/// proto field name, but for map fields it is the outer map field name (e.g.
/// `"prices"`) rather than the synthetic entry's `"value"` slot.
fn warn_excluded_refs_type(
    scan: ExcludedRefScan<'_>,
    file_name: &str,
    message_name: &str,
    field_name: &str,
    type_fqn: &str,
    warned: &mut std::collections::HashSet<(String, String)>,
) {
    // Types declared in kept files are always resolvable.
    if scan.declared_in_kept.contains(type_fqn) {
        return;
    }

    // Look up the package for the diagnostic; if the type is absent from the
    // descriptor set, codegen raises a hard error — skip quietly.
    let Some(ref_package) = scan.ctx.package_of(type_fqn) else {
        return;
    };

    // Package-less (.proto) types: the fix guidance would suggest `.` as an
    // extern_path key, which acts as a catch-all — skip to avoid misleading advice.
    if ref_package.is_empty() {
        return;
    }

    // A per-type or package-level extern_path suppresses the warning.
    if context::resolve_extern_type(type_fqn, scan.extern_paths).is_some() {
        return;
    }

    // File-level externs (e.g. `descriptor.proto` → `::buffa_descriptor`)
    // also suppress — they resolve externally even when no package mapping exists.
    if scan.file_extern_covered.contains(type_fqn) {
        return;
    }

    // Deduplicate by (file, type_fqn): one warning per unique referenced type per file.
    if !warned.insert((file_name.to_string(), type_fqn.to_string())) {
        return;
    }

    scan.ctx.warn(CodeGenWarning::ExcludedPackageFieldRef {
        file_name: file_name.to_string(),
        message_name: message_name.to_string(),
        field_name: field_name.to_string(),
        ref_package: ref_package.to_string(),
        type_fqn: type_fqn.to_string(),
    });
}

fn warn_excluded_refs_field(
    scan: ExcludedRefScan<'_>,
    file_name: &str,
    field: &crate::generated::descriptor::FieldDescriptorProto,
    message_name: &str,
    warned: &mut std::collections::HashSet<(String, String)>,
) {
    let Some(type_fqn) = field.type_name.as_deref().filter(|s| !s.is_empty()) else {
        return;
    };
    warn_excluded_refs_type(
        scan,
        file_name,
        message_name,
        field.name.as_deref().unwrap_or("?"),
        type_fqn,
        warned,
    );
}

fn warn_excluded_refs_msg(
    scan: ExcludedRefScan<'_>,
    file_name: &str,
    msg: &crate::generated::descriptor::DescriptorProto,
    parent_path: &str,
    warned: &mut std::collections::HashSet<(String, String)>,
) {
    let msg_name = msg.name.as_deref().unwrap_or("?");
    let message_path = if parent_path.is_empty() {
        msg_name.to_string()
    } else {
        format!("{parent_path}.{msg_name}")
    };
    use crate::generated::descriptor::field_descriptor_proto::Label;
    for field in &msg.field {
        // Always check the field itself: for plain message fields this emits a
        // warning when the type is excluded; for genuine map fields, type_name
        // points at the synthetic entry (same file, in declared_in_kept), so
        // warn_excluded_refs_type returns immediately with no warning.
        warn_excluded_refs_field(scan, file_name, field, &message_path, warned);

        // Additionally, for map fields, look through the synthetic entry to the
        // value field: the entry is safe (declared_in_kept), but the value type
        // may be from an excluded package. Attribute the warning to the outer
        // map field name (e.g. "prices"), not the entry's "value" slot.
        //
        // The LABEL_REPEATED gate mirrors every other is_map_field call site:
        // is_map_field looks at the type, not the label, so a singular field
        // typed as the synthetic entry would otherwise get the value-slot
        // check. The field itself is already checked above either way.
        let is_repeated = field.label.unwrap_or_default() == Label::LABEL_REPEATED;
        if is_repeated && crate::message::is_map_field(msg, field) {
            // Malformed entries (no key/value) are silently skipped — this is a
            // diagnostic pass; real codegen errors on the same descriptor follow.
            if let Ok((_, value_field)) = crate::impl_message::find_map_entry_fields(msg, field) {
                if let Some(type_fqn) = value_field.type_name.as_deref().filter(|s| !s.is_empty()) {
                    warn_excluded_refs_type(
                        scan,
                        file_name,
                        &message_path,
                        field.name.as_deref().unwrap_or("?"),
                        type_fqn,
                        warned,
                    );
                }
            }
        }
    }
    for ext in &msg.extension {
        warn_excluded_refs_field(scan, file_name, ext, &message_path, warned);
    }
    for nested in &msg.nested_type {
        // Skip synthetic map-entry messages: their cross-package references are
        // checked above via the owning map field.
        if nested
            .options
            .as_option()
            .and_then(|o| o.map_entry)
            .unwrap_or(false)
        {
            continue;
        }
        warn_excluded_refs_msg(scan, file_name, nested, &message_path, warned);
    }
}

/// Like [`generate`], but also returns the non-fatal [`CodeGenWarning`]s
/// collected during generation (e.g. enums whose idiomatic CamelCase aliases
/// were suppressed by a naming conflict).
///
/// Report each warning through its [`Display`](core::fmt::Display) impl — e.g.
/// as a `cargo:warning=...` from a `build.rs`, or on stderr from a standalone
/// generator — or match on it for programmatic handling. [`generate`] discards
/// them.
///
/// A name listed twice in `files_to_generate` is generated once.
///
/// Warnings are returned only on success. On error, any warnings already
/// collected are dropped along with the partial output — the [`CodeGenError`]
/// is the actionable signal.
///
/// # Errors
///
/// - [`CodeGenError::FileNotFound`] if a name in `files_to_generate` has no
///   matching descriptor.
/// - [`CodeGenError::OutputFileNameConflict`] if two generated files would
///   be written to the same output path.
/// - [`CodeGenError::InvalidTypeNamePrefix`] if
///   [`CodeGenConfig::type_name_prefix`] is neither empty nor PascalCase.
/// - [`CodeGenError::InvalidCustomAttribute`] if a custom attribute string,
///   such as one in [`CodeGenConfig::type_attributes`], is not one or more
///   outer `#[...]` attributes.
/// - [`CodeGenError::Other`] if `config` sets an option without the option
///   it requires: `generate_reflection_vtable` or `shared_descriptor_pool`
///   without `generate_reflection`, `shared_descriptor_pool_root` without
///   `shared_descriptor_pool`, or `idiomatic_imports` without
///   `file_per_package`.
/// - [`CodeGenError::Other`] if an active feature-gate name in
///   [`CodeGenConfig::feature_gate_names`] is not a valid Cargo feature name,
///   or if `shared_descriptor_pool_root` or an `exclude_packages` entry is
///   malformed.
/// - [`CodeGenError::SharedCorpusContextMismatch`] if
///   [`CodeGenConfig::shared_corpus_context`] was built from a different
///   corpus or different rules than this call uses.
/// - For a valid schema whose names collide in the generated Rust:
///   [`CodeGenError::OneofEnumNameConflict`],
///   [`CodeGenError::OneofVariantNameConflict`],
///   [`CodeGenError::TypeNameConflict`],
///   [`CodeGenError::ModuleNameConflict`],
///   [`CodeGenError::ReservedFieldName`] or
///   [`CodeGenError::ReservedModuleName`].
/// - [`CodeGenError::DuplicateFieldNumber`] if a message of a file in
///   `files_to_generate` has two fields with one field number, which protoc
///   rejects.
/// - Other [`CodeGenError`] variants for a schema that generation does not
///   support or a malformed descriptor, such as
///   [`CodeGenError::MissingField`].
pub fn generate_with_diagnostics(
    file_descriptors: &[FileDescriptorProto],
    files_to_generate: &[String],
    config: &CodeGenConfig,
) -> Result<(Vec<GeneratedFile>, Vec<CodeGenWarning>), CodeGenError> {
    // Vtable reflection resolves against the per-package descriptor pool, which
    // is emitted by bridge-mode reflection — so it requires `generate_reflection`.
    // It does NOT require views: the owned `impl ReflectMessage` is self-contained,
    // so with views off, vtable mode still emits owned-message reflection (the
    // view impls are simply skipped along with the views).
    if config.generate_reflection_vtable && !config.generate_reflection {
        return Err(CodeGenError::Other(
            "generate_reflection_vtable requires generate_reflection to be enabled \
             (it provides the descriptor pool the reflect impls resolve against)"
                .into(),
        ));
    }

    // Shared-pool mode only rearranges where the reflection descriptor bytes
    // live, so it is meaningless — and would silently no-op — without
    // reflection. Reject it up front rather than dropping the flag.
    if config.shared_descriptor_pool && !config.generate_reflection {
        return Err(CodeGenError::Other(
            "shared_descriptor_pool requires generate_reflection to be enabled \
             (it deduplicates the embedded reflection descriptor pool)"
                .into(),
        ));
    }

    // shared_descriptor_pool_root only overrides how the shared root is
    // reached, so — like shared_descriptor_pool without generate_reflection
    // above — it is meaningless, and would silently no-op, without
    // shared_descriptor_pool itself. Reject it up front rather than
    // dropping the override.
    if let Some(root) = &config.shared_descriptor_pool_root {
        if !config.shared_descriptor_pool {
            return Err(CodeGenError::Other(
                "shared_descriptor_pool_root requires shared_descriptor_pool to be \
                 enabled (it overrides the path to the shared root, which only exists \
                 in shared-pool mode)"
                    .into(),
            ));
        }
        validate_shared_root_path(root)?;
    }

    // Idiomatic imports place `use` directives in the package-root scope,
    // which is only single-writer (collision-free by construction) when the
    // whole package is one generated file.
    if config.idiomatic_imports && !config.file_per_package {
        return Err(CodeGenError::Other(
            "idiomatic_imports requires file_per_package to be enabled (the multi-file \
             layout include!-merges every proto's content into the shared package root, \
             where emitted `use` directives could collide across files)"
                .into(),
        ));
    }

    // Active feature-gate names are emitted verbatim into
    // `#[cfg(feature = "...")]`; an invalid name fails open (the cfg is
    // permanently false and the gated impls silently compile away), so it
    // must be a hard error here rather than a debug assertion — build
    // scripts and protoc plugins typically run as release builds.
    if let Err((kind, name)) = config.feature_gates().validate() {
        return Err(CodeGenError::Other(format!(
            "invalid {kind} feature-gate name {name:?}: a Cargo feature name starts \
             with an ASCII alphanumeric or '_' and contains only alphanumerics, \
             '_', '-', '+', or '.'; an invalid name would leave the emitted \
             #[cfg(feature = ...)] permanently false, silently compiling the \
             gated impls away"
        )));
    }

    config.validate_type_name_prefix()?;
    context::validate_custom_attributes(config)?;

    // Normalize exclude_packages entries (optional leading dot stripped). The
    // plugin normalizes before it gets here and buffa-build validates in
    // `compile()`, so this is the one place a direct `CodeGenConfig` caller's
    // entries are checked; the message is the normalizer's own.
    let normalized_excludes: Vec<String> = config
        .exclude_packages
        .iter()
        .map(|entry| {
            normalize_exclude_package(entry)
                .map_err(|e| CodeGenError::Other(format!("exclude_package {entry:?}: {e}")))
        })
        .collect::<Result<_, _>>()?;
    // Drop files whose proto package is listed in `config.exclude_packages`
    // BEFORE building the codegen context, so that context decisions that key
    // on `files_to_generate` membership (e.g. WKT auto-extern-path injection,
    // descriptor.proto suppression) see the filtered set. Their descriptors
    // stay in `file_descriptors` for type resolution; only code generation is
    // skipped. A file with no matching descriptor is kept — the FileNotFound
    // error below is more actionable than silently dropping it here.
    let effective_files_to_generate: std::borrow::Cow<'_, [String]> =
        if normalized_excludes.is_empty() {
            std::borrow::Cow::Borrowed(files_to_generate)
        } else {
            std::borrow::Cow::Owned(
                files_to_generate
                    .iter()
                    .filter(|name| {
                        match file_descriptors
                            .iter()
                            .find(|fd| fd.name.as_deref() == Some(name.as_str()))
                        {
                            Some(fd) => !package_is_excluded(
                                fd.package.as_deref().unwrap_or(""),
                                &normalized_excludes,
                            ),
                            None => true,
                        }
                    })
                    .cloned()
                    .collect(),
            )
        };
    let files_to_generate: &[String] = &effective_files_to_generate;

    // Feature overrides are applied by mutating the descriptor set up front,
    // so every downstream consumer — feature resolution, all generation
    // paths, and the embedded reflection descriptor pool — reads the same
    // overridden features. With no overrides configured this is a no-op
    // borrow.
    let overridden =
        feature_overrides::apply_feature_overrides(file_descriptors, &config.feature_overrides);
    let file_descriptors: &[FileDescriptorProto] =
        overridden.as_ref().map_or(file_descriptors, |o| &o.files);

    if let Some(shared) = &config.shared_corpus_context {
        shared.check(file_descriptors, config)?;
    }
    let ctx = context::CodeGenContext::for_generate(file_descriptors, files_to_generate, config);

    // An inert rule means the user opted a path out of its default semantics
    // and silently didn't get it — warn per rule so typos surface at build
    // time instead of as production behavior surprises.
    if let Some(o) = &overridden {
        for (rule, ovr) in &o.unmatched {
            ctx.warn(CodeGenWarning::FeatureOverrideMatchedNothing {
                rule: rule.clone(),
                feature: ovr.feature_name(),
                value: ovr.value_name(),
            });
        }
    }

    // A `preserve_unknown_fields_in` rule that names no generated message
    // (typo, field path, extern-mapped package) leaves its intended messages
    // on the global default — for a re-enable rule, silently losing
    // round-trip fidelity — so warn per rule.
    for (rule, _) in &config.preserve_unknown_fields_in {
        if !rule_matches_generated_message(rule, file_descriptors, files_to_generate) {
            ctx.warn(CodeGenWarning::PreserveUnknownFieldsRuleMatchedNothing {
                rule: rule.clone(),
            });
        }
    }

    let known_files = file_descriptors
        .iter()
        .filter_map(|file| file.name.clone())
        .collect::<Vec<_>>();
    for rule in &config.zeroize_messages {
        if rule.trim().is_empty() {
            return Err(CodeGenError::ZeroizeRuleMatchedNothing { rule: rule.clone() });
        }
        if !rule_matches_generated_message(rule, file_descriptors, &known_files) {
            if config.allow_unmatched_message_rules {
                ctx.warn(CodeGenWarning::ZeroizeRuleMatchedNothing { rule: rule.clone() });
            } else {
                return Err(CodeGenError::ZeroizeRuleMatchedNothing { rule: rule.clone() });
            }
        }
    }
    for rule in &config.deny_view_json {
        if rule.trim().is_empty() {
            return Err(CodeGenError::ViewJsonRuleMatchedNothing { rule: rule.clone() });
        }
        if !rule_matches_generated_message(rule, file_descriptors, &known_files) {
            if config.allow_unmatched_message_rules {
                ctx.warn(CodeGenWarning::ViewJsonRuleMatchedNothing { rule: rule.clone() });
            } else {
                return Err(CodeGenError::ViewJsonRuleMatchedNothing { rule: rule.clone() });
            }
        }
    }

    if !config.deny_view_json.is_empty() && (!config.generate_json || !config.generate_views) {
        ctx.warn(CodeGenWarning::ViewJsonRulesRequireJsonAndViews);
    }

    // A JSON policy needs generated JSON, and a listed type must be one that a
    // representation rule actually selects.
    if !config.json_policy_types.is_empty() && !config.generate_json {
        ctx.warn(CodeGenWarning::JsonPolicyTypesRequireJson);
    }
    // Validate configuration bindings, not just fields in this invocation.
    // Buf's directory strategy gives each process only that directory's files;
    // policy types used by another directory must still be accepted here.
    let representation_types = unshadowed_rules(&config.bytes_fields)
        .filter_map(|repr| match repr {
            BytesRepr::Custom(path) => Some(path),
            _ => None,
        })
        .chain(
            unshadowed_rules(&config.string_fields).filter_map(|repr| match repr {
                StringRepr::Custom(path) => Some(path),
                _ => None,
            }),
        )
        .collect::<Vec<_>>();
    for rust_type in &config.json_policy_types {
        let key = context::rust_type_key(rust_type);
        let selected = representation_types
            .iter()
            .any(|path| context::rust_type_key(path) == key);
        if !selected {
            return Err(CodeGenError::JsonPolicyTypeMatchedNothing {
                rust_type: rust_type.clone(),
            });
        }
    }
    // A correctly-spelled rule must not hide another rule that silently lost
    // the policy. Compare type names only after checking exact parsed spelling;
    // deliberate same-name types remain usable by listing each one explicitly.
    for selected in representation_types {
        if config
            .json_policy_types
            .iter()
            .any(|listed| context::rust_type_key(listed) == context::rust_type_key(selected))
        {
            continue;
        }
        let Some(selected_name) = context::rust_type_name(selected) else {
            continue;
        };
        if let Some(listed) = config.json_policy_types.iter().find(|listed| {
            context::rust_type_name(listed).as_deref() == Some(selected_name.as_str())
        }) {
            return Err(CodeGenError::JsonPolicyTypeNearMiss {
                selected: selected.clone(),
                listed: listed.clone(),
            });
        }
    }

    // JSON strictness needs JSON deserializers to attach to. Warn once per run.
    if !config.generate_json
        && (config.deny_unknown_json_fields
            || config
                .deny_unknown_json_fields_in
                .iter()
                .any(|(_, enabled)| *enabled))
    {
        ctx.warn(CodeGenWarning::DenyUnknownJsonFieldsRequiresJson);
    }

    // Same treatment for `deny_unknown_json_fields_in`: an inert enabling rule
    // leaves its messages silently ignoring unknown JSON keys, which is the
    // exact failure the rule was added to stop.
    for (rule, _) in &config.deny_unknown_json_fields_in {
        if !rule_matches_generated_message(rule, file_descriptors, files_to_generate) {
            ctx.warn(CodeGenWarning::DenyUnknownJsonFieldsRuleMatchedNothing {
                rule: rule.clone(),
            });
        }
    }

    // Warn per inert `skip_debug` rule; `SkipDebugRuleMatchedNothing`
    // documents the consequence.
    for rule in &config.skip_debug {
        if !rule_matches_generated_message(rule, file_descriptors, files_to_generate)
            && !rule_names_generated_enum(rule, file_descriptors, files_to_generate)
        {
            ctx.warn(CodeGenWarning::SkipDebugRuleMatchedNothing { rule: rule.clone() });
        }
    }

    // A field-type rule that matches no generated field leaves the fields it
    // was written for on their default Rust type, and the build still
    // succeeds, so warn per rule.
    let field_type_rules = [
        ("bytes_fields", rule_paths(&config.bytes_fields)),
        ("string_fields", rule_paths(&config.string_fields)),
        ("map_fields", rule_paths(&config.map_fields)),
        ("repeated_fields", rule_paths(&config.repeated_fields)),
    ];
    let mut every_file: Option<Vec<String>> = None;
    for (option, rules) in field_type_rules {
        for rule in rules {
            if rule_matches_field_in(rule, file_descriptors, files_to_generate) {
                continue;
            }
            let every_file: &[String] = every_file.get_or_insert_with(|| {
                file_descriptors
                    .iter()
                    .filter_map(|fd| fd.name.clone())
                    .collect()
            });
            ctx.warn(CodeGenWarning::FieldTypeRuleMatchedNothing {
                rule: rule.clone(),
                option,
                matches_ungenerated: rule_matches_field_in(rule, file_descriptors, every_file),
            });
        }
    }

    // A rule that names no generated message (typo, field path, extern-mapped
    // package) leaves its messages on the global strategy.
    for (rule, _) in &config.codec_strategy_in {
        if !rule_matches_generated_message(rule, file_descriptors, files_to_generate) {
            ctx.warn(CodeGenWarning::CodecStrategyRuleMatchedNothing { rule: rule.clone() });
        }
    }
    // Two fields with one number make the generated code wrong under either
    // codec. Checked before the table plan: a message that also cannot use
    // the table would otherwise get the plan's advice to select the unrolled
    // codec, which fails here too.
    for (file, _) in generated_files(file_descriptors, files_to_generate) {
        check_field_numbers(&file.message_type, file.package.as_deref().unwrap_or(""))?;
    }
    if ctx.table_codec_requested() {
        ctx.plan_table_codec(file_descriptors, files_to_generate)?;
    }

    // Lazy views need the eager view machinery; warn once per run.
    if config.lazy_views && !config.generate_views {
        ctx.warn(CodeGenWarning::LazyViewsRequireViews);
    }

    // Warn about exclude_packages entries that matched no package in the full
    // descriptor set — likely a typo or stale entry. Checked against
    // file_descriptors (not just files_to_generate) so plugin users without
    // include_imports don't get spurious warnings for packages they never
    // compiled in the first place.
    for package in &normalized_excludes {
        let matched = file_descriptors.iter().any(|fd| {
            package_is_excluded(
                fd.package.as_deref().unwrap_or(""),
                std::slice::from_ref(package),
            )
        });
        if !matched {
            ctx.warn(CodeGenWarning::ExcludePackageMatchedNothing {
                package: package.clone(),
            });
        }
    }

    // Group requested files by package. BTreeMap → deterministic output order.
    let mut by_package: std::collections::BTreeMap<String, Vec<&FileDescriptorProto>> =
        std::collections::BTreeMap::new();
    let mut grouped = std::collections::HashSet::new();
    for file_name in files_to_generate {
        // A file listed twice is generated once.
        if !grouped.insert(file_name.as_str()) {
            continue;
        }
        let file_desc = file_descriptors
            .iter()
            .find(|f| f.name.as_deref() == Some(file_name.as_str()))
            .ok_or_else(|| CodeGenError::FileNotFound(file_name.clone()))?;
        let pkg = file_desc.package.as_deref().unwrap_or("").to_string();
        by_package.entry(pkg).or_default().push(file_desc);
    }

    // Warn when a kept file references a type that is not being generated and
    // has no extern_path mapping. This catches exclude_package misuse (and
    // missing extern_path) before the consumer gets a dangling `super::…::Type`
    // compile error with no indication of the configuration gap.
    {
        let extern_paths = effective_extern_paths(file_descriptors, files_to_generate, config);

        // Collect the FQNs of every type declared in a kept file.
        // These are always safe to reference (generated in place).
        let mut declared_in_kept: std::collections::HashSet<String> =
            std::collections::HashSet::new();
        for files in by_package.values() {
            for &file in files {
                collect_fqns_in_file(file, &mut declared_in_kept);
            }
        }

        // Collect FQNs covered by file-level externs (e.g. descriptor.proto →
        // ::buffa_descriptor). These resolve externally even when the package-level
        // extern_paths don't cover them — suppressing false positives when the
        // auto-injected .google.protobuf package mapping is overridden.
        let file_extern_paths = effective_file_extern_paths(files_to_generate, config);
        let mut file_extern_covered: std::collections::HashSet<String> =
            std::collections::HashSet::new();
        for (fe_file, _) in &file_extern_paths {
            if let Some(fd) = file_descriptors
                .iter()
                .find(|f| f.name.as_deref() == Some(fe_file.as_str()))
            {
                collect_fqns_in_file(fd, &mut file_extern_covered);
            }
        }

        let scan = ExcludedRefScan {
            ctx: &ctx,
            extern_paths: &extern_paths,
            declared_in_kept: &declared_in_kept,
            file_extern_covered: &file_extern_covered,
        };
        let mut warned: std::collections::HashSet<(String, String)> =
            std::collections::HashSet::new();
        for files in by_package.values() {
            for &file in files {
                let file_name = file.name.as_deref().unwrap_or("?");
                for msg in &file.message_type {
                    warn_excluded_refs_msg(scan, file_name, msg, "", &mut warned);
                }
                for ext in &file.extension {
                    warn_excluded_refs_field(scan, file_name, ext, "", &mut warned);
                }
            }
        }
    }

    // Reflection: serialize the FileDescriptorSet once, regardless of how
    // many packages are in the request, so the build-time re-encoding cost
    // doesn't scale with the package count. In the default mode each package
    // embeds this copy; in shared-pool mode the bytes are embedded once by the
    // module-tree builder, not per package, so `generate` needs no copy at all.
    // In shared mode (without a `shared_descriptor_pool_root` override) the
    // tree root gains a `pub mod __buffa_fds`; reserve that name against user
    // packages/types the same way `__buffa` is reserved, so a
    // `package __buffa_fds;` (or a root-package type named `__buffa_fds`) fails
    // with a clear error instead of a duplicate-module collision at the root.
    // With an override the reservation is skipped for both absolute and
    // crate-relative roots: buffa cannot verify where the override points,
    // so a package/type actually named `__buffa_fds` in this tree would go
    // undetected rather than erroring here.
    if config.shared_descriptor_pool && config.shared_descriptor_pool_root.is_none() {
        validate_shared_root_name(file_descriptors, files_to_generate)?;
    }

    // `file_descriptors` is the override-applied set (rebound above). The
    // default path embeds it directly; shared mode embeds nothing here and
    // leaves the single copy to the front-end, which must reproduce the same
    // overrides via `encode_descriptor_set`. On the plugin path — where the
    // packaging plugin can't see the override options — that combination is
    // rejected up front (see `protoc-gen-reallyme-buffa`).
    let fds_bytes = if config.generate_reflection && !config.shared_descriptor_pool {
        reflect::encode_fds_once(file_descriptors)
    } else {
        Vec::new()
    };

    // Custom owned types used as elements of a `repeated` field need a
    // `ProtoElemJson` (JSON) and/or `ReflectElement` (vtable) impl, which buffa
    // cannot provide for a foreign type (orphan rule). Collect them once across
    // the whole request, render the impls, and hand them to the first package so
    // they are emitted exactly once (a per-package emit would collide, E0119).
    let custom_elems = collect_custom_elements(&ctx, file_descriptors, files_to_generate, false);
    let custom_elem_impls = render_custom_elem_impls(&ctx, &custom_elems)?;

    let empty_impls = TokenStream::new();
    let mut output = Vec::new();
    let mut output_names = OutputNames::default();
    let mut custom_emitted = false;
    for (package, files) in by_package {
        let impls = if custom_emitted {
            &empty_impls
        } else {
            custom_emitted = true;
            &custom_elem_impls
        };
        generate_package(
            &ctx,
            &package,
            &files,
            &fds_bytes,
            impls,
            &mut output_names,
            &mut output,
        )?;
    }

    Ok((output, ctx.take_warnings()))
}

/// The output paths assigned so far in one [`generate`] call, each with the
/// input it was generated from, in the form
/// [`CodeGenError::OutputFileNameConflict`] documents.
#[derive(Default)]
struct OutputNames(std::collections::HashMap<String, String>);

impl OutputNames {
    /// Records that `source` generates `file_name`.
    ///
    /// # Errors
    ///
    /// [`CodeGenError::OutputFileNameConflict`] if another input already
    /// generates `file_name`.
    fn claim(&mut self, file_name: &str, source: String) -> Result<(), CodeGenError> {
        use std::collections::hash_map::Entry;
        match self.0.entry(file_name.to_owned()) {
            Entry::Occupied(first) => Err(CodeGenError::OutputFileNameConflict {
                file_name: file_name.to_owned(),
                first_source: first.get().clone(),
                second_source: source,
            }),
            Entry::Vacant(slot) => {
                slot.insert(source);
                Ok(())
            }
        }
    }
}

/// Generate a module tree that assembles per-package `.mod.rs` files into
/// nested `pub mod` blocks matching the protobuf package hierarchy.
///
/// Each entry is a `(mod_file_name, package)` pair where `package` is the
/// dot-separated protobuf package name (e.g., `"google.api"`) and
/// `mod_file_name` is the corresponding `<pkg>.mod.rs` (only
/// [`GeneratedFileKind::PackageMod`] outputs need wiring; per-proto
/// content files are reached via `include!` from the stitcher).
///
/// `include_mode` controls how `include!` paths are emitted.
///
/// `emit_inner_allow` adds a `#![allow(...)]` inner attribute at the top —
/// valid when the output is used directly as a module file (`mod.rs`),
/// invalid when consumed via `include!`.
pub fn generate_module_tree<F: AsRef<str>, P: AsRef<str>>(
    entries: &[(F, P)],
    include_mode: IncludeMode<'_>,
    emit_inner_allow: bool,
) -> String {
    use std::collections::BTreeMap;
    use std::fmt::Write;

    use crate::idents::escape_mod_ident;

    #[derive(Default)]
    struct ModNode {
        files: Vec<String>,
        children: BTreeMap<String, Self>,
    }

    let mut root = ModNode::default();

    for (file_name, package) in entries {
        let package = package.as_ref();
        let pkg_parts: Vec<&str> = if package.is_empty() {
            vec![]
        } else {
            package.split('.').collect()
        };

        let mut node = &mut root;
        for seg in &pkg_parts {
            node = node.children.entry(seg.to_string()).or_default();
        }
        node.files.push(file_name.as_ref().to_string());
    }

    let lints = ALLOW_LINTS.join(", ");
    let mut out = String::new();
    out.push_str(GENERATED_HEADER);
    if emit_inner_allow {
        let _ = writeln!(out, "#![allow({lints})]");
    }
    let _ = writeln!(out);

    fn emit(out: &mut String, node: &ModNode, depth: usize, mode: IncludeMode<'_>, lints: &str) {
        let indent = "    ".repeat(depth);

        for file in &node.files {
            match mode {
                IncludeMode::Relative(prefix) => {
                    let path = format!("{prefix}{file}");
                    let _ = writeln!(out, "{indent}include!({path:?});");
                }
                IncludeMode::OutDir => {
                    let path = format!("/{file}");
                    let _ = writeln!(
                        out,
                        "{indent}include!(concat!(env!(\"OUT_DIR\"), {path:?}));"
                    );
                }
            }
        }

        for (name, child) in &node.children {
            let escaped = escape_mod_ident(name);
            let _ = writeln!(out, "{indent}#[allow({lints})]");
            let _ = writeln!(out, "{indent}pub mod {escaped} {{");
            let _ = writeln!(out, "{indent}    use super::*;");
            emit(out, child, depth + 1, mode, lints);
            let _ = writeln!(out, "{indent}}}");
        }
    }

    emit(&mut out, &root, 0, include_mode, &lints);
    out
}

/// How [`generate_module_tree`] emits `include!` paths.
#[derive(Debug, Clone, Copy)]
pub enum IncludeMode<'a> {
    /// `include!("<prefix><file>")` — relative to the including file.
    /// Prefix is typically `""` or `"gen/"`.
    Relative(&'a str),
    /// `include!(concat!(env!("OUT_DIR"), "/<file>"))` — for build.rs output.
    OutDir,
}

/// The corpus-wide state `CodeGenContext` derives on every `generate()`
/// call — which oneof variants are unboxed, which message fields are stored
/// inline, and the raw comment text per fully-qualified name — none of which
/// depends on the extern paths that legitimately vary per call in a
/// one-crate-per-package workspace. Build one with [`SharedCorpusContext::new`]
/// from the whole corpus and set [`CodeGenConfig::shared_corpus_context`] on
/// every per-package config to skip that work on each call.
///
/// A context is only valid for the exact `files` and the same
/// `unboxed_oneof_fields`/`pointer_fields` it was built from; `generate`
/// checks both and returns [`CodeGenError::SharedCorpusContextMismatch`]
/// rather than emitting code resolved against a different corpus. The
/// context holds the corpus comment map for as long as any clone of it lives,
/// so drop it once code generation is done. Cloning shares the precomputed
/// state (`Arc`s inside), and the type is `Send + Sync`, so one context can
/// be handed to parallel per-package `generate()` calls.
///
/// # Examples
///
/// ```
/// use buffa_codegen::{CodeGenConfig, SharedCorpusContext};
/// # use buffa_codegen::generated::descriptor::FileDescriptorProto;
/// # let corpus: Vec<FileDescriptorProto> = Vec::new();
/// # let packages: Vec<(String, Vec<String>)> = Vec::new();
/// let base = CodeGenConfig::default();
/// let shared = SharedCorpusContext::new(&corpus, &base);
/// for (extern_prefix, files_to_generate) in packages {
///     let mut config = base.clone();
///     config.extern_paths.push((extern_prefix, "::other_crate".to_string()));
///     config.shared_corpus_context = Some(shared.clone());
///     let _files = buffa_codegen::generate(&corpus, &files_to_generate, &config)?;
/// }
/// # Ok::<(), buffa_codegen::CodeGenError>(())
/// ```
#[derive(Clone)]
pub struct SharedCorpusContext {
    /// The exact corpus this context was built from, compared by full
    /// structural equality in [`check`](Self::check) rather than just file
    /// names — see `check` for why.
    files: std::sync::Arc<Vec<generated::descriptor::FileDescriptorProto>>,
    unboxed_oneof_fields: std::sync::Arc<Vec<String>>,
    pointer_fields: std::sync::Arc<Vec<(String, PointerRepr)>>,
    unboxed_oneof_variants: std::sync::Arc<std::collections::HashSet<String>>,
    inlined_message_fields: std::sync::Arc<std::collections::HashSet<String>>,
    comment_map: std::sync::Arc<std::collections::HashMap<String, String>>,
}

impl SharedCorpusContext {
    /// Precompute the corpus-wide state for `files` under `config`'s oneof
    /// and pointer-representation rules, for reuse across every `generate()`
    /// call that passes the same `files` and rules (see
    /// [`CodeGenConfig::shared_corpus_context`]).
    #[must_use]
    pub fn new(
        files: &[generated::descriptor::FileDescriptorProto],
        config: &CodeGenConfig,
    ) -> Self {
        let msg_index = oneof::message_index(files);
        let unboxed_oneof_variants = oneof::resolve_unboxed_variants(
            &msg_index,
            &config.unboxed_oneof_fields,
            &config.pointer_fields,
        );
        let inlined_message_fields = oneof::resolve_inlined_fields(
            &msg_index,
            &config.unboxed_oneof_fields,
            &config.pointer_fields,
        );
        let comment_map = files.iter().flat_map(comments::fqn_comments).collect();
        Self {
            files: std::sync::Arc::new(files.to_vec()),
            unboxed_oneof_fields: std::sync::Arc::new(config.unboxed_oneof_fields.clone()),
            pointer_fields: std::sync::Arc::new(config.pointer_fields.clone()),
            unboxed_oneof_variants: std::sync::Arc::new(unboxed_oneof_variants),
            inlined_message_fields: std::sync::Arc::new(inlined_message_fields),
            comment_map: std::sync::Arc::new(comment_map),
        }
    }

    /// Refuse a context built from a different corpus or different
    /// oneof/pointer-repr rules than this call's. Compares the full corpus
    /// by structural equality rather than just file names, since
    /// `SharedCorpusContext` has no lifetime tying it to the caller's
    /// `files` — a `Vec` can keep its allocation across an ordinary
    /// `pop()` + `push()` of a different file, so a pointer/length check
    /// would be unsound. O(corpus) per call; ~25-28% added wall/CPU time on
    /// a 2895-crate corpus versus a name-only comparison, still a ~2.3x win
    /// over not sharing the context at all.
    pub(crate) fn check(
        &self,
        files: &[generated::descriptor::FileDescriptorProto],
        config: &CodeGenConfig,
    ) -> Result<(), CodeGenError> {
        let what = if *files != self.files[..] {
            "files"
        } else if *self.unboxed_oneof_fields != config.unboxed_oneof_fields {
            "unboxed_oneof_fields"
        } else if *self.pointer_fields != config.pointer_fields {
            "pointer_fields"
        } else {
            return Ok(());
        };
        Err(CodeGenError::SharedCorpusContextMismatch { what })
    }

    pub(crate) fn unboxed_oneof_variants(
        &self,
    ) -> &std::sync::Arc<std::collections::HashSet<String>> {
        &self.unboxed_oneof_variants
    }

    pub(crate) fn inlined_message_fields(
        &self,
    ) -> &std::sync::Arc<std::collections::HashSet<String>> {
        &self.inlined_message_fields
    }

    pub(crate) fn comment_map(&self) -> &std::sync::Arc<std::collections::HashMap<String, String>> {
        &self.comment_map
    }
}

// The comment map is the whole corpus's comment text; print sizes, not
// contents, so a `{:?}` of a `CodeGenConfig` stays readable.
impl core::fmt::Debug for SharedCorpusContext {
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        f.debug_struct("SharedCorpusContext")
            .field("files", &self.files.len())
            .field("unboxed_oneof_variants", &self.unboxed_oneof_variants.len())
            .field("inlined_message_fields", &self.inlined_message_fields.len())
            .field("comments", &self.comment_map.len())
            .finish()
    }
}

/// Encode the shared reflection `FileDescriptorSet` for a codegen run, with
/// `source_code_info` stripped, ready to embed once at the module-tree root in
/// [shared-pool mode](CodeGenConfig::shared_descriptor_pool).
///
/// `file_descriptors` is the full transitive closure (the same slice passed to
/// [`generate`]). Front-ends (`buffa-build`, `protoc-gen-reallyme-buffa-packaging`)
/// call this to obtain the single copy of the bytes, then hand them to
/// [`shared_descriptor_root_module`].
#[must_use]
pub fn encode_descriptor_set(
    file_descriptors: &[generated::descriptor::FileDescriptorProto],
    feature_overrides: &[(String, FeatureOverride)],
) -> Vec<u8> {
    // `generate` applies feature overrides to the descriptors up front and the
    // default (non-shared) path embeds *that* override-applied set, so the
    // embedded reflection descriptors match the generated code. Shared mode
    // skips `generate`'s encode, so any front-end computing the shared copy
    // here must apply the same transform — otherwise the shared pool reports
    // un-overridden features (e.g. an `open_enums_in` enum still closed) and
    // disagrees with the code. Pass the same `feature_overrides` the codegen
    // config carries; `&[]` when none are configured (the common case, a
    // borrow with no clone).
    let overridden =
        feature_overrides::apply_feature_overrides(file_descriptors, feature_overrides);
    let files = overridden.as_ref().map_or(file_descriptors, |o| &o.files);
    reflect::encode_fds_once(files)
}

/// How [`shared_descriptor_root_module`] embeds the descriptor set into the
/// generated tree. Both forms decode to byte-identical runtime data; they
/// differ only in generated-source size and whether a sidecar file is written.
#[derive(Debug, Clone, Copy)]
#[non_exhaustive]
pub enum FdsEmbedding<'a> {
    /// Embed the bytes inline as a byte-string literal. Self-contained: no extra
    /// file, but the descriptor bytes cost several times their size in
    /// generated Rust source. This is all the plugin path can do, since
    /// protoc's `CodeGeneratorResponse` carries only UTF-8 text.
    Inline,
    /// `include_bytes!` a sidecar file the caller writes next to the generated
    /// tree, keeping the bytes out of the Rust source entirely. `file_name` is
    /// the sidecar's name; `mode` mirrors [`generate_module_tree`]'s —
    /// [`IncludeMode::Relative`] for a checked-in sibling,
    /// [`IncludeMode::OutDir`] for build-script output. The caller is
    /// responsible for writing `fds_bytes` to that file.
    Sidecar {
        file_name: &'a str,
        mode: IncludeMode<'a>,
    },
}

/// Render the shared `__buffa_fds` root module as formatted Rust source, for a
/// front-end to prepend to the module-tree file in
/// [shared-pool mode](CodeGenConfig::shared_descriptor_pool). Every package's
/// `__buffa::reflect` module delegates here, so the descriptor set is embedded
/// once for the whole tree instead of once per package.
///
/// `fds_bytes` is the output of [`encode_descriptor_set`]. `embedding` chooses
/// inline vs. an `include_bytes!` sidecar (see [`FdsEmbedding`]). `gate` wraps
/// the module in `#[cfg(feature = "<gate>")]` when `Some`, to match
/// [`CodeGenConfig::reflect_feature_gate`] (so the root module and the
/// per-package delegations appear and disappear together); pass `None` when
/// reflection is unconditional.
///
/// # Panics
///
/// Panics if the rendered module fails to parse — it is machine-generated, so
/// a parse failure is a codegen bug.
#[must_use]
pub fn shared_descriptor_root_module(
    fds_bytes: &[u8],
    embedding: FdsEmbedding<'_>,
    gate: Option<&str>,
) -> String {
    let source = match embedding {
        FdsEmbedding::Inline => reflect::FdsSource::Inline(fds_bytes),
        FdsEmbedding::Sidecar {
            file_name,
            mode: IncludeMode::Relative(prefix),
        } => {
            let path = format!("{prefix}{file_name}");
            reflect::FdsSource::IncludeBytes(quote::quote! { #path })
        }
        FdsEmbedding::Sidecar {
            file_name,
            mode: IncludeMode::OutDir,
        } => {
            let slash_name = format!("/{file_name}");
            reflect::FdsSource::IncludeBytes(
                quote::quote! { concat!(env!("OUT_DIR"), #slash_name) },
            )
        }
    };
    let tokens = feature_gates::cfg_block(reflect::shared_root_module(source), gate);
    let file = syn::parse2::<syn::File>(tokens)
        .expect("shared descriptor root module must parse as a Rust file");
    prettyplease::unparse(&file)
}

/// Validate [`CodeGenConfig::shared_descriptor_pool_root`]'s string form: an
/// absolute (`::`-prefixed) or `crate`-relative path of plain `::`-separated
/// identifiers, no generic or parenthesized arguments.
///
/// `syn::Path` alone isn't strict enough here — it happily parses
/// `::k::__buffa_fds<T>`, which would then splice into uncompilable
/// generated code (`pub use ::k::__buffa_fds<T>::FILE_DESCRIPTOR_SET_BYTES;`),
/// exactly the downstream failure this check exists to prevent. A leading
/// `::` or `crate` is required because the same string is spliced verbatim
/// at every package depth in the tree — a plain relative path could only
/// ever be correct from one depth.
fn validate_shared_root_path(path: &str) -> Result<(), CodeGenError> {
    let is_absolute = path.starts_with("::");
    let is_crate_relative = path == "crate" || path.starts_with("crate::");
    if !is_absolute && !is_crate_relative {
        return Err(CodeGenError::Other(format!(
            "shared_descriptor_pool_root must be an absolute (`::`-prefixed) or \
             crate-relative (`crate`-prefixed) path — the same value is spliced \
             verbatim at every package depth, so a plain relative path would only \
             be correct from one depth: {path:?}"
        )));
    }
    let rest = path.strip_prefix("::").unwrap_or(path);
    if rest.is_empty() {
        return Err(CodeGenError::Other(format!(
            "shared_descriptor_pool_root has no path after the `::` prefix: {path:?}"
        )));
    }
    for (i, segment) in rest.split("::").enumerate() {
        let mut chars = segment.chars();
        let is_ident = chars
            .next()
            .is_some_and(|c| c.is_ascii_alphabetic() || c == '_')
            && chars.all(|c| c.is_ascii_alphanumeric() || c == '_');
        if !is_ident {
            return Err(CodeGenError::Other(format!(
                "shared_descriptor_pool_root segment {segment:?} is not a plain \
                 identifier (no generic or parenthesized arguments, ASCII only) — \
                 the value is spliced verbatim into generated code: {path:?}"
            )));
        }
        // `_`, `self`, `Self` and `super` are identifiers to the scan above but
        // not usable path segments; `crate` is only legal first.
        let is_path_keyword =
            matches!(segment, "_" | "self" | "Self" | "super") || (i > 0 && segment == "crate");
        if is_path_keyword {
            return Err(CodeGenError::Other(format!(
                "shared_descriptor_pool_root segment {segment:?} is a path keyword \
                 and cannot be spliced into generated code: {path:?}"
            )));
        }
    }
    Ok(())
}

/// Reject user names that would collide with the shared descriptor root module
/// (`reflect::SHARED_ROOT_MOD`) placed at the module-tree root in shared-pool
/// mode. Mirrors how [`SENTINEL_MOD`](context::SENTINEL_MOD)/`__buffa` is
/// reserved: any package segment equal to the reserved name, plus a
/// root-package (unnamed) message whose *module* name (snake_cased, matching
/// `validate_file`) or a file-level enum name equals it.
///
/// Only files actually being generated are checked — an import-only package
/// named `__buffa_fds` emits no module, so it must not trip this guard.
fn validate_shared_root_name(
    files: &[FileDescriptorProto],
    files_to_generate: &[String],
) -> Result<(), CodeGenError> {
    use std::collections::HashSet;

    let reserved = reflect::SHARED_ROOT_MOD;
    let generated: HashSet<&str> = files_to_generate.iter().map(String::as_str).collect();
    let reserved_err = |location: String| CodeGenError::ReservedModuleName {
        name: reserved.to_string(),
        location,
    };

    for file in files {
        if !generated.contains(file.name.as_deref().unwrap_or("")) {
            continue;
        }
        let package = file.package.as_deref().unwrap_or("");
        // Every package segment becomes a `pub mod <seg>`; the reserved name in
        // any of them collides with the tree-root `__buffa_fds`.
        if package.split('.').any(|seg| seg == reserved) {
            return Err(reserved_err(format!(
                "package '{package}' (reserved by shared_descriptor_pool)"
            )));
        }
        // Only the unnamed root package puts items beside `__buffa_fds`; named
        // packages nest theirs under `pub mod <segment>`. A message's
        // nested-types module is snake_cased (like `validate_file`), so compare
        // against that; file-level enums are emitted verbatim.
        if package.is_empty() {
            for m in &file.message_type {
                let name = m.name.as_deref().unwrap_or("");
                if crate::oneof::to_snake_case(name) == reserved {
                    return Err(reserved_err(format!(
                        "message '{name}' (its module `{reserved}` is reserved by \
                         shared_descriptor_pool)"
                    )));
                }
            }
            for e in &file.enum_type {
                if e.name.as_deref() == Some(reserved) {
                    return Err(reserved_err(format!(
                        "enum '{reserved}' (reserved by shared_descriptor_pool)"
                    )));
                }
            }
        }
    }
    Ok(())
}

/// Rejects two sibling types that [`idents::local_type_name`] maps to one
/// Rust name. An empty name is skipped; [`required_type_name`] reports it.
fn check_type_names<'a>(
    scope: &str,
    names: impl Iterator<Item = &'a str>,
    type_name_prefix: &str,
) -> Result<(), CodeGenError> {
    let mut seen: std::collections::HashMap<String, &str> = std::collections::HashMap::new();
    for name in names.filter(|name| !name.is_empty()) {
        let rust_name = idents::local_type_name(type_name_prefix, name);
        if let Some(first) = seen.insert(rust_name.clone(), name) {
            return Err(CodeGenError::TypeNameConflict {
                scope: scope.to_string(),
                first_type: first.to_string(),
                second_type: name.to_string(),
                rust_name,
            });
        }
    }
    Ok(())
}

/// Returns [`CodeGenError::DuplicateFieldNumber`] for the first message of
/// `messages`, or nested in one, that has two fields with one number.
/// `scope` is the full name of what contains `messages`: the package, or the
/// enclosing message.
///
/// A oneof member is a field of the message, so it is compared with every
/// other field. An extension declared in the message is a field of its
/// extendee, so it is not compared with the message's own fields, and an
/// extension's number is not checked against its extendee here.
fn check_field_numbers(
    messages: &[crate::generated::descriptor::DescriptorProto],
    scope: &str,
) -> Result<(), CodeGenError> {
    for msg in messages {
        let name = msg.name.as_deref().unwrap_or("");
        let fqn = if scope.is_empty() {
            name.to_string()
        } else {
            format!("{scope}.{name}")
        };
        let mut seen: std::collections::HashMap<i32, &str> = std::collections::HashMap::new();
        for field in &msg.field {
            let Some(number) = field.number else {
                continue;
            };
            let field_name = field.name.as_deref().unwrap_or("");
            if let Some(first) = seen.insert(number, field_name) {
                return Err(CodeGenError::DuplicateFieldNumber {
                    message_name: fqn,
                    first_field: first.to_string(),
                    second_field: field_name.to_string(),
                    number,
                });
            }
        }
        check_field_numbers(&msg.nested_type, &fqn)?;
    }
    Ok(())
}

/// Validate one input descriptor before generating code for it.
///
/// Checks, in one walk of the message tree:
///
/// - **Required type names**: every message and enum has a non-empty name.
/// - **Reserved field names**: no field starts with `__buffa_` (would clash
///   with generated `__buffa_unknown_fields` / `__buffa_cached_size`).
/// - **Module-name conflicts**: no two sibling messages snake_case to the
///   same module name (e.g. `HTTPRequest` vs `HttpRequest`).
/// - **Type-name conflicts**: no two messages or enums nested in one message
///   escape to the same Rust type name (e.g. `bool` vs `bool_`). The caller
///   checks the package-level types, which span files.
/// - **Reserved sentinel**: no package segment, message-module name, or
///   file-level enum name equals [`SENTINEL_MOD`](context::SENTINEL_MOD).
///   Ancillary types live under `pkg::__buffa::…`; a proto element
///   emitting an item named `__buffa` at package root would produce
///   E0428 against `pub mod __buffa`. This is the only name buffa
///   reserves in user namespace.
fn validate_file(file: &FileDescriptorProto, type_name_prefix: &str) -> Result<(), CodeGenError> {
    use std::collections::HashMap;

    let sentinel = context::SENTINEL_MOD;
    let package = file.package.as_deref().unwrap_or("");
    if package.split('.').any(|seg| seg == sentinel) {
        return Err(CodeGenError::ReservedModuleName {
            name: sentinel.to_string(),
            location: format!("package '{package}'"),
        });
    }
    // File-level enums emit `pub enum <name>` at package root with the
    // proto name preserved verbatim (no PascalCase normalization), so a
    // proto `enum __buffa` would land beside `pub mod __buffa`. Nested
    // enums live inside their owner message's module and cannot collide
    // with the package-root sentinel, so only file-level is checked.
    for enum_type in &file.enum_type {
        let name = required_type_name(enum_type.name.as_deref(), "enum.name")?;
        if name == sentinel {
            return Err(CodeGenError::ReservedModuleName {
                name: sentinel.to_string(),
                location: format!("enum '{package}.{name}'"),
            });
        }
    }

    fn walk(
        messages: &[crate::generated::descriptor::DescriptorProto],
        scope: &str,
        sentinel: &str,
        type_name_prefix: &str,
    ) -> Result<(), CodeGenError> {
        // snake_case module name → original proto name (for conflict diag).
        let mut seen: HashMap<String, &str> = HashMap::new();

        for msg in messages {
            let name = required_type_name(msg.name.as_deref(), "message.name")?;
            let fqn = if scope.is_empty() {
                name.to_string()
            } else {
                format!("{scope}.{name}")
            };

            for enum_type in &msg.enum_type {
                required_type_name(enum_type.name.as_deref(), "enum.name")?;
            }
            check_type_names(
                &fqn,
                msg.nested_type
                    .iter()
                    .filter_map(|m| m.name.as_deref())
                    .chain(msg.enum_type.iter().filter_map(|e| e.name.as_deref())),
                type_name_prefix,
            )?;

            for field in &msg.field {
                if let Some(fname) = &field.name {
                    if fname.starts_with("__buffa_") {
                        return Err(CodeGenError::ReservedFieldName {
                            message_name: fqn,
                            field_name: fname.clone(),
                        });
                    }
                }
            }

            let module_name = crate::oneof::to_snake_case(name);
            if module_name == sentinel {
                return Err(CodeGenError::ReservedModuleName {
                    name: sentinel.to_string(),
                    location: format!("message '{fqn}'"),
                });
            }
            if let Some(existing) = seen.get(&module_name) {
                return Err(CodeGenError::ModuleNameConflict {
                    scope: scope.to_string(),
                    name_a: existing.to_string(),
                    name_b: name.to_string(),
                    module_name,
                });
            }
            seen.insert(module_name, name);

            walk(&msg.nested_type, &fqn, sentinel, type_name_prefix)?;
        }
        Ok(())
    }

    walk(&file.message_type, package, sentinel, type_name_prefix)
}

/// Returns the name of a message or enum descriptor, or
/// [`CodeGenError::MissingField`]`(field)` if the name is absent or empty.
///
/// An empty name cannot be a Rust identifier, so it is rejected like an
/// absent one.
fn required_type_name<'a>(
    name: Option<&'a str>,
    field: &'static str,
) -> Result<&'a str, CodeGenError> {
    name.filter(|name| !name.is_empty())
        .ok_or(CodeGenError::MissingField(field))
}

/// Per-proto content streams plus the file stem, ready to be formatted.
struct ProtoContent {
    stem: String,
    owned: TokenStream,
    view: TokenStream,
    lazy_view: TokenStream,
    oneof: TokenStream,
    view_oneof: TokenStream,
    ext: TokenStream,
    /// Candidate `pub use` re-exports targeting the package root (top-level
    /// view structs, file-level extension consts). Filtered against the
    /// package-wide root namespace in [`generate_package_mod`] — the package
    /// can span multiple `.proto` files, so collisions are only knowable at
    /// the stitcher level.
    root_reexports: Vec<message::ReexportCandidate>,
}

/// Generate the per-`.proto` content token streams for one input file.
/// Each ancillary kind that has no content yields an empty stream and
/// is dropped at the file-emission stage.
fn generate_proto_content(
    ctx: &context::CodeGenContext,
    current_package: &str,
    file: &FileDescriptorProto,
    reg: &mut message::RegistryPaths,
) -> Result<ProtoContent, CodeGenError> {
    use crate::idents::make_field_ident;
    use crate::message::MessageOutput;

    validate_file(file, &ctx.config.type_name_prefix)?;

    let resolver = imports::ImportResolver::new();
    let features = crate::features::for_file(file);

    let mut owned = TokenStream::new();
    let mut view = TokenStream::new();
    let mut lazy_view = TokenStream::new();
    let mut oneof = TokenStream::new();
    let mut view_oneof = TokenStream::new();
    let mut ext = TokenStream::new();
    let mut root_reexports: Vec<message::ReexportCandidate> = Vec::new();
    let sentinel = make_field_ident(context::SENTINEL_MOD);

    for enum_type in &file.enum_type {
        let enum_proto_name = enum_type.name.as_deref().unwrap_or("");
        let enum_rust_name = ctx.config.prefixed_type_name(enum_proto_name);
        let enum_fqn = if current_package.is_empty() {
            enum_proto_name.to_string()
        } else {
            format!("{}.{}", current_package, enum_proto_name)
        };
        owned.extend(enumeration::generate_enum(
            ctx,
            enum_type,
            &enum_rust_name,
            &enum_fqn,
            &features,
            &resolver,
        )?);
    }

    for message_type in &file.message_type {
        let top_level_name = message_type.name.as_deref().unwrap_or("");
        let rust_name = ctx.config.prefixed_type_name(top_level_name);
        let proto_fqn = if current_package.is_empty() {
            top_level_name.to_string()
        } else {
            format!("{}.{}", current_package, top_level_name)
        };
        let MessageOutput {
            owned_top,
            owned_mod,
            oneof_tree: msg_oneof,
            view_tree: msg_view,
            lazy_view_tree: msg_lazy_view,
            view_oneof_tree: msg_view_oneof,
            reg: msg_reg,
        } = message::generate_message(
            ctx,
            message_type,
            current_package,
            &rust_name,
            &proto_fqn,
            &crate::features::message_scope_features(&features, message_type, true),
            &resolver,
        )?;
        owned.extend(owned_top);
        let mod_name = ctx.nested_module_name(current_package, top_level_name);
        let mod_ident = make_field_ident(&mod_name);
        let mod_doc = message::module_rename_doc(top_level_name, &mod_name);
        for p in msg_reg.json_ext {
            reg.json_ext.push(quote! { #mod_ident :: #p });
        }
        for p in msg_reg.text_ext {
            reg.text_ext.push(quote! { #mod_ident :: #p });
        }
        reg.json_any.extend(msg_reg.json_any);
        reg.text_any.extend(msg_reg.text_any);

        if !owned_mod.is_empty() {
            owned.extend(quote! {
                #mod_doc
                pub mod #mod_ident {
                    #[allow(unused_imports)]
                    use super::*;
                    #owned_mod
                }
            });
        }
        oneof.extend(msg_oneof);
        view.extend(msg_view);
        lazy_view.extend(msg_lazy_view);
        view_oneof.extend(msg_view_oneof);

        // Top-level message view → re-export at package root. The leading
        // `self::` is load-bearing: when consumers nest packages with
        // `pub mod a { use super::*; pub mod a_b { use super::*; … } }`
        // (`buffa-build`'s `_include.rs` does this), a parent package's
        // `__buffa` is in scope via the glob, and Rust's import-resolution
        // pass treats a glob-imported name as ambiguous against a
        // **macro-expanded** local one (the `pub mod __buffa` block arrives
        // via `include!()`), even though a non-macro local definition would
        // shadow the glob — see rustc E0659. `self::` resolves it
        // deterministically. `#[doc(inline)]` makes rustdoc render the type's
        // full page at the natural path instead of a "Re-export of …" stub.
        if ctx.config.generate_views {
            let view_ident = format_ident!("{rust_name}View");
            root_reexports.push(message::ReexportCandidate {
                name: view_ident.to_string(),
                tokens: feature_gates::cfg_block(
                    quote! {
                        #[doc(inline)]
                        pub use self :: #sentinel :: view :: #view_ident;
                    },
                    ctx.config.feature_gates().views,
                ),
            });
            // The owned-view wrapper gets the same natural-path treatment as
            // the view struct, so `pkg::FooOwnedView` works out of the box.
            let owned_view_ident = format_ident!("{rust_name}OwnedView");
            root_reexports.push(message::ReexportCandidate {
                name: owned_view_ident.to_string(),
                tokens: feature_gates::cfg_block(
                    quote! {
                        #[doc(inline)]
                        pub use self :: #sentinel :: view :: #owned_view_ident;
                    },
                    ctx.config.feature_gates().views,
                ),
            });
            if ctx.config.lazy_views {
                let lazy_ident = format_ident!("{rust_name}LazyView");
                root_reexports.push(message::ReexportCandidate {
                    name: lazy_ident.to_string(),
                    tokens: feature_gates::cfg_block(
                        quote! {
                            #[doc(inline)]
                            pub use self :: #sentinel :: lazy_view :: #lazy_ident;
                        },
                        ctx.config.feature_gates().views,
                    ),
                });
            }
        }
    }

    // File-level `extend` declarations → `__buffa::ext::` (depth 2).
    let (file_ext_tokens, file_ext_json, file_ext_text) = extension::generate_extensions(
        ctx,
        &file.extension,
        current_package,
        2,
        &features,
        current_package,
    )?;
    ext.extend(file_ext_tokens);
    for id in file_ext_json {
        reg.json_ext.push(quote! { #sentinel :: ext :: #id });
    }
    for id in file_ext_text {
        reg.text_ext.push(quote! { #sentinel :: ext :: #id });
    }
    // File-level extension consts → re-export at package root. `self::` and
    // `#[doc(inline)]` for the same reasons as the view re-exports above.
    for ext_field in &file.extension {
        let const_ident = extension::extension_const_ident(ext_field.name.as_deref().unwrap_or(""));
        root_reexports.push(message::ReexportCandidate {
            name: const_ident.to_string(),
            tokens: quote! {
                #[doc(inline)]
                pub use self :: #sentinel :: ext :: #const_ident;
            },
        });
    }

    Ok(ProtoContent {
        stem: proto_path_to_stem(file.name.as_deref().unwrap_or("")),
        owned,
        view,
        lazy_view,
        oneof,
        view_oneof,
        ext,
        root_reexports,
    })
}

/// Per-section token streams for one package, ready for the stitcher.
///
/// In per-file mode each section holds `include!("<stem>...rs")` calls; in
/// `file_per_package` mode each holds the actual generated items.
#[derive(Default)]
struct PackageSections {
    owned: Vec<TokenStream>,
    view: Vec<TokenStream>,
    lazy_view: Vec<TokenStream>,
    oneof: Vec<TokenStream>,
    view_oneof: Vec<TokenStream>,
    ext: Vec<TokenStream>,
}

impl PackageSections {
    /// Append one proto file's generated items in-line.
    ///
    /// Empty streams are skipped so each section's emptiness reflects
    /// "the package has no content of this kind" — symmetric with the
    /// per-file branch that filters at file-emission time.
    fn push_inline(&mut self, pc: ProtoContent) {
        let push_if_nonempty = |dst: &mut Vec<TokenStream>, ts: TokenStream| {
            if !ts.is_empty() {
                dst.push(ts);
            }
        };
        push_if_nonempty(&mut self.owned, pc.owned);
        push_if_nonempty(&mut self.view, pc.view);
        push_if_nonempty(&mut self.lazy_view, pc.lazy_view);
        push_if_nonempty(&mut self.oneof, pc.oneof);
        push_if_nonempty(&mut self.view_oneof, pc.view_oneof);
        push_if_nonempty(&mut self.ext, pc.ext);
    }
}

/// Generate all output files for one proto package: up to five content
/// files per `.proto` (empty ancillary kinds are skipped) plus one
/// `<pkg>.mod.rs` stitcher, or a single `<pkg>.rs` when
/// [`CodeGenConfig::file_per_package`] is set.
fn generate_package(
    ctx: &context::CodeGenContext,
    current_package: &str,
    files: &[&FileDescriptorProto],
    fds_bytes: &[u8],
    // Deduped `ProtoElemJson` / `ReflectElement` impls for custom repeated
    // element types, collected generation-wide and emitted into exactly one
    // package's `__buffa` module (empty for every package but the first).
    custom_elem_impls: &TokenStream,
    output_names: &mut OutputNames,
    out: &mut Vec<GeneratedFile>,
) -> Result<(), CodeGenError> {
    // Registry paths are package-root-relative; `register_types` lives at
    // `__buffa::register_types` (one level deep), so each path gets a
    // single `super::` prefix when emitted into the fn body.
    let mut reg = message::RegistryPaths::default();
    let mut root_reexports: Vec<message::ReexportCandidate> = Vec::new();

    // Package-level types share one module whichever file declares them.
    check_type_names(
        current_package,
        files.iter().flat_map(|file| {
            file.message_type
                .iter()
                .filter_map(|m| m.name.as_deref())
                .chain(file.enum_type.iter().filter_map(|e| e.name.as_deref()))
        }),
        &ctx.config.type_name_prefix,
    )?;

    // Idiomatic imports: dry-run the package's generation once with the
    // registry collecting, so the set of package-root path references is
    // known — by construction, exactly the set the real pass will emit —
    // then assign short names and generate for real with the registry
    // resolving. Generation is deterministic, so the two passes see the
    // same references; assignment sorts the collected set, so the result
    // is also stable under `.proto` file reordering. The dry run's other
    // outputs (tokens, registry paths, re-export candidates, warnings) are
    // discarded; only the candidate *names* feed the occupied set, since a
    // surviving re-export occupies a root name a `use` must not claim.
    if ctx.config.idiomatic_imports && ctx.config.file_per_package {
        ctx.imports_begin_collecting();
        let warn_mark = ctx.warnings_len();
        let mut scratch_reg = message::RegistryPaths::default();
        let mut occupied = root_occupied_names(ctx, files);
        for file in files {
            let pc = generate_proto_content(ctx, current_package, file, &mut scratch_reg)?;
            occupied.extend(pc.root_reexports.into_iter().map(|c| c.name));
        }
        ctx.truncate_warnings(warn_mark);
        occupied.insert("register_types".to_string());
        // The reflect re-export names (`descriptor_pool`,
        // `FILE_DESCRIPTOR_SET_BYTES`) are reserved inside
        // `root_occupied_names` itself.
        let collected = ctx.imports_take_collected();
        ctx.imports_set_resolving(imports::RootImports::assign(&collected, &occupied));
    }

    let sections = if ctx.config.file_per_package {
        let mut sections = PackageSections::default();
        for file in files {
            let mut pc = generate_proto_content(ctx, current_package, file, &mut reg)?;
            root_reexports.append(&mut pc.root_reexports);
            sections.push_inline(pc);
        }
        sections
    } else {
        let mut sections = PackageSections::default();
        for file in files {
            let mut pc = generate_proto_content(ctx, current_package, file, &mut reg)?;
            root_reexports.append(&mut pc.root_reexports);
            let source = file.name.as_deref().unwrap_or("");
            let stem = pc.stem;

            // Empty ancillary token streams are skipped — neither the
            // content file nor the stitcher's `include!` is emitted.
            let emit = |suffix: &str,
                        kind: GeneratedFileKind,
                        tokens: TokenStream,
                        section: &mut Vec<TokenStream>,
                        output_names: &mut OutputNames,
                        out: &mut Vec<GeneratedFile>|
             -> Result<(), CodeGenError> {
                if tokens.is_empty() {
                    return Ok(());
                }
                let name = format!("{stem}{suffix}.rs");
                output_names.claim(&name, source.to_owned())?;
                section.push(quote! { include!(#name); });
                out.push(GeneratedFile {
                    name,
                    package: current_package.to_string(),
                    kind,
                    content: format_tokens(tokens, source)?,
                });
                Ok(())
            };
            emit(
                "",
                GeneratedFileKind::Owned,
                pc.owned,
                &mut sections.owned,
                output_names,
                out,
            )?;
            emit(
                ".__view",
                GeneratedFileKind::View,
                pc.view,
                &mut sections.view,
                output_names,
                out,
            )?;
            emit(
                ".__lazy_view",
                GeneratedFileKind::LazyView,
                pc.lazy_view,
                &mut sections.lazy_view,
                output_names,
                out,
            )?;
            emit(
                ".__oneof",
                GeneratedFileKind::Oneof,
                pc.oneof,
                &mut sections.oneof,
                output_names,
                out,
            )?;
            emit(
                ".__view_oneof",
                GeneratedFileKind::ViewOneof,
                pc.view_oneof,
                &mut sections.view_oneof,
                output_names,
                out,
            )?;
            emit(
                ".__ext",
                GeneratedFileKind::Ext,
                pc.ext,
                &mut sections.ext,
                output_names,
                out,
            )?;
        }
        sections
    };

    let reexport_block = surviving_root_reexports(ctx, files, &reg, root_reexports);

    let mod_name = if ctx.config.file_per_package {
        package_to_filename(current_package)
    } else {
        package_to_mod_filename(current_package)
    };
    let mod_source = if current_package.is_empty() {
        "the unnamed package".to_owned()
    } else {
        format!("package {current_package}")
    };
    output_names.claim(&mod_name, mod_source)?;
    out.push(GeneratedFile {
        name: mod_name,
        package: current_package.to_string(),
        kind: GeneratedFileKind::PackageMod,
        content: generate_package_mod(
            ctx,
            current_package,
            &sections,
            &reg,
            &reexport_block,
            fds_bytes,
            custom_elem_impls,
        )?,
    });

    // Drop the import registry so its bindings can't leak into the next
    // package's generation.
    ctx.imports_reset();

    Ok(())
}

/// Names occupied at a package's root by real items: top-level messages,
/// enums, message nested-types modules, and the `__buffa` sentinel itself.
///
/// The package root is shared across every `.proto` file in the package, so
/// the set is built from *all* of them. File-level extension consts live in
/// `__buffa::ext::`, not at the root, so they are re-export *candidates*
/// (added by `generate_proto_content`) rather than occupants. Used both to
/// filter root re-exports and as the base reserved set for
/// `idiomatic_imports` short-name assignment.
fn root_occupied_names(
    ctx: &context::CodeGenContext,
    files: &[&FileDescriptorProto],
) -> std::collections::BTreeSet<String> {
    let mut occupied = std::collections::BTreeSet::new();
    occupied.insert(context::SENTINEL_MOD.to_string());
    for file in files {
        let package = file.package.as_deref().unwrap_or("");
        for m in &file.message_type {
            let name = m.name.as_deref().unwrap_or("");
            // The declared struct name carries the configured prefix; the
            // module name stays proto-derived.
            occupied.insert(ctx.config.prefixed_type_name(name));
            occupied.insert(ctx.nested_module_name(package, name));
        }
        for e in &file.enum_type {
            occupied.insert(
                ctx.config
                    .prefixed_type_name(e.name.as_deref().unwrap_or("")),
            );
        }
    }
    // The reflect surface is re-exported at the package root directly by
    // `generate_package_mod` (not via a `ReexportCandidate`), so candidates
    // that could share its names — an extension const named
    // `file_descriptor_set_bytes` becomes `FILE_DESCRIPTOR_SET_BYTES` —
    // must be filtered against it here or the two `pub use`s collide
    // (E0252) in the generated package root.
    if ctx.config.generate_reflection {
        occupied.insert("descriptor_pool".to_string());
        occupied.insert("FILE_DESCRIPTOR_SET_BYTES".to_string());
    }
    occupied
}

/// Filter the candidate package-root re-exports against the package's
/// existing root namespace and against each other, returning the surviving
/// `pub use` lines.
///
/// The package root is shared across every `.proto` file in the package, so
/// the occupied-name set must be built from *all* of them — a top-level
/// message named `FooView` declared in `a.proto` would shadow `Foo`'s view
/// re-export from `b.proto`.
fn surviving_root_reexports(
    ctx: &context::CodeGenContext,
    files: &[&FileDescriptorProto],
    reg: &message::RegistryPaths,
    mut candidates: Vec<message::ReexportCandidate>,
) -> TokenStream {
    use crate::idents::make_field_ident;

    let occupied = root_occupied_names(ctx, files);

    // `register_types`, when emitted, lives at `__buffa::register_types`.
    // `self::` and `#[doc(inline)]` for the same reasons as the view
    // re-exports above. Same `any(json, text)` gate as the fn itself.
    if ctx.config.emit_register_fn && !reg.is_empty() {
        let sentinel = make_field_ident(context::SENTINEL_MOD);
        let json_or_text = ctx.config.feature_gates().json_or_text();
        candidates.push(message::ReexportCandidate {
            name: "register_types".to_string(),
            tokens: feature_gates::cfg_block_any(
                quote! {
                    #[doc(inline)]
                    pub use self :: #sentinel :: register_types;
                },
                &json_or_text,
            ),
        });
    }

    message::emit_surviving_reexports(candidates, &occupied)
}

/// Render the per-package stitcher: owned items at root plus the
/// `__buffa::{view,oneof,ext,...}` module wrappers, followed by the
/// surviving package-root `pub use` re-exports.
fn generate_package_mod(
    ctx: &context::CodeGenContext,
    current_package: &str,
    sections: &PackageSections,
    reg: &message::RegistryPaths,
    root_reexports: &TokenStream,
    fds_bytes: &[u8],
    custom_elem_impls: &TokenStream,
) -> Result<String, CodeGenError> {
    use crate::idents::make_field_ident;

    let owned = &sections.owned;
    let view = &sections.view;
    let lazy_view = &sections.lazy_view;
    let view_oneof = &sections.view_oneof;
    let oneof = &sections.oneof;
    let ext = &sections.ext;

    // Each ancillary module is emitted only when its section has
    // content. The natural-path re-exports outside `__buffa` target
    // these modules — they are emitted only when their target items
    // exist, so the conditions align and re-exports never reference
    // a missing module.
    let view_oneof_mod = if !view_oneof.is_empty() {
        quote! {
            pub mod oneof {
                #[allow(unused_imports)]
                use super::*;
                #(#view_oneof)*
            }
        }
    } else {
        TokenStream::new()
    };

    // `view_oneof` is only populated for messages that have oneofs, and
    // every message also contributes to `view`, so `!view.is_empty()` is
    // sufficient — `view_oneof` non-empty implies `view` non-empty.
    debug_assert!(view_oneof.is_empty() || !view.is_empty());
    let view_mod = if ctx.config.generate_views && !view.is_empty() {
        feature_gates::cfg_block(
            quote! {
                pub mod view {
                    #[allow(unused_imports)]
                    use super::*;
                    #(#view)*
                    #view_oneof_mod
                }
            },
            ctx.config.feature_gates().views,
        )
    } else {
        TokenStream::new()
    };

    // `lazy_view` is only populated when `view` is (the lazy family is
    // generated per-message alongside the eager view).
    debug_assert!(lazy_view.is_empty() || !view.is_empty());
    let lazy_view_mod = if !lazy_view.is_empty() {
        feature_gates::cfg_block(
            quote! {
                pub mod lazy_view {
                    #[allow(unused_imports)]
                    use super::*;
                    #(#lazy_view)*
                }
            },
            ctx.config.feature_gates().views,
        )
    } else {
        TokenStream::new()
    };

    let oneof_mod = if !oneof.is_empty() {
        quote! {
            pub mod oneof {
                #[allow(unused_imports)]
                use super::*;
                #(#oneof)*
            }
        }
    } else {
        TokenStream::new()
    };

    let ext_mod = if !ext.is_empty() {
        quote! {
            pub mod ext {
                #[allow(unused_imports)]
                use super::*;
                #(#ext)*
            }
        }
    } else {
        TokenStream::new()
    };

    let register_fn = if ctx.config.emit_register_fn && !reg.is_empty() {
        let gates = ctx.config.feature_gates();
        // When the gated consts (`__*_JSON_ANY` / `__*_TEXT_ANY`) are
        // `#[cfg(feature = "...")]`, each registration statement that
        // references them gets the same gate. `#[cfg]` on a statement is
        // allowed; the call disappears with the const.
        let json_regs = reg
            .json_any
            .iter()
            .map(|p| {
                feature_gates::cfg_block(quote! { reg.register_json_any(super::#p); }, gates.json)
            })
            .chain(reg.json_ext.iter().map(|p| {
                feature_gates::cfg_block(quote! { reg.register_json_ext(super::#p); }, gates.json)
            }));
        let text_regs = reg
            .text_any
            .iter()
            .map(|p| {
                feature_gates::cfg_block(quote! { reg.register_text_any(super::#p); }, gates.text)
            })
            .chain(reg.text_ext.iter().map(|p| {
                feature_gates::cfg_block(quote! { reg.register_text_ext(super::#p); }, gates.text)
            }));
        // When gating, a feature subset may leave one bucket of statements
        // cfg'd out while the other survives — `reg` is still used. But if
        // `register_types` itself is gated on `any(json, text)` (below),
        // the only reachable bodies have at least one statement, so `reg`
        // can't be unused. Keep `#[allow(unused_variables)]` defensively
        // anyway: it's harmless, and the alternative — proving the
        // invariant holds across future statement-shape changes — is
        // brittle.
        let allow_unused = if ctx.config.gate_impls_on_crate_features {
            quote! { #[allow(unused_variables)] }
        } else {
            quote! {}
        };
        // The fn is useless without at least one of the gated modes that
        // populate it — and `::buffa::type_registry::TypeRegistry` may
        // become feature-gated in the runtime in a future release. Gate the
        // fn on `any(...)` of whichever modes are active so it disappears
        // alongside the last entry.
        feature_gates::cfg_block_any(
            quote! {
                /// Register this package's `Any` type entries and extension entries.
                #allow_unused
                pub fn register_types(reg: &mut ::buffa::type_registry::TypeRegistry) {
                    #(#json_regs)*
                    #(#text_regs)*
                }
            },
            &gates.json_or_text(),
        )
    } else {
        TokenStream::new()
    };

    // Reflection: embed the FileDescriptorSet bytes and a lazy pool
    // accessor so per-message `Reflectable` impls have a descriptor pool to
    // resolve against. Lives inside `__buffa` so the impls can reach it via
    // a relative `__buffa::reflect::descriptor_pool()` path. Package-root
    // `pub use`s re-export `descriptor_pool` and `FILE_DESCRIPTOR_SET_BYTES`
    // so consumers don't have to route through the reserved `__buffa`
    // sentinel.
    let (reflect_mod, reflect_reexport) = if ctx.config.generate_reflection {
        let gate = ctx.config.feature_gates().reflect;
        // Shared mode: delegate to the single root `__buffa_fds` module
        // instead of embedding this package's own byte copy.
        let pool_module = if ctx.config.shared_descriptor_pool {
            reflect::reflect_pool_module_shared(
                current_package,
                ctx.config.shared_descriptor_pool_root.as_deref(),
            )
        } else {
            reflect::reflect_pool_module(fds_bytes)
        };
        (
            feature_gates::cfg_block(pool_module, gate),
            reflect::reflect_reexports(&quote! { __buffa }, gate),
        )
    } else {
        (TokenStream::new(), TokenStream::new())
    };

    let sentinel = make_field_ident(context::SENTINEL_MOD);
    // The whole `pub mod __buffa { ... }` wrapper is itself omitted
    // when none of its inner modules or `register_types` exist.
    let buffa_mod = if view_mod.is_empty()
        && lazy_view_mod.is_empty()
        && oneof_mod.is_empty()
        && ext_mod.is_empty()
        && register_fn.is_empty()
        && reflect_mod.is_empty()
        && custom_elem_impls.is_empty()
    {
        TokenStream::new()
    } else {
        let allow = allow_lints_attr();
        quote! {
            #allow
            pub mod #sentinel {
                #[allow(unused_imports)]
                use super::*;
                #view_mod
                #lazy_view_mod
                #oneof_mod
                #ext_mod
                #register_fn
                #reflect_mod
                #custom_elem_impls
            }
        }
    };

    // Idiomatic imports: the `use` block backing the package-root short
    // names (empty unless the registry is in its resolution phase). Only
    // ever non-empty in file_per_package mode, where this output is the
    // whole single-writer package file.
    //
    // Load-bearing lint coupling: impl bodies still write fully-qualified
    // paths (e.g. `::buffa::MessageField<…>`) for types this block also
    // imports — exactly what `unused_qualifications` flags. That lint is
    // suppressed by the `ALLOW_LINTS` attr the module-tree wrapper carries,
    // so generated files must keep their `#[allow]` wrapper when consumed.
    let use_block = ctx.imports_use_block();

    let tokens = quote! {
        #use_block
        #(#owned)*
        #buffa_mod
        #reflect_reexport
        #root_reexports
    };

    format_tokens(tokens, "")
}

/// Format a token stream into a generated-file string with the standard
/// header comment.
fn format_tokens(tokens: TokenStream, source: &str) -> Result<String, CodeGenError> {
    let syntax_tree =
        syn::parse2::<syn::File>(tokens).map_err(|e| CodeGenError::InvalidSyntax(e.to_string()))?;
    let formatted = prettyplease::unparse(&syntax_tree);
    let source_line = if source.is_empty() {
        String::new()
    } else {
        format!("// source: {source}\n")
    };
    Ok(format!("{GENERATED_HEADER}{source_line}\n{formatted}"))
}

/// Convert a proto package name to its `.mod.rs` stitcher filename.
///
/// e.g., `"google.protobuf"` → `"google.protobuf.mod.rs"`. The unnamed
/// package uses the [`SENTINEL_MOD`](context::SENTINEL_MOD) name as its
/// filename stem — `package __buffa;` is already rejected by
/// `validate_file`, so the unnamed-package stitcher cannot
/// collide with any real package's.
pub fn package_to_mod_filename(package: &str) -> String {
    if package.is_empty() {
        format!("{}.mod.rs", context::SENTINEL_MOD)
    } else {
        format!("{package}.mod.rs")
    }
}

/// Returns `true` if `package` is covered by any entry in `excludes`.
///
/// Intended for packages that `include_imports` pulls into
/// `file_to_generate` but that a caller does not want emitted — typically
/// option-only imports such as `buf.validate` or `gnostic.openapi.v3`, whose
/// types are referenced only from custom options and never appear as message
/// fields.
///
/// An exclusion matches a package exactly, or as a dotted-path prefix on a
/// component boundary: `"buf.validate"` covers `buf.validate` and
/// `buf.validate.foo`, but not `buf.validatex`. Entries are proto package
/// paths without a leading dot (`buf.validate`, not `.buf.validate`); an
/// empty entry matches only the unnamed package.
///
/// `generate_with_diagnostics` (which filters `files_to_generate` before
/// building the codegen context) and `protoc-gen-reallyme-buffa-packaging` (which
/// filters the packages it stitches into `mod.rs`) route their exclusion
/// through this one predicate, so the two are guaranteed to drop exactly the
/// same set — the invariant the packaging plugin's "Matching a codegen
/// plugin's output set" note depends on.
pub fn package_is_excluded(package: &str, excludes: &[String]) -> bool {
    excludes.iter().any(|ex| {
        package == ex
            || (package.len() > ex.len()
                && package.starts_with(ex.as_str())
                && package.as_bytes()[ex.len()] == b'.')
    })
}

/// Normalize and validate one `exclude_package` option value: trim
/// whitespace, strip the optional leading dot, reject an empty result or a
/// value with empty components (`buf.validate.`, `buf..validate`) — those
/// could never match a real package, so a typo would otherwise be a silent
/// no-op.
///
/// The plugin option-string parsers and `generate_with_diagnostics` all run
/// entries through this function so normalization cannot drift — the same
/// reason they share [`package_is_excluded`].
///
/// # Errors
///
/// Returns the user-facing message for a malformed value. The error is a
/// plain `String` (not [`CodeGenError`]) deliberately: this is plugin
/// option-string parsing, and both plugins' parse layers are
/// `Result<_, String>` end to end, surfaced verbatim by protoc.
pub fn normalize_exclude_package(value: &str) -> Result<String, String> {
    let pkg = value.trim();
    let pkg = pkg.strip_prefix('.').unwrap_or(pkg);
    if pkg.is_empty() || pkg.split('.').any(str::is_empty) {
        return Err(
            "'exclude_package' requires a non-empty proto package with no \
             empty components, e.g. exclude_package=.buf.validate"
                .to_string(),
        );
    }
    Ok(pkg.to_string())
}

/// Normalize and validate the proto side of one `extern_path` mapping.
///
/// Trims whitespace, adds the leading dot if absent, drops one trailing dot,
/// and rejects a name with an empty segment (`my..common`) or with a segment
/// that is not a protobuf identifier (`my.common-name`). Such a name matches
/// no type, so a typo would otherwise leave the mapping silently unused.
/// `"."`, the catch-all, is returned as is.
///
/// The `protoc-gen-reallyme-buffa` option parser and `buffa-build` both run entries
/// through this function, so the two front ends accept the same names.
///
/// # Errors
///
/// Returns the user-facing message for a malformed name, quoting the name as
/// given. The error is a plain `String` for the reason
/// [`normalize_exclude_package`] gives.
pub fn normalize_extern_path_proto_name(value: &str) -> Result<String, String> {
    const EXPECTED: &str = "expected '.' or a dotted protobuf package or type name, \
                            e.g. .my.pkg or .my.pkg.Type";
    let given = value.trim();
    if given == "." {
        return Ok(given.to_string());
    }
    let name = given.strip_prefix('.').unwrap_or(given);
    let name = name.strip_suffix('.').unwrap_or(name);
    for segment in name.split('.') {
        if segment.is_empty() {
            return Err(format!(
                "'extern_path' proto name '{given}' has an empty segment; {EXPECTED}"
            ));
        }
        // protoc's identifier rule: a letter or `_`, then letters, digits or `_`.
        let mut chars = segment.chars();
        let starts_ok = chars
            .next()
            .is_some_and(|c| c.is_ascii_alphabetic() || c == '_');
        if !(starts_ok && chars.all(|c| c.is_ascii_alphanumeric() || c == '_')) {
            return Err(format!(
                "'extern_path' proto name '{given}': segment '{segment}' is not a \
                 protobuf identifier; {EXPECTED}"
            ));
        }
    }
    Ok(format!(".{name}"))
}

#[cfg(test)]
mod extern_path_proto_name_tests {
    use super::normalize_extern_path_proto_name as normalize;

    #[test]
    fn accepts_and_normalizes_valid_names() {
        for (given, normalized) in [
            (".", "."),
            (".my.common", ".my.common"),
            ("my.common", ".my.common"),
            (".my.common.", ".my.common"),
            (" my.v2.Type_1 ", ".my.v2.Type_1"),
            ("._internal._Foo", "._internal._Foo"),
        ] {
            assert_eq!(normalize(given), Ok(normalized.to_string()), "{given:?}");
        }
    }

    #[test]
    fn empty_segment_error_quotes_the_name_as_given() {
        for given in [
            "",
            "..",
            "..my",
            "my..common",
            ".my.common..",
            ".my.common..Shared",
        ] {
            let err = normalize(given).unwrap_err();
            assert!(
                err.contains(&format!("'{given}' has an empty segment")),
                "{given:?}: {err}"
            );
        }
    }

    #[test]
    fn invalid_identifier_error_names_the_segment() {
        for (given, segment) in [
            ("my.123", "123"),
            (".my.common-name.", "common-name"),
            ("my.com mon", "com mon"),
        ] {
            let err = normalize(given).unwrap_err();
            assert!(
                err.contains(&format!("proto name '{given}': segment '{segment}'")),
                "{given:?}: {err}"
            );
        }
    }
}

#[cfg(test)]
mod package_exclusion_tests {
    use super::package_is_excluded;

    fn ex(list: &[&str]) -> Vec<String> {
        list.iter().map(|s| s.to_string()).collect()
    }

    #[test]
    fn exact_match_is_excluded() {
        assert!(package_is_excluded("buf.validate", &ex(&["buf.validate"])));
    }

    #[test]
    fn subpackage_matches_on_component_boundary() {
        assert!(package_is_excluded("gnostic.openapi.v3", &ex(&["gnostic"])));
        assert!(package_is_excluded(
            "buf.validate.priv",
            &ex(&["buf.validate"])
        ));
    }

    #[test]
    fn prefix_without_boundary_does_not_match() {
        assert!(!package_is_excluded(
            "buf.validatex",
            &ex(&["buf.validate"])
        ));
        assert!(!package_is_excluded("gnostics", &ex(&["gnostic"])));
    }

    #[test]
    fn unrelated_package_is_kept() {
        assert!(!package_is_excluded(
            "example.user.v1",
            &ex(&["buf.validate", "gnostic"])
        ));
    }

    #[test]
    fn empty_exclude_list_keeps_everything() {
        assert!(!package_is_excluded("buf.validate", &ex(&[])));
    }

    // An empty exclude entry is unreachable through either plugin
    // (`normalize_exclude_package` rejects it); this pins the raw
    // predicate's documented behavior for direct callers.
    #[test]
    fn empty_entry_matches_only_the_unnamed_package() {
        assert!(package_is_excluded("", &ex(&[""])));
        assert!(!package_is_excluded("foo", &ex(&[""])));
    }

    #[test]
    fn normalize_strips_dot_and_rejects_malformed() {
        use super::normalize_exclude_package;
        assert_eq!(
            normalize_exclude_package(".buf.validate").as_deref(),
            Ok("buf.validate")
        );
        assert_eq!(
            normalize_exclude_package("gnostic").as_deref(),
            Ok("gnostic")
        );
        assert!(normalize_exclude_package("").is_err());
        assert!(normalize_exclude_package(".").is_err());
        assert!(normalize_exclude_package("  ").is_err());
        // Entries that could never match a real package are rejected, not
        // silently accepted as no-ops.
        assert!(normalize_exclude_package("buf.validate.").is_err());
        assert!(normalize_exclude_package("buf..validate").is_err());
    }
}

/// Convert a proto package name to its [`file_per_package`] output filename.
///
/// e.g., `"google.protobuf"` → `"google.protobuf.rs"`. The unnamed
/// package uses [`SENTINEL_MOD`](context::SENTINEL_MOD) — same
/// collision-avoidance as [`package_to_mod_filename`].
///
/// [`file_per_package`]: CodeGenConfig::file_per_package
pub fn package_to_filename(package: &str) -> String {
    if package.is_empty() {
        format!("{}.rs", context::SENTINEL_MOD)
    } else {
        format!("{package}.rs")
    }
}

/// Convert a `.proto` file path to its content-file stem.
///
/// e.g., `"google/protobuf/timestamp.proto"` → `"google.protobuf.timestamp"`.
/// Content files append `""`, `".__view"`, `".__oneof"`,
/// `".__view_oneof"`, or `".__ext"` plus `".rs"` — emitted only for
/// kinds with non-empty content.
pub fn proto_path_to_stem(proto_path: &str) -> String {
    let without_ext = proto_path.strip_suffix(".proto").unwrap_or(proto_path);
    without_ext.replace('/', ".")
}

/// Merge downstream [`Companion`](GeneratedFileKind::Companion) files into
/// the per-package stitcher produced by [`generate`].
///
/// For each companion file this function locates the
/// [`PackageMod`](GeneratedFileKind::PackageMod) entry in `files` with a
/// matching package and appends `include!("<name>");` at file scope after
/// buffa's own output — at package root, alongside the owned message types,
/// not under `__buffa::`. The companion files themselves are appended to
/// `files` so that build integrations can write everything to disk in one
/// pass.
///
/// **Call this once per build**; it does not deduplicate, so a second call
/// with the same companions emits a second `include!` for each, which fails
/// to compile downstream with a duplicate-definition error.
///
/// `name` must be a bare-sibling filename — the same convention buffa uses
/// for its own `include!` calls, so it resolves relative to the stitcher
/// without any `OUT_DIR` prefix. Names must not contain `/` or `\`, must not
/// be empty, `.` or `..`, and must not collide with any of buffa's own
/// generated filenames for the same package (`<stem>.rs`, `<stem>.__view.rs`,
/// etc.) — pick an unused suffix such as `<stem>.__myplugin.rs`. The name is
/// written into the `include!` as an escaped string literal, as buffa's own
/// include paths are.
///
/// Companion files with no matching `PackageMod` (e.g. for a package buffa
/// did not generate any output for) are still appended to `files` but no
/// `include!` is emitted; the caller is responsible for wiring them up. If
/// you don't expect orphans, check that every companion's `package` appears
/// in `files` as a `PackageMod` after calling.
///
/// # Panics
///
/// Panics if a companion's `name` contains `/` or `\`, or is empty, `.` or
/// `..`. Every name is checked before `files` is changed.
#[track_caller]
pub fn apply_companions(files: &mut Vec<GeneratedFile>, companions: Vec<GeneratedFile>) {
    for comp in &companions {
        assert!(
            !comp.name.contains(['/', '\\']),
            "companion file name {:?} contains a path separator ('/' or '\\'); use a \
             bare file name such as `<stem>.__myplugin.rs`, which include!() resolves \
             next to the stitcher",
            comp.name
        );
        assert!(
            !matches!(comp.name.as_str(), "" | "." | ".."),
            "companion file name {:?} is empty, `.` or `..`, which names a directory, \
             not a file; use a bare file name such as `<stem>.__myplugin.rs`",
            comp.name
        );
    }
    for comp in &companions {
        if let Some(pkg_mod) = files
            .iter_mut()
            .find(|f| f.kind == GeneratedFileKind::PackageMod && f.package == comp.package)
        {
            pkg_mod
                .content
                .push_str(&format!("include!({:?});\n", comp.name));
        }
    }
    files.extend(companions);
}

/// Why a selected message cannot use recursive cleanup.
#[derive(Debug, Clone, Copy, PartialEq, Eq, thiserror::Error)]
#[non_exhaustive]
pub enum ZeroizeConfigurationErrorReason {
    /// Ordinary reflection would copy a guarded descendant into a dynamic snapshot.
    #[error(
        "containing messages need cleanup too so reflection cannot snapshot a guarded descendant"
    )]
    ReflectionParent,
    /// Unknown payload storage is not a wipe owner.
    #[error("requires unknown_fields=false")]
    UnknownFieldStorage,
    /// Strict UTF-8 mapping cannot select a custom raw map key.
    #[error("raw byte map keys under strict_utf8_mapping cannot use guarded representations")]
    RawMapKey,
    /// A buffer still has its ordinary representation.
    #[error("every bytes/string slot requires a custom Zeroize + ZeroizeOnDrop representation")]
    BufferRepresentation,
    /// A guarded representation could use default JSON decoding.
    #[error(
        "requires json_policy_type for each custom bytes/string representation when json=true"
    )]
    JsonPolicy,
}

/// Code generation error.
#[derive(Debug, Clone, thiserror::Error)]
#[non_exhaustive]
pub enum CodeGenError {
    /// A view-export restriction matches no known message.
    #[error("deny_view_json rule '{rule}' matches no known message")]
    ViewJsonRuleMatchedNothing { rule: String },
    /// A cleanup selector matches no message in the request's descriptors.
    #[error("zeroize_in rule '{rule}' matches no known message")]
    ZeroizeRuleMatchedNothing { rule: String },

    /// A listed policy type is not selected by any unshadowed representation rule.
    #[error("json_policy_type '{rust_type}' is not selected by any unshadowed bytes/string rule; match the representation type spelling exactly")]
    JsonPolicyTypeMatchedNothing { rust_type: String },
    /// A representation has the same final type name as a listed policy, but a different spelling.
    #[error("representation type '{selected}' has the same name as json_policy_type '{listed}', but a different spelling; list the exact type or correct the representation rule")]
    JsonPolicyTypeNearMiss { selected: String, listed: String },

    /// A selected message cannot satisfy the recursive cleanup contract.
    #[error("zeroize message '{message}': {reason}")]
    InvalidZeroizeConfiguration {
        /// Protobuf message name from the schema.
        message: String,
        /// A fixed, typed configuration reason.
        reason: ZeroizeConfigurationErrorReason,
    },

    /// A required field was absent in a descriptor, or a message or enum name
    /// was empty.
    ///
    /// The string is the descriptor field, such as `message.name` or
    /// `field.type_name`.
    #[error("missing required descriptor field: {0}")]
    MissingField(&'static str),
    /// A resolved type path string could not be parsed as a Rust type.
    #[error("invalid Rust type path: '{0}'")]
    InvalidTypePath(String),
    /// A [`json_policy_types`](CodeGenConfig::json_policy_types) `string`
    /// type is the key type of an enum-valued `map`. Policy keys do not yet
    /// support the enum map helpers' unknown-value filtering. The string is
    /// the map field's proto path.
    #[error(
        "enum-valued map field '{0}' has a json_policy_type string key; \
         policy keys do not support enum map filtering, so select another key representation"
    )]
    JsonPolicyMapKey(String),
    /// A `box_type_custom` pointer template did not contain the `*` placeholder.
    ///
    /// The custom pointer wraps the message type, so the template must mark where
    /// it goes with `*`, e.g. `"::smallbox::SmallBox<*, smallbox::space::S4>"`.
    #[error("box_type template must contain a `*` placeholder for the message type: '{0}'")]
    MissingWildcard(String),
    /// A `repeated_type_custom` collection template did not contain the `*`
    /// element placeholder.
    ///
    /// Unlike the scalar `string_type_custom` / `bytes_type_custom` knobs (which
    /// take a complete type path), a collection template wraps the element type
    /// and must mark where it goes with `*`, e.g. `"::my_crate::SmallList<*>"`.
    #[error("repeated_type template must contain a `*` element placeholder: '{0}'")]
    MissingListPlaceholder(String),
    /// The accumulated `TokenStream` failed to parse as valid Rust syntax.
    #[error("generated code failed to parse as Rust: {0}")]
    InvalidSyntax(String),
    /// A requested file was not present in the descriptor set.
    #[error("file_to_generate '{0}' not found in descriptor set")]
    FileNotFound(String),
    /// Two generated files would be written to the same output path. A
    /// content file is named after its `.proto` path with `/` replaced by
    /// `.`, so `foo/bar.proto` and `foo.bar.proto` both produce `foo.bar.rs`;
    /// a package's module file is `<package>.mod.rs`, which is also the
    /// content file of `foo/mod.proto` in package `foo`.
    ///
    /// Resolve by renaming a proto file (the only one involved, when the
    /// other source is a package), or by setting
    /// [`CodeGenConfig::file_per_package`], which emits one file per package
    /// and no per-proto content files.
    #[error(
        "output file name conflict: {first_source} and {second_source} both \
         generate '{file_name}'; rename a proto file so that the output names \
         differ, or enable file_per_package"
    )]
    OutputFileNameConflict {
        /// The output path that both inputs map to.
        file_name: String,
        /// The input that generated the path first: the `.proto` file path
        /// as its descriptor names it for a content file, or
        /// `package <name>` (`the unnamed package` for a file that declares
        /// no package) for a package's module file.
        first_source: String,
        /// The input that generated the path second, in the same form as
        /// `first_source`.
        second_source: String,
    },
    /// Unexpected descriptor state (e.g. a map entry or oneof that cannot be
    /// resolved to a known descriptor field).
    #[error("codegen error: {0}")]
    Other(String),
    /// A proto field name uses the `__buffa_` reserved prefix, which would
    /// conflict with buffa's internal generated fields.
    #[error(
        "reserved field name '{field_name}' in message '{message_name}': \
             proto field names starting with '__buffa_' conflict with buffa's \
             internal fields"
    )]
    ReservedFieldName {
        message_name: String,
        field_name: String,
    },
    /// Two sibling messages produce the same Rust module name after
    /// snake_case conversion (e.g., `HTTPRequest` and `HttpRequest` both
    /// become `pub mod http_request`).
    #[error(
        "module name conflict in '{scope}': messages '{name_a}' and '{name_b}' \
         both produce module '{module_name}'"
    )]
    ModuleNameConflict {
        scope: String,
        name_a: String,
        name_b: String,
        module_name: String,
    },
    /// Two oneofs of one message produce the same Rust enum name after
    /// PascalCase conversion and keyword escaping (e.g., `foo_bar` and
    /// `foo__bar` both become `FooBar`; `self` and `self_` both become
    /// `Self_`). Resolve by renaming one of the oneofs. A oneof's name is in
    /// neither the wire format nor JSON, so the rename changes generated
    /// code only.
    #[error(
        "oneof enum name conflict in message '{message_name}': oneofs \
         '{first_oneof}' and '{second_oneof}' both map to Rust enum '{rust_name}'; \
         rename one of them"
    )]
    OneofEnumNameConflict {
        /// Fully-qualified proto name of the message, without a leading dot.
        message_name: String,
        /// Proto name of the oneof declared first.
        first_oneof: String,
        /// Proto name of the oneof declared second.
        second_oneof: String,
        /// The Rust enum name that both oneofs map to.
        rust_name: String,
    },
    /// Two members of one oneof produce the same Rust variant name after
    /// PascalCase conversion and keyword escaping (e.g., `foo` and `foo_`
    /// both become `Foo`; `foo_bar` and `foo__bar` both become `FooBar`;
    /// `self` and `self_` both become `Self_`). Resolve by renaming one of
    /// the members. A member's name is its default JSON and text-format
    /// name, so the rename changes those too unless the field sets a
    /// `json_name`; the wire format is unaffected.
    #[error(
        "oneof variant name conflict in message '{message_name}': members \
         '{first_field}' and '{second_field}' of oneof '{oneof_name}' both map \
         to Rust variant '{rust_name}'; rename one of them"
    )]
    OneofVariantNameConflict {
        /// Fully-qualified proto name of the message, without a leading dot.
        message_name: String,
        /// Proto name of the oneof that declares both members.
        oneof_name: String,
        /// Proto name of the member declared first.
        first_field: String,
        /// Proto name of the member declared second.
        second_field: String,
        /// The Rust variant name that both members map to.
        rust_name: String,
    },
    /// Two types, each a message or an enum, declared at package level in
    /// one package or nested in one message, produce the same Rust type
    /// name. With an empty [`CodeGenConfig::type_name_prefix`], a type named
    /// after a Rust keyword (`type`, `Self`), or after a primitive type that
    /// generated code uses (`bool`, `str`, `u8`, `usize`, `i32`, `i64`,
    /// `u32`, `u64`, `f32`, `f64`), is generated with a trailing `_`, so
    /// `bool` and `bool_` both become `bool_`.
    ///
    /// Resolve by renaming one of the types, which changes its full name and
    /// its `Any` type URL, or by setting a prefix: with prefix `Pb` the two
    /// types are `Pbbool` and `Pbbool_`.
    #[error(
        "type name conflict in '{scope}': '{first_type}' and '{second_type}' \
         both map to Rust type '{rust_name}'; rename one of them"
    )]
    TypeNameConflict {
        /// Fully-qualified proto name of the package or message that
        /// declares both types, without a leading dot. Empty for a
        /// package-level conflict in a file that declares no package.
        scope: String,
        /// Proto simple name of the type visited first: within each file,
        /// messages in declaration order, then enums.
        first_type: String,
        /// Proto simple name of the type visited second.
        second_type: String,
        /// The Rust type name that both map to.
        rust_name: String,
    },
    /// A proto package segment, message name, or file-level enum name
    /// would emit a Rust item matching the reserved sentinel `__buffa`.
    ///
    /// This is the only name buffa reserves in user namespace. Resolve by
    /// renaming the proto element.
    #[error(
        "reserved name '{name}' at {location}: this name is reserved for \
         buffa's generated ancillary types (views, oneof enums, \
         extensions). Rename the proto element."
    )]
    ReservedModuleName { name: String, location: String },
    /// [`CodeGenConfig::shared_corpus_context`] was built from a different
    /// corpus or different oneof/pointer-repr rules than this call's.
    ///
    /// `what` names the mismatch: `"files"`, `"unboxed_oneof_fields"`, or
    /// `"pointer_fields"`. Build the context with
    /// [`SharedCorpusContext::new`] from the same `files` and config as every
    /// `generate()` call that uses it.
    #[error(
        "shared_corpus_context was built from different {what} than this \
         generate() call; build it from the same files and oneof/pointer-repr \
         config as every call that uses it"
    )]
    SharedCorpusContextMismatch { what: &'static str },
    /// The input contains a message with `option message_set_wire_format = true`
    /// but [`CodeGenConfig::allow_message_set`] was not set.
    #[error(
        "message '{message_name}' uses `option message_set_wire_format = true` \
         but CodeGenConfig::allow_message_set is false; MessageSet is a legacy \
         wire format — set allow_message_set(true) if this is intentional"
    )]
    MessageSetNotSupported { message_name: String },
    /// A custom attribute string configured via [`CodeGenConfig::type_attributes`],
    /// [`CodeGenConfig::field_attributes`], [`CodeGenConfig::message_attributes`],
    /// [`CodeGenConfig::enum_attributes`], [`CodeGenConfig::oneof_attributes`],
    /// or [`CodeGenConfig::oneof_struct_field_attributes`] is not one or more
    /// outer `#[...]` attributes. An empty string, an inner attribute
    /// `#![...]` and a string with any token outside an attribute are all
    /// rejected, whether or not the rule's path matches a generated item.
    #[error(
        "invalid custom attribute for path '{path}': '{attribute}' must be one or \
         more outer `#[...]` attributes ({detail})"
    )]
    InvalidCustomAttribute {
        path: String,
        attribute: String,
        detail: String,
    },
    /// [`CodeGenConfig::type_name_prefix`] is not PascalCase
    /// (`[A-Z][A-Za-z0-9]*`), so prepending it to a type name would produce
    /// an invalid or unconventionally-cased Rust identifier.
    #[error(
        "invalid type_name_prefix '{prefix}': must be empty or PascalCase \
         (start with an ASCII uppercase letter, followed by ASCII letters \
         and digits only)"
    )]
    InvalidTypeNamePrefix { prefix: String },
    /// Two fields of one message, in a file being generated, have the same
    /// field number. protoc rejects such a message, so the descriptor was
    /// built in code or changed after protoc wrote it.
    ///
    /// Generated code for it would write both fields with one field number
    /// and decode every record with that number into one of them, so the
    /// error is returned whichever codec is selected.
    #[error(
        "duplicate field number in message '{message_name}': fields '{first_field}' and \
         '{second_field}' are both numbered {number}; protoc rejects this, so renumber one of \
         them in the code or tool that built the descriptor"
    )]
    DuplicateFieldNumber {
        /// The message's full name, without a leading dot.
        message_name: String,
        /// The name of the field declared first.
        first_field: String,
        /// The name of the field declared second.
        second_field: String,
        /// The number both fields have, as the descriptor gives it. It may be
        /// outside the valid range for a field number.
        number: i32,
    },
}

#[cfg(test)]
mod tests;

mod guarded_arbitrary;
mod inspect;
mod sensitive;