buffa-codegen 0.7.1

Shared code generation logic for buffa (descriptor → Rust source)
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
//! Message struct code generation.

use crate::generated::descriptor::field_descriptor_proto::{Label, Type};
use crate::generated::descriptor::DescriptorProto;
use proc_macro2::{Ident, TokenStream};
use quote::{format_ident, quote};

use crate::context::{ancillary_prefix, AncillaryKind, CodeGenContext, MessageScope};
use crate::defaults::parse_default_value;
use crate::features::ResolvedFeatures;
use crate::impl_message::{is_explicit_presence_scalar, is_real_oneof_member};
use crate::CodeGenError;

/// Qualified paths to the per-message / per-extension registry `const` items
/// emitted alongside the structs, bubbled up to the file-level
/// `register_types` fn. Each vec is relative to the scope where the
/// corresponding consts land (see `generate_message`'s doc comment).
#[derive(Default)]
pub(crate) struct RegistryPaths {
    /// `__*_JSON_ANY` consts (relative to the struct's scope).
    pub json_any: Vec<TokenStream>,
    /// `__*_TEXT_ANY` consts (relative to the struct's scope).
    pub text_any: Vec<TokenStream>,
    /// `__*_JSON_EXT` consts (relative to the message's module scope).
    pub json_ext: Vec<TokenStream>,
    /// `__*_TEXT_EXT` consts (relative to the message's module scope).
    pub text_ext: Vec<TokenStream>,
}

impl RegistryPaths {
    /// True when no entries were collected — gates whether the package
    /// stitcher emits `register_types` at all.
    pub(crate) fn is_empty(&self) -> bool {
        self.json_any.is_empty()
            && self.text_any.is_empty()
            && self.json_ext.is_empty()
            && self.text_ext.is_empty()
    }
}

/// Separated output streams for a single message (and its nested messages,
/// already wrapped in `pub mod {nested_name} {}` blocks at each level).
///
/// Each `*_tree` stream mirrors the message-nesting structure: a top-level
/// message `Foo` with nested `Bar` produces an `oneof_tree` containing
/// `pub mod foo { /* Foo's oneofs */ pub mod bar { /* Bar's oneofs */ } }`.
/// The package-level assembler in `lib.rs` places each tree under its
/// `__buffa::<kind>::` root.
#[derive(Default)]
pub(crate) struct MessageOutput {
    /// Owned struct + impls — emitted at the message's owned-tree position.
    pub owned_top: TokenStream,
    /// Nested types (enums, nested-message structs, nested extensions) —
    /// emitted inside the message's `pub mod {name} {}` in the owned tree.
    pub owned_mod: TokenStream,
    /// Oneof enum definitions, wrapped in `pub mod {msg_name} { … }`.
    /// Destined for `__buffa::oneof::`.
    pub oneof_tree: TokenStream,
    /// View struct + impls, wrapped per-message-level. Destined for
    /// `__buffa::view::`.
    pub view_tree: TokenStream,
    /// Oneof view enum definitions, wrapped per-message-level. Destined
    /// for `__buffa::view::oneof::`.
    pub view_oneof_tree: TokenStream,
    /// Registry const paths (relative to the package root).
    pub reg: RegistryPaths,
}

/// Generate Rust code for a message type (and its nested types).
///
/// `current_package` is the proto package of the file being generated.
/// Types belonging to this package are referenced without the module prefix
/// since the generated code will be wrapped in `pub mod pkg { ... }`.
///
/// `rust_name` is the Rust struct name to emit.  For top-level messages this
/// is the proto message name; for nested messages it is the simple proto name
/// (e.g. `Inner`) since module nesting provides scoping.
///
/// `proto_fqn` is the fully-qualified proto type name without a leading dot
/// (e.g. `google.protobuf.Timestamp`, `my.package.Outer.Inner`).  It is used
/// to emit the `TYPE_URL` constant.
/// Returns a [`MessageOutput`] bundling the separated owned / oneof /
/// view / view-oneof token streams plus registry-const paths.
pub(crate) fn generate_message(
    ctx: &CodeGenContext,
    msg: &DescriptorProto,
    current_package: &str,
    rust_name: &str,
    proto_fqn: &str,
    features: &ResolvedFeatures,
    resolver: &crate::imports::ImportResolver,
) -> Result<MessageOutput, CodeGenError> {
    let scope = MessageScope {
        ctx,
        current_package,
        proto_fqn,
        features,
        nesting: 0,
    };
    generate_message_with_nesting(scope, msg, rust_name, resolver)
}

