Skip to main content

desert_macro/
lib.rs

1use proc_macro::TokenStream;
2use proc_macro2::{Ident, Span};
3use quote::{quote, ToTokens};
4use std::collections::HashMap;
5use syn::punctuated::Punctuated;
6use syn::{Attribute, Data, DeriveInput, Expr, Fields, Lit, LitStr, Meta, Token, Type};
7
8struct DesertAttributes {
9    transparent: bool,
10    sorted_constructors: bool,
11    custom: Option<Type>,
12    evolution_steps: Vec<proc_macro2::TokenStream>,
13    field_defaults: HashMap<String, Expr>,
14}
15
16fn parse_desert_attributes(attrs: &[Attribute]) -> DesertAttributes {
17    let mut transparent = false;
18    let mut sorted_constructors = false;
19    let mut custom: Option<Type> = None;
20    let mut evolution_steps = Vec::new();
21    let mut field_defaults = HashMap::new();
22
23    for attr in attrs {
24        if attr.path().is_ident("desert") {
25            let nested = attr
26                .parse_args_with(Punctuated::<Meta, Token![,]>::parse_terminated)
27                .expect("desert args");
28            for meta in nested {
29                match meta {
30                    Meta::Path(path) => {
31                        if path.is_ident("transparent") {
32                            transparent = true;
33                        } else if path.is_ident("sorted_constructors") {
34                            sorted_constructors = true;
35                        } else {
36                            panic!("Unknown desert attribute: {:?}", path.get_ident());
37                        }
38                    }
39                    Meta::List(list) => {
40                        if list.path.is_ident("evolution") {
41                            let nested_evolution = list
42                                .parse_args_with(Punctuated::<Meta, Token![,]>::parse_terminated)
43                                .expect("evolution steps");
44                            for meta in nested_evolution {
45                                match meta {
46                                    Meta::Path(path) => {
47                                        panic!("Invalid evolution step: {:?}", path.get_ident());
48                                    }
49                                    Meta::List(list) => {
50                                        if list.path.is_ident("FieldAdded") {
51                                            let args = list
52                                                .parse_args_with(
53                                                    Punctuated::<Expr, Token![,]>::parse_terminated,
54                                                )
55                                                .expect("FieldAdded arguments");
56                                            if args.len() != 2 {
57                                                panic!(
58                                                    "Invalid number of arguments for FieldAdded"
59                                                );
60                                            }
61                                            let field_name = match &args[0] {
62                                                Expr::Lit(lit) => match &lit.lit {
63                                                    Lit::Str(field_name) => field_name.value(),
64                                                    _ => panic!("Invalid field name for FieldAdded - must be a string literal"),
65                                                }
66                                                other => panic!("Invalid field name for FieldAdded - must be a string literal but it was {}",
67                                                                expr_type(other)
68                                                ),
69                                            };
70                                            let field_default = &args[1];
71
72                                            field_defaults
73                                                .insert(field_name.clone(), field_default.clone());
74                                            evolution_steps.push(quote! {
75                                                desert_rust::Evolution::FieldAdded {
76                                                    name: #field_name.to_string(),
77                                                }
78                                            });
79                                        } else if list.path.is_ident("FieldMadeOptional") {
80                                            let field_name_lit: LitStr = list
81                                                .parse_args()
82                                                .expect("FieldMadeOptional argument");
83                                            let field_name = field_name_lit.value();
84
85                                            evolution_steps.push(quote! {
86                                                desert_rust::Evolution::FieldMadeOptional {
87                                                    name: #field_name.to_string(),
88                                                }
89                                            });
90                                        } else if list.path.is_ident("FieldRemoved") {
91                                            let field_name_lit: LitStr = list
92                                                .parse_args()
93                                                .expect("FieldMadeOptional argument");
94                                            let field_name = field_name_lit.value();
95
96                                            evolution_steps.push(quote! {
97                                                desert_rust::Evolution::FieldRemoved {
98                                                    name: #field_name.to_string(),
99                                                }
100                                            });
101                                        } else if list.path.is_ident("FieldMadeTransient") {
102                                            let field_name_lit: LitStr = list
103                                                .parse_args()
104                                                .expect("FieldMadeOptional argument");
105                                            let field_name = field_name_lit.value();
106
107                                            evolution_steps.push(quote! {
108                                                desert_rust::Evolution::FieldMadeTransient {
109                                                    name: #field_name.to_string(),
110                                                }
111                                            });
112                                        } else {
113                                            panic!(
114                                                "Invalid evolution step: {:?}",
115                                                list.path.get_ident()
116                                            );
117                                        }
118                                    }
119                                    Meta::NameValue(name_value) => {
120                                        panic!(
121                                            "Invalid evolution step: {:?}",
122                                            name_value.path.get_ident()
123                                        );
124                                    }
125                                }
126                            }
127                        } else {
128                            panic!("Unknown desert list attribute: {:?}", list.path.get_ident());
129                        }
130                    }
131                    Meta::NameValue(name_value) => {
132                        if name_value.path.is_ident("custom") {
133                            let ty: Type = syn::parse2(name_value.value.to_token_stream())
134                                .expect("custom attribute must be a type");
135                            custom = Some(ty);
136                        } else {
137                            panic!(
138                                "Invalid desert attribute: {:?}",
139                                name_value.path.get_ident()
140                            );
141                        }
142                    }
143                }
144            }
145        }
146    }
147    DesertAttributes {
148        transparent,
149        sorted_constructors,
150        custom,
151        evolution_steps,
152        field_defaults,
153    }
154}
155
156fn check_raw(ident: &Ident) -> (String, bool) {
157    let ident_s = ident.to_string();
158    if let Some(raw_ident_s) = ident_s.strip_prefix("r#") {
159        (raw_ident_s.to_string(), true)
160    } else {
161        (ident_s, false)
162    }
163}
164
165fn get_metadata_ident(name: &Ident) -> Ident {
166    let (base_name, raw) = check_raw(name);
167    if raw {
168        Ident::new_raw(
169            &format!("{base_name}_metadata").to_uppercase(),
170            Span::call_site(),
171        )
172    } else {
173        Ident::new(
174            &format!("{base_name}_metadata").to_uppercase(),
175            Span::call_site(),
176        )
177    }
178}
179
180fn get_case_metadata_ident(name: &Ident, case_name: &Ident) -> Ident {
181    let (base_name, raw1) = check_raw(name);
182    let (base_case_name, raw2) = check_raw(case_name);
183    if raw1 || raw2 {
184        Ident::new_raw(
185            &format!("{base_name}_{base_case_name}_metadata").to_uppercase(),
186            Span::call_site(),
187        )
188    } else {
189        Ident::new(
190            &format!("{base_name}_{base_case_name}_metadata").to_uppercase(),
191            Span::call_site(),
192        )
193    }
194}
195
196#[allow(clippy::too_many_arguments)]
197fn push_deserialization_case(
198    declarations: &mut Vec<proc_macro2::TokenStream>,
199    helpers: &mut Vec<proc_macro2::TokenStream>,
200    cases: &mut Vec<proc_macro2::TokenStream>,
201    isolated_cases: &mut Vec<proc_macro2::TokenStream>,
202    helpers_trait_name: &Ident,
203    helper_name: &Ident,
204    case_idx: u32,
205    body: proc_macro2::TokenStream,
206) {
207    let helper_body = body.clone();
208    declarations.push(quote! {
209        fn #helper_name(
210            context: &mut desert_rust::DeserializationContext<'_>,
211        ) -> desert_rust::Result<Self>;
212    });
213    helpers.push(quote! {
214        #[allow(unused_assignments, unused_variables)]
215        #[inline(never)]
216        fn #helper_name(
217            context: &mut desert_rust::DeserializationContext<'_>,
218        ) -> desert_rust::Result<Self> {
219            use desert_rust::BinaryInput;
220
221            #helper_body
222        }
223    });
224    cases.push(quote! {
225        #case_idx => {
226            #body
227        },
228    });
229    isolated_cases.push(quote! {
230        #case_idx => <Self as #helpers_trait_name>::#helper_name(context),
231    });
232}
233
234// TODO: attribute to force/disable option field detection for a field (because it's based on names only)
235// TODO: attribute to use different field names (for Scala compatibility)
236#[proc_macro_derive(BinaryCodec, attributes(desert, transient))]
237pub fn derive_binary_codec(input: TokenStream) -> TokenStream {
238    let ast: DeriveInput = syn::parse(input).expect("derive input");
239
240    let attrs = parse_desert_attributes(&ast.attrs);
241    let transparent = attrs.transparent;
242    let use_sorted_constructors = attrs.sorted_constructors;
243    let evolution_steps = &attrs.evolution_steps;
244    let field_defaults = attrs.field_defaults;
245    let version = evolution_steps.len();
246    let vplus1 = version + 1;
247
248    let mut push_evolution_steps = Vec::new();
249    for evolution_step in evolution_steps {
250        push_evolution_steps.push(quote! {
251            evolution_steps.push(#evolution_step);
252        });
253    }
254
255    let name = &ast.ident;
256    let metadata_name = get_metadata_ident(name);
257    let (base_name, _) = check_raw(name);
258    let mut helpers_trait_name = format!("__DesertDeserializationHelpersFor{base_name}");
259    while ast.generics.params.iter().any(|parameter| match parameter {
260        syn::GenericParam::Lifetime(parameter) => parameter.lifetime.ident == helpers_trait_name,
261        syn::GenericParam::Type(parameter) => parameter.ident == helpers_trait_name,
262        syn::GenericParam::Const(parameter) => parameter.ident == helpers_trait_name,
263    }) {
264        helpers_trait_name.push('_');
265    }
266    let helpers_trait_name = Ident::new(&helpers_trait_name, Span::mixed_site());
267
268    // Process generics for the impl blocks
269    let mut generics_for_impl = ast.generics.clone();
270    let mut where_clauses = Vec::new();
271    for param in &generics_for_impl.params {
272        if let syn::GenericParam::Type(type_param) = param {
273            let ident = &type_param.ident;
274            where_clauses.push(format!(
275                "{}: desert_rust::BinarySerializer + desert_rust::BinaryDeserializer",
276                ident
277            ));
278        }
279    }
280    if !where_clauses.is_empty() {
281        let where_clause_str = format!("where {}", where_clauses.join(", "));
282        generics_for_impl.where_clause = Some(syn::parse_str(&where_clause_str).unwrap());
283    }
284
285    let (impl_generics, ty_generics, where_clause) = generics_for_impl.split_for_impl();
286
287    let mut metadata = Vec::new();
288    let mut serialization_commands = Vec::new();
289    let mut deserialization_commands = Vec::new();
290    let mut direct_serialization_commands = Vec::new();
291    let mut direct_deserialization_commands = Vec::new();
292    let mut isolated_deserialization_commands = Vec::new();
293    let mut isolated_direct_deserialization_commands = Vec::new();
294    let mut deserialization_helper_declarations = Vec::new();
295    let mut deserialization_helpers = Vec::new();
296    let is_record;
297
298    match ast.data {
299        Data::Struct(struct_data) => {
300            if transparent {
301                match &struct_data.fields {
302                    Fields::Unnamed(fields) if fields.unnamed.len() == 1 => {
303                        let gen = quote! {
304                            #[allow(unused_assignments, unused_variables)]
305                            impl #impl_generics desert_rust::BinarySerializer for #name #ty_generics #where_clause {
306                                fn serialize<Output: desert_rust::BinaryOutput>(&self, context: &mut desert_rust::SerializationContext<Output>) -> desert_rust::Result<()> {
307                                    desert_rust::BinarySerializer::serialize(&self.0, context)
308                                }
309                            }
310                            #[allow(unused_assignments, unused_variables)]
311                            impl #impl_generics desert_rust::BinaryDeserializer for #name #ty_generics #where_clause {
312                                fn deserialize<'a, 'b>(context: &'a mut desert_rust::DeserializationContext<'b>) -> desert_rust::Result<Self> {
313                                    Ok(Self(desert_rust::BinaryDeserializer::deserialize(context)?))
314                                }
315                            }
316                        };
317                        return gen.into();
318                    }
319                    Fields::Named(fields) if fields.named.len() == 1 => {
320                        let field_name = &fields.named[0].ident;
321                        let gen = quote! {
322                            #[allow(unused_assignments, unused_variables)]
323                            impl #impl_generics desert_rust::BinarySerializer for #name #ty_generics #where_clause {
324                                fn serialize<Output: desert_rust::BinaryOutput>(&self, context: &mut desert_rust::SerializationContext<Output>) -> desert_rust::Result<()> {
325                                    desert_rust::BinarySerializer::serialize(&self.#field_name, context)
326                                }
327                            }
328                            #[allow(unused_assignments, unused_variables)]
329                            impl #impl_generics desert_rust::BinaryDeserializer for #name #ty_generics #where_clause {
330                                fn deserialize<'a, 'b>(context: &'a mut desert_rust::DeserializationContext<'b>) -> desert_rust::Result<Self> {
331                                    Ok(Self { #field_name: desert_rust::BinaryDeserializer::deserialize(context)? })
332                                }
333                            }
334                        };
335                        return gen.into();
336                    }
337                    _ => panic!("transparent can only be used on single-element tuple structs"),
338                }
339            }
340            is_record = true;
341            let mut field_patterns = Vec::new();
342            for field in struct_data.fields.iter() {
343                let field_ident = field.ident.as_ref().unwrap();
344                field_patterns.push(quote! { #field_ident });
345            }
346            serialization_commands.push(quote! {
347               let #name { #(#field_patterns),* } = self;
348            });
349            direct_serialization_commands.push(quote! {
350               let #name { #(#field_patterns),* } = self;
351            });
352            derive_field_serialization(
353                field_defaults,
354                &mut serialization_commands,
355                &mut deserialization_commands,
356                &struct_data.fields,
357            );
358            derive_direct_field_serialization(
359                &mut direct_serialization_commands,
360                &mut direct_deserialization_commands,
361                &struct_data.fields,
362            );
363        }
364        Data::Enum(enum_data) => {
365            if transparent {
366                panic!("transparent is not supported for enums");
367            }
368            is_record = false;
369
370            let mut ser_cases = Vec::new();
371            let mut deser_cases = Vec::new();
372            let mut direct_ser_cases = Vec::new();
373            let mut direct_deser_cases = Vec::new();
374            let mut isolated_deser_cases = Vec::new();
375            let mut isolated_direct_deser_cases = Vec::new();
376
377            let mut variants = enum_data.variants.iter().cloned().collect::<Vec<_>>();
378            if use_sorted_constructors {
379                variants.sort_by_key(|variant| variant.ident.to_string());
380            }
381
382            let mut effective_case_idx: u32 = 0;
383            for variant in variants {
384                let is_transient = variant
385                    .attrs
386                    .iter()
387                    .any(|attr| attr.path().is_ident("transient"));
388                let case_name = &variant.ident;
389                let deserialization_helper_name = Ident::new(
390                    &format!("desert_deserialize_variant_{effective_case_idx}"),
391                    Span::call_site(),
392                );
393                let direct_deserialization_helper_name = Ident::new(
394                    &format!("desert_deserialize_direct_variant_{effective_case_idx}"),
395                    Span::call_site(),
396                );
397
398                let pattern = match &variant.fields {
399                    Fields::Unit => {
400                        quote! { #name::#case_name }
401                    }
402                    Fields::Named(named_fields) => {
403                        let mut field_patterns = Vec::new();
404                        for field in named_fields.named.iter() {
405                            let field_ident = field.ident.as_ref().unwrap();
406                            field_patterns.push(quote! { #field_ident });
407                        }
408                        quote! { #name::#case_name { #(#field_patterns),* } }
409                    }
410                    Fields::Unnamed(unnamed_fields) => {
411                        let mut field_patterns = Vec::new();
412                        for n in 0..unnamed_fields.unnamed.len() {
413                            let field_ident = Ident::new(&format!("field{}", n), Span::call_site());
414                            field_patterns.push(quote! { #field_ident });
415                        }
416                        quote! { #name::#case_name(#(#field_patterns),*) }
417                    }
418                };
419
420                if !is_transient {
421                    let variant_attrs = parse_desert_attributes(&variant.attrs);
422                    let variant_transparent = variant_attrs.transparent;
423                    let variant_custom = variant_attrs.custom;
424                    let case_evolution_steps = &variant_attrs.evolution_steps;
425                    let case_field_defaults = variant_attrs.field_defaults;
426                    if variant_transparent || variant_custom.is_some() {
427                        // transparent on a variant case means we don't want to treat it as an evolvable record type, but directly
428                        // serialize the single-element field of it as-is
429                        // custom is similar to transparent but wraps the field in the provided type
430                        if !((variant.fields.is_empty() && variant_transparent)
431                            || variant.fields.len() == 1)
432                        {
433                            panic!("transparent and custom are not allowed on non-single field variants");
434                        } else if matches!(variant.fields, Fields::Unit) {
435                            // A transparent unit variant is represented by just the constructor idx and
436                            // not extendable later with fields
437                            ser_cases.push(quote! {
438                                #pattern => {
439                                    serializer.write_constructor(
440                                        #effective_case_idx,
441                                        |desert_inner_serialization_context| {
442                                            Ok(())
443                                        }
444                                    )?;
445                                }
446                            });
447                            push_deserialization_case(
448                                &mut deserialization_helper_declarations,
449                                &mut deserialization_helpers,
450                                &mut deser_cases,
451                                &mut isolated_deser_cases,
452                                &helpers_trait_name,
453                                &deserialization_helper_name,
454                                effective_case_idx,
455                                quote! { Ok(#name::#case_name) },
456                            );
457                            direct_ser_cases.push(quote! {
458                                #pattern => {
459                                    desert_rust::BinaryOutput::write_var_u32(context, #effective_case_idx);
460                                }
461                            });
462                            push_deserialization_case(
463                                &mut deserialization_helper_declarations,
464                                &mut deserialization_helpers,
465                                &mut direct_deser_cases,
466                                &mut isolated_direct_deser_cases,
467                                &helpers_trait_name,
468                                &direct_deserialization_helper_name,
469                                effective_case_idx,
470                                quote! { Ok(#name::#case_name) },
471                            );
472                        } else {
473                            let single_field = match &variant.fields {
474                                Fields::Named(named_fields) => {
475                                    named_fields.named[0].ident.clone().unwrap()
476                                }
477                                Fields::Unnamed(_) => Ident::new("field0", Span::call_site()),
478                                Fields::Unit => unreachable!(),
479                            };
480
481                            if let Some(ref custom_type) = variant_custom {
482                                ser_cases.push(
483                                    quote! {
484                                        #pattern => {
485                                            serializer.write_constructor(
486                                                #effective_case_idx,
487                                                |desert_inner_serialization_context| {
488                                                    let wrapped = #custom_type(::std::borrow::Cow::Borrowed(#single_field));
489                                                    desert_rust::BinarySerializer::serialize(&wrapped, desert_inner_serialization_context)
490                                                }
491                                            )?;
492                                        }
493                                    }
494                                );
495                                direct_ser_cases.push(
496                                    quote! {
497                                        #pattern => {
498                                            desert_rust::BinaryOutput::write_var_u32(context, #effective_case_idx);
499                                            let wrapped = #custom_type(::std::borrow::Cow::Borrowed(#single_field));
500                                            desert_rust::BinarySerializer::serialize(&wrapped, context)?;
501                                        }
502                                    }
503                                );
504                            } else {
505                                ser_cases.push(
506                                    quote! {
507                                        #pattern => {
508                                            serializer.write_constructor(
509                                                #effective_case_idx,
510                                                |desert_inner_serialization_context| {
511                                                    desert_rust::BinarySerializer::serialize(#single_field, desert_inner_serialization_context)
512                                                }
513                                            )?;
514                                        }
515                                    }
516                                );
517                                direct_ser_cases.push(
518                                    quote! {
519                                        #pattern => {
520                                            desert_rust::BinaryOutput::write_var_u32(context, #effective_case_idx);
521                                            desert_rust::BinarySerializer::serialize(#single_field, context)?;
522                                        }
523                                    }
524                                );
525                            }
526
527                            let construct_case = if let Some(ref custom_type) = variant_custom {
528                                match &variant.fields {
529                                    Fields::Unit => unreachable!(),
530                                    Fields::Named(_) => {
531                                        quote! { #name::#case_name {
532                                                #single_field: {
533                                                    let #custom_type(inner) = desert_rust::BinaryDeserializer::deserialize(context)?;
534                                                    inner.into_owned()
535                                                }
536                                            }
537                                        }
538                                    }
539                                    Fields::Unnamed(_) => {
540                                        quote! { #name::#case_name({
541                                                let #custom_type(inner) = desert_rust::BinaryDeserializer::deserialize(context)?;
542                                                inner.into_owned()
543                                            })
544                                        }
545                                    }
546                                }
547                            } else {
548                                match &variant.fields {
549                                    Fields::Unit => unreachable!(),
550                                    Fields::Named(_) => {
551                                        quote! { #name::#case_name {
552                                                #single_field: desert_rust::BinaryDeserializer::deserialize(context)?
553                                            }
554                                        }
555                                    }
556                                    Fields::Unnamed(_) => {
557                                        quote! { #name::#case_name(desert_rust::BinaryDeserializer::deserialize(context)?) }
558                                    }
559                                }
560                            };
561
562                            push_deserialization_case(
563                                &mut deserialization_helper_declarations,
564                                &mut deserialization_helpers,
565                                &mut deser_cases,
566                                &mut isolated_deser_cases,
567                                &helpers_trait_name,
568                                &deserialization_helper_name,
569                                effective_case_idx,
570                                quote! { Ok(#construct_case) },
571                            );
572                            push_deserialization_case(
573                                &mut deserialization_helper_declarations,
574                                &mut deserialization_helpers,
575                                &mut direct_deser_cases,
576                                &mut isolated_direct_deser_cases,
577                                &helpers_trait_name,
578                                &direct_deserialization_helper_name,
579                                effective_case_idx,
580                                quote! { Ok(#construct_case) },
581                            );
582                        }
583                    } else {
584                        let version = case_evolution_steps.len();
585                        let vplus1 = version + 1;
586
587                        let mut case_push_evolution_steps = Vec::new();
588                        for evolution_step in case_evolution_steps {
589                            case_push_evolution_steps.push(quote! {
590                                evolution_steps.push(#evolution_step);
591                            });
592                        }
593                        let mut case_serialization_commands = Vec::new();
594                        let mut case_deserialization_commands = Vec::new();
595                        let mut direct_case_serialization_commands = Vec::new();
596                        let mut direct_case_deserialization_commands = Vec::new();
597
598                        let new_v = if version == 0 {
599                            quote! { new_v0 }
600                        } else {
601                            quote! { new }
602                        };
603
604                        let case_metadata_name = get_case_metadata_ident(name, case_name);
605
606                        metadata.push(quote! {
607                            desert_rust::lazy_static! {
608                                static ref #case_metadata_name: desert_rust::adt::AdtMetadata = {
609                                    let mut evolution_steps: Vec<desert_rust::Evolution> = Vec::new();
610                                    evolution_steps.push(desert_rust::Evolution::InitialVersion);
611                                    #(#case_push_evolution_steps)*
612
613                                    desert_rust::adt::AdtMetadata::new(
614                                        evolution_steps,
615                                    )
616                                };
617                            }
618                        });
619
620                        derive_field_serialization(
621                            case_field_defaults,
622                            &mut case_serialization_commands,
623                            &mut case_deserialization_commands,
624                            &variant.fields,
625                        );
626                        derive_direct_field_serialization(
627                            &mut direct_case_serialization_commands,
628                            &mut direct_case_deserialization_commands,
629                            &variant.fields,
630                        );
631
632                        ser_cases.push(
633                            quote! {
634                            #pattern => {
635                                serializer.write_constructor(
636                                    #effective_case_idx,
637                                    |desert_inner_serialization_context| {
638                                        let mut serializer = desert_rust::adt::AdtSerializer::<_, #vplus1>::#new_v(&#case_metadata_name, desert_inner_serialization_context);
639                                        #(#case_serialization_commands)*
640                                        serializer.finish()
641                                    }
642                                )?;
643                            }
644                        }
645                        );
646
647                        if version == 0 {
648                            direct_ser_cases.push(
649                                quote! {
650                                    #pattern => {
651                                        desert_rust::BinaryOutput::write_var_u32(context, #effective_case_idx);
652                                        desert_rust::BinaryOutput::write_u8(context, 0);
653                                        #(#direct_case_serialization_commands)*
654                                    }
655                                }
656                            );
657                        } else {
658                            direct_ser_cases.push(
659                                quote! {
660                                    #pattern => {
661                                        desert_rust::BinaryOutput::write_var_u32(context, #effective_case_idx);
662                                        let mut serializer = desert_rust::adt::AdtSerializer::<_, #vplus1>::#new_v(&#case_metadata_name, context);
663                                        #(#case_serialization_commands)*
664                                        serializer.finish()?;
665                                    }
666                                }
667                            );
668                        }
669
670                        let construct_case = match &variant.fields {
671                            Fields::Unit => {
672                                quote! { #name::#case_name }
673                            }
674                            Fields::Named(_) => {
675                                quote! { #name::#case_name {
676                                        #(#case_deserialization_commands)*
677                                    }
678                                }
679                            }
680                            Fields::Unnamed(_) => {
681                                quote! { #name::#case_name(#(#case_deserialization_commands)*) }
682                            }
683                        };
684
685                        push_deserialization_case(
686                            &mut deserialization_helper_declarations,
687                            &mut deserialization_helpers,
688                            &mut deser_cases,
689                            &mut isolated_deser_cases,
690                            &helpers_trait_name,
691                            &deserialization_helper_name,
692                            effective_case_idx,
693                            quote! {
694                                let stored_version = context.read_u8()?;
695                                let mut deserializer = if stored_version == 0 {
696                                    desert_rust::adt::AdtDeserializer::<#vplus1>::new_v0(&#case_metadata_name, context)?
697                                } else {
698                                    desert_rust::adt::AdtDeserializer::<#vplus1>::new(&#case_metadata_name, context, stored_version)?
699                                };
700                                Ok(#construct_case)
701                            },
702                        );
703
704                        let direct_construct_case = match &variant.fields {
705                            Fields::Unit => {
706                                quote! { #name::#case_name }
707                            }
708                            Fields::Named(_) => {
709                                quote! { #name::#case_name {
710                                        #(#direct_case_deserialization_commands)*
711                                    }
712                                }
713                            }
714                            Fields::Unnamed(_) => {
715                                quote! { #name::#case_name(#(#direct_case_deserialization_commands)*) }
716                            }
717                        };
718
719                        if version == 0 {
720                            push_deserialization_case(
721                                &mut deserialization_helper_declarations,
722                                &mut deserialization_helpers,
723                                &mut direct_deser_cases,
724                                &mut isolated_direct_deser_cases,
725                                &helpers_trait_name,
726                                &direct_deserialization_helper_name,
727                                effective_case_idx,
728                                quote! {
729                                    let stored_version = context.read_u8()?;
730                                    if stored_version == 0 {
731                                        Ok(#direct_construct_case)
732                                    } else {
733                                        let mut deserializer = desert_rust::adt::AdtDeserializer::<#vplus1>::new(&#case_metadata_name, context, stored_version)?;
734                                        Ok(#construct_case)
735                                    }
736                                },
737                            );
738                        } else {
739                            push_deserialization_case(
740                                &mut deserialization_helper_declarations,
741                                &mut deserialization_helpers,
742                                &mut direct_deser_cases,
743                                &mut isolated_direct_deser_cases,
744                                &helpers_trait_name,
745                                &direct_deserialization_helper_name,
746                                effective_case_idx,
747                                quote! {
748                                    let stored_version = context.read_u8()?;
749                                    let mut deserializer = if stored_version == 0 {
750                                        desert_rust::adt::AdtDeserializer::<#vplus1>::new_v0(&#case_metadata_name, context)?
751                                    } else {
752                                        desert_rust::adt::AdtDeserializer::<#vplus1>::new(&#case_metadata_name, context, stored_version)?
753                                    };
754                                    Ok(#construct_case)
755                                },
756                            );
757                        }
758                    }
759
760                    effective_case_idx += 1;
761                } else {
762                    let name_string = name.to_string();
763                    let case_name_string = case_name.to_string();
764                    ser_cases.push(quote! {
765                        #pattern => {
766                            return Err(desert_rust::Error::SerializingTransientConstructor {
767                                type_name: #name_string.to_string(),
768                                constructor_name: #case_name_string.to_string(),
769                            });
770                        }
771                    });
772                    direct_ser_cases.push(quote! {
773                        #pattern => {
774                            return Err(desert_rust::Error::SerializingTransientConstructor {
775                                type_name: #name_string.to_string(),
776                                constructor_name: #case_name_string.to_string(),
777                            });
778                        }
779                    });
780                }
781            }
782
783            serialization_commands.push(quote! {
784                match self {
785                    #(#ser_cases),*
786                }
787            });
788
789            deserialization_commands.push(quote! {
790                 let desert_constructor_idx = deserializer.read_constructor_idx()?;
791                 match desert_constructor_idx {
792                     #(#deser_cases)*
793                    other => {
794                        Err(desert_rust::Error::InvalidConstructorId {
795                            type_name: stringify!(#name).to_string(),
796                            constructor_id: other,
797                        })
798                    }
799                 }
800            });
801            isolated_deserialization_commands.push(quote! {
802                 let desert_constructor_idx = deserializer.read_constructor_idx()?;
803                 match desert_constructor_idx {
804                     #(#isolated_deser_cases)*
805                    other => {
806                        Err(desert_rust::Error::InvalidConstructorId {
807                            type_name: stringify!(#name).to_string(),
808                            constructor_id: other,
809                        })
810                    }
811                 }
812            });
813            direct_serialization_commands.push(quote! {
814                match self {
815                    #(#direct_ser_cases),*
816                }
817            });
818            direct_deserialization_commands.push(quote! {
819                 let desert_constructor_idx = context.read_var_u32()?;
820                 match desert_constructor_idx {
821                     #(#direct_deser_cases)*
822                    other => {
823                        Err(desert_rust::Error::InvalidConstructorId {
824                            type_name: stringify!(#name).to_string(),
825                            constructor_id: other,
826                        })
827                    }
828                 }
829            });
830            isolated_direct_deserialization_commands.push(quote! {
831                 let desert_constructor_idx = context.read_var_u32()?;
832                 match desert_constructor_idx {
833                     #(#isolated_direct_deser_cases)*
834                    other => {
835                        Err(desert_rust::Error::InvalidConstructorId {
836                            type_name: stringify!(#name).to_string(),
837                            constructor_id: other,
838                        })
839                    }
840                 }
841            });
842        }
843        Data::Union(_) => {
844            panic!("Unions are not supported");
845        }
846    }
847
848    metadata.push(quote! {
849        desert_rust::lazy_static! {
850            static ref #metadata_name: desert_rust::adt::AdtMetadata = {
851                let mut evolution_steps: Vec<desert_rust::Evolution> = Vec::new();
852                evolution_steps.push(desert_rust::Evolution::InitialVersion);
853                #(#push_evolution_steps)*
854
855                desert_rust::adt::AdtMetadata::new(
856                    evolution_steps,
857                )
858            };
859        }
860    });
861
862    let new_v = if version == 0 {
863        quote! { new_v0 }
864    } else {
865        quote! { new }
866    };
867
868    let deserialization = if is_record {
869        quote! {
870            Ok(Self {
871                    #(#deserialization_commands)*
872            })
873        }
874    } else {
875        quote! {
876            #(#deserialization_commands)*
877        }
878    };
879    let deserialization_direct = if is_record {
880        quote! {
881            Ok(Self {
882                    #(#direct_deserialization_commands)*
883            })
884        }
885    } else {
886        quote! {
887            #(#direct_deserialization_commands)*
888        }
889    };
890    let isolated_deserialization = quote! {
891        #(#isolated_deserialization_commands)*
892    };
893    let isolated_deserialization_direct = quote! {
894        #(#isolated_direct_deserialization_commands)*
895    };
896
897    let deserializer_body = if version == 0 {
898        if is_record {
899            quote! {
900                use desert_rust::BinaryInput;
901
902                let stored_version = context.read_u8()?;
903                if stored_version == 0 {
904                    #deserialization_direct
905                } else {
906                    let mut deserializer = desert_rust::adt::AdtDeserializer::<#vplus1>::new(&#metadata_name, context, stored_version)?;
907                    #deserialization
908                }
909            }
910        } else {
911            quote! {
912                #[cfg(debug_assertions)]
913                {
914                    trait #helpers_trait_name: Sized {
915                        #(#deserialization_helper_declarations)*
916                    }
917
918                    impl #impl_generics #helpers_trait_name for #name #ty_generics #where_clause {
919                        #(#deserialization_helpers)*
920                    }
921
922                    use desert_rust::BinaryInput;
923
924                    let stored_version = context.read_u8()?;
925                    if stored_version == 0 {
926                        #isolated_deserialization_direct
927                    } else {
928                        let mut deserializer = desert_rust::adt::AdtDeserializer::<#vplus1>::new(&#metadata_name, context, stored_version)?;
929                        #isolated_deserialization
930                    }
931                }
932                #[cfg(not(debug_assertions))]
933                {
934                    use desert_rust::BinaryInput;
935
936                    let stored_version = context.read_u8()?;
937                    if stored_version == 0 {
938                        #deserialization_direct
939                    } else {
940                        let mut deserializer = desert_rust::adt::AdtDeserializer::<#vplus1>::new(&#metadata_name, context, stored_version)?;
941                        #deserialization
942                    }
943                }
944            }
945        }
946    } else if is_record {
947        quote! {
948            use desert_rust::BinaryInput;
949
950            let stored_version = context.read_u8()?;
951            let mut deserializer = if stored_version == 0 {
952                desert_rust::adt::AdtDeserializer::<#vplus1>::new_v0(&#metadata_name, context)?
953            } else {
954                desert_rust::adt::AdtDeserializer::<#vplus1>::new(&#metadata_name, context, stored_version)?
955            };
956            #deserialization
957        }
958    } else {
959        quote! {
960            #[cfg(debug_assertions)]
961            {
962                trait #helpers_trait_name: Sized {
963                    #(#deserialization_helper_declarations)*
964                }
965
966                impl #impl_generics #helpers_trait_name for #name #ty_generics #where_clause {
967                    #(#deserialization_helpers)*
968                }
969
970                use desert_rust::BinaryInput;
971
972                let stored_version = context.read_u8()?;
973                let mut deserializer = if stored_version == 0 {
974                    desert_rust::adt::AdtDeserializer::<#vplus1>::new_v0(&#metadata_name, context)?
975                } else {
976                    desert_rust::adt::AdtDeserializer::<#vplus1>::new(&#metadata_name, context, stored_version)?
977                };
978                #isolated_deserialization
979            }
980            #[cfg(not(debug_assertions))]
981            {
982                use desert_rust::BinaryInput;
983
984                let stored_version = context.read_u8()?;
985                let mut deserializer = if stored_version == 0 {
986                    desert_rust::adt::AdtDeserializer::<#vplus1>::new_v0(&#metadata_name, context)?
987                } else {
988                    desert_rust::adt::AdtDeserializer::<#vplus1>::new(&#metadata_name, context, stored_version)?
989                };
990                #deserialization
991            }
992        }
993    };
994
995    let gen = if version == 0 {
996        quote! {
997            #(#metadata)*
998
999            impl #impl_generics desert_rust::BinarySerializer for #name #ty_generics #where_clause {
1000                #[allow(unused_assignments, unused_variables)]
1001                fn serialize<Output: desert_rust::BinaryOutput>(&self, context: &mut desert_rust::SerializationContext<Output>) -> desert_rust::Result<()> {
1002                    desert_rust::BinaryOutput::write_u8(context, 0);
1003                    #(#direct_serialization_commands)*
1004                    Ok(())
1005                }
1006            }
1007
1008            impl #impl_generics desert_rust::BinaryDeserializer for #name #ty_generics #where_clause {
1009                #[allow(unused_assignments, unused_variables)]
1010                fn deserialize<'a, 'b>(context: &'a mut desert_rust::DeserializationContext<'b>) -> desert_rust::Result<Self> {
1011                    #deserializer_body
1012                }
1013            }
1014        }
1015    } else {
1016        quote! {
1017            #(#metadata)*
1018
1019            impl #impl_generics desert_rust::BinarySerializer for #name #ty_generics #where_clause {
1020                #[allow(unused_assignments, unused_variables)]
1021                fn serialize<Output: desert_rust::BinaryOutput>(&self, context: &mut desert_rust::SerializationContext<Output>) -> desert_rust::Result<()> {
1022                    let mut serializer = desert_rust::adt::AdtSerializer::<_, #vplus1>::#new_v(&#metadata_name, context);
1023                    #(#serialization_commands)*
1024                    serializer.finish()
1025                }
1026            }
1027
1028            impl #impl_generics desert_rust::BinaryDeserializer for #name #ty_generics #where_clause {
1029                #[allow(unused_assignments, unused_variables)]
1030                fn deserialize<'a, 'b>(context: &'a mut desert_rust::DeserializationContext<'b>) -> desert_rust::Result<Self> {
1031                    #deserializer_body
1032                }
1033            }
1034        }
1035    };
1036
1037    gen.into()
1038}
1039
1040fn derive_field_serialization(
1041    field_defaults: HashMap<String, Expr>,
1042    serialization_commands: &mut Vec<proc_macro2::TokenStream>,
1043    deserialization_commands: &mut Vec<proc_macro2::TokenStream>,
1044    fields: &Fields,
1045) {
1046    for (n, field) in fields.iter().enumerate() {
1047        let n_ident = Ident::new(&format!("field{n}"), Span::call_site());
1048        let field_ident = field.ident.as_ref().unwrap_or(&n_ident);
1049        let field_name = field_ident.to_string();
1050
1051        let mut transient = None;
1052        for attr in &field.attrs {
1053            if attr.path().is_ident("transient") {
1054                let args = attr
1055                    .parse_args_with(Punctuated::<Expr, Token![,]>::parse_terminated)
1056                    .unwrap_or_default();
1057                if args.len() != 1 {
1058                    panic!("#[transient(default)] on fields needs a default value");
1059                }
1060                let field_default = args[0].clone();
1061                transient = Some(field_default);
1062            }
1063        }
1064
1065        match transient {
1066            None => {
1067                serialization_commands.push(quote! {
1068                    serializer.write_field(#field_name, &#field_ident)?;
1069                });
1070
1071                if is_option(&field.ty) {
1072                    match field_defaults.get(&field_name) {
1073                        Some(field_default) => {
1074                            if field.ident.is_some() {
1075                                deserialization_commands.push(quote! {
1076                                    #field_ident: deserializer.read_optional_field(#field_name, Some(#field_default))?,
1077                                });
1078                            } else {
1079                                deserialization_commands.push(quote! {
1080                                    deserializer.read_optional_field(#field_name, Some(#field_default))?,
1081                                });
1082                            }
1083                        }
1084                        None => {
1085                            if field.ident.is_some() {
1086                                deserialization_commands.push(quote! {
1087                                   #field_ident: deserializer.read_optional_field(#field_name, None)?,
1088                                });
1089                            } else {
1090                                deserialization_commands.push(quote! {
1091                                   deserializer.read_optional_field(#field_name, None)?,
1092                                });
1093                            }
1094                        }
1095                    }
1096                } else {
1097                    match field_defaults.get(&field_name) {
1098                        Some(field_default) => {
1099                            if field.ident.is_some() {
1100                                deserialization_commands.push(quote! {
1101                                    #field_ident: deserializer.read_field(#field_name, Some(#field_default))?,
1102                                });
1103                            } else {
1104                                deserialization_commands.push(quote! {
1105                                    deserializer.read_field(#field_name, Some(#field_default))?,
1106                                });
1107                            }
1108                        }
1109                        None => {
1110                            if field.ident.is_some() {
1111                                deserialization_commands.push(quote! {
1112                                   #field_ident: deserializer.read_field(#field_name, None)?,
1113                                });
1114                            } else {
1115                                deserialization_commands.push(quote! {
1116                                   deserializer.read_field(#field_name, None)?,
1117                                });
1118                            }
1119                        }
1120                    }
1121                }
1122            }
1123            Some(transient_default_value) => {
1124                if field.ident.is_some() {
1125                    deserialization_commands.push(quote! {
1126                      #field_ident: #transient_default_value,
1127                    });
1128                } else {
1129                    deserialization_commands.push(quote! {
1130                      #transient_default_value,
1131                    });
1132                }
1133            }
1134        }
1135    }
1136}
1137
1138fn derive_direct_field_serialization(
1139    serialization_commands: &mut Vec<proc_macro2::TokenStream>,
1140    deserialization_commands: &mut Vec<proc_macro2::TokenStream>,
1141    fields: &Fields,
1142) {
1143    for (n, field) in fields.iter().enumerate() {
1144        let n_ident = Ident::new(&format!("field{n}"), Span::call_site());
1145        let field_ident = field.ident.as_ref().unwrap_or(&n_ident);
1146
1147        let mut transient = None;
1148        for attr in &field.attrs {
1149            if attr.path().is_ident("transient") {
1150                let args = attr
1151                    .parse_args_with(Punctuated::<Expr, Token![,]>::parse_terminated)
1152                    .unwrap_or_default();
1153                if args.len() != 1 {
1154                    panic!("#[transient(default)] on fields needs a default value");
1155                }
1156                transient = Some(args[0].clone());
1157            }
1158        }
1159
1160        match transient {
1161            None => {
1162                serialization_commands.push(quote! {
1163                    desert_rust::BinarySerializer::serialize(#field_ident, context)?;
1164                });
1165
1166                if field.ident.is_some() {
1167                    deserialization_commands.push(quote! {
1168                        #field_ident: desert_rust::BinaryDeserializer::deserialize(context)?,
1169                    });
1170                } else {
1171                    deserialization_commands.push(quote! {
1172                        desert_rust::BinaryDeserializer::deserialize(context)?,
1173                    });
1174                }
1175            }
1176            Some(transient_default_value) => {
1177                if field.ident.is_some() {
1178                    deserialization_commands.push(quote! {
1179                        #field_ident: #transient_default_value,
1180                    });
1181                } else {
1182                    deserialization_commands.push(quote! {
1183                        #transient_default_value,
1184                    });
1185                }
1186            }
1187        }
1188    }
1189}
1190
1191fn is_option(ty: &Type) -> bool {
1192    match ty {
1193        Type::Group(group) => is_option(&group.elem),
1194        Type::Paren(paren) => is_option(&paren.elem),
1195        Type::Path(type_path) if type_path.qself.is_none() => {
1196            let idents = type_path
1197                .path
1198                .segments
1199                .iter()
1200                .map(|segment| segment.ident.to_string())
1201                .collect::<Vec<_>>();
1202            idents == vec!["Option"]
1203                || idents == vec!["std", "option", "Option"]
1204                || idents == vec!["core", "option", "Option"]
1205        }
1206        _ => false,
1207    }
1208}
1209
1210fn expr_type(expr: &Expr) -> String {
1211    match expr {
1212        Expr::Array(_) => "array".to_string(),
1213        Expr::Assign(_) => "assign".to_string(),
1214        Expr::Async(_) => "async".to_string(),
1215        Expr::Await(_) => "await".to_string(),
1216        Expr::Binary(_) => "binary".to_string(),
1217        Expr::Block(_) => "block".to_string(),
1218        Expr::Break(_) => "break".to_string(),
1219        Expr::Call(_) => "call".to_string(),
1220        Expr::Cast(_) => "cast".to_string(),
1221        Expr::Closure(_) => "closure".to_string(),
1222        Expr::Const(_) => "const".to_string(),
1223        Expr::Continue(_) => "continue".to_string(),
1224        Expr::Field(_) => "field".to_string(),
1225        Expr::ForLoop(_) => "for loop".to_string(),
1226        Expr::Group(_) => "group".to_string(),
1227        Expr::If(_) => "if".to_string(),
1228        Expr::Index(_) => "index".to_string(),
1229        Expr::Infer(_) => "infer".to_string(),
1230        Expr::Let(_) => "let".to_string(),
1231        Expr::Lit(_) => "lit".to_string(),
1232        Expr::Loop(_) => "loop".to_string(),
1233        Expr::Macro(_) => "macro".to_string(),
1234        Expr::Match(_) => "match".to_string(),
1235        Expr::MethodCall(_) => "method call".to_string(),
1236        Expr::Paren(_) => "paren".to_string(),
1237        Expr::Path(_) => "path".to_string(),
1238        Expr::Range(_) => "range".to_string(),
1239        Expr::Reference(_) => "reference".to_string(),
1240        Expr::Repeat(_) => "repeat".to_string(),
1241        Expr::Return(_) => "return".to_string(),
1242        Expr::Struct(_) => "struct".to_string(),
1243        Expr::Try(_) => "try".to_string(),
1244        Expr::TryBlock(_) => "try block".to_string(),
1245        Expr::Tuple(_) => "tuple".to_string(),
1246        Expr::Unary(_) => "unary".to_string(),
1247        Expr::Unsafe(_) => "unsafe".to_string(),
1248        Expr::Verbatim(_) => "verbatim".to_string(),
1249        Expr::While(_) => "while".to_string(),
1250        Expr::Yield(_) => "yield".to_string(),
1251        _ => "unknown".to_string(),
1252    }
1253}