blob: 6faa897fa67be189424c7cbdc2cb425ddb81fc35 [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
Markus Armbruster12f8e1b2015-04-02 14:46:39 +020016import errno
Markus Armbruster2114f5a2015-04-02 13:12:21 +020017import getopt
Lluís Vilanova33aaad52014-05-02 15:52:35 +020018import os
Markus Armbruster2caba362013-07-27 17:41:56 +020019import sys
Markus Armbruster47299262015-05-14 06:50:47 -060020import string
Michael Roth0f923be2011-07-19 14:50:39 -050021
Eric Blakeb52c4b92015-05-04 09:05:00 -060022builtin_types = {
Kevin Wolf69dd62d2013-07-08 16:14:21 +020023 'str': 'QTYPE_QSTRING',
24 'int': 'QTYPE_QINT',
25 'number': 'QTYPE_QFLOAT',
26 'bool': 'QTYPE_QBOOL',
27 'int8': 'QTYPE_QINT',
28 'int16': 'QTYPE_QINT',
29 'int32': 'QTYPE_QINT',
30 'int64': 'QTYPE_QINT',
31 'uint8': 'QTYPE_QINT',
32 'uint16': 'QTYPE_QINT',
33 'uint32': 'QTYPE_QINT',
34 'uint64': 'QTYPE_QINT',
Eric Blakecb17f792015-05-04 09:05:01 -060035 'size': 'QTYPE_QINT',
Kevin Wolf69dd62d2013-07-08 16:14:21 +020036}
37
Eric Blake10d4d992015-05-04 09:05:23 -060038# Whitelist of commands allowed to return a non-dictionary
39returns_whitelist = [
40 # From QMP:
41 'human-monitor-command',
42 'query-migrate-cache-size',
43 'query-tpm-models',
44 'query-tpm-types',
45 'ringbuf-read',
46
47 # From QGA:
48 'guest-file-open',
49 'guest-fsfreeze-freeze',
50 'guest-fsfreeze-freeze-list',
51 'guest-fsfreeze-status',
52 'guest-fsfreeze-thaw',
53 'guest-get-time',
54 'guest-set-vcpus',
55 'guest-sync',
56 'guest-sync-delimited',
57
58 # From qapi-schema-test:
59 'user_def_cmd3',
60]
61
Eric Blake4dc2e692015-05-04 09:05:17 -060062enum_types = []
63struct_types = []
64union_types = []
65events = []
66all_names = {}
67
Lluís Vilanovaa719a272014-05-07 20:46:15 +020068def error_path(parent):
69 res = ""
70 while parent:
71 res = ("In file included from %s:%d:\n" % (parent['file'],
72 parent['line'])) + res
73 parent = parent['parent']
74 return res
75
Markus Armbruster2caba362013-07-27 17:41:56 +020076class QAPISchemaError(Exception):
77 def __init__(self, schema, msg):
Markus Armbruster54414042015-06-09 16:22:45 +020078 self.fname = schema.fname
Markus Armbruster2caba362013-07-27 17:41:56 +020079 self.msg = msg
Wenchao Xia515b9432014-03-04 18:44:33 -080080 self.col = 1
81 self.line = schema.line
82 for ch in schema.src[schema.line_pos:schema.pos]:
83 if ch == '\t':
Markus Armbruster2caba362013-07-27 17:41:56 +020084 self.col = (self.col + 7) % 8 + 1
85 else:
86 self.col += 1
Markus Armbruster54414042015-06-09 16:22:45 +020087 self.info = schema.incl_info
Markus Armbruster2caba362013-07-27 17:41:56 +020088
89 def __str__(self):
Lluís Vilanovaa719a272014-05-07 20:46:15 +020090 return error_path(self.info) + \
Markus Armbruster54414042015-06-09 16:22:45 +020091 "%s:%d:%d: %s" % (self.fname, self.line, self.col, self.msg)
Markus Armbruster2caba362013-07-27 17:41:56 +020092
Wenchao Xiab86b05e2014-03-04 18:44:34 -080093class QAPIExprError(Exception):
94 def __init__(self, expr_info, msg):
Lluís Vilanovaa719a272014-05-07 20:46:15 +020095 self.info = expr_info
Wenchao Xiab86b05e2014-03-04 18:44:34 -080096 self.msg = msg
97
98 def __str__(self):
Lluís Vilanovaa719a272014-05-07 20:46:15 +020099 return error_path(self.info['parent']) + \
100 "%s:%d: %s" % (self.info['file'], self.info['line'], self.msg)
Wenchao Xiab86b05e2014-03-04 18:44:34 -0800101
Markus Armbrusterc7a3f252013-07-27 17:41:55 +0200102class QAPISchema:
Michael Roth0f923be2011-07-19 14:50:39 -0500103
Markus Armbrustera1366082015-06-09 16:54:09 +0200104 def __init__(self, fp, previously_included = [], incl_info = None):
Markus Armbruster54414042015-06-09 16:22:45 +0200105 abs_fname = os.path.abspath(fp.name)
Markus Armbruster8608d252015-06-09 18:32:29 +0200106 fname = fp.name
Markus Armbruster54414042015-06-09 16:22:45 +0200107 self.fname = fname
Markus Armbruster54414042015-06-09 16:22:45 +0200108 previously_included.append(abs_fname)
109 self.incl_info = incl_info
Markus Armbrusterc7a3f252013-07-27 17:41:55 +0200110 self.src = fp.read()
111 if self.src == '' or self.src[-1] != '\n':
112 self.src += '\n'
113 self.cursor = 0
Wenchao Xia515b9432014-03-04 18:44:33 -0800114 self.line = 1
115 self.line_pos = 0
Markus Armbrusterc7a3f252013-07-27 17:41:55 +0200116 self.exprs = []
117 self.accept()
Michael Roth0f923be2011-07-19 14:50:39 -0500118
Markus Armbrusterc7a3f252013-07-27 17:41:55 +0200119 while self.tok != None:
Markus Armbruster54414042015-06-09 16:22:45 +0200120 expr_info = {'file': fname, 'line': self.line,
121 'parent': self.incl_info}
Lluís Vilanovaa719a272014-05-07 20:46:15 +0200122 expr = self.get_expr(False)
123 if isinstance(expr, dict) and "include" in expr:
124 if len(expr) != 1:
125 raise QAPIExprError(expr_info, "Invalid 'include' directive")
126 include = expr["include"]
127 if not isinstance(include, str):
128 raise QAPIExprError(expr_info,
129 'Expected a file name (string), got: %s'
130 % include)
Markus Armbruster54414042015-06-09 16:22:45 +0200131 incl_abs_fname = os.path.join(os.path.dirname(abs_fname),
132 include)
Markus Armbrustera1366082015-06-09 16:54:09 +0200133 # catch inclusion cycle
134 inf = expr_info
135 while inf:
136 if incl_abs_fname == os.path.abspath(inf['file']):
Stefan Hajnoczi7ac9a9d2014-08-27 12:08:51 +0100137 raise QAPIExprError(expr_info, "Inclusion loop for %s"
138 % include)
Markus Armbrustera1366082015-06-09 16:54:09 +0200139 inf = inf['parent']
Benoît Canet24fd8482014-05-16 12:51:56 +0200140 # skip multiple include of the same file
Markus Armbruster54414042015-06-09 16:22:45 +0200141 if incl_abs_fname in previously_included:
Benoît Canet24fd8482014-05-16 12:51:56 +0200142 continue
Lluís Vilanovaa719a272014-05-07 20:46:15 +0200143 try:
Markus Armbruster54414042015-06-09 16:22:45 +0200144 fobj = open(incl_abs_fname, 'r')
Luiz Capitulino34788812014-05-20 13:50:19 -0400145 except IOError, e:
Lluís Vilanovaa719a272014-05-07 20:46:15 +0200146 raise QAPIExprError(expr_info,
147 '%s: %s' % (e.strerror, include))
Markus Armbrustera1366082015-06-09 16:54:09 +0200148 exprs_include = QAPISchema(fobj, previously_included,
149 expr_info)
Lluís Vilanovaa719a272014-05-07 20:46:15 +0200150 self.exprs.extend(exprs_include.exprs)
151 else:
152 expr_elem = {'expr': expr,
153 'info': expr_info}
154 self.exprs.append(expr_elem)
Michael Roth0f923be2011-07-19 14:50:39 -0500155
Markus Armbrusterc7a3f252013-07-27 17:41:55 +0200156 def accept(self):
157 while True:
Markus Armbrusterc7a3f252013-07-27 17:41:55 +0200158 self.tok = self.src[self.cursor]
Markus Armbruster2caba362013-07-27 17:41:56 +0200159 self.pos = self.cursor
Markus Armbrusterc7a3f252013-07-27 17:41:55 +0200160 self.cursor += 1
161 self.val = None
Michael Roth0f923be2011-07-19 14:50:39 -0500162
Markus Armbrusterf1a145e2013-07-27 17:42:01 +0200163 if self.tok == '#':
Markus Armbrusterc7a3f252013-07-27 17:41:55 +0200164 self.cursor = self.src.find('\n', self.cursor)
165 elif self.tok in ['{', '}', ':', ',', '[', ']']:
166 return
167 elif self.tok == "'":
168 string = ''
169 esc = False
170 while True:
171 ch = self.src[self.cursor]
172 self.cursor += 1
173 if ch == '\n':
Markus Armbruster2caba362013-07-27 17:41:56 +0200174 raise QAPISchemaError(self,
175 'Missing terminating "\'"')
Markus Armbrusterc7a3f252013-07-27 17:41:55 +0200176 if esc:
Eric Blakea7f59662015-05-04 09:05:36 -0600177 if ch == 'b':
178 string += '\b'
179 elif ch == 'f':
180 string += '\f'
181 elif ch == 'n':
182 string += '\n'
183 elif ch == 'r':
184 string += '\r'
185 elif ch == 't':
186 string += '\t'
187 elif ch == 'u':
188 value = 0
189 for x in range(0, 4):
190 ch = self.src[self.cursor]
191 self.cursor += 1
192 if ch not in "0123456789abcdefABCDEF":
193 raise QAPISchemaError(self,
194 '\\u escape needs 4 '
195 'hex digits')
196 value = (value << 4) + int(ch, 16)
197 # If Python 2 and 3 didn't disagree so much on
198 # how to handle Unicode, then we could allow
199 # Unicode string defaults. But most of QAPI is
200 # ASCII-only, so we aren't losing much for now.
201 if not value or value > 0x7f:
202 raise QAPISchemaError(self,
203 'For now, \\u escape '
204 'only supports non-zero '
205 'values up to \\u007f')
206 string += chr(value)
207 elif ch in "\\/'\"":
208 string += ch
209 else:
210 raise QAPISchemaError(self,
211 "Unknown escape \\%s" %ch)
Markus Armbrusterc7a3f252013-07-27 17:41:55 +0200212 esc = False
213 elif ch == "\\":
214 esc = True
215 elif ch == "'":
216 self.val = string
217 return
218 else:
219 string += ch
Markus Armbrustere565d932015-06-10 08:24:58 +0200220 elif self.src.startswith("true", self.pos):
221 self.val = True
222 self.cursor += 3
223 return
224 elif self.src.startswith("false", self.pos):
225 self.val = False
226 self.cursor += 4
227 return
228 elif self.src.startswith("null", self.pos):
229 self.val = None
230 self.cursor += 3
231 return
Markus Armbrusterc7a3f252013-07-27 17:41:55 +0200232 elif self.tok == '\n':
233 if self.cursor == len(self.src):
234 self.tok = None
235 return
Wenchao Xia515b9432014-03-04 18:44:33 -0800236 self.line += 1
237 self.line_pos = self.cursor
Markus Armbruster9213aa52013-07-27 17:41:57 +0200238 elif not self.tok.isspace():
239 raise QAPISchemaError(self, 'Stray "%s"' % self.tok)
Michael Roth0f923be2011-07-19 14:50:39 -0500240
Markus Armbrusterc7a3f252013-07-27 17:41:55 +0200241 def get_members(self):
242 expr = OrderedDict()
Markus Armbruster6974ccd2013-07-27 17:41:58 +0200243 if self.tok == '}':
244 self.accept()
245 return expr
246 if self.tok != "'":
247 raise QAPISchemaError(self, 'Expected string or "}"')
248 while True:
Markus Armbrusterc7a3f252013-07-27 17:41:55 +0200249 key = self.val
250 self.accept()
Markus Armbruster6974ccd2013-07-27 17:41:58 +0200251 if self.tok != ':':
252 raise QAPISchemaError(self, 'Expected ":"')
253 self.accept()
Wenchao Xia4b359912014-03-04 18:44:32 -0800254 if key in expr:
255 raise QAPISchemaError(self, 'Duplicate key "%s"' % key)
Markus Armbruster5f3cd2b2013-07-27 17:41:59 +0200256 expr[key] = self.get_expr(True)
Markus Armbruster6974ccd2013-07-27 17:41:58 +0200257 if self.tok == '}':
Markus Armbrusterc7a3f252013-07-27 17:41:55 +0200258 self.accept()
Markus Armbruster6974ccd2013-07-27 17:41:58 +0200259 return expr
260 if self.tok != ',':
261 raise QAPISchemaError(self, 'Expected "," or "}"')
262 self.accept()
263 if self.tok != "'":
264 raise QAPISchemaError(self, 'Expected string')
Michael Roth0f923be2011-07-19 14:50:39 -0500265
Markus Armbrusterc7a3f252013-07-27 17:41:55 +0200266 def get_values(self):
267 expr = []
Markus Armbruster6974ccd2013-07-27 17:41:58 +0200268 if self.tok == ']':
269 self.accept()
270 return expr
Fam Zhenge53188a2015-05-04 09:05:18 -0600271 if not self.tok in "{['tfn":
272 raise QAPISchemaError(self, 'Expected "{", "[", "]", string, '
273 'boolean or "null"')
Markus Armbruster6974ccd2013-07-27 17:41:58 +0200274 while True:
Markus Armbruster5f3cd2b2013-07-27 17:41:59 +0200275 expr.append(self.get_expr(True))
Markus Armbruster6974ccd2013-07-27 17:41:58 +0200276 if self.tok == ']':
Markus Armbrusterc7a3f252013-07-27 17:41:55 +0200277 self.accept()
Markus Armbruster6974ccd2013-07-27 17:41:58 +0200278 return expr
279 if self.tok != ',':
280 raise QAPISchemaError(self, 'Expected "," or "]"')
281 self.accept()
Michael Roth0f923be2011-07-19 14:50:39 -0500282
Markus Armbruster5f3cd2b2013-07-27 17:41:59 +0200283 def get_expr(self, nested):
284 if self.tok != '{' and not nested:
285 raise QAPISchemaError(self, 'Expected "{"')
Markus Armbrusterc7a3f252013-07-27 17:41:55 +0200286 if self.tok == '{':
287 self.accept()
288 expr = self.get_members()
289 elif self.tok == '[':
290 self.accept()
291 expr = self.get_values()
Fam Zhenge53188a2015-05-04 09:05:18 -0600292 elif self.tok in "'tfn":
Markus Armbrusterc7a3f252013-07-27 17:41:55 +0200293 expr = self.val
294 self.accept()
Markus Armbruster6974ccd2013-07-27 17:41:58 +0200295 else:
296 raise QAPISchemaError(self, 'Expected "{", "[" or string')
Markus Armbrusterc7a3f252013-07-27 17:41:55 +0200297 return expr
Kevin Wolfbd9927f2013-07-01 16:31:50 +0200298
Wenchao Xiab86b05e2014-03-04 18:44:34 -0800299def find_base_fields(base):
300 base_struct_define = find_struct(base)
301 if not base_struct_define:
302 return None
303 return base_struct_define['data']
304
Eric Blake811d04f2015-05-04 09:05:10 -0600305# Return the qtype of an alternate branch, or None on error.
306def find_alternate_member_qtype(qapi_type):
Eric Blake44bd1272015-05-04 09:05:08 -0600307 if builtin_types.has_key(qapi_type):
308 return builtin_types[qapi_type]
309 elif find_struct(qapi_type):
310 return "QTYPE_QDICT"
311 elif find_enum(qapi_type):
312 return "QTYPE_QSTRING"
Eric Blake811d04f2015-05-04 09:05:10 -0600313 elif find_union(qapi_type):
314 return "QTYPE_QDICT"
Eric Blake44bd1272015-05-04 09:05:08 -0600315 return None
316
Wenchao Xiabceae762014-03-06 17:08:56 -0800317# Return the discriminator enum define if discriminator is specified as an
318# enum type, otherwise return None.
319def discriminator_find_enum_define(expr):
320 base = expr.get('base')
321 discriminator = expr.get('discriminator')
322
323 if not (discriminator and base):
324 return None
325
326 base_fields = find_base_fields(base)
327 if not base_fields:
328 return None
329
330 discriminator_type = base_fields.get(discriminator)
331 if not discriminator_type:
332 return None
333
334 return find_enum(discriminator_type)
335
Eric Blakec9e0a792015-05-04 09:05:22 -0600336valid_name = re.compile('^[a-zA-Z_][a-zA-Z0-9_.-]*$')
337def check_name(expr_info, source, name, allow_optional = False,
338 enum_member = False):
339 global valid_name
340 membername = name
341
342 if not isinstance(name, str):
343 raise QAPIExprError(expr_info,
344 "%s requires a string name" % source)
345 if name.startswith('*'):
346 membername = name[1:]
347 if not allow_optional:
348 raise QAPIExprError(expr_info,
349 "%s does not allow optional name '%s'"
350 % (source, name))
351 # Enum members can start with a digit, because the generated C
352 # code always prefixes it with the enum name
353 if enum_member:
354 membername = '_' + membername
355 if not valid_name.match(membername):
356 raise QAPIExprError(expr_info,
357 "%s uses invalid name '%s'" % (source, name))
358
Eric Blakedd883c62015-05-04 09:05:21 -0600359def check_type(expr_info, source, value, allow_array = False,
Eric Blake2cbf0992015-05-04 09:05:24 -0600360 allow_dict = False, allow_optional = False,
361 allow_star = False, allow_metas = []):
Eric Blakedd883c62015-05-04 09:05:21 -0600362 global all_names
363 orig_value = value
364
365 if value is None:
366 return
367
Eric Blake2cbf0992015-05-04 09:05:24 -0600368 if allow_star and value == '**':
Eric Blakedd883c62015-05-04 09:05:21 -0600369 return
370
371 # Check if array type for value is okay
372 if isinstance(value, list):
373 if not allow_array:
374 raise QAPIExprError(expr_info,
375 "%s cannot be an array" % source)
376 if len(value) != 1 or not isinstance(value[0], str):
377 raise QAPIExprError(expr_info,
378 "%s: array type must contain single type name"
379 % source)
380 value = value[0]
381 orig_value = "array of %s" %value
382
383 # Check if type name for value is okay
384 if isinstance(value, str):
Eric Blake2cbf0992015-05-04 09:05:24 -0600385 if value == '**':
386 raise QAPIExprError(expr_info,
387 "%s uses '**' but did not request 'gen':false"
388 % source)
Eric Blakedd883c62015-05-04 09:05:21 -0600389 if not value in all_names:
390 raise QAPIExprError(expr_info,
391 "%s uses unknown type '%s'"
392 % (source, orig_value))
393 if not all_names[value] in allow_metas:
394 raise QAPIExprError(expr_info,
395 "%s cannot use %s type '%s'"
396 % (source, all_names[value], orig_value))
397 return
398
399 # value is a dictionary, check that each member is okay
400 if not isinstance(value, OrderedDict):
401 raise QAPIExprError(expr_info,
402 "%s should be a dictionary" % source)
403 if not allow_dict:
404 raise QAPIExprError(expr_info,
405 "%s should be a type name" % source)
406 for (key, arg) in value.items():
Eric Blakec9e0a792015-05-04 09:05:22 -0600407 check_name(expr_info, "Member of %s" % source, key,
408 allow_optional=allow_optional)
Eric Blake6b5abc72015-05-04 09:05:33 -0600409 # Todo: allow dictionaries to represent default values of
410 # an optional argument.
Eric Blakedd883c62015-05-04 09:05:21 -0600411 check_type(expr_info, "Member '%s' of %s" % (key, source), arg,
Eric Blake6b5abc72015-05-04 09:05:33 -0600412 allow_array=True, allow_star=allow_star,
Eric Blakedd883c62015-05-04 09:05:21 -0600413 allow_metas=['built-in', 'union', 'alternate', 'struct',
Eric Blake6b5abc72015-05-04 09:05:33 -0600414 'enum'])
Eric Blakedd883c62015-05-04 09:05:21 -0600415
Eric Blakeff55d722015-05-04 09:05:37 -0600416def check_member_clash(expr_info, base_name, data, source = ""):
417 base = find_struct(base_name)
418 assert base
419 base_members = base['data']
420 for key in data.keys():
421 if key.startswith('*'):
422 key = key[1:]
423 if key in base_members or "*" + key in base_members:
424 raise QAPIExprError(expr_info,
425 "Member name '%s'%s clashes with base '%s'"
426 % (key, source, base_name))
427 if base.get('base'):
428 check_member_clash(expr_info, base['base'], data, source)
429
Eric Blakedd883c62015-05-04 09:05:21 -0600430def check_command(expr, expr_info):
431 name = expr['command']
Eric Blake2cbf0992015-05-04 09:05:24 -0600432 allow_star = expr.has_key('gen')
433
Eric Blakedd883c62015-05-04 09:05:21 -0600434 check_type(expr_info, "'data' for command '%s'" % name,
Eric Blakec9e0a792015-05-04 09:05:22 -0600435 expr.get('data'), allow_dict=True, allow_optional=True,
Eric Blake2cbf0992015-05-04 09:05:24 -0600436 allow_metas=['union', 'struct'], allow_star=allow_star)
Eric Blake10d4d992015-05-04 09:05:23 -0600437 returns_meta = ['union', 'struct']
438 if name in returns_whitelist:
439 returns_meta += ['built-in', 'alternate', 'enum']
Eric Blakedd883c62015-05-04 09:05:21 -0600440 check_type(expr_info, "'returns' for command '%s'" % name,
441 expr.get('returns'), allow_array=True, allow_dict=True,
Eric Blake2cbf0992015-05-04 09:05:24 -0600442 allow_optional=True, allow_metas=returns_meta,
443 allow_star=allow_star)
Eric Blakedd883c62015-05-04 09:05:21 -0600444
Wenchao Xia21cd70d2014-06-18 08:43:28 +0200445def check_event(expr, expr_info):
Eric Blake4dc2e692015-05-04 09:05:17 -0600446 global events
447 name = expr['event']
Wenchao Xia21cd70d2014-06-18 08:43:28 +0200448 params = expr.get('data')
Eric Blake4dc2e692015-05-04 09:05:17 -0600449
450 if name.upper() == 'MAX':
451 raise QAPIExprError(expr_info, "Event name 'MAX' cannot be created")
452 events.append(name)
Eric Blakedd883c62015-05-04 09:05:21 -0600453 check_type(expr_info, "'data' for event '%s'" % name,
Eric Blakec9e0a792015-05-04 09:05:22 -0600454 expr.get('data'), allow_dict=True, allow_optional=True,
Eric Blakedd883c62015-05-04 09:05:21 -0600455 allow_metas=['union', 'struct'])
Wenchao Xia21cd70d2014-06-18 08:43:28 +0200456
Wenchao Xiab86b05e2014-03-04 18:44:34 -0800457def check_union(expr, expr_info):
458 name = expr['union']
459 base = expr.get('base')
460 discriminator = expr.get('discriminator')
461 members = expr['data']
Eric Blake44bd1272015-05-04 09:05:08 -0600462 values = { 'MAX': '(automatic)' }
Wenchao Xiab86b05e2014-03-04 18:44:34 -0800463
Eric Blakefd41dd42015-05-04 09:05:25 -0600464 # If the object has a member 'base', its value must name a struct,
Eric Blakea8d4a2e2015-05-04 09:05:07 -0600465 # and there must be a discriminator.
466 if base is not None:
467 if discriminator is None:
468 raise QAPIExprError(expr_info,
469 "Union '%s' requires a discriminator to go "
470 "along with base" %name)
Eric Blake44bd1272015-05-04 09:05:08 -0600471
Eric Blake811d04f2015-05-04 09:05:10 -0600472 # Two types of unions, determined by discriminator.
Eric Blake811d04f2015-05-04 09:05:10 -0600473
474 # With no discriminator it is a simple union.
475 if discriminator is None:
Eric Blake44bd1272015-05-04 09:05:08 -0600476 enum_define = None
Eric Blakedd883c62015-05-04 09:05:21 -0600477 allow_metas=['built-in', 'union', 'alternate', 'struct', 'enum']
Eric Blake44bd1272015-05-04 09:05:08 -0600478 if base is not None:
479 raise QAPIExprError(expr_info,
Eric Blake811d04f2015-05-04 09:05:10 -0600480 "Simple union '%s' must not have a base"
Eric Blake44bd1272015-05-04 09:05:08 -0600481 % name)
482
483 # Else, it's a flat union.
484 else:
485 # The object must have a string member 'base'.
486 if not isinstance(base, str):
487 raise QAPIExprError(expr_info,
488 "Flat union '%s' must have a string base field"
489 % name)
Wenchao Xiab86b05e2014-03-04 18:44:34 -0800490 base_fields = find_base_fields(base)
491 if not base_fields:
492 raise QAPIExprError(expr_info,
Eric Blakefd41dd42015-05-04 09:05:25 -0600493 "Base '%s' is not a valid struct"
Wenchao Xiab86b05e2014-03-04 18:44:34 -0800494 % base)
495
Eric Blakec9e0a792015-05-04 09:05:22 -0600496 # The value of member 'discriminator' must name a non-optional
Eric Blakefd41dd42015-05-04 09:05:25 -0600497 # member of the base struct.
Eric Blakec9e0a792015-05-04 09:05:22 -0600498 check_name(expr_info, "Discriminator of flat union '%s'" % name,
499 discriminator)
Wenchao Xiab86b05e2014-03-04 18:44:34 -0800500 discriminator_type = base_fields.get(discriminator)
501 if not discriminator_type:
502 raise QAPIExprError(expr_info,
503 "Discriminator '%s' is not a member of base "
Eric Blakefd41dd42015-05-04 09:05:25 -0600504 "struct '%s'"
Wenchao Xiab86b05e2014-03-04 18:44:34 -0800505 % (discriminator, base))
506 enum_define = find_enum(discriminator_type)
Eric Blakedd883c62015-05-04 09:05:21 -0600507 allow_metas=['struct']
Wenchao Xia52230702014-03-04 18:44:39 -0800508 # Do not allow string discriminator
509 if not enum_define:
510 raise QAPIExprError(expr_info,
511 "Discriminator '%s' must be of enumeration "
512 "type" % discriminator)
Wenchao Xiab86b05e2014-03-04 18:44:34 -0800513
514 # Check every branch
515 for (key, value) in members.items():
Eric Blakec9e0a792015-05-04 09:05:22 -0600516 check_name(expr_info, "Member of union '%s'" % name, key)
517
Eric Blakedd883c62015-05-04 09:05:21 -0600518 # Each value must name a known type; furthermore, in flat unions,
Eric Blakeff55d722015-05-04 09:05:37 -0600519 # branches must be a struct with no overlapping member names
Eric Blakedd883c62015-05-04 09:05:21 -0600520 check_type(expr_info, "Member '%s' of union '%s'" % (key, name),
521 value, allow_array=True, allow_metas=allow_metas)
Eric Blakeff55d722015-05-04 09:05:37 -0600522 if base:
523 branch_struct = find_struct(value)
524 assert branch_struct
525 check_member_clash(expr_info, base, branch_struct['data'],
526 " of branch '%s'" % key)
Eric Blakedd883c62015-05-04 09:05:21 -0600527
Eric Blake44bd1272015-05-04 09:05:08 -0600528 # If the discriminator names an enum type, then all members
Wenchao Xiab86b05e2014-03-04 18:44:34 -0800529 # of 'data' must also be members of the enum type.
Eric Blake44bd1272015-05-04 09:05:08 -0600530 if enum_define:
531 if not key in enum_define['enum_values']:
532 raise QAPIExprError(expr_info,
533 "Discriminator value '%s' is not found in "
534 "enum '%s'" %
535 (key, enum_define["enum_name"]))
536
537 # Otherwise, check for conflicts in the generated enum
538 else:
Markus Armbrusterfa6068a2015-05-14 06:50:49 -0600539 c_key = camel_to_upper(key)
Eric Blake44bd1272015-05-04 09:05:08 -0600540 if c_key in values:
541 raise QAPIExprError(expr_info,
542 "Union '%s' member '%s' clashes with '%s'"
543 % (name, key, values[c_key]))
544 values[c_key] = key
545
Eric Blake811d04f2015-05-04 09:05:10 -0600546def check_alternate(expr, expr_info):
Eric Blakeab916fa2015-05-04 09:05:13 -0600547 name = expr['alternate']
Eric Blake811d04f2015-05-04 09:05:10 -0600548 members = expr['data']
549 values = { 'MAX': '(automatic)' }
550 types_seen = {}
Eric Blake44bd1272015-05-04 09:05:08 -0600551
Eric Blake811d04f2015-05-04 09:05:10 -0600552 # Check every branch
553 for (key, value) in members.items():
Eric Blakec9e0a792015-05-04 09:05:22 -0600554 check_name(expr_info, "Member of alternate '%s'" % name, key)
555
Eric Blake811d04f2015-05-04 09:05:10 -0600556 # Check for conflicts in the generated enum
Markus Armbrusterfa6068a2015-05-14 06:50:49 -0600557 c_key = camel_to_upper(key)
Eric Blake811d04f2015-05-04 09:05:10 -0600558 if c_key in values:
559 raise QAPIExprError(expr_info,
Eric Blakeab916fa2015-05-04 09:05:13 -0600560 "Alternate '%s' member '%s' clashes with '%s'"
561 % (name, key, values[c_key]))
Eric Blake811d04f2015-05-04 09:05:10 -0600562 values[c_key] = key
563
564 # Ensure alternates have no type conflicts.
Eric Blakedd883c62015-05-04 09:05:21 -0600565 check_type(expr_info, "Member '%s' of alternate '%s'" % (key, name),
566 value,
567 allow_metas=['built-in', 'union', 'struct', 'enum'])
Eric Blake811d04f2015-05-04 09:05:10 -0600568 qtype = find_alternate_member_qtype(value)
Eric Blakedd883c62015-05-04 09:05:21 -0600569 assert qtype
Eric Blake811d04f2015-05-04 09:05:10 -0600570 if qtype in types_seen:
571 raise QAPIExprError(expr_info,
Eric Blakeab916fa2015-05-04 09:05:13 -0600572 "Alternate '%s' member '%s' can't "
Eric Blake811d04f2015-05-04 09:05:10 -0600573 "be distinguished from member '%s'"
574 % (name, key, types_seen[qtype]))
575 types_seen[qtype] = key
Wenchao Xiab86b05e2014-03-04 18:44:34 -0800576
Eric Blakecf393592015-05-04 09:05:04 -0600577def check_enum(expr, expr_info):
578 name = expr['enum']
579 members = expr.get('data')
580 values = { 'MAX': '(automatic)' }
581
582 if not isinstance(members, list):
583 raise QAPIExprError(expr_info,
584 "Enum '%s' requires an array for 'data'" % name)
585 for member in members:
Eric Blakec9e0a792015-05-04 09:05:22 -0600586 check_name(expr_info, "Member of enum '%s'" %name, member,
587 enum_member=True)
Markus Armbrusterfa6068a2015-05-14 06:50:49 -0600588 key = camel_to_upper(member)
Eric Blakecf393592015-05-04 09:05:04 -0600589 if key in values:
590 raise QAPIExprError(expr_info,
591 "Enum '%s' member '%s' clashes with '%s'"
592 % (name, member, values[key]))
593 values[key] = member
594
Eric Blakedd883c62015-05-04 09:05:21 -0600595def check_struct(expr, expr_info):
Eric Blakefd41dd42015-05-04 09:05:25 -0600596 name = expr['struct']
Eric Blakedd883c62015-05-04 09:05:21 -0600597 members = expr['data']
598
Eric Blakefd41dd42015-05-04 09:05:25 -0600599 check_type(expr_info, "'data' for struct '%s'" % name, members,
Eric Blakec9e0a792015-05-04 09:05:22 -0600600 allow_dict=True, allow_optional=True)
Eric Blakefd41dd42015-05-04 09:05:25 -0600601 check_type(expr_info, "'base' for struct '%s'" % name, expr.get('base'),
Eric Blakedd883c62015-05-04 09:05:21 -0600602 allow_metas=['struct'])
Eric Blakeff55d722015-05-04 09:05:37 -0600603 if expr.get('base'):
604 check_member_clash(expr_info, expr['base'], expr['data'])
Eric Blakedd883c62015-05-04 09:05:21 -0600605
Wenchao Xiab86b05e2014-03-04 18:44:34 -0800606def check_exprs(schema):
607 for expr_elem in schema.exprs:
608 expr = expr_elem['expr']
Eric Blakecf393592015-05-04 09:05:04 -0600609 info = expr_elem['info']
610
611 if expr.has_key('enum'):
612 check_enum(expr, info)
613 elif expr.has_key('union'):
Eric Blakeab916fa2015-05-04 09:05:13 -0600614 check_union(expr, info)
615 elif expr.has_key('alternate'):
616 check_alternate(expr, info)
Eric Blakefd41dd42015-05-04 09:05:25 -0600617 elif expr.has_key('struct'):
Eric Blakedd883c62015-05-04 09:05:21 -0600618 check_struct(expr, info)
619 elif expr.has_key('command'):
620 check_command(expr, info)
Eric Blakecf393592015-05-04 09:05:04 -0600621 elif expr.has_key('event'):
622 check_event(expr, info)
Eric Blakedd883c62015-05-04 09:05:21 -0600623 else:
624 assert False, 'unexpected meta type'
Wenchao Xiab86b05e2014-03-04 18:44:34 -0800625
Eric Blake0545f6b2015-05-04 09:05:15 -0600626def check_keys(expr_elem, meta, required, optional=[]):
627 expr = expr_elem['expr']
628 info = expr_elem['info']
629 name = expr[meta]
630 if not isinstance(name, str):
631 raise QAPIExprError(info,
632 "'%s' key must have a string value" % meta)
633 required = required + [ meta ]
634 for (key, value) in expr.items():
635 if not key in required and not key in optional:
636 raise QAPIExprError(info,
637 "Unknown key '%s' in %s '%s'"
638 % (key, meta, name))
Eric Blake2cbf0992015-05-04 09:05:24 -0600639 if (key == 'gen' or key == 'success-response') and value != False:
640 raise QAPIExprError(info,
641 "'%s' of %s '%s' should only use false value"
642 % (key, meta, name))
Eric Blake0545f6b2015-05-04 09:05:15 -0600643 for key in required:
644 if not expr.has_key(key):
645 raise QAPIExprError(info,
646 "Key '%s' is missing from %s '%s'"
647 % (key, meta, name))
648
649
Markus Armbruster54414042015-06-09 16:22:45 +0200650def parse_schema(fname):
Eric Blake4dc2e692015-05-04 09:05:17 -0600651 global all_names
652 exprs = []
653
Eric Blake268a1c52015-05-04 09:05:09 -0600654 # First pass: read entire file into memory
Markus Armbruster2caba362013-07-27 17:41:56 +0200655 try:
Markus Armbruster54414042015-06-09 16:22:45 +0200656 schema = QAPISchema(open(fname, "r"))
Lluís Vilanovaa719a272014-05-07 20:46:15 +0200657 except (QAPISchemaError, QAPIExprError), e:
Markus Armbruster2caba362013-07-27 17:41:56 +0200658 print >>sys.stderr, e
659 exit(1)
660
Wenchao Xiab86b05e2014-03-04 18:44:34 -0800661 try:
Eric Blake0545f6b2015-05-04 09:05:15 -0600662 # Next pass: learn the types and check for valid expression keys. At
663 # this point, top-level 'include' has already been flattened.
Eric Blake4dc2e692015-05-04 09:05:17 -0600664 for builtin in builtin_types.keys():
665 all_names[builtin] = 'built-in'
Eric Blake268a1c52015-05-04 09:05:09 -0600666 for expr_elem in schema.exprs:
667 expr = expr_elem['expr']
Eric Blake4dc2e692015-05-04 09:05:17 -0600668 info = expr_elem['info']
Eric Blake268a1c52015-05-04 09:05:09 -0600669 if expr.has_key('enum'):
Eric Blake0545f6b2015-05-04 09:05:15 -0600670 check_keys(expr_elem, 'enum', ['data'])
Eric Blake4dc2e692015-05-04 09:05:17 -0600671 add_enum(expr['enum'], info, expr['data'])
Eric Blake268a1c52015-05-04 09:05:09 -0600672 elif expr.has_key('union'):
Eric Blake0545f6b2015-05-04 09:05:15 -0600673 check_keys(expr_elem, 'union', ['data'],
674 ['base', 'discriminator'])
Eric Blake4dc2e692015-05-04 09:05:17 -0600675 add_union(expr, info)
Eric Blake0545f6b2015-05-04 09:05:15 -0600676 elif expr.has_key('alternate'):
677 check_keys(expr_elem, 'alternate', ['data'])
Eric Blake4dc2e692015-05-04 09:05:17 -0600678 add_name(expr['alternate'], info, 'alternate')
Eric Blakefd41dd42015-05-04 09:05:25 -0600679 elif expr.has_key('struct'):
680 check_keys(expr_elem, 'struct', ['data'], ['base'])
Eric Blake4dc2e692015-05-04 09:05:17 -0600681 add_struct(expr, info)
Eric Blake0545f6b2015-05-04 09:05:15 -0600682 elif expr.has_key('command'):
683 check_keys(expr_elem, 'command', [],
684 ['data', 'returns', 'gen', 'success-response'])
Eric Blake4dc2e692015-05-04 09:05:17 -0600685 add_name(expr['command'], info, 'command')
Eric Blake0545f6b2015-05-04 09:05:15 -0600686 elif expr.has_key('event'):
687 check_keys(expr_elem, 'event', [], ['data'])
Eric Blake4dc2e692015-05-04 09:05:17 -0600688 add_name(expr['event'], info, 'event')
Eric Blake0545f6b2015-05-04 09:05:15 -0600689 else:
690 raise QAPIExprError(expr_elem['info'],
691 "Expression is missing metatype")
Eric Blake268a1c52015-05-04 09:05:09 -0600692 exprs.append(expr)
693
694 # Try again for hidden UnionKind enum
695 for expr_elem in schema.exprs:
696 expr = expr_elem['expr']
697 if expr.has_key('union'):
698 if not discriminator_find_enum_define(expr):
Eric Blake4dc2e692015-05-04 09:05:17 -0600699 add_enum('%sKind' % expr['union'], expr_elem['info'],
700 implicit=True)
Eric Blakeab916fa2015-05-04 09:05:13 -0600701 elif expr.has_key('alternate'):
Eric Blake4dc2e692015-05-04 09:05:17 -0600702 add_enum('%sKind' % expr['alternate'], expr_elem['info'],
703 implicit=True)
Eric Blake268a1c52015-05-04 09:05:09 -0600704
705 # Final pass - validate that exprs make sense
Wenchao Xiab86b05e2014-03-04 18:44:34 -0800706 check_exprs(schema)
707 except QAPIExprError, e:
708 print >>sys.stderr, e
709 exit(1)
710
Michael Roth0f923be2011-07-19 14:50:39 -0500711 return exprs
712
713def parse_args(typeinfo):
Eric Blakefe2a9302015-05-04 09:05:02 -0600714 if isinstance(typeinfo, str):
Kevin Wolfb35284e2013-07-01 16:31:51 +0200715 struct = find_struct(typeinfo)
716 assert struct != None
717 typeinfo = struct['data']
718
Michael Roth0f923be2011-07-19 14:50:39 -0500719 for member in typeinfo:
720 argname = member
721 argentry = typeinfo[member]
722 optional = False
Michael Roth0f923be2011-07-19 14:50:39 -0500723 if member.startswith('*'):
724 argname = member[1:]
725 optional = True
Eric Blake6b5abc72015-05-04 09:05:33 -0600726 # Todo: allow argentry to be OrderedDict, for providing the
727 # value of an optional argument.
728 yield (argname, argentry, optional)
Michael Roth0f923be2011-07-19 14:50:39 -0500729
Michael Roth0f923be2011-07-19 14:50:39 -0500730def camel_case(name):
731 new_name = ''
732 first = True
733 for ch in name:
734 if ch in ['_', '-']:
735 first = True
736 elif first:
737 new_name += ch.upper()
738 first = False
739 else:
740 new_name += ch.lower()
741 return new_name
742
Markus Armbruster849bc532015-05-14 06:50:53 -0600743# ENUMName -> ENUM_NAME, EnumName1 -> ENUM_NAME1
744# ENUM_NAME -> ENUM_NAME, ENUM_NAME1 -> ENUM_NAME1, ENUM_Name2 -> ENUM_NAME2
745# ENUM24_Name -> ENUM24_NAME
746def camel_to_upper(value):
747 c_fun_str = c_name(value, False)
748 if value.isupper():
749 return c_fun_str
750
751 new_name = ''
752 l = len(c_fun_str)
753 for i in range(l):
754 c = c_fun_str[i]
755 # When c is upper and no "_" appears before, do more checks
756 if c.isupper() and (i > 0) and c_fun_str[i - 1] != "_":
757 # Case 1: next string is lower
758 # Case 2: previous string is digit
759 if (i < (l - 1) and c_fun_str[i + 1].islower()) or \
760 c_fun_str[i - 1].isdigit():
761 new_name += '_'
762 new_name += c
763 return new_name.lstrip('_').upper()
764
765def c_enum_const(type_name, const_name):
766 return camel_to_upper(type_name + '_' + const_name)
767
Eric Blake18df5152015-05-14 06:50:48 -0600768c_name_trans = string.maketrans('.-', '__')
Markus Armbruster47299262015-05-14 06:50:47 -0600769
Eric Blakec6405b52015-05-14 06:50:55 -0600770# Map @name to a valid C identifier.
771# If @protect, avoid returning certain ticklish identifiers (like
772# C keywords) by prepending "q_".
773#
774# Used for converting 'name' from a 'name':'type' qapi definition
775# into a generated struct member, as well as converting type names
776# into substrings of a generated C function name.
777# '__a.b_c' -> '__a_b_c', 'x-foo' -> 'x_foo'
778# protect=True: 'int' -> 'q_int'; protect=False: 'int' -> 'int'
Eric Blake18df5152015-05-14 06:50:48 -0600779def c_name(name, protect=True):
Blue Swirl427a1a22012-07-30 15:46:55 +0000780 # ANSI X3J11/88-090, 3.1.1
781 c89_words = set(['auto', 'break', 'case', 'char', 'const', 'continue',
782 'default', 'do', 'double', 'else', 'enum', 'extern', 'float',
783 'for', 'goto', 'if', 'int', 'long', 'register', 'return',
784 'short', 'signed', 'sizeof', 'static', 'struct', 'switch',
785 'typedef', 'union', 'unsigned', 'void', 'volatile', 'while'])
786 # ISO/IEC 9899:1999, 6.4.1
787 c99_words = set(['inline', 'restrict', '_Bool', '_Complex', '_Imaginary'])
788 # ISO/IEC 9899:2011, 6.4.1
789 c11_words = set(['_Alignas', '_Alignof', '_Atomic', '_Generic', '_Noreturn',
790 '_Static_assert', '_Thread_local'])
791 # GCC http://gcc.gnu.org/onlinedocs/gcc-4.7.1/gcc/C-Extensions.html
792 # excluding _.*
793 gcc_words = set(['asm', 'typeof'])
Tomoki Sekiyama6f880092013-08-07 11:39:43 -0400794 # C++ ISO/IEC 14882:2003 2.11
795 cpp_words = set(['bool', 'catch', 'class', 'const_cast', 'delete',
796 'dynamic_cast', 'explicit', 'false', 'friend', 'mutable',
797 'namespace', 'new', 'operator', 'private', 'protected',
798 'public', 'reinterpret_cast', 'static_cast', 'template',
799 'this', 'throw', 'true', 'try', 'typeid', 'typename',
800 'using', 'virtual', 'wchar_t',
801 # alternative representations
802 'and', 'and_eq', 'bitand', 'bitor', 'compl', 'not',
803 'not_eq', 'or', 'or_eq', 'xor', 'xor_eq'])
Paolo Bonzini10577252012-09-19 16:31:07 +0200804 # namespace pollution:
Max Reitz8592a542013-12-20 19:28:18 +0100805 polluted_words = set(['unix', 'errno'])
Tomoki Sekiyama6f880092013-08-07 11:39:43 -0400806 if protect and (name in c89_words | c99_words | c11_words | gcc_words | cpp_words | polluted_words):
Blue Swirl427a1a22012-07-30 15:46:55 +0000807 return "q_" + name
Eric Blake18df5152015-05-14 06:50:48 -0600808 return name.translate(c_name_trans)
Michael Roth0f923be2011-07-19 14:50:39 -0500809
Eric Blakec6405b52015-05-14 06:50:55 -0600810# Map type @name to the C typedef name for the list form.
811#
812# ['Name'] -> 'NameList', ['x-Foo'] -> 'x_FooList', ['int'] -> 'intList'
Michael Roth0f923be2011-07-19 14:50:39 -0500813def c_list_type(name):
Eric Blakec6405b52015-05-14 06:50:55 -0600814 return type_name(name) + 'List'
Michael Roth0f923be2011-07-19 14:50:39 -0500815
Eric Blakec6405b52015-05-14 06:50:55 -0600816# Map type @value to the C typedef form.
817#
818# Used for converting 'type' from a 'member':'type' qapi definition
819# into the alphanumeric portion of the type for a generated C parameter,
820# as well as generated C function names. See c_type() for the rest of
821# the conversion such as adding '*' on pointer types.
822# 'int' -> 'int', '[x-Foo]' -> 'x_FooList', '__a.b_c' -> '__a_b_c'
Eric Blaked5573442015-05-14 06:50:54 -0600823def type_name(value):
824 if type(value) == list:
825 return c_list_type(value[0])
Eric Blakec6405b52015-05-14 06:50:55 -0600826 if value in builtin_types.keys():
827 return value
828 return c_name(value)
Michael Roth0f923be2011-07-19 14:50:39 -0500829
Eric Blakefd41dd42015-05-04 09:05:25 -0600830def add_name(name, info, meta, implicit = False):
Eric Blake4dc2e692015-05-04 09:05:17 -0600831 global all_names
Eric Blakefd41dd42015-05-04 09:05:25 -0600832 check_name(info, "'%s'" % meta, name)
Eric Blake4dc2e692015-05-04 09:05:17 -0600833 if name in all_names:
834 raise QAPIExprError(info,
835 "%s '%s' is already defined"
836 % (all_names[name], name))
837 if not implicit and name[-4:] == 'Kind':
838 raise QAPIExprError(info,
839 "%s '%s' should not end in 'Kind'"
840 % (meta, name))
841 all_names[name] = meta
Kevin Wolfb35284e2013-07-01 16:31:51 +0200842
Eric Blake4dc2e692015-05-04 09:05:17 -0600843def add_struct(definition, info):
Kevin Wolfb35284e2013-07-01 16:31:51 +0200844 global struct_types
Eric Blakefd41dd42015-05-04 09:05:25 -0600845 name = definition['struct']
846 add_name(name, info, 'struct')
Kevin Wolfb35284e2013-07-01 16:31:51 +0200847 struct_types.append(definition)
848
849def find_struct(name):
850 global struct_types
851 for struct in struct_types:
Eric Blakefd41dd42015-05-04 09:05:25 -0600852 if struct['struct'] == name:
Kevin Wolfb35284e2013-07-01 16:31:51 +0200853 return struct
854 return None
Michael Roth0f923be2011-07-19 14:50:39 -0500855
Eric Blake4dc2e692015-05-04 09:05:17 -0600856def add_union(definition, info):
Kevin Wolfea66c6d2013-07-16 10:49:41 +0200857 global union_types
Eric Blake4dc2e692015-05-04 09:05:17 -0600858 name = definition['union']
859 add_name(name, info, 'union')
Eric Blakeab916fa2015-05-04 09:05:13 -0600860 union_types.append(definition)
Kevin Wolfea66c6d2013-07-16 10:49:41 +0200861
862def find_union(name):
863 global union_types
864 for union in union_types:
865 if union['union'] == name:
866 return union
867 return None
868
Eric Blake4dc2e692015-05-04 09:05:17 -0600869def add_enum(name, info, enum_values = None, implicit = False):
Michael Roth0f923be2011-07-19 14:50:39 -0500870 global enum_types
Eric Blake4dc2e692015-05-04 09:05:17 -0600871 add_name(name, info, 'enum', implicit)
Wenchao Xiadad1fca2014-03-04 18:44:31 -0800872 enum_types.append({"enum_name": name, "enum_values": enum_values})
873
874def find_enum(name):
875 global enum_types
876 for enum in enum_types:
877 if enum['enum_name'] == name:
878 return enum
879 return None
Michael Roth0f923be2011-07-19 14:50:39 -0500880
881def is_enum(name):
Wenchao Xiadad1fca2014-03-04 18:44:31 -0800882 return find_enum(name) != None
Michael Roth0f923be2011-07-19 14:50:39 -0500883
Amos Kong05dfb262014-06-10 19:25:53 +0800884eatspace = '\033EATSPACE.'
Eric Blaked5573442015-05-14 06:50:54 -0600885pointer_suffix = ' *' + eatspace
Amos Kong05dfb262014-06-10 19:25:53 +0800886
Eric Blakec6405b52015-05-14 06:50:55 -0600887# Map type @name to its C type expression.
888# If @is_param, const-qualify the string type.
889#
890# This function is used for computing the full C type of 'member':'name'.
Amos Kong05dfb262014-06-10 19:25:53 +0800891# A special suffix is added in c_type() for pointer types, and it's
892# stripped in mcgen(). So please notice this when you check the return
893# value of c_type() outside mcgen().
Eric Blaked5573442015-05-14 06:50:54 -0600894def c_type(value, is_param=False):
895 if value == 'str':
Amos Kong0d14eeb2014-06-10 19:25:52 +0800896 if is_param:
Eric Blaked5573442015-05-14 06:50:54 -0600897 return 'const char' + pointer_suffix
898 return 'char' + pointer_suffix
Amos Kong05dfb262014-06-10 19:25:53 +0800899
Eric Blaked5573442015-05-14 06:50:54 -0600900 elif value == 'int':
Michael Roth0f923be2011-07-19 14:50:39 -0500901 return 'int64_t'
Eric Blaked5573442015-05-14 06:50:54 -0600902 elif (value == 'int8' or value == 'int16' or value == 'int32' or
903 value == 'int64' or value == 'uint8' or value == 'uint16' or
904 value == 'uint32' or value == 'uint64'):
905 return value + '_t'
906 elif value == 'size':
Laszlo Ersek092705d2012-07-17 16:17:07 +0200907 return 'uint64_t'
Eric Blaked5573442015-05-14 06:50:54 -0600908 elif value == 'bool':
Michael Roth0f923be2011-07-19 14:50:39 -0500909 return 'bool'
Eric Blaked5573442015-05-14 06:50:54 -0600910 elif value == 'number':
Michael Roth0f923be2011-07-19 14:50:39 -0500911 return 'double'
Eric Blaked5573442015-05-14 06:50:54 -0600912 elif type(value) == list:
913 return c_list_type(value[0]) + pointer_suffix
914 elif is_enum(value):
Eric Blakec6405b52015-05-14 06:50:55 -0600915 return c_name(value)
Eric Blaked5573442015-05-14 06:50:54 -0600916 elif value == None:
Michael Roth0f923be2011-07-19 14:50:39 -0500917 return 'void'
Eric Blaked5573442015-05-14 06:50:54 -0600918 elif value in events:
919 return camel_case(value) + 'Event' + pointer_suffix
Michael Roth0f923be2011-07-19 14:50:39 -0500920 else:
Eric Blaked5573442015-05-14 06:50:54 -0600921 # complex type name
922 assert isinstance(value, str) and value != ""
Eric Blakec6405b52015-05-14 06:50:55 -0600923 return c_name(value) + pointer_suffix
Amos Kong05dfb262014-06-10 19:25:53 +0800924
Eric Blaked5573442015-05-14 06:50:54 -0600925def is_c_ptr(value):
926 return c_type(value).endswith(pointer_suffix)
Michael Roth0f923be2011-07-19 14:50:39 -0500927
928def genindent(count):
929 ret = ""
930 for i in range(count):
931 ret += " "
932 return ret
933
934indent_level = 0
935
936def push_indent(indent_amount=4):
937 global indent_level
938 indent_level += indent_amount
939
940def pop_indent(indent_amount=4):
941 global indent_level
942 indent_level -= indent_amount
943
944def cgen(code, **kwds):
945 indent = genindent(indent_level)
946 lines = code.split('\n')
947 lines = map(lambda x: indent + x, lines)
948 return '\n'.join(lines) % kwds + '\n'
949
950def mcgen(code, **kwds):
Amos Kong05dfb262014-06-10 19:25:53 +0800951 raw = cgen('\n'.join(code.split('\n')[1:-1]), **kwds)
952 return re.sub(re.escape(eatspace) + ' *', '', raw)
Michael Roth0f923be2011-07-19 14:50:39 -0500953
954def basename(filename):
955 return filename.split("/")[-1]
956
957def guardname(filename):
Michael Rothd8e1f212011-11-29 16:47:48 -0600958 guard = basename(filename).rsplit(".", 1)[0]
959 for substr in [".", " ", "-"]:
960 guard = guard.replace(substr, "_")
961 return guard.upper() + '_H'
Michael Rothc0afa9c2013-05-10 17:46:00 -0500962
963def guardstart(name):
964 return mcgen('''
965
966#ifndef %(name)s
967#define %(name)s
968
969''',
970 name=guardname(name))
971
972def guardend(name):
973 return mcgen('''
974
975#endif /* %(name)s */
976
977''',
978 name=guardname(name))
Markus Armbruster2114f5a2015-04-02 13:12:21 +0200979
980def parse_command_line(extra_options = "", extra_long_options = []):
981
982 try:
983 opts, args = getopt.gnu_getopt(sys.argv[1:],
Markus Armbruster16d80f62015-04-02 13:32:16 +0200984 "chp:o:" + extra_options,
Markus Armbruster2114f5a2015-04-02 13:12:21 +0200985 ["source", "header", "prefix=",
Markus Armbruster16d80f62015-04-02 13:32:16 +0200986 "output-dir="] + extra_long_options)
Markus Armbruster2114f5a2015-04-02 13:12:21 +0200987 except getopt.GetoptError, err:
Markus Armbrusterb4540962015-04-02 13:17:34 +0200988 print >>sys.stderr, "%s: %s" % (sys.argv[0], str(err))
Markus Armbruster2114f5a2015-04-02 13:12:21 +0200989 sys.exit(1)
990
991 output_dir = ""
992 prefix = ""
993 do_c = False
994 do_h = False
995 extra_opts = []
996
997 for oa in opts:
998 o, a = oa
999 if o in ("-p", "--prefix"):
1000 prefix = a
Markus Armbruster2114f5a2015-04-02 13:12:21 +02001001 elif o in ("-o", "--output-dir"):
1002 output_dir = a + "/"
1003 elif o in ("-c", "--source"):
1004 do_c = True
1005 elif o in ("-h", "--header"):
1006 do_h = True
1007 else:
1008 extra_opts.append(oa)
1009
1010 if not do_c and not do_h:
1011 do_c = True
1012 do_h = True
1013
Markus Armbruster16d80f62015-04-02 13:32:16 +02001014 if len(args) != 1:
1015 print >>sys.stderr, "%s: need exactly one argument" % sys.argv[0]
Markus Armbrusterb4540962015-04-02 13:17:34 +02001016 sys.exit(1)
Markus Armbruster54414042015-06-09 16:22:45 +02001017 fname = args[0]
Markus Armbrusterb4540962015-04-02 13:17:34 +02001018
Markus Armbruster54414042015-06-09 16:22:45 +02001019 return (fname, output_dir, do_c, do_h, prefix, extra_opts)
Markus Armbruster12f8e1b2015-04-02 14:46:39 +02001020
1021def open_output(output_dir, do_c, do_h, prefix, c_file, h_file,
1022 c_comment, h_comment):
1023 c_file = output_dir + prefix + c_file
1024 h_file = output_dir + prefix + h_file
1025
1026 try:
1027 os.makedirs(output_dir)
1028 except os.error, e:
1029 if e.errno != errno.EEXIST:
1030 raise
1031
1032 def maybe_open(really, name, opt):
1033 if really:
1034 return open(name, opt)
1035 else:
1036 import StringIO
1037 return StringIO.StringIO()
1038
1039 fdef = maybe_open(do_c, c_file, 'w')
1040 fdecl = maybe_open(do_h, h_file, 'w')
1041
1042 fdef.write(mcgen('''
1043/* AUTOMATICALLY GENERATED, DO NOT MODIFY */
1044%(comment)s
1045''',
1046 comment = c_comment))
1047
1048 fdecl.write(mcgen('''
1049/* AUTOMATICALLY GENERATED, DO NOT MODIFY */
1050%(comment)s
1051#ifndef %(guard)s
1052#define %(guard)s
1053
1054''',
1055 comment = h_comment, guard = guardname(h_file)))
1056
1057 return (fdef, fdecl)
1058
1059def close_output(fdef, fdecl):
1060 fdecl.write('''
1061#endif
1062''')
Markus Armbruster12f8e1b2015-04-02 14:46:39 +02001063 fdecl.close()
Markus Armbruster12f8e1b2015-04-02 14:46:39 +02001064 fdef.close()