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

//! # stateful_macro_rules
//!
//! `stateful_macro_rules` makes it easier to write `macro_rules` with states.
//! It is especially useful where the `macro_rule` needs to take a list of
//! inputs with various patterns.
//!
//! Refer to [`stateful_macro_rules`](macro.stateful_macro_rules.html) for
//! the documentation of the main macro.

use proc_macro::TokenStream as StdTokenStream;
use proc_macro2::TokenStream;

mod error;
mod state;
mod util;

use error::Error;
use error::Result;
use state::StatefulMacroRule;
use util::describe_tokens;
use util::split_meta;
use util::split_tokens;
use util::Describe::{G, I, P};

/// Generate `macro_rules!` macros that have states.
///
/// ## Basic: Macro name and body
///
/// To specify the generated macro name and its final expanded content, use
/// `name() { body }`.
///
/// For example, the code below generates a macro called `foo!()` and it
/// expands to `"foo"`.
///
/// ```
/// # use stateful_macro_rules::stateful_macro_rules;
/// stateful_macro_rules! {
///     foo() { "foo" };
/// }
/// ```
///
/// ## States
///
/// To define states, add them to the `()` after the macro name. A state can
/// be defined as `state_name: (pattern) = (default_value))`. Multiple
/// states are separated by `,`. States can be referred by their pattern
/// name.
///
/// For example, the code below defines a `plus!()` macro with `x` and `y`
/// states (but there is no real way to use this macro):
///
/// ```
/// # use stateful_macro_rules::stateful_macro_rules;
/// stateful_macro_rules! {
///     pos(x: ($x:expr) = (0), y: ($y:expr) = (0)) { ($x, $y) };
/// }
/// ```
///
/// ## Rules
///
/// To make the macro useful, macro rules like `(pattern) => { body }` are
/// needed. Unlike rules in classic `macro_rules!`, the `pattern` matches
/// incomplete tokens (use `...` to mark the incomplete portion), and `body`
/// can only contain changes to states like `state_name.set(tokens)`, or
/// `state_name.append(tokens)`.
///
/// ```
/// # #![allow(macro_expanded_macro_exports_accessed_by_absolute_paths)]
/// # use stateful_macro_rules::stateful_macro_rules;
/// stateful_macro_rules! {
///     pos(x: ($x:expr) = (0), y: ($y:expr) = (0)) { ($x, $y) };
///     (incx($i:expr) ...) => { x.set($x + $i); };
///     (incx ...) => { x.set($x + 1); };
///     (incy($i:expr) ...) => { y.set($y + $i); };
///     (incy ...) => { y.set($y + 1); };
///
///     // `...` is implicitly at the end
///     (reset) => { x.set(0); y.set(0); };  
///
///     // `...` can be in the middle
///     (eval( ... )) => { };
/// }
/// assert_eq!(pos!(incx(3) reset incy incy(10) incx), (1, 11));
/// assert_eq!(pos!(eval(incx(10) incy(20))), (10, 20));
/// ```
///
/// # Conditional Rules
///
/// Rules can be disabled by states. This is done by the `when` block.
///
/// ```
/// # #![allow(macro_expanded_macro_exports_accessed_by_absolute_paths)]
/// # use stateful_macro_rules::stateful_macro_rules;
/// stateful_macro_rules! {
///     toggle(result: ($v:tt) = (0)) { $v };
///     (T) when { result: (0) } => { result.set(1); };
///     (T) when { result: (1) } => { result.set(0); };
/// }
/// assert_eq!(toggle![T T T], 1);
/// ```
///
/// # Debugging
///
/// If the `debug` feature is on, `debug;` can be used to print the
/// generated code to stderr. The code can be used as a drop-in macro
/// replacement to help debugging.
#[proc_macro]
pub fn stateful_macro_rules(input: StdTokenStream) -> StdTokenStream {
    match stateful_macro_rules_fallible(input.into()) {
        Ok(t) => t.into(),
        Err(e) => e.into(),
    }
}

