blob: 3a54c7fc7c54ca7d491d43e2feada5121e5769d0 [file] [log] [blame]
Michael Roth0f923be2011-07-19 14:50:39 -05001#
2# QAPI helper library
3#
4# Copyright IBM, Corp. 2011
5#
6# Authors:
7# Anthony Liguori <aliguori@us.ibm.com>
8#
9# This work is licensed under the terms of the GNU GPLv2.
10# See the COPYING.LIB file in the top-level directory.
11
12from ordereddict import OrderedDict
13
Michael Rothc0afa9c2013-05-10 17:46:00 -050014builtin_types = [
15 'str', 'int', 'number', 'bool',
16 'int8', 'int16', 'int32', 'int64',
17 'uint8', 'uint16', 'uint32', 'uint64'
18]
19
Michael Roth0f923be2011-07-19 14:50:39 -050020def tokenize(data):
21 while len(data):
Luiz Capitulinoe0d45df2012-06-29 20:53:37 -030022 ch = data[0]
23 data = data[1:]
24 if ch in ['{', '}', ':', ',', '[', ']']:
25 yield ch
26 elif ch in ' \n':
27 None
28 elif ch == "'":
Michael Roth0f923be2011-07-19 14:50:39 -050029 string = ''
Luiz Capitulinoe0d45df2012-06-29 20:53:37 -030030 esc = False
31 while True:
32 if (data == ''):
33 raise Exception("Mismatched quotes")
34 ch = data[0]
Michael Roth0f923be2011-07-19 14:50:39 -050035 data = data[1:]
Luiz Capitulinoe0d45df2012-06-29 20:53:37 -030036 if esc:
37 string += ch
38 esc = False
39 elif ch == "\\":
40 esc = True
41 elif ch == "'":
42 break
43 else:
44 string += ch
Michael Roth0f923be2011-07-19 14:50:39 -050045 yield string
46
47def parse(tokens):
48 if tokens[0] == '{':
49 ret = OrderedDict()
50 tokens = tokens[1:]
51 while tokens[0] != '}':
52 key = tokens[0]
53 tokens = tokens[1:]
54
55 tokens = tokens[1:] # :
56
57 value, tokens = parse(tokens)
58
59 if tokens[0] == ',':
60 tokens = tokens[1:]
61
62 ret[key] = value
63 tokens = tokens[1:]
64 return ret, tokens
65 elif tokens[0] == '[':
66 ret = []
67 tokens = tokens[1:]
68 while tokens[0] != ']':
69 value, tokens = parse(tokens)
70 if tokens[0] == ',':
71 tokens = tokens[1:]
72 ret.append(value)
73 tokens = tokens[1:]
74 return ret, tokens
75 else:
76 return tokens[0], tokens[1:]
77
78def evaluate(string):
79 return parse(map(lambda x: x, tokenize(string)))[0]
80
Kevin Wolfbd9927f2013-07-01 16:31:50 +020081def get_expr(fp):
Michael Roth0f923be2011-07-19 14:50:39 -050082 expr = ''
Michael Roth0f923be2011-07-19 14:50:39 -050083
84 for line in fp:
85 if line.startswith('#') or line == '\n':
86 continue
87
88 if line.startswith(' '):
89 expr += line
90 elif expr:
Kevin Wolfbd9927f2013-07-01 16:31:50 +020091 yield expr
Michael Roth0f923be2011-07-19 14:50:39 -050092 expr = line
93 else:
94 expr += line
95
96 if expr:
Kevin Wolfbd9927f2013-07-01 16:31:50 +020097 yield expr
98
99def parse_schema(fp):
100 exprs = []
101
102 for expr in get_expr(fp):
Michael Roth0f923be2011-07-19 14:50:39 -0500103 expr_eval = evaluate(expr)
Kevin Wolfbd9927f2013-07-01 16:31:50 +0200104
Michael Roth0f923be2011-07-19 14:50:39 -0500105 if expr_eval.has_key('enum'):
106 add_enum(expr_eval['enum'])
107 elif expr_eval.has_key('union'):
Kevin Wolfea66c6d2013-07-16 10:49:41 +0200108 add_union(expr_eval)
Michael Roth0f923be2011-07-19 14:50:39 -0500109 add_enum('%sKind' % expr_eval['union'])
Kevin Wolfb35284e2013-07-01 16:31:51 +0200110 elif expr_eval.has_key('type'):
111 add_struct(expr_eval)
Michael Roth0f923be2011-07-19 14:50:39 -0500112 exprs.append(expr_eval)
113
114 return exprs
115
116def parse_args(typeinfo):
Kevin Wolfb35284e2013-07-01 16:31:51 +0200117 if isinstance(typeinfo, basestring):
118 struct = find_struct(typeinfo)
119 assert struct != None
120 typeinfo = struct['data']
121
Michael Roth0f923be2011-07-19 14:50:39 -0500122 for member in typeinfo:
123 argname = member
124 argentry = typeinfo[member]
125 optional = False
126 structured = False
127 if member.startswith('*'):
128 argname = member[1:]
129 optional = True
130 if isinstance(argentry, OrderedDict):
131 structured = True
132 yield (argname, argentry, optional, structured)
133
134def de_camel_case(name):
135 new_name = ''
136 for ch in name:
137 if ch.isupper() and new_name:
138 new_name += '_'
139 if ch == '-':
140 new_name += '_'
141 else:
142 new_name += ch.lower()
143 return new_name
144
145def camel_case(name):
146 new_name = ''
147 first = True
148 for ch in name:
149 if ch in ['_', '-']:
150 first = True
151 elif first:
152 new_name += ch.upper()
153 first = False
154 else:
155 new_name += ch.lower()
156 return new_name
157
Paolo Bonzinieda50a62012-09-19 16:31:06 +0200158def c_var(name, protect=True):
Blue Swirl427a1a22012-07-30 15:46:55 +0000159 # ANSI X3J11/88-090, 3.1.1
160 c89_words = set(['auto', 'break', 'case', 'char', 'const', 'continue',
161 'default', 'do', 'double', 'else', 'enum', 'extern', 'float',
162 'for', 'goto', 'if', 'int', 'long', 'register', 'return',
163 'short', 'signed', 'sizeof', 'static', 'struct', 'switch',
164 'typedef', 'union', 'unsigned', 'void', 'volatile', 'while'])
165 # ISO/IEC 9899:1999, 6.4.1
166 c99_words = set(['inline', 'restrict', '_Bool', '_Complex', '_Imaginary'])
167 # ISO/IEC 9899:2011, 6.4.1
168 c11_words = set(['_Alignas', '_Alignof', '_Atomic', '_Generic', '_Noreturn',
169 '_Static_assert', '_Thread_local'])
170 # GCC http://gcc.gnu.org/onlinedocs/gcc-4.7.1/gcc/C-Extensions.html
171 # excluding _.*
172 gcc_words = set(['asm', 'typeof'])
Paolo Bonzini10577252012-09-19 16:31:07 +0200173 # namespace pollution:
174 polluted_words = set(['unix'])
175 if protect and (name in c89_words | c99_words | c11_words | gcc_words | polluted_words):
Blue Swirl427a1a22012-07-30 15:46:55 +0000176 return "q_" + name
Federico Simoncellic9da2282012-03-20 13:54:35 +0000177 return name.replace('-', '_').lstrip("*")
178
Paolo Bonzinieda50a62012-09-19 16:31:06 +0200179def c_fun(name, protect=True):
180 return c_var(name, protect).replace('.', '_')
Michael Roth0f923be2011-07-19 14:50:39 -0500181
182def c_list_type(name):
183 return '%sList' % name
184
185def type_name(name):
186 if type(name) == list:
187 return c_list_type(name[0])
188 return name
189
190enum_types = []
Kevin Wolfb35284e2013-07-01 16:31:51 +0200191struct_types = []
Kevin Wolfea66c6d2013-07-16 10:49:41 +0200192union_types = []
Kevin Wolfb35284e2013-07-01 16:31:51 +0200193
194def add_struct(definition):
195 global struct_types
196 struct_types.append(definition)
197
198def find_struct(name):
199 global struct_types
200 for struct in struct_types:
201 if struct['type'] == name:
202 return struct
203 return None
Michael Roth0f923be2011-07-19 14:50:39 -0500204
Kevin Wolfea66c6d2013-07-16 10:49:41 +0200205def add_union(definition):
206 global union_types
207 union_types.append(definition)
208
209def find_union(name):
210 global union_types
211 for union in union_types:
212 if union['union'] == name:
213 return union
214 return None
215
Michael Roth0f923be2011-07-19 14:50:39 -0500216def add_enum(name):
217 global enum_types
218 enum_types.append(name)
219
220def is_enum(name):
221 global enum_types
222 return (name in enum_types)
223
224def c_type(name):
225 if name == 'str':
226 return 'char *'
227 elif name == 'int':
228 return 'int64_t'
Laszlo Ersekc46f18c2012-07-17 16:17:06 +0200229 elif (name == 'int8' or name == 'int16' or name == 'int32' or
230 name == 'int64' or name == 'uint8' or name == 'uint16' or
231 name == 'uint32' or name == 'uint64'):
232 return name + '_t'
Laszlo Ersek092705d2012-07-17 16:17:07 +0200233 elif name == 'size':
234 return 'uint64_t'
Michael Roth0f923be2011-07-19 14:50:39 -0500235 elif name == 'bool':
236 return 'bool'
237 elif name == 'number':
238 return 'double'
239 elif type(name) == list:
240 return '%s *' % c_list_type(name[0])
241 elif is_enum(name):
242 return name
243 elif name == None or len(name) == 0:
244 return 'void'
245 elif name == name.upper():
246 return '%sEvent *' % camel_case(name)
247 else:
248 return '%s *' % name
249
250def genindent(count):
251 ret = ""
252 for i in range(count):
253 ret += " "
254 return ret
255
256indent_level = 0
257
258def push_indent(indent_amount=4):
259 global indent_level
260 indent_level += indent_amount
261
262def pop_indent(indent_amount=4):
263 global indent_level
264 indent_level -= indent_amount
265
266def cgen(code, **kwds):
267 indent = genindent(indent_level)
268 lines = code.split('\n')
269 lines = map(lambda x: indent + x, lines)
270 return '\n'.join(lines) % kwds + '\n'
271
272def mcgen(code, **kwds):
273 return cgen('\n'.join(code.split('\n')[1:-1]), **kwds)
274
275def basename(filename):
276 return filename.split("/")[-1]
277
278def guardname(filename):
Michael Rothd8e1f212011-11-29 16:47:48 -0600279 guard = basename(filename).rsplit(".", 1)[0]
280 for substr in [".", " ", "-"]:
281 guard = guard.replace(substr, "_")
282 return guard.upper() + '_H'
Michael Rothc0afa9c2013-05-10 17:46:00 -0500283
284def guardstart(name):
285 return mcgen('''
286
287#ifndef %(name)s
288#define %(name)s
289
290''',
291 name=guardname(name))
292
293def guardend(name):
294 return mcgen('''
295
296#endif /* %(name)s */
297
298''',
299 name=guardname(name))