lib.rs 9.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249
  1. use proc_macro::TokenStream;
  2. use proc_macro2::Ident;
  3. use quote::quote;
  4. use syn::{
  5. parse_macro_input, parse_quote, visit_mut::VisitMut, Expr, FnArg, GenericArgument, ItemFn,
  6. ItemMod, ItemStruct, PathArguments, ReturnType, Stmt, Type, TypePath,
  7. };
  8. #[derive(Default)]
  9. struct SystemTransform {
  10. return_values: usize,
  11. }
  12. #[derive(Default)]
  13. struct Extractor {
  14. context_struct_name: Option<String>,
  15. field_count: Option<usize>,
  16. }
  17. /// This macro attribute is used to define a BOLT system.
  18. ///
  19. /// Bolt components are themselves programs. The macro adds parsing and serialization
  20. ///
  21. /// # Example
  22. /// ```ignore
  23. /// #[system]
  24. /// pub mod system_fly {
  25. /// pub fn execute(ctx: Context<Component>, _args: Vec<u8>) -> Result<Position> {
  26. /// let pos = Position {
  27. /// x: ctx.accounts.position.x,
  28. /// y: ctx.accounts.position.y,
  29. /// z: ctx.accounts.position.z + 1,
  30. /// };
  31. /// Ok(pos)
  32. /// }
  33. /// }
  34. /// ```
  35. #[proc_macro_attribute]
  36. pub fn system(attr: TokenStream, item: TokenStream) -> TokenStream {
  37. let mut ast = parse_macro_input!(item as ItemMod);
  38. let _attr = parse_macro_input!(attr as syn::AttributeArgs);
  39. // Extract the number of components from the module
  40. let mut extractor = Extractor::default();
  41. extractor.visit_item_mod_mut(&mut ast);
  42. if let Some(components_len) = extractor.field_count {
  43. let use_super = syn::parse_quote! { use super::*; };
  44. if let Some(ref mut content) = ast.content {
  45. content.1.insert(0, syn::Item::Use(use_super));
  46. }
  47. let mut transform = SystemTransform {
  48. return_values: components_len,
  49. };
  50. transform.visit_item_mod_mut(&mut ast);
  51. // Add `#[program]` macro and try_to_vec implementation
  52. let expanded = quote! {
  53. #[program]
  54. #ast
  55. };
  56. TokenStream::from(expanded)
  57. } else {
  58. panic!(
  59. "Could not find the component bundle: {} in the module",
  60. extractor.context_struct_name.unwrap()
  61. );
  62. }
  63. }
  64. /// Visits the AST and modifies the system function
  65. impl VisitMut for SystemTransform {
  66. // Modify the return instruction to return Result<Vec<u8>>
  67. fn visit_expr_mut(&mut self, expr: &mut Expr) {
  68. if let Some(inner_variable) = Self::extract_inner_ok_expression(expr) {
  69. let new_return_expr: Expr = match inner_variable {
  70. Expr::Tuple(tuple_expr) => {
  71. let tuple_elements = tuple_expr.elems.iter().map(|elem| {
  72. quote! { (#elem).try_to_vec()? }
  73. });
  74. parse_quote! { Ok((#(#tuple_elements),*)) }
  75. }
  76. _ => {
  77. parse_quote! {
  78. #inner_variable.try_to_vec()
  79. }
  80. }
  81. };
  82. *expr = new_return_expr;
  83. }
  84. }
  85. // Modify the return type of the system function to Result<Vec<u8>,*>
  86. fn visit_item_fn_mut(&mut self, item_fn: &mut ItemFn) {
  87. if item_fn.sig.ident == "execute" {
  88. // Modify the return type to Result<Vec<u8>> if necessary
  89. if let ReturnType::Type(_, type_box) = &item_fn.sig.output {
  90. if let Type::Path(type_path) = &**type_box {
  91. if self.return_values > 1 {
  92. item_fn.sig.ident = Ident::new(
  93. format!("execute_{}", self.return_values).as_str(),
  94. item_fn.sig.ident.span(),
  95. );
  96. }
  97. if !Self::check_is_vec_u8(type_path) {
  98. Self::modify_fn_return_type(item_fn, self.return_values);
  99. // Modify the return statement inside the function body
  100. let block = &mut item_fn.block;
  101. for stmt in &mut block.stmts {
  102. if let Stmt::Expr(ref mut expr) | Stmt::Semi(ref mut expr, _) = stmt {
  103. self.visit_expr_mut(expr);
  104. }
  105. }
  106. }
  107. }
  108. }
  109. }
  110. }
  111. // Visit all the functions inside the system module
  112. fn visit_item_mod_mut(&mut self, item_mod: &mut ItemMod) {
  113. for item in &mut item_mod.content.as_mut().unwrap().1 {
  114. if let syn::Item::Fn(item_fn) = item {
  115. self.visit_item_fn_mut(item_fn)
  116. }
  117. }
  118. }
  119. }
  120. impl SystemTransform {
  121. // Helper function to check if a type is `Vec<u8>` or `(Vec<u8>, Vec<u8>, ...)`
  122. fn check_is_vec_u8(ty: &TypePath) -> bool {
  123. if let Some(segment) = ty.path.segments.last() {
  124. if segment.ident == "Result" {
  125. if let PathArguments::AngleBracketed(args) = &segment.arguments {
  126. if let Some(GenericArgument::Type(Type::Tuple(tuple))) = args.args.first() {
  127. return tuple.elems.iter().all(|elem| {
  128. if let Type::Path(type_path) = elem {
  129. if let Some(segment) = type_path.path.segments.first() {
  130. return segment.ident == "Vec" && Self::is_u8_vec(segment);
  131. }
  132. }
  133. false
  134. });
  135. } else if let Some(GenericArgument::Type(Type::Path(type_path))) =
  136. args.args.first()
  137. {
  138. if let Some(segment) = type_path.path.segments.first() {
  139. return segment.ident == "Vec" && Self::is_u8_vec(segment);
  140. }
  141. }
  142. }
  143. }
  144. }
  145. false
  146. }
  147. // Helper function to check if a type is Vec<u8>
  148. fn is_u8_vec(segment: &syn::PathSegment) -> bool {
  149. if let PathArguments::AngleBracketed(args) = &segment.arguments {
  150. if let Some(GenericArgument::Type(Type::Path(path))) = args.args.first() {
  151. if let Some(segment) = path.path.segments.first() {
  152. return segment.ident == "u8";
  153. }
  154. }
  155. }
  156. false
  157. }
  158. // Helper function to modify the return type of a function to be Result<Vec<u8>> or Result<(Vec<u8>, Vec<u8>, ...)>
  159. fn modify_fn_return_type(item_fn: &mut ItemFn, ret_values: usize) {
  160. item_fn.sig.output = if ret_values == 1 {
  161. parse_quote! { -> Result<(Vec<u8>,)> }
  162. } else {
  163. let types = std::iter::repeat(quote! { Vec<u8> })
  164. .take(ret_values)
  165. .collect::<Vec<_>>();
  166. let tuple = quote! { (#(#types),*) };
  167. syn::parse2(quote! { -> Result<#tuple> }).unwrap()
  168. };
  169. }
  170. // Helper function to check if an expression is an `Ok(...)` or `return Ok(...);` variant
  171. fn extract_inner_ok_expression(expr: &Expr) -> Option<&Expr> {
  172. match expr {
  173. Expr::Call(expr_call) => {
  174. // Direct `Ok(...)` call
  175. if let Expr::Path(expr_path) = &*expr_call.func {
  176. if let Some(last_segment) = expr_path.path.segments.last() {
  177. if last_segment.ident == "Ok" && !expr_call.args.is_empty() {
  178. // Return the first argument of the Ok(...) call
  179. return expr_call.args.first();
  180. }
  181. }
  182. }
  183. }
  184. Expr::Return(expr_return) => {
  185. // `return Ok(...);`
  186. if let Some(expr_return_inner) = &expr_return.expr {
  187. if let Expr::Call(expr_call) = expr_return_inner.as_ref() {
  188. if let Expr::Path(expr_path) = &*expr_call.func {
  189. if let Some(last_segment) = expr_path.path.segments.last() {
  190. if last_segment.ident == "Ok" && !expr_call.args.is_empty() {
  191. // Return the first argument of the return Ok(...) call
  192. return expr_call.args.first();
  193. }
  194. }
  195. }
  196. }
  197. }
  198. }
  199. _ => {}
  200. }
  201. None
  202. }
  203. }
  204. /// Visits the AST to extract the number of input components
  205. impl VisitMut for Extractor {
  206. fn visit_item_fn_mut(&mut self, i: &mut ItemFn) {
  207. for input in &i.sig.inputs {
  208. if let FnArg::Typed(pat_type) = input {
  209. if let Type::Path(type_path) = &*pat_type.ty {
  210. let last_segment = type_path.path.segments.last().unwrap();
  211. if last_segment.ident == "Context" {
  212. if let PathArguments::AngleBracketed(args) = &last_segment.arguments {
  213. if let Some(syn::GenericArgument::Type(syn::Type::Path(type_path))) =
  214. args.args.first()
  215. {
  216. let ident = &type_path.path.segments.first().unwrap().ident;
  217. self.context_struct_name = Some(ident.to_string());
  218. }
  219. }
  220. }
  221. }
  222. }
  223. }
  224. }
  225. fn visit_item_struct_mut(&mut self, i: &mut ItemStruct) {
  226. if let Some(name) = &self.context_struct_name {
  227. if i.ident == name {
  228. self.field_count = Some(i.fields.len());
  229. }
  230. }
  231. }
  232. }