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
//! Parses a raw `macro_rules!`-string.

use proc_macro2::{Delimiter, Ident, Literal, Punct, TokenStream, TokenTree};

use syn::ext::IdentExt;
use syn::parse::{Error, Parse, ParseBuffer, ParseStream, Result};
use syn::token::{Brace, Bracket, Dollar, Paren};
use syn::Lifetime;

#[cfg_attr(feature = "extra-traits", derive(Debug))]
pub struct MacroRules {
    pub name: Ident,
    pub rules: Vec<Rule>,
}

#[cfg_attr(feature = "extra-traits", derive(Debug))]
pub struct Rule {
    pub matcher: Vec<Matcher>,
    pub expansion: TokenStream,
}

#[cfg_attr(feature = "extra-traits", derive(Debug))]
pub enum Matcher {
    Punct(Punct),
    Ident(Ident),
    Lifetime(Lifetime),
    Literal(Literal),
    Group {
        delimiter: Delimiter,
        content: Vec<Matcher>,
    },
    Repeat {
        content: Vec<Matcher>,
        separator: Option<Separator>,
        repetition: Repetition,
    },
    Fragment {
        name: Ident,
        fragment: Fragment,
    },
}

#[derive(PartialEq, Eq, Clone, Hash, Debug, PartialOrd, Ord)]
pub enum Repetition {
    /// `$(...)*`
    Repeated,
    /// `$(...)+`
    AtLeastOnce,
    /// `$(...)?`
    AtMostOnce,
}

#[derive(Debug)]
pub enum Separator {
    Punct(Punct),
    Ident(Ident),
    Literal(Literal),
}

#[derive(PartialEq, Eq, Clone, Hash, Debug, PartialOrd, Ord)]
pub enum Fragment {
    Ident,
    Path,
    Expr,
    Ty,
    Pat,
    Stmt,
    Block,
    Item,
    Meta,
    Tt,
    Vis,
    Literal,
    Lifetime,
}

fn delimited(input: ParseStream<'_>) -> Result<(Delimiter, ParseBuffer<'_>)> {
    let content;
    let delimiter = if input.peek(Paren) {
        parenthesized!(content in input);
        Delimiter::Parenthesis
    } else if input.peek(Brace) {
        braced!(content in input);
        Delimiter::Brace
    } else if input.peek(Bracket) {
        bracketed!(content in input);
        Delimiter::Bracket
    } else {
        return Err(input.error("expected delimiter"));
    };
    Ok((delimiter, content))
}

impl Parse for MacroRules {
    fn parse(input: ParseStream<'_>) -> Result<Self> {
        // Parse `macro_rules! macro_name`.
        custom_keyword!(macro_rules);
        input.parse::<macro_rules>()?;
        input.parse::<Token![!]>()?;
        let name: Ident = input.parse()?;

        // Parse the delimited macro rules.
        let (delimiter, content) = delimited(&input)?;
        let rules = Rule::parse_many(&content)?;

        // Require trailing semicolon after parens or brackets.
        match delimiter {
            Delimiter::Parenthesis | Delimiter::Bracket => {
                input.parse::<Token![;]>()?;
            }
            Delimiter::Brace | Delimiter::None => {}
        }

        Ok(MacroRules { name, rules })
    }
}

impl Rule {
    fn parse_many(input: ParseStream<'_>) -> Result<Vec<Self>> {
        let rules = input.parse_terminated::<Rule, Token![;]>(Rule::parse)?;
        if rules.is_empty() {
            Err(input.error("expected at least one macro rule"))
        } else {
            Ok(rules.into_iter().collect())
        }
    }
}

impl Parse for Rule {
    fn parse(input: ParseStream<'_>) -> Result<Self> {
        // Parse the input pattern.
        let content = delimited(&input)?.1;
        let matcher = Matcher::parse_many(&content)?;

        input.parse::<Token![=>]>()?;

        // Parse the expansion tokens.
        let content = delimited(&input)?.1;
        let expansion: TokenStream = content.parse()?;

        Ok(Rule { matcher, expansion })
    }
}

impl Matcher {
    fn parse_many(input: ParseStream<'_>) -> Result<Vec<Self>> {
        let mut matchers = Vec::new();
        while !input.is_empty() {
            matchers.push(input.parse()?);
        }
        Ok(matchers)
    }
}

impl Parse for Matcher {
    fn parse(input: ParseStream<'_>) -> Result<Self> {
        if input.peek(Paren) || input.peek(Bracket) || input.peek(Brace) {
            let (delimiter, content) = delimited(&input)?;
            let content = Matcher::parse_many(&content)?;
            Ok(Matcher::Group { delimiter, content })
        } else if input.parse::<Option<Dollar>>()?.is_some() {
            if input.peek(Paren) {
                let content;
                parenthesized!(content in input);
                let content = Matcher::parse_many(&content)?;
                let separator = Separator::parse_optional(input)?;
                let repetition: Repetition = input.parse()?;
                if repetition == Repetition::AtMostOnce && separator.is_some() {
                    return Err(
                        input.error("the `?` macro repetition operator does not take a separator")
                    );
                }
                Ok(Matcher::Repeat {
                    content,
                    separator,
                    repetition,
                })
            } else {
                let name = Ident::parse_any(input)?;
                input.parse::<Token![:]>()?;
                let fragment: Fragment = input.parse()?;
                Ok(Matcher::Fragment { name, fragment })
            }
        } else if let Some(lifetime) = input.parse()? {
            Ok(Matcher::Lifetime(lifetime))
        } else {
            match input.parse()? {
                TokenTree::Ident(ident) => Ok(Matcher::Ident(ident)),
                TokenTree::Punct(punct) => Ok(Matcher::Punct(punct)),
                TokenTree::Literal(literal) => Ok(Matcher::Literal(literal)),
                TokenTree::Group(_) => unreachable!(),
            }
        }
    }
}

