bolt_anchor_derive_serde/
lib.rs

1extern crate proc_macro;
2
3use borsh_derive_internal::*;
4use proc_macro::TokenStream;
5use proc_macro2::{Span, TokenStream as TokenStream2};
6use syn::{Ident, Item};
7
8fn gen_borsh_serialize(input: TokenStream) -> TokenStream2 {
9    let cratename = Ident::new("borsh", Span::call_site());
10
11    let item: Item = syn::parse(input).unwrap();
12    let res = match item {
13        Item::Struct(item) => struct_ser(&item, cratename),
14        Item::Enum(item) => enum_ser(&item, cratename),
15        Item::Union(item) => union_ser(&item, cratename),
16        // Derive macros can only be defined on structs, enums, and unions.
17        _ => unreachable!(),
18    };
19
20    match res {
21        Ok(res) => res,
22        Err(err) => err.to_compile_error(),
23    }
24}
25
26#[proc_macro_derive(AnchorSerialize, attributes(borsh_skip))]
27pub fn anchor_serialize(input: TokenStream) -> TokenStream {
28    #[cfg(not(feature = "idl-build"))]
29    let ret = gen_borsh_serialize(input);
30    #[cfg(feature = "idl-build")]
31    let ret = gen_borsh_serialize(input.clone());
32
33    #[cfg(feature = "idl-build")]
34    {
35        use anchor_syn::idl::build::*;
36        use quote::quote;
37
38        let idl_build_impl = match syn::parse(input).unwrap() {
39            Item::Struct(item) => impl_idl_build_struct(&item),
40            Item::Enum(item) => impl_idl_build_enum(&item),
41            Item::Union(item) => impl_idl_build_union(&item),
42            // Derive macros can only be defined on structs, enums, and unions.
43            _ => unreachable!(),
44        };
45
46        return TokenStream::from(quote! {
47            #ret
48            #idl_build_impl
49        });
50    };
51
52    #[allow(unreachable_code)]
53    TokenStream::from(ret)
54}
55
56fn gen_borsh_deserialize(input: TokenStream) -> TokenStream2 {
57    let cratename = Ident::new("borsh", Span::call_site());
58
59    let item: Item = syn::parse(input).unwrap();
60    let res = match item {
61        Item::Struct(item) => struct_de(&item, cratename),
62        Item::Enum(item) => enum_de(&item, cratename),
63        Item::Union(item) => union_de(&item, cratename),
64        // Derive macros can only be defined on structs, enums, and unions.
65        _ => unreachable!(),
66    };
67
68    match res {
69        Ok(res) => res,
70        Err(err) => err.to_compile_error(),
71    }
72}
73
74#[proc_macro_derive(AnchorDeserialize, attributes(borsh_skip, borsh_init))]
75pub fn borsh_deserialize(input: TokenStream) -> TokenStream {
76    TokenStream::from(gen_borsh_deserialize(input))
77}