prosto_derive 0.11.26

Procedural macros for proto_rs, Rust as a first-class citizen in the protobuf ecosystem
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
use std::collections::BTreeSet;

use proc_macro2::TokenStream as TokenStream2;
use quote::quote;
use syn::DeriveInput;
use syn::Ident;
use syn::ItemEnum;
use syn::Lit;
use syn::parse_quote;
use syn::spanned::Spanned;

use super::build_validate_with_ext_impl;
use super::generic_bounds::add_proto_wire_bounds;
use super::unified_field_handler::FieldAccess;
use super::unified_field_handler::FieldInfo;
use super::unified_field_handler::assign_tags;
use super::unified_field_handler::compute_decode_ty;
use super::unified_field_handler::compute_proto_ty;
use super::unified_field_handler::decode_conversion_assign;
use super::unified_field_handler::encode_conversion_expr;
use super::unified_field_handler::field_proto_default_expr;
use super::unified_field_handler::needs_decode_conversion;
use super::unified_field_handler::needs_encode_conversion;
use super::unified_field_handler::parse_path_string;
use super::unified_field_handler::sanitize_enum;
use crate::parse::UnifiedProtoConfig;
use crate::utils::parse_field_config;
use crate::utils::parse_field_type;
use crate::utils::resolved_field_type;

