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