impl Separator {
    fn parse_optional(input: ParseStream<'_>) -> Result<Option<Self>> {
        if input.peek(Token![*]) || input.peek(Token![+]) || input.peek(Token![?]) {
            Ok(None)
        } else {
            input.parse().map(Some)
        }
    }
}

impl Parse for Separator {
    fn parse(input: ParseStream<'_>) -> Result<Self> {
        Ok(match input.parse()? {
            TokenTree::Ident(ident) => Separator::Ident(ident),
            // FIXME: multi-character punctuation
            TokenTree::Punct(punct) => Separator::Punct(punct),
            TokenTree::Literal(literal) => Separator::Literal(literal),
            TokenTree::Group(group) => {
                return Err(Error::new(group.span(), "unexpected token"));
            }
        })
    }
}

impl Parse for Repetition {
    fn parse(input: ParseStream<'_>) -> Result<Self> {
        if input.parse::<Option<Token![*]>>()?.is_some() {
            Ok(Repetition::Repeated)
        } else if input.parse::<Option<Token![+]>>()?.is_some() {
            Ok(Repetition::AtLeastOnce)
        } else if input.parse::<Option<Token![?]>>()?.is_some() {
            Ok(Repetition::AtMostOnce)
        } else {
            Err(input.error("expected `*` or `+` or `?`"))
        }
    }
}

impl Parse for Fragment {
    fn parse(input: ParseStream<'_>) -> Result<Self> {
        let ident: Ident = input.parse()?;
        match ident.to_string().as_str() {
            "ident" => Ok(Fragment::Ident),
            "path" => Ok(Fragment::Path),
            "expr" => Ok(Fragment::Expr),
            "ty" => Ok(Fragment::Ty),
            "pat" => Ok(Fragment::Pat),
            "stmt" => Ok(Fragment::Stmt),
            "block" => Ok(Fragment::Block),
            "item" => Ok(Fragment::Item),
            "meta" => Ok(Fragment::Meta),
            "tt" => Ok(Fragment::Tt),
            "vis" => Ok(Fragment::Vis),
            "literal" => Ok(Fragment::Literal),
            "lifetime" => Ok(Fragment::Lifetime),
            _ => Err(Error::new(ident.span(), "unrecognized fragment specifier")),
        }
    }
}

pub fn parse(src: &str) -> Result<MacroRules> {
    syn::parse_str::<MacroRules>(src)
}

#[cfg(test)]
mod tests {

    use super::*;

    #[test]
    fn trailing_semicolon_is_required() {
        // If the macro is delimited by parens or brackets, there has to be
        // a trailing semicolon. While this is not a strictly useful requirement,
        // we test this so the parser does not fall behind.
        let src = r#"macro_rules! a ( (a) => { $a } );"#;
        parse(&src).unwrap();
        let src = r#"macro_rules! a ( (a) => { $a } )"#;
        parse(&src).err().expect("Expected missing semicolon-error");
        let src = r#"macro_rules! a [ (a) => { $a } ]"#;
        parse(&src).err().expect("Expected missing semicolon-error");
        let src = r#"macro_rules! a { (a) => { $a } }"#;
        parse(&src).unwrap();
    }

    #[test]
    fn qmark_repeat_disallows_separator() {
        // Issue 21
        let src = r#"macro_rules! m { ($($tt:tt)-?) => {} }"#;
        let err = parse(&src).err().expect("Should not have parsed");
        assert!(err.to_string().contains("does not take a separator"));
    }

    #[test]
    fn keywords_as_fragment_names() {
        // Issue 5
        let src = r#"macro_rules! a { ($self:ident) => { ... }; }"#;
        parse(&src).unwrap();
    }

    #[test]
    fn should_parse() {
        // A more or less random collection of macro_rules!()-blocks which should parse
        // successfully.
        let fixture = &[
            r#"macro_rules! a {
(
$item:item
$block:block
$stmt:stmt
$pat:pat
$expr:expr
$ty:ty
$ident:ident
$path:path
$vis:vis
$literal:literal
$meta:meta
$lifetime:lifetime
) => {};
}"#,
            r#"macro_rules! vec {
    ( $ elem : expr ; $ n : expr ) => { ... };
    ( $ ( $ x : expr ) , * ) => { ... };
    ( $ ( $ x : expr , ) * ) => { ... };
}"#,
            r#"macro_rules! println {
    () => { ... };
    ($fmt:expr) => { ... };
    ($fmt:expr, $($arg:tt)*) => { ... };
}"#,
            r#"macro_rules! assert_eq {
    ( $ left : expr , $ right : expr ) => { ... };
    ( $ left : expr , $ right : expr , ) => { ... };
    (
$ left : expr , $ right : expr , $ ( $ arg : tt ) + ) => { ... };
}"#,
            r#"macro_rules! panic {
    () => { ... };
    ($msg:expr) => { ... };
    ($msg:expr,) => { ... };
    ($fmt:expr, $($arg:tt)+) => { ... };
}"#,
            r#"macro_rules! input_end {
    ($i:expr,) => { ... };
}"#,
            r#"macro_rules! apply {
    ($i:expr, $fun:expr, $($args:expr),* ) => { ... };
}"#,
        ][..];
        for src in fixture {
            parse(&src).expect(src);
        }
    }
}