1use convert_case::Casing;
2use proc_macro2::Ident;
3use quote::{format_ident, quote};
4
5use crate::Job;
6
7fn to_syn_type(ty: &tx3_lang::ir::Type) -> syn::Type {
8 match ty {
9 tx3_lang::ir::Type::Int => syn::parse_str("i64").unwrap(),
10 tx3_lang::ir::Type::Bool => syn::parse_str("bool").unwrap(),
11 tx3_lang::ir::Type::Bytes => syn::parse_str("Vec<u8>").unwrap(),
12 tx3_lang::ir::Type::Unit => syn::parse_str("()").unwrap(),
13 tx3_lang::ir::Type::Address => syn::parse_str("tx3_lang::ArgValue").unwrap(),
14 tx3_lang::ir::Type::UtxoRef => syn::parse_str("tx3_lang::ArgValue").unwrap(),
15 tx3_lang::ir::Type::Custom(name) => syn::parse_str(name).unwrap(),
16 tx3_lang::ir::Type::AnyAsset => syn::parse_str("tx3_lang::ArgValue").unwrap(),
17 tx3_lang::ir::Type::Undefined => unreachable!(),
18 }
19}
20
21pub fn generate(job: &Job) {
22 let mut output = String::new();
23
24 for tx_def in job.protocol.txs() {
25 let proto_tx = job.protocol.new_tx(&tx_def.name).unwrap();
26 let proto_bytes: Vec<u8> = proto_tx.ir_bytes();
27
28 let bytes_name = format_ident!("PROTO_{}", tx_def.name.to_uppercase());
29
30 let struct_name =
31 format_ident!("{}Params", tx_def.name.to_case(convert_case::Case::Pascal));
32
33 let proto_bytes_literal =
35 syn::LitByteStr::new(&proto_bytes, proc_macro2::Span::call_site());
36
37 let fn_name = format_ident!("new_{}_tx", tx_def.name.to_lowercase());
38
39 let param_names: Vec<Ident> = proto_tx
40 .find_params()
41 .keys()
42 .map(|name| format_ident!("{}", name.to_case(convert_case::Case::Snake)))
43 .collect();
44
45 let param_types: Vec<syn::Type> =
46 proto_tx.find_params().values().map(to_syn_type).collect();
47
48 let tokens = quote! {
49 pub const #bytes_name: &[u8] = #proto_bytes_literal;
50
51 pub struct #struct_name {
52 #(#param_names: #param_types),*
53 }
54
55 pub fn #fn_name(params: #struct_name) -> Result<tx3_lang::ProtoTx, tx3_lang::applying::Error> {
56 let mut proto_tx = tx3_lang::ProtoTx::from_ir_bytes(#bytes_name).unwrap();
57
58 #(proto_tx.set_arg(stringify!(#param_names), params.#param_names.into());)*
59
60 proto_tx.apply()
61 }
62 };
63
64 output.push_str(&tokens.to_string());
65 output.push_str("\n\n");
66 }
67
68 std::fs::write(job.dest_path.join(format!("{}.rs", job.name)), output).unwrap();
69}