cpp_bundle_generator.py revision c2e0dbddbe15c98d52c4786dac06cb8952a8ae6d
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('// Puts all API schemas in |schemas|.') 219 c.Append('static void Get(' 220 'std::map<std::string, base::StringPiece>* schemas);') 221 c.Eblock('};'); 222 c.Append() 223 c.Concat(cpp_util.CloseNamespace(self._bundle._cpp_namespace)) 224 return self._bundle._GenerateHeader('generated_schemas', c) 225 226class _SchemasCCGenerator(object): 227 """Generates a code.Code object for the generated schemas .cc file""" 228 229 def __init__(self, cpp_bundle): 230 self._bundle = cpp_bundle 231 232 def Generate(self, namespace): 233 c = code.Code() 234 c.Append(cpp_util.CHROMIUM_LICENSE) 235 c.Append() 236 c.Append('#include "%s"' % (os.path.join(SOURCE_BASE_PATH, 237 'generated_schemas.h'))) 238 c.Append() 239 c.Concat(cpp_util.OpenNamespace(self._bundle._cpp_namespace)) 240 c.Append() 241 c.Append('// static') 242 c.Sblock('void GeneratedSchemas::Get(' 243 'std::map<std::string, base::StringPiece>* schemas) {') 244 for api in self._bundle._api_defs: 245 namespace = self._bundle._model.namespaces[api.get('namespace')] 246 # JSON parsing code expects lists of schemas, so dump a singleton list. 247 json_content = json.dumps([_RemoveDescriptions(api)], 248 separators=(',', ':')) 249 # Escape all double-quotes and backslashes. For this to output a valid 250 # JSON C string, we need to escape \ and ". 251 json_content = json_content.replace('\\', '\\\\').replace('"', '\\"') 252 c.Append('(*schemas)["%s"] = "%s";' % (namespace.name, json_content)) 253 c.Eblock('}') 254 c.Append() 255 c.Concat(cpp_util.CloseNamespace(self._bundle._cpp_namespace)) 256 c.Append() 257 return c 258