aoc-parse 0.2.13

A little library for parsing your Advent of Code puzzle input
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
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
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
# 2021 examples

## 2021 Dec 1

```text
199
200
208
210
...
```

```rust
lines(uint)
```

I had to compromise and let Rust have its static types, so this will actually be something more like

```rust
lines(u64)
```


## 2021 Dec 2

```text
forward 5
down 5
forward 8
up 3
...
```

```rust
#[derive(Deserialize)]
enum Command {
    Forward(u64),
    Down(u64),
    Up(u64),
}

lines({
    "forward" uint,
    "down" uint,
    "up" uint,
})
```

or maybe `lines(<Command>)`, if the parser can be completely autogenerated from
the `enum` alone, which is maybe too much to hope for.

This seems very hard to do, so I will settle for

```
lines({
    "forward " (n:u64) => Command::Forward(n),
    "down " (n:u64) => Command::Down(n),
    "up " (n:u64) => Command::Up(n),
})
```

## 2021 Dec 3

```text
00100
11110
10110
10111
...
```

```rust
lines(uint_bin)
```

If you prefer `Vec<bool>` output, that's possible too; you'd just need to write

```rust
lines(digit_bin+)
```

## 2021 Dec 4

```text
7,4,9,5,11,17,23,2,0,14,21,24,10,16,13,6,15,25,12,22,18,20,8,19,3,26,1

22 13 17 11  0
 8  2 23  4 24
21  9 14 16  7
 6 10  3 18  5
 1 12 20 15 19

 3 15  0  2 22
 9 18 13 17  5
19  8  7 25 23
20 11 10 24  4
14 21 16 12  6

...
```

```rust
sections(
  repeat_separated_by(int, ","),
  grid_ws(int),
)
```

A way to specify the width and height of the grid would be nice.


## 2021 Dec 5

```text
0,9 -> 5,9
8,0 -> 0,8
9,4 -> 3,4
2,2 -> 2,1
```

```rust
lines(vec2(uint) " -> " vec2(uint))
```

or maybe `lines(uint "," uint " -> " uint "," uint)`

or `lines("{},{} -> {},{}")`


## 2021 Dec 6

```text
3,4,3,1,2
```

```rust
repeat_separated_by(int, ",")
```


## 2021 Dec 7

Similar to Dec 6.

```text
16,1,2,0,4,2,7,1,2,14
```


## 2021 Dec 8

```text
be cfbegad cbdgef fgaecd cgeb fdcge agebfd fecdb fabcd edb | fdgacbe cefdb cefbgd gcbe
edbfga begcd cbg gc gcadebf fbgde acbgfd abcde gfcbed gfec | fcgedb cgb dgebacf gc
fgaebd cg bdaec gdafb agbcfd gdcbef bgcad gfac gcb cdgabef | cg cg fdcagb cbg
fbegcd cbd adcefb dageb afcb bc aefdc ecdab fgdeca fcdbega | efabcd cedba gadfec cb
```

```rust
struct Pattern(u8);

struct Entry {
    patterns: [Pattern; 10],
    output_value: [Pattern; 4],
}

rule seg = char("abcdefg");
rule pat = seg+;
lines(
    (patterns: fields_n(pat, 10)) " | " (output_value: fields_n(pat, 4))
)
```


## 2021 Dec 9

```text
2199943210
3987894921
9856789892
8767896789
...
```

```rust
grid(digit)
```


## 2021 Dec 10

```text
[({(<(())[]>[[{[]{<()<>>
[(()[<>])]({[<{<<[]>>(
{([(<{}[<>[]}>{[]{[(<()>
(((({<>}<{<{<>}{[]{[]{}
...
```

```rust
lines(str)
```

...though I'm actually a little confused what that could possibly mean. Is the
grammar of `str` inferred from context? Like, here it's enclosed by `lines()`
and therefore `str` means `/[^\n]*/`?


## 2021 Dec 11

```text
5483143223
2745854711
5264556173
6141336146
...
```