fn generate_message_with_nesting(
    scope: MessageScope<'_>,
    msg: &DescriptorProto,
    rust_name: &str,
    resolver: &crate::imports::ImportResolver,
) -> Result<MessageOutput, CodeGenError> {
    let MessageScope {
        ctx,
        current_package,
        proto_fqn,
        features,
        nesting,
    } = scope;
    let name_ident = format_ident!("{}", rust_name);

    // MessageSet wire format: legacy Google encoding that wraps each extension
    // in a group at field 1. protoc enforces the "no regular fields" invariant
    // on the descriptor, so we don't re-check it here. The flag is read again
    // inside `generate_message_impl` to branch the unknown-fields snippets.
    let is_message_set = msg
        .options
        .as_option()
        .and_then(|o| o.message_set_wire_format)
        .unwrap_or(false);
    if is_message_set && !ctx.config.allow_message_set {
        return Err(CodeGenError::MessageSetNotSupported {
            message_name: proto_fqn.to_string(),
        });
    }

    // Nested enums — simple name, emitted inside the message's module.
    let nested_enums = msg
        .enum_type
        .iter()
        .map(|e| {
            let enum_name = e.name.as_deref().unwrap_or("");
            let enum_fqn = format!("{}.{}", proto_fqn, enum_name);
            crate::enumeration::generate_enum(ctx, e, enum_name, &enum_fqn, features, resolver)
        })
        .collect::<Result<Vec<_>, _>>()?;

    // Nested messages (skip map entry synthetics) — simple name, emitted
    // inside the message's module.
    //
    let nested_msgs = msg
        .nested_type
        .iter()
        .filter(|nested| {
            !nested
                .options
                .as_option()
                .and_then(|o| o.map_entry)
                .unwrap_or(false)
        })
        .map(|nested| {
            let nested_proto_name = nested.name.as_deref().unwrap_or("");
            let nested_fqn = format!("{}.{}", proto_fqn, nested_proto_name);
            let msg_features =
                crate::features::resolve_child(features, crate::features::message_features(nested));
            generate_message_with_nesting(
                scope.nested(&nested_fqn, &msg_features),
                nested,
                nested_proto_name,
                resolver,
            )
        })
        .collect::<Result<Vec<_>, _>>()?;

    // Direct struct fields (real oneof fields are excluded; they go in the oneof enum).
    // Type resolution uses the package path since the struct sits at the
    // package level, not inside the message's module.
    let generated_fields: Vec<GeneratedField> = msg
        .field
        .iter()
        .map(|f| generate_field(scope, msg, f, resolver))
        .collect::<Result<Vec<_>, _>>()?
        .into_iter()
        .flatten()
        .collect();
    let direct_fields: Vec<&TokenStream> = generated_fields.iter().map(|f| &f.tokens).collect();

    // Collect (identifier, redacted) pairs for the manual Debug impl
    // (excludes __buffa_ internals).
    let mut debug_fields: Vec<(&Ident, bool)> = generated_fields
        .iter()
        .map(|f| (&f.ident, f.debug_redact))
        .collect();

    let setter_methods: TokenStream = generated_fields
        .iter()
        .filter_map(|f| f.setter.as_ref().map(|s| (f, s)))
        .map(|(f, s)| {
            let field_ident = &f.ident;
            let setter_ident = &s.ident;
            let field_name = field_ident.to_string();
            // Raw identifiers (e.g. `r#type`) don't resolve as intra-doc
            // links, so fall back to plain code formatting for those.
            let doc = if let Some(stripped) = field_name.strip_prefix("r#") {
                format!("Sets `{stripped}` to `Some(value)`, consuming and returning `self`.")
            } else {
                format!(
                    "Sets [`Self::{field_name}`] to `Some(value)`, consuming and returning `self`."
                )
            };
            let body = if s.use_into {
                quote! { Some(value.into()) }
            } else {
                quote! { Some(value) }
            };
            let param = &s.param_type;
            quote! {
                #[must_use = "with_* setters return `self` by value; assign or chain the result"]
                #[inline]
                #[doc = #doc]
                pub fn #setter_ident(mut self, value: #param) -> Self {
                    self.#field_ident = #body;
                    self
                }
            }
        })
        .collect();

    // Module name for this message (snake_case of proto name). Used for the
    // `__buffa` ancillary trees (view/oneof), which are sentinel-isolated and so
    // never need deconfliction.
    let proto_name = msg.name.as_deref().unwrap_or(rust_name);
    let mod_name_str = crate::oneof::to_snake_case(proto_name);
    let mod_ident = make_field_ident(&mod_name_str);

    // The module name under which THIS message's owned `owned_mod` is wrapped by
    // its caller. For a top-level message (nesting 0) the caller is `lib.rs`,
    // which uses the deconflicted name (issue #135); for a nested message the
    // parent wraps with the raw snake name. The owned Any-registry paths bubbled
    // from nested messages are prefixed with this so they resolve to the actual
    // module location.
    let owned_wrap_ident = if nesting == 0 {
        make_field_ident(&ctx.nested_module_name(current_package, proto_name))
    } else {
        mod_ident.clone()
    };

    // Compute oneof enum identifiers for all non-synthetic oneofs up front.
    let oneof_idents = crate::oneof::resolve_oneof_idents(msg);

    // Path prefix from this struct's emission scope to its oneof enums at
    // `__buffa::oneof::<msg_path>::`. The owned struct sits at `nesting`
    // levels below the package root.
    let oneof_prefix = ancillary_prefix(AncillaryKind::Oneof, current_package, proto_fqn, nesting);

    let gates = ctx.config.feature_gates();

    // One `Option<OneofEnum>` field in the struct per non-synthetic oneof.
    let oneof_serde_attr = if ctx.config.generate_json {
        crate::feature_gates::cfg_attr(quote! { serde(flatten) }, gates.json)
    } else {
        quote! {}
    };
    let oneof_generated: Vec<(TokenStream, Ident)> = msg
        .oneof_decl
        .iter()
        .enumerate()
        .filter_map(|(idx, oneof)| {
            let enum_ident = oneof_idents.get(&idx)?;
            let oneof_name = oneof.name.as_deref()?;
            let field_ident = make_field_ident(oneof_name);
            let opt = resolver.option();
            let tokens = quote! {
                #oneof_serde_attr
                pub #field_ident: #opt<#oneof_prefix #enum_ident>,
            };
            Some((tokens, field_ident))
        })
        .collect();
    let oneof_struct_fields: Vec<&TokenStream> = oneof_generated.iter().map(|(t, _)| t).collect();
    // Redaction of oneof payloads is handled by the oneof enum's own Debug impl.
    debug_fields.extend(oneof_generated.iter().map(|(_, id)| (id, false)));

    // When JSON is on, `__buffa_unknown_fields` becomes a `#[serde(flatten)]`
    // newtype wrapper whose Serialize/Deserialize route through the extension
    // registry. The wrapper has `Deref<Target = UnknownFields>` so all binary
    // encode/decode paths in impl_message.rs are unaffected (method-call
    // auto-deref and `&wrapper` → `&UnknownFields` coercion both apply).
    //
    // Gated on `has_extension_ranges`: protoc rejects `extend Foo { ... }`
    // when `Foo` lacks an `extensions N to M;` declaration, so a message
    // without one can never have a registry entry naming it as extendee.
    // Without this gate, the wrapper is pure overhead — `#[serde(flatten)]`
    // on derive-Deserialize buffers every unknown key through serde's
    // `Content::Map` (String key + `serde_json::Value` DOM) before the
    // wrapper can discard it. With the gate, extension-range-free messages
    // keep the pre-extensions `#[serde(skip)]` behavior (zero-alloc
    // `IgnoredAny` skip for unknown keys).
    let has_extension_ranges = !msg.extension_range.is_empty();
    let use_ext_json_wrapper =
        ctx.config.generate_json && ctx.config.preserve_unknown_fields && has_extension_ranges;
    let ext_json_wrapper_ident = format_ident!("__{}ExtJson", rust_name);
    let (unknown_fields_field, ext_json_wrapper_def) = if use_ext_json_wrapper {
        let arbitrary_attr = if ctx.config.generate_arbitrary {
            quote! { #[cfg_attr(feature = "arbitrary", derive(::arbitrary::Arbitrary))] }
        } else {
            quote! {}
        };
        let proto_fqn_lit = proto_fqn;
        // The wrapper struct and its Deref/DerefMut/From impls are
        // unconditional: encode/decode reach `__buffa_unknown_fields.push(..)`
        // through `DerefMut`, so the wrapper is part of the message's wire
        // codec, not just its JSON codec. Only the `Serialize` / `Deserialize`
        // impls (which reach into `extension_registry`, requiring
        // `buffa/json`) are feature-gated. This keeps the field's *type*
        // stable across feature combinations — a struct field can't change
        // type behind a `cfg`.
        let serde_impls = crate::feature_gates::cfg_block(
            quote! {
                impl ::serde::Serialize for #ext_json_wrapper_ident {
                    fn serialize<S: ::serde::Serializer>(&self, s: S)
                        -> ::core::result::Result<S::Ok, S::Error>
                    {
                        ::buffa::extension_registry::serialize_extensions(#proto_fqn_lit, &self.0, s)
                    }
                }
            },
            gates.json,
        );
        let serde_de_impl = crate::feature_gates::cfg_block(
            quote! {
                impl<'de> ::serde::Deserialize<'de> for #ext_json_wrapper_ident {
                    fn deserialize<D: ::serde::Deserializer<'de>>(d: D)
                        -> ::core::result::Result<Self, D::Error>
                    {
                        ::buffa::extension_registry::deserialize_extensions(#proto_fqn_lit, d).map(Self)
                    }
                }
            },
            gates.json,
        );
        let wrapper = quote! {
            #[doc(hidden)]
            #[derive(Clone, Debug, Default, PartialEq)]
            #[repr(transparent)]
            #arbitrary_attr
            pub struct #ext_json_wrapper_ident(pub ::buffa::UnknownFields);

            impl ::core::ops::Deref for #ext_json_wrapper_ident {
                type Target = ::buffa::UnknownFields;
                fn deref(&self) -> &::buffa::UnknownFields { &self.0 }
            }
            impl ::core::ops::DerefMut for #ext_json_wrapper_ident {
                fn deref_mut(&mut self) -> &mut ::buffa::UnknownFields { &mut self.0 }
            }
            impl ::core::convert::From<::buffa::UnknownFields> for #ext_json_wrapper_ident {
                fn from(u: ::buffa::UnknownFields) -> Self { Self(u) }
            }
            #serde_impls
            #serde_de_impl
        };
        let flatten_attr = crate::feature_gates::cfg_attr(quote! { serde(flatten) }, gates.json);
        let field = quote! {
            #flatten_attr
            #[doc(hidden)]
            pub __buffa_unknown_fields: #ext_json_wrapper_ident,
        };
        (field, wrapper)
    } else if ctx.config.preserve_unknown_fields {
        // No wrapper — either generate_json is off, or this message has no
        // extension ranges. In the latter case the serde derive is present
        // and we must `#[serde(skip)]` to exclude the field from JSON; in
        // the former the attribute is harmless (no derive to read it).
        let skip_attr = if ctx.config.generate_json {
            crate::feature_gates::cfg_attr(quote! { serde(skip) }, gates.json)
        } else {
            quote! {}
        };
        let field = quote! {
            #skip_attr
            #[doc(hidden)]
            pub __buffa_unknown_fields: ::buffa::UnknownFields,
        };
        (field, quote! {})
    } else {
        (quote! {}, quote! {})
    };

    // Does this message have real (non-synthetic) oneofs?
    let has_real_oneofs = !oneof_struct_fields.is_empty();

    // Messages declaring `extensions N to M;` accept `"[...]"` JSON keys.
    // With only `#[derive(Deserialize)]`, serde's flatten already routes them
    // to the wrapper's Deserialize — but that path buffers all unclaimed keys
    // into a serde_json::Value first. The custom impl matches them inline.

    // When serde is enabled and the message has oneofs, we generate a custom
    // Deserialize impl so that duplicate-oneof-field and null-value errors
    // propagate correctly (serde's #[serde(flatten)] + Option<T> swallows them).
    // Extension ranges also force the custom impl so `"[...]"` keys are
    // handled inline without buffering.
    let needs_custom_deserialize = ctx.config.generate_json
        && (has_real_oneofs || (has_extension_ranges && ctx.config.preserve_unknown_fields));

    // Oneof enum definitions — emitted inside the message's module.
    // Pass the file-level package as current_package, since
    // nesting=1 in the oneof codegen handles the module depth.
    let oneof_enums = msg
        .oneof_decl
        .iter()
        .enumerate()
        .map(|(idx, oneof)| {
            crate::oneof::generate_oneof_enum(
                ctx,
                msg,
                idx,
                oneof,
                current_package,
                proto_fqn,
                features,
                resolver,
                &oneof_idents,
                nesting,
            )
        })
        .collect::<Result<Vec<_>, _>>()?;

    let message_impl = crate::impl_message::generate_message_impl(
        ctx,
        msg,
        ctx.config.preserve_unknown_fields,
        rust_name,
        current_package,
        proto_fqn,
        features,
        &oneof_idents,
        &oneof_prefix,
        nesting,
    )?;

    let text_impl = crate::impl_text::generate_text_impl(
        ctx,
        msg,
        rust_name,
        current_package,
        proto_fqn,
        features,
        has_extension_ranges,
        &oneof_idents,
        &oneof_prefix,
        nesting,
    )?;

    let type_url = format!("type.googleapis.com/{proto_fqn}");
    let upper = crate::oneof::to_snake_case(rust_name).to_uppercase();

    // JSON Any entry — one per message with `generate_json`. Always
    // `is_wkt: false`: WKTs live in buffa-types and register themselves via
    // the hand-written `register_wkt_types` which knows which types get
    // `"value"` wrapping in Any JSON. The `any_to_json::<M>` /
    // `any_from_json::<M>` monomorphizations coerce to fn pointers in const
    // context (same pattern as enum_to_json<E> in extension_registry).
    let (json_any_const, json_any_ident) = if ctx.config.generate_json {
        let ident = format_ident!("__{}_JSON_ANY", upper);
        let tokens = crate::feature_gates::cfg_block(
            quote! {
                #[doc(hidden)]
                pub const #ident: ::buffa::type_registry::JsonAnyEntry
                    = ::buffa::type_registry::JsonAnyEntry {
                        type_url: #type_url,
                        to_json: ::buffa::type_registry::any_to_json::<#name_ident>,
                        from_json: ::buffa::type_registry::any_from_json::<#name_ident>,
                        is_wkt: false,
                    };
            },
            gates.json,
        );
        (tokens, Some(ident))
    } else {
        (quote! {}, None)
    };

    // Text Any entry — one per message with `generate_text`. Independent of
    // `generate_json`: M implements TextFormat iff `generate_text` was on,
    // and the monomorphization only typechecks then. No `Option<fn>`
    // placeholder — JSON and text entries are separate consts in
    // feature-split maps, so presence in the text map means text-capable.
    let (text_any_const, text_any_ident) = if ctx.config.generate_text {
        let ident = format_ident!("__{}_TEXT_ANY", upper);
        let tokens = crate::feature_gates::cfg_block(
            quote! {
                #[doc(hidden)]
                pub const #ident: ::buffa::type_registry::TextAnyEntry
                    = ::buffa::type_registry::TextAnyEntry {
                        type_url: #type_url,
                        text_encode: ::buffa::type_registry::any_encode_text::<#name_ident>,
                        text_merge: ::buffa::type_registry::any_merge_text::<#name_ident>,
                    };
            },
            gates.text,
        );
        (tokens, Some(ident))
    } else {
        (quote! {}, None)
    };

    let serde_struct_derive = if ctx.config.generate_json {
        let derives = if needs_custom_deserialize {
            // Only derive Serialize; Deserialize is generated separately.
            quote! { derive(::serde::Serialize) }
        } else {
            quote! { derive(::serde::Serialize, ::serde::Deserialize) }
        };
        let derive_attr = crate::feature_gates::cfg_attr(derives, gates.json);
        let default_attr = crate::feature_gates::cfg_attr(quote! { serde(default) }, gates.json);
        quote! {
            #derive_attr
            #default_attr
        }
    } else {
        quote! {}
    };
    let arbitrary_derive = if ctx.config.generate_arbitrary {
        quote! { #[cfg_attr(feature = "arbitrary", derive(::arbitrary::Arbitrary))] }
    } else {
        quote! {}
    };
    let custom_type_attrs =
        CodeGenContext::matching_attributes(&ctx.config.type_attributes, proto_fqn)?;
    let custom_message_attrs =
        CodeGenContext::matching_attributes(&ctx.config.message_attributes, proto_fqn)?;
    let custom_deserialize = if needs_custom_deserialize {
        crate::feature_gates::cfg_block(
            generate_custom_deserialize(
                scope,
                msg,
                &name_ident,
                &oneof_prefix,
                resolver,
                has_extension_ranges,
                &oneof_idents,
            )?,
            gates.json,
        )
    } else {
        quote! {}
    };

    // ProtoElemJson impl for use in proto_seq / proto_map containers.
    // Delegates to the derived/generated Serialize + Deserialize.
    let proto_elem_json_impl = if ctx.config.generate_json {
        crate::feature_gates::cfg_block(
            quote! {
                impl ::buffa::json_helpers::ProtoElemJson for #name_ident {
                    fn serialize_proto_json<S: ::serde::Serializer>(
                        v: &Self,
                        s: S,
                    ) -> ::core::result::Result<S::Ok, S::Error> {
                        ::serde::Serialize::serialize(v, s)
                    }
                    fn deserialize_proto_json<'de, D: ::serde::Deserializer<'de>>(
                        d: D,
                    ) -> ::core::result::Result<Self, D::Error> {
                        <Self as ::serde::Deserialize>::deserialize(d)
                    }
                }
            },
            gates.json,
        )
    } else {
        quote! {}
    };

    // Check if any non-optional field has a custom default value, which
    // requires a hand-written `impl Default` instead of `#[derive(Default)]`.
    let custom_default_impl = generate_custom_default(
        ctx,
        msg,
        &name_ident,
        current_package,
        proto_fqn,
        features,
        nesting,
    )?;
    let derive_default = if custom_default_impl.is_some() {
        quote! {}
    } else {
        quote! { Default, }
    };
    let custom_default_impl = custom_default_impl.unwrap_or_default();

    // Build module items from nested messages. Each nested message contributes:
    // - Its struct + impls (top_level) go directly into our module
    // - Its nested types (owned_mod) go into a sub-module in the owned tree
    // - Its ancillary trees nest under `pub mod {nested_name}` in each tree
    // - Its registry const paths bubble up, prefixed appropriately
    let mut nested_items = TokenStream::new();
    let mut nested_oneof_tree = TokenStream::new();
    let mut nested_view_tree = TokenStream::new();
    let mut nested_view_oneof_tree = TokenStream::new();
    // Any-entry paths are relative to THIS struct's scope (top_level).
    // Our own consts land alongside our struct; nested messages' consts land
    // in our owned_mod, which the caller wraps in `pub mod #mod_ident`, so
    // their returned paths get prefixed with `#mod_ident::`.
    // Extension-entry paths are relative to the message's MODULE scope.
    let mut reg_paths = RegistryPaths::default();
    if let Some(id) = &json_any_ident {
        reg_paths.json_any.push(quote! { #id });
    }
    if let Some(id) = &text_any_ident {
        reg_paths.text_any.push(quote! { #id });
    }
    let non_map_nested: Vec<&DescriptorProto> = msg
        .nested_type
        .iter()
        .filter(|n| {
            !n.options
                .as_option()
                .and_then(|o| o.map_entry)
                .unwrap_or(false)
        })
        .collect();
    for (nested_desc, nested_out) in non_map_nested.iter().zip(nested_msgs) {
        nested_items.extend(nested_out.owned_top);
        let nested_name = nested_desc.name.as_deref().unwrap_or("");
        let nested_mod = make_field_ident(&crate::oneof::to_snake_case(nested_name));
        // Extension paths: nested's module-scope → our module-scope = prefix
        // with the nested message's own module ident.
        for p in nested_out.reg.json_ext {
            reg_paths.json_ext.push(quote! { #nested_mod :: #p });
        }
        for p in nested_out.reg.text_ext {
            reg_paths.text_ext.push(quote! { #nested_mod :: #p });
        }
        // Any paths: nested's struct-scope → our struct-scope = prefix with the
        // module our owned_mod is wrapped in (deconflicted at the top level).
        for p in nested_out.reg.json_any {
            reg_paths.json_any.push(quote! { #owned_wrap_ident :: #p });
        }
        for p in nested_out.reg.text_any {
            reg_paths.text_any.push(quote! { #owned_wrap_ident :: #p });
        }

        if !nested_out.owned_mod.is_empty() {
            let inner = nested_out.owned_mod;
            nested_items.extend(quote! {
                pub mod #nested_mod {
                    #[allow(unused_imports)]
                    use super::*;
                    #inner
                }
            });
        }
        // Ancillary trees: each nested message's tree is already wrapped in
        // its own `pub mod {nested_name}`; we collect them as siblings.
        nested_oneof_tree.extend(nested_out.oneof_tree);
        nested_view_tree.extend(nested_out.view_tree);
        nested_view_oneof_tree.extend(nested_out.view_oneof_tree);
    }

    // `extend` declarations nested inside this message. The consts land in
    // the message's `pub mod`, one `super::` hop from package level.
    // `proto_fqn` is the scope for JSON full_name construction.
    let (nested_extensions, nested_ext_json, nested_ext_text) =
        crate::extension::generate_extensions(
            ctx,
            &msg.extension,
            current_package,
            // Extensions declared inside this message live in its module
            // (`pub mod {msg} { pub fn register_extensions() { ... } }`),
            // so type references inside them need one additional `super::`
            // hop beyond the current message's own nesting.
            nesting + 1,
            features,
            proto_fqn,
        )?;
    for id in nested_ext_json {
        reg_paths.json_ext.push(quote! { #id });
    }
    for id in nested_ext_text {
        reg_paths.text_ext.push(quote! { #id });
    }

    // "Natural-path" re-exports of this message's ancillary types — `pub use`
    // lines pointing into the canonical `__buffa::` tree. Skipped when the
    // natural name would collide with a real nested item (or another
    // re-export); see `collect_natural_reexports`.
    let natural_reexports = collect_natural_reexports(scope, msg, &oneof_idents, &non_map_nested);

    // Owned-module items: nested enums, nested message structs + sub-modules,
    // and message-nested extensions. Oneof enums move out to `oneof_tree`.
    // Natural-path re-exports come last so that, if a message has only
    // re-exports (no nested types), the surrounding `pub mod {msg}` block is
    // still emitted.
    let owned_mod = quote! {
        #(#nested_enums)*
        #nested_items
        #nested_extensions
        #natural_reexports
    };

    // This message's view (struct + view-oneof enums), emitted with
    // `nesting` = msg-nesting; view.rs adds the +2/+3 kind-depth offsets.
    let (own_view_top, own_view_oneofs) = if ctx.config.generate_views {
        crate::view::generate_view_with_nesting(scope, msg, rust_name)?
    } else {
        (TokenStream::new(), TokenStream::new())
    };

    // Wrap ancillary streams in this message's `pub mod {snake_name}`.
    // View structs sit *beside* their message's module (so `Foo`'s view is
    // at `view::FooView`, `Foo.Bar`'s at `view::foo::BarView`); oneof and
    // view-oneof enums sit *inside* it (so `Foo`'s oneof `kind` is at
    // `oneof::foo::Kind`).
    let wrap = |body: TokenStream| -> TokenStream {
        if body.is_empty() {
            return TokenStream::new();
        }
        quote! {
            pub mod #mod_ident {
                #[allow(unused_imports)]
                use super::*;
                #body
            }
        }
    };
    let oneof_tree = wrap(quote! { #(#oneof_enums)* #nested_oneof_tree });
    let view_oneof_tree = wrap(quote! { #own_view_oneofs #nested_view_oneof_tree });
    let view_tree = {
        let nested_wrapped = wrap(nested_view_tree);
        quote! { #own_view_top #nested_wrapped }
    };

    // Generate a manual Debug impl that excludes internal __buffa_ fields.
    // Fields marked `[debug_redact = true]` print DEBUG_REDACT_PLACEHOLDER
    // instead of their value, mirroring protobuf's DebugString redaction.
    let struct_name_str = name_ident.to_string();
    // Labels match what `#[derive(Debug)]` prints: raw-ident fields (`r#type`)
    // show as `type`, consistent with the view struct's Debug impl.
    let debug_field_names: Vec<String> = debug_fields
        .iter()
        .map(|(id, _)| id.to_string().trim_start_matches("r#").to_string())
        .collect();
    let debug_field_values: Vec<TokenStream> = debug_fields
        .iter()
        .map(|(id, redacted)| {
            if *redacted {
                quote! { &::core::format_args!(#DEBUG_REDACT_PLACEHOLDER) }
            } else {
                quote! { &self.#id }
            }
        })
        .collect();
    let debug_impl = quote! {
        impl ::core::fmt::Debug for #name_ident {
            fn fmt(&self, f: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result {
                f.debug_struct(#struct_name_str)
                    #(.field(#debug_field_names, #debug_field_values))*
                    .finish()
            }
        }
    };

    let message_doc =
        crate::comments::doc_attrs_resolved(ctx.comment(proto_fqn), proto_fqn, &ctx.type_map);

    let with_setters_impl = if ctx.config.generate_with_setters && !setter_methods.is_empty() {
        quote! {
            impl #name_ident {
                #setter_methods
            }
        }
    } else {
        quote! {}
    };

    let top_level = quote! {
        #message_doc
        #[derive(Clone, PartialEq, #derive_default)]
        #serde_struct_derive
        #arbitrary_derive
        #custom_type_attrs
        #custom_message_attrs
        pub struct #name_ident {
            #(#direct_fields)*
            #(#oneof_struct_fields)*
            #unknown_fields_field
        }

        #debug_impl

        #custom_default_impl

        impl #name_ident {
            /// Protobuf type URL for this message, for use with `Any::pack` and
            /// `Any::unpack_if`.
            ///
            /// Format: `type.googleapis.com/<fully.qualified.TypeName>`
            pub const TYPE_URL: &'static str = #type_url;
        }

        #with_setters_impl

        #message_impl

        #text_impl

        #custom_deserialize

        #proto_elem_json_impl

        #ext_json_wrapper_def

        #json_any_const
        #text_any_const
    };

    Ok(MessageOutput {
        owned_top: top_level,
        owned_mod,
        oneof_tree,
        view_tree,
        view_oneof_tree,
        reg: reg_paths,
    })
}

// ── Natural-path re-exports ──────────────────────────────────────────────────
//
// Ancillary types (views, oneof enums, view-oneof enums) live unconditionally
// under the canonical `__buffa::` tree so their paths can never collide with
// user proto types. As an ergonomic convenience we *also* `pub use` each one
// at the "natural" location a user would look for first — the message's
// snake_case module — but only when the natural name is unambiguous. The
// canonical path is the source of truth: generated method signatures, field
// types, and downstream codegen always use `__buffa::…`.
//
// Natural names within `pub mod {msg} { … }`:
// - nested message `Bar`'s view  → `BarView` ← `__buffa::view::<msg>::BarView`
// - oneof `kind`'s enum          → `Kind`    ← `__buffa::oneof::<msg>::Kind`
// - oneof `kind`'s view enum     → `KindView`← `__buffa::view::oneof::<msg>::Kind`
//
// A re-export is silently skipped when its natural name is already occupied
// by a real nested item (message, enum, extension const, or the snake_case
// sub-module of a nested message), or by another candidate re-export. Both
// participants in a candidate↔candidate collision are skipped — never
// "first one wins" — so the result is order-independent.

/// One candidate `pub use` re-export targeting a generated Rust module.
pub(crate) struct ReexportCandidate {
    /// Natural name at the target location (the leaf the user will write).
    pub(crate) name: String,
    /// `pub use` statement, ready to splice into the target module.
    pub(crate) tokens: TokenStream,
}

/// Build the `pub use` re-export block for a message's `pub mod {msg} { … }`.
///
/// Returns an empty stream when there are no surviving candidates (so the
/// caller's `owned_mod.is_empty()` check still works for messages with no
/// nested items and no re-exports).
fn collect_natural_reexports(
    scope: MessageScope<'_>,
    msg: &DescriptorProto,
    oneof_idents: &std::collections::HashMap<usize, Ident>,
    non_map_nested: &[&DescriptorProto],
) -> TokenStream {
    use std::collections::BTreeSet;

    let MessageScope {
        ctx,
        current_package,
        proto_fqn,
        nesting,
        ..
    } = scope;

    if !ctx.config.generate_views && oneof_idents.is_empty() {
        // Nothing in the `__buffa::` tree relates to this message's module.
        return TokenStream::new();
    }

    // Names already occupied inside `pub mod {msg} { … }` by real items.
    let mut occupied: BTreeSet<String> = BTreeSet::new();
    for nested in non_map_nested {
        let name = nested.name.as_deref().unwrap_or("");
        // Both the nested struct (`Bar`) and its sub-module (`bar`) reserve a
        // type-namespace slot. The sub-module name only matters when it
        // happens to be PascalCase (e.g. proto `message X` → `pub mod x`
        // is benign, but proto `message FooView` → `pub mod foo_view` is
        // also benign). We track both for safety with no real cost.
        occupied.insert(name.to_string());
        occupied.insert(crate::oneof::to_snake_case(name));
    }
    for e in &msg.enum_type {
        occupied.insert(e.name.as_deref().unwrap_or("").to_string());
    }
    for ext in &msg.extension {
        occupied.insert(
            crate::extension::extension_const_ident(ext.name.as_deref().unwrap_or("")).to_string(),
        );
    }

    // The `pub use` statements live one module level deeper than the struct.
    let from_nesting = nesting + 1;
    let view_prefix = ancillary_prefix(
        AncillaryKind::View,
        current_package,
        proto_fqn,
        from_nesting,
    );
    let oneof_prefix = ancillary_prefix(
        AncillaryKind::Oneof,
        current_package,
        proto_fqn,
        from_nesting,
    );
    let view_oneof_prefix = ancillary_prefix(
        AncillaryKind::ViewOneof,
        current_package,
        proto_fqn,
        from_nesting,
    );

    let mut candidates: Vec<ReexportCandidate> = Vec::new();

    // `#[doc(inline)]` makes rustdoc render the full type page at the
    // natural path instead of a "Re-export of …" stub pointing back at
    // `__buffa::`. The re-exports are the documented entry point; the
    // canonical path is the spelled-out fallback.
    let inline = quote! { #[doc(inline)] };

    // Owned oneof enums: `__buffa::oneof::<msg>::Kind` → `Kind`.
    let mut oneof_pairs: Vec<(usize, &Ident)> = oneof_idents.iter().map(|(k, v)| (*k, v)).collect();
    oneof_pairs.sort_by_key(|(idx, _)| *idx);
    for (_, enum_ident) in &oneof_pairs {
        candidates.push(ReexportCandidate {
            name: enum_ident.to_string(),
            tokens: quote! { #inline pub use #oneof_prefix #enum_ident; },
        });
    }

    if ctx.config.generate_views {
        let views_gate = ctx.config.feature_gates().views;
        // Nested-message views: `__buffa::view::<msg>::BarView` → `BarView`.
        // The owned-view wrapper rides along: `BarOwnedView` → `BarOwnedView`.
        for nested in non_map_nested {
            let view_ident = format_ident!("{}View", nested.name.as_deref().unwrap_or(""));
            candidates.push(ReexportCandidate {
                name: view_ident.to_string(),
                tokens: crate::feature_gates::cfg_block(
                    quote! { #inline pub use #view_prefix #view_ident; },
                    views_gate,
                ),
            });
            let owned_view_ident =
                format_ident!("{}OwnedView", nested.name.as_deref().unwrap_or(""));
            candidates.push(ReexportCandidate {
                name: owned_view_ident.to_string(),
                tokens: crate::feature_gates::cfg_block(
                    quote! { #inline pub use #view_prefix #owned_view_ident; },
                    views_gate,
                ),
            });
        }
        // View oneof enums: `__buffa::view::oneof::<msg>::Kind` → `KindView`.
        for (_, enum_ident) in &oneof_pairs {
            let view_ident = format_ident!("{}View", enum_ident);
            candidates.push(ReexportCandidate {
                name: view_ident.to_string(),
                tokens: crate::feature_gates::cfg_block(
                    quote! { #inline pub use #view_oneof_prefix #enum_ident as #view_ident; },
                    views_gate,
                ),
            });
        }
    }

    emit_surviving_reexports(candidates, &occupied)
}

/// Filter `candidates` against `occupied` and against each other, emitting
/// only the unambiguous ones.
///
/// A candidate survives iff its name is absent from `occupied` and it is the
/// only candidate targeting that name. When two or more candidates collide
/// with each other, *all* of them are dropped — never "first one wins" — so
/// the result is order-independent and stable across descriptor reordering.
pub(crate) fn emit_surviving_reexports(
    candidates: Vec<ReexportCandidate>,
    occupied: &std::collections::BTreeSet<String>,
) -> TokenStream {
    use std::collections::BTreeMap;
    let mut counts: BTreeMap<String, usize> = BTreeMap::new();
    for c in &candidates {
        *counts.entry(c.name.clone()).or_insert(0) += 1;
    }
    let mut out = TokenStream::new();
    for c in candidates {
        if occupied.contains(&c.name) || counts[&c.name] > 1 {
            continue;
        }
        out.extend(c.tokens);
    }
    out
}

// ── Custom Deserialize for messages with oneofs ──────────────────────────────
//
// serde's `#[serde(flatten)]` on `Option<T>` silently swallows deserialization
// errors from `T::deserialize`, converting them to `None`.  This prevents
// oneof duplicate-field rejection from propagating.  For messages that contain
// at least one real oneof, we generate a hand-written `Deserialize` impl that
// handles oneof fields inline in the message visitor.

/// Generate a custom `Deserialize` impl for a message that has oneofs.
///
/// Regular fields are deserialized using the same serde helpers as the
/// derive-based approach.  Oneof fields are handled inline with
/// `NullableDeserializeSeed` (null -> variant not set) and duplicate
/// detection (error on second non-null variant).
fn generate_custom_deserialize(
    scope: MessageScope<'_>,
    msg: &DescriptorProto,
    name_ident: &proc_macro2::Ident,
    oneof_prefix: &TokenStream,
    resolver: &crate::imports::ImportResolver,
    has_extension_ranges: bool,
    oneof_idents: &std::collections::HashMap<usize, Ident>,
) -> Result<TokenStream, CodeGenError> {
    let MessageScope {
        ctx,
        current_package,
        proto_fqn,
        features,
        nesting,
        ..
    } = scope;
    let mut field_vars = Vec::new();
    let mut match_arms = Vec::new();
    let mut field_inits = Vec::new();

    // Regular (non-oneof) fields.
    for field in &msg.field {
        if is_real_oneof_member(field) {
            continue;
        }
        let (var, arm, init) = custom_deser_regular_field(scope, msg, field, resolver)?;
        field_vars.push(var);
        match_arms.push(arm);
        field_inits.push(init);
    }

    // Oneof groups.
    for (idx, oneof) in msg.oneof_decl.iter().enumerate() {
        let result = custom_deser_oneof_group(
            ctx,
            msg,
            idx,
            oneof,
            current_package,
            proto_fqn,
            oneof_prefix,
            features,
            resolver,
            oneof_idents,
            nesting,
        )?;
        let Some((var, arms, init)) = result else {
            continue;
        };
        field_vars.push(var);
        match_arms.extend(arms);
        field_inits.push(init);
    }

    // `"[pkg.ext]"` keys — collect the decoded UnknownField records in a
    // local Vec, then push into `__r.__buffa_unknown_fields` after `__r` is
    // built below (it doesn't exist yet inside the match loop).
    // Emitted only when the message declares `extensions N to M;` AND
    // preserve_unknown_fields is on (otherwise there's nowhere to store them).
    let (ext_var, ext_arm, ext_init) = if has_extension_ranges && ctx.config.preserve_unknown_fields
    {
        let proto_fqn_lit = proto_fqn;
        let var = quote! {
            let mut __ext_records: ::buffa::alloc::vec::Vec<::buffa::UnknownField>
                = ::buffa::alloc::vec::Vec::new();
        };
        let arm = quote! {
            __k if __k.starts_with('[') => {
                let __v: ::buffa::serde_json::Value = map.next_value()?;
                match ::buffa::extension_registry::deserialize_extension_key(
                    #proto_fqn_lit, __k, __v,
                ) {
                    ::core::option::Option::Some(::core::result::Result::Ok(__recs)) => {
                        for __rec in __recs {
                            __ext_records.push(__rec);
                        }
                    }
                    ::core::option::Option::Some(::core::result::Result::Err(__e)) => {
                        return ::core::result::Result::Err(
                            <A::Error as ::serde::de::Error>::custom(__e),
                        );
                    }
                    ::core::option::Option::None => {}
                }
            }
        };
        let init = quote! {
            for __rec in __ext_records {
                __r.__buffa_unknown_fields.push(__rec);
            }
        };
        (var, arm, init)
    } else {
        (quote! {}, quote! {}, quote! {})
    };

    // Assemble the impl block.
    let expecting_msg = format!("struct {name_ident}");

    Ok(quote! {
        impl<'de> serde::Deserialize<'de> for #name_ident {
            fn deserialize<D: serde::Deserializer<'de>>(d: D) -> ::core::result::Result<Self, D::Error> {
                struct _V;
                impl<'de> serde::de::Visitor<'de> for _V {
                    type Value = #name_ident;

                    fn expecting(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
                        f.write_str(#expecting_msg)
                    }

                    #[allow(clippy::field_reassign_with_default)]
                    fn visit_map<A: serde::de::MapAccess<'de>>(
                        self,
                        mut map: A,
                    ) -> ::core::result::Result<#name_ident, A::Error> {
                        #(#field_vars)*
                        #ext_var

                        while let Some(key) = map.next_key::<::buffa::alloc::string::String>()? {
                            match key.as_str() {
                                #(#match_arms)*
                                #ext_arm
                                _ => { map.next_value::<serde::de::IgnoredAny>()?; }
                            }
                        }

                        // Start from the struct's Default (which may be a
                        // custom impl honouring proto2 [default = ...]
                        // annotations), then overwrite fields present in JSON.
                        let mut __r = <#name_ident as ::core::default::Default>::default();
                        #(#field_inits)*
                        #ext_init
                        Ok(__r)
                    }
                }
                d.deserialize_map(_V)
            }
        }
    })
}

/// Generate a `DeserializeSeed` wrapper that calls `inner` inside `deserialize`.
///
/// Produces a block expression:
/// ```ignore
/// { struct _S; impl DeserializeSeed for _S { ... } map.next_value_seed(_S)? }
/// ```
/// where the body of `deserialize` is `inner`, which should return
/// `Result<rust_type, D::Error>` using `d` as the deserializer binding.
fn deser_seed_expr(rust_type: &TokenStream, inner: TokenStream) -> TokenStream {
    quote! {{
        struct _S;
        impl<'de> serde::de::DeserializeSeed<'de> for _S {
            type Value = #rust_type;
            fn deserialize<D: serde::Deserializer<'de>>(self, d: D)
                -> ::core::result::Result<#rust_type, D::Error>
            {
                #inner
            }
        }
        map.next_value_seed(_S)?
    }}
}

/// Emit the variable declaration, match arm, and field initializer for one
/// regular (non-oneof) field in a custom `Deserialize` impl.
fn custom_deser_regular_field(
    scope: MessageScope<'_>,
    msg: &DescriptorProto,
    field: &crate::generated::descriptor::FieldDescriptorProto,
    resolver: &crate::imports::ImportResolver,
) -> Result<(TokenStream, TokenStream, TokenStream), CodeGenError> {
    let MessageScope { ctx, features, .. } = scope;
    let field_name = field
        .name
        .as_deref()
        .ok_or(CodeGenError::MissingField("field.name"))?;
    let json_name = field.json_name.as_deref().unwrap_or(field_name);
    let var_ident = format_ident!("__f_{}", field_name);
    let field_ident = make_field_ident(field_name);

    let info = classify_field(scope, msg, field, resolver)?;
    let rust_type = &info.rust_type;

    let field_features = crate::features::resolve_field(ctx, field, features);
    let (with_module, null_deser) = field_deser_modules(
        crate::impl_message::effective_type(ctx, field, features),
        &info,
        &field_features,
    );

    // Deserialization expression for the field value.
    let deser_expr = if is_value_field(field, info.is_repeated, info.is_map) {
        // MessageField<Value> must forward null to Value::deserialize
        // rather than treating it as "field absent".
        let inner = quote! { ::buffa::json_helpers::message_field_always_present(d) };
        deser_seed_expr(rust_type, inner)
    } else if let Some(module) = with_module {
        let module_path: syn::Path = syn::parse_str(module)
            .map_err(|_| CodeGenError::InvalidTypePath(module.to_string()))?;
        let inner = quote! { #module_path::deserialize(d) };
        deser_seed_expr(rust_type, inner)
    } else if null_deser.is_some() {
        // repeated / map without a specific helper -> null_as_default
        let inner = quote! { ::buffa::json_helpers::null_as_default(d) };
        deser_seed_expr(rust_type, inner)
    } else {
        quote! { map.next_value::<#rust_type>()? }
    };

    // Match arm accepting both json_name and proto_name.
    let arm = if json_name != field_name {
        quote! { #json_name | #field_name => { #var_ident = Some(#deser_expr); } }
    } else {
        quote! { #json_name => { #var_ident = Some(#deser_expr); } }
    };

    let var_decl = quote! { let mut #var_ident: ::core::option::Option<#rust_type> = None; };
    // Overwrite only if present — missing fields keep the struct's Default
    // (which honours proto2 [default = X], unlike <T>::default()).
    let field_init = quote! {
        if let ::core::option::Option::Some(v) = #var_ident { __r.#field_ident = v; }
    };
    Ok((var_decl, arm, field_init))
}

/// Emit the variable declaration, match arms, and field initializer for one
/// oneof group in a custom `Deserialize` impl.
///
/// Returns `None` if the oneof has no real (non-synthetic) fields.
#[allow(clippy::too_many_arguments)]
fn custom_deser_oneof_group(
    ctx: &CodeGenContext,
    msg: &DescriptorProto,
    idx: usize,
    oneof: &crate::generated::descriptor::OneofDescriptorProto,
    current_package: &str,
    proto_fqn: &str,
    oneof_prefix: &TokenStream,
    features: &ResolvedFeatures,
    resolver: &crate::imports::ImportResolver,
    oneof_idents: &std::collections::HashMap<usize, Ident>,
    nesting: usize,
) -> Result<Option<(TokenStream, Vec<TokenStream>, TokenStream)>, CodeGenError> {
    let oneof_name = oneof
        .name
        .as_deref()
        .ok_or(CodeGenError::MissingField("oneof.name"))?;

    let enum_ident = match oneof_idents.get(&idx) {
        Some(id) => id.clone(),
        None => return Ok(None),
    };

    let var_ident = format_ident!("__oneof_{}", oneof_name);
    let field_ident = make_field_ident(oneof_name);

    let var_decl =
        quote! { let mut #var_ident: ::core::option::Option<#oneof_prefix #enum_ident> = None; };
    let mut arms = Vec::new();

    for field in &msg.field {
        if !is_real_oneof_member(field) || field.oneof_index != Some(idx as i32) {
            continue;
        }
        let proto_name = field
            .name
            .as_deref()
            .ok_or(CodeGenError::MissingField("field.name"))?;
        let json_name = field.json_name.as_deref().unwrap_or(proto_name);
        let variant_ident = crate::oneof::oneof_variant_ident(proto_name);
        let field_type = crate::impl_message::effective_type(ctx, field, features);
        // bytes_fields override: feeds #variant_type into the _DeserSeed
        // return type, which pins the generic T in json_helpers::bytes::
        // deserialize to Bytes (vs the Vec<u8> default). No downstream
        // shim needed — the helper is generic over T: From<Vec<u8>>.
        let variant_string_repr = if field_type == Type::TYPE_STRING {
            crate::impl_message::field_string_repr(ctx, proto_fqn, proto_name)
        } else {
            crate::StringRepr::String
        };
        let variant_type = if field_type == Type::TYPE_BYTES
            && crate::impl_message::field_uses_bytes(ctx, proto_fqn, proto_name)
        {
            quote! { ::buffa::bytes::Bytes }
        } else if field_type == Type::TYPE_STRING && !variant_string_repr.is_default() {
            variant_string_repr.type_path(resolver)
        } else {
            scalar_or_message_type_nested(ctx, field, current_package, nesting, features, resolver)?
        };

        let qualified_enum: TokenStream = quote! { #oneof_prefix #enum_ident };
        let arm = crate::oneof::oneof_variant_deser_arm(&crate::oneof::OneofVariantDeserInput {
            variant_ident: &variant_ident,
            variant_type: &variant_type,
            json_name,
            proto_name,
            field_type,
            null_forward: crate::oneof::null_is_valid_value(field),
            is_boxed: crate::oneof::variant_boxed(
                ctx,
                field_type,
                &format!(".{proto_fqn}.{oneof_name}.{proto_name}"),
            ),
            enum_ident: &qualified_enum,
            result_var: &var_ident,
            oneof_name,
        });
        arms.push(arm);
    }

    let field_init = quote! { __r.#field_ident = #var_ident; };
    Ok(Some((var_decl, arms, field_init)))
}

/// Returns `true` for singular `google.protobuf.Value` fields.
///
/// For these fields, JSON `null` represents a valid `NullValue` rather than
/// "field absent", so deserialization must forward null to `Value::deserialize`.
fn is_value_field(
    field: &crate::generated::descriptor::FieldDescriptorProto,
    is_repeated: bool,
    is_map: bool,
) -> bool {
    field.r#type.unwrap_or_default() == Type::TYPE_MESSAGE
        && !is_repeated
        && !is_map
        && field.type_name.as_deref() == Some(".google.protobuf.Value")
}

/// Resolved Rust type and map-entry metadata for a single field.
#[derive(Debug)]
struct FieldInfo {
    rust_type: TokenStream,
    /// Type to use in the struct field declaration. Differs from `rust_type`
    /// only for self-referential message fields, where it uses `Self` instead
    /// of the concrete name. `rust_type` stays concrete for serde-deserialize
    /// codegen, which runs inside a local Visitor impl where `Self` binds to
    /// the wrong type.
    struct_field_type: TokenStream,
    is_repeated: bool,
    is_map: bool,
    /// Whether this field has explicit presence and uses `Option<T>` wrapping.
    /// True for proto3 `optional` scalars and proto2 `optional` (non-required)
    /// scalars. Not true for message fields (which use `MessageField<T>`),
    /// repeated fields, or proto2 `required` fields.
    is_optional: bool,
    /// True when the field is proto type `bytes` AND matches the `bytes_fields`
    /// config — i.e. the struct field type is `bytes::Bytes` not `Vec<u8>`.
    use_bytes: bool,
    /// True when the field is `map<K, bytes>` AND the outer map field matches
    /// the `bytes_fields` config — i.e. the map value type is `bytes::Bytes`
    /// not `Vec<u8>`. Mutually exclusive with `use_bytes` (a map field's outer
    /// type is `MESSAGE`, not `BYTES`).
    map_value_use_bytes: bool,
    /// The owned Rust type used for this field when it is proto type `string`
    /// (singular, optional, or repeated; map keys/values are unaffected).
    /// [`StringRepr::String`] for non-string fields and for string fields with
    /// no matching `string_fields` rule.
    string_repr: crate::StringRepr,
    /// Proto2 `required` (or editions `LEGACY_REQUIRED`). Required fields
    /// must always appear in JSON output regardless of value, matching the
    /// binary encoder's always-encode semantics.
    is_required: bool,
    map_key_type: Option<Type>,
    map_value_type: Option<Type>,
    /// Closedness of the **value enum** when `map_value_type == TYPE_ENUM`.
    /// Resolved from the map entry's value-field descriptor (which is
    /// TYPE_ENUM, so `resolve_field` correctly overlays the referenced
    /// enum's `enum_type`). Cannot be derived from the map field's own
    /// features — that field is TYPE_MESSAGE so the overlay doesn't fire.
    /// See `map_serde_module`.
    map_value_enum_closed: Option<bool>,
    /// The bare inner type `T` when `is_optional = true` (`rust_type` is `Option<T>`).
    /// `None` for all non-optional fields.
    inner_opt_type: Option<TokenStream>,
}

/// Resolve the Rust type and map-entry metadata for a single field.
///
/// Shared by `generate_field` (struct declaration) and the custom
/// deserialize codegen to avoid duplicating the type-resolution
/// if/else chain.
fn classify_field(
    scope: MessageScope<'_>,
    msg: &DescriptorProto,
    field: &crate::generated::descriptor::FieldDescriptorProto,
    resolver: &crate::imports::ImportResolver,
) -> Result<FieldInfo, CodeGenError> {
    let MessageScope {
        ctx,
        current_package,
        proto_fqn,
        features,
        nesting,
    } = scope;
    let label = field.label.unwrap_or_default();
    let field_type = crate::impl_message::effective_type(ctx, field, features);
    let is_repeated = label == Label::LABEL_REPEATED;
    let map_entry = if is_repeated {
        find_map_entry(msg, field)
    } else {
        None
    };
    let is_map = map_entry.is_some();
    let is_optional = is_explicit_presence_scalar(field, field_type, features);
    let is_required = crate::impl_message::is_required_field(field, features);

    // Check if this bytes field should use bytes::Bytes.
    let field_name = field.name.as_deref().unwrap_or("");
    let field_fqn = format!(".{}.{}", proto_fqn, field_name);
    let use_bytes = field_type == Type::TYPE_BYTES && ctx.use_bytes_type(&field_fqn);

    // For `map<K, bytes>`, the outer field type is MESSAGE (synthetic entry),
    // so `use_bytes` is false; the value type is decided by the shared
    // `map_value_use_bytes` predicate (also used by the binary/text decoders and
    // the view→owned conversion, so all sites stay in agreement). The bytes-key
    // carve-out is documented there.
    let map_value_use_bytes = map_entry.is_some_and(|e| {
        crate::impl_message::map_value_use_bytes(
            ctx,
            map_entry_key_type(ctx, e, features),
            map_entry_value_type(ctx, e, features),
            proto_fqn,
            field_name,
        )
    });

    let bytes_type = if use_bytes {
        quote! { ::buffa::bytes::Bytes }
    } else {
        let vec = resolver.vec();
        quote! { #vec<u8> }
    };

    // Configurable owned representation for `string` fields (default `String`).
    // Map keys/values are unaffected — they always use `String`. (The bytes
    // path now propagates `bytes_fields` to map values via
    // `map_value_use_bytes`; the string path has no equivalent yet.)
    let string_repr = if field_type == Type::TYPE_STRING {
        ctx.string_repr(&field_fqn)
    } else {
        crate::StringRepr::String
    };
    let string_type = string_repr.type_path(resolver);

    let mut inner_opt_type: Option<TokenStream> = None;
    let rust_type = if let Some(entry) = map_entry {
        map_rust_type_from_entry(scope, entry, map_value_use_bytes, resolver)?
    } else if is_repeated {
        let elem = if field_type == Type::TYPE_BYTES {
            bytes_type
        } else if field_type == Type::TYPE_STRING {
            string_type
        } else {
            scalar_or_message_type_nested(ctx, field, current_package, nesting, features, resolver)?
        };
        {
            let vec = resolver.vec();
            quote! { #vec<#elem> }
        }
    } else if field_type == Type::TYPE_MESSAGE || field_type == Type::TYPE_GROUP {
        let inner = resolve_message_type(scope, field)?;
        {
            let mf = resolver.message_field();
            quote! { #mf<#inner> }
        }
    } else if is_optional {
        let inner = if field_type == Type::TYPE_ENUM {
            resolve_enum_type(scope, field, resolver)?
        } else if field_type == Type::TYPE_BYTES {
            bytes_type
        } else if field_type == Type::TYPE_STRING {
            string_type
        } else {
            scalar_rust_type(field_type, resolver)?
        };
        inner_opt_type = Some(inner.clone());
        {
            let opt = resolver.option();
            quote! { #opt<#inner> }
        }
    } else if field_type == Type::TYPE_ENUM {
        resolve_enum_type(scope, field, resolver)?
    } else if field_type == Type::TYPE_BYTES {
        bytes_type
    } else if field_type == Type::TYPE_STRING {
        string_type
    } else {
        scalar_rust_type(field_type, resolver)?
    };

    // Self-referential struct fields (e.g. DescriptorProto.nested_type) can
    // use `Self` in the struct declaration. Only message-typed, non-map
    // fields qualify. `rust_type` stays concrete for the serde-deserialize
    // path — that codegen runs inside `impl Visitor for _V` where `Self`
    // means `_V`, not the message.
    let self_fqn = format!(".{proto_fqn}");
    let is_self_ref = field.type_name.as_deref() == Some(self_fqn.as_str()) && !is_map;
    let struct_field_type = if is_self_ref {
        if is_repeated {
            let vec = resolver.vec();
            quote! { #vec<Self> }
        } else {
            let mf = resolver.message_field();
            quote! { #mf<Self> }
        }
    } else {
        rust_type.clone()
    };

    let map_key_type = map_entry.and_then(|e| map_entry_key_type(ctx, e, features));
    let map_value_type = map_entry.and_then(|e| map_entry_value_type(ctx, e, features));

    // For enum-valued maps, resolve closedness via the MapEntry's value
    // field descriptor (TYPE_ENUM — resolve_field overlays the referenced
    // enum's enum_type). Matches what map_rust_type_from_entry →
    // resolve_enum_type does for the Rust type, so serde module selection
    // and Rust type agree even when a per-enum CLOSED override differs
    // from the file-level default (editions only).
    let map_value_enum_closed = if map_value_type == Some(Type::TYPE_ENUM) {
        map_entry
            .and_then(|e| e.field.iter().find(|f| f.number == Some(2)))
            .map(|val_fd| {
                let val_features = crate::features::resolve_field(ctx, val_fd, features);
                is_closed_enum(&val_features)
            })
    } else {
        None
    };

    Ok(FieldInfo {
        rust_type,
        struct_field_type,
        is_repeated,
        is_map,
        is_optional,
        is_required,
        use_bytes,
        map_value_use_bytes,
        string_repr,
        map_key_type,
        map_value_type,
        map_value_enum_closed,
        inner_opt_type,
    })
}

/// Setter method info for a single explicit-presence field.
struct SetterInfo {
    ident: Ident,
    param_type: TokenStream,
    /// `true`  → emit `Some(value.into())` and take `impl Into<T>`.
    ///   Set for `string` (accepts `&str`), `bytes` (accepts `b"..."`
    ///   array literals via `From<&[u8; N]> for Vec<u8>`, or `Vec<u8>`
    ///   for `bytes_fields`-tagged `bytes::Bytes`), and `enum`
    ///   (accepts the bare variant via `From<E> for EnumValue<E>`).
    /// `false` → emit `Some(value)` and take `T` directly.
    ///   Set for numeric scalars and `bool` — `impl Into<i32>` would
    ///   make integer literals ambiguous (`30` could be `i8`/`i16`/...);
    ///   the bare type lets inference settle them.
    use_into: bool,
}

/// Generate a single field declaration.
///
/// Returns `None` for fields that belong to a real oneof — those are
/// represented by the `Option<OneofEnum>` field added by `generate_message`.
/// Result of generating a single struct field: the field declaration tokens
/// and the field identifier (for use in the manual `Debug` impl).
struct GeneratedField {
    tokens: TokenStream,
    ident: Ident,
    setter: Option<SetterInfo>,
    /// Field carries `[debug_redact = true]`; the generated `Debug` impl
    /// prints [`DEBUG_REDACT_PLACEHOLDER`] instead of the value.
    debug_redact: bool,
}

fn generate_field(
    scope: MessageScope<'_>,
    msg: &DescriptorProto,
    field: &crate::generated::descriptor::FieldDescriptorProto,
    resolver: &crate::imports::ImportResolver,
) -> Result<Option<GeneratedField>, CodeGenError> {
    let MessageScope {
        ctx,
        proto_fqn,
        features,
        ..
    } = scope;
    let field_name = field
        .name
        .as_deref()
        .ok_or(CodeGenError::MissingField("field.name"))?;
    let field_number = field.number.unwrap_or(0);

    // Real oneof fields are excluded from the struct body.
    if is_real_oneof_member(field) {
        return Ok(None);
    }

    let info = classify_field(scope, msg, field, resolver)?;
    let rust_name = make_field_ident(field_name);

    let field_fqn = format!("{}.{}", proto_fqn, field_name);
    let tag_line = format!("Field {field_number}: `{field_name}`");
    let doc = crate::comments::doc_attrs_with_tag_resolved(
        ctx.comment(&field_fqn),
        &tag_line,
        proto_fqn,
        &ctx.type_map,
    );
    let serde_attr = if ctx.config.generate_json {
        serde_field_attr(ctx, field, field_name, &info, features)
    } else {
        quote! {}
    };
    let custom_field_attrs =
        CodeGenContext::matching_attributes(&ctx.config.field_attributes, &field_fqn)?;
    let arbitrary_field_attr = if ctx.config.generate_arbitrary && info.use_bytes && !info.is_map {
        let helper = if info.is_optional {
            quote! { ::buffa::__private::arbitrary_bytes_opt }
        } else if info.is_repeated {
            quote! { ::buffa::__private::arbitrary_bytes_vec }
        } else {
            quote! { ::buffa::__private::arbitrary_bytes }
        };
        quote! { #[cfg_attr(feature = "arbitrary", arbitrary(with = #helper))] }
    } else if ctx.config.generate_arbitrary && info.map_value_use_bytes {
        // `HashMap<K, Bytes>` has no native `Arbitrary` impl (`Bytes` lacks
        // one); generate a per-key-type shim that builds `HashMap<K, Vec<u8>>`
        // first and maps values to `Bytes`. Wire-equivalent.
        quote! { #[cfg_attr(feature = "arbitrary", arbitrary(with = ::buffa::__private::arbitrary_bytes_map))] }
    } else if ctx.config.generate_arbitrary
        && info.string_repr == crate::StringRepr::EcoString
        && !info.is_map
    {
        // `ecow::EcoString` has no native `Arbitrary` impl; smol_str and
        // compact_str do, so only EcoString needs the shim.
        let helper = if info.is_optional {
            quote! { ::buffa::__private::arbitrary_ecow_opt }
        } else if info.is_repeated {
            quote! { ::buffa::__private::arbitrary_ecow_vec }
        } else {
            quote! { ::buffa::__private::arbitrary_ecow }
        };
        quote! { #[cfg_attr(feature = "arbitrary", arbitrary(with = #helper))] }
    } else {
        quote! {}
    };
    let rust_type = &info.struct_field_type;
    let tokens = quote! {
        #doc
        #serde_attr
        #arbitrary_field_attr
        #custom_field_attrs
        pub #rust_name: #rust_type,
    };

    // Use inner_opt_type as the gate: it is set only when classify_field
    // actually took the is_optional branch (i.e. the struct field is Option<T>).
    // is_optional alone is not sufficient — proto2 repeated fields can have
    // is_optional=true (explicit-presence default) while is_repeated=true.
    let setter = if let Some(inner) = &info.inner_opt_type {
        let field_type = crate::impl_message::effective_type(ctx, field, features);
        let setter_ident = format_ident!("with_{}", field_name);
        // impl Into<T> where a common conversion exists:
        //   String: &str. Vec<u8>: &[u8; N] (From<&[T; N]> stable since Rust 1.74).
        //   bytes::Bytes: Vec<u8>. EnumValue<E>: E (From<E> impl on EnumValue).
        let (param_type, use_into) = match field_type {
            Type::TYPE_STRING | Type::TYPE_BYTES | Type::TYPE_ENUM => {
                (quote! { impl Into<#inner> }, true)
            }
            _ => (quote! { #inner }, false),
        };
        Some(SetterInfo {
            ident: setter_ident,
            param_type,
            use_into,
        })
    } else {
        None
    };

    Ok(Some(GeneratedField {
        tokens,
        ident: rust_name,
        setter,
        debug_redact: is_debug_redacted(field),
    }))
}

pub(crate) fn is_map_field(
    msg: &DescriptorProto,
    field: &crate::generated::descriptor::FieldDescriptorProto,
) -> bool {
    field.r#type.unwrap_or_default() == Type::TYPE_MESSAGE && find_map_entry(msg, field).is_some()
}

/// Marker emitted by generated `Debug` impls in place of values whose field is
/// annotated `[debug_redact = true]`. Interpolated into `format_args!` as the
/// format string, so it must not contain `{` or `}`.
pub(crate) const DEBUG_REDACT_PLACEHOLDER: &str = "[REDACTED]";

/// True when the field carries `[debug_redact = true]`, i.e. its value must
/// not appear in generated `Debug` output.
pub(crate) fn is_debug_redacted(
    field: &crate::generated::descriptor::FieldDescriptorProto,
) -> bool {
    field
        .options
        .as_option()
        .and_then(|o| o.debug_redact)
        .unwrap_or(false)
}

/// Find the synthetic map-entry nested message for a map field.
///
/// Returns `None` if the field is not a map field (no matching nested type
/// with `map_entry = true`).  Used by all map-related helpers to avoid
/// duplicating the lookup predicate.
///
/// The match uses suffix comparison (`type_name.ends_with(".{name}")`)
/// rather than full FQN equality. This is safe because `msg.nested_type`
/// only contains types nested within this message, and protobuf does not
/// allow duplicate type names within a single message scope.
pub(crate) fn find_map_entry<'a>(
    msg: &'a DescriptorProto,
    field: &crate::generated::descriptor::FieldDescriptorProto,
) -> Option<&'a DescriptorProto> {
    let type_name = field.type_name.as_deref()?;
    msg.nested_type.iter().find(|nested| {
        nested
            .options
            .as_option()
            .and_then(|o| o.map_entry)
            .unwrap_or(false)
            && nested
                .name
                .as_deref()
                .is_some_and(|n| type_name.ends_with(&format!(".{n}")))
    })
}

/// Return the effective proto `Type` of a map entry's key field.
fn map_entry_key_type(
    ctx: &CodeGenContext,
    entry: &DescriptorProto,
    features: &ResolvedFeatures,
) -> Option<Type> {
    let key_field = entry.field.iter().find(|f| f.number == Some(1))?;
    Some(crate::impl_message::effective_type_in_map_entry(
        ctx, key_field, features,
    ))
}

/// Return the effective proto `Type` of a map entry's value field.
fn map_entry_value_type(
    ctx: &CodeGenContext,
    entry: &DescriptorProto,
    features: &ResolvedFeatures,
) -> Option<Type> {
    let value_field = entry.field.iter().find(|f| f.number == Some(2))?;
    Some(crate::impl_message::effective_type_in_map_entry(
        ctx,
        value_field,
        features,
    ))
}

/// Build the `HashMap<K, V>` Rust type from an already-resolved map entry descriptor.
///
/// `value_use_bytes` overrides the default `Vec<u8>` for a `bytes`-valued
/// map when the outer map field matches `bytes_fields`. Computed by the
/// caller (`classify_field`) so map and non-map paths share the same check.
fn map_rust_type_from_entry(
    scope: MessageScope<'_>,
    entry: &DescriptorProto,
    value_use_bytes: bool,
    resolver: &crate::imports::ImportResolver,
) -> Result<TokenStream, CodeGenError> {
    let MessageScope {
        ctx,
        current_package,
        features,
        nesting,
        ..
    } = scope;
    let key_field = entry
        .field
        .iter()
        .find(|f| f.number == Some(1))
        .ok_or(CodeGenError::MissingField("map_entry.key"))?;
    let value_field = entry
        .field
        .iter()
        .find(|f| f.number == Some(2))
        .ok_or(CodeGenError::MissingField("map_entry.value"))?;

    let key_type = scalar_or_message_type_nested(
        ctx,
        key_field,
        current_package,
        nesting,
        features,
        resolver,
    )?;
    let value_type = if value_use_bytes
        && crate::impl_message::effective_type_in_map_entry(ctx, value_field, features)
            == Type::TYPE_BYTES
    {
        quote! { ::buffa::bytes::Bytes }
    } else {
        scalar_or_message_type_nested(
            ctx,
            value_field,
            current_package,
            nesting,
            features,
            resolver,
        )?
    };

    let hm = resolver.hashmap();
    Ok(quote! { #hm<#key_type, #value_type> })
}

/// Resolve the Rust type for a scalar, message, or enum field.
///
/// `current_package` is used to produce unqualified names for types in the
/// same proto package (they will be in the same generated `pub mod`).
/// `nesting` is the module depth of the *consumer* of this type (every
/// `pub mod` step away from the package root adds one hop). Used by both
/// this module and `oneof.rs`.
pub(crate) fn scalar_or_message_type_nested(
    ctx: &CodeGenContext,
    field: &crate::generated::descriptor::FieldDescriptorProto,
    current_package: &str,
    nesting: usize,
    features: &ResolvedFeatures,
    resolver: &crate::imports::ImportResolver,
) -> Result<TokenStream, CodeGenError> {
    let scope = MessageScope {
        ctx,
        current_package,
        proto_fqn: "",
        features,
        nesting,
    };
    match crate::impl_message::effective_type(ctx, field, features) {
        Type::TYPE_MESSAGE | Type::TYPE_GROUP => resolve_message_type(scope, field),
        Type::TYPE_ENUM => resolve_enum_type(scope, field, resolver),
        other => scalar_rust_type(other, resolver),
    }
}

fn resolve_message_type(
    scope: MessageScope<'_>,
    field: &crate::generated::descriptor::FieldDescriptorProto,
) -> Result<TokenStream, CodeGenError> {
    let type_name = field
        .type_name
        .as_deref()
        .ok_or(CodeGenError::MissingField("field.type_name"))?;
    let path_str = scope
        .ctx
        .rust_type_relative(type_name, scope.current_package, scope.nesting)
        .ok_or_else(|| {
            CodeGenError::Other(format!(
                "message type '{type_name}' not found in descriptor set; \
                 ensure all imports are included with --include_imports"
            ))
        })?;
    let ty = rust_path_to_tokens(&path_str);
    Ok(quote! { #ty })
}

fn resolve_enum_type(
    scope: MessageScope<'_>,
    field: &crate::generated::descriptor::FieldDescriptorProto,
    resolver: &crate::imports::ImportResolver,
) -> Result<TokenStream, CodeGenError> {
    let type_name = field
        .type_name
        .as_deref()
        .ok_or(CodeGenError::MissingField("field.type_name"))?;
    let path_str = scope
        .ctx
        .rust_type_relative(type_name, scope.current_package, scope.nesting)
        .ok_or_else(|| {
            CodeGenError::Other(format!(
                "enum type '{type_name}' not found in descriptor set; \
                 ensure all imports are included with --include_imports"
            ))
        })?;
    let ty = rust_path_to_tokens(&path_str);
    let field_features = crate::features::resolve_field(scope.ctx, field, scope.features);
    if is_closed_enum(&field_features) {
        Ok(quote! { #ty })
    } else {
        let ev = resolver.enum_value();
        Ok(quote! { #ev<#ty> })
    }
}

/// Returns `true` when `features.enum_type` is CLOSED.
///
/// **Important:** `enum_type` is a property of the ENUM DECLARATION, not the
/// field. For this to return the correct value, the caller must have already
/// resolved the enum's own features into the passed `features` — see
/// [`crate::features::resolve_field`] which does this automatically for
/// enum-typed fields by looking up the referenced enum's closedness.
pub(crate) fn is_closed_enum(features: &ResolvedFeatures) -> bool {
    features.enum_type == crate::features::EnumType::Closed
}

fn scalar_rust_type(
    t: Type,
    resolver: &crate::imports::ImportResolver,
) -> Result<TokenStream, CodeGenError> {
    match t {
        Type::TYPE_DOUBLE => Ok(quote! { f64 }),
        Type::TYPE_FLOAT => Ok(quote! { f32 }),
        Type::TYPE_INT64 | Type::TYPE_SINT64 | Type::TYPE_SFIXED64 => Ok(quote! { i64 }),
        Type::TYPE_UINT64 | Type::TYPE_FIXED64 => Ok(quote! { u64 }),
        Type::TYPE_INT32 | Type::TYPE_SINT32 | Type::TYPE_SFIXED32 => Ok(quote! { i32 }),
        Type::TYPE_UINT32 | Type::TYPE_FIXED32 => Ok(quote! { u32 }),
        Type::TYPE_BOOL => Ok(quote! { bool }),
        Type::TYPE_STRING => Ok(resolver.string()),
        Type::TYPE_BYTES => {
            let vec = resolver.vec();
            Ok(quote! { #vec<u8> })
        }
        Type::TYPE_GROUP | Type::TYPE_MESSAGE | Type::TYPE_ENUM => Err(CodeGenError::Other(
            format!("scalar_rust_type called for non-scalar type {:?}", t),
        )),
    }
}

/// Determine the `with` module and `null_as_default` deserializer for a
/// non-oneof field.  Shared between `serde_field_attr` (for derive-based
/// deserialization) and `generate_custom_deserialize` (for hand-generated
/// Deserialize impls on messages with oneofs).
fn field_deser_modules(
    field_type: Type,
    info: &FieldInfo,
    features: &ResolvedFeatures,
) -> (Option<&'static str>, Option<&'static str>) {
    let with_module = if info.is_map {
        map_serde_module(info)
    } else if info.is_repeated {
        repeated_serde_module(field_type, features)
    } else if info.is_optional {
        optional_serde_module(field_type, features)
    } else {
        singular_serde_module(field_type, features)
    };

    let null_deser = if with_module.is_none() && (info.is_repeated || info.is_map) {
        Some("::buffa::json_helpers::null_as_default")
    } else {
        None
    };

    (with_module, null_deser)
}

/// Does this scalar type need proto3-JSON special encoding in containers?
///
/// int64/uint64 → quoted strings; float/double → NaN/Inf tokens; bytes →
/// base64. For bool/string/int32/uint32/sint32/sfixed32/fixed32, derive
/// serde is already proto3-JSON compliant — routing through ProtoElemJson
/// adds trait-dispatch overhead (and for proto_map, a `.to_string()` alloc
/// per key) for no correctness benefit.
fn value_needs_proto_json(ty: Type) -> bool {
    matches!(
        ty,
        Type::TYPE_INT64
            | Type::TYPE_SINT64
            | Type::TYPE_SFIXED64
            | Type::TYPE_UINT64
            | Type::TYPE_FIXED64
            | Type::TYPE_FLOAT
            | Type::TYPE_DOUBLE
            | Type::TYPE_BYTES
    )
}

/// Serde module for map fields (keyed by key/value types).
///
/// Uses `proto_map` (generic over `V: ProtoElemJson`) only when the value
/// type needs proto3-JSON special encoding (int64→quoted, float→NaN token,
/// bytes→base64). For simple values (string, bool, 32-bit ints) with string
/// keys, returns `None` to use derive — zero overhead. Non-string keys still
/// use `string_key_map` for key stringification.
///
/// Open-enum map values keep `map_enum` for its ignore-unknown-values
/// filtering behavior (a `JsonParseOptions` feature proto_map doesn't have).
///
/// Key stringification: serde_json's `MapKeySerializer` auto-stringifies
/// all proto map key types (i32/i64/u32/u64/bool → `"42"`/`"true"`/etc.)
/// and parses them back, so `map_enum`/`map_closed_enum` delegating to
/// `HashMap`'s default serde is correct for non-string keys without an
/// explicit `string_key_map` wrapper.
fn map_serde_module(info: &FieldInfo) -> Option<&'static str> {
    // Bytes key (from strict_utf8_mapping normalizing string→bytes):
    // keys are base64-encoded, not Display-stringified. proto_map's
    // Display-based key serialization doesn't work here.
    if matches!(info.map_key_type, Some(Type::TYPE_BYTES)) {
        return Some(if matches!(info.map_value_type, Some(Type::TYPE_BYTES)) {
            "::buffa::json_helpers::bytes_key_bytes_val_map"
        } else {
            "::buffa::json_helpers::bytes_key_map"
        });
    }

    // Enum values (both open and closed) need the unknown-value filtering
    // behavior of map_enum / map_closed_enum (ignore_unknown_enum_values
    // option). proto_map lacks this.
    //
    // Closedness MUST come from info.map_value_enum_closed (resolved from
    // the MapEntry value field, which is TYPE_ENUM), NOT from the map
    // field's own features (TYPE_MESSAGE → resolve_field skips the
    // enum_type overlay → stale file-level default). See classify_field.
    if let Some(closed) = info.map_value_enum_closed {
        return Some(if closed {
            "::buffa::json_helpers::map_closed_enum"
        } else {
            "::buffa::json_helpers::map_enum"
        });
    }

    // Message values: derived Serialize/Deserialize is already proto-JSON.
    // Default serde for HashMap<String, Message> works. Non-string keys
    // still need stringification via string_key_map.
    if matches!(info.map_value_type, Some(Type::TYPE_MESSAGE)) {
        let is_string_key = matches!(info.map_key_type, Some(Type::TYPE_STRING));
        return if is_string_key {
            None
        } else {
            Some("::buffa::json_helpers::string_key_map")
        };
    }

    // Scalar value types: only route through proto_map if the value needs
    // proto-JSON encoding. For simple values with string keys, derive is
    // correct and avoids proto_map's per-key `.to_string()` allocation.
    let value_ty = info.map_value_type.unwrap_or(Type::TYPE_STRING);
    let is_string_key = matches!(info.map_key_type, Some(Type::TYPE_STRING));
    if value_needs_proto_json(value_ty) {
        // Value needs special encoding (int64 quoted, bytes base64, etc.).
        Some("::buffa::json_helpers::proto_map")
    } else if is_string_key {
        // String key + simple value: derive is proto-JSON compliant, zero overhead.
        None
    } else {
        // Non-string key + simple value: need key stringification only.
        Some("::buffa::json_helpers::string_key_map")
    }
}

/// Serde module for repeated fields.
///
/// Uses `proto_seq` (generic over `T: ProtoElemJson`) only for element types
/// that need proto3-JSON special encoding. For string/bool/32-bit ints,
/// derive is correct and avoids trait-dispatch overhead.
///
/// Enums keep the `_enum` / `_closed_enum` modules for their
/// ignore-unknown-values filtering behavior (JsonParseOptions).
fn repeated_serde_module(field_type: Type, features: &ResolvedFeatures) -> Option<&'static str> {
    match field_type {
        // Enums need ignore_unknown_enum_values filtering.
        Type::TYPE_ENUM => Some(if is_closed_enum(features) {
            "::buffa::json_helpers::repeated_closed_enum"
        } else {
            "::buffa::json_helpers::repeated_enum"
        }),
        // Messages/groups: derived Serialize is already proto-JSON.
        Type::TYPE_MESSAGE | Type::TYPE_GROUP => None,
        // Simple scalar types (string, bool, 32-bit ints): derive is
        // proto-JSON compliant. Only route through proto_seq for types
        // that need special encoding (int64 quoted, bytes base64, etc.).
        ty if value_needs_proto_json(ty) => Some("::buffa::json_helpers::proto_seq"),
        _ => None,
    }
}

/// Serde module for explicit-presence (optional) fields.
fn optional_serde_module(field_type: Type, features: &ResolvedFeatures) -> Option<&'static str> {
    match field_type {
        Type::TYPE_INT32 | Type::TYPE_SINT32 | Type::TYPE_SFIXED32 => {
            Some("::buffa::json_helpers::opt_int32")
        }
        Type::TYPE_UINT32 | Type::TYPE_FIXED32 => Some("::buffa::json_helpers::opt_uint32"),
        Type::TYPE_INT64 | Type::TYPE_SINT64 | Type::TYPE_SFIXED64 => {
            Some("::buffa::json_helpers::opt_int64")
        }
        Type::TYPE_UINT64 | Type::TYPE_FIXED64 => Some("::buffa::json_helpers::opt_uint64"),
        Type::TYPE_FLOAT => Some("::buffa::json_helpers::opt_float"),
        Type::TYPE_DOUBLE => Some("::buffa::json_helpers::opt_double"),
        Type::TYPE_BYTES => Some("::buffa::json_helpers::opt_bytes"),
        Type::TYPE_ENUM => Some(if is_closed_enum(features) {
            "::buffa::json_helpers::opt_closed_enum"
        } else {
            "::buffa::json_helpers::opt_enum"
        }),
        _ => None,
    }
}

/// Serde module for singular (non-optional, non-repeated) fields.
fn singular_serde_module(field_type: Type, features: &ResolvedFeatures) -> Option<&'static str> {
    match field_type {
        Type::TYPE_BOOL => Some("::buffa::json_helpers::proto_bool"),
        Type::TYPE_STRING => Some("::buffa::json_helpers::proto_string"),
        Type::TYPE_INT32 | Type::TYPE_SINT32 | Type::TYPE_SFIXED32 => {
            Some("::buffa::json_helpers::int32")
        }
        Type::TYPE_UINT32 | Type::TYPE_FIXED32 => Some("::buffa::json_helpers::uint32"),
        Type::TYPE_INT64 | Type::TYPE_SINT64 | Type::TYPE_SFIXED64 => {
            Some("::buffa::json_helpers::int64")
        }
        Type::TYPE_UINT64 | Type::TYPE_FIXED64 => Some("::buffa::json_helpers::uint64"),
        Type::TYPE_FLOAT => Some("::buffa::json_helpers::float"),
        Type::TYPE_DOUBLE => Some("::buffa::json_helpers::double"),
        Type::TYPE_BYTES => Some("::buffa::json_helpers::bytes"),
        Type::TYPE_ENUM => Some(if is_closed_enum(features) {
            "::buffa::json_helpers::closed_enum"
        } else {
            "::buffa::json_helpers::proto_enum"
        }),
        _ => None,
    }
}

/// Determine the `skip_serializing_if` predicate for a field.
fn skip_serializing_predicate(
    field_type: Type,
    info: &FieldInfo,
    features: &ResolvedFeatures,
) -> Option<&'static str> {
    if info.is_required {
        // Proto2 required fields must always be present in JSON, even at
        // their default value — mirrors the binary encoder's always-encode
        // semantics (impl_message.rs is_proto2_required check).
        None
    } else if info.is_map {
        Some("::buffa::__private::HashMap::is_empty")
    } else if info.is_repeated {
        Some("::buffa::json_helpers::skip_if::is_empty_vec")
    } else if info.is_optional {
        Some("::core::option::Option::is_none")
    } else {
        Some(singular_skip_predicate(field_type, features))
    }
}

/// Determine the `skip_serializing_if` predicate for a singular field.
///
/// Every singular type has a default-value predicate, so this always
/// returns one — the caller [`skip_serializing_predicate`] supplies the
/// `None` cases (required/repeated/map/optional fields).
fn singular_skip_predicate(field_type: Type, features: &ResolvedFeatures) -> &'static str {
    match field_type {
        Type::TYPE_MESSAGE | Type::TYPE_GROUP => {
            "::buffa::json_helpers::skip_if::is_unset_message_field"
        }
        Type::TYPE_ENUM => {
            if is_closed_enum(features) {
                "::buffa::json_helpers::skip_if::is_default_closed_enum"
            } else {
                "::buffa::json_helpers::skip_if::is_default_enum_value"
            }
        }
        Type::TYPE_INT64 | Type::TYPE_SINT64 | Type::TYPE_SFIXED64 => {
            "::buffa::json_helpers::skip_if::is_zero_i64"
        }
        Type::TYPE_UINT64 | Type::TYPE_FIXED64 => "::buffa::json_helpers::skip_if::is_zero_u64",
        Type::TYPE_INT32 | Type::TYPE_SINT32 | Type::TYPE_SFIXED32 => {
            "::buffa::json_helpers::skip_if::is_zero_i32"
        }
        Type::TYPE_UINT32 | Type::TYPE_FIXED32 => "::buffa::json_helpers::skip_if::is_zero_u32",
        Type::TYPE_BOOL => "::buffa::json_helpers::skip_if::is_false",
        Type::TYPE_FLOAT => "::buffa::json_helpers::skip_if::is_zero_f32",
        Type::TYPE_DOUBLE => "::buffa::json_helpers::skip_if::is_zero_f64",
        Type::TYPE_STRING => "::buffa::json_helpers::skip_if::is_empty_str",
        Type::TYPE_BYTES => "::buffa::json_helpers::skip_if::is_empty_bytes",
    }
}

/// Build a `#[serde(...)]` attribute for a direct (non-oneof) field.
///
/// Emits `rename` using the proto JSON name, `skip_serializing_if` for
/// default-value suppression (proto3 JSON omits fields at their default),
/// and `with` for types that require special proto JSON encoding (int64,
/// uint64, float, double, bytes).
/// Repeated, map, and optional wrappers dispatch to container-specific
/// helper modules that handle per-element encoding.
fn serde_field_attr(
    ctx: &CodeGenContext,
    field: &crate::generated::descriptor::FieldDescriptorProto,
    field_name: &str,
    info: &FieldInfo,
    features: &ResolvedFeatures,
) -> TokenStream {
    let field_type = crate::impl_message::effective_type(ctx, field, features);
    let field_features = crate::features::resolve_field(ctx, field, features);
    let json_name = field.json_name.as_deref().unwrap_or(field_name);
    let (with_module, null_deser) = field_deser_modules(field_type, info, &field_features);

    let skip_if = skip_serializing_predicate(field_type, info, &field_features);

    // Proto3 JSON spec: parsers must accept both the camelCase json_name
    // and the original proto field name.  Emit `alias` when they differ.
    let needs_alias = json_name != field_name;

    // Build the attribute parts list to avoid a combinatorial match.
    let alias_part = if needs_alias {
        quote! { , alias = #field_name }
    } else {
        quote! {}
    };
    let with_part = if let Some(module) = with_module {
        quote! { , with = #module }
    } else {
        quote! {}
    };
    let skip_part = if let Some(skip) = skip_if {
        quote! { , skip_serializing_if = #skip }
    } else {
        quote! {}
    };
    let deser_part = if is_value_field(field, info.is_repeated, info.is_map) {
        quote! { , deserialize_with = "::buffa::json_helpers::message_field_always_present" }
    } else if let Some(deser) = null_deser {
        quote! { , deserialize_with = #deser }
    } else {
        quote! {}
    };

    crate::feature_gates::cfg_attr(
        quote! { serde(rename = #json_name #alias_part #with_part #skip_part #deser_part) },
        ctx.config.feature_gates().json,
    )
}

/// Generate a custom `impl Default` for a message when any non-optional field
/// has a custom `default_value`.
///
/// Returns `Some(impl_block)` if a custom default is needed, `None` otherwise
/// (in which case the struct should `#[derive(Default)]`).
fn generate_custom_default(
    ctx: &CodeGenContext,
    msg: &DescriptorProto,
    name_ident: &Ident,
    current_package: &str,
    proto_fqn: &str,
    features: &ResolvedFeatures,
    nesting: usize,
) -> Result<Option<TokenStream>, CodeGenError> {
    // Custom defaults only apply when field presence is explicit (proto2,
    // or editions with explicit presence).
    if features.field_presence != crate::features::FieldPresence::Explicit {
        return Ok(None);
    }

    // First pass: check if any field has a custom default that matters.
    let mut has_custom = false;
    for field in &msg.field {
        if is_real_oneof_member(field) {
            continue;
        }
        let field_type = crate::impl_message::effective_type(ctx, field, features);
        let is_optional = is_explicit_presence_scalar(field, field_type, features);
        let is_repeated = field.label.unwrap_or_default() == Label::LABEL_REPEATED;
        if is_optional
            || is_repeated
            || field_type == Type::TYPE_MESSAGE
            || field_type == Type::TYPE_GROUP
        {
            continue;
        }
        if field
            .default_value
            .as_deref()
            .is_some_and(|s| !s.is_empty())
        {
            has_custom = true;
            break;
        }
    }

    if !has_custom {
        return Ok(None);
    }

    // Second pass: build field initializers.
    let mut field_inits = Vec::new();

    for field in &msg.field {
        if is_real_oneof_member(field) {
            continue;
        }
        let field_name = field
            .name
            .as_deref()
            .ok_or(CodeGenError::MissingField("field.name"))?;
        let field_ident = make_field_ident(field_name);
        let field_type = crate::impl_message::effective_type(ctx, field, features);
        let is_optional = is_explicit_presence_scalar(field, field_type, features);
        let is_repeated = field.label.unwrap_or_default() == Label::LABEL_REPEATED;

        if is_optional
            || is_repeated
            || field_type == Type::TYPE_MESSAGE
            || field_type == Type::TYPE_GROUP
        {
            field_inits.push(quote! { #field_ident: ::core::default::Default::default(), });
            continue;
        }

        if let Some(expr) = parse_default_value(
            field,
            ctx,
            current_package,
            features,
            nesting,
            crate::impl_message::field_string_repr(ctx, proto_fqn, field_name),
        )? {
            field_inits.push(quote! { #field_ident: #expr, });
        } else {
            field_inits.push(quote! { #field_ident: ::core::default::Default::default(), });
        }
    }

    // Oneof fields default to None.
    for (idx, oneof) in msg.oneof_decl.iter().enumerate() {
        let oneof_name = oneof
            .name
            .as_deref()
            .ok_or(CodeGenError::MissingField("oneof.name"))?;
        let has_real = msg
            .field
            .iter()
            .any(|f| is_real_oneof_member(f) && f.oneof_index == Some(idx as i32));
        if has_real {
            let ident = make_field_ident(oneof_name);
            field_inits.push(quote! { #ident: ::core::default::Default::default(), });
        }
    }

    let unknown_fields_init = if ctx.config.preserve_unknown_fields {
        quote! { __buffa_unknown_fields: ::core::default::Default::default(), }
    } else {
        quote! {}
    };

    Ok(Some(quote! {
        impl ::core::default::Default for #name_ident {
            fn default() -> Self {
                Self {
                    #(#field_inits)*
                    #unknown_fields_init
                }
            }
        }
    }))
}

// Ident/path helpers re-exported from the public `idents` module so existing
// `crate::message::*` imports continue to work unchanged.
pub(crate) use crate::idents::{make_field_ident, rust_path_to_tokens};