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 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 FIXME: Not currently used in build. | |
41 This is a rewrite of the Perl IDL compiler in Python, but is not complete. | |
42 Once it is complete, we will switch all IDL files over to Python at once. | |
43 Until then, please work on the Perl IDL compiler. | |
44 For details, see bug http://crbug.com/239771 | |
45 | |
46 Input: An object of class IdlDefinitions, containing an IDL interface X | |
47 Output: V8X.h and V8X.cpp | |
48 """ | |
49 | |
50 import os | |
51 import posixpath | |
52 import re | |
53 import sys | |
54 | |
55 # Path handling for libraries and templates | |
56 # Paths have to be normalized because Jinja uses the exact template path to | |
57 # determine the hash used in the cache filename, and we need a pre-caching step | |
58 # to be concurrency-safe. Use absolute path because __file__ is absolute if | |
59 # module is imported, and relative if executed directly. | |
60 # If paths differ between pre-caching and individual file compilation, the cache | |
61 # is regenerated, which causes a race condition and breaks concurrent build, | |
62 # since some compile processes will try to read the partially written cache. | |
63 module_path = os.path.dirname(os.path.realpath(__file__)) | |
64 third_party_dir = os.path.normpath(os.path.join( | |
65 module_path, os.pardir, os.pardir, os.pardir, os.pardir, os.pardir)) | |
66 templates_dir = os.path.normpath(os.path.join( | |
67 module_path, os.pardir, os.pardir, 'templates')) | |
68 | |
69 # jinja2 is in chromium's third_party directory. | |
70 # Insert at 1 so at front to override system libraries, and | |
71 # after path[0] == invoking script dir | |
72 sys.path.insert(1, third_party_dir) | |
73 import jinja2 | |
74 | |
75 import v8_callback_interface | |
76 from v8_globals import includes, interfaces | |
77 import v8_interface | |
78 import v8_types | |
79 from v8_utilities import capitalize, cpp_name, conditional_string, v8_class_name | |
80 | |
81 | |
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) | |
87 | |
88 # Set global type info | |
89 v8_types.set_ancestors(dict( | |
90 (interface_name, interface_info['ancestors']) | |
91 for interface_name, interface_info in interfaces_info.iteritems() | |
92 if 'ancestors' in interface_info)) | |
93 v8_types.set_callback_interfaces(set( | |
94 interface_name | |
95 for interface_name, interface_info in interfaces_info.iteritems() | |
96 if interface_info['is_callback_interface'])) | |
97 v8_types.set_implemented_as_interfaces(dict( | |
98 (interface_name, interface_info['implemented_as']) | |
99 for interface_name, interface_info in interfaces_info.iteritems() | |
100 if 'implemented_as' in interface_info)) | |
101 v8_types.set_will_be_garbage_collected_types(set( | |
102 interface_name | |
103 for interface_name, interface_info in interfaces_info.iteritems() | |
104 if 'inherited_extended_attributes' in interface_info and | |
105 'WillBeGarbageCollected' in interface_info['inherited_extended_a
ttributes'])) | |
106 | |
107 def generate_code(self, definitions, interface_name): | |
108 """Returns .h/.cpp code as (header_text, cpp_text).""" | |
109 try: | |
110 interface = definitions.interfaces[interface_name] | |
111 except KeyError: | |
112 raise Exception('%s not in IDL definitions' % interface_name) | |
113 | |
114 # Store other interfaces for introspection | |
115 interfaces.update(definitions.interfaces) | |
116 | |
117 # Set local type info | |
118 v8_types.set_callback_functions(definitions.callback_functions.keys()) | |
119 v8_types.set_enums((enum.name, enum.values) | |
120 for enum in definitions.enumerations.values()) | |
121 | |
122 # Select appropriate Jinja template and contents function | |
123 if interface.is_callback: | |
124 header_template_filename = 'callback_interface.h' | |
125 cpp_template_filename = 'callback_interface.cpp' | |
126 generate_contents = v8_callback_interface.generate_callback_interfac
e | |
127 else: | |
128 header_template_filename = 'interface.h' | |
129 cpp_template_filename = 'interface.cpp' | |
130 generate_contents = v8_interface.generate_interface | |
131 header_template = self.jinja_env.get_template(header_template_filename) | |
132 cpp_template = self.jinja_env.get_template(cpp_template_filename) | |
133 | |
134 # Generate contents (input parameters for Jinja) | |
135 template_contents = generate_contents(interface) | |
136 | |
137 # Add includes for interface itself and any dependencies | |
138 interface_info = self.interfaces_info[interface_name] | |
139 template_contents['header_includes'].add(interface_info['include_path']) | |
140 template_contents['header_includes'] = sorted(template_contents['header_
includes']) | |
141 includes.update(interface_info.get('dependencies_include_paths', [])) | |
142 template_contents['cpp_includes'] = sorted(includes) | |
143 | |
144 # Render Jinja templates | |
145 header_text = header_template.render(template_contents) | |
146 cpp_text = cpp_template.render(template_contents) | |
147 return header_text, cpp_text | |
148 | |
149 | |
150 def initialize_jinja_env(cache_dir): | |
151 jinja_env = jinja2.Environment( | |
152 loader=jinja2.FileSystemLoader(templates_dir), | |
153 # Bytecode cache is not concurrency-safe unless pre-cached: | |
154 # if pre-cached this is read-only, but writing creates a race condition. | |
155 bytecode_cache=jinja2.FileSystemBytecodeCache(cache_dir), | |
156 keep_trailing_newline=True, # newline-terminate generated files | |
157 lstrip_blocks=True, # so can indent control flow tags | |
158 trim_blocks=True) | |
159 jinja_env.filters.update({ | |
160 'blink_capitalize': capitalize, | |
161 'conditional': conditional_if_endif, | |
162 'runtime_enabled': runtime_enabled_if, | |
163 }) | |
164 return jinja_env | |
165 | |
166 | |
167 # [Conditional] | |
168 def conditional_if_endif(code, conditional_string): | |
169 # Jinja2 filter to generate if/endif directive blocks | |
170 if not conditional_string: | |
171 return code | |
172 return ('#if %s\n' % conditional_string + | |
173 code + | |
174 '#endif // %s\n' % conditional_string) | |
175 | |
176 | |
177 # [RuntimeEnabled] | |
178 def runtime_enabled_if(code, runtime_enabled_function_name): | |
179 if not runtime_enabled_function_name: | |
180 return code | |
181 # Indent if statement to level of original code | |
182 indent = re.match(' *', code).group(0) | |
183 return ('%sif (%s())\n' % (indent, runtime_enabled_function_name) + | |
184 ' %s' % code) | |
185 | |
186 | |
187 ################################################################################ | |
188 | |
189 def main(argv): | |
190 # If file itself executed, cache templates | |
191 try: | |
192 cache_dir = argv[1] | |
193 dummy_filename = argv[2] | |
194 except IndexError as err: | |
195 print 'Usage: %s OUTPUT_DIR DUMMY_FILENAME' % argv[0] | |
196 return 1 | |
197 | |
198 # Cache templates | |
199 jinja_env = initialize_jinja_env(cache_dir) | |
200 template_filenames = [filename for filename in os.listdir(templates_dir) | |
201 # Skip .svn, directories, etc. | |
202 if filename.endswith(('.cpp', '.h'))] | |
203 for template_filename in template_filenames: | |
204 jinja_env.get_template(template_filename) | |
205 | |
206 # Create a dummy file as output for the build system, | |
207 # since filenames of individual cache files are unpredictable and opaque | |
208 # (they are hashes of the template path, which varies based on environment) | |
209 with open(dummy_filename, 'w') as dummy_file: | |
210 pass # |open| creates or touches the file | |
211 | |
212 | |
213 if __name__ == '__main__': | |
214 sys.exit(main(sys.argv)) | |
OLD | NEW |