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.
7 from model
import Platforms
8 from schema_util
import CapitalizeFirstLetter
9 from schema_util
import JsFunctionNameToClassName
16 def _RemoveDescriptions(node
):
17 """Returns a copy of |schema| with "description" fields removed.
19 if isinstance(node
, dict):
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
):
26 result
[key
] = _RemoveDescriptions(value
)
28 if isinstance(node
, list):
29 return [_RemoveDescriptions(v
) for v
in node
]
33 class CppBundleGenerator(object):
34 """This class contains methods to generate code based on multiple schemas.
47 self
._api
_defs
= api_defs
48 self
._cpp
_type
_generator
= cpp_type_generator
49 self
._cpp
_namespace
= cpp_namespace
50 self
._source
_file
_dir
= source_file_dir
51 self
._impl
_dir
= impl_dir
53 self
.api_cc_generator
= _APICCGenerator(self
)
54 self
.api_h_generator
= _APIHGenerator(self
)
55 self
.schemas_cc_generator
= _SchemasCCGenerator(self
)
56 self
.schemas_h_generator
= _SchemasHGenerator(self
)
58 def _GenerateHeader(self
, file_base
, body_code
):
59 """Generates a code.Code object for a header file
62 - |file_base| - the base of the filename, e.g. 'foo' (for 'foo.h')
63 - |body_code| - the code to put in between the multiple inclusion guards"""
65 c
.Append(cpp_util
.CHROMIUM_LICENSE
)
67 c
.Append(cpp_util
.GENERATED_BUNDLE_FILE_MESSAGE
% self
._source
_file
_dir
)
68 ifndef_name
= cpp_util
.GenerateIfndefName(self
._source
_file
_dir
, file_base
)
70 c
.Append('#ifndef %s' % ifndef_name
)
71 c
.Append('#define %s' % ifndef_name
)
75 c
.Append('#endif // %s' % ifndef_name
)
79 def _GetPlatformIfdefs(self
, model_object
):
80 """Generates the "defined" conditional for an #if check if |model_object|
81 has platform restrictions. Returns None if there are no restrictions.
83 if model_object
.platforms
is None:
86 for platform
in model_object
.platforms
:
87 if platform
== Platforms
.CHROMEOS
:
88 ifdefs
.append('defined(OS_CHROMEOS)')
89 elif platform
== Platforms
.LINUX
:
90 ifdefs
.append('defined(OS_LINUX)')
91 elif platform
== Platforms
.MAC
:
92 ifdefs
.append('defined(OS_MACOSX)')
93 elif platform
== Platforms
.WIN
:
94 ifdefs
.append('defined(OS_WIN)')
96 raise ValueError("Unsupported platform ifdef: %s" % platform
.name
)
97 return ' || '.join(ifdefs
)
99 def _GenerateRegisterFunctions(self
, namespace_name
, function
):
101 function_ifdefs
= self
._GetPlatformIfdefs
(function
)
102 if function_ifdefs
is not None:
103 c
.Append("#if %s" % function_ifdefs
, indent_level
=0)
105 function_name
= JsFunctionNameToClassName(namespace_name
, function
.name
)
106 c
.Append("registry->RegisterFunction<%sFunction>();" % (
109 if function_ifdefs
is not None:
110 c
.Append("#endif // %s" % function_ifdefs
, indent_level
=0)
113 def _GenerateFunctionRegistryRegisterAll(self
):
115 c
.Append('// static')
116 c
.Sblock('void GeneratedFunctionRegistry::RegisterAll('
117 'ExtensionFunctionRegistry* registry) {')
118 for namespace
in self
._model
.namespaces
.values():
119 namespace_ifdefs
= self
._GetPlatformIfdefs
(namespace
)
120 if namespace_ifdefs
is not None:
121 c
.Append("#if %s" % namespace_ifdefs
, indent_level
=0)
123 namespace_name
= CapitalizeFirstLetter(namespace
.name
.replace(
124 "experimental.", ""))
125 for function
in namespace
.functions
.values():
126 if function
.nocompile
:
128 c
.Concat(self
._GenerateRegisterFunctions
(namespace
.name
, function
))
130 for type_
in namespace
.types
.values():
131 for function
in type_
.functions
.values():
132 if function
.nocompile
:
134 namespace_types_name
= JsFunctionNameToClassName(
135 namespace
.name
, type_
.name
)
136 c
.Concat(self
._GenerateRegisterFunctions
(namespace_types_name
,
139 if namespace_ifdefs
is not None:
140 c
.Append("#endif // %s" % namespace_ifdefs
, indent_level
=0)
145 class _APIHGenerator(object):
146 """Generates the header for API registration / declaration"""
147 def __init__(self
, cpp_bundle
):
148 self
._bundle
= cpp_bundle
150 def Generate(self
, namespace
):
153 c
.Append('#include <string>')
155 c
.Append('#include "base/basictypes.h"')
157 c
.Append("class ExtensionFunctionRegistry;")
159 c
.Concat(cpp_util
.OpenNamespace(self
._bundle
._cpp
_namespace
))
161 c
.Append('class GeneratedFunctionRegistry {')
163 c
.Append('static void RegisterAll('
164 'ExtensionFunctionRegistry* registry);')
167 c
.Concat(cpp_util
.CloseNamespace(self
._bundle
._cpp
_namespace
))
168 return self
._bundle
._GenerateHeader
('generated_api', c
)
171 class _APICCGenerator(object):
172 """Generates a code.Code object for the generated API .cc file"""
174 def __init__(self
, cpp_bundle
):
175 self
._bundle
= cpp_bundle
177 def Generate(self
, namespace
):
179 c
.Append(cpp_util
.CHROMIUM_LICENSE
)
181 c
.Append('#include "%s"' % (os
.path
.join(self
._bundle
._source
_file
_dir
,
184 for namespace
in self
._bundle
._model
.namespaces
.values():
185 namespace_name
= namespace
.unix_name
.replace("experimental_", "")
186 implementation_header
= namespace
.compiler_options
.get(
188 "%s/%s/%s_api.h" % (self
._bundle
._impl
_dir
,
191 if not os
.path
.exists(
192 os
.path
.join(self
._bundle
._root
,
193 os
.path
.normpath(implementation_header
))):
194 if "implemented_in" in namespace
.compiler_options
:
195 raise ValueError('Header file for namespace "%s" specified in '
196 'compiler_options not found: %s' %
197 (namespace
.unix_name
, implementation_header
))
199 ifdefs
= self
._bundle
._GetPlatformIfdefs
(namespace
)
200 if ifdefs
is not None:
201 c
.Append("#if %s" % ifdefs
, indent_level
=0)
203 c
.Append('#include "%s"' % implementation_header
)
205 if ifdefs
is not None:
206 c
.Append("#endif // %s" % ifdefs
, indent_level
=0)
209 '"extensions/browser/extension_function_registry.h"')
211 c
.Concat(cpp_util
.OpenNamespace(self
._bundle
._cpp
_namespace
))
213 c
.Concat(self
._bundle
._GenerateFunctionRegistryRegisterAll
())
215 c
.Concat(cpp_util
.CloseNamespace(self
._bundle
._cpp
_namespace
))
220 class _SchemasHGenerator(object):
221 """Generates a code.Code object for the generated schemas .h file"""
222 def __init__(self
, cpp_bundle
):
223 self
._bundle
= cpp_bundle
225 def Generate(self
, namespace
):
227 c
.Append('#include <map>')
228 c
.Append('#include <string>')
230 c
.Append('#include "base/strings/string_piece.h"')
232 c
.Concat(cpp_util
.OpenNamespace(self
._bundle
._cpp
_namespace
))
234 c
.Append('class GeneratedSchemas {')
236 c
.Append('// Determines if schema named |name| is generated.')
237 c
.Append('static bool IsGenerated(std::string name);')
239 c
.Append('// Gets the API schema named |name|.')
240 c
.Append('static base::StringPiece Get(const std::string& name);')
243 c
.Concat(cpp_util
.CloseNamespace(self
._bundle
._cpp
_namespace
))
244 return self
._bundle
._GenerateHeader
('generated_schemas', c
)
247 def _FormatNameAsConstant(name
):
248 """Formats a name to be a C++ constant of the form kConstantName"""
249 name
= '%s%s' % (name
[0].upper(), name
[1:])
250 return 'k%s' % re
.sub('_[a-z]',
251 lambda m
: m
.group(0)[1].upper(),
252 name
.replace('.', '_'))
255 class _SchemasCCGenerator(object):
256 """Generates a code.Code object for the generated schemas .cc file"""
258 def __init__(self
, cpp_bundle
):
259 self
._bundle
= cpp_bundle
261 def Generate(self
, namespace
):
263 c
.Append(cpp_util
.CHROMIUM_LICENSE
)
265 c
.Append('#include "%s"' % (os
.path
.join(self
._bundle
._source
_file
_dir
,
266 'generated_schemas.h')))
268 c
.Append('#include "base/lazy_instance.h"')
270 c
.Append('namespace {')
271 for api
in self
._bundle
._api
_defs
:
272 namespace
= self
._bundle
._model
.namespaces
[api
.get('namespace')]
273 # JSON parsing code expects lists of schemas, so dump a singleton list.
274 json_content
= json
.dumps([_RemoveDescriptions(api
)],
275 separators
=(',', ':'))
276 # Escape all double-quotes and backslashes. For this to output a valid
277 # JSON C string, we need to escape \ and ".
278 json_content
= json_content
.replace('\\', '\\\\').replace('"', '\\"')
279 c
.Append('const char %s[] = "%s";' %
280 (_FormatNameAsConstant(namespace
.name
), json_content
))
282 c
.Concat(cpp_util
.OpenNamespace(self
._bundle
._cpp
_namespace
))
284 c
.Sblock('struct Static {')
285 c
.Sblock('Static() {')
286 for api
in self
._bundle
._api
_defs
:
287 namespace
= self
._bundle
._model
.namespaces
[api
.get('namespace')]
288 c
.Append('schemas["%s"] = %s;' % (namespace
.name
,
289 _FormatNameAsConstant(namespace
.name
)))
292 c
.Append('std::map<std::string, const char*> schemas;')
295 c
.Append('base::LazyInstance<Static> g_lazy_instance;')
297 c
.Append('// static')
298 c
.Sblock('base::StringPiece GeneratedSchemas::Get('
299 'const std::string& name) {')
300 c
.Append('return IsGenerated(name) ? '
301 'g_lazy_instance.Get().schemas[name] : "";')
304 c
.Append('// static')
305 c
.Sblock('bool GeneratedSchemas::IsGenerated(std::string name) {')
306 c
.Append('return g_lazy_instance.Get().schemas.count(name) > 0;')
309 c
.Concat(cpp_util
.CloseNamespace(self
._bundle
._cpp
_namespace
))