osdep: Fix compilation failure on BSD systems
[qemu-kvm.git] / scripts / qapi-types.py
blobcf601ae2d23c5d2cab39ecaf88f03fd569ced40e
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):
20 return mcgen('''
21 typedef struct %(name)s %(name)s;
23 typedef struct %(name)sList
25 %(name)s *value;
26 struct %(name)sList *next;
27 } %(name)sList;
28 ''',
29 name=name)
31 def generate_struct(structname, fieldname, members):
32 ret = mcgen('''
33 struct %(name)s
35 ''',
36 name=structname)
38 for argname, argentry, optional, structured in parse_args(members):
39 if optional:
40 ret += mcgen('''
41 bool has_%(c_name)s;
42 ''',
43 c_name=c_var(argname))
44 if structured:
45 push_indent()
46 ret += generate_struct("", argname, argentry)
47 pop_indent()
48 else:
49 ret += mcgen('''
50 %(c_type)s %(c_name)s;
51 ''',
52 c_type=c_type(argentry), c_name=c_var(argname))
54 if len(fieldname):
55 fieldname = " " + fieldname
56 ret += mcgen('''
57 }%(field)s;
58 ''',
59 field=fieldname)
61 return ret
63 def generate_enum_lookup(name, values):
64 ret = mcgen('''
65 const char *%(name)s_lookup[] = {
66 ''',
67 name=name)
68 i = 0
69 for value in values:
70 ret += mcgen('''
71 "%(value)s",
72 ''',
73 value=value)
75 ret += mcgen('''
76 NULL,
79 ''')
80 return ret
82 def generate_enum_name(name):
83 if name.isupper():
84 return c_fun(name)
85 new_name = ''
86 for c in c_fun(name):
87 if c.isupper():
88 new_name += '_'
89 new_name += c
90 return new_name.lstrip('_').upper()
92 def generate_enum(name, values):
93 lookup_decl = mcgen('''
94 extern const char *%(name)s_lookup[];
95 ''',
96 name=name)
98 enum_decl = mcgen('''
99 typedef enum %(name)s
101 ''',
102 name=name)
104 # append automatically generated _MAX value
105 enum_values = values + [ 'MAX' ]
107 i = 0
108 for value in enum_values:
109 enum_decl += mcgen('''
110 %(abbrev)s_%(value)s = %(i)d,
111 ''',
112 abbrev=de_camel_case(name).upper(),
113 value=generate_enum_name(value),
114 i=i)
115 i += 1
117 enum_decl += mcgen('''
118 } %(name)s;
119 ''',
120 name=name)
122 return lookup_decl + enum_decl
124 def generate_union(name, typeinfo):
125 ret = mcgen('''
126 struct %(name)s
128 %(name)sKind kind;
129 union {
130 void *data;
131 ''',
132 name=name)
134 for key in typeinfo:
135 ret += mcgen('''
136 %(c_type)s %(c_name)s;
137 ''',
138 c_type=c_type(typeinfo[key]),
139 c_name=c_fun(key))
141 ret += mcgen('''
144 ''')
146 return ret
148 def generate_type_cleanup_decl(name):
149 ret = mcgen('''
150 void qapi_free_%(type)s(%(c_type)s obj);
151 ''',
152 c_type=c_type(name),type=name)
153 return ret
155 def generate_type_cleanup(name):
156 ret = mcgen('''
157 void qapi_free_%(type)s(%(c_type)s obj)
159 QapiDeallocVisitor *md;
160 Visitor *v;
162 if (!obj) {
163 return;
166 md = qapi_dealloc_visitor_new();
167 v = qapi_dealloc_get_visitor(md);
168 visit_type_%(type)s(v, &obj, NULL, NULL);
169 qapi_dealloc_visitor_cleanup(md);
171 ''',
172 c_type=c_type(name),type=name)
173 return ret
176 try:
177 opts, args = getopt.gnu_getopt(sys.argv[1:], "chp:o:",
178 ["source", "header", "prefix=", "output-dir="])
179 except getopt.GetoptError, err:
180 print str(err)
181 sys.exit(1)
183 output_dir = ""
184 prefix = ""
185 c_file = 'qapi-types.c'
186 h_file = 'qapi-types.h'
188 do_c = False
189 do_h = False
191 for o, a in opts:
192 if o in ("-p", "--prefix"):
193 prefix = a
194 elif o in ("-o", "--output-dir"):
195 output_dir = a + "/"
196 elif o in ("-c", "--source"):
197 do_c = True
198 elif o in ("-h", "--header"):
199 do_h = True
201 if not do_c and not do_h:
202 do_c = True
203 do_h = True
205 c_file = output_dir + prefix + c_file
206 h_file = output_dir + prefix + h_file
208 try:
209 os.makedirs(output_dir)
210 except os.error, e:
211 if e.errno != errno.EEXIST:
212 raise
214 def maybe_open(really, name, opt):
215 if really:
216 return open(name, opt)
217 else:
218 import StringIO
219 return StringIO.StringIO()
221 fdef = maybe_open(do_c, c_file, 'w')
222 fdecl = maybe_open(do_h, h_file, 'w')
224 fdef.write(mcgen('''
225 /* AUTOMATICALLY GENERATED, DO NOT MODIFY */
228 * deallocation functions for schema-defined QAPI types
230 * Copyright IBM, Corp. 2011
232 * Authors:
233 * Anthony Liguori <aliguori@us.ibm.com>
234 * Michael Roth <mdroth@linux.vnet.ibm.com>
236 * This work is licensed under the terms of the GNU LGPL, version 2.1 or later.
237 * See the COPYING.LIB file in the top-level directory.
241 #include "qapi/qapi-dealloc-visitor.h"
242 #include "%(prefix)sqapi-types.h"
243 #include "%(prefix)sqapi-visit.h"
245 ''', prefix=prefix))
247 fdecl.write(mcgen('''
248 /* AUTOMATICALLY GENERATED, DO NOT MODIFY */
251 * schema-defined QAPI types
253 * Copyright IBM, Corp. 2011
255 * Authors:
256 * Anthony Liguori <aliguori@us.ibm.com>
258 * This work is licensed under the terms of the GNU LGPL, version 2.1 or later.
259 * See the COPYING.LIB file in the top-level directory.
263 #ifndef %(guard)s
264 #define %(guard)s
266 #include "qemu-common.h"
268 ''',
269 guard=guardname(h_file)))
271 exprs = parse_schema(sys.stdin)
272 exprs = filter(lambda expr: not expr.has_key('gen'), exprs)
274 for expr in exprs:
275 ret = "\n"
276 if expr.has_key('type'):
277 ret += generate_fwd_struct(expr['type'], expr['data'])
278 elif expr.has_key('enum'):
279 ret += generate_enum(expr['enum'], expr['data'])
280 fdef.write(generate_enum_lookup(expr['enum'], expr['data']))
281 elif expr.has_key('union'):
282 ret += generate_fwd_struct(expr['union'], expr['data']) + "\n"
283 ret += generate_enum('%sKind' % expr['union'], expr['data'].keys())
284 fdef.write(generate_enum_lookup('%sKind' % expr['union'], expr['data'].keys()))
285 else:
286 continue
287 fdecl.write(ret)
289 for expr in exprs:
290 ret = "\n"
291 if expr.has_key('type'):
292 ret += generate_struct(expr['type'], "", expr['data']) + "\n"
293 ret += generate_type_cleanup_decl(expr['type'] + "List")
294 fdef.write(generate_type_cleanup(expr['type'] + "List") + "\n")
295 ret += generate_type_cleanup_decl(expr['type'])
296 fdef.write(generate_type_cleanup(expr['type']) + "\n")
297 elif expr.has_key('union'):
298 ret += generate_union(expr['union'], expr['data'])
299 ret += generate_type_cleanup_decl(expr['union'] + "List")
300 fdef.write(generate_type_cleanup(expr['union'] + "List") + "\n")
301 ret += generate_type_cleanup_decl(expr['union'])
302 fdef.write(generate_type_cleanup(expr['union']) + "\n")
303 else:
304 continue
305 fdecl.write(ret)
307 fdecl.write('''
308 #endif
309 ''')
311 fdecl.flush()
312 fdecl.close()
314 fdef.flush()
315 fdef.close()