-
Notifications
You must be signed in to change notification settings - Fork 1
/
generate.py
executable file
·203 lines (183 loc) · 6.87 KB
/
generate.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
#!/usr/bin/env python3
from argparse import ArgumentParser
import json
import re
RE_TYPE_ARR = re.compile(r"(.*)\[(\d+)\]")
RE_TYPE_PTR = re.compile(r"(.*)\*")
RE_TYPE_UXX = re.compile(r"unsigned (.+)")
RE_DEFINE_COLOR = re.compile(r"CLITERAL\(Color\){ (\d+), (\d+), (\d+), (\d+) }")
def identifier(s):
# Set of Sunder keywords to be substituted. Update as necessary.
KEYWORDS = {"type"}
# Substitute `<identifier>` for `<identifier>_` if the identifier would be
# a reserved keyword.
return f"{s}_" if s in KEYWORDS else s
def generate_type(s):
s = s.replace("const ", "").strip()
match = RE_TYPE_ARR.match(s)
if match:
return f"[{match[2]}]{generate_type(match[1])}"
match = RE_TYPE_PTR.match(s)
if match:
return f"*{generate_type(match[1])}" if match[1].strip() != "void" else "*any"
match = RE_TYPE_UXX.match(s)
if match:
return f"u{match[1]}"
if s == "int":
return "sint"
if s == "short":
return "sshort"
if s == "long":
return "slong"
if s == "long long":
return "slonglong"
return s.strip()
def generate_version(j):
name = j["name"]
type = j["type"]
value = j["value"]
if name != "RAYLIB_VERSION":
return None
return f"let {name} = \"{value}\";"
def generate_color(j):
name = j["name"]
type = j["type"]
value = j["value"]
desc = j["description"]
if type != "COLOR":
return None
match = RE_DEFINE_COLOR.match(value)
return f"let {name} = (:Color){{.r={match[1]}, .g={match[2]}, .b={match[3]}, .a={match[4]}}}; # {desc}"
return None
def generate_alias(j):
name = j["name"]
type = generate_type(j["type"])
desc = j["description"]
return f"type {name} = {type}; # {desc}"
def generate_callback(j):
is_variadic = False
name = j["name"]
desc = j["description"]
func_params = list()
for param in j["params"]:
if param["type"] == "..." or param["type"] == "va_list":
is_variadic = True
param_type = generate_type(param["type"])
func_params.append(param_type)
func_return = generate_type(j["returnType"])
if is_variadic:
return "\n".join([
f"# [SKIPPED] {name}: Callback of type `func({', '.join(func_params)}) {func_return}` is variadic.",
f"type {name} = *any; # {desc}"
])
if len(desc) == 0:
return f"type {name} = func({', '.join(func_params)}) {func_return};"
return f"type {name} = func({', '.join(func_params)}) {func_return}; # {desc}"
def generate_enum(j):
lines = list()
name = j["name"]
desc = j["description"]
# Although Sunder supports enums, raylib funtions taking enum arguments use
# int or unsigned int for the corresponding function parameter type and/or
# struct member type. Enums are generated as either sint or uint values in
# order to avoid a requiring cast on an enum value every use.
USE_UINT = {
# SetConfigFlags takes `unsigned int` for its `flags` parameter.
"ConfigFlags",
}
type = "uint" if name in USE_UINT else "sint"
if desc:
lines.append(f"# {desc}")
lines.append(f"type {name} = {type}; # (enum) {desc}")
for value in j["values"]:
value_name = value["name"]
value_value = value["value"]
value_desc = value["description"]
lines.append(f"let {value_name}: {name} = {value_value}; # {value_desc}")
return "\n".join(lines)
def generate_struct(j):
lines = list()
name = j["name"]
desc = j["description"]
if desc:
lines.append(f"# {desc}")
lines.append(f"struct {name} {{")
for field in j["fields"]:
field_name = field["name"]
field_type = generate_type(field["type"])
field_desc = field["description"]
field_comment = f" # {field_desc}" if field_desc else ""
lines.append(f" var {identifier(field_name)}: {field_type};{field_comment}")
lines.append(f"}}")
return "\n".join(lines)
def generate_function(j):
is_variadic = False
name = j["name"]
desc = j["description"]
func_params = list()
if "params" in j:
for param in j["params"]:
if param["type"] == "..." or param["type"] == "va_list":
is_variadic = True
param_name = identifier(param["name"])
param_type = generate_type(param["type"])
func_params.append(f"{param_name}: {param_type}")
func_return = generate_type(j["returnType"])
comment = f" # {desc}" if desc else ""
if is_variadic:
return "\n".join([
f"# [SKIPPED] {name}: Function of type `func({', '.join(func_params)}) {func_return}` is variadic.",
f"type {name} = *any;{comment}"
])
return f"extern func {name}({', '.join(func_params)}) {func_return};{comment}"
def main(args):
with open(args.json) as f:
api = json.loads(f.read())
# raylib.h
if args.kind == "raylib":
version = list(filter(lambda x: x is not None, map(generate_version, api["defines"])))
colors = list(filter(lambda x: x is not None, map(generate_color, api["defines"])))
aliases = list(map(generate_alias, api["aliases"]))
# XXX: Opaque types discovered by a Sunder parse error.
opaque = [
"extern type rAudioBuffer; # opaque struct",
"extern type rAudioProcessor; # opaque struct",
]
callbacks = list(map(generate_callback, api["callbacks"]))
enums = list(map(generate_enum, api["enums"]))
structs = list(map(generate_struct, api["structs"]))
functions = list(map(generate_function, api["functions"]))
print("\n\n".join([
"import \"c\";",
"\n".join(version),
"\n".join(colors),
"\n".join(aliases),
"\n".join(opaque),
"\n".join(callbacks),
"\n\n".join(enums),
"\n\n".join(structs),
"\n".join(functions),
]))
return
# raymath.h
if args.kind == "raymath":
# Skip generating struct declarations, since structs with the same name
# and layout are declared in raylib.sunder. The exceptions to struct
# generation are the float3 and float16 types unique to raymath.h.
structs = [
generate_struct(j) for j in api["structs"]
if j["name"] == "float3" or j["name"] == "float16"
]
functions = list(map(generate_function, api["functions"]))
print("\n\n".join([
"import \"c\";" + "\n" + "import \"raylib.sunder\";",
"\n\n".join(structs),
"\n".join(functions),
]))
return
raise Exception(f"unknown binding generation kind `{args.kind}`")
if __name__ == "__main__":
parser = ArgumentParser(description="Generate bindings from the raylib API JSON")
parser.add_argument("kind")
parser.add_argument("json")
main(parser.parse_args())