blob: 6a339d60b5b49614cfc3fbe415b538eb55a2905a [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
161 elif self.tok == '\n':
162 if self.cursor == len(self.src):
163 self.tok = None
164 return
Wenchao Xia515b9432014-03-04 18:44:33 -0800165 self.line += 1
166 self.line_pos = self.cursor
Markus Armbruster9213aa52013-07-27 17:41:57 +0200167 elif not self.tok.isspace():
168 raise QAPISchemaError(self, 'Stray "%s"' % self.tok)
Michael Roth0f923be2011-07-19 14:50:39 -0500169
Markus Armbrusterc7a3f252013-07-27 17:41:55 +0200170 def get_members(self):
171 expr = OrderedDict()
Markus Armbruster6974ccd2013-07-27 17:41:58 +0200172 if self.tok == '}':
173 self.accept()
174 return expr
175 if self.tok != "'":
176 raise QAPISchemaError(self, 'Expected string or "}"')
177 while True:
Markus Armbrusterc7a3f252013-07-27 17:41:55 +0200178 key = self.val
179 self.accept()
Markus Armbruster6974ccd2013-07-27 17:41:58 +0200180 if self.tok != ':':
181 raise QAPISchemaError(self, 'Expected ":"')
182 self.accept()
Wenchao Xia4b359912014-03-04 18:44:32 -0800183 if key in expr:
184 raise QAPISchemaError(self, 'Duplicate key "%s"' % key)
Markus Armbruster5f3cd2b2013-07-27 17:41:59 +0200185 expr[key] = self.get_expr(True)
Markus Armbruster6974ccd2013-07-27 17:41:58 +0200186 if self.tok == '}':
Markus Armbrusterc7a3f252013-07-27 17:41:55 +0200187 self.accept()
Markus Armbruster6974ccd2013-07-27 17:41:58 +0200188 return expr
189 if self.tok != ',':
190 raise QAPISchemaError(self, 'Expected "," or "}"')
191 self.accept()
192 if self.tok != "'":
193 raise QAPISchemaError(self, 'Expected string')
Michael Roth0f923be2011-07-19 14:50:39 -0500194
Markus Armbrusterc7a3f252013-07-27 17:41:55 +0200195 def get_values(self):
196 expr = []
Markus Armbruster6974ccd2013-07-27 17:41:58 +0200197 if self.tok == ']':
198 self.accept()
199 return expr
200 if not self.tok in [ '{', '[', "'" ]:
201 raise QAPISchemaError(self, 'Expected "{", "[", "]" or string')
202 while True:
Markus Armbruster5f3cd2b2013-07-27 17:41:59 +0200203 expr.append(self.get_expr(True))
Markus Armbruster6974ccd2013-07-27 17:41:58 +0200204 if self.tok == ']':
Markus Armbrusterc7a3f252013-07-27 17:41:55 +0200205 self.accept()
Markus Armbruster6974ccd2013-07-27 17:41:58 +0200206 return expr
207 if self.tok != ',':
208 raise QAPISchemaError(self, 'Expected "," or "]"')
209 self.accept()
Michael Roth0f923be2011-07-19 14:50:39 -0500210
Markus Armbruster5f3cd2b2013-07-27 17:41:59 +0200211 def get_expr(self, nested):
212 if self.tok != '{' and not nested:
213 raise QAPISchemaError(self, 'Expected "{"')
Markus Armbrusterc7a3f252013-07-27 17:41:55 +0200214 if self.tok == '{':
215 self.accept()
216 expr = self.get_members()
217 elif self.tok == '[':
218 self.accept()
219 expr = self.get_values()
Markus Armbruster6974ccd2013-07-27 17:41:58 +0200220 elif self.tok == "'":
Markus Armbrusterc7a3f252013-07-27 17:41:55 +0200221 expr = self.val
222 self.accept()
Markus Armbruster6974ccd2013-07-27 17:41:58 +0200223 else:
224 raise QAPISchemaError(self, 'Expected "{", "[" or string')
Markus Armbrusterc7a3f252013-07-27 17:41:55 +0200225 return expr
Kevin Wolfbd9927f2013-07-01 16:31:50 +0200226
Wenchao Xiab86b05e2014-03-04 18:44:34 -0800227def find_base_fields(base):
228 base_struct_define = find_struct(base)
229 if not base_struct_define:
230 return None
231 return base_struct_define['data']
232
Eric Blake811d04f2015-05-04 09:05:10 -0600233# Return the qtype of an alternate branch, or None on error.
234def find_alternate_member_qtype(qapi_type):
Eric Blake44bd1272015-05-04 09:05:08 -0600235 if builtin_types.has_key(qapi_type):
236 return builtin_types[qapi_type]
237 elif find_struct(qapi_type):
238 return "QTYPE_QDICT"
239 elif find_enum(qapi_type):
240 return "QTYPE_QSTRING"
Eric Blake811d04f2015-05-04 09:05:10 -0600241 elif find_union(qapi_type):
242 return "QTYPE_QDICT"
Eric Blake44bd1272015-05-04 09:05:08 -0600243 return None
244
Wenchao Xiabceae762014-03-06 17:08:56 -0800245# Return the discriminator enum define if discriminator is specified as an
246# enum type, otherwise return None.
247def discriminator_find_enum_define(expr):
248 base = expr.get('base')
249 discriminator = expr.get('discriminator')
250
251 if not (discriminator and base):
252 return None
253
254 base_fields = find_base_fields(base)
255 if not base_fields:
256 return None
257
258 discriminator_type = base_fields.get(discriminator)
259 if not discriminator_type:
260 return None
261
262 return find_enum(discriminator_type)
263
Wenchao Xia21cd70d2014-06-18 08:43:28 +0200264def check_event(expr, expr_info):
Eric Blake4dc2e692015-05-04 09:05:17 -0600265 global events
266 name = expr['event']
Wenchao Xia21cd70d2014-06-18 08:43:28 +0200267 params = expr.get('data')
Eric Blake4dc2e692015-05-04 09:05:17 -0600268
269 if name.upper() == 'MAX':
270 raise QAPIExprError(expr_info, "Event name 'MAX' cannot be created")
271 events.append(name)
272
Wenchao Xia21cd70d2014-06-18 08:43:28 +0200273 if params:
274 for argname, argentry, optional, structured in parse_args(params):
275 if structured:
276 raise QAPIExprError(expr_info,
277 "Nested structure define in event is not "
Wenchao Xiad6f9c822014-06-24 16:33:59 -0700278 "supported, event '%s', argname '%s'"
Wenchao Xia21cd70d2014-06-18 08:43:28 +0200279 % (expr['event'], argname))
280
Wenchao Xiab86b05e2014-03-04 18:44:34 -0800281def check_union(expr, expr_info):
282 name = expr['union']
283 base = expr.get('base')
284 discriminator = expr.get('discriminator')
285 members = expr['data']
Eric Blake44bd1272015-05-04 09:05:08 -0600286 values = { 'MAX': '(automatic)' }
Wenchao Xiab86b05e2014-03-04 18:44:34 -0800287
Eric Blakea8d4a2e2015-05-04 09:05:07 -0600288 # If the object has a member 'base', its value must name a complex type,
289 # and there must be a discriminator.
290 if base is not None:
291 if discriminator is None:
292 raise QAPIExprError(expr_info,
293 "Union '%s' requires a discriminator to go "
294 "along with base" %name)
Eric Blake44bd1272015-05-04 09:05:08 -0600295
Eric Blake811d04f2015-05-04 09:05:10 -0600296 # Two types of unions, determined by discriminator.
Eric Blake811d04f2015-05-04 09:05:10 -0600297
298 # With no discriminator it is a simple union.
299 if discriminator is None:
Eric Blake44bd1272015-05-04 09:05:08 -0600300 enum_define = None
301 if base is not None:
302 raise QAPIExprError(expr_info,
Eric Blake811d04f2015-05-04 09:05:10 -0600303 "Simple union '%s' must not have a base"
Eric Blake44bd1272015-05-04 09:05:08 -0600304 % name)
305
306 # Else, it's a flat union.
307 else:
308 # The object must have a string member 'base'.
309 if not isinstance(base, str):
310 raise QAPIExprError(expr_info,
311 "Flat union '%s' must have a string base field"
312 % name)
Wenchao Xiab86b05e2014-03-04 18:44:34 -0800313 base_fields = find_base_fields(base)
314 if not base_fields:
315 raise QAPIExprError(expr_info,
316 "Base '%s' is not a valid type"
317 % base)
318
Wenchao Xiab86b05e2014-03-04 18:44:34 -0800319 # The value of member 'discriminator' must name a member of the
320 # base type.
Eric Blake44bd1272015-05-04 09:05:08 -0600321 if not isinstance(discriminator, str):
322 raise QAPIExprError(expr_info,
323 "Flat union '%s' discriminator must be a string"
324 % name)
Wenchao Xiab86b05e2014-03-04 18:44:34 -0800325 discriminator_type = base_fields.get(discriminator)
326 if not discriminator_type:
327 raise QAPIExprError(expr_info,
328 "Discriminator '%s' is not a member of base "
329 "type '%s'"
330 % (discriminator, base))
331 enum_define = find_enum(discriminator_type)
Wenchao Xia52230702014-03-04 18:44:39 -0800332 # Do not allow string discriminator
333 if not enum_define:
334 raise QAPIExprError(expr_info,
335 "Discriminator '%s' must be of enumeration "
336 "type" % discriminator)
Wenchao Xiab86b05e2014-03-04 18:44:34 -0800337
338 # Check every branch
339 for (key, value) in members.items():
Eric Blake44bd1272015-05-04 09:05:08 -0600340 # If the discriminator names an enum type, then all members
Wenchao Xiab86b05e2014-03-04 18:44:34 -0800341 # of 'data' must also be members of the enum type.
Eric Blake44bd1272015-05-04 09:05:08 -0600342 if enum_define:
343 if not key in enum_define['enum_values']:
344 raise QAPIExprError(expr_info,
345 "Discriminator value '%s' is not found in "
346 "enum '%s'" %
347 (key, enum_define["enum_name"]))
348
349 # Otherwise, check for conflicts in the generated enum
350 else:
351 c_key = _generate_enum_string(key)
352 if c_key in values:
353 raise QAPIExprError(expr_info,
354 "Union '%s' member '%s' clashes with '%s'"
355 % (name, key, values[c_key]))
356 values[c_key] = key
357
Eric Blake811d04f2015-05-04 09:05:10 -0600358def check_alternate(expr, expr_info):
Eric Blakeab916fa2015-05-04 09:05:13 -0600359 name = expr['alternate']
Eric Blake811d04f2015-05-04 09:05:10 -0600360 members = expr['data']
361 values = { 'MAX': '(automatic)' }
362 types_seen = {}
Eric Blake44bd1272015-05-04 09:05:08 -0600363
Eric Blake811d04f2015-05-04 09:05:10 -0600364 # Check every branch
365 for (key, value) in members.items():
366 # Check for conflicts in the generated enum
367 c_key = _generate_enum_string(key)
368 if c_key in values:
369 raise QAPIExprError(expr_info,
Eric Blakeab916fa2015-05-04 09:05:13 -0600370 "Alternate '%s' member '%s' clashes with '%s'"
371 % (name, key, values[c_key]))
Eric Blake811d04f2015-05-04 09:05:10 -0600372 values[c_key] = key
373
374 # Ensure alternates have no type conflicts.
375 if isinstance(value, list):
376 raise QAPIExprError(expr_info,
Eric Blakeab916fa2015-05-04 09:05:13 -0600377 "Alternate '%s' member '%s' must "
Eric Blake811d04f2015-05-04 09:05:10 -0600378 "not be array type" % (name, key))
379 qtype = find_alternate_member_qtype(value)
380 if not qtype:
381 raise QAPIExprError(expr_info,
Eric Blakeab916fa2015-05-04 09:05:13 -0600382 "Alternate '%s' member '%s' has "
Eric Blake811d04f2015-05-04 09:05:10 -0600383 "invalid type '%s'" % (name, key, value))
384 if qtype in types_seen:
385 raise QAPIExprError(expr_info,
Eric Blakeab916fa2015-05-04 09:05:13 -0600386 "Alternate '%s' member '%s' can't "
Eric Blake811d04f2015-05-04 09:05:10 -0600387 "be distinguished from member '%s'"
388 % (name, key, types_seen[qtype]))
389 types_seen[qtype] = key
Wenchao Xiab86b05e2014-03-04 18:44:34 -0800390
Eric Blakecf393592015-05-04 09:05:04 -0600391def check_enum(expr, expr_info):
392 name = expr['enum']
393 members = expr.get('data')
394 values = { 'MAX': '(automatic)' }
395
396 if not isinstance(members, list):
397 raise QAPIExprError(expr_info,
398 "Enum '%s' requires an array for 'data'" % name)
399 for member in members:
400 if not isinstance(member, str):
401 raise QAPIExprError(expr_info,
402 "Enum '%s' member '%s' is not a string"
403 % (name, member))
404 key = _generate_enum_string(member)
405 if key in values:
406 raise QAPIExprError(expr_info,
407 "Enum '%s' member '%s' clashes with '%s'"
408 % (name, member, values[key]))
409 values[key] = member
410
Wenchao Xiab86b05e2014-03-04 18:44:34 -0800411def check_exprs(schema):
412 for expr_elem in schema.exprs:
413 expr = expr_elem['expr']
Eric Blakecf393592015-05-04 09:05:04 -0600414 info = expr_elem['info']
415
416 if expr.has_key('enum'):
417 check_enum(expr, info)
418 elif expr.has_key('union'):
Eric Blakeab916fa2015-05-04 09:05:13 -0600419 check_union(expr, info)
420 elif expr.has_key('alternate'):
421 check_alternate(expr, info)
Eric Blakecf393592015-05-04 09:05:04 -0600422 elif expr.has_key('event'):
423 check_event(expr, info)
Wenchao Xiab86b05e2014-03-04 18:44:34 -0800424
Eric Blake0545f6b2015-05-04 09:05:15 -0600425def check_keys(expr_elem, meta, required, optional=[]):
426 expr = expr_elem['expr']
427 info = expr_elem['info']
428 name = expr[meta]
429 if not isinstance(name, str):
430 raise QAPIExprError(info,
431 "'%s' key must have a string value" % meta)
432 required = required + [ meta ]
433 for (key, value) in expr.items():
434 if not key in required and not key in optional:
435 raise QAPIExprError(info,
436 "Unknown key '%s' in %s '%s'"
437 % (key, meta, name))
438 for key in required:
439 if not expr.has_key(key):
440 raise QAPIExprError(info,
441 "Key '%s' is missing from %s '%s'"
442 % (key, meta, name))
443
444
Lluís Vilanova33aaad52014-05-02 15:52:35 +0200445def parse_schema(input_file):
Eric Blake4dc2e692015-05-04 09:05:17 -0600446 global all_names
447 exprs = []
448
Eric Blake268a1c52015-05-04 09:05:09 -0600449 # First pass: read entire file into memory
Markus Armbruster2caba362013-07-27 17:41:56 +0200450 try:
Lluís Vilanova33aaad52014-05-02 15:52:35 +0200451 schema = QAPISchema(open(input_file, "r"))
Lluís Vilanovaa719a272014-05-07 20:46:15 +0200452 except (QAPISchemaError, QAPIExprError), e:
Markus Armbruster2caba362013-07-27 17:41:56 +0200453 print >>sys.stderr, e
454 exit(1)
455
Wenchao Xiab86b05e2014-03-04 18:44:34 -0800456 try:
Eric Blake0545f6b2015-05-04 09:05:15 -0600457 # Next pass: learn the types and check for valid expression keys. At
458 # this point, top-level 'include' has already been flattened.
Eric Blake4dc2e692015-05-04 09:05:17 -0600459 for builtin in builtin_types.keys():
460 all_names[builtin] = 'built-in'
Eric Blake268a1c52015-05-04 09:05:09 -0600461 for expr_elem in schema.exprs:
462 expr = expr_elem['expr']
Eric Blake4dc2e692015-05-04 09:05:17 -0600463 info = expr_elem['info']
Eric Blake268a1c52015-05-04 09:05:09 -0600464 if expr.has_key('enum'):
Eric Blake0545f6b2015-05-04 09:05:15 -0600465 check_keys(expr_elem, 'enum', ['data'])
Eric Blake4dc2e692015-05-04 09:05:17 -0600466 add_enum(expr['enum'], info, expr['data'])
Eric Blake268a1c52015-05-04 09:05:09 -0600467 elif expr.has_key('union'):
Eric Blake0545f6b2015-05-04 09:05:15 -0600468 check_keys(expr_elem, 'union', ['data'],
469 ['base', 'discriminator'])
Eric Blake4dc2e692015-05-04 09:05:17 -0600470 add_union(expr, info)
Eric Blake0545f6b2015-05-04 09:05:15 -0600471 elif expr.has_key('alternate'):
472 check_keys(expr_elem, 'alternate', ['data'])
Eric Blake4dc2e692015-05-04 09:05:17 -0600473 add_name(expr['alternate'], info, 'alternate')
Eric Blake268a1c52015-05-04 09:05:09 -0600474 elif expr.has_key('type'):
Eric Blake0545f6b2015-05-04 09:05:15 -0600475 check_keys(expr_elem, 'type', ['data'], ['base'])
Eric Blake4dc2e692015-05-04 09:05:17 -0600476 add_struct(expr, info)
Eric Blake0545f6b2015-05-04 09:05:15 -0600477 elif expr.has_key('command'):
478 check_keys(expr_elem, 'command', [],
479 ['data', 'returns', 'gen', 'success-response'])
Eric Blake4dc2e692015-05-04 09:05:17 -0600480 add_name(expr['command'], info, 'command')
Eric Blake0545f6b2015-05-04 09:05:15 -0600481 elif expr.has_key('event'):
482 check_keys(expr_elem, 'event', [], ['data'])
Eric Blake4dc2e692015-05-04 09:05:17 -0600483 add_name(expr['event'], info, 'event')
Eric Blake0545f6b2015-05-04 09:05:15 -0600484 else:
485 raise QAPIExprError(expr_elem['info'],
486 "Expression is missing metatype")
Eric Blake268a1c52015-05-04 09:05:09 -0600487 exprs.append(expr)
488
489 # Try again for hidden UnionKind enum
490 for expr_elem in schema.exprs:
491 expr = expr_elem['expr']
492 if expr.has_key('union'):
493 if not discriminator_find_enum_define(expr):
Eric Blake4dc2e692015-05-04 09:05:17 -0600494 add_enum('%sKind' % expr['union'], expr_elem['info'],
495 implicit=True)
Eric Blakeab916fa2015-05-04 09:05:13 -0600496 elif expr.has_key('alternate'):
Eric Blake4dc2e692015-05-04 09:05:17 -0600497 add_enum('%sKind' % expr['alternate'], expr_elem['info'],
498 implicit=True)
Eric Blake268a1c52015-05-04 09:05:09 -0600499
500 # Final pass - validate that exprs make sense
Wenchao Xiab86b05e2014-03-04 18:44:34 -0800501 check_exprs(schema)
502 except QAPIExprError, e:
503 print >>sys.stderr, e
504 exit(1)
505
Michael Roth0f923be2011-07-19 14:50:39 -0500506 return exprs
507
508def parse_args(typeinfo):
Eric Blakefe2a9302015-05-04 09:05:02 -0600509 if isinstance(typeinfo, str):
Kevin Wolfb35284e2013-07-01 16:31:51 +0200510 struct = find_struct(typeinfo)
511 assert struct != None
512 typeinfo = struct['data']
513
Michael Roth0f923be2011-07-19 14:50:39 -0500514 for member in typeinfo:
515 argname = member
516 argentry = typeinfo[member]
517 optional = False
518 structured = False
519 if member.startswith('*'):
520 argname = member[1:]
521 optional = True
522 if isinstance(argentry, OrderedDict):
523 structured = True
524 yield (argname, argentry, optional, structured)
525
526def de_camel_case(name):
527 new_name = ''
528 for ch in name:
529 if ch.isupper() and new_name:
530 new_name += '_'
531 if ch == '-':
532 new_name += '_'
533 else:
534 new_name += ch.lower()
535 return new_name
536
537def camel_case(name):
538 new_name = ''
539 first = True
540 for ch in name:
541 if ch in ['_', '-']:
542 first = True
543 elif first:
544 new_name += ch.upper()
545 first = False
546 else:
547 new_name += ch.lower()
548 return new_name
549
Paolo Bonzinieda50a62012-09-19 16:31:06 +0200550def c_var(name, protect=True):
Blue Swirl427a1a22012-07-30 15:46:55 +0000551 # ANSI X3J11/88-090, 3.1.1
552 c89_words = set(['auto', 'break', 'case', 'char', 'const', 'continue',
553 'default', 'do', 'double', 'else', 'enum', 'extern', 'float',
554 'for', 'goto', 'if', 'int', 'long', 'register', 'return',
555 'short', 'signed', 'sizeof', 'static', 'struct', 'switch',
556 'typedef', 'union', 'unsigned', 'void', 'volatile', 'while'])
557 # ISO/IEC 9899:1999, 6.4.1
558 c99_words = set(['inline', 'restrict', '_Bool', '_Complex', '_Imaginary'])
559 # ISO/IEC 9899:2011, 6.4.1
560 c11_words = set(['_Alignas', '_Alignof', '_Atomic', '_Generic', '_Noreturn',
561 '_Static_assert', '_Thread_local'])
562 # GCC http://gcc.gnu.org/onlinedocs/gcc-4.7.1/gcc/C-Extensions.html
563 # excluding _.*
564 gcc_words = set(['asm', 'typeof'])
Tomoki Sekiyama6f880092013-08-07 11:39:43 -0400565 # C++ ISO/IEC 14882:2003 2.11
566 cpp_words = set(['bool', 'catch', 'class', 'const_cast', 'delete',
567 'dynamic_cast', 'explicit', 'false', 'friend', 'mutable',
568 'namespace', 'new', 'operator', 'private', 'protected',
569 'public', 'reinterpret_cast', 'static_cast', 'template',
570 'this', 'throw', 'true', 'try', 'typeid', 'typename',
571 'using', 'virtual', 'wchar_t',
572 # alternative representations
573 'and', 'and_eq', 'bitand', 'bitor', 'compl', 'not',
574 'not_eq', 'or', 'or_eq', 'xor', 'xor_eq'])
Paolo Bonzini10577252012-09-19 16:31:07 +0200575 # namespace pollution:
Max Reitz8592a542013-12-20 19:28:18 +0100576 polluted_words = set(['unix', 'errno'])
Tomoki Sekiyama6f880092013-08-07 11:39:43 -0400577 if protect and (name in c89_words | c99_words | c11_words | gcc_words | cpp_words | polluted_words):
Blue Swirl427a1a22012-07-30 15:46:55 +0000578 return "q_" + name
Federico Simoncellic9da2282012-03-20 13:54:35 +0000579 return name.replace('-', '_').lstrip("*")
580
Paolo Bonzinieda50a62012-09-19 16:31:06 +0200581def c_fun(name, protect=True):
582 return c_var(name, protect).replace('.', '_')
Michael Roth0f923be2011-07-19 14:50:39 -0500583
584def c_list_type(name):
585 return '%sList' % name
586
587def type_name(name):
588 if type(name) == list:
589 return c_list_type(name[0])
590 return name
591
Eric Blake4dc2e692015-05-04 09:05:17 -0600592def add_name(name, info, meta, implicit = False):
593 global all_names
594 if name in all_names:
595 raise QAPIExprError(info,
596 "%s '%s' is already defined"
597 % (all_names[name], name))
598 if not implicit and name[-4:] == 'Kind':
599 raise QAPIExprError(info,
600 "%s '%s' should not end in 'Kind'"
601 % (meta, name))
602 all_names[name] = meta
Kevin Wolfb35284e2013-07-01 16:31:51 +0200603
Eric Blake4dc2e692015-05-04 09:05:17 -0600604def add_struct(definition, info):
Kevin Wolfb35284e2013-07-01 16:31:51 +0200605 global struct_types
Eric Blake4dc2e692015-05-04 09:05:17 -0600606 name = definition['type']
607 add_name(name, info, 'struct')
Kevin Wolfb35284e2013-07-01 16:31:51 +0200608 struct_types.append(definition)
609
610def find_struct(name):
611 global struct_types
612 for struct in struct_types:
613 if struct['type'] == name:
614 return struct
615 return None
Michael Roth0f923be2011-07-19 14:50:39 -0500616
Eric Blake4dc2e692015-05-04 09:05:17 -0600617def add_union(definition, info):
Kevin Wolfea66c6d2013-07-16 10:49:41 +0200618 global union_types
Eric Blake4dc2e692015-05-04 09:05:17 -0600619 name = definition['union']
620 add_name(name, info, 'union')
Eric Blakeab916fa2015-05-04 09:05:13 -0600621 union_types.append(definition)
Kevin Wolfea66c6d2013-07-16 10:49:41 +0200622
623def find_union(name):
624 global union_types
625 for union in union_types:
626 if union['union'] == name:
627 return union
628 return None
629
Eric Blake4dc2e692015-05-04 09:05:17 -0600630def add_enum(name, info, enum_values = None, implicit = False):
Michael Roth0f923be2011-07-19 14:50:39 -0500631 global enum_types
Eric Blake4dc2e692015-05-04 09:05:17 -0600632 add_name(name, info, 'enum', implicit)
Wenchao Xiadad1fca2014-03-04 18:44:31 -0800633 enum_types.append({"enum_name": name, "enum_values": enum_values})
634
635def find_enum(name):
636 global enum_types
637 for enum in enum_types:
638 if enum['enum_name'] == name:
639 return enum
640 return None
Michael Roth0f923be2011-07-19 14:50:39 -0500641
642def is_enum(name):
Wenchao Xiadad1fca2014-03-04 18:44:31 -0800643 return find_enum(name) != None
Michael Roth0f923be2011-07-19 14:50:39 -0500644
Amos Kong05dfb262014-06-10 19:25:53 +0800645eatspace = '\033EATSPACE.'
646
647# A special suffix is added in c_type() for pointer types, and it's
648# stripped in mcgen(). So please notice this when you check the return
649# value of c_type() outside mcgen().
Amos Kong0d14eeb2014-06-10 19:25:52 +0800650def c_type(name, is_param=False):
Michael Roth0f923be2011-07-19 14:50:39 -0500651 if name == 'str':
Amos Kong0d14eeb2014-06-10 19:25:52 +0800652 if is_param:
Amos Kong05dfb262014-06-10 19:25:53 +0800653 return 'const char *' + eatspace
654 return 'char *' + eatspace
655
Michael Roth0f923be2011-07-19 14:50:39 -0500656 elif name == 'int':
657 return 'int64_t'
Laszlo Ersekc46f18c2012-07-17 16:17:06 +0200658 elif (name == 'int8' or name == 'int16' or name == 'int32' or
659 name == 'int64' or name == 'uint8' or name == 'uint16' or
660 name == 'uint32' or name == 'uint64'):
661 return name + '_t'
Laszlo Ersek092705d2012-07-17 16:17:07 +0200662 elif name == 'size':
663 return 'uint64_t'
Michael Roth0f923be2011-07-19 14:50:39 -0500664 elif name == 'bool':
665 return 'bool'
666 elif name == 'number':
667 return 'double'
668 elif type(name) == list:
Amos Kong05dfb262014-06-10 19:25:53 +0800669 return '%s *%s' % (c_list_type(name[0]), eatspace)
Michael Roth0f923be2011-07-19 14:50:39 -0500670 elif is_enum(name):
671 return name
672 elif name == None or len(name) == 0:
673 return 'void'
Eric Blake4dc2e692015-05-04 09:05:17 -0600674 elif name in events:
Amos Kong05dfb262014-06-10 19:25:53 +0800675 return '%sEvent *%s' % (camel_case(name), eatspace)
Michael Roth0f923be2011-07-19 14:50:39 -0500676 else:
Amos Kong05dfb262014-06-10 19:25:53 +0800677 return '%s *%s' % (name, eatspace)
678
679def is_c_ptr(name):
680 suffix = "*" + eatspace
681 return c_type(name).endswith(suffix)
Michael Roth0f923be2011-07-19 14:50:39 -0500682
683def genindent(count):
684 ret = ""
685 for i in range(count):
686 ret += " "
687 return ret
688
689indent_level = 0
690
691def push_indent(indent_amount=4):
692 global indent_level
693 indent_level += indent_amount
694
695def pop_indent(indent_amount=4):
696 global indent_level
697 indent_level -= indent_amount
698
699def cgen(code, **kwds):
700 indent = genindent(indent_level)
701 lines = code.split('\n')
702 lines = map(lambda x: indent + x, lines)
703 return '\n'.join(lines) % kwds + '\n'
704
705def mcgen(code, **kwds):
Amos Kong05dfb262014-06-10 19:25:53 +0800706 raw = cgen('\n'.join(code.split('\n')[1:-1]), **kwds)
707 return re.sub(re.escape(eatspace) + ' *', '', raw)
Michael Roth0f923be2011-07-19 14:50:39 -0500708
709def basename(filename):
710 return filename.split("/")[-1]
711
712def guardname(filename):
Michael Rothd8e1f212011-11-29 16:47:48 -0600713 guard = basename(filename).rsplit(".", 1)[0]
714 for substr in [".", " ", "-"]:
715 guard = guard.replace(substr, "_")
716 return guard.upper() + '_H'
Michael Rothc0afa9c2013-05-10 17:46:00 -0500717
718def guardstart(name):
719 return mcgen('''
720
721#ifndef %(name)s
722#define %(name)s
723
724''',
725 name=guardname(name))
726
727def guardend(name):
728 return mcgen('''
729
730#endif /* %(name)s */
731
732''',
733 name=guardname(name))
Wenchao Xia62996592014-03-04 18:44:35 -0800734
Wenchao Xia5d371f42014-03-04 18:44:40 -0800735# ENUMName -> ENUM_NAME, EnumName1 -> ENUM_NAME1
736# ENUM_NAME -> ENUM_NAME, ENUM_NAME1 -> ENUM_NAME1, ENUM_Name2 -> ENUM_NAME2
737# ENUM24_Name -> ENUM24_NAME
738def _generate_enum_string(value):
739 c_fun_str = c_fun(value, False)
Wenchao Xiab0b58192014-03-04 18:44:36 -0800740 if value.isupper():
Wenchao Xia5d371f42014-03-04 18:44:40 -0800741 return c_fun_str
742
Wenchao Xia62996592014-03-04 18:44:35 -0800743 new_name = ''
Wenchao Xia5d371f42014-03-04 18:44:40 -0800744 l = len(c_fun_str)
745 for i in range(l):
746 c = c_fun_str[i]
747 # When c is upper and no "_" appears before, do more checks
748 if c.isupper() and (i > 0) and c_fun_str[i - 1] != "_":
749 # Case 1: next string is lower
750 # Case 2: previous string is digit
751 if (i < (l - 1) and c_fun_str[i + 1].islower()) or \
752 c_fun_str[i - 1].isdigit():
753 new_name += '_'
Wenchao Xia62996592014-03-04 18:44:35 -0800754 new_name += c
755 return new_name.lstrip('_').upper()
Wenchao Xiab0b58192014-03-04 18:44:36 -0800756
757def generate_enum_full_value(enum_name, enum_value):
Wenchao Xia5d371f42014-03-04 18:44:40 -0800758 abbrev_string = _generate_enum_string(enum_name)
759 value_string = _generate_enum_string(enum_value)
Wenchao Xiab0b58192014-03-04 18:44:36 -0800760 return "%s_%s" % (abbrev_string, value_string)