blob: 868f08b59326ef23349aaa903099458b319f90ce [file] [log] [blame]
Michael Roth0f923be2011-07-19 14:50:39 -05001#
2# QAPI helper library
3#
4# Copyright IBM, Corp. 2011
Eric Blakefe2a9302015-05-04 09:05:02 -06005# Copyright (c) 2013-2015 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#
Markus Armbruster678e48a2014-03-01 08:40:34 +010011# This work is licensed under the terms of the GNU GPL, version 2.
12# See the COPYING file in the top-level directory.
Michael Roth0f923be2011-07-19 14:50:39 -050013
Lluís Vilanovaa719a272014-05-07 20:46:15 +020014import re
Michael Roth0f923be2011-07-19 14:50:39 -050015from ordereddict import OrderedDict
Lluís Vilanova33aaad52014-05-02 15:52:35 +020016import os
Markus Armbruster2caba362013-07-27 17:41:56 +020017import sys
Michael Roth0f923be2011-07-19 14:50:39 -050018
Eric Blakeb52c4b92015-05-04 09:05:00 -060019builtin_types = {
Kevin Wolf69dd62d2013-07-08 16:14:21 +020020 'str': 'QTYPE_QSTRING',
21 'int': 'QTYPE_QINT',
22 'number': 'QTYPE_QFLOAT',
23 'bool': 'QTYPE_QBOOL',
24 'int8': 'QTYPE_QINT',
25 'int16': 'QTYPE_QINT',
26 'int32': 'QTYPE_QINT',
27 'int64': 'QTYPE_QINT',
28 'uint8': 'QTYPE_QINT',
29 'uint16': 'QTYPE_QINT',
30 'uint32': 'QTYPE_QINT',
31 'uint64': 'QTYPE_QINT',
Eric Blakecb17f792015-05-04 09:05:01 -060032 'size': 'QTYPE_QINT',
Kevin Wolf69dd62d2013-07-08 16:14:21 +020033}
34
Lluís Vilanovaa719a272014-05-07 20:46:15 +020035def error_path(parent):
36 res = ""
37 while parent:
38 res = ("In file included from %s:%d:\n" % (parent['file'],
39 parent['line'])) + res
40 parent = parent['parent']
41 return res
42
Markus Armbruster2caba362013-07-27 17:41:56 +020043class QAPISchemaError(Exception):
44 def __init__(self, schema, msg):
Lluís Vilanovaa719a272014-05-07 20:46:15 +020045 self.input_file = schema.input_file
Markus Armbruster2caba362013-07-27 17:41:56 +020046 self.msg = msg
Wenchao Xia515b9432014-03-04 18:44:33 -080047 self.col = 1
48 self.line = schema.line
49 for ch in schema.src[schema.line_pos:schema.pos]:
50 if ch == '\t':
Markus Armbruster2caba362013-07-27 17:41:56 +020051 self.col = (self.col + 7) % 8 + 1
52 else:
53 self.col += 1
Lluís Vilanovaa719a272014-05-07 20:46:15 +020054 self.info = schema.parent_info
Markus Armbruster2caba362013-07-27 17:41:56 +020055
56 def __str__(self):
Lluís Vilanovaa719a272014-05-07 20:46:15 +020057 return error_path(self.info) + \
58 "%s:%d:%d: %s" % (self.input_file, self.line, self.col, self.msg)
Markus Armbruster2caba362013-07-27 17:41:56 +020059
Wenchao Xiab86b05e2014-03-04 18:44:34 -080060class QAPIExprError(Exception):
61 def __init__(self, expr_info, msg):
Lluís Vilanovaa719a272014-05-07 20:46:15 +020062 self.info = expr_info
Wenchao Xiab86b05e2014-03-04 18:44:34 -080063 self.msg = msg
64
65 def __str__(self):
Lluís Vilanovaa719a272014-05-07 20:46:15 +020066 return error_path(self.info['parent']) + \
67 "%s:%d: %s" % (self.info['file'], self.info['line'], self.msg)
Wenchao Xiab86b05e2014-03-04 18:44:34 -080068
Markus Armbrusterc7a3f252013-07-27 17:41:55 +020069class QAPISchema:
Michael Roth0f923be2011-07-19 14:50:39 -050070
Benoît Canet24fd8482014-05-16 12:51:56 +020071 def __init__(self, fp, input_relname=None, include_hist=[],
72 previously_included=[], parent_info=None):
73 """ include_hist is a stack used to detect inclusion cycles
74 previously_included is a global state used to avoid multiple
75 inclusions of the same file"""
Lluís Vilanovaa719a272014-05-07 20:46:15 +020076 input_fname = os.path.abspath(fp.name)
77 if input_relname is None:
78 input_relname = fp.name
79 self.input_dir = os.path.dirname(input_fname)
80 self.input_file = input_relname
81 self.include_hist = include_hist + [(input_relname, input_fname)]
Benoît Canet24fd8482014-05-16 12:51:56 +020082 previously_included.append(input_fname)
Lluís Vilanovaa719a272014-05-07 20:46:15 +020083 self.parent_info = parent_info
Markus Armbrusterc7a3f252013-07-27 17:41:55 +020084 self.src = fp.read()
85 if self.src == '' or self.src[-1] != '\n':
86 self.src += '\n'
87 self.cursor = 0
Wenchao Xia515b9432014-03-04 18:44:33 -080088 self.line = 1
89 self.line_pos = 0
Markus Armbrusterc7a3f252013-07-27 17:41:55 +020090 self.exprs = []
91 self.accept()
Michael Roth0f923be2011-07-19 14:50:39 -050092
Markus Armbrusterc7a3f252013-07-27 17:41:55 +020093 while self.tok != None:
Lluís Vilanovaa719a272014-05-07 20:46:15 +020094 expr_info = {'file': input_relname, 'line': self.line, 'parent': self.parent_info}
95 expr = self.get_expr(False)
96 if isinstance(expr, dict) and "include" in expr:
97 if len(expr) != 1:
98 raise QAPIExprError(expr_info, "Invalid 'include' directive")
99 include = expr["include"]
100 if not isinstance(include, str):
101 raise QAPIExprError(expr_info,
102 'Expected a file name (string), got: %s'
103 % include)
104 include_path = os.path.join(self.input_dir, include)
Stefan Hajnoczi7ac9a9d2014-08-27 12:08:51 +0100105 for elem in self.include_hist:
106 if include_path == elem[1]:
107 raise QAPIExprError(expr_info, "Inclusion loop for %s"
108 % include)
Benoît Canet24fd8482014-05-16 12:51:56 +0200109 # skip multiple include of the same file
110 if include_path in previously_included:
111 continue
Lluís Vilanovaa719a272014-05-07 20:46:15 +0200112 try:
113 fobj = open(include_path, 'r')
Luiz Capitulino34788812014-05-20 13:50:19 -0400114 except IOError, e:
Lluís Vilanovaa719a272014-05-07 20:46:15 +0200115 raise QAPIExprError(expr_info,
116 '%s: %s' % (e.strerror, include))
Benoît Canet24fd8482014-05-16 12:51:56 +0200117 exprs_include = QAPISchema(fobj, include, self.include_hist,
118 previously_included, expr_info)
Lluís Vilanovaa719a272014-05-07 20:46:15 +0200119 self.exprs.extend(exprs_include.exprs)
120 else:
121 expr_elem = {'expr': expr,
122 'info': expr_info}
123 self.exprs.append(expr_elem)
Michael Roth0f923be2011-07-19 14:50:39 -0500124
Markus Armbrusterc7a3f252013-07-27 17:41:55 +0200125 def accept(self):
126 while True:
Markus Armbrusterc7a3f252013-07-27 17:41:55 +0200127 self.tok = self.src[self.cursor]
Markus Armbruster2caba362013-07-27 17:41:56 +0200128 self.pos = self.cursor
Markus Armbrusterc7a3f252013-07-27 17:41:55 +0200129 self.cursor += 1
130 self.val = None
Michael Roth0f923be2011-07-19 14:50:39 -0500131
Markus Armbrusterf1a145e2013-07-27 17:42:01 +0200132 if self.tok == '#':
Markus Armbrusterc7a3f252013-07-27 17:41:55 +0200133 self.cursor = self.src.find('\n', self.cursor)
134 elif self.tok in ['{', '}', ':', ',', '[', ']']:
135 return
136 elif self.tok == "'":
137 string = ''
138 esc = False
139 while True:
140 ch = self.src[self.cursor]
141 self.cursor += 1
142 if ch == '\n':
Markus Armbruster2caba362013-07-27 17:41:56 +0200143 raise QAPISchemaError(self,
144 'Missing terminating "\'"')
Markus Armbrusterc7a3f252013-07-27 17:41:55 +0200145 if esc:
146 string += ch
147 esc = False
148 elif ch == "\\":
149 esc = True
150 elif ch == "'":
151 self.val = string
152 return
153 else:
154 string += ch
155 elif self.tok == '\n':
156 if self.cursor == len(self.src):
157 self.tok = None
158 return
Wenchao Xia515b9432014-03-04 18:44:33 -0800159 self.line += 1
160 self.line_pos = self.cursor
Markus Armbruster9213aa52013-07-27 17:41:57 +0200161 elif not self.tok.isspace():
162 raise QAPISchemaError(self, 'Stray "%s"' % self.tok)
Michael Roth0f923be2011-07-19 14:50:39 -0500163
Markus Armbrusterc7a3f252013-07-27 17:41:55 +0200164 def get_members(self):
165 expr = OrderedDict()
Markus Armbruster6974ccd2013-07-27 17:41:58 +0200166 if self.tok == '}':
167 self.accept()
168 return expr
169 if self.tok != "'":
170 raise QAPISchemaError(self, 'Expected string or "}"')
171 while True:
Markus Armbrusterc7a3f252013-07-27 17:41:55 +0200172 key = self.val
173 self.accept()
Markus Armbruster6974ccd2013-07-27 17:41:58 +0200174 if self.tok != ':':
175 raise QAPISchemaError(self, 'Expected ":"')
176 self.accept()
Wenchao Xia4b359912014-03-04 18:44:32 -0800177 if key in expr:
178 raise QAPISchemaError(self, 'Duplicate key "%s"' % key)
Markus Armbruster5f3cd2b2013-07-27 17:41:59 +0200179 expr[key] = self.get_expr(True)
Markus Armbruster6974ccd2013-07-27 17:41:58 +0200180 if self.tok == '}':
Markus Armbrusterc7a3f252013-07-27 17:41:55 +0200181 self.accept()
Markus Armbruster6974ccd2013-07-27 17:41:58 +0200182 return expr
183 if self.tok != ',':
184 raise QAPISchemaError(self, 'Expected "," or "}"')
185 self.accept()
186 if self.tok != "'":
187 raise QAPISchemaError(self, 'Expected string')
Michael Roth0f923be2011-07-19 14:50:39 -0500188
Markus Armbrusterc7a3f252013-07-27 17:41:55 +0200189 def get_values(self):
190 expr = []
Markus Armbruster6974ccd2013-07-27 17:41:58 +0200191 if self.tok == ']':
192 self.accept()
193 return expr
194 if not self.tok in [ '{', '[', "'" ]:
195 raise QAPISchemaError(self, 'Expected "{", "[", "]" or string')
196 while True:
Markus Armbruster5f3cd2b2013-07-27 17:41:59 +0200197 expr.append(self.get_expr(True))
Markus Armbruster6974ccd2013-07-27 17:41:58 +0200198 if self.tok == ']':
Markus Armbrusterc7a3f252013-07-27 17:41:55 +0200199 self.accept()
Markus Armbruster6974ccd2013-07-27 17:41:58 +0200200 return expr
201 if self.tok != ',':
202 raise QAPISchemaError(self, 'Expected "," or "]"')
203 self.accept()
Michael Roth0f923be2011-07-19 14:50:39 -0500204
Markus Armbruster5f3cd2b2013-07-27 17:41:59 +0200205 def get_expr(self, nested):
206 if self.tok != '{' and not nested:
207 raise QAPISchemaError(self, 'Expected "{"')
Markus Armbrusterc7a3f252013-07-27 17:41:55 +0200208 if self.tok == '{':
209 self.accept()
210 expr = self.get_members()
211 elif self.tok == '[':
212 self.accept()
213 expr = self.get_values()
Markus Armbruster6974ccd2013-07-27 17:41:58 +0200214 elif self.tok == "'":
Markus Armbrusterc7a3f252013-07-27 17:41:55 +0200215 expr = self.val
216 self.accept()
Markus Armbruster6974ccd2013-07-27 17:41:58 +0200217 else:
218 raise QAPISchemaError(self, 'Expected "{", "[" or string')
Markus Armbrusterc7a3f252013-07-27 17:41:55 +0200219 return expr
Kevin Wolfbd9927f2013-07-01 16:31:50 +0200220
Wenchao Xiab86b05e2014-03-04 18:44:34 -0800221def find_base_fields(base):
222 base_struct_define = find_struct(base)
223 if not base_struct_define:
224 return None
225 return base_struct_define['data']
226
Eric Blake811d04f2015-05-04 09:05:10 -0600227# Return the qtype of an alternate branch, or None on error.
228def find_alternate_member_qtype(qapi_type):
Eric Blake44bd1272015-05-04 09:05:08 -0600229 if builtin_types.has_key(qapi_type):
230 return builtin_types[qapi_type]
231 elif find_struct(qapi_type):
232 return "QTYPE_QDICT"
233 elif find_enum(qapi_type):
234 return "QTYPE_QSTRING"
Eric Blake811d04f2015-05-04 09:05:10 -0600235 elif find_union(qapi_type):
236 return "QTYPE_QDICT"
Eric Blake44bd1272015-05-04 09:05:08 -0600237 return None
238
Wenchao Xiabceae762014-03-06 17:08:56 -0800239# Return the discriminator enum define if discriminator is specified as an
240# enum type, otherwise return None.
241def discriminator_find_enum_define(expr):
242 base = expr.get('base')
243 discriminator = expr.get('discriminator')
244
245 if not (discriminator and base):
246 return None
247
248 base_fields = find_base_fields(base)
249 if not base_fields:
250 return None
251
252 discriminator_type = base_fields.get(discriminator)
253 if not discriminator_type:
254 return None
255
256 return find_enum(discriminator_type)
257
Wenchao Xia21cd70d2014-06-18 08:43:28 +0200258def check_event(expr, expr_info):
259 params = expr.get('data')
260 if params:
261 for argname, argentry, optional, structured in parse_args(params):
262 if structured:
263 raise QAPIExprError(expr_info,
264 "Nested structure define in event is not "
Wenchao Xiad6f9c822014-06-24 16:33:59 -0700265 "supported, event '%s', argname '%s'"
Wenchao Xia21cd70d2014-06-18 08:43:28 +0200266 % (expr['event'], argname))
267
Wenchao Xiab86b05e2014-03-04 18:44:34 -0800268def check_union(expr, expr_info):
269 name = expr['union']
270 base = expr.get('base')
271 discriminator = expr.get('discriminator')
272 members = expr['data']
Eric Blake44bd1272015-05-04 09:05:08 -0600273 values = { 'MAX': '(automatic)' }
Wenchao Xiab86b05e2014-03-04 18:44:34 -0800274
Eric Blakea8d4a2e2015-05-04 09:05:07 -0600275 # If the object has a member 'base', its value must name a complex type,
276 # and there must be a discriminator.
277 if base is not None:
278 if discriminator is None:
279 raise QAPIExprError(expr_info,
280 "Union '%s' requires a discriminator to go "
281 "along with base" %name)
Eric Blake44bd1272015-05-04 09:05:08 -0600282
Eric Blake811d04f2015-05-04 09:05:10 -0600283 # Two types of unions, determined by discriminator.
Eric Blake811d04f2015-05-04 09:05:10 -0600284
285 # With no discriminator it is a simple union.
286 if discriminator is None:
Eric Blake44bd1272015-05-04 09:05:08 -0600287 enum_define = None
288 if base is not None:
289 raise QAPIExprError(expr_info,
Eric Blake811d04f2015-05-04 09:05:10 -0600290 "Simple union '%s' must not have a base"
Eric Blake44bd1272015-05-04 09:05:08 -0600291 % name)
292
293 # Else, it's a flat union.
294 else:
295 # The object must have a string member 'base'.
296 if not isinstance(base, str):
297 raise QAPIExprError(expr_info,
298 "Flat union '%s' must have a string base field"
299 % name)
Wenchao Xiab86b05e2014-03-04 18:44:34 -0800300 base_fields = find_base_fields(base)
301 if not base_fields:
302 raise QAPIExprError(expr_info,
303 "Base '%s' is not a valid type"
304 % base)
305
Wenchao Xiab86b05e2014-03-04 18:44:34 -0800306 # The value of member 'discriminator' must name a member of the
307 # base type.
Eric Blake44bd1272015-05-04 09:05:08 -0600308 if not isinstance(discriminator, str):
309 raise QAPIExprError(expr_info,
310 "Flat union '%s' discriminator must be a string"
311 % name)
Wenchao Xiab86b05e2014-03-04 18:44:34 -0800312 discriminator_type = base_fields.get(discriminator)
313 if not discriminator_type:
314 raise QAPIExprError(expr_info,
315 "Discriminator '%s' is not a member of base "
316 "type '%s'"
317 % (discriminator, base))
318 enum_define = find_enum(discriminator_type)
Wenchao Xia52230702014-03-04 18:44:39 -0800319 # Do not allow string discriminator
320 if not enum_define:
321 raise QAPIExprError(expr_info,
322 "Discriminator '%s' must be of enumeration "
323 "type" % discriminator)
Wenchao Xiab86b05e2014-03-04 18:44:34 -0800324
325 # Check every branch
326 for (key, value) in members.items():
Eric Blake44bd1272015-05-04 09:05:08 -0600327 # If the discriminator names an enum type, then all members
Wenchao Xiab86b05e2014-03-04 18:44:34 -0800328 # of 'data' must also be members of the enum type.
Eric Blake44bd1272015-05-04 09:05:08 -0600329 if enum_define:
330 if not key in enum_define['enum_values']:
331 raise QAPIExprError(expr_info,
332 "Discriminator value '%s' is not found in "
333 "enum '%s'" %
334 (key, enum_define["enum_name"]))
335
336 # Otherwise, check for conflicts in the generated enum
337 else:
338 c_key = _generate_enum_string(key)
339 if c_key in values:
340 raise QAPIExprError(expr_info,
341 "Union '%s' member '%s' clashes with '%s'"
342 % (name, key, values[c_key]))
343 values[c_key] = key
344
Eric Blake811d04f2015-05-04 09:05:10 -0600345def check_alternate(expr, expr_info):
Eric Blakeab916fa2015-05-04 09:05:13 -0600346 name = expr['alternate']
Eric Blake811d04f2015-05-04 09:05:10 -0600347 members = expr['data']
348 values = { 'MAX': '(automatic)' }
349 types_seen = {}
Eric Blake44bd1272015-05-04 09:05:08 -0600350
Eric Blake811d04f2015-05-04 09:05:10 -0600351 # Check every branch
352 for (key, value) in members.items():
353 # Check for conflicts in the generated enum
354 c_key = _generate_enum_string(key)
355 if c_key in values:
356 raise QAPIExprError(expr_info,
Eric Blakeab916fa2015-05-04 09:05:13 -0600357 "Alternate '%s' member '%s' clashes with '%s'"
358 % (name, key, values[c_key]))
Eric Blake811d04f2015-05-04 09:05:10 -0600359 values[c_key] = key
360
361 # Ensure alternates have no type conflicts.
362 if isinstance(value, list):
363 raise QAPIExprError(expr_info,
Eric Blakeab916fa2015-05-04 09:05:13 -0600364 "Alternate '%s' member '%s' must "
Eric Blake811d04f2015-05-04 09:05:10 -0600365 "not be array type" % (name, key))
366 qtype = find_alternate_member_qtype(value)
367 if not qtype:
368 raise QAPIExprError(expr_info,
Eric Blakeab916fa2015-05-04 09:05:13 -0600369 "Alternate '%s' member '%s' has "
Eric Blake811d04f2015-05-04 09:05:10 -0600370 "invalid type '%s'" % (name, key, value))
371 if qtype in types_seen:
372 raise QAPIExprError(expr_info,
Eric Blakeab916fa2015-05-04 09:05:13 -0600373 "Alternate '%s' member '%s' can't "
Eric Blake811d04f2015-05-04 09:05:10 -0600374 "be distinguished from member '%s'"
375 % (name, key, types_seen[qtype]))
376 types_seen[qtype] = key
Wenchao Xiab86b05e2014-03-04 18:44:34 -0800377
Eric Blakecf393592015-05-04 09:05:04 -0600378def check_enum(expr, expr_info):
379 name = expr['enum']
380 members = expr.get('data')
381 values = { 'MAX': '(automatic)' }
382
383 if not isinstance(members, list):
384 raise QAPIExprError(expr_info,
385 "Enum '%s' requires an array for 'data'" % name)
386 for member in members:
387 if not isinstance(member, str):
388 raise QAPIExprError(expr_info,
389 "Enum '%s' member '%s' is not a string"
390 % (name, member))
391 key = _generate_enum_string(member)
392 if key in values:
393 raise QAPIExprError(expr_info,
394 "Enum '%s' member '%s' clashes with '%s'"
395 % (name, member, values[key]))
396 values[key] = member
397
Wenchao Xiab86b05e2014-03-04 18:44:34 -0800398def check_exprs(schema):
399 for expr_elem in schema.exprs:
400 expr = expr_elem['expr']
Eric Blakecf393592015-05-04 09:05:04 -0600401 info = expr_elem['info']
402
403 if expr.has_key('enum'):
404 check_enum(expr, info)
405 elif expr.has_key('union'):
Eric Blakeab916fa2015-05-04 09:05:13 -0600406 check_union(expr, info)
407 elif expr.has_key('alternate'):
408 check_alternate(expr, info)
Eric Blakecf393592015-05-04 09:05:04 -0600409 elif expr.has_key('event'):
410 check_event(expr, info)
Wenchao Xiab86b05e2014-03-04 18:44:34 -0800411
Eric Blake0545f6b2015-05-04 09:05:15 -0600412def check_keys(expr_elem, meta, required, optional=[]):
413 expr = expr_elem['expr']
414 info = expr_elem['info']
415 name = expr[meta]
416 if not isinstance(name, str):
417 raise QAPIExprError(info,
418 "'%s' key must have a string value" % meta)
419 required = required + [ meta ]
420 for (key, value) in expr.items():
421 if not key in required and not key in optional:
422 raise QAPIExprError(info,
423 "Unknown key '%s' in %s '%s'"
424 % (key, meta, name))
425 for key in required:
426 if not expr.has_key(key):
427 raise QAPIExprError(info,
428 "Key '%s' is missing from %s '%s'"
429 % (key, meta, name))
430
431
Lluís Vilanova33aaad52014-05-02 15:52:35 +0200432def parse_schema(input_file):
Eric Blake268a1c52015-05-04 09:05:09 -0600433 # First pass: read entire file into memory
Markus Armbruster2caba362013-07-27 17:41:56 +0200434 try:
Lluís Vilanova33aaad52014-05-02 15:52:35 +0200435 schema = QAPISchema(open(input_file, "r"))
Lluís Vilanovaa719a272014-05-07 20:46:15 +0200436 except (QAPISchemaError, QAPIExprError), e:
Markus Armbruster2caba362013-07-27 17:41:56 +0200437 print >>sys.stderr, e
438 exit(1)
439
Kevin Wolfbd9927f2013-07-01 16:31:50 +0200440 exprs = []
441
Wenchao Xiab86b05e2014-03-04 18:44:34 -0800442 try:
Eric Blake0545f6b2015-05-04 09:05:15 -0600443 # Next pass: learn the types and check for valid expression keys. At
444 # this point, top-level 'include' has already been flattened.
Eric Blake268a1c52015-05-04 09:05:09 -0600445 for expr_elem in schema.exprs:
446 expr = expr_elem['expr']
447 if expr.has_key('enum'):
Eric Blake0545f6b2015-05-04 09:05:15 -0600448 check_keys(expr_elem, 'enum', ['data'])
449 add_enum(expr['enum'], expr['data'])
Eric Blake268a1c52015-05-04 09:05:09 -0600450 elif expr.has_key('union'):
Eric Blake0545f6b2015-05-04 09:05:15 -0600451 check_keys(expr_elem, 'union', ['data'],
452 ['base', 'discriminator'])
Eric Blake268a1c52015-05-04 09:05:09 -0600453 add_union(expr)
Eric Blake0545f6b2015-05-04 09:05:15 -0600454 elif expr.has_key('alternate'):
455 check_keys(expr_elem, 'alternate', ['data'])
Eric Blake268a1c52015-05-04 09:05:09 -0600456 elif expr.has_key('type'):
Eric Blake0545f6b2015-05-04 09:05:15 -0600457 check_keys(expr_elem, 'type', ['data'], ['base'])
Eric Blake268a1c52015-05-04 09:05:09 -0600458 add_struct(expr)
Eric Blake0545f6b2015-05-04 09:05:15 -0600459 elif expr.has_key('command'):
460 check_keys(expr_elem, 'command', [],
461 ['data', 'returns', 'gen', 'success-response'])
462 elif expr.has_key('event'):
463 check_keys(expr_elem, 'event', [], ['data'])
464 else:
465 raise QAPIExprError(expr_elem['info'],
466 "Expression is missing metatype")
Eric Blake268a1c52015-05-04 09:05:09 -0600467 exprs.append(expr)
468
469 # Try again for hidden UnionKind enum
470 for expr_elem in schema.exprs:
471 expr = expr_elem['expr']
472 if expr.has_key('union'):
473 if not discriminator_find_enum_define(expr):
474 add_enum('%sKind' % expr['union'])
Eric Blakeab916fa2015-05-04 09:05:13 -0600475 elif expr.has_key('alternate'):
476 add_enum('%sKind' % expr['alternate'])
Eric Blake268a1c52015-05-04 09:05:09 -0600477
478 # Final pass - validate that exprs make sense
Wenchao Xiab86b05e2014-03-04 18:44:34 -0800479 check_exprs(schema)
480 except QAPIExprError, e:
481 print >>sys.stderr, e
482 exit(1)
483
Michael Roth0f923be2011-07-19 14:50:39 -0500484 return exprs
485
486def parse_args(typeinfo):
Eric Blakefe2a9302015-05-04 09:05:02 -0600487 if isinstance(typeinfo, str):
Kevin Wolfb35284e2013-07-01 16:31:51 +0200488 struct = find_struct(typeinfo)
489 assert struct != None
490 typeinfo = struct['data']
491
Michael Roth0f923be2011-07-19 14:50:39 -0500492 for member in typeinfo:
493 argname = member
494 argentry = typeinfo[member]
495 optional = False
496 structured = False
497 if member.startswith('*'):
498 argname = member[1:]
499 optional = True
500 if isinstance(argentry, OrderedDict):
501 structured = True
502 yield (argname, argentry, optional, structured)
503
504def de_camel_case(name):
505 new_name = ''
506 for ch in name:
507 if ch.isupper() and new_name:
508 new_name += '_'
509 if ch == '-':
510 new_name += '_'
511 else:
512 new_name += ch.lower()
513 return new_name
514
515def camel_case(name):
516 new_name = ''
517 first = True
518 for ch in name:
519 if ch in ['_', '-']:
520 first = True
521 elif first:
522 new_name += ch.upper()
523 first = False
524 else:
525 new_name += ch.lower()
526 return new_name
527
Paolo Bonzinieda50a62012-09-19 16:31:06 +0200528def c_var(name, protect=True):
Blue Swirl427a1a22012-07-30 15:46:55 +0000529 # ANSI X3J11/88-090, 3.1.1
530 c89_words = set(['auto', 'break', 'case', 'char', 'const', 'continue',
531 'default', 'do', 'double', 'else', 'enum', 'extern', 'float',
532 'for', 'goto', 'if', 'int', 'long', 'register', 'return',
533 'short', 'signed', 'sizeof', 'static', 'struct', 'switch',
534 'typedef', 'union', 'unsigned', 'void', 'volatile', 'while'])
535 # ISO/IEC 9899:1999, 6.4.1
536 c99_words = set(['inline', 'restrict', '_Bool', '_Complex', '_Imaginary'])
537 # ISO/IEC 9899:2011, 6.4.1
538 c11_words = set(['_Alignas', '_Alignof', '_Atomic', '_Generic', '_Noreturn',
539 '_Static_assert', '_Thread_local'])
540 # GCC http://gcc.gnu.org/onlinedocs/gcc-4.7.1/gcc/C-Extensions.html
541 # excluding _.*
542 gcc_words = set(['asm', 'typeof'])
Tomoki Sekiyama6f880092013-08-07 11:39:43 -0400543 # C++ ISO/IEC 14882:2003 2.11
544 cpp_words = set(['bool', 'catch', 'class', 'const_cast', 'delete',
545 'dynamic_cast', 'explicit', 'false', 'friend', 'mutable',
546 'namespace', 'new', 'operator', 'private', 'protected',
547 'public', 'reinterpret_cast', 'static_cast', 'template',
548 'this', 'throw', 'true', 'try', 'typeid', 'typename',
549 'using', 'virtual', 'wchar_t',
550 # alternative representations
551 'and', 'and_eq', 'bitand', 'bitor', 'compl', 'not',
552 'not_eq', 'or', 'or_eq', 'xor', 'xor_eq'])
Paolo Bonzini10577252012-09-19 16:31:07 +0200553 # namespace pollution:
Max Reitz8592a542013-12-20 19:28:18 +0100554 polluted_words = set(['unix', 'errno'])
Tomoki Sekiyama6f880092013-08-07 11:39:43 -0400555 if protect and (name in c89_words | c99_words | c11_words | gcc_words | cpp_words | polluted_words):
Blue Swirl427a1a22012-07-30 15:46:55 +0000556 return "q_" + name
Federico Simoncellic9da2282012-03-20 13:54:35 +0000557 return name.replace('-', '_').lstrip("*")
558
Paolo Bonzinieda50a62012-09-19 16:31:06 +0200559def c_fun(name, protect=True):
560 return c_var(name, protect).replace('.', '_')
Michael Roth0f923be2011-07-19 14:50:39 -0500561
562def c_list_type(name):
563 return '%sList' % name
564
565def type_name(name):
566 if type(name) == list:
567 return c_list_type(name[0])
568 return name
569
570enum_types = []
Kevin Wolfb35284e2013-07-01 16:31:51 +0200571struct_types = []
Kevin Wolfea66c6d2013-07-16 10:49:41 +0200572union_types = []
Kevin Wolfb35284e2013-07-01 16:31:51 +0200573
574def add_struct(definition):
575 global struct_types
576 struct_types.append(definition)
577
578def find_struct(name):
579 global struct_types
580 for struct in struct_types:
581 if struct['type'] == name:
582 return struct
583 return None
Michael Roth0f923be2011-07-19 14:50:39 -0500584
Kevin Wolfea66c6d2013-07-16 10:49:41 +0200585def add_union(definition):
586 global union_types
Eric Blakeab916fa2015-05-04 09:05:13 -0600587 union_types.append(definition)
Kevin Wolfea66c6d2013-07-16 10:49:41 +0200588
589def find_union(name):
590 global union_types
591 for union in union_types:
592 if union['union'] == name:
593 return union
594 return None
595
Wenchao Xiadad1fca2014-03-04 18:44:31 -0800596def add_enum(name, enum_values = None):
Michael Roth0f923be2011-07-19 14:50:39 -0500597 global enum_types
Wenchao Xiadad1fca2014-03-04 18:44:31 -0800598 enum_types.append({"enum_name": name, "enum_values": enum_values})
599
600def find_enum(name):
601 global enum_types
602 for enum in enum_types:
603 if enum['enum_name'] == name:
604 return enum
605 return None
Michael Roth0f923be2011-07-19 14:50:39 -0500606
607def is_enum(name):
Wenchao Xiadad1fca2014-03-04 18:44:31 -0800608 return find_enum(name) != None
Michael Roth0f923be2011-07-19 14:50:39 -0500609
Amos Kong05dfb262014-06-10 19:25:53 +0800610eatspace = '\033EATSPACE.'
611
612# A special suffix is added in c_type() for pointer types, and it's
613# stripped in mcgen(). So please notice this when you check the return
614# value of c_type() outside mcgen().
Amos Kong0d14eeb2014-06-10 19:25:52 +0800615def c_type(name, is_param=False):
Michael Roth0f923be2011-07-19 14:50:39 -0500616 if name == 'str':
Amos Kong0d14eeb2014-06-10 19:25:52 +0800617 if is_param:
Amos Kong05dfb262014-06-10 19:25:53 +0800618 return 'const char *' + eatspace
619 return 'char *' + eatspace
620
Michael Roth0f923be2011-07-19 14:50:39 -0500621 elif name == 'int':
622 return 'int64_t'
Laszlo Ersekc46f18c2012-07-17 16:17:06 +0200623 elif (name == 'int8' or name == 'int16' or name == 'int32' or
624 name == 'int64' or name == 'uint8' or name == 'uint16' or
625 name == 'uint32' or name == 'uint64'):
626 return name + '_t'
Laszlo Ersek092705d2012-07-17 16:17:07 +0200627 elif name == 'size':
628 return 'uint64_t'
Michael Roth0f923be2011-07-19 14:50:39 -0500629 elif name == 'bool':
630 return 'bool'
631 elif name == 'number':
632 return 'double'
633 elif type(name) == list:
Amos Kong05dfb262014-06-10 19:25:53 +0800634 return '%s *%s' % (c_list_type(name[0]), eatspace)
Michael Roth0f923be2011-07-19 14:50:39 -0500635 elif is_enum(name):
636 return name
637 elif name == None or len(name) == 0:
638 return 'void'
639 elif name == name.upper():
Amos Kong05dfb262014-06-10 19:25:53 +0800640 return '%sEvent *%s' % (camel_case(name), eatspace)
Michael Roth0f923be2011-07-19 14:50:39 -0500641 else:
Amos Kong05dfb262014-06-10 19:25:53 +0800642 return '%s *%s' % (name, eatspace)
643
644def is_c_ptr(name):
645 suffix = "*" + eatspace
646 return c_type(name).endswith(suffix)
Michael Roth0f923be2011-07-19 14:50:39 -0500647
648def genindent(count):
649 ret = ""
650 for i in range(count):
651 ret += " "
652 return ret
653
654indent_level = 0
655
656def push_indent(indent_amount=4):
657 global indent_level
658 indent_level += indent_amount
659
660def pop_indent(indent_amount=4):
661 global indent_level
662 indent_level -= indent_amount
663
664def cgen(code, **kwds):
665 indent = genindent(indent_level)
666 lines = code.split('\n')
667 lines = map(lambda x: indent + x, lines)
668 return '\n'.join(lines) % kwds + '\n'
669
670def mcgen(code, **kwds):
Amos Kong05dfb262014-06-10 19:25:53 +0800671 raw = cgen('\n'.join(code.split('\n')[1:-1]), **kwds)
672 return re.sub(re.escape(eatspace) + ' *', '', raw)
Michael Roth0f923be2011-07-19 14:50:39 -0500673
674def basename(filename):
675 return filename.split("/")[-1]
676
677def guardname(filename):
Michael Rothd8e1f212011-11-29 16:47:48 -0600678 guard = basename(filename).rsplit(".", 1)[0]
679 for substr in [".", " ", "-"]:
680 guard = guard.replace(substr, "_")
681 return guard.upper() + '_H'
Michael Rothc0afa9c2013-05-10 17:46:00 -0500682
683def guardstart(name):
684 return mcgen('''
685
686#ifndef %(name)s
687#define %(name)s
688
689''',
690 name=guardname(name))
691
692def guardend(name):
693 return mcgen('''
694
695#endif /* %(name)s */
696
697''',
698 name=guardname(name))
Wenchao Xia62996592014-03-04 18:44:35 -0800699
Wenchao Xia5d371f42014-03-04 18:44:40 -0800700# ENUMName -> ENUM_NAME, EnumName1 -> ENUM_NAME1
701# ENUM_NAME -> ENUM_NAME, ENUM_NAME1 -> ENUM_NAME1, ENUM_Name2 -> ENUM_NAME2
702# ENUM24_Name -> ENUM24_NAME
703def _generate_enum_string(value):
704 c_fun_str = c_fun(value, False)
Wenchao Xiab0b58192014-03-04 18:44:36 -0800705 if value.isupper():
Wenchao Xia5d371f42014-03-04 18:44:40 -0800706 return c_fun_str
707
Wenchao Xia62996592014-03-04 18:44:35 -0800708 new_name = ''
Wenchao Xia5d371f42014-03-04 18:44:40 -0800709 l = len(c_fun_str)
710 for i in range(l):
711 c = c_fun_str[i]
712 # When c is upper and no "_" appears before, do more checks
713 if c.isupper() and (i > 0) and c_fun_str[i - 1] != "_":
714 # Case 1: next string is lower
715 # Case 2: previous string is digit
716 if (i < (l - 1) and c_fun_str[i + 1].islower()) or \
717 c_fun_str[i - 1].isdigit():
718 new_name += '_'
Wenchao Xia62996592014-03-04 18:44:35 -0800719 new_name += c
720 return new_name.lstrip('_').upper()
Wenchao Xiab0b58192014-03-04 18:44:36 -0800721
722def generate_enum_full_value(enum_name, enum_value):
Wenchao Xia5d371f42014-03-04 18:44:40 -0800723 abbrev_string = _generate_enum_string(enum_name)
724 value_string = _generate_enum_string(enum_value)
Wenchao Xiab0b58192014-03-04 18:44:36 -0800725 return "%s_%s" % (abbrev_string, value_string)