blob: 1dd91eed421aa34f5f041699df6bd56957cc8e23 [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 Blake4dc2e692015-05-04 09:05:17 -060035enum_types = []
36struct_types = []
37union_types = []
38events = []
39all_names = {}
40
Lluís Vilanovaa719a272014-05-07 20:46:15 +020041def error_path(parent):
42 res = ""
43 while parent:
44 res = ("In file included from %s:%d:\n" % (parent['file'],
45 parent['line'])) + res
46 parent = parent['parent']
47 return res
48
Markus Armbruster2caba362013-07-27 17:41:56 +020049class QAPISchemaError(Exception):
50 def __init__(self, schema, msg):
Lluís Vilanovaa719a272014-05-07 20:46:15 +020051 self.input_file = schema.input_file
Markus Armbruster2caba362013-07-27 17:41:56 +020052 self.msg = msg
Wenchao Xia515b9432014-03-04 18:44:33 -080053 self.col = 1
54 self.line = schema.line
55 for ch in schema.src[schema.line_pos:schema.pos]:
56 if ch == '\t':
Markus Armbruster2caba362013-07-27 17:41:56 +020057 self.col = (self.col + 7) % 8 + 1
58 else:
59 self.col += 1
Lluís Vilanovaa719a272014-05-07 20:46:15 +020060 self.info = schema.parent_info
Markus Armbruster2caba362013-07-27 17:41:56 +020061
62 def __str__(self):
Lluís Vilanovaa719a272014-05-07 20:46:15 +020063 return error_path(self.info) + \
64 "%s:%d:%d: %s" % (self.input_file, self.line, self.col, self.msg)
Markus Armbruster2caba362013-07-27 17:41:56 +020065
Wenchao Xiab86b05e2014-03-04 18:44:34 -080066class QAPIExprError(Exception):
67 def __init__(self, expr_info, msg):
Lluís Vilanovaa719a272014-05-07 20:46:15 +020068 self.info = expr_info
Wenchao Xiab86b05e2014-03-04 18:44:34 -080069 self.msg = msg
70
71 def __str__(self):
Lluís Vilanovaa719a272014-05-07 20:46:15 +020072 return error_path(self.info['parent']) + \
73 "%s:%d: %s" % (self.info['file'], self.info['line'], self.msg)
Wenchao Xiab86b05e2014-03-04 18:44:34 -080074
Markus Armbrusterc7a3f252013-07-27 17:41:55 +020075class QAPISchema:
Michael Roth0f923be2011-07-19 14:50:39 -050076
Benoît Canet24fd8482014-05-16 12:51:56 +020077 def __init__(self, fp, input_relname=None, include_hist=[],
78 previously_included=[], parent_info=None):
79 """ include_hist is a stack used to detect inclusion cycles
80 previously_included is a global state used to avoid multiple
81 inclusions of the same file"""
Lluís Vilanovaa719a272014-05-07 20:46:15 +020082 input_fname = os.path.abspath(fp.name)
83 if input_relname is None:
84 input_relname = fp.name
85 self.input_dir = os.path.dirname(input_fname)
86 self.input_file = input_relname
87 self.include_hist = include_hist + [(input_relname, input_fname)]
Benoît Canet24fd8482014-05-16 12:51:56 +020088 previously_included.append(input_fname)
Lluís Vilanovaa719a272014-05-07 20:46:15 +020089 self.parent_info = parent_info
Markus Armbrusterc7a3f252013-07-27 17:41:55 +020090 self.src = fp.read()
91 if self.src == '' or self.src[-1] != '\n':
92 self.src += '\n'
93 self.cursor = 0
Wenchao Xia515b9432014-03-04 18:44:33 -080094 self.line = 1
95 self.line_pos = 0
Markus Armbrusterc7a3f252013-07-27 17:41:55 +020096 self.exprs = []
97 self.accept()
Michael Roth0f923be2011-07-19 14:50:39 -050098
Markus Armbrusterc7a3f252013-07-27 17:41:55 +020099 while self.tok != None:
Lluís Vilanovaa719a272014-05-07 20:46:15 +0200100 expr_info = {'file': input_relname, 'line': self.line, 'parent': self.parent_info}
101 expr = self.get_expr(False)
102 if isinstance(expr, dict) and "include" in expr:
103 if len(expr) != 1:
104 raise QAPIExprError(expr_info, "Invalid 'include' directive")
105 include = expr["include"]
106 if not isinstance(include, str):
107 raise QAPIExprError(expr_info,
108 'Expected a file name (string), got: %s'
109 % include)
110 include_path = os.path.join(self.input_dir, include)
Stefan Hajnoczi7ac9a9d2014-08-27 12:08:51 +0100111 for elem in self.include_hist:
112 if include_path == elem[1]:
113 raise QAPIExprError(expr_info, "Inclusion loop for %s"
114 % include)
Benoît Canet24fd8482014-05-16 12:51:56 +0200115 # skip multiple include of the same file
116 if include_path in previously_included:
117 continue
Lluís Vilanovaa719a272014-05-07 20:46:15 +0200118 try:
119 fobj = open(include_path, 'r')
Luiz Capitulino34788812014-05-20 13:50:19 -0400120 except IOError, e:
Lluís Vilanovaa719a272014-05-07 20:46:15 +0200121 raise QAPIExprError(expr_info,
122 '%s: %s' % (e.strerror, include))
Benoît Canet24fd8482014-05-16 12:51:56 +0200123 exprs_include = QAPISchema(fobj, include, self.include_hist,
124 previously_included, expr_info)
Lluís Vilanovaa719a272014-05-07 20:46:15 +0200125 self.exprs.extend(exprs_include.exprs)
126 else:
127 expr_elem = {'expr': expr,
128 'info': expr_info}
129 self.exprs.append(expr_elem)
Michael Roth0f923be2011-07-19 14:50:39 -0500130
Markus Armbrusterc7a3f252013-07-27 17:41:55 +0200131 def accept(self):
132 while True:
Markus Armbrusterc7a3f252013-07-27 17:41:55 +0200133 self.tok = self.src[self.cursor]
Markus Armbruster2caba362013-07-27 17:41:56 +0200134 self.pos = self.cursor
Markus Armbrusterc7a3f252013-07-27 17:41:55 +0200135 self.cursor += 1
136 self.val = None
Michael Roth0f923be2011-07-19 14:50:39 -0500137
Markus Armbrusterf1a145e2013-07-27 17:42:01 +0200138 if self.tok == '#':
Markus Armbrusterc7a3f252013-07-27 17:41:55 +0200139 self.cursor = self.src.find('\n', self.cursor)
140 elif self.tok in ['{', '}', ':', ',', '[', ']']:
141 return
142 elif self.tok == "'":
143 string = ''
144 esc = False
145 while True:
146 ch = self.src[self.cursor]
147 self.cursor += 1
148 if ch == '\n':
Markus Armbruster2caba362013-07-27 17:41:56 +0200149 raise QAPISchemaError(self,
150 'Missing terminating "\'"')
Markus Armbrusterc7a3f252013-07-27 17:41:55 +0200151 if esc:
152 string += ch
153 esc = False
154 elif ch == "\\":
155 esc = True
156 elif ch == "'":
157 self.val = string
158 return
159 else:
160 string += ch
Fam Zhenge53188a2015-05-04 09:05:18 -0600161 elif self.tok in "tfn":
162 val = self.src[self.cursor - 1:]
163 if val.startswith("true"):
164 self.val = True
165 self.cursor += 3
166 return
167 elif val.startswith("false"):
168 self.val = False
169 self.cursor += 4
170 return
171 elif val.startswith("null"):
172 self.val = None
173 self.cursor += 3
174 return
Markus Armbrusterc7a3f252013-07-27 17:41:55 +0200175 elif self.tok == '\n':
176 if self.cursor == len(self.src):
177 self.tok = None
178 return
Wenchao Xia515b9432014-03-04 18:44:33 -0800179 self.line += 1
180 self.line_pos = self.cursor
Markus Armbruster9213aa52013-07-27 17:41:57 +0200181 elif not self.tok.isspace():
182 raise QAPISchemaError(self, 'Stray "%s"' % self.tok)
Michael Roth0f923be2011-07-19 14:50:39 -0500183
Markus Armbrusterc7a3f252013-07-27 17:41:55 +0200184 def get_members(self):
185 expr = OrderedDict()
Markus Armbruster6974ccd2013-07-27 17:41:58 +0200186 if self.tok == '}':
187 self.accept()
188 return expr
189 if self.tok != "'":
190 raise QAPISchemaError(self, 'Expected string or "}"')
191 while True:
Markus Armbrusterc7a3f252013-07-27 17:41:55 +0200192 key = self.val
193 self.accept()
Markus Armbruster6974ccd2013-07-27 17:41:58 +0200194 if self.tok != ':':
195 raise QAPISchemaError(self, 'Expected ":"')
196 self.accept()
Wenchao Xia4b359912014-03-04 18:44:32 -0800197 if key in expr:
198 raise QAPISchemaError(self, 'Duplicate key "%s"' % key)
Markus Armbruster5f3cd2b2013-07-27 17:41:59 +0200199 expr[key] = self.get_expr(True)
Markus Armbruster6974ccd2013-07-27 17:41:58 +0200200 if self.tok == '}':
Markus Armbrusterc7a3f252013-07-27 17:41:55 +0200201 self.accept()
Markus Armbruster6974ccd2013-07-27 17:41:58 +0200202 return expr
203 if self.tok != ',':
204 raise QAPISchemaError(self, 'Expected "," or "}"')
205 self.accept()
206 if self.tok != "'":
207 raise QAPISchemaError(self, 'Expected string')
Michael Roth0f923be2011-07-19 14:50:39 -0500208
Markus Armbrusterc7a3f252013-07-27 17:41:55 +0200209 def get_values(self):
210 expr = []
Markus Armbruster6974ccd2013-07-27 17:41:58 +0200211 if self.tok == ']':
212 self.accept()
213 return expr
Fam Zhenge53188a2015-05-04 09:05:18 -0600214 if not self.tok in "{['tfn":
215 raise QAPISchemaError(self, 'Expected "{", "[", "]", string, '
216 'boolean or "null"')
Markus Armbruster6974ccd2013-07-27 17:41:58 +0200217 while True:
Markus Armbruster5f3cd2b2013-07-27 17:41:59 +0200218 expr.append(self.get_expr(True))
Markus Armbruster6974ccd2013-07-27 17:41:58 +0200219 if self.tok == ']':
Markus Armbrusterc7a3f252013-07-27 17:41:55 +0200220 self.accept()
Markus Armbruster6974ccd2013-07-27 17:41:58 +0200221 return expr
222 if self.tok != ',':
223 raise QAPISchemaError(self, 'Expected "," or "]"')
224 self.accept()
Michael Roth0f923be2011-07-19 14:50:39 -0500225
Markus Armbruster5f3cd2b2013-07-27 17:41:59 +0200226 def get_expr(self, nested):
227 if self.tok != '{' and not nested:
228 raise QAPISchemaError(self, 'Expected "{"')
Markus Armbrusterc7a3f252013-07-27 17:41:55 +0200229 if self.tok == '{':
230 self.accept()
231 expr = self.get_members()
232 elif self.tok == '[':
233 self.accept()
234 expr = self.get_values()
Fam Zhenge53188a2015-05-04 09:05:18 -0600235 elif self.tok in "'tfn":
Markus Armbrusterc7a3f252013-07-27 17:41:55 +0200236 expr = self.val
237 self.accept()
Markus Armbruster6974ccd2013-07-27 17:41:58 +0200238 else:
239 raise QAPISchemaError(self, 'Expected "{", "[" or string')
Markus Armbrusterc7a3f252013-07-27 17:41:55 +0200240 return expr
Kevin Wolfbd9927f2013-07-01 16:31:50 +0200241
Wenchao Xiab86b05e2014-03-04 18:44:34 -0800242def find_base_fields(base):
243 base_struct_define = find_struct(base)
244 if not base_struct_define:
245 return None
246 return base_struct_define['data']
247
Eric Blake811d04f2015-05-04 09:05:10 -0600248# Return the qtype of an alternate branch, or None on error.
249def find_alternate_member_qtype(qapi_type):
Eric Blake44bd1272015-05-04 09:05:08 -0600250 if builtin_types.has_key(qapi_type):
251 return builtin_types[qapi_type]
252 elif find_struct(qapi_type):
253 return "QTYPE_QDICT"
254 elif find_enum(qapi_type):
255 return "QTYPE_QSTRING"
Eric Blake811d04f2015-05-04 09:05:10 -0600256 elif find_union(qapi_type):
257 return "QTYPE_QDICT"
Eric Blake44bd1272015-05-04 09:05:08 -0600258 return None
259
Wenchao Xiabceae762014-03-06 17:08:56 -0800260# Return the discriminator enum define if discriminator is specified as an
261# enum type, otherwise return None.
262def discriminator_find_enum_define(expr):
263 base = expr.get('base')
264 discriminator = expr.get('discriminator')
265
266 if not (discriminator and base):
267 return None
268
269 base_fields = find_base_fields(base)
270 if not base_fields:
271 return None
272
273 discriminator_type = base_fields.get(discriminator)
274 if not discriminator_type:
275 return None
276
277 return find_enum(discriminator_type)
278
Wenchao Xia21cd70d2014-06-18 08:43:28 +0200279def check_event(expr, expr_info):
Eric Blake4dc2e692015-05-04 09:05:17 -0600280 global events
281 name = expr['event']
Wenchao Xia21cd70d2014-06-18 08:43:28 +0200282 params = expr.get('data')
Eric Blake4dc2e692015-05-04 09:05:17 -0600283
284 if name.upper() == 'MAX':
285 raise QAPIExprError(expr_info, "Event name 'MAX' cannot be created")
286 events.append(name)
287
Wenchao Xia21cd70d2014-06-18 08:43:28 +0200288 if params:
289 for argname, argentry, optional, structured in parse_args(params):
290 if structured:
291 raise QAPIExprError(expr_info,
292 "Nested structure define in event is not "
Wenchao Xiad6f9c822014-06-24 16:33:59 -0700293 "supported, event '%s', argname '%s'"
Wenchao Xia21cd70d2014-06-18 08:43:28 +0200294 % (expr['event'], argname))
295
Wenchao Xiab86b05e2014-03-04 18:44:34 -0800296def check_union(expr, expr_info):
297 name = expr['union']
298 base = expr.get('base')
299 discriminator = expr.get('discriminator')
300 members = expr['data']
Eric Blake44bd1272015-05-04 09:05:08 -0600301 values = { 'MAX': '(automatic)' }
Wenchao Xiab86b05e2014-03-04 18:44:34 -0800302
Eric Blakea8d4a2e2015-05-04 09:05:07 -0600303 # If the object has a member 'base', its value must name a complex type,
304 # and there must be a discriminator.
305 if base is not None:
306 if discriminator is None:
307 raise QAPIExprError(expr_info,
308 "Union '%s' requires a discriminator to go "
309 "along with base" %name)
Eric Blake44bd1272015-05-04 09:05:08 -0600310
Eric Blake811d04f2015-05-04 09:05:10 -0600311 # Two types of unions, determined by discriminator.
Eric Blake811d04f2015-05-04 09:05:10 -0600312
313 # With no discriminator it is a simple union.
314 if discriminator is None:
Eric Blake44bd1272015-05-04 09:05:08 -0600315 enum_define = None
316 if base is not None:
317 raise QAPIExprError(expr_info,
Eric Blake811d04f2015-05-04 09:05:10 -0600318 "Simple union '%s' must not have a base"
Eric Blake44bd1272015-05-04 09:05:08 -0600319 % name)
320
321 # Else, it's a flat union.
322 else:
323 # The object must have a string member 'base'.
324 if not isinstance(base, str):
325 raise QAPIExprError(expr_info,
326 "Flat union '%s' must have a string base field"
327 % name)
Wenchao Xiab86b05e2014-03-04 18:44:34 -0800328 base_fields = find_base_fields(base)
329 if not base_fields:
330 raise QAPIExprError(expr_info,
331 "Base '%s' is not a valid type"
332 % base)
333
Wenchao Xiab86b05e2014-03-04 18:44:34 -0800334 # The value of member 'discriminator' must name a member of the
335 # base type.
Eric Blake44bd1272015-05-04 09:05:08 -0600336 if not isinstance(discriminator, str):
337 raise QAPIExprError(expr_info,
338 "Flat union '%s' discriminator must be a string"
339 % name)
Wenchao Xiab86b05e2014-03-04 18:44:34 -0800340 discriminator_type = base_fields.get(discriminator)
341 if not discriminator_type:
342 raise QAPIExprError(expr_info,
343 "Discriminator '%s' is not a member of base "
344 "type '%s'"
345 % (discriminator, base))
346 enum_define = find_enum(discriminator_type)
Wenchao Xia52230702014-03-04 18:44:39 -0800347 # Do not allow string discriminator
348 if not enum_define:
349 raise QAPIExprError(expr_info,
350 "Discriminator '%s' must be of enumeration "
351 "type" % discriminator)
Wenchao Xiab86b05e2014-03-04 18:44:34 -0800352
353 # Check every branch
354 for (key, value) in members.items():
Eric Blake44bd1272015-05-04 09:05:08 -0600355 # If the discriminator names an enum type, then all members
Wenchao Xiab86b05e2014-03-04 18:44:34 -0800356 # of 'data' must also be members of the enum type.
Eric Blake44bd1272015-05-04 09:05:08 -0600357 if enum_define:
358 if not key in enum_define['enum_values']:
359 raise QAPIExprError(expr_info,
360 "Discriminator value '%s' is not found in "
361 "enum '%s'" %
362 (key, enum_define["enum_name"]))
363
364 # Otherwise, check for conflicts in the generated enum
365 else:
366 c_key = _generate_enum_string(key)
367 if c_key in values:
368 raise QAPIExprError(expr_info,
369 "Union '%s' member '%s' clashes with '%s'"
370 % (name, key, values[c_key]))
371 values[c_key] = key
372
Eric Blake811d04f2015-05-04 09:05:10 -0600373def check_alternate(expr, expr_info):
Eric Blakeab916fa2015-05-04 09:05:13 -0600374 name = expr['alternate']
Eric Blake811d04f2015-05-04 09:05:10 -0600375 members = expr['data']
376 values = { 'MAX': '(automatic)' }
377 types_seen = {}
Eric Blake44bd1272015-05-04 09:05:08 -0600378
Eric Blake811d04f2015-05-04 09:05:10 -0600379 # Check every branch
380 for (key, value) in members.items():
381 # Check for conflicts in the generated enum
382 c_key = _generate_enum_string(key)
383 if c_key in values:
384 raise QAPIExprError(expr_info,
Eric Blakeab916fa2015-05-04 09:05:13 -0600385 "Alternate '%s' member '%s' clashes with '%s'"
386 % (name, key, values[c_key]))
Eric Blake811d04f2015-05-04 09:05:10 -0600387 values[c_key] = key
388
389 # Ensure alternates have no type conflicts.
390 if isinstance(value, list):
391 raise QAPIExprError(expr_info,
Eric Blakeab916fa2015-05-04 09:05:13 -0600392 "Alternate '%s' member '%s' must "
Eric Blake811d04f2015-05-04 09:05:10 -0600393 "not be array type" % (name, key))
394 qtype = find_alternate_member_qtype(value)
395 if not qtype:
396 raise QAPIExprError(expr_info,
Eric Blakeab916fa2015-05-04 09:05:13 -0600397 "Alternate '%s' member '%s' has "
Eric Blake811d04f2015-05-04 09:05:10 -0600398 "invalid type '%s'" % (name, key, value))
399 if qtype in types_seen:
400 raise QAPIExprError(expr_info,
Eric Blakeab916fa2015-05-04 09:05:13 -0600401 "Alternate '%s' member '%s' can't "
Eric Blake811d04f2015-05-04 09:05:10 -0600402 "be distinguished from member '%s'"
403 % (name, key, types_seen[qtype]))
404 types_seen[qtype] = key
Wenchao Xiab86b05e2014-03-04 18:44:34 -0800405
Eric Blakecf393592015-05-04 09:05:04 -0600406def check_enum(expr, expr_info):
407 name = expr['enum']
408 members = expr.get('data')
409 values = { 'MAX': '(automatic)' }
410
411 if not isinstance(members, list):
412 raise QAPIExprError(expr_info,
413 "Enum '%s' requires an array for 'data'" % name)
414 for member in members:
415 if not isinstance(member, str):
416 raise QAPIExprError(expr_info,
417 "Enum '%s' member '%s' is not a string"
418 % (name, member))
419 key = _generate_enum_string(member)
420 if key in values:
421 raise QAPIExprError(expr_info,
422 "Enum '%s' member '%s' clashes with '%s'"
423 % (name, member, values[key]))
424 values[key] = member
425
Wenchao Xiab86b05e2014-03-04 18:44:34 -0800426def check_exprs(schema):
427 for expr_elem in schema.exprs:
428 expr = expr_elem['expr']
Eric Blakecf393592015-05-04 09:05:04 -0600429 info = expr_elem['info']
430
431 if expr.has_key('enum'):
432 check_enum(expr, info)
433 elif expr.has_key('union'):
Eric Blakeab916fa2015-05-04 09:05:13 -0600434 check_union(expr, info)
435 elif expr.has_key('alternate'):
436 check_alternate(expr, info)
Eric Blakecf393592015-05-04 09:05:04 -0600437 elif expr.has_key('event'):
438 check_event(expr, info)
Wenchao Xiab86b05e2014-03-04 18:44:34 -0800439
Eric Blake0545f6b2015-05-04 09:05:15 -0600440def check_keys(expr_elem, meta, required, optional=[]):
441 expr = expr_elem['expr']
442 info = expr_elem['info']
443 name = expr[meta]
444 if not isinstance(name, str):
445 raise QAPIExprError(info,
446 "'%s' key must have a string value" % meta)
447 required = required + [ meta ]
448 for (key, value) in expr.items():
449 if not key in required and not key in optional:
450 raise QAPIExprError(info,
451 "Unknown key '%s' in %s '%s'"
452 % (key, meta, name))
453 for key in required:
454 if not expr.has_key(key):
455 raise QAPIExprError(info,
456 "Key '%s' is missing from %s '%s'"
457 % (key, meta, name))
458
459
Lluís Vilanova33aaad52014-05-02 15:52:35 +0200460def parse_schema(input_file):
Eric Blake4dc2e692015-05-04 09:05:17 -0600461 global all_names
462 exprs = []
463
Eric Blake268a1c52015-05-04 09:05:09 -0600464 # First pass: read entire file into memory
Markus Armbruster2caba362013-07-27 17:41:56 +0200465 try:
Lluís Vilanova33aaad52014-05-02 15:52:35 +0200466 schema = QAPISchema(open(input_file, "r"))
Lluís Vilanovaa719a272014-05-07 20:46:15 +0200467 except (QAPISchemaError, QAPIExprError), e:
Markus Armbruster2caba362013-07-27 17:41:56 +0200468 print >>sys.stderr, e
469 exit(1)
470
Wenchao Xiab86b05e2014-03-04 18:44:34 -0800471 try:
Eric Blake0545f6b2015-05-04 09:05:15 -0600472 # Next pass: learn the types and check for valid expression keys. At
473 # this point, top-level 'include' has already been flattened.
Eric Blake4dc2e692015-05-04 09:05:17 -0600474 for builtin in builtin_types.keys():
475 all_names[builtin] = 'built-in'
Eric Blake268a1c52015-05-04 09:05:09 -0600476 for expr_elem in schema.exprs:
477 expr = expr_elem['expr']
Eric Blake4dc2e692015-05-04 09:05:17 -0600478 info = expr_elem['info']
Eric Blake268a1c52015-05-04 09:05:09 -0600479 if expr.has_key('enum'):
Eric Blake0545f6b2015-05-04 09:05:15 -0600480 check_keys(expr_elem, 'enum', ['data'])
Eric Blake4dc2e692015-05-04 09:05:17 -0600481 add_enum(expr['enum'], info, expr['data'])
Eric Blake268a1c52015-05-04 09:05:09 -0600482 elif expr.has_key('union'):
Eric Blake0545f6b2015-05-04 09:05:15 -0600483 check_keys(expr_elem, 'union', ['data'],
484 ['base', 'discriminator'])
Eric Blake4dc2e692015-05-04 09:05:17 -0600485 add_union(expr, info)
Eric Blake0545f6b2015-05-04 09:05:15 -0600486 elif expr.has_key('alternate'):
487 check_keys(expr_elem, 'alternate', ['data'])
Eric Blake4dc2e692015-05-04 09:05:17 -0600488 add_name(expr['alternate'], info, 'alternate')
Eric Blake268a1c52015-05-04 09:05:09 -0600489 elif expr.has_key('type'):
Eric Blake0545f6b2015-05-04 09:05:15 -0600490 check_keys(expr_elem, 'type', ['data'], ['base'])
Eric Blake4dc2e692015-05-04 09:05:17 -0600491 add_struct(expr, info)
Eric Blake0545f6b2015-05-04 09:05:15 -0600492 elif expr.has_key('command'):
493 check_keys(expr_elem, 'command', [],
494 ['data', 'returns', 'gen', 'success-response'])
Eric Blake4dc2e692015-05-04 09:05:17 -0600495 add_name(expr['command'], info, 'command')
Eric Blake0545f6b2015-05-04 09:05:15 -0600496 elif expr.has_key('event'):
497 check_keys(expr_elem, 'event', [], ['data'])
Eric Blake4dc2e692015-05-04 09:05:17 -0600498 add_name(expr['event'], info, 'event')
Eric Blake0545f6b2015-05-04 09:05:15 -0600499 else:
500 raise QAPIExprError(expr_elem['info'],
501 "Expression is missing metatype")
Eric Blake268a1c52015-05-04 09:05:09 -0600502 exprs.append(expr)
503
504 # Try again for hidden UnionKind enum
505 for expr_elem in schema.exprs:
506 expr = expr_elem['expr']
507 if expr.has_key('union'):
508 if not discriminator_find_enum_define(expr):
Eric Blake4dc2e692015-05-04 09:05:17 -0600509 add_enum('%sKind' % expr['union'], expr_elem['info'],
510 implicit=True)
Eric Blakeab916fa2015-05-04 09:05:13 -0600511 elif expr.has_key('alternate'):
Eric Blake4dc2e692015-05-04 09:05:17 -0600512 add_enum('%sKind' % expr['alternate'], expr_elem['info'],
513 implicit=True)
Eric Blake268a1c52015-05-04 09:05:09 -0600514
515 # Final pass - validate that exprs make sense
Wenchao Xiab86b05e2014-03-04 18:44:34 -0800516 check_exprs(schema)
517 except QAPIExprError, e:
518 print >>sys.stderr, e
519 exit(1)
520
Michael Roth0f923be2011-07-19 14:50:39 -0500521 return exprs
522
523def parse_args(typeinfo):
Eric Blakefe2a9302015-05-04 09:05:02 -0600524 if isinstance(typeinfo, str):
Kevin Wolfb35284e2013-07-01 16:31:51 +0200525 struct = find_struct(typeinfo)
526 assert struct != None
527 typeinfo = struct['data']
528
Michael Roth0f923be2011-07-19 14:50:39 -0500529 for member in typeinfo:
530 argname = member
531 argentry = typeinfo[member]
532 optional = False
533 structured = False
534 if member.startswith('*'):
535 argname = member[1:]
536 optional = True
537 if isinstance(argentry, OrderedDict):
538 structured = True
539 yield (argname, argentry, optional, structured)
540
541def de_camel_case(name):
542 new_name = ''
543 for ch in name:
544 if ch.isupper() and new_name:
545 new_name += '_'
546 if ch == '-':
547 new_name += '_'
548 else:
549 new_name += ch.lower()
550 return new_name
551
552def camel_case(name):
553 new_name = ''
554 first = True
555 for ch in name:
556 if ch in ['_', '-']:
557 first = True
558 elif first:
559 new_name += ch.upper()
560 first = False
561 else:
562 new_name += ch.lower()
563 return new_name
564
Paolo Bonzinieda50a62012-09-19 16:31:06 +0200565def c_var(name, protect=True):
Blue Swirl427a1a22012-07-30 15:46:55 +0000566 # ANSI X3J11/88-090, 3.1.1
567 c89_words = set(['auto', 'break', 'case', 'char', 'const', 'continue',
568 'default', 'do', 'double', 'else', 'enum', 'extern', 'float',
569 'for', 'goto', 'if', 'int', 'long', 'register', 'return',
570 'short', 'signed', 'sizeof', 'static', 'struct', 'switch',
571 'typedef', 'union', 'unsigned', 'void', 'volatile', 'while'])
572 # ISO/IEC 9899:1999, 6.4.1
573 c99_words = set(['inline', 'restrict', '_Bool', '_Complex', '_Imaginary'])
574 # ISO/IEC 9899:2011, 6.4.1
575 c11_words = set(['_Alignas', '_Alignof', '_Atomic', '_Generic', '_Noreturn',
576 '_Static_assert', '_Thread_local'])
577 # GCC http://gcc.gnu.org/onlinedocs/gcc-4.7.1/gcc/C-Extensions.html
578 # excluding _.*
579 gcc_words = set(['asm', 'typeof'])
Tomoki Sekiyama6f880092013-08-07 11:39:43 -0400580 # C++ ISO/IEC 14882:2003 2.11
581 cpp_words = set(['bool', 'catch', 'class', 'const_cast', 'delete',
582 'dynamic_cast', 'explicit', 'false', 'friend', 'mutable',
583 'namespace', 'new', 'operator', 'private', 'protected',
584 'public', 'reinterpret_cast', 'static_cast', 'template',
585 'this', 'throw', 'true', 'try', 'typeid', 'typename',
586 'using', 'virtual', 'wchar_t',
587 # alternative representations
588 'and', 'and_eq', 'bitand', 'bitor', 'compl', 'not',
589 'not_eq', 'or', 'or_eq', 'xor', 'xor_eq'])
Paolo Bonzini10577252012-09-19 16:31:07 +0200590 # namespace pollution:
Max Reitz8592a542013-12-20 19:28:18 +0100591 polluted_words = set(['unix', 'errno'])
Tomoki Sekiyama6f880092013-08-07 11:39:43 -0400592 if protect and (name in c89_words | c99_words | c11_words | gcc_words | cpp_words | polluted_words):
Blue Swirl427a1a22012-07-30 15:46:55 +0000593 return "q_" + name
Federico Simoncellic9da2282012-03-20 13:54:35 +0000594 return name.replace('-', '_').lstrip("*")
595
Paolo Bonzinieda50a62012-09-19 16:31:06 +0200596def c_fun(name, protect=True):
597 return c_var(name, protect).replace('.', '_')
Michael Roth0f923be2011-07-19 14:50:39 -0500598
599def c_list_type(name):
600 return '%sList' % name
601
602def type_name(name):
603 if type(name) == list:
604 return c_list_type(name[0])
605 return name
606
Eric Blake4dc2e692015-05-04 09:05:17 -0600607def add_name(name, info, meta, implicit = False):
608 global all_names
609 if name in all_names:
610 raise QAPIExprError(info,
611 "%s '%s' is already defined"
612 % (all_names[name], name))
613 if not implicit and name[-4:] == 'Kind':
614 raise QAPIExprError(info,
615 "%s '%s' should not end in 'Kind'"
616 % (meta, name))
617 all_names[name] = meta
Kevin Wolfb35284e2013-07-01 16:31:51 +0200618
Eric Blake4dc2e692015-05-04 09:05:17 -0600619def add_struct(definition, info):
Kevin Wolfb35284e2013-07-01 16:31:51 +0200620 global struct_types
Eric Blake4dc2e692015-05-04 09:05:17 -0600621 name = definition['type']
622 add_name(name, info, 'struct')
Kevin Wolfb35284e2013-07-01 16:31:51 +0200623 struct_types.append(definition)
624
625def find_struct(name):
626 global struct_types
627 for struct in struct_types:
628 if struct['type'] == name:
629 return struct
630 return None
Michael Roth0f923be2011-07-19 14:50:39 -0500631
Eric Blake4dc2e692015-05-04 09:05:17 -0600632def add_union(definition, info):
Kevin Wolfea66c6d2013-07-16 10:49:41 +0200633 global union_types
Eric Blake4dc2e692015-05-04 09:05:17 -0600634 name = definition['union']
635 add_name(name, info, 'union')
Eric Blakeab916fa2015-05-04 09:05:13 -0600636 union_types.append(definition)
Kevin Wolfea66c6d2013-07-16 10:49:41 +0200637
638def find_union(name):
639 global union_types
640 for union in union_types:
641 if union['union'] == name:
642 return union
643 return None
644
Eric Blake4dc2e692015-05-04 09:05:17 -0600645def add_enum(name, info, enum_values = None, implicit = False):
Michael Roth0f923be2011-07-19 14:50:39 -0500646 global enum_types
Eric Blake4dc2e692015-05-04 09:05:17 -0600647 add_name(name, info, 'enum', implicit)
Wenchao Xiadad1fca2014-03-04 18:44:31 -0800648 enum_types.append({"enum_name": name, "enum_values": enum_values})
649
650def find_enum(name):
651 global enum_types
652 for enum in enum_types:
653 if enum['enum_name'] == name:
654 return enum
655 return None
Michael Roth0f923be2011-07-19 14:50:39 -0500656
657def is_enum(name):
Wenchao Xiadad1fca2014-03-04 18:44:31 -0800658 return find_enum(name) != None
Michael Roth0f923be2011-07-19 14:50:39 -0500659
Amos Kong05dfb262014-06-10 19:25:53 +0800660eatspace = '\033EATSPACE.'
661
662# A special suffix is added in c_type() for pointer types, and it's
663# stripped in mcgen(). So please notice this when you check the return
664# value of c_type() outside mcgen().
Amos Kong0d14eeb2014-06-10 19:25:52 +0800665def c_type(name, is_param=False):
Michael Roth0f923be2011-07-19 14:50:39 -0500666 if name == 'str':
Amos Kong0d14eeb2014-06-10 19:25:52 +0800667 if is_param:
Amos Kong05dfb262014-06-10 19:25:53 +0800668 return 'const char *' + eatspace
669 return 'char *' + eatspace
670
Michael Roth0f923be2011-07-19 14:50:39 -0500671 elif name == 'int':
672 return 'int64_t'
Laszlo Ersekc46f18c2012-07-17 16:17:06 +0200673 elif (name == 'int8' or name == 'int16' or name == 'int32' or
674 name == 'int64' or name == 'uint8' or name == 'uint16' or
675 name == 'uint32' or name == 'uint64'):
676 return name + '_t'
Laszlo Ersek092705d2012-07-17 16:17:07 +0200677 elif name == 'size':
678 return 'uint64_t'
Michael Roth0f923be2011-07-19 14:50:39 -0500679 elif name == 'bool':
680 return 'bool'
681 elif name == 'number':
682 return 'double'
683 elif type(name) == list:
Amos Kong05dfb262014-06-10 19:25:53 +0800684 return '%s *%s' % (c_list_type(name[0]), eatspace)
Michael Roth0f923be2011-07-19 14:50:39 -0500685 elif is_enum(name):
686 return name
687 elif name == None or len(name) == 0:
688 return 'void'
Eric Blake4dc2e692015-05-04 09:05:17 -0600689 elif name in events:
Amos Kong05dfb262014-06-10 19:25:53 +0800690 return '%sEvent *%s' % (camel_case(name), eatspace)
Michael Roth0f923be2011-07-19 14:50:39 -0500691 else:
Amos Kong05dfb262014-06-10 19:25:53 +0800692 return '%s *%s' % (name, eatspace)
693
694def is_c_ptr(name):
695 suffix = "*" + eatspace
696 return c_type(name).endswith(suffix)
Michael Roth0f923be2011-07-19 14:50:39 -0500697
698def genindent(count):
699 ret = ""
700 for i in range(count):
701 ret += " "
702 return ret
703
704indent_level = 0
705
706def push_indent(indent_amount=4):
707 global indent_level
708 indent_level += indent_amount
709
710def pop_indent(indent_amount=4):
711 global indent_level
712 indent_level -= indent_amount
713
714def cgen(code, **kwds):
715 indent = genindent(indent_level)
716 lines = code.split('\n')
717 lines = map(lambda x: indent + x, lines)
718 return '\n'.join(lines) % kwds + '\n'
719
720def mcgen(code, **kwds):
Amos Kong05dfb262014-06-10 19:25:53 +0800721 raw = cgen('\n'.join(code.split('\n')[1:-1]), **kwds)
722 return re.sub(re.escape(eatspace) + ' *', '', raw)
Michael Roth0f923be2011-07-19 14:50:39 -0500723
724def basename(filename):
725 return filename.split("/")[-1]
726
727def guardname(filename):
Michael Rothd8e1f212011-11-29 16:47:48 -0600728 guard = basename(filename).rsplit(".", 1)[0]
729 for substr in [".", " ", "-"]:
730 guard = guard.replace(substr, "_")
731 return guard.upper() + '_H'
Michael Rothc0afa9c2013-05-10 17:46:00 -0500732
733def guardstart(name):
734 return mcgen('''
735
736#ifndef %(name)s
737#define %(name)s
738
739''',
740 name=guardname(name))
741
742def guardend(name):
743 return mcgen('''
744
745#endif /* %(name)s */
746
747''',
748 name=guardname(name))
Wenchao Xia62996592014-03-04 18:44:35 -0800749
Wenchao Xia5d371f42014-03-04 18:44:40 -0800750# ENUMName -> ENUM_NAME, EnumName1 -> ENUM_NAME1
751# ENUM_NAME -> ENUM_NAME, ENUM_NAME1 -> ENUM_NAME1, ENUM_Name2 -> ENUM_NAME2
752# ENUM24_Name -> ENUM24_NAME
753def _generate_enum_string(value):
754 c_fun_str = c_fun(value, False)
Wenchao Xiab0b58192014-03-04 18:44:36 -0800755 if value.isupper():
Wenchao Xia5d371f42014-03-04 18:44:40 -0800756 return c_fun_str
757
Wenchao Xia62996592014-03-04 18:44:35 -0800758 new_name = ''
Wenchao Xia5d371f42014-03-04 18:44:40 -0800759 l = len(c_fun_str)
760 for i in range(l):
761 c = c_fun_str[i]
762 # When c is upper and no "_" appears before, do more checks
763 if c.isupper() and (i > 0) and c_fun_str[i - 1] != "_":
764 # Case 1: next string is lower
765 # Case 2: previous string is digit
766 if (i < (l - 1) and c_fun_str[i + 1].islower()) or \
767 c_fun_str[i - 1].isdigit():
768 new_name += '_'
Wenchao Xia62996592014-03-04 18:44:35 -0800769 new_name += c
770 return new_name.lstrip('_').upper()
Wenchao Xiab0b58192014-03-04 18:44:36 -0800771
772def generate_enum_full_value(enum_name, enum_value):
Wenchao Xia5d371f42014-03-04 18:44:40 -0800773 abbrev_string = _generate_enum_string(enum_name)
774 value_string = _generate_enum_string(enum_value)
Wenchao Xiab0b58192014-03-04 18:44:36 -0800775 return "%s_%s" % (abbrev_string, value_string)