crabmole-derive 0.1.0

Crabmole derives
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
//! Crabmole derives
#![deny(missing_docs)]

use proc_macro2::{Delimiter, Spacing, TokenTree};
use quote::quote;
use syn::{
    parse::{Parse, Parser},
    Type, Visibility,
};

#[derive(Debug, Default)]
struct Constants {
    normal: Vec<proc_macro2::TokenStream>,
    structs: Vec<proc_macro2::TokenStream>,
}

/// Declare constants like Go.
///
/// # Examples
/// ## All in one
/// ```rust
/// use crabmole_derive::constn;
///
/// pub struct Foo<T, R>(T, R);
///
/// pub struct Bar<R, T>(R, T);
///
/// constn! {
///     u8 {
///         pub FOO_0 = 0;
///         /// The first element
///         pub(crate) FOO_1 = 1;
///         pub FOO_2 = 2;
///     },
///     Foo<u64, i64> {
///         pub FOO_00 = Foo(0, 0);
///         pub FOO_11 = Foo(1, 1);
///         FOO_22 = Foo(2, 2);
///     },
///     impl Foo<u32, u64> {
///         u32 {
///             pub B0 = 0;
///             pub B1 = 1;
///             pub B2 = 2;
///         },
///         Bar<u32, u64> {
///             pub BAR_0 = Bar(0, 0);
///         },
///
///     },
///     impl<T: core::fmt::Debug, R: core::fmt::Debug> Foo<T, R> {
///         Bar<u64, i64> {
///             pub BAR_00 = Bar(0, 0);
///             pub(crate) BAR_11 = Bar(1, 1);
///             BAR_22 = Bar(2, 2);
///         },
///         u32 {
///             pub BAR_1 = 1;
///             pub BAR_2 = 2;
///             pub BAR_3 = 3;
///         }
///     },
/// }
/// ```
///
/// ## Declare constants for struct
/// ```rust
/// use crabmole_derive::constn;
///
/// #[derive(PartialEq, Eq, Debug)]
/// pub struct Foo(u32);
///
/// constn! {
///     u8 {
///         pub U1 = 1;
///         pub(crate) U2 = 2;
///     },
///     Foo {
///
///         pub FOO_A = Foo(1);
///         pub(crate) FOO_B = Foo(2);
///         FOO_C = Foo(3);
///
///     }
/// }
///
/// assert_eq!(FOO_A, Foo(1));
/// assert_eq!(FOO_B, Foo(2));
/// assert_eq!(FOO_C, Foo(3));
/// assert_eq!(U1, 1);
/// assert_eq!(U2, 2);
/// ```
///
/// ## Declare generic constants
/// ```rust
/// use crabmole_derive::constn;
///
/// #[derive(Debug, PartialEq, Eq)]
/// pub struct Foo<T>(T);
///
/// constn! {
///     Foo<u32> {
///         A = Foo(1);
///         pub(crate) B = Foo(2);
///     }
/// }
///
/// assert_eq!(A, Foo(1));
/// assert_eq!(B, Foo(2));
/// ```
///
/// ## Declare constants for generics with trait bounds
/// ```rust
/// use crabmole_derive::constn;
///
/// struct Bar<T>(T);
///
/// constn! {
///     impl<T: core::fmt::Debug> Bar<T> {
///         u8 {
///             pub A = 1;
///             pub(crate) B = 2;
///             C = 3;
///         },
///         u16 {
///             pub D = 1;
///             pub(crate) E = 2;
///             F = 3;
///         }
///     }
/// }
///
/// #[derive(Debug)]
/// struct Baz;
///
/// assert_eq!(Bar::<Baz>::A, 1);
/// assert_eq!(Bar::<Baz>::B, 2);
/// assert_eq!(Bar::<Baz>::C, 3);
/// assert_eq!(Bar::<Baz>::D, 1);
/// assert_eq!(Bar::<Baz>::E, 2);
/// assert_eq!(Bar::<Baz>::F, 3);
/// ```
///
/// ## Declare constants for generics
/// ```rust
/// use crabmole_derive::constn;
///
/// struct Bar<T>(T);
///
/// constn! {
///     impl Bar<u32> {
///         u8 {
///             pub D = 1;
///             pub(crate) E = 2;
///             F = 3;
///         }
///     }
/// }
///
/// assert_eq!(Bar::<u32>::D, 1);
/// assert_eq!(Bar::<u32>::E, 2);
/// assert_eq!(Bar::<u32>::F, 3);
/// ```
#[proc_macro]
pub fn constn(input: proc_macro::TokenStream) -> proc_macro::TokenStream {
    let input: proc_macro2::TokenStream = input.into();
    let mut iter = input.into_iter().peekable();
    let mut consts = Constants::default();
    while let Some(tt) = iter.next() {
        match tt {
            TokenTree::Ident(target) => {
                if target == "impl" {
                    let mut impl_statement = vec![TokenTree::Ident(target)];
                    'inner: for tt in iter.by_ref() {
                        match tt {
                            TokenTree::Group(g)
                                if g.delimiter() == Delimiter::Brace
                                    || g.delimiter() == Delimiter::Parenthesis =>
                            {
                                let sub_iter = g.stream().into_iter();
                                let mut const_ty_segments = Vec::new();
                                let mut impls = Vec::new();
                                let mut next_const_ty = false;
                                for tt in sub_iter {
                                    match tt {
                                        TokenTree::Group(g)
                                            if g.delimiter() == Delimiter::Brace
                                                || g.delimiter() == Delimiter::Parenthesis =>
                                        {
                                            let mut subsub_iter = g.stream().into_iter();
                                            let const_ty = match Type::parse
                                                .parse2(quote! { #(#const_ty_segments)* })
                                            {
                                                Ok(v) => v,
                                                Err(e) => {
                                                    return e.to_compile_error().into();
                                                }
                                            };
                                            let const_exprs = match hanlde_struct_constructs_declare(
                                                const_ty,
                                                &mut subsub_iter,
                                            ) {
                                                Ok(v) => v,
                                                Err(e) => {
                                                    return e.to_compile_error().into();
                                                }
                                            };
                                            impls.push(quote! {
                                                #(#const_exprs)*
                                            });
                                            const_ty_segments.clear();
                                            next_const_ty = true;
                                        }
                                        TokenTree::Punct(p) => {
                                            if p.as_char() == ',' && next_const_ty {
                                                next_const_ty = false;
                                                continue;
                                            } else {
                                                const_ty_segments.push(TokenTree::Punct(p));
                                            }
                                        }
                                        x => {
                                            const_ty_segments.push(x);
                                        }
                                    }
                                }
                                consts.structs.push(quote! {
                                    #(#impl_statement)* {
                                        #(#impls)*
                                    }
                                });
                                break 'inner;
                            }
                            x => impl_statement.push(x),
                        }
                    }
                    impl_statement.clear();
                } else {
                    let mut const_ty_segments = vec![TokenTree::Ident(target)];
                    let mut const_exprs = Vec::new();
                    'inner: for tt in iter.by_ref() {
                        match tt {
                            TokenTree::Group(g)
                                if g.delimiter() == Delimiter::Brace
                                    || g.delimiter() == Delimiter::Parenthesis =>
                            {
                                let mut sub_iter = g.stream().into_iter();
                                let const_ty =
                                    match Type::parse.parse2(quote! { #(#const_ty_segments)* }) {
                                        Ok(v) => v,
                                        Err(e) => {
                                            return e.to_compile_error().into();
                                        }
                                    };
                                const_exprs = match hanlde_normal_constants_declare(
                                    const_ty,
                                    &mut sub_iter,
                                ) {
                                    Ok(v) => v,
                                    Err(e) => {
                                        return e.to_compile_error().into();
                                    }
                                };
                                break 'inner;
                            }
                            x => const_ty_segments.push(x),
                        }
                    }
                    consts.normal.push(quote! {
                        #(#const_exprs)*
                    });
                }
            }
            TokenTree::Punct(p) => {
                if p.as_char() != ',' {
                    return syn::Error::new(p.span(), "constn: expected comma")
                        .to_compile_error()
                        .into();
                }
            }
            x => {
                return syn::Error::new(x.span(), "constn: expected identifier")
                    .to_compile_error()
                    .into()
            }
        }
    }

    let Constants { normal, structs } = consts;

    quote! {
        #(#normal)*

        #(#structs)*
    }
    .into()
}

