reallyme-buffa-codegen 0.1.0

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
// Modified by ReallyMe Technologies Limited.
//! Code generation for vtable-mode reflection on view types.
//!
//! When [`CodeGenConfig::generate_reflection`](crate::CodeGenConfig::generate_reflection)
//! and the internal `generate_reflection_vtable` flag are both set, each
//! generated view type gets:
//!
//! - `impl ::buffa_descriptor::reflect::ReflectMessage for FooView<'a>` — a
//!   zero-copy reflective accessor that reads struct fields directly, with no
//!   encode/decode round-trip and no `DynamicMessage`.
//! - `impl ::buffa_descriptor::reflect::ReflectElement for FooView<'a>` — so a
//!   `RepeatedView`/`MapView` of this message reflects through the generic
//!   container impls in `buffa-descriptor` (see that crate's `reflect::view`).
//! - A memoized per-message `MessageIndex` accessor.
//!
//! The bridge-mode `Reflectable` impl (on the owned message) is emitted
//! separately by [`reflect`](crate::reflect) and is unaffected; the
//! `Reflectable::reflect()` body switch to borrow the view directly is wired in
//! a later change. This module only adds the `ReflectMessage` surface.

use std::collections::HashMap;

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

use crate::context::{CodeGenContext, MessageScope, SENTINEL_MOD};
use crate::features::resolve_field;
use crate::generated::descriptor::field_descriptor_proto::{Label, Type};
use crate::generated::descriptor::{DescriptorProto, FieldDescriptorProto};
use crate::idents::make_field_ident;
use crate::impl_message::{
    effective_type, is_explicit_presence_scalar, is_real_oneof_member, is_required_field,
    is_supported_field_type,
};
use crate::message::{is_closed_enum, is_map_field};
use crate::oneof::oneof_variant_ident;
use crate::view::resolve_view_ty_tokens;
use crate::CodeGenError;

/// The `ValueRef` scalar variant for a wire-numeric proto type.
///
/// Mirrors the wire form, matching `DynamicMessage`: `int32`/`sint32`/`sfixed32`
/// all map to `I32`, etc. String, bytes, enum, and message types are handled by
/// the callers, not here.
pub(crate) fn scalar_variant(ty: Type) -> TokenStream {
    match ty {
        Type::TYPE_INT32 | Type::TYPE_SINT32 | Type::TYPE_SFIXED32 => quote! { I32 },
        Type::TYPE_INT64 | Type::TYPE_SINT64 | Type::TYPE_SFIXED64 => quote! { I64 },
        Type::TYPE_UINT32 | Type::TYPE_FIXED32 => quote! { U32 },
        Type::TYPE_UINT64 | Type::TYPE_FIXED64 => quote! { U64 },
        Type::TYPE_BOOL => quote! { Bool },
        Type::TYPE_FLOAT => quote! { F32 },
        Type::TYPE_DOUBLE => quote! { F64 },
        // Non-scalar types never reach this helper.
        _ => quote! { Bool },
    }
}

/// The default literal for a wire-numeric proto type (`0`, `0.0`, or `false`).
pub(crate) fn scalar_default(ty: Type) -> TokenStream {
    match ty {
        Type::TYPE_BOOL => quote! { false },
        Type::TYPE_FLOAT | Type::TYPE_DOUBLE => quote! { 0.0 },
        _ => quote! { 0 },
    }
}

