LEFT | RIGHT |
1 #!/usr/bin/env python | 1 #!/usr/bin/env python |
2 | 2 |
3 import json | 3 import json |
4 import os | 4 import os |
5 import re | 5 import re |
6 import subprocess | 6 import subprocess |
7 import warnings | 7 import warnings |
8 | 8 |
9 EMSCRIPTEN_PATH = '../emscripten' | 9 EMSCRIPTEN_PATH = '../emscripten' |
10 SOURCE_DIR = './compiled' | 10 SOURCE_DIR = './compiled' |
11 SOURCE_FILES = [ | 11 SOURCE_FILES = [ |
12 os.path.join(SOURCE_DIR, f) | 12 os.path.join(SOURCE_DIR, f) |
13 for f in os.listdir(SOURCE_DIR) | 13 for f in os.listdir(SOURCE_DIR) |
14 if f.endswith('.cpp') | 14 if f.endswith('.cpp') |
15 ] | 15 ] |
16 API_FILE = os.path.join(SOURCE_DIR, 'api.cpp') | 16 BINDINGS_FILE = os.path.join(SOURCE_DIR, 'bindings.cpp') |
17 API_OUTPUT = os.path.join(SOURCE_DIR, 'api.js') | 17 BINDINGS_GENERATOR = os.path.join(SOURCE_DIR, 'bindings.cpp.js') |
| 18 BINDINGS_OUTPUT = os.path.join(SOURCE_DIR, 'bindings.js') |
18 COMPILER_OUTPUT = './lib/compiled.js' | 19 COMPILER_OUTPUT = './lib/compiled.js' |
19 GENERATION_PARAMS = { | 20 GENERATION_PARAMS = { |
20 'SHELL_FILE': "'%s'" % os.path.abspath(os.path.join(SOURCE_DIR, 'shell.js')), | 21 'SHELL_FILE': "'%s'" % os.path.abspath(os.path.join(SOURCE_DIR, 'shell.js')), |
| 22 'ASM_JS': 2, # "almost asm" |
21 'TOTAL_MEMORY': 16*1024*1024, | 23 'TOTAL_MEMORY': 16*1024*1024, |
22 'TOTAL_STACK': 1*1024*1024, | 24 'TOTAL_STACK': 1*1024*1024, |
23 'ALLOW_MEMORY_GROWTH': 1, | 25 'ALLOW_MEMORY_GROWTH': 1, |
24 'NO_EXIT_RUNTIME': 1, | 26 'NO_EXIT_RUNTIME': 1, |
25 'DISABLE_EXCEPTION_CATCHING': 0, | |
26 'NO_DYNAMIC_EXECUTION': 1, | 27 'NO_DYNAMIC_EXECUTION': 1, |
27 'NO_BROWSER': 1, | 28 'NO_BROWSER': 1, |
28 'NO_FILESYSTEM': 1, | 29 'NO_FILESYSTEM': 1, |
29 'INVOKE_RUN': 0, | 30 'INVOKE_RUN': 0, |
30 'NODE_STDOUT_FLUSH_WORKAROUND': 0, | 31 'NODE_STDOUT_FLUSH_WORKAROUND': 0, |
31 } | 32 } |
32 DEFINES = ['DEBUG'] | 33 DEFINES = [] |
33 ADDITIONAL_PARAMS = ['-O3', '-m32', '-std=gnu++11', '--memory-init-file', '0', | 34 ADDITIONAL_PARAMS = ['-O3', '-m32', '-std=gnu++14', '--memory-init-file', '0', |
34 '--emit-symbol-map'] | 35 '--emit-symbol-map'] |
35 | 36 |
36 def getenv(): | 37 def getenv(): |
37 path = [] | 38 path = [] |
38 env = {} | 39 env = {} |
39 output = subprocess.check_output([ | 40 output = subprocess.check_output([ |
40 '/bin/sh', '-c', os.path.join(EMSCRIPTEN_PATH, 'emsdk_env.sh')]) | 41 '/bin/bash', '-c', os.path.join(EMSCRIPTEN_PATH, 'emsdk_env.sh')]) |
41 for line in output.splitlines(): | 42 for line in output.splitlines(): |
42 match = re.search(r'^\s*PATH\s*\+=\s*(.*)', line) | 43 match = re.search(r'^\s*PATH\s*\+=\s*(.*)', line) |
43 if match: | 44 if match: |
44 path.append(match.group(1)) | 45 path.append(match.group(1)) |
45 match = re.search(r'^\s*(\w+)\s*=\s*(.*)', line) | 46 match = re.search(r'^\s*(\w+)\s*=\s*(.*)', line) |
46 if match: | 47 if match: |
47 env[match.group(1)] = match.group(2) | 48 env[match.group(1)] = match.group(2) |
48 env['PATH'] = ':'.join([os.environ['PATH']] + path) | 49 env['PATH'] = os.pathsep.join([os.environ['PATH']] + path) |
49 return env | 50 return env |
50 | 51 |
51 def generate_api(env): | 52 def generate_bindings(env): |
52 params = [os.path.join(env['EMSCRIPTEN'], 'emcc'), '-E', API_FILE] | 53 params = [os.path.join(env['EMSCRIPTEN'], 'emcc'), BINDINGS_FILE, |
53 params.extend(ADDITIONAL_PARAMS) | 54 '-o', BINDINGS_GENERATOR, '-std=gnu++14', '-DPRINT_BINDINGS', |
54 output = subprocess.check_output(params, env=env) | 55 '-s', 'WARN_ON_UNDEFINED_SYMBOLS=0', |
| 56 ] |
| 57 subprocess.check_call(params, env=env) |
55 | 58 |
56 differentiators = {} | 59 node = subprocess.check_output('which node', env=env, shell=True).strip(); |
57 differentiator = None | 60 with open(BINDINGS_OUTPUT, 'w') as file: |
58 | 61 subprocess.check_call([node, BINDINGS_GENERATOR], env=env, stdout=file) |
59 cls = None | |
60 method = None | |
61 | |
62 def wrap_call(func, is_instance, result_type, string_args): | |
63 prefix = '''\ | |
64 function() | |
65 { | |
66 var params = Array.prototype.slice.apply(arguments); | |
67 ''' | |
68 suffix = '''\ | |
69 return result; | |
70 }''' | |
71 | |
72 if result_type != 'primitive' or len(string_args): | |
73 prefix += ' var sp = Runtime.stackSave();\n' | |
74 suffix = ' Runtime.stackRestore(sp);\n' + suffix | |
75 | |
76 for pos in string_args: | |
77 prefix += ' params[%i] = createString(params[%i]);\n' % (pos, pos) | |
78 | |
79 if is_instance: | |
80 prefix += ' params.unshift(this._pointer);\n' | |
81 | |
82 if result_type == 'primitive': | |
83 prefix += ' var result = _%s.apply(null, params);\n' % func | |
84 elif result_type == 'string': | |
85 prefix += ' params.unshift(createString());\n' | |
86 prefix += ' _%s.apply(null, params);\n' % func | |
87 prefix += ' var result = getStringData(params[0]);\n' | |
88 else: | |
89 prefix += ' params.unshift(_CreatePointer());\n' | |
90 prefix += ' _%s.apply(null, params);\n' % func | |
91 if result_type in differentiators: | |
92 prefix += ' var type = _%s(params[0]);\n' % differentiator['func'] | |
93 prefix += ' if (type in %s_mapping)\n' % result_type | |
94 prefix += ' var result = new (exports[%s_mapping[type]])(params[0]);\
n' % result_type | |
95 prefix += ' else\n' | |
96 prefix += ' throw new Error("Unexpected %s type: " + type);\n' % resu
lt_type | |
97 else: | |
98 prefix += ' var result = %s(params[0]);\n' % result_type | |
99 | |
100 return prefix + suffix | |
101 | |
102 def property_descriptor(property): | |
103 if property['type'] == 'static': | |
104 return 'value: %s' % property['getter'] | |
105 | |
106 result = 'get: %s' % wrap_call(property['getter'], True, property['type'], [
]) | |
107 if property['setter'] is not None: | |
108 string_args = [0] if property['type'] == 'string' else [] | |
109 result += ', set: %s' % wrap_call(property['setter'], True, 'primitive', s
tring_args) | |
110 return result | |
111 | |
112 def method_descriptor(method): | |
113 return wrap_call(method['func'], method['type'] == 'instance', | |
114 method['result'], method['string_args']) | |
115 | |
116 def write_class(file, cls): | |
117 name = cls['name'] | |
118 if name in differentiators: | |
119 print >>file, 'var %s_mapping = %s;' % ( | |
120 name, json.dumps(differentiators[name]['mapping'], sort_keys=True)) | |
121 | |
122 print >>file, 'exports.%s = createClass(%s);' % ( | |
123 name, 'exports.' + cls['superclass'] if cls['superclass'] else '') | |
124 for property in cls['properties']: | |
125 print >>file, 'Object.defineProperty(exports.%s.prototype, "%s", {%s});' %
( | |
126 name, property['name'], property_descriptor(property)) | |
127 for method in cls['methods']: | |
128 obj = ('exports.%s' if method['type'] == 'class' else 'exports.%s.prototyp
e') % name | |
129 print >>file, '%s.%s = %s;' % ( | |
130 obj, method['name'], method_descriptor(method)) | |
131 for initializer in cls['class_initializers']: | |
132 print >>file, '_%s();' % initializer | |
133 | |
134 def handle_class(name): | |
135 if cls is not None: | |
136 write_class(file, cls) | |
137 differentiator = None | |
138 return { | |
139 'name': command[1], | |
140 'superclass': None, | |
141 'properties': [], | |
142 'methods': [], | |
143 'class_initializers': [], | |
144 } | |
145 | |
146 def handle_superclass(name): | |
147 if cls is None: | |
148 warnings.warn('Superclass declared outside a class: ' + name) | |
149 return | |
150 differentiator = None | |
151 cls['superclass'] = name | |
152 | |
153 def handle_class_init(func): | |
154 if cls is None: | |
155 warnings.warn('Class initializer declared outside a class: ' + func) | |
156 return | |
157 differentiator = None | |
158 method = None | |
159 cls['class_initializers'].append(func) | |
160 | |
161 def handle_differentiator(cls, func): | |
162 differentiator = {'func': func, 'mapping': {}} | |
163 differentiators[cls] = differentiator | |
164 return differentiator | |
165 | |
166 def handle_differentiator_mapping(value, subclass): | |
167 if differentiator is None: | |
168 warnings.warn('Differentiator mapping declared without a differentiator: '
+ subclass) | |
169 return | |
170 differentiator['mapping'][value] = subclass | |
171 | |
172 def handle_property(type, name, getter, setter): | |
173 if cls is None: | |
174 warnings.warn('Property declared outside a class: ' + name) | |
175 return | |
176 method = None | |
177 differentiator = None | |
178 cls['properties'].append({ | |
179 'type': type, | |
180 'name': name, | |
181 'getter': getter, | |
182 'setter': setter, | |
183 }) | |
184 | |
185 def handle_method(type, name, func): | |
186 if cls is None: | |
187 warnings.warn('Method declared outside a class: ' + name) | |
188 return | |
189 differentiator = None | |
190 method = { | |
191 'type': type, | |
192 'name': name, | |
193 'func': func, | |
194 'result': 'primitive', | |
195 'string_args': [], | |
196 } | |
197 cls['methods'].append(method) | |
198 return method | |
199 | |
200 def handle_method_result(type): | |
201 if method is None: | |
202 warnings.warn('Method result declared without a method definition') | |
203 return | |
204 method['result'] = type | |
205 | |
206 def handle_string_arg(pos): | |
207 if method is None: | |
208 warnings.warn('Argument type declared without a method definition') | |
209 return | |
210 method['string_args'].append(int(pos)) | |
211 | |
212 with open(API_OUTPUT, 'w') as file: | |
213 for line in output.splitlines(): | |
214 match = re.search(r'#pragma\s+comment\((.+?)\)', line) | |
215 if match: | |
216 command = match.group(1).strip().split() | |
217 if command[0] == 'class': | |
218 cls = handle_class(command[1]) | |
219 elif command[0] == 'augments': | |
220 handle_superclass(command[1]) | |
221 elif command[0] == 'class_init': | |
222 handle_class_init(command[1]) | |
223 elif command[0] == 'differentiator': | |
224 differentiator = handle_differentiator(command[1], command[2]) | |
225 elif command[0] == 'differentiator_mapping': | |
226 handle_differentiator_mapping(command[1], command[2]) | |
227 elif command[0] == 'property': | |
228 handle_property('primitive', command[1], command[2], command[3] if len
(command) > 3 else None) | |
229 elif command[0] == 'string_property': | |
230 handle_property('string', command[1], command[2], command[3] if len(co
mmand) > 3 else None) | |
231 elif command[0] == 'static_property': | |
232 handle_property('static', command[1], command[2], None) | |
233 elif command[0] == 'method': | |
234 method = handle_method('instance', command[1], command[2]) | |
235 elif command[0] == 'class_method': | |
236 method = handle_method('class', command[1], command[2]) | |
237 elif command[0] == 'string_result': | |
238 handle_method_result('string') | |
239 elif command[0] == 'pointer_result': | |
240 handle_method_result(command[1]) | |
241 elif command[0] == 'string_arg': | |
242 handle_string_arg(command[1]) | |
243 else: | |
244 warnings.warn('Unknown declaration: ' + str(command)) | |
245 | |
246 if cls is not None: | |
247 write_class(file, cls) | |
248 | 62 |
249 def run_compiler(env): | 63 def run_compiler(env): |
250 params = [ | 64 params = [ |
251 os.path.join(env['EMSCRIPTEN'], 'emcc'), | 65 os.path.join(env['EMSCRIPTEN'], 'emcc'), |
252 '-o', COMPILER_OUTPUT, | 66 '-o', COMPILER_OUTPUT, |
253 '--post-js', API_OUTPUT, | 67 '--post-js', BINDINGS_OUTPUT, |
254 ] | 68 ] |
255 params.extend(SOURCE_FILES) | 69 params.extend(SOURCE_FILES) |
256 params.extend('-D' + flag for flag in DEFINES) | 70 params.extend('-D' + flag for flag in DEFINES) |
257 for key, value in GENERATION_PARAMS.iteritems(): | 71 for key, value in GENERATION_PARAMS.iteritems(): |
258 params.extend(['-s', '%s=%s' % (key, str(value))]) | 72 params.extend(['-s', '%s=%s' % (key, str(value))]) |
259 params.extend(ADDITIONAL_PARAMS) | 73 params.extend(ADDITIONAL_PARAMS) |
260 subprocess.check_call(params, env=env) | 74 subprocess.check_call(params, env=env) |
261 | 75 |
262 if __name__ == '__main__': | 76 if __name__ == '__main__': |
263 env = getenv() | 77 env = getenv() |
264 generate_api(env) | 78 generate_bindings(env) |
265 run_compiler(env) | 79 run_compiler(env) |
LEFT | RIGHT |