Merge Chromium + Blink git repositories
[chromium-blink-merge.git] / tools / json_schema_compiler / h_generator.py
blob0035f7f66410fbb6fccf7dc547151b5a1205abf3
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.
5 import os
7 from code import Code
8 from model import PropertyType
9 import cpp_util
10 import schema_util
12 class HGenerator(object):
13 def __init__(self, type_generator):
14 self._type_generator = type_generator
16 def Generate(self, namespace):
17 return _Generator(namespace, self._type_generator).Generate()
20 class _Generator(object):
21 """A .h generator for a namespace.
22 """
23 def __init__(self, namespace, cpp_type_generator):
24 self._namespace = namespace
25 self._type_helper = cpp_type_generator
26 self._generate_error_messages = namespace.compiler_options.get(
27 'generate_error_messages', False)
29 def Generate(self):
30 """Generates a Code object with the .h for a single namespace.
31 """
32 c = Code()
33 (c.Append(cpp_util.CHROMIUM_LICENSE)
34 .Append()
35 .Append(cpp_util.GENERATED_FILE_MESSAGE % self._namespace.source_file)
36 .Append()
39 # Hack: for the purpose of gyp the header file will always be the source
40 # file with its file extension replaced by '.h'. Assume so.
41 output_file = os.path.splitext(self._namespace.source_file)[0] + '.h'
42 ifndef_name = cpp_util.GenerateIfndefName(output_file)
44 # Hack: tabs and windows have circular references, so only generate hard
45 # references for them (i.e. anything that can't be forward declared). In
46 # other cases, generate soft dependencies so that they can include
47 # non-optional types from other namespaces.
48 include_soft = self._namespace.name not in ('tabs', 'windows')
50 (c.Append('#ifndef %s' % ifndef_name)
51 .Append('#define %s' % ifndef_name)
52 .Append()
53 .Append('#include <map>')
54 .Append('#include <string>')
55 .Append('#include <vector>')
56 .Append()
57 .Append('#include "base/basictypes.h"')
58 .Append('#include "base/logging.h"')
59 .Append('#include "base/memory/linked_ptr.h"')
60 .Append('#include "base/memory/scoped_ptr.h"')
61 .Append('#include "base/values.h"')
62 .Cblock(self._type_helper.GenerateIncludes(include_soft=include_soft))
63 .Append()
66 # Hack: we're not generating soft includes for tabs and windows, so we need
67 # to generate forward declarations for them.
68 if not include_soft:
69 c.Cblock(self._type_helper.GenerateForwardDeclarations())
71 cpp_namespace = cpp_util.GetCppNamespace(
72 self._namespace.environment.namespace_pattern,
73 self._namespace.unix_name)
74 c.Concat(cpp_util.OpenNamespace(cpp_namespace))
75 c.Append()
76 if self._namespace.properties:
77 (c.Append('//')
78 .Append('// Properties')
79 .Append('//')
80 .Append()
82 for prop in self._namespace.properties.values():
83 property_code = self._type_helper.GeneratePropertyValues(
84 prop,
85 'extern const %(type)s %(name)s;')
86 if property_code:
87 c.Cblock(property_code)
88 if self._namespace.types:
89 (c.Append('//')
90 .Append('// Types')
91 .Append('//')
92 .Append()
93 .Cblock(self._GenerateTypes(self._FieldDependencyOrder(),
94 is_toplevel=True,
95 generate_typedefs=True))
97 if self._namespace.functions:
98 (c.Append('//')
99 .Append('// Functions')
100 .Append('//')
101 .Append()
103 for function in self._namespace.functions.values():
104 c.Cblock(self._GenerateFunction(function))
105 if self._namespace.events:
106 (c.Append('//')
107 .Append('// Events')
108 .Append('//')
109 .Append()
111 for event in self._namespace.events.values():
112 c.Cblock(self._GenerateEvent(event))
113 (c.Concat(cpp_util.CloseNamespace(cpp_namespace))
114 .Append('#endif // %s' % ifndef_name)
115 .Append()
117 return c
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_):
126 if type_ in path:
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.
143 c = Code()
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))
151 c.Eblock('};')
152 return c
154 def _GenerateFields(self, props):
155 """Generates the field declarations when declaring a type.
157 c = Code()
158 needs_blank_line = False
159 for prop in props:
160 if needs_blank_line:
161 c.Append()
162 needs_blank_line = True
163 if prop.description:
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),
170 prop.unix_name))
172 return c
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
179 modifier(s).
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))
185 c = Code()
187 if type_.functions:
188 # Wrap functions within types in the type's namespace.
189 (c.Append('namespace %s {' % classname)
190 .Append()
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, is_toplevel=is_toplevel))
199 if generate_typedefs:
200 (c.Append('typedef std::vector<%s > %s;' % (
201 self._type_helper.GetCppType(type_.item_type),
202 classname))
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 '
216 (c.Append()
217 .Append('%sstd::string ToString(%s as_enum);' %
218 (maybe_static, classname))
219 .Append('%s%s Parse%s(const std::string& as_string);' %
220 (maybe_static, classname, classname))
222 elif type_.property_type in (PropertyType.CHOICES,
223 PropertyType.OBJECT):
224 if type_.description:
225 c.Comment(type_.description)
226 (c.Sblock('struct %(classname)s {')
227 .Append('%(classname)s();')
228 .Append('~%(classname)s();')
230 if type_.origin.from_json:
231 (c.Append()
232 .Comment('Populates a %s object from a base::Value. Returns'
233 ' whether |out| was successfully populated.' % classname)
234 .Append('static bool Populate(%s);' % self._GenerateParams(
235 ('const base::Value& value', '%s* out' % classname)))
237 if is_toplevel:
238 (c.Append()
239 .Comment('Creates a %s object from a base::Value, or NULL on '
240 'failure.' % classname)
241 .Append('static scoped_ptr<%s> FromValue(%s);' % (
242 classname, self._GenerateParams(('const base::Value& value',))))
244 if type_.origin.from_client:
245 value_type = ('base::Value'
246 if type_.property_type is PropertyType.CHOICES else
247 'base::DictionaryValue')
248 (c.Append()
249 .Comment('Returns a new %s representing the serialized form of this '
250 '%s object.' % (value_type, classname))
251 .Append('scoped_ptr<%s> ToValue() const;' % value_type)
253 if type_.property_type == PropertyType.CHOICES:
254 # Choices are modelled with optional fields for each choice. Exactly one
255 # field of the choice is guaranteed to be set by the compiler.
256 c.Cblock(self._GenerateTypes(type_.choices))
257 c.Append('// Choices:')
258 for choice_type in type_.choices:
259 c.Append('%s as_%s;' % (
260 self._type_helper.GetCppType(choice_type, is_ptr=True),
261 choice_type.unix_name))
262 else:
263 properties = type_.properties.values()
264 (c.Append()
265 .Cblock(self._GenerateTypes(p.type_ for p in properties))
266 .Cblock(self._GenerateFields(properties)))
267 if type_.additional_properties is not None:
268 # Most additionalProperties actually have type "any", which is better
269 # modelled as a DictionaryValue rather than a map of string -> Value.
270 if type_.additional_properties.property_type == PropertyType.ANY:
271 c.Append('base::DictionaryValue additional_properties;')
272 else:
273 (c.Cblock(self._GenerateType(type_.additional_properties))
274 .Append('std::map<std::string, %s> additional_properties;' %
275 cpp_util.PadForGenerics(
276 self._type_helper.GetCppType(type_.additional_properties,
277 is_in_container=True)))
279 (c.Eblock()
280 .Append()
281 .Sblock(' private:')
282 .Append('DISALLOW_COPY_AND_ASSIGN(%(classname)s);')
283 .Eblock('};')
285 return c.Substitute({'classname': classname})
287 def _GenerateEvent(self, event):
288 """Generates the namespaces for an event.
290 c = Code()
291 # TODO(kalman): use event.unix_name not Classname.
292 event_namespace = cpp_util.Classname(event.name)
293 (c.Append('namespace %s {' % event_namespace)
294 .Append()
295 .Concat(self._GenerateEventNameConstant(event))
296 .Concat(self._GenerateCreateCallbackArguments(event))
297 .Append('} // namespace %s' % event_namespace)
299 return c
301 def _GenerateFunction(self, function):
302 """Generates the namespaces and structs for a function.
304 c = Code()
305 # TODO(kalman): Use function.unix_name not Classname here.
306 function_namespace = cpp_util.Classname(function.name)
307 # Windows has a #define for SendMessage, so to avoid any issues, we need
308 # to not use the name.
309 if function_namespace == 'SendMessage':
310 function_namespace = 'PassMessage'
311 (c.Append('namespace %s {' % function_namespace)
312 .Append()
313 .Cblock(self._GenerateFunctionParams(function))
315 if function.callback:
316 c.Cblock(self._GenerateFunctionResults(function.callback))
317 c.Append('} // namespace %s' % function_namespace)
318 return c
320 def _GenerateFunctionParams(self, function):
321 """Generates the struct for passing parameters from JSON to a function.
323 if not function.params:
324 return Code()
326 c = Code()
327 (c.Sblock('struct Params {')
328 .Append('static scoped_ptr<Params> Create(%s);' % self._GenerateParams(
329 ('const base::ListValue& args',)))
330 .Append('~Params();')
331 .Append()
332 .Cblock(self._GenerateTypes(p.type_ for p in function.params))
333 .Cblock(self._GenerateFields(function.params))
334 .Eblock()
335 .Append()
336 .Sblock(' private:')
337 .Append('Params();')
338 .Append()
339 .Append('DISALLOW_COPY_AND_ASSIGN(Params);')
340 .Eblock('};')
342 return c
344 def _GenerateTypes(self, types, is_toplevel=False, generate_typedefs=False):
345 """Generate the structures required by a property such as OBJECT classes
346 and enums.
348 c = Code()
349 for type_ in types:
350 c.Cblock(self._GenerateType(type_,
351 is_toplevel=is_toplevel,
352 generate_typedefs=generate_typedefs))
353 return c
355 def _GenerateCreateCallbackArguments(self, function):
356 """Generates functions for passing parameters to a callback.
358 c = Code()
359 params = function.params
360 c.Cblock(self._GenerateTypes((p.type_ for p in params), is_toplevel=True))
362 declaration_list = []
363 for param in params:
364 if param.description:
365 c.Comment(param.description)
366 declaration_list.append(cpp_util.GetParameterDeclaration(
367 param, self._type_helper.GetCppType(param.type_)))
368 c.Append('scoped_ptr<base::ListValue> Create(%s);' %
369 ', '.join(declaration_list))
370 return c
372 def _GenerateEventNameConstant(self, event):
373 """Generates a constant string array for the event name.
375 c = Code()
376 c.Append('extern const char kEventName[]; // "%s.%s"' % (
377 self._namespace.name, event.name))
378 c.Append()
379 return c
381 def _GenerateFunctionResults(self, callback):
382 """Generates namespace for passing a function's result back.
384 c = Code()
385 (c.Append('namespace Results {')
386 .Append()
387 .Concat(self._GenerateCreateCallbackArguments(callback))
388 .Append('} // namespace Results')
390 return c
392 def _GenerateParams(self, params):
393 """Builds the parameter list for a function, given an array of parameters.
395 # |error| is populated with warnings and/or errors found during parsing.
396 # |error| being set does not necessarily imply failure and may be
397 # recoverable.
398 # For example, optional properties may have failed to parse, but the
399 # parser was able to continue.
400 if self._generate_error_messages:
401 params += ('base::string16* error',)
402 return ', '.join(str(p) for p in params)