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
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
//! Code generation for zero-copy borrowed message view types.
//!
//! For each proto message `Foo` this module generates:
//!
//! - `FooView<'a>`: a struct whose string/bytes fields are `&'a str`/`&'a [u8]`,
//!   borrowing directly from the input buffer without allocation.
//! - A `FooKindView<'a>` enum for each oneof, mirroring the owned `FooKind`
//!   but with borrowed variants.
//! - `impl MessageView<'a> for FooView<'a>`: provides `decode_view` (zero-copy
//!   decode) and `to_owned_message` (conversion to the owned type).

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

use crate::context::{ancillary_prefix, AncillaryKind, CodeGenContext, MessageScope, SENTINEL_MOD};
use crate::features::ResolvedFeatures;
use crate::impl_message::{
    closed_enum_decode, closed_enum_decode_with_unknown, decode_fn_token, effective_type,
    effective_type_in_map_entry, field_string_repr, field_uses_bytes, find_map_entry_fields,
    is_explicit_presence_scalar, is_packed_type, is_real_oneof_member, is_required_field,
    is_supported_field_type, map_value_use_bytes, validated_field_number, wire_type_byte,
    wire_type_check, wire_type_token,
};
use crate::message::{is_closed_enum, is_map_field, make_field_ident, rust_path_to_tokens};
use crate::oneof::{is_null_value_field, serde_helper_path};
use crate::CodeGenError;

/// Token stream that pushes a closed-enum unknown value's raw wire span to
/// `view.__buffa_unknown_fields`. Requires `before_tag` and `cur` in scope
/// (the decode loop captures `before_tag` before reading the tag).
///
/// Returns empty tokens when `preserve_unknown_fields` is false. In that case
/// `closed_enum_decode_with_unknown` collapses to `closed_enum_decode`.
fn closed_enum_view_unknown_route(preserve_unknown_fields: bool) -> TokenStream {
    if preserve_unknown_fields {
        quote! {
            let __span_len = before_tag.len() - cur.len();
            view.__buffa_unknown_fields.push_raw(&before_tag[..__span_len]);
        }
    } else {
        quote! {}
    }
}

