Rietveld Code Review Tool
Help | Bug tracker | Discussion group | Source code

Side by Side Diff: compile

Issue 29333474: Issue 4125 - [emscripten] Convert filter classes to C++ (Closed)
Patch Set: Improved performance Created Jan. 28, 2016, 2:31 p.m.
Left:
Right:
Use n/p to move between diff chunks; N/P to move between comments.
Jump to:
View unified diff | Download patch
« no previous file with comments | « .hgignore ('k') | compiled/ActiveFilter.h » ('j') | no next file with comments »
Toggle Intra-line Diffs ('i') | Expand Comments ('e') | Collapse Comments ('c') | Show Comments Hide Comments ('s')
OLDNEW
(Empty)
1 #!/usr/bin/env python
2
3 import json
4 import os
5 import re
6 import subprocess
7 import warnings
8
9 EMSCRIPTEN_PATH = '../emscripten'
10 SOURCE_DIR = './compiled'
11 SOURCE_FILES = [
12 os.path.join(SOURCE_DIR, f)
13 for f in os.listdir(SOURCE_DIR)
14 if f.endswith('.cpp')
15 ]
16 API_FILE = os.path.join(SOURCE_DIR, 'api.cpp')
17 API_OUTPUT = os.path.join(SOURCE_DIR, 'api.js')
18 COMPILER_OUTPUT = './lib/compiled.js'
19 GENERATION_PARAMS = {
20 'SHELL_FILE': "'%s'" % os.path.abspath(os.path.join(SOURCE_DIR, 'shell.js')),
21 'TOTAL_MEMORY': 16*1024*1024,
22 'TOTAL_STACK': 1*1024*1024,
23 'ALLOW_MEMORY_GROWTH': 1,
24 'NO_EXIT_RUNTIME': 1,
25 'DISABLE_EXCEPTION_CATCHING': 0,
26 'NO_DYNAMIC_EXECUTION': 1,
27 'NO_BROWSER': 1,
28 'NO_FILESYSTEM': 1,
29 'INVOKE_RUN': 0,
30 'NODE_STDOUT_FLUSH_WORKAROUND': 0,
31 }
32 DEFINES = ['DEBUG']
33 ADDITIONAL_PARAMS = ['-O3', '-m32', '-std=gnu++11', '--memory-init-file', '0',
34 '--emit-symbol-map']
35
36 def getenv():
37 path = []
38 env = {}
39 output = subprocess.check_output([
40 '/bin/sh', '-c', os.path.join(EMSCRIPTEN_PATH, 'emsdk_env.sh')])
41 for line in output.splitlines():
42 match = re.search(r'^\s*PATH\s*\+=\s*(.*)', line)
43 if match:
44 path.append(match.group(1))
45 match = re.search(r'^\s*(\w+)\s*=\s*(.*)', line)
46 if match:
47 env[match.group(1)] = match.group(2)
48 env['PATH'] = ':'.join([os.environ['PATH']] + path)
49 return env
50
51 def generate_api(env):
52 params = [os.path.join(env['EMSCRIPTEN'], 'emcc'), '-E', API_FILE]
53 params.extend(ADDITIONAL_PARAMS)
54 output = subprocess.check_output(params, env=env)
55
56 differentiators = {}
57 differentiator = None
58
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
249 def run_compiler(env):
250 params = [
251 os.path.join(env['EMSCRIPTEN'], 'emcc'),
252 '-o', COMPILER_OUTPUT,
253 '--post-js', API_OUTPUT,
254 ]
255 params.extend(SOURCE_FILES)
256 params.extend('-D' + flag for flag in DEFINES)
257 for key, value in GENERATION_PARAMS.iteritems():
258 params.extend(['-s', '%s=%s' % (key, str(value))])
259 params.extend(ADDITIONAL_PARAMS)
260 subprocess.check_call(params, env=env)
261
262 if __name__ == '__main__':
263 env = getenv()
264 generate_api(env)
265 run_compiler(env)
OLDNEW
« no previous file with comments | « .hgignore ('k') | compiled/ActiveFilter.h » ('j') | no next file with comments »

Powered by Google App Engine
This is Rietveld