Chromium Code Reviews
chromiumcodereview-hr@appspot.gserviceaccount.com (chromiumcodereview-hr) | Please choose your nickname with Settings | Help | Chromium Project | Gerrit Changes | Sign out
(59)

Side by Side Diff: tools/json_schema_compiler/cc_generator.py

Issue 16462004: Add optional schema compiler error messages Base URL: https://chromium.googlesource.com/chromium/src.git@master
Patch Set: Kalman's requests Created 7 years, 6 months ago
Use n/p to move between diff chunks; N/P to move between comments. Draft comments are only viewable by you.
Jump to:
View unified diff | Download patch
OLDNEW
1 # Copyright (c) 2012 The Chromium Authors. All rights reserved. 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 2 # Use of this source code is governed by a BSD-style license that can be
3 # found in the LICENSE file. 3 # found in the LICENSE file.
4 4
5 from code import Code 5 from code import Code
6 from model import PropertyType, Type 6 from model import PropertyType, Type
7 import cpp_util 7 import cpp_util
8 import model 8 import model
9 import schema_util 9 import schema_util
10 import sys 10 import sys
(...skipping 13 matching lines...) Expand all
24 """A .cc generator for a namespace. 24 """A .cc generator for a namespace.
25 """ 25 """
26 def __init__(self, namespace, cpp_type_generator, cpp_namespace): 26 def __init__(self, namespace, cpp_type_generator, cpp_namespace):
27 self._namespace = namespace 27 self._namespace = namespace
28 self._type_helper = cpp_type_generator 28 self._type_helper = cpp_type_generator
29 self._cpp_namespace = cpp_namespace 29 self._cpp_namespace = cpp_namespace
30 self._target_namespace = ( 30 self._target_namespace = (
31 self._type_helper.GetCppNamespaceName(self._namespace)) 31 self._type_helper.GetCppNamespaceName(self._namespace))
32 self._util_cc_helper = ( 32 self._util_cc_helper = (
33 util_cc_helper.UtilCCHelper(self._type_helper)) 33 util_cc_helper.UtilCCHelper(self._type_helper))
34 self._generate_error_messages = namespace.compiler_options.get(
35 'generate_error_messages', False)
34 36
35 def Generate(self): 37 def Generate(self):
36 """Generates a Code object with the .cc for a single namespace. 38 """Generates a Code object with the .cc for a single namespace.
37 """ 39 """
38 c = Code() 40 c = Code()
39 (c.Append(cpp_util.CHROMIUM_LICENSE) 41 (c.Append(cpp_util.CHROMIUM_LICENSE)
40 .Append() 42 .Append()
41 .Append(cpp_util.GENERATED_FILE_MESSAGE % self._namespace.source_file) 43 .Append(cpp_util.GENERATED_FILE_MESSAGE % self._namespace.source_file)
42 .Append() 44 .Append()
43 .Append(self._util_cc_helper.GetIncludePath()) 45 .Append(self._util_cc_helper.GetIncludePath())
(...skipping 132 matching lines...) Expand 10 before | Expand all | Expand 10 after
176 178
177 def _GenerateTypePopulate(self, cpp_namespace, type_): 179 def _GenerateTypePopulate(self, cpp_namespace, type_):
178 """Generates the function for populating a type given a pointer to it. 180 """Generates the function for populating a type given a pointer to it.
179 181
180 E.g for type "Foo", generates Foo::Populate() 182 E.g for type "Foo", generates Foo::Populate()
181 """ 183 """
182 classname = cpp_util.Classname(schema_util.StripNamespace(type_.name)) 184 classname = cpp_util.Classname(schema_util.StripNamespace(type_.name))
183 c = Code() 185 c = Code()
184 (c.Append('// static') 186 (c.Append('// static')
185 .Append('bool %(namespace)s::Populate(') 187 .Append('bool %(namespace)s::Populate(')
186 .Sblock(' const base::Value& value, %(name)s* out) {') 188 .Sblock(' %s) {' % self._GenerateParams(
187 ) 189 ('const base::Value& value', '%(name)s* out'))))
190
188 if type_.property_type == PropertyType.CHOICES: 191 if type_.property_type == PropertyType.CHOICES:
189 for choice in type_.choices: 192 for choice in type_.choices:
190 value_type = cpp_util.GetValueType(self._type_helper.FollowRef(choice)) 193 value_type = cpp_util.GetValueType(self._type_helper.FollowRef(choice))
191 (c.Sblock('if (value.IsType(%s)) {' % value_type) 194 (c.Sblock('if (value.IsType(%s)) {' % value_type)
192 .Concat(self._GeneratePopulateVariableFromValue( 195 .Concat(self._GeneratePopulateVariableFromValue(
193 choice, 196 choice,
194 '(&value)', 197 '(&value)',
195 'out->as_%s' % choice.unix_name, 198 'out->as_%s' % choice.unix_name,
196 'false', 199 'false',
197 is_ptr=True)) 200 is_ptr=True))
198 .Append('return true;') 201 .Append('return true;')
199 .Eblock('}') 202 .Eblock('}')
200 ) 203 )
201 c.Append('return false;') 204 (c.Concat(self._GenerateError(
205 '"unexpected type, got " + ' +
206 self._util_cc_helper.GetValueTypeString('value')))
207 .Append('return false;'))
202 elif type_.property_type == PropertyType.OBJECT: 208 elif type_.property_type == PropertyType.OBJECT:
203 (c.Append('if (!value.IsType(base::Value::TYPE_DICTIONARY))') 209 (c.Sblock('if (!value.IsType(base::Value::TYPE_DICTIONARY)) {')
204 .Append(' return false;') 210 .Concat(self._GenerateError(
205 ) 211 '"expected dictionary, got " + ' +
212 self._util_cc_helper.GetValueTypeString('value')))
213 .Append('return false;')
214 .Eblock('}'))
215
206 if type_.properties or type_.additional_properties is not None: 216 if type_.properties or type_.additional_properties is not None:
207 c.Append('const base::DictionaryValue* dict = ' 217 c.Append('const base::DictionaryValue* dict = '
208 'static_cast<const base::DictionaryValue*>(&value);') 218 'static_cast<const base::DictionaryValue*>(&value);')
209 for prop in type_.properties.values(): 219 for prop in type_.properties.values():
210 c.Concat(self._InitializePropertyToDefault(prop, 'out')) 220 c.Concat(self._InitializePropertyToDefault(prop, 'out'))
211 for prop in type_.properties.values(): 221 for prop in type_.properties.values():
212 c.Concat(self._GenerateTypePopulateProperty(prop, 'dict', 'out')) 222 c.Concat(self._GenerateTypePopulateProperty(prop, 'dict', 'out'))
213 if type_.additional_properties is not None: 223 if type_.additional_properties is not None:
214 if type_.additional_properties.property_type == PropertyType.ANY: 224 if type_.additional_properties.property_type == PropertyType.ANY:
215 c.Append('out->additional_properties.MergeDictionary(dict);') 225 c.Append('out->additional_properties.MergeDictionary(dict);')
(...skipping 30 matching lines...) Expand all
246 'if (%(src)s->GetWithoutPathExpansion("%(key)s", &%(value_var)s)) {') 256 'if (%(src)s->GetWithoutPathExpansion("%(key)s", &%(value_var)s)) {')
247 .Concat(self._GeneratePopulatePropertyFromValue( 257 .Concat(self._GeneratePopulatePropertyFromValue(
248 prop, value_var, dst, 'false'))) 258 prop, value_var, dst, 'false')))
249 underlying_type = self._type_helper.FollowRef(prop.type_) 259 underlying_type = self._type_helper.FollowRef(prop.type_)
250 if underlying_type.property_type == PropertyType.ENUM: 260 if underlying_type.property_type == PropertyType.ENUM:
251 (c.Append('} else {') 261 (c.Append('} else {')
252 .Append('%%(dst)s->%%(name)s = %s;' % 262 .Append('%%(dst)s->%%(name)s = %s;' %
253 self._type_helper.GetEnumNoneValue(prop.type_))) 263 self._type_helper.GetEnumNoneValue(prop.type_)))
254 c.Eblock('}') 264 c.Eblock('}')
255 else: 265 else:
256 (c.Append( 266 (c.Sblock(
257 'if (!%(src)s->GetWithoutPathExpansion("%(key)s", &%(value_var)s))') 267 'if (!%(src)s->GetWithoutPathExpansion("%(key)s", &%(value_var)s)) {')
258 .Append(' return false;') 268 .Concat(self._GenerateError('"\'%%(key)s\' is required"'))
269 .Append('return false;')
270 .Eblock('}')
259 .Concat(self._GeneratePopulatePropertyFromValue( 271 .Concat(self._GeneratePopulatePropertyFromValue(
260 prop, value_var, dst, 'false')) 272 prop, value_var, dst, 'false'))
261 ) 273 )
262 c.Append() 274 c.Append()
263 c.Substitute({ 275 c.Substitute({
264 'value_var': value_var, 276 'value_var': value_var,
265 'key': prop.name, 277 'key': prop.name,
266 'src': src, 278 'src': src,
267 'dst': dst, 279 'dst': dst,
268 'name': prop.unix_name 280 'name': prop.unix_name
269 }) 281 })
270 return c 282 return c
271 283
272 def _GenerateTypeFromValue(self, cpp_namespace, type_): 284 def _GenerateTypeFromValue(self, cpp_namespace, type_):
273 classname = cpp_util.Classname(schema_util.StripNamespace(type_.name)) 285 classname = cpp_util.Classname(schema_util.StripNamespace(type_.name))
274 c = Code() 286 c = Code()
275 (c.Append('// static') 287 (c.Append('// static')
276 .Append('scoped_ptr<%s> %s::FromValue(const base::Value& value) {' % ( 288 .Append('scoped_ptr<%s> %s::FromValue(%s) {' % (classname,
277 classname, cpp_namespace)) 289 cpp_namespace, self._GenerateParams(('const base::Value& value',))))
278 .Append(' scoped_ptr<%s> out(new %s());' % (classname, classname)) 290 .Append(' scoped_ptr<%s> out(new %s());' % (classname, classname))
279 .Append(' if (!Populate(value, out.get()))') 291 .Append(' if (!Populate(%s))' % self._GenerateArgs(
292 ('value', 'out.get()')))
280 .Append(' return scoped_ptr<%s>();' % classname) 293 .Append(' return scoped_ptr<%s>();' % classname)
281 .Append(' return out.Pass();') 294 .Append(' return out.Pass();')
282 .Append('}') 295 .Append('}')
283 ) 296 )
284 return c 297 return c
285 298
286 def _GenerateTypeToValue(self, cpp_namespace, type_): 299 def _GenerateTypeToValue(self, cpp_namespace, type_):
287 """Generates a function that serializes the type into a base::Value. 300 """Generates a function that serializes the type into a base::Value.
288 E.g. for type "Foo" generates Foo::ToValue() 301 E.g. for type "Foo" generates Foo::ToValue()
289 """ 302 """
(...skipping 181 matching lines...) Expand 10 before | Expand all | Expand 10 after
471 def _GenerateParamsCheck(self, function, var): 484 def _GenerateParamsCheck(self, function, var):
472 """Generates a check for the correct number of arguments when creating 485 """Generates a check for the correct number of arguments when creating
473 Params. 486 Params.
474 """ 487 """
475 c = Code() 488 c = Code()
476 num_required = 0 489 num_required = 0
477 for param in function.params: 490 for param in function.params:
478 if not param.optional: 491 if not param.optional:
479 num_required += 1 492 num_required += 1
480 if num_required == len(function.params): 493 if num_required == len(function.params):
481 c.Append('if (%(var)s.GetSize() != %(total)d)') 494 c.Sblock('if (%(var)s.GetSize() != %(total)d) {')
482 elif not num_required: 495 elif not num_required:
483 c.Append('if (%(var)s.GetSize() > %(total)d)') 496 c.Sblock('if (%(var)s.GetSize() > %(total)d) {')
484 else: 497 else:
485 c.Append('if (%(var)s.GetSize() < %(required)d' 498 c.Sblock('if (%(var)s.GetSize() < %(required)d'
486 ' || %(var)s.GetSize() > %(total)d)') 499 ' || %(var)s.GetSize() > %(total)d) {')
487 c.Append(' return scoped_ptr<Params>();') 500 (c.Concat(self._GenerateError(
488 c.Substitute({ 501 '"expected %%(total)d arguments, got " + %%(var)s.GetSize()'))
502 .Append('return scoped_ptr<Params>();')
503 .Eblock('}')
504 .Substitute({
489 'var': var, 505 'var': var,
490 'required': num_required, 506 'required': num_required,
491 'total': len(function.params), 507 'total': len(function.params),
492 }) 508 }))
493 return c 509 return c
494 510
495 def _GenerateFunctionParamsCreate(self, function): 511 def _GenerateFunctionParamsCreate(self, function):
496 """Generate function to create an instance of Params. The generated 512 """Generate function to create an instance of Params. The generated
497 function takes a base::ListValue of arguments. 513 function takes a base::ListValue of arguments.
498 514
499 E.g for function "Bar", generate Bar::Params::Create() 515 E.g for function "Bar", generate Bar::Params::Create()
500 """ 516 """
501 c = Code() 517 c = Code()
502 (c.Append('// static') 518 (c.Append('// static')
503 .Sblock('scoped_ptr<Params> ' 519 .Sblock('scoped_ptr<Params> Params::Create(%s) {' % self._GenerateParams(
504 'Params::Create(const base::ListValue& args) {') 520 ['const base::ListValue& args']))
505 .Concat(self._GenerateParamsCheck(function, 'args')) 521 .Concat(self._GenerateParamsCheck(function, 'args'))
506 .Append('scoped_ptr<Params> params(new Params());') 522 .Append('scoped_ptr<Params> params(new Params());'))
507 )
508 523
509 for param in function.params: 524 for param in function.params:
510 c.Concat(self._InitializePropertyToDefault(param, 'params')) 525 c.Concat(self._InitializePropertyToDefault(param, 'params'))
511 526
512 for i, param in enumerate(function.params): 527 for i, param in enumerate(function.params):
513 # Any failure will cause this function to return. If any argument is 528 # Any failure will cause this function to return. If any argument is
514 # incorrect or missing, those following it are not processed. Note that 529 # incorrect or missing, those following it are not processed. Note that
515 # for optional arguments, we allow missing arguments and proceed because 530 # for optional arguments, we allow missing arguments and proceed because
516 # there may be other arguments following it. 531 # there may be other arguments following it.
517 failure_value = 'scoped_ptr<Params>()' 532 failure_value = 'scoped_ptr<Params>()'
518 c.Append() 533 c.Append()
519 value_var = param.unix_name + '_value' 534 value_var = param.unix_name + '_value'
520 (c.Append('const base::Value* %(value_var)s = NULL;') 535 (c.Append('const base::Value* %(value_var)s = NULL;')
521 .Append('if (args.Get(%(i)s, &%(value_var)s) &&') 536 .Append('if (args.Get(%(i)s, &%(value_var)s) &&')
522 .Sblock(' !%(value_var)s->IsType(base::Value::TYPE_NULL)) {') 537 .Sblock(' !%(value_var)s->IsType(base::Value::TYPE_NULL)) {')
523 .Concat(self._GeneratePopulatePropertyFromValue( 538 .Concat(self._GeneratePopulatePropertyFromValue(
524 param, value_var, 'params', failure_value)) 539 param, value_var, 'params', failure_value))
525 .Eblock('}') 540 .Eblock('}')
526 ) 541 )
527 if not param.optional: 542 if not param.optional:
528 (c.Sblock('else {') 543 (c.Sblock('else {')
544 .Concat(self._GenerateError('"\'%%(key)s\' is required"'))
529 .Append('return %s;' % failure_value) 545 .Append('return %s;' % failure_value)
530 .Eblock('}') 546 .Eblock('}'))
531 ) 547 c.Substitute({'value_var': value_var, 'i': i, 'key': param.name})
532 c.Substitute({'value_var': value_var, 'i': i})
533 (c.Append() 548 (c.Append()
534 .Append('return params.Pass();') 549 .Append('return params.Pass();')
535 .Eblock('}') 550 .Eblock('}')
536 .Append() 551 .Append()
537 ) 552 )
538 553
539 return c 554 return c
540 555
541 def _GeneratePopulatePropertyFromValue(self, 556 def _GeneratePopulatePropertyFromValue(self,
542 prop, 557 prop,
(...skipping 23 matching lines...) Expand all
566 |failure_value|. 581 |failure_value|.
567 """ 582 """
568 c = Code() 583 c = Code()
569 c.Sblock('{') 584 c.Sblock('{')
570 585
571 underlying_type = self._type_helper.FollowRef(type_) 586 underlying_type = self._type_helper.FollowRef(type_)
572 587
573 if underlying_type.property_type.is_fundamental: 588 if underlying_type.property_type.is_fundamental:
574 if is_ptr: 589 if is_ptr:
575 (c.Append('%(cpp_type)s temp;') 590 (c.Append('%(cpp_type)s temp;')
576 .Append('if (!%s)' % cpp_util.GetAsFundamentalValue( 591 .Sblock('if (!%s) {' % cpp_util.GetAsFundamentalValue(
577 self._type_helper.FollowRef(type_), src_var, '&temp')) 592 self._type_helper.FollowRef(type_), src_var, '&temp'))
578 .Append(' return %(failure_value)s;') 593 .Concat(self._GenerateError(
594 '"\'%%(key)s\': expected %%(cpp_type)s, got " + ' +
595 self._util_cc_helper.GetValueTypeString('%%(src_var)s', True)))
596 .Append('return %(failure_value)s;')
597 .Eblock('}')
579 .Append('%(dst_var)s.reset(new %(cpp_type)s(temp));') 598 .Append('%(dst_var)s.reset(new %(cpp_type)s(temp));')
580 ) 599 )
581 else: 600 else:
582 (c.Append('if (!%s)' % cpp_util.GetAsFundamentalValue( 601 (c.Sblock('if (!%s) {' % cpp_util.GetAsFundamentalValue(
583 self._type_helper.FollowRef(type_), 602 self._type_helper.FollowRef(type_),
584 src_var, 603 src_var,
585 '&%s' % dst_var)) 604 '&%s' % dst_var))
586 .Append(' return %(failure_value)s;') 605 .Concat(self._GenerateError(
606 '"\'%%(key)s\': expected %%(cpp_type)s, got " + ' +
607 self._util_cc_helper.GetValueTypeString('%%(src_var)s', True)))
608 .Append('return %(failure_value)s;')
609 .Eblock('}')
587 ) 610 )
588 elif underlying_type.property_type == PropertyType.OBJECT: 611 elif underlying_type.property_type == PropertyType.OBJECT:
589 if is_ptr: 612 if is_ptr:
590 (c.Append('const base::DictionaryValue* dictionary = NULL;') 613 (c.Append('const base::DictionaryValue* dictionary = NULL;')
591 .Append('if (!%(src_var)s->GetAsDictionary(&dictionary))') 614 .Sblock('if (!%(src_var)s->GetAsDictionary(&dictionary)) {')
615 .Concat(self._GenerateError(
616 '"\'%%(key)s\': expected dictionary, got " + ' +
617 self._util_cc_helper.GetValueTypeString('%%(src_var)s', True)))
618 .Append('return %(failure_value)s;')
619 .Eblock('}')
620 .Append('scoped_ptr<%(cpp_type)s> temp(new %(cpp_type)s());')
621 .Append('if (!%%(cpp_type)s::Populate(%s)) {' % self._GenerateArgs(
622 ('*dictionary', 'temp.get()')))
592 .Append(' return %(failure_value)s;') 623 .Append(' return %(failure_value)s;')
593 .Append('scoped_ptr<%(cpp_type)s> temp(new %(cpp_type)s());') 624 .Append('}')
594 .Append('if (!%(cpp_type)s::Populate(*dictionary, temp.get()))')
595 .Append(' return %(failure_value)s;')
596 .Append('%(dst_var)s = temp.Pass();') 625 .Append('%(dst_var)s = temp.Pass();')
597 ) 626 )
598 else: 627 else:
599 (c.Append('const base::DictionaryValue* dictionary = NULL;') 628 (c.Append('const base::DictionaryValue* dictionary = NULL;')
600 .Append('if (!%(src_var)s->GetAsDictionary(&dictionary))') 629 .Sblock('if (!%(src_var)s->GetAsDictionary(&dictionary)) {')
630 .Concat(self._GenerateError(
631 '"\'%%(key)s\': expected dictionary, got " + ' +
632 self._util_cc_helper.GetValueTypeString('%%(src_var)s', True)))
633 .Append('return %(failure_value)s;')
634 .Eblock('}')
635 .Append('if (!%%(cpp_type)s::Populate(%s)) {' % self._GenerateArgs(
636 ('*dictionary', '&%(dst_var)s')))
601 .Append(' return %(failure_value)s;') 637 .Append(' return %(failure_value)s;')
602 .Append('if (!%(cpp_type)s::Populate(*dictionary, &%(dst_var)s))') 638 .Append('}')
603 .Append(' return %(failure_value)s;')
604 ) 639 )
605 elif underlying_type.property_type == PropertyType.FUNCTION: 640 elif underlying_type.property_type == PropertyType.FUNCTION:
606 if is_ptr: 641 if is_ptr:
607 c.Append('%(dst_var)s.reset(new base::DictionaryValue());') 642 c.Append('%(dst_var)s.reset(new base::DictionaryValue());')
608 elif underlying_type.property_type == PropertyType.ANY: 643 elif underlying_type.property_type == PropertyType.ANY:
609 c.Append('%(dst_var)s.reset(%(src_var)s->DeepCopy());') 644 c.Append('%(dst_var)s.reset(%(src_var)s->DeepCopy());')
610 elif underlying_type.property_type == PropertyType.ARRAY: 645 elif underlying_type.property_type == PropertyType.ARRAY:
611 # util_cc_helper deals with optional and required arrays 646 # util_cc_helper deals with optional and required arrays
612 (c.Append('const base::ListValue* list = NULL;') 647 (c.Append('const base::ListValue* list = NULL;')
613 .Append('if (!%(src_var)s->GetAsList(&list))') 648 .Sblock('if (!%(src_var)s->GetAsList(&list)) {')
614 .Append(' return %(failure_value)s;')) 649 .Concat(self._GenerateError(
650 '"\'%%(key)s\': expected list, got " + ' +
651 self._util_cc_helper.GetValueTypeString('%%(src_var)s', True)))
652 .Append('return %(failure_value)s;')
653 .Eblock('}'))
615 item_type = underlying_type.item_type 654 item_type = underlying_type.item_type
616 if item_type.property_type == PropertyType.ENUM: 655 if item_type.property_type == PropertyType.ENUM:
617 c.Concat(self._GenerateListValueToEnumArrayConversion( 656 c.Concat(self._GenerateListValueToEnumArrayConversion(
618 item_type, 657 item_type,
619 'list', 658 'list',
620 dst_var, 659 dst_var,
621 failure_value, 660 failure_value,
622 is_ptr=is_ptr)) 661 is_ptr=is_ptr))
623 else: 662 else:
624 (c.Append('if (!%s)' % self._util_cc_helper.PopulateArrayFromList( 663 (c.Sblock('if (!%s) {' % self._util_cc_helper.PopulateArrayFromList(
625 underlying_type, 664 underlying_type,
626 'list', 665 'list',
627 dst_var, 666 dst_var,
628 is_ptr)) 667 is_ptr))
629 .Append(' return %(failure_value)s;') 668 .Concat(self._GenerateError(
669 '"unable to populate array \'%%(array_key)s\'"'))
not at google - send to devlin 2013/06/19 17:02:08 better this explicitly be parent_key
670 .Append('return %(failure_value)s;')
671 .Eblock('}')
630 ) 672 )
631 elif underlying_type.property_type == PropertyType.CHOICES: 673 elif underlying_type.property_type == PropertyType.CHOICES:
632 if is_ptr: 674 if is_ptr:
633 (c.Append('scoped_ptr<%(cpp_type)s> temp(new %(cpp_type)s());') 675 (c.Append('scoped_ptr<%(cpp_type)s> temp(new %(cpp_type)s());')
634 .Append('if (!%(cpp_type)s::Populate(*%(src_var)s, temp.get()))') 676 .Append('if (!%%(cpp_type)s::Populate(%s))' % self._GenerateArgs(
677 ('*%(src_var)s', 'temp.get()')))
635 .Append(' return %(failure_value)s;') 678 .Append(' return %(failure_value)s;')
636 .Append('%(dst_var)s = temp.Pass();') 679 .Append('%(dst_var)s = temp.Pass();')
637 ) 680 )
638 else: 681 else:
639 (c.Append('if (!%(cpp_type)s::Populate(*%(src_var)s, &%(dst_var)s))') 682 (c.Append('if (!%%(cpp_type)s::Populate(%s))' % self._GenerateArgs(
640 .Append(' return %(failure_value)s;') 683 ('*%(src_var)s', '&%(dst_var)s')))
641 ) 684 .Append(' return %(failure_value)s;'))
642 elif underlying_type.property_type == PropertyType.ENUM: 685 elif underlying_type.property_type == PropertyType.ENUM:
643 c.Concat(self._GenerateStringToEnumConversion(type_, 686 c.Concat(self._GenerateStringToEnumConversion(type_,
644 src_var, 687 src_var,
645 dst_var, 688 dst_var,
646 failure_value)) 689 failure_value))
647 elif underlying_type.property_type == PropertyType.BINARY: 690 elif underlying_type.property_type == PropertyType.BINARY:
648 (c.Append('if (!%(src_var)s->IsType(%(value_type)s))') 691 (c.Sblock('if (!%(src_var)s->IsType(%(value_type)s)) {')
649 .Append(' return %(failure_value)s;') 692 .Concat(self._GenerateError(
693 '"\'%%(key)s\': expected %(value_type)s, got " + ' +
694 self._util_cc_helper.GetValueTypeString('%(src_var)s', True)))
695 .Append('return %(failure_value)s;')
696 .Eblock('}')
650 .Append('const base::BinaryValue* binary_value =') 697 .Append('const base::BinaryValue* binary_value =')
651 .Append(' static_cast<const base::BinaryValue*>(%(src_var)s);') 698 .Append(' static_cast<const base::BinaryValue*>(%(src_var)s);')
652 ) 699 )
653 if is_ptr: 700 if is_ptr:
654 (c.Append('%(dst_var)s.reset(') 701 (c.Append('%(dst_var)s.reset(')
655 .Append(' new std::string(binary_value->GetBuffer(),') 702 .Append(' new std::string(binary_value->GetBuffer(),')
656 .Append(' binary_value->GetSize()));') 703 .Append(' binary_value->GetSize()));')
657 ) 704 )
658 else: 705 else:
659 (c.Append('%(dst_var)s.assign(binary_value->GetBuffer(),') 706 (c.Append('%(dst_var)s.assign(binary_value->GetBuffer(),')
660 .Append(' binary_value->GetSize());') 707 .Append(' binary_value->GetSize());')
661 ) 708 )
662 else: 709 else:
663 raise NotImplementedError(type_) 710 raise NotImplementedError(type_)
664 711
665 sub = { 712 sub = {
666 'cpp_type': self._type_helper.GetCppType(type_), 713 'cpp_type': self._type_helper.GetCppType(type_),
667 'src_var': src_var, 714 'src_var': src_var,
668 'dst_var': dst_var, 715 'dst_var': dst_var,
669 'failure_value': failure_value, 716 'failure_value': failure_value,
717 'key': type_.name,
718 'array_key': type_.parent.name
670 } 719 }
671 720
672 if underlying_type.property_type not in (PropertyType.ANY, 721 if underlying_type.property_type not in (PropertyType.ANY,
673 PropertyType.CHOICES): 722 PropertyType.CHOICES):
674 sub['value_type'] = cpp_util.GetValueType(underlying_type) 723 sub['value_type'] = cpp_util.GetValueType(underlying_type)
675 724
676 return c.Eblock('}').Substitute(sub) 725 return c.Eblock('}').Substitute(sub)
677 726
678 def _GenerateListValueToEnumArrayConversion(self, 727 def _GenerateListValueToEnumArrayConversion(self,
679 item_type, 728 item_type,
(...skipping 29 matching lines...) Expand all
709 src_var, 758 src_var,
710 dst_var, 759 dst_var,
711 failure_value): 760 failure_value):
712 """Returns Code that converts a string type in |src_var| to an enum with 761 """Returns Code that converts a string type in |src_var| to an enum with
713 type |type_| in |dst_var|. In the generated code, if |src_var| is not 762 type |type_| in |dst_var|. In the generated code, if |src_var| is not
714 a valid enum name then the function will return |failure_value|. 763 a valid enum name then the function will return |failure_value|.
715 """ 764 """
716 c = Code() 765 c = Code()
717 enum_as_string = '%s_as_string' % type_.unix_name 766 enum_as_string = '%s_as_string' % type_.unix_name
718 (c.Append('std::string %s;' % enum_as_string) 767 (c.Append('std::string %s;' % enum_as_string)
719 .Append('if (!%s->GetAsString(&%s))' % (src_var, enum_as_string)) 768 .Sblock('if (!%s->GetAsString(&%s)) {' % (src_var, enum_as_string))
720 .Append(' return %s;' % failure_value) 769 .Concat(self._GenerateError(
770 '"\'%%(key)s\': expected string, got " + ' +
771 self._util_cc_helper.GetValueTypeString('%%(src_var)s', True)))
772 .Append('return %s;' % failure_value)
773 .Eblock('}')
721 .Append('%s = Parse%s(%s);' % (dst_var, 774 .Append('%s = Parse%s(%s);' % (dst_var,
722 self._type_helper.GetCppType(type_), 775 self._type_helper.GetCppType(type_),
723 enum_as_string)) 776 enum_as_string))
724 .Append('if (%s == %s)' % (dst_var, 777 .Sblock('if (%s == %s) {' % (dst_var,
725 self._type_helper.GetEnumNoneValue(type_))) 778 self._type_helper.GetEnumNoneValue(type_)))
726 .Append(' return %s;' % failure_value) 779 .Concat(self._GenerateError(
780 '"got bad enum value from \'%%(key)s\'"'))
781 .Append('return %s;' % failure_value)
782 .Eblock('}')
783 .Substitute({'src_var': src_var, 'key': type_.name})
727 ) 784 )
728 return c 785 return c
729 786
730 def _GeneratePropertyFunctions(self, namespace, params): 787 def _GeneratePropertyFunctions(self, namespace, params):
731 """Generates the member functions for a list of parameters. 788 """Generates the member functions for a list of parameters.
732 """ 789 """
733 return self._GenerateTypes(namespace, (param.type_ for param in params)) 790 return self._GenerateTypes(namespace, (param.type_ for param in params))
734 791
735 def _GenerateTypes(self, namespace, types): 792 def _GenerateTypes(self, namespace, types):
736 """Generates the member functions for a list of types. 793 """Generates the member functions for a list of types.
(...skipping 97 matching lines...) Expand 10 before | Expand all | Expand 10 after
834 """ 891 """
835 c = Code() 892 c = Code()
836 underlying_type = self._type_helper.FollowRef(prop.type_) 893 underlying_type = self._type_helper.FollowRef(prop.type_)
837 if (underlying_type.property_type == PropertyType.ENUM and 894 if (underlying_type.property_type == PropertyType.ENUM and
838 prop.optional): 895 prop.optional):
839 c.Append('%s->%s = %s;' % ( 896 c.Append('%s->%s = %s;' % (
840 dst, 897 dst,
841 prop.unix_name, 898 prop.unix_name,
842 self._type_helper.GetEnumNoneValue(prop.type_))) 899 self._type_helper.GetEnumNoneValue(prop.type_)))
843 return c 900 return c
901
902 def _GenerateError(self, body):
903 """Generates an error message pertaining to population failure.
904
905 E.g 'expected bool, got int'
906 """
907 c = Code()
908 if not self._generate_error_messages:
909 return c
910 (c.Append('if (error)')
911 .Append(' *error = ' + body + ';'))
912 return c
913
914 def _GenerateParams(self, params):
915 """Builds the parameter list for a function, given an array of parameters.
916 """
917 if self._generate_error_messages:
918 params += ('std::string* error',)
919 return ', '.join(str(p) for p in params)
not at google - send to devlin 2013/06/19 17:02:08 here and below should be something more like: if
920
921 def _GenerateArgs(self, args):
922 """Builds the argument list for a function, given an array of arguments.
923 """
924 if self._generate_error_messages:
925 args += ('error',)
926 return ', '.join(str(a) for a in args)
OLDNEW
« no previous file with comments | « no previous file | tools/json_schema_compiler/code.py » ('j') | tools/json_schema_compiler/h_generator.py » ('J')

Powered by Google App Engine
This is Rietveld 408576698