blob: e391b5a649a670fb67d9520d22f6d64db16c2197 [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
Eric Blake10d4d992015-05-04 09:05:23 -060035# Whitelist of commands allowed to return a non-dictionary
36returns_whitelist = [
37 # From QMP:
38 'human-monitor-command',
39 'query-migrate-cache-size',
40 'query-tpm-models',
41 'query-tpm-types',
42 'ringbuf-read',
43
44 # From QGA:
45 'guest-file-open',
46 'guest-fsfreeze-freeze',
47 'guest-fsfreeze-freeze-list',
48 'guest-fsfreeze-status',
49 'guest-fsfreeze-thaw',
50 'guest-get-time',
51 'guest-set-vcpus',
52 'guest-sync',
53 'guest-sync-delimited',
54
55 # From qapi-schema-test:
56 'user_def_cmd3',
57]
58
Eric Blake4dc2e692015-05-04 09:05:17 -060059enum_types = []
60struct_types = []
61union_types = []
62events = []
63all_names = {}
64
Lluís Vilanovaa719a272014-05-07 20:46:15 +020065def error_path(parent):
66 res = ""
67 while parent:
68 res = ("In file included from %s:%d:\n" % (parent['file'],
69 parent['line'])) + res
70 parent = parent['parent']
71 return res
72
Markus Armbruster2caba362013-07-27 17:41:56 +020073class QAPISchemaError(Exception):
74 def __init__(self, schema, msg):
Lluís Vilanovaa719a272014-05-07 20:46:15 +020075 self.input_file = schema.input_file
Markus Armbruster2caba362013-07-27 17:41:56 +020076 self.msg = msg
Wenchao Xia515b9432014-03-04 18:44:33 -080077 self.col = 1
78 self.line = schema.line
79 for ch in schema.src[schema.line_pos:schema.pos]:
80 if ch == '\t':
Markus Armbruster2caba362013-07-27 17:41:56 +020081 self.col = (self.col + 7) % 8 + 1
82 else:
83 self.col += 1
Lluís Vilanovaa719a272014-05-07 20:46:15 +020084 self.info = schema.parent_info
Markus Armbruster2caba362013-07-27 17:41:56 +020085
86 def __str__(self):
Lluís Vilanovaa719a272014-05-07 20:46:15 +020087 return error_path(self.info) + \
88 "%s:%d:%d: %s" % (self.input_file, self.line, self.col, self.msg)
Markus Armbruster2caba362013-07-27 17:41:56 +020089
Wenchao Xiab86b05e2014-03-04 18:44:34 -080090class QAPIExprError(Exception):
91 def __init__(self, expr_info, msg):
Lluís Vilanovaa719a272014-05-07 20:46:15 +020092 self.info = expr_info
Wenchao Xiab86b05e2014-03-04 18:44:34 -080093 self.msg = msg
94
95 def __str__(self):
Lluís Vilanovaa719a272014-05-07 20:46:15 +020096 return error_path(self.info['parent']) + \
97 "%s:%d: %s" % (self.info['file'], self.info['line'], self.msg)
Wenchao Xiab86b05e2014-03-04 18:44:34 -080098
Markus Armbrusterc7a3f252013-07-27 17:41:55 +020099class QAPISchema:
Michael Roth0f923be2011-07-19 14:50:39 -0500100
Benoît Canet24fd8482014-05-16 12:51:56 +0200101 def __init__(self, fp, input_relname=None, include_hist=[],
102 previously_included=[], parent_info=None):
103 """ include_hist is a stack used to detect inclusion cycles
104 previously_included is a global state used to avoid multiple
105 inclusions of the same file"""
Lluís Vilanovaa719a272014-05-07 20:46:15 +0200106 input_fname = os.path.abspath(fp.name)
107 if input_relname is None:
108 input_relname = fp.name
109 self.input_dir = os.path.dirname(input_fname)
110 self.input_file = input_relname
111 self.include_hist = include_hist + [(input_relname, input_fname)]
Benoît Canet24fd8482014-05-16 12:51:56 +0200112 previously_included.append(input_fname)
Lluís Vilanovaa719a272014-05-07 20:46:15 +0200113 self.parent_info = parent_info
Markus Armbrusterc7a3f252013-07-27 17:41:55 +0200114 self.src = fp.read()
115 if self.src == '' or self.src[-1] != '\n':
116 self.src += '\n'
117 self.cursor = 0
Wenchao Xia515b9432014-03-04 18:44:33 -0800118 self.line = 1
119 self.line_pos = 0
Markus Armbrusterc7a3f252013-07-27 17:41:55 +0200120 self.exprs = []
121 self.accept()
Michael Roth0f923be2011-07-19 14:50:39 -0500122
Markus Armbrusterc7a3f252013-07-27 17:41:55 +0200123 while self.tok != None:
Lluís Vilanovaa719a272014-05-07 20:46:15 +0200124 expr_info = {'file': input_relname, 'line': self.line, 'parent': self.parent_info}
125 expr = self.get_expr(False)
126 if isinstance(expr, dict) and "include" in expr:
127 if len(expr) != 1:
128 raise QAPIExprError(expr_info, "Invalid 'include' directive")
129 include = expr["include"]
130 if not isinstance(include, str):
131 raise QAPIExprError(expr_info,
132 'Expected a file name (string), got: %s'
133 % include)
134 include_path = os.path.join(self.input_dir, include)
Stefan Hajnoczi7ac9a9d2014-08-27 12:08:51 +0100135 for elem in self.include_hist:
136 if include_path == elem[1]:
137 raise QAPIExprError(expr_info, "Inclusion loop for %s"
138 % include)
Benoît Canet24fd8482014-05-16 12:51:56 +0200139 # skip multiple include of the same file
140 if include_path in previously_included:
141 continue
Lluís Vilanovaa719a272014-05-07 20:46:15 +0200142 try:
143 fobj = open(include_path, 'r')
Luiz Capitulino34788812014-05-20 13:50:19 -0400144 except IOError, e:
Lluís Vilanovaa719a272014-05-07 20:46:15 +0200145 raise QAPIExprError(expr_info,
146 '%s: %s' % (e.strerror, include))
Benoît Canet24fd8482014-05-16 12:51:56 +0200147 exprs_include = QAPISchema(fobj, include, self.include_hist,
148 previously_included, expr_info)
Lluís Vilanovaa719a272014-05-07 20:46:15 +0200149 self.exprs.extend(exprs_include.exprs)
150 else:
151 expr_elem = {'expr': expr,
152 'info': expr_info}
153 self.exprs.append(expr_elem)
Michael Roth0f923be2011-07-19 14:50:39 -0500154
Markus Armbrusterc7a3f252013-07-27 17:41:55 +0200155 def accept(self):
156 while True:
Markus Armbrusterc7a3f252013-07-27 17:41:55 +0200157 self.tok = self.src[self.cursor]
Markus Armbruster2caba362013-07-27 17:41:56 +0200158 self.pos = self.cursor
Markus Armbrusterc7a3f252013-07-27 17:41:55 +0200159 self.cursor += 1
160 self.val = None
Michael Roth0f923be2011-07-19 14:50:39 -0500161
Markus Armbrusterf1a145e2013-07-27 17:42:01 +0200162 if self.tok == '#':
Markus Armbrusterc7a3f252013-07-27 17:41:55 +0200163 self.cursor = self.src.find('\n', self.cursor)
164 elif self.tok in ['{', '}', ':', ',', '[', ']']:
165 return
166 elif self.tok == "'":
167 string = ''
168 esc = False
169 while True:
170 ch = self.src[self.cursor]
171 self.cursor += 1
172 if ch == '\n':
Markus Armbruster2caba362013-07-27 17:41:56 +0200173 raise QAPISchemaError(self,
174 'Missing terminating "\'"')
Markus Armbrusterc7a3f252013-07-27 17:41:55 +0200175 if esc:
176 string += ch
177 esc = False
178 elif ch == "\\":
179 esc = True
180 elif ch == "'":
181 self.val = string
182 return
183 else:
184 string += ch
Fam Zhenge53188a2015-05-04 09:05:18 -0600185 elif self.tok in "tfn":
186 val = self.src[self.cursor - 1:]
187 if val.startswith("true"):
188 self.val = True
189 self.cursor += 3
190 return
191 elif val.startswith("false"):
192 self.val = False
193 self.cursor += 4
194 return
195 elif val.startswith("null"):
196 self.val = None
197 self.cursor += 3
198 return
Markus Armbrusterc7a3f252013-07-27 17:41:55 +0200199 elif self.tok == '\n':
200 if self.cursor == len(self.src):
201 self.tok = None
202 return
Wenchao Xia515b9432014-03-04 18:44:33 -0800203 self.line += 1
204 self.line_pos = self.cursor
Markus Armbruster9213aa52013-07-27 17:41:57 +0200205 elif not self.tok.isspace():
206 raise QAPISchemaError(self, 'Stray "%s"' % self.tok)
Michael Roth0f923be2011-07-19 14:50:39 -0500207
Markus Armbrusterc7a3f252013-07-27 17:41:55 +0200208 def get_members(self):
209 expr = OrderedDict()
Markus Armbruster6974ccd2013-07-27 17:41:58 +0200210 if self.tok == '}':
211 self.accept()
212 return expr
213 if self.tok != "'":
214 raise QAPISchemaError(self, 'Expected string or "}"')
215 while True:
Markus Armbrusterc7a3f252013-07-27 17:41:55 +0200216 key = self.val
217 self.accept()
Markus Armbruster6974ccd2013-07-27 17:41:58 +0200218 if self.tok != ':':
219 raise QAPISchemaError(self, 'Expected ":"')
220 self.accept()
Wenchao Xia4b359912014-03-04 18:44:32 -0800221 if key in expr:
222 raise QAPISchemaError(self, 'Duplicate key "%s"' % key)
Markus Armbruster5f3cd2b2013-07-27 17:41:59 +0200223 expr[key] = self.get_expr(True)
Markus Armbruster6974ccd2013-07-27 17:41:58 +0200224 if self.tok == '}':
Markus Armbrusterc7a3f252013-07-27 17:41:55 +0200225 self.accept()
Markus Armbruster6974ccd2013-07-27 17:41:58 +0200226 return expr
227 if self.tok != ',':
228 raise QAPISchemaError(self, 'Expected "," or "}"')
229 self.accept()
230 if self.tok != "'":
231 raise QAPISchemaError(self, 'Expected string')
Michael Roth0f923be2011-07-19 14:50:39 -0500232
Markus Armbrusterc7a3f252013-07-27 17:41:55 +0200233 def get_values(self):
234 expr = []
Markus Armbruster6974ccd2013-07-27 17:41:58 +0200235 if self.tok == ']':
236 self.accept()
237 return expr
Fam Zhenge53188a2015-05-04 09:05:18 -0600238 if not self.tok in "{['tfn":
239 raise QAPISchemaError(self, 'Expected "{", "[", "]", string, '
240 'boolean or "null"')
Markus Armbruster6974ccd2013-07-27 17:41:58 +0200241 while True:
Markus Armbruster5f3cd2b2013-07-27 17:41:59 +0200242 expr.append(self.get_expr(True))
Markus Armbruster6974ccd2013-07-27 17:41:58 +0200243 if self.tok == ']':
Markus Armbrusterc7a3f252013-07-27 17:41:55 +0200244 self.accept()
Markus Armbruster6974ccd2013-07-27 17:41:58 +0200245 return expr
246 if self.tok != ',':
247 raise QAPISchemaError(self, 'Expected "," or "]"')
248 self.accept()
Michael Roth0f923be2011-07-19 14:50:39 -0500249
Markus Armbruster5f3cd2b2013-07-27 17:41:59 +0200250 def get_expr(self, nested):
251 if self.tok != '{' and not nested:
252 raise QAPISchemaError(self, 'Expected "{"')
Markus Armbrusterc7a3f252013-07-27 17:41:55 +0200253 if self.tok == '{':
254 self.accept()
255 expr = self.get_members()
256 elif self.tok == '[':
257 self.accept()
258 expr = self.get_values()
Fam Zhenge53188a2015-05-04 09:05:18 -0600259 elif self.tok in "'tfn":
Markus Armbrusterc7a3f252013-07-27 17:41:55 +0200260 expr = self.val
261 self.accept()
Markus Armbruster6974ccd2013-07-27 17:41:58 +0200262 else:
263 raise QAPISchemaError(self, 'Expected "{", "[" or string')
Markus Armbrusterc7a3f252013-07-27 17:41:55 +0200264 return expr
Kevin Wolfbd9927f2013-07-01 16:31:50 +0200265
Wenchao Xiab86b05e2014-03-04 18:44:34 -0800266def find_base_fields(base):
267 base_struct_define = find_struct(base)
268 if not base_struct_define:
269 return None
270 return base_struct_define['data']
271
Eric Blake811d04f2015-05-04 09:05:10 -0600272# Return the qtype of an alternate branch, or None on error.
273def find_alternate_member_qtype(qapi_type):
Eric Blake44bd1272015-05-04 09:05:08 -0600274 if builtin_types.has_key(qapi_type):
275 return builtin_types[qapi_type]
276 elif find_struct(qapi_type):
277 return "QTYPE_QDICT"
278 elif find_enum(qapi_type):
279 return "QTYPE_QSTRING"
Eric Blake811d04f2015-05-04 09:05:10 -0600280 elif find_union(qapi_type):
281 return "QTYPE_QDICT"
Eric Blake44bd1272015-05-04 09:05:08 -0600282 return None
283
Wenchao Xiabceae762014-03-06 17:08:56 -0800284# Return the discriminator enum define if discriminator is specified as an
285# enum type, otherwise return None.
286def discriminator_find_enum_define(expr):
287 base = expr.get('base')
288 discriminator = expr.get('discriminator')
289
290 if not (discriminator and base):
291 return None
292
293 base_fields = find_base_fields(base)
294 if not base_fields:
295 return None
296
297 discriminator_type = base_fields.get(discriminator)
298 if not discriminator_type:
299 return None
300
301 return find_enum(discriminator_type)
302
Eric Blakec9e0a792015-05-04 09:05:22 -0600303valid_name = re.compile('^[a-zA-Z_][a-zA-Z0-9_.-]*$')
304def check_name(expr_info, source, name, allow_optional = False,
305 enum_member = False):
306 global valid_name
307 membername = name
308
309 if not isinstance(name, str):
310 raise QAPIExprError(expr_info,
311 "%s requires a string name" % source)
312 if name.startswith('*'):
313 membername = name[1:]
314 if not allow_optional:
315 raise QAPIExprError(expr_info,
316 "%s does not allow optional name '%s'"
317 % (source, name))
318 # Enum members can start with a digit, because the generated C
319 # code always prefixes it with the enum name
320 if enum_member:
321 membername = '_' + membername
322 if not valid_name.match(membername):
323 raise QAPIExprError(expr_info,
324 "%s uses invalid name '%s'" % (source, name))
325
Eric Blakedd883c62015-05-04 09:05:21 -0600326def check_type(expr_info, source, value, allow_array = False,
Eric Blake2cbf0992015-05-04 09:05:24 -0600327 allow_dict = False, allow_optional = False,
328 allow_star = False, allow_metas = []):
Eric Blakedd883c62015-05-04 09:05:21 -0600329 global all_names
330 orig_value = value
331
332 if value is None:
333 return
334
Eric Blake2cbf0992015-05-04 09:05:24 -0600335 if allow_star and value == '**':
Eric Blakedd883c62015-05-04 09:05:21 -0600336 return
337
338 # Check if array type for value is okay
339 if isinstance(value, list):
340 if not allow_array:
341 raise QAPIExprError(expr_info,
342 "%s cannot be an array" % source)
343 if len(value) != 1 or not isinstance(value[0], str):
344 raise QAPIExprError(expr_info,
345 "%s: array type must contain single type name"
346 % source)
347 value = value[0]
348 orig_value = "array of %s" %value
349
350 # Check if type name for value is okay
351 if isinstance(value, str):
Eric Blake2cbf0992015-05-04 09:05:24 -0600352 if value == '**':
353 raise QAPIExprError(expr_info,
354 "%s uses '**' but did not request 'gen':false"
355 % source)
Eric Blakedd883c62015-05-04 09:05:21 -0600356 if not value in all_names:
357 raise QAPIExprError(expr_info,
358 "%s uses unknown type '%s'"
359 % (source, orig_value))
360 if not all_names[value] in allow_metas:
361 raise QAPIExprError(expr_info,
362 "%s cannot use %s type '%s'"
363 % (source, all_names[value], orig_value))
364 return
365
366 # value is a dictionary, check that each member is okay
367 if not isinstance(value, OrderedDict):
368 raise QAPIExprError(expr_info,
369 "%s should be a dictionary" % source)
370 if not allow_dict:
371 raise QAPIExprError(expr_info,
372 "%s should be a type name" % source)
373 for (key, arg) in value.items():
Eric Blakec9e0a792015-05-04 09:05:22 -0600374 check_name(expr_info, "Member of %s" % source, key,
375 allow_optional=allow_optional)
Eric Blakedd883c62015-05-04 09:05:21 -0600376 check_type(expr_info, "Member '%s' of %s" % (key, source), arg,
Eric Blakec9e0a792015-05-04 09:05:22 -0600377 allow_array=True, allow_dict=True, allow_optional=True,
Eric Blakedd883c62015-05-04 09:05:21 -0600378 allow_metas=['built-in', 'union', 'alternate', 'struct',
Eric Blake2cbf0992015-05-04 09:05:24 -0600379 'enum'], allow_star=allow_star)
Eric Blakedd883c62015-05-04 09:05:21 -0600380
381def check_command(expr, expr_info):
382 name = expr['command']
Eric Blake2cbf0992015-05-04 09:05:24 -0600383 allow_star = expr.has_key('gen')
384
Eric Blakedd883c62015-05-04 09:05:21 -0600385 check_type(expr_info, "'data' for command '%s'" % name,
Eric Blakec9e0a792015-05-04 09:05:22 -0600386 expr.get('data'), allow_dict=True, allow_optional=True,
Eric Blake2cbf0992015-05-04 09:05:24 -0600387 allow_metas=['union', 'struct'], allow_star=allow_star)
Eric Blake10d4d992015-05-04 09:05:23 -0600388 returns_meta = ['union', 'struct']
389 if name in returns_whitelist:
390 returns_meta += ['built-in', 'alternate', 'enum']
Eric Blakedd883c62015-05-04 09:05:21 -0600391 check_type(expr_info, "'returns' for command '%s'" % name,
392 expr.get('returns'), allow_array=True, allow_dict=True,
Eric Blake2cbf0992015-05-04 09:05:24 -0600393 allow_optional=True, allow_metas=returns_meta,
394 allow_star=allow_star)
Eric Blakedd883c62015-05-04 09:05:21 -0600395
Wenchao Xia21cd70d2014-06-18 08:43:28 +0200396def check_event(expr, expr_info):
Eric Blake4dc2e692015-05-04 09:05:17 -0600397 global events
398 name = expr['event']
Wenchao Xia21cd70d2014-06-18 08:43:28 +0200399 params = expr.get('data')
Eric Blake4dc2e692015-05-04 09:05:17 -0600400
401 if name.upper() == 'MAX':
402 raise QAPIExprError(expr_info, "Event name 'MAX' cannot be created")
403 events.append(name)
Eric Blakedd883c62015-05-04 09:05:21 -0600404 check_type(expr_info, "'data' for event '%s'" % name,
Eric Blakec9e0a792015-05-04 09:05:22 -0600405 expr.get('data'), allow_dict=True, allow_optional=True,
Eric Blakedd883c62015-05-04 09:05:21 -0600406 allow_metas=['union', 'struct'])
Wenchao Xia21cd70d2014-06-18 08:43:28 +0200407 if params:
408 for argname, argentry, optional, structured in parse_args(params):
409 if structured:
410 raise QAPIExprError(expr_info,
411 "Nested structure define in event is not "
Wenchao Xiad6f9c822014-06-24 16:33:59 -0700412 "supported, event '%s', argname '%s'"
Wenchao Xia21cd70d2014-06-18 08:43:28 +0200413 % (expr['event'], argname))
414
Wenchao Xiab86b05e2014-03-04 18:44:34 -0800415def check_union(expr, expr_info):
416 name = expr['union']
417 base = expr.get('base')
418 discriminator = expr.get('discriminator')
419 members = expr['data']
Eric Blake44bd1272015-05-04 09:05:08 -0600420 values = { 'MAX': '(automatic)' }
Wenchao Xiab86b05e2014-03-04 18:44:34 -0800421
Eric Blakea8d4a2e2015-05-04 09:05:07 -0600422 # If the object has a member 'base', its value must name a complex type,
423 # and there must be a discriminator.
424 if base is not None:
425 if discriminator is None:
426 raise QAPIExprError(expr_info,
427 "Union '%s' requires a discriminator to go "
428 "along with base" %name)
Eric Blake44bd1272015-05-04 09:05:08 -0600429
Eric Blake811d04f2015-05-04 09:05:10 -0600430 # Two types of unions, determined by discriminator.
Eric Blake811d04f2015-05-04 09:05:10 -0600431
432 # With no discriminator it is a simple union.
433 if discriminator is None:
Eric Blake44bd1272015-05-04 09:05:08 -0600434 enum_define = None
Eric Blakedd883c62015-05-04 09:05:21 -0600435 allow_metas=['built-in', 'union', 'alternate', 'struct', 'enum']
Eric Blake44bd1272015-05-04 09:05:08 -0600436 if base is not None:
437 raise QAPIExprError(expr_info,
Eric Blake811d04f2015-05-04 09:05:10 -0600438 "Simple union '%s' must not have a base"
Eric Blake44bd1272015-05-04 09:05:08 -0600439 % name)
440
441 # Else, it's a flat union.
442 else:
443 # The object must have a string member 'base'.
444 if not isinstance(base, str):
445 raise QAPIExprError(expr_info,
446 "Flat union '%s' must have a string base field"
447 % name)
Wenchao Xiab86b05e2014-03-04 18:44:34 -0800448 base_fields = find_base_fields(base)
449 if not base_fields:
450 raise QAPIExprError(expr_info,
451 "Base '%s' is not a valid type"
452 % base)
453
Eric Blakec9e0a792015-05-04 09:05:22 -0600454 # The value of member 'discriminator' must name a non-optional
455 # member of the base type.
456 check_name(expr_info, "Discriminator of flat union '%s'" % name,
457 discriminator)
Wenchao Xiab86b05e2014-03-04 18:44:34 -0800458 discriminator_type = base_fields.get(discriminator)
459 if not discriminator_type:
460 raise QAPIExprError(expr_info,
461 "Discriminator '%s' is not a member of base "
462 "type '%s'"
463 % (discriminator, base))
464 enum_define = find_enum(discriminator_type)
Eric Blakedd883c62015-05-04 09:05:21 -0600465 allow_metas=['struct']
Wenchao Xia52230702014-03-04 18:44:39 -0800466 # Do not allow string discriminator
467 if not enum_define:
468 raise QAPIExprError(expr_info,
469 "Discriminator '%s' must be of enumeration "
470 "type" % discriminator)
Wenchao Xiab86b05e2014-03-04 18:44:34 -0800471
472 # Check every branch
473 for (key, value) in members.items():
Eric Blakec9e0a792015-05-04 09:05:22 -0600474 check_name(expr_info, "Member of union '%s'" % name, key)
475
Eric Blakedd883c62015-05-04 09:05:21 -0600476 # Each value must name a known type; furthermore, in flat unions,
477 # branches must be a struct
478 check_type(expr_info, "Member '%s' of union '%s'" % (key, name),
479 value, allow_array=True, allow_metas=allow_metas)
480
Eric Blake44bd1272015-05-04 09:05:08 -0600481 # If the discriminator names an enum type, then all members
Wenchao Xiab86b05e2014-03-04 18:44:34 -0800482 # of 'data' must also be members of the enum type.
Eric Blake44bd1272015-05-04 09:05:08 -0600483 if enum_define:
484 if not key in enum_define['enum_values']:
485 raise QAPIExprError(expr_info,
486 "Discriminator value '%s' is not found in "
487 "enum '%s'" %
488 (key, enum_define["enum_name"]))
489
490 # Otherwise, check for conflicts in the generated enum
491 else:
492 c_key = _generate_enum_string(key)
493 if c_key in values:
494 raise QAPIExprError(expr_info,
495 "Union '%s' member '%s' clashes with '%s'"
496 % (name, key, values[c_key]))
497 values[c_key] = key
498
Eric Blake811d04f2015-05-04 09:05:10 -0600499def check_alternate(expr, expr_info):
Eric Blakeab916fa2015-05-04 09:05:13 -0600500 name = expr['alternate']
Eric Blake811d04f2015-05-04 09:05:10 -0600501 members = expr['data']
502 values = { 'MAX': '(automatic)' }
503 types_seen = {}
Eric Blake44bd1272015-05-04 09:05:08 -0600504
Eric Blake811d04f2015-05-04 09:05:10 -0600505 # Check every branch
506 for (key, value) in members.items():
Eric Blakec9e0a792015-05-04 09:05:22 -0600507 check_name(expr_info, "Member of alternate '%s'" % name, key)
508
Eric Blake811d04f2015-05-04 09:05:10 -0600509 # Check for conflicts in the generated enum
510 c_key = _generate_enum_string(key)
511 if c_key in values:
512 raise QAPIExprError(expr_info,
Eric Blakeab916fa2015-05-04 09:05:13 -0600513 "Alternate '%s' member '%s' clashes with '%s'"
514 % (name, key, values[c_key]))
Eric Blake811d04f2015-05-04 09:05:10 -0600515 values[c_key] = key
516
517 # Ensure alternates have no type conflicts.
Eric Blakedd883c62015-05-04 09:05:21 -0600518 check_type(expr_info, "Member '%s' of alternate '%s'" % (key, name),
519 value,
520 allow_metas=['built-in', 'union', 'struct', 'enum'])
Eric Blake811d04f2015-05-04 09:05:10 -0600521 qtype = find_alternate_member_qtype(value)
Eric Blakedd883c62015-05-04 09:05:21 -0600522 assert qtype
Eric Blake811d04f2015-05-04 09:05:10 -0600523 if qtype in types_seen:
524 raise QAPIExprError(expr_info,
Eric Blakeab916fa2015-05-04 09:05:13 -0600525 "Alternate '%s' member '%s' can't "
Eric Blake811d04f2015-05-04 09:05:10 -0600526 "be distinguished from member '%s'"
527 % (name, key, types_seen[qtype]))
528 types_seen[qtype] = key
Wenchao Xiab86b05e2014-03-04 18:44:34 -0800529
Eric Blakecf393592015-05-04 09:05:04 -0600530def check_enum(expr, expr_info):
531 name = expr['enum']
532 members = expr.get('data')
533 values = { 'MAX': '(automatic)' }
534
535 if not isinstance(members, list):
536 raise QAPIExprError(expr_info,
537 "Enum '%s' requires an array for 'data'" % name)
538 for member in members:
Eric Blakec9e0a792015-05-04 09:05:22 -0600539 check_name(expr_info, "Member of enum '%s'" %name, member,
540 enum_member=True)
Eric Blakecf393592015-05-04 09:05:04 -0600541 key = _generate_enum_string(member)
542 if key in values:
543 raise QAPIExprError(expr_info,
544 "Enum '%s' member '%s' clashes with '%s'"
545 % (name, member, values[key]))
546 values[key] = member
547
Eric Blakedd883c62015-05-04 09:05:21 -0600548def check_struct(expr, expr_info):
549 name = expr['type']
550 members = expr['data']
551
552 check_type(expr_info, "'data' for type '%s'" % name, members,
Eric Blakec9e0a792015-05-04 09:05:22 -0600553 allow_dict=True, allow_optional=True)
Eric Blakedd883c62015-05-04 09:05:21 -0600554 check_type(expr_info, "'base' for type '%s'" % name, expr.get('base'),
555 allow_metas=['struct'])
556
Wenchao Xiab86b05e2014-03-04 18:44:34 -0800557def check_exprs(schema):
558 for expr_elem in schema.exprs:
559 expr = expr_elem['expr']
Eric Blakecf393592015-05-04 09:05:04 -0600560 info = expr_elem['info']
561
562 if expr.has_key('enum'):
563 check_enum(expr, info)
564 elif expr.has_key('union'):
Eric Blakeab916fa2015-05-04 09:05:13 -0600565 check_union(expr, info)
566 elif expr.has_key('alternate'):
567 check_alternate(expr, info)
Eric Blakedd883c62015-05-04 09:05:21 -0600568 elif expr.has_key('type'):
569 check_struct(expr, info)
570 elif expr.has_key('command'):
571 check_command(expr, info)
Eric Blakecf393592015-05-04 09:05:04 -0600572 elif expr.has_key('event'):
573 check_event(expr, info)
Eric Blakedd883c62015-05-04 09:05:21 -0600574 else:
575 assert False, 'unexpected meta type'
Wenchao Xiab86b05e2014-03-04 18:44:34 -0800576
Eric Blake0545f6b2015-05-04 09:05:15 -0600577def check_keys(expr_elem, meta, required, optional=[]):
578 expr = expr_elem['expr']
579 info = expr_elem['info']
580 name = expr[meta]
581 if not isinstance(name, str):
582 raise QAPIExprError(info,
583 "'%s' key must have a string value" % meta)
584 required = required + [ meta ]
585 for (key, value) in expr.items():
586 if not key in required and not key in optional:
587 raise QAPIExprError(info,
588 "Unknown key '%s' in %s '%s'"
589 % (key, meta, name))
Eric Blake2cbf0992015-05-04 09:05:24 -0600590 if (key == 'gen' or key == 'success-response') and value != False:
591 raise QAPIExprError(info,
592 "'%s' of %s '%s' should only use false value"
593 % (key, meta, name))
Eric Blake0545f6b2015-05-04 09:05:15 -0600594 for key in required:
595 if not expr.has_key(key):
596 raise QAPIExprError(info,
597 "Key '%s' is missing from %s '%s'"
598 % (key, meta, name))
599
600
Lluís Vilanova33aaad52014-05-02 15:52:35 +0200601def parse_schema(input_file):
Eric Blake4dc2e692015-05-04 09:05:17 -0600602 global all_names
603 exprs = []
604
Eric Blake268a1c52015-05-04 09:05:09 -0600605 # First pass: read entire file into memory
Markus Armbruster2caba362013-07-27 17:41:56 +0200606 try:
Lluís Vilanova33aaad52014-05-02 15:52:35 +0200607 schema = QAPISchema(open(input_file, "r"))
Lluís Vilanovaa719a272014-05-07 20:46:15 +0200608 except (QAPISchemaError, QAPIExprError), e:
Markus Armbruster2caba362013-07-27 17:41:56 +0200609 print >>sys.stderr, e
610 exit(1)
611
Wenchao Xiab86b05e2014-03-04 18:44:34 -0800612 try:
Eric Blake0545f6b2015-05-04 09:05:15 -0600613 # Next pass: learn the types and check for valid expression keys. At
614 # this point, top-level 'include' has already been flattened.
Eric Blake4dc2e692015-05-04 09:05:17 -0600615 for builtin in builtin_types.keys():
616 all_names[builtin] = 'built-in'
Eric Blake268a1c52015-05-04 09:05:09 -0600617 for expr_elem in schema.exprs:
618 expr = expr_elem['expr']
Eric Blake4dc2e692015-05-04 09:05:17 -0600619 info = expr_elem['info']
Eric Blake268a1c52015-05-04 09:05:09 -0600620 if expr.has_key('enum'):
Eric Blake0545f6b2015-05-04 09:05:15 -0600621 check_keys(expr_elem, 'enum', ['data'])
Eric Blake4dc2e692015-05-04 09:05:17 -0600622 add_enum(expr['enum'], info, expr['data'])
Eric Blake268a1c52015-05-04 09:05:09 -0600623 elif expr.has_key('union'):
Eric Blake0545f6b2015-05-04 09:05:15 -0600624 check_keys(expr_elem, 'union', ['data'],
625 ['base', 'discriminator'])
Eric Blake4dc2e692015-05-04 09:05:17 -0600626 add_union(expr, info)
Eric Blake0545f6b2015-05-04 09:05:15 -0600627 elif expr.has_key('alternate'):
628 check_keys(expr_elem, 'alternate', ['data'])
Eric Blake4dc2e692015-05-04 09:05:17 -0600629 add_name(expr['alternate'], info, 'alternate')
Eric Blake268a1c52015-05-04 09:05:09 -0600630 elif expr.has_key('type'):
Eric Blake0545f6b2015-05-04 09:05:15 -0600631 check_keys(expr_elem, 'type', ['data'], ['base'])
Eric Blake4dc2e692015-05-04 09:05:17 -0600632 add_struct(expr, info)
Eric Blake0545f6b2015-05-04 09:05:15 -0600633 elif expr.has_key('command'):
634 check_keys(expr_elem, 'command', [],
635 ['data', 'returns', 'gen', 'success-response'])
Eric Blake4dc2e692015-05-04 09:05:17 -0600636 add_name(expr['command'], info, 'command')
Eric Blake0545f6b2015-05-04 09:05:15 -0600637 elif expr.has_key('event'):
638 check_keys(expr_elem, 'event', [], ['data'])
Eric Blake4dc2e692015-05-04 09:05:17 -0600639 add_name(expr['event'], info, 'event')
Eric Blake0545f6b2015-05-04 09:05:15 -0600640 else:
641 raise QAPIExprError(expr_elem['info'],
642 "Expression is missing metatype")
Eric Blake268a1c52015-05-04 09:05:09 -0600643 exprs.append(expr)
644
645 # Try again for hidden UnionKind enum
646 for expr_elem in schema.exprs:
647 expr = expr_elem['expr']
648 if expr.has_key('union'):
649 if not discriminator_find_enum_define(expr):
Eric Blake4dc2e692015-05-04 09:05:17 -0600650 add_enum('%sKind' % expr['union'], expr_elem['info'],
651 implicit=True)
Eric Blakeab916fa2015-05-04 09:05:13 -0600652 elif expr.has_key('alternate'):
Eric Blake4dc2e692015-05-04 09:05:17 -0600653 add_enum('%sKind' % expr['alternate'], expr_elem['info'],
654 implicit=True)
Eric Blake268a1c52015-05-04 09:05:09 -0600655
656 # Final pass - validate that exprs make sense
Wenchao Xiab86b05e2014-03-04 18:44:34 -0800657 check_exprs(schema)
658 except QAPIExprError, e:
659 print >>sys.stderr, e
660 exit(1)
661
Michael Roth0f923be2011-07-19 14:50:39 -0500662 return exprs
663
664def parse_args(typeinfo):
Eric Blakefe2a9302015-05-04 09:05:02 -0600665 if isinstance(typeinfo, str):
Kevin Wolfb35284e2013-07-01 16:31:51 +0200666 struct = find_struct(typeinfo)
667 assert struct != None
668 typeinfo = struct['data']
669
Michael Roth0f923be2011-07-19 14:50:39 -0500670 for member in typeinfo:
671 argname = member
672 argentry = typeinfo[member]
673 optional = False
674 structured = False
675 if member.startswith('*'):
676 argname = member[1:]
677 optional = True
678 if isinstance(argentry, OrderedDict):
679 structured = True
680 yield (argname, argentry, optional, structured)
681
682def de_camel_case(name):
683 new_name = ''
684 for ch in name:
685 if ch.isupper() and new_name:
686 new_name += '_'
687 if ch == '-':
688 new_name += '_'
689 else:
690 new_name += ch.lower()
691 return new_name
692
693def camel_case(name):
694 new_name = ''
695 first = True
696 for ch in name:
697 if ch in ['_', '-']:
698 first = True
699 elif first:
700 new_name += ch.upper()
701 first = False
702 else:
703 new_name += ch.lower()
704 return new_name
705
Paolo Bonzinieda50a62012-09-19 16:31:06 +0200706def c_var(name, protect=True):
Blue Swirl427a1a22012-07-30 15:46:55 +0000707 # ANSI X3J11/88-090, 3.1.1
708 c89_words = set(['auto', 'break', 'case', 'char', 'const', 'continue',
709 'default', 'do', 'double', 'else', 'enum', 'extern', 'float',
710 'for', 'goto', 'if', 'int', 'long', 'register', 'return',
711 'short', 'signed', 'sizeof', 'static', 'struct', 'switch',
712 'typedef', 'union', 'unsigned', 'void', 'volatile', 'while'])
713 # ISO/IEC 9899:1999, 6.4.1
714 c99_words = set(['inline', 'restrict', '_Bool', '_Complex', '_Imaginary'])
715 # ISO/IEC 9899:2011, 6.4.1
716 c11_words = set(['_Alignas', '_Alignof', '_Atomic', '_Generic', '_Noreturn',
717 '_Static_assert', '_Thread_local'])
718 # GCC http://gcc.gnu.org/onlinedocs/gcc-4.7.1/gcc/C-Extensions.html
719 # excluding _.*
720 gcc_words = set(['asm', 'typeof'])
Tomoki Sekiyama6f880092013-08-07 11:39:43 -0400721 # C++ ISO/IEC 14882:2003 2.11
722 cpp_words = set(['bool', 'catch', 'class', 'const_cast', 'delete',
723 'dynamic_cast', 'explicit', 'false', 'friend', 'mutable',
724 'namespace', 'new', 'operator', 'private', 'protected',
725 'public', 'reinterpret_cast', 'static_cast', 'template',
726 'this', 'throw', 'true', 'try', 'typeid', 'typename',
727 'using', 'virtual', 'wchar_t',
728 # alternative representations
729 'and', 'and_eq', 'bitand', 'bitor', 'compl', 'not',
730 'not_eq', 'or', 'or_eq', 'xor', 'xor_eq'])
Paolo Bonzini10577252012-09-19 16:31:07 +0200731 # namespace pollution:
Max Reitz8592a542013-12-20 19:28:18 +0100732 polluted_words = set(['unix', 'errno'])
Tomoki Sekiyama6f880092013-08-07 11:39:43 -0400733 if protect and (name in c89_words | c99_words | c11_words | gcc_words | cpp_words | polluted_words):
Blue Swirl427a1a22012-07-30 15:46:55 +0000734 return "q_" + name
Federico Simoncellic9da2282012-03-20 13:54:35 +0000735 return name.replace('-', '_').lstrip("*")
736
Paolo Bonzinieda50a62012-09-19 16:31:06 +0200737def c_fun(name, protect=True):
738 return c_var(name, protect).replace('.', '_')
Michael Roth0f923be2011-07-19 14:50:39 -0500739
740def c_list_type(name):
741 return '%sList' % name
742
743def type_name(name):
744 if type(name) == list:
745 return c_list_type(name[0])
746 return name
747
Eric Blakec9e0a792015-05-04 09:05:22 -0600748def add_name(name, info, meta, implicit = False, source = None):
Eric Blake4dc2e692015-05-04 09:05:17 -0600749 global all_names
Eric Blakec9e0a792015-05-04 09:05:22 -0600750 if not source:
751 source = "'%s'" % meta
752 check_name(info, source, name)
Eric Blake4dc2e692015-05-04 09:05:17 -0600753 if name in all_names:
754 raise QAPIExprError(info,
755 "%s '%s' is already defined"
756 % (all_names[name], name))
757 if not implicit and name[-4:] == 'Kind':
758 raise QAPIExprError(info,
759 "%s '%s' should not end in 'Kind'"
760 % (meta, name))
761 all_names[name] = meta
Kevin Wolfb35284e2013-07-01 16:31:51 +0200762
Eric Blake4dc2e692015-05-04 09:05:17 -0600763def add_struct(definition, info):
Kevin Wolfb35284e2013-07-01 16:31:51 +0200764 global struct_types
Eric Blake4dc2e692015-05-04 09:05:17 -0600765 name = definition['type']
Eric Blakec9e0a792015-05-04 09:05:22 -0600766 add_name(name, info, 'struct', source="'type'")
Kevin Wolfb35284e2013-07-01 16:31:51 +0200767 struct_types.append(definition)
768
769def find_struct(name):
770 global struct_types
771 for struct in struct_types:
772 if struct['type'] == name:
773 return struct
774 return None
Michael Roth0f923be2011-07-19 14:50:39 -0500775
Eric Blake4dc2e692015-05-04 09:05:17 -0600776def add_union(definition, info):
Kevin Wolfea66c6d2013-07-16 10:49:41 +0200777 global union_types
Eric Blake4dc2e692015-05-04 09:05:17 -0600778 name = definition['union']
779 add_name(name, info, 'union')
Eric Blakeab916fa2015-05-04 09:05:13 -0600780 union_types.append(definition)
Kevin Wolfea66c6d2013-07-16 10:49:41 +0200781
782def find_union(name):
783 global union_types
784 for union in union_types:
785 if union['union'] == name:
786 return union
787 return None
788
Eric Blake4dc2e692015-05-04 09:05:17 -0600789def add_enum(name, info, enum_values = None, implicit = False):
Michael Roth0f923be2011-07-19 14:50:39 -0500790 global enum_types
Eric Blake4dc2e692015-05-04 09:05:17 -0600791 add_name(name, info, 'enum', implicit)
Wenchao Xiadad1fca2014-03-04 18:44:31 -0800792 enum_types.append({"enum_name": name, "enum_values": enum_values})
793
794def find_enum(name):
795 global enum_types
796 for enum in enum_types:
797 if enum['enum_name'] == name:
798 return enum
799 return None
Michael Roth0f923be2011-07-19 14:50:39 -0500800
801def is_enum(name):
Wenchao Xiadad1fca2014-03-04 18:44:31 -0800802 return find_enum(name) != None
Michael Roth0f923be2011-07-19 14:50:39 -0500803
Amos Kong05dfb262014-06-10 19:25:53 +0800804eatspace = '\033EATSPACE.'
805
806# A special suffix is added in c_type() for pointer types, and it's
807# stripped in mcgen(). So please notice this when you check the return
808# value of c_type() outside mcgen().
Amos Kong0d14eeb2014-06-10 19:25:52 +0800809def c_type(name, is_param=False):
Michael Roth0f923be2011-07-19 14:50:39 -0500810 if name == 'str':
Amos Kong0d14eeb2014-06-10 19:25:52 +0800811 if is_param:
Amos Kong05dfb262014-06-10 19:25:53 +0800812 return 'const char *' + eatspace
813 return 'char *' + eatspace
814
Michael Roth0f923be2011-07-19 14:50:39 -0500815 elif name == 'int':
816 return 'int64_t'
Laszlo Ersekc46f18c2012-07-17 16:17:06 +0200817 elif (name == 'int8' or name == 'int16' or name == 'int32' or
818 name == 'int64' or name == 'uint8' or name == 'uint16' or
819 name == 'uint32' or name == 'uint64'):
820 return name + '_t'
Laszlo Ersek092705d2012-07-17 16:17:07 +0200821 elif name == 'size':
822 return 'uint64_t'
Michael Roth0f923be2011-07-19 14:50:39 -0500823 elif name == 'bool':
824 return 'bool'
825 elif name == 'number':
826 return 'double'
827 elif type(name) == list:
Amos Kong05dfb262014-06-10 19:25:53 +0800828 return '%s *%s' % (c_list_type(name[0]), eatspace)
Michael Roth0f923be2011-07-19 14:50:39 -0500829 elif is_enum(name):
830 return name
831 elif name == None or len(name) == 0:
832 return 'void'
Eric Blake4dc2e692015-05-04 09:05:17 -0600833 elif name in events:
Amos Kong05dfb262014-06-10 19:25:53 +0800834 return '%sEvent *%s' % (camel_case(name), eatspace)
Michael Roth0f923be2011-07-19 14:50:39 -0500835 else:
Amos Kong05dfb262014-06-10 19:25:53 +0800836 return '%s *%s' % (name, eatspace)
837
838def is_c_ptr(name):
839 suffix = "*" + eatspace
840 return c_type(name).endswith(suffix)
Michael Roth0f923be2011-07-19 14:50:39 -0500841
842def genindent(count):
843 ret = ""
844 for i in range(count):
845 ret += " "
846 return ret
847
848indent_level = 0
849
850def push_indent(indent_amount=4):
851 global indent_level
852 indent_level += indent_amount
853
854def pop_indent(indent_amount=4):
855 global indent_level
856 indent_level -= indent_amount
857
858def cgen(code, **kwds):
859 indent = genindent(indent_level)
860 lines = code.split('\n')
861 lines = map(lambda x: indent + x, lines)
862 return '\n'.join(lines) % kwds + '\n'
863
864def mcgen(code, **kwds):
Amos Kong05dfb262014-06-10 19:25:53 +0800865 raw = cgen('\n'.join(code.split('\n')[1:-1]), **kwds)
866 return re.sub(re.escape(eatspace) + ' *', '', raw)
Michael Roth0f923be2011-07-19 14:50:39 -0500867
868def basename(filename):
869 return filename.split("/")[-1]
870
871def guardname(filename):
Michael Rothd8e1f212011-11-29 16:47:48 -0600872 guard = basename(filename).rsplit(".", 1)[0]
873 for substr in [".", " ", "-"]:
874 guard = guard.replace(substr, "_")
875 return guard.upper() + '_H'
Michael Rothc0afa9c2013-05-10 17:46:00 -0500876
877def guardstart(name):
878 return mcgen('''
879
880#ifndef %(name)s
881#define %(name)s
882
883''',
884 name=guardname(name))
885
886def guardend(name):
887 return mcgen('''
888
889#endif /* %(name)s */
890
891''',
892 name=guardname(name))
Wenchao Xia62996592014-03-04 18:44:35 -0800893
Wenchao Xia5d371f42014-03-04 18:44:40 -0800894# ENUMName -> ENUM_NAME, EnumName1 -> ENUM_NAME1
895# ENUM_NAME -> ENUM_NAME, ENUM_NAME1 -> ENUM_NAME1, ENUM_Name2 -> ENUM_NAME2
896# ENUM24_Name -> ENUM24_NAME
897def _generate_enum_string(value):
898 c_fun_str = c_fun(value, False)
Wenchao Xiab0b58192014-03-04 18:44:36 -0800899 if value.isupper():
Wenchao Xia5d371f42014-03-04 18:44:40 -0800900 return c_fun_str
901
Wenchao Xia62996592014-03-04 18:44:35 -0800902 new_name = ''
Wenchao Xia5d371f42014-03-04 18:44:40 -0800903 l = len(c_fun_str)
904 for i in range(l):
905 c = c_fun_str[i]
906 # When c is upper and no "_" appears before, do more checks
907 if c.isupper() and (i > 0) and c_fun_str[i - 1] != "_":
908 # Case 1: next string is lower
909 # Case 2: previous string is digit
910 if (i < (l - 1) and c_fun_str[i + 1].islower()) or \
911 c_fun_str[i - 1].isdigit():
912 new_name += '_'
Wenchao Xia62996592014-03-04 18:44:35 -0800913 new_name += c
914 return new_name.lstrip('_').upper()
Wenchao Xiab0b58192014-03-04 18:44:36 -0800915
916def generate_enum_full_value(enum_name, enum_value):
Wenchao Xia5d371f42014-03-04 18:44:40 -0800917 abbrev_string = _generate_enum_string(enum_name)
918 value_string = _generate_enum_string(enum_value)
Wenchao Xiab0b58192014-03-04 18:44:36 -0800919 return "%s_%s" % (abbrev_string, value_string)