h_generator.py revision 010d83a9304c5a91596085d917d248abff47903a
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
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
20
21class _Generator(object):
22  """A .h generator for a namespace.
23  """
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)
32
33  def Generate(self):
34    """Generates a Code object with the .h for a single namespace.
35    """
36    c = Code()
37    (c.Append(cpp_util.CHROMIUM_LICENSE)
38      .Append()
39      .Append(cpp_util.GENERATED_FILE_MESSAGE % self._namespace.source_file)
40      .Append()
41    )
42
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)
47      .Append()
48      .Append('#include <map>')
49      .Append('#include <string>')
50      .Append('#include <vector>')
51      .Append()
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())
58      .Append()
59    )
60
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
65    # #includes.
66    forward_declarations = (
67        self._type_helper.GenerateForwardDeclarations())
68    if not forward_declarations.IsEmpty():
69      (c.Append()
70        .Cblock(forward_declarations)
71      )
72
73    c.Concat(self._type_helper.GetNamespaceStart())
74    c.Append()
75    if self._namespace.properties:
76      (c.Append('//')
77        .Append('// Properties')
78        .Append('//')
79        .Append()
80      )
81      for property in self._namespace.properties.values():
82        property_code = self._type_helper.GeneratePropertyValues(
83            property,
84            'extern const %(type)s %(name)s;')
85        if property_code:
86          c.Cblock(property_code)
87    if self._namespace.types:
88      (c.Append('//')
89        .Append('// Types')
90        .Append('//')
91        .Append()
92        .Cblock(self._GenerateTypes(self._FieldDependencyOrder(),
93                                    is_toplevel=True,
94                                    generate_typedefs=True))
95      )
96    if self._namespace.functions:
97      (c.Append('//')
98        .Append('// Functions')
99        .Append('//')
100        .Append()
101      )
102      for function in self._namespace.functions.values():
103        c.Cblock(self._GenerateFunction(function))
104    if self._namespace.events:
105      (c.Append('//')
106        .Append('// Events')
107        .Append('//')
108        .Append()
109      )
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)
115      .Append()
116    )
117    return c
118
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.
122    """
123    dependency_order = []
124
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_)
135
136    for type_ in self._namespace.types.values():
137      ExpandType([], type_)
138    return dependency_order
139
140  def _GenerateEnumDeclaration(self, enum_name, type_):
141    """Generate a code object with the  declaration of a C++ enum.
142    """
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
153
154  def _GenerateFields(self, props):
155    """Generates the field declarations when declaring a type.
156    """
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))
171      )
172    return c
173
174  def _GenerateType(self, type_, is_toplevel=False, generate_typedefs=False):
175    """Generates a struct for |type_|.
176
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.
183    """
184    classname = cpp_util.Classname(schema_util.StripNamespace(type_.name))
185    c = Code()
186
187    if type_.functions:
188      # Wrap functions within types in the type's namespace.
189      (c.Append('namespace %s {' % classname)
190        .Append()
191      )
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),
202                       classname))
203        )
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 %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))
223      )
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();')
231      )
232      if type_.origin.from_json:
233        (c.Append()
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)))
238        )
239        if is_toplevel:
240          (c.Append()
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',))))
245          )
246      if type_.origin.from_client:
247        value_type = ('base::Value'
248                      if type_.property_type is PropertyType.CHOICES else
249                      'base::DictionaryValue')
250        (c.Append()
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)
254        )
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))
264      else:
265        properties = type_.properties.values()
266        (c.Append()
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;')
274          else:
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)))
280            )
281      (c.Eblock()
282        .Append()
283        .Sblock(' private:')
284          .Append('DISALLOW_COPY_AND_ASSIGN(%(classname)s);')
285        .Eblock('};')
286      )
287    return c.Substitute({'classname': classname})
288
289  def _GenerateEvent(self, event):
290    """Generates the namespaces for an event.
291    """
292    c = Code()
293    # TODO(kalman): use event.unix_name not Classname.
294    event_namespace = cpp_util.Classname(event.name)
295    (c.Append('namespace %s {' % event_namespace)
296      .Append()
297      .Concat(self._GenerateEventNameConstant(event))
298      .Concat(self._GenerateCreateCallbackArguments(event))
299      .Eblock('}  // namespace %s' % event_namespace)
300    )
301    return c
302
303  def _GenerateFunction(self, function):
304    """Generates the namespaces and structs for a function.
305    """
306    c = Code()
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)
314      .Append()
315      .Cblock(self._GenerateFunctionParams(function))
316    )
317    if function.callback:
318      c.Cblock(self._GenerateFunctionResults(function.callback))
319    c.Append('}  // namespace %s' % function_namespace)
320    return c
321
322  def _GenerateFunctionParams(self, function):
323    """Generates the struct for passing parameters from JSON to a function.
324    """
325    if not function.params:
326      return Code()
327
328    c = Code()
329    (c.Sblock('struct Params {')
330      .Append('static scoped_ptr<Params> Create(%s);' % self._GenerateParams(
331          ('const base::ListValue& args',)))
332      .Append('~Params();')
333      .Append()
334      .Cblock(self._GenerateTypes(p.type_ for p in function.params))
335      .Cblock(self._GenerateFields(function.params))
336      .Eblock()
337      .Append()
338      .Sblock(' private:')
339        .Append('Params();')
340        .Append()
341        .Append('DISALLOW_COPY_AND_ASSIGN(Params);')
342      .Eblock('};')
343    )
344    return c
345
346  def _GenerateTypes(self, types, is_toplevel=False, generate_typedefs=False):
347    """Generate the structures required by a property such as OBJECT classes
348    and enums.
349    """
350    c = Code()
351    for type_ in types:
352      c.Cblock(self._GenerateType(type_,
353                                  is_toplevel=is_toplevel,
354                                  generate_typedefs=generate_typedefs))
355    return c
356
357  def _GenerateCreateCallbackArguments(self, function):
358    """Generates functions for passing parameters to a callback.
359    """
360    c = Code()
361    params = function.params
362    c.Cblock(self._GenerateTypes((p.type_ for p in params), is_toplevel=True))
363
364    declaration_list = []
365    for param in params:
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))
372    return c
373
374  def _GenerateEventNameConstant(self, event):
375    """Generates a constant string array for the event name.
376    """
377    c = Code()
378    c.Append('extern const char kEventName[];  // "%s.%s"' % (
379                 self._namespace.name, event.name))
380    c.Append()
381    return c
382
383  def _GenerateFunctionResults(self, callback):
384    """Generates namespace for passing a function's result back.
385    """
386    c = Code()
387    (c.Append('namespace Results {')
388      .Append()
389      .Concat(self._GenerateCreateCallbackArguments(callback))
390      .Append('}  // namespace Results')
391    )
392    return c
393
394  def _GenerateParams(self, params):
395    """Builds the parameter list for a function, given an array of parameters.
396    """
397    # |error| is populated with warnings and/or errors found during parsing.
398    # |error| being set does not necessarily imply failure and may be
399    # recoverable.
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)
405