buffa-codegen 0.5.0

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
//! 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_uses_bytes, find_map_entry_fields,
    is_explicit_presence_scalar, is_packed_type, is_real_oneof_member, is_supported_field_type,
    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::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 direct_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<_>>();

    // One `Option<Kind<'a>>` per non-synthetic oneof.
    let oneof_struct_fields =
        oneof_view_struct_fields(ctx, msg, &view_oneof_prefix, features, &oneof_idents)?;

    // 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
        }
    };

    // 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);

    let top_level = quote! {
        #view_doc
        #[derive(Clone, Debug, Default)]
        pub struct #view_ident<'a> {
            #(#direct_fields)*
            #(#oneof_struct_fields)*
            #unknown_fields_field
            #phantom_field
        }

        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

        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
            }
        }
    };

    Ok((top_level, mod_items))
}

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

fn view_struct_field(
    scope: MessageScope<'_>,
    msg: &DescriptorProto,
    field: &FieldDescriptorProto,
) -> Result<Option<TokenStream>, 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)?;
        return Ok(Some(quote! {
            #doc
            pub #ident: #map_ty,
        }));
    }

    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)?
    } else {
        view_singular_type(scope, field)?
    };

    // 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
    };

    Ok(Some(quote! {
        #doc
        pub #ident: #struct_ty,
    }))
}

fn view_singular_type(
    scope: MessageScope<'_>,
    field: &FieldDescriptorProto,
) -> 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<&'a str> },
            Type::TYPE_BYTES => quote! { ::core::option::Option<&'a [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! { &'a str }),
        Type::TYPE_BYTES => Ok(quote! { &'a [u8] }),
        Type::TYPE_MESSAGE | Type::TYPE_GROUP => {
            let view_ty = resolve_view_ty_tokens(scope, field)?;
            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)),
    }
}

fn view_repeated_type(
    scope: MessageScope<'_>,
    field: &FieldDescriptorProto,
) -> 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<'a, &'a str> }),
        Type::TYPE_BYTES => Ok(quote! { ::buffa::RepeatedView<'a, &'a [u8]> }),
        Type::TYPE_MESSAGE | Type::TYPE_GROUP => {
            let view_ty = resolve_view_ty_tokens(scope, field)?;
            Ok(quote! { ::buffa::RepeatedView<'a, #view_ty> })
        }
        Type::TYPE_ENUM => {
            let et = resolve_enum_ty(scope, field)?;
            if is_closed_enum(features) {
                Ok(quote! { ::buffa::RepeatedView<'a, #et> })
            } else {
                Ok(quote! { ::buffa::RepeatedView<'a, ::buffa::EnumValue<#et>> })
            }
        }
        _ => {
            let st = scalar_ty(ty);
            Ok(quote! { ::buffa::RepeatedView<'a, #st> })
        }
    }
}

/// Build the `::buffa::MapView<'a, K, V>` type for a map field.
fn view_map_type(
    scope: MessageScope<'_>,
    msg: &DescriptorProto,
    field: &FieldDescriptorProto,
) -> 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! { &'a str },
        // utf8_validation = NONE on a string map key → &'a [u8].
        Type::TYPE_BYTES => quote! { &'a [u8] },
        ty => scalar_ty(ty),
    };

    let val_ty = match effective_type_in_map_entry(ctx, val_fd, features) {
        Type::TYPE_STRING => quote! { &'a str },
        Type::TYPE_BYTES => quote! { &'a [u8] },
        Type::TYPE_MESSAGE => {
            let view_ty = resolve_view_ty_tokens(scope, val_fd)?;
            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<'a, #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.
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>, 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! {}
        };
        out.push(quote! {
            pub #field_ident: ::core::option::Option<#view_oneof_prefix #enum_ident #generics>,
        });
    }
    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! { ::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! {}
    };

    Ok(quote! {
        #[derive(Clone, Debug)]
        pub enum #base_ident #generics {
            #(#variants,)*
        }
    })
}

// ---------------------------------------------------------------------------
// 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)? },
            _ => unreachable!(),
        };
        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)?); }
    };
    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)?;
                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, 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)
}

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 => quote! { self.#ident.map(|s| s.to_string()) },
            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 => quote! { self.#ident.to_string() },
        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,
) -> Result<TokenStream, CodeGenError> {
    let MessageScope { ctx, proto_fqn, .. } = scope;
    Ok(match ty {
        Type::TYPE_STRING => quote! { self.#ident.iter().map(|s| s.to_string()).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, features, .. } = scope;
    let (key_fd, val_fd) = find_map_entry_fields(msg, field)?;

    let key_conv = match effective_type_in_map_entry(ctx, key_fd, features) {
        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 },
    };

    let val_conv = match effective_type_in_map_entry(ctx, val_fd, features) {
        Type::TYPE_STRING => quote! { v.to_string() },
        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, field_name: &str) -> TokenStream {
    let MessageScope { ctx, proto_fqn, .. } = scope;
    match ty {
        Type::TYPE_STRING => quote! { v.to_string() },
        // 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 => {
            quote! { ::buffa::alloc::boxed::Box::new(v.to_owned_from_source(__buffa_src)) }
        }
        _ => quote! { *v },
    }
}

// ---------------------------------------------------------------------------
// 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 },
        _ => 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).
fn resolve_view_ty_tokens(
    scope: MessageScope<'_>,
    field: &FieldDescriptorProto,
) -> Result<TokenStream, CodeGenError> {
    let path = resolve_view_path(scope, field)?;
    Ok(quote! { #path <'a> })
}

/// 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")))
}