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
pub use crate::parsers::{alt, empty, lines, opt, plus, sequence, single_value, skip, star};

/// Macro that creates a parser for a given pattern.
///
/// See [the top-level documentation][lib] for more about how to write patterns.
///
/// Here's a formal syntax for patterns:
///
/// ```text
/// pattern ::= expr
///
/// expr ::= seq
///   | seq "=>" rust_expr      -- custom conversion
///
/// seq ::= lterm
///   | seq lterm               -- concatenated subpatterns
///
/// lterm ::= term
///   | ident ":" term          -- labeled subpattern
///
/// term ::= prim
///   | term "*"                -- optional repeating
///   | term "+"                -- repeating
///   | term "?"                -- optional
///
/// prim ::= "(" expr ")"
///   | "(" ident ":" expr ")"  -- labeled subpattern
///   | ident "(" expr,* ")"    -- function call
///   | ident                   -- named parser (when not followed by `(`)
///   | literal                 -- exact string
///   | "{" expr,* "}"          -- one-of syntax
///
/// ident ::= a Rust identifier
/// expr ::= a Rust expression
/// literal ::= a Rust literal
/// ```
///
/// [lib]: crate#patterns
#[macro_export]
macro_rules! parser {
    ($($pattern:tt)*) => { $crate::aoc_parse_helper!( $( $pattern )* ) }
}

