anpa 0.11.0

A generic monadic parser combinator library inspired by Haskell's parsec.
Documentation
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
427
428
429
430
431
432
433
434
435
436
437
438
439
/// Shorthand for creating a parser. All parsers shall return `Option<T>`
/// ### Example:
/// ```
/// use anpa::create_parser;
/// # use anpa::core::parse;
///
/// let p = create_parser!(s, {
///     /* Define parser behavior using state `s` */
///     # Some(())
/// });
///
/// # parse(p, "test");
/// ```
#[macro_export]
macro_rules! create_parser {
    ($state:ident, $f:expr) => {
        move |$state: &mut $crate::core::AnpaState<_, _>| $f
    }
}

/// Shorthand for creating a deferred parser. This is mandatory when creating recursive parsers.
///
/// ### Example:
/// ```
/// use anpa::defer_parser;
/// use anpa::core::*;
/// use anpa::combinators::{middle, not_empty, or};
/// use anpa::parsers::{item_while, take};
///
/// /// Can parse e.g. "(((something)))"
/// fn in_parens<'a>() -> impl StrParser<'a> {
///     defer_parser!(or(
///         not_empty(item_while(|c: char| c.is_alphanumeric())),
///         middle(take('('), in_parens(), take(')')))
///     )
/// }
///
/// assert_eq!(parse(in_parens(), "((((inside))))" ).result, Some("inside"));
///
/// ```
#[macro_export]
macro_rules! defer_parser {
    ($p:expr) => {
        $crate::create_parser!(s, $p(s))
    }
}

/// Variadic version of [`combinators::bind`](crate::combinators::bind), where all provided parsers must succeed.
/// ### Arguments
/// * `f` - the transformation function. Its arguments must match the result types of `p...` in
///         both type and number.
/// * `p...` - any number of parsers.
#[macro_export]
macro_rules! bind {
    ($f:expr, $($p:expr),* $(,)?) => {
        $crate::create_parser!(s, $f($($p(s)?),*)(s))
    };
}

/// Variadic version of [`combinators::map`](crate::combinators::map), where all provided parsers must succeed.
/// ### Arguments
/// * `f` - the transformation function. Its arguments must match the result types of `p...` in
///         both type and number.
/// * `p...` - any number of parsers.
#[macro_export]
macro_rules! map {
    ($f:expr, $($p:expr),* $(,)?) => {
        $crate::create_parser!(s, Some($f($($p(s)?),*)))
    };
}

/// Variadic version of [`combinators::map_if`](crate::combinators::map_if), where all provided parsers must succeed.
/// ### Arguments
/// * `f` - the transformation function. Its arguments must match the result types of `p...` in
///         both type and number.
/// * `p...` - any number of parsers.
#[macro_export]
macro_rules! map_if {
    ($f:expr, $($p:expr),* $(,)?) => {
        $crate::create_parser!(s, Some($f($($p(s)?),*)?))
    };
}

/// Convert a number of parsers to a single parser producing a tuple with all the results.
/// ### Arguments
/// * `p...` - any number of parsers.
#[macro_export]
macro_rules! tuplify {
    ($($p:expr),* $(,)?) => {
        $crate::create_parser!(s, Some(($($p(s)?),*)))
    };
}

/// Create a parser that successfully returns `x`.
///
/// ### Arguments
/// * `x` - the result to be returned from the parser.
#[macro_export]
macro_rules! pure {
    ($x:expr) => {
        $crate::create_parser!(_s, Some($x))
    };
}

/// A helper macro to generate variadic macros using repeated application of the rightmost
/// argument of a binary function.
///
/// E.g. for 4 arguments, the resulting function will be constructed as:
/// `f(e1, f(e2, f(e3, e4)))`
///
/// ### Arguments
/// * `f` - a binary function.
/// * `e...` - any number of arguments.
#[macro_export]
macro_rules! variadic {
    ($f:expr, $e:expr) => {
        $e
    };
    ($f:expr, $e:expr, $($e2:expr),*) => {
        $f($e, $crate::variadic!($f, $($e2),*))
    };
}

/// Variadic version of [`combinators::or`](crate::combinators::or).
///
/// ### Arguments
/// * `p...` - any number of parsers.
#[macro_export]
macro_rules! or {
    ($($p:expr),* $(,)?) => {
        $crate::variadic!($crate::combinators::or, $($p),*)
    };
}

/// Variadic version of [`or_no_partial`](crate::combinators::or_no_partial).
///
/// ### Arguments
/// * `p...` - any number of parsers.
#[macro_export]
macro_rules! or_no_partial {
    ($($p:expr),* $(,)?) => {
        $crate::variadic!($crate::combinators::or_no_partial, $($p),*)
    };
}

/// Variadic version of [`combinators::or_diff`](crate::combinators::or_diff).
///
/// ### Arguments
/// * `p...` - any number of parsers.
#[macro_export]
macro_rules! or_diff {
    ($($p:expr),* $(,)?) => {
        $crate::variadic!($crate::combinators::or_diff, $($p),*)
    };
}

