Chromium Code Reviews
chromiumcodereview-hr@appspot.gserviceaccount.com (chromiumcodereview-hr) | Please choose your nickname with Settings | Help | Chromium Project | Gerrit Changes | Sign out
(258)

Side by Side Diff: sky/engine/bindings/scripts/code_generator_v8.py

Issue 922053002: Remove unused V8 integration code in Sky (Closed) Base URL: git@github.com:domokit/mojo.git@master
Patch Set: Created 5 years, 10 months ago
Use n/p to move between diff chunks; N/P to move between comments. Draft comments are only viewable by you.
Jump to:
View unified diff | Download patch
OLDNEW
(Empty)
1 # Copyright (C) 2013 Google Inc. All rights reserved.
2 #
3 # Redistribution and use in source and binary forms, with or without
4 # modification, are permitted provided that the following conditions are
5 # met:
6 #
7 # * Redistributions of source code must retain the above copyright
8 # notice, this list of conditions and the following disclaimer.
9 # * Redistributions in binary form must reproduce the above
10 # copyright notice, this list of conditions and the following disclaimer
11 # in the documentation and/or other materials provided with the
12 # distribution.
13 # * Neither the name of Google Inc. nor the names of its
14 # contributors may be used to endorse or promote products derived from
15 # this software without specific prior written permission.
16 #
17 # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
18 # "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
19 # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
20 # A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
21 # OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
22 # SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
23 # LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
24 # DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
25 # THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
26 # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
27 # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
28
29 """Generate Blink V8 bindings (.h and .cpp files).
30
31 If run itself, caches Jinja templates (and creates dummy file for build,
32 since cache filenames are unpredictable and opaque).
33
34 This module is *not* concurrency-safe without care: bytecode caching creates
35 a race condition on cache *write* (crashes if one process tries to read a
36 partially-written cache). However, if you pre-cache the templates (by running
37 the module itself), then you can parallelize compiling individual files, since
38 cache *reading* is safe.
39
40 Input: An object of class IdlDefinitions, containing an IDL interface X
41 Output: V8X.h and V8X.cpp
42
43 Design doc: http://www.chromium.org/developers/design-documents/idl-compiler
44 """
45
46 import os
47 import posixpath
48 import re
49 import sys
50
51 # Path handling for libraries and templates
52 # Paths have to be normalized because Jinja uses the exact template path to
53 # determine the hash used in the cache filename, and we need a pre-caching step
54 # to be concurrency-safe. Use absolute path because __file__ is absolute if
55 # module is imported, and relative if executed directly.
56 # If paths differ between pre-caching and individual file compilation, the cache
57 # is regenerated, which causes a race condition and breaks concurrent build,
58 # since some compile processes will try to read the partially written cache.
59 module_path, module_filename = os.path.split(os.path.realpath(__file__))
60 third_party_dir = os.path.normpath(os.path.join(
61 module_path, os.pardir, os.pardir, os.pardir, os.pardir, 'third_party'))
62 templates_dir = os.path.normpath(os.path.join(
63 module_path, os.pardir, 'templates'))
64 # Make sure extension is .py, not .pyc or .pyo, so doesn't depend on caching
65 module_pyname = os.path.splitext(module_filename)[0] + '.py'
66
67 # jinja2 is in chromium's third_party directory.
68 # Insert at 1 so at front to override system libraries, and
69 # after path[0] == invoking script dir
70 sys.path.insert(1, third_party_dir)
71 import jinja2
72
73 import idl_types
74 from idl_types import IdlType
75 import v8_callback_interface
76 import v8_dictionary
77 from v8_globals import includes, interfaces
78 import v8_interface
79 import v8_types
80 from v8_utilities import capitalize, cpp_name, conditional_string, v8_class_name
81
82
83 KNOWN_COMPONENTS = frozenset(['core', 'modules'])
84
85
86 def render_template(interface_info, header_template, cpp_template,
87 template_context):
88 template_context['code_generator'] = module_pyname
89
90 # Add includes for any dependencies
91 template_context['header_includes'] = sorted(
92 template_context['header_includes'])
93 includes.update(interface_info.get('dependencies_include_paths', []))
94 template_context['cpp_includes'] = sorted(includes)
95
96 header_text = header_template.render(template_context)
97 cpp_text = cpp_template.render(template_context)
98 return header_text, cpp_text
99
100
101 class CodeGeneratorBase(object):
102 """Base class for v8 bindings generator and IDL dictionary impl generator"""
103
104 def __init__(self, interfaces_info, cache_dir, output_dir):
105 interfaces_info = interfaces_info or {}
106 self.interfaces_info = interfaces_info
107 self.jinja_env = initialize_jinja_env(cache_dir)
108 self.output_dir = output_dir
109
110 # Set global type info
111 idl_types.set_ancestors(dict(
112 (interface_name, interface_info['ancestors'])
113 for interface_name, interface_info in interfaces_info.iteritems()
114 if interface_info['ancestors']))
115 IdlType.set_callback_interfaces(set(
116 interface_name
117 for interface_name, interface_info in interfaces_info.iteritems()
118 if interface_info['is_callback_interface']))
119 IdlType.set_dictionaries(set(
120 dictionary_name
121 for dictionary_name, interface_info in interfaces_info.iteritems()
122 if interface_info['is_dictionary']))
123 IdlType.set_implemented_as_interfaces(dict(
124 (interface_name, interface_info['implemented_as'])
125 for interface_name, interface_info in interfaces_info.iteritems()
126 if interface_info['implemented_as']))
127 v8_types.set_component_dirs(dict(
128 (interface_name, interface_info['component_dir'])
129 for interface_name, interface_info in interfaces_info.iteritems()))
130
131 def generate_code(self, definitions, definition_name):
132 """Returns .h/.cpp code as ((path, content)...)."""
133 # Set local type info
134 IdlType.set_callback_functions(definitions.callback_functions.keys())
135 IdlType.set_enums((enum.name, enum.values)
136 for enum in definitions.enumerations.values())
137 return self.generate_code_internal(definitions, definition_name)
138
139 def generate_code_internal(self, definitions, definition_name):
140 # This should be implemented in subclasses.
141 raise NotImplementedError()
142
143
144 class CodeGeneratorV8(CodeGeneratorBase):
145 def __init__(self, interfaces_info, cache_dir, output_dir):
146 CodeGeneratorBase.__init__(self, interfaces_info, cache_dir, output_dir)
147
148 def output_paths(self, definition_name):
149 header_path = posixpath.join(self.output_dir,
150 'V8%s.h' % definition_name)
151 cpp_path = posixpath.join(self.output_dir, 'V8%s.cpp' % definition_name)
152 return header_path, cpp_path
153
154 def generate_code_internal(self, definitions, definition_name):
155 if definition_name in definitions.interfaces:
156 return self.generate_interface_code(
157 definitions, definition_name,
158 definitions.interfaces[definition_name])
159 if definition_name in definitions.dictionaries:
160 return self.generate_dictionary_code(
161 definitions, definition_name,
162 definitions.dictionaries[definition_name])
163 raise ValueError('%s is not in IDL definitions' % definition_name)
164
165 def generate_interface_code(self, definitions, interface_name, interface):
166 # Store other interfaces for introspection
167 interfaces.update(definitions.interfaces)
168
169 # Select appropriate Jinja template and contents function
170 if interface.is_callback:
171 header_template_filename = 'callback_interface.h'
172 cpp_template_filename = 'callback_interface.cpp'
173 interface_context = v8_callback_interface.callback_interface_context
174 else:
175 header_template_filename = 'interface.h'
176 cpp_template_filename = 'interface.cpp'
177 interface_context = v8_interface.interface_context
178 header_template = self.jinja_env.get_template(header_template_filename)
179 cpp_template = self.jinja_env.get_template(cpp_template_filename)
180
181 interface_info = self.interfaces_info[interface_name]
182
183 template_context = interface_context(interface)
184 # Add the include for interface itself
185 template_context['header_includes'].add(interface_info['include_path'])
186 header_text, cpp_text = render_template(
187 interface_info, header_template, cpp_template, template_context)
188 header_path, cpp_path = self.output_paths(interface_name)
189 return (
190 (header_path, header_text),
191 (cpp_path, cpp_text),
192 )
193
194 def generate_dictionary_code(self, definitions, dictionary_name,
195 dictionary):
196 header_template = self.jinja_env.get_template('dictionary_v8.h')
197 cpp_template = self.jinja_env.get_template('dictionary_v8.cpp')
198 template_context = v8_dictionary.dictionary_context(dictionary)
199 interface_info = self.interfaces_info[dictionary_name]
200 # Add the include for interface itself
201 template_context['header_includes'].add(interface_info['include_path'])
202 header_text, cpp_text = render_template(
203 interface_info, header_template, cpp_template, template_context)
204 header_path, cpp_path = self.output_paths(dictionary_name)
205 return (
206 (header_path, header_text),
207 (cpp_path, cpp_text),
208 )
209
210
211 class CodeGeneratorDictionaryImpl(CodeGeneratorBase):
212 def __init__(self, interfaces_info, cache_dir, output_dir):
213 CodeGeneratorBase.__init__(self, interfaces_info, cache_dir, output_dir)
214
215 def output_paths(self, definition_name, interface_info):
216 if interface_info['component_dir'] in KNOWN_COMPONENTS:
217 output_dir = posixpath.join(self.output_dir,
218 interface_info['relative_dir'])
219 else:
220 output_dir = self.output_dir
221 header_path = posixpath.join(output_dir, '%s.h' % definition_name)
222 cpp_path = posixpath.join(output_dir, '%s.cpp' % definition_name)
223 return header_path, cpp_path
224
225 def generate_code_internal(self, definitions, definition_name):
226 if not definition_name in definitions.dictionaries:
227 raise ValueError('%s is not an IDL dictionary')
228 dictionary = definitions.dictionaries[definition_name]
229 interface_info = self.interfaces_info[definition_name]
230 header_template = self.jinja_env.get_template('dictionary_impl.h')
231 cpp_template = self.jinja_env.get_template('dictionary_impl.cpp')
232 template_context = v8_dictionary.dictionary_impl_context(
233 dictionary, self.interfaces_info)
234 header_text, cpp_text = render_template(
235 interface_info, header_template, cpp_template, template_context)
236 header_path, cpp_path = self.output_paths(
237 definition_name, interface_info)
238 return (
239 (header_path, header_text),
240 (cpp_path, cpp_text),
241 )
242
243
244 def initialize_jinja_env(cache_dir):
245 jinja_env = jinja2.Environment(
246 loader=jinja2.FileSystemLoader(templates_dir),
247 # Bytecode cache is not concurrency-safe unless pre-cached:
248 # if pre-cached this is read-only, but writing creates a race condition.
249 bytecode_cache=jinja2.FileSystemBytecodeCache(cache_dir),
250 keep_trailing_newline=True, # newline-terminate generated files
251 lstrip_blocks=True, # so can indent control flow tags
252 trim_blocks=True)
253 jinja_env.filters.update({
254 'blink_capitalize': capitalize,
255 'conditional': conditional_if_endif,
256 'exposed': exposed_if,
257 'runtime_enabled': runtime_enabled_if,
258 })
259 return jinja_env
260
261
262 def generate_indented_conditional(code, conditional):
263 # Indent if statement to level of original code
264 indent = re.match(' *', code).group(0)
265 return ('%sif (%s) {\n' % (indent, conditional) +
266 ' %s\n' % '\n '.join(code.splitlines()) +
267 '%s}\n' % indent)
268
269
270 # [Conditional]
271 def conditional_if_endif(code, conditional_string):
272 # Jinja2 filter to generate if/endif directive blocks
273 if not conditional_string:
274 return code
275 return ('#if %s\n' % conditional_string +
276 code +
277 '#endif // %s\n' % conditional_string)
278
279
280 # [Exposed]
281 def exposed_if(code, exposed_test):
282 if not exposed_test:
283 return code
284 return generate_indented_conditional(code, 'context && (%s)' % exposed_test)
285
286
287 # [RuntimeEnabled]
288 def runtime_enabled_if(code, runtime_enabled_function_name):
289 if not runtime_enabled_function_name:
290 return code
291 return generate_indented_conditional(code, '%s()' % runtime_enabled_function _name)
292
293
294 ################################################################################
295
296 def main(argv):
297 # If file itself executed, cache templates
298 try:
299 cache_dir = argv[1]
300 dummy_filename = argv[2]
301 except IndexError as err:
302 print 'Usage: %s CACHE_DIR DUMMY_FILENAME' % argv[0]
303 return 1
304
305 # Cache templates
306 jinja_env = initialize_jinja_env(cache_dir)
307 template_filenames = [filename for filename in os.listdir(templates_dir)
308 # Skip .svn, directories, etc.
309 if filename.endswith(('.cpp', '.h'))]
310 for template_filename in template_filenames:
311 jinja_env.get_template(template_filename)
312
313 # Create a dummy file as output for the build system,
314 # since filenames of individual cache files are unpredictable and opaque
315 # (they are hashes of the template path, which varies based on environment)
316 with open(dummy_filename, 'w') as dummy_file:
317 pass # |open| creates or touches the file
318
319
320 if __name__ == '__main__':
321 sys.exit(main(sys.argv))
OLDNEW
« no previous file with comments | « sky/engine/bindings/scripts/blink_idl_parser.py ('k') | sky/engine/bindings/scripts/compute_global_objects.py » ('j') | no next file with comments »

Powered by Google App Engine
This is Rietveld 408576698