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.
6 from model import PropertyType
10 class HGenerator(object):
11 def __init__(self, type_generator, cpp_namespace):
12 self._type_generator = type_generator
13 self._cpp_namespace = cpp_namespace
15 def Generate(self, namespace):
16 return _Generator(namespace,
18 self._cpp_namespace).Generate()
21 class _Generator(object):
22 """A .h generator for a namespace.
24 def __init__(self, namespace, cpp_type_generator, cpp_namespace):
25 self._namespace = namespace
26 self._type_helper = cpp_type_generator
27 self._cpp_namespace = cpp_namespace
28 self._target_namespace = (
29 self._type_helper.GetCppNamespaceName(self._namespace))
30 self._generate_error_messages = namespace.compiler_options.get(
31 'generate_error_messages', False)
34 """Generates a Code object with the .h for a single namespace.
37 (c.Append(cpp_util.CHROMIUM_LICENSE)
39 .Append(cpp_util.GENERATED_FILE_MESSAGE % self._namespace.source_file)
43 ifndef_name = cpp_util.GenerateIfndefName(self._namespace.source_file_dir,
44 self._target_namespace)
45 (c.Append('#ifndef %s' % ifndef_name)
46 .Append('#define %s' % ifndef_name)
48 .Append('#include <map>')
49 .Append('#include <string>')
50 .Append('#include <vector>')
52 .Append('#include "base/basictypes.h"')
53 .Append('#include "base/logging.h"')
54 .Append('#include "base/memory/linked_ptr.h"')
55 .Append('#include "base/memory/scoped_ptr.h"')
56 .Append('#include "base/values.h"')
57 .Cblock(self._type_helper.GenerateIncludes())
61 c.Concat(cpp_util.OpenNamespace(self._cpp_namespace))
62 # TODO(calamity): These forward declarations should be #includes to allow
63 # $ref types from other files to be used as required params. This requires
64 # some detangling of windows and tabs which will currently lead to circular
66 forward_declarations = (
67 self._type_helper.GenerateForwardDeclarations())
68 if not forward_declarations.IsEmpty():
70 .Cblock(forward_declarations)
73 c.Concat(self._type_helper.GetNamespaceStart())
75 if self._namespace.properties:
77 .Append('// Properties')
81 for property in self._namespace.properties.values():
82 property_code = self._type_helper.GeneratePropertyValues(
84 'extern const %(type)s %(name)s;')
86 c.Cblock(property_code)
87 if self._namespace.types:
92 .Cblock(self._GenerateTypes(self._FieldDependencyOrder(),
94 generate_typedefs=True))
96 if self._namespace.functions:
98 .Append('// Functions')
102 for function in self._namespace.functions.values():
103 c.Cblock(self._GenerateFunction(function))
104 if self._namespace.events:
110 for event in self._namespace.events.values():
111 c.Cblock(self._GenerateEvent(event))
112 (c.Concat(self._type_helper.GetNamespaceEnd())
113 .Concat(cpp_util.CloseNamespace(self._cpp_namespace))
114 .Append('#endif // %s' % ifndef_name)
119 def _FieldDependencyOrder(self):
120 """Generates the list of types in the current namespace in an order in which
121 depended-upon types appear before types which depend on them.
123 dependency_order = []
125 def ExpandType(path, type_):
127 raise ValueError("Illegal circular dependency via cycle " +
128 ", ".join(map(lambda x: x.name, path + [type_])))
129 for prop in type_.properties.values():
130 if (prop.type_ == PropertyType.REF and
131 schema_util.GetNamespace(prop.ref_type) == self._namespace.name):
132 ExpandType(path + [type_], self._namespace.types[prop.ref_type])
133 if not type_ in dependency_order:
134 dependency_order.append(type_)
136 for type_ in self._namespace.types.values():
137 ExpandType([], type_)
138 return dependency_order
140 def _GenerateEnumDeclaration(self, enum_name, type_):
141 """Generate a code object with the declaration of a C++ enum.
144 c.Sblock('enum %s {' % enum_name)
145 c.Append(self._type_helper.GetEnumNoneValue(type_) + ',')
146 for value in type_.enum_values:
147 current_enum_string = self._type_helper.GetEnumValue(type_, value)
148 c.Append(current_enum_string + ',')
149 c.Append('%s = %s,' % (
150 self._type_helper.GetEnumLastValue(type_), current_enum_string))
154 def _GenerateFields(self, props):
155 """Generates the field declarations when declaring a type.
158 needs_blank_line = False
162 needs_blank_line = True
164 c.Comment(prop.description)
165 # ANY is a base::Value which is abstract and cannot be a direct member, so
166 # we always need to wrap it in a scoped_ptr.
167 is_ptr = prop.optional or prop.type_.property_type == PropertyType.ANY
168 (c.Append('%s %s;' % (
169 self._type_helper.GetCppType(prop.type_, is_ptr=is_ptr),
174 def _GenerateType(self, type_, is_toplevel=False, generate_typedefs=False):
175 """Generates a struct for |type_|.
177 |is_toplevel| implies that the type was declared in the "types" field
178 of an API schema. This determines the correct function
180 |generate_typedefs| controls whether primitive types should be generated as
181 a typedef. This may not always be desired. If false,
182 primitive types are ignored.
184 classname = cpp_util.Classname(schema_util.StripNamespace(type_.name))
188 # Wrap functions within types in the type's namespace.
189 (c.Append('namespace %s {' % classname)
192 for function in type_.functions.values():
193 c.Cblock(self._GenerateFunction(function))
194 c.Append('} // namespace %s' % classname)
195 elif type_.property_type == PropertyType.ARRAY:
196 if generate_typedefs and type_.description:
197 c.Comment(type_.description)
198 c.Cblock(self._GenerateType(type_.item_type))
199 if generate_typedefs:
200 (c.Append('typedef std::vector<%s > %s;' % (
201 self._type_helper.GetCppType(type_.item_type),
204 elif type_.property_type == PropertyType.STRING:
205 if generate_typedefs:
206 if type_.description:
207 c.Comment(type_.description)
208 c.Append('typedef std::string %(classname)s;')
209 elif type_.property_type == PropertyType.ENUM:
210 if type_.description:
211 c.Comment(type_.description)
212 c.Cblock(self._GenerateEnumDeclaration(classname, type_));
213 # Top level enums are in a namespace scope so the methods shouldn't be
214 # static. On the other hand, those declared inline (e.g. in an object) do.
215 maybe_static = '' if is_toplevel else 'static '
217 .Append('%sstd::string %sToString(%s as_enum);' %
218 (maybe_static, classname, classname))
219 .Append('%sstd::string ToString(%s as_enum);' %
220 (maybe_static, classname))
221 .Append('%s%s Parse%s(const std::string& as_string);' %
222 (maybe_static, classname, classname))
224 elif type_.property_type in (PropertyType.CHOICES,
225 PropertyType.OBJECT):
226 if type_.description:
227 c.Comment(type_.description)
228 (c.Sblock('struct %(classname)s {')
229 .Append('%(classname)s();')
230 .Append('~%(classname)s();')
232 if type_.origin.from_json:
234 .Comment('Populates a %s object from a base::Value. Returns'
235 ' whether |out| was successfully populated.' % classname)
236 .Append('static bool Populate(%s);' % self._GenerateParams(
237 ('const base::Value& value', '%s* out' % classname)))
241 .Comment('Creates a %s object from a base::Value, or NULL on '
242 'failure.' % classname)
243 .Append('static scoped_ptr<%s> FromValue(%s);' % (
244 classname, self._GenerateParams(('const base::Value& value',))))
246 if type_.origin.from_client:
247 value_type = ('base::Value'
248 if type_.property_type is PropertyType.CHOICES else
249 'base::DictionaryValue')
251 .Comment('Returns a new %s representing the serialized form of this '
252 '%s object.' % (value_type, classname))
253 .Append('scoped_ptr<%s> ToValue() const;' % value_type)
255 if type_.property_type == PropertyType.CHOICES:
256 # Choices are modelled with optional fields for each choice. Exactly one
257 # field of the choice is guaranteed to be set by the compiler.
258 c.Cblock(self._GenerateTypes(type_.choices))
259 c.Append('// Choices:')
260 for choice_type in type_.choices:
261 c.Append('%s as_%s;' % (
262 self._type_helper.GetCppType(choice_type, is_ptr=True),
263 choice_type.unix_name))
265 properties = type_.properties.values()
267 .Cblock(self._GenerateTypes(p.type_ for p in properties))
268 .Cblock(self._GenerateFields(properties)))
269 if type_.additional_properties is not None:
270 # Most additionalProperties actually have type "any", which is better
271 # modelled as a DictionaryValue rather than a map of string -> Value.
272 if type_.additional_properties.property_type == PropertyType.ANY:
273 c.Append('base::DictionaryValue additional_properties;')
275 (c.Cblock(self._GenerateType(type_.additional_properties))
276 .Append('std::map<std::string, %s> additional_properties;' %
277 cpp_util.PadForGenerics(
278 self._type_helper.GetCppType(type_.additional_properties,
279 is_in_container=True)))
284 .Append('DISALLOW_COPY_AND_ASSIGN(%(classname)s);')
287 return c.Substitute({'classname': classname})
289 def _GenerateEvent(self, event):
290 """Generates the namespaces for an event.
293 # TODO(kalman): use event.unix_name not Classname.
294 event_namespace = cpp_util.Classname(event.name)
295 (c.Append('namespace %s {' % event_namespace)
297 .Concat(self._GenerateEventNameConstant(event))
298 .Concat(self._GenerateCreateCallbackArguments(event))
299 .Eblock('} // namespace %s' % event_namespace)
303 def _GenerateFunction(self, function):
304 """Generates the namespaces and structs for a function.
307 # TODO(kalman): Use function.unix_name not Classname here.
308 function_namespace = cpp_util.Classname(function.name)
309 # Windows has a #define for SendMessage, so to avoid any issues, we need
310 # to not use the name.
311 if function_namespace == 'SendMessage':
312 function_namespace = 'PassMessage'
313 (c.Append('namespace %s {' % function_namespace)
315 .Cblock(self._GenerateFunctionParams(function))
317 if function.callback:
318 c.Cblock(self._GenerateFunctionResults(function.callback))
319 c.Append('} // namespace %s' % function_namespace)
322 def _GenerateFunctionParams(self, function):
323 """Generates the struct for passing parameters from JSON to a function.
325 if not function.params:
329 (c.Sblock('struct Params {')
330 .Append('static scoped_ptr<Params> Create(%s);' % self._GenerateParams(
331 ('const base::ListValue& args',)))
332 .Append('~Params();')
334 .Cblock(self._GenerateTypes(p.type_ for p in function.params))
335 .Cblock(self._GenerateFields(function.params))
341 .Append('DISALLOW_COPY_AND_ASSIGN(Params);')
346 def _GenerateTypes(self, types, is_toplevel=False, generate_typedefs=False):
347 """Generate the structures required by a property such as OBJECT classes
352 c.Cblock(self._GenerateType(type_,
353 is_toplevel=is_toplevel,
354 generate_typedefs=generate_typedefs))
357 def _GenerateCreateCallbackArguments(self, function):
358 """Generates functions for passing parameters to a callback.
361 params = function.params
362 c.Cblock(self._GenerateTypes((p.type_ for p in params), is_toplevel=True))
364 declaration_list = []
366 if param.description:
367 c.Comment(param.description)
368 declaration_list.append(cpp_util.GetParameterDeclaration(
369 param, self._type_helper.GetCppType(param.type_)))
370 c.Append('scoped_ptr<base::ListValue> Create(%s);' %
371 ', '.join(declaration_list))
374 def _GenerateEventNameConstant(self, event):
375 """Generates a constant string array for the event name.
378 c.Append('extern const char kEventName[]; // "%s.%s"' % (
379 self._namespace.name, event.name))
383 def _GenerateFunctionResults(self, callback):
384 """Generates namespace for passing a function's result back.
387 (c.Append('namespace Results {')
389 .Concat(self._GenerateCreateCallbackArguments(callback))
390 .Append('} // namespace Results')
394 def _GenerateParams(self, params):
395 """Builds the parameter list for a function, given an array of parameters.
397 # |error| is populated with warnings and/or errors found during parsing.
398 # |error| being set does not necessarily imply failure and may be
400 # For example, optional properties may have failed to parse, but the
401 # parser was able to continue.
402 if self._generate_error_messages:
403 params += ('base::string16* error',)
404 return ', '.join(str(p) for p in params)