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