Merge remote-tracking branch 'remotes/kevin/tags/for-upstream' into staging
[qemu.git] / scripts / qapi-types.py
1 #
2 # QAPI types generator
3 #
4 # Copyright IBM, Corp. 2011
5 #
6 # Authors:
7 # Anthony Liguori <aliguori@us.ibm.com>
8 #
9 # This work is licensed under the terms of the GNU GPL, version 2.
10 # See the COPYING file in the top-level directory.
11
12 from ordereddict import OrderedDict
13 from qapi import *
14 import sys
15 import os
16 import getopt
17 import errno
18
19 def generate_fwd_struct(name, members, builtin_type=False):
20 if builtin_type:
21 return mcgen('''
22
23 typedef struct %(name)sList
24 {
25 union {
26 %(type)s value;
27 uint64_t padding;
28 };
29 struct %(name)sList *next;
30 } %(name)sList;
31 ''',
32 type=c_type(name),
33 name=name)
34
35 return mcgen('''
36
37 typedef struct %(name)s %(name)s;
38
39 typedef struct %(name)sList
40 {
41 union {
42 %(name)s *value;
43 uint64_t padding;
44 };
45 struct %(name)sList *next;
46 } %(name)sList;
47 ''',
48 name=name)
49
50 def generate_fwd_enum_struct(name, members):
51 return mcgen('''
52 typedef struct %(name)sList
53 {
54 union {
55 %(name)s value;
56 uint64_t padding;
57 };
58 struct %(name)sList *next;
59 } %(name)sList;
60 ''',
61 name=name)
62
63 def generate_struct_fields(members):
64 ret = ''
65
66 for argname, argentry, optional, structured in parse_args(members):
67 if optional:
68 ret += mcgen('''
69 bool has_%(c_name)s;
70 ''',
71 c_name=c_var(argname))
72 if structured:
73 push_indent()
74 ret += generate_struct({ "field": argname, "data": argentry})
75 pop_indent()
76 else:
77 ret += mcgen('''
78 %(c_type)s %(c_name)s;
79 ''',
80 c_type=c_type(argentry), c_name=c_var(argname))
81
82 return ret
83
84 def generate_struct(expr):
85
86 structname = expr.get('type', "")
87 fieldname = expr.get('field', "")
88 members = expr['data']
89 base = expr.get('base')
90
91 ret = mcgen('''
92 struct %(name)s
93 {
94 ''',
95 name=structname)
96
97 if base:
98 ret += generate_struct_fields({'base': base})
99
100 ret += generate_struct_fields(members)
101
102 if len(fieldname):
103 fieldname = " " + fieldname
104 ret += mcgen('''
105 }%(field)s;
106 ''',
107 field=fieldname)
108
109 return ret
110
111 def generate_enum_lookup(name, values):
112 ret = mcgen('''
113 const char *%(name)s_lookup[] = {
114 ''',
115 name=name)
116 i = 0
117 for value in values:
118 ret += mcgen('''
119 "%(value)s",
120 ''',
121 value=value)
122
123 ret += mcgen('''
124 NULL,
125 };
126
127 ''')
128 return ret
129
130 def generate_enum(name, values):
131 lookup_decl = mcgen('''
132 extern const char *%(name)s_lookup[];
133 ''',
134 name=name)
135
136 enum_decl = mcgen('''
137 typedef enum %(name)s
138 {
139 ''',
140 name=name)
141
142 # append automatically generated _MAX value
143 enum_values = values + [ 'MAX' ]
144
145 i = 0
146 for value in enum_values:
147 enum_full_value = generate_enum_full_value(name, value)
148 enum_decl += mcgen('''
149 %(enum_full_value)s = %(i)d,
150 ''',
151 enum_full_value = enum_full_value,
152 i=i)
153 i += 1
154
155 enum_decl += mcgen('''
156 } %(name)s;
157 ''',
158 name=name)
159
160 return lookup_decl + enum_decl
161
162 def generate_anon_union_qtypes(expr):
163
164 name = expr['union']
165 members = expr['data']
166
167 ret = mcgen('''
168 const int %(name)s_qtypes[QTYPE_MAX] = {
169 ''',
170 name=name)
171
172 for key in members:
173 qapi_type = members[key]
174 if builtin_type_qtypes.has_key(qapi_type):
175 qtype = builtin_type_qtypes[qapi_type]
176 elif find_struct(qapi_type):
177 qtype = "QTYPE_QDICT"
178 elif find_union(qapi_type):
179 qtype = "QTYPE_QDICT"
180 else:
181 assert False, "Invalid anonymous union member"
182
183 ret += mcgen('''
184 [ %(qtype)s ] = %(abbrev)s_KIND_%(enum)s,
185 ''',
186 qtype = qtype,
187 abbrev = de_camel_case(name).upper(),
188 enum = c_fun(de_camel_case(key),False).upper())
189
190 ret += mcgen('''
191 };
192 ''')
193 return ret
194
195
196 def generate_union(expr):
197
198 name = expr['union']
199 typeinfo = expr['data']
200
201 base = expr.get('base')
202 discriminator = expr.get('discriminator')
203
204 enum_define = discriminator_find_enum_define(expr)
205 if enum_define:
206 discriminator_type_name = enum_define['enum_name']
207 else:
208 discriminator_type_name = '%sKind' % (name)
209
210 ret = mcgen('''
211 struct %(name)s
212 {
213 %(discriminator_type_name)s kind;
214 union {
215 void *data;
216 ''',
217 name=name,
218 discriminator_type_name=discriminator_type_name)
219
220 for key in typeinfo:
221 ret += mcgen('''
222 %(c_type)s %(c_name)s;
223 ''',
224 c_type=c_type(typeinfo[key]),
225 c_name=c_fun(key))
226
227 ret += mcgen('''
228 };
229 ''')
230
231 if base:
232 base_fields = find_struct(base)['data']
233 if discriminator:
234 base_fields = base_fields.copy()
235 del base_fields[discriminator]
236 ret += generate_struct_fields(base_fields)
237 else:
238 assert not discriminator
239
240 ret += mcgen('''
241 };
242 ''')
243 if discriminator == {}:
244 ret += mcgen('''
245 extern const int %(name)s_qtypes[];
246 ''',
247 name=name)
248
249
250 return ret
251
252 def generate_type_cleanup_decl(name):
253 ret = mcgen('''
254 void qapi_free_%(type)s(%(c_type)s obj);
255 ''',
256 c_type=c_type(name),type=name)
257 return ret
258
259 def generate_type_cleanup(name):
260 ret = mcgen('''
261
262 void qapi_free_%(type)s(%(c_type)s obj)
263 {
264 QapiDeallocVisitor *md;
265 Visitor *v;
266
267 if (!obj) {
268 return;
269 }
270
271 md = qapi_dealloc_visitor_new();
272 v = qapi_dealloc_get_visitor(md);
273 visit_type_%(type)s(v, &obj, NULL, NULL);
274 qapi_dealloc_visitor_cleanup(md);
275 }
276 ''',
277 c_type=c_type(name),type=name)
278 return ret
279
280
281 try:
282 opts, args = getopt.gnu_getopt(sys.argv[1:], "chbp:o:",
283 ["source", "header", "builtins",
284 "prefix=", "output-dir="])
285 except getopt.GetoptError, err:
286 print str(err)
287 sys.exit(1)
288
289 output_dir = ""
290 prefix = ""
291 c_file = 'qapi-types.c'
292 h_file = 'qapi-types.h'
293
294 do_c = False
295 do_h = False
296 do_builtins = False
297
298 for o, a in opts:
299 if o in ("-p", "--prefix"):
300 prefix = a
301 elif o in ("-o", "--output-dir"):
302 output_dir = a + "/"
303 elif o in ("-c", "--source"):
304 do_c = True
305 elif o in ("-h", "--header"):
306 do_h = True
307 elif o in ("-b", "--builtins"):
308 do_builtins = True
309
310 if not do_c and not do_h:
311 do_c = True
312 do_h = True
313
314 c_file = output_dir + prefix + c_file
315 h_file = output_dir + prefix + h_file
316
317 try:
318 os.makedirs(output_dir)
319 except os.error, e:
320 if e.errno != errno.EEXIST:
321 raise
322
323 def maybe_open(really, name, opt):
324 if really:
325 return open(name, opt)
326 else:
327 import StringIO
328 return StringIO.StringIO()
329
330 fdef = maybe_open(do_c, c_file, 'w')
331 fdecl = maybe_open(do_h, h_file, 'w')
332
333 fdef.write(mcgen('''
334 /* AUTOMATICALLY GENERATED, DO NOT MODIFY */
335
336 /*
337 * deallocation functions for schema-defined QAPI types
338 *
339 * Copyright IBM, Corp. 2011
340 *
341 * Authors:
342 * Anthony Liguori <aliguori@us.ibm.com>
343 * Michael Roth <mdroth@linux.vnet.ibm.com>
344 *
345 * This work is licensed under the terms of the GNU LGPL, version 2.1 or later.
346 * See the COPYING.LIB file in the top-level directory.
347 *
348 */
349
350 #include "qapi/dealloc-visitor.h"
351 #include "%(prefix)sqapi-types.h"
352 #include "%(prefix)sqapi-visit.h"
353
354 ''', prefix=prefix))
355
356 fdecl.write(mcgen('''
357 /* AUTOMATICALLY GENERATED, DO NOT MODIFY */
358
359 /*
360 * schema-defined QAPI types
361 *
362 * Copyright IBM, Corp. 2011
363 *
364 * Authors:
365 * Anthony Liguori <aliguori@us.ibm.com>
366 *
367 * This work is licensed under the terms of the GNU LGPL, version 2.1 or later.
368 * See the COPYING.LIB file in the top-level directory.
369 *
370 */
371
372 #ifndef %(guard)s
373 #define %(guard)s
374
375 #include <stdbool.h>
376 #include <stdint.h>
377
378 ''',
379 guard=guardname(h_file)))
380
381 exprs = parse_schema(sys.stdin)
382 exprs = filter(lambda expr: not expr.has_key('gen'), exprs)
383
384 fdecl.write(guardstart("QAPI_TYPES_BUILTIN_STRUCT_DECL"))
385 for typename in builtin_types:
386 fdecl.write(generate_fwd_struct(typename, None, builtin_type=True))
387 fdecl.write(guardend("QAPI_TYPES_BUILTIN_STRUCT_DECL"))
388
389 for expr in exprs:
390 ret = "\n"
391 if expr.has_key('type'):
392 ret += generate_fwd_struct(expr['type'], expr['data'])
393 elif expr.has_key('enum'):
394 ret += generate_enum(expr['enum'], expr['data']) + "\n"
395 ret += generate_fwd_enum_struct(expr['enum'], expr['data'])
396 fdef.write(generate_enum_lookup(expr['enum'], expr['data']))
397 elif expr.has_key('union'):
398 ret += generate_fwd_struct(expr['union'], expr['data']) + "\n"
399 enum_define = discriminator_find_enum_define(expr)
400 if not enum_define:
401 ret += generate_enum('%sKind' % expr['union'], expr['data'].keys())
402 fdef.write(generate_enum_lookup('%sKind' % expr['union'],
403 expr['data'].keys()))
404 if expr.get('discriminator') == {}:
405 fdef.write(generate_anon_union_qtypes(expr))
406 else:
407 continue
408 fdecl.write(ret)
409
410 # to avoid header dependency hell, we always generate declarations
411 # for built-in types in our header files and simply guard them
412 fdecl.write(guardstart("QAPI_TYPES_BUILTIN_CLEANUP_DECL"))
413 for typename in builtin_types:
414 fdecl.write(generate_type_cleanup_decl(typename + "List"))
415 fdecl.write(guardend("QAPI_TYPES_BUILTIN_CLEANUP_DECL"))
416
417 # ...this doesn't work for cases where we link in multiple objects that
418 # have the functions defined, so we use -b option to provide control
419 # over these cases
420 if do_builtins:
421 fdef.write(guardstart("QAPI_TYPES_BUILTIN_CLEANUP_DEF"))
422 for typename in builtin_types:
423 fdef.write(generate_type_cleanup(typename + "List"))
424 fdef.write(guardend("QAPI_TYPES_BUILTIN_CLEANUP_DEF"))
425
426 for expr in exprs:
427 ret = "\n"
428 if expr.has_key('type'):
429 ret += generate_struct(expr) + "\n"
430 ret += generate_type_cleanup_decl(expr['type'] + "List")
431 fdef.write(generate_type_cleanup(expr['type'] + "List") + "\n")
432 ret += generate_type_cleanup_decl(expr['type'])
433 fdef.write(generate_type_cleanup(expr['type']) + "\n")
434 elif expr.has_key('union'):
435 ret += generate_union(expr)
436 ret += generate_type_cleanup_decl(expr['union'] + "List")
437 fdef.write(generate_type_cleanup(expr['union'] + "List") + "\n")
438 ret += generate_type_cleanup_decl(expr['union'])
439 fdef.write(generate_type_cleanup(expr['union']) + "\n")
440 elif expr.has_key('enum'):
441 ret += generate_type_cleanup_decl(expr['enum'] + "List")
442 fdef.write(generate_type_cleanup(expr['enum'] + "List") + "\n")
443 else:
444 continue
445 fdecl.write(ret)
446
447 fdecl.write('''
448 #endif
449 ''')
450
451 fdecl.flush()
452 fdecl.close()
453
454 fdef.flush()
455 fdef.close()