Same as dec 9, basically, but suppose we now enforce the 10x10 size:

```rust
lines(repeat(digit, 10), 10)
```

or maybe `list(list(digit, "", 10), "\n", 10)`


## 2021 Dec 12

```text
start-A
start-b
A-c
A-b
b-d
A-end
b-end
```

```rust
rule node = {
    "start" => START,
    "end" => END,
    name: regex(r"\w+") => name_to_node_id(name)
};
lines(seq(node, "-", node))
```


## 2021 Dec 13

```text
6,10
0,14
9,10
0,3
...

fold along y=7
fold along x=5
```

```rust
sections(
    lines(vec2(uint)),
    lines({
        "fold along x=" (x: uint) => FoldX(x),
        "fold along y=" (y: uint) => FoldY(y),
    })
)
```

Or:

```rust
sections(
    lines(vec2(uint)),
    lines({
        FoldX: "fold along x=" uint,
        FoldY: "fold along y=" uint,
    })
)
```


## 2021 Dec 14

```text
NNCB

CH -> B
HH -> N
CB -> H
NH -> C
```

```rust
sections(upper+, upper+ " -> " upper+)
```


## 2021 Dec 15

The first grid.

```text
1163751742
1381373672
2136511328
3694931569
7463417111
1319128137
1359912421
3125421639
1293138521
2311944581
```

```rust
grid(digit)
```


## 2021 Dec 16

```text
8A004A801A8002F478
```

```rust
uint_hex
```


## 2021 Dec 17

```text
target area: x=20..30, y=-10..-5
```

```rust
"target area: x=" int ".." int ", y=" int ".." int
```

Or just `"target area: x={int}..{int}, y={int}..{int}"`


## 2021 Dec 18

```text
[[[0,[5,8]],[[1,7],[9,6]]],[[4,[1,2]],[[1,4],2]]]
[[[5,[2,8]],4],[5,[[9,9],0]]]
[6,[[[6,2],[5,6]],[[7,6],[4,7]]]]
[[[6,[0,7]],[0,9]],[4,[9,[9,0]]]]
...
```

```rust
rule num = {
  n: uint => Number::Regular(n),
  "[" (l: num) "," (r: num) "]" => Pair(l, r),
};
lines(num)
```


## 2021 Dec 19

```text
--- scanner 0 ---
404,-588,-901
528,-643,409
-838,591,734
390,-675,-793
...

--- scanner 1 ---
686,422,578
605,423,415
515,917,-361
-336,658,858
...
```

```rust
sections(
    lines(
        "--- scanner " uint " ---",
        vec3(int),
    )
)
```


## 2021 Dec 20

```text
..#.#..#####.#.#.#.###.##.....###.##.#..###.####..#####..#....#..#..##..###..######.###...####..#..#####..##..#.#####...##.#.#..#.##..#.#......#.###.######.###.####...#.##.##..#..#..#####.....#.#....###..#.##......#.....#..#..#..##..#...##.######.####.####.#.#...#.......#..#.#.#...####.##.#......#..#...##.#.##..#...##.#.##..###.#......#.#.......#.#.#.####.###.##...#.....####.#..#..#.##.#....##..#.####....##...##..#...#......#.#.......#.......##..####..#...#.#.#...##..#.#..###..#####........#..####......#..#

#..#.
#....
##..#
..#..
..###
```

```rust
rule bool = {
    "#" => true,
    "." => false,
};
sections(
    repeat(bool, 512),
    (g: grid(bool)) => Image { grid: g, elsewhere: false },
)
```


## 2021 Dec 21

```text
Player 1 starting position: 6
Player 2 starting position: 10
```

```rust
lines(
    "Player 1 starting position: " uint,
    "Player 2 starting position: " uint,
)
```


## 2021 Dec 22

```text
on x=10..12,y=10..12,z=10..12
on x=11..13,y=11..13,z=11..13
off x=9..11,y=9..11,z=9..11
on x=10..10,y=10..10,z=10..10
```

