-
Notifications
You must be signed in to change notification settings - Fork 100
Expand file tree
/
Copy pathderive_event.rs
More file actions
336 lines (311 loc) · 11.4 KB
/
derive_event.rs
File metadata and controls
336 lines (311 loc) · 11.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
use crate::{
attribute::remove_attributes_from_item, default_crate_path, doc::docs_from_attrs,
map_type::map_type, shaking, spec_shaking_v2_enabled, symbol, DEFAULT_XDR_RW_LIMITS,
};
use darling::{ast::NestedMeta, Error, FromMeta};
use heck::ToSnakeCase;
use itertools::Itertools as _;
use proc_macro2::Span;
use proc_macro2::TokenStream as TokenStream2;
use quote::{format_ident, quote};
use stellar_xdr::curr::{
ScSpecEntry, ScSpecEventDataFormat, ScSpecEventParamLocationV0, ScSpecEventParamV0,
ScSpecEventV0, ScSymbol, StringM, WriteXdr,
};
use syn::{parse2, spanned::Spanned, Data, DeriveInput, Fields, LitStr, Path};
#[derive(Debug, FromMeta)]
struct ContractEventArgs {
#[darling(default = "default_crate_path")]
crate_path: Path,
lib: Option<String>,
export: Option<bool>,
#[darling(default)]
topics: Option<Vec<LitStr>>,
#[darling(default)]
data_format: DataFormat,
}
#[derive(Copy, Clone, Debug, Default)]
pub enum DataFormat {
SingleValue,
Vec,
#[default]
Map,
}
impl FromMeta for DataFormat {
fn from_string(v: &str) -> Result<Self, Error> {
match v {
"single-value" => Ok(Self::SingleValue),
"vec" => Ok(Self::Vec),
"map" => Ok(Self::Map),
_ => Err(Error::custom(format!(
r#"data_format {v} must be one of: "single-value", "vec", or "map"."#
))),
}
}
}
impl Into<ScSpecEventDataFormat> for DataFormat {
fn into(self) -> ScSpecEventDataFormat {
match self {
Self::SingleValue => ScSpecEventDataFormat::SingleValue,
Self::Vec => ScSpecEventDataFormat::Vec,
Self::Map => ScSpecEventDataFormat::Map,
}
}
}
pub fn derive_event(metadata: TokenStream2, input: TokenStream2) -> TokenStream2 {
match derive_event_or_err(metadata, input) {
Ok(tokens) => tokens,
Err(err) => err.write_errors(),
}
}
fn derive_event_or_err(metadata: TokenStream2, input: TokenStream2) -> Result<TokenStream2, Error> {
let args = NestedMeta::parse_meta_list(metadata.into())?;
let args = ContractEventArgs::from_list(&args)?;
let input = parse2::<DeriveInput>(input)?;
let derived = derive_impls(&args, &input)?;
let mut input = input;
remove_attributes_from_item(&mut input.data, &["topic", "data"]);
Ok(quote! {
#input
#derived
}
.into())
}
fn derive_impls(args: &ContractEventArgs, input: &DeriveInput) -> Result<TokenStream2, Error> {
// Collect errors as they are encountered and emit them at the end.
let mut errors = Error::accumulator();
let ident = &input.ident;
let (gen_impl, gen_types, gen_where) = input.generics.split_for_impl();
let path = &args.crate_path;
// Check event name length
const EVENT_NAME_LENGTH: u32 = 32;
let event_name = input.ident.to_string();
let event_name_len = event_name.len();
let event_name: StringM<EVENT_NAME_LENGTH> = errors
.handle(event_name.try_into().map_err(|_| {
Error::custom(format!(
"event name has length {event_name_len} greater than length limit of {EVENT_NAME_LENGTH}"
))
.with_span(&input.ident.span())
}))
.unwrap_or_default();
let prefix_topics = if let Some(prefix_topics) = &args.topics {
prefix_topics.iter().map(|t| t.value()).collect()
} else {
vec![input.ident.to_string().to_snake_case()]
};
let fields =
match &input.data {
Data::Struct(struct_) => match &struct_.fields {
Fields::Named(fields) => fields.named.iter().collect::<Vec<_>>(),
Fields::Unnamed(_) => Err(Error::custom(
"structs with unnamed fields are not supported as contract events",
)
.with_span(&struct_.fields.span()))?,
Fields::Unit => Err(Error::custom(
"structs with no fields are not supported as contract events",
)
.with_span(&struct_.fields.span()))?,
},
Data::Enum(_) => Err(Error::custom("enums are not supported as contract events")
.with_span(&input.span()))?,
Data::Union(_) => Err(Error::custom("unions are not supported as contract events")
.with_span(&input.span()))?,
};
// Collect field types for SpecShakingMarker
let field_types: Vec<_> = fields.iter().map(|f| &f.ty).collect();
// Map each field of the struct to a spec for a param.
let params = fields
.iter()
.map(|field| {
let ident = field.ident.as_ref().unwrap();
let is_topic = field.attrs.iter().any(|a| a.path().is_ident("topic"));
let location = if is_topic {
ScSpecEventParamLocationV0::TopicList
} else {
ScSpecEventParamLocationV0::Data
};
let doc = docs_from_attrs(&field.attrs);
const NAME_LENGTH: u32 = 30;
let name = ident.to_string();
let name_len = name.len();
let name: StringM<NAME_LENGTH> = errors
.handle(name.try_into().map_err(|_| {
Error::custom(format!(
"event field name has length {name_len} greater than length limit of {NAME_LENGTH}"
))
.with_span(&field.ident.span())
}))
.unwrap_or_default();
let type_ = errors
.handle_in(|| Ok(map_type(&field.ty, true, false)?))
.unwrap_or_default();
ScSpecEventParamV0 {
location,
doc,
name,
type_,
}
})
.collect::<Vec<_>>();
// If errors have occurred, return them.
let mut errors = errors.checkpoint()?;
// Generated code spec.
let export = args.export.unwrap_or(true);
let export_gen = if export {
Some(quote! { #[cfg_attr(target_family = "wasm", link_section = "contractspecv0")] })
} else {
None
};
let spec_entry = ScSpecEntry::EventV0(ScSpecEventV0 {
data_format: args.data_format.into(),
doc: docs_from_attrs(&input.attrs),
lib: args.lib.as_deref().unwrap_or_default().try_into().unwrap(),
name: ScSymbol(event_name),
prefix_topics: prefix_topics
.iter()
.map(|t| t.try_into().unwrap())
.collect::<Vec<_>>()
.try_into()
.unwrap(),
params: params
.iter()
.map(|p| p.clone())
.collect::<Vec<_>>()
.try_into()
.unwrap(),
});
let spec_xdr = spec_entry.to_xdr(DEFAULT_XDR_RW_LIMITS).unwrap();
let spec_xdr_lit = proc_macro2::Literal::byte_string(spec_xdr.as_slice());
let spec_xdr_len = spec_xdr.len();
let spec_ident = format_ident!(
"__SPEC_XDR_EVENT_{}",
input.ident.to_string().to_uppercase()
);
let spec_shaking_call = if export && spec_shaking_v2_enabled() {
Some(quote! { <Self as #path::SpecShakingMarker>::spec_shaking_marker(); })
} else {
None
};
// Generated code spec.
let spec_gen = quote! {
#export_gen
pub static #spec_ident: [u8; #spec_xdr_len] = #ident::spec_xdr();
impl #gen_impl #ident #gen_types #gen_where {
pub const fn spec_xdr() -> [u8; #spec_xdr_len] {
*#spec_xdr_lit
}
}
};
// SpecShakingMarker impl - only generated when export is true and
// spec shaking v2 is enabled.
let spec_shaking_impl = if export && spec_shaking_v2_enabled() {
Some(shaking::generate_marker_impl(
path,
quote!(#ident),
&spec_xdr,
field_types.iter().cloned(),
Some(quote!(#gen_impl)),
Some(quote!(#gen_types)),
Some(quote!(#gen_where)),
))
} else {
None
};
// Prepare Topics Conversion to Vec<Val>.
let prefix_topics_symbols = prefix_topics.iter().map(|t| {
symbol::short_or_long(
&args.crate_path,
quote!(env),
&LitStr::new(&t, Span::call_site()),
)
});
let topic_idents = params
.iter()
.filter(|p| p.location == ScSpecEventParamLocationV0::TopicList)
.map(|p| format_ident!("{}", p.name.to_string()))
.collect::<Vec<_>>();
let topics_to_vec_val = quote! {
use #path::IntoVal;
(
#(&#prefix_topics_symbols,)*
#({ let v: #path::Val = self.#topic_idents.into_val(env); v },)*
).into_val(env)
};
// Prepare Data Conversion to Val.
let data_params = params
.iter()
.filter(|p| p.location == ScSpecEventParamLocationV0::Data)
.collect::<Vec<_>>();
let data_params_count = data_params.len();
let data_idents = data_params
.iter()
.map(|p| format_ident!("{}", p.name.to_string()))
.collect::<Vec<_>>();
let data_to_val = match args.data_format {
DataFormat::SingleValue if data_params_count == 0 => quote! {
#path::Val::VOID.to_val()
},
DataFormat::SingleValue => {
if data_params_count > 1 {
errors.push(Error::custom(
"data_format = \"single-value\" requires exactly 0 or 1 data fields, but found more",
));
}
quote! {
use #path::IntoVal;
#(self.#data_idents.into_val(env))*
}
}
DataFormat::Vec if data_params_count == 0 => quote! {
use #path::IntoVal;
#path::Vec::<#path::Val>::new(env).into_val(env)
},
DataFormat::Vec => quote! {
use #path::IntoVal;
(
#({ let v: #path::Val = self.#data_idents.into_val(env); v },)*
).into_val(env)
},
DataFormat::Map => {
// Must be sorted for map_new_from_slices
let data_idents_sorted = data_params
.iter()
.sorted_by_key(|p| p.name.to_string())
.map(|p| format_ident!("{}", p.name.to_string()))
.collect::<Vec<_>>();
let data_strs_sorted = data_idents_sorted
.iter()
.map(|i| i.to_string())
.collect::<Vec<_>>();
quote! {
use #path::{EnvBase,IntoVal,unwrap::UnwrapInfallible};
const KEYS: [&'static str; #data_params_count] = [#(#data_strs_sorted),*];
let vals: [#path::Val; #data_params_count] = [
#(self.#data_idents_sorted.into_val(env)),*
];
env.map_new_from_slices(&KEYS, &vals).unwrap_infallible().into()
}
}
};
// Output.
let output = quote! {
#spec_gen
#spec_shaking_impl
impl #gen_impl #path::Event for #ident #gen_types #gen_where {
fn topics(&self, env: &#path::Env) -> #path::Vec<#path::Val> {
#topics_to_vec_val
}
fn data(&self, env: &#path::Env) -> #path::Val {
#data_to_val
}
}
impl #gen_impl #ident #gen_types #gen_where {
pub fn publish(&self, env: &#path::Env) {
#spec_shaking_call
<_ as #path::Event>::publish(self, env);
}
}
};
errors.finish_with(output)
}