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

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

Issue 10022005: Let json schema compiler handle using arrays as types (Closed) Base URL: http://git.chromium.org/chromium/src.git@master
Patch Set: Cleaned up code Created 8 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 model import PropertyType 5 from model import PropertyType
6 import any_helper 6 import any_helper
7 import code 7 import code
8 import cpp_util 8 import cpp_util
9 import model 9 import model
10 import sys 10 import sys
11 import util_cc_helper 11 import util_cc_helper
12 12
13 class CCGenerator(object): 13 class CCGenerator(object):
14 """A .cc generator for a namespace. 14 """A .cc generator for a namespace.
15 """ 15 """
16 def __init__(self, namespace, cpp_type_generator): 16 def __init__(self, namespace, cpp_type_generator, referenced_schemas):
Yoyo Zhou 2012/04/12 00:54:57 You can remove this since you don't use this anymo
17 self._cpp_type_generator = cpp_type_generator 17 self._cpp_type_generator = cpp_type_generator
18 self._referenced_schemas = referenced_schemas
18 self._namespace = namespace 19 self._namespace = namespace
19 self._target_namespace = ( 20 self._target_namespace = (
20 self._cpp_type_generator.GetCppNamespaceName(self._namespace)) 21 self._cpp_type_generator.GetCppNamespaceName(self._namespace))
21 self._util_cc_helper = ( 22 self._util_cc_helper = (
22 util_cc_helper.UtilCCHelper(self._cpp_type_generator)) 23 util_cc_helper.UtilCCHelper(self._cpp_type_generator))
23 self._any_helper = any_helper.AnyHelper() 24 self._any_helper = any_helper.AnyHelper()
24 25
25 def Generate(self): 26 def Generate(self):
26 """Generates a code.Code object with the .cc for a single namespace. 27 """Generates a code.Code object with the .cc for a single namespace.
27 """ 28 """
(...skipping 63 matching lines...) Expand 10 before | Expand all | Expand 10 after
91 if type_.properties: 92 if type_.properties:
92 raise NotImplementedError('\n'.join(model.GetModelHierarchy(type_)) + 93 raise NotImplementedError('\n'.join(model.GetModelHierarchy(type_)) +
93 '\nCannot generate both functions and properties on a type') 94 '\nCannot generate both functions and properties on a type')
94 for function in type_.functions.values(): 95 for function in type_.functions.values():
95 (c.Concat( 96 (c.Concat(
96 self._GenerateFunction( 97 self._GenerateFunction(
97 cpp_namespace + '::' + cpp_util.Classname(function.name), 98 cpp_namespace + '::' + cpp_util.Classname(function.name),
98 function)) 99 function))
99 .Append() 100 .Append()
100 ) 101 )
101 else: 102 elif type_.type_ == PropertyType.OBJECT:
102 (c.Concat(self._GeneratePropertyFunctions( 103 (c.Concat(self._GeneratePropertyFunctions(
103 cpp_namespace, type_.properties.values())) 104 cpp_namespace, type_.properties.values()))
104 .Sblock('%(namespace)s::%(classname)s()') 105 .Sblock('%(namespace)s::%(classname)s()')
105 .Concat(self._GenerateInitializersAndBody(type_)) 106 .Concat(self._GenerateInitializersAndBody(type_))
106 .Eblock('%(namespace)s::~%(classname)s() {}') 107 .Eblock('%(namespace)s::~%(classname)s() {}')
107 .Append() 108 .Append()
108 ) 109 )
109 if type_.from_json: 110 if type_.from_json:
110 (c.Concat(self._GenerateTypePopulate(cpp_namespace, type_)) 111 (c.Concat(self._GenerateTypePopulate(cpp_namespace, type_))
111 .Append() 112 .Append()
(...skipping 202 matching lines...) Expand 10 before | Expand all | Expand 10 after
314 315
315 E.g for std::string, generate Value::CreateStringValue(var) 316 E.g for std::string, generate Value::CreateStringValue(var)
316 """ 317 """
317 if prop.type_ == PropertyType.CHOICES: 318 if prop.type_ == PropertyType.CHOICES:
318 # CHOICES conversion not implemented. If needed, write something to 319 # CHOICES conversion not implemented. If needed, write something to
319 # generate a function that returns a scoped_ptr<Value> and put it in 320 # generate a function that returns a scoped_ptr<Value> and put it in
320 # _GeneratePropertyFunctions, then use it here. Look at CreateEnumValue() 321 # _GeneratePropertyFunctions, then use it here. Look at CreateEnumValue()
321 # for reference. 322 # for reference.
322 raise NotImplementedError( 323 raise NotImplementedError(
323 'Conversion of CHOICES to Value not implemented') 324 'Conversion of CHOICES to Value not implemented')
324 if prop.type_ in (PropertyType.REF, PropertyType.OBJECT): 325 if self._IsObjectOrObjectRef(prop):
325 if prop.optional: 326 if prop.optional:
326 return '%s->ToValue().release()' % var 327 return '%s->ToValue().release()' % var
327 else: 328 else:
328 return '%s.ToValue().release()' % var 329 return '%s.ToValue().release()' % var
329 elif prop.type_ == PropertyType.ANY: 330 elif prop.type_ == PropertyType.ANY:
330 return '%s.DeepCopy()' % self._any_helper.GetValue(prop, var) 331 return '%s.DeepCopy()' % self._any_helper.GetValue(prop, var)
331 elif prop.type_ == PropertyType.ADDITIONAL_PROPERTIES: 332 elif prop.type_ == PropertyType.ADDITIONAL_PROPERTIES:
332 return '%s.DeepCopy()' % var 333 return '%s.DeepCopy()' % var
333 elif prop.type_ == PropertyType.ENUM: 334 elif prop.type_ == PropertyType.ENUM:
334 return 'CreateEnumValue(%s).release()' % var 335 return 'CreateEnumValue(%s).release()' % var
335 elif prop.type_ == PropertyType.ARRAY: 336 elif self._IsArrayOrArrayRef(prop):
336 return '%s.release()' % self._util_cc_helper.CreateValueFromArray( 337 return '%s.release()' % self._util_cc_helper.CreateValueFromArray(
337 prop, var) 338 self._cpp_type_generator.GetReferencedProperty(prop), var,
339 prop.optional)
338 elif prop.type_.is_fundamental: 340 elif prop.type_.is_fundamental:
339 if prop.optional: 341 if prop.optional:
340 var = '*' + var 342 var = '*' + var
341 return { 343 return {
342 PropertyType.STRING: 'Value::CreateStringValue(%s)', 344 PropertyType.STRING: 'Value::CreateStringValue(%s)',
343 PropertyType.BOOLEAN: 'Value::CreateBooleanValue(%s)', 345 PropertyType.BOOLEAN: 'Value::CreateBooleanValue(%s)',
344 PropertyType.INTEGER: 'Value::CreateIntegerValue(%s)', 346 PropertyType.INTEGER: 'Value::CreateIntegerValue(%s)',
345 PropertyType.DOUBLE: 'Value::CreateDoubleValue(%s)', 347 PropertyType.DOUBLE: 'Value::CreateDoubleValue(%s)',
346 }[prop.type_] % var 348 }[prop.type_] % var
347 else: 349 else:
(...skipping 100 matching lines...) Expand 10 before | Expand all | Expand 10 after
448 .Append('if (%s)' % 450 .Append('if (%s)' %
449 cpp_util.GetAsFundamentalValue(prop, value_var, '&temp')) 451 cpp_util.GetAsFundamentalValue(prop, value_var, '&temp'))
450 .Append(' %(dst)s->%(name)s.reset(new %(ctype)s(temp));') 452 .Append(' %(dst)s->%(name)s.reset(new %(ctype)s(temp));')
451 ) 453 )
452 else: 454 else:
453 (c.Append('if (!%s)' % 455 (c.Append('if (!%s)' %
454 cpp_util.GetAsFundamentalValue( 456 cpp_util.GetAsFundamentalValue(
455 prop, value_var, '&%s->%s' % (dst, prop.unix_name))) 457 prop, value_var, '&%s->%s' % (dst, prop.unix_name)))
456 .Append('return %(failure_value)s;') 458 .Append('return %(failure_value)s;')
457 ) 459 )
458 elif prop.type_ in (PropertyType.OBJECT, PropertyType.REF): 460 elif self._IsObjectOrObjectRef(prop):
459 if prop.optional: 461 if prop.optional:
460 (c.Append('DictionaryValue* dictionary = NULL;') 462 (c.Append('DictionaryValue* dictionary = NULL;')
461 .Append('if (!%(value_var)s->GetAsDictionary(&dictionary))') 463 .Append('if (!%(value_var)s->GetAsDictionary(&dictionary))')
462 .Append(' return %(failure_value)s;') 464 .Append(' return %(failure_value)s;')
463 .Append('scoped_ptr<%(ctype)s> temp(new %(ctype)s());') 465 .Append('scoped_ptr<%(ctype)s> temp(new %(ctype)s());')
464 .Append('if (!%(ctype)s::Populate(*dictionary, temp.get()))') 466 .Append('if (!%(ctype)s::Populate(*dictionary, temp.get()))')
465 .Append(' return %(failure_value)s;') 467 .Append(' return %(failure_value)s;')
466 .Append('%(dst)s->%(name)s = temp.Pass();') 468 .Append('%(dst)s->%(name)s = temp.Pass();')
467 ) 469 )
468 else: 470 else:
469 (c.Append('DictionaryValue* dictionary = NULL;') 471 (c.Append('DictionaryValue* dictionary = NULL;')
470 .Append('if (!%(value_var)s->GetAsDictionary(&dictionary))') 472 .Append('if (!%(value_var)s->GetAsDictionary(&dictionary))')
471 .Append(' return %(failure_value)s;') 473 .Append(' return %(failure_value)s;')
472 .Append( 474 .Append(
473 'if (!%(ctype)s::Populate(*dictionary, &%(dst)s->%(name)s))') 475 'if (!%(ctype)s::Populate(*dictionary, &%(dst)s->%(name)s))')
474 .Append(' return %(failure_value)s;') 476 .Append(' return %(failure_value)s;')
475 ) 477 )
476 elif prop.type_ == PropertyType.ANY: 478 elif prop.type_ == PropertyType.ANY:
477 if prop.optional: 479 if prop.optional:
478 c.Append('%(dst)s->%(name)s.reset(new Any());') 480 c.Append('%(dst)s->%(name)s.reset(new Any());')
479 c.Append(self._any_helper.Init(prop, value_var, dst) + ';') 481 c.Append(self._any_helper.Init(prop, value_var, dst) + ';')
480 elif prop.type_ == PropertyType.ARRAY: 482 elif self._IsArrayOrArrayRef(prop):
481 # util_cc_helper deals with optional and required arrays 483 # util_cc_helper deals with optional and required arrays
482 (c.Append('ListValue* list = NULL;') 484 (c.Append('ListValue* list = NULL;')
483 .Append('if (!%(value_var)s->GetAsList(&list))') 485 .Append('if (!%(value_var)s->GetAsList(&list))')
484 .Append(' return %(failure_value)s;') 486 .Append(' return %(failure_value)s;')
485 .Append('if (!%s)' % self._util_cc_helper.PopulateArrayFromList( 487 .Append('if (!%s)' % self._util_cc_helper.PopulateArrayFromList(
486 prop, 'list', dst + '->' + prop.unix_name)) 488 self._cpp_type_generator.GetReferencedProperty(prop), 'list',
489 dst + '->' + prop.unix_name, prop.optional))
487 .Append(' return %(failure_value)s;') 490 .Append(' return %(failure_value)s;')
488 ) 491 )
489 elif prop.type_ == PropertyType.CHOICES: 492 elif prop.type_ == PropertyType.CHOICES:
490 type_var = '%(dst)s->%(name)s_type' 493 type_var = '%(dst)s->%(name)s_type'
491 c.Sblock('switch (%(value_var)s->GetType()) {') 494 c.Sblock('switch (%(value_var)s->GetType()) {')
492 for choice in self._cpp_type_generator.GetExpandedChoicesInParams([prop]): 495 for choice in self._cpp_type_generator.GetExpandedChoicesInParams([prop]):
493 (c.Sblock('case %s: {' % cpp_util.GetValueType(choice)) 496 (c.Sblock('case %s: {' % cpp_util.GetValueType(
497 self._cpp_type_generator.GetReferencedProperty(choice).type_))
494 .Concat(self._GeneratePopulatePropertyFromValue( 498 .Concat(self._GeneratePopulatePropertyFromValue(
495 choice, value_var, dst, failure_value, check_type=False)) 499 choice, value_var, dst, failure_value, check_type=False))
496 .Append('%s = %s;' % 500 .Append('%s = %s;' %
497 (type_var, 501 (type_var,
498 self._cpp_type_generator.GetEnumValue( 502 self._cpp_type_generator.GetEnumValue(
499 prop, choice.type_.name))) 503 prop, choice.type_.name)))
500 .Append('break;') 504 .Append('break;')
501 .Eblock('}') 505 .Eblock('}')
502 ) 506 )
503 (c.Append('default:') 507 (c.Append('default:')
(...skipping 21 matching lines...) Expand all
525 raise NotImplementedError(prop.type_) 529 raise NotImplementedError(prop.type_)
526 c.Eblock('}') 530 c.Eblock('}')
527 sub = { 531 sub = {
528 'value_var': value_var, 532 'value_var': value_var,
529 'name': prop.unix_name, 533 'name': prop.unix_name,
530 'dst': dst, 534 'dst': dst,
531 'failure_value': failure_value, 535 'failure_value': failure_value,
532 } 536 }
533 if prop.type_ not in (PropertyType.CHOICES, PropertyType.ANY): 537 if prop.type_ not in (PropertyType.CHOICES, PropertyType.ANY):
534 sub['ctype'] = self._cpp_type_generator.GetType(prop) 538 sub['ctype'] = self._cpp_type_generator.GetType(prop)
535 sub['value_type'] = cpp_util.GetValueType(prop) 539 sub['value_type'] = cpp_util.GetValueType(self._cpp_type_generator
540 .GetReferencedProperty(prop).type_)
536 c.Substitute(sub) 541 c.Substitute(sub)
537 return c 542 return c
538 543
539 def _GeneratePropertyFunctions(self, param_namespace, params): 544 def _GeneratePropertyFunctions(self, param_namespace, params):
540 """Generate the functions for structures generated by a property such as 545 """Generate the functions for structures generated by a property such as
541 CreateEnumValue for ENUMs and Populate/ToValue for Params/Result objects. 546 CreateEnumValue for ENUMs and Populate/ToValue for Params/Result objects.
542 """ 547 """
543 c = code.Code() 548 c = code.Code()
544 for param in params: 549 for param in params:
545 if param.type_ == PropertyType.OBJECT: 550 if param.type_ == PropertyType.OBJECT:
(...skipping 63 matching lines...) Expand 10 before | Expand all | Expand 10 after
609 if prop.type_ in (PropertyType.ENUM, PropertyType.CHOICES): 614 if prop.type_ in (PropertyType.ENUM, PropertyType.CHOICES):
610 if prop.optional: 615 if prop.optional:
611 prop_name = prop.unix_name 616 prop_name = prop.unix_name
612 if prop.type_ == PropertyType.CHOICES: 617 if prop.type_ == PropertyType.CHOICES:
613 prop_name = prop.unix_name + '_type' 618 prop_name = prop.unix_name + '_type'
614 c.Append('%s->%s = %s;' % ( 619 c.Append('%s->%s = %s;' % (
615 dst, 620 dst,
616 prop_name, 621 prop_name,
617 self._cpp_type_generator.GetEnumNoneValue(prop))) 622 self._cpp_type_generator.GetEnumNoneValue(prop)))
618 return c 623 return c
624
625 def _IsObjectOrObjectRef(self, prop):
626 """Determines if this property is an Object or is a ref to an Object.
627 """
628 return (self._cpp_type_generator.GetReferencedProperty(prop).type_ ==
629 PropertyType.OBJECT)
630
631 def _IsArrayOrArrayRef(self, prop):
632 """Determines if this property is an Array or is a ref to an Array.
633 """
634 return (self._cpp_type_generator.GetReferencedProperty(prop).type_ ==
635 PropertyType.ARRAY)
OLDNEW

Powered by Google App Engine
This is Rietveld 408576698