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
use super::super::util::*;
use super::{
DataTypeBase, FieldOrOneofExt, Message, PackageOrMessage, PackageOrMessageExt, PURORO_INTERNAL,
PURORO_LIB,
};
use crate::syn::{parse2, Attribute, Expr, Ident, Item, ItemImpl, Path, Type};
use crate::Result;
use ::itertools::Itertools;
use ::once_cell::unsync::OnceCell;
use ::quote::{format_ident, quote};
use ::std::fmt::Debug;
use ::std::rc::Rc;
#[derive(Debug, Default)]
struct Cache {
message_struct_type: OnceCell<Rc<Type>>,
bitfield_size: OnceCell<usize>,
}
impl Message {
pub(crate) fn bitfield_size(&self) -> Result<usize> {
self.cache()
.get::<Cache>()?
.bitfield_size
.get_or_try_init(|| {
let mut tail = 0;
for field in self.fields()? {
if let Some(next_tail) = field.maybe_allocated_bitfield_tail()? {
tail = next_tail;
} else {
tail = field.assign_and_get_bitfield_tail(tail)?;
}
}
for oneof in self.oneofs()? {
if let Some(next_tail) = oneof.maybe_allocated_bitfield_tail()? {
tail = next_tail;
} else {
tail = oneof.assign_and_get_bitfield_tail(tail)?;
}
}
Ok(tail)
})
.cloned()
}
pub(crate) fn gen_message_struct_type(&self) -> Result<Rc<Type>> {
self.cache()
.get::<Cache>()?
.message_struct_type
.get_or_try_init(|| {
let parent = self.parent()?.gen_rust_module_path()?;
let ident = self.gen_message_struct_ident()?;
Ok(Rc::new(parse2(quote! { #parent :: #ident })?))
})
.cloned()
}
pub(crate) fn gen_fields_struct_path(&self) -> Result<Rc<Path>> {
let parent = self.parent()?.gen_rust_module_path()?;
let ident = self.gen_fields_struct_ident()?;
Ok(Rc::new(parse2(quote! { #parent :: _fields :: #ident })?))
}
pub(crate) fn gen_fields_struct_type(
&self,
generics: impl Iterator<Item = Rc<Type>>,
) -> Result<Rc<Type>> {
let path = self.gen_fields_struct_path()?;
let generics = generics.collect::<Vec<_>>();
Ok(Rc::new(parse2(quote! { #path :: < #(#generics,)* > })?))
}
pub(crate) fn gen_view_struct_type(&self) -> Result<Rc<Type>> {
let parent = self.parent()?.gen_rust_module_path()?;
let ident = self.gen_view_struct_ident()?;
Ok(Rc::new(parse2(quote! { #parent :: _view :: #ident })?))
}
pub(crate) fn gen_message_struct_items(&self) -> Result<Vec<Item>> {
let ident = self.gen_message_struct_ident()?;
let view_type = self.gen_view_struct_type()?;
let fields_or_oneofs_methods = self
.fields_or_oneofs()?
.map(|fo| (Ok(fo.gen_message_struct_methods()?.into_iter())))
.flatten_ok()
.collect::<Result<Vec<_>>>()?;
let oneofs = self.oneofs()?.collect::<Vec<_>>();
let oneof_field_methods = oneofs
.iter()
.map(|o| o.fields())
.flatten_ok()
.map(|f| Ok(f?.gen_message_struct_methods()?.into_iter()))
.flatten_ok()
.collect::<Result<Vec<_>>>()?;
let message_impl = self.gen_message_struct_message_impl()?;
let message_internal_impl = self.gen_message_struct_message_internal_impl()?;
let clone_impl = self.gen_message_struct_impl_clone()?;
let debug_impl = self.gen_message_struct_impl_debug()?;
let deref_impl = self.gen_message_struct_impl_deref()?;
let partial_eq_impl = self.gen_message_struct_impl_partial_eq()?;
let docs = self.gen_message_struct_doc_attrs()?;
let item_struct = parse2(quote! {
#[derive(::std::default::Default)]
#(#docs)*
pub struct #ident {
view: #view_type,
}
})?;
let impl_struct = parse2(quote! {
impl #ident {
#(#fields_or_oneofs_methods)*
#(#oneof_field_methods)*
}
})?;
Ok(vec![
item_struct,
impl_struct,
message_impl.into(),
message_internal_impl.into(),
clone_impl.into(),
debug_impl.into(),
deref_impl.into(),
partial_eq_impl.into(),
])
}
pub(crate) fn gen_fields_struct_items(&self) -> Result<Vec<Item>> {
let ident = self.gen_fields_struct_ident()?;
let generics = self
.fields_or_oneofs()?
.map(|fo| fo.gen_fields_struct_generic_param_ident())
.collect::<Result<Vec<_>>>()?;
let fields = self
.fields_or_oneofs()?
.map(|fo| fo.gen_fields_struct_field())
.collect::<Result<Vec<_>>>()?;
Ok(vec![parse2(quote! {
#[derive(::std::default::Default)]
pub struct #ident <#(#generics),*> {
#(#fields,)*
}
})?])
}
pub(crate) fn gen_view_struct_items(&self) -> Result<Vec<Item>> {
let ident = self.gen_view_struct_ident()?;
let fields_types = self
.fields_or_oneofs()?
.map(|fo| fo.gen_fields_struct_field_type())
.collect::<Result<Vec<_>>>()?;
let fields_struct_type = self.gen_fields_struct_type(fields_types.into_iter())?;
let bitfield_size_in_u32_array = (self.bitfield_size()? + 31) / 32;
let fields_or_oneofs_methods = self
.fields_or_oneofs()?
.map(|fo| (Ok(fo.gen_view_struct_methods()?.into_iter())))
.flatten_ok()
.collect::<Result<Vec<_>>>()?;
let oneofs = self.oneofs()?.collect::<Vec<_>>();
let oneof_field_methods = oneofs
.iter()
.map(|o| o.fields())
.flatten_ok()
.map(|f| Ok(f?.gen_view_struct_methods()?.into_iter()))
.flatten_ok()
.collect::<Result<Vec<_>>>()?;
let clone_impl = self.gen_view_struct_impl_clone()?;
let drop_impl = self.gen_view_struct_impl_drop()?;
let debug_impl = self.gen_view_struct_impl_debug()?;
let partial_eq_impl = self.gen_view_struct_impl_partial_eq()?;
Ok(vec![
parse2(quote! {
#[derive(::std::default::Default)]
pub struct #ident {
pub(super) fields: #fields_struct_type,
pub(super) shared: #PURORO_INTERNAL::SharedItemsImpl<#bitfield_size_in_u32_array>,
}
})?,
parse2(quote! {
impl #ident {
#(#fields_or_oneofs_methods)*
#(#oneof_field_methods)*
}
})?,
clone_impl.into(),
drop_impl.into(),
debug_impl.into(),
partial_eq_impl.into(),
])
}
fn gen_message_struct_ident(&self) -> Result<Ident> {
Ok(format_ident!(
"{}",
self.name()?
.to_camel_case()
.escape_rust_keywords()
.to_string()
))
}
fn gen_fields_struct_ident(&self) -> Result<Ident> {
Ok(format_ident!(
"{}Fields",
self.name()?.to_camel_case().to_string()
))
}
fn gen_view_struct_ident(&self) -> Result<Ident> {
Ok(format_ident!(
"{}View",
self.name()?.to_camel_case().to_string()
))
}
fn gen_message_struct_message_impl(&self) -> Result<ItemImpl> {
let ident = self.gen_message_struct_ident()?;
let out_ident = quote! { out };
let out_expr = parse2(quote! { out })?;
let ser_stmts = self
.fields_or_oneofs()?
.map(|fo| fo.gen_message_struct_impl_message_ser_stmt(&out_expr))
.collect::<Result<Vec<_>>>()?;
Ok(parse2(quote! {
impl #PURORO_LIB::Message for #ident {
fn from_bytes_iter<I: ::std::iter::Iterator<Item=::std::io::Result<u8>>>(iter: I) -> #PURORO_LIB::Result<Self> {
let mut msg = <Self as ::std::default::Default>::default();
msg.merge_from_bytes_iter(iter)?;
::std::result::Result::Ok(msg)
}
fn merge_from_bytes_iter<I: ::std::iter::Iterator<Item =::std::io::Result<u8>>>(
&mut self,
iter: I
) -> #PURORO_LIB::Result<()> {
let mut pos_iter = #PURORO_INTERNAL::PosIter::new(iter);
let mut scoped_iter = #PURORO_INTERNAL::ScopedIter::from_mut_pos_iter(&mut pos_iter);
<Self as #PURORO_INTERNAL::MessageInternal>::merge_from_scoped_bytes_iter(self, &mut scoped_iter)?;
scoped_iter.drop_and_check_scope_completed()?;
Ok(())
}
fn to_bytes<W: ::std::io::Write>(&self, #[allow(unused)] #out_ident: &mut W) -> #PURORO_LIB::Result<()> {
#[allow(unused)] use #PURORO_INTERNAL::OneofUnion as _;
use #PURORO_INTERNAL::{SharedItems as _, UnknownFields as _};
#(#ser_stmts)*
self.shared.unknown_fields().ser_to_write(#out_ident)?;
::std::result::Result::Ok(())
}
}
})?)
}
fn gen_message_struct_message_internal_impl(&self) -> Result<ItemImpl> {
let ident = self.gen_message_struct_ident()?;
let field_data_ident: Ident = parse2(quote! { field_data })?;
let field_data_expr = parse2(quote! { field_data })?;
let deser_arms = self
.fields_or_oneofs()?
.map(|fo| {
Ok(fo
.gen_message_struct_impl_message_deser_arms(&field_data_expr)?
.into_iter())
})
.flatten_ok()
.collect::<Result<Vec<_>>>()?;
Ok(parse2(quote! {
impl #PURORO_INTERNAL::MessageInternal for #ident {
fn merge_from_scoped_bytes_iter<'a, I: ::std::iter::Iterator<Item =::std::io::Result<u8>>>(
&mut self,
iter: &mut #PURORO_INTERNAL::ScopedIter<'a, I>,
) -> #PURORO_LIB::Result<()> {
use #PURORO_INTERNAL::ser::FieldData;
#[allow(unused)] use #PURORO_INTERNAL::OneofUnion as _;
use #PURORO_INTERNAL::{SharedItems as _, UnknownFields as _};
#[allow(unused)] use ::std::result::Result;
#[allow(unused)] use ::std::result::Result::{Ok, Err};
#[allow(unused)] use ::std::vec::Vec;
use #PURORO_LIB::PuroroError;
while let Some((number, #field_data_ident)) = FieldData::from_bytes_scoped_iter(iter.by_ref())? {
let result: #PURORO_LIB::Result<()> = (|| {
match number {
#(#deser_arms)*
_ => {
let field_data = #field_data_ident.map(|iter| {
iter.collect::<Result<Vec<_>, _>>()
}).transpose()?;
Err(PuroroError::UnknownFieldNumber(field_data))?
}
}
Ok(())
})();
match result {
Ok(_) => (),
Err(PuroroError::UnknownFieldNumber(field_data)) => {
self.view.shared.unknown_fields_mut().push(number, field_data)?;
}
Err(e) => Err(e)?,
}
}
Ok(())
}
}
})?)
}
fn gen_message_struct_impl_clone(&self) -> Result<ItemImpl> {
let ident = self.gen_message_struct_ident()?;
Ok(parse2(quote! {
impl ::std::clone::Clone for #ident {
fn clone(&self) -> Self {
Self {
view: ::std::clone::Clone::clone(&self.view),
}
}
}
})?)
}
fn gen_message_struct_impl_debug(&self) -> Result<ItemImpl> {
let ident = self.gen_message_struct_ident()?;
let view_type = self.gen_view_struct_type()?;
Ok(parse2(quote! {
impl ::std::fmt::Debug for #ident {
fn fmt(&self, fmt: &mut ::std::fmt::Formatter<'_>) -> ::std::result::Result<(), ::std::fmt::Error> {
<#view_type as ::std::fmt::Debug>::fmt(&self.view, fmt)
}
}
})?)
}
fn gen_message_struct_impl_deref(&self) -> Result<ItemImpl> {
let ident = self.gen_message_struct_ident()?;
let view_type = self.gen_view_struct_type()?;
Ok(parse2(quote! {
impl ::std::ops::Deref for #ident {
type Target = #view_type;
fn deref(&self) -> &Self::Target {
&self.view
}
}
})?)
}
fn gen_message_struct_impl_partial_eq(&self) -> Result<ItemImpl> {
let ident = self.gen_message_struct_ident()?;
Ok(parse2(quote! {
impl ::std::cmp::PartialEq for #ident {
fn eq(&self, rhs: &Self) -> bool {
&self.view == &rhs.view
}
}
})?)
}
fn gen_view_struct_impl_drop(&self) -> Result<ItemImpl> {
let ident = self.gen_view_struct_ident()?;
let oneof_idents = self
.oneofs()?
.map(|o| o.gen_fields_struct_field_ident())
.collect::<Result<Vec<_>>>()?;
Ok(parse2(quote! {
impl ::std::ops::Drop for #ident {
fn drop(&mut self) {
#[allow(unused)] use #PURORO_INTERNAL::{OneofUnion as _, SharedItems as _};
#(self.fields.#oneof_idents.clear(self.shared.bitfield_mut());)*
}
}
})?)
}
fn gen_view_struct_impl_debug(&self) -> Result<ItemImpl> {
let ident = self.gen_view_struct_ident()?;
let mut debug_fields: Expr = parse2(quote! { debug_struct })?;
for field_or_oneof in self.fields_or_oneofs()? {
field_or_oneof.gen_view_struct_impl_debug_method_call(&mut debug_fields)?;
}
Ok(parse2(quote! {
impl ::std::fmt::Debug for #ident {
fn fmt(&self, fmt: &mut ::std::fmt::Formatter<'_>) -> ::std::result::Result<(), ::std::fmt::Error> {
use #PURORO_INTERNAL::{SharedItems as _, UnknownFields as _};
let mut debug_struct = fmt.debug_struct(stringify!(#ident));
#debug_fields;
self.shared.unknown_fields().debug_struct_fields(&mut debug_struct)?;
debug_struct.finish()
}
}
})?)
}
fn gen_view_struct_impl_partial_eq(&self) -> Result<ItemImpl> {
let ident = self.gen_view_struct_ident()?;
let rhs_expr = parse2(quote! { rhs })?;
let cmp_exprs = self
.fields_or_oneofs()?
.map(|fo| fo.gen_view_struct_impl_partial_eq_cmp(&rhs_expr))
.collect::<Result<Vec<_>>>()?;
Ok(parse2(quote! {
impl ::std::cmp::PartialEq for #ident {
fn eq(&self, rhs: &Self) -> bool {
#[allow(unused)] use #PURORO_INTERNAL::OneofUnion as _;
use #PURORO_INTERNAL::SharedItems as _;
true
#( && #cmp_exprs)*
&& self.shared.unknown_fields() == rhs.shared.unknown_fields()
}
}
})?)
}
fn gen_message_struct_doc_attrs(&self) -> Result<Vec<Attribute>> {
let input_file = self.input_file()?;
let Some(sci) = input_file.source_code_info(self.location_path()?)? else {
return Ok(Vec::new());
};
Ok(sci.gen_doc_attributes()?)
}
fn gen_view_struct_impl_clone(&self) -> Result<ItemImpl> {
let ident = self.gen_view_struct_ident()?;
let fields_struct_type = self.gen_fields_struct_path()?;
let field_values = self
.fields_or_oneofs()?
.map(|fo| fo.gen_message_struct_impl_clone_field_value())
.collect::<Result<Vec<_>>>()?;
Ok(parse2(quote! {
impl ::std::clone::Clone for #ident {
fn clone(&self) -> Self {
#[allow(unused)] use #PURORO_INTERNAL::SharedItems as _;
Self {
fields: #fields_struct_type {
#(#field_values,)*
},
shared: ::std::clone::Clone::clone(&self.shared),
}
}
}
})?)
}
}