```rust
rule range = (start: uint) ".." (stop: uint) => start..stop;
rule onoff = { "on" => true, "off" => false };
lines(
    (on: onoff) " x=" (x: range) ",y=" (y: range) ",z=" (z: range) =>
        Cuboid {on, x, y, z}
)
```


## 2021 Dec 23

A weird one.

```text
#############
#...........#
###B#C#B#D###
  #A#D#C#A#
  #########
```

```rust
rule amph = char("ABCD");
(
    "#############\n"
    "#...........#\n"
    "###" amph "#" amph "#" amph "#" amph "###\n"
    "  #" amph "#" amph "#" amph "#" amph "#\n"
    "  #########\n"
)
```


### 2021 Dec 24

```text
inp z
inp x
mul z 3
eql z x
```

```rust
#[derive(Deserialize)]
enum Register { W, X, Y, Z }

enum Operand { Reg(Register), Imm(i64) }

rule v = " " {
    r: char("wxyz") => Operand::Reg(r),
    u: uint => Operand::Imm(u),
};
lines({
    "inp" v,
    "add" v v,
    "mul" v v,
    "div" v v,
    "mod" v v,
    "eql" v v,
})
```

Maybe `rule v = " " { char("wxyz"), uint };` would suffice.

When smooshing a match for `"inp" v` into an enum type, the string at the start
is checked against the variant names, case-insensitively. This feature is
specifically because assembly-like languages are so common.


### 2021 Dec 25

```text
v...>>.vv>
.vv>>.vv..
>>.>v>...v
>>v>>.>.v.
v>v.vv.v..
>.>>..v...
.vv..>.>v.
v.v..>>v.v
....v..v.>
```

```rust
grid(char(".v>"))
```

## 2020

### 2020 Dec 1

Like 2021 Dec 1.

### 2020 Dec 2

```
1-3 a: abcde
1-3 b: cdefg
2-9 c: ccccccccc
```

```rust
lines(uint "-" uint " " lower ": " lower+)
```

### 2020 Dec 3

```
..##.......
#...#...#..
.#....#..#.
..#.#...#.#
...
```

```rust
grid(char(".#"))
```

### 2020 Dec 4

```
ecl:gry pid:860033327 eyr:2020 hcl:#fffffd
byr:1937 iyr:2017 cid:147 hgt:183cm

iyr:2013 ecl:amb cid:350 eyr:2023 pid:028048884
hcl:#cfa07d byr:1929

hcl:#ae17e1 iyr:2013
eyr:2024
ecl:brn pid:760753108 byr:1931
hgt:179cm
```

```rust
sections(repeat_separated_by(lower+ ":" regex(r"[^ ]*"), char(" \n")))
```

This will require the `repeat_separated_by` parser to do a little backtracking.


### 2020 Dec 5

```
FBBFBFBLRR
FBFFFFFLLR
FBBBBBBLLR
FFBFBBBRLL
FBBFFFFLRR
```

```rust
lines(
  repeat(char("FB"), 7)
  repeat(char("LR"), 3)
)
```

### 2020 Dec 6

```
abc

a
b
c

ab
ac

a
a
a
a

b
```

```rust
sections(lines(lower+))
```

### 2020 Dec 7

```
light red bags contain 1 bright white bag, 2 muted yellow bags.
dark orange bags contain 3 bright white bags, 4 muted yellow bags.
bright white bags contain 1 shiny gold bag.
muted yellow bags contain 2 shiny gold bags, 9 faded blue bags.
shiny gold bags contain 1 dark olive bag, 2 vibrant plum bags.
dark olive bags contain 3 faded blue bags, 4 dotted black bags.
vibrant plum bags contain 5 faded blue bags, 6 dotted black bags.
faded blue bags contain no other bags.
dotted black bags contain no other bags.
```

```rust
struct Bags { 
    count: usize,
    color: String,
}

struct Rule {
    color: String,
    contents: Vec<Bags>,
}

lines(
    (color: regex(".*"))
    " bags contain "
    (contents: {
        "no other bags" => vec![],
        repeat_separated_by(
            (count: uint) (color: regex(".*")) regex("bag[s]?"),
            ", "
        ),
    })
    "."
)
```

