soroban_env_macros/
lib.rs1mod call_macro_with_all_host_functions;
2mod path;
3mod synth_dispatch_host_fn_tests;
4mod synth_linear_memory_tests;
5mod synth_wasm_expr_type;
6use serde::{Deserialize, Serialize};
7
8extern crate proc_macro;
9
10use proc_macro::TokenStream;
11use quote::{quote, ToTokens};
12use syn::{parse::Parse, parse_macro_input, Ident, LitInt, LitStr, Token};
13
14#[cfg(not(feature = "next"))]
16use stellar_xdr::curr as xdr;
17#[cfg(feature = "next")]
18use stellar_xdr::next as xdr;
19
20use crate::xdr::{Limits, ScEnvMetaEntry, ScEnvMetaEntryInterfaceVersion, WriteXdr};
21
22#[cfg(not(feature = "next"))]
27pub(crate) const LEDGER_PROTOCOL_VERSION: u32 = 22;
28#[cfg(feature = "next")]
29pub(crate) const LEDGER_PROTOCOL_VERSION: u32 = 23;
30
31struct MetaInput {
32 pub interface_version: ScEnvMetaEntryInterfaceVersion,
33}
34
35impl Parse for MetaInput {
36 fn parse(input: syn::parse::ParseStream) -> syn::Result<Self> {
37 Ok(MetaInput {
38 interface_version: {
39 assert_eq!(input.parse::<Ident>()?, "ledger_protocol_version");
40 input.parse::<Token![:]>()?;
41 let proto: u32 = input.parse::<LitInt>()?.base10_parse()?;
42 input.parse::<Token![,]>()?;
43 assert_eq!(input.parse::<Ident>()?, "pre_release_version");
44 input.parse::<Token![:]>()?;
45 let pre: u32 = input.parse::<LitInt>()?.base10_parse()?;
46 input.parse::<Token![,]>()?;
47 assert_eq!(proto, LEDGER_PROTOCOL_VERSION);
48 ScEnvMetaEntryInterfaceVersion {
49 protocol: proto,
50 pre_release: pre,
51 }
52 },
53 })
54 }
55}
56
57struct MetaConstsOutput {
58 pub input: MetaInput,
59}
60
61impl MetaConstsOutput {
62 pub fn to_meta_entries(&self) -> Vec<ScEnvMetaEntry> {
63 vec![ScEnvMetaEntry::ScEnvMetaKindInterfaceVersion(
64 self.input.interface_version.clone(),
65 )]
66 }
67}
68
69impl ToTokens for MetaConstsOutput {
70 fn to_tokens(&self, tokens: &mut proc_macro2::TokenStream) {
71 let proto = &self.input.interface_version.protocol;
73 let pre = &self.input.interface_version.pre_release;
74
75 let meta_xdr = self
77 .to_meta_entries()
78 .into_iter()
79 .map(|entry| entry.to_xdr(Limits::none()))
81 .collect::<Result<Vec<Vec<u8>>, crate::xdr::Error>>()
82 .unwrap()
83 .concat();
84 let meta_xdr_len = meta_xdr.len();
85 let meta_xdr_lit = proc_macro2::Literal::byte_string(meta_xdr.as_slice());
86
87 tokens.extend(quote! {
89 pub const INTERFACE_VERSION: ScEnvMetaEntryInterfaceVersion = ScEnvMetaEntryInterfaceVersion{
90 protocol: #proto,
91 pre_release: #pre,
92 };
93 pub const XDR: [u8; #meta_xdr_len] = *#meta_xdr_lit;
94 });
95 }
96}
97
98#[derive(Default, Debug, Clone, PartialEq, Serialize, Deserialize)]
99pub(crate) struct Root {
100 pub(crate) modules: Vec<Module>,
101}
102
103#[derive(Default, Debug, Clone, PartialEq, Serialize, Deserialize)]
104pub(crate) struct Module {
105 pub(crate) name: String,
106 pub(crate) export: String,
107 pub(crate) functions: Vec<Function>,
108}
109
110#[derive(Default, Debug, Clone, PartialEq, Serialize, Deserialize)]
111pub(crate) struct Function {
112 pub(crate) export: String,
113 pub(crate) name: String,
114 pub(crate) args: Vec<Arg>,
115 pub(crate) r#return: String,
116 pub(crate) docs: Option<String>,
117 pub(crate) min_supported_protocol: Option<u32>,
118 pub(crate) max_supported_protocol: Option<u32>,
119}
120
121#[derive(Default, Debug, Clone, PartialEq, Serialize, Deserialize)]
122#[serde(rename_all = "camelCase")]
123pub(crate) struct Arg {
124 pub(crate) name: String,
125 pub(crate) r#type: String,
126}
127
128fn load_env_file(file_lit: LitStr) -> Result<Root, syn::Error> {
129 let file_str = file_lit.value();
130 let file_path = path::abs_from_rel_to_manifest(&file_str);
131
132 let file = std::fs::File::open(file_path).map_err(|e| {
133 syn::Error::new(
134 file_lit.span(),
135 format!("error reading file '{file_str}': {e}"),
136 )
137 })?;
138
139 serde_json::from_reader(file).map_err(|e| {
140 syn::Error::new(
141 file_lit.span(),
142 format!("error parsing file '{file_str}': {e}"),
143 )
144 })
145}
146
147#[proc_macro]
148pub fn generate_env_meta_consts(input: TokenStream) -> TokenStream {
149 let meta_input = parse_macro_input!(input as MetaInput);
150 let meta_consts_output = MetaConstsOutput { input: meta_input };
151 quote! { #meta_consts_output }.into()
152}
153
154#[proc_macro]
155pub fn generate_call_macro_with_all_host_functions(input: TokenStream) -> TokenStream {
156 let file = parse_macro_input!(input as LitStr);
157 match call_macro_with_all_host_functions::generate(file) {
158 Ok(t) => t.into(),
159 Err(e) => e.to_compile_error().into(),
160 }
161}
162
163#[proc_macro]
164pub fn generate_synth_wasm_expr_type(input: TokenStream) -> TokenStream {
165 let file = parse_macro_input!(input as LitStr);
166 match synth_wasm_expr_type::generate(file) {
167 Ok(t) => t.into(),
168 Err(e) => e.to_compile_error().into(),
169 }
170}
171
172#[proc_macro]
173pub fn generate_synth_dispatch_host_fn_tests(input: TokenStream) -> TokenStream {
174 let file = parse_macro_input!(input as LitStr);
175 let mut impls: TokenStream = TokenStream::new();
176 let wasms: TokenStream =
177 match synth_dispatch_host_fn_tests::generate_wasm_module_calling_host_functions(
178 file.clone(),
179 ) {
180 Ok(t) => t.into(),
181 Err(e) => e.to_compile_error().into(),
182 };
183 let dispatch_wrong_types: TokenStream =
184 match synth_dispatch_host_fn_tests::generate_hostfn_call_with_wrong_types(file.clone()) {
185 Ok(t) => t.into(),
186 Err(e) => e.to_compile_error().into(),
187 };
188 let dispatch_invalid_obj_handles: TokenStream =
189 match synth_dispatch_host_fn_tests::generate_hostfn_call_with_invalid_obj_handles(file) {
190 Ok(t) => t.into(),
191 Err(e) => e.to_compile_error().into(),
192 };
193 impls.extend(wasms);
194 impls.extend(dispatch_wrong_types);
195 impls.extend(dispatch_invalid_obj_handles);
196 impls
197}
198
199#[proc_macro]
200pub fn generate_linear_memory_host_fn_tests(input: TokenStream) -> TokenStream {
201 let file = parse_macro_input!(input as LitStr);
202 let mut impls: TokenStream = TokenStream::new();
203 let wasms: TokenStream =
204 match synth_linear_memory_tests::generate_wasm_module_with_preloaded_linear_memory(file) {
205 Ok(t) => t.into(),
206 Err(e) => e.to_compile_error().into(),
207 };
208 let testset1: TokenStream =
209 match synth_linear_memory_tests::generate_tests_for_malformed_key_slices() {
210 Ok(t) => t.into(),
211 Err(e) => e.to_compile_error().into(),
212 };
213 let testset2: TokenStream =
214 match synth_linear_memory_tests::generate_tests_for_malformed_val_data() {
215 Ok(t) => t.into(),
216 Err(e) => e.to_compile_error().into(),
217 };
218 let testset3: TokenStream = match synth_linear_memory_tests::generate_tests_for_bytes() {
219 Ok(t) => t.into(),
220 Err(e) => e.to_compile_error().into(),
221 };
222 impls.extend(wasms);
223 impls.extend(testset1);
224 impls.extend(testset2);
225 impls.extend(testset3);
226 impls
227}