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