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
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
pub type ParseResult<'a, T> = Result<(ParseInput<'a>, T), ParseError>;
pub type ParseInput<'a> = &'a [u8];
pub type ParseError = &'static str;
macro_rules! any_of {
($lt:lifetime, $($parser:expr),+ $(,)?) => {
move |input: $crate::common::parser::ParseInput <$lt>| {
$(
if let Ok((input, value)) = $parser(input) {
return Ok((input, value));
}
)+
Err("No parser succeeded")
}
};
}
pub fn empty(input: ParseInput) -> ParseResult<()> {
if input.is_empty() {
Ok((input, ()))
} else {
Err("not empty")
}
}
pub fn fully_consumed<'a, T>(
mut parser: impl FnMut(ParseInput<'a>) -> ParseResult<'a, T>,
) -> impl FnMut(ParseInput<'a>) -> ParseResult<'a, T> {
move |input: ParseInput| {
let (input, value) = parser(input)?;
let (input, _) = empty(input)?;
Ok((input, value))
}
}
pub fn consumed_cnt<'a, T>(
mut parser: impl FnMut(ParseInput<'a>) -> ParseResult<'a, T>,
) -> impl FnMut(ParseInput<'a>) -> ParseResult<'a, usize> {
move |input: ParseInput| {
let len = input.len();
let (input, _) = parser(input)?;
Ok((input, len - input.len()))
}
}
pub fn map<'a, T, U>(
mut parser: impl FnMut(ParseInput<'a>) -> ParseResult<'a, T>,
f: impl Fn(T) -> U,
) -> impl FnMut(ParseInput<'a>) -> ParseResult<'a, U> {
move |input: ParseInput| {
let (input, value) = parser(input)?;
Ok((input, f(value)))
}
}
pub fn prefixed<'a, T1, T2>(
mut prefix: impl FnMut(ParseInput<'a>) -> ParseResult<'a, T1>,
mut parser: impl FnMut(ParseInput<'a>) -> ParseResult<'a, T2>,
) -> impl FnMut(ParseInput<'a>) -> ParseResult<'a, T2> {
move |input: ParseInput| {
let (input, _) = prefix(input)?;
let (input, value) = parser(input)?;
Ok((input, value))
}
}
pub fn suffixed<'a, T1, T2>(
mut parser: impl FnMut(ParseInput<'a>) -> ParseResult<'a, T1>,
mut suffix: impl FnMut(ParseInput<'a>) -> ParseResult<'a, T2>,
) -> impl FnMut(ParseInput<'a>) -> ParseResult<'a, T1> {
move |input: ParseInput| {
let (input, value) = parser(input)?;
let (input, _) = suffix(input)?;
Ok((input, value))
}
}
pub fn maybe<'a, T>(
mut parser: impl FnMut(ParseInput<'a>) -> ParseResult<'a, T>,
) -> impl FnMut(ParseInput<'a>) -> ParseResult<'a, Option<T>> {
move |input: ParseInput| match parser(input) {
Ok((input, value)) => Ok((input, Some(value))),
Err(_) => Ok((input, None)),
}
}
pub fn not<'a, T>(
mut parser: impl FnMut(ParseInput<'a>) -> ParseResult<'a, T>,
) -> impl FnMut(ParseInput<'a>) -> ParseResult<'a, ()> {
move |input: ParseInput| match parser(input) {
Ok(_) => Err("parser succeeded"),
Err(_) => Ok((input, ())),
}
}
pub fn peek<'a, T>(
mut parser: impl FnMut(ParseInput<'a>) -> ParseResult<'a, T>,
) -> impl FnMut(ParseInput<'a>) -> ParseResult<'a, T> {
move |input: ParseInput| {
let (_, value) = parser(input)?;
Ok((input, value))
}
}
pub fn one_or_more<'a, T>(
mut parser: impl FnMut(ParseInput<'a>) -> ParseResult<'a, T>,
) -> impl FnMut(ParseInput<'a>) -> ParseResult<'a, Vec<T>> {
move |input: ParseInput| {
let mut results = Vec::new();
let mut next = Some(input);
while let Some(input) = next.take() {
match parser(input) {
Ok((input, value)) => {
next = Some(input);
results.push(value);
}
Err(_) => {
next = Some(input);
break;
}
}
}
if results.is_empty() {
return Err("Parser failed to suceed once");
}
Ok((next.unwrap(), results))
}
}
pub fn zero_or_more<'a, T>(
parser: impl FnMut(ParseInput<'a>) -> ParseResult<'a, T>,
) -> impl FnMut(ParseInput<'a>) -> ParseResult<'a, Vec<T>> {
let mut parser = maybe(one_or_more(parser));
move |input: ParseInput| {
let (input, results) = parser(input)?;
Ok((input, results.unwrap_or_default()))
}
}
pub fn take_until_byte(
mut predicate: impl FnMut(u8) -> bool,
) -> impl FnMut(ParseInput) -> ParseResult<ParseInput> {
move |input: ParseInput| {
let (input, value) = match input.iter().enumerate().find(|(_, b)| predicate(**b)) {
Some((i, _)) if i == 0 => (input, b"".as_slice()),
Some((i, _)) => (&input[i..], &input[..i]),
None => (b"".as_slice(), input),
};
Ok((input, value))
}
}
pub fn take_until_byte_1(
predicate: impl FnMut(u8) -> bool,
) -> impl FnMut(ParseInput) -> ParseResult<ParseInput> {
let mut parser = take_until_byte(predicate);
move |input: ParseInput| {
let (input, value) = parser(input)?;
if value.is_empty() {
return Err("did not consume 1 byte");
}
Ok((input, value))
}
}
pub fn rtake_until_byte(
mut predicate: impl FnMut(u8) -> bool,
) -> impl FnMut(ParseInput) -> ParseResult<ParseInput> {
move |input: ParseInput| {
let len = input.len();
let (input, value) = match input.iter().enumerate().rev().find(|(_, b)| predicate(**b)) {
Some((i, _)) if i == len - 1 => (input, b"".as_slice()),
Some((i, _)) => (&input[..=i], &input[i + 1..]),
None => (b"".as_slice(), input),
};
Ok((input, value))
}
}
pub fn rtake_until_byte_1(
predicate: impl FnMut(u8) -> bool,
) -> impl FnMut(ParseInput) -> ParseResult<ParseInput> {
let mut parser = rtake_until_byte(predicate);
move |input: ParseInput| {
let (input, value) = parser(input)?;
if value.is_empty() {
return Err("did not consume 1 byte");
}
Ok((input, value))
}
}
pub fn take(cnt: usize) -> impl FnMut(ParseInput) -> ParseResult<ParseInput> {
move |input: ParseInput| {
if cnt == 0 {
Err("take(cnt) cannot have cnt == 0")
} else if cnt > input.len() {
Err("take(cnt) not enough bytes")
} else {
Ok((&input[cnt..], &input[..cnt]))
}
}
}
pub fn bytes<'a>(bytes: &[u8]) -> impl FnMut(ParseInput<'a>) -> ParseResult<&'a [u8]> + '_ {
move |input: ParseInput<'a>| {
if input.is_empty() {
return Err("Empty input");
} else if input.len() < bytes.len() {
return Err("Not enough bytes");
}
if input.starts_with(bytes) {
Ok((&input[bytes.len()..], &input[..bytes.len()]))
} else {
Err("Wrong bytes")
}
}
}
pub fn byte(byte: u8) -> impl FnMut(ParseInput) -> ParseResult<u8> {
move |input: ParseInput| {
if input.is_empty() {
return Err("Empty input");
}
if input.starts_with(&[byte]) {
Ok((&input[1..], byte))
} else {
Err("Wrong byte")
}
}
}
#[cfg(test)]
mod tests {
use super::*;
mod parsers {
use super::*;
fn parse_fail(_: ParseInput) -> ParseResult<ParseInput> {
Err("bad parser")
}
fn take_all(input: ParseInput) -> ParseResult<ParseInput> {
Ok((b"", input))
}
mod empty {
use super::*;
#[test]
fn should_succeed_if_input_empty() {
let (input, _) = empty(b"").unwrap();
assert_eq!(input, b"");
}
#[test]
fn should_fail_if_input_not_empty() {
let _ = empty(b"a").unwrap_err();
}
}
mod fully_consumed {
use super::*;
#[test]
fn should_succeed_if_child_parser_fully_consumed_input() {
let (input, value) = fully_consumed(take(3))(b"abc").unwrap();
assert_eq!(input, b"");
assert_eq!(value, b"abc");
}
#[test]
fn should_fail_if_child_parser_did_not_fully_consume_input() {
let _ = fully_consumed(take(2))(b"abc").unwrap_err();
}
#[test]
fn should_fail_if_child_parser_fails() {
let _ = fully_consumed(take(4))(b"abc").unwrap_err();
}
}
mod consumed_cnt {
use super::*;
#[test]
fn should_succeed_if_child_parser_succeeds() {
let (input, value) = consumed_cnt(take(2))(b"abc").unwrap();
assert_eq!(input, b"c");
assert_eq!(value, 2);
}
#[test]
fn should_fail_if_child_parser_fails() {
let _ = consumed_cnt(take(4))(b"abc").unwrap_err();
}
}
mod map {
use super::*;
#[test]
fn should_transform_child_parser_result() {
let (input, value) = map(take(2), |value| value.len())(b"abc").unwrap();
assert_eq!(input, b"c");
assert_eq!(value, 2);
}
#[test]
fn should_fail_if_child_parser_fails() {
let _ = map(take(4), |value| value.len())(b"abc").unwrap_err();
}
}
mod prefixed {
use super::*;
#[test]
fn should_fail_if_prefix_parser_fails() {
let _ = prefixed(parse_fail, take_all)(b"abc").unwrap_err();
}
#[test]
fn should_fail_if_main_parser_fails() {
let _ = prefixed(take(1), parse_fail)(b"abc").unwrap_err();
}
#[test]
fn should_return_value_of_main_parser_when_succeeds() {
let (input, value) = prefixed(take(1), take(1))(b"abc").unwrap();
assert_eq!(input, b"c");
assert_eq!(value, b"b");
}
}
mod suffixed {
use super::*;
#[test]
fn should_fail_if_suffixed_parser_fails() {
let _ = suffixed(parse_fail, take_all)(b"abc").unwrap_err();
}
#[test]
fn should_fail_if_main_parser_fails() {
let _ = suffixed(take(1), parse_fail)(b"abc").unwrap_err();
}
#[test]
fn should_return_value_of_main_parser_when_succeeds() {
let (input, value) = suffixed(take(1), take(1))(b"abc").unwrap();
assert_eq!(input, b"c");
assert_eq!(value, b"a");
}
}
mod maybe {
use super::*;
#[test]
fn should_return_some_value_if_wrapped_parser_succeeds() {
let (input, value) = maybe(take(2))(b"abc").unwrap();
assert_eq!(input, b"c");
assert_eq!(value, Some(b"ab".as_slice()));
}
#[test]
fn should_return_none_if_wrapped_parser_fails() {
let (input, value) = maybe(parse_fail)(b"abc").unwrap();
assert_eq!(input, b"abc");
assert_eq!(value, None);
}
}
mod not {
use super::*;
#[test]
fn should_succeed_when_child_parser_fails() {
let (input, _) = not(parse_fail)(b"abc").unwrap();
assert_eq!(input, b"abc");
}
#[test]
fn should_fail_when_child_parser_succeeds() {
not(byte(b'a'))(b"abc").unwrap_err();
}
}
mod peek {
use super::*;
#[test]
fn should_succeed_but_not_advance_input_when_child_parser_succeeds() {
let (input, value) = peek(byte(b'a'))(b"abc").unwrap();
assert_eq!(input, b"abc");
assert_eq!(value, b'a');
}
#[test]
fn should_fail_when_child_parser_fails() {
peek(byte(b'b'))(b"abc").unwrap_err();
}
}
mod one_or_more {
use super::*;
#[test]
fn should_fail_if_child_parser_never_succeeds() {
one_or_more(byte(b'b'))(b"abc").unwrap_err();
}
#[test]
fn should_succeed_if_child_parser_succeeds_at_least_once() {
let (input, value) = one_or_more(take(2))(b"abc").unwrap();
assert_eq!(input, b"c");
assert_eq!(value, vec![b"ab"]);
}
#[test]
fn should_succeed_if_child_parser_succeeds_at_multiple_times() {
let (input, value) = one_or_more(take(2))(b"abcde").unwrap();
assert_eq!(input, b"e");
assert_eq!(value, vec![b"ab", b"cd"]);
}
}
mod zero_or_more {
use super::*;
#[test]
fn should_succeed_if_child_parser_never_succeeds() {
let (input, value) = zero_or_more(byte(b'b'))(b"abc").unwrap();
assert_eq!(input, b"abc");
assert_eq!(value, Vec::new());
}
#[test]
fn should_succeed_if_child_parser_succeeds_at_least_once() {
let (input, value) = zero_or_more(take(2))(b"abc").unwrap();
assert_eq!(input, b"c");
assert_eq!(value, vec![b"ab"]);
}
#[test]
fn should_succeed_if_child_parser_succeeds_at_multiple_times() {
let (input, value) = zero_or_more(take(2))(b"abcde").unwrap();
assert_eq!(input, b"e");
assert_eq!(value, vec![b"ab", b"cd"]);
}
}
mod take_util_byte {
use super::*;
#[test]
fn should_consume_until_predicate_matches() {
let (input, value) = take_until_byte(|c| c == b'c')(b"abcde").unwrap();
assert_eq!(input, b"cde");
assert_eq!(value, b"ab");
}
#[test]
fn should_consume_completely_if_predicate_never_matches() {
let (input, value) = take_until_byte(|c| c == b'z')(b"abcde").unwrap();
assert_eq!(input, b"");
assert_eq!(value, b"abcde");
}
#[test]
fn should_succeed_if_nothing_consumed_because_matched_immediately() {
let (input, value) = take_until_byte(|c| c == b'a')(b"abcde").unwrap();
assert_eq!(input, b"abcde");
assert_eq!(value, b"");
}
#[test]
fn should_succeed_fail_if_input_is_empty() {
let (input, value) = take_until_byte(|c| c == b'a')(b"").unwrap();
assert_eq!(input, b"");
assert_eq!(value, b"");
}
}
mod rtake_util_byte {
use super::*;
#[test]
fn should_consume_from_back_until_predicate_matches() {
let (input, value) = rtake_until_byte(|c| c == b'c')(b"abcde").unwrap();
assert_eq!(input, b"abc");
assert_eq!(value, b"de");
}
#[test]
fn should_consume_from_back_completely_if_predicate_never_matches() {
let (input, value) = rtake_until_byte(|c| c == b'z')(b"abcde").unwrap();
assert_eq!(input, b"");
assert_eq!(value, b"abcde");
}
#[test]
fn should_succeed_if_nothing_consumed_because_matched_immediately() {
let (input, value) = rtake_until_byte(|c| c == b'e')(b"abcde").unwrap();
assert_eq!(input, b"abcde");
assert_eq!(value, b"");
}
#[test]
fn should_succeed_fail_if_input_is_empty() {
let (input, value) = rtake_until_byte(|c| c == b'a')(b"").unwrap();
assert_eq!(input, b"");
assert_eq!(value, b"");
}
}
mod take {
use super::*;
#[test]
fn should_consume_cnt_bytes() {
let (input, value) = take(2)(b"abc").unwrap();
assert_eq!(input, b"c");
assert_eq!(value, b"ab");
}
#[test]
fn should_fail_if_takes_nothing() {
take(0)(b"abc").unwrap_err();
}
#[test]
fn should_fail_if_not_enough_bytes() {
take(4)(b"abc").unwrap_err();
}
#[test]
fn should_support_taking_exactly_enough_bytes_as_input() {
let (input, value) = take(3)(b"abc").unwrap();
assert_eq!(input, b"");
assert_eq!(value, b"abc");
}
}
mod bytes {
use super::*;
#[test]
fn should_succeed_if_bytes_match_start_of_input() {
let (input, value) = bytes(b"ab")(b"abc").unwrap();
assert_eq!(input, b"c");
assert_eq!(value, b"ab");
}
#[test]
fn should_fail_if_bytes_do_not_match_start_of_input() {
let _ = bytes(b"bc")(b"abc").unwrap_err();
}
#[test]
fn should_fail_if_input_is_empty() {
let _ = bytes(b"ab")(b"").unwrap_err();
}
}
mod byte {
use super::*;
#[test]
fn should_succeed_if_next_byte_matches() {
let (input, value) = byte(b'a')(b"abc").unwrap();
assert_eq!(input, b"bc");
assert_eq!(value, b'a');
}
#[test]
fn should_fail_if_next_byte_does_not_match() {
let _ = byte(b'b')(b"abc").unwrap_err();
}
#[test]
fn should_fail_if_input_is_empty() {
let _ = byte(b'a')(b"").unwrap_err();
}
}
}
}