### 2020 Dec 8

```
nop +0
acc +1
jmp +4
acc +3
jmp -3
acc -99
...
```

```rust
#[derive(Deserialize)]
enum Insn {
    Acc(isize),
    Jmp(isize),
    Nop(isize),
}

rule arg ::= {
    "+" (u: uint) => u as isize,
    "-" (u: uint) => -(u as isize),
};
{
    "acc" arg,
    "jmp" arg,
    "nop" arg,
} as Insn
```

### 2020 Dec 9

Same as Dec 1.

### 2020 Dec 10

Same as Dec 1.

### 2020 Dec 11

```
L.LL.LL.LL
LLLLLLL.LL
L.L.L..L..
LLLL.LL.LL
L.LL.LL.LL
L.LLLLL.LL
..L.L.....
LLLLLLLLLL
L.LLLLLL.L
L.LLLLL.LL
```

```rust
grid(char(".L#"))
```

### 2020 Day 12

```
F10
N3
F7
R90
F11
```

```rust
#[derive(Deserialize)]
enum Op {
    N, S, E, W, L, R, F
}

#[derive(Deserialize)]
struct Insn {
    op: Op,
    arg: usize,
}

lines((op: char("NSEWLRF")) (arg: uint))
```

### Types

If possible, I want the grammar notation to specify only the grammar; and then
you specify the output type you want and Rust finagles the parser output into
that type, a process I call "smooshing".

The problem is that sometimes you do want to specify the mapping directly in
your code; smooshing might not always work. Particularly around enums. So I
need to support that too, and the two things conflict pretty badly.

Currently Rust expressions are allowed in a parser spec, after the special `=>`
token; but I have no idea how this is going to work.


### Data model for the parser language

```rust
enum ParserExpr {
    StringLiteral(&'static str),
    Map(Box<ParserExpr>, Box<dyn Fn(ParsedValue) -> Result<ParsedValue, ParseError>>),
    Label(String, Box<ParserExpr>),
    Sequence(Vec<ParserExpr>),
    Repeat(Box<ParserExpr>, usize),
    Optional(Box<ParserExpr>),
    NamedRule(String),
    Call(String, Vec<ParserExpr>),
    OneOf(Vec<ParserExpr>),
}

enum ParsedValue {
    None,
    Exact(&'static str),
    Sequence(Vec<ParsedValue>),
    Repeat(Vec<ParsedValue>),
    Labelled(String, Box<ParsedValue>),
    RustValue(Box<dyn Any>),
}

```

### Syntax for the parser language

Here's the grammar of the parser language. Note that the grammar description
language I'm using here to specify the grammar description language is not that
language ... so ... just ... sorry, I guess.

```text
ident ::= a Rust identifier
expr ::= a Rust expression
literal ::= a Rust literal

parser ::= rule* expr

rule ::= "rule" ident "=" expr ";"

expr ::= label
  | label "=>" rust_expr        => Map($1, |...pattern of $1...| $2)

label ::= cast
  | ident ":" cast              => Label($1, $2)

cast ::= seq
  | seq "as" ty                 => Map($1, |x| $2::try_from(x))

seq ::= term
  | seq term                    => $1.seq($2)

term ::= prim
  | prim "*"                    => Repeat($1, 0)
  | prim "+"                    => Repeat($1, 1)
  | prim "?"                    => Optional($1)
  | ident "(" expr,* ")"        => Call($1, $2)

prim ::= "(" expr ")"
  | ident                       => NamedRule($1)
  | literal                     => Literal($1)
  | "{" expr,* "}"              => OneOf($1)
```


`ident` is a Rust identifier.
The `expr` after `=>` is a Rust expression.
`ty` is a Rust type expression.
`literal` is a Rust literal.

`prim ::= literal` is how exact strings get into the language; but it also
matches numeric and boolean literals, specifically for use in function
arguments. Some functions need to take some constant argument.

