cc_generator.py revision 5d1f7b1de12d16ceb2c938c56701a3e8bfa558f7
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      .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    c.Append()
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    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 new base::StringValue(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 'new base::StringValue(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
595    underlying_type = self._type_helper.FollowRef(type_)
596
597    if underlying_type.property_type.is_fundamental:
598      if is_ptr:
599        (c.Append('%(cpp_type)s temp;')
600          .Sblock('if (!%s) {' % cpp_util.GetAsFundamentalValue(
601                      self._type_helper.FollowRef(type_), src_var, '&temp'))
602          .Concat(self._GenerateError(
603            '"\'%%(key)s\': expected ' + '%s, got " + %s' % (
604                type_.name,
605                self._util_cc_helper.GetValueTypeString(
606                    '%%(src_var)s', True))))
607          .Append('return %(failure_value)s;')
608          .Eblock('}')
609          .Append('%(dst_var)s.reset(new %(cpp_type)s(temp));')
610        )
611      else:
612        (c.Sblock('if (!%s) {' % cpp_util.GetAsFundamentalValue(
613                      self._type_helper.FollowRef(type_),
614                      src_var,
615                      '&%s' % dst_var))
616          .Concat(self._GenerateError(
617            '"\'%%(key)s\': expected ' + '%s, got " + %s' % (
618                type_.name,
619                self._util_cc_helper.GetValueTypeString(
620                    '%%(src_var)s', True))))
621          .Append('return %(failure_value)s;')
622          .Eblock('}')
623        )
624    elif underlying_type.property_type == PropertyType.OBJECT:
625      if is_ptr:
626        (c.Append('const base::DictionaryValue* dictionary = NULL;')
627          .Sblock('if (!%(src_var)s->GetAsDictionary(&dictionary)) {')
628          .Concat(self._GenerateError(
629            '"\'%%(key)s\': expected dictionary, got " + ' +
630            self._util_cc_helper.GetValueTypeString('%%(src_var)s', True)))
631          .Append('return %(failure_value)s;')
632          .Eblock('}')
633          .Append('scoped_ptr<%(cpp_type)s> temp(new %(cpp_type)s());')
634          .Append('if (!%%(cpp_type)s::Populate(%s)) {' % self._GenerateArgs(
635            ('*dictionary', 'temp.get()')))
636          .Append('  return %(failure_value)s;')
637          .Append('}')
638          .Append('%(dst_var)s = temp.Pass();')
639        )
640      else:
641        (c.Append('const base::DictionaryValue* dictionary = NULL;')
642          .Sblock('if (!%(src_var)s->GetAsDictionary(&dictionary)) {')
643          .Concat(self._GenerateError(
644            '"\'%%(key)s\': expected dictionary, got " + ' +
645            self._util_cc_helper.GetValueTypeString('%%(src_var)s', True)))
646          .Append('return %(failure_value)s;')
647          .Eblock('}')
648          .Append('if (!%%(cpp_type)s::Populate(%s)) {' % self._GenerateArgs(
649            ('*dictionary', '&%(dst_var)s')))
650          .Append('  return %(failure_value)s;')
651          .Append('}')
652        )
653    elif underlying_type.property_type == PropertyType.FUNCTION:
654      if is_ptr:
655        c.Append('%(dst_var)s.reset(new base::DictionaryValue());')
656    elif underlying_type.property_type == PropertyType.ANY:
657      c.Append('%(dst_var)s.reset(%(src_var)s->DeepCopy());')
658    elif underlying_type.property_type == PropertyType.ARRAY:
659      # util_cc_helper deals with optional and required arrays
660      (c.Append('const base::ListValue* list = NULL;')
661        .Sblock('if (!%(src_var)s->GetAsList(&list)) {')
662          .Concat(self._GenerateError(
663            '"\'%%(key)s\': expected list, got " + ' +
664            self._util_cc_helper.GetValueTypeString('%%(src_var)s', True)))
665          .Append('return %(failure_value)s;')
666          .Eblock('}'))
667      item_type = self._type_helper.FollowRef(underlying_type.item_type)
668      if item_type.property_type == PropertyType.ENUM:
669        c.Concat(self._GenerateListValueToEnumArrayConversion(
670                     item_type,
671                     'list',
672                     dst_var,
673                     failure_value,
674                     is_ptr=is_ptr))
675      else:
676        (c.Sblock('if (!%s) {' % self._util_cc_helper.PopulateArrayFromList(
677              underlying_type,
678              'list',
679              dst_var,
680              is_ptr))
681          .Concat(self._GenerateError(
682            '"unable to populate array \'%%(parent_key)s\'"'))
683          .Append('return %(failure_value)s;')
684          .Eblock('}')
685        )
686    elif underlying_type.property_type == PropertyType.CHOICES:
687      if is_ptr:
688        (c.Append('scoped_ptr<%(cpp_type)s> temp(new %(cpp_type)s());')
689          .Append('if (!%%(cpp_type)s::Populate(%s))' % self._GenerateArgs(
690            ('*%(src_var)s', 'temp.get()')))
691          .Append('  return %(failure_value)s;')
692          .Append('%(dst_var)s = temp.Pass();')
693        )
694      else:
695        (c.Append('if (!%%(cpp_type)s::Populate(%s))' % self._GenerateArgs(
696            ('*%(src_var)s', '&%(dst_var)s')))
697          .Append('  return %(failure_value)s;'))
698    elif underlying_type.property_type == PropertyType.ENUM:
699      c.Concat(self._GenerateStringToEnumConversion(type_,
700                                                    src_var,
701                                                    dst_var,
702                                                    failure_value))
703    elif underlying_type.property_type == PropertyType.BINARY:
704      (c.Sblock('if (!%(src_var)s->IsType(base::Value::TYPE_BINARY)) {')
705        .Concat(self._GenerateError(
706          '"\'%%(key)s\': expected binary, got " + ' +
707          self._util_cc_helper.GetValueTypeString('%%(src_var)s', True)))
708        .Append('return %(failure_value)s;')
709        .Eblock('}')
710        .Append('const base::BinaryValue* binary_value =')
711        .Append('    static_cast<const base::BinaryValue*>(%(src_var)s);')
712      )
713      if is_ptr:
714        (c.Append('%(dst_var)s.reset(')
715          .Append('    new std::string(binary_value->GetBuffer(),')
716          .Append('                    binary_value->GetSize()));')
717        )
718      else:
719        (c.Append('%(dst_var)s.assign(binary_value->GetBuffer(),')
720          .Append('                   binary_value->GetSize());')
721        )
722    else:
723      raise NotImplementedError(type_)
724    if c.IsEmpty():
725      return c
726    return Code().Sblock('{').Concat(c.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    })).Eblock('}')
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(
790            enum_value.name
791            for enum_value in self._type_helper.FollowRef(type_).enum_values) +
792        '\\", got \\"" + %s + "\\""' % enum_as_string))
793      .Append('return %s;' % failure_value)
794      .Eblock('}')
795      .Substitute({'src_var': src_var, 'key': type_.name})
796    )
797    return c
798
799  def _GeneratePropertyFunctions(self, namespace, params):
800    """Generates the member functions for a list of parameters.
801    """
802    return self._GenerateTypes(namespace, (param.type_ for param in params))
803
804  def _GenerateTypes(self, namespace, types):
805    """Generates the member functions for a list of types.
806    """
807    c = Code()
808    for type_ in types:
809      c.Cblock(self._GenerateType(namespace, type_))
810    return c
811
812  def _GenerateEnumToString(self, cpp_namespace, type_):
813    """Generates ToString() which gets the string representation of an enum.
814    """
815    c = Code()
816    classname = cpp_util.Classname(schema_util.StripNamespace(type_.name))
817
818    if cpp_namespace is not None:
819      c.Append('// static')
820    maybe_namespace = '' if cpp_namespace is None else '%s::' % cpp_namespace
821
822    c.Sblock('std::string %sToString(%s enum_param) {' %
823                 (maybe_namespace, classname))
824    c.Sblock('switch (enum_param) {')
825    for enum_value in self._type_helper.FollowRef(type_).enum_values:
826      (c.Append('case %s: ' % self._type_helper.GetEnumValue(type_, enum_value))
827        .Append('  return "%s";' % enum_value.name))
828    (c.Append('case %s:' % self._type_helper.GetEnumNoneValue(type_))
829      .Append('  return "";')
830      .Eblock('}')
831      .Append('NOTREACHED();')
832      .Append('return "";')
833      .Eblock('}')
834    )
835    return c
836
837  def _GenerateEnumFromString(self, cpp_namespace, type_):
838    """Generates FromClassNameString() which gets an enum from its string
839    representation.
840    """
841    c = Code()
842    classname = cpp_util.Classname(schema_util.StripNamespace(type_.name))
843
844    if cpp_namespace is not None:
845      c.Append('// static')
846    maybe_namespace = '' if cpp_namespace is None else '%s::' % cpp_namespace
847
848    c.Sblock('%s%s %sParse%s(const std::string& enum_string) {' %
849                 (maybe_namespace, classname, maybe_namespace, classname))
850    for i, enum_value in enumerate(
851          self._type_helper.FollowRef(type_).enum_values):
852      # This is broken up into all ifs with no else ifs because we get
853      # "fatal error C1061: compiler limit : blocks nested too deeply"
854      # on Windows.
855      (c.Append('if (enum_string == "%s")' % enum_value.name)
856        .Append('  return %s;' %
857            self._type_helper.GetEnumValue(type_, enum_value)))
858    (c.Append('return %s;' % self._type_helper.GetEnumNoneValue(type_))
859      .Eblock('}')
860    )
861    return c
862
863  def _GenerateCreateCallbackArguments(self, function_scope, callback):
864    """Generate all functions to create Value parameters for a callback.
865
866    E.g for function "Bar", generate Bar::Results::Create
867    E.g for event "Baz", generate Baz::Create
868
869    function_scope: the function scope path, e.g. Foo::Bar for the function
870                    Foo::Bar::Baz(). May be None if there is no function scope.
871    callback: the Function object we are creating callback arguments for.
872    """
873    c = Code()
874    params = callback.params
875    c.Concat(self._GeneratePropertyFunctions(function_scope, params))
876
877    (c.Sblock('scoped_ptr<base::ListValue> %(function_scope)s'
878                  'Create(%(declaration_list)s) {')
879      .Append('scoped_ptr<base::ListValue> create_results('
880              'new base::ListValue());')
881    )
882    declaration_list = []
883    for param in params:
884      declaration_list.append(cpp_util.GetParameterDeclaration(
885          param, self._type_helper.GetCppType(param.type_)))
886      c.Append('create_results->Append(%s);' %
887          self._CreateValueFromType(param.type_, param.unix_name))
888    c.Append('return create_results.Pass();')
889    c.Eblock('}')
890    c.Substitute({
891        'function_scope': ('%s::' % function_scope) if function_scope else '',
892        'declaration_list': ', '.join(declaration_list),
893        'param_names': ', '.join(param.unix_name for param in params)
894    })
895    return c
896
897  def _GenerateEventNameConstant(self, function_scope, event):
898    """Generates a constant string array for the event name.
899    """
900    c = Code()
901    c.Append('const char kEventName[] = "%s.%s";' % (
902                 self._namespace.name, event.name))
903    return c
904
905  def _InitializePropertyToDefault(self, prop, dst):
906    """Initialize a model.Property to its default value inside an object.
907
908    E.g for optional enum "state", generate dst->state = STATE_NONE;
909
910    dst: Type*
911    """
912    c = Code()
913    underlying_type = self._type_helper.FollowRef(prop.type_)
914    if (underlying_type.property_type == PropertyType.ENUM and
915        prop.optional):
916      c.Append('%s->%s = %s;' % (
917        dst,
918        prop.unix_name,
919        self._type_helper.GetEnumNoneValue(prop.type_)))
920    return c
921
922  def _GenerateError(self, body):
923    """Generates an error message pertaining to population failure.
924
925    E.g 'expected bool, got int'
926    """
927    c = Code()
928    if not self._generate_error_messages:
929      return c
930    (c.Append('if (error)')
931      .Append('  *error = base::UTF8ToUTF16(' + body + ');'))
932    return c
933
934  def _GenerateParams(self, params):
935    """Builds the parameter list for a function, given an array of parameters.
936    """
937    if self._generate_error_messages:
938      params = list(params) + ['base::string16* error']
939    return ', '.join(str(p) for p in params)
940
941  def _GenerateArgs(self, args):
942    """Builds the argument list for a function, given an array of arguments.
943    """
944    if self._generate_error_messages:
945      args = list(args) + ['error']
946    return ', '.join(str(a) for a in args)
947