lib.rs 2.4 KB

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