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
use heck::CamelCase;
use proc_macro2::{Span, TokenStream};
use quote::{format_ident, quote, ToTokens};
use syn::{
    parse::{Error, Parse, ParseStream, Result},
    parse_macro_input, ItemImpl, Token,
};

// The `impl MyActor` the `#[actor]` or `#[async_actor]` attribute was specified on.
struct ActorDef(ItemImpl);

impl Parse for ActorDef {
    fn parse(input: ParseStream) -> Result<Self> {
        let lookahead = input.lookahead1();
        if lookahead.peek(Token![impl]) {
            let item: ItemImpl = input.parse()?;
            if item.trait_.is_some() {
                return Err(Error::new(Span::call_site(), "expected non-trait impl"));
            }
            Ok(Self(item))
        } else {
            Err(lookahead.error())
        }
    }
}

impl ToTokens for ActorDef {
    fn to_tokens(&self, tokens: &mut TokenStream) {
        self.0.to_tokens(tokens);
    }
}

struct MsgType<'a>(&'a ItemImpl);

impl<'a> ToTokens for MsgType<'a> {
    fn to_tokens(&self, tokens: &mut TokenStream) {
        let actor_ty_ident = actor_type_ident(&self.0.self_ty);
        let actor_msg_ident = format_ident!("{}Msg", actor_ty_ident);

        let msg_cases = self.0.items.iter().map(|item| match item {
            syn::ImplItem::Method(method) => method_to_enum_case(method),
            _ => panic!("Method definition expected"),
        });

        let expanded = quote! {
            pub enum #actor_msg_ident {
                #(#msg_cases),*
            }
        };

        expanded.to_tokens(tokens);
    }
}

// This will generate the `impl Actor for MyActor`
struct ImplActor<'a>(&'a ItemImpl);

impl<'a> ToTokens for ImplActor<'a> {
    fn to_tokens(&self, tokens: &mut TokenStream) {
        let actor_ty_ident = actor_type_ident(&self.0.self_ty);
        let actor_msg_ident = format_ident!("{}Msg", actor_ty_ident);

        let pat_cases = self.0.items.iter().map(|item| match item {
            syn::ImplItem::Method(method) => {
                method_to_message_pattern_match(&actor_msg_ident, method, false)
            }
            _ => panic!("Only methods supported in #[actor]"),
        });

        let expanded = quote! {
            impl ::tractor::Actor for #actor_ty_ident {
                type Msg = #actor_msg_ident;
            }

            impl ::tractor::ActorBehavior for #actor_ty_ident {
                fn handle(&mut self, msg: #actor_msg_ident, ctx: &::tractor::Context<Self>) {
                    match msg {
                        #(#pat_cases),*
                    }
                }
            }
        };

        expanded.to_tokens(tokens);
    }
}

// This will generate the `impl AsyncActor for MyActor`
struct ImplAsyncActor<'a>(&'a ItemImpl);

impl<'a> ToTokens for ImplAsyncActor<'a> {
    fn to_tokens(&self, tokens: &mut TokenStream) {
        let actor_ty_ident = actor_type_ident(&self.0.self_ty);
        let actor_msg_ident = format_ident!("{}Msg", actor_ty_ident);

        let pat_cases = self.0.items.iter().map(|item| match item {
            syn::ImplItem::Method(method) => {
                method_to_message_pattern_match(&actor_msg_ident, method, true)
            }
            _ => panic!("Only methods supported in #[actor]"),
        });

        let expanded = quote! {
            impl ::tractor::Actor for #actor_ty_ident {
                type Msg = #actor_msg_ident;
            }

            #[::async_trait::async_trait]
            impl ::tractor::ActorBehaviorAsync for #actor_ty_ident {
                async fn handle(&mut self, msg: #actor_msg_ident, ctx: &::tractor::Context<Self>) {
                    match msg {
                        #(#pat_cases),*
                    }
                }
            }
        };

        expanded.to_tokens(tokens);
    }
}

// This will generate the empty `impl ActorHooks for MyActor {}`
struct ImplActorHooks<'a>(&'a ItemImpl);

