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

Side by Side Diff: bindings/dart/scripts/code_generator_dart.py

Issue 540533002: Roll IDL to Dartium37 (r181268) (Closed) Base URL: https://dart.googlecode.com/svn/third_party/WebCore
Patch Set: Created 6 years, 3 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 | Annotate | Revision Log
« no previous file with comments | « bindings/dart/scripts/__init__.py ('k') | bindings/dart/scripts/compiler.py » ('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 # 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
88 from v8_globals import includes, interfaces
89
90 # TODO(jacobr): remove this hacked together list.
91 INTERFACES_WITHOUT_RESOLVERS = frozenset([
92 'TypeConversions',
93 'GCObservation',
94 'InternalProfilers',
95 'InternalRuntimeFlags',
96 'InternalSettings',
97 'InternalSettingsGenerated',
98 'Internals',
99 'LayerRect',
100 'LayerRectList',
101 'MallocStatistics',
102 'TypeConversions'])
103
104 class CodeGeneratorDart(object):
105 def __init__(self, interfaces_info, cache_dir):
106 interfaces_info = interfaces_info or {}
107 self.interfaces_info = interfaces_info
108 self.jinja_env = initialize_jinja_env(cache_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_implemented_as_interfaces(dict(
120 (interface_name, interface_info['implemented_as'])
121 for interface_name, interface_info in interfaces_info.iteritems()
122 if interface_info['implemented_as']))
123 IdlType.set_garbage_collected_types(set(
124 interface_name
125 for interface_name, interface_info in interfaces_info.iteritems()
126 if 'GarbageCollected' in interface_info['inherited_extended_attribut es']))
127 IdlType.set_will_be_garbage_collected_types(set(
128 interface_name
129 for interface_name, interface_info in interfaces_info.iteritems()
130 if 'WillBeGarbageCollected' in interface_info['inherited_extended_at tributes']))
131
132 def generate_code(self, definitions, interface_name, idl_pickle_filename,
133 only_if_changed):
134 """Returns .h/.cpp code as (header_text, cpp_text)."""
135 try:
136 interface = definitions.interfaces[interface_name]
137 except KeyError:
138 raise Exception('%s not in IDL definitions' % interface_name)
139
140 # Store other interfaces for introspection
141 interfaces.update(definitions.interfaces)
142
143 # Set local type info
144 IdlType.set_callback_functions(definitions.callback_functions.keys())
145 IdlType.set_enums((enum.name, enum.values)
146 for enum in definitions.enumerations.values())
147
148 # Select appropriate Jinja template and contents function
149 if interface.is_callback:
150 header_template_filename = 'callback_interface_h.template'
151 cpp_template_filename = 'callback_interface_cpp.template'
152 generate_contents = dart_callback_interface.generate_callback_interf ace
153 else:
154 header_template_filename = 'interface_h.template'
155 cpp_template_filename = 'interface_cpp.template'
156 generate_contents = dart_interface.generate_interface
157 header_template = self.jinja_env.get_template(header_template_filename)
158 cpp_template = self.jinja_env.get_template(cpp_template_filename)
159
160 # Generate contents (input parameters for Jinja)
161 template_contents = generate_contents(interface)
162 template_contents['code_generator'] = module_pyname
163
164 # Add includes for interface itself and any dependencies
165 interface_info = self.interfaces_info[interface_name]
166 template_contents['header_includes'].add(interface_info['include_path'])
167 template_contents['header_includes'] = sorted(template_contents['header_ includes'])
168 includes.update(interface_info.get('dependencies_include_paths', []))
169
170 # Remove includes that are not needed for Dart and trigger fatal
171 # compile warnings if included. These IDL files need to be
172 # imported by Dart to generate the list of events but the
173 # associated header files do not contain any code used by Dart.
174 includes.discard('core/dom/GlobalEventHandlers.h')
175 includes.discard('core/frame/DOMWindowEventHandlers.h')
176
177 template_contents['cpp_includes'] = sorted(includes)
178
179 idl_world = {'interface': None, 'callback': None}
180
181 # Load the pickle file for this IDL.
182 if os.path.isfile(idl_pickle_filename):
183 with open(idl_pickle_filename) as idl_pickle_file:
184 idl_global_data = pickle.load(idl_pickle_file)
185 idl_pickle_file.close()
186 idl_world['interface'] = idl_global_data['interface']
187 idl_world['callback'] = idl_global_data['callback']
188
189 if 'interface_name' in template_contents:
190 interface_global = {'name': template_contents['interface_name'],
191 'parent_interface': template_contents['parent_in terface'],
192 'is_active_dom_object': template_contents['is_ac tive_dom_object'],
193 'is_event_target': template_contents['is_event_t arget'],
194 'has_resolver': template_contents['interface_nam e'] not in INTERFACES_WITHOUT_RESOLVERS,
195 'is_node': template_contents['is_node'],
196 'conditional_string': template_contents['conditi onal_string'],
197 }
198 idl_world['interface'] = interface_global
199 else:
200 callback_global = {'name': template_contents['cpp_class']}
201 idl_world['callback'] = callback_global
202
203 write_pickle_file(idl_pickle_filename, idl_world, only_if_changed)
204
205 # Render Jinja templates
206 header_text = header_template.render(template_contents)
207 cpp_text = cpp_template.render(template_contents)
208 return header_text, cpp_text
209
210 # Generates global file for all interfaces.
211 def generate_globals(self, global_pickle_directories, output_directory):
212 header_template_filename = 'global_h.template'
213 cpp_template_filename = 'global_cpp.template'
214
215 # Delete the global pickle file we'll rebuild from each pickle generated
216 # for each IDL file '(%s_globals.pickle) % interface_name'.
217 global_pickle_filename = os.path.join(output_directory, 'global.pickle')
218 if os.path.isfile(global_pickle_filename):
219 os.remove(global_pickle_filename)
220
221 # List of all interfaces and callbacks for global code generation.
222 world = {'interfaces': [], 'callbacks': []}
223
224 # Load all pickled data for each interface.
225 for pickle_directory in global_pickle_directories:
226 listing = os.listdir(pickle_directory)
227 for filename in listing:
228 if filename.endswith('_globals.pickle'):
229 idl_filename = os.path.join(pickle_directory, filename)
230 with open(idl_filename) as idl_pickle_file:
231 idl_world = pickle.load(idl_pickle_file)
232 if 'interface' in idl_world:
233 # FIXME: Why are some of these None?
234 if idl_world['interface']:
235 world['interfaces'].append(idl_world['interface' ])
236 if 'callbacks' in idl_world:
237 # FIXME: Why are some of these None?
238 if idl_world['callbacks']:
239 world['callbacks'].append(idl_world['callback'])
240 idl_pickle_file.close()
241
242 world['interfaces'] = sorted(world['interfaces'], key=lambda (x): x['nam e'])
243 world['callbacks'] = sorted(world['callbacks'], key=lambda (x): x['name' ])
244
245 template_contents = world
246 template_contents['code_generator'] = module_pyname
247
248 header_template = self.jinja_env.get_template(header_template_filename)
249 header_text = header_template.render(template_contents)
250
251 cpp_template = self.jinja_env.get_template(cpp_template_filename)
252 cpp_text = cpp_template.render(template_contents)
253 return header_text, cpp_text
254
255
256 def initialize_jinja_env(cache_dir):
257 jinja_env = jinja2.Environment(
258 loader=jinja2.FileSystemLoader(templates_dir),
259 # Bytecode cache is not concurrency-safe unless pre-cached:
260 # if pre-cached this is read-only, but writing creates a race condition.
261 # bytecode_cache=jinja2.FileSystemBytecodeCache(cache_dir),
262 keep_trailing_newline=True, # newline-terminate generated files
263 lstrip_blocks=True, # so can indent control flow tags
264 trim_blocks=True)
265 jinja_env.filters.update({
266 'blink_capitalize': DartUtilities.capitalize,
267 'conditional': conditional_if_endif,
268 'runtime_enabled': runtime_enabled_if,
269 })
270 return jinja_env
271
272
273 # [Conditional]
274 def conditional_if_endif(code, conditional_string):
275 # Jinja2 filter to generate if/endif directive blocks
276 if not conditional_string:
277 return code
278 return ('#if %s\n' % conditional_string +
279 code +
280 '#endif // %s\n' % conditional_string)
281
282
283 # [RuntimeEnabled]
284 def runtime_enabled_if(code, runtime_enabled_function_name):
285 if not runtime_enabled_function_name:
286 return code
287 # Indent if statement to level of original code
288 indent = re.match(' *', code).group(0)
289 return ('%sif (%s())\n' % (indent, runtime_enabled_function_name) +
290 ' %s' % code)
291
292
293 ################################################################################
294
295 def main(argv):
296 # If file itself executed, cache templates
297 try:
298 cache_dir = argv[1]
299 dummy_filename = argv[2]
300 except IndexError as err:
301 print 'Usage: %s OUTPUT_DIR DUMMY_FILENAME' % argv[0]
302 return 1
303
304 # Cache templates
305 jinja_env = initialize_jinja_env(cache_dir)
306 template_filenames = [filename for filename in os.listdir(templates_dir)
307 # Skip .svn, directories, etc.
308 if filename.endswith(('.cpp', '.h', '.template'))]
309 for template_filename in template_filenames:
310 jinja_env.get_template(template_filename)
311
312 # Create a dummy file as output for the build system,
313 # since filenames of individual cache files are unpredictable and opaque
314 # (they are hashes of the template path, which varies based on environment)
315 with open(dummy_filename, 'w') as dummy_file:
316 pass # |open| creates or touches the file
317
318
319 if __name__ == '__main__':
320 sys.exit(main(sys.argv))
OLDNEW
« no previous file with comments | « bindings/dart/scripts/__init__.py ('k') | bindings/dart/scripts/compiler.py » ('j') | no next file with comments »

Powered by Google App Engine
This is Rietveld 408576698