cpp_type_generator.py revision 2a99a7e74a7f215066514fe81d2bfa6639d9eddd
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 5from code import Code 6from model import Namespace, PropertyType, Type 7import cpp_util 8from json_parse import OrderedDict 9from operator import attrgetter 10import schema_util 11 12class _TypeDependency(object): 13 """Contains information about a dependency a namespace has on a type: the 14 type's model, and whether that dependency is "hard" meaning that it cannot be 15 forward declared. 16 """ 17 def __init__(self, type_, hard=False): 18 self.type_ = type_ 19 self.hard = hard 20 21 def GetSortKey(self): 22 return '%s.%s' % (self.type_.namespace.name, self.type_.name) 23 24class CppTypeGenerator(object): 25 """Manages the types of properties and provides utilities for getting the 26 C++ type out of a model.Property 27 """ 28 def __init__(self, model, schema_loader, default_namespace=None): 29 """Creates a cpp_type_generator. The given root_namespace should be of the 30 format extensions::api::sub. The generator will generate code suitable for 31 use in the given model's namespace. 32 """ 33 self._default_namespace = default_namespace 34 if self._default_namespace is None: 35 self._default_namespace = model.namespaces.values()[0] 36 self._schema_loader = schema_loader 37 38 def GetCppNamespaceName(self, namespace): 39 """Gets the mapped C++ namespace name for the given namespace relative to 40 the root namespace. 41 """ 42 return namespace.unix_name 43 44 def GetNamespaceStart(self): 45 """Get opening self._default_namespace namespace declaration. 46 """ 47 return Code().Append('namespace %s {' % 48 self.GetCppNamespaceName(self._default_namespace)) 49 50 def GetNamespaceEnd(self): 51 """Get closing self._default_namespace namespace declaration. 52 """ 53 return Code().Append('} // %s' % 54 self.GetCppNamespaceName(self._default_namespace)) 55 56 def GetEnumNoneValue(self, type_): 57 """Gets the enum value in the given model.Property indicating no value has 58 been set. 59 """ 60 return '%s_NONE' % self.FollowRef(type_).unix_name.upper() 61 62 def GetEnumValue(self, type_, enum_value): 63 """Gets the enum value of the given model.Property of the given type. 64 65 e.g VAR_STRING 66 """ 67 return '%s_%s' % (self.FollowRef(type_).unix_name.upper(), 68 cpp_util.Classname(enum_value.upper())) 69 70 def GetCppType(self, type_, is_ptr=False, is_in_container=False): 71 """Translates a model.Property or model.Type into its C++ type. 72 73 If REF types from different namespaces are referenced, will resolve 74 using self._schema_loader. 75 76 Use |is_ptr| if the type is optional. This will wrap the type in a 77 scoped_ptr if possible (it is not possible to wrap an enum). 78 79 Use |is_in_container| if the type is appearing in a collection, e.g. a 80 std::vector or std::map. This will wrap it in the correct type with spacing. 81 """ 82 cpp_type = None 83 if type_.property_type == PropertyType.REF: 84 ref_type = self._FindType(type_.ref_type) 85 if ref_type is None: 86 raise KeyError('Cannot find referenced type: %s' % type_.ref_type) 87 if self._default_namespace is ref_type.namespace: 88 cpp_type = ref_type.name 89 else: 90 cpp_type = '%s::%s' % (ref_type.namespace.unix_name, ref_type.name) 91 elif type_.property_type == PropertyType.BOOLEAN: 92 cpp_type = 'bool' 93 elif type_.property_type == PropertyType.INTEGER: 94 cpp_type = 'int' 95 elif type_.property_type == PropertyType.INT64: 96 cpp_type = 'int64' 97 elif type_.property_type == PropertyType.DOUBLE: 98 cpp_type = 'double' 99 elif type_.property_type == PropertyType.STRING: 100 cpp_type = 'std::string' 101 elif type_.property_type == PropertyType.ENUM: 102 cpp_type = cpp_util.Classname(type_.name) 103 elif type_.property_type == PropertyType.ANY: 104 cpp_type = 'base::Value' 105 elif (type_.property_type == PropertyType.OBJECT or 106 type_.property_type == PropertyType.CHOICES): 107 cpp_type = cpp_util.Classname(type_.name) 108 elif type_.property_type == PropertyType.FUNCTION: 109 # Functions come into the json schema compiler as empty objects. We can 110 # record these as empty DictionaryValues so that we know if the function 111 # was passed in or not. 112 cpp_type = 'base::DictionaryValue' 113 elif type_.property_type == PropertyType.ARRAY: 114 item_cpp_type = self.GetCppType(type_.item_type, is_in_container=True) 115 cpp_type = 'std::vector<%s>' % cpp_util.PadForGenerics(item_cpp_type) 116 elif type_.property_type == PropertyType.BINARY: 117 cpp_type = 'std::string' 118 else: 119 raise NotImplementedError('Cannot get type of %s' % type_.property_type) 120 121 # HACK: optional ENUM is represented elsewhere with a _NONE value, so it 122 # never needs to be wrapped in pointer shenanigans. 123 # TODO(kalman): change this - but it's an exceedingly far-reaching change. 124 if not self.FollowRef(type_).property_type == PropertyType.ENUM: 125 if is_in_container and (is_ptr or not self.IsCopyable(type_)): 126 cpp_type = 'linked_ptr<%s>' % cpp_util.PadForGenerics(cpp_type) 127 elif is_ptr: 128 cpp_type = 'scoped_ptr<%s>' % cpp_util.PadForGenerics(cpp_type) 129 130 return cpp_type 131 132 def IsCopyable(self, type_): 133 return not (self.FollowRef(type_).property_type in (PropertyType.ANY, 134 PropertyType.ARRAY, 135 PropertyType.OBJECT, 136 PropertyType.CHOICES)) 137 138 def GenerateForwardDeclarations(self): 139 """Returns the forward declarations for self._default_namespace. 140 """ 141 c = Code() 142 143 for namespace, dependencies in self._NamespaceTypeDependencies().items(): 144 c.Append('namespace %s {' % namespace.unix_name) 145 for dependency in dependencies: 146 # No point forward-declaring hard dependencies. 147 if dependency.hard: 148 continue 149 # Add more ways to forward declare things as necessary. 150 if dependency.type_.property_type == PropertyType.OBJECT: 151 c.Append('struct %s;' % dependency.type_.name) 152 c.Append('}') 153 154 return c 155 156 def GenerateIncludes(self, include_soft=False): 157 """Returns the #include lines for self._default_namespace. 158 """ 159 c = Code() 160 for namespace, dependencies in self._NamespaceTypeDependencies().items(): 161 for dependency in dependencies: 162 if dependency.hard or include_soft: 163 c.Append('#include "%s/%s.h"' % (namespace.source_file_dir, 164 namespace.unix_name)) 165 return c 166 167 def _FindType(self, full_name): 168 """Finds the model.Type with name |qualified_name|. If it's not from 169 |self._default_namespace| then it needs to be qualified. 170 """ 171 namespace = self._schema_loader.ResolveType(full_name, 172 self._default_namespace) 173 if namespace is None: 174 raise KeyError('Cannot resolve type %s. Maybe it needs a prefix ' 175 'if it comes from another namespace?' % full_name) 176 return namespace.types[schema_util.StripNamespace(full_name)] 177 178 def FollowRef(self, type_): 179 """Follows $ref link of types to resolve the concrete type a ref refers to. 180 181 If the property passed in is not of type PropertyType.REF, it will be 182 returned unchanged. 183 """ 184 if type_.property_type != PropertyType.REF: 185 return type_ 186 return self.FollowRef(self._FindType(type_.ref_type)) 187 188 def _NamespaceTypeDependencies(self): 189 """Returns a dict ordered by namespace name containing a mapping of 190 model.Namespace to every _TypeDependency for |self._default_namespace|, 191 sorted by the type's name. 192 """ 193 dependencies = set() 194 for function in self._default_namespace.functions.values(): 195 for param in function.params: 196 dependencies |= self._TypeDependencies(param.type_, 197 hard=not param.optional) 198 if function.callback: 199 for param in function.callback.params: 200 dependencies |= self._TypeDependencies(param.type_, 201 hard=not param.optional) 202 for type_ in self._default_namespace.types.values(): 203 for prop in type_.properties.values(): 204 dependencies |= self._TypeDependencies(prop.type_, 205 hard=not prop.optional) 206 for event in self._default_namespace.events.values(): 207 for param in event.params: 208 dependencies |= self._TypeDependencies(param.type_, 209 hard=not param.optional) 210 211 # Make sure that the dependencies are returned in alphabetical order. 212 dependency_namespaces = OrderedDict() 213 for dependency in sorted(dependencies, key=_TypeDependency.GetSortKey): 214 namespace = dependency.type_.namespace 215 if namespace is self._default_namespace: 216 continue 217 if namespace not in dependency_namespaces: 218 dependency_namespaces[namespace] = [] 219 dependency_namespaces[namespace].append(dependency) 220 221 return dependency_namespaces 222 223 def _TypeDependencies(self, type_, hard=False): 224 """Gets all the type dependencies of a property. 225 """ 226 deps = set() 227 if type_.property_type == PropertyType.REF: 228 deps.add(_TypeDependency(self._FindType(type_.ref_type), hard=hard)) 229 elif type_.property_type == PropertyType.ARRAY: 230 # Non-copyable types are not hard because they are wrapped in linked_ptrs 231 # when generated. Otherwise they're typedefs, so they're hard (though we 232 # could generate those typedefs in every dependent namespace, but that 233 # seems weird). 234 deps = self._TypeDependencies(type_.item_type, 235 hard=self.IsCopyable(type_.item_type)) 236 elif type_.property_type == PropertyType.CHOICES: 237 for type_ in type_.choices: 238 deps |= self._TypeDependencies(type_, hard=self.IsCopyable(type_)) 239 elif type_.property_type == PropertyType.OBJECT: 240 for p in type_.properties.values(): 241 deps |= self._TypeDependencies(p.type_, hard=not p.optional) 242 return deps 243 244 def GeneratePropertyValues(self, property, line, nodoc=False): 245 """Generates the Code to display all value-containing properties. 246 """ 247 c = Code() 248 if not nodoc: 249 c.Comment(property.description) 250 251 if property.value is not None: 252 c.Append(line % { 253 "type": self.GetCppType(property.type_), 254 "name": property.name, 255 "value": property.value 256 }) 257 else: 258 has_child_code = False 259 c.Sblock('namespace %s {' % property.name) 260 for child_property in property.type_.properties.values(): 261 child_code = self.GeneratePropertyValues(child_property, 262 line, 263 nodoc=nodoc) 264 if child_code: 265 has_child_code = True 266 c.Concat(child_code) 267 c.Eblock('} // namespace %s' % property.name) 268 if not has_child_code: 269 c = None 270 return c 271