impl<'a> ToTokens for ImplActorHooks<'a> {
    fn to_tokens(&self, tokens: &mut TokenStream) {
        let actor_ty_ident = actor_type_ident(&self.0.self_ty);

        let expanded = quote! {
            impl ::tractor::ActorHooks for #actor_ty_ident {
            }
        };

        expanded.to_tokens(tokens);
    }
}
//
// This will generate the empty `impl ActorHooksAsync for MyActor {}`
struct ImplActorHooksAsync<'a>(&'a ItemImpl);

impl<'a> ToTokens for ImplActorHooksAsync<'a> {
    fn to_tokens(&self, tokens: &mut TokenStream) {
        let actor_ty_ident = actor_type_ident(&self.0.self_ty);

        let expanded = quote! {
            impl ::tractor::ActorHooksAsync for #actor_ty_ident {
            }
        };

        expanded.to_tokens(tokens);
    }
}

// This will generate the code for `trait MyActorRef : Channel<MyActorMsg> { .. }`
struct ActorRefTrait<'a>(&'a ItemImpl);

impl<'a> ToTokens for ActorRefTrait<'a> {
    fn to_tokens(&self, tokens: &mut TokenStream) {
        let actor_ty_ident = actor_type_ident(&self.0.self_ty);
        let actor_msg_ident = format_ident!("{}Msg", actor_ty_ident);
        let actor_ref_trait = format_ident!("{}Ref", actor_ty_ident);

        let trait_methods = self.0.items.iter().map(|item| match item {
            syn::ImplItem::Method(method) => method_to_trait_method(&actor_msg_ident, method),
            _ => panic!("Only methods supported in #[actor]"),
        });

        let expanded = quote! {
            pub trait #actor_ref_trait : ::tractor::Address<#actor_ty_ident> {
                #(#trait_methods)*
            }
            impl #actor_ref_trait for Addr<#actor_ty_ident> {}
        };

        expanded.to_tokens(tokens);
    }
}

fn should_derive_hooks(args: proc_macro::TokenStream) -> bool {
    args.into_iter().any(|arg| match arg {
        proc_macro::TokenTree::Ident(ident) => ident.to_string() == "derive_hooks",
        _ => false,
    })
}

#[proc_macro_attribute]
pub fn actor(
    args: proc_macro::TokenStream,
    input: proc_macro::TokenStream,
) -> proc_macro::TokenStream {
    let mut tokens = TokenStream::new();

    let actor_def = parse_macro_input!(input as ActorDef);
    actor_def.to_tokens(&mut tokens);

    MsgType(&actor_def.0).to_tokens(&mut tokens);
    ImplActor(&actor_def.0).to_tokens(&mut tokens);
    ActorRefTrait(&actor_def.0).to_tokens(&mut tokens);

    if should_derive_hooks(args) {
        ImplActorHooks(&actor_def.0).to_tokens(&mut tokens);
    }

    proc_macro::TokenStream::from(tokens)
}

#[proc_macro_attribute]
pub fn async_actor(
    args: proc_macro::TokenStream,
    input: proc_macro::TokenStream,
) -> proc_macro::TokenStream {
    let mut tokens = TokenStream::new();

    let actor_def = parse_macro_input!(input as ActorDef);
    actor_def.to_tokens(&mut tokens);

    MsgType(&actor_def.0).to_tokens(&mut tokens);
    ImplAsyncActor(&actor_def.0).to_tokens(&mut tokens);
    ActorRefTrait(&actor_def.0).to_tokens(&mut tokens);

    if should_derive_hooks(args) {
        ImplActorHooks(&actor_def.0).to_tokens(&mut tokens);
    }

    proc_macro::TokenStream::from(tokens)
}

fn actor_type_ident(ty: &syn::Type) -> syn::Ident {
    match ty {
        syn::Type::Path(type_path) => type_path.path.get_ident().cloned().unwrap(),
        _ => panic!(),
    }
}

