Fix build break
[chromium-blink-merge.git] / tools / json_schema_compiler / h_generator.py
blob140670d7d0df34731b2ee9e0defa493f280d1888
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 from code import Code
6 from model import PropertyType, Type
7 import cpp_util
8 import schema_util
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,
17 self._type_generator,
18 self._cpp_namespace).Generate()
20 class _Generator(object):
21 """A .h generator for a namespace.
22 """
23 def __init__(self, namespace, cpp_type_generator, cpp_namespace):
24 self._namespace = namespace
25 self._type_helper = cpp_type_generator
26 self._cpp_namespace = cpp_namespace
27 self._target_namespace = (
28 self._type_helper.GetCppNamespaceName(self._namespace))
30 def Generate(self):
31 """Generates a Code object with the .h for a single namespace.
32 """
33 c = Code()
34 (c.Append(cpp_util.CHROMIUM_LICENSE)
35 .Append()
36 .Append(cpp_util.GENERATED_FILE_MESSAGE % self._namespace.source_file)
37 .Append()
40 ifndef_name = cpp_util.GenerateIfndefName(self._namespace.source_file_dir,
41 self._target_namespace)
42 (c.Append('#ifndef %s' % ifndef_name)
43 .Append('#define %s' % ifndef_name)
44 .Append()
45 .Append('#include <map>')
46 .Append('#include <string>')
47 .Append('#include <vector>')
48 .Append()
49 .Append('#include "base/basictypes.h"')
50 .Append('#include "base/logging.h"')
51 .Append('#include "base/memory/linked_ptr.h"')
52 .Append('#include "base/memory/scoped_ptr.h"')
53 .Append('#include "base/values.h"')
54 .Cblock(self._type_helper.GenerateIncludes())
55 .Append()
58 c.Concat(cpp_util.OpenNamespace(self._cpp_namespace))
59 # TODO(calamity): These forward declarations should be #includes to allow
60 # $ref types from other files to be used as required params. This requires
61 # some detangling of windows and tabs which will currently lead to circular
62 # #includes.
63 forward_declarations = (
64 self._type_helper.GenerateForwardDeclarations())
65 if not forward_declarations.IsEmpty():
66 (c.Append()
67 .Cblock(forward_declarations)
70 c.Concat(self._type_helper.GetNamespaceStart())
71 c.Append()
72 if self._namespace.properties:
73 (c.Append('//')
74 .Append('// Properties')
75 .Append('//')
76 .Append()
78 for property in self._namespace.properties.values():
79 property_code = self._type_helper.GeneratePropertyValues(
80 property,
81 'extern const %(type)s %(name)s;')
82 if property_code:
83 c.Cblock(property_code)
84 if self._namespace.types:
85 (c.Append('//')
86 .Append('// Types')
87 .Append('//')
88 .Append()
89 .Cblock(self._GenerateTypes(self._FieldDependencyOrder(),
90 is_toplevel=True,
91 generate_typedefs=True))
93 if self._namespace.functions:
94 (c.Append('//')
95 .Append('// Functions')
96 .Append('//')
97 .Append()
99 for function in self._namespace.functions.values():
100 c.Cblock(self._GenerateFunction(function))
101 if self._namespace.events:
102 (c.Append('//')
103 .Append('// Events')
104 .Append('//')
105 .Append()
107 for event in self._namespace.events.values():
108 c.Cblock(self._GenerateEvent(event))
109 (c.Concat(self._type_helper.GetNamespaceEnd())
110 .Concat(cpp_util.CloseNamespace(self._cpp_namespace))
111 .Append('#endif // %s' % ifndef_name)
112 .Append()
114 return c
116 def _FieldDependencyOrder(self):
117 """Generates the list of types in the current namespace in an order in which
118 depended-upon types appear before types which depend on them.
120 dependency_order = []
122 def ExpandType(path, type_):
123 if type_ in path:
124 raise ValueError("Illegal circular dependency via cycle " +
125 ", ".join(map(lambda x: x.name, path + [type_])))
126 for prop in type_.properties.values():
127 if (prop.type_ == PropertyType.REF and
128 schema_util.GetNamespace(prop.ref_type) == self._namespace.name):
129 ExpandType(path + [type_], self._namespace.types[prop.ref_type])
130 if not type_ in dependency_order:
131 dependency_order.append(type_)
133 for type_ in self._namespace.types.values():
134 ExpandType([], type_)
135 return dependency_order
137 def _GenerateEnumDeclaration(self, enum_name, type_):
138 """Generate the declaration of a C++ enum.
140 c = Code()
141 c.Sblock('enum %s {' % enum_name)
142 c.Append(self._type_helper.GetEnumNoneValue(type_) + ',')
143 for value in type_.enum_values:
144 c.Append(self._type_helper.GetEnumValue(type_, value) + ',')
145 return c.Eblock('};')
147 def _GenerateFields(self, props):
148 """Generates the field declarations when declaring a type.
150 c = Code()
151 needs_blank_line = False
152 for prop in props:
153 if needs_blank_line:
154 c.Append()
155 needs_blank_line = True
156 if prop.description:
157 c.Comment(prop.description)
158 # ANY is a base::Value which is abstract and cannot be a direct member, so
159 # we always need to wrap it in a scoped_ptr.
160 is_ptr = prop.optional or prop.type_.property_type == PropertyType.ANY
161 (c.Append('%s %s;' % (
162 self._type_helper.GetCppType(prop.type_, is_ptr=is_ptr),
163 prop.unix_name))
165 return c
167 def _GenerateType(self, type_, is_toplevel=False, generate_typedefs=False):
168 """Generates a struct for |type_|.
170 |is_toplevel| implies that the type was declared in the "types" field
171 of an API schema. This determines the correct function
172 modifier(s).
173 |generate_typedefs| controls whether primitive types should be generated as
174 a typedef. This may not always be desired. If false,
175 primitive types are ignored.
177 classname = cpp_util.Classname(schema_util.StripNamespace(type_.name))
178 c = Code()
180 if type_.functions:
181 # Wrap functions within types in the type's namespace.
182 (c.Append('namespace %s {' % classname)
183 .Append()
185 for function in type_.functions.values():
186 c.Cblock(self._GenerateFunction(function))
187 c.Append('} // namespace %s' % classname)
188 elif type_.property_type == PropertyType.ARRAY:
189 if generate_typedefs and type_.description:
190 c.Comment(type_.description)
191 c.Cblock(self._GenerateType(type_.item_type))
192 if generate_typedefs:
193 (c.Append('typedef std::vector<%s > %s;' % (
194 self._type_helper.GetCppType(type_.item_type),
195 classname))
197 elif type_.property_type == PropertyType.STRING:
198 if generate_typedefs:
199 if type_.description:
200 c.Comment(type_.description)
201 c.Append('typedef std::string %(classname)s;')
202 elif type_.property_type == PropertyType.ENUM:
203 if type_.description:
204 c.Comment(type_.description)
205 c.Sblock('enum %(classname)s {')
206 c.Append('%s,' % self._type_helper.GetEnumNoneValue(type_))
207 for value in type_.enum_values:
208 c.Append('%s,' % self._type_helper.GetEnumValue(type_, value))
209 # Top level enums are in a namespace scope so the methods shouldn't be
210 # static. On the other hand, those declared inline (e.g. in an object) do.
211 maybe_static = '' if is_toplevel else 'static '
212 (c.Eblock('};')
213 .Append()
214 .Append('%sstd::string ToString(%s as_enum);' %
215 (maybe_static, classname))
216 .Append('%s%s Parse%s(const std::string& as_string);' %
217 (maybe_static, classname, classname))
219 elif type_.property_type == PropertyType.OBJECT:
220 if type_.description:
221 c.Comment(type_.description)
222 (c.Sblock('struct %(classname)s {')
223 .Append('%(classname)s();')
224 .Append('~%(classname)s();')
226 if type_.origin.from_json:
227 (c.Append()
228 .Comment('Populates a %s object from a base::Value. Returns'
229 ' whether |out| was successfully populated.' % classname)
230 .Append('static bool Populate(const base::Value& value, '
231 '%(classname)s* out);')
233 if type_.origin.from_client:
234 (c.Append()
235 .Comment('Returns a new base::DictionaryValue representing the'
236 ' serialized form of this %s object.' % classname)
237 .Append('scoped_ptr<base::DictionaryValue> ToValue() const;')
239 properties = type_.properties.values()
240 (c.Append()
241 .Cblock(self._GenerateTypes(p.type_ for p in properties))
242 .Cblock(self._GenerateFields(properties)))
243 if type_.additional_properties is not None:
244 # Most additionalProperties actually have type "any", which is better
245 # modelled as a DictionaryValue rather than a map of string -> Value.
246 if type_.additional_properties.property_type == PropertyType.ANY:
247 c.Append('base::DictionaryValue additional_properties;')
248 else:
249 (c.Cblock(self._GenerateType(type_.additional_properties))
250 .Append('std::map<std::string, %s> additional_properties;' %
251 cpp_util.PadForGenerics(
252 self._type_helper.GetCppType(type_.additional_properties,
253 is_in_container=True)))
255 (c.Eblock()
256 .Append()
257 .Sblock(' private:')
258 .Append('DISALLOW_COPY_AND_ASSIGN(%(classname)s);')
259 .Eblock('};')
261 elif type_.property_type == PropertyType.CHOICES:
262 if type_.description:
263 c.Comment(type_.description)
264 # Choices are modelled with optional fields for each choice. Exactly one
265 # field of the choice is guaranteed to be set by the compiler.
266 (c.Sblock('struct %(classname)s {')
267 .Append('%(classname)s();')
268 .Append('~%(classname)s();')
269 .Append())
270 c.Cblock(self._GenerateTypes(type_.choices))
271 if type_.origin.from_json:
272 (c.Comment('Populates a %s object from a base::Value. Returns'
273 ' whether |out| was successfully populated.' % classname)
274 .Append('static bool Populate(const base::Value& value, '
275 '%(classname)s* out);')
276 .Append()
278 if type_.origin.from_client:
279 (c.Comment('Returns a new base::Value representing the'
280 ' serialized form of this %s object.' % classname)
281 .Append('scoped_ptr<base::Value> ToValue() const;')
282 .Append()
284 c.Append('// Choices:')
285 for choice_type in type_.choices:
286 c.Append('%s as_%s;' % (
287 self._type_helper.GetCppType(choice_type, is_ptr=True),
288 choice_type.unix_name))
289 c.Eblock('};')
290 c.Substitute({'classname': classname})
291 return c
293 def _GenerateEvent(self, event):
294 """Generates the namespaces for an event.
296 c = Code()
297 # TODO(kalman): use event.unix_name not Classname.
298 event_namespace = cpp_util.Classname(event.name)
299 (c.Append('namespace %s {' % event_namespace)
300 .Append()
301 .Concat(self._GenerateCreateCallbackArguments(event))
302 .Eblock('} // namespace %s' % event_namespace)
304 return c
306 def _GenerateFunction(self, function):
307 """Generates the namespaces and structs for a function.
309 c = Code()
310 # TODO(kalman): Use function.unix_name not Classname here.
311 function_namespace = cpp_util.Classname(function.name)
312 (c.Append('namespace %s {' % function_namespace)
313 .Append()
314 .Cblock(self._GenerateFunctionParams(function))
316 if function.callback:
317 c.Cblock(self._GenerateFunctionResults(function.callback))
318 c.Append('} // namespace %s' % function_namespace)
319 return c
321 def _GenerateFunctionParams(self, function):
322 """Generates the struct for passing parameters from JSON to a function.
324 if not function.params:
325 return Code()
327 c = Code()
328 (c.Sblock('struct Params {')
329 .Append('static scoped_ptr<Params> Create(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 _GenerateFunctionResults(self, callback):
373 """Generates namespace for passing a function's result back.
375 c = Code()
376 (c.Append('namespace Results {')
377 .Append()
378 .Concat(self._GenerateCreateCallbackArguments(callback))
379 .Append('} // namespace Results')
381 return c