-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathparser.py
67 lines (47 loc) · 1.33 KB
/
parser.py
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
from typing import Iterable, Union
from enum import Enum, auto
from dataclasses import dataclass
class Go(Enum):
LEFT = auto()
RIGHT = auto()
UP = auto()
DOWN = auto()
@dataclass
class Paint:
pass
@dataclass
class Times:
count: int
@dataclass
class End:
times_idx: int
Command = Union[Go, Paint, Times, End]
class ParseError(Exception):
pass
def parse(lines: Iterable[str]) -> Iterable[Command]:
loops = []
for idx, line in enumerate(lines):
command, *rest = line.strip().split()
if command.isdigit() and len(rest) == 1 and rest[0] == 'times':
yield Times(count=int(command))
loops.append(idx)
continue
if rest:
raise ParseError('the only command with arguments is times')
if command == 'left':
yield Go.LEFT
elif command == 'right':
yield Go.RIGHT
elif command == 'up':
yield Go.UP
elif command == 'down':
yield Go.DOWN
elif command == 'paint':
yield Paint()
elif command == 'end':
if not loops:
raise ParseError('unpaired end found')
loop_location = loops.pop()
yield End(times_idx=loop_location)
else:
raise ParseError(f'unknown command {command!r}')