qapi: Support downstream enums
[qemu/kevin.git] / scripts / qapi-types.py
blob1593fc65616f6b9503c1ec8d63bda25e0942accf
2 # QAPI types generator
4 # Copyright IBM, Corp. 2011
6 # Authors:
7 # Anthony Liguori <aliguori@us.ibm.com>
9 # This work is licensed under the terms of the GNU GPL, version 2.
10 # See the COPYING file in the top-level directory.
12 from ordereddict import OrderedDict
13 from qapi import *
14 import sys
15 import os
16 import getopt
17 import errno
19 def generate_fwd_struct(name, members, builtin_type=False):
20 if builtin_type:
21 return mcgen('''
23 typedef struct %(name)sList
25 union {
26 %(type)s value;
27 uint64_t padding;
29 struct %(name)sList *next;
30 } %(name)sList;
31 ''',
32 type=c_type(name),
33 name=name)
35 return mcgen('''
37 typedef struct %(name)s %(name)s;
39 typedef struct %(name)sList
41 union {
42 %(name)s *value;
43 uint64_t padding;
45 struct %(name)sList *next;
46 } %(name)sList;
47 ''',
48 name=name)
50 def generate_fwd_enum_struct(name, members):
51 return mcgen('''
52 typedef struct %(name)sList
54 union {
55 %(name)s value;
56 uint64_t padding;
58 struct %(name)sList *next;
59 } %(name)sList;
60 ''',
61 name=c_name(name))
63 def generate_struct_fields(members):
64 ret = ''
66 for argname, argentry, optional in parse_args(members):
67 if optional:
68 ret += mcgen('''
69 bool has_%(c_name)s;
70 ''',
71 c_name=c_name(argname))
72 ret += mcgen('''
73 %(c_type)s %(c_name)s;
74 ''',
75 c_type=c_type(argentry), c_name=c_name(argname))
77 return ret
79 def generate_struct(expr):
81 structname = expr.get('struct', "")
82 fieldname = expr.get('field', "")
83 members = expr['data']
84 base = expr.get('base')
86 ret = mcgen('''
87 struct %(name)s
89 ''',
90 name=structname)
92 if base:
93 ret += generate_struct_fields({'base': base})
95 ret += generate_struct_fields(members)
97 # Make sure that all structs have at least one field; this avoids
98 # potential issues with attempting to malloc space for zero-length structs
99 # in C, and also incompatibility with C++ (where an empty struct is size 1).
100 if not base and not members:
101 ret += mcgen('''
102 char qapi_dummy_field_for_empty_struct;
103 ''')
105 if len(fieldname):
106 fieldname = " " + fieldname
107 ret += mcgen('''
108 }%(field)s;
109 ''',
110 field=fieldname)
112 return ret
114 def generate_enum_lookup(name, values):
115 ret = mcgen('''
116 const char *%(name)s_lookup[] = {
117 ''',
118 name=c_name(name))
119 i = 0
120 for value in values:
121 index = c_enum_const(name, value)
122 ret += mcgen('''
123 [%(index)s] = "%(value)s",
124 ''',
125 index = index, value = value)
127 max_index = c_enum_const(name, 'MAX')
128 ret += mcgen('''
129 [%(max_index)s] = NULL,
132 ''',
133 max_index=max_index)
134 return ret
136 def generate_enum(name, values):
137 name = c_name(name)
138 lookup_decl = mcgen('''
139 extern const char *%(name)s_lookup[];
140 ''',
141 name=name)
143 enum_decl = mcgen('''
144 typedef enum %(name)s
146 ''',
147 name=name)
149 # append automatically generated _MAX value
150 enum_values = values + [ 'MAX' ]
152 i = 0
153 for value in enum_values:
154 enum_full_value = c_enum_const(name, value)
155 enum_decl += mcgen('''
156 %(enum_full_value)s = %(i)d,
157 ''',
158 enum_full_value = enum_full_value,
159 i=i)
160 i += 1
162 enum_decl += mcgen('''
163 } %(name)s;
164 ''',
165 name=name)
167 return lookup_decl + enum_decl
169 def generate_alternate_qtypes(expr):
171 name = expr['alternate']
172 members = expr['data']
174 ret = mcgen('''
175 const int %(name)s_qtypes[QTYPE_MAX] = {
176 ''',
177 name=name)
179 for key in members:
180 qtype = find_alternate_member_qtype(members[key])
181 assert qtype, "Invalid alternate member"
183 ret += mcgen('''
184 [ %(qtype)s ] = %(enum_const)s,
185 ''',
186 qtype = qtype, enum_const = c_enum_const(name + 'Kind', key))
188 ret += mcgen('''
190 ''')
191 return ret
194 def generate_union(expr, meta):
196 name = expr[meta]
197 typeinfo = expr['data']
199 base = expr.get('base')
200 discriminator = expr.get('discriminator')
202 enum_define = discriminator_find_enum_define(expr)
203 if enum_define:
204 discriminator_type_name = enum_define['enum_name']
205 else:
206 discriminator_type_name = '%sKind' % (name)
208 ret = mcgen('''
209 struct %(name)s
211 %(discriminator_type_name)s kind;
212 union {
213 void *data;
214 ''',
215 name=name,
216 discriminator_type_name=discriminator_type_name)
218 for key in typeinfo:
219 ret += mcgen('''
220 %(c_type)s %(c_name)s;
221 ''',
222 c_type=c_type(typeinfo[key]),
223 c_name=c_name(key))
225 ret += mcgen('''
227 ''')
229 if base:
230 assert discriminator
231 base_fields = find_struct(base)['data'].copy()
232 del base_fields[discriminator]
233 ret += generate_struct_fields(base_fields)
234 else:
235 assert not discriminator
237 ret += mcgen('''
239 ''')
240 if meta == 'alternate':
241 ret += mcgen('''
242 extern const int %(name)s_qtypes[];
243 ''',
244 name=name)
247 return ret
249 def generate_type_cleanup_decl(name):
250 ret = mcgen('''
251 void qapi_free_%(name)s(%(c_type)s obj);
252 ''',
253 c_type=c_type(name), name=c_name(name))
254 return ret
256 def generate_type_cleanup(name):
257 ret = mcgen('''
259 void qapi_free_%(name)s(%(c_type)s obj)
261 QapiDeallocVisitor *md;
262 Visitor *v;
264 if (!obj) {
265 return;
268 md = qapi_dealloc_visitor_new();
269 v = qapi_dealloc_get_visitor(md);
270 visit_type_%(name)s(v, &obj, NULL, NULL);
271 qapi_dealloc_visitor_cleanup(md);
273 ''',
274 c_type=c_type(name), name=c_name(name))
275 return ret
278 try:
279 opts, args = getopt.gnu_getopt(sys.argv[1:], "chbp:i:o:",
280 ["source", "header", "builtins",
281 "prefix=", "input-file=", "output-dir="])
282 except getopt.GetoptError, err:
283 print str(err)
284 sys.exit(1)
286 output_dir = ""
287 input_file = ""
288 prefix = ""
289 c_file = 'qapi-types.c'
290 h_file = 'qapi-types.h'
292 do_c = False
293 do_h = False
294 do_builtins = False
296 for o, a in opts:
297 if o in ("-p", "--prefix"):
298 prefix = a
299 elif o in ("-i", "--input-file"):
300 input_file = 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
310 if not do_c and not do_h:
311 do_c = True
312 do_h = True
314 c_file = output_dir + prefix + c_file
315 h_file = output_dir + prefix + h_file
317 try:
318 os.makedirs(output_dir)
319 except os.error, e:
320 if e.errno != errno.EEXIST:
321 raise
323 def maybe_open(really, name, opt):
324 if really:
325 return open(name, opt)
326 else:
327 import StringIO
328 return StringIO.StringIO()
330 fdef = maybe_open(do_c, c_file, 'w')
331 fdecl = maybe_open(do_h, h_file, 'w')
333 fdef.write(mcgen('''
334 /* AUTOMATICALLY GENERATED, DO NOT MODIFY */
337 * deallocation functions for schema-defined QAPI types
339 * Copyright IBM, Corp. 2011
341 * Authors:
342 * Anthony Liguori <aliguori@us.ibm.com>
343 * Michael Roth <mdroth@linux.vnet.ibm.com>
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.
350 #include "qapi/dealloc-visitor.h"
351 #include "%(prefix)sqapi-types.h"
352 #include "%(prefix)sqapi-visit.h"
354 ''', prefix=prefix))
356 fdecl.write(mcgen('''
357 /* AUTOMATICALLY GENERATED, DO NOT MODIFY */
360 * schema-defined QAPI types
362 * Copyright IBM, Corp. 2011
364 * Authors:
365 * Anthony Liguori <aliguori@us.ibm.com>
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.
372 #ifndef %(guard)s
373 #define %(guard)s
375 #include <stdbool.h>
376 #include <stdint.h>
378 ''',
379 guard=guardname(h_file)))
381 exprs = parse_schema(input_file)
382 exprs = filter(lambda expr: not expr.has_key('gen'), exprs)
384 fdecl.write(guardstart("QAPI_TYPES_BUILTIN_STRUCT_DECL"))
385 for typename in builtin_types.keys():
386 fdecl.write(generate_fwd_struct(typename, None, builtin_type=True))
387 fdecl.write(guardend("QAPI_TYPES_BUILTIN_STRUCT_DECL"))
389 for expr in exprs:
390 ret = "\n"
391 if expr.has_key('struct'):
392 ret += generate_fwd_struct(expr['struct'], 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 elif expr.has_key('alternate'):
405 ret += generate_fwd_struct(expr['alternate'], expr['data']) + "\n"
406 ret += generate_enum('%sKind' % expr['alternate'], expr['data'].keys())
407 fdef.write(generate_enum_lookup('%sKind' % expr['alternate'],
408 expr['data'].keys()))
409 fdef.write(generate_alternate_qtypes(expr))
410 else:
411 continue
412 fdecl.write(ret)
414 # to avoid header dependency hell, we always generate declarations
415 # for built-in types in our header files and simply guard them
416 fdecl.write(guardstart("QAPI_TYPES_BUILTIN_CLEANUP_DECL"))
417 for typename in builtin_types.keys():
418 fdecl.write(generate_type_cleanup_decl(typename + "List"))
419 fdecl.write(guardend("QAPI_TYPES_BUILTIN_CLEANUP_DECL"))
421 # ...this doesn't work for cases where we link in multiple objects that
422 # have the functions defined, so we use -b option to provide control
423 # over these cases
424 if do_builtins:
425 fdef.write(guardstart("QAPI_TYPES_BUILTIN_CLEANUP_DEF"))
426 for typename in builtin_types.keys():
427 fdef.write(generate_type_cleanup(typename + "List"))
428 fdef.write(guardend("QAPI_TYPES_BUILTIN_CLEANUP_DEF"))
430 for expr in exprs:
431 ret = "\n"
432 if expr.has_key('struct'):
433 ret += generate_struct(expr) + "\n"
434 ret += generate_type_cleanup_decl(expr['struct'] + "List")
435 fdef.write(generate_type_cleanup(expr['struct'] + "List") + "\n")
436 ret += generate_type_cleanup_decl(expr['struct'])
437 fdef.write(generate_type_cleanup(expr['struct']) + "\n")
438 elif expr.has_key('union'):
439 ret += generate_union(expr, 'union')
440 ret += generate_type_cleanup_decl(expr['union'] + "List")
441 fdef.write(generate_type_cleanup(expr['union'] + "List") + "\n")
442 ret += generate_type_cleanup_decl(expr['union'])
443 fdef.write(generate_type_cleanup(expr['union']) + "\n")
444 elif expr.has_key('alternate'):
445 ret += generate_union(expr, 'alternate')
446 ret += generate_type_cleanup_decl(expr['alternate'] + "List")
447 fdef.write(generate_type_cleanup(expr['alternate'] + "List") + "\n")
448 ret += generate_type_cleanup_decl(expr['alternate'])
449 fdef.write(generate_type_cleanup(expr['alternate']) + "\n")
450 elif expr.has_key('enum'):
451 ret += generate_type_cleanup_decl(expr['enum'] + "List")
452 fdef.write(generate_type_cleanup(expr['enum'] + "List") + "\n")
453 else:
454 continue
455 fdecl.write(ret)
457 fdecl.write('''
458 #endif
459 ''')
461 fdecl.flush()
462 fdecl.close()
464 fdef.flush()
465 fdef.close()