bilrost-derive 0.1015.0

A compact protobuf-like serializer and deserializer for the Rust Language.
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
use crate::attrs::{
    bilrost_attrs, named_attr, set_bool, set_option, set_option_with_display, tag_attr,
    tag_list_attr, word_attr, TagList,
};
use crate::crate_name;
use crate::field::traits::{
    DecodeLifetime::{self, Borrowed, Owned},
    DecodeMode::{self, Distinguished, Relaxed},
    FieldBearer, SinglyTagged, Tagged,
    WhereFor::{self, Decode, Encode},
};
use crate::field::{
    ident_string, parse_message_fields, Field, FieldTarget, InitMode, MessageFieldsSorted,
};
use alloc::boxed::Box;
use alloc::format;
use alloc::string::ToString;
use alloc::vec;
use alloc::vec::Vec;
use eyre::{bail, eyre as err, Report as Error};
use itertools::Itertools;
use proc_macro2::{Span, TokenStream};
use quote::{quote, ToTokens};
use syn::{parse_str, Fields, Ident, Index, Meta, Type, Variant};

/// A field in a bilrost message or oneof
#[derive(Clone)]
pub struct MessageField {
    tag: u32,
    value: ValueField,
    /// In structs, we can create inherent implementations with helper methods for getting and
    /// setting enumeration values through translated types. This is only possible on messages, and
    /// even when "variant types" are available those types are unlikely to be allowed to have impls
    /// of their own.
    enumeration_ty: Option<Type>,
}

#[derive(Clone)]
struct ValueField {
    ty: Type,
    encoding: Type,
    /// If a field is part of a recursion of messages, currently the chain needs to be broken so
    /// that there is not a cyclic dependency of type constraints on the implementation of message
    /// traits. When a field is marked with the "recurses" attribute, it will not be checked in the
    /// `where` clause of the implementation, and the type must always be supported by its encoding.
    recurses: bool,
}

#[derive(Clone)]
pub struct OneofVariant {
    tag: u32,
    variant_ident: Ident,
    contents: VariantContents,
}

// TODO: use this to let the empty variant have ignored fields
// #[derive(Clone)]
// pub struct EmptyVariant {
//     variant_ident: Ident,
//     contents: Vec<IgnoredField>,
// }

#[derive(Clone)]
enum VariantContents {
    Value(Box<FieldInVariant>),
    Message(Vec<Field>),
}

#[derive(Clone)]
struct FieldInVariant {
    ident_within_variant: TokenStream,
    value: ValueField,
}

impl MessageField {
    pub fn new(
        ty: &Type,
        attrs: Vec<Meta>,
        inferred_tag: Option<u32>,
    ) -> Result<Box<MessageField>, Error> {
        let mut tag = None;
        let mut enumeration_ty: Option<Type> = None;
        let mut remaining_attrs = vec![];

        for attr in attrs {
            if let Some(t) = tag_attr(&attr)? {
                set_option(&mut tag, t, "duplicate tag attributes")?;
            } else if let Some(t) = named_attr(&attr, "enumeration")? {
                set_option_with_display(
                    &mut enumeration_ty,
                    t,
                    "duplicate enumeration attributes",
                    |ty| quote!(<#ty>).to_string(),
                )?;
            } else {
                remaining_attrs.push(attr);
            }
        }

        let value = ValueField::new(ty, remaining_attrs, "general")?;

        let tag = match tag.or(inferred_tag) {
            Some(tag) => tag,
            None => bail!("missing tag attribute"),
        };

        Ok(Box::new(MessageField {
            tag,
            value,
            enumeration_ty,
        }))
    }

    pub fn ty(&self) -> &Type {
        &self.value.ty
    }

    pub fn has_enumeration_type(&self) -> bool {
        self.enumeration_ty.is_some()
    }

    /// Returns a statement which encodes the field using buffer `buf` and tag writer `tw`. `target`
    /// should be a reference to the field value.
    pub fn encode(&self, target: TokenStream) -> TokenStream {
        let crate_ = crate_name();
        let tag = self.tag;
        let encoding = &self.value.encoding;
        let ty = &self.value.ty;
        quote! {
            <() as #crate_::encoding::Encoder<#encoding, #ty>>::encode(#tag, #target, buf, tw);
        }
    }

    /// Returns a statement which encodes the field using buffer `buf` and tag writer `tw`. `target`
    /// should be a reference to the field value.
    pub fn prepend(&self, target: TokenStream) -> TokenStream {
        let crate_ = crate_name();
        let tag = self.tag;
        let encoding = &self.value.encoding;
        let ty = &self.value.ty;
        quote! {
            <() as #crate_::encoding::Encoder<#encoding, #ty>>::prepend_encode(
                #tag,
                #target,
                buf,
                tw,
            );
        }
    }

