-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsdl_parser.py
287 lines (229 loc) · 8.48 KB
/
sdl_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
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
import importlib
import inspect
import os
import shutil
import sys
import time
from pcpp.pcmd import CmdPreprocessor
from setup import PATH_BY_UNIT, SDL_ROOT
import utils
if not PATH_BY_UNIT:
print("Error: no units chosen to parse. Please edit PATH_BY_UNIT in setup.py.")
sys.exit(1)
_FILE_STR: str = """
from tree_sitter import Node
from visitor import visitor
@visitor
class {0}Visitor:
def __init__(
self,
unit: str,
):
pass
def visit_function(self, rules: dict[str, Node | list[Node]]):
raise NotImplementedError
def visit_enum(self, rules: dict[str, Node | list[Node]]):
raise NotImplementedError
def visit_opaque(self, rules: dict[str, Node | list[Node]]):
raise NotImplementedError
def visit_struct(self, rules: dict[str, Node | list[Node]]):
raise NotImplementedError
def visit_union(self, rules: dict[str, Node | list[Node]]):
raise NotImplementedError
def visit_bitflag(self, rules: dict[str, Node | list[Node]]):
raise NotImplementedError
def visit_alias(self, rules: dict[str, Node | list[Node]]):
raise NotImplementedError
def visit_callback(self, rules: dict[str, Node | list[Node]]):
raise NotImplementedError
def visit_fn_macro(self, rules: dict[str, Node | list[Node]]):
raise NotImplementedError
def visit_const(self, rules: dict[str, Node | list[Node]]):
raise NotImplementedError
"""
if len(sys.argv) < 2 or sys.argv[1] == "--help":
print("Usage: python sdl_parser.py <path-to-bind-gen-module> <gen-args>...")
sys.exit(1)
elif sys.argv[1] == "--new":
if len(sys.argv) < 3:
print("Usage: python sdl_parser.py --new <module-name>")
sys.exit(1)
if os.path.exists(f"gen/{sys.argv[2]}.py"):
print("Module already exists")
sys.exit(1)
with open(f"gen/{sys.argv[2]}.py", "w") as f:
f.write(_FILE_STR.format(sys.argv[2].capitalize()))
sys.exit(0)
mod = importlib.import_module(sys.argv[1])
gen = mod.__name__[mod.__name__.find(".") + 1 :]
_vis = [mem for mem in inspect.getmembers(mod) if mem[0] == "Visitor"]
if not _vis:
print("Module does not contain a Visitor class")
sys.exit(1)
else:
visitor = getattr(mod, _vis[0][0])
def os_defines() -> list[str]:
match sys.platform:
case "aix":
return ["-D", "_AIX"]
case "android":
return ["-D", "__ANDROID__", "-D", "ANDROID"]
case "cygwin":
return ["-D", "_WIN32", "-D", "__CYGWIN__"]
case "darwin":
return ["-D", "__APPLE__", "-D", "__MACH__"]
case "emscripten":
return ["-D", "__EMSCRIPTEN__"]
case "ios":
return ["-D", "__APPLE__", "-D", "__IOS__"]
case "linux":
return ["-D", "__linux__"]
case "wasi":
return ["-D", "__wasi__"]
case "win32":
return [
"-D",
"_WIN32",
"-D",
"_MSC_VER=1900", # VS2015 should be enough
]
def parse_file(*args, input: str, output: str):
os.makedirs(os.path.dirname(output), exist_ok=True)
_ = CmdPreprocessor(
argv=[
"<dummy-arg-doesnt-matter>",
input,
"-o",
output,
*args,
*os_defines(),
"-D",
"SDL_MAIN_USE_CALLBACKS", # test
"-D",
"SDLCALL=", # tree-sitter has a hard time parsing __cdecl
"-D",
"SDL_DECLSPEC=", # save us some time and headaches
"-D",
"SDL_DEPRECATED=", # save us some time and headaches
"-D",
"SDL_UNUSED=", # save us some time and headaches
"-D",
"SDL_ASSERT_LEVEL=1", # save us some time and headaches
"-D",
"SDL_NODISCARD=", # save us some time and headaches
"-D",
"SDL_NORETURN=", # save us some time and headaches
"-D",
"SDL_ANALYZER_NORETURN=", # save us some time and headaches
"-D",
"SDL_MALLOC=", # save us some time and headaches
"-D",
"SDL_ALLOC_SIZE=", # save us some time and headaches
"-D",
"SDL_ALLOC_SIZE2=", # save us some time and headaches
"-D",
"SDL_BYTEORDER=SDL_LIL_ENDIAN", # save us some time and headaches
"-D",
"SDL_FLOATWORDORDER=SDL_LIL_ENDIAN", # save us some time and headaches
"-D",
"SDL_SLOW_MEMCPY", # save us some time and headaches
"-D",
"SDL_SLOW_MEMMOVE", # save us some time and headaches
"-D",
"SDL_SLOW_MEMSET", # save us some time and headaches
"-D",
"SDL_COMPILE_TIME_ASSERT", # save us some time and headaches
"-D",
"SDL_FALLTHROUGH=", # save us some time and headaches
"-D",
"NULL=0", # save us some time and headaches
"-D",
"SDL_INLINE=", # save us some time and headaches
"-D",
"SDL_FORCE_INLINE=", # save us some time and headaches
"-D",
"DOXYGEN_SHOULD_IGNORE_THIS", # we are not interested anything doxygen doesn't want
"-U",
"SDL_WIKI_DOCUMENTATION_SECTION", # this is never defined (we're not building the wiki)
"-D",
"SDL_BeginThreadFunction",
"-D",
"SDL_EndThreadFunction",
"-D",
"SDL_platform_defines_h_", # save us some time and headaches
"-D",
"SDL_oldnames_h_", # save us some time and headaches
"-D",
"SDL_stdinc_h_", # save us some time and headaches
"-D",
"SDL_version_h_", # save us some time and headaches
"-D",
"SDL_hidapi_h_", # we don't care about this
"-D",
# we are not including SDL_stdinc.h, but this is needed
# the cast to `int` is needed since this is used on enums
# and enums are considered `int` in C
"""SDL_FOURCC(A, B, C, D)=\
(int)((SDL_static_cast(Uint32, SDL_static_cast(Uint8, (A))) << 0) | \
(SDL_static_cast(Uint32, SDL_static_cast(Uint8, (B))) << 8) | \
(SDL_static_cast(Uint32, SDL_static_cast(Uint8, (C))) << 16) | \
(SDL_static_cast(Uint32, SDL_static_cast(Uint8, (D))) << 24))""",
"-D",
"SDL_static_cast(T, V)=((T)(V))", # save us some time and headaches
# skip this as we need them to detect platform-specific code
"--passthru-defines", # keep defines in output
"--passthru-unknown-exprs", # NOTE: this keeps the ifdef/endif blocks
"--passthru-unfound-includes", # skip missing includes
"--passthru-comments", # keep comments in output
"--output-encoding",
"utf-8", # output encoding
"--line-directive",
"", # don't output line directives
]
)
with open(output, "r") as f:
infile = f.read()
parser = utils.parser()
tree = parser.parse(infile.encode())
return tree
def parse_query(file: str):
with open(file, "r") as f:
query_txt = f.read()
query = utils.query(query_txt)
return query
def parse_extension(ext: str, query):
sdl_ext = f"SDL_{ext}"
tree = parse_file(
input=f"{SDL_ROOT}/{PATH_BY_UNIT[sdl_ext]}",
output=f"out/{gen}/pp/{sdl_ext}.i",
)
root = tree.root_node
vis = visitor(ext)
for i, rules in query.matches(root):
vis.visit(rules)
def main():
query = parse_query("query.scm")
tree = parse_file(
"-I",
SDL_ROOT,
input=f"{SDL_ROOT}/{PATH_BY_UNIT['SDL']}",
output=f"out/{gen}/pp/SDL.i",
)
root = tree.root_node
vis = visitor("SDL")
for i, rules in query.matches(root):
vis.visit(rules)
for ext in PATH_BY_UNIT.keys():
if ext == "SDL":
continue
parse_extension(ext[4:], query)
# copy any file from the gen folder to the out folder
if os.path.exists(f"gen/{gen}/"):
for file in os.listdir(f"gen/{gen}/"):
if os.path.exists(f"out/{gen}/{file}"):
os.remove(f"out/{gen}/{file}")
shutil.copy(f"gen/{gen}/{file}", f"out/{gen}/{file}")
if __name__ == "__main__": # At this point, this is just for readability
start = time.time()
main()
print(f"Elapsed: {time.time() - start:.2f}s")