fn method_to_enum_case(method: &syn::ImplItemMethod) -> proc_macro2::TokenStream {
    match method.sig.output {
        syn::ReturnType::Default => {}
        _ => panic!("Behaviors have to return ()"),
    }

    let method_name = method.sig.ident.to_string();
    let enum_case_ident = format_ident!("{}", method_name.as_str().to_camel_case());

    let mut inputs_iter = method.sig.inputs.iter();
    match inputs_iter.next() {
        Some(syn::FnArg::Receiver(recv)) if recv.reference.is_some() => {}
        _ => panic!("Behaviors require &self or &mut self receiver"),
    }

    let args = inputs_iter.map(|arg| match arg {
        syn::FnArg::Typed(pat_type) => pat_type,
        _ => panic!(""),
    });

    quote! {
        #enum_case_ident { #(#args),* }
    }
}

// This generates something like:
//
//     AdderMsg::Add {num: m_num} => self.add(m_num)
//
fn method_to_message_pattern_match(
    msg_type: &syn::Ident,
    method: &syn::ImplItemMethod,
    use_await: bool,
) -> proc_macro2::TokenStream {
    match method.sig.output {
        syn::ReturnType::Default => {}
        _ => panic!("Behaviors have to return ()"),
    }

    let method_ident = &method.sig.ident;
    let method_name = method_ident.to_string();
    let enum_case = format_ident!("{}", method_name.as_str().to_camel_case());

    let mut inputs_iter = method.sig.inputs.iter();
    match inputs_iter.next() {
        Some(syn::FnArg::Receiver(recv)) if recv.reference.is_some() => {}
        _ => panic!("Behaviors require &self or &mut self receiver"),
    }

    let args = inputs_iter
        .map(|arg| match arg {
            syn::FnArg::Typed(pat_type) => match pat_type.pat.as_ref() {
                syn::Pat::Ident(pat_ident) => (
                    pat_ident.ident.clone(),
                    format_ident!("m_{}", pat_ident.ident),
                ),
                _ => panic!("Ident required"),
            },
            _ => panic!("Requires syn::FnArg::Typed"),
        })
        .collect::<Vec<_>>();

    let patterns = args.iter().map(|(a, b)| quote! { #a : #b });
    let vars = args.iter().map(|(_a, b)| b);

    if use_await {
        quote! {
            #msg_type :: #enum_case { #(#patterns),* } => self . #method_ident (#(#vars),*) . await
        }
    } else {
        quote! {
            #msg_type :: #enum_case { #(#patterns),* } => self . #method_ident (#(#vars),*)
        }
    }
}

// This generates something like:
//
//     fn add(&self, num: usize) { self.send(AdderMsg::Add {num}) };
//
fn method_to_trait_method(
    msg_type: &syn::Ident,
    method: &syn::ImplItemMethod,
) -> proc_macro2::TokenStream {
    match method.sig.output {
        syn::ReturnType::Default => {}
        _ => panic!("Behaviors have to return ()"),
    }

    let method_ident = &method.sig.ident;
    let method_name = method_ident.to_string();
    let enum_case = format_ident!("{}", method_name.as_str().to_camel_case());

    let args_with_type: Vec<TokenStream> = {
        let mut inputs_iter = method.sig.inputs.iter();
        match inputs_iter.next() {
            Some(syn::FnArg::Receiver(recv)) if recv.reference.is_some() => {}
            _ => panic!("Behaviors require &self or &mut self receiver"),
        }

        inputs_iter
            .map(|arg| match arg {
                syn::FnArg::Typed(pat_type) => quote! { #pat_type },
                _ => panic!("Requires syn::FnArg::Typed"),
            })
            .collect()
    };

    let args: Vec<syn::Ident> = {
        let mut inputs_iter = method.sig.inputs.iter();
        match inputs_iter.next() {
            Some(syn::FnArg::Receiver(recv)) if recv.reference.is_some() => {}
            _ => panic!("Behaviors require &self or &mut self receiver"),
        }

        inputs_iter
            .map(|arg| match arg {
                syn::FnArg::Typed(pat_type) => match pat_type.pat.as_ref() {
                    syn::Pat::Ident(pat_ident) => pat_ident.ident.clone(),
                    _ => panic!("Ident required"),
                },
                _ => panic!("Requires syn::FnArg::Typed"),
            })
            .collect()
    };

    quote! {
        fn #method_ident (&self, #(#args_with_type),*) {
            self.send(#msg_type :: #enum_case { #(#args),* });
        }
    }
}