OLD | NEW |
---|---|
(Empty) | |
1 #!/usr/bin/env python | |
2 # Copyright 2012 The Chromium Authors. All rights reserved. | |
3 # Use of this source code is governed by a BSD-style license that can be | |
4 # found in the LICENSE file. | |
5 | |
6 # Format for the JSON schema file: | |
7 # { | |
8 # "type_name": "DesiredCStructName", | |
9 # "headers": [ // Optional list of headers to be included by the .h. | |
10 # "path/to/header.h" | |
11 # ], | |
12 # "schema": [ // Fields of the generated structure. | |
13 # { | |
14 # "field": "my_enum_field", | |
15 # "type": "enum", // Either: int, string, string16, enum, array. | |
16 # "default": "RED", // Optional. Cannot be used for array. | |
17 # "ctype": "Color" // Only for enum, specify the C type. | |
18 # }, | |
19 # { | |
20 # "field": "my_int_array_field", // my_int_array_field_size will also | |
21 # "type": "array", // be generated. | |
22 # "contents": { | |
23 # "type": "int" // Either: int, string, string16, enum, array. | |
24 # } | |
25 # }, | |
26 # ... | |
27 # ] | |
28 # } | |
29 # | |
30 # Format for the JSON description file: | |
31 # { | |
32 # "int_variables": { // An optional list of constant int variables. | |
33 # "kDesiredConstantName": 45 | |
34 # }, | |
35 # "elements": { // All the elements for which to create static | |
36 # // initialization code in the .cc file. | |
37 # "my_const_variable": { | |
38 # "my_int_field": 10, | |
39 # "my_string_field": "foo bar", | |
40 # "my_enum_field": "BLACK", | |
41 # "my_int_array_field": [ 1, 2, 3, 5, 7 ], | |
42 # }, | |
43 # "my_other_const_variable": { | |
44 # ... | |
45 # } | |
46 # } | |
47 # } | |
48 | |
49 import json | |
50 from datetime import datetime | |
51 import os.path | |
52 import sys | |
53 import optparse | |
54 import copy | |
55 _script_path = os.path.realpath(__file__) | |
56 _old_path = copy.copy(sys.path) | |
57 | |
58 sys.path.insert(0, os.path.normpath(_script_path + "/../../")) | |
59 try: | |
60 import json_comment_eater | |
61 finally: | |
62 sys.path = _old_path | |
not at google - send to devlin
2012/11/13 20:28:07
nit: rather than storing _old_path use sys.path.po
beaudoin
2012/11/13 21:42:04
/facepalm :)
Done.
| |
63 | |
64 import struct_generator | |
65 import element_generator | |
66 | |
67 HEAD = """// Copyright %d The Chromium Authors. All rights reserved. | |
68 // Use of this source code is governed by a BSD-style license that can be | |
69 // found in the LICENSE file. | |
70 | |
71 // GENERATED FROM THE SCHEMA DEFINITION AND DESCRIPTION IN | |
72 // %s | |
73 // %s | |
74 // DO NOT EDIT. | |
75 | |
76 """ | |
77 | |
78 def _GenerateHeaderGuard(h_filename): | |
79 """Generates the string used in #ifndef guarding the header file. | |
80 """ | |
81 return (('%s_' % h_filename) | |
82 .upper().replace(os.sep, '_').replace('/', '_').replace('.', '_')) | |
83 | |
84 def _GenerateH(fileroot, head, namespace, schema, description): | |
85 """Generates the .h file containing the definition of the structure specified | |
86 by the schema. | |
87 | |
88 Args: | |
89 fileroot: The filename and path of the file to create, without an extension. | |
90 head: The string to output as the header of the .h file. | |
91 namespace: A string corresponding to the C++ namespace to use. | |
92 schema: A dict containing the schema. See comment at the top of this file. | |
93 description: A dict containing the description. See comment at the top of | |
94 this file. | |
95 """ | |
96 | |
97 h_filename = fileroot + '.h' | |
98 with open(h_filename, 'w') as f: | |
99 f.write(head) | |
100 header_guard = _GenerateHeaderGuard(h_filename) | |
101 f.write('#ifndef %s\n' % header_guard) | |
102 f.write('#define %s\n' % header_guard) | |
103 f.write('\n') | |
104 | |
105 try: | |
106 for header in schema['headers']: | |
107 f.write('#include "%s"\n' % header) | |
108 except KeyError: | |
not at google - send to devlin
2012/11/13 20:28:07
use schema.get('headers', []) rather than keyerror
beaudoin
2012/11/13 21:42:04
Done.
| |
109 pass | |
110 f.write('\n') | |
111 | |
112 if namespace: | |
113 f.write('namespace %s {\n' % namespace) | |
114 f.write('\n') | |
115 | |
116 f.write(struct_generator.GenerateStruct( | |
117 schema['type_name'], schema['schema'])) | |
118 f.write('\n') | |
119 | |
120 try: | |
121 for var_name, value in description['int_variables'].items(): | |
122 f.write('extern const int %s;\n' % var_name) | |
123 f.write('\n') | |
124 except KeyError: | |
not at google - send to devlin
2012/11/13 20:28:07
use description.get('int_variables', []) rather th
beaudoin
2012/11/13 21:42:04
Done.
| |
125 pass | |
126 | |
127 for element_name, element in description['elements'].items(): | |
128 f.write('extern const %s %s;\n' % (schema['type_name'], element_name)) | |
129 | |
130 if namespace: | |
131 f.write('\n') | |
132 f.write('} // namespace %s\n' % namespace) | |
133 | |
134 f.write('\n') | |
135 f.write( '#endif // %s\n' % header_guard) | |
136 | |
137 def _GenerateCC(fileroot, head, namespace, schema, description): | |
138 """Generates the .cc file containing the static initializers for the | |
139 of the elements specified in the description. | |
140 | |
141 Args: | |
142 fileroot: The filename and path of the file to create, without an extension. | |
143 head: The string to output as the header of the .cc file. | |
144 namespace: A string corresponding to the C++ namespace to use. | |
145 schema: A dict containing the schema. See comment at the top of this file. | |
146 description: A dict containing the description. See comment at the top of | |
147 this file. | |
148 """ | |
149 with open(fileroot + '.cc', 'w') as f: | |
150 f.write(head) | |
151 | |
152 f.write('#include <stdio.h>\n') | |
153 f.write('\n') | |
154 f.write('#include "%s"\n' % (fileroot + '.h')) | |
155 f.write('\n') | |
156 | |
157 if namespace: | |
158 f.write('namespace %s {\n' % namespace) | |
159 f.write('\n') | |
160 | |
161 f.write(element_generator.GenerateElements(schema['type_name'], | |
not at google - send to devlin
2012/11/13 20:28:07
This distinction between the "struct generator" an
beaudoin
2012/11/13 21:42:04
Following chat discussion: we'll keep it like this
| |
162 schema['schema'], description)) | |
163 | |
164 if namespace: | |
165 f.write('\n') | |
166 f.write('} // namespace %s\n' % namespace) | |
167 | |
168 def _Load(filename): | |
169 """Loads a JSON file int a Python object and return this object. | |
170 """ | |
171 # TODO(beaudoin): When moving to Python 2.7 use object_pairs_hook=OrderedDict. | |
172 with open(filename, 'r') as handle: | |
173 result = json.loads(json_comment_eater.Nom(handle.read())) | |
174 return result | |
175 | |
176 if __name__ == '__main__': | |
177 parser = optparse.OptionParser( | |
178 description='Generates an C++ array of struct from a JSON description.', | |
179 usage='usage: %prog [option] -s schema description') | |
180 parser.add_option('-d', '--destdir', | |
181 help='root directory to output generated files.') | |
182 parser.add_option('-n', '--namespace', | |
183 help='C++ namespace for generated files. e.g search_providers.') | |
184 parser.add_option('-s', '--schema', help='path to the schema file, ' | |
185 'mandatory.') | |
186 (opts, args) = parser.parse_args() | |
187 | |
188 if not opts.schema: | |
189 parser.error('You must specify a --schema.') | |
190 | |
191 description_filename = os.path.normpath(args[0]) | |
192 root, ext = os.path.splitext(description_filename) | |
193 shortroot = os.path.split(root)[1] | |
194 if opts.destdir: | |
195 output_root = os.path.join(os.path.normpath(opts.destdir), shortroot) | |
196 else: | |
197 output_root = shortroot | |
198 | |
199 schema = _Load(opts.schema) | |
200 description = _Load(description_filename) | |
201 | |
202 head = HEAD % (datetime.now().year, opts.schema, description_filename) | |
203 _GenerateH(output_root, head, opts.namespace, schema, description) | |
204 _GenerateCC(output_root, head, opts.namespace, schema, description) | |
OLD | NEW |