/// Variadic version of [`or_diff_no_partial`](crate::combinators::or_diff_no_partial).
///
/// ### Arguments
/// * `p...` - any number of parsers.
#[macro_export]
macro_rules! or_diff_no_partial {
    ($($p:expr),* $(,)?) => {
        $crate::variadic!($crate::combinators::or_diff_no_partial, $($p),*)
    };
}

/// Variadic version of [`combinators::greedy_or`](crate::combinators::greedy_or), where
/// the result of the parser with the most consumed input will be returned.
///
/// ### Arguments
/// * `p...` - any number of parsers.
#[macro_export]
macro_rules! greedy_or {
    ($($p:expr),* $(,)?) => {
        $crate::variadic!($crate::combinators::greedy_or, $($p),*)
    };
}

/// Variadic version of [`combinators::left`](crate::combinators::left), where
/// only the leftmost parser's result will be returned.
///
/// ### Arguments
/// * `p...` - any number of parsers.
#[macro_export]
macro_rules! left {
    ($($p:expr),* $(,)?) => {
        $crate::variadic!($crate::combinators::left, $($p),*)
    };
}

/// Variadic version of [`combinators::right`](crate::combinators::right), where
/// only the rightmost parser's result will be returned.
///
/// ### Arguments
/// * `p...` - any number of parsers.
#[macro_export]
macro_rules! right {
    ($($p:expr),* $(,)?) => {
        $crate::variadic!($crate::combinators::right, $($p),*)
    };
}

/// Variadic parser that succeeds if the next item matches the provided
/// patterns. Note that unlike `matches!`, this macro accepts multiple
/// patterns.
///
/// ### Arguments
/// * `patterns` - match patterns (as one would pass to `matches!`)
///
/// ### Example:
/// ```
/// use anpa::core::*;
/// use anpa::item_matches;
///
/// let p = item_matches!('0' | '1');
///
/// assert_eq!(parse(p, "012").result, Some('0'));
/// assert_eq!(parse(p, "123").result, Some('1'));
/// assert_eq!(parse(p, "234").result, None);
/// ```
#[macro_export]
macro_rules! item_matches {
    ($($($patterns:pat_param)|+ $(if $guard:expr)?),+ $(,)?) => {
        $crate::parsers::item_if(|c| {
            match c {
                $($($patterns)|+ $(if $guard)? => true,)+
                _ => false
            }
        })
    };
}

/// Alternative to the [`parsers::take`](crate::parsers::take) parser that
/// inlines the argument into the parser.
///
/// This can give better performance and/or smaller binary size, or the opposite.
/// Try it and don't forget to measure!
///
/// This macro is likely only useful when passing a literal as argument.
///
/// ### Arguments
/// * `prefix` - the prefix to parse.
#[macro_export]
macro_rules! take {
    ($prefix:expr) => {
        $crate::create_parser!(s, {
            $crate::prefix::Prefix::take_prefix(&$prefix, s.input).map(|(res, rest)| {
                s.input = rest;
                res
            })
        })
    }
}

/// Alternative to the [`parsers::skip`](crate::parsers::skip) parser that
/// inlines the argument into the parser.
///
/// This can give better performance and/or smaller binary size, or the opposite.
/// Try it and don't forget to measure!
///
/// This macro is likely only useful when passing a literal as argument.
///
/// ### Arguments
/// * `prefix` - the prefix to parse.
#[macro_export]
macro_rules! skip {
    ($prefix:expr) => {
        $crate::create_parser!(s, {
            s.input = $crate::prefix::Prefix::skip_prefix(&$prefix, s.input)?;
            Some(())
        })
    }
}
/// Alternative to the [`parsers::until`](crate::parsers::until) parser that
/// inlines the argument into the parser.
///
/// This can give better performance and/or smaller binary size, or the opposite.
/// Try it and don't forget to measure!
///
/// This macro is likely only useful when passing a literal as argument.
///
/// ### Arguments
/// * `needle` - the element to search for.
#[macro_export]
macro_rules! until {
    ($needle:expr) => {
        $crate::create_parser!(s, {
            let (size, index) = $crate::needle::Needle::find_in(&$needle, s.input)?;
            let res = $crate::slicelike::SliceLike::slice_to(s.input, index);
            s.input = $crate::slicelike::SliceLike::slice_from(s.input, index + size);
            Some(res)
        })
    }
}

#[macro_export]
macro_rules! choose_internal {
    ($state:ident, $p:expr => $res:ident $(: $t:ty)?; $($cond:expr => $new_p:expr),* $(,)?) => {
        $crate::create_parser!($state, {
            let $res $(:$t)? = $p;

            $(if $cond {
                return $new_p($state)
            })*

            None
        })
    };

    ($state:ident, $p:expr; $($arm:pat_param $(| $alt:pat_param)* $(if $guard:expr)? => $new_p:expr),* $(,)?) => {
        $crate::create_parser!($state, {
            match $p {
                $(
                    $arm $(| $alt)* $(if $guard)? => $new_p($state),
                )*
                #[allow(unreachable_patterns)]
                _ => None
            }
        })
    };
}

