blob: 75fc28252d68fd56acd40cf8b4a73db398420aed [file] [log] [blame]
Michael Roth0f923be2011-07-19 14:50:39 -05001#
2# QAPI helper library
3#
4# Copyright IBM, Corp. 2011
Markus Armbrusterc7a3f252013-07-27 17:41:55 +02005# Copyright (c) 2013 Red Hat Inc.
Michael Roth0f923be2011-07-19 14:50:39 -05006#
7# Authors:
8# Anthony Liguori <aliguori@us.ibm.com>
Markus Armbrusterc7a3f252013-07-27 17:41:55 +02009# Markus Armbruster <armbru@redhat.com>
Michael Roth0f923be2011-07-19 14:50:39 -050010#
11# This work is licensed under the terms of the GNU GPLv2.
12# See the COPYING.LIB file in the top-level directory.
13
14from ordereddict import OrderedDict
Markus Armbruster2caba362013-07-27 17:41:56 +020015import sys
Michael Roth0f923be2011-07-19 14:50:39 -050016
Michael Rothc0afa9c2013-05-10 17:46:00 -050017builtin_types = [
18 'str', 'int', 'number', 'bool',
19 'int8', 'int16', 'int32', 'int64',
20 'uint8', 'uint16', 'uint32', 'uint64'
21]
22
Kevin Wolf69dd62d2013-07-08 16:14:21 +020023builtin_type_qtypes = {
24 'str': 'QTYPE_QSTRING',
25 'int': 'QTYPE_QINT',
26 'number': 'QTYPE_QFLOAT',
27 'bool': 'QTYPE_QBOOL',
28 'int8': 'QTYPE_QINT',
29 'int16': 'QTYPE_QINT',
30 'int32': 'QTYPE_QINT',
31 'int64': 'QTYPE_QINT',
32 'uint8': 'QTYPE_QINT',
33 'uint16': 'QTYPE_QINT',
34 'uint32': 'QTYPE_QINT',
35 'uint64': 'QTYPE_QINT',
36}
37
Markus Armbruster2caba362013-07-27 17:41:56 +020038class QAPISchemaError(Exception):
39 def __init__(self, schema, msg):
40 self.fp = schema.fp
41 self.msg = msg
42 self.line = self.col = 1
43 for ch in schema.src[0:schema.pos]:
44 if ch == '\n':
45 self.line += 1
46 self.col = 1
47 elif ch == '\t':
48 self.col = (self.col + 7) % 8 + 1
49 else:
50 self.col += 1
51
52 def __str__(self):
53 return "%s:%s:%s: %s" % (self.fp.name, self.line, self.col, self.msg)
54
Markus Armbrusterc7a3f252013-07-27 17:41:55 +020055class QAPISchema:
Michael Roth0f923be2011-07-19 14:50:39 -050056
Markus Armbrusterc7a3f252013-07-27 17:41:55 +020057 def __init__(self, fp):
58 self.fp = fp
59 self.src = fp.read()
60 if self.src == '' or self.src[-1] != '\n':
61 self.src += '\n'
62 self.cursor = 0
63 self.exprs = []
64 self.accept()
Michael Roth0f923be2011-07-19 14:50:39 -050065
Markus Armbrusterc7a3f252013-07-27 17:41:55 +020066 while self.tok != None:
Markus Armbruster5f3cd2b2013-07-27 17:41:59 +020067 self.exprs.append(self.get_expr(False))
Michael Roth0f923be2011-07-19 14:50:39 -050068
Markus Armbrusterc7a3f252013-07-27 17:41:55 +020069 def accept(self):
70 while True:
71 bol = self.cursor == 0 or self.src[self.cursor-1] == '\n'
72 self.tok = self.src[self.cursor]
Markus Armbruster2caba362013-07-27 17:41:56 +020073 self.pos = self.cursor
Markus Armbrusterc7a3f252013-07-27 17:41:55 +020074 self.cursor += 1
75 self.val = None
Michael Roth0f923be2011-07-19 14:50:39 -050076
Markus Armbrusterc7a3f252013-07-27 17:41:55 +020077 if self.tok == '#' and bol:
78 self.cursor = self.src.find('\n', self.cursor)
79 elif self.tok in ['{', '}', ':', ',', '[', ']']:
80 return
81 elif self.tok == "'":
82 string = ''
83 esc = False
84 while True:
85 ch = self.src[self.cursor]
86 self.cursor += 1
87 if ch == '\n':
Markus Armbruster2caba362013-07-27 17:41:56 +020088 raise QAPISchemaError(self,
89 'Missing terminating "\'"')
Markus Armbrusterc7a3f252013-07-27 17:41:55 +020090 if esc:
91 string += ch
92 esc = False
93 elif ch == "\\":
94 esc = True
95 elif ch == "'":
96 self.val = string
97 return
98 else:
99 string += ch
100 elif self.tok == '\n':
101 if self.cursor == len(self.src):
102 self.tok = None
103 return
Markus Armbruster9213aa52013-07-27 17:41:57 +0200104 elif not self.tok.isspace():
105 raise QAPISchemaError(self, 'Stray "%s"' % self.tok)
Michael Roth0f923be2011-07-19 14:50:39 -0500106
Markus Armbrusterc7a3f252013-07-27 17:41:55 +0200107 def get_members(self):
108 expr = OrderedDict()
Markus Armbruster6974ccd2013-07-27 17:41:58 +0200109 if self.tok == '}':
110 self.accept()
111 return expr
112 if self.tok != "'":
113 raise QAPISchemaError(self, 'Expected string or "}"')
114 while True:
Markus Armbrusterc7a3f252013-07-27 17:41:55 +0200115 key = self.val
116 self.accept()
Markus Armbruster6974ccd2013-07-27 17:41:58 +0200117 if self.tok != ':':
118 raise QAPISchemaError(self, 'Expected ":"')
119 self.accept()
Markus Armbruster5f3cd2b2013-07-27 17:41:59 +0200120 expr[key] = self.get_expr(True)
Markus Armbruster6974ccd2013-07-27 17:41:58 +0200121 if self.tok == '}':
Markus Armbrusterc7a3f252013-07-27 17:41:55 +0200122 self.accept()
Markus Armbruster6974ccd2013-07-27 17:41:58 +0200123 return expr
124 if self.tok != ',':
125 raise QAPISchemaError(self, 'Expected "," or "}"')
126 self.accept()
127 if self.tok != "'":
128 raise QAPISchemaError(self, 'Expected string')
Michael Roth0f923be2011-07-19 14:50:39 -0500129
Markus Armbrusterc7a3f252013-07-27 17:41:55 +0200130 def get_values(self):
131 expr = []
Markus Armbruster6974ccd2013-07-27 17:41:58 +0200132 if self.tok == ']':
133 self.accept()
134 return expr
135 if not self.tok in [ '{', '[', "'" ]:
136 raise QAPISchemaError(self, 'Expected "{", "[", "]" or string')
137 while True:
Markus Armbruster5f3cd2b2013-07-27 17:41:59 +0200138 expr.append(self.get_expr(True))
Markus Armbruster6974ccd2013-07-27 17:41:58 +0200139 if self.tok == ']':
Markus Armbrusterc7a3f252013-07-27 17:41:55 +0200140 self.accept()
Markus Armbruster6974ccd2013-07-27 17:41:58 +0200141 return expr
142 if self.tok != ',':
143 raise QAPISchemaError(self, 'Expected "," or "]"')
144 self.accept()
Michael Roth0f923be2011-07-19 14:50:39 -0500145
Markus Armbruster5f3cd2b2013-07-27 17:41:59 +0200146 def get_expr(self, nested):
147 if self.tok != '{' and not nested:
148 raise QAPISchemaError(self, 'Expected "{"')
Markus Armbrusterc7a3f252013-07-27 17:41:55 +0200149 if self.tok == '{':
150 self.accept()
151 expr = self.get_members()
152 elif self.tok == '[':
153 self.accept()
154 expr = self.get_values()
Markus Armbruster6974ccd2013-07-27 17:41:58 +0200155 elif self.tok == "'":
Markus Armbrusterc7a3f252013-07-27 17:41:55 +0200156 expr = self.val
157 self.accept()
Markus Armbruster6974ccd2013-07-27 17:41:58 +0200158 else:
159 raise QAPISchemaError(self, 'Expected "{", "[" or string')
Markus Armbrusterc7a3f252013-07-27 17:41:55 +0200160 return expr
Kevin Wolfbd9927f2013-07-01 16:31:50 +0200161
162def parse_schema(fp):
Markus Armbruster2caba362013-07-27 17:41:56 +0200163 try:
164 schema = QAPISchema(fp)
165 except QAPISchemaError as e:
166 print >>sys.stderr, e
167 exit(1)
168
Kevin Wolfbd9927f2013-07-01 16:31:50 +0200169 exprs = []
170
Markus Armbrusterc7a3f252013-07-27 17:41:55 +0200171 for expr_eval in schema.exprs:
Michael Roth0f923be2011-07-19 14:50:39 -0500172 if expr_eval.has_key('enum'):
173 add_enum(expr_eval['enum'])
174 elif expr_eval.has_key('union'):
Kevin Wolfea66c6d2013-07-16 10:49:41 +0200175 add_union(expr_eval)
Michael Roth0f923be2011-07-19 14:50:39 -0500176 add_enum('%sKind' % expr_eval['union'])
Kevin Wolfb35284e2013-07-01 16:31:51 +0200177 elif expr_eval.has_key('type'):
178 add_struct(expr_eval)
Michael Roth0f923be2011-07-19 14:50:39 -0500179 exprs.append(expr_eval)
180
181 return exprs
182
183def parse_args(typeinfo):
Kevin Wolfb35284e2013-07-01 16:31:51 +0200184 if isinstance(typeinfo, basestring):
185 struct = find_struct(typeinfo)
186 assert struct != None
187 typeinfo = struct['data']
188
Michael Roth0f923be2011-07-19 14:50:39 -0500189 for member in typeinfo:
190 argname = member
191 argentry = typeinfo[member]
192 optional = False
193 structured = False
194 if member.startswith('*'):
195 argname = member[1:]
196 optional = True
197 if isinstance(argentry, OrderedDict):
198 structured = True
199 yield (argname, argentry, optional, structured)
200
201def de_camel_case(name):
202 new_name = ''
203 for ch in name:
204 if ch.isupper() and new_name:
205 new_name += '_'
206 if ch == '-':
207 new_name += '_'
208 else:
209 new_name += ch.lower()
210 return new_name
211
212def camel_case(name):
213 new_name = ''
214 first = True
215 for ch in name:
216 if ch in ['_', '-']:
217 first = True
218 elif first:
219 new_name += ch.upper()
220 first = False
221 else:
222 new_name += ch.lower()
223 return new_name
224
Paolo Bonzinieda50a62012-09-19 16:31:06 +0200225def c_var(name, protect=True):
Blue Swirl427a1a22012-07-30 15:46:55 +0000226 # ANSI X3J11/88-090, 3.1.1
227 c89_words = set(['auto', 'break', 'case', 'char', 'const', 'continue',
228 'default', 'do', 'double', 'else', 'enum', 'extern', 'float',
229 'for', 'goto', 'if', 'int', 'long', 'register', 'return',
230 'short', 'signed', 'sizeof', 'static', 'struct', 'switch',
231 'typedef', 'union', 'unsigned', 'void', 'volatile', 'while'])
232 # ISO/IEC 9899:1999, 6.4.1
233 c99_words = set(['inline', 'restrict', '_Bool', '_Complex', '_Imaginary'])
234 # ISO/IEC 9899:2011, 6.4.1
235 c11_words = set(['_Alignas', '_Alignof', '_Atomic', '_Generic', '_Noreturn',
236 '_Static_assert', '_Thread_local'])
237 # GCC http://gcc.gnu.org/onlinedocs/gcc-4.7.1/gcc/C-Extensions.html
238 # excluding _.*
239 gcc_words = set(['asm', 'typeof'])
Paolo Bonzini10577252012-09-19 16:31:07 +0200240 # namespace pollution:
241 polluted_words = set(['unix'])
242 if protect and (name in c89_words | c99_words | c11_words | gcc_words | polluted_words):
Blue Swirl427a1a22012-07-30 15:46:55 +0000243 return "q_" + name
Federico Simoncellic9da2282012-03-20 13:54:35 +0000244 return name.replace('-', '_').lstrip("*")
245
Paolo Bonzinieda50a62012-09-19 16:31:06 +0200246def c_fun(name, protect=True):
247 return c_var(name, protect).replace('.', '_')
Michael Roth0f923be2011-07-19 14:50:39 -0500248
249def c_list_type(name):
250 return '%sList' % name
251
252def type_name(name):
253 if type(name) == list:
254 return c_list_type(name[0])
255 return name
256
257enum_types = []
Kevin Wolfb35284e2013-07-01 16:31:51 +0200258struct_types = []
Kevin Wolfea66c6d2013-07-16 10:49:41 +0200259union_types = []
Kevin Wolfb35284e2013-07-01 16:31:51 +0200260
261def add_struct(definition):
262 global struct_types
263 struct_types.append(definition)
264
265def find_struct(name):
266 global struct_types
267 for struct in struct_types:
268 if struct['type'] == name:
269 return struct
270 return None
Michael Roth0f923be2011-07-19 14:50:39 -0500271
Kevin Wolfea66c6d2013-07-16 10:49:41 +0200272def add_union(definition):
273 global union_types
274 union_types.append(definition)
275
276def find_union(name):
277 global union_types
278 for union in union_types:
279 if union['union'] == name:
280 return union
281 return None
282
Michael Roth0f923be2011-07-19 14:50:39 -0500283def add_enum(name):
284 global enum_types
285 enum_types.append(name)
286
287def is_enum(name):
288 global enum_types
289 return (name in enum_types)
290
291def c_type(name):
292 if name == 'str':
293 return 'char *'
294 elif name == 'int':
295 return 'int64_t'
Laszlo Ersekc46f18c2012-07-17 16:17:06 +0200296 elif (name == 'int8' or name == 'int16' or name == 'int32' or
297 name == 'int64' or name == 'uint8' or name == 'uint16' or
298 name == 'uint32' or name == 'uint64'):
299 return name + '_t'
Laszlo Ersek092705d2012-07-17 16:17:07 +0200300 elif name == 'size':
301 return 'uint64_t'
Michael Roth0f923be2011-07-19 14:50:39 -0500302 elif name == 'bool':
303 return 'bool'
304 elif name == 'number':
305 return 'double'
306 elif type(name) == list:
307 return '%s *' % c_list_type(name[0])
308 elif is_enum(name):
309 return name
310 elif name == None or len(name) == 0:
311 return 'void'
312 elif name == name.upper():
313 return '%sEvent *' % camel_case(name)
314 else:
315 return '%s *' % name
316
317def genindent(count):
318 ret = ""
319 for i in range(count):
320 ret += " "
321 return ret
322
323indent_level = 0
324
325def push_indent(indent_amount=4):
326 global indent_level
327 indent_level += indent_amount
328
329def pop_indent(indent_amount=4):
330 global indent_level
331 indent_level -= indent_amount
332
333def cgen(code, **kwds):
334 indent = genindent(indent_level)
335 lines = code.split('\n')
336 lines = map(lambda x: indent + x, lines)
337 return '\n'.join(lines) % kwds + '\n'
338
339def mcgen(code, **kwds):
340 return cgen('\n'.join(code.split('\n')[1:-1]), **kwds)
341
342def basename(filename):
343 return filename.split("/")[-1]
344
345def guardname(filename):
Michael Rothd8e1f212011-11-29 16:47:48 -0600346 guard = basename(filename).rsplit(".", 1)[0]
347 for substr in [".", " ", "-"]:
348 guard = guard.replace(substr, "_")
349 return guard.upper() + '_H'
Michael Rothc0afa9c2013-05-10 17:46:00 -0500350
351def guardstart(name):
352 return mcgen('''
353
354#ifndef %(name)s
355#define %(name)s
356
357''',
358 name=guardname(name))
359
360def guardend(name):
361 return mcgen('''
362
363#endif /* %(name)s */
364
365''',
366 name=guardname(name))