Roll src/third_party/WebKit f007c95:0171005 (svn 185074:185088)
[chromium-blink-merge.git] / tools / json_schema_compiler / cpp_bundle_generator.py
blob0a4f9a6c7a8f4391de68e439bfcd0a94a99f1bec
1 # Copyright (c) 2012 The Chromium Authors. All rights reserved.
2 # Use of this source code is governed by a BSD-style license that can be
3 # found in the LICENSE file.
5 import code
6 import cpp_util
7 from model import Platforms
8 from schema_util import CapitalizeFirstLetter
9 from schema_util import JsFunctionNameToClassName
11 import json
12 import os
13 import re
16 def _RemoveDescriptions(node):
17 """Returns a copy of |schema| with "description" fields removed.
18 """
19 if isinstance(node, dict):
20 result = {}
21 for key, value in node.items():
22 # Some schemas actually have properties called "description", so only
23 # remove descriptions that have string values.
24 if key == 'description' and isinstance(value, basestring):
25 continue
26 result[key] = _RemoveDescriptions(value)
27 return result
28 if isinstance(node, list):
29 return [_RemoveDescriptions(v) for v in node]
30 return node
33 class CppBundleGenerator(object):
34 """This class contains methods to generate code based on multiple schemas.
35 """
37 def __init__(self,
38 root,
39 model,
40 api_defs,
41 cpp_type_generator,
42 cpp_namespace_pattern,
43 source_file_dir,
44 impl_dir):
45 self._root = root
46 self._model = model
47 self._api_defs = api_defs
48 self._cpp_type_generator = cpp_type_generator
49 self._source_file_dir = source_file_dir
50 self._impl_dir = impl_dir
52 # Hack: assume that the C++ namespace for the bundle is the namespace of the
53 # files without the last component of the namespace. A cleaner way to do
54 # this would be to make it a separate variable in the gyp file.
55 self._cpp_namespace = cpp_namespace_pattern.rsplit('::', 1)[0]
57 self.api_cc_generator = _APICCGenerator(self)
58 self.api_h_generator = _APIHGenerator(self)
59 self.schemas_cc_generator = _SchemasCCGenerator(self)
60 self.schemas_h_generator = _SchemasHGenerator(self)
62 def _GenerateHeader(self, file_base, body_code):
63 """Generates a code.Code object for a header file
65 Parameters:
66 - |file_base| - the base of the filename, e.g. 'foo' (for 'foo.h')
67 - |body_code| - the code to put in between the multiple inclusion guards"""
68 c = code.Code()
69 c.Append(cpp_util.CHROMIUM_LICENSE)
70 c.Append()
71 c.Append(cpp_util.GENERATED_BUNDLE_FILE_MESSAGE % self._source_file_dir)
72 ifndef_name = cpp_util.GenerateIfndefName(
73 '%s/%s.h' % (self._source_file_dir, file_base))
74 c.Append()
75 c.Append('#ifndef %s' % ifndef_name)
76 c.Append('#define %s' % ifndef_name)
77 c.Append()
78 c.Concat(body_code)
79 c.Append()
80 c.Append('#endif // %s' % ifndef_name)
81 c.Append()
82 return c
84 def _GetPlatformIfdefs(self, model_object):
85 """Generates the "defined" conditional for an #if check if |model_object|
86 has platform restrictions. Returns None if there are no restrictions.
87 """
88 if model_object.platforms is None:
89 return None
90 ifdefs = []
91 for platform in model_object.platforms:
92 if platform == Platforms.CHROMEOS:
93 ifdefs.append('defined(OS_CHROMEOS)')
94 elif platform == Platforms.LINUX:
95 ifdefs.append('defined(OS_LINUX)')
96 elif platform == Platforms.MAC:
97 ifdefs.append('defined(OS_MACOSX)')
98 elif platform == Platforms.WIN:
99 ifdefs.append('defined(OS_WIN)')
100 else:
101 raise ValueError("Unsupported platform ifdef: %s" % platform.name)
102 return ' || '.join(ifdefs)
104 def _GenerateRegisterFunctions(self, namespace_name, function):
105 c = code.Code()
106 function_ifdefs = self._GetPlatformIfdefs(function)
107 if function_ifdefs is not None:
108 c.Append("#if %s" % function_ifdefs, indent_level=0)
110 function_name = JsFunctionNameToClassName(namespace_name, function.name)
111 c.Append("registry->RegisterFunction<%sFunction>();" % (
112 function_name))
114 if function_ifdefs is not None:
115 c.Append("#endif // %s" % function_ifdefs, indent_level=0)
116 return c
118 def _GenerateFunctionRegistryRegisterAll(self):
119 c = code.Code()
120 c.Append('// static')
121 c.Sblock('void GeneratedFunctionRegistry::RegisterAll('
122 'ExtensionFunctionRegistry* registry) {')
123 for namespace in self._model.namespaces.values():
124 namespace_ifdefs = self._GetPlatformIfdefs(namespace)
125 if namespace_ifdefs is not None:
126 c.Append("#if %s" % namespace_ifdefs, indent_level=0)
128 namespace_name = CapitalizeFirstLetter(namespace.name.replace(
129 "experimental.", ""))
130 for function in namespace.functions.values():
131 if function.nocompile:
132 continue
133 c.Concat(self._GenerateRegisterFunctions(namespace.name, function))
135 for type_ in namespace.types.values():
136 for function in type_.functions.values():
137 if function.nocompile:
138 continue
139 namespace_types_name = JsFunctionNameToClassName(
140 namespace.name, type_.name)
141 c.Concat(self._GenerateRegisterFunctions(namespace_types_name,
142 function))
144 if namespace_ifdefs is not None:
145 c.Append("#endif // %s" % namespace_ifdefs, indent_level=0)
146 c.Eblock("}")
147 return c
150 class _APIHGenerator(object):
151 """Generates the header for API registration / declaration"""
152 def __init__(self, cpp_bundle):
153 self._bundle = cpp_bundle
155 def Generate(self, _): # namespace not relevant, this is a bundle
156 c = code.Code()
158 c.Append('#include <string>')
159 c.Append()
160 c.Append('#include "base/basictypes.h"')
161 c.Append()
162 c.Append("class ExtensionFunctionRegistry;")
163 c.Append()
164 c.Concat(cpp_util.OpenNamespace(self._bundle._cpp_namespace))
165 c.Append()
166 c.Append('class GeneratedFunctionRegistry {')
167 c.Sblock(' public:')
168 c.Append('static void RegisterAll('
169 'ExtensionFunctionRegistry* registry);')
170 c.Eblock('};')
171 c.Append()
172 c.Concat(cpp_util.CloseNamespace(self._bundle._cpp_namespace))
173 return self._bundle._GenerateHeader('generated_api', c)
176 class _APICCGenerator(object):
177 """Generates a code.Code object for the generated API .cc file"""
179 def __init__(self, cpp_bundle):
180 self._bundle = cpp_bundle
182 def Generate(self, _): # namespace not relevant, this is a bundle
183 c = code.Code()
184 c.Append(cpp_util.CHROMIUM_LICENSE)
185 c.Append()
186 c.Append('#include "%s"' % (
187 os.path.join(self._bundle._impl_dir,
188 'generated_api_registration.h')))
189 c.Append()
190 for namespace in self._bundle._model.namespaces.values():
191 namespace_name = namespace.unix_name.replace("experimental_", "")
192 implementation_header = namespace.compiler_options.get(
193 "implemented_in",
194 "%s/%s/%s_api.h" % (self._bundle._impl_dir,
195 namespace_name,
196 namespace_name))
197 if not os.path.exists(
198 os.path.join(self._bundle._root,
199 os.path.normpath(implementation_header))):
200 if "implemented_in" in namespace.compiler_options:
201 raise ValueError('Header file for namespace "%s" specified in '
202 'compiler_options not found: %s' %
203 (namespace.unix_name, implementation_header))
204 continue
205 ifdefs = self._bundle._GetPlatformIfdefs(namespace)
206 if ifdefs is not None:
207 c.Append("#if %s" % ifdefs, indent_level=0)
209 c.Append('#include "%s"' % implementation_header)
211 if ifdefs is not None:
212 c.Append("#endif // %s" % ifdefs, indent_level=0)
213 c.Append()
214 c.Append('#include '
215 '"extensions/browser/extension_function_registry.h"')
216 c.Append()
217 c.Concat(cpp_util.OpenNamespace(self._bundle._cpp_namespace))
218 c.Append()
219 c.Concat(self._bundle._GenerateFunctionRegistryRegisterAll())
220 c.Append()
221 c.Concat(cpp_util.CloseNamespace(self._bundle._cpp_namespace))
222 c.Append()
223 return c
226 class _SchemasHGenerator(object):
227 """Generates a code.Code object for the generated schemas .h file"""
228 def __init__(self, cpp_bundle):
229 self._bundle = cpp_bundle
231 def Generate(self, _): # namespace not relevant, this is a bundle
232 c = code.Code()
233 c.Append('#include <map>')
234 c.Append('#include <string>')
235 c.Append()
236 c.Append('#include "base/strings/string_piece.h"')
237 c.Append()
238 c.Concat(cpp_util.OpenNamespace(self._bundle._cpp_namespace))
239 c.Append()
240 c.Append('class GeneratedSchemas {')
241 c.Sblock(' public:')
242 c.Append('// Determines if schema named |name| is generated.')
243 c.Append('static bool IsGenerated(std::string name);')
244 c.Append()
245 c.Append('// Gets the API schema named |name|.')
246 c.Append('static base::StringPiece Get(const std::string& name);')
247 c.Eblock('};')
248 c.Append()
249 c.Concat(cpp_util.CloseNamespace(self._bundle._cpp_namespace))
250 return self._bundle._GenerateHeader('generated_schemas', c)
253 def _FormatNameAsConstant(name):
254 """Formats a name to be a C++ constant of the form kConstantName"""
255 name = '%s%s' % (name[0].upper(), name[1:])
256 return 'k%s' % re.sub('_[a-z]',
257 lambda m: m.group(0)[1].upper(),
258 name.replace('.', '_'))
261 class _SchemasCCGenerator(object):
262 """Generates a code.Code object for the generated schemas .cc file"""
264 def __init__(self, cpp_bundle):
265 self._bundle = cpp_bundle
267 def Generate(self, _): # namespace not relevant, this is a bundle
268 c = code.Code()
269 c.Append(cpp_util.CHROMIUM_LICENSE)
270 c.Append()
271 c.Append('#include "%s"' % (os.path.join(self._bundle._source_file_dir,
272 'generated_schemas.h')))
273 c.Append()
274 c.Append('#include "base/lazy_instance.h"')
275 c.Append()
276 c.Append('namespace {')
277 for api in self._bundle._api_defs:
278 namespace = self._bundle._model.namespaces[api.get('namespace')]
279 # JSON parsing code expects lists of schemas, so dump a singleton list.
280 json_content = json.dumps([_RemoveDescriptions(api)],
281 separators=(',', ':'))
282 # Escape all double-quotes and backslashes. For this to output a valid
283 # JSON C string, we need to escape \ and ". Note that some schemas are
284 # too large to compile on windows. Split the JSON up into several
285 # strings, since apparently that helps.
286 max_length = 8192
287 segments = [json_content[i:i + max_length].replace('\\', '\\\\')
288 .replace('"', '\\"')
289 for i in xrange(0, len(json_content), max_length)]
290 c.Append('const char %s[] = "%s";' %
291 (_FormatNameAsConstant(namespace.name), '" "'.join(segments)))
292 c.Append('}')
293 c.Concat(cpp_util.OpenNamespace(self._bundle._cpp_namespace))
294 c.Append()
295 c.Sblock('struct Static {')
296 c.Sblock('Static() {')
297 for api in self._bundle._api_defs:
298 namespace = self._bundle._model.namespaces[api.get('namespace')]
299 c.Append('schemas["%s"] = %s;' % (namespace.name,
300 _FormatNameAsConstant(namespace.name)))
301 c.Eblock('}')
302 c.Append()
303 c.Append('std::map<std::string, const char*> schemas;')
304 c.Eblock('};')
305 c.Append()
306 c.Append('base::LazyInstance<Static> g_lazy_instance;')
307 c.Append()
308 c.Append('// static')
309 c.Sblock('base::StringPiece GeneratedSchemas::Get('
310 'const std::string& name) {')
311 c.Append('return IsGenerated(name) ? '
312 'g_lazy_instance.Get().schemas[name] : "";')
313 c.Eblock('}')
314 c.Append()
315 c.Append('// static')
316 c.Sblock('bool GeneratedSchemas::IsGenerated(std::string name) {')
317 c.Append('return g_lazy_instance.Get().schemas.count(name) > 0;')
318 c.Eblock('}')
319 c.Append()
320 c.Concat(cpp_util.CloseNamespace(self._bundle._cpp_namespace))
321 c.Append()
322 return c