1 # Copyright (C) 2013 Google Inc. All rights reserved.
3 # Redistribution and use in source and binary forms, with or without
4 # modification, are permitted provided that the following conditions are
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
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.
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.
29 """Generate Blink V8 bindings (.h and .cpp files).
31 If run itself, caches Jinja templates (and creates dummy file for build,
32 since cache filenames are unpredictable and opaque).
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.
40 Input: An object of class IdlDefinitions, containing an IDL interface X
41 Output: V8X.h and V8X.cpp
43 Design doc: http://www.chromium.org/developers/design-documents/idl-compiler
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))
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'
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)
74 from idl_types import IdlType
75 import v8_callback_interface
76 from v8_globals import includes, interfaces
79 from v8_utilities import capitalize, cpp_name, conditional_string, v8_class_name
82 class CodeGeneratorV8(object):
83 def __init__(self, interfaces_info, cache_dir):
84 interfaces_info = interfaces_info or {}
85 self.interfaces_info = interfaces_info
86 self.jinja_env = initialize_jinja_env(cache_dir)
88 # Set global type info
89 idl_types.set_ancestors(dict(
90 (interface_name, interface_info['ancestors'])
91 for interface_name, interface_info in interfaces_info.iteritems()
92 if interface_info['ancestors']))
93 IdlType.set_callback_interfaces(set(
95 for interface_name, interface_info in interfaces_info.iteritems()
96 if interface_info['is_callback_interface']))
97 IdlType.set_implemented_as_interfaces(dict(
98 (interface_name, interface_info['implemented_as'])
99 for interface_name, interface_info in interfaces_info.iteritems()
100 if interface_info['implemented_as']))
101 IdlType.set_garbage_collected_types(set(
103 for interface_name, interface_info in interfaces_info.iteritems()
104 if 'GarbageCollected' in interface_info['inherited_extended_attributes']))
105 IdlType.set_will_be_garbage_collected_types(set(
107 for interface_name, interface_info in interfaces_info.iteritems()
108 if 'WillBeGarbageCollected' in interface_info['inherited_extended_attributes']))
110 def generate_code(self, definitions, interface_name):
111 """Returns .h/.cpp code as (header_text, cpp_text)."""
113 interface = definitions.interfaces[interface_name]
115 raise Exception('%s not in IDL definitions' % interface_name)
117 # Store other interfaces for introspection
118 interfaces.update(definitions.interfaces)
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())
125 # Select appropriate Jinja template and contents function
126 if interface.is_callback:
127 header_template_filename = 'callback_interface.h'
128 cpp_template_filename = 'callback_interface.cpp'
129 generate_contents = v8_callback_interface.generate_callback_interface
131 header_template_filename = 'interface.h'
132 cpp_template_filename = 'interface.cpp'
133 generate_contents = v8_interface.generate_interface
134 header_template = self.jinja_env.get_template(header_template_filename)
135 cpp_template = self.jinja_env.get_template(cpp_template_filename)
137 # Generate contents (input parameters for Jinja)
138 template_contents = generate_contents(interface)
139 template_contents['code_generator'] = module_pyname
141 # Add includes for interface itself and any dependencies
142 interface_info = self.interfaces_info[interface_name]
143 template_contents['header_includes'].add(interface_info['include_path'])
144 template_contents['header_includes'] = sorted(template_contents['header_includes'])
145 includes.update(interface_info.get('dependencies_include_paths', []))
146 template_contents['cpp_includes'] = sorted(includes)
148 # Render Jinja templates
149 header_text = header_template.render(template_contents)
150 cpp_text = cpp_template.render(template_contents)
151 return header_text, cpp_text
154 def initialize_jinja_env(cache_dir):
155 jinja_env = jinja2.Environment(
156 loader=jinja2.FileSystemLoader(templates_dir),
157 # Bytecode cache is not concurrency-safe unless pre-cached:
158 # if pre-cached this is read-only, but writing creates a race condition.
159 bytecode_cache=jinja2.FileSystemBytecodeCache(cache_dir),
160 keep_trailing_newline=True, # newline-terminate generated files
161 lstrip_blocks=True, # so can indent control flow tags
163 jinja_env.filters.update({
164 'blink_capitalize': capitalize,
165 'conditional': conditional_if_endif,
166 'runtime_enabled': runtime_enabled_if,
172 def conditional_if_endif(code, conditional_string):
173 # Jinja2 filter to generate if/endif directive blocks
174 if not conditional_string:
176 return ('#if %s\n' % conditional_string +
178 '#endif // %s\n' % conditional_string)
182 def runtime_enabled_if(code, runtime_enabled_function_name):
183 if not runtime_enabled_function_name:
185 # Indent if statement to level of original code
186 indent = re.match(' *', code).group(0)
187 return ('%sif (%s())\n' % (indent, runtime_enabled_function_name) +
191 ################################################################################
194 # If file itself executed, cache templates
197 dummy_filename = argv[2]
198 except IndexError as err:
199 print 'Usage: %s OUTPUT_DIR DUMMY_FILENAME' % argv[0]
203 jinja_env = initialize_jinja_env(cache_dir)
204 template_filenames = [filename for filename in os.listdir(templates_dir)
205 # Skip .svn, directories, etc.
206 if filename.endswith(('.cpp', '.h'))]
207 for template_filename in template_filenames:
208 jinja_env.get_template(template_filename)
210 # Create a dummy file as output for the build system,
211 # since filenames of individual cache files are unpredictable and opaque
212 # (they are hashes of the template path, which varies based on environment)
213 with open(dummy_filename, 'w') as dummy_file:
214 pass # |open| creates or touches the file
217 if __name__ == '__main__':
218 sys.exit(main(sys.argv))