reallyme-buffa-codegen 0.1.2

ReallyMe fork: 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
//! The table codec: one static `buffa::table::Table` per message and a
//! `Message` impl that forwards to the interpreters in `buffa::table`.
//!
//! Which messages get one is decided by [`crate::table_plan`]; this module
//! emits the code for a message the plan selected.

use std::collections::{BTreeMap, HashMap, HashSet};

use proc_macro2::TokenStream;
use quote::{format_ident, quote};

use crate::context::{ancillary_prefix, AncillaryKind, MessageScope};
use crate::generated::descriptor::field_descriptor_proto::Type;
use crate::generated::descriptor::{DescriptorProto, FieldDescriptorProto};
use crate::idents::rust_path_to_tokens;
use crate::message::classify_field;
use crate::table_plan::{
    table_fields, type_stem, Card, MapField, OneofMembership, PlainField, Shape, TableField,
};
use crate::CodeGenError;

/// The name of the static table of the message struct `rust_name`.
fn table_ident(rust_name: &str) -> proc_macro2::Ident {
    format_ident!("__BUFFA_TABLE_{}", rust_name)
}

/// The path of the static table of the message type whose struct is at
/// `type_path`: the last segment is replaced by the table's name.
fn table_path(type_path: &str) -> Result<TokenStream, CodeGenError> {
    if type_path.starts_with("::") || type_path.starts_with("crate::") {
        return Err(CodeGenError::Other(format!(
            "table codec: message type `{type_path}` is generated by another crate, \
             so it has no table here"
        )));
    }
    let (head, last) = match type_path.rsplit_once("::") {
        Some((head, last)) => (format!("{head}::"), last),
        None => (String::new(), type_path),
    };
    Ok(rust_path_to_tokens(&format!("{head}__BUFFA_TABLE_{last}")))
}

/// The table ABI this generator emits, which `buffa::table::ABI` must equal
/// for the generated tables to build. Bump both when the meaning of an existing
/// table entry changes.
pub(crate) const TABLE_ABI: u32 = 1;

