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

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: Clark'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 164 matching lines...) Expand 10 before | Expand all | Expand 10 after
175 return Code().Append(s) 175 return Code().Append(s)
176 176
177 def _GenerateTypePopulate(self, cpp_namespace, type_): 177 def _GenerateTypePopulate(self, cpp_namespace, type_):
178 """Generates the function for populating a type given a pointer to it. 178 """Generates the function for populating a type given a pointer to it.
179 179
180 E.g for type "Foo", generates Foo::Populate() 180 E.g for type "Foo", generates Foo::Populate()
181 """ 181 """
182 classname = cpp_util.Classname(schema_util.StripNamespace(type_.name)) 182 classname = cpp_util.Classname(schema_util.StripNamespace(type_.name))
183 c = Code() 183 c = Code()
184 (c.Append('// static') 184 (c.Append('// static')
185 .Append('bool %(namespace)s::Populate(') 185 .Append('bool %(namespace)s::Populate('))
186 .Sblock(' const base::Value& value, %(name)s* out) {') 186 if self._namespace.generate_error_messages:
187 ) 187 c.Sblock(' const base::Value& value, %(name)s* out, '
188 'std::string* error) {')
189 else:
190 c.Sblock(' const base::Value& value, %(name)s* out) {')
not at google - send to devlin 2013/06/11 18:33:43 I looked at h_generator first so are making commen
Aaron Jacobs 2013/06/14 02:00:37 Done.
191
188 if type_.property_type == PropertyType.CHOICES: 192 if type_.property_type == PropertyType.CHOICES:
189 for choice in type_.choices: 193 for choice in type_.choices:
190 value_type = cpp_util.GetValueType(self._type_helper.FollowRef(choice)) 194 value_type = cpp_util.GetValueType(self._type_helper.FollowRef(choice))
191 (c.Sblock('if (value.IsType(%s)) {' % value_type) 195 (c.Sblock('if (value.IsType(%s)) {' % value_type)
192 .Concat(self._GeneratePopulateVariableFromValue( 196 .Concat(self._GeneratePopulateVariableFromValue(
193 choice, 197 choice,
194 '(&value)', 198 '(&value)',
195 'out->as_%s' % choice.unix_name, 199 'out->as_%s' % choice.unix_name,
196 'false', 200 'false',
197 is_ptr=True)) 201 is_ptr=True))
198 .Append('return true;') 202 .Append('return true;')
199 .Eblock('}') 203 .Eblock('}')
200 ) 204 )
205 if self._namespace.generate_error_messages:
206 self._GenerateError(c,
not at google - send to devlin 2013/06/11 18:33:43 instead of passing |c| in, make _GenerateError ret
Aaron Jacobs 2013/06/14 02:00:37 Done.
207 'type-check',
208 '"unexpected type, got " << value.GetType()')
not at google - send to devlin 2013/06/11 18:33:43 value.GetType() returns an int but we should show
Aaron Jacobs 2013/06/14 02:00:37 Done (kinda) - I'm not completely sure how to get
201 c.Append('return false;') 209 c.Append('return false;')
202 elif type_.property_type == PropertyType.OBJECT: 210 elif type_.property_type == PropertyType.OBJECT:
203 (c.Append('if (!value.IsType(base::Value::TYPE_DICTIONARY))') 211 c.Append('if (!value.IsType(base::Value::TYPE_DICTIONARY)) {')
204 .Append(' return false;') 212 if self._namespace.generate_error_messages:
205 ) 213 self._GenerateError(c,
214 'type-check',
215 '"expected dictionary, got " << value.GetType()',
216 True)
217 (c.Append(' return false;')
218 .Append('}'))
219
206 if type_.properties or type_.additional_properties is not None: 220 if type_.properties or type_.additional_properties is not None:
207 c.Append('const base::DictionaryValue* dict = ' 221 c.Append('const base::DictionaryValue* dict = '
208 'static_cast<const base::DictionaryValue*>(&value);') 222 'static_cast<const base::DictionaryValue*>(&value);')
209 for prop in type_.properties.values(): 223 for prop in type_.properties.values():
210 c.Concat(self._InitializePropertyToDefault(prop, 'out')) 224 c.Concat(self._InitializePropertyToDefault(prop, 'out'))
211 for prop in type_.properties.values(): 225 for prop in type_.properties.values():
212 c.Concat(self._GenerateTypePopulateProperty(prop, 'dict', 'out')) 226 c.Concat(self._GenerateTypePopulateProperty(prop, 'dict', 'out'))
213 if type_.additional_properties is not None: 227 if type_.additional_properties is not None:
214 if type_.additional_properties.property_type == PropertyType.ANY: 228 if type_.additional_properties.property_type == PropertyType.ANY:
215 c.Append('out->additional_properties.MergeDictionary(dict);') 229 c.Append('out->additional_properties.MergeDictionary(dict);')
(...skipping 30 matching lines...) Expand all
246 'if (%(src)s->GetWithoutPathExpansion("%(key)s", &%(value_var)s)) {') 260 'if (%(src)s->GetWithoutPathExpansion("%(key)s", &%(value_var)s)) {')
247 .Concat(self._GeneratePopulatePropertyFromValue( 261 .Concat(self._GeneratePopulatePropertyFromValue(
248 prop, value_var, dst, 'false'))) 262 prop, value_var, dst, 'false')))
249 underlying_type = self._type_helper.FollowRef(prop.type_) 263 underlying_type = self._type_helper.FollowRef(prop.type_)
250 if underlying_type.property_type == PropertyType.ENUM: 264 if underlying_type.property_type == PropertyType.ENUM:
251 (c.Append('} else {') 265 (c.Append('} else {')
252 .Append('%%(dst)s->%%(name)s = %s;' % 266 .Append('%%(dst)s->%%(name)s = %s;' %
253 self._type_helper.GetEnumNoneValue(prop.type_))) 267 self._type_helper.GetEnumNoneValue(prop.type_)))
254 c.Eblock('}') 268 c.Eblock('}')
255 else: 269 else:
256 (c.Append( 270 c.Append(
257 'if (!%(src)s->GetWithoutPathExpansion("%(key)s", &%(value_var)s))') 271 'if (!%(src)s->GetWithoutPathExpansion("%(key)s", &%(value_var)s)) {')
258 .Append(' return false;') 272 if self._namespace.generate_error_messages:
273 self._GenerateError(c,
274 'get-from-dict',
275 '"key not found: %(key)s"',
not at google - send to devlin 2013/06/11 18:33:43 '"%(key)s" is required'
Aaron Jacobs 2013/06/14 02:00:37 Done.
276 True)
277 (c.Append(' return false;')
278 .Append('}')
259 .Concat(self._GeneratePopulatePropertyFromValue( 279 .Concat(self._GeneratePopulatePropertyFromValue(
260 prop, value_var, dst, 'false')) 280 prop, value_var, dst, 'false'))
261 ) 281 )
262 c.Append() 282 c.Append()
263 c.Substitute({ 283 c.Substitute({
264 'value_var': value_var, 284 'value_var': value_var,
265 'key': prop.name, 285 'key': prop.name,
266 'src': src, 286 'src': src,
267 'dst': dst, 287 'dst': dst,
268 'name': prop.unix_name 288 'name': prop.unix_name
269 }) 289 })
270 return c 290 return c
271 291
272 def _GenerateTypeFromValue(self, cpp_namespace, type_): 292 def _GenerateTypeFromValue(self, cpp_namespace, type_):
273 classname = cpp_util.Classname(schema_util.StripNamespace(type_.name)) 293 classname = cpp_util.Classname(schema_util.StripNamespace(type_.name))
274 c = Code() 294 c = Code()
275 (c.Append('// static') 295 c.Append('// static')
276 .Append('scoped_ptr<%s> %s::FromValue(const base::Value& value) {' % ( 296 if self._namespace.generate_error_messages:
297 c.Append('scoped_ptr<%s> %s::FromValue(const base::Value& value, '
298 'std::string* error) {' % (classname, cpp_namespace))
299 else:
300 c.Append('scoped_ptr<%s> %s::FromValue(const base::Value& value) {' % (
277 classname, cpp_namespace)) 301 classname, cpp_namespace))
278 .Append(' scoped_ptr<%s> out(new %s());' % (classname, classname)) 302 c.Append(' scoped_ptr<%s> out(new %s());' % (classname, classname))
279 .Append(' if (!Populate(value, out.get()))') 303 if self._namespace.generate_error_messages:
280 .Append(' return scoped_ptr<%s>();' % classname) 304 c.Append(' if (!Populate(value, out.get(), error))')
305 else:
306 c.Append(' if (!Populate(value, out.get()))')
307 (c.Append(' return scoped_ptr<%s>();' % classname)
281 .Append(' return out.Pass();') 308 .Append(' return out.Pass();')
282 .Append('}') 309 .Append('}')
283 ) 310 )
284 return c 311 return c
285 312
286 def _GenerateTypeToValue(self, cpp_namespace, type_): 313 def _GenerateTypeToValue(self, cpp_namespace, type_):
287 """Generates a function that serializes the type into a base::Value. 314 """Generates a function that serializes the type into a base::Value.
288 E.g. for type "Foo" generates Foo::ToValue() 315 E.g. for type "Foo" generates Foo::ToValue()
289 """ 316 """
290 if type_.property_type == PropertyType.OBJECT: 317 if type_.property_type == PropertyType.OBJECT:
(...skipping 180 matching lines...) Expand 10 before | Expand all | Expand 10 after
471 def _GenerateParamsCheck(self, function, var): 498 def _GenerateParamsCheck(self, function, var):
472 """Generates a check for the correct number of arguments when creating 499 """Generates a check for the correct number of arguments when creating
473 Params. 500 Params.
474 """ 501 """
475 c = Code() 502 c = Code()
476 num_required = 0 503 num_required = 0
477 for param in function.params: 504 for param in function.params:
478 if not param.optional: 505 if not param.optional:
479 num_required += 1 506 num_required += 1
480 if num_required == len(function.params): 507 if num_required == len(function.params):
481 c.Append('if (%(var)s.GetSize() != %(total)d)') 508 c.Append('if (%(var)s.GetSize() != %(total)d) {')
482 elif not num_required: 509 elif not num_required:
483 c.Append('if (%(var)s.GetSize() > %(total)d)') 510 c.Append('if (%(var)s.GetSize() > %(total)d) {')
484 else: 511 else:
485 c.Append('if (%(var)s.GetSize() < %(required)d' 512 c.Append('if (%(var)s.GetSize() < %(required)d'
486 ' || %(var)s.GetSize() > %(total)d)') 513 ' || %(var)s.GetSize() > %(total)d) {')
514 if self._namespace.generate_error_messages:
515 self._GenerateError(c,
516 'params',
517 '"expected %(total)d arguments, got " << %(var)s.GetSize()',
518 True)
487 c.Append(' return scoped_ptr<Params>();') 519 c.Append(' return scoped_ptr<Params>();')
520 c.Append('}')
488 c.Substitute({ 521 c.Substitute({
489 'var': var, 522 'var': var,
490 'required': num_required, 523 'required': num_required,
491 'total': len(function.params), 524 'total': len(function.params),
492 }) 525 })
493 return c 526 return c
494 527
495 def _GenerateFunctionParamsCreate(self, function): 528 def _GenerateFunctionParamsCreate(self, function):
496 """Generate function to create an instance of Params. The generated 529 """Generate function to create an instance of Params. The generated
497 function takes a base::ListValue of arguments. 530 function takes a base::ListValue of arguments.
498 531
499 E.g for function "Bar", generate Bar::Params::Create() 532 E.g for function "Bar", generate Bar::Params::Create()
500 """ 533 """
501 c = Code() 534 c = Code()
502 (c.Append('// static') 535 c.Append('// static')
503 .Sblock('scoped_ptr<Params> ' 536 if self._namespace.generate_error_messages:
537 c.Sblock('scoped_ptr<Params> Params::Create('
538 'const base::ListValue& args, std::string* error) {')
539 else:
540 c.Sblock('scoped_ptr<Params> '
504 'Params::Create(const base::ListValue& args) {') 541 'Params::Create(const base::ListValue& args) {')
505 .Concat(self._GenerateParamsCheck(function, 'args')) 542 (c.Concat(self._GenerateParamsCheck(function, 'args'))
506 .Append('scoped_ptr<Params> params(new Params());') 543 .Append('scoped_ptr<Params> params(new Params());'))
507 )
508 544
509 for param in function.params: 545 for param in function.params:
510 c.Concat(self._InitializePropertyToDefault(param, 'params')) 546 c.Concat(self._InitializePropertyToDefault(param, 'params'))
511 547
512 for i, param in enumerate(function.params): 548 for i, param in enumerate(function.params):
513 # Any failure will cause this function to return. If any argument is 549 # Any failure will cause this function to return. If any argument is
514 # incorrect or missing, those following it are not processed. Note that 550 # incorrect or missing, those following it are not processed. Note that
515 # for optional arguments, we allow missing arguments and proceed because 551 # for optional arguments, we allow missing arguments and proceed because
516 # there may be other arguments following it. 552 # there may be other arguments following it.
517 failure_value = 'scoped_ptr<Params>()' 553 failure_value = 'scoped_ptr<Params>()'
518 c.Append() 554 c.Append()
519 value_var = param.unix_name + '_value' 555 value_var = param.unix_name + '_value'
520 (c.Append('const base::Value* %(value_var)s = NULL;') 556 (c.Append('const base::Value* %(value_var)s = NULL;')
521 .Append('if (args.Get(%(i)s, &%(value_var)s) &&') 557 .Append('if (args.Get(%(i)s, &%(value_var)s) &&')
522 .Sblock(' !%(value_var)s->IsType(base::Value::TYPE_NULL)) {') 558 .Sblock(' !%(value_var)s->IsType(base::Value::TYPE_NULL)) {')
523 .Concat(self._GeneratePopulatePropertyFromValue( 559 .Concat(self._GeneratePopulatePropertyFromValue(
524 param, value_var, 'params', failure_value)) 560 param, value_var, 'params', failure_value))
525 .Eblock('}') 561 .Eblock('}')
526 ) 562 )
527 if not param.optional: 563 if not param.optional:
528 (c.Sblock('else {') 564 c.Sblock('else {')
529 .Append('return %s;' % failure_value) 565 if self._namespace.generate_error_messages:
530 .Eblock('}') 566 self._GenerateError(c,
531 ) 567 'params',
568 '"missing non-optional value: %(value_var)s"')
not at google - send to devlin 2013/06/11 18:33:43 '"%s" is required'
Aaron Jacobs 2013/06/14 02:00:37 Done.
569 (c.Append('return %s;' % failure_value)
570 .Eblock('}'))
532 c.Substitute({'value_var': value_var, 'i': i}) 571 c.Substitute({'value_var': value_var, 'i': i})
533 (c.Append() 572 (c.Append()
534 .Append('return params.Pass();') 573 .Append('return params.Pass();')
535 .Eblock('}') 574 .Eblock('}')
536 .Append() 575 .Append()
537 ) 576 )
538 577
539 return c 578 return c
540 579
541 def _GeneratePopulatePropertyFromValue(self, 580 def _GeneratePopulatePropertyFromValue(self,
(...skipping 24 matching lines...) Expand all
566 |failure_value|. 605 |failure_value|.
567 """ 606 """
568 c = Code() 607 c = Code()
569 c.Sblock('{') 608 c.Sblock('{')
570 609
571 underlying_type = self._type_helper.FollowRef(type_) 610 underlying_type = self._type_helper.FollowRef(type_)
572 611
573 if underlying_type.property_type.is_fundamental: 612 if underlying_type.property_type.is_fundamental:
574 if is_ptr: 613 if is_ptr:
575 (c.Append('%(cpp_type)s temp;') 614 (c.Append('%(cpp_type)s temp;')
576 .Append('if (!%s)' % cpp_util.GetAsFundamentalValue( 615 .Append('if (!%s) {' % cpp_util.GetAsFundamentalValue(
577 self._type_helper.FollowRef(type_), src_var, '&temp')) 616 self._type_helper.FollowRef(type_), src_var, '&temp')))
578 .Append(' return %(failure_value)s;') 617 if self._namespace.generate_error_messages:
618 self._GenerateError(c,
619 'get-as-type',
620 '"expected %s, got " << %s->GetType()' %
not at google - send to devlin 2013/06/11 18:33:43 same comments re key name
Aaron Jacobs 2013/06/14 02:00:37 Done.
621 (self._type_helper.GetCppType(type_), src_var), True)
622 (c.Append(' return %(failure_value)s;')
623 .Append('}')
579 .Append('%(dst_var)s.reset(new %(cpp_type)s(temp));') 624 .Append('%(dst_var)s.reset(new %(cpp_type)s(temp));')
580 ) 625 )
581 else: 626 else:
582 (c.Append('if (!%s)' % cpp_util.GetAsFundamentalValue( 627 (c.Append('if (!%s) {' % cpp_util.GetAsFundamentalValue(
583 self._type_helper.FollowRef(type_), 628 self._type_helper.FollowRef(type_),
584 src_var, 629 src_var,
585 '&%s' % dst_var)) 630 '&%s' % dst_var)))
586 .Append(' return %(failure_value)s;') 631 if self._namespace.generate_error_messages:
632 self._GenerateError(c,
633 'get-as-type',
634 '"expected %s, got " << %s->GetType()' %
635 (self._type_helper.GetCppType(type_), src_var), True)
636 (c.Append(' return %(failure_value)s;')
637 .Append('}')
587 ) 638 )
588 elif underlying_type.property_type == PropertyType.OBJECT: 639 elif underlying_type.property_type == PropertyType.OBJECT:
589 if is_ptr: 640 if is_ptr:
590 (c.Append('const base::DictionaryValue* dictionary = NULL;') 641 (c.Append('const base::DictionaryValue* dictionary = NULL;')
591 .Append('if (!%(src_var)s->GetAsDictionary(&dictionary))') 642 .Append('if (!%(src_var)s->GetAsDictionary(&dictionary)) {'))
592 .Append(' return %(failure_value)s;') 643 if self._namespace.generate_error_messages:
593 .Append('scoped_ptr<%(cpp_type)s> temp(new %(cpp_type)s());') 644 self._GenerateError(c,
594 .Append('if (!%(cpp_type)s::Populate(*dictionary, temp.get()))') 645 'get-as-dict',
595 .Append(' return %(failure_value)s;') 646 '"expected dictionary, got " << %(src_var)s->GetType()', True)
647 (c.Append(' return %(failure_value)s;')
648 .Append('}')
649 .Append('scoped_ptr<%(cpp_type)s> temp(new %(cpp_type)s());'))
650 if self._namespace.generate_error_messages:
651 c.Append('if (!%(cpp_type)s::Populate('
652 '*dictionary, temp.get(), error)) {')
653 else:
654 c.Append('if (!%(cpp_type)s::Populate(*dictionary, temp.get())) {')
655 (c.Append(' return %(failure_value)s;')
656 .Append('}')
596 .Append('%(dst_var)s = temp.Pass();') 657 .Append('%(dst_var)s = temp.Pass();')
597 ) 658 )
598 else: 659 else:
599 (c.Append('const base::DictionaryValue* dictionary = NULL;') 660 (c.Append('const base::DictionaryValue* dictionary = NULL;')
600 .Append('if (!%(src_var)s->GetAsDictionary(&dictionary))') 661 .Append('if (!%(src_var)s->GetAsDictionary(&dictionary)) {'))
601 .Append(' return %(failure_value)s;') 662 if self._namespace.generate_error_messages:
602 .Append('if (!%(cpp_type)s::Populate(*dictionary, &%(dst_var)s))') 663 self._GenerateError(c,
603 .Append(' return %(failure_value)s;') 664 'get-as-dict',
665 '"expected dictionary, got " << %(src_var)s->GetType()', True)
666 (c.Append(' return %(failure_value)s;')
667 .Append('}'))
668 if self._namespace.generate_error_messages:
669 c.Append('if (!%(cpp_type)s::Populate('
670 '*dictionary, &%(dst_var)s, error)) {')
671 else:
672 c.Append('if (!%(cpp_type)s::Populate(*dictionary, &%(dst_var)s)) {')
673 (c.Append(' return %(failure_value)s;')
674 .Append('}')
not at google - send to devlin 2013/06/11 18:33:43 same comments; and is there a way to avoid so much
Aaron Jacobs 2013/06/14 02:00:37 Done.
604 ) 675 )
605 elif underlying_type.property_type == PropertyType.FUNCTION: 676 elif underlying_type.property_type == PropertyType.FUNCTION:
606 if is_ptr: 677 if is_ptr:
607 c.Append('%(dst_var)s.reset(new base::DictionaryValue());') 678 c.Append('%(dst_var)s.reset(new base::DictionaryValue());')
608 elif underlying_type.property_type == PropertyType.ANY: 679 elif underlying_type.property_type == PropertyType.ANY:
609 c.Append('%(dst_var)s.reset(%(src_var)s->DeepCopy());') 680 c.Append('%(dst_var)s.reset(%(src_var)s->DeepCopy());')
610 elif underlying_type.property_type == PropertyType.ARRAY: 681 elif underlying_type.property_type == PropertyType.ARRAY:
611 # util_cc_helper deals with optional and required arrays 682 # util_cc_helper deals with optional and required arrays
612 (c.Append('const base::ListValue* list = NULL;') 683 (c.Append('const base::ListValue* list = NULL;')
613 .Append('if (!%(src_var)s->GetAsList(&list))') 684 .Append('if (!%(src_var)s->GetAsList(&list)) {'))
614 .Append(' return %(failure_value)s;')) 685 if self._namespace.generate_error_messages:
686 self._GenerateError(c,
687 'get-as-list',
688 '"expected list, got " << %(src_var)s->GetType()', True)
689 (c.Append(' return %(failure_value)s;')
not at google - send to devlin 2013/06/11 18:33:43 as well as saying what the key is, it would be nic
690 .Append('}'))
615 item_type = underlying_type.item_type 691 item_type = underlying_type.item_type
616 if item_type.property_type == PropertyType.ENUM: 692 if item_type.property_type == PropertyType.ENUM:
617 c.Concat(self._GenerateListValueToEnumArrayConversion( 693 c.Concat(self._GenerateListValueToEnumArrayConversion(
618 item_type, 694 item_type,
619 'list', 695 'list',
620 dst_var, 696 dst_var,
621 failure_value, 697 failure_value,
622 is_ptr=is_ptr)) 698 is_ptr=is_ptr))
623 else: 699 else:
624 (c.Append('if (!%s)' % self._util_cc_helper.PopulateArrayFromList( 700 c.Append('if (!%s) {' % self._util_cc_helper.PopulateArrayFromList(
625 underlying_type, 701 underlying_type,
626 'list', 702 'list',
627 dst_var, 703 dst_var,
628 is_ptr)) 704 is_ptr))
629 .Append(' return %(failure_value)s;') 705 if self._namespace.generate_error_messages:
706 self._GenerateError(c,
707 'populate-array',
708 '"unable to populate array"',
not at google - send to devlin 2013/06/11 18:33:43 yeah; bummer. maybe those methods need to be chang
709 True)
710 (c.Append(' return %(failure_value)s;')
711 .Append('}')
630 ) 712 )
631 elif underlying_type.property_type == PropertyType.CHOICES: 713 elif underlying_type.property_type == PropertyType.CHOICES:
632 if is_ptr: 714 if is_ptr:
633 (c.Append('scoped_ptr<%(cpp_type)s> temp(new %(cpp_type)s());') 715 c.Append('scoped_ptr<%(cpp_type)s> temp(new %(cpp_type)s());')
634 .Append('if (!%(cpp_type)s::Populate(*%(src_var)s, temp.get()))') 716 if self._namespace.generate_error_messages:
635 .Append(' return %(failure_value)s;') 717 c.Append('if (!%(cpp_type)s::Populate('
718 '*%(src_var)s, temp.get(), error))')
719 else:
720 c.Append('if (!%(cpp_type)s::Populate(*%(src_var)s, temp.get()))')
721 (c.Append(' return %(failure_value)s;')
636 .Append('%(dst_var)s = temp.Pass();') 722 .Append('%(dst_var)s = temp.Pass();')
637 ) 723 )
638 else: 724 else:
639 (c.Append('if (!%(cpp_type)s::Populate(*%(src_var)s, &%(dst_var)s))') 725 if self._namespace.generate_error_messages:
640 .Append(' return %(failure_value)s;') 726 c.Append('if (!%(cpp_type)s::Populate('
641 ) 727 '*%(src_var)s, &%(dst_var)s, error))')
728 else:
729 c.Append('if (!%(cpp_type)s::Populate(*%(src_var)s, &%(dst_var)s))')
730 c.Append(' return %(failure_value)s;')
642 elif underlying_type.property_type == PropertyType.ENUM: 731 elif underlying_type.property_type == PropertyType.ENUM:
643 c.Concat(self._GenerateStringToEnumConversion(type_, 732 c.Concat(self._GenerateStringToEnumConversion(type_,
644 src_var, 733 src_var,
645 dst_var, 734 dst_var,
646 failure_value)) 735 failure_value))
647 elif underlying_type.property_type == PropertyType.BINARY: 736 elif underlying_type.property_type == PropertyType.BINARY:
648 (c.Append('if (!%(src_var)s->IsType(%(value_type)s))') 737 c.Append('if (!%(src_var)s->IsType(%(value_type)s)) {')
649 .Append(' return %(failure_value)s;') 738 if self._namespace.generate_error_messages:
739 self._GenerateError(c,
740 'type-check',
741 '"expected %(value_type)s, got " << %(src_var)s->GetType()', True)
742 (c.Append(' return %(failure_value)s;')
743 .Append('}')
650 .Append('const base::BinaryValue* binary_value =') 744 .Append('const base::BinaryValue* binary_value =')
651 .Append(' static_cast<const base::BinaryValue*>(%(src_var)s);') 745 .Append(' static_cast<const base::BinaryValue*>(%(src_var)s);')
652 ) 746 )
653 if is_ptr: 747 if is_ptr:
654 (c.Append('%(dst_var)s.reset(') 748 (c.Append('%(dst_var)s.reset(')
655 .Append(' new std::string(binary_value->GetBuffer(),') 749 .Append(' new std::string(binary_value->GetBuffer(),')
656 .Append(' binary_value->GetSize()));') 750 .Append(' binary_value->GetSize()));')
657 ) 751 )
658 else: 752 else:
659 (c.Append('%(dst_var)s.assign(binary_value->GetBuffer(),') 753 (c.Append('%(dst_var)s.assign(binary_value->GetBuffer(),')
(...skipping 49 matching lines...) Expand 10 before | Expand all | Expand 10 after
709 src_var, 803 src_var,
710 dst_var, 804 dst_var,
711 failure_value): 805 failure_value):
712 """Returns Code that converts a string type in |src_var| to an enum with 806 """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 807 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|. 808 a valid enum name then the function will return |failure_value|.
715 """ 809 """
716 c = Code() 810 c = Code()
717 enum_as_string = '%s_as_string' % type_.unix_name 811 enum_as_string = '%s_as_string' % type_.unix_name
718 (c.Append('std::string %s;' % enum_as_string) 812 (c.Append('std::string %s;' % enum_as_string)
719 .Append('if (!%s->GetAsString(&%s))' % (src_var, enum_as_string)) 813 .Append('if (!%s->GetAsString(&%s)) {' % (src_var, enum_as_string)))
720 .Append(' return %s;' % failure_value) 814 if self._namespace.generate_error_messages:
815 self._GenerateError(c,
816 'get-as-string',
817 '"expected std::string, got " << %s->GetType()' % src_var, True)
818 (c.Append(' return %s;' % failure_value)
819 .Append('}')
721 .Append('%s = Parse%s(%s);' % (dst_var, 820 .Append('%s = Parse%s(%s);' % (dst_var,
722 self._type_helper.GetCppType(type_), 821 self._type_helper.GetCppType(type_),
723 enum_as_string)) 822 enum_as_string))
724 .Append('if (%s == %s)' % (dst_var, 823 .Append('if (%s == %s) {' % (dst_var,
725 self._type_helper.GetEnumNoneValue(type_))) 824 self._type_helper.GetEnumNoneValue(type_))))
726 .Append(' return %s;' % failure_value) 825 if self._namespace.generate_error_messages:
826 self._GenerateError(c,
827 'get-from-string',
828 '"got bad enum value from variable \'%s\'"' % dst_var, True)
829 (c.Append(' return %s;' % failure_value)
830 .Append('}')
727 ) 831 )
728 return c 832 return c
729 833
730 def _GeneratePropertyFunctions(self, namespace, params): 834 def _GeneratePropertyFunctions(self, namespace, params):
731 """Generates the member functions for a list of parameters. 835 """Generates the member functions for a list of parameters.
732 """ 836 """
733 return self._GenerateTypes(namespace, (param.type_ for param in params)) 837 return self._GenerateTypes(namespace, (param.type_ for param in params))
734 838
735 def _GenerateTypes(self, namespace, types): 839 def _GenerateTypes(self, namespace, types):
736 """Generates the member functions for a list of types. 840 """Generates the member functions for a list of types.
(...skipping 97 matching lines...) Expand 10 before | Expand all | Expand 10 after
834 """ 938 """
835 c = Code() 939 c = Code()
836 underlying_type = self._type_helper.FollowRef(prop.type_) 940 underlying_type = self._type_helper.FollowRef(prop.type_)
837 if (underlying_type.property_type == PropertyType.ENUM and 941 if (underlying_type.property_type == PropertyType.ENUM and
838 prop.optional): 942 prop.optional):
839 c.Append('%s->%s = %s;' % ( 943 c.Append('%s->%s = %s;' % (
840 dst, 944 dst,
841 prop.unix_name, 945 prop.unix_name,
842 self._type_helper.GetEnumNoneValue(prop.type_))) 946 self._type_helper.GetEnumNoneValue(prop.type_)))
843 return c 947 return c
948
949 def _GenerateError(self, c, location, body, indent = False):
not at google - send to devlin 2013/06/11 18:33:43 - return the code don't append to an argument - co
Aaron Jacobs 2013/06/14 02:00:37 Done.
950 """Generates an error message pertaining to population failure, and appends
951 it to |c|.
952
953 E.g...
954 (get-from-dict): 'key not found: content' at
955 gen/chrome/common/extensions/api/omnibox.cc:241
956 """
not at google - send to devlin 2013/06/11 18:33:43 assert self._ShouldGenerateErrors()
957 padding = '';
958 if indent:
959 padding = ' ';
960 (c.Append(padding + 'if (error) {')
961 .Append(padding + ' std::stringstream ss;')
not at google - send to devlin 2013/06/11 18:33:43 just use string concatenation
Aaron Jacobs 2013/06/14 02:00:37 Done.
962 .Append(padding + ' ss << "' + location + ': \'" << ' + body +
963 ' << "\' at " << __FILE__ << ":" << (__LINE__ - 3);')
not at google - send to devlin 2013/06/11 18:33:43 this is all unlikely to be of interest to an exten
Aaron Jacobs 2013/06/14 02:00:37 Done.
964 .Append(padding + ' *error = ss.str();')
965 .Append(padding + '}'))
OLDNEW
« no previous file with comments | « no previous file | tools/json_schema_compiler/h_generator.py » ('j') | tools/json_schema_compiler/h_generator.py » ('J')

Powered by Google App Engine
This is Rietveld 408576698