#[macro_export]
#[doc(hidden)]
macro_rules! aoc_parse_helper {
    // aoc_parse_helper!(@seq [expr] [stack] [patterns])
    //
    // Submacro to transform a pattern matching `expr` to a Rust Parser
    // expression.
    //
    // Gradually parses the tokens in `expr`, producing `stack` (in reverse)
    // and `patterns` (in reverse for no good reason), then at the end converts
    // those output-stacks into a Rust parser-expression using `@reverse` and
    // `@reverse_pats`.
    //
    // `stack` is a list of Rust expressions, parsers for the elements of the
    // `expr`. `patterns` is a list of patterns that match the output of the
    // overall SequenceParser we will build from the bits in `stack`.
    //
    // BUG: Because of the simplistic way this macro-parses the input, it
    // doesn't reject some bad syntax like `foo?(x)` or `foo??` or `foo++`.

    // Mapper at the end of a pattern that is not labeled, `expr ::= label => rust_expr`.
    (@seq [ => $mapper:expr ] [ $($stack:tt)* ] [ $($pats:tt ,)* ]) => {
        $crate::Parser::map(
            $crate::aoc_parse_helper!(@seq [] [ $($stack)* ] [ $($pats ,)* ]) ,
            | ( $crate::aoc_parse_helper!(@reverse_pats [ $($pats ,)* ] []) ) | $mapper ,
        )
    };

    // Reject unsupported non-greedy regex syntax.
    (@seq [ * ? $($tail:tt)* ] [ $($stack:expr ,)* ] [ $($pats:tt ,)* ]) => {
        core::compile_error!("non-greedy quantifier `*?` is not supported")
    };

    // Reject unsupported non-greedy regex syntax.
    (@seq [ + ? $($tail:tt)* ] [ $($stack:expr ,)* ] [ $($pats:tt ,)* ]) => {
        core::compile_error!("non-greedy quantifier `+?` is not supported")
    };

    // Detect Kleene * and apply it to the preceding term.
    (@seq [ * $($tail:tt)* ] [ $top:expr , $($stack:expr ,)* ] [ $($pats:tt ,)* ]) => {
        $crate::aoc_parse_helper!(@seq [ $($tail)* ] [ $crate::macros::star($top) , $($stack ,)* ] [ $($pats ,)* ])
    };

    // Detect Kleene + and apply it to the preceding term.
    (@seq [ + $($tail:tt)* ] [ $top:expr , $($stack:expr ,)* ] [ $($pats:tt ,)* ]) => {
        $crate::aoc_parse_helper!(@seq [ $($tail)* ] [ $crate::macros::plus($top) , $($stack ,)* ] [ $($pats ,)* ])
    };

    // Detect optional `?` and apply it to the preceding term.
    (@seq [ ? $($tail:tt)* ] [ $top:expr , $($stack:tt)* ] [ $($pats:tt ,)* ]) => {
        $crate::aoc_parse_helper!(@seq [ $($tail)* ] [ $crate::macros::opt($top) , $($stack)* ] [ $($pats ,)* ])
    };

    // A quantifier at the beginning of input (nothing on the stack) is an errror.
    (@seq [ * $($tail:tt)* ] [ ] [ $($pats:tt ,)* ]) => {
        core::compile_error!("quantifier `*` has to come after something, not at the start of an expression.")
    };
    (@seq [ + $($tail:tt)* ] [ ] [ $($pats:tt ,)* ]) => {
        core::compile_error!("quantifier `+` has to come after something, not at the start of an expression.")
    };
    (@seq [ ? $($tail:tt)* ] [ ] [ $($pats:tt ,)* ]) => {
        core::compile_error!("quantifier `?` has to come after something, not at the start of an expression.")
    };

    // Reject incorrect label syntax.
    (@seq [ $label:ident : => $($tail:tt)* ] [ $($stack:expr ,)* ] [ $($pats:tt ,)* ]) => {
        core::compile_error!(
            core::concat!("missing pattern after `", core::stringify!($label), ":`")
        );
    };
    (@seq [ $label:ident : ] [ $($stack:expr ,)* ] [ $($pats:tt ,)* ]) => {
        core::compile_error!(
            core::concat!("missing pattern after `", core::stringify!($label), ":`")
        );
    };
    (@seq [ $label1:ident : $label2:ident : ] [ $($stack:expr ,)* ] [ $($pats:tt ,)* ]) => {
        core::compile_error!(
            core::concat!(
                "missing pattern between `", core::stringify!($label1), ":` and `"
                    core::stringify!($label2), ":`"
            )
        );
    };

    // Function call
    (@seq [ $f:ident ( $($args:tt)* ) $($tail:tt)* ] [ $($stack:expr ,)* ] [ $($pats:tt ,)* ]) => {
        $crate::aoc_parse_helper!(
            @seq
            [ $($tail)* ]
            [
                $crate::aoc_parse_helper!(@args ( $f ) [ $( $args )* ] [] ())
                ,
                $($stack ,)*
            ]
            [ _ , $($pats ,)* ]
        )
    };

    // Labelled function call
    (@seq [ $label:ident : $f:ident ( $( $args:tt )* )  $( $tail:tt )* ] [ $($stack:expr ,)* ] [ $($pats:tt ,)* ]) => {
        $crate::aoc_parse_helper!(
            @seq
            [ $($tail)* ]
            [
                $crate::aoc_parse_helper!(@args ( $f ) [ $( $args )* ] [] ())
                ,
                $($stack ,)*
            ]
            [ $label , $($pats ,)* ]
        )
    };

    // any Rust literal (strings and chars are valid patterns; others may be
    // used as function arguments)
    (@seq [ $x:literal $($tail:tt)* ] [ $($stack:expr ,)* ] [ $($pats:tt ,)* ]) => {
        $crate::aoc_parse_helper!(
            @seq
            [ $($tail)* ]
            [
                $crate::aoc_parse_helper!(@prim $x) ,
                $($stack ,)*
            ]
            [ #, /* no pattern */ $($pats ,)* ]
        )
    };

    // Other labeled term
    (@seq [ $label:ident : $x:tt $($tail:tt)* ] [ $($stack:expr ,)* ] [ $($pats:tt ,)* ]) => {
        $crate::aoc_parse_helper!(
            @seq
            [ $($tail)* ]
            [
                $crate::aoc_parse_helper!(@prim $x) ,
                $($stack ,)*
            ]
            [ $label , $($pats ,)* ]
        )
    };

    // the first `tt` of any other `term`
    (@seq [ $x:tt $($tail:tt)* ] [ $($stack:expr ,)* ] [ $($pats:tt ,)* ]) => {
        $crate::aoc_parse_helper!(
            @seq
            [ $($tail)* ]
            [
                $crate::aoc_parse_helper!(@prim $x) ,
                $($stack ,)*
            ]
            [ _ , $($pats ,)* ]
        )
    };

    // end of input
    (@seq [ ] [ $($parts:expr ,)* ] [ $($pats:tt ,)* ]) => {
        $crate::aoc_parse_helper!(@reverse [ $($parts ,)* ] [])
    };

    // anything not matched by this point is an error
    (@seq [ $($tail:tt)* ] [ $($parts:expr ,)* ] [ $($pats:tt ,)* ]) => {
        core::compile_error!(stringify!(unrecognized syntax @ $($tail)*))
    };

    // aoc_parse_helper!(@reverse [input expr stack] [output stack])
    //
    // Take the stack of parsers and produce a single sequence-parser.
    (@reverse [ ] [ ]) => {
        $crate::macros::empty()
    };
    (@reverse [ ] [ $out:expr ]) => {
        $out
    };
    (@reverse [ $head:expr , $($tail:expr ,)* ] [ ]) => {
        $crate::aoc_parse_helper!(@reverse [ $($tail ,)* ] [ $head ])
    };
    (@reverse [ $head:expr , $($tail:expr ,)* ] [ $out:expr ]) => {
        $crate::aoc_parse_helper!(@reverse [ $($tail ,)* ] [ $crate::macros::sequence($head, $out) ])
    };

    // aoc_parse_helper!(@reverse_pats [pattern stack] [output stack])
    //
    // Take the stack of Rust patterns, possibly interspersed with `#`
    // to indicate "no pattern", and produce a single pattern.
    (@reverse_pats [ ] [ $out:pat , ]) => {
        $out  // don't produce a singleton-tuple-pattern
    };
    (@reverse_pats [ ] [ $($out:pat ,)* ]) => {
        ( $( $out , )* )
    };
    (@reverse_pats [ #, $($tail:tt ,)* ] [ $( $out:pat , )* ]) => {
        $crate::aoc_parse_helper!(@reverse_pats [ $( $tail , )* ] [ $( $out , ) * ])
    };
    (@reverse_pats [ $head:pat , $($tail:tt ,)* ] [ $($out:pat ,)* ]) => {
        $crate::aoc_parse_helper!(@reverse_pats [ $( $tail , )* ] [ $head, $($out ,)* ])
    };

    // aoc_parse_helper!(@prim pattern)
    //
    // Transform a `prim` into a Rust Parser expression.
    (@prim $x:ident) => {
        $x
    };
    (@prim $x:literal) => {
        $x
    };
    (@prim ( $($nested:tt)* )) => {
        $crate::macros::single_value(
            $crate::aoc_parse_helper!(@seq [ $( $nested )* ] [ ] [ ])
        )
    };
    (@prim { $($nested:tt)* }) => {
        $crate::aoc_parse_helper!(@list [ $( $nested )* ] [ ] [ ])
    };

    // aoc_parse_helper!(@args fn_expr [unexamined input tokens] [current argument holding area] [transformed output argument exprs])
    //
    // Transform argument lists.

    // end of an argument in an argument list
    (@args ( $f:expr ) [ , $($tail:tt)* ] [ $($seq:tt)* ] ( $( $arg:expr , )* )) => {
        $crate::aoc_parse_helper!(
            @args
            ( $f )
            [ $( $tail )* ]
            [ ]
            (
                $( $arg , )*
                $crate::aoc_parse_helper!(@seq [ $( $seq )* ] [ ] [ ]) ,
            )
        )
    };

    // not the end of an arg; just move a token from the input to the holding area
    (@args ( $f:expr ) [ $next:tt $($tail:tt)* ] [ $($seq:tt)* ] ( $( $out:expr , )* )) => {
        $crate::aoc_parse_helper!(
            @args
            ( $f )
            [ $( $tail )* ]
            [ $( $seq )* $next ]
            ( $( $out , )* )
        )
    };

    // end of argument list, after trailing comma or empty
    (@args ( $f:expr ) [] [] ( $( $out:expr , )* )) => {
        $f ( $( $out , )* )
    };

    // end of argument list with no trailing comma: infer one
    (@args ( $f:expr ) [] [ $($seq:tt)+ ] ( $( $out:expr , )* )) => {
        $crate::aoc_parse_helper!(@args ( $f ) [,] [ $($seq)+ ] ( $( $out , )* ))
    };

    // aoc_parse_helper!(@list [unexamined input tokens] [current arm holding area] [transformed output arm parser expressions])
    //
    // The list of patterns in the body of an alternation.

    // end of first arm of an alternation
    (@list [ , $($tail:tt)* ] [ $($seq:tt)* ] [ ]) => {
        $crate::aoc_parse_helper!(
            @list
            [ $( $tail )* ]
            [ ]
            [ $crate::aoc_parse_helper!(@seq [ $( $seq )* ] [ ] [ ]) ]
        )
    };

    // end of a non-first arm of an alternation
    (@list [ , $($tail:tt)* ] [ $($seq:tt)* ] [ $out:expr ]) => {
        $crate::aoc_parse_helper!(
            @list
            [ $( $tail )* ]
            [ ]
            [ $crate::macros::alt($out, $crate::aoc_parse_helper!(@seq [ $( $seq )* ] [ ] [ ])) ]
        )
    };

    // not the end of an arm; just move a token from the input to the holding area
    (@list [ $next:tt $($tail:tt)* ] [ $($seq:tt)* ] [ $($out:expr)? ]) => {
        $crate::aoc_parse_helper!(
            @list
            [ $( $tail )* ]
            [ $( $seq )* $next ]
            [ $( $out )? ]
        )
    };

    // completely empty alternation; could technically be understood as never matching,
    // but it's not a useful thing to express, so reject.
    (@list [ ] [ ] [ ]) => {
        ::core::compile_error("no arms in alternation")
    };

    // end of alternation after comma
    (@list [ ] [ ] [ $out:expr ]) => {
        $out
    };

    // end of alternation with no comma: infer one
    (@list [ ] [ $($seq:tt)+ ] [ $( $out:expr )? ]) => {
        $crate::aoc_parse_helper!(@list [,] [ $($seq)+ ] [ $( $out )? ])
    };

    // aoc_parse_helper!(@...) - This is an internal error, shouldn't happen in the wild.
    (@ $($tail:tt)*) => {
        ::core::compile_error!(stringify!(unrecognized syntax @ $($tail)*))
    };

    // Hand anything else off to the @seq submacro.
    ($($tail:tt)*) => {
        $crate::macros::single_value(
            $crate::aoc_parse_helper!(@seq [ $($tail)* ] [ ] [ ])
        )
    };
}