fn hanlde_struct_constructs_declare(
    ty: Type,
    iter: &mut dyn Iterator<Item = TokenTree>,
) -> syn::Result<Vec<proc_macro2::TokenStream>> {
    let mut constants = Vec::new();
    let mut iter = iter.peekable();
    while iter.peek().is_some() {
        let mut expr = take_while_not_semicolon(&mut iter).into_iter().peekable();
        while expr.peek().is_some() {
            let mut lhs = take_while_equal(&mut expr).into_iter().peekable();
            let (size, _) = lhs.size_hint();
            if size == 1 {
                let rhs = take_after_equal(&mut expr);
                let lhs = match lhs.next().unwrap() {
                    TokenTree::Ident(i) => i,
                    x => return Err(syn::Error::new(x.span(), "constn: expected identifier")),
                };
                constants.push(quote! (
                    const #lhs: #ty = #rhs;
                ));
                continue;
            }

            if size == 2 {
                let rhs = take_after_equal(&mut expr);
                let vis = match lhs.next().unwrap() {
                    TokenTree::Ident(i) => syn::parse_str::<Visibility>(&i.to_string())?,
                    x => return Err(syn::Error::new(x.span(), "constn: expected identifier")),
                };
                let lhs = match lhs.next().unwrap() {
                    TokenTree::Ident(i) => i,
                    x => return Err(syn::Error::new(x.span(), "constn: expected identifier")),
                };
                constants.push(quote! (
                    #vis const #lhs: #ty = #rhs;
                ));
                continue;
            }

            let rhs = take_after_equal(&mut expr);
            let vis = lhs.clone().take(size - 1);
            let lhs = match lhs.last().unwrap() {
                TokenTree::Ident(i) => i,
                x => return Err(syn::Error::new(x.span(), "constn: expected identifier")),
            };
            constants.push(quote! (
                #(#vis)* const #lhs: #ty = #rhs;
            ));
        }
    }

    Ok(constants)
}