/// Convert a borrowed bytes view to the owned field type.
///
/// When `use_bytes_type()` is active for this field, emits
/// `::buffa::view::bytes_from_source(__buffa_src, expr)` so
/// `to_owned_from_source(Some(buf))` produces a zero-copy `Bytes::slice_ref`;
/// `None` falls back to `copy_from_slice`. Otherwise emits `(expr).to_vec()`.
///
/// `expr` may be `&[u8]` (singular/optional) or `&&[u8]` (repeated-iter,
/// oneof match-ergonomics). Both branches accept either: `.to_vec()` via
/// method auto-deref, `bytes_from_source`'s `&[u8]` arg via auto-deref.
fn bytes_to_owned(
    ctx: &CodeGenContext,
    proto_fqn: &str,
    field_name: &str,
    expr: TokenStream,
) -> TokenStream {
    if field_uses_bytes(ctx, proto_fqn, field_name) {
        quote! { ::buffa::view::bytes_from_source(__buffa_src, #expr) }
    } else {
        quote! { (#expr).to_vec() }
    }
}

/// `scope.nesting` is the **message-nesting** of the owning message (0 for
/// top-level). View structs are emitted into `__buffa::view::<msg_path>::`,
/// so the view body's total depth below the package root is
/// `scope.nesting + 2`; view-oneof enums go to
/// `__buffa::view::oneof::<msg_path>::`, depth `scope.nesting + 4`.
pub(crate) fn generate_view_with_nesting(
    scope: MessageScope<'_>,
    msg: &DescriptorProto,
    rust_name: &str,
) -> Result<(TokenStream, TokenStream), CodeGenError> {
    let MessageScope {
        ctx,
        current_package,
        proto_fqn,
        features,
        nesting,
    } = scope;

    // Note: nested views are generated by generate_message, not here.
    // This function only generates the view for the current message.

    let oneof_idents = crate::oneof::resolve_oneof_idents(msg);

    let view_ident = format_ident!("{}View", rust_name);

    // Total module depth of the view-struct body below the package root.
    // All field-type / decode-arm / to-owned helpers below resolve paths
    // relative to this depth, so pass `view_scope` (not `scope`).
    let view_depth = nesting + 2;
    let view_scope = MessageScope {
        nesting: view_depth,
        ..scope
    };
    // Path prefixes from the view struct's scope to its ancillary enums.
    let view_oneof_prefix = ancillary_prefix(
        AncillaryKind::ViewOneof,
        current_package,
        proto_fqn,
        view_depth,
    );
    let owned_oneof_prefix =
        ancillary_prefix(AncillaryKind::Oneof, current_package, proto_fqn, view_depth);

    // View struct fields (excludes real-oneof members, map fields, and
    // unsupported types like groups).
    let view_fields = msg
        .field
        .iter()
        .filter(|f| is_supported_field_type(f.r#type.unwrap_or_default()))
        .map(|f| view_struct_field(view_scope, msg, f))
        .collect::<Result<Vec<_>, _>>()?
        .into_iter()
        .flatten()
        .collect::<Vec<_>>();
    let direct_fields: Vec<&TokenStream> =
        view_fields.iter().map(|(tokens, _, _)| tokens).collect();

    // One `Option<Kind<'a>>` per non-synthetic oneof.
    let oneof_view_fields =
        oneof_view_struct_fields(ctx, msg, &view_oneof_prefix, features, &oneof_idents)?;
    let oneof_struct_fields: Vec<&TokenStream> =
        oneof_view_fields.iter().map(|(tokens, _)| tokens).collect();

    // Oneof view enum definitions (go into `__buffa::view::oneof::<msg>::`).
    let oneof_view_enums = msg
        .oneof_decl
        .iter()
        .enumerate()
        .map(|(idx, oneof)| generate_oneof_view_enum(scope, msg, idx, oneof, &oneof_idents))
        .collect::<Result<Vec<_>, _>>()?;

    // decode_view match arms.
    let (scalar_arms, repeated_arms, oneof_arms) =
        build_decode_arms(view_scope, msg, &view_oneof_prefix, &oneof_idents)?;

    // to_owned_message field initialisers.
    let owned_fields = build_to_owned_fields(
        view_scope,
        msg,
        &view_oneof_prefix,
        &owned_oneof_prefix,
        &oneof_idents,
    )?;

    let unknown_fields_field = if ctx.config.preserve_unknown_fields {
        quote! { pub __buffa_unknown_fields: ::buffa::UnknownFieldsView<'a>, }
    } else {
        quote! {}
    };
    let view_encode_methods = crate::impl_message::build_view_encode_methods(
        ctx,
        msg,
        ctx.config.preserve_unknown_fields,
        features,
        &oneof_idents,
        &view_oneof_prefix,
    )?;
    let view_encode_impl = quote! {
        impl<'a> ::buffa::ViewEncode<'a> for #view_ident<'a> {
            #view_encode_methods
        }
    };

    // The view participates in the same name-keyed registries as the
    // owned message — a generic event-sourcing dispatch should not have
    // to round-trip a zero-copy view through `to_owned_message()` just
    // to read its FQN. Same consts, different `Self`.
    let message_name_impl = crate::impl_message::message_name_impl(
        current_package,
        proto_fqn,
        &quote! { <'a> },
        &quote! { #view_ident<'a> },
    );

    let serialize_impl = if ctx.config.generate_json {
        crate::feature_gates::cfg_block(
            generate_view_serialize(
                view_scope,
                msg,
                &view_ident,
                &view_oneof_prefix,
                &oneof_idents,
            )?,
            ctx.config.feature_gates().json,
        )
    } else {
        quote! {}
    };

    // Vtable-mode reflection: `impl ReflectMessage` directly on the view.
    // Skipped for map entry synthetic messages (not registered in the pool by
    // name; consumers never reflect over them directly), matching the
    // bridge-mode `Reflectable` skip.
    let is_map_entry = msg
        .options
        .as_option()
        .is_some_and(|o| o.map_entry.unwrap_or(false));
    let reflect_view_impls =
        if ctx.config.generate_reflection && ctx.config.generate_reflection_vtable && !is_map_entry
        {
            // `reflect_view_impls` emits three sibling items (the ReflectMessage
            // impl, the ReflectElement impl, and an inherent impl for the
            // memoized index). `cfg_const_block` wraps them in a single
            // `#[cfg] const _` so one gate covers all three; a bare `cfg_block`
            // would gate only the first and leak the rest.
            crate::feature_gates::cfg_const_block(
                crate::reflect_view::reflect_view_impls(
                    view_scope,
                    msg,
                    &view_ident,
                    view_depth,
                    &view_oneof_prefix,
                    &oneof_idents,
                )?,
                ctx.config.feature_gates().reflect,
            )
        } else {
            quote! {}
        };

    // When preserving unknowns we capture `before_tag` so we can compute the
    // raw byte span after `skip_field` advances the cursor.
    let before_tag_capture = if ctx.config.preserve_unknown_fields {
        quote! { let before_tag = cur; }
    } else {
        quote! {}
    };
    let unknown_field_handling = if ctx.config.preserve_unknown_fields {
        quote! {
            let span_len = before_tag.len() - cur.len();
            view.__buffa_unknown_fields.push_raw(&before_tag[..span_len]);
        }
    } else {
        quote! {}
    };

    // If no field borrows from 'a (all-scalar message with unknown-fields
    // preservation disabled), inject PhantomData<&'a ()> so the struct's
    // lifetime param is used. _decode_depth(buf: &'a [u8]) requires 'a.
    let phantom_field =
        if message_view_has_borrowing_field(ctx, msg, features, ctx.config.preserve_unknown_fields)
        {
            quote! {}
        } else {
            quote! { #[doc(hidden)] pub __buffa_phantom: ::core::marker::PhantomData<&'a ()>, }
        };

    let mod_items = quote! {
        #(#oneof_view_enums)*
    };

    // Path from the view-struct scope (depth `nesting + 2`) to its owned
    // counterpart at the mirrored owned-tree position. Same package by
    // construction; `rust_type_relative` returns `super^(n+2)::<within>`.
    let owned_path: TokenStream = {
        let dotted = format!(".{proto_fqn}");
        let p = ctx
            .rust_type_relative(&dotted, current_package, view_depth)
            .ok_or_else(|| {
                CodeGenError::Other(format!(
                    "owned type for '{proto_fqn}' not resolvable from view tree"
                ))
            })?;
        rust_path_to_tokens(&p)
    };

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

    // `FooOwnedView`: a `'static` OwnedView handle with per-field accessors.
    // Skipped for map-entry synthetic messages (never decoded standalone).
    let owned_view_wrapper = if is_map_entry {
        quote! {}
    } else {
        crate::owned_view::generate_owned_view_wrapper(
            view_scope,
            msg,
            rust_name,
            &view_ident,
            &owned_path,
            &view_oneof_prefix,
            &oneof_idents,
        )?
    };

    // Fields marked `[debug_redact = true]` print a placeholder instead of
    // their value. The `Debug` derive is swapped for a manual impl only when
    // at least one field is redacted, so unaffected views keep byte-identical
    // output. Oneof payload redaction is handled by the view-oneof enum.
    // Like the owned message's Debug impl, the manual impl lists proto fields
    // only — `__buffa_unknown_fields` is deliberately excluded because unknown
    // fields can carry redacted data from a newer schema version.
    let any_redacted = view_fields.iter().any(|(_, _, redacted)| *redacted);
    let (view_debug_derive, view_debug_impl) = if any_redacted {
        let placeholder = crate::message::DEBUG_REDACT_PLACEHOLDER;
        let view_name_str = view_ident.to_string();
        let mut debug_field_names: Vec<String> = Vec::new();
        let mut debug_field_values: Vec<TokenStream> = Vec::new();
        for (_, ident, redacted) in &view_fields {
            // Label matches what the derive prints: raw-ident fields
            // (`r#type`) show as `type`.
            debug_field_names.push(ident.to_string().trim_start_matches("r#").to_string());
            debug_field_values.push(if *redacted {
                quote! { &::core::format_args!(#placeholder) }
            } else {
                quote! { &self.#ident }
            });
        }
        for (_, ident) in &oneof_view_fields {
            debug_field_names.push(ident.to_string().trim_start_matches("r#").to_string());
            debug_field_values.push(quote! { &self.#ident });
        }
        (
            quote! { #[derive(Clone, Default)] },
            quote! {
                impl<'a> ::core::fmt::Debug for #view_ident<'a> {
                    fn fmt(&self, f: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result {
                        f.debug_struct(#view_name_str)
                            #(.field(#debug_field_names, #debug_field_values))*
                            .finish()
                    }
                }
            },
        )
    } else {
        (quote! { #[derive(Clone, Debug, Default)] }, quote! {})
    };

    let top_level = quote! {
        #view_doc
        #view_debug_derive
        pub struct #view_ident<'a> {
            #(#direct_fields)*
            #(#oneof_struct_fields)*
            #unknown_fields_field
            #phantom_field
        }

        #view_debug_impl

        impl<'a> #view_ident<'a> {
            /// Decode from `buf`, enforcing a recursion depth limit for nested messages.
            ///
            /// Called by [`::buffa::MessageView::decode_view`] with [`::buffa::RECURSION_LIMIT`]
            /// and by generated sub-message decode arms with `depth - 1`.
            ///
            /// **Not part of the public API.** Named with a leading underscore to
            /// signal that it is for generated-code use only.
            #[doc(hidden)]
            pub fn _decode_depth(
                buf: &'a [u8],
                depth: u32,
            ) -> ::core::result::Result<Self, ::buffa::DecodeError> {
                let mut view = Self::default();
                view._merge_into_view(buf, depth)?;
                ::core::result::Result::Ok(view)
            }

            /// Merge fields from `buf` into this view (proto merge semantics).
            ///
            /// Repeated fields append; singular fields last-wins; singular
            /// MESSAGE fields merge recursively. Used by sub-message decode
            /// arms when the same field appears multiple times on the wire.
            ///
            /// **Not part of the public API.**
            #[doc(hidden)]
            pub fn _merge_into_view(
                &mut self,
                buf: &'a [u8],
                depth: u32,
            ) -> ::core::result::Result<(), ::buffa::DecodeError> {
                // `depth` may be unused for messages with no nested sub-message fields.
                let _ = depth;
                // Rebind as `view` so the arm-generating functions (which emit
                // `view.#ident`) work unchanged.
                #[allow(unused_variables)]
                let view = self;
                let mut cur: &'a [u8] = buf;
                while !cur.is_empty() {
                    #before_tag_capture
                    let tag = ::buffa::encoding::Tag::decode(&mut cur)?;
                    match tag.field_number() {
                        #(#scalar_arms)*
                        #(#repeated_arms)*
                        #(#oneof_arms)*
                        _ => {
                            ::buffa::encoding::skip_field_depth(tag, &mut cur, depth)?;
                            #unknown_field_handling
                        }
                    }
                }
                ::core::result::Result::Ok(())
            }
        }

        impl<'a> ::buffa::MessageView<'a> for #view_ident<'a> {
            type Owned = #owned_path;

            fn decode_view(
                buf: &'a [u8],
            ) -> ::core::result::Result<Self, ::buffa::DecodeError> {
                Self::_decode_depth(buf, ::buffa::RECURSION_LIMIT)
            }

            fn decode_view_with_limit(
                buf: &'a [u8],
                depth: u32,
            ) -> ::core::result::Result<Self, ::buffa::DecodeError> {
                Self::_decode_depth(buf, depth)
            }

            fn to_owned_message(&self) -> #owned_path {
                self.to_owned_from_source(None)
            }

            // useless_conversion: __buffa_unknown_fields uses `.into()` to
            // unify the `UnknownFields` (no-wrapper) and `__<Name>ExtJson`
            // (generate_json wrapper) cases; no-op in the former.
            #[allow(clippy::useless_conversion, clippy::needless_update)]
            fn to_owned_from_source(
                &self,
                __buffa_src: ::core::option::Option<&::buffa::bytes::Bytes>,
            ) -> #owned_path {
                #[allow(unused_imports)]
                use ::buffa::alloc::string::ToString as _;
                let _ = __buffa_src;
                #owned_path {
                    #(#owned_fields)*
                    ..::core::default::Default::default()
                }
            }
        }

        #view_encode_impl

        #serialize_impl

        #message_name_impl

        impl<'v> ::buffa::DefaultViewInstance for #view_ident<'v> {
            fn default_view_instance<'a>() -> &'a Self
            where
                Self: 'a,
            {
                static VALUE: ::buffa::__private::OnceBox<#view_ident<'static>>
                    = ::buffa::__private::OnceBox::new();
                VALUE.get_or_init(|| ::buffa::alloc::boxed::Box::new(
                    <#view_ident<'static>>::default(),
                ))
            }
        }

        impl ::buffa::ViewReborrow for #view_ident<'static> {
            type Reborrowed<'b> = #view_ident<'b>;
            fn reborrow<'b>(this: &'b Self) -> &'b Self::Reborrowed<'b> {
                this
            }
        }

        #owned_view_wrapper

        #reflect_view_impls
    };

    Ok((top_level, mod_items))
}

// ---------------------------------------------------------------------------
// View struct field declarations
// ---------------------------------------------------------------------------

fn view_struct_field(
    scope: MessageScope<'_>,
    msg: &DescriptorProto,
    field: &FieldDescriptorProto,
) -> Result<Option<(TokenStream, proc_macro2::Ident, bool)>, CodeGenError> {
    let MessageScope { ctx, proto_fqn, .. } = scope;
    // Real oneof members go into the oneof enum, not directly on the struct.
    if is_real_oneof_member(field) {
        return Ok(None);
    }

    let field_name = field
        .name
        .as_deref()
        .ok_or(CodeGenError::MissingField("field.name"))?;
    let label = field.label.unwrap_or_default();
    let is_repeated = label == Label::LABEL_REPEATED;
    let field_fqn = format!("{}.{}", proto_fqn, field_name);
    let proto_comment = ctx.comment(&field_fqn);

    if is_repeated && is_map_field(msg, field) {
        let ident = make_field_ident(field_name);
        let number = field.number.unwrap_or(0);
        let tag_line = format!("Field {number}: `{field_name}` (map)");
        let doc = crate::comments::doc_attrs_with_tag_resolved(
            proto_comment,
            &tag_line,
            proto_fqn,
            &ctx.type_map,
        );
        let map_ty = view_map_type(scope, msg, field, &quote! { 'a })?;
        let tokens = quote! {
            #doc
            pub #ident: #map_ty,
        };
        return Ok(Some((
            tokens,
            ident,
            crate::message::is_debug_redacted(field),
        )));
    }

    let ident = make_field_ident(field_name);
    let number = field.number.unwrap_or(0);
    let tag_line = format!("Field {number}: `{field_name}`");
    let doc = crate::comments::doc_attrs_with_tag_resolved(
        proto_comment,
        &tag_line,
        proto_fqn,
        &ctx.type_map,
    );

    let rust_type = if is_repeated {
        view_repeated_type(scope, field, &quote! { 'a })?
    } else {
        view_singular_type(scope, field, &quote! { 'a })?
    };

    // Self-referential view fields (e.g. HttpRuleView.additional_bindings)
    // can use `Self` — inside `struct FooView<'a>`, `Self` means `FooView<'a>`
    // with the lifetime applied. Override only for message-typed, non-map
    // struct fields; decode and to_owned paths use the resolved type as-is
    // via the helper functions so no conflict there.
    let self_fqn = format!(".{proto_fqn}");
    let struct_ty = if field.type_name.as_deref() == Some(self_fqn.as_str()) {
        if is_repeated {
            quote! { ::buffa::RepeatedView<'a, Self> }
        } else {
            quote! { ::buffa::MessageFieldView<Self> }
        }
    } else {
        rust_type
    };

    let tokens = quote! {
        #doc
        pub #ident: #struct_ty,
    };
    Ok(Some((
        tokens,
        ident,
        crate::message::is_debug_redacted(field),
    )))
}

/// Field type for a singular (non-repeated, non-map) view field, with `lt` as
/// the borrow lifetime (`'a` inside the view struct, `'_` in accessor return
/// position on the generated owned-view wrapper).
pub(crate) fn view_singular_type(
    scope: MessageScope<'_>,
    field: &FieldDescriptorProto,
    lt: &TokenStream,
) -> Result<TokenStream, CodeGenError> {
    let MessageScope {
        ctx,
        features: parent_features,
        ..
    } = scope;
    let features = &crate::features::resolve_field(ctx, field, parent_features);
    let ty = effective_type(ctx, field, features);

    if is_explicit_presence_scalar(field, ty, features) {
        return Ok(match ty {
            Type::TYPE_STRING => quote! { ::core::option::Option<&#lt str> },
            Type::TYPE_BYTES => quote! { ::core::option::Option<&#lt [u8]> },
            Type::TYPE_ENUM => {
                let et = resolve_enum_ty(scope, field)?;
                if is_closed_enum(features) {
                    quote! { ::core::option::Option<#et> }
                } else {
                    quote! { ::core::option::Option<::buffa::EnumValue<#et>> }
                }
            }
            _ => {
                let st = scalar_ty(ty);
                quote! { ::core::option::Option<#st> }
            }
        });
    }

    match ty {
        Type::TYPE_STRING => Ok(quote! { &#lt str }),
        Type::TYPE_BYTES => Ok(quote! { &#lt [u8] }),
        Type::TYPE_MESSAGE | Type::TYPE_GROUP => {
            let view_ty = resolve_view_ty_tokens(scope, field, lt)?;
            Ok(quote! { ::buffa::MessageFieldView<#view_ty> })
        }
        Type::TYPE_ENUM => {
            let et = resolve_enum_ty(scope, field)?;
            if is_closed_enum(features) {
                Ok(quote! { #et })
            } else {
                Ok(quote! { ::buffa::EnumValue<#et> })
            }
        }
        _ => Ok(scalar_ty(ty)),
    }
}

/// Field type for a repeated (non-map) view field, with `lt` as the borrow
/// lifetime — see [`view_singular_type`].
pub(crate) fn view_repeated_type(
    scope: MessageScope<'_>,
    field: &FieldDescriptorProto,
    lt: &TokenStream,
) -> Result<TokenStream, CodeGenError> {
    let MessageScope {
        ctx,
        features: parent_features,
        ..
    } = scope;
    let features = &crate::features::resolve_field(ctx, field, parent_features);
    let ty = effective_type(ctx, field, features);
    match ty {
        Type::TYPE_STRING => Ok(quote! { ::buffa::RepeatedView<#lt, &#lt str> }),
        Type::TYPE_BYTES => Ok(quote! { ::buffa::RepeatedView<#lt, &#lt [u8]> }),
        Type::TYPE_MESSAGE | Type::TYPE_GROUP => {
            let view_ty = resolve_view_ty_tokens(scope, field, lt)?;
            Ok(quote! { ::buffa::RepeatedView<#lt, #view_ty> })
        }
        Type::TYPE_ENUM => {
            let et = resolve_enum_ty(scope, field)?;
            if is_closed_enum(features) {
                Ok(quote! { ::buffa::RepeatedView<#lt, #et> })
            } else {
                Ok(quote! { ::buffa::RepeatedView<#lt, ::buffa::EnumValue<#et>> })
            }
        }
        _ => {
            let st = scalar_ty(ty);
            Ok(quote! { ::buffa::RepeatedView<#lt, #st> })
        }
    }
}

/// Build the `::buffa::MapView<K, V>` type for a map field, with `lt` as the
/// borrow lifetime — see [`view_singular_type`].
pub(crate) fn view_map_type(
    scope: MessageScope<'_>,
    msg: &DescriptorProto,
    field: &FieldDescriptorProto,
    lt: &TokenStream,
) -> Result<TokenStream, CodeGenError> {
    let MessageScope { ctx, features, .. } = scope;
    let (key_fd, val_fd) = find_map_entry_fields(msg, field)?;

    let key_ty = match effective_type_in_map_entry(ctx, key_fd, features) {
        Type::TYPE_STRING => quote! { &#lt str },
        // utf8_validation = NONE on a string map key → &'a [u8].
        Type::TYPE_BYTES => quote! { &#lt [u8] },
        ty => scalar_ty(ty),
    };

    let val_ty = match effective_type_in_map_entry(ctx, val_fd, features) {
        Type::TYPE_STRING => quote! { &#lt str },
        Type::TYPE_BYTES => quote! { &#lt [u8] },
        Type::TYPE_MESSAGE => {
            let view_ty = resolve_view_ty_tokens(scope, val_fd, lt)?;
            quote! { #view_ty }
        }
        Type::TYPE_ENUM => {
            let et = resolve_enum_ty(scope, val_fd)?;
            let val_features = crate::features::resolve_field(ctx, val_fd, features);
            if is_closed_enum(&val_features) {
                quote! { #et }
            } else {
                quote! { ::buffa::EnumValue<#et> }
            }
        }
        ty => scalar_ty(ty),
    };

    Ok(quote! { ::buffa::MapView<#lt, #key_ty, #val_ty> })
}

/// Does the oneof's view enum need a `'a` lifetime parameter?
///
/// String/bytes/message/group variants borrow from the input buffer;
/// scalar and enum variants don't. An all-scalar oneof must not emit
/// `<'a>` or the unused-lifetime check (E0392) fires.
pub(crate) fn oneof_view_needs_lifetime(
    ctx: &CodeGenContext,
    fields: &[&FieldDescriptorProto],
    features: &ResolvedFeatures,
) -> bool {
    fields.iter().any(|f| {
        matches!(
            effective_type(ctx, f, features),
            Type::TYPE_STRING | Type::TYPE_BYTES | Type::TYPE_MESSAGE | Type::TYPE_GROUP
        )
    })
}

/// Does the message's view struct have any field that borrows from `'a`?
///
/// Repeated, map, string, bytes, message, group fields all use `'a`.
/// Only an all-scalar/enum message with `preserve_unknown_fields=false`
/// has no borrowing fields — in that case a PhantomData marker is needed
/// to keep the `<'a>` lifetime valid for `_decode_depth(buf: &'a [u8])`.
fn message_view_has_borrowing_field(
    ctx: &CodeGenContext,
    msg: &DescriptorProto,
    features: &ResolvedFeatures,
    preserve_unknown_fields: bool,
) -> bool {
    if preserve_unknown_fields {
        // UnknownFieldsView<'a> always uses 'a.
        return true;
    }
    for f in &msg.field {
        if is_real_oneof_member(f) {
            continue; // oneof members checked below via oneof_view_needs_lifetime
        }
        // Repeated and map fields always use 'a (RepeatedView<'a, T>, MapView<'a, K, V>).
        if f.label.unwrap_or_default()
            == crate::generated::descriptor::field_descriptor_proto::Label::LABEL_REPEATED
        {
            return true;
        }
        // Singular string/bytes/message/group borrow.
        if matches!(
            effective_type(ctx, f, features),
            Type::TYPE_STRING | Type::TYPE_BYTES | Type::TYPE_MESSAGE | Type::TYPE_GROUP
        ) {
            return true;
        }
    }
    // Check oneofs: an all-scalar oneof doesn't borrow, but one with a
    // string/bytes/message/group variant does.
    for (idx, _) in msg.oneof_decl.iter().enumerate() {
        let fields: Vec<_> = msg
            .field
            .iter()
            .filter(|f| is_real_oneof_member(f) && f.oneof_index == Some(idx as i32))
            .collect();
        if oneof_view_needs_lifetime(ctx, &fields, features) {
            return true;
        }
    }
    false
}

fn oneof_view_struct_fields(
    ctx: &CodeGenContext,
    msg: &DescriptorProto,
    view_oneof_prefix: &TokenStream,
    features: &ResolvedFeatures,
    oneof_idents: &std::collections::HashMap<usize, proc_macro2::Ident>,
) -> Result<Vec<(TokenStream, proc_macro2::Ident)>, CodeGenError> {
    let mut out = Vec::new();
    for (idx, oneof) in msg.oneof_decl.iter().enumerate() {
        let enum_ident = match oneof_idents.get(&idx) {
            Some(id) => id,
            None => continue,
        };
        let fields: Vec<_> = msg
            .field
            .iter()
            .filter(|f| is_real_oneof_member(f) && f.oneof_index == Some(idx as i32))
            .collect();
        if fields.is_empty() {
            continue;
        }
        let oneof_name = oneof
            .name
            .as_deref()
            .ok_or(CodeGenError::MissingField("oneof.name"))?;
        let field_ident = make_field_ident(oneof_name);
        let generics = if oneof_view_needs_lifetime(ctx, &fields, features) {
            quote! { <'a> }
        } else {
            quote! {}
        };
        let tokens = quote! {
            pub #field_ident: ::core::option::Option<#view_oneof_prefix #enum_ident #generics>,
        };
        out.push((tokens, field_ident));
    }
    Ok(out)
}

// ---------------------------------------------------------------------------
// Oneof view enum
// ---------------------------------------------------------------------------

fn generate_oneof_view_enum(
    scope: MessageScope<'_>,
    msg: &DescriptorProto,
    idx: usize,
    _oneof: &OneofDescriptorProto,
    oneof_idents: &std::collections::HashMap<usize, proc_macro2::Ident>,
) -> Result<TokenStream, CodeGenError> {
    let MessageScope { ctx, features, .. } = scope;
    let base_ident = match oneof_idents.get(&idx) {
        Some(id) => id,
        None => return Ok(TokenStream::new()),
    };

    let fields: Vec<_> = msg
        .field
        .iter()
        .filter(|f| is_real_oneof_member(f) && f.oneof_index == Some(idx as i32))
        .collect();

    if fields.is_empty() {
        return Ok(TokenStream::new());
    }

    // View-oneof enums share the owned oneof's identifier (no `View` suffix)
    // — the `__buffa::view::oneof::` tree position disambiguates. They live
    // at depth `msg_nesting + 4` (sentinel + view + oneof + msg_path).
    let enum_body_depth = scope.nesting + 4;
    let body_scope = MessageScope {
        nesting: enum_body_depth,
        ..scope
    };

    let variants = fields
        .iter()
        .map(|f| {
            let name = f
                .name
                .as_deref()
                .ok_or(CodeGenError::MissingField("field.name"))?;
            let variant = crate::oneof::oneof_variant_ident(name);
            let ty = effective_type(ctx, f, features);
            let f_features = crate::features::resolve_field(ctx, f, features);
            let vty = match ty {
                Type::TYPE_STRING => quote! { &'a str },
                Type::TYPE_BYTES => quote! { &'a [u8] },
                Type::TYPE_MESSAGE | Type::TYPE_GROUP => {
                    let view_ty = resolve_view_ty_tokens(body_scope, f, &quote! { 'a })?;
                    quote! { ::buffa::alloc::boxed::Box<#view_ty> }
                }
                Type::TYPE_ENUM => {
                    let et = resolve_enum_ty(body_scope, f)?;
                    if is_closed_enum(&f_features) {
                        quote! { #et }
                    } else {
                        quote! { ::buffa::EnumValue<#et> }
                    }
                }
                _ => scalar_ty(ty),
            };
            Ok(quote! { #variant(#vty) })
        })
        .collect::<Result<Vec<_>, CodeGenError>>()?;

    let generics = if oneof_view_needs_lifetime(ctx, &fields, features) {
        quote! { <'a> }
    } else {
        quote! {}
    };

    // Variants whose field is `[debug_redact = true]` print a placeholder
    // instead of their payload (same rule as the owned oneof enum).
    let any_redacted = fields.iter().any(|f| crate::message::is_debug_redacted(f));
    let (debug_derive, debug_impl) = if any_redacted {
        let placeholder = crate::message::DEBUG_REDACT_PLACEHOLDER;
        let arms = fields
            .iter()
            .map(|field| {
                let name = field
                    .name
                    .as_deref()
                    .ok_or(CodeGenError::MissingField("field.name"))?;
                let ident = crate::oneof::oneof_variant_ident(name);
                let label = ident.to_string();
                Ok(if crate::message::is_debug_redacted(field) {
                    quote! {
                        Self::#ident(_) => f
                            .debug_tuple(#label)
                            .field(&::core::format_args!(#placeholder))
                            .finish(),
                    }
                } else {
                    quote! {
                        Self::#ident(value) => f.debug_tuple(#label).field(value).finish(),
                    }
                })
            })
            .collect::<Result<Vec<_>, CodeGenError>>()?;
        (
            quote! { #[derive(Clone)] },
            quote! {
                impl #generics ::core::fmt::Debug for #base_ident #generics {
                    fn fmt(&self, f: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result {
                        match self {
                            #(#arms)*
                        }
                    }
                }
            },
        )
    } else {
        (quote! { #[derive(Clone, Debug)] }, quote! {})
    };

    Ok(quote! {
        #debug_derive
        pub enum #base_ident #generics {
            #(#variants,)*
        }

        #debug_impl
    })
}

// ---------------------------------------------------------------------------
// decode_view match arms
// ---------------------------------------------------------------------------

#[allow(clippy::type_complexity)]
fn build_decode_arms(
    scope: MessageScope<'_>,
    msg: &DescriptorProto,
    view_oneof_prefix: &TokenStream,
    oneof_idents: &std::collections::HashMap<usize, proc_macro2::Ident>,
) -> Result<(Vec<TokenStream>, Vec<TokenStream>, Vec<TokenStream>), CodeGenError> {
    let scalar_fields: Vec<_> = msg
        .field
        .iter()
        .filter(|f| {
            if is_real_oneof_member(f) {
                return false;
            }
            f.label.unwrap_or_default() != Label::LABEL_REPEATED
                && is_supported_field_type(f.r#type.unwrap_or_default())
        })
        .collect();
    let scalar_arms = scalar_fields
        .iter()
        .map(|f| scalar_decode_arm(scope, f))
        .collect::<Result<Vec<_>, _>>()?;

    let repeated_fields: Vec<_> = msg
        .field
        .iter()
        .filter(|f| {
            f.label.unwrap_or_default() == Label::LABEL_REPEATED
                && !is_map_field(msg, f)
                && is_supported_field_type(f.r#type.unwrap_or_default())
        })
        .collect();
    let mut repeated_arms: Vec<_> = repeated_fields
        .iter()
        .map(|f| repeated_decode_arm(scope, f))
        .collect::<Result<Vec<_>, _>>()?;

    // Map fields: decode entries into MapView.
    let map_fields: Vec<_> = msg
        .field
        .iter()
        .filter(|f| f.label.unwrap_or_default() == Label::LABEL_REPEATED && is_map_field(msg, f))
        .collect();
    let map_arms = map_fields
        .iter()
        .map(|f| map_decode_arm(scope, msg, f))
        .collect::<Result<Vec<_>, _>>()?;
    repeated_arms.extend(map_arms);

    let mut oneof_arms: Vec<TokenStream> = Vec::new();
    for (idx, oneof) in msg.oneof_decl.iter().enumerate() {
        let base_ident = match oneof_idents.get(&idx) {
            Some(id) => id,
            None => continue,
        };
        let oneof_name = oneof
            .name
            .as_deref()
            .ok_or(CodeGenError::MissingField("oneof.name"))?;
        let fields: Vec<_> = msg
            .field
            .iter()
            .filter(|f| is_real_oneof_member(f) && f.oneof_index == Some(idx as i32))
            .collect();
        oneof_arms.extend(oneof_decode_arms(
            scope,
            base_ident,
            oneof_name,
            &fields,
            view_oneof_prefix,
        )?);
    }

    Ok((scalar_arms, repeated_arms, oneof_arms))
}

fn scalar_decode_arm(
    scope: MessageScope<'_>,
    field: &FieldDescriptorProto,
) -> Result<TokenStream, CodeGenError> {
    let MessageScope {
        ctx,
        features: parent_features,
        ..
    } = scope;
    let preserve_unknown_fields = ctx.config.preserve_unknown_fields;
    let features = &crate::features::resolve_field(ctx, field, parent_features);
    let field_name = field
        .name
        .as_deref()
        .ok_or(CodeGenError::MissingField("field.name"))?;
    let field_number = validated_field_number(field)?;
    let ty = effective_type(ctx, field, features);
    let ident = make_field_ident(field_name);
    let wire_type = wire_type_token(ty);
    let expected_byte = wire_type_byte(ty);

    let wire_check = wire_type_check(field_number, &wire_type, expected_byte);

    if is_explicit_presence_scalar(field, ty, features) {
        let assign = match ty {
            Type::TYPE_STRING => {
                quote! { view.#ident = Some(::buffa::types::borrow_str(&mut cur)?); }
            }
            Type::TYPE_BYTES => {
                quote! { view.#ident = Some(::buffa::types::borrow_bytes(&mut cur)?); }
            }
            Type::TYPE_ENUM => {
                if is_closed_enum(features) {
                    let unknown_route = closed_enum_view_unknown_route(preserve_unknown_fields);
                    closed_enum_decode_with_unknown(
                        &quote! { &mut cur },
                        quote! { view.#ident = Some(__v); },
                        unknown_route,
                    )
                } else {
                    quote! {
                        view.#ident = Some(::buffa::EnumValue::from(::buffa::types::decode_int32(&mut cur)?));
                    }
                }
            }
            _ => {
                let dfn = decode_fn_token(ty);
                quote! { view.#ident = Some(#dfn(&mut cur)?); }
            }
        };
        return Ok(quote! { #field_number => { #wire_check #assign } });
    }

    let assign = match ty {
        Type::TYPE_STRING => quote! { view.#ident = ::buffa::types::borrow_str(&mut cur)?; },
        Type::TYPE_BYTES => quote! { view.#ident = ::buffa::types::borrow_bytes(&mut cur)?; },
        Type::TYPE_ENUM => {
            if is_closed_enum(features) {
                let unknown_route = closed_enum_view_unknown_route(preserve_unknown_fields);
                closed_enum_decode_with_unknown(
                    &quote! { &mut cur },
                    quote! { view.#ident = __v; },
                    unknown_route,
                )
            } else {
                quote! { view.#ident = ::buffa::EnumValue::from(::buffa::types::decode_int32(&mut cur)?); }
            }
        }
        Type::TYPE_MESSAGE => {
            let vt = resolve_view_decode_tokens(scope, field)?;
            quote! {
                if depth == 0 {
                    return Err(::buffa::DecodeError::RecursionLimitExceeded);
                }
                let sub = ::buffa::types::borrow_bytes(&mut cur)?;
                // Proto merge semantics: if this field appeared before,
                // merge the new bytes into the existing view.
                match view.#ident.as_mut() {
                    Some(existing) => existing._merge_into_view(sub, depth - 1)?,
                    None => view.#ident = ::buffa::MessageFieldView::set(
                        #vt::_decode_depth(sub, depth - 1)?
                    ),
                }
            }
        }
        Type::TYPE_GROUP => {
            let vt = resolve_view_decode_tokens(scope, field)?;
            quote! {
                if depth == 0 {
                    return Err(::buffa::DecodeError::RecursionLimitExceeded);
                }
                let sub = ::buffa::types::borrow_group(&mut cur, #field_number, depth - 1)?;
                match view.#ident.as_mut() {
                    Some(existing) => existing._merge_into_view(sub, depth - 1)?,
                    None => view.#ident = ::buffa::MessageFieldView::set(
                        #vt::_decode_depth(sub, depth - 1)?
                    ),
                }
            }
        }
        _ => {
            let dfn = decode_fn_token(ty);
            quote! { view.#ident = #dfn(&mut cur)?; }
        }
    };

    Ok(quote! { #field_number => { #wire_check #assign } })
}

fn repeated_decode_arm(
    scope: MessageScope<'_>,
    field: &FieldDescriptorProto,
) -> Result<TokenStream, CodeGenError> {
    let MessageScope {
        ctx,
        features: parent_features,
        ..
    } = scope;
    let preserve_unknown_fields = ctx.config.preserve_unknown_fields;
    let features = &crate::features::resolve_field(ctx, field, parent_features);
    let field_name = field
        .name
        .as_deref()
        .ok_or(CodeGenError::MissingField("field.name"))?;
    let field_number = validated_field_number(field)?;
    let ty = effective_type(ctx, field, features);
    let ident = make_field_ident(field_name);

    // Message: always LengthDelimited, unpacked.
    if ty == Type::TYPE_MESSAGE {
        let ld_check = wire_type_check(
            field_number,
            &quote! { ::buffa::encoding::WireType::LengthDelimited },
            2u8,
        );
        let vt = resolve_view_decode_tokens(scope, field)?;
        return Ok(quote! {
            #field_number => {
                #ld_check
                if depth == 0 {
                    return Err(::buffa::DecodeError::RecursionLimitExceeded);
                }
                let sub = ::buffa::types::borrow_bytes(&mut cur)?;
                view.#ident.push(#vt::_decode_depth(sub, depth - 1)?);
            }
        });
    }

    // Group: StartGroup wire type, unpacked.
    if ty == Type::TYPE_GROUP {
        let sg_check = wire_type_check(
            field_number,
            &quote! { ::buffa::encoding::WireType::StartGroup },
            3u8,
        );
        let vt = resolve_view_decode_tokens(scope, field)?;
        return Ok(quote! {
            #field_number => {
                #sg_check
                if depth == 0 {
                    return Err(::buffa::DecodeError::RecursionLimitExceeded);
                }
                let sub = ::buffa::types::borrow_group(&mut cur, #field_number, depth - 1)?;
                view.#ident.push(#vt::_decode_depth(sub, depth - 1)?);
            }
        });
    }

    // String and bytes: unpacked only (no packed encoding for LD types).
    if !is_packed_type(ty) {
        let ld_check = wire_type_check(
            field_number,
            &quote! { ::buffa::encoding::WireType::LengthDelimited },
            2u8,
        );
        let borrow = match ty {
            Type::TYPE_STRING => quote! { ::buffa::types::borrow_str(&mut cur)? },
            Type::TYPE_BYTES => quote! { ::buffa::types::borrow_bytes(&mut cur)? },
            // Message and group are handled by early returns above; the
            // remaining types satisfy `is_packed_type` and never reach this
            // unpacked branch. Enumerated so adding a `Type` variant is a
            // compile error here rather than a runtime panic during codegen.
            Type::TYPE_MESSAGE
            | Type::TYPE_GROUP
            | Type::TYPE_ENUM
            | Type::TYPE_BOOL
            | Type::TYPE_INT32
            | Type::TYPE_INT64
            | Type::TYPE_UINT32
            | Type::TYPE_UINT64
            | Type::TYPE_SINT32
            | Type::TYPE_SINT64
            | Type::TYPE_FIXED32
            | Type::TYPE_FIXED64
            | Type::TYPE_SFIXED32
            | Type::TYPE_SFIXED64
            | Type::TYPE_FLOAT
            | Type::TYPE_DOUBLE => {
                unreachable!("view repeated decode arm: unhandled unpacked type {:?}", ty)
            }
        };
        return Ok(quote! {
            #field_number => {
                #ld_check
                view.#ident.push(#borrow);
            }
        });
    }

    // Packed numeric/enum: accept both packed (LengthDelimited) and unpacked.
    let elem_wire_type = wire_type_token(ty);
    let closed = is_closed_enum(features);
    let push_known = quote! { view.#ident.push(__v); };
    let packed_elem = if ty == Type::TYPE_ENUM {
        if closed {
            closed_enum_decode(&quote! { &mut pcur }, push_known.clone())
        } else {
            quote! { view.#ident.push(::buffa::EnumValue::from(::buffa::types::decode_int32(&mut pcur)?)); }
        }
    } else {
        let dfn = decode_fn_token(ty);
        quote! { view.#ident.push(#dfn(&mut pcur)?); }
    };

    // Fixed-size types can reserve the exact element count. For varints and
    // bools, every element occupies at least one byte, so the payload length
    // is a safe upper bound.
    let reserve_divisor: usize = match ty {
        Type::TYPE_FIXED32 | Type::TYPE_SFIXED32 | Type::TYPE_FLOAT => 4,
        Type::TYPE_FIXED64 | Type::TYPE_SFIXED64 | Type::TYPE_DOUBLE => 8,
        _ => 1,
    };
    let reserve_stmt = if reserve_divisor > 1 {
        quote! { view.#ident.reserve(payload.len() / #reserve_divisor); }
    } else {
        quote! { view.#ident.reserve(payload.len()); }
    };

    let unpacked_elem = if ty == Type::TYPE_ENUM {
        if closed {
            // Unpacked: each element has its own tag, so `before_tag` captures
            // the per-element span. Packed (above) can't do this — the tag
            // covers the whole blob — so packed unknowns are still dropped.
            let unknown_route = closed_enum_view_unknown_route(preserve_unknown_fields);
            closed_enum_decode_with_unknown(&quote! { &mut cur }, push_known, unknown_route)
        } else {
            quote! { view.#ident.push(::buffa::EnumValue::from(::buffa::types::decode_int32(&mut cur)?)); }
        }
    } else {
        let dfn = decode_fn_token(ty);
        quote! { view.#ident.push(#dfn(&mut cur)?); }
    };

    Ok(quote! {
        #field_number => {
            if tag.wire_type() == ::buffa::encoding::WireType::LengthDelimited {
                // Packed: extract payload, decode elements via local cursor.
                let payload = ::buffa::types::borrow_bytes(&mut cur)?;
                #reserve_stmt
                let mut pcur: &[u8] = payload;
                while !pcur.is_empty() { #packed_elem }
            } else if tag.wire_type() == #elem_wire_type {
                // Unpacked (backward-compat with old encoders).
                #unpacked_elem
            } else {
                return Err(::buffa::DecodeError::WireTypeMismatch {
                    field_number: #field_number,
                    expected: 2u8,
                    actual: tag.wire_type() as u8,
                });
            }
        }
    })
}

fn map_decode_arm(
    scope: MessageScope<'_>,
    msg: &DescriptorProto,
    field: &FieldDescriptorProto,
) -> Result<TokenStream, CodeGenError> {
    let MessageScope { ctx, features, .. } = scope;
    let field_name = field
        .name
        .as_deref()
        .ok_or(CodeGenError::MissingField("field.name"))?;
    let field_number = validated_field_number(field)?;
    let ident = make_field_ident(field_name);
    let (key_fd, val_fd) = find_map_entry_fields(msg, field)?;

    let ld_check = wire_type_check(
        field_number,
        &quote! { ::buffa::encoding::WireType::LengthDelimited },
        2u8,
    );

    // Default values for key and value when the entry sub-message omits them.
    let key_default = match effective_type_in_map_entry(ctx, key_fd, features) {
        Type::TYPE_STRING => quote! { "" },
        Type::TYPE_BYTES => quote! { &[][..] },
        _ => quote! { ::core::default::Default::default() },
    };
    let val_default = match effective_type_in_map_entry(ctx, val_fd, features) {
        Type::TYPE_STRING => quote! { "" },
        Type::TYPE_BYTES => quote! { &[][..] },
        _ => quote! { ::core::default::Default::default() },
    };

    let decode_key = map_view_entry_decode(scope, key_fd, &format_ident!("key"))?;
    let decode_val = map_view_entry_decode(scope, val_fd, &format_ident!("val"))?;

    Ok(quote! {
        #field_number => {
            #ld_check
            let entry_bytes = ::buffa::types::borrow_bytes(&mut cur)?;
            let mut entry_cur: &'a [u8] = entry_bytes;
            let mut key = #key_default;
            let mut val = #val_default;
            while !entry_cur.is_empty() {
                let entry_tag = ::buffa::encoding::Tag::decode(&mut entry_cur)?;
                match entry_tag.field_number() {
                    1 => { #decode_key }
                    2 => { #decode_val }
                    _ => { ::buffa::encoding::skip_field_depth(entry_tag, &mut entry_cur, depth)?; }
                }
            }
            view.#ident.push(key, val);
        }
    })
}

/// Generate the decode statement for one field inside a map-entry sub-message.
///
/// Uses zero-copy `borrow_str`/`borrow_bytes` for string/bytes fields and
/// decodes message values into view types.
fn map_view_entry_decode(
    scope: MessageScope<'_>,
    fd: &FieldDescriptorProto,
    var: &proc_macro2::Ident,
) -> Result<TokenStream, CodeGenError> {
    let MessageScope {
        ctx,
        features: parent_features,
        ..
    } = scope;
    let features = &crate::features::resolve_field(ctx, fd, parent_features);
    let ty = effective_type_in_map_entry(ctx, fd, features);
    let wire_type = wire_type_token(ty);
    let wire_byte = wire_type_byte(ty);
    let tag_check = quote! {
        if entry_tag.wire_type() != #wire_type {
            return ::core::result::Result::Err(::buffa::DecodeError::WireTypeMismatch {
                field_number: entry_tag.field_number(),
                expected: #wire_byte,
                actual: entry_tag.wire_type() as u8,
            });
        }
    };

    let assign = match ty {
        Type::TYPE_STRING => quote! { #var = ::buffa::types::borrow_str(&mut entry_cur)?; },
        Type::TYPE_BYTES => quote! { #var = ::buffa::types::borrow_bytes(&mut entry_cur)?; },
        Type::TYPE_ENUM => {
            if is_closed_enum(features) {
                closed_enum_decode(&quote! { &mut entry_cur }, quote! { #var = __v; })
            } else {
                quote! { #var = ::buffa::EnumValue::from(::buffa::types::decode_int32(&mut entry_cur)?); }
            }
        }
        Type::TYPE_MESSAGE => {
            let vt = resolve_view_decode_tokens(scope, fd)?;
            quote! {
                if depth == 0 {
                    return Err(::buffa::DecodeError::RecursionLimitExceeded);
                }
                let sub = ::buffa::types::borrow_bytes(&mut entry_cur)?;
                #var = #vt::_decode_depth(sub, depth - 1)?;
            }
        }
        _ => {
            let dfn = decode_fn_token(ty);
            quote! { #var = #dfn(&mut entry_cur)?; }
        }
    };

    Ok(quote! { #tag_check #assign })
}

fn oneof_decode_arms(
    scope: MessageScope<'_>,
    base_ident: &proc_macro2::Ident,
    oneof_name: &str,
    fields: &[&FieldDescriptorProto],
    view_oneof_prefix: &TokenStream,
) -> Result<Vec<TokenStream>, CodeGenError> {
    let MessageScope { ctx, features, .. } = scope;
    let preserve_unknown_fields = ctx.config.preserve_unknown_fields;
    let field_ident = make_field_ident(oneof_name);
    let view_enum: TokenStream = quote! { #view_oneof_prefix #base_ident };

    fields
        .iter()
        .map(|field| {
            let name = field
                .name
                .as_deref()
                .ok_or(CodeGenError::MissingField("field.name"))?;
            let field_number = validated_field_number(field)?;
            let ty = effective_type(ctx, field, features);
            let field_features = crate::features::resolve_field(ctx, field, features);
            let variant = crate::oneof::oneof_variant_ident(name);
            let wire_type = wire_type_token(ty);
            let expected_byte = wire_type_byte(ty);
            let wire_check = wire_type_check(field_number, &wire_type, expected_byte);

            let value = match ty {
                Type::TYPE_STRING => quote! { ::buffa::types::borrow_str(&mut cur)? },
                Type::TYPE_BYTES => quote! { ::buffa::types::borrow_bytes(&mut cur)? },
                Type::TYPE_MESSAGE => {
                    let vt = resolve_view_decode_tokens(scope, field)?;
                    // Proto merge semantics: if this same variant is already set,
                    // merge into the existing boxed view rather than replacing.
                    // Uses an early `return Ok(...)` since the merge path doesn't
                    // fit the `value` expression shape used by scalar variants.
                    return Ok(quote! {
                        #field_number => {
                            #wire_check
                            if depth == 0 {
                                return Err(::buffa::DecodeError::RecursionLimitExceeded);
                            }
                            let sub = ::buffa::types::borrow_bytes(&mut cur)?;
                            if let Some(#view_enum::#variant(ref mut existing)) = view.#field_ident {
                                existing._merge_into_view(sub, depth - 1)?;
                            } else {
                                view.#field_ident = Some(#view_enum::#variant(
                                    ::buffa::alloc::boxed::Box::new(
                                        #vt::_decode_depth(sub, depth - 1)?
                                    )
                                ));
                            }
                        }
                    });
                }
                Type::TYPE_GROUP => {
                    let vt = resolve_view_decode_tokens(scope, field)?;
                    return Ok(quote! {
                        #field_number => {
                            #wire_check
                            if depth == 0 {
                                return Err(::buffa::DecodeError::RecursionLimitExceeded);
                            }
                            let sub = ::buffa::types::borrow_group(&mut cur, #field_number, depth - 1)?;
                            if let Some(#view_enum::#variant(ref mut existing)) = view.#field_ident {
                                existing._merge_into_view(sub, depth - 1)?;
                            } else {
                                view.#field_ident = Some(#view_enum::#variant(
                                    ::buffa::alloc::boxed::Box::new(
                                        #vt::_decode_depth(sub, depth - 1)?
                                    )
                                ));
                            }
                        }
                    });
                }
                Type::TYPE_ENUM => {
                    if is_closed_enum(&field_features) {
                        let unknown_route =
                            closed_enum_view_unknown_route(preserve_unknown_fields);
                        let decode = closed_enum_decode_with_unknown(
                            &quote! { &mut cur },
                            quote! { view.#field_ident = Some(#view_enum::#variant(__v)); },
                            unknown_route,
                        );
                        return Ok(quote! {
                            #field_number => {
                                #wire_check
                                #decode
                            }
                        });
                    }
                    quote! { ::buffa::EnumValue::from(::buffa::types::decode_int32(&mut cur)?) }
                }
                _ => {
                    let dfn = decode_fn_token(ty);
                    quote! { #dfn(&mut cur)? }
                }
            };

            Ok(quote! {
                #field_number => {
                    #wire_check
                    view.#field_ident = Some(#view_enum::#variant(#value));
                }
            })
        })
        .collect()
}

// ---------------------------------------------------------------------------
// to_owned_message field initialisers
// ---------------------------------------------------------------------------

fn build_to_owned_fields(
    scope: MessageScope<'_>,
    msg: &DescriptorProto,
    view_oneof_prefix: &TokenStream,
    owned_oneof_prefix: &TokenStream,
    oneof_idents: &std::collections::HashMap<usize, proc_macro2::Ident>,
) -> Result<Vec<TokenStream>, CodeGenError> {
    let MessageScope { ctx, features, .. } = scope;
    let preserve_unknown_fields = ctx.config.preserve_unknown_fields;
    let mut out = Vec::new();

    for field in &msg.field {
        // Real oneof members are handled below per-group.
        if is_real_oneof_member(field) {
            continue;
        }
        let name = field
            .name
            .as_deref()
            .ok_or(CodeGenError::MissingField("field.name"))?;
        let ident = make_field_ident(name);
        let is_repeated = field.label.unwrap_or_default() == Label::LABEL_REPEATED;
        if is_repeated && is_map_field(msg, field) {
            let expr = map_to_owned_expr(scope, msg, field, &ident)?;
            out.push(quote! { #ident: #expr, });
            continue;
        }
        let ty = effective_type(ctx, field, features);
        let init = if is_repeated {
            repeated_to_owned(scope, ty, &ident, name)
        } else {
            singular_to_owned(scope, field, ty, &ident, name)?
        };
        out.push(quote! { #ident: #init, });
    }

    // Oneof groups.
    for (idx, oneof) in msg.oneof_decl.iter().enumerate() {
        let base_ident = match oneof_idents.get(&idx) {
            Some(id) => id,
            None => continue,
        };
        let oneof_name = oneof
            .name
            .as_deref()
            .ok_or(CodeGenError::MissingField("oneof.name"))?;
        let group: Vec<_> = msg
            .field
            .iter()
            .filter(|f| is_real_oneof_member(f) && f.oneof_index == Some(idx as i32))
            .collect();
        if group.is_empty() {
            continue;
        }
        let field_ident = make_field_ident(oneof_name);
        let view_enum: TokenStream = quote! { #view_oneof_prefix #base_ident };
        let owned_enum: TokenStream = quote! { #owned_oneof_prefix #base_ident };

        let match_arms = group
            .iter()
            .map(|f| {
                let fname = f
                    .name
                    .as_deref()
                    .ok_or(CodeGenError::MissingField("field.name"))?;
                let variant = crate::oneof::oneof_variant_ident(fname);
                let ty = effective_type(ctx, f, features);
                let conv = oneof_variant_to_owned(scope, ty, oneof_name, fname);
                Ok(quote! {
                    #view_enum::#variant(v) => #owned_enum::#variant(#conv),
                })
            })
            .collect::<Result<Vec<_>, CodeGenError>>()?;

        out.push(quote! {
            #field_ident: self.#field_ident.as_ref().map(|v| match v { #(#match_arms)* }),
        });
    }

    // Emit `unknown_fields` conversion so round-trip via decode_view +
    // to_owned_message preserves unknown fields. `.into()` is a no-op when
    // the owned field is `UnknownFields`; when generate_json is on it wraps
    // in the per-message `__<Name>ExtJson` newtype (which has `From<UnknownFields>`).
    if preserve_unknown_fields {
        out.push(quote! {
            __buffa_unknown_fields: self
                .__buffa_unknown_fields
                .to_owned()
                .unwrap_or_default()
                .into(),
        });
    }

    Ok(out)
}

/// Convert a string view binding to the owned `string`-field type.
///
/// The default `String` keeps the original `binding.to_string()` (which
/// auto-derefs through a `&&str` binding), so default output is byte-identical
/// to before this knob existed. Other representations build via `From<&str>`
/// with the owned field type driving `Into` inference; `Into::into` takes its
/// argument by value and does not auto-deref, so `double_ref` sites (iterator
/// and match-ergonomics bindings that are `&&str`) get one explicit `*`.
fn str_view_to_owned(
    repr: crate::StringRepr,
    binding: TokenStream,
    double_ref: bool,
) -> TokenStream {
    if repr.is_default() {
        quote! { #binding.to_string() }
    } else if double_ref {
        quote! { ::core::convert::Into::into(*#binding) }
    } else {
        quote! { ::core::convert::Into::into(#binding) }
    }
}

fn singular_to_owned(
    scope: MessageScope<'_>,
    field: &FieldDescriptorProto,
    ty: Type,
    ident: &proc_macro2::Ident,
    field_name: &str,
) -> Result<TokenStream, CodeGenError> {
    let MessageScope {
        ctx,
        proto_fqn,
        features,
        ..
    } = scope;
    if is_explicit_presence_scalar(field, ty, features) {
        return Ok(match ty {
            Type::TYPE_STRING => {
                // Option<&str>::map. The default keeps `|s| s.to_string()`; for
                // other reprs pass the `Into::into` fn directly rather than
                // wrapping it in a closure (avoids clippy::redundant_closure in
                // the consumer crate). Inference picks the target from the field.
                if field_string_repr(ctx, proto_fqn, field_name).is_default() {
                    quote! { self.#ident.map(|s| s.to_string()) }
                } else {
                    quote! { self.#ident.map(::core::convert::Into::into) }
                }
            }
            Type::TYPE_BYTES => {
                let conv = bytes_to_owned(ctx, proto_fqn, field_name, quote! { b });
                quote! { self.#ident.map(|b| #conv) }
            }
            _ => quote! { self.#ident },
        });
    }
    Ok(match ty {
        Type::TYPE_STRING => str_view_to_owned(
            field_string_repr(ctx, proto_fqn, field_name),
            quote! { self.#ident },
            false,
        ),
        Type::TYPE_BYTES => bytes_to_owned(ctx, proto_fqn, field_name, quote! { self.#ident }),
        Type::TYPE_MESSAGE | Type::TYPE_GROUP => {
            let owned_path = resolve_owned_path(scope, field)?;
            // Use rust_path_to_tokens, not syn::parse_str: the latter chokes
            // on keyword segments like `super::super::type::LatLng`.
            let owned_ty = crate::message::rust_path_to_tokens(&owned_path);
            quote! {
                match self.#ident.as_option() {
                    Some(v) => ::buffa::MessageField::<#owned_ty>::some(
                        v.to_owned_from_source(__buffa_src),
                    ),
                    None => ::buffa::MessageField::none(),
                }
            }
        }
        _ => quote! { self.#ident },
    })
}

fn repeated_to_owned(
    scope: MessageScope<'_>,
    ty: Type,
    ident: &proc_macro2::Ident,
    field_name: &str,
) -> TokenStream {
    let MessageScope { ctx, proto_fqn, .. } = scope;
    match ty {
        Type::TYPE_STRING => {
            // RepeatedView<&str>::iter() yields `&&str` (double ref).
            let conv = str_view_to_owned(
                field_string_repr(ctx, proto_fqn, field_name),
                quote! { s },
                true,
            );
            quote! { self.#ident.iter().map(|s| #conv).collect() }
        }
        Type::TYPE_BYTES => {
            // Vec<&[u8]>::iter() → b: &&[u8]. bytes_to_owned handles double-ref.
            let conv = bytes_to_owned(ctx, proto_fqn, field_name, quote! { b });
            quote! { self.#ident.iter().map(|b| #conv).collect() }
        }
        Type::TYPE_MESSAGE | Type::TYPE_GROUP => {
            quote! { self.#ident.iter().map(|v| v.to_owned_from_source(__buffa_src)).collect() }
        }
        _ => quote! { self.#ident.to_vec() },
    }
}

fn map_to_owned_expr(
    scope: MessageScope<'_>,
    msg: &DescriptorProto,
    field: &FieldDescriptorProto,
    ident: &proc_macro2::Ident,
) -> Result<TokenStream, CodeGenError> {
    let MessageScope {
        ctx,
        proto_fqn,
        features,
        ..
    } = scope;
    let (key_fd, val_fd) = find_map_entry_fields(msg, field)?;
    let field_name = field
        .name
        .as_deref()
        .ok_or(CodeGenError::MissingField("field.name"))?;
    let key_ty = effective_type_in_map_entry(ctx, key_fd, features);
    let val_ty = effective_type_in_map_entry(ctx, val_fd, features);

    let key_conv = match key_ty {
        Type::TYPE_STRING => quote! { k.to_string() },
        // utf8_validation = NONE on a string map key: &[u8] → Vec<u8>.
        Type::TYPE_BYTES => quote! { k.to_vec() },
        _ => quote! { *k },
    };

    // `bytes_fields` on the outer map field promotes `bytes` values to `Bytes`,
    // matching the owned-side map type (shared carve-out in `map_value_use_bytes`).
    // When it holds, emit `bytes_from_source` directly: the predicate already
    // implies `field_uses_bytes`, so routing through `bytes_to_owned` (which
    // re-checks it) would be redundant.
    let value_use_bytes =
        map_value_use_bytes(ctx, Some(key_ty), Some(val_ty), proto_fqn, field_name);
    let val_conv = match val_ty {
        Type::TYPE_STRING => quote! { v.to_string() },
        Type::TYPE_BYTES if value_use_bytes => {
            quote! { ::buffa::view::bytes_from_source(__buffa_src, v) }
        }
        Type::TYPE_BYTES => quote! { v.to_vec() },
        Type::TYPE_MESSAGE => {
            // Verify the owned path resolves (catches missing imports at codegen time).
            let _owned_path = resolve_owned_path(scope, val_fd)?;
            quote! { v.to_owned_from_source(__buffa_src) }
        }
        _ => quote! { *v },
    };

    Ok(quote! {
        self.#ident.iter().map(|(k, v)| (#key_conv, #val_conv)).collect()
    })
}

fn oneof_variant_to_owned(
    scope: MessageScope<'_>,
    ty: Type,
    oneof_name: &str,
    field_name: &str,
) -> TokenStream {
    let MessageScope { ctx, proto_fqn, .. } = scope;
    match ty {
        Type::TYPE_STRING => {
            // Match ergonomics on `&ViewEnum` binds `v` as `&&str` (double ref).
            str_view_to_owned(
                field_string_repr(ctx, proto_fqn, field_name),
                quote! { v },
                true,
            )
        }
        // match-ergonomics on &ViewEnum → v: &&[u8]. bytes_to_owned handles it.
        Type::TYPE_BYTES => bytes_to_owned(ctx, proto_fqn, field_name, quote! { v }),
        Type::TYPE_MESSAGE | Type::TYPE_GROUP => {
            // The owned variant is boxed unless opted out; `v` derefs through
            // the view's own `Box` either way, so only the wrapper differs.
            let owned = quote! { v.to_owned_from_source(__buffa_src) };
            if crate::oneof::variant_boxed(
                ctx,
                ty,
                &format!(".{proto_fqn}.{oneof_name}.{field_name}"),
            ) {
                quote! { ::buffa::alloc::boxed::Box::new(#owned) }
            } else {
                owned
            }
        }
        _ => quote! { *v },
    }
}

// ---------------------------------------------------------------------------
// Serialize impl generation
// ---------------------------------------------------------------------------

/// Emit `impl serde::Serialize for FooView<'_>` when `generate_json` is true.
fn generate_view_serialize(
    scope: MessageScope<'_>,
    msg: &DescriptorProto,
    view_ident: &proc_macro2::Ident,
    view_oneof_prefix: &TokenStream,
    oneof_idents: &std::collections::HashMap<usize, proc_macro2::Ident>,
) -> Result<TokenStream, CodeGenError> {
    let mut stmts: Vec<TokenStream> = Vec::new();

    for field in &msg.field {
        if is_real_oneof_member(field) {
            continue;
        }
        if !is_supported_field_type(field.r#type.unwrap_or_default()) {
            continue;
        }
        stmts.push(view_field_serialize_stmt(scope, msg, field)?);
    }

    for (idx, oneof) in msg.oneof_decl.iter().enumerate() {
        let base_ident = match oneof_idents.get(&idx) {
            Some(id) => id,
            None => continue,
        };
        let oneof_name = oneof
            .name
            .as_deref()
            .ok_or(CodeGenError::MissingField("oneof.name"))?;
        let field_ident = make_field_ident(oneof_name);
        let view_enum = quote! { #view_oneof_prefix #base_ident };
        let fields: Vec<_> = msg
            .field
            .iter()
            .filter(|f| is_real_oneof_member(f) && f.oneof_index == Some(idx as i32))
            .collect();
        if fields.is_empty() {
            continue;
        }
        let arms = fields
            .iter()
            .map(|f| view_oneof_serialize_arm(scope, f, &view_enum))
            .collect::<Result<Vec<_>, _>>()?;
        stmts.push(quote! {
            if let ::core::option::Option::Some(ref __ov) = self.#field_ident {
                match __ov { #(#arms)* }
            }
        });
    }

    Ok(quote! {
        /// Serializes this view as protobuf JSON.
        ///
        /// Implicit-presence fields with default values are omitted, `required`
        /// fields are always emitted, explicit-presence (`optional`) fields are
        /// emitted only when set, bytes fields are base64-encoded, and enum
        /// values are their proto name strings.
        ///
        /// This impl uses `serialize_map(None)` because the number of emitted
        /// fields depends on default-omission rules; serializers that require
        /// known map lengths (e.g. `bincode`) will return a runtime error.
        /// Use the owned message type for those formats.
        impl<'__a> ::serde::Serialize for #view_ident<'__a> {
            fn serialize<__S: ::serde::Serializer>(
                &self,
                __s: __S,
            ) -> ::core::result::Result<__S::Ok, __S::Error> {
                use ::serde::ser::SerializeMap as _;
                let mut __map = __s.serialize_map(::core::option::Option::None)?;
                #(#stmts)*
                __map.end()
            }
        }
    })
}

/// Generate a single serialize statement for one direct (non-oneof) view field.
fn view_field_serialize_stmt(
    scope: MessageScope<'_>,
    msg: &DescriptorProto,
    field: &FieldDescriptorProto,
) -> Result<TokenStream, CodeGenError> {
    let MessageScope {
        ctx,
        features: parent_features,
        ..
    } = scope;
    let f_features = crate::features::resolve_field(ctx, field, parent_features);

    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 ident = make_field_ident(field_name);
    let label = field.label.unwrap_or_default();
    let is_repeated = label == Label::LABEL_REPEATED;
    let is_required = is_required_field(field, parent_features);
    let ty = effective_type(ctx, field, parent_features);

    // ── Map field ─────────────────────────────────────────────────────────────
    if is_repeated && is_map_field(msg, field) {
        let (key_fd, val_fd) = find_map_entry_fields(msg, field)?;
        let key_raw = effective_type_in_map_entry(ctx, key_fd, parent_features);
        let val_raw = effective_type_in_map_entry(ctx, val_fd, parent_features);
        let val_f = crate::features::resolve_field(ctx, val_fd, parent_features);

        let key_ty = match key_raw {
            Type::TYPE_STRING => quote! { &'__a str },
            Type::TYPE_BYTES => quote! { &'__a [u8] },
            kt => scalar_ty(kt),
        };
        let val_ty = match val_raw {
            Type::TYPE_STRING => quote! { &'__a str },
            Type::TYPE_BYTES => quote! { &'__a [u8] },
            Type::TYPE_MESSAGE => {
                let path = resolve_view_path(scope, val_fd)?;
                quote! { #path <'__a> }
            }
            Type::TYPE_ENUM => {
                let et = resolve_enum_ty(scope, val_fd)?;
                if is_closed_enum(&val_f) {
                    quote! { #et }
                } else {
                    quote! { ::buffa::EnumValue<#et> }
                }
            }
            vt => scalar_ty(vt),
        };

        // Key wrapper struct. Protobuf JSON requires map keys to be encoded
        // as JSON strings regardless of the key's proto type:
        // - String keys are already strings — passed through unwrapped.
        // - Bytes keys (which only arise when `utf8_validation = NONE` rewrites
        //   a `string` key to `&[u8]` in the view) are base64-encoded, mirroring
        //   the owned-side `bytes_key_*_map` helpers' `Base64Wrapper`.
        // - All other scalar keys (int32/64, uint32/64, bool — the only other
        //   key types proto allows) are stringified via `collect_str`, mirroring
        //   the owned-side `proto_map::serialize` `DisplayKey` wrapper.
        // The explicit wrappers make the view encoding byte-identical to the
        // owned encoding for any serde backend, not just `serde_json` (whose
        // `MapKeySerializer` happens to stringify primitives on its own).
        let (key_wrapper, key_expr) = match key_raw {
            Type::TYPE_STRING => (quote! {}, quote! { k }),
            Type::TYPE_BYTES => (
                quote! {
                    struct _WK<'__x>(&'__x [u8]);
                    impl ::serde::Serialize for _WK<'_> {
                        fn serialize<__S: ::serde::Serializer>(&self, __s: __S) -> ::core::result::Result<__S::Ok, __S::Error> {
                            ::buffa::json_helpers::bytes::serialize(self.0, __s)
                        }
                    }
                },
                quote! { &_WK(k) },
            ),
            _ => (
                quote! {
                    struct _WK(#key_ty);
                    impl ::serde::Serialize for _WK {
                        fn serialize<__S: ::serde::Serializer>(&self, __s: __S) -> ::core::result::Result<__S::Ok, __S::Error> {
                            __s.collect_str(&self.0)
                        }
                    }
                },
                // k: &K (Copy scalar) — explicit deref into the wrapper field.
                quote! { &_WK(*k) },
            ),
        };

        // Value wrapper struct (for types needing special encoding).
        let (val_wrapper, val_expr) = match val_raw {
            Type::TYPE_BYTES => (
                quote! {
                    struct _WV<'__x>(&'__x [u8]);
                    impl ::serde::Serialize for _WV<'_> {
                        fn serialize<__S: ::serde::Serializer>(&self, __s: __S) -> ::core::result::Result<__S::Ok, __S::Error> {
                            ::buffa::json_helpers::bytes::serialize(self.0, __s)
                        }
                    }
                },
                // v: &&[u8] — deref coercion from &&[u8] to &[u8] at _WV struct init.
                quote! { &_WV(v) },
            ),
            Type::TYPE_ENUM if is_closed_enum(&val_f) => {
                let et = resolve_enum_ty(scope, val_fd)?;
                (
                    quote! {
                        struct _WV(#et);
                        impl ::serde::Serialize for _WV {
                            fn serialize<__S: ::serde::Serializer>(&self, __s: __S) -> ::core::result::Result<__S::Ok, __S::Error> {
                                ::buffa::json_helpers::closed_enum::serialize(&self.0, __s)
                            }
                        }
                    },
                    // v: &E (Copy) — explicit deref needed for scalar struct field.
                    quote! { &_WV(*v) },
                )
            }
            vt if serde_helper_path(vt).is_some() => {
                let helper = serde_helper_path(vt).unwrap();
                (
                    quote! {
                        struct _WV(#val_ty);
                        impl ::serde::Serialize for _WV {
                            fn serialize<__S: ::serde::Serializer>(&self, __s: __S) -> ::core::result::Result<__S::Ok, __S::Error> {
                                #helper::serialize(&self.0, __s)
                            }
                        }
                    },
                    // v: &scalar — explicit deref needed for scalar struct field.
                    quote! { &_WV(*v) },
                )
            }
            _ => (quote! {}, quote! { v }),
        };

        // Include '__a only when key/val types actually reference the view lifetime.
        let key_uses_a = matches!(key_raw, Type::TYPE_STRING | Type::TYPE_BYTES);
        let val_uses_a = matches!(
            val_raw,
            Type::TYPE_STRING | Type::TYPE_BYTES | Type::TYPE_MESSAGE
        );
        let (wm_struct_decl, wm_impl_hdr, wm_impl_ty) = if key_uses_a || val_uses_a {
            (
                quote! { struct _WM<'__a, '__x>(&'__x ::buffa::MapView<'__x, #key_ty, #val_ty>); },
                quote! { impl<'__a> },
                quote! { _WM<'__a, '_> },
            )
        } else {
            (
                quote! { struct _WM<'__x>(&'__x ::buffa::MapView<'__x, #key_ty, #val_ty>); },
                quote! { impl },
                quote! { _WM<'_> },
            )
        };
        return Ok(quote! {
            if !self.#ident.is_empty() {
                #wm_struct_decl
                #wm_impl_hdr ::serde::Serialize for #wm_impl_ty {
                    fn serialize<__S: ::serde::Serializer>(&self, __s: __S) -> ::core::result::Result<__S::Ok, __S::Error> {
                        use ::serde::ser::SerializeMap as _;
                        #key_wrapper
                        #val_wrapper
                        // `iter_unique` deduplicates wire-level duplicate keys
                        // (last-write-wins), matching the owned `HashMap`
                        // decode semantics and producing valid JSON.
                        // `len()` (not `len_unique()`) is used for the size
                        // hint: it is exact for well-formed wire data, an
                        // upper bound for adversarial duplicates, and avoids
                        // a second O(n²) dedup pass on every serialize.
                        let mut __m = __s.serialize_map(::core::option::Option::Some(self.0.len()))?;
                        for (k, v) in self.0.iter_unique() {
                            __m.serialize_entry(#key_expr, #val_expr)?;
                        }
                        __m.end()
                    }
                }
                __map.serialize_entry(#json_name, &_WM(&self.#ident))?;
            }
        });
    }

    // ── Repeated field ────────────────────────────────────────────────────────
    if is_repeated {
        let seq_wrapper = match ty {
            Type::TYPE_BYTES => quote! {
                struct _WSeq<'__x>(&'__x [&'__x [u8]]);
                impl ::serde::Serialize for _WSeq<'_> {
                    fn serialize<__S: ::serde::Serializer>(&self, __s: __S) -> ::core::result::Result<__S::Ok, __S::Error> {
                        use ::serde::ser::SerializeSeq as _;
                        let mut __seq = __s.serialize_seq(::core::option::Option::Some(self.0.len()))?;
                        for v in self.0 {
                            struct _WE<'__x>(&'__x [u8]);
                            impl ::serde::Serialize for _WE<'_> {
                                fn serialize<__S: ::serde::Serializer>(&self, __s: __S) -> ::core::result::Result<__S::Ok, __S::Error> {
                                    ::buffa::json_helpers::bytes::serialize(self.0, __s)
                                }
                            }
                            __seq.serialize_element(&_WE(v))?;
                        }
                        __seq.end()
                    }
                }
            },
            Type::TYPE_ENUM if is_closed_enum(&f_features) => {
                let et = resolve_enum_ty(scope, field)?;
                quote! {
                    struct _WSeq<'__x>(&'__x [#et]);
                    impl ::serde::Serialize for _WSeq<'_> {
                        fn serialize<__S: ::serde::Serializer>(&self, __s: __S) -> ::core::result::Result<__S::Ok, __S::Error> {
                            ::buffa::json_helpers::repeated_closed_enum::serialize(self.0, __s)
                        }
                    }
                }
            }
            Type::TYPE_ENUM => {
                let et = resolve_enum_ty(scope, field)?;
                quote! {
                    struct _WSeq<'__x>(&'__x [::buffa::EnumValue<#et>]);
                    impl ::serde::Serialize for _WSeq<'_> {
                        fn serialize<__S: ::serde::Serializer>(&self, __s: __S) -> ::core::result::Result<__S::Ok, __S::Error> {
                            ::buffa::json_helpers::repeated_enum::serialize(self.0, __s)
                        }
                    }
                }
            }
            scalar_ty_val if serde_helper_path(scalar_ty_val).is_some() => {
                let elem_ty = scalar_ty(scalar_ty_val);
                quote! {
                    struct _WSeq<'__x>(&'__x [#elem_ty]);
                    impl ::serde::Serialize for _WSeq<'_> {
                        fn serialize<__S: ::serde::Serializer>(&self, __s: __S) -> ::core::result::Result<__S::Ok, __S::Error> {
                            ::buffa::json_helpers::proto_seq::serialize(self.0, __s)
                        }
                    }
                }
            }
            _ => quote! {},
        };

        let seq_val = if seq_wrapper.is_empty() {
            // Explicit deref: RepeatedView doesn't impl Serialize, but &[T] does.
            quote! { &*self.#ident }
        } else {
            // Deref coercion from &RepeatedView<'a,T> to &[T] at struct-init site.
            quote! { &_WSeq(&self.#ident) }
        };

        return Ok(quote! {
            if !self.#ident.is_empty() {
                #seq_wrapper
                __map.serialize_entry(#json_name, #seq_val)?;
            }
        });
    }

    // ── Explicit-presence (proto3 optional) scalar ────────────────────────────
    if is_explicit_presence_scalar(field, ty, &f_features) {
        // opt_* helpers from json_helpers take &Option<owned_T>, not &Option<view_T>.
        // Handle each case inline so the view's Option<&str>/Option<&[u8]> work.
        let entry = match ty {
            Type::TYPE_STRING => quote! {
                if let ::core::option::Option::Some(__v) = self.#ident {
                    __map.serialize_entry(#json_name, __v)?;
                }
            },
            Type::TYPE_BYTES => quote! {
                if let ::core::option::Option::Some(__v) = self.#ident {
                    struct _W<'__x>(&'__x [u8]);
                    impl ::serde::Serialize for _W<'_> {
                        fn serialize<__S: ::serde::Serializer>(&self, __s: __S) -> ::core::result::Result<__S::Ok, __S::Error> {
                            ::buffa::json_helpers::bytes::serialize(self.0, __s)
                        }
                    }
                    __map.serialize_entry(#json_name, &_W(__v))?;
                }
            },
            Type::TYPE_ENUM if is_closed_enum(&f_features) => {
                let et = resolve_enum_ty(scope, field)?;
                quote! {
                    if let ::core::option::Option::Some(__v) = self.#ident {
                        struct _W(#et);
                        impl ::serde::Serialize for _W {
                            fn serialize<__S: ::serde::Serializer>(&self, __s: __S) -> ::core::result::Result<__S::Ok, __S::Error> {
                                ::buffa::json_helpers::closed_enum::serialize(&self.0, __s)
                            }
                        }
                        __map.serialize_entry(#json_name, &_W(__v))?;
                    }
                }
            }
            Type::TYPE_ENUM => quote! {
                if let ::core::option::Option::Some(ref __v) = self.#ident {
                    __map.serialize_entry(#json_name, __v)?;
                }
            },
            scalar if serde_helper_path(scalar).is_some() => {
                let helper = serde_helper_path(scalar).unwrap();
                let elem_ty = scalar_ty(scalar);
                quote! {
                    if let ::core::option::Option::Some(__v) = self.#ident {
                        struct _W(#elem_ty);
                        impl ::serde::Serialize for _W {
                            fn serialize<__S: ::serde::Serializer>(&self, __s: __S) -> ::core::result::Result<__S::Ok, __S::Error> {
                                #helper::serialize(&self.0, __s)
                            }
                        }
                        __map.serialize_entry(#json_name, &_W(__v))?;
                    }
                }
            }
            _ => quote! {
                if let ::core::option::Option::Some(__v) = self.#ident {
                    __map.serialize_entry(#json_name, &__v)?;
                }
            },
        };
        return Ok(entry);
    }

    // ── Singular fields ───────────────────────────────────────────────────────
    let (skip_cond, serialize_stmt) = match ty {
        Type::TYPE_STRING => (
            quote! { !::buffa::json_helpers::skip_if::is_empty_str(self.#ident) },
            quote! { __map.serialize_entry(#json_name, self.#ident)?; },
        ),
        Type::TYPE_BYTES => (
            quote! { !::buffa::json_helpers::skip_if::is_empty_bytes(self.#ident) },
            quote! {
                struct _W<'__x>(&'__x [u8]);
                impl ::serde::Serialize for _W<'_> {
                    fn serialize<__S: ::serde::Serializer>(&self, __s: __S) -> ::core::result::Result<__S::Ok, __S::Error> {
                        ::buffa::json_helpers::bytes::serialize(self.0, __s)
                    }
                }
                __map.serialize_entry(#json_name, &_W(self.#ident))?;
            },
        ),
        Type::TYPE_MESSAGE | Type::TYPE_GROUP => (
            quote! { self.#ident.is_set() },
            quote! {
                if let ::core::option::Option::Some(__v) = self.#ident.as_option() {
                    __map.serialize_entry(#json_name, __v)?;
                }
            },
        ),
        Type::TYPE_ENUM if is_closed_enum(&f_features) => {
            let et = resolve_enum_ty(scope, field)?;
            let skip_fn = quote! { ::buffa::json_helpers::skip_if::is_default_closed_enum };
            (
                quote! { !#skip_fn(&self.#ident) },
                quote! {
                    struct _W(#et);
                    impl ::serde::Serialize for _W {
                        fn serialize<__S: ::serde::Serializer>(&self, __s: __S) -> ::core::result::Result<__S::Ok, __S::Error> {
                            ::buffa::json_helpers::closed_enum::serialize(&self.0, __s)
                        }
                    }
                    __map.serialize_entry(#json_name, &_W(self.#ident))?;
                },
            )
        }
        Type::TYPE_ENUM => (
            quote! { !::buffa::json_helpers::skip_if::is_default_enum_value(&self.#ident) },
            quote! { __map.serialize_entry(#json_name, &self.#ident)?; },
        ),
        scalar if serde_helper_path(scalar).is_some() => {
            let helper = serde_helper_path(scalar).unwrap();
            let skip_path = scalar_skip_predicate(scalar);
            let elem_ty = scalar_ty(scalar);
            (
                quote! { !#skip_path(&self.#ident) },
                quote! {
                    struct _W(#elem_ty);
                    impl ::serde::Serialize for _W {
                        fn serialize<__S: ::serde::Serializer>(&self, __s: __S) -> ::core::result::Result<__S::Ok, __S::Error> {
                            #helper::serialize(&self.0, __s)
                        }
                    }
                    __map.serialize_entry(#json_name, &_W(self.#ident))?;
                },
            )
        }
        Type::TYPE_BOOL => (
            quote! { self.#ident },
            quote! { __map.serialize_entry(#json_name, &self.#ident)?; },
        ),
        _ => (
            quote! { self.#ident != ::core::default::Default::default() },
            quote! { __map.serialize_entry(#json_name, &self.#ident)?; },
        ),
    };

    // Message fields handle skip internally via the if-let. Required fields
    // are always serialized. Both are wrapped in a block so that any local
    // `struct _W` declarations inside `serialize_stmt` do not collide when
    // multiple such fields appear in the same message.
    if matches!(ty, Type::TYPE_MESSAGE | Type::TYPE_GROUP) || is_required {
        return Ok(quote! { { #serialize_stmt } });
    }

    Ok(quote! {
        if #skip_cond {
            #serialize_stmt
        }
    })
}

/// Return the `skip_if` predicate path string for a scalar type that has a helper.
fn scalar_skip_predicate(ty: Type) -> TokenStream {
    match ty {
        Type::TYPE_BOOL => quote! { ::buffa::json_helpers::skip_if::is_false },
        Type::TYPE_INT32 | Type::TYPE_SINT32 | Type::TYPE_SFIXED32 => {
            quote! { ::buffa::json_helpers::skip_if::is_zero_i32 }
        }
        Type::TYPE_UINT32 | Type::TYPE_FIXED32 => {
            quote! { ::buffa::json_helpers::skip_if::is_zero_u32 }
        }
        Type::TYPE_INT64 | Type::TYPE_SINT64 | Type::TYPE_SFIXED64 => {
            quote! { ::buffa::json_helpers::skip_if::is_zero_i64 }
        }
        Type::TYPE_UINT64 | Type::TYPE_FIXED64 => {
            quote! { ::buffa::json_helpers::skip_if::is_zero_u64 }
        }
        Type::TYPE_FLOAT => quote! { ::buffa::json_helpers::skip_if::is_zero_f32 },
        Type::TYPE_DOUBLE => quote! { ::buffa::json_helpers::skip_if::is_zero_f64 },
        // The single call site is gated by `serde_helper_path(ty).is_some()`,
        // which only matches the scalar types above. Bytes is handled in an
        // earlier match arm.
        Type::TYPE_STRING
        | Type::TYPE_BYTES
        | Type::TYPE_ENUM
        | Type::TYPE_MESSAGE
        | Type::TYPE_GROUP => {
            unreachable!("scalar_skip_predicate called for non-scalar {:?}", ty)
        }
    }
}

/// Generate a single `match` arm for one oneof variant in the inlined oneof serialization.
///
/// The arm is used inside:
/// ```text
/// if let Some(ref __ov) = self.field { match __ov { <arm>, ... } }
/// ```
fn view_oneof_serialize_arm(
    scope: MessageScope<'_>,
    field: &FieldDescriptorProto,
    view_enum: &TokenStream,
) -> Result<TokenStream, CodeGenError> {
    let MessageScope { ctx, features, .. } = scope;
    let f_features = crate::features::resolve_field(ctx, field, features);

    let name = field
        .name
        .as_deref()
        .ok_or(CodeGenError::MissingField("field.name"))?;
    let json_name = field.json_name.as_deref().unwrap_or(name);
    let variant = crate::oneof::oneof_variant_ident(name);
    let ty = effective_type(ctx, field, features);

    // NullValue must serialize as JSON `null`, not "NULL_VALUE".
    if is_null_value_field(field) {
        return Ok(quote! {
            #view_enum::#variant(_) => {
                __map.serialize_entry(#json_name, &())?;
            }
        });
    }

    // Pattern match on &ViewEnum gives v: &inner_type (with match ergonomics).
    let arm_body = match ty {
        Type::TYPE_STRING => {
            // v: &&str — deref coercion from &&str to &str at the serialize_entry call.
            quote! { __map.serialize_entry(#json_name, v)?; }
        }
        Type::TYPE_BYTES => {
            // v: &&[u8] — deref coercion from &&[u8] to &[u8] in _W constructor.
            quote! {
                struct _W<'__x>(&'__x [u8]);
                impl ::serde::Serialize for _W<'_> {
                    fn serialize<__S: ::serde::Serializer>(&self, __s: __S) -> ::core::result::Result<__S::Ok, __S::Error> {
                        ::buffa::json_helpers::bytes::serialize(self.0, __s)
                    }
                }
                __map.serialize_entry(#json_name, &_W(v))?;
            }
        }
        Type::TYPE_MESSAGE | Type::TYPE_GROUP => {
            // v: &Box<FooView> → Box<FooView>: Serialize when FooView: Serialize.
            quote! { __map.serialize_entry(#json_name, v)?; }
        }
        Type::TYPE_ENUM if is_closed_enum(&f_features) => {
            let et = resolve_enum_ty(scope, field)?;
            quote! {
                struct _W(#et);
                impl ::serde::Serialize for _W {
                    fn serialize<__S: ::serde::Serializer>(&self, __s: __S) -> ::core::result::Result<__S::Ok, __S::Error> {
                        ::buffa::json_helpers::closed_enum::serialize(&self.0, __s)
                    }
                }
                __map.serialize_entry(#json_name, &_W(*v))?;
            }
        }
        Type::TYPE_ENUM => {
            // v: &EnumValue<E> — has its own Serialize impl.
            quote! { __map.serialize_entry(#json_name, v)?; }
        }
        scalar if serde_helper_path(scalar).is_some() => {
            let helper = serde_helper_path(scalar).unwrap();
            let sty = scalar_ty(scalar);
            // v: &scalar_type → copy and wrap.
            quote! {
                struct _W(#sty);
                impl ::serde::Serialize for _W {
                    fn serialize<__S: ::serde::Serializer>(&self, __s: __S) -> ::core::result::Result<__S::Ok, __S::Error> {
                        #helper::serialize(&self.0, __s)
                    }
                }
                __map.serialize_entry(#json_name, &_W(*v))?;
            }
        }
        _ => {
            // bool, i32, u32: direct serialize.
            quote! { __map.serialize_entry(#json_name, v)?; }
        }
    };

    Ok(quote! {
        #view_enum::#variant(v) => { #arm_body }
    })
}

// ---------------------------------------------------------------------------
// Shared helpers
// ---------------------------------------------------------------------------

/// Scalar Rust type for view fields (same as owned scalars; no borrowing needed).
fn scalar_ty(ty: Type) -> TokenStream {
    match ty {
        Type::TYPE_DOUBLE => quote! { f64 },
        Type::TYPE_FLOAT => quote! { f32 },
        Type::TYPE_INT64 | Type::TYPE_SINT64 | Type::TYPE_SFIXED64 => quote! { i64 },
        Type::TYPE_UINT64 | Type::TYPE_FIXED64 => quote! { u64 },
        Type::TYPE_INT32 | Type::TYPE_SINT32 | Type::TYPE_SFIXED32 => quote! { i32 },
        Type::TYPE_UINT32 | Type::TYPE_FIXED32 => quote! { u32 },
        Type::TYPE_BOOL => quote! { bool },
        Type::TYPE_STRING
        | Type::TYPE_BYTES
        | Type::TYPE_ENUM
        | Type::TYPE_MESSAGE
        | Type::TYPE_GROUP => unreachable!("scalar_ty called for non-scalar {:?}", ty),
    }
}

/// Resolve the enum Rust type (same as owned — enums are Copy/Clone integers).
fn resolve_enum_ty(
    scope: MessageScope<'_>,
    field: &FieldDescriptorProto,
) -> Result<TokenStream, CodeGenError> {
    let type_name = field
        .type_name
        .as_deref()
        .ok_or(CodeGenError::MissingField("field.type_name"))?;
    let path = scope
        .ctx
        .rust_type_relative(type_name, scope.current_package, scope.nesting)
        .ok_or_else(|| CodeGenError::Other(format!("enum type '{type_name}' not found")))?;
    Ok(rust_path_to_tokens(&path))
}

/// Resolve the view type tokens for a message field
/// (e.g. `".pkg.Address"` → `super^n::__buffa::view::AddressView<'a>`).
///
/// `scope.nesting` must be the **total** depth of the caller below the
/// package root (msg-nesting + kind-depth offset already applied by the
/// caller — `+2` for view-struct bodies, `+4` for view-oneof-enum bodies).
pub(crate) fn resolve_view_ty_tokens(
    scope: MessageScope<'_>,
    field: &FieldDescriptorProto,
    lt: &TokenStream,
) -> Result<TokenStream, CodeGenError> {
    let path = resolve_view_path(scope, field)?;
    Ok(quote! { #path <#lt> })
}

/// Resolve the view type tokens used for `decode_view` calls (no lifetime).
fn resolve_view_decode_tokens(
    scope: MessageScope<'_>,
    field: &FieldDescriptorProto,
) -> Result<TokenStream, CodeGenError> {
    resolve_view_path(scope, field)
}

/// Compute the path to a message field's **view struct** from `scope`.
///
/// Splits the resolved owned-type path at the target-package boundary and
/// inserts `__buffa::view::` between the halves, appending `View` to the
/// final identifier.
fn resolve_view_path(
    scope: MessageScope<'_>,
    field: &FieldDescriptorProto,
) -> Result<TokenStream, CodeGenError> {
    let type_name = field
        .type_name
        .as_deref()
        .ok_or(CodeGenError::MissingField("field.type_name"))?;
    let split = scope
        .ctx
        .rust_type_relative_split(type_name, scope.current_package, scope.nesting)
        .ok_or_else(|| CodeGenError::Other(format!("message type '{type_name}' not found")))?;

    let to_pkg = if split.to_package.is_empty() {
        TokenStream::new()
    } else {
        let p = rust_path_to_tokens(&split.to_package);
        quote! { #p :: }
    };
    let sentinel = make_field_ident(SENTINEL_MOD);
    let (within_prefix, last) = match split.within_package.rsplit_once("::") {
        Some((prefix, last)) => {
            let p = rust_path_to_tokens(prefix);
            (quote! { #p :: }, last.to_string())
        }
        None => (TokenStream::new(), split.within_package.clone()),
    };
    let view_ident = make_field_ident(&format!("{last}View"));
    Ok(quote! { #to_pkg #sentinel :: view :: #within_prefix #view_ident })
}

fn resolve_owned_path(
    scope: MessageScope<'_>,
    field: &FieldDescriptorProto,
) -> Result<String, CodeGenError> {
    let type_name = field
        .type_name
        .as_deref()
        .ok_or(CodeGenError::MissingField("field.type_name"))?;
    scope
        .ctx
        .rust_type_relative(type_name, scope.current_package, scope.nesting)
        .ok_or_else(|| CodeGenError::Other(format!("message type '{type_name}' not found")))
}