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
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
use crate::utils::{
extract_block_type_from_trait_path, extract_impl_trait,
extract_parameter_names_types_and_borrows, generate_crate_access, generate_hidden_includes,
generate_method_runtime_api_impl_name, return_type_extract_type, AllowSelfRefInParameters,
RequireQualifiedTraitPath,
};
use proc_macro2::{Span, TokenStream};
use quote::{quote, quote_spanned};
use syn::{
fold::{self, Fold},
parse::{Error, Parse, ParseStream, Result},
parse_macro_input, parse_quote,
spanned::Spanned,
Attribute, Ident, ItemImpl, Pat, Type, TypePath,
};
const HIDDEN_INCLUDES_ID: &str = "MOCK_IMPL_RUNTIME_APIS";
const ADVANCED_ATTRIBUTE: &str = "advanced";
struct RuntimeApiImpls {
impls: Vec<ItemImpl>,
}
impl Parse for RuntimeApiImpls {
fn parse(input: ParseStream) -> Result<Self> {
let mut impls = Vec::new();
while !input.is_empty() {
impls.push(ItemImpl::parse(input)?);
}
if impls.is_empty() {
Err(Error::new(Span::call_site(), "No api implementation given!"))
} else {
Ok(Self { impls })
}
}
}
fn implement_common_api_traits(block_type: TypePath, self_ty: Type) -> Result<TokenStream> {
let crate_ = generate_crate_access(HIDDEN_INCLUDES_ID);
Ok(quote!(
impl #crate_::ApiExt<#block_type> for #self_ty {
type StateBackend = #crate_::InMemoryBackend<#crate_::HashFor<#block_type>>;
fn execute_in_transaction<F: FnOnce(&Self) -> #crate_::TransactionOutcome<R>, R>(
&self,
call: F,
) -> R where Self: Sized {
call(self).into_inner()
}
fn has_api<A: #crate_::RuntimeApiInfo + ?Sized>(
&self,
_: &#crate_::BlockId<#block_type>,
) -> std::result::Result<bool, #crate_::ApiError> where Self: Sized {
Ok(true)
}
fn has_api_with<A: #crate_::RuntimeApiInfo + ?Sized, P: Fn(u32) -> bool>(
&self,
_: &#crate_::BlockId<#block_type>,
pred: P,
) -> std::result::Result<bool, #crate_::ApiError> where Self: Sized {
Ok(pred(A::VERSION))
}
fn api_version<A: #crate_::RuntimeApiInfo + ?Sized>(
&self,
_: &#crate_::BlockId<#block_type>,
) -> std::result::Result<Option<u32>, #crate_::ApiError> where Self: Sized {
Ok(Some(A::VERSION))
}
fn record_proof(&mut self) {
unimplemented!("`record_proof` not implemented for runtime api mocks")
}
fn extract_proof(&mut self) -> Option<#crate_::StorageProof> {
unimplemented!("`extract_proof` not implemented for runtime api mocks")
}
fn proof_recorder(&self) -> Option<#crate_::ProofRecorder<#block_type>> {
unimplemented!("`proof_recorder` not implemented for runtime api mocks")
}
fn into_storage_changes(
&self,
_: &Self::StateBackend,
_: <#block_type as #crate_::BlockT>::Hash,
) -> std::result::Result<
#crate_::StorageChanges<Self::StateBackend, #block_type>,
String
> where Self: Sized {
unimplemented!("`into_storage_changes` not implemented for runtime api mocks")
}
}
impl #crate_::Core<#block_type> for #self_ty {
fn Core_version_runtime_api_impl(
&self,
_: &#crate_::BlockId<#block_type>,
_: #crate_::ExecutionContext,
_: Option<()>,
_: Vec<u8>,
) -> std::result::Result<#crate_::NativeOrEncoded<#crate_::RuntimeVersion>, #crate_::ApiError> {
unimplemented!("Not required for testing!")
}
fn Core_execute_block_runtime_api_impl(
&self,
_: &#crate_::BlockId<#block_type>,
_: #crate_::ExecutionContext,
_: Option<#block_type>,
_: Vec<u8>,
) -> std::result::Result<#crate_::NativeOrEncoded<()>, #crate_::ApiError> {
unimplemented!("Not required for testing!")
}
fn Core_initialize_block_runtime_api_impl(
&self,
_: &#crate_::BlockId<#block_type>,
_: #crate_::ExecutionContext,
_: Option<&<#block_type as #crate_::BlockT>::Header>,
_: Vec<u8>,
) -> std::result::Result<#crate_::NativeOrEncoded<()>, #crate_::ApiError> {
unimplemented!("Not required for testing!")
}
}
))
}
fn has_advanced_attribute(attributes: &mut Vec<Attribute>) -> bool {
let mut found = false;
attributes.retain(|attr| {
if attr.path.is_ident(ADVANCED_ATTRIBUTE) {
found = true;
false
} else {
true
}
});
found
}
fn get_at_param_name(
is_advanced: bool,
param_names: &mut Vec<Pat>,
param_types_and_borrows: &mut Vec<(TokenStream, bool)>,
function_span: Span,
default_block_id_type: &TokenStream,
) -> Result<(TokenStream, TokenStream)> {
if is_advanced {
if param_names.is_empty() {
return Err(Error::new(
function_span,
format!(
"If using the `{}` attribute, it is required that the function \
takes at least one argument, the `BlockId`.",
ADVANCED_ATTRIBUTE,
),
))
}
let ptype_and_borrows = param_types_and_borrows.remove(0);
let span = ptype_and_borrows.1.span();
if !ptype_and_borrows.1 {
return Err(Error::new(
span,
"`BlockId` needs to be taken by reference and not by value!",
))
}
let name = param_names.remove(0);
Ok((quote!( #name ), ptype_and_borrows.0))
} else {
Ok((quote!(_), default_block_id_type.clone()))
}
}
struct FoldRuntimeApiImpl<'a> {
block_type: &'a TypePath,
impl_trait: &'a Ident,
}
impl<'a> Fold for FoldRuntimeApiImpl<'a> {
fn fold_impl_item_method(&mut self, mut input: syn::ImplItemMethod) -> syn::ImplItemMethod {
let block = {
let crate_ = generate_crate_access(HIDDEN_INCLUDES_ID);
let is_advanced = has_advanced_attribute(&mut input.attrs);
let mut errors = Vec::new();
let (mut param_names, mut param_types_and_borrows) =
match extract_parameter_names_types_and_borrows(
&input.sig,
AllowSelfRefInParameters::YesButIgnore,
) {
Ok(res) => (
res.iter().map(|v| v.0.clone()).collect::<Vec<_>>(),
res.iter()
.map(|v| {
let ty = &v.1;
let borrow = &v.2;
(quote_spanned!(ty.span() => #borrow #ty ), v.2.is_some())
})
.collect::<Vec<_>>(),
),
Err(e) => {
errors.push(e.to_compile_error());
(Default::default(), Default::default())
},
};
let block_type = &self.block_type;
let block_id_type = quote!( &#crate_::BlockId<#block_type> );
let (at_param_name, block_id_type) = match get_at_param_name(
is_advanced,
&mut param_names,
&mut param_types_and_borrows,
input.span(),
&block_id_type,
) {
Ok(res) => res,
Err(e) => {
errors.push(e.to_compile_error());
(quote!(_), block_id_type)
},
};
let param_types = param_types_and_borrows.iter().map(|v| &v.0);
input.sig.inputs = parse_quote! {
&self,
#at_param_name: #block_id_type,
_: #crate_::ExecutionContext,
___params___sp___api___: Option<( #( #param_types ),* )>,
_: Vec<u8>,
};
input.sig.ident =
generate_method_runtime_api_impl_name(&self.impl_trait, &input.sig.ident);
if !is_advanced {
let ret_type = return_type_extract_type(&input.sig.output);
input.sig.output = parse_quote!(
-> std::result::Result<#crate_::NativeOrEncoded<#ret_type>, #crate_::ApiError>
);
}
let orig_block = input.block.clone();
let construct_return_value = if is_advanced {
quote!( (move || #orig_block)() )
} else {
quote! {
let __fn_implementation__ = move || #orig_block;
Ok(#crate_::NativeOrEncoded::Native(__fn_implementation__()))
}
};
parse_quote!(
{
#( #errors )*
let (#( #param_names ),*) = ___params___sp___api___
.expect("Mocked runtime apis don't support calling deprecated api versions");
#construct_return_value
}
)
};
let mut input = fold::fold_impl_item_method(self, input);
input.block = block;
input
}
}
struct GeneratedRuntimeApiImpls {
impls: TokenStream,
block_type: TypePath,
self_ty: Type,
}
fn generate_runtime_api_impls(impls: &[ItemImpl]) -> Result<GeneratedRuntimeApiImpls> {
let mut result = Vec::with_capacity(impls.len());
let mut global_block_type: Option<TypePath> = None;
let mut self_ty: Option<Box<Type>> = None;
for impl_ in impls {
let impl_trait_path = extract_impl_trait(&impl_, RequireQualifiedTraitPath::No)?;
let impl_trait = &impl_trait_path
.segments
.last()
.ok_or_else(|| Error::new(impl_trait_path.span(), "Empty trait path not possible!"))?
.clone();
let block_type = extract_block_type_from_trait_path(impl_trait_path)?;
self_ty = match self_ty.take() {
Some(self_ty) =>
if self_ty == impl_.self_ty {
Some(self_ty)
} else {
let mut error = Error::new(
impl_.self_ty.span(),
"Self type should not change between runtime apis",
);
error.combine(Error::new(self_ty.span(), "First self type found here"));
return Err(error)
},
None => Some(impl_.self_ty.clone()),
};
global_block_type = match global_block_type.take() {
Some(global_block_type) =>
if global_block_type == *block_type {
Some(global_block_type)
} else {
let mut error = Error::new(
block_type.span(),
"Block type should be the same between all runtime apis.",
);
error.combine(Error::new(
global_block_type.span(),
"First block type found here",
));
return Err(error)
},
None => Some(block_type.clone()),
};
let mut visitor = FoldRuntimeApiImpl { block_type, impl_trait: &impl_trait.ident };
result.push(visitor.fold_item_impl(impl_.clone()));
}
Ok(GeneratedRuntimeApiImpls {
impls: quote!( #( #result )* ),
block_type: global_block_type.expect("There is a least one runtime api; qed"),
self_ty: *self_ty.expect("There is at least one runtime api; qed"),
})
}
pub fn mock_impl_runtime_apis_impl(input: proc_macro::TokenStream) -> proc_macro::TokenStream {
let RuntimeApiImpls { impls: api_impls } = parse_macro_input!(input as RuntimeApiImpls);
mock_impl_runtime_apis_impl_inner(&api_impls)
.unwrap_or_else(|e| e.to_compile_error())
.into()
}
fn mock_impl_runtime_apis_impl_inner(api_impls: &[ItemImpl]) -> Result<TokenStream> {
let hidden_includes = generate_hidden_includes(HIDDEN_INCLUDES_ID);
let GeneratedRuntimeApiImpls { impls, block_type, self_ty } =
generate_runtime_api_impls(api_impls)?;
let api_traits = implement_common_api_traits(block_type, self_ty)?;
Ok(quote!(
#hidden_includes
#impls
#api_traits
))
}