Merge Chromium + Blink git repositories
[chromium-blink-merge.git] / tools / json_to_struct / struct_generator.py
blob5849d82b4511d3124c669098c3713ac2aaf532bd
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 def _GenerateArrayField(field_info):
6 """Generate a string defining an array field in a C structure.
7 """
8 contents = field_info['contents']
9 contents['field'] = '* ' + field_info['field']
10 if contents['type'] == 'array':
11 raise RuntimeError('Nested arrays are not supported.')
12 return (GenerateField(contents) + ';\n' +
13 ' const size_t %s_size') % field_info['field'];
15 def GenerateField(field_info):
16 """Generate a string defining a field of the type specified by
17 field_info['type'] in a C structure.
18 """
19 field = field_info['field']
20 type = field_info['type']
21 if type == 'int':
22 return 'const int %s' % field
23 elif type == 'string':
24 return 'const char* const %s' % field
25 elif type == 'string16':
26 return 'const wchar_t* const %s' % field
27 elif type == 'enum':
28 return 'const %s %s' % (field_info['ctype'], field)
29 elif type == 'array':
30 return _GenerateArrayField(field_info)
31 elif type == 'struct':
32 return 'const %s %s' % (field_info['type_name'], field)
33 else:
34 raise RuntimeError('Unknown field type "%s"' % type)
36 def GenerateStruct(type_name, schema):
37 """Generate a string defining a structure containing the fields specified in
38 the schema list.
39 """
40 lines = [];
41 lines.append('struct %s {' % type_name)
42 for field_info in schema:
43 if field_info['type'] == 'struct':
44 lines.insert(0, GenerateStruct(field_info['type_name'],
45 field_info['fields']))
46 elif (field_info['type'] == 'array'
47 and field_info['contents']['type'] == 'struct'):
48 contents = field_info['contents']
49 lines.insert(0, GenerateStruct(contents['type_name'],
50 contents['fields']))
51 lines.append(' ' + GenerateField(field_info) + ';')
52 lines.append('};');
53 return '\n'.join(lines) + '\n';