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
extern crate proc_macro;
use proc_macro::TokenStream;
use quote::quote;
use syn::{parse_macro_input, Data, DeriveInput, Fields, ItemEnum, Lit, Meta};
// The attribute macro for schema generation
#[proc_macro_attribute]
pub fn schema(attr: TokenStream, item: TokenStream) -> TokenStream {
let input = parse_macro_input!(item as DeriveInput);
let name = &input.ident;
// Parse the attribute to extract schema type and optional name
let attr_meta = parse_macro_input!(attr as Meta);
let (schema_type, explicit_name) = match attr_meta {
Meta::Path(path) => {
let schema_type = path.get_ident().unwrap().to_string();
(schema_type, None)
}
Meta::NameValue(name_value) => {
let schema_type = name_value.path.get_ident().unwrap().to_string();
let explicit_name = match name_value.lit {
Lit::Str(lit_str) => lit_str.value(),
_ => panic!("Expected string literal for schema name"),
};
(schema_type, Some(explicit_name))
}
_ => panic!("Unsupported attribute format"),
};
let schema_impl = match schema_type.as_str() {
"Atom" => generate_atom_schema(&name, explicit_name.as_ref().map(|s| s.as_str())),
"Structural" => generate_structural_schema(&input.data),
"Nominal" => generate_nominal_schema(&name, &input.data, explicit_name.as_ref().map(|s| s.as_str())),
_ => panic!("Unsupported schema type"),
};
let expanded = quote! {
#input
impl ::irpc_schema::HasSchema for #name {
fn schema() -> ::irpc_schema::Schema {
#schema_impl
}
}
};
TokenStream::from(expanded)
}
// Generates an Atom schema (just the type name)
fn generate_atom_schema(name: &syn::Ident, explicit_name: Option<&str>) -> proc_macro2::TokenStream {
let type_name = match explicit_name {
Some(name) => name.to_string(),
None => name.to_string(),
};
quote! {
::irpc_schema::Schema::Atom(#type_name.to_string())
}
}
// Generates a Structural schema (tuples or unnamed structs)
fn generate_structural_schema(data: &syn::Data) -> proc_macro2::TokenStream {
match data {
Data::Struct(data_struct) => match &data_struct.fields {
Fields::Named(fields) => {
let types: Vec<proc_macro2::TokenStream> = fields
.named
.iter()
.map(|f| {
let ty = &f.ty;
quote! {
<#ty as ::irpc_schema::HasSchema>::schema()
}
})
.collect();
if types.is_empty() {
quote! {
::irpc_schema::Schema::Unit
}
} else {
quote! {
::irpc_schema::Schema::Product(vec![#(#types),*])
}
}
}
Fields::Unnamed(fields) => {
let types: Vec<proc_macro2::TokenStream> = fields
.unnamed
.iter()
.map(|f| {
let ty = &f.ty;
quote! {
<#ty as ::irpc_schema::HasSchema>::schema()
}
})
.collect();
if types.is_empty() {
quote! {
::irpc_schema::Schema::Unit
}
} else {
quote! {
::irpc_schema::Schema::Product(vec![#(#types),*])
}
}
}
Fields::Unit => quote! {
::irpc_schema::Schema::Unit
},
},
Data::Enum(data_enum) => {
let variant_schemas: Vec<proc_macro2::TokenStream> = data_enum
.variants
.iter()
.map(|v| {
let variant_fields = match &v.fields {
Fields::Named(fields) => fields
.named
.iter()
.map(|f| {
let ty = &f.ty;
quote! {
<#ty as ::irpc_schema::HasSchema>::schema()
}
})
.collect(),
Fields::Unnamed(fields) => fields
.unnamed
.iter()
.map(|f| {
let ty = &f.ty;
quote! {
<#ty as ::irpc_schema::HasSchema>::schema()
}
})
.collect(),
Fields::Unit => vec![],
};
if variant_fields.is_empty() {
quote! {
::irpc_schema::Schema::Unit
}
} else {
quote! {
::irpc_schema::Schema::Product(vec![#(#variant_fields),*])
}
}
})
.collect();
if variant_schemas.is_empty() {
return quote! {
::irpc_schema::Schema::Bottom
};
}
quote! {
::irpc_schema::Schema::Sum(vec![#(#variant_schemas),*])
}
}
_ => panic!("Unsupported type for Structural schema"),
}
}
// Generates a Nominal schema (Struct or Enum with names)
fn generate_nominal_schema(name: &syn::Ident, data: &syn::Data, explicit_name: Option<&str>) -> proc_macro2::TokenStream {
let name_text = explicit_name.unwrap_or(&name.to_string()).to_string();
match data {
Data::Struct(data_struct) => match &data_struct.fields {
Fields::Named(fields) => {
let field_schemas: Vec<proc_macro2::TokenStream> = fields
.named
.iter()
.map(|f| {
let field_name = f.ident.as_ref().unwrap().to_string();
let field_type = &f.ty;
quote! {
::irpc_schema::Named(#field_name.to_string(), <#field_type as ::irpc_schema::HasSchema>::schema())
}
})
.collect();
let schema = if field_schemas.is_empty() {
quote! { ::irpc_schema::Schema::Unit }
} else {
quote! { ::irpc_schema::Schema::Struct(vec![#(#field_schemas),*]) }
};
quote! {
::irpc_schema::Schema::Named(
Box::new(::irpc_schema::Named(#name_text.to_string(), #schema))
)
}
}
Fields::Unnamed(fields) => {
let field_schemas: Vec<proc_macro2::TokenStream> = fields
.unnamed
.iter()
.enumerate()
.map(|(_i, f)| {
let field_type = &f.ty;
quote! {
<#field_type as ::irpc_schema::HasSchema>::schema()
}
})
.collect();
let schema = if field_schemas.is_empty() {
quote! { ::irpc_schema::Schema::Unit }
} else {
quote! { ::irpc_schema::Schema::Product(vec![#(#field_schemas),*]) }
};
quote! {
::irpc_schema::Schema::Named(
Box::new(::irpc_schema::Named(#name_text.to_string(), #schema))
)
}
}
Fields::Unit => quote! {
::irpc_schema::Schema::Named(
Box::new(::irpc_schema::Named(#name_text.to_string(), ::irpc_schema::Schema::Unit))
)
},
},
Data::Enum(data_enum) => {
let variants: Vec<proc_macro2::TokenStream> = data_enum
.variants
.iter()
.map(|v| {
let variant_name = &v.ident;
let variant_name_text = variant_name.to_string();
match &v.fields {
Fields::Named(fields) => {
let named = fields
.named
.iter()
.map(|f| {
let field_type = &f.ty;
let field_name = f.ident.as_ref().unwrap().to_string();
quote! {
::irpc_schema::Named(#field_name.to_string(),<#field_type as ::irpc_schema::HasSchema>::schema())
}
})
.collect::<Vec<_>>();
let schema_type = if named.is_empty() {
quote! { ::irpc_schema::Schema::Unit }
} else if named.len() == 1 {
quote! { ::irpc_schema::Schema::Struct(vec![#(#named),*]) }
} else {
quote! { ::irpc_schema::Schema::Enum(vec![#(#named),*]) }
};
quote! {
::irpc_schema::Named(
#variant_name_text.to_string(),
#schema_type
)
}
}
Fields::Unnamed(fields) => {
let unnamed = fields
.unnamed
.iter()
.map(|f| {
let field_type = &f.ty;
quote! {
<#field_type as ::irpc_schema::HasSchema>::schema()
}
})
.collect::<Vec<_>>();
let schema_type = if unnamed.is_empty() {
quote! { ::irpc_schema::Schema::Unit }
} else if unnamed.len() == 1 {
quote! { ::irpc_schema::Schema::Product(vec![#(#unnamed),*]) }
} else {
quote! { ::irpc_schema::Schema::Sum(vec![#(#unnamed),*]) }
};
quote! {
::irpc_schema::Named(
#variant_name_text.to_string(),
#schema_type
)
}
}
Fields::Unit => {
quote! {
::irpc_schema::Named(
#variant_name_text.to_string(),
::irpc_schema::Schema::Unit
)
}
}
}
})
.collect::<Vec<_>>();
let schema = if variants.is_empty() {
quote! { ::irpc_schema::Schema::Bottom }
} else if variants.len() == 1 {
quote! { ::irpc_schema::Schema::Struct(vec![#(#variants),*]) }
} else {
quote! { ::irpc_schema::Schema::Enum(vec![#(#variants),*]) }
};
quote! {
::irpc_schema::Schema::Named(
Box::new(::irpc_schema::Named(#name_text.to_string(), #schema))
)
}
}
_ => panic!("Unsupported type for Nominal schema"),
}
}
/// Implements stable serialization and deserialization for an enum with
/// a number of distinct variants.
///
/// Each variant must have a single unnamed field of distinct type. Each type
/// must implement `HasSchema`.
#[proc_macro_attribute]
pub fn serialize_stable(_attr: TokenStream, item: TokenStream) -> TokenStream {
// Parse the input tokens into a syntax tree
let input = parse_macro_input!(item as ItemEnum);
// Get the original enum
let original_enum = input.clone();
// Get the name of the enum
let enum_name = &input.ident;
// Generate names for our hash struct
let hashes_struct_name =
syn::Ident::new(&format!("{}SchemaHashes", enum_name), enum_name.span());
let static_name = syn::Ident::new(&format!("__{}_SCHEMA_HASHES", enum_name), enum_name.span());
// Collect all variants
let variants = &input.variants;
// Make sure all variants have a single unnamed field
for variant in variants {
match &variant.fields {
Fields::Unnamed(fields) if fields.unnamed.len() == 1 => {
// This is good - a single unnamed field
}
_ => panic!("HashDiscriminator only supports variants with a single unnamed field"),
}
}
// Collect all variant names and their field types
let mut variant_names = Vec::new();
let mut field_types = Vec::new();
for variant in variants {
let variant_name = &variant.ident;
variant_names.push(variant_name);
let field_type = match &variant.fields {
Fields::Unnamed(fields) => &fields.unnamed.first().unwrap().ty,
_ => unreachable!(), // We've already checked this above
};
field_types.push(field_type);
}
// Define fields for our SchemaHashes struct
let hash_fields = variant_names.iter().map(|variant_name| {
quote! { pub #variant_name: [u8; 32] }
});
// Generate initialization for our SchemaHashes struct
let hash_inits =
variant_names
.iter()
.zip(field_types.iter())
.map(|(variant_name, field_type)| {
quote! {
#variant_name: *<#field_type as ::irpc_schema::HasSchema>::schema().stable_hash().as_bytes()
}
});
// Generate serialization arms using the static hashes
let serialize_arms = variant_names.iter().map(|variant_name| {
quote! {
#enum_name::#variant_name(payload) => {
let hash = hashes.#variant_name;
let mut tup = serializer.serialize_tuple(2)?;
tup.serialize_element(&hash)?;
tup.serialize_element(payload)?;
tup.end()
}
}
});
// Generate deserialization branches using the static hashes
let deserialize_branches =
variant_names
.iter()
.zip(field_types.iter())
.map(|(variant_name, field_type)| {
quote! {
if hash_bytes == hashes.#variant_name {
let payload = seq.next_element::<#field_type>()?.ok_or_else(||
serde::de::Error::custom("missing payload"))?;
return Ok(#enum_name::#variant_name(payload));
}
}
});
// Generate the implementation
let generated_impls = quote! {
// The original enum definition
#original_enum
// Define a struct to hold the schema hashes
struct #hashes_struct_name {
#(#hash_fields),*
}
// Create a static instance of our hashes using std::sync::OnceLock
use std::sync::OnceLock;
static #static_name: OnceLock<#hashes_struct_name> = OnceLock::new();
impl #hashes_struct_name {
// Create a new instance with all the hashes computed
fn new() -> Self {
Self {
#(#hash_inits),*
}
}
// Static accessor function to get or initialize the global instance
fn get() -> &'static Self {
#static_name.get_or_init(|| Self::new())
}
}
// Implementation of serde::Serialize for the enum
impl serde::Serialize for #enum_name {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: serde::Serializer,
{
use serde::ser::SerializeTuple;
let hashes = #hashes_struct_name::get();
match self {
#(#serialize_arms),*
}
}
}
// Implementation of serde::Deserialize for the enum with visitor inside
impl<'de> serde::Deserialize<'de> for #enum_name {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: serde::Deserializer<'de>,
{
// Define the visitor struct inside the deserialize implementation
struct Visitor;
impl<'de> serde::de::Visitor<'de> for Visitor {
type Value = #enum_name;
fn expecting(&self, formatter: &mut std::fmt::Formatter) -> std::fmt::Result {
formatter.write_str("a tuple with a hash discriminator and payload")
}
fn visit_seq<A>(self, mut seq: A) -> Result<Self::Value, A::Error>
where
A: serde::de::SeqAccess<'de>,
{
// Deserialize the hash discriminator (first element)
let hash_bytes = seq.next_element::<[u8; 32]>()?.ok_or_else(||
serde::de::Error::custom("missing hash"))?;
// Get the schema hashes
let hashes = #hashes_struct_name::get();
// Check against our static hashes
#(#deserialize_branches)*
// If none matched, return an error
Err(serde::de::Error::custom("unknown discriminator"))
}
}
// Use the locally-defined visitor
deserializer.deserialize_tuple(2, Visitor)
}
}
};
// Return the generated code
TokenStream::from(generated_impls)
}