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
use proc_macro2::{Span, TokenStream};
use syn::{
parse_quote, spanned::Spanned, token, Attribute, Error, FnArg, Ident, ItemTrait, Lit, Meta,
NestedMeta, Pat, PatType, Result, Signature, TraitItem, TraitItemMethod, Type,
};
use proc_macro_crate::{crate_name, FoundCrate};
use std::{
collections::{btree_map::Entry, BTreeMap},
env,
};
use quote::quote;
use inflector::Inflector;
pub struct RuntimeInterfaceFunction<'a> {
latest_version: u32,
versions: BTreeMap<u32, &'a TraitItemMethod>,
}
impl<'a> RuntimeInterfaceFunction<'a> {
fn new(version: u32, trait_item: &'a TraitItemMethod) -> Self {
Self {
latest_version: version,
versions: {
let mut res = BTreeMap::new();
res.insert(version, trait_item);
res
},
}
}
pub fn latest_version(&self) -> (u32, &TraitItemMethod) {
(
self.latest_version,
self.versions.get(&self.latest_version).expect(
"If latest_version has a value, the key with this value is in the versions; qed",
),
)
}
}
pub struct RuntimeInterface<'a> {
items: BTreeMap<syn::Ident, RuntimeInterfaceFunction<'a>>,
}
impl<'a> RuntimeInterface<'a> {
pub fn latest_versions(&self) -> impl Iterator<Item = (u32, &TraitItemMethod)> {
self.items.iter().map(|(_, item)| item.latest_version())
}
pub fn all_versions(&self) -> impl Iterator<Item = (u32, &TraitItemMethod)> {
self.items
.iter()
.flat_map(|(_, item)| item.versions.iter())
.map(|(v, i)| (*v, *i))
}
}
pub fn generate_runtime_interface_include() -> TokenStream {
match crate_name("sp-runtime-interface") {
Ok(FoundCrate::Itself) => quote!(),
Ok(FoundCrate::Name(crate_name)) => {
let crate_name = Ident::new(&crate_name, Span::call_site());
quote!(
#[doc(hidden)]
extern crate #crate_name as proc_macro_runtime_interface;
)
},
Err(e) => {
let err = Error::new(Span::call_site(), e).to_compile_error();
quote!( #err )
},
}
}
pub fn generate_crate_access() -> TokenStream {
if env::var("CARGO_PKG_NAME").unwrap() == "sp-runtime-interface" {
quote!(sp_runtime_interface)
} else {
quote!(proc_macro_runtime_interface)
}
}
pub fn create_exchangeable_host_function_ident(name: &Ident) -> Ident {
Ident::new(&format!("host_{}", name), Span::call_site())
}
pub fn create_host_function_ident(name: &Ident, version: u32, trait_name: &Ident) -> Ident {
Ident::new(
&format!("ext_{}_{}_version_{}", trait_name.to_string().to_snake_case(), name, version),
Span::call_site(),
)
}
pub fn create_function_ident_with_version(name: &Ident, version: u32) -> Ident {
Ident::new(&format!("{}_version_{}", name, version), Span::call_site())
}
pub fn get_function_arguments<'a>(sig: &'a Signature) -> impl Iterator<Item = PatType> + 'a {
sig.inputs
.iter()
.filter_map(|a| match a {
FnArg::Receiver(_) => None,
FnArg::Typed(pat_type) => Some(pat_type),
})
.enumerate()
.map(|(i, arg)| {
let mut res = arg.clone();
if let Pat::Wild(wild) = &*arg.pat {
let ident =
Ident::new(&format!("__runtime_interface_generated_{}_", i), wild.span());
res.pat = Box::new(parse_quote!( #ident ))
}
res
})
}
pub fn get_function_argument_names<'a>(sig: &'a Signature) -> impl Iterator<Item = Box<Pat>> + 'a {
get_function_arguments(sig).map(|pt| pt.pat)
}
pub fn get_function_argument_types<'a>(sig: &'a Signature) -> impl Iterator<Item = Box<Type>> + 'a {
get_function_arguments(sig).map(|pt| pt.ty)
}
pub fn get_function_argument_types_without_ref<'a>(
sig: &'a Signature,
) -> impl Iterator<Item = Box<Type>> + 'a {
get_function_arguments(sig).map(|pt| pt.ty).map(|ty| match *ty {
Type::Reference(type_ref) => type_ref.elem,
_ => ty,
})
}
pub fn get_function_argument_names_and_types_without_ref<'a>(
sig: &'a Signature,
) -> impl Iterator<Item = (Box<Pat>, Box<Type>)> + 'a {
get_function_arguments(sig).map(|pt| match *pt.ty {
Type::Reference(type_ref) => (pt.pat, type_ref.elem),
_ => (pt.pat, pt.ty),
})
}
pub fn get_function_argument_types_ref_and_mut<'a>(
sig: &'a Signature,
) -> impl Iterator<Item = Option<(token::And, Option<token::Mut>)>> + 'a {
get_function_arguments(sig).map(|pt| pt.ty).map(|ty| match *ty {
Type::Reference(type_ref) => Some((type_ref.and_token, type_ref.mutability)),
_ => None,
})
}
fn get_trait_methods<'a>(trait_def: &'a ItemTrait) -> impl Iterator<Item = &'a TraitItemMethod> {
trait_def.items.iter().filter_map(|i| match i {
TraitItem::Method(ref method) => Some(method),
_ => None,
})
}
fn parse_version_attribute(version: &Attribute) -> Result<u32> {
let meta = version.parse_meta()?;
let err = Err(Error::new(
meta.span(),
"Unexpected `version` attribute. The supported format is `#[version(1)]`",
));
match meta {
Meta::List(list) =>
if list.nested.len() != 1 {
err
} else if let Some(NestedMeta::Lit(Lit::Int(i))) = list.nested.first() {
i.base10_parse()
} else {
err
},
_ => err,
}
}
fn get_item_version(item: &TraitItemMethod) -> Result<Option<u32>> {
item.attrs
.iter()
.find(|attr| attr.path.is_ident("version"))
.map(|attr| parse_version_attribute(attr))
.transpose()
}
pub fn get_runtime_interface<'a>(trait_def: &'a ItemTrait) -> Result<RuntimeInterface<'a>> {
let mut functions: BTreeMap<syn::Ident, RuntimeInterfaceFunction<'a>> = BTreeMap::new();
for item in get_trait_methods(trait_def) {
let name = item.sig.ident.clone();
let version = get_item_version(item)?.unwrap_or(1);
match functions.entry(name.clone()) {
Entry::Vacant(entry) => {
entry.insert(RuntimeInterfaceFunction::new(version, item));
},
Entry::Occupied(mut entry) => {
if let Some(existing_item) = entry.get().versions.get(&version) {
let mut err = Error::new(item.span(), "Duplicated version attribute");
err.combine(Error::new(
existing_item.span(),
"Previous version with the same number defined here",
));
return Err(err)
}
let interface_item = entry.get_mut();
if interface_item.latest_version < version {
interface_item.latest_version = version;
}
interface_item.versions.insert(version, item);
},
}
}
for function in functions.values() {
let mut next_expected = 1;
for (version, item) in function.versions.iter() {
if next_expected != *version {
return Err(Error::new(
item.span(),
format!(
"Unexpected version attribute: missing version '{}' for this function",
next_expected
),
))
}
next_expected += 1;
}
}
Ok(RuntimeInterface { items: functions })
}