-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathgenerator.py
More file actions
executable file
·175 lines (146 loc) · 5.34 KB
/
generator.py
File metadata and controls
executable file
·175 lines (146 loc) · 5.34 KB
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
#!/usr/bin/python
import os
import re
from os import walk
header_path = "/usr/include/SDL2/"
out_folder = "generated/"
included = list(map(re.compile, [
r"^SDL_(.*)"
]))
excluded = list(map(re.compile, [
r"^SDL_test(.*)",
r"^SDL_opengl(.*)",
]))
excluded.extend(map(lambda n: re.compile("SDL_" + n + ".h"), [
"assert", "atomic", "bits", "config", "endian", "filesystem", "loadso",
"log", "main", "mutex", "name", "platform", "quit", "revision", "rwops",
"shape", "stdinc", "system", "syswm", "thread", "timer", "types",
]))
def useful_names(name):
for regex in included:
if not regex.match(name):
return False
for regex in excluded:
if regex.match(name):
return False
return True
header_filenames = []
for (dirpath, dirnames, filenames) in walk(header_path):
header_filenames.extend(filenames)
header_filenames = list(filter(useful_names, header_filenames))
header_filenames.sort()
headers = list(
map(lambda f: (f, os.path.join(header_path, f)), header_filenames))
# -------------------------- Source transformation -----------------------------
CONST_REGEX = re.compile(
r"#define\s+(?P<name>[a-zA-Z]\w*)\s+\(?(?P<value>[\w\d&|<>+\-*/\"]*)[\s\)]", re.MULTILINE)
STRUCT_REGEX = re.compile(
r"(?<=typedef struct)(?:[\s\w]*)\{(?P<contents>[^}]*)\}(?:\s*)(?:\w*?)(?:\s*)(?P<name>\w*);")
ENUM_REGEX = re.compile(
r"(?<=typedef enum)(?:[\s\w]*)\{(?P<contents>[^}]*)\}(?:\s*)(?:\w*?)(?:\s*)(?P<name>\w*);")
FUNCTION_REGEX = re.compile(
r"(?<=extern DECLSPEC )(?P<return_type>[\w\s\*]*)(?:SDLCALL)\s*(?P<name>[\w\d]*)\((?P<params>[\w\d\s,\*]*)\);")
TYPE_MAP = {
'Uint8': 'byte',
'Sint8': 'sbyte',
'Uint16': 'ushort',
'Sint16': 'short',
'Uint32': 'uint',
'Sint32': 'int',
'Uint64': 'ulong',
'Sint64': 'long',
'char': 'IntPtr'
}
def sanitize(source):
return source.replace("@{", "").replace("@}", "")
def extract_defines(source):
result = ""
matches = [m.groupdict() for m in CONST_REGEX.finditer(source)]
for match in matches:
if not match["value"]:
continue
const_type = "int"
if "\"" in match["value"]:
const_type = "string"
result += "public const " + const_type + " " + match["name"] + " = "
result += match["value"] + ";\n"
return result + "\n"
def extract_structs(source):
result = ""
matches = [m.groupdict() for m in STRUCT_REGEX.finditer(source)]
for match in matches:
result += "[StructLayout(LayoutKind.Sequential)]\n"
result += "public struct " + match["name"] + "\n{\n"
result += match["contents"]
result += "\n}\n"
return result + "\n"
def extract_enums(source):
result = ""
matches = [m.groupdict() for m in ENUM_REGEX.finditer(source)]
for match in matches:
result += "public enum " + match["name"] + "\n{\n"
result += match["contents"]
result += "\n}\n"
return result + "\n"
def rewrite_function_return_type(name):
name = name.strip()
if name.startswith('const '):
name = name[6:]
if '*' not in name:
if name in TYPE_MAP:
name = TYPE_MAP[name]
return name
return 'IntPtr'
def rewrite_function_param(param):
if '*' not in param:
return param
(p_type, p_name) = (param.split('*')
[0].strip(), param.split('*')[1].strip())
if p_type in TYPE_MAP:
p_type = TYPE_MAP[p_type]
if p_type != 'IntPtr':
p_type = 'ref ' + p_type
return p_type + " " + p_name
def rewrite_function_params(params_str):
if params_str == "void":
return ""
params = map(lambda s: s.strip(), params_str.split(","))
params = map(lambda s: s[6:] if s.startswith('const ') else s, params)
params = map(rewrite_function_param, params)
return ", ".join(params)
def extract_functions(source):
result = ""
matches = [m.groupdict() for m in FUNCTION_REGEX.finditer(source)]
for match in matches:
result += "[DllImport(\"libSDL2.so\")]\n"
result += "public static extern "
result += rewrite_function_return_type(match["return_type"])
result += " " + match["name"]
result += "(" + rewrite_function_params(match["params"]) + ");\n"
return result + "\n"
def build_source(class_name, contents, all_classes):
contents = sanitize(contents)
result = "using System;\nusing System.Runtime.InteropServices;\n\n"
result += "using SDL2;\n"
for other_class in all_classes:
if other_class != class_name:
result += "using static SDL2." + other_class + ";\n"
result += "\nnamespace SDL2\n{\npublic static class "
result += class_name
result += "\n{\n"
result += extract_defines(contents)
result += extract_enums(contents)
result += extract_structs(contents)
result += extract_functions(contents)
result += "}\n}\n"
return result
# ------------------------------------------------------------------------------
all_classes = list(map(lambda h_p: h_p[0][:-2], headers))
os.makedirs(out_folder, exist_ok=True)
for (header, path) in headers:
header_file = open(path, mode='r')
contents = header_file.read()
header_file.close()
source_file = open(os.path.join(out_folder, header[:-2] + ".cs"), mode="w")
source_file.write(build_source(header[:-2], contents, all_classes))
source_file.close()