lib.rs 6.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194
  1. use std::collections::VecDeque;
  2. use proc_macro::TokenStream;
  3. use proc_macro2::{Ident, TokenStream as TokenStream2, TokenTree};
  4. use quote::{quote, quote_spanned, ToTokens};
  5. use syn::{
  6. parse::ParseStream, parse2, parse_macro_input, Attribute, DeriveInput, Fields, GenericArgument,
  7. LitInt, PathArguments, Type, TypeArray,
  8. };
  9. /// Implements a [`Space`](./trait.Space.html) trait on the given
  10. /// struct or enum.
  11. ///
  12. /// For types that have a variable size like String and Vec, it is necessary to indicate the size by the `max_len` attribute.
  13. /// For nested types, it is necessary to specify a size for each variable type (see example).
  14. ///
  15. /// # Example
  16. /// ```ignore
  17. /// #[account]
  18. /// #[derive(InitSpace)]
  19. /// pub struct ExampleAccount {
  20. /// pub data: u64,
  21. /// #[max_len(50)]
  22. /// pub string_one: String,
  23. /// #[max_len(10, 5)]
  24. /// pub nested: Vec<Vec<u8>>,
  25. /// }
  26. ///
  27. /// #[derive(Accounts)]
  28. /// pub struct Initialize<'info> {
  29. /// #[account(mut)]
  30. /// pub payer: Signer<'info>,
  31. /// pub system_program: Program<'info, System>,
  32. /// #[account(init, payer = payer, space = 8 + ExampleAccount::INIT_SPACE)]
  33. /// pub data: Account<'info, ExampleAccount>,
  34. /// }
  35. /// ```
  36. #[proc_macro_derive(InitSpace, attributes(max_len))]
  37. pub fn derive_init_space(item: TokenStream) -> TokenStream {
  38. let input = parse_macro_input!(item as DeriveInput);
  39. let (impl_generics, ty_generics, where_clause) = input.generics.split_for_impl();
  40. let name = input.ident;
  41. let expanded: TokenStream2 = match input.data {
  42. syn::Data::Struct(strct) => match strct.fields {
  43. Fields::Named(named) => {
  44. let recurse = named.named.into_iter().map(|f| {
  45. let mut max_len_args = get_max_len_args(&f.attrs);
  46. len_from_type(f.ty, &mut max_len_args)
  47. });
  48. quote! {
  49. #[automatically_derived]
  50. impl #impl_generics anchor_lang::Space for #name #ty_generics #where_clause {
  51. const INIT_SPACE: usize = 0 #(+ #recurse)*;
  52. }
  53. }
  54. }
  55. _ => panic!("Please use named fields in account structure"),
  56. },
  57. syn::Data::Enum(enm) => {
  58. let variants = enm.variants.into_iter().map(|v| {
  59. let len = v.fields.into_iter().map(|f| {
  60. let mut max_len_args = get_max_len_args(&f.attrs);
  61. len_from_type(f.ty, &mut max_len_args)
  62. });
  63. quote! {
  64. 0 #(+ #len)*
  65. }
  66. });
  67. let max = gen_max(variants);
  68. quote! {
  69. #[automatically_derived]
  70. impl anchor_lang::Space for #name {
  71. const INIT_SPACE: usize = 1 + #max;
  72. }
  73. }
  74. }
  75. _ => unimplemented!(),
  76. };
  77. TokenStream::from(expanded)
  78. }
  79. fn gen_max<T: Iterator<Item = TokenStream2>>(mut iter: T) -> TokenStream2 {
  80. if let Some(item) = iter.next() {
  81. let next_item = gen_max(iter);
  82. quote!(anchor_lang::__private::max(#item, #next_item))
  83. } else {
  84. quote!(0)
  85. }
  86. }
  87. fn len_from_type(ty: Type, attrs: &mut Option<VecDeque<TokenStream2>>) -> TokenStream2 {
  88. match ty {
  89. Type::Array(TypeArray { elem, len, .. }) => {
  90. let array_len = len.to_token_stream();
  91. let type_len = len_from_type(*elem, attrs);
  92. quote!((#array_len * #type_len))
  93. }
  94. Type::Path(ty_path) => {
  95. let path_segment = ty_path.path.segments.last().unwrap();
  96. let ident = &path_segment.ident;
  97. let type_name = ident.to_string();
  98. let first_ty = get_first_ty_arg(&path_segment.arguments);
  99. match type_name.as_str() {
  100. "i8" | "u8" | "bool" => quote!(1),
  101. "i16" | "u16" => quote!(2),
  102. "i32" | "u32" | "f32" => quote!(4),
  103. "i64" | "u64" | "f64" => quote!(8),
  104. "i128" | "u128" => quote!(16),
  105. "String" => {
  106. let max_len = get_next_arg(ident, attrs);
  107. quote!((4 + #max_len))
  108. }
  109. "Pubkey" => quote!(32),
  110. "Option" => {
  111. if let Some(ty) = first_ty {
  112. let type_len = len_from_type(ty, attrs);
  113. quote!((1 + #type_len))
  114. } else {
  115. quote_spanned!(ident.span() => compile_error!("Invalid argument in Vec"))
  116. }
  117. }
  118. "Vec" => {
  119. if let Some(ty) = first_ty {
  120. let max_len = get_next_arg(ident, attrs);
  121. let type_len = len_from_type(ty, attrs);
  122. quote!((4 + #type_len * #max_len))
  123. } else {
  124. quote_spanned!(ident.span() => compile_error!("Invalid argument in Vec"))
  125. }
  126. }
  127. _ => {
  128. let ty = &ty_path.path;
  129. quote!(<#ty as anchor_lang::Space>::INIT_SPACE)
  130. }
  131. }
  132. }
  133. _ => panic!("Type {ty:?} is not supported"),
  134. }
  135. }
  136. fn get_first_ty_arg(args: &PathArguments) -> Option<Type> {
  137. match args {
  138. PathArguments::AngleBracketed(bracket) => bracket.args.iter().find_map(|el| match el {
  139. GenericArgument::Type(ty) => Some(ty.to_owned()),
  140. _ => None,
  141. }),
  142. _ => None,
  143. }
  144. }
  145. fn parse_len_arg(item: ParseStream) -> Result<VecDeque<TokenStream2>, syn::Error> {
  146. let mut result = VecDeque::new();
  147. while let Some(token_tree) = item.parse()? {
  148. match token_tree {
  149. TokenTree::Ident(ident) => result.push_front(quote!((#ident as usize))),
  150. TokenTree::Literal(lit) => {
  151. if let Ok(lit_int) = parse2::<LitInt>(lit.into_token_stream()) {
  152. result.push_front(quote!(#lit_int))
  153. }
  154. }
  155. _ => (),
  156. }
  157. }
  158. Ok(result)
  159. }
  160. fn get_max_len_args(attributes: &[Attribute]) -> Option<VecDeque<TokenStream2>> {
  161. attributes
  162. .iter()
  163. .find(|a| a.path.is_ident("max_len"))
  164. .and_then(|a| a.parse_args_with(parse_len_arg).ok())
  165. }
  166. fn get_next_arg(ident: &Ident, args: &mut Option<VecDeque<TokenStream2>>) -> TokenStream2 {
  167. if let Some(arg_list) = args {
  168. if let Some(arg) = arg_list.pop_back() {
  169. quote!(#arg)
  170. } else {
  171. quote_spanned!(ident.span() => compile_error!("The number of lengths are invalid."))
  172. }
  173. } else {
  174. quote_spanned!(ident.span() => compile_error!("Expected max_len attribute."))
  175. }
  176. }