pub(super) fn generate_complex_enum_impl(
    input: &DeriveInput,
    item_enum: &ItemEnum,
    data: &syn::DataEnum,
    config: &UnifiedProtoConfig,
) -> syn::Result<TokenStream2> {
    let enum_item = sanitize_enum(item_enum.clone());

    let name = &input.ident;
    let generics = &input.generics;

    let default_index = crate::utils::find_marked_default_variant(data)?.unwrap_or(0);
    let mut variants = collect_variant_infos(data, config)?;
    if variants.is_empty() {
        return Err(syn::Error::new(
            input.ident.span(),
            "proto_message enum must contain at least one variant",
        ));
    }
    if default_index >= variants.len() {
        return Err(syn::Error::new(input.ident.span(), "#[default] variant index is out of bounds"));
    }
    variants[default_index].is_default = true;

    let bound_fields = collect_variant_fields(&variants);
    let bounded_generics = add_proto_wire_bounds(generics, bound_fields);
    let (impl_generics, ty_generics, where_clause) = bounded_generics.split_for_impl();

    let merge_field_arms = variants.iter().map(|variant| build_variant_merge_arm(name, variant)).collect::<Vec<_>>();
    let default_expr = build_variant_default_expr(&variants[default_index], name);
    let is_default_arms = variants.iter().map(|variant| build_variant_is_default_arm(variant, name)).collect::<Vec<_>>();
    let encode_arms = variants.iter().map(|variant| build_variant_encode_arm(variant, name)).collect::<Vec<_>>();
    let field_validation_arms = build_variant_field_validation_arms(name, &variants);
    let has_field_validation = !field_validation_arms.is_empty();
    let field_validation = if field_validation_arms.is_empty() {
        quote! {}
    } else {
        quote! {
            match &mut shadow {
                #(#field_validation_arms,)*
                _ => {}
            }
        }
    };
    let merge_field_validation_arms = build_variant_field_validation_arms(name, &variants);
    let merge_field_validation = if merge_field_validation_arms.is_empty() {
        quote! {}
    } else {
        quote! {
            match self {
                #(#merge_field_validation_arms,)*
                _ => {}
            }
        }
    };
    let decode_field_validation_arms = build_variant_field_validation_arms(name, &variants);
    let decode_field_validation = if decode_field_validation_arms.is_empty() {
        quote! {}
    } else {
        quote! {
            match &mut value {
                #(#decode_field_validation_arms,)*
                _ => {}
            }
        }
    };

    let validate_with_ext_impl = build_validate_with_ext_impl(config);
    let validate_with_ext_proto_impl = if config.has_suns() {
        TokenStream2::new()
    } else {
        validate_with_ext_impl.clone()
    };
    let message_validation = if let Some(validator_fn) = &config.validator {
        let validator_path: syn::Path = syn::parse_str(validator_fn).expect("invalid validator function path");
        quote! {
            #validator_path(&mut shadow)?;
        }
    } else {
        quote! {}
    };
    let merge_message_validation = if let Some(validator_fn) = &config.validator {
        let validator_path: syn::Path = syn::parse_str(validator_fn).expect("invalid validator function path");
        quote! {
            #validator_path(self)?;
        }
    } else {
        quote! {}
    };
    let decode_message_validation = if let Some(validator_fn) = &config.validator {
        let validator_path: syn::Path = syn::parse_str(validator_fn).expect("invalid validator function path");
        quote! {
            #validator_path(&mut value)?;
        }
    } else {
        quote! {}
    };
    let post_decode_impl = if config.validator.is_none() && !has_field_validation {
        quote! {}
    } else {
        quote! {
            #[inline]
            fn post_decode(value: Self::ShadowDecoded) -> Result<Self, ::proto_rs::DecodeError> {
                let mut shadow = value;
                #field_validation
                #message_validation
                Ok(shadow)
            }
        }
    };

    let mut shadow_generics = bounded_generics.clone();
    shadow_generics.params.insert(0, parse_quote!('a));
    let (shadow_impl_generics, _shadow_ty_generics, shadow_where_clause) = shadow_generics.split_for_impl();

    let sun_impls = if config.has_suns() {
        let sun_impls = config.suns.iter().map(|sun| {
            let target_ty = &sun.ty;
            quote! {
                impl #impl_generics ::proto_rs::ProtoExt for #target_ty #where_clause {
                    const KIND: ::proto_rs::ProtoKind = ::proto_rs::ProtoKind::Message;
                }

                impl #impl_generics ::proto_rs::ProtoEncode for #target_ty #where_clause {
                    type Shadow<'a> = #name #ty_generics;
                }

                impl #impl_generics ::proto_rs::ProtoDecode for #target_ty #where_clause {
                    type ShadowDecoded = #name #ty_generics;

                    #[inline]
                    fn post_decode(value: Self::ShadowDecoded) -> Result<Self, ::proto_rs::DecodeError> {
                        let shadow = value;
                        let mut shadow = shadow;
                        #field_validation
                        #message_validation
                        <#name #ty_generics as ::proto_rs::ProtoShadowDecode<#target_ty>>::to_sun(shadow)
                    }

                    #validate_with_ext_impl
                }

                impl #impl_generics ::proto_rs::ProtoDefault for #target_ty #where_clause {
                    #[inline]
                    fn proto_default() -> Self {
                        let shadow = <#name #ty_generics as ::proto_rs::ProtoDefault>::proto_default();
                        <#name #ty_generics as ::proto_rs::ProtoShadowDecode<#target_ty>>::to_sun(shadow)
                            .expect("failed to build default sun value")
                    }
                }

                impl #impl_generics ::proto_rs::ProtoFieldMerge for #target_ty #where_clause {
                    #[inline]
                    fn merge_value(
                        &mut self,
                        wire_type: ::proto_rs::encoding::WireType,
                        buf: &mut impl ::proto_rs::bytes::Buf,
                        ctx: ::proto_rs::encoding::DecodeContext,
                    ) -> Result<(), ::proto_rs::DecodeError> {
                        let mut shadow = <#name #ty_generics as ::proto_rs::ProtoShadowEncode<'_, #target_ty>>::from_sun(self);
                        <#name #ty_generics as ::proto_rs::ProtoDecoder>::merge(&mut shadow, wire_type, buf, ctx)?;
                        *self = <#name #ty_generics as ::proto_rs::ProtoShadowDecode<#target_ty>>::to_sun(shadow)?;
                        Ok(())
                    }
                }

                impl #impl_generics ::proto_rs::ProtoArchive for #target_ty #where_clause {
                    #[inline]
                    fn is_default(&self) -> bool {
                        let shadow = <#name #ty_generics as ::proto_rs::ProtoShadowEncode<'_, #target_ty>>::from_sun(self);
                        <#name #ty_generics as ::proto_rs::ProtoArchive>::is_default(&shadow)
                    }

                    #[inline]
                    fn archive<const TAG: u32>(&self, w: &mut impl ::proto_rs::RevWriter) {
                        let shadow = <#name #ty_generics as ::proto_rs::ProtoShadowEncode<'_, #target_ty>>::from_sun(self);
                        <#name #ty_generics as ::proto_rs::ProtoArchive>::archive::<TAG>(&shadow, w)
                    }
                }
            }
        });
        quote! { #( #sun_impls )* }
    } else {
        quote! {}
    };

    Ok(quote! {
        #enum_item

        impl #impl_generics ::proto_rs::ProtoExt for #name #ty_generics #where_clause {
            const KIND: ::proto_rs::ProtoKind = ::proto_rs::ProtoKind::Message;
        }

        impl #impl_generics ::proto_rs::ProtoDecoder for #name #ty_generics #where_clause {
            #[inline]
            fn merge_field(
                value: &mut Self,
                tag: u32,
                wire_type: ::proto_rs::encoding::WireType,
                buf: &mut impl ::proto_rs::bytes::Buf,
                ctx: ::proto_rs::encoding::DecodeContext,
            ) -> Result<(), ::proto_rs::DecodeError> {
                match tag {
                    #(#merge_field_arms,)*
                    _ => ::proto_rs::encoding::skip_field(wire_type, tag, buf, ctx),
                }
            }

            #[inline]
            fn merge(&mut self, wire_type: ::proto_rs::encoding::WireType, buf: &mut impl ::proto_rs::bytes::Buf, ctx: ::proto_rs::encoding::DecodeContext) -> Result<(), ::proto_rs::DecodeError> {
                if wire_type != ::proto_rs::encoding::WireType::LengthDelimited {
                    return Err(::proto_rs::DecodeError::new(format!("invalid wire type {}", <Self as ::proto_rs::ProtoExt>::KIND.dbg_name())));
                }
                ctx.limit_reached()?;
                let len = ::proto_rs::encoding::decode_varint(buf)? as usize;
                let remaining = buf.remaining();
                if len > remaining {
                    return Err(::proto_rs::DecodeError::new("buffer underflow"));
                }
                let limit = remaining - len;
                while buf.remaining() > limit {
                    Self::decode_one_field(self, buf, ctx)?;
                }
                #merge_field_validation
                #merge_message_validation
                Ok(())
            }

            #[inline]
            fn decode(mut buf: impl ::proto_rs::bytes::Buf, ctx: ::proto_rs::encoding::DecodeContext) -> Result<Self, ::proto_rs::DecodeError>
            where
                Self: ::proto_rs::ProtoDefault,
            {
                ctx.limit_reached()?;
                let mut value = <Self as ::proto_rs::ProtoDefault>::proto_default();
                Self::decode_into(&mut value, &mut buf, ctx)?;
                #decode_field_validation
                #decode_message_validation
                Ok(value)
            }
        }

        impl #impl_generics ::proto_rs::ProtoDefault for #name #ty_generics #where_clause {
            #[inline]
            fn proto_default() -> Self {
                #default_expr
            }
        }

        impl #impl_generics ::proto_rs::ProtoDecode for #name #ty_generics #where_clause {
            type ShadowDecoded = Self;
            #post_decode_impl
            #validate_with_ext_proto_impl
        }

        impl #impl_generics ::proto_rs::ProtoShadowDecode<#name #ty_generics> for #name #ty_generics #where_clause {
            #[inline]
            fn to_sun(self) -> Result<#name #ty_generics, ::proto_rs::DecodeError> {
                Ok(self)
            }
        }

        impl #shadow_impl_generics ::proto_rs::ProtoShadowEncode<'a, #name #ty_generics> for &'a #name #ty_generics #shadow_where_clause {
            #[inline]
            fn from_sun(value: &'a #name #ty_generics) -> Self {
                value
            }
        }

        impl #shadow_impl_generics ::proto_rs::ProtoArchive for &'a #name #ty_generics #shadow_where_clause {
            #[inline]
            fn is_default(&self) -> bool {
                match *self {
                    #(#is_default_arms,)*
                }
            }

            #[inline]
            fn archive<const TAG: u32>(&self, w: &mut impl ::proto_rs::RevWriter) {
                let mark = w.mark();
                match *self {
                    #(#encode_arms,)*
                }
                if TAG != 0 {
                    let payload_len = w.written_since(mark);
                    w.put_varint(payload_len as u64);
                    ::proto_rs::ArchivedProtoField::<TAG, Self>::put_key(w);
                }
            }
        }

        impl #impl_generics ::proto_rs::ProtoArchive for #name #ty_generics #where_clause {
            #[inline]
            fn is_default(&self) -> bool {
                <&Self as ::proto_rs::ProtoArchive>::is_default(&self)
            }

            #[inline]
            fn archive<const TAG: u32>(&self, w: &mut impl ::proto_rs::RevWriter) {
                <&Self as ::proto_rs::ProtoArchive>::archive::<TAG>(&self, w)
            }
        }

        impl #impl_generics ::proto_rs::ProtoEncode for #name #ty_generics #where_clause {
            type Shadow<'a> = &'a #name #ty_generics;
        }

        #sun_impls
    })
}

