-
Notifications
You must be signed in to change notification settings - Fork 15
/
_pglr_test_.py
executable file
·265 lines (193 loc) · 6.33 KB
/
_pglr_test_.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
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
#!/usr/bin/python3
import os
import re
import sys
from parglare import Grammar
macronames = []
structnames = []
macronamere = re.compile(r"([A-Za-z@_\$\?][A-Za-z@_\$\?0-9]*)")
commentid = re.compile(r"COMMENT\s+([^ ]).*?\1[^\r\n]*", flags=re.DOTALL)
def macro_action(context, nodes, name):
macronames.insert(0, name.lower())
print(f"added ~~{name}~~")
return nodes
def macroname(head, input, pos):
if not (mtch := macronamere.match(input[pos:])):
return None
result = mtch.group().lower()
if result not in macronames:
return None
print(f"matched ~^~{result}~^~ in macronames")
return result
class Token:
def __init__(self, type, value) -> None:
self.type = type
self.value = value
def __repr__(self) -> str:
from pprint import pformat
return pformat(vars(self))
def get_raw(context):
return context.input_str[context.start_position: context.end_position]
"""
def build_ast(nodes, type=''):
if isinstance(nodes, parglare.parser.NodeNonTerm) and nodes.children:
if len(nodes.children) == 1:
return build_ast(nodes.children[0], nodes.symbol.name)
else:
l = []
for n in nodes.children:
if not n.symbol.name in ['COMMA']:
l.append(build_ast(n, nodes.symbol.name))
return l
else:
return Node(name=nodes.symbol.name, type=type, keyword=nodes.symbol.keyword, value=nodes.value)
"""
def make_token(context, nodes):
if len(nodes) == 1 and context.production.rhs[0].name not in (
"type", "e01", "e02", "e03", "e04", "e05", "e06", "e07", "e08", "e09", "e10", "e11"):
nodes = Token(context.production.rhs[0].name, nodes[0])
print(f"mt~{nodes!s}~")
if context.production.rhs[0].name in (
"type", "e01", "e02", "e03", "e04", "e05", "e06", "e07", "e08", "e09", "e10", "e11"):
nodes = nodes[0]
return nodes
cur_segment = "ds" # !
indirection = 0 # !
def segoverride(context, nodes):
global cur_segment
if isinstance(nodes[0], list):
cur_segment = nodes[0][-1]
return nodes[0][:-1] + [Token("segoverride", nodes[0][-1]), nodes[2]]
cur_segment = nodes[0] # !
return [Token("segoverride", nodes[0]), nodes[2]]
def ptrdir(context, nodes):
if len(nodes) == 3:
return [Token("ptrdir", nodes[0]), nodes[2]]
else:
return [Token("ptrdir", nodes[0]), nodes[1]]
def includedir(context, nodes, name):
print(name)
return nodes
def asminstruction(context, nodes, instruction, args):
global cur_segment
global indirection
print(
f"instruction {get_raw(context)} {nodes!s} ~~ {cur_segment!s} {indirection!s}",
)
cur_segment = "ds" # !
indirection = 0 # !
return nodes
def notdir(context, nodes):
nodes[0] = "~"
return nodes
def ordir(context, nodes):
nodes[1] = "|"
return nodes
def xordir(context, nodes):
nodes[1] = "^"
return nodes
def anddir(context, nodes):
nodes[1] = " & "
return nodes
def register(context, nodes):
return Token("register", nodes[0].lower())
def segmentregister(context, nodes):
return Token("segmentregister", nodes[0].lower())
def sqexpr(context, nodes):
global indirection
indirection = 1
res = nodes[1]
# if isinstance(res, list):
return Token("sqexpr", res)
def offsetdir(context, nodes):
# global indirection
return Token("offsetdir", nodes[1])
def segmdir(context, nodes):
# global indirection
return Token("segmdir", nodes[1])
def instrprefix(context, nodes):
print(f"instrprefix /~{nodes!s}" + "~\\")
return nodes
def LABEL(context, nodes):
return Token("LABEL", nodes)
def STRING(context, nodes):
return Token("STRING", nodes)
def INTEGER(context, nodes):
return Token("INTEGER", nodes)
def expr(context, nodes):
return Token("expr", make_token(context, nodes))
def structname(head, s, pos):
if not (mtch := macronamere.match(s[pos:])):
return None
result = mtch.group().lower()
if result not in structnames:
return None
logging.debug(f" ~^~{result}~^~ in structnames")
return result
def structdir(context, nodes, name, item):
print("structdir", nodes)
structnames.insert(0, name.children.lower())
print(f"structname added ~~{name.children}~~")
return [] # Token('structdir', nodes) TODO ignore by now
def structinstdir(context, nodes, label, type, values):
print(f"structinstdir{label!s}{type!s}{values!s}")
return nodes # Token('structdir', nodes) TODO ignore by now
def memberdir(context, nodes, variable, field):
result = Token("memberdir", [variable, field])
print(result)
return result
def commentkw(head, s, pos):
return mtch.group(0) if (mtch := commentid.match(s[pos:])) else None
recognizers = {
"macroname": macroname,
"structname": structname,
"COMMENTKW": commentkw,
}
actions = {
"field": make_token,
"memberdir": memberdir,
"structinstdir": structinstdir,
"expr": expr,
"structinstance": make_token,
"structdir": structdir,
"includedir": includedir,
"instrprefix": instrprefix,
"macrodir": macro_action,
"asminstruction": asminstruction,
"STRING": STRING,
"LABEL": LABEL,
"INTEGER": INTEGER,
"aexpr": make_token,
"cexpr": make_token,
"cxzexpr": make_token,
"flagname": make_token,
"primary": make_token,
"recordconst": make_token,
"simpleexpr": make_token,
"sizearg": make_token,
"term": make_token,
"segoverride": segoverride,
"ptrdir": ptrdir,
"offsetdir": offsetdir,
"segmdir": segmdir,
"register": register,
"segmentregister": segmentregister,
"sqexpr": sqexpr,
"notdir": notdir,
"ordir": ordir,
"xordir": xordir,
"anddir": anddir,
}
file_name = f"{os.path.dirname(os.path.realpath(__file__))}/masm2c/_masm61.pg"
grammar = Grammar.from_file(file_name, ignore_case=True, recognizers=recognizers)
from parglare import Parser
parser = Parser(grammar, debug=True, actions=actions, debug_colors=True)
codeset = "cp437"
if sys.version_info[0] >= 3:
sys.stdout.reconfigure(encoding="utf-8")
for i in sys.argv[1:]:
with open(i, encoding=codeset) as f:
input_str = f.read()
result = parser.parse(input_str, file_name=file_name)
from pprint import pprint
pprint(result)