pub(crate) fn stateful_macro_rules_fallible(input: TokenStream) -> Result<TokenStream> {
    let mut rule = StatefulMacroRule::default();
    #[cfg(feature = "debug")]
    let mut debug = false;
    for tokens in split_tokens(input, ';') {
        let (meta, tokens) = split_meta(&tokens);
        match describe_tokens(tokens)[..] {
            // #[doc = r"foo"]
            // name ( k: ty = v, k: ty = v, ) { result }
            [I(i), G('(', s), G('{', r)] => {
                rule.set_attributes(meta)?;
                rule.set_name(i.clone())?;
                rule.set_state(s)?;
                rule.set_return(None, r)?;
            }

            // #[doc = r"foo"]
            // name ( k: ty = v, k: ty = v, ) { result }
            [I(i), G('(', s), I(iw), G('{', w), G('{', r)] if iw.to_string() == "when" => {
                rule.set_attributes(meta)?;
                rule.set_name(i.clone())?;
                rule.set_state(s)?;
                rule.set_return(Some(w.stream()), r)?;
            }

            // (pat) => { ... }
            [G('(', pat), P('='), P('>'), G('{', body)] => {
                rule.append_rule(pat.stream(), None, body.stream())?;
            }

            // (pat) when { state_name: (pat), ... } => { ... }
            [G('(', pat), I(w), G('{', state), P('='), P('>'), G('{', body)]
                if w.to_string() == "when" =>
            {
                rule.append_rule(pat.stream(), Some(state.stream()), body.stream())?;
            }

            // fs_write_expanded(path). write expanded macro to a specific file for debugging
            // purpose.
            #[cfg(feature = "debug")]
            [I(i)] if i.to_string() == "debug" => {
                debug = true;
            }

            _ => {
                return Err(Error::UnexpectedTokens(
                    tokens.to_vec(),
                    concat!(
                        "expect 'macro_name(state_name: (ty) = (default), ...) { ... };',",
                        " or '(...) => { ... };'",
                        " or '(...) when { state: (pat), ... } => { ... };'",
                        " in stateful_macro_rule!"
                    ),
                ))
            }
        }
    }

    let code = rule.generate_code()?;
    #[cfg(feature = "debug")]
    if debug {
        eprintln!("{}", util::to_string(code.clone(), 100));
    }
    Ok(code)
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::state::dollar;
    use quote::quote;

    fn to_string(t: TokenStream) -> String {
        crate::util::to_string(t, 80)
    }

    #[test]
    fn test_minimal_example() {
        let q = stateful_macro_rules_fallible(quote! {
            minimal() { "foo" }
        })
        .unwrap();

        assert_eq!(
            to_string(q),
            r#"
# [macro_export] macro_rules ! minimal
{
  { $ ($ tt : tt) * } => { $ crate :: __minimal_state ! ([$ ($ tt) *] { }) } ;
}
# [doc (hidden)] # [macro_export] macro_rules ! __minimal_state
{
  ([] { }) => { "foo" } ;
}"#
        );
    }

    #[test]
    fn test_attributes() {
        let q = stateful_macro_rules_fallible(quote! {
            #[cfg(feature = "bar")]
            /// Some comment.
            /// Foo bar.
            attriute_test() { 1 }
        })
        .unwrap();

        assert_eq!(
            to_string(q),
            r#"
# [macro_export] # [cfg (feature = "bar")] # [doc = r" Some comment."] #
[
  doc = r" Foo bar."
]
macro_rules ! attriute_test
{
  { $ ($ tt : tt) * } =>
  {
    $ crate :: __attriute_test_state ! ([$ ($ tt) *] { })
  }
  ;
}
# [doc (hidden)] # [macro_export] macro_rules ! __attriute_test_state
{
  ([] { }) => { 1 } ;
}"#
        );
    }

    #[test]
    fn test_when_clause() {
        let d = dollar();
        let q = stateful_macro_rules_fallible(quote! {
            w(b: (#d b:tt) = (false)) when { b: (true) } { "ok" };
            (t) when { b: (false) } => { b.set(true) };
        })
        .unwrap();

        assert_eq!(
            to_string(q),
            r#"
# [macro_export] macro_rules ! w
{
  { $ ($ tt : tt) * } => { $ crate :: __w_state ! ([$ ($ tt) *] { b [false] }) } ;
}
# [doc (hidden)] # [macro_export] macro_rules ! __w_state
{
  ([] { b [true] }) => { "ok" } ; ([t $ ($ _ddd : tt) *] { b [false] }) =>
  {
    $ crate :: __w_state ! ([$ ($ _ddd) *] { b [true] })
  }
  ;
}"#
        );
    }

    #[test]
    fn test_complex_example() {
        let d = dollar();
        let q = stateful_macro_rules_fallible(quote! {
            #[allow(dead_code)]
            /// Foo bar
            foo(
                x: (#d (#d i:expr)*) = (1 2),
                y: (#d (#d j:ident)*),
                z: (#d (#d t:tt)* ) = (x),
            ) {{
                let v1 = vec![#d (#d i),*];
                let v2 = vec![#d (stringify!(#d j)),*];
                format!("{:?} {:?}", v1, v2)
            }};

            // Implicit "..."
            (y += #d t:ident) => {
                y.append(#d t);
            };

            // Matching state (z).
            (y = #d t:ident ...) when { z: (x) } => {
                y.set(#d t);
                z.append(y);
            };

            (e(#d d:ident, #d e:expr) ...) => {
                x.append(#d e);
                y.append(#d d);
                // 4 dots: the entire input without "...".
                z.append(....);
            }
        })
        .unwrap();
        assert_eq!(
            to_string(q),
            r#"
# [macro_export] # [allow (dead_code)] # [doc = r" Foo bar"] macro_rules ! foo
{
  { $ ($ tt : tt) * } =>
  {
    $ crate :: __foo_state ! ([$ ($ tt) *] { x [1 2] y [] z [x] })
  }
  ;
}
# [doc (hidden)] # [macro_export] macro_rules ! __foo_state
{
  ([] { x [$ ($ i : expr) *] y [$ ($ j : ident) *] z [$ ($ t : tt) *] }) =>
  {
    {
      let v1 = vec ! [$ ($ i) , *] ; let v2 = vec ! [$ (stringify ! ($ j)) , *] ; format !
      (
        "{:?} {:?}" , v1 , v2
      )
    }
  }
  ;
  (
    [y += $ t : ident $ ($ _ddd : tt) *]
    {
      x [$ ($ i : expr) *] y [$ ($ j : ident) *] z [$ ($ t : tt) *]
    }
  )
  =>
  {
    $ crate :: __foo_state !
    (
      [$ ($ _ddd) *] { x [$ ($ i) *] y [$ ($ j) * $ t] z [$ ($ t) *] }
    )
  }
  ;
  (
    [y = $ t : ident $ ($ _ddd : tt) *]
    {
      x [$ ($ i : expr) *] y [$ ($ j : ident) *] z [x]
    }
  )
  =>
  {
    $ crate :: __foo_state ! ([$ ($ _ddd) *] { x [$ ($ i) *] y [$ t] z [x y] })
  }
  ;
  (
    [e ($ d : ident , $ e : expr) $ ($ _ddd : tt) *]
    {
      x [$ ($ i : expr) *] y [$ ($ j : ident) *] z [$ ($ t : tt) *]
    }
  )
  =>
  {
    $ crate :: __foo_state !
    (
      [$ ($ _ddd) *]
      {
        x [$ ($ i) * $ e] y [$ ($ j) * $ d] z [$ ($ t) * e ($ d , $ e)]
      }
    )
  }
  ;
}"#
        );
    }
}