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
|
#!/usr/bin/env python
'''
Use CppHeaderParser to parse some C++ headers, and generate binding code for them.
Usage:
bindings_generator.py BASENAME HEADER1 HEADER2 ... [-- "LAMBDA"]
BASENAME is the name used for output files (with added suffixes).
HEADER1 etc. are the C++ headers to parse
We generate the following:
* BASENAME.c: C bindings file, with generated C wrapper functions. You will
need to build this with your project, and make sure it compiles
properly by adding the proper #includes etc. You can also just
#include this file itself in one of your existing project files.
* BASENAME.js: JavaScript bindings file, with generated JavaScript wrapper
objects. This is a high-level wrapping, using native JS classes.
* LAMBDA: Optionally, provide the text of a lambda function here that will be
used to process the header files. This lets you manually tweak them.
The C bindings file is basically a tiny C wrapper around the C++ code.
It's only purpose is to make it easy to access the C++ code in the JS
bindings, and to prevent DFE from removing the code we care about. The
JS bindings do more serious work, creating class structures in JS and
linking them to the C bindings.
'''
import os, sys, glob, re
abspath = os.path.abspath(os.path.dirname(__file__))
def path_from_root(*pathelems):
return os.path.join(os.path.sep, *(abspath.split(os.sep)[:-1] + list(pathelems)))
exec(open(path_from_root('tools', 'shared.py'), 'r').read())
# Find ply and CppHeaderParser
sys.path = [path_from_root('third_party', 'ply'), path_from_root('third_party', 'CppHeaderParser')] + sys.path
import CppHeaderParser
#print glob.glob(path_from_root('tests', 'bullet', 'src', 'BulletCollision', 'CollisionDispatch', '*.h'))
basename = sys.argv[1]
processor = lambda line: line
if '--' in sys.argv:
index = sys.argv.index('--')
processor = eval(sys.argv[index+1])
sys.argv = sys.argv[:index]
# First pass - read everything
classes = {}
struct_parents = {}
all_h_name = basename + '.all.h'
all_h = open(all_h_name, 'w')
for header in sys.argv[2:]:
all_h.write('//// ' + header + '\n')
all_h.write(processor(open(header, 'r').read()))
all_h.close()
parsed = CppHeaderParser.CppHeader(all_h_name)
for cname, clazz in parsed.classes.iteritems():
#print 'zz see', cname
if len(clazz['methods']['public']) > 0: # Do not notice stub classes
#print 'zz for real', cname, clazz._public_structs
classes[cname] = clazz
for sname, struct in clazz._public_structs.iteritems():
struct_parents[sname] = cname
#print 'zz seen struct %s in %s' % (sname, cname)
# Second pass - generate bindings
# TODO: Bind virtual functions using dynamic binding in the C binding code
funcs = {} # name -> # of copies in the original, and originalname in a copy
gen_c = open(basename + '.c', 'w')
gen_js = open(basename + '.js', 'w')
gen_c.write('extern "C" {\n')
def generate_class(generating_cname, cname, clazz):
inherited = generating_cname != cname
for method in clazz['methods']['public']:
if method['pure_virtual']: return # Nothing to generate for pure virtual classes
for method in clazz['methods']['public']:
mname = method['name']
args = method['parameters']
constructor = mname == cname
destructor = method['destructor']
if destructor: continue
if constructor and inherited: continue
if method['pure_virtual']: continue
skip = False
for i in range(len(args)):
#print 'zz arggggggg', cname, 'x', mname, 'x', args[i]['name'], 'x', args[i]['type'], 'x'
if args[i]['name'].replace(' ', '') == '':
args[i]['name'] = 'arg' + str(i+1)
elif args[i]['name'] == '&':
args[i]['name'] = 'arg' + str(i+1)
args[i]['type'] += '&'
if '>' in args[i]['name']:
print 'WARNING: odd ">" in %s, skipping' % cname
skip = True
break
#print 'c1', struct_parents.keys()
if args[i]['type'][-1] == '&':
sname = args[i]['type'][:-1]
if sname[-1] == ' ': sname = sname[:-1]
if sname in struct_parents:
args[i]['type'] = struct_parents[sname] + '::' + sname + '&'
elif sname.replace('const ', '') in struct_parents:
sname = sname.replace('const ', '')
args[i]['type'] = 'const ' + struct_parents[sname] + '::' + sname + '&'
#print 'POST arggggggg', cname, 'x', mname, 'x', args[i]['name'], 'x', args[i]['type']
if skip:
continue
# C
ret = ((cname + ' *') if constructor else method['rtnType']).replace('virtual ', '')
callprefix = 'new ' if constructor else 'self->'
typedargs = ', '.join( ([] if constructor else [cname + ' * self']) + map(lambda arg: arg['type'] + ' ' + arg['name'], args) )
justargs = ', '.join(map(lambda arg: arg['name'], args))
fullname = 'emscripten_bind_' + generating_cname + '__' + mname
generating_cname_suffixed = generating_cname
mname_suffixed = mname
count = funcs.setdefault(fullname, 0)
funcs[fullname] += 1
# handle overloading
if count > 0:
suffix = '_' + str(count+1)
funcs[fullname + suffix] = fullname # this should never change
fullname += suffix
mname_suffixed += suffix
if constructor:
generating_cname_suffixed += suffix
actualmname = ''
if mname == '__operator___assignment_':
callprefix = '*self = '
continue # TODO
elif mname == '__operator____imult__':
callprefix = '*self * '
continue # TODO
elif mname == '__operator____iadd__':
callprefix = '*self + '
continue # TODO
elif mname == '__operator____isub__':
callprefix = '*self - '
continue # TODO
else:
actualmname = mname
gen_c.write('''
%s %s(%s) {
%s%s%s(%s);
}
''' % (ret, fullname, typedargs, 'return ' if ret.replace(' ', '') != 'void' else '', callprefix, actualmname, justargs))
# JS
if constructor:
dupe = type(funcs[fullname]) is str
if not dupe:
gen_js.write('''
function %s(%s) {
this.ptr = _%s(%s);
}
''' % (generating_cname_suffixed, justargs, fullname, justargs))
else:
gen_js.write('''
function %s(%s) {
this.ptr = _%s(%s);
}
%s.prototype = %s.prototype;
''' % (generating_cname_suffixed, justargs, fullname, justargs, generating_cname_suffixed, cname))
else:
gen_js.write('''
%s.prototype.%s = function(%s) {
%s_%s(this.ptr%s);
}
''' % (generating_cname, mname_suffixed, justargs, 'return ' if ret != 'void' else '', fullname, (', ' if len(justargs) > 0 else '') + justargs))
for cname, clazz in classes.iteritems():
generate_class(cname, cname, clazz)
# In addition, generate all methods of parent classes. We do not inherit in JS (how would we do multiple inheritance etc.?)
for parent in clazz['inherits']:
generate_class(cname, parent['class'], classes[parent['class']])
# TODO: Add a destructor
# Finish up
funcs = funcs.keys()
gen_c.write('''
}
#include <stdio.h>
struct EmscriptenEnsurer
{
EmscriptenEnsurer() {
// Actually use the binding functions, so DFE will not eliminate them
int sum = 0;
void *seen = (void*)%s;
''' % funcs[0])
for func in funcs[1:]:
gen_c.write(''' sum += (void*)%s == seen;
''' % func)
gen_c.write(''' printf("(%d)\\n", sum);
}
};
EmscriptenEnsurer emscriptenEnsurer;
''')
gen_c.close()
gen_js.close()
|