|
| 1 | +use crate::{ |
| 2 | + attribute::remove_attributes_from_item, default_crate_path, doc::docs_from_attrs, |
| 3 | + map_type::map_type, symbol, DEFAULT_XDR_RW_LIMITS, |
| 4 | +}; |
| 5 | +use darling::{ast::NestedMeta, Error, FromMeta}; |
| 6 | +use heck::ToSnakeCase; |
| 7 | +use proc_macro2::Span; |
| 8 | +use proc_macro2::TokenStream as TokenStream2; |
| 9 | +use quote::{format_ident, quote}; |
| 10 | +use stellar_xdr::curr::{ |
| 11 | + ScSpecEntry, ScSpecEventDataFormat, ScSpecEventParamLocationV0, ScSpecEventParamV0, |
| 12 | + ScSpecEventV0, WriteXdr, |
| 13 | +}; |
| 14 | +use syn::{parse2, spanned::Spanned, Data, DeriveInput, Fields, LitStr, Path}; |
| 15 | + |
| 16 | +#[derive(Debug, FromMeta)] |
| 17 | +struct ContractEventArgs { |
| 18 | + #[darling(default = "default_crate_path")] |
| 19 | + crate_path: Path, |
| 20 | + lib: Option<String>, |
| 21 | + export: Option<bool>, |
| 22 | + #[darling(default)] |
| 23 | + data_format: DataFormat, |
| 24 | + #[darling(default)] |
| 25 | + prefix_topics: Option<Vec<LitStr>>, |
| 26 | +} |
| 27 | + |
| 28 | +#[derive(Copy, Clone, Debug, Default)] |
| 29 | +pub enum DataFormat { |
| 30 | + SingleValue, |
| 31 | + Vec, |
| 32 | + #[default] |
| 33 | + Map, |
| 34 | +} |
| 35 | + |
| 36 | +impl FromMeta for DataFormat { |
| 37 | + fn from_string(v: &str) -> Result<Self, Error> { |
| 38 | + match v { |
| 39 | + "single-value" => Ok(Self::SingleValue), |
| 40 | + "vec" => Ok(Self::Vec), |
| 41 | + "map" => Ok(Self::Map), |
| 42 | + _ => Err(Error::custom(format!( |
| 43 | + r#"data_format {v} must be one of: "single-value", "vec", or "map"."# |
| 44 | + ))), |
| 45 | + } |
| 46 | + } |
| 47 | +} |
| 48 | + |
| 49 | +impl Into<ScSpecEventDataFormat> for DataFormat { |
| 50 | + fn into(self) -> ScSpecEventDataFormat { |
| 51 | + match self { |
| 52 | + Self::SingleValue => ScSpecEventDataFormat::SingleValue, |
| 53 | + Self::Vec => ScSpecEventDataFormat::Vec, |
| 54 | + Self::Map => ScSpecEventDataFormat::Map, |
| 55 | + } |
| 56 | + } |
| 57 | +} |
| 58 | + |
| 59 | +pub fn derive_event(metadata: TokenStream2, input: TokenStream2) -> TokenStream2 { |
| 60 | + match derive_event_or_err(metadata, input) { |
| 61 | + Ok(tokens) => tokens, |
| 62 | + Err(err) => err.write_errors(), |
| 63 | + } |
| 64 | +} |
| 65 | + |
| 66 | +fn derive_event_or_err(metadata: TokenStream2, input: TokenStream2) -> Result<TokenStream2, Error> { |
| 67 | + let args = NestedMeta::parse_meta_list(metadata.into())?; |
| 68 | + let args = ContractEventArgs::from_list(&args)?; |
| 69 | + let input = parse2::<DeriveInput>(input)?; |
| 70 | + let derived = derive_impls(&args, &input)?; |
| 71 | + let mut input = input; |
| 72 | + remove_attributes_from_item(&mut input.data, &["topic", "data"]); |
| 73 | + Ok(quote! { |
| 74 | + #input |
| 75 | + #derived |
| 76 | + } |
| 77 | + .into()) |
| 78 | +} |
| 79 | + |
| 80 | +fn derive_impls(args: &ContractEventArgs, input: &DeriveInput) -> Result<TokenStream2, Error> { |
| 81 | + // Collect errors as they are encountered and emit them at the end. |
| 82 | + let mut errors = Error::accumulator(); |
| 83 | + |
| 84 | + let ident = &input.ident; |
| 85 | + let path = &args.crate_path; |
| 86 | + |
| 87 | + let prefix_topics = if let Some(prefix_topics) = &args.prefix_topics { |
| 88 | + prefix_topics.iter().map(|t| t.value()).collect() |
| 89 | + } else { |
| 90 | + vec![input.ident.to_string().to_snake_case()] |
| 91 | + }; |
| 92 | + |
| 93 | + let fields = |
| 94 | + match &input.data { |
| 95 | + Data::Struct(struct_) => match &struct_.fields { |
| 96 | + Fields::Named(fields) => fields.named.iter(), |
| 97 | + Fields::Unnamed(_) => Err(Error::custom( |
| 98 | + "structs with unnamed fields are not supported as contract events", |
| 99 | + ) |
| 100 | + .with_span(&struct_.fields.span()))?, |
| 101 | + Fields::Unit => Err(Error::custom( |
| 102 | + "structs with no fields are not supported as contract events", |
| 103 | + ) |
| 104 | + .with_span(&struct_.fields.span()))?, |
| 105 | + }, |
| 106 | + Data::Enum(_) => Err(Error::custom("enums are not supported as contract events") |
| 107 | + .with_span(&input.span()))?, |
| 108 | + Data::Union(_) => Err(Error::custom("unions are not supported as contract events") |
| 109 | + .with_span(&input.span()))?, |
| 110 | + }; |
| 111 | + |
| 112 | + // Map each field of the struct to a spec for a param. |
| 113 | + let params = fields |
| 114 | + .map(|field| { |
| 115 | + let ident = field.ident.as_ref().unwrap(); |
| 116 | + let is_topic = field.attrs.iter().any(|a| a.path().is_ident("topic")); |
| 117 | + let location = if is_topic { |
| 118 | + ScSpecEventParamLocationV0::TopicList |
| 119 | + } else { |
| 120 | + ScSpecEventParamLocationV0::Data |
| 121 | + }; |
| 122 | + let doc = docs_from_attrs(&field.attrs); |
| 123 | + let name = errors |
| 124 | + .handle(ident.to_string().try_into().map_err(|_| { |
| 125 | + Error::custom("event field name is too long").with_span(&field.ident.span()) |
| 126 | + })) |
| 127 | + .unwrap_or_default(); |
| 128 | + let type_ = errors |
| 129 | + .handle_in(|| Ok(map_type(&field.ty, false)?)) |
| 130 | + .unwrap_or_default(); |
| 131 | + ScSpecEventParamV0 { |
| 132 | + location, |
| 133 | + doc, |
| 134 | + name, |
| 135 | + type_, |
| 136 | + } |
| 137 | + }) |
| 138 | + .collect::<Vec<_>>(); |
| 139 | + |
| 140 | + // If errors have occurred, return them. |
| 141 | + let errors = errors.checkpoint()?; |
| 142 | + |
| 143 | + // Generated code spec. |
| 144 | + |
| 145 | + let export = args.export.unwrap_or(true); |
| 146 | + let spec_gen = if export { |
| 147 | + let spec_entry = ScSpecEntry::EventV0(ScSpecEventV0 { |
| 148 | + data_format: args.data_format.into(), |
| 149 | + doc: docs_from_attrs(&input.attrs), |
| 150 | + lib: args.lib.as_deref().unwrap_or_default().try_into().unwrap(), |
| 151 | + name: input.ident.to_string().try_into().unwrap(), |
| 152 | + prefix_topics: prefix_topics |
| 153 | + .iter() |
| 154 | + .map(|t| t.try_into().unwrap()) |
| 155 | + .collect::<Vec<_>>() |
| 156 | + .try_into() |
| 157 | + .unwrap(), |
| 158 | + params: params |
| 159 | + .iter() |
| 160 | + .map(|p| p.clone()) |
| 161 | + .collect::<Vec<_>>() |
| 162 | + .try_into() |
| 163 | + .unwrap(), |
| 164 | + }); |
| 165 | + let spec_xdr = spec_entry.to_xdr(DEFAULT_XDR_RW_LIMITS).unwrap(); |
| 166 | + let spec_xdr_lit = proc_macro2::Literal::byte_string(spec_xdr.as_slice()); |
| 167 | + let spec_xdr_len = spec_xdr.len(); |
| 168 | + let spec_ident = format_ident!( |
| 169 | + "__SPEC_XDR_EVENT_{}", |
| 170 | + input.ident.to_string().to_uppercase() |
| 171 | + ); |
| 172 | + let ident = &input.ident; |
| 173 | + Some(quote! { |
| 174 | + #[cfg_attr(target_family = "wasm", link_section = "contractspecv0")] |
| 175 | + pub static #spec_ident: [u8; #spec_xdr_len] = #ident::spec_xdr(); |
| 176 | + |
| 177 | + impl #ident { |
| 178 | + pub const fn spec_xdr() -> [u8; #spec_xdr_len] { |
| 179 | + *#spec_xdr_lit |
| 180 | + } |
| 181 | + } |
| 182 | + }) |
| 183 | + } else { |
| 184 | + None |
| 185 | + }; |
| 186 | + |
| 187 | + // Prepare Topics Conversion to Vec<Val>. |
| 188 | + let prefix_topics_symbols = prefix_topics.iter().map(|t| { |
| 189 | + symbol::short_or_long( |
| 190 | + &args.crate_path, |
| 191 | + quote!(env), |
| 192 | + &LitStr::new(&t, Span::call_site()), |
| 193 | + ) |
| 194 | + }); |
| 195 | + let topic_idents = params |
| 196 | + .iter() |
| 197 | + .filter(|p| p.location == ScSpecEventParamLocationV0::TopicList) |
| 198 | + .map(|p| format_ident!("{}", p.name.to_string())) |
| 199 | + .collect::<Vec<_>>(); |
| 200 | + let topics_to_vec_val = quote! { |
| 201 | + ( |
| 202 | + #(&#prefix_topics_symbols,)* |
| 203 | + #(&self.#topic_idents,)* |
| 204 | + ).into_val(env) |
| 205 | + }; |
| 206 | + |
| 207 | + // Prepare Data Conversion to Val. |
| 208 | + let data_params = params |
| 209 | + .iter() |
| 210 | + .filter(|p| p.location == ScSpecEventParamLocationV0::Data) |
| 211 | + .collect::<Vec<_>>(); |
| 212 | + let data_params_count = data_params.len(); |
| 213 | + let data_idents = data_params |
| 214 | + .iter() |
| 215 | + .map(|p| format_ident!("{}", p.name.to_string())) |
| 216 | + .collect::<Vec<_>>(); |
| 217 | + let data_strs = data_idents |
| 218 | + .iter() |
| 219 | + .map(|i| i.to_string()) |
| 220 | + .collect::<Vec<_>>(); |
| 221 | + let data_to_val = match args.data_format { |
| 222 | + DataFormat::SingleValue if data_params_count == 0 => { |
| 223 | + quote! { |
| 224 | + #path::Val::VOID.to_val() |
| 225 | + } |
| 226 | + } |
| 227 | + DataFormat::SingleValue => { |
| 228 | + quote! { |
| 229 | + use #path::IntoVal; |
| 230 | + #(self.#data_idents.into_val(env))* |
| 231 | + } |
| 232 | + } |
| 233 | + DataFormat::Vec if data_params_count == 0 => quote! { |
| 234 | + use #path::IntoVal; |
| 235 | + #path::Vec::<#path::Val>::new(env).into_val(env) |
| 236 | + }, |
| 237 | + DataFormat::Vec => quote! { |
| 238 | + use #path::IntoVal; |
| 239 | + (#(&self.#data_idents,)*).into_val(env) |
| 240 | + }, |
| 241 | + DataFormat::Map => quote! { |
| 242 | + use #path::{EnvBase,IntoVal,unwrap::UnwrapInfallible}; |
| 243 | + const KEYS: [&'static str; #data_params_count] = [#(#data_strs),*]; |
| 244 | + let vals: [#path::Val; #data_params_count] = [ |
| 245 | + #(self.#data_idents.into_val(env)),* |
| 246 | + ]; |
| 247 | + env.map_new_from_slices(&KEYS, &vals).unwrap_infallible().into() |
| 248 | + }, |
| 249 | + }; |
| 250 | + |
| 251 | + // Output. |
| 252 | + let output = quote! { |
| 253 | + #spec_gen |
| 254 | + |
| 255 | + impl #path::Event for #ident { |
| 256 | + fn topics(&self, env: &#path::Env) -> #path::Vec<#path::Val> { |
| 257 | + #topics_to_vec_val |
| 258 | + } |
| 259 | + fn data(&self, env: &#path::Env) -> #path::Val { |
| 260 | + #data_to_val |
| 261 | + } |
| 262 | + } |
| 263 | + }; |
| 264 | + |
| 265 | + errors.finish_with(output) |
| 266 | +} |
0 commit comments