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.iter().map(|s| generate_function(*s)).collect();
13    quote! {
14        pub trait #trait_ident { #(#fns;)* }
15    }
16}
17
18/// Constructs a token stream representing a single function definition based on the provided
19/// function specification.
20///
21/// # Parameters
22/// - `s`: A reference to a `ScSpecFunctionV0` containing the specification of the function to generate.
23///
24/// # Returns
25/// A `TokenStream` containing the generated function definition.
26pub fn generate_function(s: &ScSpecFunctionV0) -> TokenStream {
27    let fn_ident = format_ident!("{}", s.name.to_utf8_string().unwrap());
28    let fn_inputs = s.inputs.iter().map(|input| {
29        let name = format_ident!("{}", input.name.to_utf8_string().unwrap());
30        let type_ident = generate_type_ident(&input.type_);
31        quote! { #name: #type_ident }
32    });
33    let fn_output = s
34        .outputs
35        .to_option()
36        .map(|t| generate_type_ident(&t))
37        .map(|t| quote! { -> #t });
38    quote! {
39        fn #fn_ident(env: soroban_sdk::Env, #(#fn_inputs),*) #fn_output
40    }
41}