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 }
18}
19
20pub fn generate(job: &Job) {
21 let mut output = String::new();
22
23 for tx_def in job.protocol.txs() {
24 let proto_tx = job.protocol.new_tx(&tx_def.name).unwrap();
25 let proto_bytes: Vec<u8> = proto_tx.ir_bytes();
26
27 let bytes_name = format_ident!("PROTO_{}", tx_def.name.to_uppercase());
28
29 let struct_name =
30 format_ident!("{}Params", tx_def.name.to_case(convert_case::Case::Pascal));
31
32 let proto_bytes_literal =
34 syn::LitByteStr::new(&proto_bytes, proc_macro2::Span::call_site());
35
36 let fn_name = format_ident!("new_{}_tx", tx_def.name.to_lowercase());
37
38 let param_names: Vec<Ident> = proto_tx
39 .find_params()
40 .keys()
41 .map(|name| format_ident!("{}", name.to_case(convert_case::Case::Snake)))
42 .collect();
43
44 let param_types: Vec<syn::Type> =
45 proto_tx.find_params().values().map(to_syn_type).collect();
46
47 let tokens = quote! {
48 pub const #bytes_name: &[u8] = #proto_bytes_literal;
49
50 pub struct #struct_name {
51 #(#param_names: #param_types),*
52 }
53
54 pub fn #fn_name(params: #struct_name) -> Result<tx3_lang::ProtoTx, tx3_lang::applying::Error> {
55 let mut proto_tx = tx3_lang::ProtoTx::from_ir_bytes(#bytes_name).unwrap();
56
57 #(proto_tx.set_arg(stringify!(#param_names), params.#param_names.into());)*
58
59 proto_tx.apply()
60 }
61 };
62
63 output.push_str(&tokens.to_string());
64 output.push_str("\n\n");
65 }
66
67 std::fs::write(job.dest_path.join(format!("{}.rs", job.name)), output).unwrap();
68}