make-release: Record SeaBIOS version
[qemu.git] / scripts / qapi-visit.py
1 #
2 # QAPI visitor generator
3 #
4 # Copyright IBM, Corp. 2011
5 #
6 # Authors:
7 # Anthony Liguori <aliguori@us.ibm.com>
8 # Michael Roth <mdroth@linux.vnet.ibm.com>
9 #
10 # This work is licensed under the terms of the GNU GPL, version 2.
11 # See the COPYING file in the top-level directory.
12
13 from ordereddict import OrderedDict
14 from qapi import *
15 import sys
16 import os
17 import getopt
18 import errno
19
20 def generate_visit_struct_fields(name, field_prefix, fn_prefix, members, base = None):
21 substructs = []
22 ret = ''
23 if not fn_prefix:
24 full_name = name
25 else:
26 full_name = "%s_%s" % (name, fn_prefix)
27
28 for argname, argentry, optional, structured in parse_args(members):
29 if structured:
30 if not fn_prefix:
31 nested_fn_prefix = argname
32 else:
33 nested_fn_prefix = "%s_%s" % (fn_prefix, argname)
34
35 nested_field_prefix = "%s%s." % (field_prefix, argname)
36 ret += generate_visit_struct_fields(name, nested_field_prefix,
37 nested_fn_prefix, argentry)
38
39 ret += mcgen('''
40
41 static void visit_type_%(full_name)s_fields(Visitor *m, %(name)s ** obj, Error **errp)
42 {
43 Error *err = NULL;
44 ''',
45 name=name, full_name=full_name)
46 push_indent()
47
48 if base:
49 ret += mcgen('''
50 visit_start_implicit_struct(m, (void**) &(*obj)->%(c_name)s, sizeof(%(type)s), &err);
51 if (!err) {
52 visit_type_%(type)s_fields(m, &(*obj)->%(c_prefix)s%(c_name)s, &err);
53 error_propagate(errp, err);
54 err = NULL;
55 visit_end_implicit_struct(m, &err);
56 }
57 ''',
58 c_prefix=c_var(field_prefix),
59 type=type_name(base), c_name=c_var('base'))
60
61 for argname, argentry, optional, structured in parse_args(members):
62 if optional:
63 ret += mcgen('''
64 visit_start_optional(m, &(*obj)->%(c_prefix)shas_%(c_name)s, "%(name)s", &err);
65 if ((*obj)->%(prefix)shas_%(c_name)s) {
66 ''',
67 c_prefix=c_var(field_prefix), prefix=field_prefix,
68 c_name=c_var(argname), name=argname)
69 push_indent()
70
71 if structured:
72 ret += generate_visit_struct_body(full_name, argname, argentry)
73 else:
74 ret += mcgen('''
75 visit_type_%(type)s(m, &(*obj)->%(c_prefix)s%(c_name)s, "%(name)s", &err);
76 ''',
77 c_prefix=c_var(field_prefix), prefix=field_prefix,
78 type=type_name(argentry), c_name=c_var(argname),
79 name=argname)
80
81 if optional:
82 pop_indent()
83 ret += mcgen('''
84 }
85 visit_end_optional(m, &err);
86 ''')
87
88 pop_indent()
89 ret += mcgen('''
90
91 error_propagate(errp, err);
92 }
93 ''')
94 return ret
95
96
97 def generate_visit_struct_body(field_prefix, name, members):
98 ret = mcgen('''
99 if (!error_is_set(errp)) {
100 ''')
101 push_indent()
102
103 if not field_prefix:
104 full_name = name
105 else:
106 full_name = "%s_%s" % (field_prefix, name)
107
108 if len(field_prefix):
109 ret += mcgen('''
110 Error **errp = &err; /* from outer scope */
111 Error *err = NULL;
112 visit_start_struct(m, NULL, "", "%(name)s", 0, &err);
113 ''',
114 name=name)
115 else:
116 ret += mcgen('''
117 Error *err = NULL;
118 visit_start_struct(m, (void **)obj, "%(name)s", name, sizeof(%(name)s), &err);
119 ''',
120 name=name)
121
122 ret += mcgen('''
123 if (!err) {
124 if (*obj) {
125 visit_type_%(name)s_fields(m, obj, &err);
126 error_propagate(errp, err);
127 err = NULL;
128 }
129 ''',
130 name=full_name)
131
132 pop_indent()
133 ret += mcgen('''
134 /* Always call end_struct if start_struct succeeded. */
135 visit_end_struct(m, &err);
136 }
137 error_propagate(errp, err);
138 }
139 ''')
140 return ret
141
142 def generate_visit_struct(expr):
143
144 name = expr['type']
145 members = expr['data']
146 base = expr.get('base')
147
148 ret = generate_visit_struct_fields(name, "", "", members, base)
149
150 ret += mcgen('''
151
152 void visit_type_%(name)s(Visitor *m, %(name)s ** obj, const char *name, Error **errp)
153 {
154 ''',
155 name=name)
156
157 push_indent()
158 ret += generate_visit_struct_body("", name, members)
159 pop_indent()
160
161 ret += mcgen('''
162 }
163 ''')
164 return ret
165
166 def generate_visit_list(name, members):
167 return mcgen('''
168
169 void visit_type_%(name)sList(Visitor *m, %(name)sList ** obj, const char *name, Error **errp)
170 {
171 GenericList *i, **prev = (GenericList **)obj;
172 Error *err = NULL;
173
174 if (!error_is_set(errp)) {
175 visit_start_list(m, name, &err);
176 if (!err) {
177 for (; (i = visit_next_list(m, prev, &err)) != NULL; prev = &i) {
178 %(name)sList *native_i = (%(name)sList *)i;
179 visit_type_%(name)s(m, &native_i->value, NULL, &err);
180 }
181 error_propagate(errp, err);
182 err = NULL;
183
184 /* Always call end_list if start_list succeeded. */
185 visit_end_list(m, &err);
186 }
187 error_propagate(errp, err);
188 }
189 }
190 ''',
191 name=name)
192
193 def generate_visit_enum(name, members):
194 return mcgen('''
195
196 void visit_type_%(name)s(Visitor *m, %(name)s * obj, const char *name, Error **errp)
197 {
198 visit_type_enum(m, (int *)obj, %(name)s_lookup, "%(name)s", name, errp);
199 }
200 ''',
201 name=name)
202
203 def generate_visit_anon_union(name, members):
204 ret = mcgen('''
205
206 void visit_type_%(name)s(Visitor *m, %(name)s ** obj, const char *name, Error **errp)
207 {
208 Error *err = NULL;
209
210 if (!error_is_set(errp)) {
211 visit_start_implicit_struct(m, (void**) obj, sizeof(%(name)s), &err);
212 visit_get_next_type(m, (int*) &(*obj)->kind, %(name)s_qtypes, name, &err);
213 switch ((*obj)->kind) {
214 ''',
215 name=name)
216
217 # For anon union, always use the default enum type automatically generated
218 # as "'%sKind' % (name)"
219 disc_type = '%sKind' % (name)
220
221 for key in members:
222 assert (members[key] in builtin_types
223 or find_struct(members[key])
224 or find_union(members[key])), "Invalid anonymous union member"
225
226 enum_full_value = generate_enum_full_value(disc_type, key)
227 ret += mcgen('''
228 case %(enum_full_value)s:
229 visit_type_%(c_type)s(m, &(*obj)->%(c_name)s, name, &err);
230 break;
231 ''',
232 enum_full_value = enum_full_value,
233 c_type = type_name(members[key]),
234 c_name = c_fun(key))
235
236 ret += mcgen('''
237 default:
238 abort();
239 }
240 error_propagate(errp, err);
241 err = NULL;
242 visit_end_implicit_struct(m, &err);
243 }
244 }
245 ''')
246
247 return ret
248
249
250 def generate_visit_union(expr):
251
252 name = expr['union']
253 members = expr['data']
254
255 base = expr.get('base')
256 discriminator = expr.get('discriminator')
257
258 if discriminator == {}:
259 assert not base
260 return generate_visit_anon_union(name, members)
261
262 enum_define = discriminator_find_enum_define(expr)
263 if enum_define:
264 # Use the enum type as discriminator
265 ret = ""
266 disc_type = enum_define['enum_name']
267 else:
268 # There will always be a discriminator in the C switch code, by default it
269 # is an enum type generated silently as "'%sKind' % (name)"
270 ret = generate_visit_enum('%sKind' % name, members.keys())
271 disc_type = '%sKind' % (name)
272
273 if base:
274 base_fields = find_struct(base)['data']
275 if discriminator:
276 base_fields = base_fields.copy()
277 del base_fields[discriminator]
278 ret += generate_visit_struct_fields(name, "", "", base_fields)
279
280 ret += mcgen('''
281
282 void visit_type_%(name)s(Visitor *m, %(name)s ** obj, const char *name, Error **errp)
283 {
284 Error *err = NULL;
285
286 if (!error_is_set(errp)) {
287 visit_start_struct(m, (void **)obj, "%(name)s", name, sizeof(%(name)s), &err);
288 if (!err) {
289 if (*obj) {
290 ''',
291 name=name)
292
293
294 push_indent()
295 push_indent()
296 push_indent()
297
298 if base:
299 ret += mcgen('''
300 visit_type_%(name)s_fields(m, obj, &err);
301 ''',
302 name=name)
303
304 pop_indent()
305
306 if not discriminator:
307 disc_key = "type"
308 else:
309 disc_key = discriminator
310 ret += mcgen('''
311 visit_type_%(disc_type)s(m, &(*obj)->kind, "%(disc_key)s", &err);
312 if (!err) {
313 switch ((*obj)->kind) {
314 ''',
315 disc_type = disc_type,
316 disc_key = disc_key)
317
318 for key in members:
319 if not discriminator:
320 fmt = 'visit_type_%(c_type)s(m, &(*obj)->%(c_name)s, "data", &err);'
321 else:
322 fmt = '''visit_start_implicit_struct(m, (void**) &(*obj)->%(c_name)s, sizeof(%(c_type)s), &err);
323 if (!err) {
324 visit_type_%(c_type)s_fields(m, &(*obj)->%(c_name)s, &err);
325 error_propagate(errp, err);
326 err = NULL;
327 visit_end_implicit_struct(m, &err);
328 }'''
329
330 enum_full_value = generate_enum_full_value(disc_type, key)
331 ret += mcgen('''
332 case %(enum_full_value)s:
333 ''' + fmt + '''
334 break;
335 ''',
336 enum_full_value = enum_full_value,
337 c_type=type_name(members[key]),
338 c_name=c_fun(key))
339
340 ret += mcgen('''
341 default:
342 abort();
343 }
344 }
345 error_propagate(errp, err);
346 err = NULL;
347 }
348 ''')
349 pop_indent()
350 ret += mcgen('''
351 /* Always call end_struct if start_struct succeeded. */
352 visit_end_struct(m, &err);
353 }
354 error_propagate(errp, err);
355 }
356 ''')
357
358 pop_indent();
359 ret += mcgen('''
360 }
361 ''')
362
363 return ret
364
365 def generate_declaration(name, members, genlist=True, builtin_type=False):
366 ret = ""
367 if not builtin_type:
368 ret += mcgen('''
369
370 void visit_type_%(name)s(Visitor *m, %(name)s ** obj, const char *name, Error **errp);
371 ''',
372 name=name)
373
374 if genlist:
375 ret += mcgen('''
376 void visit_type_%(name)sList(Visitor *m, %(name)sList ** obj, const char *name, Error **errp);
377 ''',
378 name=name)
379
380 return ret
381
382 def generate_enum_declaration(name, members, genlist=True):
383 ret = ""
384 if genlist:
385 ret += mcgen('''
386 void visit_type_%(name)sList(Visitor *m, %(name)sList ** obj, const char *name, Error **errp);
387 ''',
388 name=name)
389
390 return ret
391
392 def generate_decl_enum(name, members, genlist=True):
393 return mcgen('''
394
395 void visit_type_%(name)s(Visitor *m, %(name)s * obj, const char *name, Error **errp);
396 ''',
397 name=name)
398
399 try:
400 opts, args = getopt.gnu_getopt(sys.argv[1:], "chbp:o:",
401 ["source", "header", "builtins", "prefix=",
402 "output-dir="])
403 except getopt.GetoptError, err:
404 print str(err)
405 sys.exit(1)
406
407 output_dir = ""
408 prefix = ""
409 c_file = 'qapi-visit.c'
410 h_file = 'qapi-visit.h'
411
412 do_c = False
413 do_h = False
414 do_builtins = False
415
416 for o, a in opts:
417 if o in ("-p", "--prefix"):
418 prefix = a
419 elif o in ("-o", "--output-dir"):
420 output_dir = a + "/"
421 elif o in ("-c", "--source"):
422 do_c = True
423 elif o in ("-h", "--header"):
424 do_h = True
425 elif o in ("-b", "--builtins"):
426 do_builtins = True
427
428 if not do_c and not do_h:
429 do_c = True
430 do_h = True
431
432 c_file = output_dir + prefix + c_file
433 h_file = output_dir + prefix + h_file
434
435 try:
436 os.makedirs(output_dir)
437 except os.error, e:
438 if e.errno != errno.EEXIST:
439 raise
440
441 def maybe_open(really, name, opt):
442 if really:
443 return open(name, opt)
444 else:
445 import StringIO
446 return StringIO.StringIO()
447
448 fdef = maybe_open(do_c, c_file, 'w')
449 fdecl = maybe_open(do_h, h_file, 'w')
450
451 fdef.write(mcgen('''
452 /* THIS FILE IS AUTOMATICALLY GENERATED, DO NOT MODIFY */
453
454 /*
455 * schema-defined QAPI visitor functions
456 *
457 * Copyright IBM, Corp. 2011
458 *
459 * Authors:
460 * Anthony Liguori <aliguori@us.ibm.com>
461 *
462 * This work is licensed under the terms of the GNU LGPL, version 2.1 or later.
463 * See the COPYING.LIB file in the top-level directory.
464 *
465 */
466
467 #include "qemu-common.h"
468 #include "%(header)s"
469 ''',
470 header=basename(h_file)))
471
472 fdecl.write(mcgen('''
473 /* THIS FILE IS AUTOMATICALLY GENERATED, DO NOT MODIFY */
474
475 /*
476 * schema-defined QAPI visitor function
477 *
478 * Copyright IBM, Corp. 2011
479 *
480 * Authors:
481 * Anthony Liguori <aliguori@us.ibm.com>
482 *
483 * This work is licensed under the terms of the GNU LGPL, version 2.1 or later.
484 * See the COPYING.LIB file in the top-level directory.
485 *
486 */
487
488 #ifndef %(guard)s
489 #define %(guard)s
490
491 #include "qapi/visitor.h"
492 #include "%(prefix)sqapi-types.h"
493
494 ''',
495 prefix=prefix, guard=guardname(h_file)))
496
497 exprs = parse_schema(sys.stdin)
498
499 # to avoid header dependency hell, we always generate declarations
500 # for built-in types in our header files and simply guard them
501 fdecl.write(guardstart("QAPI_VISIT_BUILTIN_VISITOR_DECL"))
502 for typename in builtin_types:
503 fdecl.write(generate_declaration(typename, None, genlist=True,
504 builtin_type=True))
505 fdecl.write(guardend("QAPI_VISIT_BUILTIN_VISITOR_DECL"))
506
507 # ...this doesn't work for cases where we link in multiple objects that
508 # have the functions defined, so we use -b option to provide control
509 # over these cases
510 if do_builtins:
511 for typename in builtin_types:
512 fdef.write(generate_visit_list(typename, None))
513
514 for expr in exprs:
515 if expr.has_key('type'):
516 ret = generate_visit_struct(expr)
517 ret += generate_visit_list(expr['type'], expr['data'])
518 fdef.write(ret)
519
520 ret = generate_declaration(expr['type'], expr['data'])
521 fdecl.write(ret)
522 elif expr.has_key('union'):
523 ret = generate_visit_union(expr)
524 ret += generate_visit_list(expr['union'], expr['data'])
525 fdef.write(ret)
526
527 enum_define = discriminator_find_enum_define(expr)
528 ret = ""
529 if not enum_define:
530 ret = generate_decl_enum('%sKind' % expr['union'],
531 expr['data'].keys())
532 ret += generate_declaration(expr['union'], expr['data'])
533 fdecl.write(ret)
534 elif expr.has_key('enum'):
535 ret = generate_visit_list(expr['enum'], expr['data'])
536 ret += generate_visit_enum(expr['enum'], expr['data'])
537 fdef.write(ret)
538
539 ret = generate_decl_enum(expr['enum'], expr['data'])
540 ret += generate_enum_declaration(expr['enum'], expr['data'])
541 fdecl.write(ret)
542
543 fdecl.write('''
544 #endif
545 ''')
546
547 fdecl.flush()
548 fdecl.close()
549
550 fdef.flush()
551 fdef.close()