Xen PV Device
[qemu/ar7.git] / scripts / qapi-visit.py
blob597cca4b66ba4de5a424e46363a47d3ee9813759
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 GPLv2.
11 # See the COPYING.LIB 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):
21 substructs = []
22 ret = ''
23 full_name = name if not fn_prefix else "%s_%s" % (name, fn_prefix)
25 for argname, argentry, optional, structured in parse_args(members):
26 if structured:
27 if not fn_prefix:
28 nested_fn_prefix = argname
29 else:
30 nested_fn_prefix = "%s_%s" % (fn_prefix, argname)
32 nested_field_prefix = "%s%s." % (field_prefix, argname)
33 ret += generate_visit_struct_fields(name, nested_field_prefix,
34 nested_fn_prefix, argentry)
36 ret += mcgen('''
38 static void visit_type_%(full_name)s_fields(Visitor *m, %(name)s ** obj, Error **errp)
40 Error *err = NULL;
41 ''',
42 name=name, full_name=full_name)
43 push_indent()
45 for argname, argentry, optional, structured in parse_args(members):
46 if optional:
47 ret += mcgen('''
48 visit_start_optional(m, obj ? &(*obj)->%(c_prefix)shas_%(c_name)s : NULL, "%(name)s", &err);
49 if (obj && (*obj)->%(prefix)shas_%(c_name)s) {
50 ''',
51 c_prefix=c_var(field_prefix), prefix=field_prefix,
52 c_name=c_var(argname), name=argname)
53 push_indent()
55 if structured:
56 ret += generate_visit_struct_body(full_name, argname, argentry)
57 else:
58 ret += mcgen('''
59 visit_type_%(type)s(m, obj ? &(*obj)->%(c_prefix)s%(c_name)s : NULL, "%(name)s", &err);
60 ''',
61 c_prefix=c_var(field_prefix), prefix=field_prefix,
62 type=type_name(argentry), c_name=c_var(argname),
63 name=argname)
65 if optional:
66 pop_indent()
67 ret += mcgen('''
69 visit_end_optional(m, &err);
70 ''')
72 pop_indent()
73 ret += mcgen('''
75 error_propagate(errp, err);
77 ''')
78 return ret
81 def generate_visit_struct_body(field_prefix, name, members):
82 ret = mcgen('''
83 if (!error_is_set(errp)) {
84 ''')
85 push_indent()
87 full_name = name if not field_prefix else "%s_%s" % (field_prefix, name)
89 if len(field_prefix):
90 ret += mcgen('''
91 Error **errp = &err; /* from outer scope */
92 Error *err = NULL;
93 visit_start_struct(m, NULL, "", "%(name)s", 0, &err);
94 ''',
95 name=name)
96 else:
97 ret += mcgen('''
98 Error *err = NULL;
99 visit_start_struct(m, (void **)obj, "%(name)s", name, sizeof(%(name)s), &err);
100 ''',
101 name=name)
103 ret += mcgen('''
104 if (!err) {
105 if (!obj || *obj) {
106 visit_type_%(name)s_fields(m, obj, &err);
107 error_propagate(errp, err);
108 err = NULL;
110 ''',
111 name=full_name)
113 pop_indent()
114 ret += mcgen('''
115 /* Always call end_struct if start_struct succeeded. */
116 visit_end_struct(m, &err);
118 error_propagate(errp, err);
120 ''')
121 return ret
123 def generate_visit_struct(name, members):
124 ret = generate_visit_struct_fields(name, "", "", members)
126 ret += mcgen('''
128 void visit_type_%(name)s(Visitor *m, %(name)s ** obj, const char *name, Error **errp)
130 ''',
131 name=name)
133 push_indent()
134 ret += generate_visit_struct_body("", name, members)
135 pop_indent()
137 ret += mcgen('''
139 ''')
140 return ret
142 def generate_visit_list(name, members):
143 return mcgen('''
145 void visit_type_%(name)sList(Visitor *m, %(name)sList ** obj, const char *name, Error **errp)
147 GenericList *i, **prev = (GenericList **)obj;
148 Error *err = NULL;
150 if (!error_is_set(errp)) {
151 visit_start_list(m, name, &err);
152 if (!err) {
153 for (; (i = visit_next_list(m, prev, &err)) != NULL; prev = &i) {
154 %(name)sList *native_i = (%(name)sList *)i;
155 visit_type_%(name)s(m, &native_i->value, NULL, &err);
157 error_propagate(errp, err);
158 err = NULL;
160 /* Always call end_list if start_list succeeded. */
161 visit_end_list(m, &err);
163 error_propagate(errp, err);
166 ''',
167 name=name)
169 def generate_visit_enum(name, members):
170 return mcgen('''
172 void visit_type_%(name)s(Visitor *m, %(name)s * obj, const char *name, Error **errp)
174 visit_type_enum(m, (int *)obj, %(name)s_lookup, "%(name)s", name, errp);
176 ''',
177 name=name)
179 def generate_visit_anon_union(name, members):
180 ret = mcgen('''
182 void visit_type_%(name)s(Visitor *m, %(name)s ** obj, const char *name, Error **errp)
184 Error *err = NULL;
186 if (!error_is_set(errp)) {
187 visit_start_implicit_struct(m, (void**) obj, sizeof(%(name)s), &err);
188 visit_get_next_type(m, (int*) &(*obj)->kind, %(name)s_qtypes, name, &err);
189 switch ((*obj)->kind) {
190 ''',
191 name=name)
193 for key in members:
194 assert (members[key] in builtin_types
195 or find_struct(members[key])
196 or find_union(members[key])), "Invalid anonymous union member"
198 ret += mcgen('''
199 case %(abbrev)s_KIND_%(enum)s:
200 visit_type_%(c_type)s(m, &(*obj)->%(c_name)s, name, &err);
201 break;
202 ''',
203 abbrev = de_camel_case(name).upper(),
204 enum = c_fun(de_camel_case(key),False).upper(),
205 c_type = type_name(members[key]),
206 c_name = c_fun(key))
208 ret += mcgen('''
209 default:
210 abort();
212 error_propagate(errp, err);
213 err = NULL;
214 visit_end_implicit_struct(m, &err);
217 ''')
219 return ret
222 def generate_visit_union(expr):
224 name = expr['union']
225 members = expr['data']
227 base = expr.get('base')
228 discriminator = expr.get('discriminator')
230 if discriminator == {}:
231 assert not base
232 return generate_visit_anon_union(name, members)
234 ret = generate_visit_enum('%sKind' % name, members.keys())
236 if base:
237 base_fields = find_struct(base)['data']
238 if discriminator:
239 base_fields = base_fields.copy()
240 del base_fields[discriminator]
241 ret += generate_visit_struct_fields(name, "", "", base_fields)
243 ret += mcgen('''
245 void visit_type_%(name)s(Visitor *m, %(name)s ** obj, const char *name, Error **errp)
247 Error *err = NULL;
249 if (!error_is_set(errp)) {
250 visit_start_struct(m, (void **)obj, "%(name)s", name, sizeof(%(name)s), &err);
251 if (!err) {
252 if (obj && *obj) {
253 ''',
254 name=name)
257 push_indent()
258 push_indent()
259 push_indent()
261 if base:
262 ret += mcgen('''
263 visit_type_%(name)s_fields(m, obj, &err);
264 ''',
265 name=name)
267 pop_indent()
268 ret += mcgen('''
269 visit_type_%(name)sKind(m, &(*obj)->kind, "%(type)s", &err);
270 if (!err) {
271 switch ((*obj)->kind) {
272 ''',
273 name=name, type="type" if not discriminator else discriminator)
275 for key in members:
276 if not discriminator:
277 fmt = 'visit_type_%(c_type)s(m, &(*obj)->%(c_name)s, "data", &err);'
278 else:
279 fmt = '''visit_start_implicit_struct(m, (void**) &(*obj)->%(c_name)s, sizeof(%(c_type)s), &err);
280 if (!err) {
281 visit_type_%(c_type)s_fields(m, &(*obj)->%(c_name)s, &err);
282 error_propagate(errp, err);
283 err = NULL;
284 visit_end_implicit_struct(m, &err);
285 }'''
287 ret += mcgen('''
288 case %(abbrev)s_KIND_%(enum)s:
289 ''' + fmt + '''
290 break;
291 ''',
292 abbrev = de_camel_case(name).upper(),
293 enum = c_fun(de_camel_case(key),False).upper(),
294 c_type=type_name(members[key]),
295 c_name=c_fun(key))
297 ret += mcgen('''
298 default:
299 abort();
302 error_propagate(errp, err);
303 err = NULL;
305 ''')
306 pop_indent()
307 ret += mcgen('''
308 /* Always call end_struct if start_struct succeeded. */
309 visit_end_struct(m, &err);
311 error_propagate(errp, err);
313 ''')
315 pop_indent();
316 ret += mcgen('''
318 ''')
320 return ret
322 def generate_declaration(name, members, genlist=True, builtin_type=False):
323 ret = ""
324 if not builtin_type:
325 ret += mcgen('''
327 void visit_type_%(name)s(Visitor *m, %(name)s ** obj, const char *name, Error **errp);
328 ''',
329 name=name)
331 if genlist:
332 ret += mcgen('''
333 void visit_type_%(name)sList(Visitor *m, %(name)sList ** obj, const char *name, Error **errp);
334 ''',
335 name=name)
337 return ret
339 def generate_enum_declaration(name, members, genlist=True):
340 ret = ""
341 if genlist:
342 ret += mcgen('''
343 void visit_type_%(name)sList(Visitor *m, %(name)sList ** obj, const char *name, Error **errp);
344 ''',
345 name=name)
347 return ret
349 def generate_decl_enum(name, members, genlist=True):
350 return mcgen('''
352 void visit_type_%(name)s(Visitor *m, %(name)s * obj, const char *name, Error **errp);
353 ''',
354 name=name)
356 try:
357 opts, args = getopt.gnu_getopt(sys.argv[1:], "chbp:o:",
358 ["source", "header", "builtins", "prefix=",
359 "output-dir="])
360 except getopt.GetoptError, err:
361 print str(err)
362 sys.exit(1)
364 output_dir = ""
365 prefix = ""
366 c_file = 'qapi-visit.c'
367 h_file = 'qapi-visit.h'
369 do_c = False
370 do_h = False
371 do_builtins = False
373 for o, a in opts:
374 if o in ("-p", "--prefix"):
375 prefix = a
376 elif o in ("-o", "--output-dir"):
377 output_dir = a + "/"
378 elif o in ("-c", "--source"):
379 do_c = True
380 elif o in ("-h", "--header"):
381 do_h = True
382 elif o in ("-b", "--builtins"):
383 do_builtins = True
385 if not do_c and not do_h:
386 do_c = True
387 do_h = True
389 c_file = output_dir + prefix + c_file
390 h_file = output_dir + prefix + h_file
392 try:
393 os.makedirs(output_dir)
394 except os.error, e:
395 if e.errno != errno.EEXIST:
396 raise
398 def maybe_open(really, name, opt):
399 if really:
400 return open(name, opt)
401 else:
402 import StringIO
403 return StringIO.StringIO()
405 fdef = maybe_open(do_c, c_file, 'w')
406 fdecl = maybe_open(do_h, h_file, 'w')
408 fdef.write(mcgen('''
409 /* THIS FILE IS AUTOMATICALLY GENERATED, DO NOT MODIFY */
412 * schema-defined QAPI visitor functions
414 * Copyright IBM, Corp. 2011
416 * Authors:
417 * Anthony Liguori <aliguori@us.ibm.com>
419 * This work is licensed under the terms of the GNU LGPL, version 2.1 or later.
420 * See the COPYING.LIB file in the top-level directory.
424 #include "qemu-common.h"
425 #include "%(header)s"
426 ''',
427 header=basename(h_file)))
429 fdecl.write(mcgen('''
430 /* THIS FILE IS AUTOMATICALLY GENERATED, DO NOT MODIFY */
433 * schema-defined QAPI visitor function
435 * Copyright IBM, Corp. 2011
437 * Authors:
438 * Anthony Liguori <aliguori@us.ibm.com>
440 * This work is licensed under the terms of the GNU LGPL, version 2.1 or later.
441 * See the COPYING.LIB file in the top-level directory.
445 #ifndef %(guard)s
446 #define %(guard)s
448 #include "qapi/visitor.h"
449 #include "%(prefix)sqapi-types.h"
451 ''',
452 prefix=prefix, guard=guardname(h_file)))
454 exprs = parse_schema(sys.stdin)
456 # to avoid header dependency hell, we always generate declarations
457 # for built-in types in our header files and simply guard them
458 fdecl.write(guardstart("QAPI_VISIT_BUILTIN_VISITOR_DECL"))
459 for typename in builtin_types:
460 fdecl.write(generate_declaration(typename, None, genlist=True,
461 builtin_type=True))
462 fdecl.write(guardend("QAPI_VISIT_BUILTIN_VISITOR_DECL"))
464 # ...this doesn't work for cases where we link in multiple objects that
465 # have the functions defined, so we use -b option to provide control
466 # over these cases
467 if do_builtins:
468 fdef.write(guardstart("QAPI_VISIT_BUILTIN_VISITOR_DEF"))
469 for typename in builtin_types:
470 fdef.write(generate_visit_list(typename, None))
471 fdef.write(guardend("QAPI_VISIT_BUILTIN_VISITOR_DEF"))
473 for expr in exprs:
474 if expr.has_key('type'):
475 ret = generate_visit_struct(expr['type'], expr['data'])
476 ret += generate_visit_list(expr['type'], expr['data'])
477 fdef.write(ret)
479 ret = generate_declaration(expr['type'], expr['data'])
480 fdecl.write(ret)
481 elif expr.has_key('union'):
482 ret = generate_visit_union(expr)
483 ret += generate_visit_list(expr['union'], expr['data'])
484 fdef.write(ret)
486 ret = generate_decl_enum('%sKind' % expr['union'], expr['data'].keys())
487 ret += generate_declaration(expr['union'], expr['data'])
488 fdecl.write(ret)
489 elif expr.has_key('enum'):
490 ret = generate_visit_list(expr['enum'], expr['data'])
491 ret += generate_visit_enum(expr['enum'], expr['data'])
492 fdef.write(ret)
494 ret = generate_decl_enum(expr['enum'], expr['data'])
495 ret += generate_enum_declaration(expr['enum'], expr['data'])
496 fdecl.write(ret)
498 fdecl.write('''
499 #endif
500 ''')
502 fdecl.flush()
503 fdecl.close()
505 fdef.flush()
506 fdef.close()