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
//! Code generation for per-message owned-view wrapper types.
//!
//! For each proto message `Foo` (when views are generated) this module
//! generates `FooOwnedView`: a self-contained `'static` handle wrapping
//! `::buffa::OwnedView<FooView<'static>>` with one accessor method per field.
//! Every accessor takes `&self` and returns data borrowed from the wrapper's
//! internal buffer, so field borrows can never outlive the handle — the
//! ergonomic replacement for direct field access on `OwnedView` (which would
//! require exposing the view's synthetic `'static` lifetime and is therefore
//! not offered).
use crate::generated::descriptor::field_descriptor_proto::{Label, Type};
use crate::generated::descriptor::{DescriptorProto, FieldDescriptorProto};
use proc_macro2::TokenStream;
use quote::{format_ident, quote};
use crate::context::MessageScope;
use crate::impl_message::{effective_type, is_real_oneof_member, is_supported_field_type};
use crate::message::is_map_field;
use crate::view::{
oneof_view_needs_lifetime, view_map_type, view_repeated_type, view_singular_type,
};
use crate::{CodeGenError, CodeGenWarning};
/// Method names reserved by the wrapper itself. A proto field or oneof with
/// one of these names would collide with the wrapper's inherent methods (or,
/// for `clone`/`into`, silently shadow the standard trait method when called
/// with method syntax), so its accessor is suppressed with a
/// [`CodeGenWarning::OwnedViewAccessorSuppressed`] — the data stays reachable
/// through `view()`.
const RESERVED_WRAPPER_METHODS: &[&str] = &[
"decode",
"decode_with_options",
"from_owned",
"view",
"to_owned_message",
"bytes",
"into_bytes",
"clone",
"into",
];
/// Generate the `FooOwnedView` wrapper for `msg`.
///
/// `scope` must be the **view scope** (the same `MessageScope` used to emit
/// the view struct's field types), so that relative type paths in accessor
/// return types resolve from the wrapper's module — the wrapper is emitted
/// beside the view struct.
pub(crate) fn generate_owned_view_wrapper(
scope: MessageScope<'_>,
msg: &DescriptorProto,
rust_name: &str,
view_ident: &proc_macro2::Ident,
owned_path: &TokenStream,
view_oneof_prefix: &TokenStream,
oneof_idents: &std::collections::HashMap<usize, proc_macro2::Ident>,
) -> Result<TokenStream, CodeGenError> {
let MessageScope {
ctx,
proto_fqn,
features,
..
} = scope;
let wrapper_ident = format_ident!("{}OwnedView", rust_name);
// Accessor return types use the anonymous lifetime: in return position
// with a `&self` receiver it elides to the borrow of `self`.
let lt = quote! { '_ };
let mut accessors: Vec<TokenStream> = Vec::new();
// Plain and map/repeated fields (real-oneof members are reached through
// the oneof accessor below).
for field in &msg.field {
if !is_supported_field_type(field.r#type.unwrap_or_default()) {
continue;
}
if is_real_oneof_member(field) {
continue;
}
let field_name = field
.name
.as_deref()
.ok_or(CodeGenError::MissingField("field.name"))?;
let number = field.number.unwrap_or(0);
// The reserved-name check runs against the *resolved* Rust name, so
// an `idiomatic_field_names` conversion that lands on a reserved
// method (`toOwnedMessage` → `to_owned_message`) is also suppressed.
if RESERVED_WRAPPER_METHODS.contains(&ctx.field_rust_name(field_name, number).as_ref()) {
ctx.warn(CodeGenWarning::OwnedViewAccessorSuppressed {
wrapper_name: wrapper_ident.to_string(),
field_name: field_name.to_string(),
});
continue;
}
let ident = ctx.field_ident(field_name, number);
let field_fqn = format!("{proto_fqn}.{field_name}");
let proto_comment = ctx.comment(&field_fqn);
let label = field.label.unwrap_or_default();
let is_repeated = label == Label::LABEL_REPEATED;
let (tag_line, ret_ty, body) = if is_repeated && is_map_field(msg, field) {
let ty = view_map_type(scope, msg, field, <)?;
(
format!("Field {number}: `{field_name}` (map)"),
quote! { &#ty },
quote! { &self.0.reborrow().#ident },
)
} else if is_repeated {
let ty = view_repeated_type(scope, field, <)?;
(
format!("Field {number}: `{field_name}`"),
quote! { &#ty },
quote! { &self.0.reborrow().#ident },
)
} else {
let field_features = crate::features::resolve_field(ctx, field, features);
let ty = view_singular_type(scope, field, <)?;
let tag_line = format!("Field {number}: `{field_name}`");
match effective_type(ctx, field, &field_features) {
// Message fields are held in a `MessageFieldView` (not `Copy`);
// hand out a reference.
Type::TYPE_MESSAGE | Type::TYPE_GROUP => (
tag_line,
quote! { &#ty },
quote! { &self.0.reborrow().#ident },
),
// Scalars, enums, `&str`/`&[u8]` and their `Option`s are all
// `Copy`; return them by value.
_ => (tag_line, ty, quote! { self.0.reborrow().#ident }),
}
};
let doc = crate::comments::doc_attrs_with_tag_resolved(
proto_comment,
&tag_line,
proto_fqn,
&ctx.type_map,
);
// The accessor is another way to read the view's field, so it carries
// the field's marker, and a guard for its own read of that field.
let deprecated_attr = crate::view::view_field_deprecated_attr(ctx, field, &field_fqn)
.map(|deprecated| quote! { #deprecated #[allow(deprecated)] });
accessors.push(quote! {
#doc
#deprecated_attr
#[must_use]
pub fn #ident(&self) -> #ret_ty {
#body
}
});
}
// One accessor per non-synthetic oneof, returning `Option<&KindView>`.
for (idx, oneof) in msg.oneof_decl.iter().enumerate() {
let Some(enum_ident) = oneof_idents.get(&idx) else {
continue;
};
let fields: Vec<&FieldDescriptorProto> = msg
.field
.iter()
.filter(|f| is_real_oneof_member(f) && f.oneof_index == Some(idx as i32))
.collect();
if fields.is_empty() {
continue;
}
let oneof_name = oneof
.name
.as_deref()
.ok_or(CodeGenError::MissingField("oneof.name"))?;
if RESERVED_WRAPPER_METHODS.contains(&ctx.oneof_rust_name(oneof_name).as_ref()) {
ctx.warn(CodeGenWarning::OwnedViewAccessorSuppressed {
wrapper_name: wrapper_ident.to_string(),
field_name: oneof_name.to_string(),
});
continue;
}
let ident = ctx.oneof_ident(oneof_name);
let generics = if oneof_view_needs_lifetime(ctx, &fields, features) {
quote! { <'_> }
} else {
quote! {}
};
let doc = format!(" Oneof `{oneof_name}`.");
accessors.push(quote! {
#[doc = #doc]
#[must_use]
pub fn #ident(
&self,
) -> ::core::option::Option<&#view_oneof_prefix #enum_ident #generics> {
self.0.reborrow().#ident.as_ref()
}
});
}
let wrapper_doc = format!(
" Self-contained, `'static` owned view of a `{rust_name}` message.\n\n \
Wraps [`::buffa::OwnedView`]`<`[`{view}`]`<'static>>`: the decoded view and the \
[`::buffa::bytes::Bytes`] buffer it borrows from travel together, so the handle is \
`'static` and `Send + Sync` — suitable for async handlers, spawned tasks, and \
anywhere a `'static` bound is required.\n\n \
Field accessors return borrows tied to `&self`. Use [`Self::view`] to get the full \
[`{view}`] when you need struct patterns, iteration helpers, or to pass the view to \
lifetime-parameterised code.",
view = view_ident,
);
let view_doc = format!(" Borrow the full [`{view_ident}`] with its lifetime tied to `&self`.");
let serialize_impl = if ctx.config.generate_json {
crate::feature_gates::cfg_block(
quote! {
impl ::serde::Serialize for #wrapper_ident {
fn serialize<__S: ::serde::Serializer>(
&self,
__s: __S,
) -> ::core::result::Result<__S::Ok, __S::Error> {
::serde::Serialize::serialize(&self.0, __s)
}
}
},
ctx.config.feature_gates().json,
)
} else {
quote! {}
};
// Scoped #[allow(non_snake_case)]: accessor methods are named after the
// (resolved) member names, which can be non-snake for verbatim camelCase
// protos or collision fallbacks. Empty for conforming messages.
let non_snake_attr = ctx.message_non_snake_attr(msg);
Ok(quote! {
#[doc = #wrapper_doc]
#[derive(Clone, Debug)]
pub struct #wrapper_ident(::buffa::OwnedView<#view_ident<'static>>);
#non_snake_attr
impl #wrapper_ident {
/// Decode an owned view from a [`::buffa::bytes::Bytes`] buffer.
///
/// The view borrows directly from the buffer's data; the buffer is
/// retained inside the returned handle.
///
/// # Errors
///
/// Returns [`::buffa::DecodeError`] if the buffer contains invalid
/// protobuf data.
pub fn decode(
bytes: ::buffa::bytes::Bytes,
) -> ::core::result::Result<Self, ::buffa::DecodeError> {
::core::result::Result::Ok(#wrapper_ident(::buffa::OwnedView::decode(bytes)?))
}
/// Decode with custom [`::buffa::DecodeOptions`] (recursion limit,
/// max message size).
///
/// # Errors
///
/// Returns [`::buffa::DecodeError`] if the buffer is invalid or
/// exceeds the configured limits.
pub fn decode_with_options(
bytes: ::buffa::bytes::Bytes,
opts: &::buffa::DecodeOptions,
) -> ::core::result::Result<Self, ::buffa::DecodeError> {
::core::result::Result::Ok(#wrapper_ident(::buffa::OwnedView::decode_with_options(
bytes, opts,
)?))
}
/// Build from an owned message via an encode → decode round-trip.
///
/// # Errors
///
/// Returns [`::buffa::DecodeError::MessageTooLarge`] if the
/// message's encoded size exceeds the 2 GiB protobuf limit, or
/// another [`::buffa::DecodeError`] if the re-encoded bytes are
/// somehow invalid (should not happen for well-formed messages).
pub fn from_owned(
msg: &#owned_path,
) -> ::core::result::Result<Self, ::buffa::DecodeError> {
::core::result::Result::Ok(#wrapper_ident(::buffa::OwnedView::from_owned(msg)?))
}
#[doc = #view_doc]
#[must_use]
pub fn view(&self) -> &#view_ident<'_> {
self.0.reborrow()
}
/// Convert to the owned message type.
///
/// Infallible: this type's constructors wire-decode their
/// buffer, and a view produced by wire decoding always
/// converts. Delegates to [`::buffa::OwnedView::to_owned_message`],
/// whose contract also governs handles converted from a raw
/// [`::buffa::OwnedView`].
#[must_use]
pub fn to_owned_message(&self) -> #owned_path {
self.0.to_owned_message()
}
/// The underlying bytes buffer.
#[must_use]
pub fn bytes(&self) -> &::buffa::bytes::Bytes {
self.0.bytes()
}
/// Consume the handle, returning the underlying bytes buffer.
#[must_use]
pub fn into_bytes(self) -> ::buffa::bytes::Bytes {
self.0.into_bytes()
}
#(#accessors)*
}
impl ::core::convert::From<::buffa::OwnedView<#view_ident<'static>>> for #wrapper_ident {
fn from(inner: ::buffa::OwnedView<#view_ident<'static>>) -> Self {
#wrapper_ident(inner)
}
}
impl ::core::convert::From<#wrapper_ident> for ::buffa::OwnedView<#view_ident<'static>> {
fn from(wrapper: #wrapper_ident) -> Self {
wrapper.0
}
}
impl ::core::convert::AsRef<::buffa::OwnedView<#view_ident<'static>>> for #wrapper_ident {
fn as_ref(&self) -> &::buffa::OwnedView<#view_ident<'static>> {
&self.0
}
}
// NOTE: this is the one generated impl whose `Self` is the owned
// message path. Extern-mapped (`extern_path`) messages never reach
// this code (they are not in the generation set, so no view/wrapper
// is generated for them); if that invariant ever changes, this impl
// must be skipped for absolute `owned_path`s to avoid an orphan impl.
impl ::buffa::HasMessageView for #owned_path {
type View<'a> = #view_ident<'a>;
type ViewHandle = #wrapper_ident;
}
#serialize_impl
})
}