Newer
Older
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
//! Declaration of the JSON RPC generator procedural macros.
use self::respan::Respan;
use proc_macro2::TokenStream as TokenStream2;
use quote::quote;
use syn::Attribute;
mod attributes;
mod render_client;
mod render_server;
mod respan;
#[derive(Debug, Clone)]
pub struct RpcMethod {
pub name: syn::LitStr,
pub params: Vec<(syn::PatIdent, syn::Type)>,
pub returns: Option<syn::Type>,
pub signature: syn::TraitItemMethod,
}
impl RpcMethod {
pub fn from_item(mut method: syn::TraitItemMethod) -> Result<Self, syn::Error> {
let attributes = attributes::Method::from_attributes(&method.attrs).respan(&method.attrs.first())?;
let sig = method.sig.clone();
let name = attributes.name;
let params: Vec<_> = sig
.inputs
.into_iter()
.filter_map(|arg| match arg {
syn::FnArg::Receiver(_) => None,
syn::FnArg::Typed(arg) => match *arg.pat {
syn::Pat::Ident(name) => Some((name, *arg.ty)),
_ => panic!("Identifier in signature must be an ident"),
},
})
.collect();
let returns = match sig.output {
syn::ReturnType::Default => None,
syn::ReturnType::Type(_, output) => Some(*output),
};
// We've analyzed attributes and don't need them anymore.
method.attrs.clear();
Ok(Self { name, params, returns, signature: method })
}
}
#[derive(Debug, Clone)]
pub struct RpcSubscription {
pub name: syn::LitStr,
pub unsub_method: syn::LitStr,
pub params: Vec<(syn::PatIdent, syn::Type)>,
pub item: syn::Type,
pub signature: syn::TraitItemMethod,
}
impl RpcSubscription {
pub fn from_item(mut sub: syn::TraitItemMethod) -> Result<Self, syn::Error> {
let attributes = attributes::Subscription::from_attributes(&sub.attrs).respan(&sub.attrs.first())?;
let sig = sub.sig.clone();
let name = attributes.name;
let unsub_method = attributes.unsub;
let item = attributes.item;
let params: Vec<_> = sig
.inputs
.into_iter()
.filter_map(|arg| match arg {
syn::FnArg::Receiver(_) => None,
syn::FnArg::Typed(arg) => match *arg.pat {
syn::Pat::Ident(name) => Some((name, *arg.ty)),
_ => panic!("Identifier in signature must be an ident"),
},
})
.collect();
// We've analyzed attributes and don't need them anymore.
sub.attrs.clear();
Ok(Self { name, unsub_method, params, item, signature: sub })
}
}
#[derive(Debug)]
pub struct RpcDescription {
/// Path to the `jsonrpsee` client types part.
jsonrpsee_client_path: Option<TokenStream2>,
/// Path to the `jsonrpsee` server types part.
jsonrpsee_server_path: Option<TokenStream2>,
/// Data about RPC declaration
attrs: attributes::Rpc,
/// Trait definition in which all the attributes were stripped.
trait_def: syn::ItemTrait,
/// List of RPC methods defined in the trait.
methods: Vec<RpcMethod>,
/// List of RPC subscritpions defined in the trait.
subscriptions: Vec<RpcSubscription>,
}
impl RpcDescription {
pub fn from_item(attr: syn::Attribute, mut item: syn::ItemTrait) -> Result<Self, syn::Error> {
let attrs = attributes::Rpc::from_attributes(&[attr.clone()]).respan(&attr)?;
if !attrs.is_correct() {
return Err(syn::Error::new_spanned(&item.ident, "Either 'server' or 'client' attribute must be applied"));
}
let jsonrpsee_client_path = crate::helpers::find_jsonrpsee_client_crate().ok();
let jsonrpsee_server_path = crate::helpers::find_jsonrpsee_server_crate().ok();
if attrs.needs_client() && jsonrpsee_client_path.is_none() {
return Err(syn::Error::new_spanned(&item.ident, "Unable to locate 'jsonrpsee' client dependency"));
}
if attrs.needs_server() && jsonrpsee_server_path.is_none() {
return Err(syn::Error::new_spanned(&item.ident, "Unable to locate 'jsonrpsee' server dependency"));
}
item.attrs.clear(); // Remove RPC attributes.
let mut methods = Vec::new();
let mut subscriptions = Vec::new();
// Go through all the methods in the trait and collect methods and
// subscriptions.
for entry in item.items.iter() {
if let syn::TraitItem::Method(method) = entry {
if method.sig.receiver().is_none() {
return Err(syn::Error::new_spanned(&method.sig, "First argument of the trait must be '&self'"));
}
let mut is_method = false;
let mut is_sub = false;
if has_attr(&method.attrs, "method") {
is_method = true;
let method_data = RpcMethod::from_item(method.clone())?;
methods.push(method_data);
}
if has_attr(&method.attrs, "subscription") {
is_sub = true;
if is_method {
return Err(syn::Error::new_spanned(
&method,
"Element cannot be both subscription and method at the same time",
));
}
if method.sig.asyncness.is_some() {
return Err(syn::Error::new_spanned(&method, "Subscription methods must not be `async`"));
}
if !matches!(method.sig.output, syn::ReturnType::Default) {
return Err(syn::Error::new_spanned(&method, "Subscription methods must not return anything"));
}
let sub_data = RpcSubscription::from_item(method.clone())?;
subscriptions.push(sub_data);
}
if !is_method && !is_sub {
return Err(syn::Error::new_spanned(
&method,
"Methods must have either 'method' or 'subscription' attribute",
));
}
} else {
return Err(syn::Error::new_spanned(&entry, "Only methods allowed in RPC traits"));
}
}
if methods.is_empty() && subscriptions.is_empty() {
return Err(syn::Error::new_spanned(&item, "RPC cannot be empty"));
}
Ok(Self { jsonrpsee_client_path, jsonrpsee_server_path, attrs, trait_def: item, methods, subscriptions })
}
pub fn render(self) -> Result<TokenStream2, syn::Error> {
let server_impl = if self.attrs.needs_server() { self.render_server()? } else { TokenStream2::new() };
let client_impl = if self.attrs.needs_client() { self.render_client()? } else { TokenStream2::new() };
Ok(quote! {
#server_impl
#client_impl
})
}
/// Formats the identifier as a path relative to the resolved
/// `jsonrpsee` client path.
fn jrps_client_item(&self, item: impl quote::ToTokens) -> TokenStream2 {
let jsonrpsee = self.jsonrpsee_client_path.as_ref().unwrap();
quote! { #jsonrpsee::#item }
}
/// Formats the identifier as a path relative to the resolved
/// `jsonrpsee` server path.
fn jrps_server_item(&self, item: impl quote::ToTokens) -> TokenStream2 {
let jsonrpsee = self.jsonrpsee_server_path.as_ref().unwrap();
quote! { #jsonrpsee::#item }
}
/// Based on the namespace, renders the full name of the RPC method/subscription.
/// Examples:
/// For namespace `foo` and method `makeSpam`, result will be `foo_makeSpam`.
/// For no namespace and method `makeSpam` it will be just `makeSpam.
fn rpc_identifier(&self, method: &syn::LitStr) -> String {
if let Some(ns) = &self.attrs.namespace {
format!("{}_{}", ns.value(), method.value())
} else {
method.value()
}
}
}
fn has_attr(attrs: &[Attribute], ident: &str) -> bool {
for attr in attrs.iter().filter_map(|a| a.path.get_ident()) {
if attr == ident {
return true;
}
}
false
}