h_generator.py revision 2385ea399aae016c0806a4f9ef3c9cfe3d2a39df
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 PropertyType, Type
7import cpp_util
8import schema_util
9
10class HGenerator(object):
11  def __init__(self, type_generator, cpp_namespace):
12    self._type_generator = type_generator
13    self._cpp_namespace = cpp_namespace
14
15  def Generate(self, namespace):
16    return _Generator(namespace,
17                      self._type_generator,
18                      self._cpp_namespace).Generate()
19
20class _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))
29
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()
38    )
39
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()
56    )
57
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)
68      )
69
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()
77      )
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))
92      )
93    if self._namespace.functions:
94      (c.Append('//')
95        .Append('// Functions')
96        .Append('//')
97        .Append()
98      )
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()
106      )
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()
113    )
114    return c
115
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.
119    """
120    dependency_order = []
121
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_)
132
133    for type_ in self._namespace.types.values():
134      ExpandType([], type_)
135    return dependency_order
136
137  def _GenerateEnumDeclaration(self, enum_name, type_):
138    """Generate the declaration of a C++ enum.
139    """
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('};')
146
147  def _GenerateFields(self, props):
148    """Generates the field declarations when declaring a type.
149    """
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))
164      )
165    return c
166
167  def _GenerateType(self, type_, is_toplevel=False, generate_typedefs=False):
168    """Generates a struct for |type_|.
169
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.
176    """
177    classname = cpp_util.Classname(schema_util.StripNamespace(type_.name))
178    c = Code()
179
180    if type_.functions:
181      # Wrap functions within types in the type's namespace.
182      (c.Append('namespace %s {' % classname)
183        .Append()
184      )
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))
196        )
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))
218      )
219    elif type_.property_type in (PropertyType.CHOICES,
220                                 PropertyType.OBJECT):
221      if type_.description:
222        c.Comment(type_.description)
223      (c.Sblock('struct %(classname)s {')
224          .Append('%(classname)s();')
225          .Append('~%(classname)s();')
226      )
227      if type_.origin.from_json:
228        (c.Append()
229          .Comment('Populates a %s object from a base::Value. Returns'
230                   ' whether |out| was successfully populated.' % classname)
231          .Append('static bool Populate(const base::Value& value, '
232                  '%(classname)s* out);')
233        )
234        if is_toplevel:
235          (c.Append()
236            .Comment('Creates a %s object from a base::Value, or NULL on '
237                     'failure.' % classname)
238            .Append('static scoped_ptr<%(classname)s> '
239                        'FromValue(const base::Value& value);')
240          )
241      if type_.origin.from_client:
242        value_type = ('base::Value'
243                      if type_.property_type is PropertyType.CHOICES else
244                      'base::DictionaryValue')
245        (c.Append()
246          .Comment('Returns a new %s representing the serialized form of this '
247                   '%s object.' % (value_type, classname))
248          .Append('scoped_ptr<%s> ToValue() const;' % value_type)
249        )
250      if type_.property_type == PropertyType.CHOICES:
251        # Choices are modelled with optional fields for each choice. Exactly one
252        # field of the choice is guaranteed to be set by the compiler.
253        c.Cblock(self._GenerateTypes(type_.choices))
254        c.Append('// Choices:')
255        for choice_type in type_.choices:
256          c.Append('%s as_%s;' % (
257              self._type_helper.GetCppType(choice_type, is_ptr=True),
258              choice_type.unix_name))
259      else:
260        properties = type_.properties.values()
261        (c.Append()
262          .Cblock(self._GenerateTypes(p.type_ for p in properties))
263          .Cblock(self._GenerateFields(properties)))
264        if type_.additional_properties is not None:
265          # Most additionalProperties actually have type "any", which is better
266          # modelled as a DictionaryValue rather than a map of string -> Value.
267          if type_.additional_properties.property_type == PropertyType.ANY:
268            c.Append('base::DictionaryValue additional_properties;')
269          else:
270            (c.Cblock(self._GenerateType(type_.additional_properties))
271              .Append('std::map<std::string, %s> additional_properties;' %
272                  cpp_util.PadForGenerics(
273                      self._type_helper.GetCppType(type_.additional_properties,
274                                                   is_in_container=True)))
275            )
276      (c.Eblock()
277        .Append()
278        .Sblock(' private:')
279          .Append('DISALLOW_COPY_AND_ASSIGN(%(classname)s);')
280        .Eblock('};')
281      )
282    return c.Substitute({'classname': classname})
283
284  def _GenerateEvent(self, event):
285    """Generates the namespaces for an event.
286    """
287    c = Code()
288    # TODO(kalman): use event.unix_name not Classname.
289    event_namespace = cpp_util.Classname(event.name)
290    (c.Append('namespace %s {' % event_namespace)
291      .Append()
292      .Concat(self._GenerateEventNameConstant(event))
293      .Concat(self._GenerateCreateCallbackArguments(event))
294      .Eblock('}  // namespace %s' % event_namespace)
295    )
296    return c
297
298  def _GenerateFunction(self, function):
299    """Generates the namespaces and structs for a function.
300    """
301    c = Code()
302    # TODO(kalman): Use function.unix_name not Classname here.
303    function_namespace = cpp_util.Classname(function.name)
304    """Windows has a #define for SendMessage, so to avoid any issues, we need
305    to not use the name.
306    """
307    if function_namespace == 'SendMessage':
308      function_namespace = 'PassMessage'
309    (c.Append('namespace %s {' % function_namespace)
310      .Append()
311      .Cblock(self._GenerateFunctionParams(function))
312    )
313    if function.callback:
314      c.Cblock(self._GenerateFunctionResults(function.callback))
315    c.Append('}  // namespace %s' % function_namespace)
316    return c
317
318  def _GenerateFunctionParams(self, function):
319    """Generates the struct for passing parameters from JSON to a function.
320    """
321    if not function.params:
322      return Code()
323
324    c = Code()
325    (c.Sblock('struct Params {')
326      .Append('static scoped_ptr<Params> Create(const base::ListValue& args);')
327      .Append('~Params();')
328      .Append()
329      .Cblock(self._GenerateTypes(p.type_ for p in function.params))
330      .Cblock(self._GenerateFields(function.params))
331      .Eblock()
332      .Append()
333      .Sblock(' private:')
334        .Append('Params();')
335        .Append()
336        .Append('DISALLOW_COPY_AND_ASSIGN(Params);')
337      .Eblock('};')
338    )
339    return c
340
341  def _GenerateTypes(self, types, is_toplevel=False, generate_typedefs=False):
342    """Generate the structures required by a property such as OBJECT classes
343    and enums.
344    """
345    c = Code()
346    for type_ in types:
347      c.Cblock(self._GenerateType(type_,
348                                  is_toplevel=is_toplevel,
349                                  generate_typedefs=generate_typedefs))
350    return c
351
352  def _GenerateCreateCallbackArguments(self, function):
353    """Generates functions for passing parameters to a callback.
354    """
355    c = Code()
356    params = function.params
357    c.Cblock(self._GenerateTypes((p.type_ for p in params), is_toplevel=True))
358
359    declaration_list = []
360    for param in params:
361      if param.description:
362        c.Comment(param.description)
363      declaration_list.append(cpp_util.GetParameterDeclaration(
364          param, self._type_helper.GetCppType(param.type_)))
365    c.Append('scoped_ptr<base::ListValue> Create(%s);' %
366             ', '.join(declaration_list))
367    return c
368
369  def _GenerateEventNameConstant(self, event):
370    """Generates a constant string array for the event name.
371    """
372    c = Code()
373    c.Append('extern const char kEventName[];  // "%s.%s"' % (
374                 self._namespace.name, event.name))
375    c.Append()
376    return c
377
378  def _GenerateFunctionResults(self, callback):
379    """Generates namespace for passing a function's result back.
380    """
381    c = Code()
382    (c.Append('namespace Results {')
383      .Append()
384      .Concat(self._GenerateCreateCallbackArguments(callback))
385      .Append('}  // namespace Results')
386    )
387    return c
388