Merge remote-tracking branch 'remotes/kevin/tags/for-upstream' into staging
[qemu/ar7.git] / scripts / qapi-types.py
blobd2f815bca22f52d1ce6f4382328adb2f2a0b4877
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=name)
63 def generate_struct_fields(members):
64 ret = ''
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))
82 return ret
84 def generate_struct(expr):
86 structname = expr.get('type', "")
87 fieldname = expr.get('field', "")
88 members = expr['data']
89 base = expr.get('base')
91 ret = mcgen('''
92 struct %(name)s
94 ''',
95 name=structname)
97 if base:
98 ret += generate_struct_fields({'base': base})
100 ret += generate_struct_fields(members)
102 if len(fieldname):
103 fieldname = " " + fieldname
104 ret += mcgen('''
105 }%(field)s;
106 ''',
107 field=fieldname)
109 return ret
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)
123 ret += mcgen('''
124 NULL,
127 ''')
128 return ret
130 def generate_enum(name, values):
131 lookup_decl = mcgen('''
132 extern const char *%(name)s_lookup[];
133 ''',
134 name=name)
136 enum_decl = mcgen('''
137 typedef enum %(name)s
139 ''',
140 name=name)
142 # append automatically generated _MAX value
143 enum_values = values + [ 'MAX' ]
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
155 enum_decl += mcgen('''
156 } %(name)s;
157 ''',
158 name=name)
160 return lookup_decl + enum_decl
162 def generate_anon_union_qtypes(expr):
164 name = expr['union']
165 members = expr['data']
167 ret = mcgen('''
168 const int %(name)s_qtypes[QTYPE_MAX] = {
169 ''',
170 name=name)
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 elif find_enum(qapi_type):
181 qtype = "QTYPE_QSTRING"
182 else:
183 assert False, "Invalid anonymous union member"
185 ret += mcgen('''
186 [ %(qtype)s ] = %(abbrev)s_KIND_%(enum)s,
187 ''',
188 qtype = qtype,
189 abbrev = de_camel_case(name).upper(),
190 enum = c_fun(de_camel_case(key),False).upper())
192 ret += mcgen('''
194 ''')
195 return ret
198 def generate_union(expr):
200 name = expr['union']
201 typeinfo = expr['data']
203 base = expr.get('base')
204 discriminator = expr.get('discriminator')
206 enum_define = discriminator_find_enum_define(expr)
207 if enum_define:
208 discriminator_type_name = enum_define['enum_name']
209 else:
210 discriminator_type_name = '%sKind' % (name)
212 ret = mcgen('''
213 struct %(name)s
215 %(discriminator_type_name)s kind;
216 union {
217 void *data;
218 ''',
219 name=name,
220 discriminator_type_name=discriminator_type_name)
222 for key in typeinfo:
223 ret += mcgen('''
224 %(c_type)s %(c_name)s;
225 ''',
226 c_type=c_type(typeinfo[key]),
227 c_name=c_fun(key))
229 ret += mcgen('''
231 ''')
233 if base:
234 base_fields = find_struct(base)['data']
235 if discriminator:
236 base_fields = base_fields.copy()
237 del base_fields[discriminator]
238 ret += generate_struct_fields(base_fields)
239 else:
240 assert not discriminator
242 ret += mcgen('''
244 ''')
245 if discriminator == {}:
246 ret += mcgen('''
247 extern const int %(name)s_qtypes[];
248 ''',
249 name=name)
252 return ret
254 def generate_type_cleanup_decl(name):
255 ret = mcgen('''
256 void qapi_free_%(type)s(%(c_type)s obj);
257 ''',
258 c_type=c_type(name),type=name)
259 return ret
261 def generate_type_cleanup(name):
262 ret = mcgen('''
264 void qapi_free_%(type)s(%(c_type)s obj)
266 QapiDeallocVisitor *md;
267 Visitor *v;
269 if (!obj) {
270 return;
273 md = qapi_dealloc_visitor_new();
274 v = qapi_dealloc_get_visitor(md);
275 visit_type_%(type)s(v, &obj, NULL, NULL);
276 qapi_dealloc_visitor_cleanup(md);
278 ''',
279 c_type=c_type(name),type=name)
280 return ret
283 try:
284 opts, args = getopt.gnu_getopt(sys.argv[1:], "chbp:i:o:",
285 ["source", "header", "builtins",
286 "prefix=", "input-file=", "output-dir="])
287 except getopt.GetoptError, err:
288 print str(err)
289 sys.exit(1)
291 output_dir = ""
292 input_file = ""
293 prefix = ""
294 c_file = 'qapi-types.c'
295 h_file = 'qapi-types.h'
297 do_c = False
298 do_h = False
299 do_builtins = False
301 for o, a in opts:
302 if o in ("-p", "--prefix"):
303 prefix = a
304 elif o in ("-i", "--input-file"):
305 input_file = a
306 elif o in ("-o", "--output-dir"):
307 output_dir = a + "/"
308 elif o in ("-c", "--source"):
309 do_c = True
310 elif o in ("-h", "--header"):
311 do_h = True
312 elif o in ("-b", "--builtins"):
313 do_builtins = True
315 if not do_c and not do_h:
316 do_c = True
317 do_h = True
319 c_file = output_dir + prefix + c_file
320 h_file = output_dir + prefix + h_file
322 try:
323 os.makedirs(output_dir)
324 except os.error, e:
325 if e.errno != errno.EEXIST:
326 raise
328 def maybe_open(really, name, opt):
329 if really:
330 return open(name, opt)
331 else:
332 import StringIO
333 return StringIO.StringIO()
335 fdef = maybe_open(do_c, c_file, 'w')
336 fdecl = maybe_open(do_h, h_file, 'w')
338 fdef.write(mcgen('''
339 /* AUTOMATICALLY GENERATED, DO NOT MODIFY */
342 * deallocation functions for schema-defined QAPI types
344 * Copyright IBM, Corp. 2011
346 * Authors:
347 * Anthony Liguori <aliguori@us.ibm.com>
348 * Michael Roth <mdroth@linux.vnet.ibm.com>
350 * This work is licensed under the terms of the GNU LGPL, version 2.1 or later.
351 * See the COPYING.LIB file in the top-level directory.
355 #include "qapi/dealloc-visitor.h"
356 #include "%(prefix)sqapi-types.h"
357 #include "%(prefix)sqapi-visit.h"
359 ''', prefix=prefix))
361 fdecl.write(mcgen('''
362 /* AUTOMATICALLY GENERATED, DO NOT MODIFY */
365 * schema-defined QAPI types
367 * Copyright IBM, Corp. 2011
369 * Authors:
370 * Anthony Liguori <aliguori@us.ibm.com>
372 * This work is licensed under the terms of the GNU LGPL, version 2.1 or later.
373 * See the COPYING.LIB file in the top-level directory.
377 #ifndef %(guard)s
378 #define %(guard)s
380 #include <stdbool.h>
381 #include <stdint.h>
383 ''',
384 guard=guardname(h_file)))
386 exprs = parse_schema(input_file)
387 exprs = filter(lambda expr: not expr.has_key('gen'), exprs)
389 fdecl.write(guardstart("QAPI_TYPES_BUILTIN_STRUCT_DECL"))
390 for typename in builtin_types:
391 fdecl.write(generate_fwd_struct(typename, None, builtin_type=True))
392 fdecl.write(guardend("QAPI_TYPES_BUILTIN_STRUCT_DECL"))
394 for expr in exprs:
395 ret = "\n"
396 if expr.has_key('type'):
397 ret += generate_fwd_struct(expr['type'], expr['data'])
398 elif expr.has_key('enum'):
399 ret += generate_enum(expr['enum'], expr['data']) + "\n"
400 ret += generate_fwd_enum_struct(expr['enum'], expr['data'])
401 fdef.write(generate_enum_lookup(expr['enum'], expr['data']))
402 elif expr.has_key('union'):
403 ret += generate_fwd_struct(expr['union'], expr['data']) + "\n"
404 enum_define = discriminator_find_enum_define(expr)
405 if not enum_define:
406 ret += generate_enum('%sKind' % expr['union'], expr['data'].keys())
407 fdef.write(generate_enum_lookup('%sKind' % expr['union'],
408 expr['data'].keys()))
409 if expr.get('discriminator') == {}:
410 fdef.write(generate_anon_union_qtypes(expr))
411 else:
412 continue
413 fdecl.write(ret)
415 # to avoid header dependency hell, we always generate declarations
416 # for built-in types in our header files and simply guard them
417 fdecl.write(guardstart("QAPI_TYPES_BUILTIN_CLEANUP_DECL"))
418 for typename in builtin_types:
419 fdecl.write(generate_type_cleanup_decl(typename + "List"))
420 fdecl.write(guardend("QAPI_TYPES_BUILTIN_CLEANUP_DECL"))
422 # ...this doesn't work for cases where we link in multiple objects that
423 # have the functions defined, so we use -b option to provide control
424 # over these cases
425 if do_builtins:
426 fdef.write(guardstart("QAPI_TYPES_BUILTIN_CLEANUP_DEF"))
427 for typename in builtin_types:
428 fdef.write(generate_type_cleanup(typename + "List"))
429 fdef.write(guardend("QAPI_TYPES_BUILTIN_CLEANUP_DEF"))
431 for expr in exprs:
432 ret = "\n"
433 if expr.has_key('type'):
434 ret += generate_struct(expr) + "\n"
435 ret += generate_type_cleanup_decl(expr['type'] + "List")
436 fdef.write(generate_type_cleanup(expr['type'] + "List") + "\n")
437 ret += generate_type_cleanup_decl(expr['type'])
438 fdef.write(generate_type_cleanup(expr['type']) + "\n")
439 elif expr.has_key('union'):
440 ret += generate_union(expr)
441 ret += generate_type_cleanup_decl(expr['union'] + "List")
442 fdef.write(generate_type_cleanup(expr['union'] + "List") + "\n")
443 ret += generate_type_cleanup_decl(expr['union'])
444 fdef.write(generate_type_cleanup(expr['union']) + "\n")
445 elif expr.has_key('enum'):
446 ret += generate_type_cleanup_decl(expr['enum'] + "List")
447 fdef.write(generate_type_cleanup(expr['enum'] + "List") + "\n")
448 else:
449 continue
450 fdecl.write(ret)
452 fdecl.write('''
453 #endif
454 ''')
456 fdecl.flush()
457 fdecl.close()
459 fdef.flush()
460 fdef.close()