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
extern crate proc_macro;
use proc_macro::*;
use quote::quote;
use quote::format_ident;
use syn::{Expr, ExprReturn, FnArg, ReturnType, Stmt};
fn handler(
_attr: TokenStream,
item: TokenStream,
defer_return: quote::__private::TokenStream,
) -> TokenStream {
// There is _probably_ a more efficient way to do what I want to do, but hey I am here
// to learn so why not join me on my quest to create this procedural macro...lol
let mut defer = false;
// Parse the stream of tokens to something more usable.
let input = syn::parse_macro_input!(item as syn::ItemFn);
// Let's see if the programmer wants to respond with a deferring acknowlegdement first.
// If so, the end-result needs to be built differently.
for at in &input.attrs {
for seg in at.path.segments.clone() {
if seg.ident == "defer" {
defer = true;
}
}
}
// Ok here comes the fun part
// Get the function name
let fname = &input.sig.ident;
// Get the visibility (public fn, private fn, etc)
let vis = &input.vis;
// Get the parameters and return types
let params = &input.sig.inputs;
let ret_sig = &input.sig.output;
// Must be filled later, but define its type for now.
let ret: syn::Type;
// Get the function body
let body = &input.block;
// Check for a proper return type and fill ret if found.
match ret_sig {
ReturnType::Default => {
panic!("Expected an `Result<InteractionResponse, ()>` return type, but got no return type. Consider adding `-> Result<InteractionResponse, ()>` to your function signature.");
}
ReturnType::Type(_a, b) => {
ret = *b.clone();
}
}
// Find the name of the Context parameter
let mut ctxname: Option<syn::Ident> = None;
let mut handlename: Option<syn::Ident> = None;
// eprintln!("{:#?}", params);
// I am honestly laughing at this...
// But hey it works! :D
for p in params {
if let FnArg::Typed(t) = p {
match &*t.ty {
// This might be a Context
syn::Type::Path(b) => {
for segment in b.path.segments.clone() {
if segment.ident == "Context" {
if let syn::Pat::Ident(a) = &*t.pat {
ctxname = Some(a.ident.clone());
break;
}
}
else if segment.ident == "InteractionHandler"{
panic!("Cannot take ownership of `InteractionHandler`. Try using &InteractionHandler!")
}
}
}
// This might be an &InteractionHandler!
syn::Type::Reference(r) => {
let e = r.elem.clone();
if let syn::Type::Path(w) = &*e {
for segment in w.path.segments.clone() {
if segment.ident == "InteractionHandler" {
if let syn::Pat::Ident(a) = &*t.pat {
handlename = Some(a.ident.clone());
break;
}
}
}
}
}
_ => {
continue;
}
}
}
if let FnArg::Receiver(_) = p{
panic!("`self` arguments are not allowed. If you need to access data in your function, use the `InteractionHandler.data` field and `InteractionHandler::add_data` method")
}
}
if ctxname.is_none() {
panic!("Couldn't determine the Context parameter. Make sure you take a `Context` as an argument");
}
let mut ih_n = quote!(_);
if handlename.is_some() {
ih_n = quote!(#handlename);
}
// Using quasi-quoting to generate a new function. This is what will be the end function returned to the compiler.
if !defer {
// Build the function
let subst_fn = quote! {
#vis fn #fname (#ih_n: &mut InteractionHandler, #ctxname: Context) -> ::std::pin::Pin<::std::boxed::Box<dyn Send + ::std::future::Future<Output = #ret> + '_>>{
Box::pin(async move {
#body
})
}
};
subst_fn.into()
}
// Deferring is requested, this will require a bit more manipulation.
else {
// Create two functions. One that actually does the work, and one that handles the threading.
let act_fn = format_ident!("__actual_{}", fname);
let subst_fn = quote! {
fn #act_fn (#ih_n: &mut InteractionHandler, #ctxname: Context) -> ::std::pin::Pin<::std::boxed::Box<dyn Send + ::std::future::Future<Output = #ret> + '_>>{
Box::pin(async move {
#body
})
}
#vis fn #fname (ihd: &mut InteractionHandler, ctx: Context) -> ::std::pin::Pin<::std::boxed::Box<dyn Send + ::std::future::Future<Output = #ret> + '_>>{
Box::pin(async move {
// TODO: Try to do this without cloning.
let mut __ih_c = ihd.clone();
::rusty_interaction::actix::Arbiter::spawn(async move {
let __response = #act_fn (&mut __ih_c, ctx.clone()).await;
if let Ok(__r) = __response{
if __r.r#type != InteractionResponseType::Pong && __r.r#type != InteractionResponseType::None{
if let Err(i) = ctx.edit_original(&WebhookMessage::from(__r)).await{
::rusty_interaction::log::error!("Editing original message failed: {:?}", i);
}
}
}
else{
// Nothing
}
});
return InteractionResponseBuilder::default().respond_type(#defer_return).finish();
})
}
};
subst_fn.into()
}
}
#[proc_macro_attribute]
/// Convenience procedural macro that allows you to bind an async function to the [`InteractionHandler`] for handling component interactions.
pub fn component_handler(attr: TokenStream, item: TokenStream) -> TokenStream {
let ret = quote!(::rusty_interaction::types::interaction::InteractionResponseType::DefferedUpdateMessage);
handler(attr, item, ret)
}
#[proc_macro_attribute]
/// Convenience procedural macro that allows you to bind an async function to the [`InteractionHandler`]
pub fn slash_command(attr: TokenStream, item: TokenStream) -> TokenStream {
let ret = quote!(::rusty_interaction::types::interaction::InteractionResponseType::DefferedChannelMessageWithSource);
handler(attr, item, ret)
}
#[proc_macro_attribute]
/// Send out a deffered channel message response before doing work.
pub fn defer(_attr: TokenStream, item: TokenStream) -> TokenStream {
item
}
#[doc(hidden)]
#[proc_macro_attribute]
#[doc(hidden)]
// This is just here to make the tests work...lol
pub fn slash_command_test(_attr: TokenStream, item: TokenStream) -> TokenStream {
// There is _probably_ a more efficient way to do what I want to do, but hey I am here
// to learn so why not join me on my quest to create this procedural macro...lol
let mut defer = false;
// Parse the stream of tokens to something more usable.
let input = syn::parse_macro_input!(item as syn::ItemFn);
// Let's see if the programmer wants to respond with a deferring acknowlegdement first.
// If so, the end-result needs to be built differently.
for at in &input.attrs {
for seg in at.path.segments.clone() {
if seg.ident == "defer" {
defer = true;
}
}
}
// Ok here comes the fun part
// Get the function name
let fname = &input.sig.ident;
// Get the visibility (public fn, private fn, etc)
let vis = &input.vis;
// Get the parameters and return types
let params = &input.sig.inputs;
let ret_sig = &input.sig.output;
// Must be filled later, but define its type for now.
let ret: syn::Type;
// Get the function body
let body = &input.block;
// Check for a proper return type and fill ret if found.
match ret_sig {
ReturnType::Default => {
panic!("Expected an `InteractionResponse` return type, but got no return type. Consider adding `-> InteractionResponse` to your function signature.");
}
ReturnType::Type(_a, b) => {
ret = *b.clone();
}
}
// Find the name of the Context parameter
let mut ctxname: Option<syn::Ident> = None;
let mut handlename: Option<syn::Ident> = None;
// eprintln!("{:#?}", params);
// I am honestly laughing at this...
// But hey it works! :D
for p in params {
if let FnArg::Typed(t) = p {
match &*t.ty {
// This might be a Context
syn::Type::Path(b) => {
for segment in b.path.segments.clone() {
if segment.ident == "Context" {
if let syn::Pat::Ident(a) = &*t.pat {
ctxname = Some(a.ident.clone());
break;
}
}
}
}
// This might be an &InteractionHandler!
syn::Type::Reference(r) => {
let e = r.elem.clone();
if let syn::Type::Path(w) = &*e {
for segment in w.path.segments.clone() {
if segment.ident == "InteractionHandler" {
if let syn::Pat::Ident(a) = &*t.pat {
handlename = Some(a.ident.clone());
break;
}
}
}
}
}
_ => {
continue;
}
}
}
}
if ctxname.is_none() {
panic!("Couldn't determine the Context parameter. Make sure you take a `Context` as an argument");
}
let mut ih_n = quote!(_);
if handlename.is_some() {
ih_n = quote!(#handlename);
}
// Using quasi-quoting to generate a new function. This is what will be the end function returned to the compiler.
if !defer {
// Build the function
let subst_fn = quote! {
#vis fn #fname (#ih_n: &mut InteractionHandler, #ctxname: Context) -> ::std::pin::Pin<::std::boxed::Box<dyn Send + ::std::future::Future<Output = #ret> + '_>>{
Box::pin(async move {
#body
})
}
};
subst_fn.into()
}
// Deferring is requested, this will require a bit more manipulation.
else {
// Find the return statement and split the entire tokenstream there.
let mut ind: Option<usize> = None;
let mut expr: Option<ExprReturn> = None;
for n in 0..body.stmts.len() {
let s = &body.stmts[n];
match s {
Stmt::Expr(Expr::Return(a)) => {
expr = Some(a.clone());
ind = Some(n);
break;
}
Stmt::Semi(Expr::Return(a), _) => {
expr = Some(a.clone());
ind = Some(n);
break;
}
_ => (),
}
}
let (nbody, _reta) = body.stmts.split_at(ind.unwrap_or_else(|| {
panic!(
"Could not find return statement in slash-command. Explicit returns are required."
);
}));
// Unwrap, unwrap, unwrap, unwrap.
let expra = expr
.unwrap_or_else(|| panic!("Expected return"))
.expr
.unwrap_or_else(|| panic!("Expected some return value"));
let nvec = nbody.to_vec();
// Now that we have all the information we need, we can finally start building our new function!
// The difference here being that the non-deffered function doesn't have to spawn a new thread that
// does the actual work. Here we need it to reply with a deffered channel message.
let subst_fn = quote! {
#vis fn #fname (#ih_n: &mut InteractionHandler, #ctxname: Context) -> ::std::pin::Pin<::std::boxed::Box<dyn Send + ::std::future::Future<Output = #ret> + '_>>{
Box::pin(async move {
actix::Arbiter::spawn(async move {
#(#nvec)*
if #expra.r#type != InteractionResponseType::Pong && #expra.r#type != InteractionResponseType::None{
if let Err(i) = #ctxname.edit_original(&WebhookMessage::from(#expra)).await{
error!("Editing original message failed: {:?}", i);
}
}
});
return InteractionResponseBuilder::default().respond_type(InteractionResponseType::DefferedChannelMessageWithSource).finish();
})
}
};
subst_fn.into()
}
}