-
Notifications
You must be signed in to change notification settings - Fork 0
/
twotwodisk_parser.py
executable file
·84 lines (70 loc) · 3.02 KB
/
twotwodisk_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
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
#!/usr/bin/python3
import sys
from lark.lark import Lark
from lark import Transformer, UnexpectedToken, UnexpectedCharacters, UnexpectedEOF
from twotwodisk import TwoTwoDisk, DuplicateParmError, MissingParmError
from twotwodisk_grammar import TWOTWODISK, build_callbacks
from twotwodisk_transform import TwoTwoDiskTransformer, DuplicateDefError, SectorsBeforeNumSidesError, SideListBeforeSectorsError
try:
infile = sys.argv[1]
except IndexError:
raise SystemExit(f"Usage: {sys.argv[0]} <22DiskDef_file>")
xfm = TwoTwoDiskTransformer()
# Instantiate the parser and connect data handlers
parser = Lark(TWOTWODISK,
lexer = 'contextual',
lexer_callbacks = build_callbacks(xfm),
parser = 'lalr',
transformer = xfm)
with open(infile, "r") as f:
# Slurp in the entire file
data = f.read()
try:
# Process the input
parser.parse(data)
# If we made it here, the parse succeeded. Get dictionary of
# 22Disk definitions and print in alphabetical order
defdict = xfm.get_definitions()
for key in sorted(defdict.keys()):
val = defdict[key]
# A TwoTwoDisk object turns itself into a text representation
# of the definition when used as a string.
print(val)
except DuplicateParmError as d:
print("Duplicate parameter in definition '%s' (line: %d, column: %d)" % (d.defname, d.line, d.column))
ctxt = d.get_context(data)
print(ctxt)
except MissingParmError as d:
print("Required parameters missing from definition '%s':" % d.defname)
for parm in d.missing:
print("%s " % parm, end="")
print("\n")
except DuplicateDefError as d:
print("Duplicate definition '%s' at line: %d, column: %d" % (d.defname, d.line, d.column))
ctxt = d.get_context(data)
print(ctxt)
except SectorsBeforeNumSidesError as d:
print("SECTORS parameter seen before SIDES in definition '%s' (line: %d, column: %d)\n" % (d.defname, d.line, d.column))
ctxt = d.get_context(data)
print(ctxt)
except SideListBeforeSectorsError as d:
print("SIDE1/SIDE2 parameter seen before SECTORS in definition '%s' (line: %d, column: %d)\n" % (d.defname, d.line, d.column))
ctxt = d.get_context(data)
print(ctxt)
except UnexpectedToken as u:
print("Unxpected token at line: %d, column: %d" % (u.line, u.column))
ctxt = u.get_context(data)
print(ctxt)
if len(u.expected) > 1:
print("Expected one of:")
else:
print("Expected: ", end="")
for tok in u.expected:
name = str(parser.get_terminal(tok).pattern)
print(name.replace('\\',''))
except UnexpectedCharacters as u:
print(u)
except UnexpectedEOF as u:
print("Unexpected EOF at line: %d, column: %d\n" % (u.line, u.column))
ctxt = u.get_context(data)
print(ctxt)