# 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.