| OLD | NEW |
| (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 import logging |
| 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 |
| 74 import jinja2 |
| 75 |
| 76 import idl_types |
| 77 from idl_types import IdlType |
| 78 import dart_callback_interface |
| 79 import dart_interface |
| 80 import dart_types |
| 81 from dart_utilities import DartUtilities |
| 82 from utilities import write_pickle_file, idl_filename_to_interface_name |
| 83 from v8_globals import includes, interfaces |
| 84 |
| 85 |
| 86 class CodeGeneratorDart(object): |
| 87 def __init__(self, interfaces_info, cache_dir): |
| 88 interfaces_info = interfaces_info or {} |
| 89 self.interfaces_info = interfaces_info |
| 90 self.jinja_env = initialize_jinja_env(cache_dir) |
| 91 |
| 92 # Set global type info |
| 93 idl_types.set_ancestors(dict( |
| 94 (interface_name, interface_info['ancestors']) |
| 95 for interface_name, interface_info in interfaces_info.iteritems() |
| 96 if interface_info['ancestors'])) |
| 97 IdlType.set_callback_interfaces(set( |
| 98 interface_name |
| 99 for interface_name, interface_info in interfaces_info.iteritems() |
| 100 if interface_info['is_callback_interface'])) |
| 101 IdlType.set_implemented_as_interfaces(dict( |
| 102 (interface_name, interface_info['implemented_as']) |
| 103 for interface_name, interface_info in interfaces_info.iteritems() |
| 104 if interface_info['implemented_as'])) |
| 105 dart_types.set_component_dirs(dict( |
| 106 (interface_name, interface_info['component_dir']) |
| 107 for interface_name, interface_info in interfaces_info.iteritems())) |
| 108 |
| 109 def generate_code(self, definitions, interface_name, idl_pickle_filename, |
| 110 only_if_changed): |
| 111 """Returns .h/.cpp/.dart code as (header_text, cpp_text, dart_text).""" |
| 112 try: |
| 113 interface = definitions.interfaces[interface_name] |
| 114 except KeyError: |
| 115 raise Exception('%s not in IDL definitions' % interface_name) |
| 116 |
| 117 # Store other interfaces for introspection |
| 118 interfaces.update(definitions.interfaces) |
| 119 |
| 120 # Set local type info |
| 121 IdlType.set_callback_functions(definitions.callback_functions.keys()) |
| 122 IdlType.set_enums((enum.name, enum.values) |
| 123 for enum in definitions.enumerations.values()) |
| 124 |
| 125 # Select appropriate Jinja template and contents function |
| 126 if interface.is_callback: |
| 127 header_template_filename = 'callback_interface_h.template' |
| 128 cpp_template_filename = 'callback_interface_cpp.template' |
| 129 dart_template_filename = 'callback_interface_dart.template' |
| 130 generate_contents = dart_callback_interface.generate_callback_interf
ace |
| 131 else: |
| 132 header_template_filename = 'interface_h.template' |
| 133 cpp_template_filename = 'interface_cpp.template' |
| 134 dart_template_filename = 'interface_dart.template' |
| 135 generate_contents = dart_interface.interface_context |
| 136 header_template = self.jinja_env.get_template(header_template_filename) |
| 137 cpp_template = self.jinja_env.get_template(cpp_template_filename) |
| 138 dart_template = self.jinja_env.get_template(dart_template_filename) |
| 139 |
| 140 # Generate contents (input parameters for Jinja) |
| 141 template_contents = generate_contents(interface) |
| 142 template_contents['code_generator'] = module_pyname |
| 143 |
| 144 # Add includes for interface itself and any dependencies |
| 145 interface_info = self.interfaces_info[interface_name] |
| 146 template_contents['header_includes'].add(interface_info['include_path']) |
| 147 template_contents['header_includes'] = sorted(template_contents['header_
includes']) |
| 148 includes.update(interface_info.get('dependencies_include_paths', [])) |
| 149 |
| 150 template_contents['cpp_includes'] = sorted(includes) |
| 151 |
| 152 idl_world = {'interface': None, 'callback': None} |
| 153 |
| 154 # Load the pickle file for this IDL. |
| 155 if os.path.isfile(idl_pickle_filename): |
| 156 with open(idl_pickle_filename) as idl_pickle_file: |
| 157 idl_global_data = pickle.load(idl_pickle_file) |
| 158 idl_pickle_file.close() |
| 159 idl_world['interface'] = idl_global_data['interface'] |
| 160 idl_world['callback'] = idl_global_data['callback'] |
| 161 |
| 162 if 'interface_name' in template_contents: |
| 163 interface_global = {'component_dir': interface_info['component_dir']
, |
| 164 'name': template_contents['interface_name'], |
| 165 'parent_interface': template_contents['parent_in
terface'], |
| 166 'is_active_dom_object': template_contents['is_ac
tive_dom_object'], |
| 167 'has_resolver': template_contents['interface_nam
e'], |
| 168 'native_entries': sorted(template_contents['nati
ve_entries'], key=lambda(x): x['blink_entry']), |
| 169 } |
| 170 idl_world['interface'] = interface_global |
| 171 else: |
| 172 callback_global = {'name': template_contents['cpp_class']} |
| 173 idl_world['callback'] = callback_global |
| 174 |
| 175 write_pickle_file(idl_pickle_filename, idl_world, only_if_changed) |
| 176 |
| 177 # Render Jinja templates |
| 178 header_text = header_template.render(template_contents) |
| 179 cpp_text = cpp_template.render(template_contents) |
| 180 dart_text = dart_template.render(template_contents) |
| 181 return header_text, cpp_text, dart_text |
| 182 |
| 183 def load_global_pickles(self, global_entries): |
| 184 # List of all interfaces and callbacks for global code generation. |
| 185 world = {'interfaces': [], 'callbacks': []} |
| 186 |
| 187 # Load all pickled data for each interface. |
| 188 for (directory, file_list) in global_entries: |
| 189 for idl_filename in file_list: |
| 190 interface_name = idl_filename_to_interface_name(idl_filename) |
| 191 idl_pickle_filename = interface_name + "_globals.pickle" |
| 192 idl_pickle_filename = os.path.join(directory, idl_pickle_filenam
e) |
| 193 if not os.path.exists(idl_pickle_filename): |
| 194 logging.warn("Missing %s" % idl_pickle_filename) |
| 195 continue |
| 196 with open(idl_pickle_filename) as idl_pickle_file: |
| 197 idl_world = pickle.load(idl_pickle_file) |
| 198 if 'interface' in idl_world: |
| 199 # FIXME: Why are some of these None? |
| 200 if idl_world['interface']: |
| 201 world['interfaces'].append(idl_world['interface']) |
| 202 if 'callback' in idl_world: |
| 203 # FIXME: Why are some of these None? |
| 204 if idl_world['callback']: |
| 205 world['callbacks'].append(idl_world['callback']) |
| 206 |
| 207 world['interfaces'] = sorted(world['interfaces'], key=lambda (x): x['nam
e']) |
| 208 world['callbacks'] = sorted(world['callbacks'], key=lambda (x): x['name'
]) |
| 209 return world |
| 210 |
| 211 # Generates global file for all interfaces. |
| 212 def generate_globals(self, global_entries): |
| 213 template_contents = self.load_global_pickles(global_entries) |
| 214 template_contents['code_generator'] = module_pyname |
| 215 |
| 216 header_template_filename = 'global_h.template' |
| 217 header_template = self.jinja_env.get_template(header_template_filename) |
| 218 header_text = header_template.render(template_contents) |
| 219 |
| 220 cpp_template_filename = 'global_cpp.template' |
| 221 cpp_template = self.jinja_env.get_template(cpp_template_filename) |
| 222 cpp_text = cpp_template.render(template_contents) |
| 223 |
| 224 return header_text, cpp_text |
| 225 |
| 226 # Generates global dart blink file for all interfaces. |
| 227 def generate_dart_blink(self, global_entries): |
| 228 template_contents = self.load_global_pickles(global_entries) |
| 229 template_contents['code_generator'] = module_pyname |
| 230 |
| 231 template_filename = 'dart_blink.template' |
| 232 template = self.jinja_env.get_template(template_filename) |
| 233 |
| 234 text = template.render(template_contents) |
| 235 return text |
| 236 |
| 237 |
| 238 def initialize_jinja_env(cache_dir): |
| 239 jinja_env = jinja2.Environment( |
| 240 loader=jinja2.FileSystemLoader(templates_dir), |
| 241 # Bytecode cache is not concurrency-safe unless pre-cached: |
| 242 # if pre-cached this is read-only, but writing creates a race condition. |
| 243 # bytecode_cache=jinja2.FileSystemBytecodeCache(cache_dir), |
| 244 keep_trailing_newline=True, # newline-terminate generated files |
| 245 lstrip_blocks=True, # so can indent control flow tags |
| 246 trim_blocks=True) |
| 247 jinja_env.filters.update({ |
| 248 'blink_capitalize': DartUtilities.capitalize, |
| 249 }) |
| 250 return jinja_env |
| 251 |
| 252 |
| 253 ################################################################################ |
| 254 |
| 255 def main(argv): |
| 256 # If file itself executed, cache templates |
| 257 try: |
| 258 cache_dir = argv[1] |
| 259 dummy_filename = argv[2] |
| 260 except IndexError as err: |
| 261 print 'Usage: %s OUTPUT_DIR DUMMY_FILENAME' % argv[0] |
| 262 return 1 |
| 263 |
| 264 # Cache templates |
| 265 jinja_env = initialize_jinja_env(cache_dir) |
| 266 template_filenames = [filename for filename in os.listdir(templates_dir) |
| 267 # Skip .svn, directories, etc. |
| 268 if filename.endswith(('.cpp', '.h', '.template'))] |
| 269 for template_filename in template_filenames: |
| 270 jinja_env.get_template(template_filename) |
| 271 |
| 272 # Create a dummy file as output for the build system, |
| 273 # since filenames of individual cache files are unpredictable and opaque |
| 274 # (they are hashes of the template path, which varies based on environment) |
| 275 with open(dummy_filename, 'w') as dummy_file: |
| 276 pass # |open| creates or touches the file |
| 277 |
| 278 |
| 279 if __name__ == '__main__': |
| 280 sys.exit(main(sys.argv)) |
| OLD | NEW |