/// The number an absent enum field reads as: the enum's first declared value.
/// A descriptor-driven `DynamicMessage` returns the same number.
pub(crate) fn enum_default_number(
    ctx: &CodeGenContext,
    field: &FieldDescriptorProto,
    current_package: &str,
    nesting: usize,
) -> Result<TokenStream, CodeGenError> {
    let type_name = field
        .type_name
        .as_deref()
        .ok_or(CodeGenError::MissingField("field.type_name"))?;
    let first = crate::defaults::enum_first_value_expr(ctx, type_name, current_package, nesting)?;
    Ok(quote! { ::buffa::Enumeration::to_i32(&#first) })
}

/// Generate the vtable reflection impls for a single view type.
///
/// `view_scope` is the view struct's scope (`nesting + 2` below the package
/// root). `view_depth` is that same depth, used to climb back to the package
/// root for the `__buffa::reflect::descriptor_pool()` accessor. `oneof_idents`
/// and `view_oneof_prefix` come from the view-struct generation so oneof
/// members dispatch through the same view-oneof enum.
pub(crate) fn reflect_view_impls(
    view_scope: MessageScope<'_>,
    msg: &DescriptorProto,
    view_ident: &proc_macro2::Ident,
    view_depth: usize,
    view_oneof_prefix: &TokenStream,
    oneof_idents: &HashMap<usize, proc_macro2::Ident>,
) -> Result<TokenStream, CodeGenError> {
    let MessageScope { ctx, .. } = view_scope;
    let features = view_scope.features;
    let guarded = ctx.zeroizes_message(view_scope.proto_fqn);
    let vr = if guarded {
        quote! { ::buffa_descriptor::reflect::InspectValueRef }
    } else {
        quote! { ::buffa_descriptor::reflect::ValueRef }
    };
    let cow = if guarded {
        quote! { ::buffa_descriptor::reflect::InspectMessageRef }
    } else {
        quote! { ::buffa_descriptor::reflect::ReflectCow }
    };

    let mut get_arms: Vec<TokenStream> = Vec::new();
    let mut has_arms: Vec<TokenStream> = Vec::new();

    // Direct (non-oneof) fields.
    for field in &msg.field {
        if is_real_oneof_member(field) {
            continue;
        }
        let ty = effective_type(ctx, field, features);
        if !is_supported_field_type(ty) {
            continue;
        }
        let name = field
            .name
            .as_deref()
            .ok_or(CodeGenError::MissingField("field.name"))?;
        let id = ctx.field_ident(name, field.number.unwrap_or(0));
        // `FieldDescriptor::number()` (matched on below) returns `u32`; proto
        // field numbers are always positive.
        let number = field.number.unwrap_or(0) as u32;
        let is_repeated = field.label.unwrap_or_default() == Label::LABEL_REPEATED;

        if is_repeated && is_map_field(msg, field) {
            get_arms.push(quote! { #number => #vr::Map(&self.#id), });
            has_arms.push(if guarded {
                quote! { #number => !self.#id.is_empty(), }
            } else {
                quote! { #number => !::buffa::MapView::is_empty(&self.#id), }
            });
            continue;
        }
        if is_repeated {
            get_arms.push(quote! { #number => #vr::List(&self.#id), });
            has_arms.push(if guarded {
                quote! { #number => !self.#id.is_empty(), }
            } else {
                quote! { #number => !::buffa::RepeatedView::is_empty(&self.#id), }
            });
            continue;
        }

        let f_features = resolve_field(ctx, field, features);
        let (get_val, has_val) = if is_explicit_presence_scalar(field, ty, &f_features) {
            // Stored as `Option<T>`; absent singular returns the type default.
            match ty {
                Type::TYPE_STRING => (
                    quote! { #vr::String(self.#id.unwrap_or("")) },
                    quote! { self.#id.is_some() },
                ),
                Type::TYPE_BYTES => (
                    quote! { #vr::Bytes(self.#id.unwrap_or(&[])) },
                    quote! { self.#id.is_some() },
                ),
                Type::TYPE_ENUM => {
                    let default = enum_default_number(
                        ctx,
                        field,
                        view_scope.current_package,
                        view_scope.nesting,
                    )?;
                    (
                        quote! {
                            #vr::EnumNumber(self.#id.map_or_else(|| #default, |e| e.to_i32()))
                        },
                        quote! { self.#id.is_some() },
                    )
                }
                _ => {
                    let variant = scalar_variant(ty);
                    let def = scalar_default(ty);
                    (
                        quote! { #vr::#variant(self.#id.unwrap_or(#def)) },
                        quote! { self.#id.is_some() },
                    )
                }
            }
        } else {
            // Implicit presence: absent is the default value, present is
            // non-default. proto2 `required` fields also fall here (they are
            // stored as bare types, not `Option`); their `has()` is overridden
            // below to consult the view's wire-presence tracking.
            match ty {
                Type::TYPE_STRING => (
                    quote! { #vr::String(self.#id) },
                    quote! { !self.#id.is_empty() },
                ),
                Type::TYPE_BYTES => (
                    quote! { #vr::Bytes(self.#id) },
                    quote! { !self.#id.is_empty() },
                ),
                Type::TYPE_MESSAGE | Type::TYPE_GROUP => (
                    // `MessageFieldView` derefs to the inner view, or the static
                    // default instance when unset — so the borrow is always
                    // valid and absent fields read as the empty message.
                    quote! { #vr::Message(#cow::Borrowed(&*self.#id)) },
                    quote! { self.#id.is_set() },
                ),
                Type::TYPE_ENUM => {
                    // A closed enum's default need not be zero (editions allows
                    // a non-zero first value), so "non-default" compares against
                    // the type default rather than `to_i32() != 0`. Open enums
                    // (`EnumValue`) always default to the zero wire value.
                    let has_val = if is_closed_enum(&f_features) {
                        quote! { self.#id != ::core::default::Default::default() }
                    } else {
                        quote! { self.#id.to_i32() != 0 }
                    };
                    (quote! { #vr::EnumNumber(self.#id.to_i32()) }, has_val)
                }
                _ => {
                    let variant = scalar_variant(ty);
                    let has_val = match ty {
                        Type::TYPE_BOOL => quote! { self.#id },
                        // By bit pattern, so `-0.0` and NaN are set, as in the
                        // encoder's `is_non_default_expr`.
                        Type::TYPE_FLOAT | Type::TYPE_DOUBLE => {
                            quote! { self.#id.to_bits() != 0 }
                        }
                        _ => quote! { self.#id != 0 },
                    };
                    (quote! { #vr::#variant(self.#id) }, has_val)
                }
            }
        };
        // Required fields (#170): the view records wire presence (seen-bit
        // words / `is_set`), surfaced by the generated `has_*` accessor —
        // route reflection's `has()` through it so the two surfaces agree.
        let has_val = if is_required_field(field, features) && field.number.is_some() {
            let has_method = format_ident!(
                "has_{}",
                ctx.field_rust_name(name, field.number.unwrap_or(0))
            );
            quote! { self.#has_method() }
        } else {
            has_val
        };
        get_arms.push(quote! { #number => #get_val, });
        has_arms.push(quote! { #number => #has_val, });
    }

    // Oneof members dispatch through the `Option<KindView>` struct field.
    for (idx, oneof) in msg.oneof_decl.iter().enumerate() {
        let Some(base_ident) = oneof_idents.get(&idx) else {
            continue;
        };
        let oneof_name = oneof
            .name
            .as_deref()
            .ok_or(CodeGenError::MissingField("oneof.name"))?;
        let field_ident = ctx.oneof_ident(oneof_name);
        let view_enum = quote! { #view_oneof_prefix #base_ident };

        for field in msg
            .field
            .iter()
            .filter(|f| is_real_oneof_member(f) && f.oneof_index == Some(idx as i32))
        {
            let name = field
                .name
                .as_deref()
                .ok_or(CodeGenError::MissingField("field.name"))?;
            let number = field.number.unwrap_or(0) as u32;
            let variant = oneof_variant_ident(name);
            let ty = effective_type(ctx, field, features);

            let (active, default) = match ty {
                Type::TYPE_STRING => (quote! { #vr::String(v) }, quote! { #vr::String("") }),
                Type::TYPE_BYTES => (quote! { #vr::Bytes(v) }, quote! { #vr::Bytes(&[]) }),
                Type::TYPE_MESSAGE | Type::TYPE_GROUP => {
                    let view_ty = resolve_view_ty_tokens(view_scope, field, &quote! { 'a })?;
                    (
                        quote! { #vr::Message(#cow::Borrowed(&**v)) },
                        quote! {
                            #vr::Message(#cow::Borrowed(
                                <#view_ty as ::buffa::view::DefaultViewInstance>::default_view_instance(),
                            ))
                        },
                    )
                }
                Type::TYPE_ENUM => {
                    let default = enum_default_number(
                        ctx,
                        field,
                        view_scope.current_package,
                        view_scope.nesting,
                    )?;
                    (
                        quote! { #vr::EnumNumber(v.to_i32()) },
                        quote! { #vr::EnumNumber(#default) },
                    )
                }
                _ => {
                    let variant_v = scalar_variant(ty);
                    let def = scalar_default(ty);
                    (
                        quote! { #vr::#variant_v(*v) },
                        quote! { #vr::#variant_v(#def) },
                    )
                }
            };

            get_arms.push(quote! {
                #number => match &self.#field_ident {
                    ::core::option::Option::Some(#view_enum::#variant(v)) => #active,
                    _ => #default,
                },
            });
            has_arms.push(quote! {
                #number => ::core::matches!(
                    &self.#field_ident,
                    ::core::option::Option::Some(#view_enum::#variant(_))
                ),
            });
        }
    }

    // Path from the view module back to `__buffa::reflect::descriptor_pool()`.
    let mut supers = TokenStream::new();
    for _ in 0..view_depth {
        supers.extend(quote! { super:: });
    }
    let sentinel = make_field_ident(SENTINEL_MOD);
    let pool = quote! { #supers #sentinel::reflect::descriptor_pool() };

    let deprecated_field_allow =
        crate::message::deprecated_field_allow(ctx, msg, view_scope.proto_fqn);
    if guarded {
        return Ok(crate::inspect::message_impl(
            &quote! { <'a> },
            &quote! { #view_ident<'a> },
            &pool,
            &get_arms,
            &has_arms,
            &deprecated_field_allow,
        ));
    }
    Ok(quote! {
        #deprecated_field_allow
        impl<'a> ::buffa_descriptor::reflect::ReflectMessage for #view_ident<'a> {
            fn message_descriptor(&self) -> &::buffa_descriptor::MessageDescriptor {
                #pool.message(Self::__buffa_reflect_message_index())
            }

            fn pool(&self) -> &::buffa::alloc::sync::Arc<::buffa_descriptor::DescriptorPool> {
                #pool
            }

            fn get(&self, field: &::buffa_descriptor::FieldDescriptor) -> #vr<'_> {
                // Closed enums are stored as the bare enum type, whose `to_i32`
                // is the `Enumeration` trait method (open enums use the inherent
                // `EnumValue::to_i32`, which needs no import). No-op for messages
                // without enum fields.
                #[allow(unused_imports)]
                use ::buffa::Enumeration as _;
                match field.number() {
                    #(#get_arms)*
                    _ => {
                        ::core::debug_assert!(
                            false,
                            "field number {} is not a member of this view's reflect get()",
                            field.number(),
                        );
                        #vr::Bool(false)
                    }
                }
            }

            fn has(&self, field: &::buffa_descriptor::FieldDescriptor) -> bool {
                match field.number() {
                    #(#has_arms)*
                    _ => false,
                }
            }

            fn for_each_set(
                &self,
                f: &mut dyn ::core::ops::FnMut(&::buffa_descriptor::FieldDescriptor, #vr<'_>),
            ) {
                let md = ::buffa_descriptor::reflect::ReflectMessage::message_descriptor(self);
                for fd in md.fields() {
                    if ::buffa_descriptor::reflect::ReflectMessage::has(self, fd) {
                        f(fd, ::buffa_descriptor::reflect::ReflectMessage::get(self, fd));
                    }
                }
            }

            fn to_dynamic(&self) -> ::buffa_descriptor::reflect::DynamicMessage {
                // The one allocating path in vtable mode (an explicit owned
                // snapshot — plain field reads never reach it). Encode the view
                // directly and decode into a `DynamicMessage`, skipping the
                // intermediate owned-message tree that `from_message` would build.
                //
                // The two *memory* bounds are rescaled to the input rather than
                // left at their defaults. The two decoders measure the same
                // message in different units — a `DynamicMessage` entry is
                // wider than the borrowed view it came from — so the defaults
                // reject conversions of views that decoded perfectly well, and
                // this signature has nowhere to put a rejection.
                //
                // Scaled, not lifted: `usize::MAX` would leave the whole
                // decode_view -> to_dynamic chain with no ceiling anywhere.
                // 128 bytes of element memory per encoded byte cannot reject
                // these bytes — the widest ratio the reflective decoder can
                // reach is a packed scalar, one wire byte becoming one
                // `size_of::<Value>()` slot, and `Value` is 64 bytes — while
                // still bounding the conversion at a constant factor of what
                // the caller already holds. Floored at the default so a small
                // message is never held to a *tighter* bound than a plain
                // decode would apply.
                let bytes = ::buffa::ViewEncode::encode_to_vec(self);
                let options = ::buffa::DecodeOptions::new()
                    .with_element_memory_limit(
                        bytes
                            .len()
                            .saturating_mul(128)
                            .max(::buffa::DEFAULT_ELEMENT_MEMORY_LIMIT),
                    )
                    // One unknown field costs at least two wire bytes, so the
                    // byte count is itself an upper bound on how many the
                    // re-decode can materialize.
                    .with_unknown_field_limit(
                        bytes.len().max(::buffa::DEFAULT_UNKNOWN_FIELD_LIMIT),
                    );
                ::buffa_descriptor::reflect::DynamicMessage::decode_with_options(
                    ::buffa::alloc::sync::Arc::clone(#pool),
                    Self::__buffa_reflect_message_index(),
                    &bytes,
                    &options,
                )
                .expect("view re-encodes to bytes decodable against its own descriptor")
            }
        }

        impl<'a> ::buffa_descriptor::reflect::ReflectElement for #view_ident<'a> {
            fn as_value_ref(&self) -> #vr<'_> {
                #vr::Message(#cow::Borrowed(self))
            }
        }

        impl<'a> #view_ident<'a> {
            /// Memoized `MessageIndex` for this view's message type, resolved
            /// once against the package's embedded descriptor pool. An inherent
            /// associated fn (not a free fn) so sibling views in the same module
            /// do not collide.
            #[doc(hidden)]
            fn __buffa_reflect_message_index() -> ::buffa_descriptor::MessageIndex {
                static IDX: ::std::sync::OnceLock<::buffa_descriptor::MessageIndex> =
                    ::std::sync::OnceLock::new();
                *IDX.get_or_init(|| {
                    #pool
                        .message_index(<Self as ::buffa::MessageName>::FULL_NAME)
                        .expect("generated view type is registered in the embedded descriptor pool")
                })
            }
        }
    })
}