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
//! `macro_rules`-style syntax matching for procedural macros.
//! 
//! This crate is work-in-progress, incomplete, and probably buggy!
//! 
//! Example:
//! 
//! ```rust
//! use proc_macro_rules::rules;
//! use proc_macro2::TokenStream;
//!
//! fn main() {
//!     # use quote::quote;
//!     # test_rules(quote! { A (B C) #[inner...] ... });
//!     # test_rules(quote! { foo 1 + 1 });
//!     # test_rules(quote! { foo });
//! # }
//! #
//! # fn test_rules(tokens: TokenStream) {
//!     # const IGNORE: &str = stringify! {
//!     let tokens: TokenStream = /* ... */;
//!     # };
//!
//!     rules!(tokens => {
//!         ($finish:ident ($($found:ident)*) # [ $($inner:tt)* ] $($rest:tt)*) => {
//!             for f in found {
//!                 do_something(&finish, f, &inner, &rest[0]);
//!             }
//!         }
//!         (foo $($bar:expr)?) => {
//!             match bar {
//!                 Some(e) => foo_with_expr(e),
//!                 None => foo_no_expr(),
//!             }
//!         }
//!     });
//! }
//! #
//! # use syn::{Expr, Ident};
//! # use proc_macro2::TokenTree;
//! #
//! # fn do_something(
//! #     finish: &Ident,
//! #     f: Ident,
//! #     inner: &[TokenTree],
//! #     rest: &TokenTree,
//! # ) {}
//! # fn foo_with_expr(e: Expr) {}
//! # fn foo_no_expr() {}
//! ```
//! 
//! Import the `rules` macro with `use proc_macro_rules::rules`, then use with 
//! `rules!(tokens => { branches });` where `tokens` is an expression which
//! evaluates to a `TokenStream` (such as the argument in the definition of a
//! procedural macro).
//! 
//! Each branch in `branches` should have the form `( pattern ) => { body }` where
//! `pattern` is a macro-rules-style pattern (using all the same syntax for
//! meta-variables, AST nodes, repetition, etc.) and `body` is rust code executed
//! when the pattern is matched. Within `body`, any meta-variables in the pattern
//! are bound to variables of an appropriate type from either the
//! [proc_macro2](https://github.com/alexcrichton/proc-macro2) or
//! [syn](https://github.com/dtolnay/syn) crates. Where a meta-variable is
//! inside a repetition or option clause, it will be wrapped in a `Vec` or
//! `Option`, respectively.
//! 
//! For example, in the first branch in the above example `ident` has type
//! `syn::Ident` and `inner` has type `Vec<proc_macro2::TokenTree>`.

#[doc(hidden)]
pub extern crate syn;

pub use crate::match_set::{Fork, MatchSet};
pub use proc_macro_rules_macros::rules;

mod match_set;

// Regression tests
#[cfg(test)]
mod tests {
    use crate as proc_macro_rules;
    use super::*;

    #[test]
    fn test_smoke() {
        let tokens: proc_macro2::TokenStream = "hi (a b c) # [there] the - rest".parse().unwrap();
        rules!(tokens => {
            ($finish:ident ($($found:ident)+) # [ $($inner:tt)? ] $($rest:expr)*) => {
                assert_eq!(finish.to_string(), "hi");
                assert_eq!(found.len(), 3);
                assert!(inner.is_some());
                assert_eq!(rest.len(), 1);
                return;
            }
        });
        panic!();
    }

    #[test]
    fn test_empty() {
        let tokens: proc_macro2::TokenStream = "".parse().unwrap();
        rules!(tokens => {
            () => {
                return;
            }
        });
        panic!();
    }

    #[test]
    #[should_panic]
    fn test_no_match() {
        let tokens: proc_macro2::TokenStream = "foo".parse().unwrap();
        rules!(tokens => {
            (bar) => {}
        });
    }

    #[test]
    fn test_branches() {
        fn apply(tokens: proc_macro2::TokenStream, expected_branch: usize) {
            rules!(tokens => {
                (foo) => {
                    if expected_branch == 0 {
                        return;
                    } else {
                        panic!("branch: 0, expected: {}", expected_branch);
                    }
                }
                ($x:ident) => {
                    if expected_branch == 1 {
                        assert_eq!(x.to_string(), "bar");
                        return;
                    } else {
                        // TODO failing here!
                        panic!("branch: 1, expected: {}", expected_branch);
                    }
                }
                ($($x:ident)*) => {
                    if expected_branch == 2 {
                        assert_eq!(x.len(), 3);
                        assert_eq!(x[0].to_string(), "a");
                        assert_eq!(x[1].to_string(), "b");
                        assert_eq!(x[2].to_string(), "c");
                        return;
                    } else {
                        panic!("branch: 2, expected: {}", expected_branch);
                    }
                }
            });
            panic!("Hit no branches, expected: {}", expected_branch);
        }

        apply("foo".parse().unwrap(), 0);
        apply("bar".parse().unwrap(), 1);
        apply("a b c".parse().unwrap(), 2);
    }

    #[test]
    fn test_opt() {
        fn apply(tokens: proc_macro2::TokenStream) {
            rules!(tokens => {
                (foo $(bar),? baz) => {
                    return;
                }
            });
            panic!();
        }

        apply("foo baz".parse().unwrap());
        apply("foo bar baz".parse().unwrap());
        apply("foo bar, baz".parse().unwrap());
    }

    #[test]
    fn test_plus() {
        fn apply(tokens: proc_macro2::TokenStream) {
            rules!(tokens => {
                (foo $(bar),+ baz) => {
                    return;
                }
            });
            panic!();
        }

        apply("foo bar baz".parse().unwrap());
        apply("foo bar, baz".parse().unwrap());
        apply("foo bar, bar baz".parse().unwrap());
        apply("foo bar, bar, baz".parse().unwrap());
        apply("foo bar, bar, bar baz".parse().unwrap());
        apply("foo bar, bar, bar, baz".parse().unwrap());
    }

    #[test]
    fn test_star() {
        fn apply(tokens: proc_macro2::TokenStream) {
            rules!(tokens => {
                (foo $(bar),* baz) => {
                    return;
                }
            });
            panic!();
        }

        apply("foo baz".parse().unwrap());
        apply("foo bar baz".parse().unwrap());
        apply("foo bar, baz".parse().unwrap());
        apply("foo bar, bar baz".parse().unwrap());
        apply("foo bar, bar, baz".parse().unwrap());
        apply("foo bar, bar, bar baz".parse().unwrap());
        apply("foo bar, bar, bar, baz".parse().unwrap());
    }
}