fn hanlde_normal_constants_declare(
    ident: Type,
    iter: &mut dyn Iterator<Item = TokenTree>,
) -> syn::Result<Vec<proc_macro2::TokenStream>> {
    let mut constants = Vec::new();
    let mut iter = iter.peekable();
    while iter.peek().is_some() {
        let mut expr = take_while_not_semicolon(&mut iter).into_iter().peekable();
        while expr.peek().is_some() {
            let mut lhs = take_while_equal(&mut expr).into_iter().peekable();
            let (size, _) = lhs.size_hint();
            if size == 1 {
                let rhs = take_after_equal(&mut expr);
                let lhs = match lhs.next().unwrap() {
                    TokenTree::Ident(i) => i,
                    x => return Err(syn::Error::new(x.span(), "constn: expected identifier")),
                };
                constants.push(quote! (
                    const #lhs: #ident = #rhs;
                ));
                continue;
            }

            if size == 2 {
                let rhs = take_after_equal(&mut expr);
                let vis = match lhs.next().unwrap() {
                    TokenTree::Ident(i) => syn::parse_str::<Visibility>(&i.to_string())?,
                    x => return Err(syn::Error::new(x.span(), "constn: expected identifier")),
                };
                let lhs = match lhs.next().unwrap() {
                    TokenTree::Ident(i) => i,
                    x => return Err(syn::Error::new(x.span(), "constn: expected identifier")),
                };
                constants.push(quote! (
                    #vis const #lhs: #ident = #rhs;
                ));
                continue;
            }

            let rhs = take_after_equal(&mut expr);
            let vis = lhs.clone().take(size - 1);
            let lhs = match lhs.last().unwrap() {
                TokenTree::Ident(i) => i,
                x => return Err(syn::Error::new(x.span(), "constn: expected identifier")),
            };
            constants.push(quote! (
                #(#vis)* const #lhs: #ident = #rhs;
            ));
        }
    }

    Ok(constants)
}

fn take_while_not_semicolon(i: &mut dyn Iterator<Item = TokenTree>) -> proc_macro2::TokenStream {
    i.take_while(
        |i| !matches!(i, TokenTree::Punct(p) if p.as_char() == ';' && p.spacing() == Spacing::Alone),
      )
      .collect()
}

fn take_while_equal(i: &mut dyn Iterator<Item = TokenTree>) -> proc_macro2::TokenStream {
    i.take_while(
        |i| !matches!(i, TokenTree::Punct(p) if p.as_char() == '=' && p.spacing() == Spacing::Alone),
      )
      .collect()
}

fn take_after_equal(i: &mut dyn Iterator<Item = TokenTree>) -> proc_macro2::TokenStream {
    i.filter(
        |i| !matches!(i, TokenTree::Punct(p) if p.as_char() != '=' && p.spacing() == Spacing::Alone),
      )
      .collect()
}