cc_generator.py revision c2db58bd994c04d98e4ee2cd7565b71548655fe3
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 model
9import schema_util
10import sys
11import util_cc_helper
12
13class CCGenerator(object):
14  def __init__(self, type_generator, cpp_namespace):
15    self._type_generator = type_generator
16    self._cpp_namespace = cpp_namespace
17
18  def Generate(self, namespace):
19    return _Generator(namespace,
20                      self._type_generator,
21                      self._cpp_namespace).Generate()
22
23class _Generator(object):
24  """A .cc generator for a namespace.
25  """
26  def __init__(self, namespace, cpp_type_generator, cpp_namespace):
27    self._namespace = namespace
28    self._type_helper = cpp_type_generator
29    self._cpp_namespace = cpp_namespace
30    self._target_namespace = (
31        self._type_helper.GetCppNamespaceName(self._namespace))
32    self._util_cc_helper = (
33        util_cc_helper.UtilCCHelper(self._type_helper))
34    self._generate_error_messages = namespace.compiler_options.get(
35        'generate_error_messages', False)
36
37  def Generate(self):
38    """Generates a Code object with the .cc for a single namespace.
39    """
40    c = Code()
41    (c.Append(cpp_util.CHROMIUM_LICENSE)
42      .Append()
43      .Append(cpp_util.GENERATED_FILE_MESSAGE % self._namespace.source_file)
44      .Append()
45      .Append(self._util_cc_helper.GetIncludePath())
46      .Append('#include "base/logging.h"')
47      .Append('#include "base/strings/string_number_conversions.h"')
48      .Append('#include "%s/%s.h"' %
49          (self._namespace.source_file_dir, self._namespace.unix_name))
50      .Cblock(self._type_helper.GenerateIncludes(include_soft=True))
51      .Append()
52      .Concat(cpp_util.OpenNamespace(self._cpp_namespace))
53      .Cblock(self._type_helper.GetNamespaceStart())
54    )
55    if self._namespace.properties:
56      (c.Append('//')
57        .Append('// Properties')
58        .Append('//')
59        .Append()
60      )
61      for property in self._namespace.properties.values():
62        property_code = self._type_helper.GeneratePropertyValues(
63            property,
64            'const %(type)s %(name)s = %(value)s;',
65            nodoc=True)
66        if property_code:
67          c.Cblock(property_code)
68    if self._namespace.types:
69      (c.Append('//')
70        .Append('// Types')
71        .Append('//')
72        .Append()
73        .Cblock(self._GenerateTypes(None, self._namespace.types.values()))
74      )
75    if self._namespace.functions:
76      (c.Append('//')
77        .Append('// Functions')
78        .Append('//')
79        .Append()
80      )
81    for function in self._namespace.functions.values():
82      c.Cblock(self._GenerateFunction(function))
83    if self._namespace.events:
84      (c.Append('//')
85        .Append('// Events')
86        .Append('//')
87        .Append()
88      )
89      for event in self._namespace.events.values():
90        c.Cblock(self._GenerateEvent(event))
91    (c.Concat(self._type_helper.GetNamespaceEnd())
92      .Cblock(cpp_util.CloseNamespace(self._cpp_namespace))
93    )
94    return c
95
96  def _GenerateType(self, cpp_namespace, type_):
97    """Generates the function definitions for a type.
98    """
99    classname = cpp_util.Classname(schema_util.StripNamespace(type_.name))
100    c = Code()
101
102    if type_.functions:
103      # Wrap functions within types in the type's namespace.
104      (c.Append('namespace %s {' % classname)
105        .Append())
106      for function in type_.functions.values():
107        c.Cblock(self._GenerateFunction(function))
108      c.Append('}  // namespace %s' % classname)
109    elif type_.property_type == PropertyType.ARRAY:
110      c.Cblock(self._GenerateType(cpp_namespace, type_.item_type))
111    elif type_.property_type in (PropertyType.CHOICES,
112                                 PropertyType.OBJECT):
113      if cpp_namespace is None:
114        classname_in_namespace = classname
115      else:
116        classname_in_namespace = '%s::%s' % (cpp_namespace, classname)
117
118      if type_.property_type == PropertyType.OBJECT:
119        c.Cblock(self._GeneratePropertyFunctions(classname_in_namespace,
120                                                 type_.properties.values()))
121      else:
122        c.Cblock(self._GenerateTypes(classname_in_namespace, type_.choices))
123
124      (c.Append('%s::%s()' % (classname_in_namespace, classname))
125        .Cblock(self._GenerateInitializersAndBody(type_))
126        .Append('%s::~%s() {}' % (classname_in_namespace, classname))
127        .Append()
128      )
129      if type_.origin.from_json:
130        c.Cblock(self._GenerateTypePopulate(classname_in_namespace, type_))
131        if cpp_namespace is None:  # only generate for top-level types
132          c.Cblock(self._GenerateTypeFromValue(classname_in_namespace, type_))
133      if type_.origin.from_client:
134        c.Cblock(self._GenerateTypeToValue(classname_in_namespace, type_))
135    elif type_.property_type == PropertyType.ENUM:
136      (c.Cblock(self._GenerateEnumToString(cpp_namespace, type_))
137        .Cblock(self._GenerateEnumFromString(cpp_namespace, type_))
138      )
139
140    return c
141
142  def _GenerateInitializersAndBody(self, type_):
143    items = []
144    for prop in type_.properties.values():
145      if prop.optional:
146        continue
147
148      t = prop.type_
149      if t.property_type == PropertyType.INTEGER:
150        items.append('%s(0)' % prop.unix_name)
151      elif t.property_type == PropertyType.DOUBLE:
152        items.append('%s(0.0)' % prop.unix_name)
153      elif t.property_type == PropertyType.BOOLEAN:
154        items.append('%s(false)' % prop.unix_name)
155      elif (t.property_type == PropertyType.ANY or
156            t.property_type == PropertyType.ARRAY or
157            t.property_type == PropertyType.BINARY or  # mapped to std::string
158            t.property_type == PropertyType.CHOICES or
159            t.property_type == PropertyType.ENUM or
160            t.property_type == PropertyType.OBJECT or
161            t.property_type == PropertyType.FUNCTION or
162            t.property_type == PropertyType.REF or
163            t.property_type == PropertyType.STRING):
164        # TODO(miket): It would be nice to initialize CHOICES and ENUM, but we
165        # don't presently have the semantics to indicate which one of a set
166        # should be the default.
167        continue
168      else:
169        raise TypeError(t)
170
171    if items:
172      s = ': %s' % (', '.join(items))
173    else:
174      s = ''
175    s = s + ' {}'
176    return Code().Append(s)
177
178  def _GenerateTypePopulate(self, cpp_namespace, type_):
179    """Generates the function for populating a type given a pointer to it.
180
181    E.g for type "Foo", generates Foo::Populate()
182    """
183    classname = cpp_util.Classname(schema_util.StripNamespace(type_.name))
184    c = Code()
185    (c.Append('// static')
186      .Append('bool %(namespace)s::Populate(')
187      .Sblock('    %s) {' % self._GenerateParams(
188          ('const base::Value& value', '%(name)s* out'))))
189
190    if type_.property_type == PropertyType.CHOICES:
191      for choice in type_.choices:
192        (c.Sblock('if (%s) {' % self._GenerateValueIsTypeExpression('value',
193                                                                    choice))
194            .Concat(self._GeneratePopulateVariableFromValue(
195                choice,
196                '(&value)',
197                'out->as_%s' % choice.unix_name,
198                'false',
199                is_ptr=True))
200            .Append('return true;')
201          .Eblock('}')
202        )
203      (c.Concat(self._GenerateError(
204          '"expected %s, got " +  %s' %
205              (" or ".join(choice.name for choice in type_.choices),
206              self._util_cc_helper.GetValueTypeString('value'))))
207        .Append('return false;'))
208    elif type_.property_type == PropertyType.OBJECT:
209      (c.Sblock('if (!value.IsType(base::Value::TYPE_DICTIONARY)) {')
210        .Concat(self._GenerateError(
211          '"expected dictionary, got " + ' +
212          self._util_cc_helper.GetValueTypeString('value')))
213        .Append('return false;')
214        .Eblock('}'))
215
216      if type_.properties or type_.additional_properties is not None:
217        c.Append('const base::DictionaryValue* dict = '
218                     'static_cast<const base::DictionaryValue*>(&value);')
219      for prop in type_.properties.values():
220        c.Concat(self._InitializePropertyToDefault(prop, 'out'))
221      for prop in type_.properties.values():
222        c.Concat(self._GenerateTypePopulateProperty(prop, 'dict', 'out'))
223      if type_.additional_properties is not None:
224        if type_.additional_properties.property_type == PropertyType.ANY:
225          c.Append('out->additional_properties.MergeDictionary(dict);')
226        else:
227          cpp_type = self._type_helper.GetCppType(type_.additional_properties,
228                                                  is_in_container=True)
229          (c.Append('for (base::DictionaryValue::Iterator it(*dict);')
230            .Sblock('     !it.IsAtEnd(); it.Advance()) {')
231              .Append('%s tmp;' % cpp_type)
232              .Concat(self._GeneratePopulateVariableFromValue(
233                  type_.additional_properties,
234                  '(&it.value())',
235                  'tmp',
236                  'false'))
237              .Append('out->additional_properties[it.key()] = tmp;')
238            .Eblock('}')
239          )
240      c.Append('return true;')
241    (c.Eblock('}')
242      .Substitute({'namespace': cpp_namespace, 'name': classname}))
243    return c
244
245  def _GenerateValueIsTypeExpression(self, var, type_):
246    real_type = self._type_helper.FollowRef(type_)
247    if real_type.property_type is PropertyType.CHOICES:
248      return '(%s)' % ' || '.join(self._GenerateValueIsTypeExpression(var,
249                                                                      choice)
250                                  for choice in real_type.choices)
251    return '%s.IsType(%s)' % (var, cpp_util.GetValueType(real_type))
252
253  def _GenerateTypePopulateProperty(self, prop, src, dst):
254    """Generate the code to populate a single property in a type.
255
256    src: base::DictionaryValue*
257    dst: Type*
258    """
259    c = Code()
260    value_var = prop.unix_name + '_value'
261    c.Append('const base::Value* %(value_var)s = NULL;')
262    if prop.optional:
263      (c.Sblock(
264          'if (%(src)s->GetWithoutPathExpansion("%(key)s", &%(value_var)s)) {')
265        .Concat(self._GeneratePopulatePropertyFromValue(
266            prop, value_var, dst, 'false')))
267      underlying_type = self._type_helper.FollowRef(prop.type_)
268      if underlying_type.property_type == PropertyType.ENUM:
269        (c.Append('} else {')
270          .Append('%%(dst)s->%%(name)s = %s;' %
271              self._type_helper.GetEnumNoneValue(prop.type_)))
272      c.Eblock('}')
273    else:
274      (c.Sblock(
275          'if (!%(src)s->GetWithoutPathExpansion("%(key)s", &%(value_var)s)) {')
276        .Concat(self._GenerateError('"\'%%(key)s\' is required"'))
277        .Append('return false;')
278        .Eblock('}')
279        .Concat(self._GeneratePopulatePropertyFromValue(
280            prop, value_var, dst, 'false'))
281      )
282    c.Append()
283    c.Substitute({
284      'value_var': value_var,
285      'key': prop.name,
286      'src': src,
287      'dst': dst,
288      'name': prop.unix_name
289    })
290    return c
291
292  def _GenerateTypeFromValue(self, cpp_namespace, type_):
293    classname = cpp_util.Classname(schema_util.StripNamespace(type_.name))
294    c = Code()
295    (c.Append('// static')
296      .Append('scoped_ptr<%s> %s::FromValue(%s) {' % (classname,
297        cpp_namespace, self._GenerateParams(('const base::Value& value',))))
298      .Append('  scoped_ptr<%s> out(new %s());' % (classname, classname))
299      .Append('  if (!Populate(%s))' % self._GenerateArgs(
300          ('value', 'out.get()')))
301      .Append('    return scoped_ptr<%s>();' % classname)
302      .Append('  return out.Pass();')
303      .Append('}')
304    )
305    return c
306
307  def _GenerateTypeToValue(self, cpp_namespace, type_):
308    """Generates a function that serializes the type into a base::Value.
309    E.g. for type "Foo" generates Foo::ToValue()
310    """
311    if type_.property_type == PropertyType.OBJECT:
312      return self._GenerateObjectTypeToValue(cpp_namespace, type_)
313    elif type_.property_type == PropertyType.CHOICES:
314      return self._GenerateChoiceTypeToValue(cpp_namespace, type_)
315    else:
316      raise ValueError("Unsupported property type %s" % type_.type_)
317
318  def _GenerateObjectTypeToValue(self, cpp_namespace, type_):
319    """Generates a function that serializes an object-representing type
320    into a base::DictionaryValue.
321    """
322    c = Code()
323    (c.Sblock('scoped_ptr<base::DictionaryValue> %s::ToValue() const {' %
324          cpp_namespace)
325        .Append('scoped_ptr<base::DictionaryValue> value('
326                    'new base::DictionaryValue());')
327        .Append()
328    )
329
330    for prop in type_.properties.values():
331      if prop.optional:
332        # Optional enum values are generated with a NONE enum value.
333        underlying_type = self._type_helper.FollowRef(prop.type_)
334        if underlying_type.property_type == PropertyType.ENUM:
335          c.Sblock('if (%s != %s) {' %
336              (prop.unix_name,
337               self._type_helper.GetEnumNoneValue(prop.type_)))
338        else:
339          c.Sblock('if (%s.get()) {' % prop.unix_name)
340
341      # ANY is a base::Value which is abstract and cannot be a direct member, so
342      # it will always be a pointer.
343      is_ptr = prop.optional or prop.type_.property_type == PropertyType.ANY
344      c.Append('value->SetWithoutPathExpansion("%s", %s);' % (
345          prop.name,
346          self._CreateValueFromType(prop.type_,
347                                    'this->%s' % prop.unix_name,
348                                    is_ptr=is_ptr)))
349
350      if prop.optional:
351        c.Eblock('}');
352
353    if type_.additional_properties is not None:
354      if type_.additional_properties.property_type == PropertyType.ANY:
355        c.Append('value->MergeDictionary(&additional_properties);')
356      else:
357        # Non-copyable types will be wrapped in a linked_ptr for inclusion in
358        # maps, so we need to unwrap them.
359        needs_unwrap = (
360            not self._type_helper.IsCopyable(type_.additional_properties))
361        cpp_type = self._type_helper.GetCppType(type_.additional_properties,
362                                                is_in_container=True)
363        (c.Sblock('for (std::map<std::string, %s>::const_iterator it =' %
364                      cpp_util.PadForGenerics(cpp_type))
365          .Append('       additional_properties.begin();')
366          .Append('   it != additional_properties.end(); ++it) {')
367          .Append('value->SetWithoutPathExpansion(it->first, %s);' %
368              self._CreateValueFromType(
369                  type_.additional_properties,
370                  '%sit->second' % ('*' if needs_unwrap else '')))
371          .Eblock('}')
372        )
373
374    return (c.Append()
375             .Append('return value.Pass();')
376           .Eblock('}'))
377
378  def _GenerateChoiceTypeToValue(self, cpp_namespace, type_):
379    """Generates a function that serializes a choice-representing type
380    into a base::Value.
381    """
382    c = Code()
383    c.Sblock('scoped_ptr<base::Value> %s::ToValue() const {' % cpp_namespace)
384    c.Append('scoped_ptr<base::Value> result;');
385    for choice in type_.choices:
386      choice_var = 'as_%s' % choice.unix_name
387      (c.Sblock('if (%s) {' % choice_var)
388          .Append('DCHECK(!result) << "Cannot set multiple choices for %s";' %
389                      type_.unix_name)
390          .Append('result.reset(%s);' %
391                      self._CreateValueFromType(choice, '*%s' % choice_var))
392        .Eblock('}')
393      )
394    (c.Append('DCHECK(result) << "Must set at least one choice for %s";' %
395                  type_.unix_name)
396      .Append('return result.Pass();')
397      .Eblock('}')
398    )
399    return c
400
401  def _GenerateFunction(self, function):
402    """Generates the definitions for function structs.
403    """
404    c = Code()
405
406    # TODO(kalman): use function.unix_name not Classname.
407    function_namespace = cpp_util.Classname(function.name)
408    """Windows has a #define for SendMessage, so to avoid any issues, we need
409    to not use the name.
410    """
411    if function_namespace == 'SendMessage':
412      function_namespace = 'PassMessage'
413    (c.Append('namespace %s {' % function_namespace)
414      .Append()
415    )
416
417    # Params::Populate function
418    if function.params:
419      c.Concat(self._GeneratePropertyFunctions('Params', function.params))
420      (c.Append('Params::Params() {}')
421        .Append('Params::~Params() {}')
422        .Append()
423        .Cblock(self._GenerateFunctionParamsCreate(function))
424      )
425
426    # Results::Create function
427    if function.callback:
428      c.Concat(self._GenerateCreateCallbackArguments('Results',
429                                                     function.callback))
430
431    c.Append('}  // namespace %s' % function_namespace)
432    return c
433
434  def _GenerateEvent(self, event):
435    # TODO(kalman): use event.unix_name not Classname.
436    c = Code()
437    event_namespace = cpp_util.Classname(event.name)
438    (c.Append('namespace %s {' % event_namespace)
439      .Append()
440      .Cblock(self._GenerateEventNameConstant(None, event))
441      .Cblock(self._GenerateCreateCallbackArguments(None, event))
442      .Append('}  // namespace %s' % event_namespace)
443    )
444    return c
445
446  def _CreateValueFromType(self, type_, var, is_ptr=False):
447    """Creates a base::Value given a type. Generated code passes ownership
448    to caller.
449
450    var: variable or variable*
451
452    E.g for std::string, generate base::Value::CreateStringValue(var)
453    """
454    underlying_type = self._type_helper.FollowRef(type_)
455    if (underlying_type.property_type == PropertyType.CHOICES or
456        underlying_type.property_type == PropertyType.OBJECT):
457      if is_ptr:
458        return '(%s)->ToValue().release()' % var
459      else:
460        return '(%s).ToValue().release()' % var
461    elif (underlying_type.property_type == PropertyType.ANY or
462          underlying_type.property_type == PropertyType.FUNCTION):
463      if is_ptr:
464        vardot = '(%s)->' % var
465      else:
466        vardot = '(%s).' % var
467      return '%sDeepCopy()' % vardot
468    elif underlying_type.property_type == PropertyType.ENUM:
469      return 'base::Value::CreateStringValue(ToString(%s))' % var
470    elif underlying_type.property_type == PropertyType.BINARY:
471      if is_ptr:
472        vardot = var + '->'
473      else:
474        vardot = var + '.'
475      return ('base::BinaryValue::CreateWithCopiedBuffer(%sdata(), %ssize())' %
476              (vardot, vardot))
477    elif underlying_type.property_type == PropertyType.ARRAY:
478      return '%s.release()' % self._util_cc_helper.CreateValueFromArray(
479          underlying_type,
480          var,
481          is_ptr)
482    elif underlying_type.property_type.is_fundamental:
483      if is_ptr:
484        var = '*%s' % var
485      if underlying_type.property_type == PropertyType.STRING:
486        return 'new base::StringValue(%s)' % var
487      else:
488        return 'new base::FundamentalValue(%s)' % var
489    else:
490      raise NotImplementedError('Conversion of %s to base::Value not '
491                                'implemented' % repr(type_.type_))
492
493  def _GenerateParamsCheck(self, function, var):
494    """Generates a check for the correct number of arguments when creating
495    Params.
496    """
497    c = Code()
498    num_required = 0
499    for param in function.params:
500      if not param.optional:
501        num_required += 1
502    if num_required == len(function.params):
503      c.Sblock('if (%(var)s.GetSize() != %(total)d) {')
504    elif not num_required:
505      c.Sblock('if (%(var)s.GetSize() > %(total)d) {')
506    else:
507      c.Sblock('if (%(var)s.GetSize() < %(required)d'
508          ' || %(var)s.GetSize() > %(total)d) {')
509    (c.Concat(self._GenerateError(
510        '"expected %%(total)d arguments, got " '
511        '+ base::IntToString(%%(var)s.GetSize())'))
512      .Append('return scoped_ptr<Params>();')
513      .Eblock('}')
514      .Substitute({
515        'var': var,
516        'required': num_required,
517        'total': len(function.params),
518    }))
519    return c
520
521  def _GenerateFunctionParamsCreate(self, function):
522    """Generate function to create an instance of Params. The generated
523    function takes a base::ListValue of arguments.
524
525    E.g for function "Bar", generate Bar::Params::Create()
526    """
527    c = Code()
528    (c.Append('// static')
529      .Sblock('scoped_ptr<Params> Params::Create(%s) {' % self._GenerateParams(
530        ['const base::ListValue& args']))
531      .Concat(self._GenerateParamsCheck(function, 'args'))
532      .Append('scoped_ptr<Params> params(new Params());'))
533
534    for param in function.params:
535      c.Concat(self._InitializePropertyToDefault(param, 'params'))
536
537    for i, param in enumerate(function.params):
538      # Any failure will cause this function to return. If any argument is
539      # incorrect or missing, those following it are not processed. Note that
540      # for optional arguments, we allow missing arguments and proceed because
541      # there may be other arguments following it.
542      failure_value = 'scoped_ptr<Params>()'
543      c.Append()
544      value_var = param.unix_name + '_value'
545      (c.Append('const base::Value* %(value_var)s = NULL;')
546        .Append('if (args.Get(%(i)s, &%(value_var)s) &&')
547        .Sblock('    !%(value_var)s->IsType(base::Value::TYPE_NULL)) {')
548        .Concat(self._GeneratePopulatePropertyFromValue(
549            param, value_var, 'params', failure_value))
550        .Eblock('}')
551      )
552      if not param.optional:
553        (c.Sblock('else {')
554          .Concat(self._GenerateError('"\'%%(key)s\' is required"'))
555          .Append('return %s;' % failure_value)
556          .Eblock('}'))
557      c.Substitute({'value_var': value_var, 'i': i, 'key': param.name})
558    (c.Append()
559      .Append('return params.Pass();')
560      .Eblock('}')
561      .Append()
562    )
563
564    return c
565
566  def _GeneratePopulatePropertyFromValue(self,
567                                         prop,
568                                         src_var,
569                                         dst_class_var,
570                                         failure_value):
571    """Generates code to populate property |prop| of |dst_class_var| (a
572    pointer) from a Value*. See |_GeneratePopulateVariableFromValue| for
573    semantics.
574    """
575    return self._GeneratePopulateVariableFromValue(prop.type_,
576                                                   src_var,
577                                                   '%s->%s' % (dst_class_var,
578                                                               prop.unix_name),
579                                                   failure_value,
580                                                   is_ptr=prop.optional)
581
582  def _GeneratePopulateVariableFromValue(self,
583                                         type_,
584                                         src_var,
585                                         dst_var,
586                                         failure_value,
587                                         is_ptr=False):
588    """Generates code to populate a variable |dst_var| of type |type_| from a
589    Value* at |src_var|. The Value* is assumed to be non-NULL. In the generated
590    code, if |dst_var| fails to be populated then Populate will return
591    |failure_value|.
592    """
593    c = Code()
594    c.Sblock('{')
595
596    underlying_type = self._type_helper.FollowRef(type_)
597
598    if underlying_type.property_type.is_fundamental:
599      if is_ptr:
600        (c.Append('%(cpp_type)s temp;')
601          .Sblock('if (!%s) {' % cpp_util.GetAsFundamentalValue(
602                      self._type_helper.FollowRef(type_), src_var, '&temp'))
603          .Concat(self._GenerateError(
604            '"\'%%(key)s\': expected ' + '%s, got " + %s' % (
605                type_.name,
606                self._util_cc_helper.GetValueTypeString(
607                    '%%(src_var)s', True))))
608          .Append('return %(failure_value)s;')
609          .Eblock('}')
610          .Append('%(dst_var)s.reset(new %(cpp_type)s(temp));')
611        )
612      else:
613        (c.Sblock('if (!%s) {' % cpp_util.GetAsFundamentalValue(
614                      self._type_helper.FollowRef(type_),
615                      src_var,
616                      '&%s' % dst_var))
617          .Concat(self._GenerateError(
618            '"\'%%(key)s\': expected ' + '%s, got " + %s' % (
619                type_.name,
620                self._util_cc_helper.GetValueTypeString(
621                    '%%(src_var)s', True))))
622          .Append('return %(failure_value)s;')
623          .Eblock('}')
624        )
625    elif underlying_type.property_type == PropertyType.OBJECT:
626      if is_ptr:
627        (c.Append('const base::DictionaryValue* dictionary = NULL;')
628          .Sblock('if (!%(src_var)s->GetAsDictionary(&dictionary)) {')
629          .Concat(self._GenerateError(
630            '"\'%%(key)s\': expected dictionary, got " + ' +
631            self._util_cc_helper.GetValueTypeString('%%(src_var)s', True)))
632          .Append('return %(failure_value)s;')
633          .Eblock('}')
634          .Append('scoped_ptr<%(cpp_type)s> temp(new %(cpp_type)s());')
635          .Append('if (!%%(cpp_type)s::Populate(%s)) {' % self._GenerateArgs(
636            ('*dictionary', 'temp.get()')))
637          .Append('  return %(failure_value)s;')
638          .Append('}')
639          .Append('%(dst_var)s = temp.Pass();')
640        )
641      else:
642        (c.Append('const base::DictionaryValue* dictionary = NULL;')
643          .Sblock('if (!%(src_var)s->GetAsDictionary(&dictionary)) {')
644          .Concat(self._GenerateError(
645            '"\'%%(key)s\': expected dictionary, got " + ' +
646            self._util_cc_helper.GetValueTypeString('%%(src_var)s', True)))
647          .Append('return %(failure_value)s;')
648          .Eblock('}')
649          .Append('if (!%%(cpp_type)s::Populate(%s)) {' % self._GenerateArgs(
650            ('*dictionary', '&%(dst_var)s')))
651          .Append('  return %(failure_value)s;')
652          .Append('}')
653        )
654    elif underlying_type.property_type == PropertyType.FUNCTION:
655      if is_ptr:
656        c.Append('%(dst_var)s.reset(new base::DictionaryValue());')
657    elif underlying_type.property_type == PropertyType.ANY:
658      c.Append('%(dst_var)s.reset(%(src_var)s->DeepCopy());')
659    elif underlying_type.property_type == PropertyType.ARRAY:
660      # util_cc_helper deals with optional and required arrays
661      (c.Append('const base::ListValue* list = NULL;')
662        .Sblock('if (!%(src_var)s->GetAsList(&list)) {')
663          .Concat(self._GenerateError(
664            '"\'%%(key)s\': expected list, got " + ' +
665            self._util_cc_helper.GetValueTypeString('%%(src_var)s', True)))
666          .Append('return %(failure_value)s;')
667          .Eblock('}'))
668      item_type = self._type_helper.FollowRef(underlying_type.item_type)
669      if item_type.property_type == PropertyType.ENUM:
670        c.Concat(self._GenerateListValueToEnumArrayConversion(
671                     item_type,
672                     'list',
673                     dst_var,
674                     failure_value,
675                     is_ptr=is_ptr))
676      else:
677        (c.Sblock('if (!%s) {' % self._util_cc_helper.PopulateArrayFromList(
678              underlying_type,
679              'list',
680              dst_var,
681              is_ptr))
682          .Concat(self._GenerateError(
683            '"unable to populate array \'%%(parent_key)s\'"'))
684          .Append('return %(failure_value)s;')
685          .Eblock('}')
686        )
687    elif underlying_type.property_type == PropertyType.CHOICES:
688      if is_ptr:
689        (c.Append('scoped_ptr<%(cpp_type)s> temp(new %(cpp_type)s());')
690          .Append('if (!%%(cpp_type)s::Populate(%s))' % self._GenerateArgs(
691            ('*%(src_var)s', 'temp.get()')))
692          .Append('  return %(failure_value)s;')
693          .Append('%(dst_var)s = temp.Pass();')
694        )
695      else:
696        (c.Append('if (!%%(cpp_type)s::Populate(%s))' % self._GenerateArgs(
697            ('*%(src_var)s', '&%(dst_var)s')))
698          .Append('  return %(failure_value)s;'))
699    elif underlying_type.property_type == PropertyType.ENUM:
700      c.Concat(self._GenerateStringToEnumConversion(type_,
701                                                    src_var,
702                                                    dst_var,
703                                                    failure_value))
704    elif underlying_type.property_type == PropertyType.BINARY:
705      (c.Sblock('if (!%(src_var)s->IsType(base::Value::TYPE_BINARY)) {')
706        .Concat(self._GenerateError(
707          '"\'%%(key)s\': expected binary, got " + ' +
708          self._util_cc_helper.GetValueTypeString('%%(src_var)s', True)))
709        .Append('return %(failure_value)s;')
710        .Eblock('}')
711        .Append('const base::BinaryValue* binary_value =')
712        .Append('    static_cast<const base::BinaryValue*>(%(src_var)s);')
713      )
714      if is_ptr:
715        (c.Append('%(dst_var)s.reset(')
716          .Append('    new std::string(binary_value->GetBuffer(),')
717          .Append('                    binary_value->GetSize()));')
718        )
719      else:
720        (c.Append('%(dst_var)s.assign(binary_value->GetBuffer(),')
721          .Append('                   binary_value->GetSize());')
722        )
723    else:
724      raise NotImplementedError(type_)
725    return c.Eblock('}').Substitute({
726      'cpp_type': self._type_helper.GetCppType(type_),
727      'src_var': src_var,
728      'dst_var': dst_var,
729      'failure_value': failure_value,
730      'key': type_.name,
731      'parent_key': type_.parent.name
732    })
733
734  def _GenerateListValueToEnumArrayConversion(self,
735                                              item_type,
736                                              src_var,
737                                              dst_var,
738                                              failure_value,
739                                              is_ptr=False):
740      """Returns Code that converts a ListValue of string constants from
741      |src_var| into an array of enums of |type_| in |dst_var|. On failure,
742      returns |failure_value|.
743      """
744      c = Code()
745      accessor = '.'
746      if is_ptr:
747        accessor = '->'
748        cpp_type = self._type_helper.GetCppType(item_type, is_in_container=True)
749        c.Append('%s.reset(new std::vector<%s>);' %
750                     (dst_var, cpp_util.PadForGenerics(cpp_type)))
751      (c.Sblock('for (base::ListValue::const_iterator it = %s->begin(); '
752                     'it != %s->end(); ++it) {' % (src_var, src_var))
753        .Append('%s tmp;' % self._type_helper.GetCppType(item_type))
754        .Concat(self._GenerateStringToEnumConversion(item_type,
755                                                     '(*it)',
756                                                     'tmp',
757                                                     failure_value))
758        .Append('%s%spush_back(tmp);' % (dst_var, accessor))
759        .Eblock('}')
760      )
761      return c
762
763  def _GenerateStringToEnumConversion(self,
764                                      type_,
765                                      src_var,
766                                      dst_var,
767                                      failure_value):
768    """Returns Code that converts a string type in |src_var| to an enum with
769    type |type_| in |dst_var|. In the generated code, if |src_var| is not
770    a valid enum name then the function will return |failure_value|.
771    """
772    c = Code()
773    enum_as_string = '%s_as_string' % type_.unix_name
774    (c.Append('std::string %s;' % enum_as_string)
775      .Sblock('if (!%s->GetAsString(&%s)) {' % (src_var, enum_as_string))
776      .Concat(self._GenerateError(
777        '"\'%%(key)s\': expected string, got " + ' +
778        self._util_cc_helper.GetValueTypeString('%%(src_var)s', True)))
779      .Append('return %s;' % failure_value)
780      .Eblock('}')
781      .Append('%s = Parse%s(%s);' % (dst_var,
782                                     self._type_helper.GetCppType(type_),
783                                     enum_as_string))
784      .Sblock('if (%s == %s) {' % (dst_var,
785                                 self._type_helper.GetEnumNoneValue(type_)))
786      .Concat(self._GenerateError(
787        '\"\'%%(key)s\': expected \\"' +
788        '\\" or \\"'.join(self._type_helper.FollowRef(type_).enum_values) +
789        '\\", got \\"" + %s + "\\""' % enum_as_string))
790      .Append('return %s;' % failure_value)
791      .Eblock('}')
792      .Substitute({'src_var': src_var, 'key': type_.name})
793    )
794    return c
795
796  def _GeneratePropertyFunctions(self, namespace, params):
797    """Generates the member functions for a list of parameters.
798    """
799    return self._GenerateTypes(namespace, (param.type_ for param in params))
800
801  def _GenerateTypes(self, namespace, types):
802    """Generates the member functions for a list of types.
803    """
804    c = Code()
805    for type_ in types:
806      c.Cblock(self._GenerateType(namespace, type_))
807    return c
808
809  def _GenerateEnumToString(self, cpp_namespace, type_):
810    """Generates ToString() which gets the string representation of an enum.
811    """
812    c = Code()
813    classname = cpp_util.Classname(schema_util.StripNamespace(type_.name))
814
815    if cpp_namespace is not None:
816      c.Append('// static')
817    maybe_namespace = '' if cpp_namespace is None else '%s::' % cpp_namespace
818
819    c.Sblock('std::string %sToString(%s enum_param) {' %
820                 (maybe_namespace, classname))
821    c.Sblock('switch (enum_param) {')
822    for enum_value in self._type_helper.FollowRef(type_).enum_values:
823      (c.Append('case %s: ' % self._type_helper.GetEnumValue(type_, enum_value))
824        .Append('  return "%s";' % enum_value))
825    (c.Append('case %s:' % self._type_helper.GetEnumNoneValue(type_))
826      .Append('  return "";')
827      .Eblock('}')
828      .Append('NOTREACHED();')
829      .Append('return "";')
830      .Eblock('}')
831    )
832    return c
833
834  def _GenerateEnumFromString(self, cpp_namespace, type_):
835    """Generates FromClassNameString() which gets an enum from its string
836    representation.
837    """
838    c = Code()
839    classname = cpp_util.Classname(schema_util.StripNamespace(type_.name))
840
841    if cpp_namespace is not None:
842      c.Append('// static')
843    maybe_namespace = '' if cpp_namespace is None else '%s::' % cpp_namespace
844
845    c.Sblock('%s%s %sParse%s(const std::string& enum_string) {' %
846                 (maybe_namespace, classname, maybe_namespace, classname))
847    for i, enum_value in enumerate(
848          self._type_helper.FollowRef(type_).enum_values):
849      # This is broken up into all ifs with no else ifs because we get
850      # "fatal error C1061: compiler limit : blocks nested too deeply"
851      # on Windows.
852      (c.Append('if (enum_string == "%s")' % enum_value)
853        .Append('  return %s;' %
854            self._type_helper.GetEnumValue(type_, enum_value)))
855    (c.Append('return %s;' % self._type_helper.GetEnumNoneValue(type_))
856      .Eblock('}')
857    )
858    return c
859
860  def _GenerateCreateCallbackArguments(self, function_scope, callback):
861    """Generate all functions to create Value parameters for a callback.
862
863    E.g for function "Bar", generate Bar::Results::Create
864    E.g for event "Baz", generate Baz::Create
865
866    function_scope: the function scope path, e.g. Foo::Bar for the function
867                    Foo::Bar::Baz(). May be None if there is no function scope.
868    callback: the Function object we are creating callback arguments for.
869    """
870    c = Code()
871    params = callback.params
872    c.Concat(self._GeneratePropertyFunctions(function_scope, params))
873
874    (c.Sblock('scoped_ptr<base::ListValue> %(function_scope)s'
875                  'Create(%(declaration_list)s) {')
876      .Append('scoped_ptr<base::ListValue> create_results('
877              'new base::ListValue());')
878    )
879    declaration_list = []
880    for param in params:
881      declaration_list.append(cpp_util.GetParameterDeclaration(
882          param, self._type_helper.GetCppType(param.type_)))
883      c.Append('create_results->Append(%s);' %
884          self._CreateValueFromType(param.type_, param.unix_name))
885    c.Append('return create_results.Pass();')
886    c.Eblock('}')
887    c.Substitute({
888        'function_scope': ('%s::' % function_scope) if function_scope else '',
889        'declaration_list': ', '.join(declaration_list),
890        'param_names': ', '.join(param.unix_name for param in params)
891    })
892    return c
893
894  def _GenerateEventNameConstant(self, function_scope, event):
895    """Generates a constant string array for the event name.
896    """
897    c = Code()
898    c.Append('const char kEventName[] = "%s.%s";' % (
899                 self._namespace.name, event.name))
900    return c
901
902  def _InitializePropertyToDefault(self, prop, dst):
903    """Initialize a model.Property to its default value inside an object.
904
905    E.g for optional enum "state", generate dst->state = STATE_NONE;
906
907    dst: Type*
908    """
909    c = Code()
910    underlying_type = self._type_helper.FollowRef(prop.type_)
911    if (underlying_type.property_type == PropertyType.ENUM and
912        prop.optional):
913      c.Append('%s->%s = %s;' % (
914        dst,
915        prop.unix_name,
916        self._type_helper.GetEnumNoneValue(prop.type_)))
917    return c
918
919  def _GenerateError(self, body):
920    """Generates an error message pertaining to population failure.
921
922    E.g 'expected bool, got int'
923    """
924    c = Code()
925    if not self._generate_error_messages:
926      return c
927    (c.Append('if (error)')
928      .Append('  *error = ' + body + ';'))
929    return c
930
931  def _GenerateParams(self, params):
932    """Builds the parameter list for a function, given an array of parameters.
933    """
934    if self._generate_error_messages:
935      params = list(params) + ['std::string* error']
936    return ', '.join(str(p) for p in params)
937
938  def _GenerateArgs(self, args):
939    """Builds the argument list for a function, given an array of arguments.
940    """
941    if self._generate_error_messages:
942      args = list(args) + ['error']
943    return ', '.join(str(a) for a in args)
944