arch_init: make is_zero_page accept size
[qemu/ar7.git] / scripts / qapi-types.py
blob5222463893682430849adddcbd79eb0cb80d977e
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 GPLv2.
10 # See the COPYING.LIB 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("", argname, 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(structname, fieldname, members):
85 ret = mcgen('''
86 struct %(name)s
88 ''',
89 name=structname)
91 ret += generate_struct_fields(members)
93 if len(fieldname):
94 fieldname = " " + fieldname
95 ret += mcgen('''
96 }%(field)s;
97 ''',
98 field=fieldname)
100 return ret
102 def generate_enum_lookup(name, values):
103 ret = mcgen('''
104 const char *%(name)s_lookup[] = {
105 ''',
106 name=name)
107 i = 0
108 for value in values:
109 ret += mcgen('''
110 "%(value)s",
111 ''',
112 value=value)
114 ret += mcgen('''
115 NULL,
118 ''')
119 return ret
121 def generate_enum_name(name):
122 if name.isupper():
123 return c_fun(name, False)
124 new_name = ''
125 for c in c_fun(name, False):
126 if c.isupper():
127 new_name += '_'
128 new_name += c
129 return new_name.lstrip('_').upper()
131 def generate_enum(name, values):
132 lookup_decl = mcgen('''
133 extern const char *%(name)s_lookup[];
134 ''',
135 name=name)
137 enum_decl = mcgen('''
138 typedef enum %(name)s
140 ''',
141 name=name)
143 # append automatically generated _MAX value
144 enum_values = values + [ 'MAX' ]
146 i = 0
147 for value in enum_values:
148 enum_decl += mcgen('''
149 %(abbrev)s_%(value)s = %(i)d,
150 ''',
151 abbrev=de_camel_case(name).upper(),
152 value=generate_enum_name(value),
153 i=i)
154 i += 1
156 enum_decl += mcgen('''
157 } %(name)s;
158 ''',
159 name=name)
161 return lookup_decl + enum_decl
163 def generate_anon_union_qtypes(expr):
165 name = expr['union']
166 members = expr['data']
168 ret = mcgen('''
169 const int %(name)s_qtypes[QTYPE_MAX] = {
170 ''',
171 name=name)
173 for key in members:
174 qapi_type = members[key]
175 if builtin_type_qtypes.has_key(qapi_type):
176 qtype = builtin_type_qtypes[qapi_type]
177 elif find_struct(qapi_type):
178 qtype = "QTYPE_QDICT"
179 elif find_union(qapi_type):
180 qtype = "QTYPE_QDICT"
181 else:
182 assert False, "Invalid anonymous union member"
184 ret += mcgen('''
185 [ %(qtype)s ] = %(abbrev)s_KIND_%(enum)s,
186 ''',
187 qtype = qtype,
188 abbrev = de_camel_case(name).upper(),
189 enum = c_fun(de_camel_case(key),False).upper())
191 ret += mcgen('''
193 ''')
194 return ret
197 def generate_union(expr):
199 name = expr['union']
200 typeinfo = expr['data']
202 base = expr.get('base')
203 discriminator = expr.get('discriminator')
205 ret = mcgen('''
206 struct %(name)s
208 %(name)sKind kind;
209 union {
210 void *data;
211 ''',
212 name=name)
214 for key in typeinfo:
215 ret += mcgen('''
216 %(c_type)s %(c_name)s;
217 ''',
218 c_type=c_type(typeinfo[key]),
219 c_name=c_fun(key))
221 ret += mcgen('''
223 ''')
225 if base:
226 base_fields = find_struct(base)['data']
227 if discriminator:
228 base_fields = base_fields.copy()
229 del base_fields[discriminator]
230 ret += generate_struct_fields(base_fields)
231 else:
232 assert not discriminator
234 ret += mcgen('''
236 ''')
237 if discriminator == {}:
238 ret += mcgen('''
239 extern const int %(name)s_qtypes[];
240 ''',
241 name=name)
244 return ret
246 def generate_type_cleanup_decl(name):
247 ret = mcgen('''
248 void qapi_free_%(type)s(%(c_type)s obj);
249 ''',
250 c_type=c_type(name),type=name)
251 return ret
253 def generate_type_cleanup(name):
254 ret = mcgen('''
256 void qapi_free_%(type)s(%(c_type)s obj)
258 QapiDeallocVisitor *md;
259 Visitor *v;
261 if (!obj) {
262 return;
265 md = qapi_dealloc_visitor_new();
266 v = qapi_dealloc_get_visitor(md);
267 visit_type_%(type)s(v, &obj, NULL, NULL);
268 qapi_dealloc_visitor_cleanup(md);
270 ''',
271 c_type=c_type(name),type=name)
272 return ret
275 try:
276 opts, args = getopt.gnu_getopt(sys.argv[1:], "chbp:o:",
277 ["source", "header", "builtins",
278 "prefix=", "output-dir="])
279 except getopt.GetoptError, err:
280 print str(err)
281 sys.exit(1)
283 output_dir = ""
284 prefix = ""
285 c_file = 'qapi-types.c'
286 h_file = 'qapi-types.h'
288 do_c = False
289 do_h = False
290 do_builtins = False
292 for o, a in opts:
293 if o in ("-p", "--prefix"):
294 prefix = a
295 elif o in ("-o", "--output-dir"):
296 output_dir = a + "/"
297 elif o in ("-c", "--source"):
298 do_c = True
299 elif o in ("-h", "--header"):
300 do_h = True
301 elif o in ("-b", "--builtins"):
302 do_builtins = True
304 if not do_c and not do_h:
305 do_c = True
306 do_h = True
308 c_file = output_dir + prefix + c_file
309 h_file = output_dir + prefix + h_file
311 try:
312 os.makedirs(output_dir)
313 except os.error, e:
314 if e.errno != errno.EEXIST:
315 raise
317 def maybe_open(really, name, opt):
318 if really:
319 return open(name, opt)
320 else:
321 import StringIO
322 return StringIO.StringIO()
324 fdef = maybe_open(do_c, c_file, 'w')
325 fdecl = maybe_open(do_h, h_file, 'w')
327 fdef.write(mcgen('''
328 /* AUTOMATICALLY GENERATED, DO NOT MODIFY */
331 * deallocation functions for schema-defined QAPI types
333 * Copyright IBM, Corp. 2011
335 * Authors:
336 * Anthony Liguori <aliguori@us.ibm.com>
337 * Michael Roth <mdroth@linux.vnet.ibm.com>
339 * This work is licensed under the terms of the GNU LGPL, version 2.1 or later.
340 * See the COPYING.LIB file in the top-level directory.
344 #include "qapi/dealloc-visitor.h"
345 #include "%(prefix)sqapi-types.h"
346 #include "%(prefix)sqapi-visit.h"
348 ''', prefix=prefix))
350 fdecl.write(mcgen('''
351 /* AUTOMATICALLY GENERATED, DO NOT MODIFY */
354 * schema-defined QAPI types
356 * Copyright IBM, Corp. 2011
358 * Authors:
359 * Anthony Liguori <aliguori@us.ibm.com>
361 * This work is licensed under the terms of the GNU LGPL, version 2.1 or later.
362 * See the COPYING.LIB file in the top-level directory.
366 #ifndef %(guard)s
367 #define %(guard)s
369 #include <stdbool.h>
370 #include <stdint.h>
372 ''',
373 guard=guardname(h_file)))
375 exprs = parse_schema(sys.stdin)
376 exprs = filter(lambda expr: not expr.has_key('gen'), exprs)
378 fdecl.write(guardstart("QAPI_TYPES_BUILTIN_STRUCT_DECL"))
379 for typename in builtin_types:
380 fdecl.write(generate_fwd_struct(typename, None, builtin_type=True))
381 fdecl.write(guardend("QAPI_TYPES_BUILTIN_STRUCT_DECL"))
383 for expr in exprs:
384 ret = "\n"
385 if expr.has_key('type'):
386 ret += generate_fwd_struct(expr['type'], expr['data'])
387 elif expr.has_key('enum'):
388 ret += generate_enum(expr['enum'], expr['data']) + "\n"
389 ret += generate_fwd_enum_struct(expr['enum'], expr['data'])
390 fdef.write(generate_enum_lookup(expr['enum'], expr['data']))
391 elif expr.has_key('union'):
392 ret += generate_fwd_struct(expr['union'], expr['data']) + "\n"
393 ret += generate_enum('%sKind' % expr['union'], expr['data'].keys())
394 fdef.write(generate_enum_lookup('%sKind' % expr['union'], expr['data'].keys()))
395 if expr.get('discriminator') == {}:
396 fdef.write(generate_anon_union_qtypes(expr))
397 else:
398 continue
399 fdecl.write(ret)
401 # to avoid header dependency hell, we always generate declarations
402 # for built-in types in our header files and simply guard them
403 fdecl.write(guardstart("QAPI_TYPES_BUILTIN_CLEANUP_DECL"))
404 for typename in builtin_types:
405 fdecl.write(generate_type_cleanup_decl(typename + "List"))
406 fdecl.write(guardend("QAPI_TYPES_BUILTIN_CLEANUP_DECL"))
408 # ...this doesn't work for cases where we link in multiple objects that
409 # have the functions defined, so we use -b option to provide control
410 # over these cases
411 if do_builtins:
412 fdef.write(guardstart("QAPI_TYPES_BUILTIN_CLEANUP_DEF"))
413 for typename in builtin_types:
414 fdef.write(generate_type_cleanup(typename + "List"))
415 fdef.write(guardend("QAPI_TYPES_BUILTIN_CLEANUP_DEF"))
417 for expr in exprs:
418 ret = "\n"
419 if expr.has_key('type'):
420 ret += generate_struct(expr['type'], "", expr['data']) + "\n"
421 ret += generate_type_cleanup_decl(expr['type'] + "List")
422 fdef.write(generate_type_cleanup(expr['type'] + "List") + "\n")
423 ret += generate_type_cleanup_decl(expr['type'])
424 fdef.write(generate_type_cleanup(expr['type']) + "\n")
425 elif expr.has_key('union'):
426 ret += generate_union(expr)
427 ret += generate_type_cleanup_decl(expr['union'] + "List")
428 fdef.write(generate_type_cleanup(expr['union'] + "List") + "\n")
429 ret += generate_type_cleanup_decl(expr['union'])
430 fdef.write(generate_type_cleanup(expr['union']) + "\n")
431 elif expr.has_key('enum'):
432 ret += generate_type_cleanup_decl(expr['enum'] + "List")
433 fdef.write(generate_type_cleanup(expr['enum'] + "List") + "\n")
434 else:
435 continue
436 fdecl.write(ret)
438 fdecl.write('''
439 #endif
440 ''')
442 fdecl.flush()
443 fdecl.close()
445 fdef.flush()
446 fdef.close()