[Chromoting] Add app_remoting/internal to .gitignore
[chromium-blink-merge.git] / tools / json_schema_compiler / cc_generator.py
blobdb832bef9eac39426f0247d82130804b6bcdbacf
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 items.append('%s(%s)' % (
152 prop.unix_name,
153 self._type_helper.GetEnumNoneValue(t)))
154 elif prop.optional:
155 continue
156 elif t.property_type == PropertyType.INTEGER:
157 items.append('%s(0)' % prop.unix_name)
158 elif t.property_type == PropertyType.DOUBLE:
159 items.append('%s(0.0)' % prop.unix_name)
160 elif t.property_type == PropertyType.BOOLEAN:
161 items.append('%s(false)' % prop.unix_name)
162 elif (t.property_type == PropertyType.ANY or
163 t.property_type == PropertyType.ARRAY or
164 t.property_type == PropertyType.BINARY or
165 t.property_type == PropertyType.CHOICES or
166 t.property_type == PropertyType.OBJECT or
167 t.property_type == PropertyType.FUNCTION or
168 t.property_type == PropertyType.REF or
169 t.property_type == PropertyType.STRING):
170 # TODO(miket): It would be nice to initialize CHOICES, but we
171 # don't presently have the semantics to indicate which one of a set
172 # should be the default.
173 continue
174 else:
175 raise TypeError(t)
177 if items:
178 s = ': %s' % (', '.join(items))
179 else:
180 s = ''
181 s = s + ' {}'
182 return Code().Append(s)
184 def _GenerateTypePopulate(self, cpp_namespace, type_):
185 """Generates the function for populating a type given a pointer to it.
187 E.g for type "Foo", generates Foo::Populate()
189 classname = cpp_util.Classname(schema_util.StripNamespace(type_.name))
190 c = Code()
191 (c.Append('// static')
192 .Append('bool %(namespace)s::Populate(')
193 .Sblock(' %s) {' % self._GenerateParams(
194 ('const base::Value& value', '%(name)s* out'))))
196 if self._generate_error_messages:
197 c.Append('DCHECK(error);')
199 if type_.property_type == PropertyType.CHOICES:
200 for choice in type_.choices:
201 (c.Sblock('if (%s) {' % self._GenerateValueIsTypeExpression('value',
202 choice))
203 .Concat(self._GeneratePopulateVariableFromValue(
204 choice,
205 '(&value)',
206 'out->as_%s' % choice.unix_name,
207 'false',
208 is_ptr=True))
209 .Append('return true;')
210 .Eblock('}')
212 (c.Concat(self._GenerateError(
213 '"expected %s, got " + %s' %
214 (" or ".join(choice.name for choice in type_.choices),
215 self._util_cc_helper.GetValueTypeString('value'))))
216 .Append('return false;'))
217 elif type_.property_type == PropertyType.OBJECT:
218 (c.Sblock('if (!value.IsType(base::Value::TYPE_DICTIONARY)) {')
219 .Concat(self._GenerateError(
220 '"expected dictionary, got " + ' +
221 self._util_cc_helper.GetValueTypeString('value')))
222 .Append('return false;')
223 .Eblock('}'))
225 if type_.properties or type_.additional_properties is not None:
226 c.Append('const base::DictionaryValue* dict = '
227 'static_cast<const base::DictionaryValue*>(&value);')
228 if self._generate_error_messages:
229 c.Append('std::set<std::string> keys;')
230 for prop in type_.properties.itervalues():
231 c.Concat(self._InitializePropertyToDefault(prop, 'out'))
232 for prop in type_.properties.itervalues():
233 if self._generate_error_messages:
234 c.Append('keys.insert("%s");' % (prop.name))
235 c.Concat(self._GenerateTypePopulateProperty(prop, 'dict', 'out'))
236 # Check for extra values.
237 if self._generate_error_messages:
238 (c.Sblock('for (base::DictionaryValue::Iterator it(*dict); '
239 '!it.IsAtEnd(); it.Advance()) {')
240 .Sblock('if (!keys.count(it.key())) {')
241 .Concat(self._GenerateError('"found unexpected key \'" + '
242 'it.key() + "\'"'))
243 .Eblock('}')
244 .Eblock('}')
246 if type_.additional_properties is not None:
247 if type_.additional_properties.property_type == PropertyType.ANY:
248 c.Append('out->additional_properties.MergeDictionary(dict);')
249 else:
250 cpp_type = self._type_helper.GetCppType(type_.additional_properties,
251 is_in_container=True)
252 (c.Append('for (base::DictionaryValue::Iterator it(*dict);')
253 .Sblock(' !it.IsAtEnd(); it.Advance()) {')
254 .Append('%s tmp;' % cpp_type)
255 .Concat(self._GeneratePopulateVariableFromValue(
256 type_.additional_properties,
257 '(&it.value())',
258 'tmp',
259 'false'))
260 .Append('out->additional_properties[it.key()] = tmp;')
261 .Eblock('}')
263 c.Append('return true;')
264 (c.Eblock('}')
265 .Substitute({'namespace': cpp_namespace, 'name': classname}))
266 return c
268 def _GenerateValueIsTypeExpression(self, var, type_):
269 real_type = self._type_helper.FollowRef(type_)
270 if real_type.property_type is PropertyType.CHOICES:
271 return '(%s)' % ' || '.join(self._GenerateValueIsTypeExpression(var,
272 choice)
273 for choice in real_type.choices)
274 return '%s.IsType(%s)' % (var, cpp_util.GetValueType(real_type))
276 def _GenerateTypePopulateProperty(self, prop, src, dst):
277 """Generate the code to populate a single property in a type.
279 src: base::DictionaryValue*
280 dst: Type*
282 c = Code()
283 value_var = prop.unix_name + '_value'
284 c.Append('const base::Value* %(value_var)s = NULL;')
285 if prop.optional:
286 (c.Sblock(
287 'if (%(src)s->GetWithoutPathExpansion("%(key)s", &%(value_var)s)) {')
288 .Concat(self._GeneratePopulatePropertyFromValue(
289 prop, value_var, dst, 'false')))
290 underlying_type = self._type_helper.FollowRef(prop.type_)
291 if underlying_type.property_type == PropertyType.ENUM:
292 (c.Append('} else {')
293 .Append('%%(dst)s->%%(name)s = %s;' %
294 self._type_helper.GetEnumNoneValue(prop.type_)))
295 c.Eblock('}')
296 else:
297 (c.Sblock(
298 'if (!%(src)s->GetWithoutPathExpansion("%(key)s", &%(value_var)s)) {')
299 .Concat(self._GenerateError('"\'%%(key)s\' is required"'))
300 .Append('return false;')
301 .Eblock('}')
302 .Concat(self._GeneratePopulatePropertyFromValue(
303 prop, value_var, dst, 'false'))
305 c.Append()
306 c.Substitute({
307 'value_var': value_var,
308 'key': prop.name,
309 'src': src,
310 'dst': dst,
311 'name': prop.unix_name
313 return c
315 def _GenerateTypeFromValue(self, cpp_namespace, type_):
316 classname = cpp_util.Classname(schema_util.StripNamespace(type_.name))
317 c = Code()
318 (c.Append('// static')
319 .Append('scoped_ptr<%s> %s::FromValue(%s) {' % (classname,
320 cpp_namespace, self._GenerateParams(('const base::Value& value',))))
322 if self._generate_error_messages:
323 c.Append('DCHECK(error);')
324 (c.Append(' scoped_ptr<%s> out(new %s());' % (classname, classname))
325 .Append(' if (!Populate(%s))' % self._GenerateArgs(
326 ('value', 'out.get()')))
327 .Append(' return scoped_ptr<%s>();' % classname)
328 .Append(' return out.Pass();')
329 .Append('}')
331 return c
333 def _GenerateTypeToValue(self, cpp_namespace, type_):
334 """Generates a function that serializes the type into a base::Value.
335 E.g. for type "Foo" generates Foo::ToValue()
337 if type_.property_type == PropertyType.OBJECT:
338 return self._GenerateObjectTypeToValue(cpp_namespace, type_)
339 elif type_.property_type == PropertyType.CHOICES:
340 return self._GenerateChoiceTypeToValue(cpp_namespace, type_)
341 else:
342 raise ValueError("Unsupported property type %s" % type_.type_)
344 def _GenerateObjectTypeToValue(self, cpp_namespace, type_):
345 """Generates a function that serializes an object-representing type
346 into a base::DictionaryValue.
348 c = Code()
349 (c.Sblock('scoped_ptr<base::DictionaryValue> %s::ToValue() const {' %
350 cpp_namespace)
351 .Append('scoped_ptr<base::DictionaryValue> value('
352 'new base::DictionaryValue());')
353 .Append()
356 for prop in type_.properties.values():
357 prop_var = 'this->%s' % prop.unix_name
358 if prop.optional:
359 # Optional enum values are generated with a NONE enum value.
360 underlying_type = self._type_helper.FollowRef(prop.type_)
361 if underlying_type.property_type == PropertyType.ENUM:
362 c.Sblock('if (%s != %s) {' %
363 (prop_var,
364 self._type_helper.GetEnumNoneValue(prop.type_)))
365 else:
366 c.Sblock('if (%s.get()) {' % prop_var)
368 # ANY is a base::Value which is abstract and cannot be a direct member, so
369 # it will always be a pointer.
370 is_ptr = prop.optional or prop.type_.property_type == PropertyType.ANY
371 c.Cblock(self._CreateValueFromType(
372 'value->SetWithoutPathExpansion("%s", %%s);' % prop.name,
373 prop.name,
374 prop.type_,
375 prop_var,
376 is_ptr=is_ptr))
378 if prop.optional:
379 c.Eblock('}')
381 if type_.additional_properties is not None:
382 if type_.additional_properties.property_type == PropertyType.ANY:
383 c.Append('value->MergeDictionary(&additional_properties);')
384 else:
385 # Non-copyable types will be wrapped in a linked_ptr for inclusion in
386 # maps, so we need to unwrap them.
387 needs_unwrap = (
388 not self._type_helper.IsCopyable(type_.additional_properties))
389 (c.Sblock('for (const auto& it : additional_properties) {')
390 .Cblock(self._CreateValueFromType(
391 'value->SetWithoutPathExpansion(it.first, %s);',
392 type_.additional_properties.name,
393 type_.additional_properties,
394 '%sit.second' % ('*' if needs_unwrap else '')))
395 .Eblock('}')
398 return (c.Append()
399 .Append('return value.Pass();')
400 .Eblock('}'))
402 def _GenerateChoiceTypeToValue(self, cpp_namespace, type_):
403 """Generates a function that serializes a choice-representing type
404 into a base::Value.
406 c = Code()
407 c.Sblock('scoped_ptr<base::Value> %s::ToValue() const {' % cpp_namespace)
408 c.Append('scoped_ptr<base::Value> result;')
409 for choice in type_.choices:
410 choice_var = 'as_%s' % choice.unix_name
411 (c.Sblock('if (%s) {' % choice_var)
412 .Append('DCHECK(!result) << "Cannot set multiple choices for %s";' %
413 type_.unix_name)
414 .Cblock(self._CreateValueFromType('result.reset(%s);',
415 choice.name,
416 choice,
417 '*%s' % choice_var))
418 .Eblock('}')
420 (c.Append('DCHECK(result) << "Must set at least one choice for %s";' %
421 type_.unix_name)
422 .Append('return result.Pass();')
423 .Eblock('}')
425 return c
427 def _GenerateFunction(self, function):
428 """Generates the definitions for function structs.
430 c = Code()
432 # TODO(kalman): use function.unix_name not Classname.
433 function_namespace = cpp_util.Classname(function.name)
434 # Windows has a #define for SendMessage, so to avoid any issues, we need
435 # to not use the name.
436 if function_namespace == 'SendMessage':
437 function_namespace = 'PassMessage'
438 (c.Append('namespace %s {' % function_namespace)
439 .Append()
442 # Params::Populate function
443 if function.params:
444 c.Concat(self._GeneratePropertyFunctions('Params', function.params))
445 (c.Append('Params::Params() {}')
446 .Append('Params::~Params() {}')
447 .Append()
448 .Cblock(self._GenerateFunctionParamsCreate(function))
451 # Results::Create function
452 if function.callback:
453 c.Concat(self._GenerateCreateCallbackArguments('Results',
454 function.callback))
456 c.Append('} // namespace %s' % function_namespace)
457 return c
459 def _GenerateEvent(self, event):
460 # TODO(kalman): use event.unix_name not Classname.
461 c = Code()
462 event_namespace = cpp_util.Classname(event.name)
463 (c.Append('namespace %s {' % event_namespace)
464 .Append()
465 .Cblock(self._GenerateEventNameConstant(event))
466 .Cblock(self._GenerateCreateCallbackArguments(None, event))
467 .Append('} // namespace %s' % event_namespace)
469 return c
471 def _CreateValueFromType(self, code, prop_name, type_, var, is_ptr=False):
472 """Creates a base::Value given a type. Generated code passes ownership
473 to caller.
475 var: variable or variable*
477 E.g for std::string, generate new base::StringValue(var)
479 c = Code()
480 underlying_type = self._type_helper.FollowRef(type_)
481 if underlying_type.property_type == PropertyType.ARRAY:
482 # Enums are treated specially because C++ templating thinks that they're
483 # ints, but really they're strings. So we create a vector of strings and
484 # populate it with the names of the enum in the array. The |ToString|
485 # function of the enum can be in another namespace when the enum is
486 # referenced. Templates can not be used here because C++ templating does
487 # not support passing a namespace as an argument.
488 item_type = self._type_helper.FollowRef(underlying_type.item_type)
489 if item_type.property_type == PropertyType.ENUM:
490 varname = ('*' if is_ptr else '') + '(%s)' % var
492 maybe_namespace = ''
493 if type_.item_type.property_type == PropertyType.REF:
494 maybe_namespace = '%s::' % item_type.namespace.unix_name
496 enum_list_var = '%s_list' % prop_name
497 # Scope the std::vector variable declaration inside braces.
498 (c.Sblock('{')
499 .Append('std::vector<std::string> %s;' % enum_list_var)
500 .Append('for (const auto& it : %s) {' % varname)
501 .Append('%s.push_back(%sToString(it));' % (enum_list_var,
502 maybe_namespace))
503 .Eblock('}'))
505 # Because the std::vector above is always created for both required and
506 # optional enum arrays, |is_ptr| is set to false and uses the
507 # std::vector to create the values.
508 (c.Append(code %
509 self._GenerateCreateValueFromType(type_, enum_list_var, False))
510 .Eblock('}'))
511 return c
513 c.Append(code % self._GenerateCreateValueFromType(type_, var, is_ptr))
514 return c
516 def _GenerateCreateValueFromType(self, type_, var, is_ptr):
517 """Generates the statement to create a base::Value given a type.
519 type_: The type of the values being converted.
520 var: The name of the variable.
521 is_ptr: Whether |type_| is optional.
523 underlying_type = self._type_helper.FollowRef(type_)
524 if (underlying_type.property_type == PropertyType.CHOICES or
525 underlying_type.property_type == PropertyType.OBJECT):
526 if is_ptr:
527 return '(%s)->ToValue().release()' % var
528 else:
529 return '(%s).ToValue().release()' % var
530 elif (underlying_type.property_type == PropertyType.ANY or
531 underlying_type.property_type == PropertyType.FUNCTION):
532 if is_ptr:
533 vardot = '(%s)->' % var
534 else:
535 vardot = '(%s).' % var
536 return '%sDeepCopy()' % vardot
537 elif underlying_type.property_type == PropertyType.ENUM:
538 maybe_namespace = ''
539 if type_.property_type == PropertyType.REF:
540 maybe_namespace = '%s::' % underlying_type.namespace.unix_name
541 return 'new base::StringValue(%sToString(%s))' % (maybe_namespace, var)
542 elif underlying_type.property_type == PropertyType.BINARY:
543 if is_ptr:
544 vardot = var + '->'
545 ref = var + '.get()'
546 else:
547 vardot = var + '.'
548 ref = '&' + var
549 return ('base::BinaryValue::CreateWithCopiedBuffer(vector_as_array(%s),'
550 ' %ssize())' % (ref, vardot))
551 elif underlying_type.property_type == PropertyType.ARRAY:
552 return '%s.release()' % self._util_cc_helper.CreateValueFromArray(
553 var,
554 is_ptr)
555 elif underlying_type.property_type.is_fundamental:
556 if is_ptr:
557 var = '*%s' % var
558 if underlying_type.property_type == PropertyType.STRING:
559 return 'new base::StringValue(%s)' % var
560 else:
561 return 'new base::FundamentalValue(%s)' % var
562 else:
563 raise NotImplementedError('Conversion of %s to base::Value not '
564 'implemented' % repr(type_.type_))
566 def _GenerateParamsCheck(self, function, var):
567 """Generates a check for the correct number of arguments when creating
568 Params.
570 c = Code()
571 num_required = 0
572 for param in function.params:
573 if not param.optional:
574 num_required += 1
575 if num_required == len(function.params):
576 c.Sblock('if (%(var)s.GetSize() != %(total)d) {')
577 elif not num_required:
578 c.Sblock('if (%(var)s.GetSize() > %(total)d) {')
579 else:
580 c.Sblock('if (%(var)s.GetSize() < %(required)d'
581 ' || %(var)s.GetSize() > %(total)d) {')
582 (c.Concat(self._GenerateError(
583 '"expected %%(total)d arguments, got " '
584 '+ base::IntToString(%%(var)s.GetSize())'))
585 .Append('return scoped_ptr<Params>();')
586 .Eblock('}')
587 .Substitute({
588 'var': var,
589 'required': num_required,
590 'total': len(function.params),
592 return c
594 def _GenerateFunctionParamsCreate(self, function):
595 """Generate function to create an instance of Params. The generated
596 function takes a base::ListValue of arguments.
598 E.g for function "Bar", generate Bar::Params::Create()
600 c = Code()
601 (c.Append('// static')
602 .Sblock('scoped_ptr<Params> Params::Create(%s) {' % self._GenerateParams(
603 ['const base::ListValue& args']))
605 if self._generate_error_messages:
606 c.Append('DCHECK(error);')
607 (c.Concat(self._GenerateParamsCheck(function, 'args'))
608 .Append('scoped_ptr<Params> params(new Params());')
611 for param in function.params:
612 c.Concat(self._InitializePropertyToDefault(param, 'params'))
614 for i, param in enumerate(function.params):
615 # Any failure will cause this function to return. If any argument is
616 # incorrect or missing, those following it are not processed. Note that
617 # for optional arguments, we allow missing arguments and proceed because
618 # there may be other arguments following it.
619 failure_value = 'scoped_ptr<Params>()'
620 c.Append()
621 value_var = param.unix_name + '_value'
622 (c.Append('const base::Value* %(value_var)s = NULL;')
623 .Append('if (args.Get(%(i)s, &%(value_var)s) &&')
624 .Sblock(' !%(value_var)s->IsType(base::Value::TYPE_NULL)) {')
625 .Concat(self._GeneratePopulatePropertyFromValue(
626 param, value_var, 'params', failure_value))
627 .Eblock('}')
629 if not param.optional:
630 (c.Sblock('else {')
631 .Concat(self._GenerateError('"\'%%(key)s\' is required"'))
632 .Append('return %s;' % failure_value)
633 .Eblock('}'))
634 c.Substitute({'value_var': value_var, 'i': i, 'key': param.name})
635 (c.Append()
636 .Append('return params.Pass();')
637 .Eblock('}')
638 .Append()
641 return c
643 def _GeneratePopulatePropertyFromValue(self,
644 prop,
645 src_var,
646 dst_class_var,
647 failure_value):
648 """Generates code to populate property |prop| of |dst_class_var| (a
649 pointer) from a Value*. See |_GeneratePopulateVariableFromValue| for
650 semantics.
652 return self._GeneratePopulateVariableFromValue(prop.type_,
653 src_var,
654 '%s->%s' % (dst_class_var,
655 prop.unix_name),
656 failure_value,
657 is_ptr=prop.optional)
659 def _GeneratePopulateVariableFromValue(self,
660 type_,
661 src_var,
662 dst_var,
663 failure_value,
664 is_ptr=False):
665 """Generates code to populate a variable |dst_var| of type |type_| from a
666 Value* at |src_var|. The Value* is assumed to be non-NULL. In the generated
667 code, if |dst_var| fails to be populated then Populate will return
668 |failure_value|.
670 c = Code()
672 underlying_type = self._type_helper.FollowRef(type_)
674 if underlying_type.property_type.is_fundamental:
675 if is_ptr:
676 (c.Append('%(cpp_type)s temp;')
677 .Sblock('if (!%s) {' % cpp_util.GetAsFundamentalValue(
678 self._type_helper.FollowRef(type_), src_var, '&temp'))
679 .Concat(self._GenerateError(
680 '"\'%%(key)s\': expected ' + '%s, got " + %s' % (
681 type_.name,
682 self._util_cc_helper.GetValueTypeString(
683 '%%(src_var)s', True)))))
684 c.Append('%(dst_var)s.reset();')
685 if not self._generate_error_messages:
686 c.Append('return %(failure_value)s;')
687 (c.Eblock('}')
688 .Append('else')
689 .Append(' %(dst_var)s.reset(new %(cpp_type)s(temp));')
691 else:
692 (c.Sblock('if (!%s) {' % cpp_util.GetAsFundamentalValue(
693 self._type_helper.FollowRef(type_),
694 src_var,
695 '&%s' % dst_var))
696 .Concat(self._GenerateError(
697 '"\'%%(key)s\': expected ' + '%s, got " + %s' % (
698 type_.name,
699 self._util_cc_helper.GetValueTypeString(
700 '%%(src_var)s', True))))
701 .Append('return %(failure_value)s;')
702 .Eblock('}')
704 elif underlying_type.property_type == PropertyType.OBJECT:
705 if is_ptr:
706 (c.Append('const base::DictionaryValue* dictionary = NULL;')
707 .Sblock('if (!%(src_var)s->GetAsDictionary(&dictionary)) {')
708 .Concat(self._GenerateError(
709 '"\'%%(key)s\': expected dictionary, got " + ' +
710 self._util_cc_helper.GetValueTypeString('%%(src_var)s', True))))
711 # If an optional property fails to populate, the population can still
712 # succeed with a warning. If no error messages are generated, this
713 # warning is not set and we fail out instead.
714 if not self._generate_error_messages:
715 c.Append('return %(failure_value)s;')
716 (c.Eblock('}')
717 .Sblock('else {')
718 .Append('scoped_ptr<%(cpp_type)s> temp(new %(cpp_type)s());')
719 .Append('if (!%%(cpp_type)s::Populate(%s)) {' % self._GenerateArgs(
720 ('*dictionary', 'temp.get()')))
721 .Append(' return %(failure_value)s;')
723 (c.Append('}')
724 .Append('else')
725 .Append(' %(dst_var)s = temp.Pass();')
726 .Eblock('}')
728 else:
729 (c.Append('const base::DictionaryValue* dictionary = NULL;')
730 .Sblock('if (!%(src_var)s->GetAsDictionary(&dictionary)) {')
731 .Concat(self._GenerateError(
732 '"\'%%(key)s\': expected dictionary, got " + ' +
733 self._util_cc_helper.GetValueTypeString('%%(src_var)s', True)))
734 .Append('return %(failure_value)s;')
735 .Eblock('}')
736 .Append('if (!%%(cpp_type)s::Populate(%s)) {' % self._GenerateArgs(
737 ('*dictionary', '&%(dst_var)s')))
738 .Append(' return %(failure_value)s;')
739 .Append('}')
741 elif underlying_type.property_type == PropertyType.FUNCTION:
742 if is_ptr:
743 c.Append('%(dst_var)s.reset(new base::DictionaryValue());')
744 elif underlying_type.property_type == PropertyType.ANY:
745 c.Append('%(dst_var)s.reset(%(src_var)s->DeepCopy());')
746 elif underlying_type.property_type == PropertyType.ARRAY:
747 # util_cc_helper deals with optional and required arrays
748 (c.Append('const base::ListValue* list = NULL;')
749 .Sblock('if (!%(src_var)s->GetAsList(&list)) {')
750 .Concat(self._GenerateError(
751 '"\'%%(key)s\': expected list, got " + ' +
752 self._util_cc_helper.GetValueTypeString('%%(src_var)s', True)))
754 if is_ptr and self._generate_error_messages:
755 c.Append('%(dst_var)s.reset();')
756 else:
757 c.Append('return %(failure_value)s;')
758 c.Eblock('}')
759 c.Sblock('else {')
760 item_type = self._type_helper.FollowRef(underlying_type.item_type)
761 if item_type.property_type == PropertyType.ENUM:
762 c.Concat(self._GenerateListValueToEnumArrayConversion(
763 item_type,
764 'list',
765 dst_var,
766 failure_value,
767 is_ptr=is_ptr))
768 else:
769 c.Sblock('if (!%s) {' % self._util_cc_helper.PopulateArrayFromList(
770 'list',
771 dst_var,
772 is_ptr))
773 c.Concat(self._GenerateError(
774 '"unable to populate array \'%%(parent_key)s\'"'))
775 if is_ptr and self._generate_error_messages:
776 c.Append('%(dst_var)s.reset();')
777 else:
778 c.Append('return %(failure_value)s;')
779 c.Eblock('}')
780 c.Eblock('}')
781 elif underlying_type.property_type == PropertyType.CHOICES:
782 if is_ptr:
783 (c.Append('scoped_ptr<%(cpp_type)s> temp(new %(cpp_type)s());')
784 .Append('if (!%%(cpp_type)s::Populate(%s))' % self._GenerateArgs(
785 ('*%(src_var)s', 'temp.get()')))
786 .Append(' return %(failure_value)s;')
787 .Append('%(dst_var)s = temp.Pass();')
789 else:
790 (c.Append('if (!%%(cpp_type)s::Populate(%s))' % self._GenerateArgs(
791 ('*%(src_var)s', '&%(dst_var)s')))
792 .Append(' return %(failure_value)s;'))
793 elif underlying_type.property_type == PropertyType.ENUM:
794 c.Concat(self._GenerateStringToEnumConversion(underlying_type,
795 src_var,
796 dst_var,
797 failure_value))
798 elif underlying_type.property_type == PropertyType.BINARY:
799 (c.Append('const base::BinaryValue* binary_value = NULL;')
800 .Sblock('if (!%(src_var)s->IsType(base::Value::TYPE_BINARY)) {')
801 .Concat(self._GenerateError(
802 '"\'%%(key)s\': expected binary, got " + ' +
803 self._util_cc_helper.GetValueTypeString('%%(src_var)s', True)))
805 if not self._generate_error_messages:
806 c.Append('return %(failure_value)s;')
807 (c.Eblock('}')
808 .Sblock('else {')
809 .Append(' binary_value =')
810 .Append(' static_cast<const base::BinaryValue*>(%(src_var)s);')
812 if is_ptr:
813 (c.Append('%(dst_var)s.reset(new std::vector<char>(')
814 .Append(' binary_value->GetBuffer(),')
815 .Append(' binary_value->GetBuffer() + binary_value->GetSize()));')
817 else:
818 (c.Append('%(dst_var)s.assign(')
819 .Append(' binary_value->GetBuffer(),')
820 .Append(' binary_value->GetBuffer() + binary_value->GetSize());')
822 c.Eblock('}')
823 else:
824 raise NotImplementedError(type_)
825 if c.IsEmpty():
826 return c
827 return Code().Sblock('{').Concat(c.Substitute({
828 'cpp_type': self._type_helper.GetCppType(type_),
829 'src_var': src_var,
830 'dst_var': dst_var,
831 'failure_value': failure_value,
832 'key': type_.name,
833 'parent_key': type_.parent.name,
834 })).Eblock('}')
836 def _GenerateListValueToEnumArrayConversion(self,
837 item_type,
838 src_var,
839 dst_var,
840 failure_value,
841 is_ptr=False):
842 """Returns Code that converts a ListValue of string constants from
843 |src_var| into an array of enums of |type_| in |dst_var|. On failure,
844 returns |failure_value|.
846 c = Code()
847 accessor = '.'
848 if is_ptr:
849 accessor = '->'
850 cpp_type = self._type_helper.GetCppType(item_type, is_in_container=True)
851 c.Append('%s.reset(new std::vector<%s>);' %
852 (dst_var, cpp_util.PadForGenerics(cpp_type)))
853 (c.Sblock('for (const auto& it : *(%s)) {' % src_var)
854 .Append('%s tmp;' % self._type_helper.GetCppType(item_type))
855 .Concat(self._GenerateStringToEnumConversion(item_type,
856 '(it)',
857 'tmp',
858 failure_value))
859 .Append('%s%spush_back(tmp);' % (dst_var, accessor))
860 .Eblock('}')
862 return c
864 def _GenerateStringToEnumConversion(self,
865 type_,
866 src_var,
867 dst_var,
868 failure_value):
869 """Returns Code that converts a string type in |src_var| to an enum with
870 type |type_| in |dst_var|. In the generated code, if |src_var| is not
871 a valid enum name then the function will return |failure_value|.
873 if type_.property_type != PropertyType.ENUM:
874 raise TypeError(type_)
875 c = Code()
876 enum_as_string = '%s_as_string' % type_.unix_name
877 cpp_type_namespace = ''
878 if type_.namespace != self._namespace:
879 cpp_type_namespace = '%s::' % type_.namespace.unix_name
880 (c.Append('std::string %s;' % enum_as_string)
881 .Sblock('if (!%s->GetAsString(&%s)) {' % (src_var, enum_as_string))
882 .Concat(self._GenerateError(
883 '"\'%%(key)s\': expected string, got " + ' +
884 self._util_cc_helper.GetValueTypeString('%%(src_var)s', True)))
885 .Append('return %s;' % failure_value)
886 .Eblock('}')
887 .Append('%s = %sParse%s(%s);' % (dst_var,
888 cpp_type_namespace,
889 cpp_util.Classname(type_.name),
890 enum_as_string))
891 .Sblock('if (%s == %s%s) {' % (dst_var,
892 cpp_type_namespace,
893 self._type_helper.GetEnumNoneValue(type_)))
894 .Concat(self._GenerateError(
895 '\"\'%%(key)s\': expected \\"' +
896 '\\" or \\"'.join(
897 enum_value.name
898 for enum_value in self._type_helper.FollowRef(type_).enum_values) +
899 '\\", got \\"" + %s + "\\""' % enum_as_string))
900 .Append('return %s;' % failure_value)
901 .Eblock('}')
902 .Substitute({'src_var': src_var, 'key': type_.name})
904 return c
906 def _GeneratePropertyFunctions(self, namespace, params):
907 """Generates the member functions for a list of parameters.
909 return self._GenerateTypes(namespace, (param.type_ for param in params))
911 def _GenerateTypes(self, namespace, types):
912 """Generates the member functions for a list of types.
914 c = Code()
915 for type_ in types:
916 c.Cblock(self._GenerateType(namespace, type_))
917 return c
919 def _GenerateEnumToString(self, cpp_namespace, type_):
920 """Generates ToString() which gets the string representation of an enum.
922 c = Code()
923 classname = cpp_util.Classname(schema_util.StripNamespace(type_.name))
925 if cpp_namespace is not None:
926 c.Append('// static')
927 maybe_namespace = '' if cpp_namespace is None else '%s::' % cpp_namespace
929 c.Sblock('std::string %sToString(%s enum_param) {' %
930 (maybe_namespace, classname))
931 c.Sblock('switch (enum_param) {')
932 for enum_value in self._type_helper.FollowRef(type_).enum_values:
933 name = enum_value.name
934 if 'camel_case_enum_to_string' in self._namespace.compiler_options:
935 name = enum_value.CamelName()
936 (c.Append('case %s: ' % self._type_helper.GetEnumValue(type_, enum_value))
937 .Append(' return "%s";' % name))
938 (c.Append('case %s:' % self._type_helper.GetEnumNoneValue(type_))
939 .Append(' return "";')
940 .Eblock('}')
941 .Append('NOTREACHED();')
942 .Append('return "";')
943 .Eblock('}')
945 return c
947 def _GenerateEnumFromString(self, cpp_namespace, type_):
948 """Generates FromClassNameString() which gets an enum from its string
949 representation.
951 c = Code()
952 classname = cpp_util.Classname(schema_util.StripNamespace(type_.name))
954 if cpp_namespace is not None:
955 c.Append('// static')
956 maybe_namespace = '' if cpp_namespace is None else '%s::' % cpp_namespace
958 c.Sblock('%s%s %sParse%s(const std::string& enum_string) {' %
959 (maybe_namespace, classname, maybe_namespace, classname))
960 for _, enum_value in enumerate(
961 self._type_helper.FollowRef(type_).enum_values):
962 # This is broken up into all ifs with no else ifs because we get
963 # "fatal error C1061: compiler limit : blocks nested too deeply"
964 # on Windows.
965 (c.Append('if (enum_string == "%s")' % enum_value.name)
966 .Append(' return %s;' %
967 self._type_helper.GetEnumValue(type_, enum_value)))
968 (c.Append('return %s;' % self._type_helper.GetEnumNoneValue(type_))
969 .Eblock('}')
971 return c
973 def _GenerateCreateCallbackArguments(self,
974 function_scope,
975 callback):
976 """Generate all functions to create Value parameters for a callback.
978 E.g for function "Bar", generate Bar::Results::Create
979 E.g for event "Baz", generate Baz::Create
981 function_scope: the function scope path, e.g. Foo::Bar for the function
982 Foo::Bar::Baz(). May be None if there is no function scope.
983 callback: the Function object we are creating callback arguments for.
985 c = Code()
986 params = callback.params
987 c.Concat(self._GeneratePropertyFunctions(function_scope, params))
989 (c.Sblock('scoped_ptr<base::ListValue> %(function_scope)s'
990 'Create(%(declaration_list)s) {')
991 .Append('scoped_ptr<base::ListValue> create_results('
992 'new base::ListValue());')
994 declaration_list = []
995 for param in params:
996 declaration_list.append(cpp_util.GetParameterDeclaration(
997 param, self._type_helper.GetCppType(param.type_)))
998 c.Cblock(self._CreateValueFromType('create_results->Append(%s);',
999 param.name,
1000 param.type_,
1001 param.unix_name))
1002 c.Append('return create_results.Pass();')
1003 c.Eblock('}')
1004 c.Substitute({
1005 'function_scope': ('%s::' % function_scope) if function_scope else '',
1006 'declaration_list': ', '.join(declaration_list),
1007 'param_names': ', '.join(param.unix_name for param in params)
1009 return c
1011 def _GenerateEventNameConstant(self, event):
1012 """Generates a constant string array for the event name.
1014 c = Code()
1015 c.Append('const char kEventName[] = "%s.%s";' % (
1016 self._namespace.name, event.name))
1017 return c
1019 def _InitializePropertyToDefault(self, prop, dst):
1020 """Initialize a model.Property to its default value inside an object.
1022 E.g for optional enum "state", generate dst->state = STATE_NONE;
1024 dst: Type*
1026 c = Code()
1027 underlying_type = self._type_helper.FollowRef(prop.type_)
1028 if (underlying_type.property_type == PropertyType.ENUM and
1029 prop.optional):
1030 c.Append('%s->%s = %s;' % (
1031 dst,
1032 prop.unix_name,
1033 self._type_helper.GetEnumNoneValue(prop.type_)))
1034 return c
1036 def _GenerateError(self, body):
1037 """Generates an error message pertaining to population failure.
1039 E.g 'expected bool, got int'
1041 c = Code()
1042 if not self._generate_error_messages:
1043 return c
1044 (c.Append('if (error->length())')
1045 .Append(' error->append(UTF8ToUTF16("; "));')
1046 .Append('error->append(UTF8ToUTF16(%s));' % body))
1047 return c
1049 def _GenerateParams(self, params):
1050 """Builds the parameter list for a function, given an array of parameters.
1052 if self._generate_error_messages:
1053 params = list(params) + ['base::string16* error']
1054 return ', '.join(str(p) for p in params)
1056 def _GenerateArgs(self, args):
1057 """Builds the argument list for a function, given an array of arguments.
1059 if self._generate_error_messages:
1060 args = list(args) + ['error']
1061 return ', '.join(str(a) for a in args)