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

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

Issue 1869503004: Convert //tools to use std::unique_ptr (Closed) Base URL: https://chromium.googlesource.com/chromium/src.git@master
Patch Set: rebase, change iwyu fixes for converted directories to include <memory> Created 4 years, 8 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 6 from model import PropertyType
7 import cpp_util 7 import cpp_util
8 import schema_util 8 import schema_util
9 import util_cc_helper 9 import util_cc_helper
10 from cpp_namespace_environment import CppNamespaceEnvironment 10 from cpp_namespace_environment import CppNamespaceEnvironment
(...skipping 393 matching lines...) Expand 10 before | Expand all | Expand 10 after
404 'src': src, 404 'src': src,
405 'dst': dst, 405 'dst': dst,
406 'name': prop.unix_name 406 'name': prop.unix_name
407 }) 407 })
408 return c 408 return c
409 409
410 def _GenerateTypeFromValue(self, cpp_namespace, type_): 410 def _GenerateTypeFromValue(self, cpp_namespace, type_):
411 classname = cpp_util.Classname(schema_util.StripNamespace(type_.name)) 411 classname = cpp_util.Classname(schema_util.StripNamespace(type_.name))
412 c = Code() 412 c = Code()
413 (c.Append('// static') 413 (c.Append('// static')
414 .Append('scoped_ptr<%s> %s::FromValue(%s) {' % (classname, 414 .Append('std::unique_ptr<%s> %s::FromValue(%s) {' % (classname,
415 cpp_namespace, self._GenerateParams(('const base::Value& value',)))) 415 cpp_namespace, self._GenerateParams(('const base::Value& value',))))
416 ) 416 )
417 if self._generate_error_messages: 417 if self._generate_error_messages:
418 c.Append('DCHECK(error);') 418 c.Append('DCHECK(error);')
419 (c.Append(' scoped_ptr<%s> out(new %s());' % (classname, classname)) 419 (c.Append(' std::unique_ptr<%s> out(new %s());' % (classname, classname))
420 .Append(' if (!Populate(%s))' % self._GenerateArgs( 420 .Append(' if (!Populate(%s))' % self._GenerateArgs(
421 ('value', 'out.get()'))) 421 ('value', 'out.get()')))
422 .Append(' return scoped_ptr<%s>();' % classname) 422 .Append(' return nullptr;')
423 .Append(' return out;') 423 .Append(' return out;')
424 .Append('}') 424 .Append('}')
425 ) 425 )
426 return c 426 return c
427 427
428 def _GenerateTypeToValue(self, cpp_namespace, type_): 428 def _GenerateTypeToValue(self, cpp_namespace, type_):
429 """Generates a function that serializes the type into a base::Value. 429 """Generates a function that serializes the type into a base::Value.
430 E.g. for type "Foo" generates Foo::ToValue() 430 E.g. for type "Foo" generates Foo::ToValue()
431 """ 431 """
432 if type_.property_type == PropertyType.OBJECT: 432 if type_.property_type == PropertyType.OBJECT:
433 return self._GenerateObjectTypeToValue(cpp_namespace, type_) 433 return self._GenerateObjectTypeToValue(cpp_namespace, type_)
434 elif type_.property_type == PropertyType.CHOICES: 434 elif type_.property_type == PropertyType.CHOICES:
435 return self._GenerateChoiceTypeToValue(cpp_namespace, type_) 435 return self._GenerateChoiceTypeToValue(cpp_namespace, type_)
436 else: 436 else:
437 raise ValueError("Unsupported property type %s" % type_.type_) 437 raise ValueError("Unsupported property type %s" % type_.type_)
438 438
439 def _GenerateObjectTypeToValue(self, cpp_namespace, type_): 439 def _GenerateObjectTypeToValue(self, cpp_namespace, type_):
440 """Generates a function that serializes an object-representing type 440 """Generates a function that serializes an object-representing type
441 into a base::DictionaryValue. 441 into a base::DictionaryValue.
442 """ 442 """
443 c = Code() 443 c = Code()
444 (c.Sblock('scoped_ptr<base::DictionaryValue> %s::ToValue() const {' % 444 (c.Sblock('std::unique_ptr<base::DictionaryValue> %s::ToValue() const {' %
445 cpp_namespace) 445 cpp_namespace)
446 .Append('scoped_ptr<base::DictionaryValue> value(' 446 .Append('std::unique_ptr<base::DictionaryValue> value('
447 'new base::DictionaryValue());') 447 'new base::DictionaryValue());')
448 .Append() 448 .Append()
449 ) 449 )
450 450
451 for prop in type_.properties.values(): 451 for prop in type_.properties.values():
452 prop_var = 'this->%s' % prop.unix_name 452 prop_var = 'this->%s' % prop.unix_name
453 if prop.optional: 453 if prop.optional:
454 underlying_type = self._type_helper.FollowRef(prop.type_) 454 underlying_type = self._type_helper.FollowRef(prop.type_)
455 if underlying_type.property_type == PropertyType.ENUM: 455 if underlying_type.property_type == PropertyType.ENUM:
456 # Optional enum values are generated with a NONE enum value, 456 # Optional enum values are generated with a NONE enum value,
(...skipping 36 matching lines...) Expand 10 before | Expand all | Expand 10 after
493 493
494 return (c.Append() 494 return (c.Append()
495 .Append('return value;') 495 .Append('return value;')
496 .Eblock('}')) 496 .Eblock('}'))
497 497
498 def _GenerateChoiceTypeToValue(self, cpp_namespace, type_): 498 def _GenerateChoiceTypeToValue(self, cpp_namespace, type_):
499 """Generates a function that serializes a choice-representing type 499 """Generates a function that serializes a choice-representing type
500 into a base::Value. 500 into a base::Value.
501 """ 501 """
502 c = Code() 502 c = Code()
503 c.Sblock('scoped_ptr<base::Value> %s::ToValue() const {' % cpp_namespace) 503 c.Sblock('std::unique_ptr<base::Value> %s::ToValue() const {' %
504 c.Append('scoped_ptr<base::Value> result;') 504 cpp_namespace)
505 c.Append('std::unique_ptr<base::Value> result;')
505 for choice in type_.choices: 506 for choice in type_.choices:
506 choice_var = 'as_%s' % choice.unix_name 507 choice_var = 'as_%s' % choice.unix_name
507 # Enums cannot be wrapped with scoped_ptr, but the XXX_NONE enum value 508 # Enums cannot be wrapped with scoped_ptr, but the XXX_NONE enum value
508 # is equal to 0. 509 # is equal to 0.
509 (c.Sblock('if (%s) {' % choice_var) 510 (c.Sblock('if (%s) {' % choice_var)
510 .Append('DCHECK(!result) << "Cannot set multiple choices for %s";' % 511 .Append('DCHECK(!result) << "Cannot set multiple choices for %s";' %
511 type_.unix_name) 512 type_.unix_name)
512 .Cblock(self._CreateValueFromType('result.reset(%s);', 513 .Cblock(self._CreateValueFromType('result.reset(%s);',
513 choice.name, 514 choice.name,
514 choice, 515 choice,
(...skipping 157 matching lines...) Expand 10 before | Expand all | Expand 10 after
672 if num_required == len(function.params): 673 if num_required == len(function.params):
673 c.Sblock('if (%(var)s.GetSize() != %(total)d) {') 674 c.Sblock('if (%(var)s.GetSize() != %(total)d) {')
674 elif not num_required: 675 elif not num_required:
675 c.Sblock('if (%(var)s.GetSize() > %(total)d) {') 676 c.Sblock('if (%(var)s.GetSize() > %(total)d) {')
676 else: 677 else:
677 c.Sblock('if (%(var)s.GetSize() < %(required)d' 678 c.Sblock('if (%(var)s.GetSize() < %(required)d'
678 ' || %(var)s.GetSize() > %(total)d) {') 679 ' || %(var)s.GetSize() > %(total)d) {')
679 (c.Concat(self._GenerateError( 680 (c.Concat(self._GenerateError(
680 '"expected %%(total)d arguments, got " ' 681 '"expected %%(total)d arguments, got " '
681 '+ base::IntToString(%%(var)s.GetSize())')) 682 '+ base::IntToString(%%(var)s.GetSize())'))
682 .Append('return scoped_ptr<Params>();') 683 .Append('return nullptr;')
683 .Eblock('}') 684 .Eblock('}')
684 .Substitute({ 685 .Substitute({
685 'var': var, 686 'var': var,
686 'required': num_required, 687 'required': num_required,
687 'total': len(function.params), 688 'total': len(function.params),
688 })) 689 }))
689 return c 690 return c
690 691
691 def _GenerateFunctionParamsCreate(self, function): 692 def _GenerateFunctionParamsCreate(self, function):
692 """Generate function to create an instance of Params. The generated 693 """Generate function to create an instance of Params. The generated
693 function takes a base::ListValue of arguments. 694 function takes a base::ListValue of arguments.
694 695
695 E.g for function "Bar", generate Bar::Params::Create() 696 E.g for function "Bar", generate Bar::Params::Create()
696 """ 697 """
697 c = Code() 698 c = Code()
698 (c.Append('// static') 699 (c.Append('// static')
699 .Sblock('scoped_ptr<Params> Params::Create(%s) {' % self._GenerateParams( 700 .Sblock('std::unique_ptr<Params> Params::Create(%s) {' %
700 ['const base::ListValue& args'])) 701 self._GenerateParams(['const base::ListValue& args']))
701 ) 702 )
702 if self._generate_error_messages: 703 if self._generate_error_messages:
703 c.Append('DCHECK(error);') 704 c.Append('DCHECK(error);')
704 (c.Concat(self._GenerateParamsCheck(function, 'args')) 705 (c.Concat(self._GenerateParamsCheck(function, 'args'))
705 .Append('scoped_ptr<Params> params(new Params());') 706 .Append('std::unique_ptr<Params> params(new Params());')
706 ) 707 )
707 708
708 for param in function.params: 709 for param in function.params:
709 c.Concat(self._InitializePropertyToDefault(param, 'params')) 710 c.Concat(self._InitializePropertyToDefault(param, 'params'))
710 711
711 for i, param in enumerate(function.params): 712 for i, param in enumerate(function.params):
712 # Any failure will cause this function to return. If any argument is 713 # Any failure will cause this function to return. If any argument is
713 # incorrect or missing, those following it are not processed. Note that 714 # incorrect or missing, those following it are not processed. Note that
714 # for optional arguments, we allow missing arguments and proceed because 715 # for optional arguments, we allow missing arguments and proceed because
715 # there may be other arguments following it. 716 # there may be other arguments following it.
716 failure_value = 'scoped_ptr<Params>()' 717 failure_value = 'std::unique_ptr<Params>()'
717 c.Append() 718 c.Append()
718 value_var = param.unix_name + '_value' 719 value_var = param.unix_name + '_value'
719 (c.Append('const base::Value* %(value_var)s = NULL;') 720 (c.Append('const base::Value* %(value_var)s = NULL;')
720 .Append('if (args.Get(%(i)s, &%(value_var)s) &&') 721 .Append('if (args.Get(%(i)s, &%(value_var)s) &&')
721 .Sblock(' !%(value_var)s->IsType(base::Value::TYPE_NULL)) {') 722 .Sblock(' !%(value_var)s->IsType(base::Value::TYPE_NULL)) {')
722 .Concat(self._GeneratePopulatePropertyFromValue( 723 .Concat(self._GeneratePopulatePropertyFromValue(
723 param, value_var, 'params', failure_value)) 724 param, value_var, 'params', failure_value))
724 .Eblock('}') 725 .Eblock('}')
725 ) 726 )
726 if not param.optional: 727 if not param.optional:
(...skipping 78 matching lines...) Expand 10 before | Expand all | Expand 10 after
805 .Concat(self._GenerateError( 806 .Concat(self._GenerateError(
806 '"\'%%(key)s\': expected dictionary, got " + ' + 807 '"\'%%(key)s\': expected dictionary, got " + ' +
807 self._util_cc_helper.GetValueTypeString('%%(src_var)s', True)))) 808 self._util_cc_helper.GetValueTypeString('%%(src_var)s', True))))
808 # If an optional property fails to populate, the population can still 809 # If an optional property fails to populate, the population can still
809 # succeed with a warning. If no error messages are generated, this 810 # succeed with a warning. If no error messages are generated, this
810 # warning is not set and we fail out instead. 811 # warning is not set and we fail out instead.
811 if not self._generate_error_messages: 812 if not self._generate_error_messages:
812 c.Append('return %(failure_value)s;') 813 c.Append('return %(failure_value)s;')
813 (c.Eblock('}') 814 (c.Eblock('}')
814 .Sblock('else {') 815 .Sblock('else {')
815 .Append('scoped_ptr<%(cpp_type)s> temp(new %(cpp_type)s());') 816 .Append('std::unique_ptr<%(cpp_type)s> temp(new %(cpp_type)s());')
816 .Append('if (!%%(cpp_type)s::Populate(%s)) {' % self._GenerateArgs( 817 .Append('if (!%%(cpp_type)s::Populate(%s)) {' % self._GenerateArgs(
817 ('*dictionary', 'temp.get()'))) 818 ('*dictionary', 'temp.get()')))
818 .Append(' return %(failure_value)s;') 819 .Append(' return %(failure_value)s;')
819 ) 820 )
820 (c.Append('}') 821 (c.Append('}')
821 .Append('else') 822 .Append('else')
822 .Append(' %(dst_var)s = std::move(temp);') 823 .Append(' %(dst_var)s = std::move(temp);')
823 .Eblock('}') 824 .Eblock('}')
824 ) 825 )
825 else: 826 else:
(...skipping 43 matching lines...) Expand 10 before | Expand all | Expand 10 after
869 c.Concat(self._GenerateError( 870 c.Concat(self._GenerateError(
870 '"unable to populate array \'%%(parent_key)s\'"')) 871 '"unable to populate array \'%%(parent_key)s\'"'))
871 if is_ptr and self._generate_error_messages: 872 if is_ptr and self._generate_error_messages:
872 c.Append('%(dst_var)s.reset();') 873 c.Append('%(dst_var)s.reset();')
873 else: 874 else:
874 c.Append('return %(failure_value)s;') 875 c.Append('return %(failure_value)s;')
875 c.Eblock('}') 876 c.Eblock('}')
876 c.Eblock('}') 877 c.Eblock('}')
877 elif underlying_type.property_type == PropertyType.CHOICES: 878 elif underlying_type.property_type == PropertyType.CHOICES:
878 if is_ptr: 879 if is_ptr:
879 (c.Append('scoped_ptr<%(cpp_type)s> temp(new %(cpp_type)s());') 880 (c.Append('std::unique_ptr<%(cpp_type)s> temp(new %(cpp_type)s());')
880 .Append('if (!%%(cpp_type)s::Populate(%s))' % self._GenerateArgs( 881 .Append('if (!%%(cpp_type)s::Populate(%s))' % self._GenerateArgs(
881 ('*%(src_var)s', 'temp.get()'))) 882 ('*%(src_var)s', 'temp.get()')))
882 .Append(' return %(failure_value)s;') 883 .Append(' return %(failure_value)s;')
883 .Append('%(dst_var)s = std::move(temp);') 884 .Append('%(dst_var)s = std::move(temp);')
884 ) 885 )
885 else: 886 else:
886 (c.Append('if (!%%(cpp_type)s::Populate(%s))' % self._GenerateArgs( 887 (c.Append('if (!%%(cpp_type)s::Populate(%s))' % self._GenerateArgs(
887 ('*%(src_var)s', '&%(dst_var)s'))) 888 ('*%(src_var)s', '&%(dst_var)s')))
888 .Append(' return %(failure_value)s;')) 889 .Append(' return %(failure_value)s;'))
889 elif underlying_type.property_type == PropertyType.ENUM: 890 elif underlying_type.property_type == PropertyType.ENUM:
(...skipping 188 matching lines...) Expand 10 before | Expand all | Expand 10 after
1078 E.g for event "Baz", generate Baz::Create 1079 E.g for event "Baz", generate Baz::Create
1079 1080
1080 function_scope: the function scope path, e.g. Foo::Bar for the function 1081 function_scope: the function scope path, e.g. Foo::Bar for the function
1081 Foo::Bar::Baz(). May be None if there is no function scope. 1082 Foo::Bar::Baz(). May be None if there is no function scope.
1082 callback: the Function object we are creating callback arguments for. 1083 callback: the Function object we are creating callback arguments for.
1083 """ 1084 """
1084 c = Code() 1085 c = Code()
1085 params = callback.params 1086 params = callback.params
1086 c.Concat(self._GeneratePropertyFunctions(function_scope, params)) 1087 c.Concat(self._GeneratePropertyFunctions(function_scope, params))
1087 1088
1088 (c.Sblock('scoped_ptr<base::ListValue> %(function_scope)s' 1089 (c.Sblock('std::unique_ptr<base::ListValue> %(function_scope)s'
1089 'Create(%(declaration_list)s) {') 1090 'Create(%(declaration_list)s) {')
1090 .Append('scoped_ptr<base::ListValue> create_results(' 1091 .Append('std::unique_ptr<base::ListValue> create_results('
1091 'new base::ListValue());') 1092 'new base::ListValue());')
1092 ) 1093 )
1093 declaration_list = [] 1094 declaration_list = []
1094 for param in params: 1095 for param in params:
1095 declaration_list.append(cpp_util.GetParameterDeclaration( 1096 declaration_list.append(cpp_util.GetParameterDeclaration(
1096 param, self._type_helper.GetCppType(param.type_))) 1097 param, self._type_helper.GetCppType(param.type_)))
1097 c.Cblock(self._CreateValueFromType('create_results->Append(%s);', 1098 c.Cblock(self._CreateValueFromType('create_results->Append(%s);',
1098 param.name, 1099 param.name,
1099 param.type_, 1100 param.type_,
1100 param.unix_name)) 1101 param.unix_name))
(...skipping 54 matching lines...) Expand 10 before | Expand all | Expand 10 after
1155 if self._generate_error_messages: 1156 if self._generate_error_messages:
1156 params = list(params) + ['base::string16* error'] 1157 params = list(params) + ['base::string16* error']
1157 return ', '.join(str(p) for p in params) 1158 return ', '.join(str(p) for p in params)
1158 1159
1159 def _GenerateArgs(self, args): 1160 def _GenerateArgs(self, args):
1160 """Builds the argument list for a function, given an array of arguments. 1161 """Builds the argument list for a function, given an array of arguments.
1161 """ 1162 """
1162 if self._generate_error_messages: 1163 if self._generate_error_messages:
1163 args = list(args) + ['error'] 1164 args = list(args) + ['error']
1164 return ', '.join(str(a) for a in args) 1165 return ', '.join(str(a) for a in args)
OLDNEW
« no previous file with comments | « tools/ipc_fuzzer/message_replay/replay_process.h ('k') | tools/json_schema_compiler/cpp_type_generator.py » ('j') | no next file with comments »

Powered by Google App Engine
This is Rietveld 408576698