essrpc_macros 0.4.0

Macros for ESSRPC. Do not use this crate directly -- use the essrpc crate.
Documentation
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
434
435
//The quote macro can require a high recursion limit
#![recursion_limit = "256"]
// Clippy's suggestions for these don't compile
#![allow(clippy::explicit_counter_loop)]

extern crate proc_macro;
extern crate proc_macro2;
extern crate quote;
extern crate syn;

use core::convert::AsRef;
use proc_macro::TokenStream;
use proc_macro2::TokenStream as TokenStream2;
use proc_macro2::{Ident, Span, TokenTree};
use quote::quote;
use syn::{
    punctuated::Punctuated, token::Comma, /*spanned::Spanned,*/ FnArg, ItemTrait, LitStr, Pat,
    TraitItem, TraitItemMethod,
};

/// The main macro which does the magic. When applied to a trait `Foo`
/// generates a `FooRPCClient` type implementing
/// [RPCClient](../essrpc/trait.RPCClient.html) (and `Foo`).  as well as
/// `FooRPCServer` implementing [RPCServer](../essrpc/trait.RPCServer.html).
///
/// For an asynchronous client, the argument `async` can be used
/// (`#[essrpc(async)]`) to generate a `FooAsync` trait, which is like
/// `Foo` except every method returns a boxed `Future` instead of a
/// `Result` and a `FooAsyncRPCClient` type implementing `FooAsync`
/// and [AsyncRPCClient](../essrpc/trait.AsyncRPCClient.html).
///
/// See the crate-level documentation for examples.
#[proc_macro_attribute]
pub fn essrpc(args: TokenStream, input: TokenStream) -> TokenStream {
    let args: TokenStream2 = args.into();
    let mut sync_client = false;
    let mut async_client = false;
    for tok in args {
        if let TokenTree::Ident(ident) = tok {
            match ident.to_string().as_ref() {
                "sync" => sync_client = true,
                "async" => async_client = true,
                _ => (),
            }
        }
    }

    if !sync_client && !async_client {
        sync_client = true
    }

    let mut result: TokenStream2 = input.clone().into();

    // TODO better error handling
    let ast_trait: ItemTrait = syn::parse(input).unwrap();

    let trait_ident = ast_trait.ident;

    let mut methods: Vec<TraitItemMethod> = Vec::new();

    // Look at each method
    for item in ast_trait.items {
        if let TraitItem::Method(m) = item {
            methods.push(m.clone());
        }
    }

    if async_client {
        result.extend(create_async_client_trait(&trait_ident, &methods));
        result.extend(create_client(
            &async_client_trait_ident(&trait_ident),
            &methods,
            true,
        ));
    }
    if sync_client {
        result.extend(create_client(&trait_ident, &methods, false));
    }
    result.extend(create_server(&trait_ident, &methods));

    result.into()
}

fn client_ident(trait_ident: &Ident) -> Ident {
    Ident::new(&format!("{}RPCClient", trait_ident), Span::call_site())
}

fn client_transport_ident(async_client: bool) -> Ident {
    Ident::new(
        if async_client {
            "AsyncClientTransport"
        } else {
            "ClientTransport"
        },
        Span::call_site(),
    )
}

fn async_client_trait_ident(trait_ident: &Ident) -> Ident {
    Ident::new(&format!("{}Async", trait_ident), Span::call_site())
}

fn rpcclient_ident(async_client: bool) -> Ident {
    Ident::new(
        if async_client {
            "AsyncRPCClient"
        } else {
            "RPCClient"
        },
        Span::call_site(),
    )
}

fn server_ident(trait_ident: &Ident) -> Ident {
    Ident::new(&format!("{}RPCServer", trait_ident), Span::call_site())
}

fn make_pat_literal_str(pat: &Pat) -> LitStr {
    match pat {
        Pat::Ident(p) => make_ident_literal_str(&p.ident),
        _ => panic!("Unhandled PAT type {:?}", pat),
    }
}

fn make_ident_literal_str(ident: &Ident) -> LitStr {
    let as_str = format!("{}", ident);
    LitStr::new(&as_str, Span::call_site())
}

// True if has self param, false if has default implementation. Panics
// if no self and no default.
fn verify_self_param_or_unneeded(method: &TraitItemMethod) -> bool {
    if has_self_param(method) {
        return true;
    }
    if method.default.is_some() {
        // this method is not needed for the RPC client
        return false;
    }
    panic!(
        "RPC trait method {:?} has no self param and no default implementation",
        method
    );
}