/// Create a parser that takes evaluates a parser, and returns different
/// parsers depending on the provided conditions.
///
/// If none of the provided conditions match, the parser will fail.
///
/// The macro comes in two flavors:
/// - if-style:
/// ```
/// # use anpa::{choose, core::parse, number::integer, parsers::take};
///     let p = choose!(integer() => n; // Explicit binding to variable `v`
///                    (0_u8..=4).contains(&n) => take("range"),
///                    n == 5                  => take("five"));
/// # parse(p, "dummy");
/// ```
/// - match-style:
/// ```
/// # use anpa::{choose, core::parse, number::integer, parsers::take};
///     let p = choose!(integer(); // No binding of result.
///                     0_u8..=4 => take("range"),
///                     5        => take("five"));
/// # parse(p, "dummy");
/// ```
///
///
/// ### Example:
/// ```
/// use anpa::core::*;
/// use anpa::choose;
/// use anpa::parsers::take;
/// use anpa::number::integer;
///
/// let p_if = choose!(integer() => x: u8; // Note the semicolon
///                   x == 0 => take("zero"),
///                   x == 1 => take("one"),
///                   (2..=100).contains(&x) => take("big")
/// );
///
/// let p_match = choose!(integer(); // Note the semicolon
///                       0_u8 => take("zero"),
///                       1 => take("one"),
///                       2..=100 => take("big")
/// );
///
/// let input1 = "0zero";
/// let input2 = "1one";
/// let input3 = "2big";
/// let input4 = "100big";
/// let input5 = "101big";
/// let input6 = "0one";
/// let input7 = "1zero";
///
/// assert_eq!(parse(p_if, input1).result, Some("zero"));
/// assert_eq!(parse(p_if, input2).result, Some("one"));
/// assert_eq!(parse(p_if, input3).result, Some("big"));
/// assert_eq!(parse(p_if, input4).result, Some("big"));
/// assert_eq!(parse(p_if, input5).result, None);
/// assert_eq!(parse(p_if, input6).result, None);
/// assert_eq!(parse(p_if, input7).result, None);
///
/// assert_eq!(parse(p_match, input1).result, Some("zero"));
/// assert_eq!(parse(p_match, input2).result, Some("one"));
/// assert_eq!(parse(p_match, input3).result, Some("big"));
/// assert_eq!(parse(p_match, input4).result, Some("big"));
/// assert_eq!(parse(p_match, input5).result, None);
/// assert_eq!(parse(p_match, input6).result, None);
/// assert_eq!(parse(p_match, input7).result, None);
/// ```
#[macro_export]
macro_rules! choose {
    ($p:expr => $res:ident $(: $t:ty)?; $($cond:expr => $new_p:expr),* $(,)?) => {
        $crate::choose_internal!(s, $p(s)? => $res $(: $t)?; $($cond => $new_p),*)
    };

    ($p:expr; $($arm:pat_param $(| $alt:pat_param)* $(if $guard:expr)? => $new_p:expr),* $(,)?) => {
        $crate::choose_internal!(s, $p(s)?; $($arm $(| $alt)* $(if $guard)? => $new_p),*)
    };
}

/// Create a parser that evaluates an expression, and returns different
/// parsers depending on the provided conditions.
///
/// If none of the provided conditions match, the parser will fail.
///
/// This macro functions like [`choose!`], but acts on a value rather than on a parser.
///
/// See [`choose!`] for more details.
#[macro_export]
macro_rules! choose_pure {
    ($p:expr => $res:ident $(: $t:ty)?; $($cond:expr => $new_p:expr),* $(,)?) => {
        $crate::choose_internal!(s, $p => $res $(: $t)?; $($cond => $new_p),*)
    };

    ($p:expr; $($arm:pat_param $(| $alt:pat_param)* $(if $guard:expr)? => $new_p:expr),* $(,)?) => {
        $crate::choose_internal!(s, $p; $($arm $(| $alt)* $(if $guard)? => $new_p),*)
    };
}

/// Create a new parser trait with a concrete input type for cleaner APIs.
/// ### Arguments
/// * `id` - The identifier of the new trait
/// * `input` - The type of the input. Do not include lifetime or reference.
/// * `comment` - The doc comment to be generated for the trait
///
/// ### Example
/// ```
/// use anpa::create_parser_trait;
/// create_parser_trait!(I8Parser, [i8], "Convenience alias for a parser that parses a `&'a [i8]`");
/// ```
#[macro_export]
macro_rules! create_parser_trait {
    ($id:ident, $input:ty, $comment:expr) => {
        #[doc=$comment]
        pub trait $id<'a, O = &'a $input, S = ()>: $crate::core::Parser<&'a $input, O, S> {}
        impl<'a, O, S, P: $crate::core::Parser<&'a $input, O, S>> $id<'a, O, S> for P {}
    };
}