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
extern crate proc_macro;
use proc_macro::{TokenStream, TokenTree};
use proc_macro2::Ident;
use syn::{parse_macro_input, DeriveInput, Data, Fields, Expr, Error};
use quote::quote;
use crate::discord::StructSide;
use syn::spanned::Spanned;
macro_rules! extract_token {
($type:ident in $token:ident) => {
match $token {
::proc_macro::TokenTree::$type(ident) => ident.to_string(),
_ => panic!("Not enough arguments provided to derive macro")
}
};
($type:ident in $token:expr) => {
match $token {
Some(::proc_macro::TokenTree::$type(ident)) => ident.to_string(),
_ => panic!("Not enough arguments provided to derive macro")
}
};
}
mod json;
mod discord;
mod utils;
#[proc_macro_derive(AsJson)]
pub fn as_json(item: TokenStream) -> TokenStream {
let input: DeriveInput = parse_macro_input!(item as DeriveInput);
let name = &input.ident;
let (impl_generics, ty_generics, where_clause) = input.generics.split_for_impl();
if let Data::Struct(data_struct) = &input.data {
if let Fields::Unnamed(unnamed) = &data_struct.fields {
if unnamed.unnamed.len() == 1 {
let quote = quote! {
impl #impl_generics ::automate::encode::AsJson for #name #ty_generics #where_clause {
#[inline]
fn as_json(&self) -> String {
::automate::encode::AsJson::as_json(&self.0)
}
#[inline]
fn concat_json(&self, dest: &mut String) {
::automate::encode::AsJson::concat_json(&self.0, dest)
}
}
};
return quote.into();
} else {
panic!("Structs with multiple unnamed fields are not supported yet");
}
}
let ((fs, fns), (os, ons), recommended_size) = json::extract_fields(data_struct);
let quote = quote! {
impl #impl_generics ::automate::encode::AsJson for #name #ty_generics #where_clause {
#[inline]
fn as_json(&self) -> String {
let mut json = String::with_capacity(#recommended_size);
json.push('{');
#(
json.push_str(concat!("\"", #fns, "\":"));
::automate::encode::AsJson::concat_json(&self.#fs, &mut json);
json.push(',');
)*
#(
if let Some(optional) = &self.#os {
json.push_str(concat!("\"", #ons, "\":"));
::automate::encode::AsJson::concat_json(optional, &mut json);
json.push(',');
}
)*
if json.len() > 1 {
json.pop();
}
json.push('}');
json
}
#[inline]
fn concat_json(&self, dest: &mut String) {
let original_len = dest.len();
dest.push('{');
#(
dest.push_str(concat!("\"", #fns, "\":"));
::automate::encode::AsJson::concat_json(&self.#fs, dest);
dest.push(',');
)*
#(
if let Some(optional) = &self.#os {
dest.push_str(concat!("\"", #ons, "\":"));
::automate::encode::AsJson::concat_json(optional, dest);
dest.push(',');
}
)*
if dest.len() > original_len + 1 {
dest.pop();
}
dest.push('}');
}
}
};
quote.into()
} else {
panic!("AsJson can only be applied to structs");
}
}
#[proc_macro_attribute]
pub fn object(metadata: TokenStream, item: TokenStream) -> TokenStream {
let arguments = utils::parse_arguments_list(metadata);
let mut quote = StructSide::from_args(&arguments).appropriate_derive(&arguments);
quote.extend(item.clone());
let input: DeriveInput = parse_macro_input!(item as DeriveInput);
utils::extend_with_deref(&input, &mut quote);
quote
}
#[proc_macro_attribute]
pub fn payload(metadata: TokenStream, item: TokenStream) -> TokenStream {
let arguments = utils::parse_arguments_list(metadata);
let opcode: u8 = if let Some(tokens) = arguments.get("op") {
if tokens.len() != 2 {
panic!(discord::PAYLOAD_ERROR);
}
if tokens.get(0).unwrap() != "=" {
panic!(discord::PAYLOAD_ERROR);
}
tokens.get(1).unwrap()
.parse::<u8>()
.expect("Expected u8 argument for 'op'")
} else {
panic!(discord::PAYLOAD_ERROR);
};
let event_name: Option<String> = match arguments.get("event") {
Some(tokens) => {
if tokens.len() != 2 {
panic!(discord::PAYLOAD_ERROR);
}
if tokens.get(0).unwrap() != "=" {
panic!(discord::PAYLOAD_ERROR);
}
let name = tokens.get(1).unwrap();
if name.len() < 3 {
panic!(discord::PAYLOAD_ERROR);
}
Some((&name[1..name.len() - 1]).to_owned())
}
None => None
};
let side = StructSide::from_args(&arguments);
let mut quote = side.appropriate_derive(&arguments);
quote.extend(item.clone());
let input: DeriveInput = parse_macro_input!(item as DeriveInput);
let struct_name = &input.ident;
let (impl_generics, ty_generics, where_clause) = input.generics.split_for_impl();
if let Some(event_name) = event_name {
let constant_impl = quote! {
impl #impl_generics #struct_name #ty_generics #where_clause {
pub const EVENT_NAME: &'static str = #event_name;
}
};
quote.extend(TokenStream::from(constant_impl));
}
utils::extend_with_deref(&input, &mut quote);
if let StructSide::Client = side {
discord::append_client_quote(&input, opcode, &mut quote);
} else if let StructSide::Server = side {
discord::append_server_quote(&input, &mut quote);
} else {
discord::append_client_quote(&input, opcode, &mut quote);
discord::append_server_quote(&input, &mut quote);
}
quote
}
#[proc_macro_attribute]
pub fn convert(metadata: TokenStream, item: TokenStream) -> TokenStream {
let cloned_item = item.clone();
let input: DeriveInput = parse_macro_input!(item as DeriveInput);
let struct_name: &Ident = &input.ident;
let (impl_generics, ty_generics, where_clause) = input.generics.split_for_impl();
let (as_method_name, convertion_type): (Ident, Ident) = match metadata.into_iter().next() {
Some(TokenTree::Ident(ty)) => {
let as_method = Ident::new(&format!("as_{}", ty.to_string()), ty.span().into());
let ty = Ident::new(&ty.to_string(), ty.span().into());
(as_method, ty)
}
_ => panic!("Expected arguments under the format (type)")
};
let mut fields_ident: Vec<&Ident> = Vec::new();
let mut fields_expr: Vec<&Expr> = Vec::new();
if let Data::Enum(en) = &input.data {
for variant in &en.variants {
if variant.discriminant.is_none() {
return Error::new(variant.span(), "Convert attribute only supports C-like enums")
.to_compile_error()
.into();
}
let (_, expr) = variant.discriminant.as_ref().unwrap();
fields_ident.push(&variant.ident);
fields_expr.push(expr);
}
} else {
return Error::new(input.span(), "The convert attribute only works on enums")
.to_compile_error()
.into();
}
let mut convertible: TokenStream = quote!(#[derive(Debug, ::serde_repr::Deserialize_repr)]#[repr(#convertion_type)]).into();
convertible.extend(cloned_item);
let as_impl = quote! {
impl #impl_generics #struct_name #ty_generics #where_clause {
fn #as_method_name(&self) -> #convertion_type {
match self {
#(
#struct_name #ty_generics :: #fields_ident => #fields_expr
),*
}
}
}
impl #impl_generics ::automate::encode::AsJson for #struct_name #ty_generics #where_clause {
#[inline]
fn as_json(&self) -> String {
self.#as_method_name().to_string()
}
#[inline]
fn concat_json(&self, dest: &mut String) {
::std::fmt::Write::write_fmt(dest, format_args!("{}", self.#as_method_name())).expect("A Display implementation returned an error unexpectedly");
}
}
};
convertible.extend(TokenStream::from(as_impl));
convertible
}
fn pascal_to_snake(val: String) -> String {
let mut snake = String::new();
for c in val.chars() {
let lc = c.to_ascii_lowercase();
if !snake.is_empty() && lc != c {
snake.push('_');
}
snake.push(lc);
}
snake
}
fn pascal_to_upper_snake(val: String) -> String {
pascal_to_snake(val).to_ascii_uppercase()
}
fn pascal_to_camel(val: String) -> String {
if !val.is_empty() {
let fc = val.chars().next().unwrap();
if fc.to_ascii_lowercase() != fc {
let mut camel = String::from(&val[0..1]);
camel.push_str(&val[1..]);
return camel;
}
}
val
}
#[proc_macro_attribute]
pub fn stringify(metadata: TokenStream, item: TokenStream) -> TokenStream {
let cloned_item = item.clone();
let input: DeriveInput = parse_macro_input!(item as DeriveInput);
let struct_name: &Ident = &input.ident;
let (impl_generics, ty_generics, where_clause) = input.generics.split_for_impl();
let case: String = match metadata.into_iter().next() {
Some(TokenTree::Ident(ident)) => ident.to_string().to_ascii_lowercase(),
_ => panic!("Expected arguments under the format (snake_case|upper_snake_case|camel_case|pascal_case)")
};
let serde_case = match case.as_str() {
"snake_case" => "snake_case",
"upper_snake_case" => "SCREAMING_SNAKE_CASE",
"camel_case" => "camelCase",
"pascal_case" => "PascalCase",
_ => panic!("Expected arguments under the format (snake_case|upper_snake_case|camel_case|pascal_case)")
};
let mut fields_ident: Vec<&Ident> = Vec::new();
let mut fields_str: Vec<String> = Vec::new();
if let Data::Enum(en) = &input.data {
for variant in &en.variants {
if variant.fields.iter().count() > 0 || variant.discriminant.is_some() {
return Error::new(variant.span(), "Stringify attribute only supports enums without fields")
.to_compile_error()
.into();
}
let name = match case.as_str() {
"snake_case" => pascal_to_snake(variant.ident.to_string()),
"upper_snake_case" => pascal_to_upper_snake(variant.ident.to_string()),
"camel_case" => pascal_to_camel(variant.ident.to_string()),
"pascal_case" => variant.ident.to_string(),
_ => panic!("Expected arguments under the format (snake_case|upper_snake_case|camel_case|pascal_case)")
};
fields_ident.push(&variant.ident);
fields_str.push(name);
}
} else {
return Error::new(input.span(), "The stringify attribute only works on enums")
.to_compile_error()
.into();
}
let mut convertible: TokenStream = quote!(#[derive(Debug, Deserialize)]).into();
convertible.extend(TokenStream::from(quote!(#[serde(rename_all(deserialize = #serde_case))])));
convertible.extend(cloned_item);
let as_impl = quote! {
impl #impl_generics #struct_name #ty_generics #where_clause {
#[inline]
fn as_string(&self) -> &'static str {
match self {
#(
#struct_name #ty_generics :: #fields_ident => #fields_str
),*
}
}
}
impl #impl_generics ::automate::encode::AsJson for #struct_name #ty_generics #where_clause {
#[inline]
fn as_json(&self) -> String {
self.as_string().to_owned()
}
#[inline]
fn concat_json(&self, dest: &mut String) {
dest.push_str(self.as_string());
}
}
};
convertible.extend(TokenStream::from(as_impl));
convertible
}