#[derive(Clone)]
#[allow(clippy::large_enum_variant)]
enum VariantKind<'a> {
    Unit,
    Tuple { field: TupleVariantInfo<'a> },
    Struct { fields: Vec<FieldInfo<'a>> },
}

#[derive(Clone)]
struct VariantInfo<'a> {
    ident: &'a Ident,
    tag: u32,
    kind: VariantKind<'a>,
    is_default: bool,
}

#[derive(Clone)]
struct TupleVariantInfo<'a> {
    field: FieldInfo<'a>,
    binding_ident: Ident,
}

fn collect_variant_infos<'a>(data: &'a syn::DataEnum, _config: &'a UnifiedProtoConfig) -> syn::Result<Vec<VariantInfo<'a>>> {
    let mut used_tags = BTreeSet::new();
    let mut variants = Vec::new();

    for (idx, variant) in data.variants.iter().enumerate() {
        let tag = resolve_variant_tag(variant, idx + 1)?;
        if !used_tags.insert(tag) {
            return Err(syn::Error::new(
                variant.ident.span(),
                format!("duplicate proto(tag) attribute for enum variant: {tag}"),
            ));
        }

        let kind = match &variant.fields {
            syn::Fields::Unit => VariantKind::Unit,
            syn::Fields::Unnamed(fields) => {
                if fields.unnamed.len() != 1 {
                    return Err(syn::Error::new(
                        variant.ident.span(),
                        "complex enum tuple variants must contain exactly one field",
                    ));
                }

                let field = &fields.unnamed[0];
                let config = parse_field_config(field);
                let effective_ty = resolved_field_type(field, &config);
                let parsed = parse_field_type(&effective_ty);
                let proto_ty = compute_proto_ty(field, &config, &parsed, &effective_ty);
                let decode_ty = compute_decode_ty(field, &config, &parsed, &proto_ty);
                let binding_ident = Ident::new(
                    &format!("__proto_rs_variant_{}_value", variant.ident.to_string().to_lowercase()),
                    field.span(),
                );

                let mut field_info = FieldInfo {
                    index: 0,
                    field,
                    access: FieldAccess::Direct(quote! { #binding_ident }),
                    config,
                    tag: None,
                    parsed,
                    proto_ty,
                    decode_ty,
                };

                if !field_info.config.skip {
                    let tag = field_info.config.custom_tag.unwrap_or(1);
                    if tag == 0 {
                        return Err(syn::Error::new(field.span(), "proto field tags must be greater than or equal to 1"));
                    }
                    field_info.tag = Some(u32::try_from(tag).map_err(|_| syn::Error::new(field.span(), "proto field tag overflowed u32"))?);
                }

                VariantKind::Tuple {
                    field: TupleVariantInfo {
                        field: field_info,
                        binding_ident,
                    },
                }
            }
            syn::Fields::Named(fields_named) => {
                let mut infos: Vec<_> = fields_named
                    .named
                    .iter()
                    .enumerate()
                    .map(|(field_idx, field)| {
                        let config = parse_field_config(field);
                        let effective_ty = resolved_field_type(field, &config);
                        let parsed = parse_field_type(&effective_ty);
                        let proto_ty = compute_proto_ty(field, &config, &parsed, &effective_ty);
                        let decode_ty = compute_decode_ty(field, &config, &parsed, &proto_ty);
                        FieldInfo {
                            index: field_idx,
                            field,
                            access: FieldAccess::Direct({
                                let ident = field.ident.as_ref().expect("named variant field");
                                quote! { #ident }
                            }),
                            config,
                            tag: None,
                            parsed,
                            proto_ty,
                            decode_ty,
                        }
                    })
                    .collect();
                infos = assign_tags(infos);
                VariantKind::Struct { fields: infos }
            }
        };

        variants.push(VariantInfo {
            ident: &variant.ident,
            tag,
            kind,
            is_default: false,
        });
    }

    Ok(variants)
}

fn collect_variant_fields<'a>(variants: &'a [VariantInfo<'a>]) -> Vec<&'a FieldInfo<'a>> {
    let mut fields = Vec::new();
    for variant in variants {
        match &variant.kind {
            VariantKind::Unit => {}
            VariantKind::Tuple { field } => {
                fields.push(&field.field);
            }
            VariantKind::Struct { fields: struct_fields } => {
                fields.extend(struct_fields.iter());
            }
        }
    }
    fields
}

fn resolve_variant_tag(variant: &syn::Variant, default: usize) -> syn::Result<u32> {
    let mut custom_tag = None;

    for attr in &variant.attrs {
        if !attr.path().is_ident("proto") {
            continue;
        }

        attr.parse_nested_meta(|meta| {
            if meta.path.get_ident().is_some_and(|ident| ident == "tag") {
                if custom_tag.is_some() {
                    return Err(syn::Error::new(meta.path.span(), "duplicate proto(tag) attribute for variant"));
                }

                let lit: Lit = meta.value()?.parse()?;
                let value = match lit {
                    Lit::Int(int_lit) => int_lit.base10_parse::<usize>()?,
                    Lit::Str(str_lit) => str_lit
                        .value()
                        .parse::<usize>()
                        .map_err(|_| syn::Error::new(str_lit.span(), "proto tag must be a positive integer"))?,
                    _ => {
                        return Err(syn::Error::new(lit.span(), "proto tag must be specified as an integer"));
                    }
                };

                custom_tag = Some(value);
            }
            Ok(())
        })?;
    }

    let tag = custom_tag.unwrap_or(default);
    if tag == 0 {
        return Err(syn::Error::new(
            variant.ident.span(),
            "proto enum variant tags must be greater than or equal to 1",
        ));
    }

    let tag_u32 = u32::try_from(tag).map_err(|_| syn::Error::new(variant.ident.span(), "proto tag overflowed u32"))?;
    Ok(tag_u32)
}

// Helper: Generate encoding body for empty variants (Unit or empty Struct)
fn build_empty_variant_encode_body(tag: u32) -> TokenStream2 {
    quote! {
        w.put_varint(0);
        ::proto_rs::ArchivedProtoField::<#tag, ()>::put_key(w);
    }
}

// Helper: Generate binding patterns for struct fields (handles skip attributes)
fn build_struct_field_bindings<'a>(fields: &'a [FieldInfo<'a>]) -> impl Iterator<Item = TokenStream2> + 'a {
    fields.iter().map(|info| {
        let field_ident = info.field.ident.as_ref().expect("named field");
        if info.config.skip {
            quote! { #field_ident: _ }
        } else {
            quote! { #field_ident }
        }
    })
}

fn build_variant_default_expr(variant: &VariantInfo<'_>, enum_ident: &Ident) -> TokenStream2 {
    let ident = variant.ident;
    match &variant.kind {
        VariantKind::Unit => quote! { #enum_ident::#ident },
        VariantKind::Tuple { field } => {
            let default_expr = field_proto_default_expr(&field.field);
            quote! { #enum_ident::#ident(#default_expr) }
        }
        VariantKind::Struct { fields } => {
            if fields.is_empty() {
                quote! { #enum_ident::#ident }
            } else {
                let inits = fields.iter().map(|info| {
                    let field_ident = info.field.ident.as_ref().expect("named field");
                    let expr = field_proto_default_expr(info);
                    quote! { #field_ident: #expr }
                });
                quote! { #enum_ident::#ident { #(#inits),* } }
            }
        }
    }
}

fn build_variant_is_default_arm(variant: &VariantInfo<'_>, enum_ident: &Ident) -> TokenStream2 {
    let ident = variant.ident;
    match &variant.kind {
        VariantKind::Unit => {
            if variant.is_default {
                quote! { #enum_ident::#ident => true }
            } else {
                quote! { #enum_ident::#ident => false }
            }
        }
        VariantKind::Tuple { field } => {
            if !variant.is_default {
                return quote! { #enum_ident::#ident(..) => false };
            }
            if field.field.config.skip {
                quote! { #enum_ident::#ident(..) => true }
            } else {
                let binding_ident = &field.binding_ident;
                let field_ty = &field.field.field.ty;
                let ref_expr = quote! { &#binding_ident };
                let check_expr = if needs_encode_conversion(&field.field.config, &field.field.parsed) {
                    let converted = encode_conversion_expr(&field.field, &ref_expr);
                    quote! { ::proto_rs::ProtoArchive::is_default(&#converted) }
                } else {
                    let shadow_ty = quote! { <#field_ty as ::proto_rs::ProtoEncode>::Shadow<'_> };
                    quote! {
                        {
                            let shadow = <#shadow_ty as ::proto_rs::ProtoShadowEncode<'_, #field_ty>>::from_sun(#ref_expr);
                            ::proto_rs::ProtoArchive::is_default(&shadow)
                        }
                    }
                };
                quote! {
                    #enum_ident::#ident(#binding_ident) => { #check_expr }
                }
            }
        }
        VariantKind::Struct { fields } => {
            if !variant.is_default {
                return quote! { #enum_ident::#ident { .. } => false };
            }
            if fields.is_empty() {
                quote! { #enum_ident::#ident { .. } => true }
            } else {
                let bindings = build_struct_field_bindings(fields);
                let checks = fields.iter().filter_map(|info| {
                    if info.config.skip {
                        return None;
                    }
                    let field_ident = info.field.ident.as_ref().expect("named field");
                    let field_ty = &info.field.ty;
                    let ref_expr = quote! { &#field_ident };
                    let check_expr = if needs_encode_conversion(&info.config, &info.parsed) {
                        let converted = encode_conversion_expr(info, &ref_expr);
                        quote! { ::proto_rs::ProtoArchive::is_default(&#converted) }
                    } else {
                        let shadow_ty = quote! { <#field_ty as ::proto_rs::ProtoEncode>::Shadow<'_> };
                        quote! {
                            {
                                let shadow = <#shadow_ty as ::proto_rs::ProtoShadowEncode<'_, #field_ty>>::from_sun(#ref_expr);
                                ::proto_rs::ProtoArchive::is_default(&shadow)
                            }
                        }
                    };
                    Some(check_expr)
                });
                quote! {
                    #enum_ident::#ident { #(#bindings),* } => {
                        true #(&& #checks)*
                    }
                }
            }
        }
    }
}

fn build_variant_encode_arm(variant: &VariantInfo<'_>, enum_ident: &Ident) -> TokenStream2 {
    let ident = variant.ident;
    let tag = variant.tag;
    match &variant.kind {
        VariantKind::Unit => {
            let encode_body = build_empty_variant_encode_body(tag);
            quote! {
                #enum_ident::#ident => {
                    #encode_body
                }
            }
        }
        VariantKind::Tuple { field } => {
            let binding_ident = &field.binding_ident;
            if field.field.config.skip {
                return quote! {
                    #enum_ident::#ident(..) => {}
                };
            }
            let field_ty = &field.field.field.ty;
            let ref_expr = quote! { &#binding_ident };
            let shadow_ty = if needs_encode_conversion(&field.field.config, &field.field.parsed) {
                let proto_ty = &field.field.proto_ty;
                quote! { #proto_ty }
            } else {
                quote! { <#field_ty as ::proto_rs::ProtoEncode>::Shadow<'_> }
            };
            let shadow_expr = if needs_encode_conversion(&field.field.config, &field.field.parsed) {
                encode_conversion_expr(&field.field, &ref_expr)
            } else {
                quote! { <#shadow_ty as ::proto_rs::ProtoShadowEncode<'_, #field_ty>>::from_sun(#ref_expr) }
            };
            quote! {
                #enum_ident::#ident(#binding_ident) => {
                    let __proto_rs_shadow = #shadow_expr;
                    // Use new_always to preserve variant selection even when payload is default
                    ::proto_rs::ArchivedProtoField::<#tag, #shadow_ty>::new_always(&__proto_rs_shadow, w);
                }
            }
        }
        VariantKind::Struct { fields } => {
            let bindings = build_struct_field_bindings(fields);
            let field_encodes = fields.iter().rev().filter_map(|info| {
                if info.config.skip {
                    return None;
                }
                let field_ident = info.field.ident.as_ref().expect("named field");
                let field_tag = info.tag.expect("tag required");
                let field_ty = &info.field.ty;
                let ref_expr = quote! { &#field_ident };
                let shadow_ty = if needs_encode_conversion(&info.config, &info.parsed) {
                    let proto_ty = &info.proto_ty;
                    quote! { #proto_ty }
                } else {
                    quote! { <#field_ty as ::proto_rs::ProtoEncode>::Shadow<'_> }
                };
                let shadow_expr = if needs_encode_conversion(&info.config, &info.parsed) {
                    encode_conversion_expr(info, &ref_expr)
                } else {
                    quote! { <#shadow_ty as ::proto_rs::ProtoShadowEncode<'_, #field_ty>>::from_sun(#ref_expr) }
                };
                let shadow_ident = syn::Ident::new(
                    &format!("__proto_rs_variant_{}_shadow_{}", ident.to_string().to_lowercase(), info.index),
                    info.field.span(),
                );
                Some(quote! {
                    let #shadow_ident = #shadow_expr;
                    ::proto_rs::ArchivedProtoField::<#field_tag, #shadow_ty>::archive(&#shadow_ident, w);
                })
            });
            quote! {
                #enum_ident::#ident { #(#bindings),* } => {
                    let mark = w.mark();
                    #(#field_encodes)*
                    let payload_len = w.written_since(mark);
                    w.put_varint(payload_len as u64);
                    ::proto_rs::ArchivedProtoField::<#tag, Self>::put_key(w);
                }
            }
        }
    }
}

fn build_variant_field_validation_arms(enum_ident: &Ident, variants: &[VariantInfo<'_>]) -> Vec<TokenStream2> {
    variants
        .iter()
        .filter_map(|variant| {
            let ident = variant.ident;
            match &variant.kind {
                VariantKind::Unit => None,
                VariantKind::Tuple { field } => {
                    if field.field.config.skip {
                        return None;
                    }
                    let validator_fn = field.field.config.validator.as_ref()?;
                    let validator_path = parse_path_string(field.field.field, validator_fn);
                    let binding_ident = &field.binding_ident;
                    Some(quote! {
                        #enum_ident::#ident(#binding_ident) => {
                            #validator_path(#binding_ident)?;
                        }
                    })
                }
                VariantKind::Struct { fields } => {
                    let validators = fields
                        .iter()
                        .filter_map(|info| {
                            if info.config.skip {
                                return None;
                            }
                            let validator_fn = info.config.validator.as_ref()?;
                            let validator_path = parse_path_string(info.field, validator_fn);
                            let field_ident = info.field.ident.as_ref().expect("named field");
                            Some(quote! {
                                #validator_path(#field_ident)?;
                            })
                        })
                        .collect::<Vec<_>>();

                    if validators.is_empty() {
                        return None;
                    }

                    let bindings = fields.iter().map(|info| {
                        let field_ident = info.field.ident.as_ref().expect("named field");
                        if info.config.validator.is_some() && !info.config.skip {
                            quote! { #field_ident }
                        } else {
                            quote! { #field_ident: _ }
                        }
                    });
                    Some(quote! {
                        #enum_ident::#ident { #(#bindings),* } => {
                            #(#validators)*
                        }
                    })
                }
            }
        })
        .collect()
}

fn build_variant_merge_arm(name: &Ident, variant: &VariantInfo<'_>) -> TokenStream2 {
    let ident = variant.ident;
    let tag = variant.tag;
    match &variant.kind {
        VariantKind::Unit => {
            quote! {
                #tag => {
                    ::proto_rs::encoding::check_wire_type(
                        ::proto_rs::encoding::WireType::LengthDelimited,
                        wire_type,
                    )?;
                    // No need to check limit_reached() for unit variants - no recursion happens
                    let len = ::proto_rs::encoding::decode_varint(buf)?;
                    if len > buf.remaining() as u64 {
                        return Err(::proto_rs::DecodeError::new("buffer underflow"));
                    }
                    if len != 0 {
                        return Err(::proto_rs::DecodeError::new("expected empty variant payload"));
                    }
                    *value = #name::#ident;
                    Ok(())
                }
            }
        }
        VariantKind::Tuple { field } => {
            let binding_ident = &field.binding_ident;
            let binding_default = field_proto_default_expr(&field.field);
            let decode_stmt = if field.field.config.skip {
                quote! {
                    ::proto_rs::encoding::skip_field(wire_type, #tag, buf, ctx)?;
                }
            } else if needs_decode_conversion(&field.field.config, &field.field.parsed) {
                let tmp_ident = Ident::new(
                    &format!("__proto_rs_variant_field_{}_tmp", field.field.index),
                    field.field.field.span(),
                );
                let decode_ty = &field.field.decode_ty;
                let assign = decode_conversion_assign(&field.field, &quote! { #binding_ident }, &tmp_ident);
                quote! {
                    let mut #tmp_ident: #decode_ty = <#decode_ty as ::proto_rs::ProtoDefault>::proto_default();
                    <#decode_ty as ::proto_rs::ProtoFieldMerge>::merge_value(&mut #tmp_ident, wire_type, buf, ctx)?;
                    #assign
                }
            } else {
                let ty = &field.field.field.ty;
                quote! {
                    <#ty as ::proto_rs::ProtoFieldMerge>::merge_value(&mut #binding_ident, wire_type, buf, ctx)?;
                }
            };

            let post_hook = if field.field.config.skip {
                field.field.config.skip_deser_fn.as_ref().map(|fun| {
                    let fun_path = parse_path_string(field.field.field, fun);
                    let skip_binding_ident = Ident::new(
                        &format!("__proto_rs_variant_{}_skip_binding", ident.to_string().to_lowercase()),
                        field.field.field.span(),
                    );
                    let computed_ident = Ident::new(
                        &format!("__proto_rs_variant_{}_computed", ident.to_string().to_lowercase()),
                        field.field.field.span(),
                    );
                    quote! {
                        let #computed_ident = #fun_path(value);
                        if let #name::#ident(#skip_binding_ident) = value {
                            *#skip_binding_ident = #computed_ident;
                        }
                    }
                })
            } else {
                None
            };

            let assign_variant = if let Some(post_hook) = post_hook {
                quote! {
                    *value = #name::#ident(#binding_ident);
                    #post_hook
                }
            } else {
                quote! { *value = #name::#ident(#binding_ident); }
            };

            quote! {
                #tag => {
                    let mut #binding_ident = #binding_default;
                    #decode_stmt
                    #assign_variant
                    Ok(())
                }
            }
        }
        VariantKind::Struct { fields } => {
            let field_inits = fields.iter().map(|info| {
                let field_ident = info.field.ident.as_ref().expect("named field");
                let init = field_proto_default_expr(info);
                quote! { let mut #field_ident = #init; }
            });
            let decode_match = fields
                .iter()
                .filter_map(|info| {
                    let field_tag = info.tag?;
                    let field_ident = info.field.ident.as_ref().expect("named field");
                    if needs_decode_conversion(&info.config, &info.parsed) {
                        let tmp_ident = Ident::new(&format!("__proto_rs_variant_field_{}_tmp", info.index), info.field.span());
                        let decode_ty = &info.decode_ty;
                        let access = quote! { #field_ident };
                        let assign = decode_conversion_assign(info, &access, &tmp_ident);
                        Some(quote! {
                            #field_tag => {
                                let mut #tmp_ident: #decode_ty = <#decode_ty as ::proto_rs::ProtoDefault>::proto_default();
                                <#decode_ty as ::proto_rs::ProtoFieldMerge>::merge_value(&mut #tmp_ident, field_wire_type, buf, inner_ctx)?;
                                #assign
                            }
                        })
                    } else {
                        let ty = &info.field.ty;
                        Some(quote! {
                            #field_tag => {
                                <#ty as ::proto_rs::ProtoFieldMerge>::merge_value(&mut #field_ident, field_wire_type, buf, inner_ctx)?;
                            }
                        })
                    }
                })
                .collect::<Vec<_>>();
            let construct_expr = if fields.is_empty() {
                quote! { #name::#ident }
            } else {
                let assigns = fields.iter().map(|info| {
                    let field_ident = info.field.ident.as_ref().expect("named field");
                    quote! { #field_ident }
                });
                quote! { #name::#ident { #(#assigns),* } }
            };
            let post_hooks = fields
                .iter()
                .filter_map(|info| {
                    if !info.config.skip {
                        return None;
                    }
                    let fun = info.config.skip_deser_fn.as_ref()?;
                    let field_ident = info.field.ident.as_ref().expect("named field");
                    let fun_path = parse_path_string(info.field, fun);
                    let skip_binding_ident = Ident::new(
                        &format!(
                            "__proto_rs_variant_{}_{}_skip_binding",
                            ident.to_string().to_lowercase(),
                            info.index
                        ),
                        info.field.span(),
                    );
                    let computed_ident = Ident::new(
                        &format!("__proto_rs_variant_{}_{}_computed", ident.to_string().to_lowercase(), info.index),
                        info.field.span(),
                    );
                    Some(quote! {
                        let #computed_ident = #fun_path(value);
                        if let #name::#ident { #field_ident: #skip_binding_ident, .. } = value {
                            *#skip_binding_ident = #computed_ident;
                        }
                    })
                })
                .collect::<Vec<_>>();
            let assign_variant = if post_hooks.is_empty() {
                quote! { *value = #construct_expr; }
            } else {
                quote! {
                    *value = #construct_expr;
                    #(#post_hooks)*
                }
            };
            let decode_loop = if decode_match.is_empty() {
                quote! {
                    while buf.remaining() > limit {
                        let (field_tag, field_wire_type) = ::proto_rs::encoding::decode_key(buf)?;
                        ::proto_rs::encoding::skip_field(field_wire_type, field_tag, buf, inner_ctx)?;
                    }
                }
            } else {
                quote! {
                    while buf.remaining() > limit {
                        let (field_tag, field_wire_type) = ::proto_rs::encoding::decode_key(buf)?;
                        match field_tag {
                            #(#decode_match,)*
                            _ => ::proto_rs::encoding::skip_field(field_wire_type, field_tag, buf, inner_ctx)?,
                        }
                    }
                }
            };
            quote! {
                #tag => {
                    ::proto_rs::encoding::check_wire_type(
                        ::proto_rs::encoding::WireType::LengthDelimited,
                        wire_type,
                    )?;
                    // Check limit once at recursion boundary, then use entered context for fields
                    ctx.limit_reached()?;
                    let inner_ctx = ctx.enter_recursion();
                    let len = ::proto_rs::encoding::decode_varint(buf)?;
                    if len > buf.remaining() as u64 {
                        return Err(::proto_rs::DecodeError::new("buffer underflow"));
                    }
                    let limit = buf.remaining() - len as usize;
                    #(#field_inits)*
                    #decode_loop
                    #assign_variant
                    Ok(())
                }
            }
        }
    }
}