    /// Returns an expression which evaluates to the result of merging a decoded value into the
    /// field. The given ident must be an &mut that already refers to the destination. `target`
    /// should be a mutable reference to the field value.
    pub fn decode(
        &self,
        target: TokenStream,
        lifetime: DecodeLifetime,
        mode: DecodeMode,
    ) -> TokenStream {
        let crate_ = crate_name();
        let encoding = &self.value.encoding;
        let ty = &self.value.ty;
        let (decoder_trait, call) = match (lifetime, mode) {
            (Owned, Relaxed) => (quote!(Decoder), quote!(decode)),
            (Borrowed, Relaxed) => (quote!(BorrowDecoder), quote!(borrow_decode)),
            (Owned, Distinguished) => (quote!(DistinguishedDecoder), quote!(decode_distinguished)),
            (Borrowed, Distinguished) => (
                quote!(DistinguishedBorrowDecoder),
                quote!(borrow_decode_distinguished),
            ),
        };
        // We need to check the duplicated status of the field ourselves to attach the right field
        // name to the error while decoding.
        quote! {
            if duplicated {
                ::core::result::Result::Err(#crate_::DecodeError::new(
                    #crate_::DecodeErrorKind::UnexpectedlyRepeated
                ))
            } else {
                <() as #crate_::encoding::#decoder_trait<#encoding, #ty>>::#call(
                    wire_type,
                    #target,
                    buf,
                    ctx,
                )
            }
        }
    }

    /// Returns an expression which evaluates to the encoded length of the field. The given ident
    /// must be the location name of the field value, not a reference. `target` should be a
    /// reference to the field value.
    pub fn encoded_len(&self, target: TokenStream) -> TokenStream {
        let crate_ = crate_name();
        let tag = self.tag;
        let encoding = &self.value.encoding;
        let ty = &self.value.ty;
        quote! {
            <() as #crate_::encoding::Encoder<#encoding, #ty>>::encoded_len(#tag, #target, tm)
        }
    }

    /// Returns an expression which initializes the field's type as a guaranteed empty value with
    /// its encoding.
    pub fn empty(&self) -> TokenStream {
        let crate_ = crate_name();
        let encoding = &self.value.encoding;
        let ty = &self.value.ty;
        quote!(<() as #crate_::encoding::EmptyState<#encoding, #ty>>::empty())
    }

    /// Returns an expression which returns whether the field is considered empty in the encoding.
    /// `target` should be a reference to the field value.
    pub fn is_empty(&self, target: TokenStream) -> TokenStream {
        let crate_ = crate_name();
        let encoding = &self.value.encoding;
        let ty = &self.value.ty;
        quote!(<() as #crate_::encoding::EmptyState<#encoding, #ty>>::is_empty(#target))
    }

    /// Returns an expression which resets the field's value to empty with its encoding. `target`
    /// should be a mutable reference to the field value.
    pub fn clear(&self, target: TokenStream) -> TokenStream {
        let crate_ = crate_name();
        let encoding = &self.value.encoding;
        let ty = &self.value.ty;
        quote! {
            <() as #crate_::encoding::EmptyState<#encoding, #ty>>::clear(#target);
        }
    }

    /// Returns the where clause constraint terms for the field's encoder.
    pub fn where_terms(&self, purpose: WhereFor) -> Vec<TokenStream> {
        let crate_ = crate_name();
        if self.value.recurses {
            return vec![];
        }
        let ty = &self.value.ty;
        let encoding = &self.value.encoding;
        vec![
            match purpose {
                Encode => quote!((): #crate_::encoding::Encoder<#encoding, #ty>),
                Decode(Owned, Relaxed) => {
                    quote!((): #crate_::encoding::Decoder<#encoding, #ty>)
                }
                Decode(Borrowed, Relaxed) => {
                    quote!((): #crate_::encoding::BorrowDecoder<'__a, #encoding, #ty>)
                }
                Decode(Owned, Distinguished) => {
                    quote!((): #crate_::encoding::DistinguishedDecoder<#encoding, #ty>)
                }
                Decode(Borrowed, Distinguished) => {
                    quote!(
                        (): #crate_::encoding::DistinguishedBorrowDecoder<'__a, #encoding, #ty>
                    )
                }
            },
            // Message field encoding always requires EmptyState instead of just ForOverwrite
            // because we need to know whether a field is empty to know whether we should write
            // anything; and all the decoding traits imply the encoding trait.
            quote!((): #crate_::encoding::EmptyState<#encoding, #ty>),
        ]
    }

    /// Returns methods to embed in the message. `ident` must be the name of the field within the
    /// message struct.
    pub fn methods(&self, ident: &TokenStream) -> Option<TokenStream> {
        let crate_ = crate_name();
        let enumeration_ty = self.enumeration_ty.as_ref()?;

        let ident_str = ident_string(ident);

        // Prepend `get_` for getter methods of tuple structs.
        let get = match parse_str::<Index>(&ident_str) {
            Ok(index) => {
                let get = Ident::new(&format!("get_{}", index.index), Span::call_site());
                quote!(#get)
            }
            Err(_) => quote!(#ident),
        };

        let set = Ident::new(&format!("set_{}", ident_str), Span::call_site());

        let field_ty = &self.value.ty;

        Some(quote! {
            fn #get(
                &self
            ) -> <#enumeration_ty as #crate_::encoding::EnumerationHelper<#field_ty>>::Output {
                <
                    #enumeration_ty as #crate_::encoding::EnumerationHelper<#field_ty>
                >::help_get(self.#ident)
            }

            fn #set(
                &mut self,
                val: <#enumeration_ty as #crate_::encoding::EnumerationHelper<#field_ty>>::Input,
            ) {
                self.#ident = <
                    #enumeration_ty as #crate_::encoding::EnumerationHelper<#field_ty>
                >::help_set(val);
            }
        })
    }
}

impl SinglyTagged for MessageField {
    fn tag(&self) -> u32 {
        self.tag
    }
}

impl ValueField {
    fn new(
        ty: &Type,
        attrs: Vec<Meta>,
        implicit_default_encoding: &str,
    ) -> Result<ValueField, Error> {
        let mut encoding = None;
        let mut recurses = false;
        let mut unknown_attrs = Vec::new();

        for attr in &attrs {
            if let Some(t) = named_attr(attr, "encoding")? {
                set_option_with_display(&mut encoding, t, "duplicate encoding attributes", |t| {
                    quote!((#t)).to_string()
                })?;
            } else if word_attr(attr, "recurses") {
                set_bool(&mut recurses, "duplicate recurses attributes")?;
            } else {
                unknown_attrs.push(attr);
            }
        }

        if !unknown_attrs.is_empty() {
            bail!(
                "unknown attribute(s) for field: {attrs}",
                attrs = quote!(#(#unknown_attrs),*),
            )
        }

        let encoding =
            encoding.unwrap_or_else(|| parse_str::<Type>(implicit_default_encoding).unwrap());

        Ok(ValueField {
            ty: ty.clone(),
            encoding,
            recurses,
        })
    }
}

impl OneofVariant {
    /// Parses values specifically for within a Oneof variant, which works differently than fields
    /// within a Message.
    ///
    /// Returns `Ok` for data variants, and `Err` with just the ident for an empty variant.
    pub fn new(variant: Variant) -> Result<Option<OneofVariant>, Error> {
        let mut tag = None; // tag number
        let mut message = false; // whether this variant is marked as a "message" variant
        let mut empty = false; // whether this unit is marked as an "empty" variant
        let mut other_attrs = vec![];
        let our_attrs = bilrost_attrs(&variant.attrs)?;

        for attr in our_attrs {
            if let Some(t) = tag_attr(&attr)? {
                set_option(&mut tag, t, "duplicate tag attributes")?;
            } else if word_attr(&attr, "message") {
                set_bool(&mut message, "duplicate message attributes")?;
            } else if word_attr(&attr, "empty") {
                set_bool(&mut empty, "duplicate empty attributes")?;
            } else {
                other_attrs.push(attr);
            }
        }

        match (tag, message, empty) {
            // Implicitly or explicitly empty variant
            (None, false, _) if other_attrs.is_empty() => {
                if match variant.fields {
                    Fields::Named(fields) => fields.named.is_empty(),
                    Fields::Unnamed(fields) => fields.unnamed.is_empty(),
                    Fields::Unit => true,
                } {
                    Ok(None)
                } else {
                    // Return a error message depending on whether the variant is explicitly marked
                    // empty
                    if empty {
                        bail!(
                            "Oneof variant {variant_ident} is marked 'empty' but it has fields",
                            variant_ident = variant.ident,
                        );
                    } else {
                        bail!(
                            "missing tag attribute on variant {variant_ident}",
                            variant_ident = variant.ident,
                        );
                    }
                }
            }

            // Empty attribute plus any other attribute
            (_, _, true) => {
                bail!(
                    "the 'empty' attribute is combined with other attributes on variant \
                    {variant_ident}, but it must always be alone",
                    variant_ident = variant.ident,
                );
            }

            // Value variant with missing tag
            (None, false, false) => {
                bail!(
                    "missing tag attribute on value variant {variant_ident}",
                    variant_ident = variant.ident,
                );
            }

            // Normal value variant, neither empty nor message
            (Some(tag), false, false) => {
                let fields = match &variant.fields {
                    Fields::Named(fields) => &fields.named,
                    Fields::Unnamed(fields) => &fields.unnamed,
                    Fields::Unit => bail!(
                        "Oneof value variants must have exactly one field, but variant \
                        {variant_ident} has no fields",
                        variant_ident = variant.ident
                    ),
                };
                if fields.len() != 1 {
                    bail!(
                        "Oneof value variants must have exactly one field, but variant \
                        {variant_ident} has {num_fields} fields",
                        variant_ident = variant.ident,
                        num_fields = fields.len()
                    );
                }
                let field = fields.first().unwrap();
                Ok(Some(OneofVariant {
                    tag,
                    variant_ident: variant.ident.clone(),
                    contents: VariantContents::Value(Box::new(FieldInVariant {
                        value: ValueField::new(&field.ty, other_attrs, "general_packed")?,
                        ident_within_variant: field
                            .ident
                            .as_ref()
                            .map(ToTokens::to_token_stream)
                            .unwrap_or_else(|| quote!(0)),
                    })),
                }))
            }

            // Message variant with missing tag
            (None, true, false) => {
                bail!(
                    "missing tag attribute on message variant {variant_ident}",
                    variant_ident = variant.ident,
                );
            }

            // Message variant
            (Some(tag), true, false) => {
                let mut reserved_tags: Option<TagList> = None;
                let mut unknown_attrs = vec![];
                for attr in &other_attrs {
                    if let Some(tags) = tag_list_attr(attr, "reserved_tags", None)? {
                        set_option_with_display(
                            &mut reserved_tags,
                            tags,
                            "duplicate reserved_tags attributes",
                            TagList::display,
                        )?;
                    } else {
                        unknown_attrs.push(attr);
                    }
                }

                if !unknown_attrs.is_empty() {
                    bail!(
                        "unknown or unsupported attribute(s) for message variant {variant_ident}: \
                        {attrs}",
                        variant_ident = variant.ident,
                        attrs = quote!(#(#unknown_attrs),*),
                    );
                }

                let variant_fields =
                    parse_message_fields(variant.fields, InitMode::DefaultPerField, reserved_tags)
                        .map_err(|e| {
                            err!(
                                "in message variant {variant_ident}: {e}",
                                variant_ident = variant.ident
                            )
                        })?;

                for field in &variant_fields {
                    if field.has_enumeration_type() {
                        bail!(
                            "in message variant {variant_ident} on field {field_ident}: \
                            enumeration helpers are not supported on messages embedded inside \
                            variants since variants can't have their own methods",
                            variant_ident = variant.ident,
                            field_ident = field.ident(),
                        );
                    }
                }

                Ok(Some(OneofVariant {
                    tag,
                    variant_ident: variant.ident,
                    contents: VariantContents::Message(variant_fields),
                }))
            }
        }
    }

    pub fn ident(&self) -> &Ident {
        &self.variant_ident
    }

    pub fn has_ignored_fields(&self) -> bool {
        matches!(
            &self.contents,
            VariantContents::Message(fields)
            if fields.iter().any(Field::is_ignored)
        )
    }

    /// Generates bindings to a message variant's non-ignored fields.
    fn binding(fields: &[Field]) -> TokenStream {
        let bindings = fields
            .iter()
            .filter(|field| !field.is_ignored())
            .map(|field| {
                let field_ident = field.ident();
                let binding_ident = FieldTarget::free_field_ident(field);
                quote!(#field_ident: #binding_ident)
            });
        quote! { #(#bindings,)* .. }
    }

    pub fn encode(&self, type_ident: impl ToTokens) -> TokenStream {
        let crate_ = crate_name();
        let tag = self.tag;
        let variant_ident = &self.variant_ident;
        match &self.contents {
            VariantContents::Value(field) => {
                let encoding = &field.value.encoding;
                let ty = &field.value.ty;
                let value_ident = &field.ident_within_variant;
                quote! {
                    #type_ident::#variant_ident { #value_ident: value } => {
                        <() as #crate_::encoding::FieldEncoder<#encoding, #ty>>::encode_field(
                            #tag,
                            &value,
                            buf,
                            tw,
                        );
                    }
                }
            }
            VariantContents::Message(fields) => {
                let binding = OneofVariant::binding(fields);
                let sorted_fields = MessageFieldsSorted::new_filtering_ignored(fields);
                let encoded_len = sorted_fields.encoded_len(&FieldTarget::BoundVariantFields);
                let encode = sorted_fields.encode(&FieldTarget::BoundVariantFields);
                quote! {
                    #type_ident::#variant_ident { #binding } => {
                        tw.encode_key(#tag, #crate_::encoding::WireType::LengthDelimited, buf);
                        // TODO: encoded_len here sorts the fields again; can we extract this as a
                        //  common function call? or sort the fields only once and scan twice?
                        #crate_::encoding::encode_varint(#encoded_len as u64, buf);
                        #encode
                    }
                }
            }
        }
    }

    pub fn prepend(&self, type_ident: impl ToTokens) -> TokenStream {
        let crate_ = crate_name();
        let tag = self.tag;
        let variant_ident = &self.variant_ident;
        match &self.contents {
            VariantContents::Value(field) => {
                let encoding = &field.value.encoding;
                let ty = &field.value.ty;
                let value_ident = &field.ident_within_variant;
                quote! {
                    #type_ident::#variant_ident { #value_ident: value } => {
                        <() as #crate_::encoding::FieldEncoder<#encoding, #ty>>::prepend_field(
                            #tag,
                            &value,
                            buf,
                            tw,
                        );
                    }
                }
            }
            VariantContents::Message(fields) => {
                let binding = OneofVariant::binding(fields);
                let prepend = MessageFieldsSorted::new_filtering_ignored(fields)
                    .prepend(&FieldTarget::BoundVariantFields);
                quote! {
                    #type_ident::#variant_ident { #binding } => {
                        tw.begin_field(#tag, #crate_::encoding::WireType::LengthDelimited, buf);
                        let end = buf.remaining();
                        #prepend
                        #crate_::encoding::prepend_varint((buf.remaining() - end) as u64, buf);
                    }
                }
            }
        }
    }

    pub fn encoded_len(&self, type_ident: impl ToTokens) -> TokenStream {
        let crate_ = crate_name();
        let tag = self.tag;
        let variant_ident = &self.variant_ident;
        match &self.contents {
            VariantContents::Value(field) => {
                let encoding = &field.value.encoding;
                let ty = &field.value.ty;
                let value_ident = &field.ident_within_variant;
                quote! {
                    #type_ident::#variant_ident { #value_ident: value } => {
                        <() as #crate_::encoding::FieldEncoder<#encoding, #ty>>::field_encoded_len(
                            #tag,
                            &value,
                            tm,
                        )
                    }
                }
            }
            VariantContents::Message(fields) => {
                let binding = OneofVariant::binding(fields);
                let encoded_len = MessageFieldsSorted::new_filtering_ignored(fields)
                    .encoded_len(&FieldTarget::BoundVariantFields);
                quote! {
                    #type_ident::#variant_ident { #binding } => {
                        let total = #encoded_len;
                        total
                            + #crate_::encoding::encoded_len_varint(total as u64)
                            + tm.key_len(#tag)
                    }
                }
            }
        }
    }

    /// Oneof decoders have four different cases they may be implemented in: implemented for either
    /// NonEmptyOneof or Oneof, and either relaxed or distinguished. The code for these should all
    /// be similarly deduplicated.
    pub fn decode(
        &self,
        type_ident: impl ToTokens,
        lifetime: DecodeLifetime,
        mode: DecodeMode,
    ) -> TokenStream {
        let tag = self.tag;
        let for_overwrite = self.for_overwrite();
        let decode = self.decode_fields(lifetime, mode);
        let construct = self.construct(type_ident);
        let (decode_result, output) = match mode {
            Relaxed => (quote!(()), construct),
            Distinguished => (quote!(canon), quote!((#construct, canon))),
        };
        // It's important that we spell the whole expression for the decoder matching for oneofs as
        // a single Result expression that never early-returns with `?`; that way when we add guards
        // to the Oneof trait impls (which have natural empty variants, a collision guard, and error
        // attribution) our clause that traces the error location will see every error that occurs,
        // including errors that bubble up from the inner decoders, and those error details can
        // still path down through the oneof variant.
        quote! {
            #tag => {
                #for_overwrite
                match #decode {
                    ::core::result::Result::Ok(#decode_result) => {
                        ::core::result::Result::Ok(#output)
                    },
                    ::core::result::Result::Err(error) => ::core::result::Result::Err(error),
                }
            }
        }
    }

    fn for_overwrite(&self) -> TokenStream {
        // TODO: can we clear the variant's field(s) instead if it's already known to be present?
        match &self.contents {
            VariantContents::Value(field) => {
                let crate_ = crate_name();
                let encoding = &field.value.encoding;
                let ty = &field.value.ty;
                quote! {
                    let mut value =
                        <() as #crate_::encoding::ForOverwrite<#encoding, #ty>>::for_overwrite();
                }
            }
            VariantContents::Message(fields) => {
                let empties = fields.iter().filter_map(|field| {
                    if field.is_ignored() {
                        return None; // we don't need mutable variables to parse ignored fields into
                    }
                    let field_ident = FieldTarget::free_field_ident(field);
                    let empty = field.empty(Some(self.tag));
                    Some(quote! { let mut #field_ident = #empty; })
                });
                quote! { #(#empties)* }
            }
        }
    }

    fn decode_fields(&self, lifetime: DecodeLifetime, mode: DecodeMode) -> TokenStream {
        let crate_ = crate_name();
        match &self.contents {
            VariantContents::Value(field) => {
                let encoding = &field.value.encoding;
                let ty = &field.value.ty;
                let (decoder_trait, call) = match (lifetime, mode) {
                    (Owned, Relaxed) => (quote!(FieldDecoder), quote!(decode_field)),
                    (Borrowed, Relaxed) => {
                        (quote!(FieldBorrowDecoder), quote!(borrow_decode_field))
                    }
                    (Owned, Distinguished) => (
                        quote!(DistinguishedFieldDecoder),
                        quote!(decode_field_distinguished::<true>), // empty values are ok
                    ),
                    (Borrowed, Distinguished) => (
                        quote!(DistinguishedFieldBorrowDecoder),
                        quote!(borrow_decode_field_distinguished::<true>), // empty values are ok
                    ),
                };
                quote!(
                    <() as #crate_::encoding::#decoder_trait<#encoding, #ty>>::#call(
                        wire_type,
                        &mut value,
                        buf,
                        ctx,
                    )
                )
            }
            VariantContents::Message(fields) => {
                let variant_ident_str = self.variant_ident.to_string();
                let field_arms: Vec<_> = fields
                    .iter()
                    .filter_map(|field| {
                        if field.is_ignored() {
                            return None;
                        }
                        let tags = field.tags().into_iter().map(|tag| quote!(#tag));
                        let tags = Itertools::intersperse(tags, quote!(|));
                        let decode = field.decode(&FieldTarget::FreeVariantFields, lifetime, mode);
                        let field_ident_str = field.ident.to_string();
                        Some(quote!(#(#tags)* => match #decode {
                            ::core::result::Result::Ok(res) => ::core::result::Result::Ok(res),
                            ::core::result::Result::Err(mut error) => {
                                error.push(#variant_ident_str, #field_ident_str);
                                ::core::result::Result::Err(error)
                            }
                        }))
                    })
                    .collect();
                let (
                    result_value,
                    result_init,
                    assign_result,
                    update_result,
                    update_result_unknown_field,
                ) = match mode {
                    Relaxed => (quote!(()), None, None, None, None),
                    Distinguished => (
                        quote!(canon),
                        Some(quote!(let mut canon = #crate_::Canonicity::Canonical;)),
                        Some(quote!(let new_canon = )),
                        Some(quote!(canon.update(new_canon);)),
                        Some(quote!(canon.update(ctx.check(#crate_::Canonicity::HasExtensions)?);)),
                    ),
                };
                quote! {
                    // The decoder is wrapped in an IIFE so that we can use the try operator inside.
                    // If we get try blocks in a later edition of rust we can use those
                    // conditionally instead.
                    (|| {
                        #crate_::encoding::check_wire_type(
                            #crate_::encoding::WireType::LengthDelimited, wire_type)?;
                        let mut outer_buf = buf;
                        // msg_buf is the delimited range of this sub-message
                        let mut msg_buf = outer_buf.take_length_delimited()?;
                        let tr = &mut #crate_::encoding::TagReader::new();
                        let mut last_tag = ::core::option::Option::None::<u32>;
                        #result_init
                        while msg_buf.has_remaining()? {
                            let (tag, wire_type) = tr.decode_key(msg_buf.lend())?;
                            let duplicated = last_tag == ::core::option::Option::Some(tag);
                            last_tag = ::core::option::Option::Some(tag);
                            // individual field decodes will move and consume `buf` and `ctx`,
                            // so we (cheaply) create copies of those values here
                            let buf = msg_buf.lend();
                            let ctx = ctx.clone();
                            #assign_result match tag {
                                #(#field_arms)*
                                _ => {
                                    #update_result_unknown_field
                                    #crate_::encoding::skip_field(wire_type, buf)?;
                                    ::core::result::Result::
                                        Ok::<_, #crate_::DecodeError>(#result_value)
                                },
                            }?;
                            #update_result
                        }
                        ::core::result::Result::Ok(#result_value)
                    })()
                }
            }
        }
    }

    fn construct(&self, type_ident: impl ToTokens) -> TokenStream {
        let variant_ident = &self.variant_ident;
        match &self.contents {
            VariantContents::Value(field) => {
                let value_ident = &field.ident_within_variant;
                quote!( #type_ident::#variant_ident { #value_ident: value } )
            }
            VariantContents::Message(fields) => {
                let field_inits = fields.iter().map(|field| {
                    let ident = field.ident();
                    // currently, oneof enums can only act as if they have default-per-field;
                    // there's no kind of trait behavior that can fill all the fields of the
                    // variant like `..Default::default()`, since that would require an impl on
                    // the variant itself. so, we will only ever initialize them on a per-field
                    // basis like this.
                    if field.is_ignored() {
                        let empty = field.empty(Some(self.tag));
                        quote!(#ident: #empty)
                    } else {
                        let free_ident = FieldTarget::free_field_ident(field);
                        quote!(#ident: #free_ident)
                    }
                });
                quote! {
                    #type_ident::#variant_ident { #(#field_inits,)* }
                }
            }
        }
    }

    /// All the `__BilrostInitializer` initializer methods for any ignored fields in this variant
    /// that need them.
    pub fn initializer_methods(&self) -> Vec<TokenStream> {
        if let VariantContents::Message(fields) = &self.contents {
            fields
                .iter()
                .flat_map(|field| field.initializer_method(Some(self.tag)))
                .collect()
        } else {
            vec![]
        }
    }
}

impl FieldBearer for OneofVariant {
    fn where_terms(&self, purpose: WhereFor) -> Vec<TokenStream> {
        match &self.contents {
            VariantContents::Value(field) => field.where_terms(purpose),
            VariantContents::Message(fields) => fields.where_terms(purpose),
        }
    }
}

impl SinglyTagged for OneofVariant {
    fn tag(&self) -> u32 {
        self.tag
    }
}

/// Oneof encoding & decoding bounds for value-variants, which have trivial presence
/// information and must always embed as a single real field and thus need the
/// "value encoder/decoder" traits.
impl FieldBearer for FieldInVariant {
    fn where_terms(&self, purpose: WhereFor) -> Vec<TokenStream> {
        let crate_ = crate_name();
        if self.value.recurses {
            return vec![]; // don't generate constraints for this (sub-)field
        }
        let ty = &self.value.ty;
        let encoding = &self.value.encoding;
        vec![
            match purpose {
                Encode => quote!((): #crate_::encoding::ValueEncoder<#encoding, #ty>),
                Decode(Owned, Relaxed) => {
                    quote!((): #crate_::encoding::ValueDecoder<#encoding, #ty>)
                }
                Decode(Borrowed, Relaxed) => {
                    quote!((): #crate_::encoding::ValueBorrowDecoder<'__a, #encoding, #ty>)
                }
                Decode(Owned, Distinguished) => {
                    quote!((): #crate_::encoding::DistinguishedValueDecoder<#encoding, #ty>)
                }
                Decode(Borrowed, Distinguished) => {
                    quote!(
                        (): #crate_::encoding::
                            DistinguishedValueBorrowDecoder<'__a, #encoding, #ty>
                    )
                }
            },
            // Encoding or decoding a oneof field always has trivially externally determined
            // presence, and we never need to know whether or not the value is empty; it never
            // needs to implement the empty state.
            quote!((): #crate_::encoding::ForOverwrite<#encoding, #ty>),
        ]
    }
}