h_generator.py revision cedac228d2dd51db4b79ea1e72c7f249408ee061
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 ToString(%s as_enum);' %
218                (maybe_static, classname))
219        .Append('%s%s Parse%s(const std::string& as_string);' %
220                (maybe_static, classname, classname))
221      )
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();')
229      )
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)))
236        )
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',))))
243          )
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)
252        )
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)))
278            )
279      (c.Eblock()
280        .Append()
281        .Sblock(' private:')
282          .Append('DISALLOW_COPY_AND_ASSIGN(%(classname)s);')
283        .Eblock('};')
284      )
285    return c.Substitute({'classname': classname})
286
287  def _GenerateEvent(self, event):
288    """Generates the namespaces for an event.
289    """
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      .Eblock('}  // namespace %s' % event_namespace)
298    )
299    return c
300
301  def _GenerateFunction(self, function):
302    """Generates the namespaces and structs for a function.
303    """
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))
314    )
315    if function.callback:
316      c.Cblock(self._GenerateFunctionResults(function.callback))
317    c.Append('}  // namespace %s' % function_namespace)
318    return c
319
320  def _GenerateFunctionParams(self, function):
321    """Generates the struct for passing parameters from JSON to a function.
322    """
323    if not function.params:
324      return Code()
325
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('};')
341    )
342    return c
343
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.
347    """
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
354
355  def _GenerateCreateCallbackArguments(self, function):
356    """Generates functions for passing parameters to a callback.
357    """
358    c = Code()
359    params = function.params
360    c.Cblock(self._GenerateTypes((p.type_ for p in params), is_toplevel=True))
361
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
371
372  def _GenerateEventNameConstant(self, event):
373    """Generates a constant string array for the event name.
374    """
375    c = Code()
376    c.Append('extern const char kEventName[];  // "%s.%s"' % (
377                 self._namespace.name, event.name))
378    c.Append()
379    return c
380
381  def _GenerateFunctionResults(self, callback):
382    """Generates namespace for passing a function's result back.
383    """
384    c = Code()
385    (c.Append('namespace Results {')
386      .Append()
387      .Concat(self._GenerateCreateCallbackArguments(callback))
388      .Append('}  // namespace Results')
389    )
390    return c
391
392  def _GenerateParams(self, params):
393    """Builds the parameter list for a function, given an array of parameters.
394    """
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)
403