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

Side by Side Diff: sky/engine/bindings-dart/dart/scripts/code_generator_dart.py

Issue 918273002: Remove bindings-dart (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 C++ bindings (.h and .cpp files) for use by Dart:HTML.
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: DartX.h and DartX.cpp
42
43 Design doc: http://www.chromium.org/developers/design-documents/idl-compiler
44 """
45
46 import os
47 import cPickle as pickle
48 import re
49 import sys
50
51
52 # Path handling for libraries and templates
53 # Paths have to be normalized because Jinja uses the exact template path to
54 # determine the hash used in the cache filename, and we need a pre-caching step
55 # to be concurrency-safe. Use absolute path because __file__ is absolute if
56 # module is imported, and relative if executed directly.
57 # If paths differ between pre-caching and individual file compilation, the cache
58 # is regenerated, which causes a race condition and breaks concurrent build,
59 # since some compile processes will try to read the partially written cache.
60 module_path, module_filename = os.path.split(os.path.realpath(__file__))
61 third_party_dir = os.path.normpath(os.path.join(
62 module_path, os.pardir, os.pardir, os.pardir, os.pardir, os.pardir))
63 templates_dir = os.path.normpath(os.path.join(module_path, 'templates'))
64
65 # Make sure extension is .py, not .pyc or .pyo, so doesn't depend on caching
66 module_pyname = os.path.splitext(module_filename)[0] + '.py'
67
68 # jinja2 is in chromium's third_party directory.
69 # Insert at 1 so at front to override system libraries, and
70 # after path[0] == invoking script dir
71 sys.path.insert(1, third_party_dir)
72
73 # Add the base compiler scripts to the path here as in compiler.py
74 dart_script_path = os.path.dirname(os.path.abspath(__file__))
75 script_path = os.path.join(os.path.dirname(os.path.dirname(dart_script_path)),
76 'scripts')
77 sys.path.extend([script_path])
78
79 import jinja2
80
81 import idl_types
82 from idl_types import IdlType
83 import dart_callback_interface
84 import dart_interface
85 import dart_types
86 from dart_utilities import DartUtilities
87 from utilities import write_pickle_file, idl_filename_to_interface_name
88 from v8_globals import includes, interfaces
89
90
91 class CodeGeneratorDart(object):
92 def __init__(self, interfaces_info, cache_dir):
93 interfaces_info = interfaces_info or {}
94 self.interfaces_info = interfaces_info
95 self.jinja_env = initialize_jinja_env(cache_dir)
96
97 # Set global type info
98 idl_types.set_ancestors(dict(
99 (interface_name, interface_info['ancestors'])
100 for interface_name, interface_info in interfaces_info.iteritems()
101 if interface_info['ancestors']))
102 IdlType.set_callback_interfaces(set(
103 interface_name
104 for interface_name, interface_info in interfaces_info.iteritems()
105 if interface_info['is_callback_interface']))
106 IdlType.set_implemented_as_interfaces(dict(
107 (interface_name, interface_info['implemented_as'])
108 for interface_name, interface_info in interfaces_info.iteritems()
109 if interface_info['implemented_as']))
110 IdlType.set_garbage_collected_types(set(
111 interface_name
112 for interface_name, interface_info in interfaces_info.iteritems()
113 if 'GarbageCollected' in interface_info['inherited_extended_attribut es']))
114 IdlType.set_will_be_garbage_collected_types(set(
115 interface_name
116 for interface_name, interface_info in interfaces_info.iteritems()
117 if 'WillBeGarbageCollected' in interface_info['inherited_extended_at tributes']))
118 dart_types.set_component_dirs(dict(
119 (interface_name, interface_info['component_dir'])
120 for interface_name, interface_info in interfaces_info.iteritems()))
121
122 def generate_code(self, definitions, interface_name, idl_pickle_filename,
123 only_if_changed):
124 """Returns .h/.cpp code as (header_text, cpp_text)."""
125 try:
126 interface = definitions.interfaces[interface_name]
127 except KeyError:
128 raise Exception('%s not in IDL definitions' % interface_name)
129
130 # Store other interfaces for introspection
131 interfaces.update(definitions.interfaces)
132
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
138 # Select appropriate Jinja template and contents function
139 if interface.is_callback:
140 header_template_filename = 'callback_interface_h.template'
141 cpp_template_filename = 'callback_interface_cpp.template'
142 generate_contents = dart_callback_interface.generate_callback_interf ace
143 else:
144 header_template_filename = 'interface_h.template'
145 cpp_template_filename = 'interface_cpp.template'
146 generate_contents = dart_interface.interface_context
147 header_template = self.jinja_env.get_template(header_template_filename)
148 cpp_template = self.jinja_env.get_template(cpp_template_filename)
149
150 # Generate contents (input parameters for Jinja)
151 template_contents = generate_contents(interface)
152 template_contents['code_generator'] = module_pyname
153
154 # Add includes for interface itself and any dependencies
155 interface_info = self.interfaces_info[interface_name]
156 template_contents['header_includes'].add(interface_info['include_path'])
157 template_contents['header_includes'] = sorted(template_contents['header_ includes'])
158 includes.update(interface_info.get('dependencies_include_paths', []))
159
160 # Remove includes that are not needed for Dart and trigger fatal
161 # compile warnings if included. These IDL files need to be
162 # imported by Dart to generate the list of events but the
163 # associated header files do not contain any code used by Dart.
164 includes.discard('core/dom/GlobalEventHandlers.h')
165 includes.discard('core/frame/DOMWindowEventHandlers.h')
166
167 # Remove v8 usages not needed.
168 includes.discard('core/frame/UseCounter.h')
169 includes.discard('bindings/core/v8/V8ScriptState.h')
170 includes.discard('bindings/core/v8/V8DOMActivityLogger.h')
171 includes.discard('bindings/core/v8/V8DOMConfiguration.h')
172 includes.discard('bindings/core/v8/V8ExceptionState.h')
173 includes.discard('bindings/core/v8/V8HiddenValue.h')
174 includes.discard('bindings/core/v8/V8ObjectConstructor.h')
175 includes.discard('core/dom/ContextFeatures.h')
176 includes.discard('core/dom/Document.h')
177 includes.discard('platform/RuntimeEnabledFeatures.h')
178 includes.discard('platform/TraceEvent.h')
179
180 template_contents['cpp_includes'] = sorted(includes)
181
182 idl_world = {'interface': None, 'callback': None}
183
184 # Load the pickle file for this IDL.
185 if os.path.isfile(idl_pickle_filename):
186 with open(idl_pickle_filename) as idl_pickle_file:
187 idl_global_data = pickle.load(idl_pickle_file)
188 idl_pickle_file.close()
189 idl_world['interface'] = idl_global_data['interface']
190 idl_world['callback'] = idl_global_data['callback']
191
192 if 'interface_name' in template_contents:
193 interface_global = {'component_dir': interface_info['component_dir'] ,
194 'name': template_contents['interface_name'],
195 'parent_interface': template_contents['parent_in terface'],
196 'is_active_dom_object': template_contents['is_ac tive_dom_object'],
197 'is_event_target': template_contents['is_event_t arget'],
198 'has_resolver': template_contents['interface_nam e'],
199 'native_entries': sorted(template_contents['nati ve_entries'], key=lambda(x): x['blink_entry']),
200 'is_node': template_contents['is_node'],
201 'conditional_string': template_contents['conditi onal_string'],
202 }
203 idl_world['interface'] = interface_global
204 else:
205 callback_global = {'name': template_contents['cpp_class']}
206 idl_world['callback'] = callback_global
207
208 write_pickle_file(idl_pickle_filename, idl_world, only_if_changed)
209
210 # Render Jinja templates
211 header_text = header_template.render(template_contents)
212 cpp_text = cpp_template.render(template_contents)
213 return header_text, cpp_text
214
215 def load_global_pickles(self, global_entries):
216 # List of all interfaces and callbacks for global code generation.
217 world = {'interfaces': [], 'callbacks': []}
218
219 # Load all pickled data for each interface.
220 for (directory, file_list) in global_entries:
221 for idl_filename in file_list:
222 interface_name = idl_filename_to_interface_name(idl_filename)
223 idl_pickle_filename = interface_name + "_globals.pickle"
224 idl_pickle_filename = os.path.join(directory, idl_pickle_filenam e)
225 with open(idl_pickle_filename) as idl_pickle_file:
226 idl_world = pickle.load(idl_pickle_file)
227 if 'interface' in idl_world:
228 # FIXME: Why are some of these None?
229 if idl_world['interface']:
230 world['interfaces'].append(idl_world['interface'])
231 if 'callbacks' in idl_world:
232 # FIXME: Why are some of these None?
233 if idl_world['callbacks']:
234 world['callbacks'].append(idl_world['callback'])
235 world['interfaces'] = sorted(world['interfaces'], key=lambda (x): x['nam e'])
236 world['callbacks'] = sorted(world['callbacks'], key=lambda (x): x['name' ])
237 return world
238
239 # Generates global file for all interfaces.
240 def generate_globals(self, global_entries):
241 template_contents = self.load_global_pickles(global_entries)
242 template_contents['code_generator'] = module_pyname
243
244 header_template_filename = 'global_h.template'
245 header_template = self.jinja_env.get_template(header_template_filename)
246 header_text = header_template.render(template_contents)
247
248 cpp_template_filename = 'global_cpp.template'
249 cpp_template = self.jinja_env.get_template(cpp_template_filename)
250 cpp_text = cpp_template.render(template_contents)
251
252 return header_text, cpp_text
253
254 # Generates global dart blink file for all interfaces.
255 def generate_dart_blink(self, global_entries):
256 template_contents = self.load_global_pickles(global_entries)
257 template_contents['code_generator'] = module_pyname
258
259 template_filename = 'dart_blink.template'
260 template = self.jinja_env.get_template(template_filename)
261
262 text = template.render(template_contents)
263 return text
264
265
266 def initialize_jinja_env(cache_dir):
267 jinja_env = jinja2.Environment(
268 loader=jinja2.FileSystemLoader(templates_dir),
269 # Bytecode cache is not concurrency-safe unless pre-cached:
270 # if pre-cached this is read-only, but writing creates a race condition.
271 # bytecode_cache=jinja2.FileSystemBytecodeCache(cache_dir),
272 keep_trailing_newline=True, # newline-terminate generated files
273 lstrip_blocks=True, # so can indent control flow tags
274 trim_blocks=True)
275 jinja_env.filters.update({
276 'blink_capitalize': DartUtilities.capitalize,
277 'conditional': conditional_if_endif,
278 'runtime_enabled': runtime_enabled_if,
279 })
280 return jinja_env
281
282
283 # [Conditional]
284 def conditional_if_endif(code, conditional_string):
285 # Jinja2 filter to generate if/endif directive blocks
286 if not conditional_string:
287 return code
288 return ('#if %s\n' % conditional_string +
289 code +
290 '#endif // %s\n' % conditional_string)
291
292
293 # [RuntimeEnabled]
294 def runtime_enabled_if(code, runtime_enabled_function_name):
295 if not runtime_enabled_function_name:
296 return code
297 # Indent if statement to level of original code
298 indent = re.match(' *', code).group(0)
299 return ('%sif (%s())\n' % (indent, runtime_enabled_function_name) +
300 ' %s' % code)
301
302
303 ################################################################################
304
305 def main(argv):
306 # If file itself executed, cache templates
307 try:
308 cache_dir = argv[1]
309 dummy_filename = argv[2]
310 except IndexError as err:
311 print 'Usage: %s OUTPUT_DIR DUMMY_FILENAME' % argv[0]
312 return 1
313
314 # Cache templates
315 jinja_env = initialize_jinja_env(cache_dir)
316 template_filenames = [filename for filename in os.listdir(templates_dir)
317 # Skip .svn, directories, etc.
318 if filename.endswith(('.cpp', '.h', '.template'))]
319 for template_filename in template_filenames:
320 jinja_env.get_template(template_filename)
321
322 # Create a dummy file as output for the build system,
323 # since filenames of individual cache files are unpredictable and opaque
324 # (they are hashes of the template path, which varies based on environment)
325 with open(dummy_filename, 'w') as dummy_file:
326 pass # |open| creates or touches the file
327
328
329 if __name__ == '__main__':
330 sys.exit(main(sys.argv))
OLDNEW
« no previous file with comments | « sky/engine/bindings-dart/dart/scripts/__init__.py ('k') | sky/engine/bindings-dart/dart/scripts/compiler.py » ('j') | no next file with comments »

Powered by Google App Engine
This is Rietveld 408576698