/// The static table and `impl Message` of a message the plan selected.
///
/// # Errors
///
/// Returns an error if the message cannot use the table, which the plan
/// should have ruled out.
pub(crate) fn generate_table_impl(
    scope: MessageScope<'_>,
    msg: &DescriptorProto,
    rust_name: &str,
    resolver: &crate::imports::ImportResolver,
) -> Result<TokenStream, CodeGenError> {
    let MessageScope {
        ctx,
        proto_fqn,
        features,
        ..
    } = scope;
    let name = format_ident!("{}", rust_name);
    let table = table_ident(rust_name);
    let dotted_fqn = format!(".{proto_fqn}");
    let deprecated_field_allow = crate::message::deprecated_field_allow(ctx, msg, proto_fqn);

    let fields = table_fields(ctx, msg, &dotted_fqn, features).map_err(|why| {
        CodeGenError::Other(format!(
            "table codec: {dotted_fqn} cannot use the table: {}",
            why.detail
        ))
    })?;

    let mut entries: Vec<TokenStream> = Vec::with_capacity(fields.len());
    let mut aux: Vec<TokenStream> = Vec::new();
    let mut oneofs = Oneofs::new(scope, msg, &fields)?;
    for f in &fields {
        if let Shape::Plain(
            plain @ PlainField {
                oneof: Some(member),
                ..
            },
        ) = &f.shape
        {
            entries.push(oneofs.member_entry(scope, &name, f, plain, member, &mut aux)?);
            continue;
        }
        let (entry, aux_item) = field_entry(scope, msg, &name, f, aux.len(), resolver)?;
        entries.push(entry);
        aux.extend(aux_item);
    }
    let oneof_impls = oneofs.into_impls();

    let dense = dense_lookup(&fields, &dotted_fqn)?;
    let abi = proc_macro2::Literal::u32_unsuffixed(TABLE_ABI);

    let unknown = if ctx.preserve_unknown_fields(proto_fqn) {
        quote! { __buffa_unknown_fields }
    } else {
        quote! { none }
    };

    Ok(quote! {
        #[doc(hidden)]
        #[allow(non_upper_case_globals)]
        #deprecated_field_allow
        pub(crate) static #table: ::buffa::table::Table<#name> = ::buffa::__table!(
            #name,
            abi = #abi,
            entries = [#(#entries),*],
            dense = &[#(#dense),*],
            aux = [#(#aux),*],
            unknown = #unknown,
        );

        impl ::buffa::Message for #name {
            fn compute_size(&self, cache: &mut ::buffa::SizeCache) -> u32 {
                #table.compute_size(self, cache)
            }

            fn write_to(&self, cache: &mut ::buffa::SizeCache, buf: &mut impl ::buffa::EncodeSink) {
                #table.write_to(self, cache, buf);
            }

            fn merge_field(
                &mut self,
                tag: ::buffa::encoding::Tag,
                buf: &mut impl ::buffa::bytes::Buf,
                ctx: ::buffa::DecodeContext<'_>,
            ) -> ::core::result::Result<(), ::buffa::DecodeError> {
                #table.merge_field(self, tag, buf, ctx)
            }

            fn merge_to_limit(
                &mut self,
                buf: &mut impl ::buffa::bytes::Buf,
                ctx: ::buffa::DecodeContext<'_>,
                limit: usize,
            ) -> ::core::result::Result<(), ::buffa::DecodeError> {
                #table.merge_to_limit(self, buf, ctx, limit)
            }

            fn merge_length_delimited(
                &mut self,
                buf: &mut impl ::buffa::bytes::Buf,
                ctx: ::buffa::DecodeContext<'_>,
            ) -> ::core::result::Result<(), ::buffa::DecodeError> {
                #table.merge_length_delimited(self, buf, ctx)
            }

            fn clear(&mut self) {
                *self = ::core::default::Default::default();
            }
        }

        #(#oneof_impls)*
    })
}

/// `dense[n]` is one plus the index of the field numbered `n`, or `0`, for
/// the numbers up to the highest field number below 64.
///
/// Entries are sorted by field number, and protobuf field numbers start at
/// one, so when the numbers are distinct a field numbered below 64 is among
/// the first 63 entries. Its one-based index therefore fits in `u8` whatever
/// the total number of fields.
///
/// # Errors
///
/// Returns an error if the one-based index of a field numbered below 64 does
/// not fit in `u8`, which takes a message whose field numbers repeat.
/// `generate` rejects such a message before the table plan
/// ([`CodeGenError::DuplicateFieldNumber`]), so this is a backstop.
fn dense_lookup(fields: &[TableField<'_>], dotted_fqn: &str) -> Result<Vec<u8>, CodeGenError> {
    let top = fields
        .iter()
        .map(|f| f.number)
        .filter(|&n| n < 64)
        .max()
        .unwrap_or(0) as usize;
    let mut dense = vec![0u8; top + 1];
    for (i, f) in fields.iter().enumerate() {
        if let Some(slot) = dense.get_mut(f.number as usize) {
            // Distinct field numbers put a field numbered below 64 among the
            // first 63 sorted entries.
            *slot = u8::try_from(i + 1).map_err(|_| {
                CodeGenError::Other(format!(
                    "table codec: {dotted_fqn} has more than 255 fields numbered {} or \
                     lower, so its field numbers are not distinct",
                    f.number
                ))
            })?;
        }
    }
    Ok(dense)
}

/// The `__table_entry!` for one field, and the aux descriptor it needs, which
/// goes at index `aux_index` of the table's aux array.
fn field_entry(
    scope: MessageScope<'_>,
    msg: &DescriptorProto,
    name: &proc_macro2::Ident,
    f: &TableField<'_>,
    aux_index: usize,
    resolver: &crate::imports::ImportResolver,
) -> Result<(TokenStream, Option<TokenStream>), CodeGenError> {
    let MessageScope { ctx, .. } = scope;
    let field = f.field;
    let field_name = field.name.as_deref().unwrap_or("");
    let ident = ctx.field_ident(field_name, field.number.unwrap_or(0));
    let number = f.number;

    let aux_u16 = || u16::try_from(aux_index).map_err(|_| too_many_descriptors(scope));
    let type_path = |what: &str| type_path(scope, field, what);
    let unshortened_path = || unshortened_path(scope, field);
    let type_name = || field_type_name(field);

    let plain = match &f.shape {
        Shape::Map(map) => {
            let aux = aux_u16()?;
            let map_ty = classify_field(scope, msg, field, resolver)?.rust_type;
            let vt = map_descriptor(scope, &map_ty, map)?;
            return Ok((
                quote! {
                    ::buffa::__table_entry!(#name, #ident, Map, #number, aux = #aux, slot = #map_ty)
                },
                Some(quote! { ::buffa::table::Aux::Map(&#vt) }),
            ));
        }
        Shape::Plain(plain) => plain,
    };
    let kind = format_ident!("{}", plain.kind);

    match plain.ty {
        Type::TYPE_MESSAGE => {
            let child = type_path("message")?;
            let child_ty = rust_path_to_tokens(&child);
            // A child without a table here is reached through its `Message`
            // impl.
            let child_table = if ctx.uses_table_codec(type_name()?) {
                Some(table_path(&unshortened_path()?)?)
            } else {
                None
            };
            let (slot, aux_item) = if plain.card == Card::Repeated {
                let vt = match &child_table {
                    Some(table) => quote! { ::buffa::table::RepVt::new::<#child_ty>(&#table) },
                    None => quote! { ::buffa::table::RepVt::new_via_message::<#child_ty>() },
                };
                (
                    quote! { ::buffa::alloc::vec::Vec<#child_ty> },
                    quote! { ::buffa::table::Aux::Rep(&#vt) },
                )
            } else {
                let slot = classify_field(scope, msg, field, resolver)?.rust_type;
                let vt = match &child_table {
                    Some(table) => quote! { ::buffa::table::MsgVt::new::<#slot>(&#table) },
                    None => quote! { ::buffa::table::MsgVt::new_via_message::<#slot>() },
                };
                (slot, quote! { ::buffa::table::Aux::Msg(&#vt) })
            };
            let aux = aux_u16()?;
            Ok((
                quote! {
                    ::buffa::__table_entry!(#name, #ident, #kind, #number, aux = #aux, slot = #slot)
                },
                Some(aux_item),
            ))
        }
        Type::TYPE_ENUM => {
            let enum_ty = rust_path_to_tokens(&type_path("enum")?);
            let repeated = matches!(plain.card, Card::Repeated | Card::Packed);
            let shape = match (repeated, plain.card == Card::Optional, plain.closed_enum) {
                (true, _, true) => quote! { RepeatedClosed },
                (true, _, false) => quote! { RepeatedOpen },
                (false, true, true) => quote! { OptionalClosed },
                (false, true, false) => quote! { OptionalOpen },
                (false, false, true) => quote! { ImplicitClosed },
                (false, false, false) => quote! { ImplicitOpen },
            };
            let shape = quote! { ::buffa::table::#shape<#enum_ty> };
            let aux = aux_u16()?;
            Ok((
                quote! {
                    ::buffa::__table_entry!(
                        #name, #ident, #kind, #number,
                        aux = #aux,
                        slot = <#shape as ::buffa::table::EnumShape>::Slot
                    )
                },
                Some(quote! {
                    ::buffa::table::Aux::Enum(&::buffa::table::EnumVt::new::<#shape>())
                }),
            ))
        }
        _ => Ok((
            quote! { ::buffa::__table_entry!(#name, #ident, #kind, #number) },
            None,
        )),
    }
}

/// The `MapVt` expression for the map field of Rust type `map_ty`.
fn map_descriptor(
    scope: MessageScope<'_>,
    map_ty: &TokenStream,
    map: &MapField<'_>,
) -> Result<TokenStream, CodeGenError> {
    let marker = |ty: Type, slot: &str| -> Result<TokenStream, CodeGenError> {
        match type_stem(ty, Card::Required) {
            Some(stem) if !matches!(ty, Type::TYPE_ENUM | Type::TYPE_MESSAGE) => {
                let kind = format_ident!("{}Required", stem);
                Ok(quote! { ::buffa::table::kinds::#kind })
            }
            _ => Err(CodeGenError::Other(format!(
                "table codec: a map {slot} of type {ty:?} has no scalar kind"
            ))),
        }
    };
    let key = marker(map.key_ty, "key")?;
    Ok(match map.val_ty {
        Type::TYPE_ENUM => {
            let enum_ty = rust_path_to_tokens(&type_path(scope, map.val_field, "enum")?);
            let shape = if map.closed_enum {
                quote! { ImplicitClosed }
            } else {
                quote! { ImplicitOpen }
            };
            quote! {
                ::buffa::table::MapVt::with_enum::<#map_ty, #key, ::buffa::table::#shape<#enum_ty>>()
            }
        }
        Type::TYPE_MESSAGE => {
            let child = rust_path_to_tokens(&type_path(scope, map.val_field, "message")?);
            // A value without a table here is reached through its `Message`
            // impl.
            let msg_vt = if scope.ctx.uses_table_codec(field_type_name(map.val_field)?) {
                let child_table = table_path(&unshortened_path(scope, map.val_field)?)?;
                quote! { ::buffa::table::DirectMsgVt::new(&#child_table) }
            } else {
                quote! { ::buffa::table::DirectMsgVt::<#child>::via_message() }
            };
            quote! {
                ::buffa::table::MapVt::with_msg::<#map_ty, #key, #child>(&#msg_vt)
            }
        }
        ty => {
            let value = marker(ty, "value")?;
            quote! { ::buffa::table::MapVt::new::<#map_ty, #key, #value>() }
        }
    })
}

/// The proto path of the message or enum type of `field`.
fn field_type_name(field: &FieldDescriptorProto) -> Result<&str, CodeGenError> {
    field
        .type_name
        .as_deref()
        .ok_or(CodeGenError::MissingField("field.type_name"))
}

/// The error for a message whose table needs more descriptors than an aux
/// index can name.
fn too_many_descriptors(scope: MessageScope<'_>) -> CodeGenError {
    CodeGenError::Other(format!(
        "table codec: {}: a message has more than 65535 fields that need a descriptor",
        scope.proto_fqn
    ))
}

/// The Rust path of the message or enum type of `field`, as seen from the
/// message's scope. `what` names the kind of type in the error.
fn type_path(
    scope: MessageScope<'_>,
    field: &FieldDescriptorProto,
    what: &str,
) -> Result<String, CodeGenError> {
    let type_name = field_type_name(field)?;
    scope
        .ctx
        .rust_type_relative(type_name, scope.current_package, scope.nesting)
        .ok_or_else(|| CodeGenError::Other(format!("{what} type '{type_name}' not found")))
}

/// The path of the message type of `field` before `idiomatic_imports` shortens
/// it. The table is not among the names that `idiomatic_imports` shortens, so
/// its path is built from this one.
fn unshortened_path(
    scope: MessageScope<'_>,
    field: &FieldDescriptorProto,
) -> Result<String, CodeGenError> {
    let type_name = field_type_name(field)?;
    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")))?;
    Ok(if split.to_package.is_empty() {
        split.within_package
    } else {
        format!("{}::{}", split.to_package, split.within_package)
    })
}

/// The match arms of the `OneofEnum` implementation of one oneof enum.
#[derive(Default)]
struct OneofArms {
    number: Vec<TokenStream>,
    payload: Vec<TokenStream>,
    payload_mut: Vec<TokenStream>,
    with_default: Vec<TokenStream>,
}

/// The oneofs of the message being generated: the table entries and aux items
/// of their members, and the `OneofEnum` implementations that the interpreters
/// reach the members through.
struct Oneofs {
    /// The path of the oneof enums' module, from the message's scope.
    prefix: TokenStream,
    /// The Rust names of the oneof enums, by the oneof's index in the message.
    enum_idents: HashMap<usize, proc_macro2::Ident>,
    /// The lowest member number of each oneof.
    first: HashMap<usize, u32>,
    /// The oneofs that have a member of message type.
    with_messages: HashSet<usize>,
    /// The aux index of each oneof's descriptor, once it has one.
    group_aux: HashMap<usize, usize>,
    /// The aux index of each payload descriptor, by its tokens, so that
    /// members with the same kind of value share one.
    payload_aux: HashMap<String, usize>,
    arms: BTreeMap<usize, OneofArms>,
}

impl Oneofs {
    fn new(
        scope: MessageScope<'_>,
        msg: &DescriptorProto,
        fields: &[TableField<'_>],
    ) -> Result<Self, CodeGenError> {
        let mut first: HashMap<usize, u32> = HashMap::new();
        let mut with_messages = HashSet::new();
        for (oneof, f, plain) in fields.iter().filter_map(|f| match &f.shape {
            Shape::Plain(plain) => plain.oneof.as_ref().map(|oneof| (oneof, f, plain)),
            Shape::Map(_) => None,
        }) {
            let lowest = first.entry(oneof.index).or_insert(f.number);
            *lowest = (*lowest).min(f.number);
            if plain.ty == Type::TYPE_MESSAGE {
                with_messages.insert(oneof.index);
            }
        }
        Ok(Self {
            prefix: ancillary_prefix(
                scope.ctx,
                AncillaryKind::Oneof,
                scope.current_package,
                scope.proto_fqn,
                scope.nesting,
            ),
            enum_idents: crate::oneof::resolve_oneof_idents(msg, scope.proto_fqn)?,
            first,
            with_messages,
            group_aux: HashMap::new(),
            payload_aux: HashMap::new(),
            arms: BTreeMap::new(),
        })
    }

    /// Add `item` to `aux`, or find where the same item already is.
    fn shared_aux(&mut self, aux: &mut Vec<TokenStream>, item: TokenStream) -> usize {
        *self.payload_aux.entry(item.to_string()).or_insert_with(|| {
            aux.push(item);
            aux.len() - 1
        })
    }

    /// The `__table_entry!` of one oneof member, and the aux items it needs
    /// (its oneof's descriptor if this is the first member met, the
    /// descriptor of its value if the kind of value has one, and the member
    /// item itself), which are pushed to `aux`. Records the member's arms of
    /// the enum's implementation.
    fn member_entry(
        &mut self,
        scope: MessageScope<'_>,
        message: &proc_macro2::Ident,
        f: &TableField<'_>,
        plain: &PlainField<'_>,
        member: &OneofMembership<'_>,
        aux: &mut Vec<TokenStream>,
    ) -> Result<TokenStream, CodeGenError> {
        let ctx = scope.ctx;
        let field = f.field;
        let field_name = field.name.as_deref().unwrap_or("");
        let too_many = || too_many_descriptors(scope);
        let enum_ident = self.enum_idents.get(&member.index).ok_or_else(|| {
            CodeGenError::Other(format!(
                "table codec: {}.{field_name}: the oneof `{}` has no enum",
                scope.proto_fqn, member.name
            ))
        })?;
        let prefix = &self.prefix;
        let enum_path = quote! { #prefix #enum_ident };
        let oneof_field = ctx.oneof_ident(member.name);
        let variant = crate::oneof::oneof_variant_ident(field_name);
        let number = f.number;
        let payload_kind = format_ident!("{}", plain.kind);
        let first = self.first[&member.index];

        // The oneof's descriptor, made when its first member is met.
        let group = match self.group_aux.get(&member.index) {
            Some(&group) => group,
            None => {
                let ctor = if self.with_messages.contains(&member.index) {
                    format_ident!("with_messages")
                } else {
                    format_ident!("new")
                };
                aux.push(quote! {
                    ::buffa::table::Aux::Group(&::buffa::table::OneofVt::#ctor::<#enum_path>(
                        ::buffa::table::offset_of!(#message, #oneof_field),
                        #first,
                    ))
                });
                self.group_aux.insert(member.index, aux.len() - 1);
                aux.len() - 1
            }
        };

        // What the member's value is: the type the accessors give a pointer
        // to, the descriptor of the value, and the value a member has when it
        // is first set.
        let variant_fqn = format!(".{}.{}.{field_name}", scope.proto_fqn, member.name);
        let default = quote! { ::core::default::Default::default() };
        let (slot, value_aux, new) = match plain.ty {
            Type::TYPE_MESSAGE => {
                let child = rust_path_to_tokens(&type_path(scope, field, "message")?);
                // A child without a table here is reached through its
                // `Message` impl.
                let msg_vt = if ctx.uses_table_codec(field_type_name(field)?) {
                    let child_table = table_path(&unshortened_path(scope, field)?)?;
                    quote! { ::buffa::table::MsgVt::direct::<#child>(&#child_table) }
                } else {
                    quote! { ::buffa::table::MsgVt::direct_via_message::<#child>() }
                };
                let new = if crate::oneof::variant_boxed(ctx, plain.ty, &variant_fqn) {
                    match ctx.pointer_repr(&variant_fqn) {
                        crate::PointerRepr::Box => quote! { ::buffa::alloc::boxed::Box::default() },
                        repr => repr.pointer_new(&child, &default)?,
                    }
                } else {
                    default
                };
                (
                    child,
                    Some(quote! { ::buffa::table::Aux::Msg(&#msg_vt) }),
                    new,
                )
            }
            Type::TYPE_ENUM => {
                let enum_ty = rust_path_to_tokens(&type_path(scope, field, "enum")?);
                let shape = if plain.closed_enum {
                    quote! { ::buffa::table::ImplicitClosed<#enum_ty> }
                } else {
                    quote! { ::buffa::table::ImplicitOpen<#enum_ty> }
                };
                (
                    quote! { <#shape as ::buffa::table::EnumShape>::Slot },
                    Some(
                        quote! { ::buffa::table::Aux::Enum(&::buffa::table::EnumVt::new::<#shape>()) },
                    ),
                    default,
                )
            }
            _ => (
                quote! { <::buffa::table::kinds::#payload_kind as ::buffa::table::KindSlot>::Slot },
                None,
                default,
            ),
        };
        let value_aux = value_aux.map_or(Ok(0), |item| {
            u16::try_from(self.shared_aux(aux, item)).map_err(|_| too_many())
        })?;

        let arms = self.arms.entry(member.index).or_default();
        arms.number.push(quote! { Self::#variant(_) => #number, });
        // The pointers come from references of the type `slot`, so a variant of
        // another type does not compile (a boxed message coerces to its
        // message). They are coerced and not cast, which `trivial_casts`
        // would flag, and `ptr::from_ref` needs a Rust newer than the MSRV of
        // some crates that build this code.
        arms.payload.push(quote! {
            Self::#variant(v) => {
                let value: &#slot = v;
                let ptr: *const #slot = value;
                ptr.cast::<u8>()
            }
        });
        arms.payload_mut.push(quote! {
            Self::#variant(v) => {
                let value: &mut #slot = v;
                let ptr: *mut #slot = value;
                ptr.cast::<u8>()
            }
        });
        arms.with_default
            .push(quote! { #number => ::core::option::Option::Some(Self::#variant(#new)), });

        let leader = number == first;
        let group = u16::try_from(group).map_err(|_| too_many())?;
        aux.push(quote! {
            ::buffa::table::Aux::Member(::buffa::table::Member::new(
                #group,
                ::buffa::table::Kind::#payload_kind,
                #value_aux,
            ))
        });
        let member_aux = u16::try_from(aux.len() - 1).map_err(|_| too_many())?;
        Ok(quote! {
            ::buffa::__table_entry!(
                #message, #oneof_field, oneof(#payload_kind, #leader), #number,
                aux = #member_aux,
                slot = ::core::option::Option<#enum_path>
            )
        })
    }

    /// The `OneofEnum` implementation of every oneof enum that had a member.
    fn into_impls(self) -> Vec<TokenStream> {
        let prefix = self.prefix;
        self.arms
            .into_iter()
            .map(|(index, arms)| {
                let enum_ident = &self.enum_idents[&index];
                let OneofArms {
                    number,
                    payload,
                    payload_mut,
                    with_default,
                } = arms;
                quote! {
                    impl ::buffa::table::OneofEnum for #prefix #enum_ident {
                        fn number(&self) -> u32 {
                            match self {
                                #(#number)*
                            }
                        }

                        fn payload(&self) -> *const u8 {
                            match self {
                                #(#payload)*
                            }
                        }

                        fn payload_mut(&mut self) -> *mut u8 {
                            match self {
                                #(#payload_mut)*
                            }
                        }

                        fn with_default(number: u32) -> ::core::option::Option<Self> {
                            match number {
                                #(#with_default)*
                                _ => ::core::option::Option::None,
                            }
                        }
                    }
                }
            })
            .collect()
    }
}