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
// Modified by ReallyMe Technologies Limited.
//! Build-time integration for buffa.
//!
//! Use this crate in your `build.rs` to compile `.proto` files into Rust code
//! at build time. Parses `.proto` files into a `FileDescriptorSet` (via
//! `protoc` or `buf`), then uses `buffa-codegen` to generate Rust source.
//!
//! # Example
//!
//! ```rust,ignore
//! // build.rs
//! fn main() {
//! buffa_build::Config::new()
//! .files(&["proto/my_service.proto"])
//! .includes(&["proto/"])
//! .compile()
//! .unwrap();
//! }
//! ```
//!
//! # Requirements
//!
//! By default, requires `protoc` on the system PATH (or set via the `PROTOC`
//! environment variable) — the same as `prost-build` and `tonic-build`.
//!
//! If `protoc` is unavailable or outdated on your platform, `buf` can be
//! used instead — see [`Config::use_buf()`]. Alternatively, feed a
//! pre-compiled descriptor set via [`Config::descriptor_set()`] (a file) or
//! [`Config::descriptor_set_bytes()`] (in-memory bytes).
use std::borrow::Cow;
use std::collections::BTreeSet;
use std::path::{Component, Path, PathBuf};
use std::process::Command;
use buffa_codegen::generated::descriptor::FileDescriptorSet;
/// Typed configuration for opt-in native adapters.
pub use buffa_codegen::adapters;
#[doc(inline)]
pub use buffa_codegen::CodeGenConfig;
#[doc(inline)]
pub use buffa_codegen::FeatureGateNames;
#[doc(inline)]
pub use buffa_codegen::ReflectMode;
#[doc(inline)]
pub use buffa_codegen::{BytesRepr, CodecStrategy, MapRepr, PointerRepr, RepeatedRepr, StringRepr};
#[doc(inline)]
pub use buffa_codegen::{EnumTypeOverride, FeatureOverride};
/// How to produce a `FileDescriptorSet` from `.proto` files.
#[derive(Debug, Clone, Default)]
enum DescriptorSource {
/// Invoke `protoc` (default). Requires `protoc` on PATH or `PROTOC` env var.
#[default]
Protoc,
/// Invoke `buf build --as-file-descriptor-set`. Requires `buf` on PATH.
Buf,
/// Read a pre-built `FileDescriptorSet` from a file.
Precompiled(PathBuf),
/// Use a pre-built `FileDescriptorSet` already in memory.
Bytes(Vec<u8>),
}
/// Builder for configuring and running protobuf compilation.
pub struct Config {
files: Vec<PathBuf>,
includes: Vec<PathBuf>,
out_dir: Option<PathBuf>,
codegen_config: CodeGenConfig,
descriptor_source: DescriptorSource,
/// If set, generate a module-tree include file with this name in the
/// output directory. Users can then `include!` this single file instead
/// of manually setting up `pub mod` nesting.
include_file: Option<String>,
}
impl Config {
/// Enable typed `(buffa.ext.file).adapters` options (default: false).
///
/// Native files are written beside the portable output and included
/// explicitly in their API modules. No native adapter enters the portable
/// module tree. Missing or incomplete mappings fail before output is written.
/// Without an explicit [`Self::adapters`] configuration, at least one
/// requested file must declare the options, otherwise `compile()` fails
/// with [`adapters::ErrorReason::MissingSchemaAdapters`]. This setting
/// only controls the schema options: it does not suppress an explicit
/// [`Self::adapters`] configuration.
#[must_use]
pub fn generate_adapters(mut self, enabled: bool) -> Self {
self.codegen_config.generate_adapters = enabled;
self
}
/// Add descriptor-checked native adapters from a typed Rust configuration.
/// Replaces the previous explicit configuration; schema options, if enabled,
/// are combined with it and checked for collisions.
#[must_use]
pub fn adapters(mut self, config: adapters::AdapterConfig) -> Self {
self.codegen_config.adapters = Some(config);
self
}
/// Create a new configuration with defaults.
pub fn new() -> Self {
Self {
files: Vec::new(),
includes: Vec::new(),
out_dir: None,
codegen_config: CodeGenConfig::default(),
descriptor_source: DescriptorSource::default(),
include_file: None,
}
}
/// Add `.proto` files to compile.
#[must_use]
pub fn files(mut self, files: &[impl AsRef<Path>]) -> Self {
self.files
.extend(files.iter().map(|f| f.as_ref().to_path_buf()));
self
}
/// Add include directories for protoc to search for imports.
///
/// Directories are searched in order. If directories overlap, the first
/// matching directory determines the proto-relative file name.
#[must_use]
pub fn includes(mut self, includes: &[impl AsRef<Path>]) -> Self {
self.includes
.extend(includes.iter().map(|i| i.as_ref().to_path_buf()));
self
}
/// Set the output directory for generated files.
/// Defaults to `$OUT_DIR` if not set.
#[must_use]
pub fn out_dir(mut self, dir: impl Into<PathBuf>) -> Self {
self.out_dir = Some(dir.into());
self
}
/// Enable or disable view type generation (default: true).
#[must_use]
pub fn generate_views(mut self, enabled: bool) -> Self {
self.codegen_config.generate_views = enabled;
self
}
/// Additionally generate the lazy view family (`FooLazyView<'a>`)
/// alongside the unchanged eager views (default: false).
///
/// Lazy views decode in a single non-recursive pass, recording nested and
/// repeated message fields as undecoded byte ranges that decode on access
/// via fallible, by-value accessors (`.get()` / iteration) — untouched
/// sub-trees cost nothing. Validation of deferred bytes happens on
/// *access* (and in the fallible `to_owned_message`), not at decode.
/// Groups, oneof message variants, and map message values stay eager;
/// lazy views have no `ReflectMessage`/`OwnedView`/text surface. Eager
/// codegen output is byte-identical with or without the flag. Requires
/// [`generate_views`](Self::generate_views). See
/// [`CodeGenConfig::lazy_views`] for full semantics.
#[must_use]
pub fn lazy_views(mut self, enabled: bool) -> Self {
self.codegen_config.lazy_views = enabled;
self
}
/// Enable or disable serde JSON generation (default: false).
///
/// When enabled:
/// - Generated message structs get `Serialize`/`Deserialize` derives.
/// - Generated enum types get `Serialize`/`Deserialize` derives.
/// - Generated view types (when `generate_views` is also enabled) get a
/// manual `impl Serialize` for zero-copy JSON serialization, so
/// `serde_json::to_string(&view)` works directly:
///
/// ```ignore
/// let view = MyMsgView::decode_view(&bytes)?;
/// let json = serde_json::to_string(&view)?;
/// ```
///
/// The downstream crate must depend on `serde` and enable the `buffa/json`
/// feature for the runtime helpers. When views are enabled, the crate must
/// also enable `buffa-types/json` so the well-known type views implement
/// `Serialize`; without it, references to e.g. `TimestampView<'_>` in the
/// generated `Serialize` impl will fail with
/// `the trait bound 'TimestampView<'_>: Serialize' is not satisfied`.
///
/// **Limitations of the view `Serialize` impl:**
/// - Extension fields are not included in view JSON output; serialize the
/// owned form (`view.to_owned_message()`) to include extensions.
/// - The impl uses `serialize_map(None)` (unknown length) because the
/// number of emitted fields depends on default-omission rules. Most
/// self-describing serializers (notably `serde_json`) accept this, but
/// length-prefixed formats (e.g. `bincode`, `postcard`) will return a
/// runtime error. The owned types' derived `Serialize` does not have this
/// restriction.
#[must_use]
pub fn generate_json(mut self, enabled: bool) -> Self {
self.codegen_config.generate_json = enabled;
self
}
/// Enable or disable `impl buffa::text::TextFormat` on generated message
/// structs (default: false).
///
/// When enabled, the downstream crate must enable the `buffa/text`
/// feature for the runtime textproto encoder/decoder.
#[must_use]
pub fn generate_text(mut self, enabled: bool) -> Self {
self.codegen_config.generate_text = enabled;
self
}
/// Enable or disable `#[derive(arbitrary::Arbitrary)]` on generated
/// types (default: false).
///
/// The derive is gated behind `#[cfg_attr(feature = "arbitrary", ...)]`
/// so the downstream crate compiles with or without the feature enabled.
/// An enum with a `[deprecated = true]` variant gets a generated impl
/// under the same gate instead, because the derive would warn on that
/// variant. The impl maps input to variants as the derive does.
///
/// Your crate's Cargo feature **must be named exactly `"arbitrary"`** —
/// the generated `cfg_attr` uses that literal string and cannot be
/// customised — and it must forward to `buffa/arbitrary`:
///
/// ```toml
/// [features]
/// arbitrary = ["dep:arbitrary", "buffa/arbitrary"]
/// ```
///
/// Forgetting `"buffa/arbitrary"` produces a confusing error in generated
/// code, such as ``cannot find function `arbitrary_proto_bytes` in module
/// `buffa::__private` ``, when a `string_type` or `bytes_type` rule selects
/// a non-default type: the functions that back `#[arbitrary(with = ...)]`
/// on those fields live in `buffa` under that feature gate.
#[must_use]
pub fn generate_arbitrary(mut self, enabled: bool) -> Self {
self.codegen_config.generate_arbitrary = enabled;
self
}
/// Omit the generated `Debug` implementation for the matching messages
/// and enums, so that your crate can write its own.
///
/// Each path is a fully-qualified proto path. For messages it is a
/// prefix: `".demo.Uuid4"` names that message and the messages nested
/// inside it, `".demo"` every message in the package and its
/// sub-packages, and `"."` every message. A matched message's oneof
/// enums lose their `Debug` with it. An enum loses its `Debug` only when
/// a path is its exact name, such as `".demo.Level"`: a message or
/// package path leaves the enums under it as they are. A leading dot is
/// added if missing and trailing dots are trimmed. Repeated calls
/// accumulate.
///
/// Eager, lazy, and owned views of matched messages, and their view oneofs,
/// keep `Debug` but print only the type name and `[REDACTED]`. This also
/// hides preserved unknown wire fields. The rule affects generated
/// formatting only. For selective redaction in generated and reflective
/// formatting, use `[debug_redact = true]`. A hand-written `Debug` impl
/// for a matched owned message or oneof decides what that value prints.
///
/// Your crate then implements `Debug`:
///
/// - for every matched enum, because [`buffa::Enumeration`] requires it;
/// - for a matched message that an unmatched message or oneof holds
/// (their generated `Debug` formats it), that is generated with
/// reflection, or that a custom `repeated_type` collection holds;
/// - for a matched message's oneof enum, if your `Debug` for the message
/// prints it. For a oneof `kind` in `demo.Uuid4` the enum is
/// `demo::uuid4::Kind`.
///
/// A missing impl is a compile error. For an enum it is error E0277
/// (`Level` doesn't implement `Debug`) at the generated
/// `impl ::buffa::Enumeration for Level`. A path that matches no
/// generated message and names no generated enum prints a
/// `cargo:warning`.
///
/// # Example
///
/// ```rust,ignore
/// // build.rs
/// buffa_build::Config::new()
/// .files(&["proto/demo.proto"])
/// .includes(&["proto/"])
/// .skip_debug(&[".demo.Uuid4", ".demo.Level"])
/// .compile()?;
///
/// // src/lib.rs
/// pub mod demo {
/// buffa::include_proto!("demo");
/// }
///
/// impl core::fmt::Debug for demo::Uuid4 {
/// fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
/// write!(f, "Uuid4({:016x}{:016x})", self.msb, self.lsb)
/// }
/// }
///
/// // Prints the value's proto name, as the derive it replaces does.
/// impl core::fmt::Debug for demo::Level {
/// fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
/// f.write_str(buffa::Enumeration::proto_name(self))
/// }
/// }
/// ```
#[must_use]
pub fn skip_debug(mut self, paths: &[impl AsRef<str>]) -> Self {
for raw in paths.iter().map(AsRef::as_ref) {
let normalized = normalize_override_path(raw);
if normalized.is_empty() {
println!(
"cargo:warning=buffa: skip_debug path '{raw}' \
normalizes to empty and will be ignored"
);
continue;
}
self.codegen_config.skip_debug.push(normalized);
}
self
}
/// Reject JSON serialization of the selected messages' eager, lazy and owned
/// views before writing any output. Owned-message JSON remains available.
/// The restriction propagates to containing messages, including map values.
/// `.` selects every message; unmatched rules cause a code generation error.
/// Empty paths are errors. Disabling JSON or views warns that the rule is inactive.
#[must_use]
pub fn deny_view_json(mut self, paths: &[impl AsRef<str>]) -> Self {
self.codegen_config.deny_view_json.extend(
paths
.iter()
.map(|path| normalize_override_path(path.as_ref())),
);
self
}
/// Omit standard owned-view wrappers and `HasMessageView` for matching
/// messages and their containers. Borrowed views remain available.
/// Use `.` to select every message. Rules must match a known message.
/// Messages selected for cleanup, and their containers, are always
/// treated as selected.
///
/// This controls what code is generated. It does not disable explicit
/// use of the public `buffa::OwnedView` runtime with a borrowed view type.
#[must_use]
pub fn borrowed_views_only_in(mut self, paths: &[impl AsRef<str>]) -> Self {
self.codegen_config.borrowed_views_only_in.extend(
paths
.iter()
.map(|path| normalize_override_path(path.as_ref())),
);
self
}
/// Wrap generated `impl`s in `#[cfg(feature = "...")]` instead of
/// emitting them unconditionally (default: false).
///
/// When enabled, the impls controlled by [`generate_json`],
/// [`generate_views`], and [`generate_text`] are wrapped in
/// `#[cfg(feature = "json" | "views" | "text")]` (or
/// `#[cfg_attr(feature = ..., ...)]` for derives and field attributes)
/// rather than emitted unconditionally. The crate consuming the
/// generated code must define matching Cargo features that enable the
/// corresponding runtime support:
///
/// ```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.
///
/// Reach for this when generated code is the **public interface of a
/// library crate** consumed by downstream projects with different
/// feature needs — exactly the shape of `buffa-descriptor` and
/// `buffa-types`, which ship every impl while letting the codegen
/// toolchain (`buffa-codegen`/`buffa-build`/`protoc-gen-reallyme-buffa`) depend
/// on them with `default-features = false` and stay free of
/// `serde`/`serde_json`/`base64`. Most consumers of `buffa-build` are
/// **not** in this position: a `build.rs` that decides at build-script
/// time whether to generate JSON wants `impl Serialize` to just exist.
/// Default `false`.
///
/// [`generate_json`]: Self::generate_json
/// [`generate_views`]: Self::generate_views
/// [`generate_text`]: Self::generate_text
#[must_use]
pub fn gate_impls_on_crate_features(mut self, enabled: bool) -> Self {
self.codegen_config.gate_impls_on_crate_features = enabled;
self
}
/// Gate only 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 together).
///
/// For crates that ship views/text unconditionally but want the
/// `buffa-descriptor`-dependent (and `std`-requiring) reflection surface to
/// be opt-in. `buffa-types` is the motivating case.
///
/// **Experimental and `#[doc(hidden)]`.** This knob only controls the
/// crate-feature gate on the emitted reflection impls; the reflection
/// codegen mode itself is selected via the public
/// [`reflect_mode`](Self::reflect_mode) selector.
#[doc(hidden)]
#[must_use]
pub fn gate_reflect_on_crate_feature(mut self, enabled: bool) -> Self {
self.codegen_config.gate_reflect_on_crate_feature = enabled;
self
}
/// Set the crate feature name the gated JSON impls are conditioned on
/// (default: `"json"`).
///
/// Only meaningful together with
/// [`gate_impls_on_crate_features`](Self::gate_impls_on_crate_features);
/// inert otherwise. Use when the consuming crate gates its JSON support
/// behind a differently-named feature:
///
/// ```toml
/// [features]
/// serde = ["buffa/json", "dep:serde", "dep:serde_json"]
/// ```
///
/// ```rust,ignore
/// buffa_build::Config::new()
/// .generate_json(true)
/// .gate_impls_on_crate_features(true)
/// .json_feature_name("serde")
/// # ;
/// ```
///
/// The name is emitted verbatim into `#[cfg(feature = "...")]`
/// attributes and must be a valid Cargo feature name **declared in the
/// consuming crate's `[features]` table**. A misspelled or undeclared
/// name fails open: the `#[cfg]` is permanently false, so the gated
/// impls silently compile away (on Rust ≥ 1.80 an undeclared name at
/// least triggers the `unexpected_cfgs` warning). A name that is not a
/// valid Cargo feature name at all (empty, or containing characters
/// outside alphanumerics and `_`/`-`/`+`/`.`) makes [`compile`](Self::compile)
/// fail with an error when the gate is active.
#[must_use]
pub fn json_feature_name(mut self, name: impl Into<String>) -> Self {
self.codegen_config.feature_gate_names.json = name.into();
self
}
/// Set the crate feature name the gated view impls are conditioned on
/// (default: `"views"`).
///
/// Only meaningful together with
/// [`gate_impls_on_crate_features`](Self::gate_impls_on_crate_features);
/// inert otherwise. See [`json_feature_name`](Self::json_feature_name).
#[must_use]
pub fn views_feature_name(mut self, name: impl Into<String>) -> Self {
self.codegen_config.feature_gate_names.views = name.into();
self
}
/// Set the crate feature name the gated textproto impls are conditioned
/// on (default: `"text"`).
///
/// Only meaningful together with
/// [`gate_impls_on_crate_features`](Self::gate_impls_on_crate_features);
/// inert otherwise. See [`json_feature_name`](Self::json_feature_name).
#[must_use]
pub fn text_feature_name(mut self, name: impl Into<String>) -> Self {
self.codegen_config.feature_gate_names.text = name.into();
self
}
/// Set the crate feature name the gated reflection impls are conditioned
/// on (default: `"reflect"`).
///
/// Only meaningful together with
/// [`gate_impls_on_crate_features`](Self::gate_impls_on_crate_features)
/// (or the experimental, hidden `gate_reflect_on_crate_feature`, which
/// gates reflection alone); inert otherwise. See
/// [`json_feature_name`](Self::json_feature_name).
#[must_use]
pub fn reflect_feature_name(mut self, name: impl Into<String>) -> Self {
self.codegen_config.feature_gate_names.reflect = name.into();
self
}
/// Prepend a prefix to every generated Rust type name (default: none).
///
/// With prefix `"Rpc"`, `message User {}` generates `struct RpcUser`
/// (and `RpcUserView` / `RpcUserOwnedView`); every cross-reference 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.
///
/// Applies to message structs and enum types (top-level and nested).
/// Module names, oneof enums, [`extern_path`](Self::extern_path)-mapped
/// types (including well-known types), and the wire/JSON format are
/// unaffected.
///
/// When another crate references these prefixed types via its own
/// [`extern_path`](Self::extern_path) 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.
///
/// The prefix 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; [`compile`](Self::compile)
/// fails otherwise.
#[must_use]
pub fn type_name_prefix(mut self, prefix: impl Into<String>) -> Self {
self.codegen_config.type_name_prefix = prefix.into();
self
}
/// Enable or disable `with_*` builder-style setter methods for
/// explicit-presence fields (default: true).
///
/// 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
/// without the `Some(...)` boilerplate:
///
/// ```ignore
/// let req = MyRequest::default()
/// .with_name("alice")
/// .with_timeout_ms(30_000);
/// ```
///
/// String, bytes, and enum setters take `impl Into<T>` (so `&str`,
/// `b"..."` literals, and bare enum variants work directly); other
/// scalars take `T` to keep integer-literal inference unambiguous.
///
/// Setters are pure inherent methods with no runtime dependency — they
/// don't interact with the `json`/`views`/`text` feature gates. Disable
/// only if you want to keep generated code minimal or have a competing
/// `with_*` convention in your own crate.
#[must_use]
pub fn generate_with_setters(mut self, enabled: bool) -> Self {
self.codegen_config.generate_with_setters = enabled;
self
}
/// Enable reflection on generated types (default: off).
///
/// `generate_reflection(true)` selects [`ReflectMode::VTable`] — the fast
/// path: `foo.reflect()` borrows `foo` directly (no encode/decode
/// round-trip), and owned and view types implement `ReflectMessage`. For
/// the smaller bridge implementation (`reflect()` round-trips through a
/// [`DynamicMessage`]), use [`reflect_mode(ReflectMode::Bridge)`](Self::reflect_mode)
/// instead. `generate_reflection(false)` is [`ReflectMode::Off`].
///
/// Either mode embeds a lazily-built [`DescriptorPool`] (as
/// `FileDescriptorSet` bytes) reachable as
/// `your_crate::your_pkg::descriptor_pool()`.
///
/// # Cargo.toml setup
///
/// The consuming crate must depend on `buffa-descriptor` with the
/// `reflect` feature and on `std`:
///
/// ```toml
/// [dependencies]
/// buffa = { package = "reallyme-buffa", version = "=0.1.3", features = ["std"] }
/// buffa-descriptor = { package = "reallyme-buffa-descriptor", version = "=0.1.3", features = ["reflect", "std"] }
/// ```
///
/// When [`gate_impls_on_crate_features`](Self::gate_impls_on_crate_features)
/// is also on, the impls are wrapped in `#[cfg(feature = "reflect")]`,
/// so the consuming crate must declare a forwarding feature:
///
/// ```toml
/// [features]
/// reflect = ["buffa-descriptor/reflect"]
/// ```
///
/// **Without the feature declared, the generated `Reflectable` impls
/// silently disappear** — `cfg(feature = "reflect")` is permanently
/// false in a crate that doesn't declare it. The first call to
/// `.reflect()` fails to compile with "trait `Reflectable` not
/// implemented", which is a misleading diagnostic. Most consumers
/// should leave `gate_impls_on_crate_features` off.
///
/// Reflecting message-typed fields also requires every crate that field
/// types resolve to via an extern path — notably `buffa-types` for
/// well-known types — to enable its own reflection feature; see
/// [`reflect_mode`](Self::reflect_mode) ("Extern-path types") for the
/// `Cargo.toml` requirement and mixed-mode behavior.
///
/// # Performance
///
/// In the default vtable mode, `reflect()` borrows `self` — no round-trip,
/// no allocation; reflective accessors read fields in place. (Bridge mode
/// instead pays one encode/decode round-trip plus a heap allocation per
/// call.) Either way the first call pays a one-time pool build cost.
///
/// # Build time and binary size
///
/// By default each generated package embeds its own copy of the full
/// `FileDescriptorSet` (transitive closure). For a single-package
/// crate this is one copy. For a multi-package codegen run the bytes
/// duplicate per package — measurable for large proto trees;
/// [`shared_descriptor_pool`](Self::shared_descriptor_pool) collapses that
/// to one `include_bytes!` sidecar. The serialization happens once per
/// `compile()` call (not per package), so build-time CPU does not scale
/// with package count. Vtable mode also emits an `impl ReflectMessage` per
/// type, so it produces more code than bridge mode.
///
/// [`ReflectCow`]: https://docs.rs/reallyme-buffa-descriptor/latest/buffa_descriptor/reflect/enum.ReflectCow.html
/// [`DynamicMessage`]: https://docs.rs/reallyme-buffa-descriptor/latest/buffa_descriptor/reflect/struct.DynamicMessage.html
/// [`DescriptorPool`]: https://docs.rs/reallyme-buffa-descriptor/latest/buffa_descriptor/struct.DescriptorPool.html
#[must_use]
pub fn generate_reflection(mut self, enabled: bool) -> Self {
// The simple on/off knob selects the fast vtable path; Bridge is opt-in
// via `reflect_mode`.
let mode = if enabled {
ReflectMode::VTable
} else {
ReflectMode::Off
};
mode.apply(&mut self.codegen_config);
self
}
/// Select the reflection mode (the fuller form of
/// [`generate_reflection`](Self::generate_reflection)).
///
/// - [`ReflectMode::Off`] — no reflection (the default); equivalent to
/// `generate_reflection(false)`.
/// - [`ReflectMode::Bridge`] — `reflect()` round-trips through
/// `DynamicMessage`; smaller generated code, slower reflective access.
/// - [`ReflectMode::VTable`] — `impl ReflectMessage` on owned and view
/// types, and `reflect()` borrows `self` with no round-trip; equivalent
/// to `generate_reflection(true)`. Does not require view generation —
/// with views off, only the owned impls are emitted.
///
/// All non-`Off` modes require the consuming crate to depend on
/// `buffa-descriptor` with its `reflect` feature and on `std`. The call
/// site (`foo.reflect().get(fd)`) is identical across modes.
///
/// # Extern-path types
///
/// Reflection on a message reaches into its message-typed fields, so
/// every crate that field types resolve to via an extern path must have
/// its own reflection enabled. In particular, well-known types resolve
/// to `buffa-types` by default, and its impls are behind a cargo
/// feature: depend on `buffa-types = { ..., features = ["reflect"] }`
/// or the build fails with unsatisfied `Reflectable` /
/// `ReflectMessage` bounds on the WKT.
///
/// # Mixed modes
///
/// A vtable-mode message may embed owned message types generated in
/// bridge mode (e.g. a dependency crate that chose the smaller output):
/// reflective access degrades to an owned `DynamicMessage` snapshot at
/// that boundary instead of failing. For a bridge-grade `repeated` or
/// `map` field the snapshot is taken per element on every access, so
/// reflecting a large mixed-mode collection scales the encode/decode
/// cost by the element count. The *view* reflection surface cannot
/// degrade — every view type embedded in a vtable-mode view must itself
/// be vtable-grade, and a bridge-grade view field is a compile error.
#[must_use]
pub fn reflect_mode(mut self, mode: ReflectMode) -> Self {
mode.apply(&mut self.codegen_config);
self
}
/// Deduplicate the embedded reflection descriptor pool across packages.
///
/// With reflection enabled, each package normally embeds its own copy of
/// the full-closure `FileDescriptorSet`. For a multi-package build those
/// copies are identical, so a large proto tree carries the same bytes once
/// per package. When this is on, the descriptor set is written once as a
/// binary sidecar next to the generated tree and `include_bytes!`-d by a
/// single shared `__buffa_fds` module; every package's `descriptor_pool()`
/// / `FILE_DESCRIPTOR_SET_BYTES` delegates to it. This removes both the
/// per-package duplication and the byte-literal source expansion.
///
/// The sidecar is named `<include-file-stem>.descriptor_set.binpb` (so
/// `.include_file("gen_mod.rs")` writes `gen_mod.descriptor_set.binpb`)
/// and lands in the output directory next to the include file. With a
/// checked-in [`out_dir`](Self::out_dir), commit the sidecar alongside
/// the generated `.rs` files — the `include_bytes!` resolves relative to
/// the include file, so the pair must travel together.
///
/// Requires [`include_file`](Self::include_file) (the shared module is
/// emitted into that file at the tree root) and reflection to be enabled;
/// [`compile`](Self::compile) errors otherwise. The include file name must
/// be a bare file name, not a path: the sidecar is named after the stem
/// alone, so `a/gen.rs` and `b/gen.rs` would share one sidecar. See
/// [`CodeGenConfig::shared_descriptor_pool`].
///
/// In this mode the generated tree must be consumed *through the include
/// file* (`include!(concat!(env!("OUT_DIR"), "/gen_mod.rs"))`, or the
/// checked-in `mod gen;` flavour). Each package delegates to `__buffa_fds`
/// by a fixed number of `super::` hops from the tree root, so wiring
/// packages individually with `buffa::include_proto!` does not compile
/// here: the delegation resolves against whatever module the macro lands
/// in. Two shared-pool `compile()` calls included at the same module scope
/// likewise collide on `__buffa_fds`; give each include file its own
/// module.
#[must_use]
pub fn shared_descriptor_pool(mut self, enabled: bool) -> Self {
self.codegen_config.shared_descriptor_pool = enabled;
self
}
/// Enable or disable idiomatic `UpperCamelCase` enum aliases (matches the
/// [`CodeGenConfig`] default, currently on).
///
/// Protobuf enum values are `SHOUTY_SNAKE_CASE` and stay the definitive Rust
/// variants. When enabled, codegen additionally emits associated `const`s
/// with the enum-name prefix stripped and the name converted to
/// `UpperCamelCase` (`RULE_LEVEL_HIGH` → `RuleLevel::High`), purely
/// additively — existing references and `Debug` output are unchanged.
///
/// Aliases are suppressed per enum (with a build warning and a doc note) if
/// any two values would collide after conversion, so a match is never forced
/// to mix conventions. See [`CodeGenConfig::idiomatic_enum_aliases`].
#[must_use]
pub fn idiomatic_enum_aliases(mut self, enabled: bool) -> Self {
self.codegen_config.idiomatic_enum_aliases = enabled;
self
}
/// 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.
/// Default: `false` (proto names are emitted verbatim).
///
/// Only the generated Rust source names change; the wire format, JSON
/// (`json_name` plus the original proto name accepted on parse), text
/// format, and reflection lookups all keep the descriptor's names, so the
/// option is fully wire- and JSON-compatible. Enum values are covered by
/// [`idiomatic_enum_aliases`](Self::idiomatic_enum_aliases) instead.
///
/// Word boundaries match prost-build's (heck's) segmentation, including
/// digit-transparent case boundaries (`v2Field` → `v2_field`); unlike
/// prost, authored underscores are always preserved (`_foo` stays
/// `_foo`), so already-snake_case names are never rewritten.
///
/// If two members of one message collide after conversion (`userName` and
/// `user_name` — rejected by protoc for proto3/editions, so proto2 only),
/// the names are adjusted deterministically and a build warning is
/// emitted; see [`CodeGenConfig::idiomatic_field_names`] for the rules.
#[must_use]
pub fn idiomatic_field_names(mut self, enabled: bool) -> Self {
self.codegen_config.idiomatic_field_names = enabled;
self
}
/// Emit one `<dotted.package>.rs` file per proto package instead of the
/// per-proto-file content set plus `<pkg>.mod.rs` stitcher. Default:
/// `false`.
///
/// The single file inlines what the stitcher would otherwise `include!`,
/// producing the same module structure. Required by
/// [`idiomatic_imports`](Self::idiomatic_imports). See
/// [`CodeGenConfig::file_per_package`] for caveats about packages that
/// span multiple directories.
#[must_use]
pub fn file_per_package(mut self, enabled: bool) -> Self {
self.codegen_config.file_per_package = enabled;
self
}
/// **Experimental.** Emit `use`-backed short type names at the package
/// root instead of fully-qualified paths, so struct fields read
/// `MessageField<Timestamp>` instead of
/// `::buffa::MessageField<::buffa_types::google::protobuf::Timestamp>`.
/// Default: `false` (output is byte-for-byte identical to previous
/// releases).
///
/// Requires [`file_per_package`](Self::file_per_package) — the build
/// fails otherwise. Short names that would collide with another item at
/// the package root (or a name referenced bare by sibling emissions)
/// fall back to parent-module qualification, then to the
/// fully-qualified path.
///
/// Only package-root type *declarations* are shortened; impl bodies,
/// nested-message modules, and `__buffa` internals keep fully-qualified
/// paths. "Experimental" means the output shape may change between
/// releases and the option may be renamed or removed outside semver
/// guarantees. See [`CodeGenConfig::idiomatic_imports`] for details.
#[must_use]
pub fn idiomatic_imports(mut self, enabled: bool) -> Self {
self.codegen_config.idiomatic_imports = enabled;
self
}
/// Enable or disable unknown field preservation (default: true).
///
/// When enabled (the default), unrecognized fields encountered during
/// decode are stored and re-emitted on encode — essential for proxy /
/// middleware services and round-trip fidelity across schema versions.
///
/// **Disabling is mostly a memory optimization**: 24 bytes per owned
/// message for the `UnknownFields` `Vec` header, and one pointer per
/// view, whose backing state is allocated only once an unknown field
/// actually arrives.
///
/// A wire payload with no unknown fields does no per-field work either
/// way, but that does not make the two modes equivalent: carrying the
/// handle still shapes how the compiler moves the view, and that is
/// measurable on view-decode throughput for message-dense shapes.
/// Disabling is the only setting that removes the field outright, so it
/// is the lever to reach for when view decode is hot and round-trip
/// fidelity across schema versions is not required — as it is for
/// embedded / `no_std` targets and large in-memory collections of small
/// messages.
///
/// To keep the global off-switch and still preserve selected messages, use
/// [`preserve_unknown_fields_in`](Self::preserve_unknown_fields_in).
#[must_use]
pub fn preserve_unknown_fields(mut self, enabled: bool) -> Self {
self.codegen_config.preserve_unknown_fields = enabled;
self
}
/// Generate recursive cleanup for every owned message.
/// Requires `buffa/zeroize` and guarded field representations; see the guarded-fields guide.
/// No owned-view wrapper or `HasMessageView` impl is generated, as with
/// [`borrowed_views_only_in`](Self::borrowed_views_only_in).
#[must_use]
pub fn generate_zeroize(mut self, enabled: bool) -> Self {
self.codegen_config.generate_zeroize = enabled;
self
}
/// Generate recursive cleanup for messages under these proto path prefixes.
/// `.` matches every message. Calls accumulate. Empty or unmatched paths
/// are errors; scoped requests can explicitly allow unmatched rules.
/// Selected messages and their containers get no owned-view wrapper or
/// `HasMessageView` impl, as with
/// [`borrowed_views_only_in`](Self::borrowed_views_only_in).
#[must_use]
pub fn zeroize_in(mut self, paths: &[impl AsRef<str>]) -> Self {
self.codegen_config.zeroize_messages.extend(
paths
.iter()
.map(|path| normalize_override_path(path.as_ref())),
);
self
}
/// Enable unknown-field preservation for matching messages, on top of
/// the global [`preserve_unknown_fields`](Self::preserve_unknown_fields)
/// setting.
///
/// Each path is a fully-qualified proto path prefix, e.g.
/// `".wa.CallLogRecord"` for one message or `".wa"` for a package (same
/// matching as [`unbox_oneof_in`](Self::unbox_oneof_in)); `"."` matches
/// every message. A leading dot is added if missing and trailing dots
/// are trimmed. An empty path is warned about and ignored so `"."`
/// remains the only catch-all spelling.
///
/// A rule covers the message it names **and every message nested inside
/// it**; a rule naming a nested message does not cover its enclosing
/// message. Rules are enable-only, so this builder cannot exclude a
/// nested message from a rule that names its parent
/// ([`CodeGenConfig::preserve_unknown_fields_in`](buffa_codegen::CodeGenConfig::preserve_unknown_fields_in)
/// also accepts disabling entries, and the last matching entry wins).
/// Preservation is a property of each message *type*: a preserved
/// message's sub-messages keep their own unknown fields only if their
/// types are covered too.
///
/// Repeated calls accumulate. The call order relative to
/// [`preserve_unknown_fields`](Self::preserve_unknown_fields) does not
/// matter; the rules apply on top of whichever global value is in force
/// at [`compile`](Self::compile) time. They only change the outcome when
/// the global setting is off. A rule that matches no generated message
/// produces a `cargo:warning` from this build (surfaced via
/// [`CodeGenWarning`](buffa_codegen::CodeGenWarning)), since an inert
/// rule silently loses round-trip fidelity for the type it was meant to
/// keep.
///
/// A message that does not preserve unknown fields has no
/// `__buffa_unknown_fields` field, and so also loses everything built on
/// it: the `ExtensionSet` impl (`extension()` / `set_extension()` /
/// `has_extension()`), `ReflectMessage::unknown_fields`, extension
/// round-tripping through textproto, and `[ext]` keys in JSON.
///
/// ```rust,ignore
/// buffa_build::Config::new()
/// .preserve_unknown_fields(false)
/// .preserve_unknown_fields_in(&[".wa.CallLogRecord", ".wa.SyncdMutation"])
/// ```
#[must_use]
pub fn preserve_unknown_fields_in(mut self, paths: &[impl AsRef<str>]) -> Self {
for raw in paths.iter().map(AsRef::as_ref) {
let normalized = normalize_override_path(raw);
if normalized.is_empty() {
println!(
"cargo:warning=buffa: preserve_unknown_fields_in path '{raw}' \
normalizes to empty and will be ignored"
);
continue;
}
self.codegen_config
.preserve_unknown_fields_in
.push((normalized, true));
}
self
}
/// Make generated JSON deserializers reject unknown keys instead of
/// ignoring them (default: `false`, unknown keys are ignored).
///
/// Strictness is fixed in the generated type: code that uses the type
/// cannot switch it per call or per process. To be strict for selected
/// messages only, use
/// [`deny_unknown_json_fields_in`](Self::deny_unknown_json_fields_in).
///
/// With [`generate_json`](Self::generate_json) off there are no JSON
/// deserializers, so the option changes nothing and the build emits a
/// `cargo:warning` saying so.
///
/// The guide's "Unknown fields in JSON" section covers the error a
/// rejected key produces, how `"[pkg.ext]"` extension keys are treated,
/// and what to weigh before enabling this for every message.
#[must_use]
pub fn deny_unknown_json_fields(mut self, enabled: bool) -> Self {
self.codegen_config.deny_unknown_json_fields = enabled;
self
}
/// Reject unknown JSON fields for matching messages, on top of the global
/// [`deny_unknown_json_fields`](Self::deny_unknown_json_fields) setting.
///
/// Each path is a fully-qualified proto path prefix, e.g. `".demo.Config"`
/// for one message or `".demo"` for a package (same matching as
/// [`preserve_unknown_fields_in`](Self::preserve_unknown_fields_in));
/// `"."` matches every message. A leading dot is added if missing and
/// trailing dots are trimmed. An empty path is warned about and ignored so
/// `"."` remains the only catch-all spelling.
///
/// A rule covers the message it names **and every message nested inside
/// it**; a rule naming a nested message does not cover its enclosing
/// message. Strictness is a property of each message *type*: a strict
/// message's sub-messages reject unknown keys only if their types are
/// covered too.
///
/// Rules only enable, so this builder cannot exempt a message. With the
/// global flag on, every message is already strict and these rules add
/// nothing; to be strict everywhere except a few messages, leave the
/// global flag off and list the strict packages here.
/// (`buffa_codegen::CodeGenConfig` accepts disabling entries; neither
/// this builder nor the plugin exposes them.) With
/// [`generate_json`](Self::generate_json) off the rules change nothing,
/// and the build warns as it does for the global flag.
///
/// Repeated calls accumulate. A rule that matches no generated message
/// produces a `cargo:warning` from this build (surfaced via
/// [`CodeGenWarning`](buffa_codegen::CodeGenWarning)), since an inert rule
/// leaves the message silently ignoring the keys it was meant to reject.
///
/// ```rust,ignore
/// buffa_build::Config::new()
/// .generate_json(true)
/// .deny_unknown_json_fields_in(&[".demo.DeviceConfig"])
/// ```
#[must_use]
pub fn deny_unknown_json_fields_in(mut self, paths: &[impl AsRef<str>]) -> Self {
for raw in paths.iter().map(AsRef::as_ref) {
let normalized = normalize_override_path(raw);
if normalized.is_empty() {
println!(
"cargo:warning=buffa: deny_unknown_json_fields_in path '{raw}' \
normalizes to empty and will be ignored"
);
continue;
}
self.codegen_config
.deny_unknown_json_fields_in
.push((normalized, true));
}
self
}
/// Apply a path-scoped editions [`FeatureOverride`] to the compiled
/// descriptors before generation.
///
/// This is buffa's mechanism for integrators who must work with protos
/// they cannot modify: editions unification models proto2 and proto3 as
/// editions with fixed feature defaults, and an override behaves as if
/// the proto had been migrated to editions with that feature set at the
/// matched paths. The supported overrides are the [`FeatureOverride`]
/// variants — each is admitted only once buffa's codegen, runtime, and
/// validation handle the descriptor states it can create. Overrides
/// never change the wire format.
///
/// `path` is a fully-qualified proto path prefix. A rule may name a type
/// (for example, `".my.pkg.Status"`), a field
/// (`".my.pkg.Response.status"`), a package/message prefix, or `"."` for
/// everything the override targets. A leading dot is added if missing.
/// Map enum values match the outer map field path; oneof enum variants
/// match the direct field path. An empty path is warned about and
/// ignored so `"."` remains the only global opt-in spelling. (The
/// `protoc-gen-reallyme-buffa` plugin's `override_feature_in=` option rejects
/// empty paths with a hard error instead: a stray build-script entry
/// shouldn't fail the build, but plugin options are usually
/// machine-assembled, where an empty value is a bug.)
///
/// Repeated calls accumulate; rule order does not matter. A rule that
/// matches nothing produces a `cargo:warning` from this build (surfaced
/// via [`CodeGenWarning`](buffa_codegen::CodeGenWarning)), since an
/// inert rule silently leaves the affected paths on the semantics the
/// override exists to change.
///
/// Under reflection, the embedded descriptor pool carries the injected
/// features, so runtime reflection and descriptor-driven dynamic JSON
/// stay consistent with the generated types for both enum-scoped and
/// field-scoped rules. A field-scoped injection is buffa-specific,
/// though: other runtimes reading the exported descriptor set ignore it.
/// See [`FeatureOverride::EnumType`] for how the two scopes differ.
#[must_use]
pub fn override_feature_in(mut self, path: impl AsRef<str>, feature: FeatureOverride) -> Self {
let raw = path.as_ref();
let normalized = normalize_override_path(raw);
if normalized.is_empty() {
// Neutral wording: this also fires for the `open_enums_in` sugar,
// so the message must not name a method the caller didn't invoke.
println!(
"cargo:warning=buffa: feature override path '{raw}' normalizes to empty and will be ignored"
);
return self;
}
self.codegen_config
.feature_overrides
.push((normalized, feature));
self
}
/// Treat selected closed enums (or closed enum fields) as open in the
/// generated representation — shorthand for
/// [`override_feature_in(path, FeatureOverride::EnumType(EnumTypeOverride::Open))`](Self::override_feature_in)
/// applied to each path.
///
/// Matching closed enum fields generate as `EnumValue<E>` instead of `E`,
/// so unknown wire values are directly visible as `EnumValue::Unknown(n)`.
/// This is an opt-in migration / interop mode: it deliberately changes
/// closed-enum presence behavior for matching fields, making an unknown
/// value read as present instead of unset with the raw value represented
/// through unknown fields. An enum-type rule opens the enum itself, so
/// every field referencing it is affected; a field rule opens just that
/// field, leaving the enum's own declared openness unchanged. Both are
/// honored by buffa's descriptor-driven codecs, which resolve openness
/// per field. Prefer enum-type rules when the descriptor set leaves the
/// process: a field-level `enum_type` is not a spec-valid editions
/// feature, so other runtimes reading the exported set ignore it. That
/// preference does not help for an enum reached through `extern_path` —
/// its descriptor is not in the compiled set to mutate, so even an
/// enum-type rule is carried as a field-level override. Path grammar,
/// accumulation, and inert-rule warnings are as described on
/// [`override_feature_in`](Self::override_feature_in).
#[must_use]
pub fn open_enums_in(mut self, paths: &[impl AsRef<str>]) -> Self {
for path in paths {
self = self.override_feature_in(
path.as_ref(),
FeatureOverride::EnumType(EnumTypeOverride::Open),
);
}
self
}
/// Honor `features.utf8_validation = NONE` by emitting `Vec<u8>` / `&[u8]`
/// for such string fields instead of `String` / `&str` (default: false).
///
/// When disabled (the default), all string fields map to `String` and
/// UTF-8 is validated on decode — stricter than proto2 requires, but
/// ergonomic and safe.
///
/// When enabled, string fields with `utf8_validation = NONE` become
/// `Vec<u8>` / `&[u8]`. Decode skips validation; the caller chooses
/// 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.
///
/// **Note for proto2 users**: proto2's default is `utf8_validation = NONE`,
/// so enabling this turns ALL proto2 string fields into `Vec<u8>`. Use
/// only for new code or when profiling identifies UTF-8 validation as a
/// bottleneck (it can be 10%+ of decode CPU for string-heavy messages).
///
/// **JSON note**: fields normalized to bytes serialize as base64 in JSON
/// (the proto3 JSON encoding for `bytes`). Keep strict mapping disabled
/// for fields that need JSON string interop with other implementations.
///
/// **Interaction with [`use_bytes_type`]**: when both are enabled,
/// `map<bytes, bytes>` values stay `Vec<u8>` (the bytes-keyed JSON helper
/// is concrete `HashMap<Vec<u8>, Vec<u8>>`). All other `bytes` shapes —
/// singular / optional / repeated / oneof / `map<non-bytes, bytes>` —
/// still become `bytes::Bytes`. The asymmetry is documented; if you hit
/// it, see issue #76.
///
/// [`use_bytes_type`]: Self::use_bytes_type
#[must_use]
pub fn strict_utf8_mapping(mut self, enabled: bool) -> Self {
self.codegen_config.strict_utf8_mapping = enabled;
self
}
/// Permit `option message_set_wire_format = true` on input messages.
///
/// MessageSet is a legacy Google-internal wire format. Default: `false`
/// (such messages produce a codegen error). Set to `true` only when
/// compiling protos that interoperate with old Google-internal services.
#[must_use]
pub fn allow_message_set(mut self, enabled: bool) -> Self {
self.codegen_config.allow_message_set = enabled;
self
}
/// Declare an external type path mapping.
///
/// The matched types reference the specified Rust path instead of being
/// generated. This allows shared proto packages to be compiled once in a
/// dedicated crate and referenced from others.
///
/// `proto_path` is a fully-qualified protobuf path — either a **package**
/// (`".my.common"`, mapping every type under it to a Rust module root) or a
/// single **type FQN** (`".google.protobuf.Timestamp"`, mapping just that
/// type, the prost/tonic idiom). The leading dot is optional and is added
/// automatically. As in prost, the most specific entry wins: an exact type
/// FQN beats a covering package prefix, which in turn beats a shorter
/// prefix.
///
/// `rust_path` is where the type(s) are accessible — a module root for a
/// package mapping (e.g. `"::common_protos"`) or a full type path for a
/// per-type mapping (e.g. `"::pbjson_types::Timestamp"`). It must be an
/// absolute path (starting with `::` or `crate::`); any other value is
/// emitted into the generated code verbatim and will fail to resolve there.
///
/// **Nested types** inherit an enclosing message's per-type override:
/// mapping `.my.pkg.Outer` to `::ext::Outer` resolves `.my.pkg.Outer.Inner`
/// to `::ext::outer::Inner` — the override's parent module plus buffa's
/// usual `snake_case(MessageName)` nested-types module (snake case of the
/// *proto* message name, regardless of the override's final segment). This
/// matches the layout of another buffa-generated crate; for a target crate
/// laid out differently, add explicit per-type entries for the nested types
/// as well.
///
/// # Limitations
///
/// An extern type that is referenced by a generated **view** must map to
/// another buffa-generated crate — the view path is composed as
/// `<rust_path_root>::__buffa::view::…`, which a non-buffa crate (e.g.
/// `pbjson_types`) does not provide. Map per-type to a buffa crate, or
/// disable views ([`generate_views(false)`](Self::generate_views)), for
/// such types.
///
/// 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.
///
/// `proto_path` is `.` or a dotted protobuf package or type name. The
/// leading dot is optional and one trailing dot is ignored;
/// [`compile`](Self::compile) returns an error for a name with an empty
/// segment (`my..common`) or a segment that is not a protobuf identifier.
///
/// Other misconfigurations (a typo'd FQN target, a non-absolute
/// `rust_path`, or a view-referenced type mapped to a non-buffa crate)
/// are not diagnosed at generation time; they surface as an
/// unresolved-path error when the generated code is compiled.
///
/// # Example
///
/// ```rust,ignore
/// buffa_build::Config::new()
/// // Whole-package mapping.
/// .extern_path(".my.common", "::common_protos")
/// // Per-type mapping (issue #111) — overrides the package prefix for
/// // just this type.
/// .extern_path(".google.protobuf.Timestamp", "::common_protos::well_known::Timestamp")
/// .files(&["proto/my_service.proto"])
/// .includes(&["proto/"])
/// .compile()
/// .unwrap();
/// ```
#[must_use]
pub fn extern_path(
mut self,
proto_path: impl Into<String>,
rust_path: impl Into<String>,
) -> Self {
// Stored as given: `compile` validates the name and normalizes it to
// the fully-qualified form (".my.package" for "my.package"), so its
// error can quote what the caller wrote.
self.codegen_config
.extern_paths
.push((proto_path.into(), rust_path.into()));
self
}
/// Exclude a proto package from code generation.
///
/// `package` is the proto package to exclude (e.g. `"buf.validate"`,
/// `".gnostic.openapi.v3"`). A leading dot is optional and stripped
/// automatically. The package and all of its sub-packages are excluded:
/// `"buf.validate"` drops 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 through directory globbing, but you do not want Rust types
/// generated for those packages. Their descriptors remain available for
/// cross-package type resolution; only code generation is skipped.
///
/// **Warning**: if any kept file references an excluded package as a field
/// type, the generated code will contain dangling `super::…::Type` paths
/// that fail to compile; the build emits a `cargo:warning` naming the
/// file, message, and field before that happens. Pair `exclude_package` with
/// [`extern_path`](Self::extern_path) to map the excluded types to an
/// external crate, or do not list those `.proto` files in
/// [`files`](Self::files).
///
/// This method can be called multiple times to exclude multiple packages.
///
/// # Validation
///
/// [`compile`](Self::compile) returns an error, before running `protoc`, if
/// `package` is empty or contains invalid components (empty segments,
/// consecutive dots). A single leading dot is allowed and stripped.
///
/// # Example
///
/// ```rust,ignore
/// buffa_build::Config::new()
/// .exclude_package("buf.validate")
/// .exclude_package(".gnostic.openapi.v3")
/// .files(&["proto/my_service.proto"])
/// .includes(&["proto/", "vendor/"])
/// .compile()
/// .unwrap();
/// ```
#[must_use]
pub fn exclude_package(mut self, package: impl Into<String>) -> Self {
// Stored raw. `compile()` rejects malformed entries up front, and
// `generate_with_diagnostics` strips the optional leading dot.
self.codegen_config.exclude_packages.push(package.into());
self
}
/// Configure `bytes` fields to use `bytes::Bytes` instead of `Vec<u8>`.
///
/// Each path is a fully-qualified proto path prefix. Use `"."` to apply
/// to all bytes fields, or specify individual field paths like
/// `".my.pkg.MyMessage.data"`. Path normalization and the warning for a
/// rule that matches nothing are as described on
/// [`bytes_type_in`](Self::bytes_type_in).
///
/// Applies uniformly to singular, optional, repeated, oneof, **and
/// `map<K, bytes>`** values — the map case lets `view → owned`
/// conversion participate in the `to_owned_from_source` zero-copy
/// `slice_ref` path. One carve-out: an effective `map<bytes, bytes>` keeps
/// `Vec<u8>` values (the JSON helper for that combination is concrete
/// `HashMap<Vec<u8>, Vec<u8>>`); every other shape becomes `Bytes`. A
/// `bytes` map key is only reachable when [`strict_utf8_mapping`] is enabled
/// *and* the `map<string, bytes>` field carries
/// `[features.utf8_validation = NONE]` on its key, which normalizes the
/// string key to `bytes` — `strict_utf8_mapping` alone does not trigger it.
///
/// A **custom** `bytes` representation
/// ([`bytes_type_custom`](Self::bytes_type_custom)) is honored for
/// `map<K, bytes>` values too, the same as the built-in `Bytes` — but a
/// custom map value (like a custom `repeated` element) must be a crate-local
/// type, since codegen emits its `ReflectElement` / `InspectElement` /
/// `ProtoElemJson` impls (the orphan rule forbids them for a foreign type).
/// A type listed with [`json_policy_type`](Self::json_policy_type) gets no
/// `ProtoElemJson` impl, so only vtable reflection or reflection with
/// message cleanup requires it to be local.
///
/// [`strict_utf8_mapping`]: Self::strict_utf8_mapping
///
/// # Example
///
/// ```rust,ignore
/// buffa_build::Config::new()
/// .use_bytes_type_in(&["."]) // all bytes fields use Bytes
/// .files(&["proto/my_service.proto"])
/// .includes(&["proto/"])
/// .compile()
/// .unwrap();
/// ```
#[must_use]
pub fn use_bytes_type_in(self, paths: &[impl AsRef<str>]) -> Self {
self.bytes_type_in(BytesRepr::Bytes, paths)
}
/// Use `bytes::Bytes` for all `bytes` fields in all messages.
///
/// This is a convenience for `.use_bytes_type_in(&["."])`. Use
/// [`use_bytes_type_in`] with specific proto paths if you only want `Bytes`
/// for certain fields. See that method for the path-matching semantics, the
/// `map<K, bytes>` rule, and the `map<bytes, bytes>` carve-out under
/// [`strict_utf8_mapping`].
///
/// [`use_bytes_type_in`]: Self::use_bytes_type_in
/// [`strict_utf8_mapping`]: Self::strict_utf8_mapping
#[must_use]
pub fn use_bytes_type(self) -> Self {
self.bytes_type(BytesRepr::Bytes)
}
/// Map `bytes` fields to a [`BytesRepr`] other than `Vec<u8>` for the given
/// proto path prefixes. The bytes counterpart to
/// [`string_type_in`](Self::string_type_in).
///
/// Each path is a fully-qualified proto path prefix: a field
/// (`".my.pkg.Msg.data"`), a message, a package, or `"."` for every field.
/// A leading dot is added to each path if missing, surrounding whitespace
/// and trailing dots are ignored, and a blank entry is skipped with a
/// `cargo:warning`.
///
/// A rule whose path does not match a field of any type in a generated
/// message produces a `cargo:warning`
/// ([`CodeGenWarning::FieldTypeRuleMatchedNothing`](buffa_codegen::CodeGenWarning::FieldTypeRuleMatchedNothing)).
/// A path that matches only fields of another type does not warn.
///
/// Rules accumulate and the **last** matching rule wins, so call the broad
/// [`bytes_type`](Self::bytes_type) *first*, then `bytes_type_in` for
/// narrower overrides. For [`BytesRepr::Custom`], the downstream crate must
/// depend on the crate providing the type (buffa does not re-export it).
/// Only the owned Rust type changes — the wire format is unchanged and view
/// types still borrow `&[u8]`.
#[must_use]
pub fn bytes_type_in(mut self, repr: BytesRepr, paths: &[impl AsRef<str>]) -> Self {
self.codegen_config.bytes_fields.extend(
field_rule_paths("bytes_type_in", paths)
.into_iter()
.map(|path| (path, repr.clone())),
);
self
}
/// Map every `bytes` field in all messages to the given [`BytesRepr`].
/// Convenience for `.bytes_type_in(repr, &["."])`; call before any
/// [`bytes_type_in`](Self::bytes_type_in) overrides (last matching rule
/// wins).
#[must_use]
pub fn bytes_type(mut self, repr: BytesRepr) -> Self {
self.codegen_config
.bytes_fields
.push((".".to_string(), repr));
self
}
/// Map the matching `bytes` fields to a custom type named by its
/// fully-qualified Rust path (e.g. `"::my_crate::MyBytes"`). The type must
/// satisfy `buffa::ProtoBytes`, and the downstream crate must depend on the
/// crate providing it. Shorthand for
/// [`bytes_type_in`](Self::bytes_type_in)`(BytesRepr::Custom(path), paths)`.
///
/// # Limitations
///
/// - A **foreign** custom type used as a `repeated` element — or a
/// `map<K, bytes>` value — fails to compile under JSON, vtable reflection
/// or reflection with message cleanup: codegen emits `ProtoElemJson` /
/// `ReflectElement` / `InspectElement` impls for it, which the orphan
/// rule forbids for a foreign type. Wrap it in a crate-local newtype, or use
/// [`emit_custom_type_impls(false)`](Self::emit_custom_type_impls) when
/// the defining crate supplies those integrations. Singular / optional /
/// oneof uses work directly. A type listed with
/// [`json_policy_type`](Self::json_policy_type) gets no `ProtoElemJson`
/// impl, so only vtable reflection or reflection with message cleanup
/// requires it to be local.
/// - A `Custom` rule **does** apply to `map<K, bytes>` values (honored like
/// the built-in [`BytesRepr::Bytes`]); only the `map<bytes, bytes>`
/// carve-out keeps `Vec<u8>` values.
/// - A `path` that is not a Rust type path like `crate::Name` (for
/// example `_`, `()` or `&'static [u8]`) is reported as a codegen error
/// from [`compile`](Self::compile). Associated-type projections and
/// parenthesized type paths are supported.
/// - A custom bytes type needs no native `arbitrary::Arbitrary` impl (a
/// generic builder handles it under `generate_arbitrary`).
#[must_use]
pub fn bytes_type_custom_in(self, path: &str, paths: &[impl AsRef<str>]) -> Self {
self.bytes_type_in(BytesRepr::Custom(path.to_string()), paths)
}
/// Map every `bytes` field to the given custom type path. Convenience for
/// `.bytes_type_custom_in(path, &["."])`; see it for the limitations
/// (foreign `repeated` elements, `map` values, path parsing).
#[must_use]
pub fn bytes_type_custom(self, path: &str) -> Self {
self.bytes_type(BytesRepr::Custom(path.to_string()))
}
/// Store the matching message-typed oneof variants inline instead of
/// wrapping them in `Box<T>`.
///
/// By default every message/group oneof variant is boxed so that recursive
/// types compile. For non-recursive variants the `Box` is pure overhead (an
/// allocation per construction); this opts the matching variants out.
/// This affects the owned message enum only — view oneof variants remain
/// boxed.
///
/// Each path is a fully-qualified proto variant path prefix, e.g.
/// `".my.pkg.MyMessage.body.small"` for one variant or `".my.pkg"` for a
/// package (same matching as [`use_bytes_type_in`](Self::use_bytes_type_in)).
/// Paths are normalized as for [`bytes_type_in`](Self::bytes_type_in). A
/// rule that matches no variant is not reported.
///
/// Recursive variants cannot be stored inline (the type would be
/// unsized). A rule that names a recursive variant *exactly* is rejected
/// at codegen time; a broader prefix rule silently keeps recursive
/// variants boxed and inlines the rest. For example, with
/// `unbox_oneof_in(&[".my.pkg.Node"])`, a self-referential
/// `Node.kind.child` variant stays boxed while `Node`'s other message
/// variants become inline.
#[must_use]
pub fn unbox_oneof_in(mut self, paths: &[impl AsRef<str>]) -> Self {
self.codegen_config
.unboxed_oneof_fields
// The exact-path recursion error compares against the normalized
// form.
.extend(field_rule_paths("unbox_oneof_in", paths));
self
}
/// Store every non-recursive message-typed oneof variant inline instead of
/// boxing it. Convenience for `.unbox_oneof_in(&["."])`; recursive
/// variants stay boxed.
#[must_use]
pub fn unbox_oneof(mut self) -> Self {
self.codegen_config
.unboxed_oneof_fields
.push(".".to_string());
self
}
/// Map `string` fields to a [`StringRepr`] other than `String` for the
/// given proto path prefixes. The string counterpart to
/// [`use_bytes_type_in`](Self::use_bytes_type_in).
///
/// Each path is a fully-qualified proto path prefix (e.g.
/// `".my.pkg.MyMessage.name"` for one field, `".my.pkg"` for a package).
///
/// Rules accumulate and the **last** matching rule wins. Order therefore
/// matters: call [`string_type`](Self::string_type) (the broad default)
/// *first*, then `string_type_in` for narrower overrides — a broad rule
/// added after a specific one will shadow it.
///
/// For [`StringRepr::Custom`], the type must implement `buffa::ProtoString`,
/// and the downstream crate must depend on the crate providing it (buffa does
/// not re-export it). A foreign type cannot implement `ProtoString` directly
/// (orphan rule) — point at a local newtype, or the `buffa-smolstr` crate for
/// `smol_str::SmolStr`.
///
/// Only the owned Rust type changes: the wire format is unchanged and view
/// types still borrow `&str`. A rule that matches a `map` field applies to
/// its `string` key and its `string` value.
///
/// Path normalization and the warning for a rule that matches nothing are
/// as described on [`bytes_type_in`](Self::bytes_type_in).
///
/// # Example
///
/// ```rust,ignore
/// buffa_build::Config::new()
/// .string_type_custom("::buffa_smolstr::SmolStr") // broad default first
/// .string_type_custom_in("::my_crate::CompactStr", &[".my.pkg.Msg.body"]) // narrow override
/// .files(&["proto/my_service.proto"])
/// .includes(&["proto/"])
/// .compile()
/// .unwrap();
/// ```
#[must_use]
pub fn string_type_in(mut self, repr: StringRepr, paths: &[impl AsRef<str>]) -> Self {
self.codegen_config.string_fields.extend(
field_rule_paths("string_type_in", paths)
.into_iter()
.map(|path| (path, repr.clone())),
);
self
}
/// Map every `string` field in all messages to the given [`StringRepr`].
///
/// Convenience for `.string_type_in(repr, &["."])`. Call this *before* any
/// [`string_type_in`](Self::string_type_in) overrides, since the last
/// matching rule wins (a `"."` rule added later shadows earlier specific
/// rules). The rule also covers the `string` keys and values of `map`
/// fields.
#[must_use]
pub fn string_type(mut self, repr: StringRepr) -> Self {
self.codegen_config
.string_fields
.push((".".to_string(), repr));
self
}
/// Map the matching `string` fields to a custom type that implements
/// `buffa::ProtoString`, named by its fully-qualified Rust path (e.g.
/// `"::buffa_smolstr::SmolStr"`, or a local newtype — a foreign type cannot
/// implement the trait directly). The downstream crate must depend on the
/// crate providing it. Shorthand for
/// [`string_type_in`](Self::string_type_in)`(StringRepr::Custom(path), paths)`.
///
/// # Limitations
///
/// - Under vtable reflection ([`reflect_mode`](Self::reflect_mode) with
/// `ReflectMode::VTable`), or any reflection with message cleanup, a
/// **foreign** custom type used as a `repeated` element or as a `map` key
/// or value fails to compile: codegen emits a `ReflectElement`,
/// `InspectElement` or `ReflectMapKey` impl for it, which the orphan rule
/// forbids for a foreign type. Wrap it in a crate-local newtype, or use
/// [`emit_custom_type_impls(false)`](Self::emit_custom_type_impls) when
/// the defining crate supplies those integrations. Singular / optional /
/// oneof uses work directly.
/// - **JSON of a custom string with explicit presence (proto3 or proto2
/// `optional`, and the edition 2023 default), in a `repeated` field, in
/// a oneof, or in a `map`,** serializes through the type's own `serde`
/// impls, so such a type must implement `Serialize` / `Deserialize`. A
/// `buffa-remote-derive` newtype gets them from
/// `#[buffa(remote = ..., serde)]`; any other type derives them (an
/// external type enables its `serde` feature). A singular field with
/// implicit presence, or a proto2 `required` field, uses the
/// `proto_string` with-module and needs no `serde` impl, and so does a
/// type listed with [`json_policy_type`](Self::json_policy_type), whose
/// JSON goes through its policy in every generated JSON position.
/// - A custom type used as a `map` key must implement `Hash + Eq` for the
/// default `HashMap` container, or `Ord` for `BTreeMap`.
/// - A `path` that is not a Rust type path like `crate::Name` (for
/// example `_`, `()` or `&'static [u8]`) is reported as a codegen error
/// from [`compile`](Self::compile). Associated-type projections and
/// parenthesized type paths are supported.
/// - A custom string type needs no native `arbitrary::Arbitrary` impl (a
/// generic builder handles it under `generate_arbitrary`, as a `map` key
/// or value too).
#[must_use]
pub fn string_type_custom_in(self, path: &str, paths: &[impl AsRef<str>]) -> Self {
self.string_type_in(StringRepr::Custom(path.to_string()), paths)
}
/// Route the protobuf JSON of a custom `bytes` or `string` representation
/// through its `buffa::json_helpers::ProtoBytesJson` or `ProtoStringJson`
/// impl.
///
/// `path` names the type exactly as its
/// [`bytes_type_custom_in`](Self::bytes_type_custom_in) or
/// [`string_type_custom_in`](Self::string_type_custom_in) rule does
/// (whitespace aside). Every field of that type then serializes and
/// deserializes through the policy in the generated `serde` impls:
/// singular, optional, repeated and oneof fields, `map` keys and values,
/// and the matching fields of generated views, lazy views and owned views.
/// The type's own `serde` impls are not consulted.
/// Generated code implements no JSON trait for the type (repeated elements
/// and `map` values go through buffa's policy with-modules). With JSON
/// alone, the type may therefore be defined, together with its
/// representation and policy impls, in another crate, and separate
/// `compile()` runs into one crate may share it. With vtable reflection,
/// or reflection with message cleanup, its `repeated` and `map` uses still
/// get per-run element impls, so there it must be crate-local and
/// generated in one run (or use
/// [`emit_custom_type_impls(false)`](Self::emit_custom_type_impls)). Call
/// it once per type, in every `Config` that generates a field of the type:
/// a run that does not list it never calls the policy (bytes fields become
/// plain base64; string fields use the type's own `serde` impls). Unlisted
/// custom types keep their existing JSON behavior.
///
/// A policy shapes only the generated JSON and is not a confidentiality
/// boundary. Binary encoding, generated text format and descriptor-driven
/// reflection never call it: JSON produced or read through `DynamicMessage`
/// (including a message converted with `ReflectMessage::to_dynamic`, or with
/// `DynamicMessage::try_from_message`, which works whether or not
/// reflection is generated) encodes the field as standard base64 or a
/// plain string, so a policy that refuses export does not stop it and its
/// import checks do not run.
///
/// # Limitations
///
/// - The type must implement the policy trait; a missing impl is a
/// compile error in the generated code, naming the trait.
/// - A listed `string` type used as the key of a `map` with enum values
/// is a codegen error from [`compile`](Self::compile).
/// - A listed `string` type used as a `map` key must have a policy that
/// round-trips, and so is injective (see the `ProtoStringJson` contract):
/// otherwise import loses or alters entries. This is not checked.
/// - A type that no effective representation rule selects is an error.
/// Binding and spelling errors remain errors with JSON disabled. A valid
/// listed type while [`generate_json`](Self::generate_json) is off
/// produces a `cargo:warning` because its policy is inactive.
/// - With JSON and reflection both on
/// ([`generate_reflection`](Self::generate_reflection), or any
/// [`reflect_mode`](Self::reflect_mode) other than off), listing any type
/// produces one `cargo:warning` per `compile()` that reflective JSON
/// bypasses the policy. It is a standing reminder, not a check of your
/// schema, and buffa-build always prints it.
#[must_use]
pub fn json_policy_type(mut self, path: &str) -> Self {
self.codegen_config
.json_policy_types
.push(path.trim().to_string());
self
}
/// Control emission of custom bytes/string element integration impls.
///
/// Set this to `false` when shared representation types provide their
/// `ProtoElemJson`, `ReflectElement`, `ReflectMapKey` and `InspectElement` implementations in
/// their defining crate. A type listed with
/// [`json_policy_type`](Self::json_policy_type) needs no `ProtoElemJson`.
/// This permits foreign types and multiple generation calls without
/// orphan-rule or duplicate-impl errors. Missing traits fail
/// compilation; JSON policy selection is still required separately.
#[must_use]
pub fn emit_custom_type_impls(mut self, enabled: bool) -> Self {
self.codegen_config.emit_custom_type_impls = enabled;
self
}
/// Permit global message selectors absent from a scoped generation request.
/// Unmatched selectors still warn. Validate the complete project with this
/// disabled to catch misspelled cleanup or view-export rules as errors.
#[must_use]
pub fn allow_unmatched_message_rules(mut self, enabled: bool) -> Self {
self.codegen_config.allow_unmatched_message_rules = enabled;
self
}
/// Map every `string` field to the given custom type path. Convenience for
/// `.string_type_custom_in(path, &["."])`; see it for the limitations.
#[must_use]
pub fn string_type_custom(self, path: &str) -> Self {
self.string_type(StringRepr::Custom(path.to_string()))
}
/// Map the matching `map` fields to a [`MapRepr`] other than the default
/// `HashMap`. Rules are matched with proto-segment-aware prefix logic; the
/// **last** matching rule wins, so add a broad rule first and narrower
/// overrides after.
///
/// Path normalization and the warning for a rule that matches nothing are
/// as described on [`bytes_type_in`](Self::bytes_type_in).
///
/// Use [`MapRepr::BTreeMap`] for the buffa-provided `BTreeMap` (deterministic
/// key order, no extra dependency, no consumer code), or
/// [`MapRepr::Custom`] for a crate-local newtype that implements
/// `buffa::map_codec::MapStorage`.
///
/// Only the owned collection changes: the wire format is unchanged and view
/// types are unaffected.
///
/// # Example
///
/// ```rust,ignore
/// buffa_build::Config::new()
/// .map_type(buffa_build::MapRepr::BTreeMap) // broad default
/// .map_type_in(buffa_build::MapRepr::HashMap, &[".my.pkg.Msg.cache"]) // narrow override
/// .compile()
/// .unwrap();
/// ```
#[must_use]
pub fn map_type_in(mut self, repr: MapRepr, paths: &[impl AsRef<str>]) -> Self {
self.codegen_config.map_fields.extend(
field_rule_paths("map_type_in", paths)
.into_iter()
.map(|path| (path, repr.clone())),
);
self
}
/// Map every `map` field in all messages to the given [`MapRepr`].
/// Convenience for `.map_type_in(repr, &["."])`. Call this *before* any
/// [`map_type_in`](Self::map_type_in) overrides, since the last matching
/// rule wins.
#[must_use]
pub fn map_type(mut self, repr: MapRepr) -> Self {
self.codegen_config.map_fields.push((".".to_string(), repr));
self
}
/// Encode map entries as prost does: leave an entry's key or value out
/// when it holds the default (default: false, both are always written, as
/// the C++ and Java runtimes write them). Entries themselves are never
/// dropped.
///
/// For migrations from prost where stored or hashed map encodings must
/// not change. Decoding is unchanged: buffa, like every protobuf runtime,
/// reads both forms to the same map. One value does not survive the round
/// trip: a `-0.0` float value is left out, as prost leaves it out, and
/// decodes as `0.0`.
///
/// The default is what a missing field decodes to: zero, `false`, empty,
/// an open enum's 0 or a closed enum's first value. A message value is
/// left out when it encodes to nothing.
///
/// # Differences from prost
///
/// - prost leaves out a message value equal to its default. A value that
/// equals its default and still encodes a field, such as one with a
/// `required` field at its default or a float field holding `-0.0`, is
/// written here and not by prost.
/// - A value of an enum made open with
/// [`open_enums_in`](Self::open_enums_in) is left out at 0, which a
/// missing open enum decodes to, where prost leaves out the enum's
/// first value. The two differ only for an enum whose first value is
/// not 0. protoc rejects that as a map value, so the case can occur
/// only with a descriptor set that another tool built
/// ([`use_buf`](Self::use_buf), [`descriptor_set`](Self::descriptor_set)).
/// - The option covers the entries' bytes only. For a map with more than
/// one entry to encode identically, the entries must also come in the
/// same order: use [`map_type`](Self::map_type) with
/// [`MapRepr::BTreeMap`] where prost used `btree_map`.
///
/// # Scope
///
/// - The option applies to the owned, view and lazy view encoders of the
/// messages generated in this run. Each crate's types encode as that
/// crate was generated.
/// - `google.protobuf.Struct`, the well-known type with a map field,
/// comes from `buffa-types` and writes both fields, and so does
/// `DynamicMessage`.
/// - A lazy view keeps its singular and repeated message fields undecoded
/// and writes them as they were read, so map entries inside them keep
/// the encoding they arrived with. Every encoder writes entries kept as
/// unknown fields as they were read.
/// - 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 an error.
#[must_use]
pub fn map_entries_omit_defaults(mut self, enabled: bool) -> Self {
self.codegen_config.map_entries_omit_defaults = enabled;
self
}
/// Map the matching `map` fields to a custom collection implementing
/// `buffa::map_codec::MapStorage`, named by its fully-qualified Rust path
/// (e.g. `"::my_crate::OrderedMap"`). The path must **not** include the
/// `<K, V>` parameters — they are applied positionally. Shorthand for
/// [`map_type_in`](Self::map_type_in)`(MapRepr::Custom(path), paths)`.
///
/// # Limitations
///
/// - The path must name a **crate-local newtype** — a foreign map cannot
/// implement the buffa-owned reflection / serde traits (orphan rule).
/// Prefer the built-in [`MapRepr::BTreeMap`] unless you need a specific
/// foreign map.
/// - The newtype must implement `buffa::MapStorage` plus the derive /
/// `FromIterator` / `ReflectMap` / serde / `arbitrary` bounds documented on
/// `buffa::map_codec::MapStorage` (the canonical list). JSON and
/// `arbitrary` work for every proto map key/value type regardless of the
/// container.
/// - A path that does not parse as a Rust type is reported as a codegen
/// error from [`compile`](Self::compile).
#[must_use]
pub fn map_type_custom_in(self, path: &str, paths: &[impl AsRef<str>]) -> Self {
self.map_type_in(MapRepr::Custom(path.to_string()), paths)
}
/// Map every `map` field to the given custom collection path. Convenience
/// for `.map_type_custom_in(path, &["."])`; see it for the limitations (the
/// crate-local newtype requirement, the trait bounds, path parsing).
#[must_use]
pub fn map_type_custom(self, path: &str) -> Self {
self.map_type(MapRepr::Custom(path.to_string()))
}
/// Map the matching message fields to a [`PointerRepr`] other than the
/// default `Inline`. Rules are matched with proto-segment-aware prefix
/// logic; the **last** matching rule wins, so add a broad rule first and
/// narrower overrides after.
///
/// Paths are normalized as for [`bytes_type_in`](Self::bytes_type_in). A
/// rule that matches no field is not reported.
///
/// The default `Inline` is recursion-aware (recursive fields stay on
/// `Box`), so this knob is for opting *out*: `PointerRepr::Box` for large
/// or rarely-set submessages where reserving `size_of::<T>()` in the parent
/// is wasteful, or `PointerRepr::Custom` for a third-party pointer.
///
/// Applies to singular (and proto2 optional/required) message fields and to
/// **boxed** oneof message/group variants (matched by the variant's path).
/// A oneof variant opted into inline storage via [`unbox_oneof_in`](Self::unbox_oneof_in)
/// takes precedence and gets no pointer; recursive variants stay boxed and so
/// accept a custom pointer. Repeated message fields use a collection, not a
/// pointer. For [`PointerRepr::Custom`], the pointer must implement
/// `buffa::ProtoBox<T>` and be a crate-local newtype; the path is a
/// **template** with a `*` placeholder for the message type (e.g.
/// `"::my_crate::SmallBox<*>"`).
///
/// Only the in-memory pointer changes: the wire format is unchanged and view
/// types are unaffected.
#[must_use]
pub fn box_type_in(mut self, repr: PointerRepr, paths: &[impl AsRef<str>]) -> Self {
self.codegen_config
.pointer_fields
// The exact-path Inline recursion error compares against the
// normalized form.
.extend(
field_rule_paths("box_type_in", paths)
.into_iter()
.map(|path| (path, repr.clone())),
);
self
}
/// Choose how the binary `Message` implementation of every message is
/// generated (default: [`CodecStrategy::Unrolled`]).
///
/// On a large schema, [`CodecStrategy::Table`] makes the compiled code
/// about 40% smaller at `opt-level = "z"`, and it slows messages made of
/// many small fields; a message that cannot use it keeps its size.
/// [`CodecStrategy::Table`] says which messages stay unrolled and how a
/// table message behaves differently, and this build reports the messages
/// that stay unrolled in one `cargo:warning`. The option never changes the
/// wire format. The generated code needs Rust 1.77 or later, and `compile`
/// returns an error on an older compiler when a build script runs it (the
/// compiler is read from `RUSTC`).
///
/// Path-scoped rules for individual messages go in
/// [`codec_strategy_in`](Self::codec_strategy_in), and take precedence
/// over this setting whatever the call order.
///
/// ```rust,ignore
/// // build.rs
/// buffa_build::Config::new()
/// .files(&["proto/wa.proto"])
/// .includes(&["proto/"])
/// .codec_strategy(buffa_build::CodecStrategy::Table)
/// .codec_strategy_in(buffa_build::CodecStrategy::Unrolled, &[".wa.Message"])
/// .compile()?;
/// ```
#[must_use]
pub fn codec_strategy(mut self, strategy: CodecStrategy) -> Self {
self.codegen_config.codec_strategy = strategy;
self
}
/// Choose the [`CodecStrategy`] of the matching messages, on top of the
/// global [`codec_strategy`](Self::codec_strategy).
///
/// Each path is a fully-qualified proto path prefix, e.g. `".wa.Message"`
/// for one message or `".wa"` for a package (same matching as
/// [`preserve_unknown_fields_in`](Self::preserve_unknown_fields_in));
/// `"."` matches every message. A leading dot is added if missing,
/// trailing dots are trimmed, and a path that is empty after that prints a
/// `cargo:warning` and is ignored. A rule covers the message it names
/// **and every message nested inside it**. The **last** matching rule wins,
/// so call this after any broader rule.
///
/// A message selected for the table by a rule that cannot use it stays
/// unrolled and is counted in the warning, and it is an error if the rule
/// names the message by its exact path. A rule that matches no message
/// produces a warning.
///
/// A rule does not extend to the messages a message holds; see
/// [`CodecStrategy::Table`].
#[must_use]
pub fn codec_strategy_in(mut self, strategy: CodecStrategy, paths: &[impl AsRef<str>]) -> Self {
for raw in paths.iter().map(AsRef::as_ref) {
let normalized = normalize_override_path(raw);
if normalized.is_empty() {
println!(
"cargo:warning=buffa: codec_strategy_in path '{raw}' \
normalizes to empty and will be ignored"
);
continue;
}
self.codegen_config
.codec_strategy_in
.push((normalized, strategy));
}
self
}
/// Map every message field (and boxed oneof variant) to the given [`PointerRepr`].
/// Convenience for `.box_type_in(repr, &["."])`. Call before any
/// [`box_type_in`](Self::box_type_in) overrides, since the last matching
/// rule wins. `box_type(PointerRepr::Box)` restores the pre-0.9 boxed
/// default for every singular message field.
#[must_use]
pub fn box_type(mut self, repr: PointerRepr) -> Self {
self.codegen_config
.pointer_fields
.push((".".to_string(), repr));
self
}
/// Map the matching singular message fields to a custom pointer implementing
/// `buffa::ProtoBox<T>`, named by a Rust type-path **template** with a `*`
/// placeholder for the message type (e.g. `"::my_crate::SmallBox<*>"`).
/// Shorthand for
/// [`box_type_in`](Self::box_type_in)`(PointerRepr::Custom(template), paths)`.
///
/// # Limitations
///
/// - The template must contain at least one `*`; a template that omits it,
/// or whose substitution does not parse as a Rust type, is reported as a
/// codegen error from [`compile`](Self::compile).
/// - The pointer must be exclusively owned (`Rc`/`Arc` are unusable — the
/// decoder needs `DerefMut`) and a crate-local newtype (a foreign pointer
/// cannot implement the buffa-owned `ProtoBox`).
#[must_use]
pub fn box_type_custom_in(self, template: &str, paths: &[impl AsRef<str>]) -> Self {
self.box_type_in(PointerRepr::Custom(template.to_string()), paths)
}
/// Map every message field (and boxed oneof variant) to the given custom pointer template.
/// Convenience for `.box_type_custom_in(template, &["."])`; see it for the
/// limitations (the `*` placeholder, `Rc`/`Arc` exclusion, newtype rule).
#[must_use]
pub fn box_type_custom(self, template: &str) -> Self {
self.box_type(PointerRepr::Custom(template.to_string()))
}
/// Map the matching `repeated` fields to a [`RepeatedRepr`] other than the
/// default `Vec<T>`. Rules are matched with proto-segment-aware prefix
/// logic; the **last** matching rule wins, so add a broad rule first and
/// narrower overrides after. Applies only to `repeated` fields (not `map`).
///
/// Path normalization and the warning for a rule that matches nothing are
/// as described on [`bytes_type_in`](Self::bytes_type_in).
///
/// For [`RepeatedRepr::Custom`], the collection must implement
/// `buffa::ProtoList<T>`. Unlike the scalar `string_type_custom` /
/// `bytes_type_custom` knobs (which take a *complete* type path), this path
/// is a **template** with a `*` placeholder for the element type. Existing
/// `ProtoList` implementations work through aliases and associated types.
/// If the defining crate provides no implementation, use a crate-local
/// newtype to satisfy the orphan rule. See [`RepeatedRepr::Custom`] for
/// the bounds required by JSON, reflection and arbitrary generation.
///
/// Only the owned collection changes: the wire format is unchanged and view
/// types still borrow `&[T]`.
///
/// # Example
///
/// ```rust,ignore
/// // `SmallList<T>` is a crate-local newtype over smallvec::SmallVec that
/// // implements buffa::ProtoList (see the ProtoList docs for the template).
/// buffa_build::Config::new()
/// .repeated_type_custom("::my_crate::SmallList<*>") // broad default
/// .repeated_type_custom_in("::my_crate::SmallList8<*>", &[".my.pkg.Msg.tags"])
/// .compile()
/// .unwrap();
/// ```
#[must_use]
pub fn repeated_type_in(mut self, repr: RepeatedRepr, paths: &[impl AsRef<str>]) -> Self {
self.codegen_config.repeated_fields.extend(
field_rule_paths("repeated_type_in", paths)
.into_iter()
.map(|path| (path, repr.clone())),
);
self
}
/// Map every `repeated` field in all messages to the given
/// [`RepeatedRepr`]. Convenience for `.repeated_type_in(repr, &["."])`.
/// Call this *before* any [`repeated_type_in`](Self::repeated_type_in)
/// overrides, since the last matching rule wins.
#[must_use]
pub fn repeated_type(mut self, repr: RepeatedRepr) -> Self {
self.codegen_config
.repeated_fields
.push((".".to_string(), repr));
self
}
/// Map the matching `repeated` fields to a custom collection implementing
/// `buffa::ProtoList<T>`, named by a Rust type-path **template** with a `*`
/// placeholder for the element type (e.g. `"::my_crate::SmallList<*>"`).
/// Note the asymmetry with the scalar `string_type_custom` /
/// `bytes_type_custom` knobs: those take a *complete* path, this takes a
/// `*`-template that wraps the element. Shorthand for
/// [`repeated_type_in`](Self::repeated_type_in)`(RepeatedRepr::Custom(template), paths)`.
///
/// # Limitations
///
/// - The template must contain at least one `*`; a template that omits it,
/// or whose substitution is not a Rust type path, is reported as a
/// codegen error from [`compile`](Self::compile).
/// - The resolved collection must implement `buffa::ProtoList<T>`. An
/// associated type resolving to `Vec<T>` already satisfies this; a
/// foreign collection without an implementation needs a crate-local
/// newtype to satisfy the orphan rule.
/// - Vtable reflection requires `ReflectList`; cleanup-profile borrowed
/// inspection requires `InspectList`. Ordinary bridge reflection needs
/// neither on the owned collection.
/// - JSON scalar, enum and policy helpers decode through `ProtoList<T>`
/// and the element's JSON traits, without requiring the collection's
/// `Deserialize`. Positions using ordinary serde instead require the
/// collection's `Serialize` / `Deserialize`. See [`RepeatedRepr::Custom`]
/// for the complete representation requirements and `buffa::ProtoList`
/// for a worked newtype example.
#[must_use]
pub fn repeated_type_custom_in(self, template: &str, paths: &[impl AsRef<str>]) -> Self {
self.repeated_type_in(RepeatedRepr::Custom(template.to_string()), paths)
}
/// Map every `repeated` field to the given custom collection template.
/// Convenience for `.repeated_type_custom_in(template, &["."])`; see it for
/// the limitations (the `*` placeholder, foreign reflection, the JSON /
/// `arbitrary` requirements).
#[must_use]
pub fn repeated_type_custom(self, template: &str) -> Self {
self.repeated_type(RepeatedRepr::Custom(template.to_string()))
}
/// Add a custom attribute to generated types (messages and enums)
/// matching a proto path prefix.
///
/// `path` is a fully-qualified proto path prefix: `"."` applies to all
/// types, `".my.pkg"` to types in that package, `".my.pkg.MyMessage"`
/// to a specific type. A leading `.` is auto-prepended if omitted; a
/// trailing `.` is trimmed. Prefix matching respects proto-segment
/// boundaries, so `".my.pk"` does not match `".my.pkg.Msg"`.
///
/// `attribute` is one or more outer Rust attributes, each written with
/// its `#[...]` (e.g., `"#[derive(serde::Serialize)]"`). Any other
/// string, such as `"serde(skip)"` or an empty one, makes
/// [`compile`](Self::compile) fail with
/// [`CodeGenError::InvalidCustomAttribute`](buffa_codegen::CodeGenError),
/// whether or not `path` matches a generated type.
///
/// Multiple calls accumulate in insertion order — all matching attributes
/// are emitted, and ordering is preserved in generated code.
///
/// Also applies to generated oneof enums when `path` matches
/// `".pkg.Msg.my_oneof"` (the oneof's fully-qualified path).
///
/// # Pitfalls
///
/// buffa already emits `#[derive(Clone, PartialEq)]` on messages and
/// `#[derive(Clone, PartialEq, Debug)]` on oneofs (oneofs with a
/// `[debug_redact = true]` variant get a generated `Debug` impl instead
/// of the `Debug` derive); adding a duplicate derive via
/// `type_attribute(".", "#[derive(Clone)]")` produces a compile error in
/// the generated code.
///
/// A custom `serde::Serialize` derive has two additional requirements:
/// messages must disable unknown-field preservation because
/// `UnknownFields` does not implement `serde::Serialize`, and the `json`
/// feature must be enabled for buffa's `EnumValue` and `MessageField`
/// serde implementations. Do not combine a custom derive with
/// [`generate_json(true)`](Self::generate_json), which already generates
/// the message's serde implementations.
///
/// # Example
///
/// ```rust,ignore
/// buffa_build::Config::new()
/// // `UnknownFields` does not implement `serde::Serialize`; with this
/// // off, unknown fields are dropped on decode.
/// .preserve_unknown_fields(false)
/// .type_attribute(".", "#[derive(serde::Serialize)]")
/// .type_attribute(".my.pkg.MyEnum", "#[derive(strum::EnumIter)]")
/// .files(&["proto/my_service.proto"])
/// .includes(&["proto/"])
/// .compile()
/// .unwrap();
/// ```
#[must_use]
pub fn type_attribute(mut self, path: impl Into<String>, attribute: impl Into<String>) -> Self {
self.codegen_config
.type_attributes
.push((normalize_attr_path(path.into()), attribute.into()));
self
}
/// Add a custom attribute to generated struct fields matching a proto
/// path prefix.
///
/// `path` is a fully-qualified proto field path (e.g.,
/// `".my.pkg.MyMessage.my_field"`). `"."` applies to all fields. A
/// leading `.` is auto-prepended if omitted; a trailing `.` is trimmed.
/// Prefix matching respects proto-segment boundaries.
///
/// Also applies to oneof variants when `path` matches
/// `".pkg.Msg.my_oneof.variant_name"`, but not to the struct field holding
/// the oneof; use
/// [`oneof_struct_field_attribute`](Self::oneof_struct_field_attribute) for
/// that.
///
/// `attribute` follows the rule given for
/// [`type_attribute`](Self::type_attribute): any string that is not one
/// or more `#[...]` attributes, an empty one included, makes
/// [`compile`](Self::compile) fail.
///
/// A `#[deprecated]` supplied here wins over the one codegen derives from
/// the field's `[deprecated = true]` option — rustc permits only one
/// `deprecated` attribute per item — so this is also how to attach a note
/// naming the replacement. Either source marks every generated way to
/// reach a message field: the `with_*` setter, the same field on the
/// views, its `OwnedView` accessor and, for a `required` field, the views'
/// `has_*` method. Those carry a bare `#[deprecated]`; the attribute given
/// here, with its note, stays on the owned struct's field. Either source
/// also makes the generated items that visit the field carry
/// `#[allow(deprecated)]`.
///
/// A `deprecated` inside `cfg_attr` counts too: it replaces the
/// option-derived marker on the owned field, and the setter and view
/// markers stay unconditional.
///
/// A oneof variant gets only the attribute given here. Its view variant is
/// unmarked and the generated impls that match on it are not guarded, so
/// put `#[allow(deprecated)]` on the `mod` that includes the generated
/// file.
///
/// # Example
///
/// ```rust,ignore
/// buffa_build::Config::new()
/// .field_attribute(".my.pkg.MyMessage.secret_key", "#[serde(skip)]")
/// .files(&["proto/my_service.proto"])
/// .includes(&["proto/"])
/// .compile()
/// .unwrap();
/// ```
#[must_use]
pub fn field_attribute(
mut self,
path: impl Into<String>,
attribute: impl Into<String>,
) -> Self {
self.codegen_config
.field_attributes
.push((normalize_attr_path(path.into()), attribute.into()));
self
}
/// Add a custom attribute to generated message structs only (not enums,
/// not oneof enums — those are reached by
/// [`enum_attribute`](Self::enum_attribute) and
/// [`oneof_attribute`](Self::oneof_attribute) respectively) matching a
/// proto path prefix.
///
/// Same path-matching semantics as [`type_attribute`](Self::type_attribute) —
/// leading `.` auto-prepended, trailing `.` trimmed, proto-segment-aware
/// prefix matching, accumulation in insertion order. Useful for
/// struct-only attributes like `#[serde(default)]`.
///
/// `attribute` follows the rule given for
/// [`type_attribute`](Self::type_attribute): any string that is not one
/// or more `#[...]` attributes, an empty one included, makes
/// [`compile`](Self::compile) fail.
///
/// # Example
///
/// ```rust,ignore
/// buffa_build::Config::new()
/// .message_attribute(".", "#[serde(default)]")
/// .files(&["proto/my_service.proto"])
/// .includes(&["proto/"])
/// .compile()
/// .unwrap();
/// ```
#[must_use]
pub fn message_attribute(
mut self,
path: impl Into<String>,
attribute: impl Into<String>,
) -> Self {
self.codegen_config
.message_attributes
.push((normalize_attr_path(path.into()), attribute.into()));
self
}
/// Add a custom attribute to generated enum types only (not message
/// structs, not oneof enums — those are reached by
/// [`type_attribute`](Self::type_attribute) on the oneof's path or by
/// [`oneof_attribute`](Self::oneof_attribute)) matching a proto path
/// prefix.
///
/// Same path-matching semantics as [`type_attribute`](Self::type_attribute) —
/// leading `.` auto-prepended, trailing `.` trimmed, proto-segment-aware
/// prefix matching, accumulation in insertion order. Useful when you want
/// to inject an attribute on every enum in a package without also matching
/// the (often more numerous) messages that share the path prefix — e.g.
/// `#[derive(strum::EnumIter)]`, which only makes sense on enums.
///
/// `attribute` follows the rule given for
/// [`type_attribute`](Self::type_attribute): any string that is not one
/// or more `#[...]` attributes, an empty one included, makes
/// [`compile`](Self::compile) fail.
///
/// # Example
///
/// ```rust,ignore
/// buffa_build::Config::new()
/// .enum_attribute(".my.pkg", "#[derive(strum::EnumIter)]")
/// .files(&["proto/my_service.proto"])
/// .includes(&["proto/"])
/// .compile()
/// .unwrap();
/// ```
#[must_use]
pub fn enum_attribute(mut self, path: impl Into<String>, attribute: impl Into<String>) -> Self {
self.codegen_config
.enum_attributes
.push((normalize_attr_path(path.into()), attribute.into()));
self
}
/// Add a custom attribute to generated oneof enums only (not message
/// structs, not regular enums) matching a proto path prefix.
///
/// Same path-matching semantics as [`type_attribute`](Self::type_attribute):
/// a leading `.` is auto-prepended, a trailing `.` is trimmed, prefixes
/// match on proto-path segments, and attributes accumulate in insertion
/// order. The match key is the oneof's fully-qualified path
/// (`.my.pkg.MyMessage.my_oneof`) — the whole-enum path has no variant
/// segment; to target a single variant's field, append `.variant_name`
/// and use [`field_attribute`](Self::field_attribute) instead, and for the
/// message struct's field holding the oneof, use
/// [`oneof_struct_field_attribute`](Self::oneof_struct_field_attribute).
/// `attribute` follows the rule given for
/// [`type_attribute`](Self::type_attribute): any string that is not one
/// or more `#[...]` attributes, an empty one included, makes
/// [`compile`](Self::compile) fail.
///
/// Useful when a oneof needs a different attribute set than the
/// surrounding types — for example to keep `#[derive(serde::Serialize)]`
/// on messages and oneofs while
/// [`enum_attribute`](Self::enum_attribute) gives the regular enums a
/// different serde derive.
///
/// Applies to the owned oneof enum only; the zero-copy view-of-oneof
/// enum receives no custom attributes (true of the whole attribute
/// family). For JSON serialization of both owned types and views, use
/// [`generate_json(true)`](Self::generate_json), which emits canonical
/// protobuf-JSON impls rather than derived ones.
///
/// # Pitfalls
///
/// Generated oneof enums already derive `Clone`, `PartialEq`, and
/// `Debug` (oneofs containing `[debug_redact = true]` fields replace the
/// `Debug` derive with a manual impl). Re-deriving any of these via
/// `oneof_attribute` produces a conflicting-implementation compile error
/// inside the generated code.
///
/// For the `serde::Serialize` requirements when the surrounding messages
/// also use a custom derive, see the [`type_attribute`](Self::type_attribute)
/// pitfalls: disable unknown-field preservation for messages and enable
/// the `json` feature for buffa's serde implementations. Do not combine
/// custom derives with [`generate_json(true)`](Self::generate_json).
///
/// # Example
///
/// ```rust,ignore
/// buffa_build::Config::new()
/// // one specific oneof; ".my.pkg" would match every oneof in the package
/// .oneof_attribute(".my.pkg.MyMessage.my_oneof", "#[derive(serde::Serialize)]")
/// .files(&["proto/my_service.proto"])
/// .includes(&["proto/"])
/// .compile()
/// .unwrap();
/// ```
#[must_use]
pub fn oneof_attribute(
mut self,
path: impl Into<String>,
attribute: impl Into<String>,
) -> Self {
self.codegen_config
.oneof_attributes
.push((normalize_attr_path(path.into()), attribute.into()));
self
}
/// Add a custom attribute to the message struct's field holding a oneof
/// (the `Option<OneofEnum>` member), not to the oneof's variants.
///
/// The match key is the oneof's fully-qualified path
/// (`.my.pkg.MyMessage.my_oneof`), with the same path-matching semantics
/// as [`type_attribute`](Self::type_attribute): `".my.pkg"` reaches the
/// oneof field of every message in the package, nested ones included.
/// Attributes accumulate in insertion order, after buffa's own attributes
/// on the field.
///
/// `attribute` follows the rule given for
/// [`type_attribute`](Self::type_attribute): any string that is not one
/// or more `#[...]` attributes, an empty one included, makes
/// [`compile`](Self::compile) fail.
///
/// A rule on a variant's path (`.my.pkg.MyMessage.my_oneof.variant_name`)
/// does not match the oneof, so it has no effect, and the build does not
/// warn about it. Variants take their attributes from
/// [`field_attribute`](Self::field_attribute).
///
/// Each of these lines of the generated code for a oneof takes its
/// attributes from a different method:
///
/// ```rust,ignore
/// pub struct Event {
/// // oneof_struct_field_attribute(".pkg.Event.payload", ..)
/// pub payload: Option<event::Payload>,
/// }
///
/// // oneof_attribute(".pkg.Event.payload", ..), or type_attribute on the same path
/// pub enum Payload {
/// // field_attribute(".pkg.Event.payload.text", ..)
/// Text(String),
/// }
/// ```
///
/// `field_attribute` on the oneof's path (`.pkg.Event.payload`) matches
/// the variants only, where an attribute
/// such as `#[serde(skip_serializing_if = "...")]` is rejected. prost-build
/// puts such a `field_attribute` on the struct field as well; use this
/// method for the struct field.
///
/// Applies to the owned message struct only; the view structs do not get
/// the attribute.
///
/// A `#[deprecated]` given here marks the owned struct's field only. The
/// same field on the view structs stays unmarked, so reading the oneof
/// through a view does not warn, unlike a field deprecated through
/// `field_attribute`. The generated items that visit the owned field
/// carry `#[allow(deprecated)]`.
///
/// # Pitfalls
///
/// With [`generate_json(true)`](Self::generate_json) the field already
/// carries buffa's `#[serde(flatten)]` for the derived `Serialize`, and
/// buffa generates the `Deserialize` impl of a message with a oneof
/// instead of deriving it. So a serde attribute given here changes the
/// owned message's `Serialize` output only: `Deserialize` and the views'
/// `Serialize` ignore it. A second `flatten` is a compile error in the
/// generated code. Serde attributes here are for a serde derive that you
/// attach yourself, with `generate_json` off.
///
/// With
/// [`gate_impls_on_crate_features(true)`](Self::gate_impls_on_crate_features)
/// buffa's serde derive is compiled only under the JSON feature. Write a
/// serde attribute for it as `#[cfg_attr(feature = "json", serde(...))]`,
/// with your JSON feature's name if you renamed it, so that it is compiled
/// under the same feature.
///
/// # Example
///
/// ```rust,ignore
/// buffa_build::Config::new()
/// // `UnknownFields` does not implement `serde::Serialize`. With this
/// // off, unknown fields are dropped on decode.
/// .preserve_unknown_fields(false)
/// .message_attribute(".my.pkg.MyMessage", "#[derive(serde::Serialize)]")
/// .oneof_attribute(".my.pkg.MyMessage.my_oneof", "#[derive(serde::Serialize)]")
/// .oneof_struct_field_attribute(
/// ".my.pkg.MyMessage.my_oneof",
/// "#[serde(skip_serializing_if = \"Option::is_none\")]",
/// )
/// .files(&["proto/my_service.proto"])
/// .includes(&["proto/"])
/// .compile()
/// .unwrap();
/// ```
#[must_use]
pub fn oneof_struct_field_attribute(
mut self,
path: impl Into<String>,
attribute: impl Into<String>,
) -> Self {
self.codegen_config
.oneof_struct_field_attributes
.push((normalize_attr_path(path.into()), attribute.into()));
self
}
/// Use `buf build` instead of `protoc` for descriptor generation.
///
/// `buf` is often easier to install and keep current than `protoc`
/// (which many distros pin to old versions). This mode is intended for
/// the **single-crate case**: a `buf.yaml` at the crate root defining
/// the module layout.
///
/// Requires `buf` on PATH and a `buf.yaml` at the crate root. The
/// [`includes()`](Self::includes) setting is ignored — buf resolves
/// imports via its own module configuration.
///
/// Each path given to [`files()`](Self::files) must be **relative to its
/// owning module's directory** (the `path:` value inside `buf.yaml`), not
/// the crate root where `buf.yaml` itself lives. buf strips the module
/// path when producing `FileDescriptorProto.name`, so for
/// `modules: [{path: proto}]` and a file on disk at
/// `proto/api/v1/service.proto`, the descriptor name is
/// `api/v1/service.proto` — that is what `.files()` must contain.
/// Multiple modules in one `buf.yaml` work fine; buf enforces that
/// module-relative names are unique across the workspace.
///
/// # Monorepo / multi-module setups
///
/// For a workspace-root `buf.yaml` with many modules, this mode is a
/// poor fit. Prefer running `buf generate` with the `protoc-gen-reallyme-buffa`
/// plugin and checking in the generated code, or use
/// [`descriptor_set()`](Self::descriptor_set) with the output of
/// `buf build --as-file-descriptor-set -o fds.binpb <module-path>`
/// run as a pre-build step.
///
/// # Example
///
/// ```rust,ignore
/// // buf.yaml (at crate root):
/// // version: v2
/// // modules:
/// // - path: proto
/// //
/// // build.rs:
/// buffa_build::Config::new()
/// .use_buf()
/// .files(&["api/v1/service.proto"]) // relative to module root
/// .compile()
/// .unwrap();
/// ```
#[must_use]
pub fn use_buf(mut self) -> Self {
self.descriptor_source = DescriptorSource::Buf;
self
}
/// Use a pre-compiled `FileDescriptorSet` binary file as input.
///
/// Skips invoking `protoc` or `buf` entirely. The file must contain a
/// serialized `google.protobuf.FileDescriptorSet` (as produced by
/// `protoc --descriptor_set_out` or `buf build --as-file-descriptor-set`).
///
/// When using this, `.files()` specifies which proto files in the
/// descriptor set to generate code for (matching by proto file name).
/// For in-memory input, use [`descriptor_set_bytes()`](Self::descriptor_set_bytes).
#[must_use]
pub fn descriptor_set(mut self, path: impl Into<PathBuf>) -> Self {
self.descriptor_source = DescriptorSource::Precompiled(path.into());
self
}
/// Use a serialized `google.protobuf.FileDescriptorSet` held in memory.
///
/// Use this when the build script produces the descriptor set itself, for
/// example with an in-process compiler such as `protox`.
/// [`compile()`](Self::compile) decodes the bytes and does not invoke
/// `protoc` or `buf`. This replaces any previously configured descriptor
/// source. Pass a slice as `bytes.to_vec()`.
///
/// [`files()`](Self::files) selects which proto files in the descriptor set
/// to generate, using their exact descriptor names (relative to the proto
/// source root). The set must also contain their transitive imports.
/// [`includes()`](Self::includes) is ignored.
///
/// # Rebuilds
///
/// Print a `cargo:rerun-if-changed` or `cargo:rerun-if-env-changed` line
/// for every input the bytes were built from. `buffa-build` cannot see
/// those inputs, and `compile()` always prints a `rerun-if-env-changed`
/// line of its own, which turns off Cargo's default of rerunning the build
/// script when any file in the package changes. Without your own lines, an
/// edited `.proto` file does not rerun the script, and the generated code
/// goes stale.
///
/// # Example
///
/// ```no_run
/// # fn compile_protos_in_process() -> Vec<u8> { Vec::new() }
/// # fn main() -> Result<(), Box<dyn std::error::Error>> {
/// let bytes: Vec<u8> = compile_protos_in_process();
/// println!("cargo:rerun-if-changed=proto");
/// buffa_build::Config::new()
/// .descriptor_set_bytes(bytes)
/// .files(&["api/v1/service.proto"])
/// .compile()?;
/// # Ok(())
/// # }
/// ```
#[must_use]
pub fn descriptor_set_bytes(mut self, bytes: Vec<u8>) -> Self {
self.descriptor_source = DescriptorSource::Bytes(bytes);
self
}
/// Generate a module-tree include file alongside the per-package `.rs`
/// files.
///
/// The include file contains nested `pub mod` declarations with
/// `include!()` directives that assemble the generated code into a
/// module hierarchy matching the protobuf package structure. Users can
/// then include this single file instead of manually creating the
/// module tree.
///
/// The form of the emitted `include!` directives depends on whether
/// [`out_dir`](Self::out_dir) was set:
///
/// - **Default (`$OUT_DIR`)**: emits
/// `include!(concat!(env!("OUT_DIR"), "/foo.rs"))`, for use from
/// `build.rs` via `include!(concat!(env!("OUT_DIR"), "/<name>"))`.
/// - **Explicit `out_dir`**: emits sibling-relative `include!("foo.rs")`,
/// for checking the generated code into the source tree and referencing
/// it as a module (e.g. `mod gen;`). The include file then has to sit in
/// `out_dir` itself: `name` must be a bare file name, and
/// [`compile`](Self::compile) rejects a name with a directory part.
///
/// With [`shared_descriptor_pool`](Self::shared_descriptor_pool), `name`
/// must be a bare file name in both modes. In `$OUT_DIR` mode without the
/// shared pool, `name` may have a directory part (`"nested/_include.rs"`),
/// and [`compile`](Self::compile) creates that directory.
///
/// # Example — `build.rs` / `$OUT_DIR`
///
/// ```rust,ignore
/// // build.rs
/// buffa_build::Config::new()
/// .files(&["proto/my_service.proto"])
/// .includes(&["proto/"])
/// .include_file("_include.rs")
/// .compile()
/// .unwrap();
///
/// // lib.rs
/// include!(concat!(env!("OUT_DIR"), "/_include.rs"));
/// ```
///
/// # Example — checked-in source
///
/// ```rust,ignore
/// // codegen.rs (run manually, not from build.rs)
/// buffa_build::Config::new()
/// .files(&["proto/my_service.proto"])
/// .includes(&["proto/"])
/// .out_dir("src/gen")
/// .include_file("mod.rs")
/// .compile()
/// .unwrap();
///
/// // lib.rs
/// mod gen;
/// ```
#[must_use]
pub fn include_file(mut self, name: impl Into<String>) -> Self {
self.include_file = Some(name.into());
self
}
/// Compile proto files and generate Rust source.
///
/// # Errors
///
/// Returns an error if:
/// - `OUT_DIR` is not set and no `out_dir` was configured
/// - [`shared_descriptor_pool`](Self::shared_descriptor_pool) is set
/// without reflection enabled, without
/// [`include_file`](Self::include_file), or with an `include_file`
/// that is not a bare file name or lacks a file-name stem
/// - an explicit [`out_dir`](Self::out_dir) is combined with an
/// [`include_file`](Self::include_file) that is not a bare file name
/// - `protoc` or `buf` cannot be found on `PATH` (when using those sources)
/// - the proto compiler exits with a non-zero status (syntax errors,
/// missing imports, etc.)
/// - a precompiled descriptor set file cannot be read
/// - the descriptor set bytes cannot be decoded as a `FileDescriptorSet`
/// - an [`extern_path`](Self::extern_path) proto name has an empty
/// segment or a segment that is not a protobuf identifier
/// - a custom attribute string, given to
/// [`type_attribute`](Self::type_attribute) or one of the five methods
/// beside it, is not one or more `#[...]` attributes
/// - code generation fails (e.g. unsupported proto feature), including a
/// [`codec_strategy_in`](Self::codec_strategy_in) rule that names by its
/// exact path a message that cannot use the table codec
/// - [`CodecStrategy::Table`] is requested and the compiler is older than
/// Rust 1.77
/// - the output directory cannot be created or written to
pub fn compile(mut self) -> Result<(), Box<dyn std::error::Error>> {
// Table code needs `offset_of!`, stable in Rust 1.77. Say so once here,
// and not once per field in the compiler's output.
let table_codec_requested = self.codegen_config.codec_strategy == CodecStrategy::Table
|| self
.codegen_config
.codec_strategy_in
.iter()
.any(|(_, strategy)| *strategy == CodecStrategy::Table);
// Outside a build script `RUSTC` is unset, and the toolchain that
// compiles the generated code is unknown, so it is not checked.
if table_codec_requested {
if let Some(minor) = rustc_minor_version() {
if minor < 77 {
return Err(format!(
"CodecStrategy::Table needs Rust 1.77 or later, and this build uses \
1.{minor}; use a newer compiler or select CodecStrategy::Unrolled"
)
.into());
}
}
}
// Reject malformed `exclude_package` entries before protoc runs; the
// codegen normalizes them again, but a typo should not cost a protoc
// invocation to surface.
for entry in &self.codegen_config.exclude_packages {
if let Err(e) = buffa_codegen::normalize_exclude_package(entry) {
return Err(format!("exclude_package {entry:?}: {e}").into());
}
}
// Same for `extern_path`: a name that can match no type would leave
// the mapping silently unused. The plugin applies the same function.
for (proto, _) in &mut self.codegen_config.extern_paths {
*proto = buffa_codegen::normalize_extern_path_proto_name(proto)?;
}
// Validate the shared-pool prerequisites before doing any work, and
// check reflection first so the error names the actually-missing
// prerequisite rather than a downstream one. `generate_reflection` is
// also enforced in `buffa-codegen`, but catching it here gives a
// buffa-build-shaped message.
let sidecar = if self.codegen_config.shared_descriptor_pool {
if !self.codegen_config.generate_reflection {
return Err("shared_descriptor_pool requires reflection to be enabled \
(call generate_reflection(true) or reflect_mode(...))"
.into());
}
// The shared `__buffa_fds` module is emitted into the include file
// at the tree root; without it the per-package delegations have
// nothing to resolve against.
let Some(include_name) = self.include_file.as_deref() else {
return Err("shared_descriptor_pool requires include_file to be set \
(the shared descriptor module is emitted into it)"
.into());
};
// The sidecar is named after the include file's stem; reject names
// without one ("", ".", "..") here rather than writing a stray
// misnamed sidecar before the include-file write fails. The stem
// is computed once here and reused when the sidecar is written.
let Some(stem) = Path::new(include_name).file_stem().and_then(|s| s.to_str()) else {
return Err(format!(
"shared_descriptor_pool requires include_file to have a file name \
(the descriptor-set sidecar is named after its stem); \
got {include_name:?}"
)
.into());
};
// The sidecar is named after the stem alone and written at the
// output root, so `a/gen.rs` and `b/gen.rs` from two compile()
// calls would share `gen.descriptor_set.binpb`, and the first tree
// would build its pool from the second tree's descriptors.
if !is_bare_file_name(include_name) {
let reason = if include_name.contains('\0') {
NUL_IN_FILE_NAME
} else {
"the descriptor-set sidecar is named after the stem alone and \
written at the output root, so include files in two directories \
would share it"
};
return Err(format!(
"shared_descriptor_pool requires include_file to be a bare file name \
({reason}); got {include_name:?}"
)
.into());
}
Some(format!("{stem}.descriptor_set.binpb"))
} else {
None
};
// When out_dir is explicitly set, the include file should use
// relative `include!("foo.rs")` paths (the index is a sibling of the
// generated files). When defaulted to $OUT_DIR, keep the
// `concat!(env!("OUT_DIR"), ...)` form so that
// `include!(concat!(env!("OUT_DIR"), "/_include.rs"))` from src/
// still resolves to absolute paths.
let relative_includes = self.out_dir.is_some();
// Those relative paths name siblings of the include file, so the
// include file has to sit in the output directory itself, with or
// without the shared pool (which has already required a bare name
// above). `$OUT_DIR` mode emits absolute paths, which resolve from any
// directory.
if let Some(include_name) = self.include_file.as_deref() {
if relative_includes && !is_bare_file_name(include_name) {
let reason = if include_name.contains('\0') {
NUL_IN_FILE_NAME
} else {
"the generated include! paths are relative to the include file"
};
return Err(format!(
"include_file must be a bare file name when out_dir is set \
({reason}); got {include_name:?}"
)
.into());
}
}
let out_dir = self
.out_dir
.or_else(|| std::env::var("OUT_DIR").ok().map(PathBuf::from))
.ok_or("OUT_DIR not set and no out_dir configured")?;
// Produce a FileDescriptorSet from the configured source.
let descriptor_bytes: Cow<'_, [u8]> = match &self.descriptor_source {
DescriptorSource::Protoc => invoke_protoc(&self.files, &self.includes)?.into(),
DescriptorSource::Buf => invoke_buf()?.into(),
DescriptorSource::Precompiled(path) => std::fs::read(path)
.map_err(|e| format!("failed to read descriptor set '{}': {}", path.display(), e))?
.into(),
DescriptorSource::Bytes(bytes) => Cow::Borrowed(bytes),
};
// This descriptor set came from a protoc (or buf) invocation this build
// controls, or a path or bytes the caller supplied, so the bound is far above
// buffa's untrusted-input default — that default is sized for wire
// input and a schema of a few hundred `.proto` files exceeds it,
// descriptor types being wide structs. Still finite, so a truncated or
// stale precompiled set fails with an error rather than an OOM.
let decode_options = buffa_codegen::tooling_decode_options()?;
let fds = decode_options
.decode_from_slice::<FileDescriptorSet>(&descriptor_bytes)
.map_err(|e| {
buffa_codegen::decode_failure(
"FileDescriptorSet",
&e,
decode_options.element_memory_limit(),
)
})?;
// Determine which files were explicitly requested.
//
// `FileDescriptorProto.name` contains the path relative to the proto
// source root (protoc: `--proto_path`; buf: the module root). For
// Precompiled, Bytes, and Buf mode, `.files()` are expected to already be
// proto-relative names. For Protoc mode, strip the first matching
// include prefix.
let files_to_generate: Vec<String> = if matches!(
self.descriptor_source,
DescriptorSource::Precompiled(_) | DescriptorSource::Bytes(_) | DescriptorSource::Buf
) {
self.files
.iter()
.filter_map(|f| f.to_str().map(str::to_string))
.collect()
} else {
self.files
.iter()
.map(|f| proto_relative_name(f, &self.includes))
.filter(|s| !s.is_empty())
.collect()
};
// Generate Rust source. Per-proto content files plus a per-package
// `.mod.rs` stitcher; only the stitchers need wiring into the
// module tree (content files are reached via `include!` from
// there).
let (generated, warnings) = buffa_codegen::generate_with_diagnostics(
&fds.file,
&files_to_generate,
&self.codegen_config,
)?;
// An include tree is written after content files. Compare destinations
// before any writes: relative components, absolute paths, and existing
// directory symlinks may name an adapter despite different spellings.
// Runs without native adapters retain their existing include behavior.
if let Some(include) = self.include_file.as_deref().filter(|_| {
generated
.iter()
.any(|file| file.kind == buffa_codegen::GeneratedFileKind::Adapter)
}) {
let include_path = normalize_output_destination(&out_dir.join(include))?;
for file in generated
.iter()
.filter(|file| file.kind == buffa_codegen::GeneratedFileKind::Adapter)
{
let adapter_path = normalize_output_destination(&out_dir.join(&file.name))?;
if adapter_path
.as_os_str()
.as_encoded_bytes()
.eq_ignore_ascii_case(include_path.as_os_str().as_encoded_bytes())
{
return Err(adapters::AdapterError::from(
adapters::ErrorReason::DuplicateOutput,
)
.into());
}
}
}
// Surface non-fatal codegen diagnostics as Cargo build warnings. This
// runs inside the consumer's `build.rs`, so `cargo:warning=` is shown in
// their normal `cargo build` output.
for warning in warnings {
println!("cargo:warning=buffa: {warning}");
}
// Write output files; collect (name, package) for PackageMod entries.
let mut output_entries: Vec<(String, String)> = Vec::new();
for file in generated {
let path = out_dir.join(&file.name);
if let Some(parent) = path.parent() {
std::fs::create_dir_all(parent)?;
}
write_if_changed(&path, file.content.as_bytes())?;
if file.kind == buffa_codegen::GeneratedFileKind::PackageMod {
output_entries.push((file.name, file.package));
}
}
// Shared-pool mode needs a tree root to host the one `__buffa_fds`
// module; that root is the include file. The reflection and
// include-file prerequisites were validated up front, and `sidecar`
// is `Some` exactly when the mode is on.
// Generate the include file if requested.
if let Some(ref include_name) = self.include_file {
std::fs::create_dir_all(&out_dir)?;
let tree = generate_include_file(&output_entries, relative_includes);
let include_content = if let Some(sidecar) = sidecar {
// Embed the descriptor set once, at the tree root, instead of a
// per-package copy. Write it as a binary sidecar and
// `include_bytes!` it from the shared `__buffa_fds` module, so
// the bytes never expand into Rust byte-literal source. Every
// package's `__buffa::reflect` delegates to that module.
// The sidecar name was derived from the include file's stem up
// front, so two compile() calls sharing an out_dir don't
// clobber each other's descriptor set as long as their include
// file stems differ (`a.rs` and `b.rs`; `gen.rs` and `gen.txt`
// share `gen.descriptor_set.binpb`). The bare-name requirement
// keeps two directories from hiding one stem.
let fds_bytes = buffa_codegen::encode_descriptor_set(
&fds.file,
&self.codegen_config.feature_overrides,
);
write_if_changed(&out_dir.join(&sidecar), &fds_bytes)?;
let mode = if relative_includes {
buffa_codegen::IncludeMode::Relative("")
} else {
buffa_codegen::IncludeMode::OutDir
};
let root = buffa_codegen::shared_descriptor_root_module(
&fds_bytes,
buffa_codegen::FdsEmbedding::Sidecar {
file_name: &sidecar,
mode,
},
self.codegen_config.reflect_feature_gate(),
);
// Keep the tree's `// @generated` marker on line 1 —
// first-line generated-file detection (rustfmt's five-line
// window, diff-collapse heuristics) misses a mid-file marker —
// and put the shared root module between the header and the
// `include!` items. This relies on `generate_include_file`
// passing `emit_inner_allow = false`: an inner `#![allow]` on
// the tree's second line would be illegal after an outer item.
let (header, items) = tree
.split_once('\n')
.expect("generate_module_tree output starts with a header line");
debug_assert!(
!items.trim_start().starts_with("#!["),
"shared root module cannot precede an inner attribute"
);
format!("{header}\n{root}{items}")
} else {
tree
};
let include_path = out_dir.join(include_name);
// In `$OUT_DIR` mode the name may have a directory part.
if let Some(parent) = include_path.parent() {
std::fs::create_dir_all(parent)?;
}
write_if_changed(&include_path, include_content.as_bytes())?;
}
// Tell cargo to re-run if any proto file changes.
//
// For Buf mode, `self.files` are module-root-relative and cargo can't
// stat them — use `buf ls-files` instead, which lists all workspace
// protos with workspace-relative paths. Protoc mode uses the decoded
// descriptor set below to watch resolved transitive imports.
// The decode bound is read from the environment, and this script
// disables cargo's default env tracking by emitting rerun-if-* keys.
println!(
"cargo:rerun-if-env-changed={}",
buffa_codegen::ELEMENT_MEMORY_LIMIT_ENV
);
match self.descriptor_source {
DescriptorSource::Buf => emit_buf_rerun_if_changed(),
DescriptorSource::Protoc => {
// Rerun if PROTOC changes (different binary may accept
// protos the previous one rejected, e.g. newer editions).
println!("cargo:rerun-if-env-changed=PROTOC");
for proto_file in protoc_rerun_if_changed_paths(&fds, &self.files, &self.includes) {
println!("cargo:rerun-if-changed={}", proto_file.display());
}
}
DescriptorSource::Precompiled(ref path) => {
println!("cargo:rerun-if-changed={}", path.display());
}
// The caller tracks the inputs used to produce these bytes.
DescriptorSource::Bytes(_) => {}
}
Ok(())
}
}
/// The reason given when an include file name contains a NUL byte.
const NUL_IN_FILE_NAME: &str = "a file name cannot contain a NUL byte";
/// Resolve an output's existing components without creating its missing ones.
/// Resolve symlinks before processing `..`, matching filesystem traversal;
/// reducing all `..` components first would misidentify symlinked parents.
fn normalize_output_destination(path: &Path) -> Result<PathBuf, adapters::AdapterError> {
let invalid = || adapters::AdapterError::from(adapters::ErrorReason::InvalidOutput);
let absolute = if path.is_absolute() {
path.to_owned()
} else {
std::env::current_dir().map_err(|_| invalid())?.join(path)
};
let mut normalized = PathBuf::new();
for component in absolute.components() {
match component {
Component::Prefix(_) | Component::RootDir => normalized.push(component.as_os_str()),
Component::CurDir => {}
Component::ParentDir => {
normalized.pop();
}
Component::Normal(name) => {
normalized.push(name);
match normalized.canonicalize() {
Ok(existing) => normalized = existing,
Err(error) if error.kind() == std::io::ErrorKind::NotFound => {
// A dangling link can become live when an earlier output
// is written. Do not treat that link as a new file: its
// eventual destination cannot be compared safely yet.
match normalized.symlink_metadata() {
Ok(metadata) if !metadata.file_type().is_symlink() => {}
Err(error) if error.kind() == std::io::ErrorKind::NotFound => {}
_ => return Err(invalid()),
}
}
Err(_) => return Err(invalid()),
}
}
}
}
Ok(normalized)
}
/// Whether `name` places a file directly in the directory it is joined to. A
/// leading `./` is accepted; a backslash and a drive prefix are rejected on
/// every platform, so one build script behaves the same everywhere. A name
/// containing a NUL byte, which cannot name a file, is rejected too.
fn is_bare_file_name(name: &str) -> bool {
let name = name.strip_prefix("./").unwrap_or(name);
if name.contains('/') || name.contains('\\') || name.contains('\0') {
return false;
}
if name.as_bytes().get(1) == Some(&b':')
&& name.as_bytes().first().is_some_and(u8::is_ascii_alphabetic)
{
return false;
}
// With the separators and the drive prefix ruled out, `name` is one
// component: empty, `.`, `..`, or the file name itself.
let mut components = Path::new(name).components();
matches!(components.next(), Some(Component::Normal(_))) && components.next().is_none()
}
impl Default for Config {
fn default() -> Self {
Self::new()
}
}
/// Normalize a user-supplied attribute-match path.
///
/// - Prepends `.` if absent so all stored paths are rooted.
/// - Trims trailing `.` so `".my.pkg."` and `".my.pkg"` behave identically
/// (trailing-dot patterns otherwise never match a real FQN).
/// - The bare catch-all `"."` is preserved as-is.
fn normalize_attr_path(mut path: String) -> String {
if !path.starts_with('.') {
path.insert(0, '.');
}
if path.len() > 1 {
while path.ends_with('.') {
path.pop();
}
}
path
}
/// The minor version of the compiler that builds the crate, if `RUSTC` names
/// one and it can be read.
fn rustc_minor_version() -> Option<u32> {
let rustc = std::env::var_os("RUSTC")?;
let output = std::process::Command::new(rustc)
.arg("--version")
.output()
.ok()?;
parse_rustc_minor_version(&String::from_utf8_lossy(&output.stdout))
}
/// The minor version in the output of `rustc --version`, such as `75` in
/// `rustc 1.75.0 (82e1608df 2023-12-21)`.
fn parse_rustc_minor_version(version_output: &str) -> Option<u32> {
version_output
.split_whitespace()
.nth(1)?
.split('.')
.nth(1)?
.parse()
.ok()
}
/// Normalize a path-scoped rule's proto path: trim whitespace, prepend the
/// leading dot if absent, and strip trailing dots. Unlike
/// [`normalize_attr_path`], an entry that normalizes to empty (e.g. `"..."`)
/// is returned empty rather than collapsing to the `"."` catch-all — the
/// caller skips it, so `"."` stays the only global opt-in spelling.
fn normalize_override_path(path: &str) -> String {
let mut path = path.trim().to_string();
if path.is_empty() || path == "." {
return path;
}
if !path.starts_with('.') {
path.insert(0, '.');
}
while path.ends_with('.') {
path.pop();
}
path
}
/// Normalize the paths given to the field-rule builder method `method` with
/// [`normalize_override_path`]. An entry that normalizes to empty is skipped
/// with a `cargo:warning`.
fn field_rule_paths(method: &str, paths: &[impl AsRef<str>]) -> Vec<String> {
paths
.iter()
.map(AsRef::as_ref)
.filter_map(|raw| {
let normalized = normalize_override_path(raw);
if normalized.is_empty() {
println!(
"cargo:warning=buffa: {method} path '{raw}' normalizes to empty \
and will be ignored"
);
return None;
}
Some(normalized)
})
.collect()
}
/// Write `content` to `path` only if the file doesn't already exist with
/// identical content. Avoids bumping timestamps on unchanged files, which
/// prevents unnecessary downstream recompilation.
fn write_if_changed(path: &Path, content: &[u8]) -> std::io::Result<()> {
if let Ok(existing) = std::fs::read(path) {
if existing == content {
return Ok(());
}
}
std::fs::write(path, content)
}
/// Invoke `protoc` to produce a `FileDescriptorSet` (serialized bytes).
fn invoke_protoc(
files: &[PathBuf],
includes: &[PathBuf],
) -> Result<Vec<u8>, Box<dyn std::error::Error>> {
let protoc = std::env::var("PROTOC").unwrap_or_else(|_| "protoc".to_string());
let descriptor_file =
tempfile::NamedTempFile::new().map_err(|e| format!("failed to create temp file: {}", e))?;
let descriptor_path = descriptor_file.path().to_path_buf();
let mut cmd = Command::new(&protoc);
cmd.arg("--include_imports");
cmd.arg("--include_source_info");
cmd.arg(format!(
"--descriptor_set_out={}",
descriptor_path.display()
));
for include in includes {
cmd.arg(format!("--proto_path={}", include.display()));
}
for file in files {
cmd.arg(file.as_os_str());
}
let output = cmd
.output()
.map_err(|e| format!("failed to run protoc ({}): {}", protoc, e))?;
if !output.status.success() {
let stderr = String::from_utf8_lossy(&output.stderr);
return Err(format!("protoc failed: {}", stderr).into());
}
let bytes = std::fs::read(&descriptor_path)
.map_err(|e| format!("failed to read descriptor set: {}", e))?;
Ok(bytes)
}
/// Invoke `buf build` to produce a `FileDescriptorSet` (serialized bytes).
///
/// Requires a `buf.yaml` discoverable from the build script's cwd. Builds
/// the entire workspace — no `--path` filtering, because buf's `--path` flag
/// expects workspace-relative paths while `FileDescriptorProto.name` is
/// module-root-relative; passing user paths to both would be a contradiction.
/// Codegen filtering happens on our side via `files_to_generate` matching.
fn invoke_buf() -> Result<Vec<u8>, Box<dyn std::error::Error>> {
// buf build includes SourceCodeInfo by default (there's an
// --exclude-source-info flag to disable it), so proto comments
// propagate to generated code without an explicit opt-in here.
let output = Command::new("buf")
.arg("build")
.arg("--as-file-descriptor-set")
.arg("-o")
.arg("-")
.output()
.map_err(|e| format!("failed to run buf (is it installed and on PATH?): {e}"))?;
if !output.status.success() {
let stderr = String::from_utf8_lossy(&output.stderr);
return Err(
format!("buf build failed (is buf.yaml present at crate root?): {stderr}").into(),
);
}
Ok(output.stdout)
}
/// Emit `cargo:rerun-if-changed` directives for a buf workspace.
///
/// Runs `buf ls-files` to discover all proto files with workspace-relative
/// paths (which cargo can stat). Also watches `buf.yaml` and `buf.lock`
/// (the latter only if it exists — cargo treats a missing rerun-if-changed
/// path as always-dirty). Failure is non-fatal: worst case cargo reruns
/// every build.
fn emit_buf_rerun_if_changed() {
println!("cargo:rerun-if-changed=buf.yaml");
if Path::new("buf.lock").exists() {
println!("cargo:rerun-if-changed=buf.lock");
}
match Command::new("buf").arg("ls-files").output() {
Ok(out) if out.status.success() => {
for line in String::from_utf8_lossy(&out.stdout).lines() {
let path = line.trim();
if !path.is_empty() {
println!("cargo:rerun-if-changed={path}");
}
}
}
_ => {
// ls-files failed; cargo already knows about buf.yaml above.
// If buf itself is missing, invoke_buf() will error clearly.
}
}
}
/// Convert a filesystem proto path to the name protoc uses in the descriptor.
///
/// `FileDescriptorProto.name` is relative to the `--proto_path` include
/// directory. The name is what remains after the first include that is a
/// prefix of the file and leaves no `..` in the remainder: protoc refuses to
/// map a file through an include when the result would contain `..`, and
/// tries the next one. If no include qualifies, the name is the full path
/// (not just file_name — that would break nested proto directories).
/// Current-directory components and redundant separators are removed first,
/// as protoc does, without resolving symlinks or `..`.
fn proto_relative_name(file: &Path, includes: &[PathBuf]) -> String {
let file = normalize_proto_path(file);
let name = includes
.iter()
.find_map(|include| {
let include = normalize_proto_path(include);
// `.` contains every relative path and no rooted one. `has_root`
// also covers a Windows path that starts at the root of the
// current drive, which `is_absolute` reports as relative.
if include.as_os_str().is_empty() && file.has_root() {
return None;
}
file.strip_prefix(include).ok().filter(|name| {
!name
.components()
.any(|component| component == Component::ParentDir)
})
})
.unwrap_or(&file)
.to_str()
.unwrap_or("")
.to_string();
#[cfg(windows)]
let name = name.replace('\\', "/");
name
}
fn normalize_proto_path(path: &Path) -> PathBuf {
path.components()
.filter(|component| *component != Component::CurDir)
.collect()
}
/// Files Cargo should watch for protoc-based builds.
///
/// `protoc --include_imports` records the full transitive import closure in
/// the descriptor set. Convert descriptor-relative names back to filesystem
/// paths under the configured include roots so edits to imported protos rerun
/// codegen even when `.files()` listed only the leaf proto. Imports resolved
/// from protoc's bundled includes (the well-known types) are not under any
/// configured root and are deliberately left unwatched — they ship with the
/// protoc binary and are not user-editable.
fn protoc_rerun_if_changed_paths(
fds: &FileDescriptorSet,
files: &[PathBuf],
includes: &[PathBuf],
) -> Vec<PathBuf> {
let mut paths: BTreeSet<PathBuf> = files.iter().cloned().collect();
for file in &fds.file {
if let Some(name) = file.name.as_deref() {
if let Some(path) = resolve_descriptor_name_under_include(name, includes) {
paths.insert(path);
}
}
}
paths.into_iter().collect()
}
/// Map an include-relative descriptor name back to an on-disk path, trying
/// the include roots in `-I` order (matching protoc's own resolution).
/// Absolute or parent-traversing names are rejected outright; with no
/// include roots, the name is tried relative to the working directory.
fn resolve_descriptor_name_under_include(name: &str, includes: &[PathBuf]) -> Option<PathBuf> {
let rel = Path::new(name);
if rel.is_absolute()
|| rel
.components()
.any(|c| matches!(c, Component::ParentDir | Component::Prefix(_)))
{
return None;
}
if includes.is_empty() {
let path = PathBuf::from(rel);
return path.exists().then_some(path);
}
for include in includes {
let path = include.join(rel);
if path.exists() {
return Some(path);
}
}
None
}
/// Generate the content of an include file that assembles generated `.rs`
/// files into a nested module tree matching the protobuf package hierarchy.
///
/// Each generated file is named like `my.package.file_name.rs`. The package
/// segments become `pub mod` wrappers, and the file is `include!`d inside
/// the innermost module.
///
/// For example, files `["foo.bar.rs", "foo.baz.rs"]` produce:
/// ```text
/// pub mod foo {
/// #[allow(unused_imports)]
/// use super::*;
/// include!(concat!(env!("OUT_DIR"), "/foo.bar.rs"));
/// include!(concat!(env!("OUT_DIR"), "/foo.baz.rs"));
/// }
/// ```
///
/// When `relative` is true (the caller set [`Config::out_dir`] explicitly),
/// `include!` directives use bare sibling paths (`include!("foo.bar.rs")`)
/// instead of the `env!("OUT_DIR")` prefix, so the include file works when
/// checked into the source tree and referenced via `mod`.
fn generate_include_file(entries: &[(String, String)], relative: bool) -> String {
let mode = if relative {
buffa_codegen::IncludeMode::Relative("")
} else {
buffa_codegen::IncludeMode::OutDir
};
// Inner-allow off: this output is consumed via `include!` from
// user-authored `lib.rs`, where `#![allow(...)]` is not valid.
buffa_codegen::generate_module_tree(entries, mode, false)
}
#[cfg(test)]
mod tests {
use super::*;
fn native_adapter_input() -> (Vec<u8>, adapters::AdapterConfig) {
use buffa_codegen::generated::descriptor::{
EnumDescriptorProto, EnumValueDescriptorProto, FileDescriptorProto,
};
let file = FileDescriptorProto {
name: Some("mode.proto".into()),
package: Some("p".into()),
syntax: Some("proto3".into()),
enum_type: vec![EnumDescriptorProto {
name: Some("Mode".into()),
value: vec![
EnumValueDescriptorProto {
name: Some("MODE_UNSPECIFIED".into()),
number: Some(0),
..Default::default()
},
EnumValueDescriptorProto {
name: Some("MODE_MESSAGE".into()),
number: Some(1),
..Default::default()
},
],
..Default::default()
}],
..Default::default()
};
let config = adapters::AdapterConfig::from_json(br#"{"version":1,"selectors":[{
"file":"native.rs","name":"NativeMode","wire":{"source":".p.Mode","rust_type":"crate::wire::Mode"},
"error":{"rust_type":"crate::ContractError","value":"crate::ContractError::Invalid"},
"variants":[{"source":"MODE_MESSAGE","name":"Message"}]
}]}"#).unwrap();
(buffa_codegen::encode_descriptor_set(&[file], &[]), config)
}
#[test]
fn native_adapters_are_written_outside_the_portable_include_tree() {
let (bytes, adapters) = native_adapter_input();
let directory = tempfile::tempdir().unwrap();
Config::new()
.descriptor_set_bytes(bytes)
.files(&["mode.proto"])
.adapters(adapters)
.out_dir(directory.path())
.include_file("tree.rs")
.compile()
.unwrap();
assert!(directory.path().join("native.rs").is_file());
let tree = std::fs::read_to_string(directory.path().join("tree.rs")).unwrap();
assert!(!tree.contains("native.rs"));
assert!(tree.contains("p.mod.rs"));
}
#[test]
fn native_include_collisions_fail_before_writing_any_output() {
for include in ["native.rs", "NATIVE.rs", "./native.rs", "./NATIVE.rs"] {
assert_native_include_collision(include, true);
}
}
fn assert_native_include_collision(include: &str, explicit_out_dir: bool) {
let (bytes, adapters) = native_adapter_input();
let directory = explicit_out_dir.then(|| tempfile::tempdir().unwrap());
let path = directory.as_ref().map_or_else(
|| PathBuf::from(std::env::var_os("OUT_DIR").unwrap()),
|dir| dir.path().to_owned(),
);
std::fs::create_dir_all(&path).unwrap();
let preserved = path.join("native.rs");
std::fs::write(&preserved, b"preserved adapter").unwrap();
std::fs::write(path.join("p.rs"), b"preserved portable").unwrap();
let mut config = Config::new()
.descriptor_set_bytes(bytes)
.files(&["mode.proto"])
.adapters(adapters)
.include_file(include);
if explicit_out_dir {
config = config.out_dir(&path);
}
let error = config.compile().unwrap_err();
assert_eq!(
error
.downcast_ref::<adapters::AdapterError>()
.unwrap()
.reason,
adapters::ErrorReason::DuplicateOutput
);
assert_eq!(std::fs::read(preserved).unwrap(), b"preserved adapter");
assert_eq!(
std::fs::read(path.join("p.rs")).unwrap(),
b"preserved portable"
);
assert!(!path.join("p.mod.rs").exists());
assert_eq!(std::fs::read_dir(&path).unwrap().count(), 2);
}
#[test]
fn native_include_out_dir_collision_child() {
// OUT_DIR belongs to the child process so parallel tests never observe
// a temporary change to their build environment.
let Some(include) = std::env::var_os("NATIVE_COLLISION_INCLUDE") else {
return;
};
assert_native_include_collision(include.to_str().unwrap(), false);
}
#[test]
fn native_include_out_dir_aliases_fail_before_writing() {
let directory = tempfile::tempdir().unwrap();
let output = directory.path().join("out");
for include in [
"././native.rs".to_owned(),
"unused/../native.rs".to_owned(),
"../out/NATIVE.rs".to_owned(),
output.join("native.rs").to_str().unwrap().to_owned(),
] {
let result = std::process::Command::new(std::env::current_exe().unwrap())
.args(["--exact", "tests::native_include_out_dir_collision_child"])
.env("OUT_DIR", &output)
.env("NATIVE_COLLISION_INCLUDE", &include)
.output()
.unwrap();
assert!(
result.status.success(),
"{include}: {}",
String::from_utf8_lossy(&result.stdout)
);
}
}
#[test]
fn native_noncolliding_out_dir_include_child() {
let Some(include) = std::env::var_os("NATIVE_VALID_INCLUDE") else {
return;
};
let (bytes, adapters) = native_adapter_input();
Config::new()
.descriptor_set_bytes(bytes)
.files(&["mode.proto"])
.adapters(adapters)
.include_file(include.to_str().unwrap())
.compile()
.unwrap();
let output = PathBuf::from(std::env::var_os("OUT_DIR").unwrap());
assert!(std::fs::read_to_string(output.join("native.rs"))
.unwrap()
.contains("pub enum NativeMode"));
assert!(std::fs::read_to_string(output.join(include))
.unwrap()
.contains("p.mod.rs"));
}
#[test]
fn native_out_dir_includes_keep_distinct_destinations() {
let directory = tempfile::tempdir().unwrap();
let output = directory.path().join("out");
let includes = vec![
PathBuf::from("nested/tree.rs"),
directory.path().join("separate/native.rs"),
];
#[cfg(unix)]
let includes = {
let mut includes = includes;
// `link/..` is the symlink target's parent, not the output
// directory. A lexical reduction alone would reject this valid case.
std::fs::create_dir_all(directory.path().join("target/child")).unwrap();
std::fs::create_dir(&output).unwrap();
std::os::unix::fs::symlink(directory.path().join("target/child"), output.join("link"))
.unwrap();
includes.push(PathBuf::from("link/../native.rs"));
includes
};
for include in includes {
let result = std::process::Command::new(std::env::current_exe().unwrap())
.args([
"--exact",
"tests::native_noncolliding_out_dir_include_child",
])
.env("OUT_DIR", &output)
.env("NATIVE_VALID_INCLUDE", &include)
.output()
.unwrap();
assert!(
result.status.success(),
"{include:?}: {}",
String::from_utf8_lossy(&result.stdout)
);
}
}
#[cfg(unix)]
#[test]
fn native_include_directory_symlink_alias_is_a_collision() {
let directory = tempfile::tempdir().unwrap();
let output = directory.path().join("out");
std::fs::create_dir(&output).unwrap();
let alias = directory.path().join("alias");
std::os::unix::fs::symlink(&output, &alias).unwrap();
let result = std::process::Command::new(std::env::current_exe().unwrap())
.args(["--exact", "tests::native_include_out_dir_collision_child"])
.env("OUT_DIR", &output)
.env("NATIVE_COLLISION_INCLUDE", alias.join("native.rs"))
.output()
.unwrap();
assert!(
result.status.success(),
"{}",
String::from_utf8_lossy(&result.stdout)
);
}
#[cfg(unix)]
#[test]
fn native_include_dangling_symlink_is_rejected_before_any_writes() {
let (bytes, adapters) = native_adapter_input();
let directory = tempfile::tempdir().unwrap();
let include = directory.path().join("tree.rs");
std::os::unix::fs::symlink("native.rs", &include).unwrap();
let portable = directory.path().join("p.rs");
std::fs::write(&portable, b"preserved portable").unwrap();
let error = Config::new()
.descriptor_set_bytes(bytes)
.files(&["mode.proto"])
.adapters(adapters)
.out_dir(directory.path())
.include_file("tree.rs")
.compile()
.unwrap_err();
assert_eq!(
error
.downcast_ref::<adapters::AdapterError>()
.unwrap()
.reason,
adapters::ErrorReason::InvalidOutput
);
assert_eq!(std::fs::read(portable).unwrap(), b"preserved portable");
assert_eq!(std::fs::read_link(include).unwrap(), Path::new("native.rs"));
assert!(!directory.path().join("native.rs").exists());
assert_eq!(std::fs::read_dir(directory.path()).unwrap().count(), 2);
}
#[test]
fn feature_name_setters_reach_codegen_config() {
let config = Config::new()
.json_feature_name("serde")
.views_feature_name("zero-copy")
.text_feature_name(String::from("textproto"))
.reflect_feature_name("reflection")
.codegen_config;
let names = &config.feature_gate_names;
assert_eq!(names.json, "serde");
assert_eq!(names.views, "zero-copy");
assert_eq!(names.text, "textproto");
assert_eq!(names.reflect, "reflection");
}
#[test]
fn shared_descriptor_pool_requires_include_file() {
// The shared root module has no home without an include file, so
// compile() must reject the combination before doing any work.
let err = Config::new()
.generate_reflection(true)
.shared_descriptor_pool(true)
.out_dir("unused")
.compile()
.expect_err("shared_descriptor_pool without include_file must error");
assert!(
err.to_string().contains("include_file"),
"error should name the missing include_file: {err}"
);
}
#[test]
fn shared_descriptor_pool_setter_reaches_codegen_config() {
let config = Config::new().shared_descriptor_pool(true).codegen_config;
assert!(config.shared_descriptor_pool);
}
#[test]
fn shared_descriptor_pool_rejects_stemless_include_file() {
// The sidecar is named after the include file's stem; a name without
// one ("", ".", "..") must fail up front rather than writing a
// misnamed stray sidecar before the include-file write errors.
let err = Config::new()
.generate_reflection(true)
.shared_descriptor_pool(true)
.include_file("..")
.out_dir("unused")
.compile()
.expect_err("shared_descriptor_pool with a stemless include_file must error");
assert!(
err.to_string().contains("file name"),
"error should name the degenerate include_file: {err}"
);
}
#[test]
fn is_bare_file_name_accepts_names_in_the_joined_directory() {
for name in ["gen_mod.rs", ".gen_mod.rs", "gen_mod", "./gen_mod.rs"] {
assert!(is_bare_file_name(name), "{name:?} should be bare");
}
}
#[test]
fn is_bare_file_name_rejects_paths_and_nul() {
for name in [
"",
".",
"./",
"..",
"../gen_mod.rs",
"nested/gen_mod.rs",
"nested\\gen_mod.rs",
"/gen_mod.rs",
"C:gen_mod.rs",
"gen_mod.rs/",
"gen_mod.rs\0",
] {
assert!(!is_bare_file_name(name), "{name:?} should not be bare");
}
}
#[test]
fn shared_descriptor_pool_rejects_path_include_file() {
let dir = tempfile::tempdir().unwrap();
std::fs::create_dir(dir.path().join("nested")).unwrap();
let err = Config::new()
.generate_reflection(true)
.shared_descriptor_pool(true)
.include_file("nested/gen_mod.rs")
.descriptor_set_bytes(Vec::new())
.out_dir(dir.path())
.compile()
.expect_err("shared descriptor include_file paths must be rejected");
let message = err.to_string();
assert!(
message.contains("bare file name") && message.contains("sidecar"),
"error should name the bare-file requirement and its reason: {message}"
);
}
#[test]
fn shared_descriptor_pool_rejects_nul_include_file() {
let dir = tempfile::tempdir().unwrap();
let err = Config::new()
.generate_reflection(true)
.shared_descriptor_pool(true)
.include_file("gen_mod.rs\0")
.descriptor_set_bytes(Vec::new())
.out_dir(dir.path())
.compile()
.expect_err("shared descriptor include_file names must not contain NUL");
let message = err.to_string();
assert!(
message.contains("bare file name") && message.contains("NUL"),
"error should name the bare-file requirement and the NUL byte: {message}"
);
assert!(
!message.contains("sidecar"),
"a NUL name is not a path problem: {message}"
);
}
#[test]
fn explicit_out_dir_rejects_nul_include_file() {
let dir = tempfile::tempdir().unwrap();
let err = Config::new()
.include_file("gen_mod.rs\0")
.descriptor_set_bytes(Vec::new())
.out_dir(dir.path())
.compile()
.expect_err("include_file names must not contain NUL");
let message = err.to_string();
assert!(
message.contains("bare file name") && message.contains("NUL"),
"error should name the bare-file requirement and the NUL byte: {message}"
);
assert!(
!message.contains("relative to the include file"),
"a NUL name is not a path problem: {message}"
);
}
#[test]
fn shared_descriptor_pool_requires_reflection() {
// Checked before include_file so the error names the first missing
// prerequisite.
let err = Config::new()
.shared_descriptor_pool(true)
.include_file("gen_mod.rs")
.out_dir("unused")
.compile()
.expect_err("shared_descriptor_pool without reflection must error");
assert!(
err.to_string().contains("reflection"),
"error should name the missing reflection prerequisite: {err}"
);
}
#[test]
fn shared_descriptor_pool_writes_sidecar_and_shared_root() {
use buffa_codegen::generated::descriptor::field_descriptor_proto::{Label, Type};
use buffa_codegen::generated::descriptor::{
DescriptorProto, FieldDescriptorProto, FileDescriptorProto,
};
// A minimal one-package descriptor set, fed through descriptor_set()
// so the test needs no protoc.
let file = FileDescriptorProto {
name: Some("foo/v1/thing.proto".into()),
package: Some("foo.v1".into()),
syntax: Some("proto3".into()),
message_type: vec![DescriptorProto {
name: Some("Thing".into()),
field: vec![FieldDescriptorProto {
name: Some("id".into()),
number: Some(1),
label: Some(Label::LABEL_OPTIONAL),
r#type: Some(Type::TYPE_INT32),
..Default::default()
}],
..Default::default()
}],
..Default::default()
};
let fds_bytes = buffa_codegen::encode_descriptor_set(std::slice::from_ref(&file), &[]);
let dir = tempfile::tempdir().unwrap();
let fds_path = dir.path().join("set.binpb");
std::fs::write(&fds_path, &fds_bytes).unwrap();
let out = dir.path().join("gen");
Config::new()
.descriptor_set(&fds_path)
.files(&["foo/v1/thing.proto"])
.out_dir(&out)
.include_file("gen_mod.rs")
.generate_reflection(true)
.shared_descriptor_pool(true)
.compile()
.expect("shared-pool compile should succeed");
// The sidecar is named after the include file's stem and carries the
// same bytes the generated code was built against.
let sidecar = std::fs::read(out.join("gen_mod.descriptor_set.binpb"))
.expect("sidecar must be written next to the include file");
assert_eq!(sidecar, fds_bytes);
// The include file hosts the shared root and `include_bytes!`s the
// sidecar (out_dir is explicit, so paths are include-file-relative)
// instead of inlining the descriptor bytes as a source literal.
let include = std::fs::read_to_string(out.join("gen_mod.rs")).unwrap();
// The generated-file marker must stay on line 1 (first-line `@generated`
// detection: rustfmt, diff-collapsing heuristics), with the shared root
// module below it.
assert!(
include.starts_with("// @generated"),
"include file must lead with the @generated marker: {include}"
);
assert!(include.contains("pub mod __buffa_fds"), "{include}");
// (Two containment checks rather than one exact call text —
// prettyplease may wrap the macro call across lines.)
assert!(include.contains("include_bytes!"), "{include}");
assert!(
include.contains("\"gen_mod.descriptor_set.binpb\""),
"{include}"
);
assert!(
!include.contains("FILE_DESCRIPTOR_SET_BYTES: &[u8] = b\""),
"sidecar mode must not inline the bytes: {include}"
);
// The package's `__buffa::reflect` surface (authored by the package
// stitcher) delegates to the shared root instead of embedding its own
// copy of the descriptor set.
let pkg = std::fs::read_to_string(out.join("foo.v1.mod.rs")).unwrap();
assert!(
pkg.contains("__buffa_fds"),
"package reflect surface must delegate to the shared root: {pkg}"
);
assert!(
!pkg.contains("FILE_DESCRIPTOR_SET_BYTES: &[u8] = b\""),
"package must not embed its own descriptor copy: {pkg}"
);
}
#[test]
fn box_type_in_normalizes_leading_dot() {
// Without normalization a dotless path would silently match nothing,
// and the exact-path Inline recursion error would never fire for it.
let config = Config::new()
.box_type_in(PointerRepr::Box, &["my.pkg.Msg.inner", ".my.pkg.Other"])
.codegen_config;
assert_eq!(
config.pointer_fields,
vec![
(".my.pkg.Msg.inner".to_string(), PointerRepr::Box),
(".my.pkg.Other".to_string(), PointerRepr::Box),
]
);
}
fn rule_paths<R>(rules: &[(String, R)]) -> Vec<&str> {
rules.iter().map(|(path, _)| path.as_str()).collect()
}
#[test]
fn type_in_builders_normalize_paths() {
// A missing leading dot, surrounding whitespace and a trailing dot
// are normalized; a blank entry is skipped, so `"."` is the only
// spelling of "every field".
let paths = &["my.pkg.Msg.field", " .my.pkg.Other. ", ".", "", " ", "..."];
let expected = [".my.pkg.Msg.field", ".my.pkg.Other", "."];
let config = Config::new()
.bytes_type_in(BytesRepr::Bytes, paths)
.string_type_in(StringRepr::String, paths)
.map_type_in(MapRepr::BTreeMap, paths)
.repeated_type_in(RepeatedRepr::Vec, paths)
.box_type_in(PointerRepr::Box, paths)
.unbox_oneof_in(paths)
.codegen_config;
assert_eq!(rule_paths(&config.bytes_fields), expected);
assert_eq!(rule_paths(&config.string_fields), expected);
assert_eq!(rule_paths(&config.map_fields), expected);
assert_eq!(rule_paths(&config.repeated_fields), expected);
assert_eq!(rule_paths(&config.pointer_fields), expected);
assert_eq!(config.unboxed_oneof_fields, expected);
}
#[test]
fn bytes_alias_and_custom_in_builders_normalize_paths() {
let config = Config::new()
.use_bytes_type_in(&["my.pkg.A.data"])
.bytes_type_custom_in("::my::Bytes", &["my.pkg.B.data"])
.string_type_custom_in("::my::Str", &["my.pkg.C.name"])
.map_type_custom_in("::my::Map", &["my.pkg.D.entries"])
.repeated_type_custom_in("::my::List<*>", &["my.pkg.E.items"])
.codegen_config;
assert_eq!(config.bytes_fields[0].0, ".my.pkg.A.data");
assert_eq!(config.bytes_fields[1].0, ".my.pkg.B.data");
assert_eq!(config.string_fields[0].0, ".my.pkg.C.name");
assert_eq!(config.map_fields[0].0, ".my.pkg.D.entries");
assert_eq!(config.repeated_fields[0].0, ".my.pkg.E.items");
}
#[test]
fn unbox_oneof_in_normalizes_leading_dot() {
// Without normalization a dotless path would silently match nothing,
// and the exact-path recursion error would never fire for it.
let config = Config::new()
.unbox_oneof_in(&["my.pkg.Msg.body.small", ".my.pkg.Other"])
.codegen_config;
assert_eq!(
config.unboxed_oneof_fields,
vec![
".my.pkg.Msg.body.small".to_string(),
".my.pkg.Other".to_string()
]
);
}
#[test]
fn skip_debug_normalizes_and_accumulates_paths() {
let config = Config::new()
.skip_debug(&["demo.Uuid4", ".demo.Level.", "..."])
.skip_debug(&[" .demo.Other ", "."])
.codegen_config;
// `"..."` normalizes to empty and is dropped.
assert_eq!(
config.skip_debug,
[".demo.Uuid4", ".demo.Level", ".demo.Other", "."]
);
}
#[test]
fn deny_view_json_normalizes_and_accumulates_paths() {
let config = Config::new()
.deny_view_json(&["demo.Private.", " .demo.Other "])
.deny_view_json(&["."])
.codegen_config;
assert_eq!(config.deny_view_json, [".demo.Private", ".demo.Other", "."]);
}
#[test]
fn codec_strategy_in_normalizes_paths_and_keeps_rule_order() {
let config = Config::new()
.codec_strategy(CodecStrategy::Table)
.codec_strategy_in(CodecStrategy::Unrolled, &["my.pkg.Msg", ".my.pkg.Other."])
.codec_strategy_in(CodecStrategy::Table, &[" .my.pkg.Msg.Inner ", "."])
.codegen_config;
assert_eq!(config.codec_strategy, CodecStrategy::Table);
assert_eq!(
config.codec_strategy_in,
vec![
(".my.pkg.Msg".to_string(), CodecStrategy::Unrolled),
(".my.pkg.Other".to_string(), CodecStrategy::Unrolled),
(".my.pkg.Msg.Inner".to_string(), CodecStrategy::Table),
(".".to_string(), CodecStrategy::Table),
]
);
}
#[test]
fn rustc_minor_version_is_read_from_the_version_line() {
assert_eq!(
parse_rustc_minor_version("rustc 1.75.0 (82e1608df 2023-12-21)"),
Some(75)
);
assert_eq!(
parse_rustc_minor_version("rustc 1.98.0-nightly (abc 2027-01-01)\n"),
Some(98)
);
assert_eq!(parse_rustc_minor_version(""), None);
assert_eq!(parse_rustc_minor_version("not rustc"), None);
}
#[test]
fn codec_strategy_defaults_to_unrolled() {
let config = Config::new().codegen_config;
assert_eq!(config.codec_strategy, CodecStrategy::Unrolled);
assert!(config.codec_strategy_in.is_empty());
}
#[test]
fn deny_unknown_json_fields_in_normalizes_paths() {
let config = Config::new()
.deny_unknown_json_fields_in(&["demo.Config", ".demo.Other.", " .demo.Third ", "."])
.codegen_config;
// The global default is untouched by the path-scoped builder.
assert!(!config.deny_unknown_json_fields);
assert_eq!(
config.deny_unknown_json_fields_in,
vec![
(".demo.Config".to_string(), true),
(".demo.Other".to_string(), true),
(".demo.Third".to_string(), true),
(".".to_string(), true),
]
);
}
#[test]
fn deny_unknown_json_fields_sets_the_global_flag() {
assert!(
Config::new()
.deny_unknown_json_fields(true)
.codegen_config
.deny_unknown_json_fields
);
}
#[test]
fn preserve_unknown_fields_in_normalizes_paths() {
let config = Config::new()
.preserve_unknown_fields(false)
.preserve_unknown_fields_in(&[
"wa.CallLogRecord",
".wa.SyncdMutation.",
" .wa.Other ",
".",
])
.codegen_config;
assert!(!config.preserve_unknown_fields);
assert_eq!(
config.preserve_unknown_fields_in,
vec![
(".wa.CallLogRecord".to_string(), true),
(".wa.SyncdMutation".to_string(), true),
(".wa.Other".to_string(), true),
(".".to_string(), true),
]
);
}
#[test]
fn preserve_unknown_fields_in_empty_path_is_not_catchall() {
// `""` and `"..."` must not collapse to the `"."` catch-all, which
// would re-enable preservation for every message.
let config = Config::new()
.preserve_unknown_fields(false)
.preserve_unknown_fields_in(&["", " ", "...", ".wa.Keep"])
.codegen_config;
assert_eq!(
config.preserve_unknown_fields_in,
vec![(".wa.Keep".to_string(), true)]
);
}
#[test]
fn open_enums_in_normalizes_paths() {
// Without normalization, dotless or trailing-dot paths would silently
// match nothing.
let config = Config::new()
.open_enums_in(&[
"my.pkg.Status.",
".my.pkg.Msg.status",
".",
" my.pkg.Trimmed ",
])
.codegen_config;
let paths: Vec<&str> = config
.feature_overrides
.iter()
.map(|(p, _)| p.as_str())
.collect();
assert_eq!(
paths,
vec![
".my.pkg.Status",
".my.pkg.Msg.status",
".",
".my.pkg.Trimmed"
]
);
assert!(config
.feature_overrides
.iter()
.all(|(_, o)| *o == FeatureOverride::EnumType(EnumTypeOverride::Open)));
}
#[test]
fn override_feature_in_accumulates_and_normalizes() {
let config = Config::new()
.override_feature_in(
"my.pkg.Status.",
FeatureOverride::EnumType(EnumTypeOverride::Open),
)
.override_feature_in(
".my.pkg.Msg.e",
FeatureOverride::EnumType(EnumTypeOverride::Open),
)
.override_feature_in("...", FeatureOverride::EnumType(EnumTypeOverride::Open))
.codegen_config;
assert_eq!(
config.feature_overrides,
vec![
(
".my.pkg.Status".to_string(),
FeatureOverride::EnumType(EnumTypeOverride::Open)
),
(
".my.pkg.Msg.e".to_string(),
FeatureOverride::EnumType(EnumTypeOverride::Open)
),
]
);
}
#[test]
fn open_enums_in_empty_path_is_not_catchall() {
let config = Config::new()
.open_enums_in(&["", " ", "..."])
.codegen_config;
assert!(config.feature_overrides.is_empty());
}
#[test]
fn proto_relative_name_strips_include() {
let got = proto_relative_name(
Path::new("proto/my/service.proto"),
&[PathBuf::from("proto/")],
);
assert_eq!(got, "my/service.proto");
}
#[test]
fn proto_relative_name_normalizes_current_directory_components() {
for (file, includes, expected) in [
(
"./proto/my/service.proto",
vec!["proto"],
"my/service.proto",
),
(
"proto/my/service.proto",
vec!["./proto"],
"my/service.proto",
),
(
"./proto/my/service.proto",
vec!["./proto"],
"my/service.proto",
),
(
"proto/my/./service.proto",
vec!["proto"],
"my/service.proto",
),
("./my//pkg/./service.proto", vec![], "my/pkg/service.proto"),
("./my/pkg/service.proto", vec!["."], "my/pkg/service.proto"),
("my/pkg/service.proto", vec!["./."], "my/pkg/service.proto"),
(
"./my/pkg/service.proto",
vec!["other"],
"my/pkg/service.proto",
),
] {
let includes = includes.into_iter().map(PathBuf::from).collect::<Vec<_>>();
assert_eq!(proto_relative_name(Path::new(file), &includes), expected);
}
}
#[test]
fn proto_relative_name_normalization_preserves_include_order() {
let file = Path::new("./proto/vendor/./ext.proto");
assert_eq!(
proto_relative_name(
file,
&[PathBuf::from("./proto"), PathBuf::from("proto/vendor")]
),
"vendor/ext.proto"
);
assert_eq!(
proto_relative_name(
file,
&[PathBuf::from("./proto/vendor"), PathBuf::from("proto")]
),
"ext.proto"
);
}
#[test]
fn proto_relative_name_current_directory_include_contains_relative_files() {
// `.` listed first names the file by its full relative path, even
// when a later include is a closer match.
assert_eq!(
proto_relative_name(
Path::new("proto/my/service.proto"),
&[PathBuf::from("."), PathBuf::from("proto")]
),
"proto/my/service.proto"
);
}
#[test]
fn proto_relative_name_current_directory_does_not_match_absolute_path() {
let root = std::env::current_dir().unwrap().join("proto");
let file = root.join("my/service.proto");
assert_eq!(
proto_relative_name(&file, &[PathBuf::from("."), root]),
"my/service.proto"
);
}
#[test]
fn proto_relative_name_preserves_parent_directory_components() {
assert_eq!(
proto_relative_name(Path::new("./proto/../vendor/service.proto"), &[]),
"proto/../vendor/service.proto"
);
assert_eq!(
proto_relative_name(
Path::new("./proto/../vendor/service.proto"),
&[PathBuf::from("proto/../vendor")],
),
"service.proto"
);
}
#[test]
fn proto_relative_name_skips_prefixes_leaving_parent_components() {
assert_eq!(
proto_relative_name(
Path::new("./proto/../vendor/service.proto"),
&[
PathBuf::from("."),
PathBuf::from("proto"),
PathBuf::from("proto/../vendor"),
],
),
"service.proto"
);
}
#[test]
fn proto_relative_name_first_matching_prefix_wins() {
let got = proto_relative_name(
Path::new("proto/vendor/ext.proto"),
&[PathBuf::from("proto/"), PathBuf::from("proto/vendor/")],
);
assert_eq!(got, "vendor/ext.proto");
let got = proto_relative_name(
Path::new("proto/vendor/ext.proto"),
&[PathBuf::from("proto/vendor/"), PathBuf::from("proto/")],
);
assert_eq!(got, "ext.proto");
}
#[test]
fn proto_relative_name_skips_unmatched_prefixes() {
let got = proto_relative_name(
Path::new("proto/vendor/ext.proto"),
&[
PathBuf::from("unrelated"),
PathBuf::from("proto/"),
PathBuf::from("proto/vendor/"),
],
);
assert_eq!(got, "vendor/ext.proto");
}
#[test]
fn proto_relative_name_requires_a_complete_path_component() {
let got = proto_relative_name(
Path::new("proto/vendor2/ext.proto"),
&[PathBuf::from("proto/vendor"), PathBuf::from("proto/")],
);
assert_eq!(got, "vendor2/ext.proto");
}
#[cfg(windows)]
#[test]
fn proto_relative_name_normalizes_windows_separators() {
let got = proto_relative_name(
Path::new(r"C:\proto\vendor\ext.proto"),
&[
PathBuf::from(r"C:\proto"),
PathBuf::from(r"C:\proto\vendor"),
],
);
assert_eq!(got, "vendor/ext.proto");
let got = proto_relative_name(Path::new(r"vendor\ext.proto"), &[]);
assert_eq!(got, "vendor/ext.proto");
}
#[cfg(unix)]
#[test]
fn proto_relative_name_preserves_literal_backslashes() {
let got = proto_relative_name(
Path::new(r"proto/vendor\ext.proto"),
&[PathBuf::from("proto")],
);
assert_eq!(got, r"vendor\ext.proto");
}
#[test]
fn proto_relative_name_no_match_returns_full_path() {
// The fallback is the whole path: file_name() alone would drop the
// directories that descriptor_set() mode needs for nested packages.
let got = proto_relative_name(Path::new("my/pkg/service.proto"), &[]);
assert_eq!(got, "my/pkg/service.proto");
}
#[test]
fn proto_relative_name_no_match_with_unrelated_includes() {
let got = proto_relative_name(
Path::new("src/my.proto"),
&[PathBuf::from("other/"), PathBuf::from("third/")],
);
assert_eq!(got, "src/my.proto");
}
#[test]
fn protoc_rerun_paths_include_transitive_imports() {
use buffa_codegen::generated::descriptor::FileDescriptorProto;
let dir = tempfile::tempdir().unwrap();
let include = dir.path().join("proto");
std::fs::create_dir_all(include.join("svc")).unwrap();
std::fs::write(include.join("svc/service.proto"), b"syntax = \"proto3\";").unwrap();
std::fs::write(include.join("common.proto"), b"syntax = \"proto3\";").unwrap();
let fds = FileDescriptorSet {
file: vec![
FileDescriptorProto {
name: Some("svc/service.proto".into()),
..Default::default()
},
FileDescriptorProto {
name: Some("common.proto".into()),
..Default::default()
},
],
..Default::default()
};
let explicit = vec![include.join("svc/service.proto")];
let got: BTreeSet<_> =
protoc_rerun_if_changed_paths(&fds, &explicit, std::slice::from_ref(&include))
.into_iter()
.collect();
let expected: BTreeSet<_> = [
include.join("svc/service.proto"),
include.join("common.proto"),
]
.into_iter()
.collect();
assert_eq!(got, expected);
}
#[test]
fn protoc_rerun_paths_skip_descriptor_names_not_under_include_roots() {
use buffa_codegen::generated::descriptor::FileDescriptorProto;
let dir = tempfile::tempdir().unwrap();
let include = dir.path().join("proto");
std::fs::create_dir_all(&include).unwrap();
let fds = FileDescriptorSet {
file: vec![
FileDescriptorProto {
name: Some("missing.proto".into()),
..Default::default()
},
FileDescriptorProto {
name: Some("../outside.proto".into()),
..Default::default()
},
],
..Default::default()
};
let explicit = vec![PathBuf::from("service.proto")];
assert_eq!(
protoc_rerun_if_changed_paths(&fds, &explicit, &[include]),
explicit
);
}
#[test]
fn include_file_out_dir_mode_uses_env_var() {
let entries = vec![
("foo.bar.rs".to_string(), "foo".to_string()),
("root.rs".to_string(), String::new()),
];
let out = generate_include_file(&entries, false);
assert!(
out.contains(r#"include!(concat!(env!("OUT_DIR"), "/foo.bar.rs"));"#),
"nested-package file should use env!(OUT_DIR): {out}"
);
assert!(
out.contains(r#"include!(concat!(env!("OUT_DIR"), "/root.rs"));"#),
"empty-package file should use env!(OUT_DIR): {out}"
);
assert!(!out.contains(r#"include!("foo.bar.rs")"#));
}
#[test]
fn include_file_relative_mode_uses_sibling_paths() {
let entries = vec![
("foo.bar.rs".to_string(), "foo".to_string()),
("root.rs".to_string(), String::new()),
];
let out = generate_include_file(&entries, true);
assert!(
out.contains(r#"include!("foo.bar.rs");"#),
"nested-package file should use relative path: {out}"
);
assert!(
out.contains(r#"include!("root.rs");"#),
"empty-package file should use relative path: {out}"
);
assert!(
!out.contains("OUT_DIR"),
"relative mode must not reference OUT_DIR: {out}"
);
}
fn config_with_excluded_package() -> Config {
use buffa_codegen::generated::descriptor::{DescriptorProto, FileDescriptorProto};
let file = FileDescriptorProto {
name: Some("example.proto".into()),
package: Some("example".into()),
syntax: Some("proto3".into()),
message_type: vec![DescriptorProto {
name: Some("Message".into()),
..Default::default()
}],
..Default::default()
};
Config::new()
.descriptor_set_bytes(buffa_codegen::encode_descriptor_set(&[file], &[]))
.files(&["example.proto"])
.exclude_package("example")
}
#[test]
fn include_file_creates_output_directory_without_generated_files() {
for config in [
Config::new().descriptor_set_bytes(Vec::new()),
config_with_excluded_package(),
] {
let dir = tempfile::tempdir().unwrap();
let out = dir.path().join("nested/gen");
assert!(!out.exists());
config
.out_dir(&out)
.include_file("gen_mod.rs")
.compile()
.unwrap();
assert_eq!(
std::fs::read_to_string(out.join("gen_mod.rs")).unwrap(),
generate_include_file(&[], true)
);
assert_eq!(std::fs::read_dir(&out).unwrap().count(), 1);
}
}
#[test]
fn shared_descriptor_pool_writes_output_without_generated_files() {
let config = config_with_excluded_package();
let DescriptorSource::Bytes(ref bytes) = config.descriptor_source else {
unreachable!();
};
let expected_bytes = bytes.clone();
let dir = tempfile::tempdir().unwrap();
let out = dir.path().join("nested/gen");
config
.out_dir(&out)
.include_file("gen_mod.rs")
.generate_reflection(true)
.shared_descriptor_pool(true)
.compile()
.unwrap();
assert_eq!(
std::fs::read(out.join("gen_mod.descriptor_set.binpb")).unwrap(),
expected_bytes
);
let include = std::fs::read_to_string(out.join("gen_mod.rs")).unwrap();
assert!(include.contains("pub mod __buffa_fds"), "{include}");
assert!(
include.contains("\"gen_mod.descriptor_set.binpb\""),
"{include}"
);
assert_eq!(std::fs::read_dir(&out).unwrap().count(), 2);
}
#[test]
fn include_file_preserves_existing_directory_without_generated_files() {
let dir = tempfile::tempdir().unwrap();
let preserved = dir.path().join("existing.rs");
std::fs::write(&preserved, b"existing content").unwrap();
config_with_excluded_package()
.out_dir(dir.path())
.include_file("gen_mod.rs")
.compile()
.unwrap();
assert_eq!(std::fs::read(&preserved).unwrap(), b"existing content");
assert_eq!(
std::fs::read_to_string(dir.path().join("gen_mod.rs")).unwrap(),
generate_include_file(&[], true)
);
}
#[test]
fn include_file_reports_output_directory_that_is_a_file() {
let dir = tempfile::tempdir().unwrap();
let out = dir.path().join("gen");
std::fs::write(&out, b"existing content").unwrap();
let err = config_with_excluded_package()
.out_dir(&out)
.include_file("gen_mod.rs")
.compile()
.unwrap_err();
assert!(err.downcast_ref::<std::io::Error>().is_some(), "{err}");
assert_eq!(std::fs::read(&out).unwrap(), b"existing content");
}
#[test]
fn compile_without_include_file_does_not_create_empty_output_directory() {
let dir = tempfile::tempdir().unwrap();
let out = dir.path().join("nested/gen");
config_with_excluded_package()
.out_dir(&out)
.compile()
.unwrap();
assert!(!out.exists());
}
#[test]
fn include_file_relative_mode_nested_packages() {
// Two files in the same depth-2 package: verifies the relative flag
// propagates through recursive emit() calls and both files land in
// the same innermost mod.
let entries = vec![
("a.b.one.rs".to_string(), "a.b".to_string()),
("a.b.two.rs".to_string(), "a.b".to_string()),
];
let out = generate_include_file(&entries, true);
// Both includes should appear once, at the same depth-2 indent,
// inside a single `pub mod b { ... }`.
let indent = " "; // depth 2 = 8 spaces
assert!(
out.contains(&format!(r#"{indent}include!("a.b.one.rs");"#)),
"first file at depth 2: {out}"
);
assert!(
out.contains(&format!(r#"{indent}include!("a.b.two.rs");"#)),
"second file at depth 2: {out}"
);
assert_eq!(
out.matches("pub mod b {").count(),
1,
"both files share one `mod b`: {out}"
);
assert!(!out.contains("OUT_DIR"));
}
#[test]
fn write_if_changed_creates_new_file() {
let dir = tempfile::tempdir().unwrap();
let path = dir.path().join("new.rs");
write_if_changed(&path, b"hello").unwrap();
assert_eq!(std::fs::read(&path).unwrap(), b"hello");
}
#[test]
fn write_if_changed_skips_identical_content() {
let dir = tempfile::tempdir().unwrap();
let path = dir.path().join("same.rs");
std::fs::write(&path, b"content").unwrap();
let mtime_before = std::fs::metadata(&path).unwrap().modified().unwrap();
// Sleep briefly so any write would produce a different mtime.
std::thread::sleep(std::time::Duration::from_millis(50));
write_if_changed(&path, b"content").unwrap();
let mtime_after = std::fs::metadata(&path).unwrap().modified().unwrap();
assert_eq!(mtime_before, mtime_after);
}
#[test]
fn write_if_changed_overwrites_different_content() {
let dir = tempfile::tempdir().unwrap();
let path = dir.path().join("changed.rs");
std::fs::write(&path, b"old").unwrap();
write_if_changed(&path, b"new").unwrap();
assert_eq!(std::fs::read(&path).unwrap(), b"new");
}
#[test]
fn security_rule_normalization_never_turns_an_empty_path_into_a_catch_all() {
let config = Config::new()
.zeroize_in(&["", " . ", " demo.Record. "])
.deny_view_json(&["", " . ", " demo.Record. "]);
assert_eq!(
config.codegen_config.zeroize_messages,
["", ".", ".demo.Record"]
);
assert_eq!(
config.codegen_config.deny_view_json,
["", ".", ".demo.Record"]
);
}
#[test]
fn normalize_attr_path_prepends_leading_dot() {
assert_eq!(normalize_attr_path("my.pkg".into()), ".my.pkg");
}
#[test]
fn normalize_attr_path_preserves_leading_dot() {
assert_eq!(normalize_attr_path(".my.pkg".into()), ".my.pkg");
}
#[test]
fn normalize_attr_path_trims_trailing_dot() {
assert_eq!(normalize_attr_path("my.pkg.".into()), ".my.pkg");
assert_eq!(normalize_attr_path(".my.pkg.".into()), ".my.pkg");
assert_eq!(normalize_attr_path(".my.pkg...".into()), ".my.pkg");
}
#[test]
fn normalize_attr_path_preserves_catchall() {
assert_eq!(normalize_attr_path(".".into()), ".");
assert_eq!(normalize_attr_path("".into()), ".");
}
#[test]
fn type_attribute_forwards_normalized_path() {
let cfg = Config::new().type_attribute("my.pkg.", "#[derive(Foo)]");
assert_eq!(
cfg.codegen_config.type_attributes,
vec![(".my.pkg".to_string(), "#[derive(Foo)]".to_string())]
);
}
#[test]
fn field_attribute_forwards_normalized_path() {
let cfg = Config::new().field_attribute("pkg.Msg.f", "#[serde(skip)]");
assert_eq!(
cfg.codegen_config.field_attributes,
vec![(".pkg.Msg.f".to_string(), "#[serde(skip)]".to_string())]
);
}
#[test]
fn message_attribute_forwards_normalized_path() {
let cfg = Config::new().message_attribute(".", "#[serde(default)]");
assert_eq!(
cfg.codegen_config.message_attributes,
vec![(".".to_string(), "#[serde(default)]".to_string())]
);
}
#[test]
fn enum_attribute_forwards_normalized_path() {
let cfg = Config::new().enum_attribute("my.pkg.", "#[derive(strum::EnumIter)]");
assert_eq!(
cfg.codegen_config.enum_attributes,
vec![(
".my.pkg".to_string(),
"#[derive(strum::EnumIter)]".to_string(),
)]
);
// Other attribute lists must remain untouched.
assert!(cfg.codegen_config.type_attributes.is_empty());
assert!(cfg.codegen_config.message_attributes.is_empty());
assert!(cfg.codegen_config.field_attributes.is_empty());
}
#[test]
fn oneof_struct_field_attribute_forwards_normalized_path() {
let cfg =
Config::new().oneof_struct_field_attribute("my.pkg.Msg.payload.", "#[serde(skip)]");
assert_eq!(
cfg.codegen_config.oneof_struct_field_attributes,
vec![(
".my.pkg.Msg.payload".to_string(),
"#[serde(skip)]".to_string()
)]
);
assert!(cfg.codegen_config.oneof_attributes.is_empty());
assert!(cfg.codegen_config.field_attributes.is_empty());
assert!(cfg.codegen_config.type_attributes.is_empty());
assert!(cfg.codegen_config.message_attributes.is_empty());
assert!(cfg.codegen_config.enum_attributes.is_empty());
}
#[test]
fn oneof_attribute_forwards_normalized_path() {
let cfg = Config::new().oneof_attribute("my.pkg.Msg.payload.", "#[derive(Hash)]");
assert_eq!(
cfg.codegen_config.oneof_attributes,
vec![(
".my.pkg.Msg.payload".to_string(),
"#[derive(Hash)]".to_string()
)]
);
// Other attribute lists must remain untouched.
assert!(cfg.codegen_config.type_attributes.is_empty());
assert!(cfg.codegen_config.enum_attributes.is_empty());
assert!(cfg.codegen_config.message_attributes.is_empty());
assert!(cfg.codegen_config.field_attributes.is_empty());
assert!(cfg.codegen_config.oneof_struct_field_attributes.is_empty());
}
#[test]
fn attribute_calls_accumulate_in_insertion_order() {
let cfg = Config::new()
.type_attribute(".", "#[derive(A)]")
.type_attribute(".pkg.M", "#[derive(B)]")
.type_attribute(".", "#[derive(C)]");
let paths: Vec<_> = cfg
.codegen_config
.type_attributes
.iter()
.map(|(_, a)| a.as_str())
.collect();
assert_eq!(paths, vec!["#[derive(A)]", "#[derive(B)]", "#[derive(C)]"]);
}
#[test]
fn descriptor_set_bytes_matches_file_input() {
use buffa_codegen::generated::descriptor::field_descriptor_proto::{Label, Type};
use buffa_codegen::generated::descriptor::{
DescriptorProto, FieldDescriptorProto, FileDescriptorProto,
};
let files = [
FileDescriptorProto {
name: Some("common/types.proto".into()),
package: Some("common".into()),
syntax: Some("proto3".into()),
message_type: vec![DescriptorProto {
name: Some("Item".into()),
..Default::default()
}],
..Default::default()
},
FileDescriptorProto {
name: Some("api/v1/service.proto".into()),
package: Some("api.v1".into()),
syntax: Some("proto3".into()),
dependency: vec!["common/types.proto".into()],
message_type: vec![DescriptorProto {
name: Some("Request".into()),
field: vec![FieldDescriptorProto {
name: Some("item".into()),
number: Some(1),
label: Some(Label::LABEL_OPTIONAL),
r#type: Some(Type::TYPE_MESSAGE),
type_name: Some(".common.Item".into()),
..Default::default()
}],
..Default::default()
}],
..Default::default()
},
];
let bytes = buffa_codegen::encode_descriptor_set(&files, &[]);
let dir = tempfile::tempdir().unwrap();
let path = dir.path().join("set.binpb");
std::fs::write(&path, &bytes).unwrap();
// The file and in-memory sources produce the same output, and
// `descriptor_set_bytes` replaces a previously configured file or
// `buf` source. No proto sources or external compiler are needed.
let configs = [
Config::new().descriptor_set(&path),
Config::new()
.descriptor_set(dir.path().join("missing.binpb"))
.descriptor_set_bytes(bytes.clone()),
Config::new().use_buf().descriptor_set_bytes(bytes),
];
let mut outputs = Vec::new();
for (i, config) in configs.into_iter().enumerate() {
let out = dir.path().join(i.to_string());
config
.files(&["api/v1/service.proto"])
// Must not strip this prefix from descriptor-relative names.
.includes(&["api"])
.out_dir(&out)
.include_file("gen_mod.rs")
.generate_reflection(true)
.shared_descriptor_pool(true)
.compile()
.unwrap();
let generated: std::collections::BTreeMap<_, _> = std::fs::read_dir(&out)
.unwrap()
.map(|entry| {
let entry = entry.unwrap();
(entry.file_name(), std::fs::read(entry.path()).unwrap())
})
.collect();
let source = generated
.values()
.map(|bytes| String::from_utf8_lossy(bytes))
.collect::<Vec<_>>()
.join("\n");
assert!(source.contains("pub struct Request"));
assert!(!source.contains("pub struct Item"));
outputs.push(generated);
}
assert_eq!(outputs[0], outputs[1]);
assert_eq!(outputs[0], outputs[2]);
}
#[test]
fn descriptor_set_bytes_rejects_malformed_input() {
let dir = tempfile::tempdir().unwrap();
let out = dir.path().join("gen");
let err = Config::new()
.descriptor_set_bytes(vec![0xff])
.out_dir(&out)
.compile()
.unwrap_err();
assert!(err.to_string().contains("FileDescriptorSet"), "{err}");
assert!(!out.exists(), "invalid input must not produce output");
}
#[test]
fn descriptor_set_bytes_can_be_replaced() {
let cfg = Config::new().descriptor_set_bytes(Vec::new()).use_buf();
assert!(matches!(cfg.descriptor_source, DescriptorSource::Buf));
let cfg = Config::new()
.descriptor_set_bytes(Vec::new())
.descriptor_set("set.binpb");
assert!(matches!(
cfg.descriptor_source,
DescriptorSource::Precompiled(path) if path == Path::new("set.binpb")
));
}
#[test]
fn exclude_package_stores_raw_value_for_deferred_normalization() {
// Normalization (leading-dot strip, validation) happens in
// generate_with_diagnostics; the builder stores the raw string so
// compile() can surface errors with the original user-supplied value.
let cfg = Config::new()
.exclude_package(".buf.validate")
.exclude_package("gnostic");
assert_eq!(
cfg.codegen_config.exclude_packages,
vec![".buf.validate", "gnostic"],
);
}
#[test]
fn exclude_package_accumulates_in_order() {
let cfg = Config::new()
.exclude_package("a.b")
.exclude_package("c.d")
.exclude_package("e.f");
assert_eq!(
cfg.codegen_config.exclude_packages,
vec!["a.b", "c.d", "e.f"]
);
}
#[test]
fn exclude_package_rejects_malformed_entries_before_reading_input() {
// The descriptor set path does not exist, so an error can only come
// from the validation that runs ahead of any input processing.
let err = Config::new()
.descriptor_set("/nonexistent/set.binpb")
.files(&["foo/v1/thing.proto"])
.out_dir("/nonexistent/out")
.exclude_package("buf..validate")
.compile()
.expect_err("malformed exclude_package must fail compile()");
let msg = err.to_string();
assert!(msg.contains("exclude_package \"buf..validate\""), "{msg}");
assert!(msg.contains("empty components"), "{msg}");
}
#[test]
fn exclude_package_drops_the_package_from_the_output() {
use buffa_codegen::generated::descriptor::field_descriptor_proto::{Label, Type};
use buffa_codegen::generated::descriptor::{
DescriptorProto, FieldDescriptorProto, FileDescriptorProto,
};
// Two single-message packages, both listed for generation; the
// excluded one must produce no module, no include entry, and no
// stitcher.
let file = |name: &str, package: &str, message: &str| FileDescriptorProto {
name: Some(name.into()),
package: Some(package.into()),
syntax: Some("proto3".into()),
message_type: vec![DescriptorProto {
name: Some(message.into()),
field: vec![FieldDescriptorProto {
name: Some("id".into()),
number: Some(1),
label: Some(Label::LABEL_OPTIONAL),
r#type: Some(Type::TYPE_INT32),
..Default::default()
}],
..Default::default()
}],
..Default::default()
};
let files = [
file("foo/v1/thing.proto", "foo.v1", "Thing"),
file("buf/validate/validate.proto", "buf.validate", "Rule"),
];
let fds_bytes = buffa_codegen::encode_descriptor_set(&files, &[]);
let dir = tempfile::tempdir().unwrap();
let fds_path = dir.path().join("set.binpb");
std::fs::write(&fds_path, &fds_bytes).unwrap();
let out = dir.path().join("gen");
Config::new()
.descriptor_set(&fds_path)
.files(&["foo/v1/thing.proto", "buf/validate/validate.proto"])
.out_dir(&out)
.include_file("gen_mod.rs")
.exclude_package(".buf.validate")
.compile()
.expect("compile with an excluded package should succeed");
let names: Vec<String> = std::fs::read_dir(&out)
.unwrap()
.map(|e| e.unwrap().file_name().to_string_lossy().into_owned())
.collect();
assert!(
names.iter().any(|n| n.starts_with("foo.v1.")),
"kept package must be generated: {names:?}"
);
assert!(
!names.iter().any(|n| n.contains("buf.validate")),
"excluded package must produce no files: {names:?}"
);
let include = std::fs::read_to_string(out.join("gen_mod.rs")).unwrap();
assert!(include.contains("foo"), "{include}");
assert!(!include.contains("validate"), "{include}");
}
}