fn has_self_param(method: &TraitItemMethod) -> bool {
    let param_tokens = &method.sig.inputs;
    let first = param_tokens.first();
    first.is_some() && (matches!(first.unwrap(), FnArg::Receiver(_)))
}

// Client method implementation for the call to tx_begin_call through
// tx_finalize. This portion is shared between sync and async.
fn client_method_tx_send(method: &TraitItemMethod, id: u32) -> TokenStream2 {
    let ident = &method.sig.ident;
    let param_tokens = &method.sig.inputs;

    let mut add_param_tokens = TokenStream2::new();

    for p in param_tokens.iter() {
        if let FnArg::Typed(arg) = p {
            let name = &arg.pat;
            let name_literal = make_pat_literal_str(name);
            add_param_tokens.extend(quote!(tr.tx_add_param(#name_literal, #name, &mut state)?;));
        }
    }

    let ident_literal = make_ident_literal_str(ident);
    quote!(
        let mut tr = self.tr.lock();
        let mut state = tr.tx_begin_call(essrpc::MethodId{name: #ident_literal, num: #id})?;
        #add_param_tokens
        let state = tr.tx_finalize(state)?;
    )
}

fn async_client_method_tx_send(method: &TraitItemMethod, id: u32) -> TokenStream2 {
    let ident = &method.sig.ident;
    let param_tokens = &method.sig.inputs;

    let mut add_param_tokens = TokenStream2::new();

    for p in param_tokens.iter() {
        if let FnArg::Typed(arg) = p {
            let name = &arg.pat;
            let name_literal = make_pat_literal_str(name);
            add_param_tokens
                .extend(quote!(tr.tx_add_param(#name_literal, #name, &mut state).await?;));
        }
    }

    let ident_literal = make_ident_literal_str(ident);
    quote!(
        let mut tr = self.tr.lock().await;
        let mut state = tr.tx_begin_call(essrpc::MethodId{name: #ident_literal, num: #id}).await?;
        #add_param_tokens
        let state = tr.tx_finalize(state).await?;
    )
}

fn impl_client_method(method: &TraitItemMethod, id: u32) -> TokenStream2 {
    let ident = &method.sig.ident;
    let param_tokens = &method.sig.inputs;

    if !verify_self_param_or_unneeded(method) {
        return TokenStream2::new();
    }

    let rettype = get_return_type(method);

    let tx_send = client_method_tx_send(method, id);

    quote!(
    fn #ident(#param_tokens) -> #rettype {
        #tx_send
        let ret: std::result::Result<#rettype, essrpc::RPCError> =
            tr.rx_response(state);
        match ret {
            Ok(v) => v,
            Err(e) => Err(e.into())
        }
    })
}

fn get_return_type(method: &TraitItemMethod) -> &syn::Type {
    match method.sig.output {
        syn::ReturnType::Default => panic!(
            "RPC methods must have a return type, {} does not ",
            &method.sig.ident
        ),
        syn::ReturnType::Type(_arrow, ref t) => t,
    }
}

fn param_tokens_after_this(method: &TraitItemMethod) -> Punctuated<FnArg, Comma> {
    method.sig.inputs.clone().into_pairs().skip(1).collect()
}

fn impl_async_client_method(method: &TraitItemMethod, id: u32) -> TokenStream2 {
    let ident = &method.sig.ident;

    // get the parameters without the &self as we want to add a lifetime to that
    let param_tokens = param_tokens_after_this(method);

    if !verify_self_param_or_unneeded(method) {
        return TokenStream2::new();
    }

    let rettype = get_return_type(method);
    let tx_send = async_client_method_tx_send(method, id);

    quote!(
    async fn #ident(&self, #param_tokens) -> #rettype {
        #tx_send
        let ret = tr.rx_response(state).await?;
        ret
    })
}

fn create_async_client_trait(trait_ident: &Ident, methods: &[TraitItemMethod]) -> TokenStream2 {
    let ident = async_client_trait_ident(trait_ident);
    let mut method_decls: Vec<TokenStream2> = Vec::new();

    for method in methods {
        let rettype = get_return_type(method);
        let ident = &method.sig.ident;
        let param_tokens = param_tokens_after_this(method);
        method_decls.push(quote!(
        async fn #ident(&self, #param_tokens) -> #rettype;
            ));
    }

    quote!(
        #[essrpc::internal::rpc_async_trait]
        pub trait #ident {
           #(#method_decls)*
        }
    )
}

fn create_client(
    trait_ident: &Ident,
    methods: &[TraitItemMethod],
    async_client: bool,
) -> TokenStream2 {
    let client_ident = client_ident(trait_ident);
    let transport_ident = client_transport_ident(async_client);
    let rpcclient_ident = rpcclient_ident(async_client);

    let mut method_impl_tokens = TokenStream2::new();

    let mut mcnt = 0;
    for method in methods {
        method_impl_tokens.extend(if async_client {
            impl_async_client_method(method, mcnt)
        } else {
            impl_client_method(method, mcnt)
        });
        mcnt += 1;
    }

    let impl_attrs: Option<TokenStream2>;
    // Since our traits generally take &self, but there's no
    // expectation that our transport is Sync, we do need to use a
    // mutex to synchronize the actual RPC calls.
    let mutex_type: TokenStream2;
    if async_client {
        impl_attrs = Some(quote!(#[essrpc::internal::rpc_async_trait]));
        mutex_type = quote!(essrpc::internal::AsyncMutex);
    } else {
        impl_attrs = None;
        mutex_type = quote!(essrpc::internal::SyncMutex);
    };

    quote!(
        pub struct #client_ident<TR: essrpc::#transport_ident> {
            tr: #mutex_type<TR>
        }

        impl <TR> essrpc::#rpcclient_ident for #client_ident<TR> where
            TR: essrpc::#transport_ident {

            type TR = TR;

            fn new(transport: TR) -> Self {
                //#client_ident{tr: std::sync::Arc::new(essrpc::internal::AtomicRefCell::new(transport))}
                #client_ident{tr: #mutex_type::new(transport)}
            }
        }

        #impl_attrs
        impl <TR> #trait_ident for #client_ident<TR> where
            TR: essrpc::#transport_ident {

            #method_impl_tokens
        }
    )
}

fn create_server(trait_ident: &Ident, methods: &[TraitItemMethod]) -> TokenStream2 {
    let server_ident = server_ident(trait_ident);

    let mut server_method_matches = TokenStream2::new();
    let mut server_by_name_matches = TokenStream2::new();

    let mut mcnt = 0;
    for method in methods {
        server_method_matches.extend(create_server_match(method, mcnt));
        let ident_literal = make_ident_literal_str(&method.sig.ident);
        server_by_name_matches.extend(quote!(#ident_literal => #mcnt,));
        mcnt += 1;
    }

    quote!(
        pub struct #server_ident<T, TR> where
            T: #trait_ident,
            TR: essrpc::ServerTransport {

            tr: TR,
            imp: T
        }

        impl <T, TR> #server_ident<T, TR> where
            T: #trait_ident,
            TR: essrpc::ServerTransport {

            pub fn new(imp: T, transport: TR) -> Self {
                #server_ident{tr: transport,
                              imp: imp}
            }

            fn method_num_from_name(name: &str) -> u32 {
                match name {
                    #server_by_name_matches
                    _ => std::u32::MAX
                }
            }

        }

        impl <TR, T> essrpc::RPCServer for #server_ident<T, TR> where
            TR: essrpc::ServerTransport,
            T: #trait_ident
        {
            fn serve_single_call(&mut self) -> std::result::Result<(), essrpc::RPCError> {
                let (method, mut rxstate) = self.tr.rx_begin_call()?;
                let id = match &method {
                    essrpc::PartialMethodId::Num(num) => *num,
                    essrpc::PartialMethodId::Name(name) => Self::method_num_from_name(&name),
                };
                match id {
                    #server_method_matches
                    _ => {
                        Err(essrpc::RPCError::new(
                            essrpc::RPCErrorKind::UnknownMethod, format!("Unknown rpc method {:?}", method)))
                    }
                }
            }
        }
    )
}

fn create_server_match(method: &TraitItemMethod, id: u32) -> TokenStream2 {
    let ident = &method.sig.ident;
    let param_tokens = &method.sig.inputs;

    let mut param_retrieve_tokens = TokenStream2::new();
    let mut param_call_tokens = TokenStream2::new();
    let mut first = true;

    for p in param_tokens.iter() {
        if let FnArg::Typed(arg) = p {
            let name = &arg.pat;
            let name_literal = make_pat_literal_str(name);
            let ty = &arg.ty;
            param_retrieve_tokens.extend(
                quote!(let #name: #ty = self.tr.rx_read_param(#name_literal, &mut rxstate)?;),
            );
            if first {
                first = false;
            } else {
                param_call_tokens.extend(quote!(,))
            }
            param_call_tokens.extend(quote!(#name));
        }
    }

    quote!(
        #id => {
            #param_retrieve_tokens
            let ret = self.imp.#ident(#param_call_tokens);
            self.tr.tx_response(ret)
        },
    )
}