`named ::= ident ":" seq` assigns a name to whatever matches `seq` so that it
can be used in a `=> EXPR` Rust expression. How does this work with type
inference? I have no idea. It won't work well without more thought.

A `rule` gives a name to a pattern; `prim ::= ident` can use the name, and it
expands to the pattern. Recursive use of rules is OK.

I think I want the string `literal` to support some additional tricks like
`"{},{} -> {},{}"` where the junk matching `{}` is left unparsed until it's
time to smoosh it into a type.

There is an ambiguity in a pattern like `foo ( bar )` between the two parses
`seq ::= seq term` and `term ::= ident "(" expr,* ")"`. This is resolved in
favor of the latter. Users can disambiguate the former by adding more parens.


### Functions and built-in patterns

The built-in patterns are:

-   `int` - Arbitrary-length integer. Matches `/0|-?[1-9][0-9]*/`.
-   `uint`, `uint_bin`, `uint_hex` - Same, but in various bases,
     and disallowing the minus sign.
-   `digit` - A decimal digit. Equivalent to `char("0123456789")`.
-   `digit_bin`, `digit_hex` - Digits in various bases.
-   `lower` - One lowercase ASCII letter.
-   `upper` - One uppercase ASCII letter.

The functions are:

-   `lines(p...)` - Like `repeat_terminated_by(p, "\n")` but checks that p can't contain NL.
-   `sections(p...)` - Like `repeat_separated_by(p, "\n")` but checks that p ends with NL and can't contain a blank line (i.e. can't start with NL or contain NL NL).
-   `repeat_separated_by(p, p_sep)`
-   `fields(p...)` - Space-separated fields.
-   `fields_n(p, n)` - Exactly `n` space-separated matches for `p`.
-   `fields_commas(p...)` - Comma-separated fields.
-   `repeat(p, n)` - Exactly `n` consecutive matches for `p`, no separator.
-   `vec2(p)`, `vec3(p)` - Comma-separated pairs and triples.
-   `grid(p)`, `grid_ws(p)` - Grids, one row per line, where every row has
    the same number of p's. `grid` does not expect anything between the
    `p` matches; `grid_ws` expects whitespace and checks that p can't contain whitespace.
-   `regex(string_literal)` - A regex match. Produces strings, I guess?
-   `char(string_literal)` - Match any single character in the given string;
    returns the index of the first one that matches. Maybe also can be smooshed
    into an enum type?

I'm missing a grand unified "repeat" function that allows you to say either
"separated by" or "each followed by" or "each followed by, except the last one
is optional" or "no separator"; and also allows you to say either "repeat
exactly N times and give me an array" or "repeat 0 or more times" or "repeat 1
or more times". `rep(p, sep=p2, term=p2, min=uint, n=uint)`


I'm not super happy with the phrasing of `lines` and friends. Requirements:

-   Distinguish between cases where we expect exactly two lines and those where
    the last pattern repeats 0 or more times.

-   The first thing I type should work. No super mysterious errors.

-   By the way, it sure would be nice to detect if a `lines` argument can match
    `\n` or if a `sections` argument can match `\n\n` or if a `fields` argument
    can match a space. They usually shouldn't, unless the nested delimiter is
    considered "escaped" somehow.

It could be `tuple_lines` and `vec_lines`, for maximum annoyance, but I hope I
can do better than that... it's quite common to have one special line or
section at the top, followed by a repeating line or section pattern.

Are function-calls transparent to labels?
For example, `(x:uint) (y:uint) => (x, y)` would work, but
`f(x:uint) f(y:uint) => (x, y)` is iffy, since `f` would need to
guarantee that if it matches, then the pattern argument was matched exactly
once.

I wonder if it'd be useful to have a `pattern if test` form, where after
successfully parsing `pattern`, we evaluate the Rust boolean expression `test`,
and proceed only if it returns `true` (else fail and backtrack). We'd have to
populate all the labeled variables, I suppose. There's no great way to do this.