h_generator.py revision 90dce4d38c5ff5333bea97d859d4e484e27edf0c
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 == 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();')
225      )
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);')
232        )
233        if is_toplevel:
234          (c.Append()
235            .Comment('Creates a %s object from a base::Value, or NULL on '
236                     'failure.' % classname)
237            .Append('static scoped_ptr<%(classname)s> '
238                        'FromValue(const base::Value& value);')
239          )
240      if type_.origin.from_client:
241        (c.Append()
242          .Comment('Returns a new base::DictionaryValue representing the'
243                   ' serialized form of this %s object.' % classname)
244          .Append('scoped_ptr<base::DictionaryValue> ToValue() const;')
245        )
246      properties = type_.properties.values()
247      (c.Append()
248        .Cblock(self._GenerateTypes(p.type_ for p in properties))
249        .Cblock(self._GenerateFields(properties)))
250      if type_.additional_properties is not None:
251        # Most additionalProperties actually have type "any", which is better
252        # modelled as a DictionaryValue rather than a map of string -> Value.
253        if type_.additional_properties.property_type == PropertyType.ANY:
254          c.Append('base::DictionaryValue additional_properties;')
255        else:
256          (c.Cblock(self._GenerateType(type_.additional_properties))
257            .Append('std::map<std::string, %s> additional_properties;' %
258                cpp_util.PadForGenerics(
259                    self._type_helper.GetCppType(type_.additional_properties,
260                                                 is_in_container=True)))
261          )
262      (c.Eblock()
263        .Append()
264        .Sblock(' private:')
265          .Append('DISALLOW_COPY_AND_ASSIGN(%(classname)s);')
266        .Eblock('};')
267      )
268    elif type_.property_type == PropertyType.CHOICES:
269      if type_.description:
270        c.Comment(type_.description)
271      # Choices are modelled with optional fields for each choice. Exactly one
272      # field of the choice is guaranteed to be set by the compiler.
273      (c.Sblock('struct %(classname)s {')
274          .Append('%(classname)s();')
275          .Append('~%(classname)s();')
276          .Append())
277      c.Cblock(self._GenerateTypes(type_.choices))
278      if type_.origin.from_json:
279        (c.Comment('Populates a %s object from a base::Value. Returns'
280                   ' whether |out| was successfully populated.' % classname)
281          .Append('static bool Populate(const base::Value& value, '
282                  '%(classname)s* out);')
283          .Append()
284        )
285      if type_.origin.from_client:
286        (c.Comment('Returns a new base::Value representing the'
287                   ' serialized form of this %s object.' % classname)
288          .Append('scoped_ptr<base::Value> ToValue() const;')
289          .Append()
290        )
291      c.Append('// Choices:')
292      for choice_type in type_.choices:
293        c.Append('%s as_%s;' % (
294            self._type_helper.GetCppType(choice_type, is_ptr=True),
295            choice_type.unix_name))
296      c.Eblock('};')
297    c.Substitute({'classname': classname})
298    return c
299
300  def _GenerateEvent(self, event):
301    """Generates the namespaces for an event.
302    """
303    c = Code()
304    # TODO(kalman): use event.unix_name not Classname.
305    event_namespace = cpp_util.Classname(event.name)
306    (c.Append('namespace %s {' % event_namespace)
307      .Append()
308      .Concat(self._GenerateCreateCallbackArguments(event))
309      .Eblock('}  // namespace %s' % event_namespace)
310    )
311    return c
312
313  def _GenerateFunction(self, function):
314    """Generates the namespaces and structs for a function.
315    """
316    c = Code()
317    # TODO(kalman): Use function.unix_name not Classname here.
318    function_namespace = cpp_util.Classname(function.name)
319    """Windows has a #define for SendMessage, so to avoid any issues, we need
320    to not use the name.
321    """
322    if function_namespace == 'SendMessage':
323      function_namespace = 'PassMessage'
324    (c.Append('namespace %s {' % function_namespace)
325      .Append()
326      .Cblock(self._GenerateFunctionParams(function))
327    )
328    if function.callback:
329      c.Cblock(self._GenerateFunctionResults(function.callback))
330    c.Append('}  // namespace %s' % function_namespace)
331    return c
332
333  def _GenerateFunctionParams(self, function):
334    """Generates the struct for passing parameters from JSON to a function.
335    """
336    if not function.params:
337      return Code()
338
339    c = Code()
340    (c.Sblock('struct Params {')
341      .Append('static scoped_ptr<Params> Create(const base::ListValue& args);')
342      .Append('~Params();')
343      .Append()
344      .Cblock(self._GenerateTypes(p.type_ for p in function.params))
345      .Cblock(self._GenerateFields(function.params))
346      .Eblock()
347      .Append()
348      .Sblock(' private:')
349        .Append('Params();')
350        .Append()
351        .Append('DISALLOW_COPY_AND_ASSIGN(Params);')
352      .Eblock('};')
353    )
354    return c
355
356  def _GenerateTypes(self, types, is_toplevel=False, generate_typedefs=False):
357    """Generate the structures required by a property such as OBJECT classes
358    and enums.
359    """
360    c = Code()
361    for type_ in types:
362      c.Cblock(self._GenerateType(type_,
363                                  is_toplevel=is_toplevel,
364                                  generate_typedefs=generate_typedefs))
365    return c
366
367  def _GenerateCreateCallbackArguments(self, function):
368    """Generates functions for passing parameters to a callback.
369    """
370    c = Code()
371    params = function.params
372    c.Cblock(self._GenerateTypes((p.type_ for p in params), is_toplevel=True))
373
374    declaration_list = []
375    for param in params:
376      if param.description:
377        c.Comment(param.description)
378      declaration_list.append(cpp_util.GetParameterDeclaration(
379          param, self._type_helper.GetCppType(param.type_)))
380    c.Append('scoped_ptr<base::ListValue> Create(%s);' %
381             ', '.join(declaration_list))
382    return c
383
384  def _GenerateFunctionResults(self, callback):
385    """Generates namespace for passing a function's result back.
386    """
387    c = Code()
388    (c.Append('namespace Results {')
389      .Append()
390      .Concat(self._GenerateCreateCallbackArguments(callback))
391      .Append('}  // namespace Results')
392    )
393    return c
394