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