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