cpp_bundle_generator.py revision 7d4cd473f85ac64c3747c96c277f9e506a0d2246
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. 4 5import code 6import cpp_util 7from model import Platforms 8from schema_util import CapitalizeFirstLetter 9from schema_util import JsFunctionNameToClassName 10 11import json 12import os 13import re 14 15# TODO(miket/asargent) - parameterize this. 16SOURCE_BASE_PATH = 'chrome/common/extensions/api' 17 18def _RemoveDescriptions(node): 19 """Returns a copy of |schema| with "description" fields removed. 20 """ 21 if isinstance(node, dict): 22 result = {} 23 for key, value in node.items(): 24 # Some schemas actually have properties called "description", so only 25 # remove descriptions that have string values. 26 if key == 'description' and isinstance(value, basestring): 27 continue 28 result[key] = _RemoveDescriptions(value) 29 return result 30 if isinstance(node, list): 31 return [_RemoveDescriptions(v) for v in node] 32 return node 33 34class CppBundleGenerator(object): 35 """This class contains methods to generate code based on multiple schemas. 36 """ 37 38 def __init__(self, root, model, api_defs, cpp_type_generator, cpp_namespace): 39 self._root = root; 40 self._model = model 41 self._api_defs = api_defs 42 self._cpp_type_generator = cpp_type_generator 43 self._cpp_namespace = cpp_namespace 44 45 self.api_cc_generator = _APICCGenerator(self) 46 self.api_h_generator = _APIHGenerator(self) 47 self.schemas_cc_generator = _SchemasCCGenerator(self) 48 self.schemas_h_generator = _SchemasHGenerator(self) 49 50 def _GenerateHeader(self, file_base, body_code): 51 """Generates a code.Code object for a header file 52 53 Parameters: 54 - |file_base| - the base of the filename, e.g. 'foo' (for 'foo.h') 55 - |body_code| - the code to put in between the multiple inclusion guards""" 56 c = code.Code() 57 c.Append(cpp_util.CHROMIUM_LICENSE) 58 c.Append() 59 c.Append(cpp_util.GENERATED_BUNDLE_FILE_MESSAGE % SOURCE_BASE_PATH) 60 ifndef_name = cpp_util.GenerateIfndefName(SOURCE_BASE_PATH, file_base) 61 c.Append() 62 c.Append('#ifndef %s' % ifndef_name) 63 c.Append('#define %s' % ifndef_name) 64 c.Append() 65 c.Concat(body_code) 66 c.Append() 67 c.Append('#endif // %s' % ifndef_name) 68 c.Append() 69 return c 70 71 def _GetPlatformIfdefs(self, model_object): 72 """Generates the "defined" conditional for an #if check if |model_object| 73 has platform restrictions. Returns None if there are no restrictions. 74 """ 75 if model_object.platforms is None: 76 return None 77 ifdefs = [] 78 for platform in model_object.platforms: 79 if platform == Platforms.CHROMEOS: 80 ifdefs.append('defined(OS_CHROMEOS)') 81 else: 82 raise ValueError("Unsupported platform ifdef: %s" % platform.name) 83 return ' and '.join(ifdefs) 84 85 def _GenerateRegisterFunctions(self, namespace_name, function): 86 c = code.Code() 87 function_ifdefs = self._GetPlatformIfdefs(function) 88 if function_ifdefs is not None: 89 c.Append("#if %s" % function_ifdefs, indent_level=0) 90 91 function_name = JsFunctionNameToClassName(namespace_name, function.name) 92 c.Append("registry->RegisterFunction<%sFunction>();" % ( 93 function_name)) 94 95 if function_ifdefs is not None: 96 c.Append("#endif // %s" % function_ifdefs, indent_level=0) 97 return c 98 99 def _GenerateFunctionRegistryRegisterAll(self): 100 c = code.Code() 101 c.Append('// static') 102 c.Sblock('void GeneratedFunctionRegistry::RegisterAll(' 103 'ExtensionFunctionRegistry* registry) {') 104 for namespace in self._model.namespaces.values(): 105 namespace_ifdefs = self._GetPlatformIfdefs(namespace) 106 if namespace_ifdefs is not None: 107 c.Append("#if %s" % namespace_ifdefs, indent_level=0) 108 109 namespace_name = CapitalizeFirstLetter(namespace.name.replace( 110 "experimental.", "")) 111 for function in namespace.functions.values(): 112 if function.nocompile: 113 continue 114 c.Concat(self._GenerateRegisterFunctions(namespace.name, function)) 115 116 for type_ in namespace.types.values(): 117 for function in type_.functions.values(): 118 if function.nocompile: 119 continue 120 namespace_types_name = JsFunctionNameToClassName( 121 namespace.name, type_.name) 122 c.Concat(self._GenerateRegisterFunctions(namespace_types_name, 123 function)) 124 125 if namespace_ifdefs is not None: 126 c.Append("#endif // %s" % namespace_ifdefs, indent_level=0) 127 c.Eblock("}") 128 return c 129 130class _APIHGenerator(object): 131 """Generates the header for API registration / declaration""" 132 def __init__(self, cpp_bundle): 133 self._bundle = cpp_bundle 134 135 def Generate(self, namespace): 136 c = code.Code() 137 138 c.Append('#include <string>') 139 c.Append() 140 c.Append('#include "base/basictypes.h"') 141 c.Append() 142 c.Append("class ExtensionFunctionRegistry;") 143 c.Append() 144 c.Concat(cpp_util.OpenNamespace(self._bundle._cpp_namespace)) 145 c.Append() 146 c.Append('class GeneratedFunctionRegistry {') 147 c.Sblock(' public:') 148 c.Append('static void RegisterAll(' 149 'ExtensionFunctionRegistry* registry);') 150 c.Eblock('};'); 151 c.Append() 152 c.Concat(cpp_util.CloseNamespace(self._bundle._cpp_namespace)) 153 return self._bundle._GenerateHeader('generated_api', c) 154 155class _APICCGenerator(object): 156 """Generates a code.Code object for the generated API .cc file""" 157 158 def __init__(self, cpp_bundle): 159 self._bundle = cpp_bundle 160 161 def Generate(self, namespace): 162 c = code.Code() 163 c.Append(cpp_util.CHROMIUM_LICENSE) 164 c.Append() 165 c.Append('#include "%s"' % (os.path.join(SOURCE_BASE_PATH, 166 'generated_api.h'))) 167 c.Append() 168 for namespace in self._bundle._model.namespaces.values(): 169 namespace_name = namespace.unix_name.replace("experimental_", "") 170 implementation_header = namespace.compiler_options.get( 171 "implemented_in", 172 "chrome/browser/extensions/api/%s/%s_api.h" % (namespace_name, 173 namespace_name)) 174 if not os.path.exists( 175 os.path.join(self._bundle._root, 176 os.path.normpath(implementation_header))): 177 if "implemented_in" in namespace.compiler_options: 178 raise ValueError('Header file for namespace "%s" specified in ' 179 'compiler_options not found: %s' % 180 (namespace.unix_name, implementation_header)) 181 continue 182 ifdefs = self._bundle._GetPlatformIfdefs(namespace) 183 if ifdefs is not None: 184 c.Append("#if %s" % ifdefs, indent_level=0) 185 186 c.Append('#include "%s"' % implementation_header) 187 188 if ifdefs is not None: 189 c.Append("#endif // %s" % ifdefs, indent_level=0) 190 c.Append() 191 c.Append('#include ' 192 '"chrome/browser/extensions/extension_function_registry.h"') 193 c.Append() 194 c.Concat(cpp_util.OpenNamespace(self._bundle._cpp_namespace)) 195 c.Append() 196 c.Concat(self._bundle._GenerateFunctionRegistryRegisterAll()) 197 c.Append() 198 c.Concat(cpp_util.CloseNamespace(self._bundle._cpp_namespace)) 199 c.Append() 200 return c 201 202class _SchemasHGenerator(object): 203 """Generates a code.Code object for the generated schemas .h file""" 204 def __init__(self, cpp_bundle): 205 self._bundle = cpp_bundle 206 207 def Generate(self, namespace): 208 c = code.Code() 209 c.Append('#include <map>') 210 c.Append('#include <string>') 211 c.Append(); 212 c.Append('#include "base/strings/string_piece.h"') 213 c.Append() 214 c.Concat(cpp_util.OpenNamespace(self._bundle._cpp_namespace)) 215 c.Append() 216 c.Append('class GeneratedSchemas {') 217 c.Sblock(' public:') 218 c.Append('// Determines if schema named |name| is generated.') 219 c.Append('static bool IsGenerated(std::string name);') 220 c.Append() 221 c.Append('// Gets the API schema named |name|.') 222 c.Append('static base::StringPiece Get(const std::string& name);') 223 c.Eblock('};'); 224 c.Append() 225 c.Concat(cpp_util.CloseNamespace(self._bundle._cpp_namespace)) 226 return self._bundle._GenerateHeader('generated_schemas', c) 227 228def _FormatNameAsConstant(name): 229 """Formats a name to be a C++ constant of the form kConstantName""" 230 name = '%s%s' % (name[0].upper(), name[1:]) 231 return 'k%s' % re.sub('_[a-z]', 232 lambda m: m.group(0)[1].upper(), 233 name.replace('.', '_')) 234 235class _SchemasCCGenerator(object): 236 """Generates a code.Code object for the generated schemas .cc file""" 237 238 def __init__(self, cpp_bundle): 239 self._bundle = cpp_bundle 240 241 def Generate(self, namespace): 242 c = code.Code() 243 c.Append(cpp_util.CHROMIUM_LICENSE) 244 c.Append() 245 c.Append('#include "%s"' % (os.path.join(SOURCE_BASE_PATH, 246 'generated_schemas.h'))) 247 c.Append() 248 c.Append('#include "base/lazy_instance.h"') 249 c.Append() 250 c.Append('namespace {') 251 for api in self._bundle._api_defs: 252 namespace = self._bundle._model.namespaces[api.get('namespace')] 253 # JSON parsing code expects lists of schemas, so dump a singleton list. 254 json_content = json.dumps([_RemoveDescriptions(api)], 255 separators=(',', ':')) 256 # Escape all double-quotes and backslashes. For this to output a valid 257 # JSON C string, we need to escape \ and ". 258 json_content = json_content.replace('\\', '\\\\').replace('"', '\\"') 259 c.Append('const char %s[] = "%s";' % 260 (_FormatNameAsConstant(namespace.name), json_content)) 261 c.Append('}') 262 c.Concat(cpp_util.OpenNamespace(self._bundle._cpp_namespace)) 263 c.Append() 264 c.Sblock('struct Static {') 265 c.Sblock('Static() {') 266 for api in self._bundle._api_defs: 267 namespace = self._bundle._model.namespaces[api.get('namespace')] 268 c.Append('schemas["%s"] = %s;' % (namespace.name, 269 _FormatNameAsConstant(namespace.name))) 270 c.Eblock('}'); 271 c.Append() 272 c.Append('std::map<std::string, const char*> schemas;') 273 c.Eblock('};'); 274 c.Append() 275 c.Append('base::LazyInstance<Static> g_lazy_instance;') 276 c.Append() 277 c.Append('// static') 278 c.Sblock('base::StringPiece GeneratedSchemas::Get(' 279 'const std::string& name) {') 280 c.Append('return IsGenerated(name) ? ' 281 'g_lazy_instance.Get().schemas[name] : "";') 282 c.Eblock('}') 283 c.Append() 284 c.Append('// static') 285 c.Sblock('bool GeneratedSchemas::IsGenerated(std::string name) {') 286 c.Append('return g_lazy_instance.Get().schemas.count(name) > 0;') 287 c.Eblock('}') 288 c.Append() 289 c.Concat(cpp_util.CloseNamespace(self._bundle._cpp_namespace)) 290 c.Append() 291 return c 292