soroban_spec_rust/
trait.rs

1use proc_macro2::TokenStream;
2use quote::{format_ident, quote};
3use stellar_xdr::curr as stellar_xdr;
4use stellar_xdr::ScSpecFunctionV0;
5
6use super::types::generate_type_ident;
7
8/// Constructs a token stream containing a single trait that has a function for
9/// every function spec.
10pub fn generate_trait(name: &str, specs: &[&ScSpecFunctionV0]) -> TokenStream {
11    let trait_ident = format_ident!("{}", name);
12    let fns: Vec<_> = specs
13        .iter()
14        .map(|s| {
15            let fn_ident = format_ident!("{}", s.name.to_utf8_string().unwrap());
16            let fn_inputs = s.inputs.iter().map(|input| {
17                let name = format_ident!("{}", input.name.to_utf8_string().unwrap());
18                let type_ident = generate_type_ident(&input.type_);
19                quote! { #name: #type_ident }
20            });
21            let fn_output = s
22                .outputs
23                .to_option()
24                .map(|t| generate_type_ident(&t))
25                .map(|t| quote! { -> #t });
26            quote! {
27                fn #fn_ident(env: soroban_sdk::Env, #(#fn_inputs),*) #fn_output
28            }
29        })
30        .collect();
31    quote! {
32        pub trait #trait_ident { #(#fns;)* }
33    }
34}