block/iscsi: speed up read for unallocated sectors
[qemu/ar7.git] / scripts / qapi-visit.py
blob45ce3a957aabb0ed6175ffb13bfd3816217d79c3
2 # QAPI visitor generator
4 # Copyright IBM, Corp. 2011
6 # Authors:
7 # Anthony Liguori <aliguori@us.ibm.com>
8 # Michael Roth <mdroth@linux.vnet.ibm.com>
10 # This work is licensed under the terms of the GNU GPL, version 2.
11 # See the COPYING file in the top-level directory.
13 from ordereddict import OrderedDict
14 from qapi import *
15 import sys
16 import os
17 import getopt
18 import errno
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)
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)
35 nested_field_prefix = "%s%s." % (field_prefix, argname)
36 ret += generate_visit_struct_fields(name, nested_field_prefix,
37 nested_fn_prefix, argentry)
39 ret += mcgen('''
41 static void visit_type_%(full_name)s_fields(Visitor *m, %(name)s ** obj, Error **errp)
43 Error *err = NULL;
44 ''',
45 name=name, full_name=full_name)
46 push_indent()
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);
57 ''',
58 c_prefix=c_var(field_prefix),
59 type=type_name(base), c_name=c_var('base'))
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()
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)
81 if optional:
82 pop_indent()
83 ret += mcgen('''
85 visit_end_optional(m, &err);
86 ''')
88 pop_indent()
89 ret += mcgen('''
91 error_propagate(errp, err);
93 ''')
94 return ret
97 def generate_visit_struct_body(field_prefix, name, members):
98 ret = mcgen('''
99 if (!error_is_set(errp)) {
100 ''')
101 push_indent()
103 if not field_prefix:
104 full_name = name
105 else:
106 full_name = "%s_%s" % (field_prefix, name)
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)
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;
129 ''',
130 name=full_name)
132 pop_indent()
133 ret += mcgen('''
134 /* Always call end_struct if start_struct succeeded. */
135 visit_end_struct(m, &err);
137 error_propagate(errp, err);
139 ''')
140 return ret
142 def generate_visit_struct(expr):
144 name = expr['type']
145 members = expr['data']
146 base = expr.get('base')
148 ret = generate_visit_struct_fields(name, "", "", members, base)
150 ret += mcgen('''
152 void visit_type_%(name)s(Visitor *m, %(name)s ** obj, const char *name, Error **errp)
154 ''',
155 name=name)
157 push_indent()
158 ret += generate_visit_struct_body("", name, members)
159 pop_indent()
161 ret += mcgen('''
163 ''')
164 return ret
166 def generate_visit_list(name, members):
167 return mcgen('''
169 void visit_type_%(name)sList(Visitor *m, %(name)sList ** obj, const char *name, Error **errp)
171 GenericList *i, **prev = (GenericList **)obj;
172 Error *err = NULL;
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);
181 error_propagate(errp, err);
182 err = NULL;
184 /* Always call end_list if start_list succeeded. */
185 visit_end_list(m, &err);
187 error_propagate(errp, err);
190 ''',
191 name=name)
193 def generate_visit_enum(name, members):
194 return mcgen('''
196 void visit_type_%(name)s(Visitor *m, %(name)s * obj, const char *name, Error **errp)
198 visit_type_enum(m, (int *)obj, %(name)s_lookup, "%(name)s", name, errp);
200 ''',
201 name=name)
203 def generate_visit_anon_union(name, members):
204 ret = mcgen('''
206 void visit_type_%(name)s(Visitor *m, %(name)s ** obj, const char *name, Error **errp)
208 Error *err = NULL;
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)
217 # For anon union, always use the default enum type automatically generated
218 # as "'%sKind' % (name)"
219 disc_type = '%sKind' % (name)
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"
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))
236 ret += mcgen('''
237 default:
238 abort();
240 error_propagate(errp, err);
241 err = NULL;
242 visit_end_implicit_struct(m, &err);
245 ''')
247 return ret
250 def generate_visit_union(expr):
252 name = expr['union']
253 members = expr['data']
255 base = expr.get('base')
256 discriminator = expr.get('discriminator')
258 if discriminator == {}:
259 assert not base
260 return generate_visit_anon_union(name, members)
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)
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)
280 ret += mcgen('''
282 void visit_type_%(name)s(Visitor *m, %(name)s ** obj, const char *name, Error **errp)
284 Error *err = NULL;
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)
294 push_indent()
295 push_indent()
296 push_indent()
298 if base:
299 ret += mcgen('''
300 visit_type_%(name)s_fields(m, obj, &err);
301 ''',
302 name=name)
304 pop_indent()
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)
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 }'''
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))
340 ret += mcgen('''
341 default:
342 abort();
345 error_propagate(errp, err);
346 err = NULL;
348 ''')
349 pop_indent()
350 ret += mcgen('''
351 /* Always call end_struct if start_struct succeeded. */
352 visit_end_struct(m, &err);
354 error_propagate(errp, err);
356 ''')
358 pop_indent();
359 ret += mcgen('''
361 ''')
363 return ret
365 def generate_declaration(name, members, genlist=True, builtin_type=False):
366 ret = ""
367 if not builtin_type:
368 ret += mcgen('''
370 void visit_type_%(name)s(Visitor *m, %(name)s ** obj, const char *name, Error **errp);
371 ''',
372 name=name)
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)
380 return ret
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)
390 return ret
392 def generate_decl_enum(name, members, genlist=True):
393 return mcgen('''
395 void visit_type_%(name)s(Visitor *m, %(name)s * obj, const char *name, Error **errp);
396 ''',
397 name=name)
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)
407 output_dir = ""
408 prefix = ""
409 c_file = 'qapi-visit.c'
410 h_file = 'qapi-visit.h'
412 do_c = False
413 do_h = False
414 do_builtins = False
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
428 if not do_c and not do_h:
429 do_c = True
430 do_h = True
432 c_file = output_dir + prefix + c_file
433 h_file = output_dir + prefix + h_file
435 try:
436 os.makedirs(output_dir)
437 except os.error, e:
438 if e.errno != errno.EEXIST:
439 raise
441 def maybe_open(really, name, opt):
442 if really:
443 return open(name, opt)
444 else:
445 import StringIO
446 return StringIO.StringIO()
448 fdef = maybe_open(do_c, c_file, 'w')
449 fdecl = maybe_open(do_h, h_file, 'w')
451 fdef.write(mcgen('''
452 /* THIS FILE IS AUTOMATICALLY GENERATED, DO NOT MODIFY */
455 * schema-defined QAPI visitor functions
457 * Copyright IBM, Corp. 2011
459 * Authors:
460 * Anthony Liguori <aliguori@us.ibm.com>
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.
467 #include "qemu-common.h"
468 #include "%(header)s"
469 ''',
470 header=basename(h_file)))
472 fdecl.write(mcgen('''
473 /* THIS FILE IS AUTOMATICALLY GENERATED, DO NOT MODIFY */
476 * schema-defined QAPI visitor function
478 * Copyright IBM, Corp. 2011
480 * Authors:
481 * Anthony Liguori <aliguori@us.ibm.com>
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.
488 #ifndef %(guard)s
489 #define %(guard)s
491 #include "qapi/visitor.h"
492 #include "%(prefix)sqapi-types.h"
494 ''',
495 prefix=prefix, guard=guardname(h_file)))
497 exprs = parse_schema(sys.stdin)
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"))
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))
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)
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)
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)
539 ret = generate_decl_enum(expr['enum'], expr['data'])
540 ret += generate_enum_declaration(expr['enum'], expr['data'])
541 fdecl.write(ret)
543 fdecl.write('''
544 #endif
545 ''')
547 fdecl.flush()
548 fdecl.close()
550 fdef.flush()
551 fdef.close()