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